openpond 0.2.43 → 0.2.45

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.
Files changed (210) hide show
  1. package/dist/app-server.d.ts +18127 -5586
  2. package/dist/app-server.js +1 -1
  3. package/dist/chunks/actions-command-CRDLSPFA.js +2 -0
  4. package/dist/chunks/{app-layer-OV7RVSQW.js → app-layer-MDJFV3HZ.js} +1 -1
  5. package/dist/chunks/app-server-runtime-PJONTCCO.js +2 -0
  6. package/dist/chunks/apps-MD2DKEDW.js +2 -0
  7. package/dist/chunks/{chunk-T5QA4W2H.js → chunk-25GCTLAZ.js} +5 -5
  8. package/dist/chunks/chunk-3BJ4P5LI.js +520 -0
  9. package/dist/chunks/chunk-3SRIPOJQ.js +2 -0
  10. package/dist/chunks/{chunk-7EDOA6KD.js → chunk-4EGDKOYP.js} +3 -3
  11. package/dist/chunks/{chunk-QUNRWDVO.js → chunk-5ZFEQLRI.js} +3 -3
  12. package/dist/chunks/chunk-6BL2ZIAP.js +184 -0
  13. package/dist/chunks/chunk-6QUICEQA.js +5 -0
  14. package/dist/chunks/chunk-7D2WMUWK.js +3 -0
  15. package/dist/chunks/chunk-7KIBRK3A.js +4 -0
  16. package/dist/chunks/{chunk-O277DPTX.js → chunk-B6LYKEMU.js} +1 -1
  17. package/dist/chunks/{chunk-ZG7QX66E.js → chunk-CR6CDOKS.js} +8 -8
  18. package/dist/chunks/chunk-CXS3WXL3.js +2 -0
  19. package/dist/chunks/chunk-DWGB536R.js +19 -0
  20. package/dist/chunks/{chunk-6UPCR6EL.js → chunk-EG55BFQ4.js} +1 -1
  21. package/dist/chunks/chunk-ELNJUG64.js +17 -0
  22. package/dist/chunks/{chunk-HI7W3IVO.js → chunk-FXIUKYUR.js} +12 -12
  23. package/dist/chunks/chunk-GEDEVI4Y.js +2 -0
  24. package/dist/chunks/chunk-H3C4ZYEA.js +16 -0
  25. package/dist/chunks/chunk-HUBI3RUK.js +2 -0
  26. package/dist/chunks/{chunk-IE2WZ3I3.js → chunk-IYRHG54Q.js} +1 -1
  27. package/dist/chunks/chunk-J65BMG5Q.js +2 -0
  28. package/dist/chunks/chunk-KOR2AZVB.js +24 -0
  29. package/dist/chunks/{chunk-LLNCHGE4.js → chunk-LL4QP2IM.js} +1 -1
  30. package/dist/chunks/chunk-M2YXYBSP.js +2 -0
  31. package/dist/chunks/chunk-NPOHW5OU.js +2 -0
  32. package/dist/chunks/{chunk-KRC2S5QF.js → chunk-NXUCGKY2.js} +3 -3
  33. package/dist/chunks/chunk-PDIT2QS7.js +8 -0
  34. package/dist/chunks/{chunk-T7MJBBHE.js → chunk-PGKEDR3S.js} +1 -1
  35. package/dist/chunks/chunk-QVRNOGAU.js +21 -0
  36. package/dist/chunks/chunk-TNXILYI6.js +2 -0
  37. package/dist/chunks/chunk-TVQE3JMI.js +2 -0
  38. package/dist/chunks/chunk-U6SFIFDM.js +2409 -0
  39. package/dist/chunks/chunk-V6WBSW5Q.js +3 -0
  40. package/dist/chunks/chunk-VESOG2SS.js +2 -0
  41. package/dist/chunks/chunk-VFTUP5NQ.js +2 -0
  42. package/dist/chunks/{chunk-G2WJC6DE.js → chunk-VVV5I22A.js} +2 -2
  43. package/dist/chunks/chunk-XPB6NY7L.js +42 -0
  44. package/dist/chunks/{chunk-VG7XO6PR.js → chunk-XWLI7WJH.js} +2 -24
  45. package/dist/chunks/{chunk-KIGN4FI6.js → chunk-YWX7FKLM.js} +1 -1
  46. package/dist/chunks/cli-BKBH6FZY.js +2 -0
  47. package/dist/chunks/{configuration-command-ANYM5UYG.js → configuration-command-75ZCMZ6X.js} +1 -1
  48. package/dist/chunks/connected-evidence-UPUVVQ6P.js +2 -0
  49. package/dist/chunks/{continual-MHMPLLUZ.js → continual-WWPXK2LO.js} +1 -1
  50. package/dist/chunks/core-commands-SS2GV7WU.js +2 -0
  51. package/dist/chunks/datasets-TCLXV34N.js +2 -0
  52. package/dist/chunks/desktop-test-7ZHZHUB6.js +3 -0
  53. package/dist/chunks/{dist-GC7DXKTI.js → dist-VDN6E54A.js} +1 -1
  54. package/dist/chunks/evaluation-coordination-ZX5GLMRC.js +2 -0
  55. package/dist/chunks/experiment-improvements-O6DCQXCX.js +2 -0
  56. package/dist/chunks/experiments-JOQOBQXY.js +2 -0
  57. package/dist/chunks/{extension-5LQRULQP.js → extension-3M2CSWZB.js} +1 -1
  58. package/dist/chunks/{help-NTSTG6RR.js → help-RLRU33WN.js} +1 -1
  59. package/dist/chunks/hosted-experiment-improvement-IKO677PI.js +3 -0
  60. package/dist/chunks/hosted-harness-runtime-H2Q2SNZT.js +2 -0
  61. package/dist/chunks/hosted-profile-candidate-FHHSLJNO.js +3 -0
  62. package/dist/chunks/hosted-profile-compiler-5B256VV3.js +2 -0
  63. package/dist/chunks/hosted-profile-evaluation-control-Z25TZOW4.js +2 -0
  64. package/dist/chunks/hosted-profile-evaluation-inspection-MFYPLTZQ.js +3 -0
  65. package/dist/chunks/hosted-profile-evaluation-preparation-MAB2PSCC.js +3 -0
  66. package/dist/chunks/human-review-6H3BW7OZ.js +2 -0
  67. package/dist/chunks/learning-Y6WNDVQW.js +2 -0
  68. package/dist/chunks/{opchat-77PRAQ5W.js → opchat-3E4FH3DC.js} +1 -1
  69. package/dist/chunks/{organizations-2KWTYIPU.js → organizations-PRVCUPMN.js} +1 -1
  70. package/dist/chunks/{profile-HVLH672B.js → profile-DC4UEVVG.js} +1 -1
  71. package/dist/chunks/project-agent-ZX3CELKI.js +2 -0
  72. package/dist/chunks/sandbox-command-HHQMZK3G.js +2 -0
  73. package/dist/chunks/{sandbox-template-QMB6DSTS.js → sandbox-template-DFHWHCIQ.js} +1 -1
  74. package/dist/chunks/{src-N447LUPO.js → src-CREVQF7M.js} +1 -1
  75. package/dist/chunks/src-MAZ7OBVY.js +327 -0
  76. package/dist/chunks/taskset-TB2ICAZU.js +2 -0
  77. package/dist/chunks/{teams-bot-RNHQMPQA.js → teams-bot-BNBL57S5.js} +1 -1
  78. package/dist/chunks/training-FW5FOGR3.js +2 -0
  79. package/dist/chunks/{workspaces-V5YTXJLV.js → workspaces-WTPFRJMS.js} +1 -1
  80. package/dist/cli.js +1 -1
  81. package/dist/index.js +1 -1
  82. package/dist/profile/local-profile.d.ts +2 -0
  83. package/dist/web/assets/App-BgeSqoRS.css +1 -0
  84. package/dist/web/assets/App-C6EWFrLP.js +227 -0
  85. package/dist/web/assets/{AppDialog-v-BfV1lA.js → AppDialog-Cgn_fTGR.js} +1 -1
  86. package/dist/web/assets/AppTerminalPanel-cNYkSvM2.js +2 -0
  87. package/dist/web/assets/{AppsView-Dl-37F0w.js → AppsView-9zpKBSLv.js} +1 -1
  88. package/dist/web/assets/{BrowserSidebar-DltF217k.js → BrowserSidebar-Xo21N1ej.js} +1 -1
  89. package/dist/web/assets/{CartesianChart-gK-Ll3kX.js → CartesianChart-Bg3Lm5mZ.js} +1 -1
  90. package/dist/web/assets/{CollaborationTabs-BuWquQYn.js → CollaborationTabs-BIfgIy5X.js} +1 -1
  91. package/dist/web/assets/{CommandMenu-Cs5S8t-Q.js → CommandMenu-D9BimyPx.js} +1 -1
  92. package/dist/web/assets/{CommunityView-BJBkQEMV.js → CommunityView-BoW-yLju.js} +1 -1
  93. package/dist/web/assets/{ComposerCreateImproveStrip-C36fKc-v.js → ComposerCreateImproveStrip-BIKVEgr1.js} +1 -1
  94. package/dist/web/assets/{GetStartedView-9A49MgYA.js → GetStartedView-B99v4-hh.js} +1 -1
  95. package/dist/web/assets/HostedModelLearningReview-DEScpX2Z.js +1 -0
  96. package/dist/web/assets/HostedModelLearningSettings-4HT5eEiL.js +1 -0
  97. package/dist/web/assets/LabModelVersionDetailPage-DkYdI7gr.js +1 -0
  98. package/dist/web/assets/{LabSkillSidebar-BAKym5GY.js → LabSkillSidebar-Bp5XYipm.js} +1 -1
  99. package/dist/web/assets/LabsRoute-ACN76d2j.css +1 -0
  100. package/dist/web/assets/LabsRoute-VopO7n34.js +105 -0
  101. package/dist/web/assets/MainChatThread-3Gg0oDZT.js +2 -0
  102. package/dist/web/assets/{MainPane-gPkr0OWu.js → MainPane-CUqMVG9-.js} +11 -11
  103. package/dist/web/assets/{MarkdownText-B-au2zEv.js → MarkdownText-De0WzrEw.js} +1 -1
  104. package/dist/web/assets/{NativeSkillSidebar-DHFKZ7P1.js → NativeSkillSidebar-B4jtf5RO.js} +1 -1
  105. package/dist/web/assets/{NewExperienceSwitcher-Dhbf5KJT.js → NewExperienceSwitcher-Bg1DVr96.js} +1 -1
  106. package/dist/web/assets/{NewProjectDialog-hlAzFK2Y.js → NewProjectDialog-i_wvIBw-.js} +1 -1
  107. package/dist/web/assets/{OutputsPage-C0N2rOxE.js → OutputsPage-CZiPxLyN.js} +1 -1
  108. package/dist/web/assets/{ProjectsPage-CkHBgLPx.js → ProjectsPage-BD0eml0M.js} +1 -1
  109. package/dist/web/assets/{RightChatPanelStack-BiW6ZzPN.js → RightChatPanelStack-CEBFPHKP.js} +1 -1
  110. package/dist/web/assets/{RightSidebarHomePanel-BS9YSdYB.js → RightSidebarHomePanel-BTpU5wGh.js} +1 -1
  111. package/dist/web/assets/{ScheduledWorkPage-819sQcDR.js → ScheduledWorkPage-Y6XGoh-X.js} +1 -1
  112. package/dist/web/assets/{SettingsView-BZrOUPZb.js → SettingsView-Kh14f463.js} +3 -3
  113. package/dist/web/assets/{TeamChatView-CUNcbSa7.js → TeamChatView-5LjuRNd6.js} +1 -1
  114. package/dist/web/assets/{TerminalOverlay-MIlGPpXe.js → TerminalOverlay-BCWBSotQ.js} +1 -1
  115. package/dist/web/assets/{TrainingCreationPanel-BNcyNoa8.js → TrainingCreationPanel-hvOHRVJx.js} +1 -1
  116. package/dist/web/assets/{TrainingDraftPanel-CKV16LNC.js → TrainingDraftPanel-CGEHGljE.js} +1 -1
  117. package/dist/web/assets/{UsageSettingsSection-SVgUHnUL.js → UsageSettingsSection-B8nbqhag.js} +1 -1
  118. package/dist/web/assets/{WorkSidebarPanel-CfkaaFHA.js → WorkSidebarPanel-B6hlPEIs.js} +1 -1
  119. package/dist/web/assets/{WorkspaceDiffPanel-CQhqlqg5.js → WorkspaceDiffPanel-q8A15-0x.js} +9 -9
  120. package/dist/web/assets/{WorkspaceEnvironmentMenu-CJB-z2tS.js → WorkspaceEnvironmentMenu-BiFTPWtC.js} +1 -1
  121. package/dist/web/assets/{WorkspaceGitDialogs-B3xtasTt.js → WorkspaceGitDialogs-Dyx4Rbiy.js} +1 -1
  122. package/dist/web/assets/{WorkspaceMonacoEditor-DVfyICNZ.js → WorkspaceMonacoEditor-B1dKexHo.js} +60 -60
  123. package/dist/web/assets/{arrow-up-right-CYG4Vm07.js → arrow-up-right-CCj7SOGp.js} +1 -1
  124. package/dist/web/assets/chunk-DJWHN7NU-1eQoMoKO.js +1 -0
  125. package/dist/web/assets/{clipboard-DGSnfljX.js → clipboard-BY6ELc9Z.js} +1 -1
  126. package/dist/web/assets/{cloud-upload-Bw_zrS2y.js → cloud-upload-BOka5EKK.js} +1 -1
  127. package/dist/web/assets/cssMode-C34j8ti5.js +1 -0
  128. package/dist/web/assets/{folder-open-CcGOldH7.js → folder-open-CX2jidFj.js} +1 -1
  129. package/dist/web/assets/{folder-plus-DEIDaX2B.js → folder-plus-Dh2Q9LP3.js} +1 -1
  130. package/dist/web/assets/{git-commit-horizontal-B-Ao6y--.js → git-commit-horizontal-CfevriuT.js} +1 -1
  131. package/dist/web/assets/htmlMode-BORwVkZg.js +1 -0
  132. package/dist/web/assets/index-B9VSiz_z.css +1 -0
  133. package/dist/web/assets/{index-C8_8-lW7.js → index-BBjRfC--.js} +6 -6
  134. package/dist/web/assets/{info-DwOXHkN_.js → info-Bv3dbs3G.js} +1 -1
  135. package/dist/web/assets/{jsonMode-txmGM7K6.js → jsonMode-BYWtZ6AK.js} +4 -4
  136. package/dist/web/assets/{lspLanguageFeatures-D59Drc_9.js → lspLanguageFeatures-CEAdFSpU.js} +1 -1
  137. package/dist/web/assets/{minimize-2-C5UCV16_.js → minimize-2-MhorZwY5.js} +1 -1
  138. package/dist/web/assets/{monaco.contribution-BOmcYK8k.js → monaco.contribution-CDhPpbIo.js} +2 -2
  139. package/dist/web/assets/{monaco.contribution-CbK7796k.js → monaco.contribution-CN7AWJNd.js} +2 -2
  140. package/dist/web/assets/monaco.contribution-DHA7FuJX.js +2 -0
  141. package/dist/web/assets/{monaco.contribution-5HcktwaM.js → monaco.contribution-ZUUVx_3M.js} +2 -2
  142. package/dist/web/assets/{monitor-D4hpNTai.js → monitor-DLcrkfM5.js} +1 -1
  143. package/dist/web/assets/{python-Cie4Ghu8.js → python-CXwvPmc4.js} +1 -1
  144. package/dist/web/assets/{refresh-cw-CIOzrJnj.js → refresh-cw-BTfIxHb3.js} +1 -1
  145. package/dist/web/assets/{save-D7EtdMHG.js → save-DaN65kMq.js} +1 -1
  146. package/dist/web/assets/{square-JpDfrqp_.js → square-zRgIUdSv.js} +1 -1
  147. package/dist/web/assets/toggleHighContrast-BgpFWRpS.css +1 -0
  148. package/dist/web/assets/{toggleHighContrast-DdGkc-Be.js → toggleHighContrast-DWeRZFzr.js} +1 -1
  149. package/dist/web/assets/{tsMode-DwgEL7oI.js → tsMode-nLBhKngY.js} +1 -1
  150. package/dist/web/assets/{upload-BkwOzqS-.js → upload-BfUu4Eu1.js} +1 -1
  151. package/dist/web/assets/{useLocalAgentSchedules-bO0Qycih.js → useLocalAgentSchedules-BCITWhg2.js} +1 -1
  152. package/dist/web/assets/{useSessionTurnCache-DxUh5scW.js → useSessionTurnCache-BQMWfV8u.js} +1 -1
  153. package/dist/web/assets/{wifi-off-D6Keejtn.js → wifi-off-bdka5es5.js} +1 -1
  154. package/dist/web/assets/{workers-BgG66q0n.js → workers-z7XHFFNs.js} +1 -1
  155. package/dist/web/assets/{yaml-COMRGPWg.js → yaml-BTr4i4DD.js} +1 -1
  156. package/dist/web/index.html +5 -5
  157. package/docs/command-reference.md +85 -1
  158. package/package.json +6 -2
  159. package/dist/chunks/actions-command-DWQ3VGGP.js +0 -2
  160. package/dist/chunks/app-server-runtime-JVLXE5LF.js +0 -2
  161. package/dist/chunks/apps-5DQAYDNI.js +0 -2
  162. package/dist/chunks/chunk-3D4QN4NM.js +0 -19
  163. package/dist/chunks/chunk-45UOD2DA.js +0 -2
  164. package/dist/chunks/chunk-5IN3HQJU.js +0 -2
  165. package/dist/chunks/chunk-6KKQXETR.js +0 -5
  166. package/dist/chunks/chunk-6XF4GI35.js +0 -2
  167. package/dist/chunks/chunk-7KC5LWCU.js +0 -2
  168. package/dist/chunks/chunk-7R7O2XXP.js +0 -2
  169. package/dist/chunks/chunk-DGD52VZC.js +0 -13
  170. package/dist/chunks/chunk-E6WT4HWF.js +0 -3
  171. package/dist/chunks/chunk-EWQZASG4.js +0 -2400
  172. package/dist/chunks/chunk-IFI24VF6.js +0 -5
  173. package/dist/chunks/chunk-KDOS6YMH.js +0 -2
  174. package/dist/chunks/chunk-MDE3HHLH.js +0 -2
  175. package/dist/chunks/chunk-P45OSKQL.js +0 -4
  176. package/dist/chunks/chunk-ROJX6IYW.js +0 -578
  177. package/dist/chunks/chunk-SXN3QOW4.js +0 -3
  178. package/dist/chunks/chunk-V44RF57H.js +0 -2
  179. package/dist/chunks/chunk-VJJ3UXOI.js +0 -42
  180. package/dist/chunks/chunk-W3NG7YLC.js +0 -8
  181. package/dist/chunks/chunk-XMKAMR7M.js +0 -2
  182. package/dist/chunks/cli-7D7CYCIY.js +0 -2
  183. package/dist/chunks/core-commands-TYWE3TNW.js +0 -2
  184. package/dist/chunks/datasets-FM3UBK4R.js +0 -13
  185. package/dist/chunks/desktop-test-Z5IKJU3P.js +0 -3
  186. package/dist/chunks/experiments-IWBRIDQE.js +0 -2
  187. package/dist/chunks/hosted-harness-runtime-S75BLD57.js +0 -2
  188. package/dist/chunks/hosted-profile-compiler-JNNYWLC7.js +0 -2
  189. package/dist/chunks/hosted-profile-evaluation-control-IK4Y2EQZ.js +0 -2
  190. package/dist/chunks/hosted-profile-evaluation-inspection-YWKUB7RT.js +0 -3
  191. package/dist/chunks/hosted-profile-evaluation-preparation-JXOF73BB.js +0 -3
  192. package/dist/chunks/project-agent-7NLKJMAM.js +0 -2
  193. package/dist/chunks/sandbox-command-FNS4JBVC.js +0 -2
  194. package/dist/chunks/src-TZBL6NA7.js +0 -325
  195. package/dist/chunks/taskset-BZYQT65N.js +0 -2
  196. package/dist/chunks/training-7PST5HZU.js +0 -2
  197. package/dist/web/assets/App-7h_oHCFd.css +0 -1
  198. package/dist/web/assets/App-BEQmrTGQ.js +0 -226
  199. package/dist/web/assets/AppTerminalPanel-CnKcllS2.js +0 -2
  200. package/dist/web/assets/HostedModelLearningReview-JgxDUDio.js +0 -1
  201. package/dist/web/assets/HostedModelLearningSettings-CH7CsAhw.js +0 -1
  202. package/dist/web/assets/LabModelVersionDetailPage-N2qcy1Yv.js +0 -1
  203. package/dist/web/assets/LabsRoute-DooCmsN8.css +0 -1
  204. package/dist/web/assets/LabsRoute-Y992kQoQ.js +0 -52
  205. package/dist/web/assets/MainChatThread-CPhREQso.js +0 -2
  206. package/dist/web/assets/cssMode-CSpYOKj-.js +0 -1
  207. package/dist/web/assets/htmlMode-DstkgJXG.js +0 -1
  208. package/dist/web/assets/index-DUIWDN8o.css +0 -1
  209. package/dist/web/assets/monaco.contribution-BomZ1gys.js +0 -2
  210. package/dist/web/assets/toggleHighContrast-B7NOMXDY.css +0 -1
@@ -0,0 +1,227 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CommandMenu-D9BimyPx.js","assets/index-BBjRfC--.js","assets/index-B9VSiz_z.css","assets/CommandMenu-Cb3vNGJr.css","assets/SettingsView-Kh14f463.js","assets/refresh-cw-BTfIxHb3.js","assets/save-DaN65kMq.js","assets/MarkdownText-De0WzrEw.js","assets/folder-open-CX2jidFj.js","assets/wifi-off-bdka5es5.js","assets/useLocalAgentSchedules-BCITWhg2.js","assets/cloud-upload-BOka5EKK.js","assets/git-commit-horizontal-CfevriuT.js","assets/folder-plus-Dh2Q9LP3.js","assets/AppDialog-Cgn_fTGR.js","assets/WorkspaceDiffPanel-q8A15-0x.js","assets/training-model-data-CKOkpBBL.js","assets/info-Bv3dbs3G.js","assets/minimize-2-MhorZwY5.js","assets/clipboard-BY6ELc9Z.js","assets/SettingsView-C7av3zwv.css","assets/git-dialogs-C-F47S10.css","assets/NewProjectDialog-i_wvIBw-.js","assets/monitor-DLcrkfM5.js","assets/WorkspaceGitDialogs-Dyx4Rbiy.js","assets/upload-BfUu4Eu1.js","assets/WorkspaceEnvironmentMenu-BiFTPWtC.js","assets/square-zRgIUdSv.js","assets/WorkspaceEnvironmentMenu-DGIFdG3o.css","assets/MainPane-CUqMVG9-.js","assets/arrow-up-right-CCj7SOGp.js"])))=>i.map(i=>d[i]);
2
+ import{r as y,j as x,a as eT,_ as Er}from"./index-BBjRfC--.js";const Tk=y.createContext(void 0),Ek=e=>{const t=y.useContext(Tk);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},tT=({client:e,children:t})=>(y.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),x.jsx(Tk.Provider,{value:e,children:t})),nT={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)};var aT=class{#e=nT;#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 fr=new aT;function iT(e){setTimeout(e,0)}const oT=typeof window>"u"||"Deno"in globalThis;function la(){}function rT(e,t){return typeof e=="function"?e(t):e}function Mk(e){return typeof e=="number"&&e>=0&&e!==1/0}function jk(e,t){return Math.max(e+(t||0)-Date.now(),0)}function un(e,t){return typeof e=="function"?e(t):e}function _y(e,t){const{type:n="all",exact:a,fetchStatus:i,predicate:r,queryKey:s,stale:c}=e;if(s){if(a){if(t.queryHash!==Gg(s,t.options))return!1}else if(!Ls(t.queryKey,s))return!1}if(n!=="all"){const m=t.isActive();if(n==="active"&&!m||n==="inactive"&&m)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||i&&i!==t.state.fetchStatus||r&&!r(t))}function Cy(e,t){const{exact:n,status:a,predicate:i,mutationKey:r}=e;if(r){if(!t.options.mutationKey)return!1;if(n){if(pc(t.options.mutationKey)!==pc(r))return!1}else if(!Ls(t.options.mutationKey,r))return!1}return!(a&&t.state.status!==a||i&&!i(t))}function Gg(e,t){return(t?.queryKeyHashFn||pc)(e)}function pc(e){return JSON.stringify(e,(t,n)=>Lh(n)?Object.keys(n).sort().reduce((a,i)=>(a[i]=n[i],a),{}):n)}function Ls(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(!Ls(e[a],t[a]))return!1;return!0}const n=Object.keys(t);for(const a of n)if(!Ls(e[a],t[a]))return!1;return!0}return!1}const sT=Object.prototype.hasOwnProperty;function Ok(e,t,n=0){if(e===t)return e;if(n>500)return t;const a=Ry(e)&&Ry(t);if(!a&&!(Lh(e)&&Lh(t)))return t;const i=(a?e:Object.keys(e)).length,r=a?t:Object.keys(t),s=r.length,c=a?new Array(s):{};let m=0;for(let u=0;u<s;u++){const h=a?u:r[u],g=e[h],S=t[h];if(g===S){c[h]=g,(a?u<i:sT.call(e,h))&&m++;continue}if(g===null||S===null||typeof g!="object"||typeof S!="object"){c[h]=S;continue}const k=Ok(g,S,n+1);c[h]=k,k===g&&m++}return i===s&&m===i?e:c}function yf(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 Ry(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Lh(e){if(!Py(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Py(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Py(e){return Object.prototype.toString.call(e)==="[object Object]"}function lT(e){return new Promise(t=>{fr.setTimeout(t,e)})}function qh(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Ok(e,t):t}function cT(e,t,n=0){const a=[...e,t];return n&&a.length>n?a.slice(1):a}function dT(e,t,n=0){const a=[t,...e];return n&&a.length>n?a.slice(0,-1):a}const Jg=Symbol();function $k(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Jg?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Nk(e,t){return typeof e=="function"?e(...t):!!e}function uT(e,t,n){let a=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),a||(a=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}let mT=()=>oT;const Zg=()=>mT();var Uc=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(){}},pT=class extends Uc{#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 Yg=new pT,fT=iT;function hT(){let e=[],t=0,n=c=>{c()},a=c=>{c()},i=fT;const r=c=>{t?e.push(c):i(()=>{n(c)})},s=()=>{const c=e;e=[],c.length&&i(()=>{a(()=>{c.forEach(m=>{n(m)})})})};return{batch:c=>{let m;t++;try{m=c()}finally{t--,t||s()}return m},batchCalls:c=>(...m)=>{r(()=>{c(...m)})},schedule:r,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{a=c},setScheduler:c=>{i=c}}}const Ln=hT();var gT=class extends Uc{#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 Tu=new gT;function vT(e){return Math.min(1e3*2**e,3e4)}function Dk(e){return(e??"online")==="online"?Tu.isOnline():!0}var Uh=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Hk(e){let t=!1,n=0,a,i="pending",r,s;const c=new Promise(($,O)=>{r=$,s=O});c.catch(la);const m=()=>i!=="pending",u=$=>{if(!m()){const O=new Uh($);A(O),e.onCancel?.(O)}},h=()=>{t=!0},g=()=>{t=!1},S=()=>Yg.isFocused()&&(e.networkMode==="always"||Tu.isOnline())&&e.canRun(),k=()=>Dk(e.networkMode)&&e.canRun(),C=$=>{m()||(a?.(),i="resolved",r($))},A=$=>{m()||(a?.(),i="rejected",s($))},M=()=>new Promise($=>{a=O=>{(m()||S())&&$(O)},e.onPause?.()}).then(()=>{a=void 0,m()||e.onContinue?.()}),R=()=>{if(m())return;let $;const O=n===0?e.initialPromise:void 0;try{$=O??e.fn()}catch(j){$=Promise.reject(j)}Promise.resolve($).then(C).catch(j=>{if(m())return;const I=e.retry??(Zg()?0:3),P=e.retryDelay??vT,E=typeof P=="function"?P(n,j):P,L=I===!0||typeof I=="number"&&n<I||typeof I=="function"&&I(n,j);if(t||!L){A(j);return}n++,e.onFail?.(n,j),lT(E).then(()=>S()?void 0:M()).then(()=>{t?A(j):R()})})};return{promise:c,status:()=>i,cancel:u,continue:()=>(a?.(),c),cancelRetry:h,continueRetry:g,canStart:k,start:()=>(k()?R():M().then(R),c)}}var Lk=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Mk(this.gcTime)&&(this.#e=fr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Zg()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(fr.clearTimeout(this.#e),this.#e=void 0)}};function bT(e){return{onFetch:(t,n)=>{const a=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,r=t.state.data?.pages||[],s=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},m=0;const u=async()=>{let h=!1;const g=C=>{uT(C,()=>t.signal,()=>h=!0)},S=$k(t.options,t.fetchOptions),k=async(C,A,M)=>{if(h)return Promise.reject(t.signal.reason);if(A==null&&C.pages.length)return Promise.resolve(C);const $=(()=>{const P={client:t.client,queryKey:t.queryKey,pageParam:A,direction:M?"backward":"forward",meta:t.options.meta};return g(P),P})(),O=await S($),{maxPages:j}=t.options,I=M?dT:cT;return{pages:I(C.pages,O,j),pageParams:I(C.pageParams,A,j)}};if(i&&r.length){const C=i==="backward",A=C?qk:zh,M={pages:r,pageParams:s};c=await k(M,A(a,M),C)}else{const C=e??r.length;do{const A=m===0?s[0]??a.initialPageParam:zh(a,c);if(m>0&&A==null)break;c=await k(c,A),m++}while(m<C)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function zh(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 qk(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function gne(e,t){return t?zh(e,t)!=null:!1}function vne(e,t){return!t||!e.getPreviousPageParam?!1:qk(e,t)!=null}var yT=class extends Lk{#e;#t;#n;#a;#o;#i;#r;#l;constructor(e){super(),this.#l=!1,this.#r=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#o=e.client,this.#a=this.#o.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Ty(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#i?.promise}setOptions(e){if(this.options={...this.#r,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=Ty(this.options);t.data!==void 0&&(this.setState(Ay(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#a.remove(this)}setData(e,t){const n=qh(this.state.data,e,this.options);return this.#s({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#s({type:"setState",state:e})}cancel(e){const t=this.#i?.promise;return this.#i?.cancel(e),t?t.then(la).catch(la):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>un(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Jg||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>un(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!jk(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#a.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){const t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#i&&(this.#l||this.state.fetchStatus==="paused"&&this.state.status==="pending"?this.#i.cancel({revert:!0}):this.#i.cancelRetry()),this.scheduleGc()),this.#a.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#i?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.promise}if(e&&this.setOptions(e),!this.options.queryFn){const m=this.observers.find(u=>u.options.queryFn);m&&this.setOptions(m.options)}const n=new AbortController,a=m=>{Object.defineProperty(m,"signal",{enumerable:!0,get:()=>(this.#l=!0,n.signal)})},i=()=>{const m=$k(this.options,t),h=(()=>{const g={client:this.#o,queryKey:this.queryKey,meta:this.meta};return a(g),g})();return this.#l=!1,this.options.persister?this.options.persister(m,h,this):m(h)},s=(()=>{const m={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#o,state:this.state,fetchFn:i};return a(m),m})();(this.#e==="infinite"?bT(this.options.pages):this.options.behavior)?.onFetch(s,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==s.fetchOptions?.meta)&&this.#s({type:"fetch",meta:s.fetchOptions?.meta});const c=this.#i=Hk({initialPromise:t?.initialPromise,fn:s.fetchFn,onCancel:m=>{m instanceof Uh&&m.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(m,u)=>{this.#s({type:"failed",failureCount:m,error:u})},onPause:()=>{this.#s({type:"pause"})},onContinue:()=>{this.#s({type:"continue"})},retry:s.options.retry,retryDelay:s.options.retryDelay,networkMode:s.options.networkMode,canRun:()=>!0});try{const m=await c.start();if(m===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(m),this.#a.config.onSuccess?.(m,this),this.#a.config.onSettled?.(m,this.state.error,this),m}catch(m){if(m instanceof Uh){if(m.silent)return this.#i.promise;if(m.revert){if(this.state.data===void 0)throw m;return this.state.data}}throw this.#s({type:"error",error:m}),this.#a.config.onError?.(m,this),this.#a.config.onSettled?.(this.state.data,m,this),m}finally{this.#i===c&&(this.#i=void 0),this.scheduleGc()}}#s(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Uk(n.data,this.options),fetchMeta:e.meta??null};case"success":const a={...n,...Ay(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 i=e.error;return{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),Ln.batch(()=>{this.observers.slice().forEach(n=>{n.onQueryUpdate()}),this.#a.notify({query:this,type:"updated",action:e})})}};function Uk(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Dk(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Ay(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Ty(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 ST=class extends Uc{#e;#t=void 0;#n=void 0;#a=void 0;#o;#i;#r;#l;#s;#p;#d;#u;#c;#f=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#r=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Ey(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Bh(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Bh(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#x(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof un(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#k(),this.#t.setOptions(this.options),t._defaulted&&!yf(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const a=this.hasListeners();a&&My(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),a&&(this.#t!==n||un(this.options.enabled,this.#t)!==un(t.enabled,this.#t)||un(this.options.staleTime,this.#t)!==un(t.staleTime,this.#t))&&this.#g();const i=this.#v();a&&(this.#t!==n||un(this.options.enabled,this.#t)!==un(t.enabled,this.#t)||i!==this.#c)&&this.#b(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return yf(this.getCurrentResult(),n)||(this.#a=n,this.#i=this.options,this.#o=this.#t.state),n}getCurrentResult(){return this.#a}trackResult(e,t){return new Proxy(e,{get:(n,a)=>(this.trackProp(a),t?.(a),Reflect.get(n,a))})}trackProp(e){this.#f.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);let a=()=>{},i;const r=new Promise(s=>{i=s,a=this.#e.getQueryCache().subscribe(c=>{c.type==="updated"&&c.query.queryHash===n.queryHash&&n.state.data!==void 0&&(a(),s(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{const s=this.createResult(n,t);return i?.(s),s}).finally(()=>{a()}),r])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#a))}#m(e){this.#k();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(la)),t}#h(e){return!Zg()&&un(this.options.enabled,this.#t)!==!1&&Mk(e)}#g(){this.#S();const e=un(this.options.staleTime,this.#t);if(this.#a.isStale||!this.#h(e))return;const t=jk(this.#a.dataUpdatedAt,e)+1;this.#d=fr.setTimeout(()=>{this.#a.isStale||this.updateResult()},t)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#b(e){this.#x(),this.#c=e,!(this.#c===0||!this.#h(this.#c))&&(this.#u=fr.setInterval(()=>{(this.options.refetchIntervalInBackground||Yg.isFocused())&&this.#m()},this.#c))}#y(){this.#g(),this.#b(this.#v())}#S(){this.#d!==void 0&&(fr.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#u!==void 0&&(fr.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const n=this.#t,a=this.options,i=this.#a,r=this.#o,s=this.#i,c=e!==n?e.state:this.#n,{state:m}=e;let u={...m},h=!1,g;if(t._optimisticResults){const I=this.hasListeners(),P=!I&&Ey(e,t),E=I&&My(e,n,t,a);(P||E)&&(u={...u,...Uk(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:S,errorUpdatedAt:k,status:C}=u;g=u.data;let A=!1;if(t.placeholderData!==void 0&&g===void 0&&C==="pending"){let I;i?.isPlaceholderData&&t.placeholderData===s?.placeholderData?(I=i.data,A=!0):I=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,I!==void 0&&(C="success",g=qh(i?.data,I,t),h=!0)}if(t.select&&g!==void 0&&!A)if(i&&g===r?.data&&t.select===this.#l)g=this.#s;else try{this.#l=t.select,g=t.select(g),g=qh(i?.data,g,t),this.#s=g,this.#r=null}catch(I){this.#r=I}else g===void 0&&(this.#r=null);this.#r&&(S=this.#r,g=this.#s,k=Date.now(),C="error",h=!1);const M=u.fetchStatus==="fetching",R=C==="pending",$=C==="error",O=R&&M,j=g!==void 0;return{status:C,fetchStatus:u.fetchStatus,isPending:R,isSuccess:C==="success",isError:$,isInitialLoading:O,isLoading:O,data:g,dataUpdatedAt:u.dataUpdatedAt,error:S,errorUpdatedAt:k,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:u.dataUpdateCount>c.dataUpdateCount||u.errorUpdateCount>c.errorUpdateCount,isFetching:M,isRefetching:M&&!R,isLoadingError:$&&!j,isPaused:u.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:$&&j,isStale:Qg(e,t),refetch:this.refetch,isEnabled:un(t.enabled,e)!==!1}}updateResult(){const e=this.#a,t=this.createResult(this.#t,this.options);if(this.#o=this.#t.state,this.#i=this.options,this.#o.data!==void 0&&(this.#p=this.#t),yf(t,e))return;this.#a=t;const a=(()=>{if(!e)return!0;const{notifyOnChangeProps:i}=this.options,r=typeof i=="function"?i():i;if(r==="all"||!r&&!this.#f.size)return!0;const s=new Set(r??this.#f);return this.options.throwOnError&&s.add("error"),Object.keys(this.#a).some(c=>{const m=c;return this.#a[m]!==e[m]&&s.has(m)})})();Ln.batch(()=>{a&&this.listeners.forEach(i=>{i(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 xT(e,t){return un(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&un(t.retryOnMount,e)===!1)}function Ey(e,t){return xT(e,t)||e.state.data!==void 0&&Bh(e,t,t.refetchOnMount)}function Bh(e,t,n){if(un(t.enabled,e)!==!1&&un(t.staleTime,e)!=="static"){const a=typeof n=="function"?n(e):n;return a==="always"||a!==!1&&Qg(e,t)}return!1}function My(e,t,n,a){return(e!==t||un(a.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Qg(e,n)}function Qg(e,t){return un(t.enabled,e)!==!1&&e.isStaleByTime(un(t.staleTime,e))}var kT=class extends Lk{#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||IT(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){this.#t.includes(t)||(this.#t.push(t),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#t=this.#t.filter(n=>n!==t),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#a?.continue()??(this.state.status==="pending"?this.execute(this.state.variables):Promise.resolve())}async execute(t){const n=()=>{this.#o({type:"continue"})},a={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},i=this.#a=Hk({fn:()=>this.options.mutationFn?this.options.mutationFn(t,a):Promise.reject(new Error("No mutationFn found")),onFail:(c,m)=>{this.#o({type:"failed",failureCount:c,error:m})},onPause:()=>{this.#o({type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),r=this.state.status==="pending",s=!i.canStart();try{if(r)n();else{this.#o({type:"pending",variables:t,isPaused:s}),this.#n.config.onMutate&&await this.#n.config.onMutate(t,this,a);const m=await this.options.onMutate?.(t,a);m!==this.state.context&&this.#o({type:"pending",context:m,variables:t,isPaused:s})}const c=await i.start();return await this.#n.config.onSuccess?.(c,t,this.state.context,this,a),await this.options.onSuccess?.(c,t,this.state.context,a),await this.#n.config.onSettled?.(c,null,this.state.variables,this.state.context,this,a),await this.options.onSettled?.(c,null,t,this.state.context,a),this.#o({type:"success",data:c}),c}catch(c){try{await this.#n.config.onError?.(c,t,this.state.context,this,a)}catch(m){Promise.reject(m)}try{await this.options.onError?.(c,t,this.state.context,a)}catch(m){Promise.reject(m)}try{await this.#n.config.onSettled?.(void 0,c,this.state.variables,this.state.context,this,a)}catch(m){Promise.reject(m)}try{await this.options.onSettled?.(void 0,c,t,this.state.context,a)}catch(m){Promise.reject(m)}throw this.#o({type:"error",error:c}),c}finally{this.#a===i&&(this.#a=void 0),this.#n.runNext(this)}}#o(t){const n=a=>{switch(t.type){case"failed":return{...a,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...a,isPaused:!0};case"continue":return{...a,isPaused:!1};case"pending":return{...a,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...a,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...a,data:void 0,error:t.error,failureCount:a.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),Ln.batch(()=>{this.#t.forEach(a=>{a.onMutationUpdate(t)}),this.#n.notify({mutation:this,type:"updated",action:t})})}};function IT(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var wT=class extends Uc{#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 kT({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=Hd(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=Hd(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=Hd(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=Hd(e);return typeof t=="string"?this.#t.get(t)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Ln.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Cy(t,n))}findAll(e={}){return this.getAll().filter(t=>Cy(e,t))}notify(e){Ln.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Ln.batch(()=>Promise.all(e.map(t=>t.continue().catch(la))))}};function Hd(e){return e.options.scope?.id}var _T=class extends Uc{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){const a=t.queryKey,i=t.queryHash??Gg(a,t);let r=this.get(i);return r||(r=new yT({client:e,queryKey:a,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(a)}),this.add(r)),r}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Ln.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>_y(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>_y(e,n)):t}notify(e){Ln.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Ln.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Ln.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},CT=class{#e;#t;#n;#a;#o;#i;#r;#l;constructor(e={}){this.#e=e.queryCache||new _T,this.#t=e.mutationCache||new wT,this.#n=e.defaultOptions||{},this.#a=new Map,this.#o=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#r=Yg.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#l=Tu.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#i--,this.#i===0&&(this.#r?.(),this.#r=void 0,this.#l?.(),this.#l=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),a=n.state.data;return a===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(un(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(a))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>[t,n.data])}setQueryData(e,t,n){const a=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(a.queryHash)?.state.data,r=rT(t,i);if(r!==void 0)return this.#e.build(this,a).setData(r,{...n,manual:!0})}setQueriesData(e,t,n){return Ln.batch(()=>this.#e.findAll(e).map(({queryKey:a})=>[a,this.setQueryData(a,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;Ln.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return Ln.batch(()=>{const a=n.findAll(e),i=new Set(a);return a.forEach(r=>{r.reset()}),this.refetchQueries({type:"active",predicate:r=>i.has(r)},t)})}cancelQueries(e,t={}){const n={revert:!0,...t},a=Ln.batch(()=>this.#e.findAll(e).map(i=>i.cancel(n)));return Promise.all(a).then(la).catch(la)}invalidateQueries(e,t={}){return Ln.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},a=Ln.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let r=i.fetch(void 0,n);return n.throwOnError||(r=r.catch(la)),i.state.fetchStatus==="paused"?Promise.resolve():r}));return Promise.all(a).then(la)}async query(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t),a=n.isStaleByTime(un(t.staleTime,n))?await n.fetch(t):n.state.data,i=t.select;return i?i(a):a}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(un(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(la).catch(la)}infiniteQuery(e){return e._type="infinite",this.query(e)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(la).catch(la)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return Tu.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(pc(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(a=>{Ls(e,a.queryKey)&&Object.assign(n,a.defaultOptions)}),n}setMutationDefaults(e,t){this.#o.set(pc(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#o.values()],n={};return t.forEach(a=>{Ls(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=Gg(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===Jg&&(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 zk=y.createContext(!1),RT=()=>y.useContext(zk);zk.Provider;function PT(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}const AT=y.createContext(PT()),TT=()=>y.useContext(AT),ET=(e,t,n)=>{const a=n?.state.error&&typeof e.throwOnError=="function"?Nk(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||a)&&(t.isReset()||(e.retryOnMount=!1))},MT=e=>{y.useEffect(()=>{e.clearReset()},[e])},jT=({result:e,errorResetBoundary:t,throwOnError:n,query:a,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&a&&(i&&e.data===void 0||Nk(n,[e.error,a])),OT=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),a=e.staleTime;e.staleTime=typeof a=="function"?(...i)=>n(a(...i)):n(a),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},$T=(e,t)=>e?.suspense&&t.isPending,NT=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function DT(e,t,n){const a=RT(),i=TT(),r=Ek(),s=r.defaultQueryOptions(e),c=r.getQueryCache().get(s.queryHash),m=e.subscribed!==!1;s._optimisticResults=a?"isRestoring":m?"optimistic":void 0,OT(s),ET(s,i,c),MT(i);const[u]=y.useState(()=>new t(r,s)),h=u.getOptimisticResult(s),g=!a&&m;if(y.useSyncExternalStore(y.useCallback(S=>{const k=g?u.subscribe(Ln.batchCalls(S)):la;return u.updateResult(),k},[u,g]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),y.useEffect(()=>{u.setOptions(s)},[s,u]),$T(s,h))throw NT(s,u,i);if(jT({result:h,errorResetBoundary:i,throwOnError:s.throwOnError,query:c,suspense:s.suspense}))throw h.error;return s.notifyOnChangeProps?h:u.trackResult(h)}function Bk(e,t){return DT(e,ST)}function HT(){return new CT({defaultOptions:{queries:{staleTime:6e4,gcTime:15*6e4,retry:1,refetchOnWindowFocus:!1}}})}var jy;function ve(e,t,n){function a(c,m){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:m,constr:s,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,m);const u=s.prototype,h=Object.keys(u);for(let g=0;g<h.length;g++){const S=h[g];S in c||(c[S]=u[S].bind(c))}}const i=n?.Parent??Object;class r extends i{}Object.defineProperty(r,"name",{value:e});function s(c){var m;const u=n?.Parent?new r:this;a(u,c),(m=u._zod).deferred??(m.deferred=[]);for(const h of u._zod.deferred)h();return u}return Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class js extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Fk extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(jy=globalThis).__zod_globalConfig??(jy.__zod_globalConfig={});const Xg=globalThis.__zod_globalConfig;function go(e){return Xg}function Vk(e){const t=Object.values(e).filter(a=>typeof a=="number");return Object.entries(e).filter(([a,i])=>t.indexOf(+a)===-1).map(([a,i])=>i)}function Fh(e,t){return typeof t=="bigint"?t.toString():t}function lm(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ev(e){return e==null}function tv(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function LT(e,t){const n=e/t,a=Math.round(n),i=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-a)<i?0:n-a}const Oy=Symbol("evaluating");function At(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==Oy)return a===void 0&&(a=Oy,a=n()),a},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Mr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Wo(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function $y(e){return JSON.stringify(e)}function qT(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const Kk="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function fc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const UT=lm(()=>{if(Xg.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function qs(e){if(fc(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(fc(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Wk(e){return qs(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const zT=new Set(["string","number","symbol"]);function Us(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Go(e,t,n){const a=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(a._zod.parent=e),a}function et(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function BT(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const FT={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 VT(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=Wo(e._zod.def,{get shape(){const s={};for(const c in t){if(!(c in n.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(s[c]=n.shape[c])}return Mr(this,"shape",s),s},checks:[]});return Go(e,r)}function KT(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=Wo(e._zod.def,{get shape(){const s={...e._zod.def.shape};for(const c in t){if(!(c in n.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete s[c]}return Mr(this,"shape",s),s},checks:[]});return Go(e,r)}function WT(e,t){if(!qs(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const r=e._zod.def.shape;for(const s in t)if(Object.getOwnPropertyDescriptor(r,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=Wo(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return Mr(this,"shape",r),r}});return Go(e,i)}function GT(e,t){if(!qs(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Wo(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return Mr(this,"shape",a),a}});return Go(e,n)}function JT(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=Wo(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return Mr(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Go(e,n)}function ZT(e,t,n){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=Wo(t._zod.def,{get shape(){const c=t._zod.def.shape,m={...c};if(n)for(const u in n){if(!(u in c))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(m[u]=e?new e({type:"optional",innerType:c[u]}):c[u])}else for(const u in c)m[u]=e?new e({type:"optional",innerType:c[u]}):c[u];return Mr(this,"shape",m),m},checks:[]});return Go(t,s)}function YT(e,t,n){const a=Wo(t._zod.def,{get shape(){const i=t._zod.def.shape,r={...i};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(r[s]=new e({type:"nonoptional",innerType:i[s]}))}else for(const s in i)r[s]=new e({type:"nonoptional",innerType:i[s]});return Mr(this,"shape",r),r}});return Go(t,a)}function Ss(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 QT(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 xs(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function Ld(e){return typeof e=="string"?e:e?.message}function vo(e,t,n){const a=e.message?e.message:Ld(e.inst?._zod.def?.error?.(e))??Ld(t?.error?.(e))??Ld(n.customError?.(e))??Ld(n.localeError?.(e))??"Invalid input",{inst:i,continue:r,input:s,...c}=e;return c.path??(c.path=[]),c.message=a,t?.reportInput&&(c.input=s),c}function nv(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function hc(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}const Gk=(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,Fh,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Jk=ve("$ZodError",Gk),Zk=ve("$ZodError",Gk,{Parent:Error});function XT(e,t=n=>n.message){const n={},a=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):a.push(t(i));return{formErrors:a,fieldErrors:n}}function eE(e,t=n=>n.message){const n={_errors:[]},a=(i,r=[])=>{for(const s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(c=>a({issues:c},[...r,...s.path]));else if(s.code==="invalid_key")a({issues:s.issues},[...r,...s.path]);else if(s.code==="invalid_element")a({issues:s.issues},[...r,...s.path]);else{const c=[...r,...s.path];if(c.length===0)n._errors.push(t(s));else{let m=n,u=0;for(;u<c.length;){const h=c[u];u===c.length-1?(m[h]=m[h]||{_errors:[]},m[h]._errors.push(t(s))):m[h]=m[h]||{_errors:[]},m=m[h],u++}}}};return a(e),n}const av=e=>(t,n,a,i)=>{const r=a?{...a,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise)throw new js;if(s.issues.length){const c=new(i?.Err??e)(s.issues.map(m=>vo(m,r,go())));throw Kk(c,i?.callee),c}return s.value},iv=e=>async(t,n,a,i)=>{const r=a?{...a,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise&&(s=await s),s.issues.length){const c=new(i?.Err??e)(s.issues.map(m=>vo(m,r,go())));throw Kk(c,i?.callee),c}return s.value},cm=e=>(t,n,a)=>{const i=a?{...a,async:!1}:{async:!1},r=t._zod.run({value:n,issues:[]},i);if(r instanceof Promise)throw new js;return r.issues.length?{success:!1,error:new(e??Jk)(r.issues.map(s=>vo(s,i,go())))}:{success:!0,data:r.value}},tE=cm(Zk),dm=e=>async(t,n,a)=>{const i=a?{...a,async:!0}:{async:!0};let r=t._zod.run({value:n,issues:[]},i);return r instanceof Promise&&(r=await r),r.issues.length?{success:!1,error:new e(r.issues.map(s=>vo(s,i,go())))}:{success:!0,data:r.value}},nE=dm(Zk),aE=e=>(t,n,a)=>{const i=a?{...a,direction:"backward"}:{direction:"backward"};return av(e)(t,n,i)},iE=e=>(t,n,a)=>av(e)(t,n,a),oE=e=>async(t,n,a)=>{const i=a?{...a,direction:"backward"}:{direction:"backward"};return iv(e)(t,n,i)},rE=e=>async(t,n,a)=>iv(e)(t,n,a),sE=e=>(t,n,a)=>{const i=a?{...a,direction:"backward"}:{direction:"backward"};return cm(e)(t,n,i)},lE=e=>(t,n,a)=>cm(e)(t,n,a),cE=e=>async(t,n,a)=>{const i=a?{...a,direction:"backward"}:{direction:"backward"};return dm(e)(t,n,i)},dE=e=>async(t,n,a)=>dm(e)(t,n,a),uE=/^[cC][0-9a-z]{6,}$/,mE=/^[0-9a-z]+$/,pE=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,fE=/^[0-9a-vA-V]{20}$/,hE=/^[A-Za-z0-9]{27}$/,gE=/^[a-zA-Z0-9_-]{21}$/,vE=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,bE=/^([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})$/,Ny=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)$/,yE=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,SE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function xE(){return new RegExp(SE,"u")}const kE=/^(?:(?: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])$/,IE=/^(([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}|:))$/,wE=/^((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])$/,_E=/^(([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])$/,CE=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Yk=/^[A-Za-z0-9_-]*$/,RE=/^https?$/,PE=/^\+[1-9]\d{6,14}$/,Qk="(?:(?:\\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])))",AE=new RegExp(`^${Qk}$`);function Xk(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 TE(e){return new RegExp(`^${Xk(e)}$`)}function EE(e){const t=Xk({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(`^${Qk}T(?:${a})$`)}const ME=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},jE=/^-?\d+$/,eI=/^-?\d+(?:\.\d+)?$/,OE=/^(?:true|false)$/i,$E=/^null$/i,NE=/^[^A-Z]*$/,DE=/^[^a-z]*$/,fa=ve("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),tI={number:"number",bigint:"bigint",object:"date"},nI=ve("$ZodCheckLessThan",(e,t)=>{fa.init(e,t);const n=tI[typeof t.value];e._zod.onattach.push(a=>{const i=a._zod.bag,r=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?i.maximum=t.value:i.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})}}),aI=ve("$ZodCheckGreaterThan",(e,t)=>{fa.init(e,t);const n=tI[typeof t.value];e._zod.onattach.push(a=>{const i=a._zod.bag,r=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?i.minimum=t.value:i.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})}}),HE=ve("$ZodCheckMultipleOf",(e,t)=>{fa.init(e,t),e._zod.onattach.push(n=>{var a;(a=n._zod.bag).multipleOf??(a.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):LT(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})}}),LE=ve("$ZodCheckNumberFormat",(e,t)=>{fa.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),a=n?"int":"number",[i,r]=FT[t.format];e._zod.onattach.push(s=>{const c=s._zod.bag;c.format=t.format,c.minimum=i,c.maximum=r,n&&(c.pattern=jE)}),e._zod.check=s=>{const c=s.value;if(n){if(!Number.isInteger(c)){s.issues.push({expected:a,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?s.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}):s.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort});return}}c<i&&s.issues.push({origin:"number",input:c,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),c>r&&s.issues.push({origin:"number",input:c,code:"too_big",maximum:r,inclusive:!0,inst:e,continue:!t.abort})}}),qE=ve("$ZodCheckMaxLength",(e,t)=>{var n;fa.init(e,t),(n=e._zod.def).when??(n.when=a=>{const i=a.value;return!ev(i)&&i.length!==void 0}),e._zod.onattach.push(a=>{const i=a._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(a._zod.bag.maximum=t.maximum)}),e._zod.check=a=>{const i=a.value;if(i.length<=t.maximum)return;const s=nv(i);a.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),UE=ve("$ZodCheckMinLength",(e,t)=>{var n;fa.init(e,t),(n=e._zod.def).when??(n.when=a=>{const i=a.value;return!ev(i)&&i.length!==void 0}),e._zod.onattach.push(a=>{const i=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(a._zod.bag.minimum=t.minimum)}),e._zod.check=a=>{const i=a.value;if(i.length>=t.minimum)return;const s=nv(i);a.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),zE=ve("$ZodCheckLengthEquals",(e,t)=>{var n;fa.init(e,t),(n=e._zod.def).when??(n.when=a=>{const i=a.value;return!ev(i)&&i.length!==void 0}),e._zod.onattach.push(a=>{const i=a._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=a=>{const i=a.value,r=i.length;if(r===t.length)return;const s=nv(i),c=r>t.length;a.issues.push({origin:s,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:a.value,inst:e,continue:!t.abort})}}),um=ve("$ZodCheckStringFormat",(e,t)=>{var n,a;fa.init(e,t),e._zod.onattach.push(i=>{const r=i._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=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),BE=ve("$ZodCheckRegex",(e,t)=>{um.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})}}),FE=ve("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=NE),um.init(e,t)}),VE=ve("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=DE),um.init(e,t)}),KE=ve("$ZodCheckIncludes",(e,t)=>{fa.init(e,t);const n=Us(t.includes),a=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=a,e._zod.onattach.push(i=>{const r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(a)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),WE=ve("$ZodCheckStartsWith",(e,t)=>{fa.init(e,t);const n=new RegExp(`^${Us(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const i=a._zod.bag;i.patterns??(i.patterns=new Set),i.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})}}),GE=ve("$ZodCheckEndsWith",(e,t)=>{fa.init(e,t);const n=new RegExp(`.*${Us(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const i=a._zod.bag;i.patterns??(i.patterns=new Set),i.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})}}),JE=ve("$ZodCheckOverwrite",(e,t)=>{fa.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class ZE{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const a=t.split(`
3
+ `).filter(s=>s),i=Math.min(...a.map(s=>s.length-s.trimStart().length)),r=a.map(s=>s.slice(i)).map(s=>" ".repeat(this.indent*2)+s);for(const s of r)this.content.push(s)}compile(){const t=Function,n=this?.args,i=[...(this?.content??[""]).map(r=>` ${r}`)];return new t(...n,i.join(`
4
+ `))}}const YE={major:4,minor:4,patch:3},an=ve("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=YE;const a=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&a.unshift(e);for(const i of a)for(const r of i._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 i=(s,c,m)=>{let u=Ss(s),h;for(const g of c){if(g._zod.def.when){if(QT(s)||!g._zod.def.when(s))continue}else if(u)continue;const S=s.issues.length,k=g._zod.check(s);if(k instanceof Promise&&m?.async===!1)throw new js;if(h||k instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await k,s.issues.length!==S&&(u||(u=Ss(s,S)))});else{if(s.issues.length===S)continue;u||(u=Ss(s,S))}}return h?h.then(()=>s):s},r=(s,c,m)=>{if(Ss(s))return s.aborted=!0,s;const u=i(c,a,m);if(u instanceof Promise){if(m.async===!1)throw new js;return u.then(h=>e._zod.parse(h,m))}return e._zod.parse(u,m)};e._zod.run=(s,c)=>{if(c.skipChecks)return e._zod.parse(s,c);if(c.direction==="backward"){const u=e._zod.parse({value:s.value,issues:[]},{...c,skipChecks:!0});return u instanceof Promise?u.then(h=>r(h,s,c)):r(u,s,c)}const m=e._zod.parse(s,c);if(m instanceof Promise){if(c.async===!1)throw new js;return m.then(u=>i(u,a,c))}return i(m,a,c)}}At(e,"~standard",()=>({validate:i=>{try{const r=tE(e,i);return r.success?{value:r.data}:{issues:r.error?.issues}}catch{return nE(e,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),ov=ve("$ZodString",(e,t)=>{an.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ME(e._zod.bag),e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),sn=ve("$ZodStringFormat",(e,t)=>{um.init(e,t),ov.init(e,t)}),QE=ve("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=bE),sn.init(e,t)}),XE=ve("$ZodUUID",(e,t)=>{if(t.version){const a={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(a===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Ny(a))}else t.pattern??(t.pattern=Ny());sn.init(e,t)}),eM=ve("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=yE),sn.init(e,t)}),tM=ve("$ZodURL",(e,t)=>{sn.init(e,t),e._zod.check=n=>{try{const a=n.value.trim();if(!t.normalize&&t.protocol?.source===RE.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 i=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.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(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.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=i.href:n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),nM=ve("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=xE()),sn.init(e,t)}),aM=ve("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=gE),sn.init(e,t)}),iM=ve("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=uE),sn.init(e,t)}),oM=ve("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=mE),sn.init(e,t)}),rM=ve("$ZodULID",(e,t)=>{t.pattern??(t.pattern=pE),sn.init(e,t)}),sM=ve("$ZodXID",(e,t)=>{t.pattern??(t.pattern=fE),sn.init(e,t)}),lM=ve("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=hE),sn.init(e,t)}),cM=ve("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=EE(t)),sn.init(e,t)}),dM=ve("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=AE),sn.init(e,t)}),uM=ve("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=TE(t)),sn.init(e,t)}),mM=ve("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=vE),sn.init(e,t)}),pM=ve("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=kE),sn.init(e,t),e._zod.bag.format="ipv4"}),fM=ve("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=IE),sn.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),hM=ve("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=wE),sn.init(e,t)}),gM=ve("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=_E),sn.init(e,t),e._zod.check=n=>{const a=n.value.split("/");try{if(a.length!==2)throw new Error;const[i,r]=a;if(!r)throw new Error;const s=Number(r);if(`${s}`!==r)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function iI(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const vM=ve("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=CE),sn.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{iI(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function bM(e){if(!Yk.test(e))return!1;const t=e.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return iI(n)}const yM=ve("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Yk),sn.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{bM(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),SM=ve("$ZodE164",(e,t)=>{t.pattern??(t.pattern=PE),sn.init(e,t)});function xM(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[a]=n;if(!a)return!1;const i=JSON.parse(atob(a));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}const kM=ve("$ZodJWT",(e,t)=>{sn.init(e,t),e._zod.check=n=>{xM(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),oI=ve("$ZodNumber",(e,t)=>{an.init(e,t),e._zod.pattern=e._zod.bag.pattern??eI,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const i=n.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;const r=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...r?{received:r}:{}}),n}}),IM=ve("$ZodNumberFormat",(e,t)=>{LE.init(e,t),oI.init(e,t)}),wM=ve("$ZodBoolean",(e,t)=>{an.init(e,t),e._zod.pattern=OE,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=!!n.value}catch{}const i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),_M=ve("$ZodNull",(e,t)=>{an.init(e,t),e._zod.pattern=$E,e._zod.values=new Set([null]),e._zod.parse=(n,a)=>{const i=n.value;return i===null||n.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),n}}),CM=ve("$ZodUnknown",(e,t)=>{an.init(e,t),e._zod.parse=n=>n}),RM=ve("$ZodNever",(e,t)=>{an.init(e,t),e._zod.parse=(n,a)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Dy(e,t,n){e.issues.length&&t.issues.push(...xs(n,e.issues)),t.value[n]=e.value}const PM=ve("$ZodArray",(e,t)=>{an.init(e,t),e._zod.parse=(n,a)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const r=[];for(let s=0;s<i.length;s++){const c=i[s],m=t.element._zod.run({value:c,issues:[]},a);m instanceof Promise?r.push(m.then(u=>Dy(u,n,s))):Dy(m,n,s)}return r.length?Promise.all(r).then(()=>n):n}});function Eu(e,t,n,a,i,r){const s=n in a;if(e.issues.length){if(i&&r&&!s)return;t.issues.push(...xs(n,e.issues))}if(!s&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?s&&(t.value[n]=void 0):t.value[n]=e.value}function rI(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=BT(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function sI(e,t,n,a,i,r){const s=[],c=i.keySet,m=i.catchall._zod,u=m.def.type,h=m.optin==="optional",g=m.optout==="optional";for(const S in t){if(S==="__proto__"||c.has(S))continue;if(u==="never"){s.push(S);continue}const k=m.run({value:t[S],issues:[]},a);k instanceof Promise?e.push(k.then(C=>Eu(C,n,S,t,h,g))):Eu(k,n,S,t,h,g)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:r}),e.length?Promise.all(e).then(()=>n):n}const AM=ve("$ZodObject",(e,t)=>{if(an.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const c=t.shape;Object.defineProperty(t,"shape",{get:()=>{const m={...c};return Object.defineProperty(t,"shape",{value:m}),m}})}const a=lm(()=>rI(t));At(e._zod,"propValues",()=>{const c=t.shape,m={};for(const u in c){const h=c[u]._zod;if(h.values){m[u]??(m[u]=new Set);for(const g of h.values)m[u].add(g)}}return m});const i=fc,r=t.catchall;let s;e._zod.parse=(c,m)=>{s??(s=a.value);const u=c.value;if(!i(u))return c.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),c;c.value={};const h=[],g=s.shape;for(const S of s.keys){const k=g[S],C=k._zod.optin==="optional",A=k._zod.optout==="optional",M=k._zod.run({value:u[S],issues:[]},m);M instanceof Promise?h.push(M.then(R=>Eu(R,c,S,u,C,A))):Eu(M,c,S,u,C,A)}return r?sI(h,u,c,m,a.value,e):h.length?Promise.all(h).then(()=>c):c}}),TM=ve("$ZodObjectJIT",(e,t)=>{AM.init(e,t);const n=e._zod.parse,a=lm(()=>rI(t)),i=S=>{const k=new ZE(["shape","payload","ctx"]),C=a.value,A=O=>{const j=$y(O);return`shape[${j}]._zod.run({ value: input[${j}], issues: [] }, ctx)`};k.write("const input = payload.value;");const M=Object.create(null);let R=0;for(const O of C.keys)M[O]=`key_${R++}`;k.write("const newResult = {};");for(const O of C.keys){const j=M[O],I=$y(O),P=S[O],E=P?._zod?.optin==="optional",L=P?._zod?.optout==="optional";k.write(`const ${j} = ${A(O)};`),E&&L?k.write(`
5
+ if (${j}.issues.length) {
6
+ if (${I} in input) {
7
+ payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
8
+ ...iss,
9
+ path: iss.path ? [${I}, ...iss.path] : [${I}]
10
+ })));
11
+ }
12
+ }
13
+
14
+ if (${j}.value === undefined) {
15
+ if (${I} in input) {
16
+ newResult[${I}] = undefined;
17
+ }
18
+ } else {
19
+ newResult[${I}] = ${j}.value;
20
+ }
21
+
22
+ `):E?k.write(`
23
+ if (${j}.issues.length) {
24
+ payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
25
+ ...iss,
26
+ path: iss.path ? [${I}, ...iss.path] : [${I}]
27
+ })));
28
+ }
29
+
30
+ if (${j}.value === undefined) {
31
+ if (${I} in input) {
32
+ newResult[${I}] = undefined;
33
+ }
34
+ } else {
35
+ newResult[${I}] = ${j}.value;
36
+ }
37
+
38
+ `):k.write(`
39
+ const ${j}_present = ${I} in input;
40
+ if (${j}.issues.length) {
41
+ payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
42
+ ...iss,
43
+ path: iss.path ? [${I}, ...iss.path] : [${I}]
44
+ })));
45
+ }
46
+ if (!${j}_present && !${j}.issues.length) {
47
+ payload.issues.push({
48
+ code: "invalid_type",
49
+ expected: "nonoptional",
50
+ input: undefined,
51
+ path: [${I}]
52
+ });
53
+ }
54
+
55
+ if (${j}_present) {
56
+ if (${j}.value === undefined) {
57
+ newResult[${I}] = undefined;
58
+ } else {
59
+ newResult[${I}] = ${j}.value;
60
+ }
61
+ }
62
+
63
+ `)}k.write("payload.value = newResult;"),k.write("return payload;");const $=k.compile();return(O,j)=>$(S,O,j)};let r;const s=fc,c=!Xg.jitless,u=c&&UT.value,h=t.catchall;let g;e._zod.parse=(S,k)=>{g??(g=a.value);const C=S.value;return s(C)?c&&u&&k?.async===!1&&k.jitless!==!0?(r||(r=i(t.shape)),S=r(S,k),h?sI([],C,S,k,g,e):S):n(S,k):(S.issues.push({expected:"object",code:"invalid_type",input:C,inst:e}),S)}});function Hy(e,t,n,a){for(const r of e)if(r.issues.length===0)return t.value=r.value,t;const i=e.filter(r=>!Ss(r));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(r=>r.issues.map(s=>vo(s,a,go())))}),t)}const lI=ve("$ZodUnion",(e,t)=>{an.init(e,t),At(e._zod,"optin",()=>t.options.some(a=>a._zod.optin==="optional")?"optional":void 0),At(e._zod,"optout",()=>t.options.some(a=>a._zod.optout==="optional")?"optional":void 0),At(e._zod,"values",()=>{if(t.options.every(a=>a._zod.values))return new Set(t.options.flatMap(a=>Array.from(a._zod.values)))}),At(e._zod,"pattern",()=>{if(t.options.every(a=>a._zod.pattern)){const a=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${a.map(i=>tv(i.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(a,i)=>{if(n)return n(a,i);let r=!1;const s=[];for(const c of t.options){const m=c._zod.run({value:a.value,issues:[]},i);if(m instanceof Promise)s.push(m),r=!0;else{if(m.issues.length===0)return m;s.push(m)}}return r?Promise.all(s).then(c=>Hy(c,a,e,i)):Hy(s,a,e,i)}}),EM=ve("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,lI.init(e,t);const n=e._zod.parse;At(e._zod,"propValues",()=>{const i={};for(const r of t.options){const s=r._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const[c,m]of Object.entries(s)){i[c]||(i[c]=new Set);for(const u of m)i[c].add(u)}}return i});const a=lm(()=>{const i=t.options,r=new Map;for(const s of i){const c=s._zod.propValues?.[t.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const m of c){if(r.has(m))throw new Error(`Duplicate discriminator value "${String(m)}"`);r.set(m,s)}}return r});e._zod.parse=(i,r)=>{const s=i.value;if(!fc(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),i;const c=a.value.get(s?.[t.discriminator]);return c?c._zod.run(i,r):t.unionFallback||r.direction==="backward"?n(i,r):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(a.value.keys()),input:s,path:[t.discriminator],inst:e}),i)}}),MM=ve("$ZodIntersection",(e,t)=>{an.init(e,t),e._zod.parse=(n,a)=>{const i=n.value,r=t.left._zod.run({value:i,issues:[]},a),s=t.right._zod.run({value:i,issues:[]},a);return r instanceof Promise||s instanceof Promise?Promise.all([r,s]).then(([m,u])=>Ly(n,m,u)):Ly(n,r,s)}});function Vh(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(qs(e)&&qs(t)){const n=Object.keys(t),a=Object.keys(e).filter(r=>n.indexOf(r)!==-1),i={...e,...t};for(const r of a){const s=Vh(e[r],t[r]);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};i[r]=s.data}return{valid:!0,data:i}}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 i=e[a],r=t[a],s=Vh(i,r);if(!s.valid)return{valid:!1,mergeErrorPath:[a,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Ly(e,t,n){const a=new Map;let i;for(const c of t.issues)if(c.code==="unrecognized_keys"){i??(i=c);for(const m of c.keys)a.has(m)||a.set(m,{}),a.get(m).l=!0}else e.issues.push(c);for(const c of n.issues)if(c.code==="unrecognized_keys")for(const m of c.keys)a.has(m)||a.set(m,{}),a.get(m).r=!0;else e.issues.push(c);const r=[...a].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(r.length&&i&&e.issues.push({...i,keys:r}),Ss(e))return e;const s=Vh(t.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}const jM=ve("$ZodRecord",(e,t)=>{an.init(e,t),e._zod.parse=(n,a)=>{const i=n.value;if(!qs(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;const r=[],s=t.keyType._zod.values;if(s){n.value={};const c=new Set;for(const u of s)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){c.add(typeof u=="number"?u.toString():u);const h=t.keyType._zod.run({value:u,issues:[]},a);if(h instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(h.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:h.issues.map(k=>vo(k,a,go())),input:u,path:[u],inst:e});continue}const g=h.value,S=t.valueType._zod.run({value:i[u],issues:[]},a);S instanceof Promise?r.push(S.then(k=>{k.issues.length&&n.issues.push(...xs(u,k.issues)),n.value[g]=k.value})):(S.issues.length&&n.issues.push(...xs(u,S.issues)),n.value[g]=S.value)}let m;for(const u in i)c.has(u)||(m=m??[],m.push(u));m&&m.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:m})}else{n.value={};for(const c of Reflect.ownKeys(i)){if(c==="__proto__"||!Object.prototype.propertyIsEnumerable.call(i,c))continue;let m=t.keyType._zod.run({value:c,issues:[]},a);if(m instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof c=="string"&&eI.test(c)&&m.issues.length){const g=t.keyType._zod.run({value:Number(c),issues:[]},a);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");g.issues.length===0&&(m=g)}if(m.issues.length){t.mode==="loose"?n.value[c]=i[c]:n.issues.push({code:"invalid_key",origin:"record",issues:m.issues.map(g=>vo(g,a,go())),input:c,path:[c],inst:e});continue}const h=t.valueType._zod.run({value:i[c],issues:[]},a);h instanceof Promise?r.push(h.then(g=>{g.issues.length&&n.issues.push(...xs(c,g.issues)),n.value[m.value]=g.value})):(h.issues.length&&n.issues.push(...xs(c,h.issues)),n.value[m.value]=h.value)}}return r.length?Promise.all(r).then(()=>n):n}}),OM=ve("$ZodEnum",(e,t)=>{an.init(e,t);const n=Vk(t.entries),a=new Set(n);e._zod.values=a,e._zod.pattern=new RegExp(`^(${n.filter(i=>zT.has(typeof i)).map(i=>typeof i=="string"?Us(i):i.toString()).join("|")})$`),e._zod.parse=(i,r)=>{const s=i.value;return a.has(s)||i.issues.push({code:"invalid_value",values:n,input:s,inst:e}),i}}),$M=ve("$ZodLiteral",(e,t)=>{if(an.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(a=>typeof a=="string"?Us(a):a?Us(a.toString()):String(a)).join("|")})$`),e._zod.parse=(a,i)=>{const r=a.value;return n.has(r)||a.issues.push({code:"invalid_value",values:t.values,input:r,inst:e}),a}}),NM=ve("$ZodTransform",(e,t)=>{an.init(e,t),e._zod.optin="optional",e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new Fk(e.constructor.name);const i=t.transform(n.value,n);if(a.async)return(i instanceof Promise?i:Promise.resolve(i)).then(s=>(n.value=s,n.fallback=!0,n));if(i instanceof Promise)throw new js;return n.value=i,n.fallback=!0,n}});function qy(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const cI=ve("$ZodOptional",(e,t)=>{an.init(e,t),e._zod.optin="optional",e._zod.optout="optional",At(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),At(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${tv(n.source)})?$`):void 0}),e._zod.parse=(n,a)=>{if(t.innerType._zod.optin==="optional"){const i=n.value,r=t.innerType._zod.run(n,a);return r instanceof Promise?r.then(s=>qy(s,i)):qy(r,i)}return n.value===void 0?n:t.innerType._zod.run(n,a)}}),DM=ve("$ZodExactOptional",(e,t)=>{cI.init(e,t),At(e._zod,"values",()=>t.innerType._zod.values),At(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,a)=>t.innerType._zod.run(n,a)}),HM=ve("$ZodNullable",(e,t)=>{an.init(e,t),At(e._zod,"optin",()=>t.innerType._zod.optin),At(e._zod,"optout",()=>t.innerType._zod.optout),At(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${tv(n.source)}|null)$`):void 0}),At(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,a)=>n.value===null?n:t.innerType._zod.run(n,a)}),LM=ve("$ZodDefault",(e,t)=>{an.init(e,t),e._zod.optin="optional",At(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(r=>Uy(r,t)):Uy(i,t)}});function Uy(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const qM=ve("$ZodPrefault",(e,t)=>{an.init(e,t),e._zod.optin="optional",At(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>(a.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,a))}),UM=ve("$ZodNonOptional",(e,t)=>{an.init(e,t),At(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(a=>a!==void 0)):void 0}),e._zod.parse=(n,a)=>{const i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(r=>zy(r,e)):zy(i,e)}});function zy(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 zM=ve("$ZodCatch",(e,t)=>{an.init(e,t),e._zod.optin="optional",At(e._zod,"optout",()=>t.innerType._zod.optout),At(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(r=>(n.value=r.value,r.issues.length&&(n.value=t.catchValue({...n,error:{issues:r.issues.map(s=>vo(s,a,go()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(r=>vo(r,a,go()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),dI=ve("$ZodPipe",(e,t)=>{an.init(e,t),At(e._zod,"values",()=>t.in._zod.values),At(e._zod,"optin",()=>t.in._zod.optin),At(e._zod,"optout",()=>t.out._zod.optout),At(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,a)=>{if(a.direction==="backward"){const r=t.out._zod.run(n,a);return r instanceof Promise?r.then(s=>qd(s,t.in,a)):qd(r,t.in,a)}const i=t.in._zod.run(n,a);return i instanceof Promise?i.then(r=>qd(r,t.out,a)):qd(i,t.out,a)}});function qd(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 BM=ve("$ZodPreprocess",(e,t)=>{dI.init(e,t)}),FM=ve("$ZodReadonly",(e,t)=>{an.init(e,t),At(e._zod,"propValues",()=>t.innerType._zod.propValues),At(e._zod,"values",()=>t.innerType._zod.values),At(e._zod,"optin",()=>t.innerType?._zod?.optin),At(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const i=t.innerType._zod.run(n,a);return i instanceof Promise?i.then(By):By(i)}});function By(e){return e.value=Object.freeze(e.value),e}const VM=ve("$ZodLazy",(e,t)=>{an.init(e,t),At(e._zod,"innerType",()=>{const n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),At(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),At(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),At(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),At(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,a)=>e._zod.innerType._zod.run(n,a)}),KM=ve("$ZodCustom",(e,t)=>{fa.init(e,t),an.init(e,t),e._zod.parse=(n,a)=>n,e._zod.check=n=>{const a=n.value,i=t.fn(a);if(i instanceof Promise)return i.then(r=>Fy(r,n,a,e));Fy(i,n,a,e)}});function Fy(e,t,n,a){if(!e){const i={code:"custom",input:n,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(i.params=a._zod.def.params),t.issues.push(hc(i))}}var Vy;class WM{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 i={...a,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function GM(){return new WM}(Vy=globalThis).__zod_globalRegistry??(Vy.__zod_globalRegistry=GM());const Wl=globalThis.__zod_globalRegistry;function JM(e,t){return new e({type:"string",...et(t)})}function ZM(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...et(t)})}function Ky(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...et(t)})}function uI(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...et(t)})}function YM(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...et(t)})}function QM(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...et(t)})}function XM(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...et(t)})}function ej(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...et(t)})}function tj(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...et(t)})}function nj(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...et(t)})}function aj(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...et(t)})}function ij(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...et(t)})}function oj(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...et(t)})}function rj(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...et(t)})}function sj(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...et(t)})}function lj(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...et(t)})}function cj(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...et(t)})}function dj(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...et(t)})}function uj(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...et(t)})}function mj(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...et(t)})}function pj(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...et(t)})}function fj(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...et(t)})}function hj(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...et(t)})}function gj(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...et(t)})}function vj(e,t){return new e({type:"string",format:"date",check:"string_format",...et(t)})}function bj(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...et(t)})}function yj(e,t){return new e({type:"string",format:"duration",check:"string_format",...et(t)})}function Sj(e,t){return new e({type:"number",checks:[],...et(t)})}function yne(e,t){return new e({type:"number",coerce:!0,checks:[],...et(t)})}function xj(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...et(t)})}function kj(e,t){return new e({type:"boolean",...et(t)})}function Ij(e,t){return new e({type:"null",...et(t)})}function wj(e){return new e({type:"unknown"})}function _j(e,t){return new e({type:"never",...et(t)})}function Wy(e,t){return new nI({check:"less_than",...et(t),value:e,inclusive:!1})}function Sf(e,t){return new nI({check:"less_than",...et(t),value:e,inclusive:!0})}function Gy(e,t){return new aI({check:"greater_than",...et(t),value:e,inclusive:!1})}function xf(e,t){return new aI({check:"greater_than",...et(t),value:e,inclusive:!0})}function Jy(e,t){return new HE({check:"multiple_of",...et(t),value:e})}function mI(e,t){return new qE({check:"max_length",...et(t),maximum:e})}function Mu(e,t){return new UE({check:"min_length",...et(t),minimum:e})}function pI(e,t){return new zE({check:"length_equals",...et(t),length:e})}function Cj(e,t){return new BE({check:"string_format",format:"regex",...et(t),pattern:e})}function Rj(e){return new FE({check:"string_format",format:"lowercase",...et(e)})}function Pj(e){return new VE({check:"string_format",format:"uppercase",...et(e)})}function Aj(e,t){return new KE({check:"string_format",format:"includes",...et(t),includes:e})}function Tj(e,t){return new WE({check:"string_format",format:"starts_with",...et(t),prefix:e})}function Ej(e,t){return new GE({check:"string_format",format:"ends_with",...et(t),suffix:e})}function nl(e){return new JE({check:"overwrite",tx:e})}function Mj(e){return nl(t=>t.normalize(e))}function jj(){return nl(e=>e.trim())}function Oj(){return nl(e=>e.toLowerCase())}function $j(){return nl(e=>e.toUpperCase())}function Nj(){return nl(e=>qT(e))}function Dj(e,t,n){return new e({type:"array",element:t,...et(n)})}function Hj(e,t,n){const a=et(n);return a.abort??(a.abort=!0),new e({type:"custom",check:"custom",fn:t,...a})}function Lj(e,t,n){return new e({type:"custom",check:"custom",fn:t,...et(n)})}function qj(e,t){const n=Uj(a=>(a.addIssue=i=>{if(typeof i=="string")a.issues.push(hc(i,a.value,n._zod.def));else{const r=i;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(hc(r))}},e(a.value,a)),t);return n}function Uj(e,t){const n=new fa({check:"custom",...et(t)});return n._zod.check=e,n}function fI(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Wl,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function vn(e,t,n={path:[],schemaPath:[]}){var a;const i=e._zod.def,r=t.seen.get(e);if(r)return r.count++,n.schemaPath.includes(e)&&(r.cycle=n.path),r.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const c=e._zod.toJSONSchema?.();if(c)s.schema=c;else{const h={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,h);else{const S=s.schema,k=t.processors[i.type];if(!k)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);k(e,t,S,h)}const g=e._zod.parent;g&&(s.ref||(s.ref=g),vn(g,t,h),t.seen.get(g).isParent=!0)}const m=t.metadataRegistry.get(e);return m&&Object.assign(s.schema,m),t.io==="input"&&Jn(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&"_prefault"in s.schema&&((a=s.schema).default??(a.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function hI(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=new Map;for(const s of e.seen.entries()){const c=e.metadataRegistry.get(s[0])?.id;if(c){const m=a.get(c);if(m&&m!==s[0])throw new Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);a.set(c,s[0])}}const i=s=>{const c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(s[0])?.id,S=e.external.uri??(C=>C);if(g)return{ref:S(g)};const k=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=k,{defId:k,ref:`${S("__shared")}#/${c}/${k}`}}if(s[1]===n)return{ref:"#"};const u=`#/${c}/`,h=s[1].schema.id??`__schema${e.counter++}`;return{defId:h,ref:u+h}},r=s=>{if(s[1].schema.$ref)return;const c=s[1],{ref:m,defId:u}=i(s);c.def={...c.schema},u&&(c.defId=u);const h=c.schema;for(const g in h)delete h[g];h.$ref=m};if(e.cycles==="throw")for(const s of e.seen.entries()){const c=s[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
64
+
65
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const c=s[1];if(t===s[0]){r(s);continue}if(e.external){const u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){r(s);continue}}if(e.metadataRegistry.get(s[0])?.id){r(s);continue}if(c.cycle){r(s);continue}if(c.count>1&&e.reused==="ref"){r(s);continue}}}function gI(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=c=>{const m=e.seen.get(c);if(m.ref===null)return;const u=m.def??m.schema,h={...u},g=m.ref;if(m.ref=null,g){a(g);const k=e.seen.get(g),C=k.schema;if(C.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(C)):Object.assign(u,C),Object.assign(u,h),c._zod.parent===g)for(const M in u)M==="$ref"||M==="allOf"||M in h||delete u[M];if(C.$ref&&k.def)for(const M in u)M==="$ref"||M==="allOf"||M in k.def&&JSON.stringify(u[M])===JSON.stringify(k.def[M])&&delete u[M]}const S=c._zod.parent;if(S&&S!==g){a(S);const k=e.seen.get(S);if(k?.schema.$ref&&(u.$ref=k.schema.$ref,k.def))for(const C in u)C==="$ref"||C==="allOf"||C in k.def&&JSON.stringify(u[C])===JSON.stringify(k.def[C])&&delete u[C]}e.override({zodSchema:c,jsonSchema:u,path:m.path??[]})};for(const c of[...e.seen.entries()].reverse())a(c[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$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");i.$id=e.external.uri(c)}Object.assign(i,n.def??n.schema);const r=e.metadataRegistry.get(t)?.id;r!==void 0&&i.id===r&&delete i.id;const s=e.external?.defs??{};for(const c of e.seen.entries()){const m=c[1];m.def&&m.defId&&(m.def.id===m.defId&&delete m.def.id,s[m.defId]=m.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?i.$defs=s:i.definitions=s);try{const c=JSON.parse(JSON.stringify(i));return Object.defineProperty(c,"~standard",{value:{...t["~standard"],jsonSchema:{input:ju(t,"input",e.processors),output:ju(t,"output",e.processors)}},enumerable:!1,writable:!1}),c}catch{throw new Error("Error converting schema to JSON.")}}function Jn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const a=e._zod.def;if(a.type==="transform")return!0;if(a.type==="array")return Jn(a.element,n);if(a.type==="set")return Jn(a.valueType,n);if(a.type==="lazy")return Jn(a.getter(),n);if(a.type==="promise"||a.type==="optional"||a.type==="nonoptional"||a.type==="nullable"||a.type==="readonly"||a.type==="default"||a.type==="prefault")return Jn(a.innerType,n);if(a.type==="intersection")return Jn(a.left,n)||Jn(a.right,n);if(a.type==="record"||a.type==="map")return Jn(a.keyType,n)||Jn(a.valueType,n);if(a.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Jn(a.in,n)||Jn(a.out,n);if(a.type==="object"){for(const i in a.shape)if(Jn(a.shape[i],n))return!0;return!1}if(a.type==="union"){for(const i of a.options)if(Jn(i,n))return!0;return!1}if(a.type==="tuple"){for(const i of a.items)if(Jn(i,n))return!0;return!!(a.rest&&Jn(a.rest,n))}return!1}const zj=(e,t={})=>n=>{const a=fI({...n,processors:t});return vn(e,a),hI(a,e),gI(a,e)},ju=(e,t,n={})=>a=>{const{libraryOptions:i,target:r}=a??{},s=fI({...i??{},target:r,io:t,processors:n});return vn(e,s),hI(s,e),gI(s,e)},Bj={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Fj=(e,t,n,a)=>{const i=n;i.type="string";const{minimum:r,maximum:s,format:c,patterns:m,contentEncoding:u}=e._zod.bag;if(typeof r=="number"&&(i.minLength=r),typeof s=="number"&&(i.maxLength=s),c&&(i.format=Bj[c]??c,i.format===""&&delete i.format,c==="time"&&delete i.format),u&&(i.contentEncoding=u),m&&m.size>0){const h=[...m];h.length===1?i.pattern=h[0].source:h.length>1&&(i.allOf=[...h.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},Vj=(e,t,n,a)=>{const i=n,{minimum:r,maximum:s,format:c,multipleOf:m,exclusiveMaximum:u,exclusiveMinimum:h}=e._zod.bag;typeof c=="string"&&c.includes("int")?i.type="integer":i.type="number";const g=typeof h=="number"&&h>=(r??Number.NEGATIVE_INFINITY),S=typeof u=="number"&&u<=(s??Number.POSITIVE_INFINITY),k=t.target==="draft-04"||t.target==="openapi-3.0";g?k?(i.minimum=h,i.exclusiveMinimum=!0):i.exclusiveMinimum=h:typeof r=="number"&&(i.minimum=r),S?k?(i.maximum=u,i.exclusiveMaximum=!0):i.exclusiveMaximum=u:typeof s=="number"&&(i.maximum=s),typeof m=="number"&&(i.multipleOf=m)},Kj=(e,t,n,a)=>{n.type="boolean"},Wj=(e,t,n,a)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},Gj=(e,t,n,a)=>{n.not={}},Jj=(e,t,n,a)=>{},Zj=(e,t,n,a)=>{const i=e._zod.def,r=Vk(i.entries);r.every(s=>typeof s=="number")&&(n.type="number"),r.every(s=>typeof s=="string")&&(n.type="string"),n.enum=r},Yj=(e,t,n,a)=>{const i=e._zod.def,r=[];for(const s of i.values)if(s===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");r.push(Number(s))}else r.push(s);if(r.length!==0)if(r.length===1){const s=r[0];n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[s]:n.const=s}else r.every(s=>typeof s=="number")&&(n.type="number"),r.every(s=>typeof s=="string")&&(n.type="string"),r.every(s=>typeof s=="boolean")&&(n.type="boolean"),r.every(s=>s===null)&&(n.type="null"),n.enum=r},Qj=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Xj=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},eO=(e,t,n,a)=>{const i=n,r=e._zod.def,{minimum:s,maximum:c}=e._zod.bag;typeof s=="number"&&(i.minItems=s),typeof c=="number"&&(i.maxItems=c),i.type="array",i.items=vn(r.element,t,{...a,path:[...a.path,"items"]})},tO=(e,t,n,a)=>{const i=n,r=e._zod.def;i.type="object",i.properties={};const s=r.shape;for(const u in s)i.properties[u]=vn(s[u],t,{...a,path:[...a.path,"properties",u]});const c=new Set(Object.keys(s)),m=new Set([...c].filter(u=>{const h=r.shape[u]._zod;return t.io==="input"?h.optin===void 0:h.optout===void 0}));m.size>0&&(i.required=Array.from(m)),r.catchall?._zod.def.type==="never"?i.additionalProperties=!1:r.catchall?r.catchall&&(i.additionalProperties=vn(r.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},nO=(e,t,n,a)=>{const i=e._zod.def,r=i.inclusive===!1,s=i.options.map((c,m)=>vn(c,t,{...a,path:[...a.path,r?"oneOf":"anyOf",m]}));r?n.oneOf=s:n.anyOf=s},aO=(e,t,n,a)=>{const i=e._zod.def,r=vn(i.left,t,{...a,path:[...a.path,"allOf",0]}),s=vn(i.right,t,{...a,path:[...a.path,"allOf",1]}),c=u=>"allOf"in u&&Object.keys(u).length===1,m=[...c(r)?r.allOf:[r],...c(s)?s.allOf:[s]];n.allOf=m},iO=(e,t,n,a)=>{const i=n,r=e._zod.def;i.type="object";const s=r.keyType,m=s._zod.bag?.patterns;if(r.mode==="loose"&&m&&m.size>0){const h=vn(r.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});i.patternProperties={};for(const g of m)i.patternProperties[g.source]=h}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(i.propertyNames=vn(r.keyType,t,{...a,path:[...a.path,"propertyNames"]})),i.additionalProperties=vn(r.valueType,t,{...a,path:[...a.path,"additionalProperties"]});const u=s._zod.values;if(u){const h=[...u].filter(g=>typeof g=="string"||typeof g=="number");h.length>0&&(i.required=h)}},oO=(e,t,n,a)=>{const i=e._zod.def,r=vn(i.innerType,t,a),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=i.innerType,n.nullable=!0):n.anyOf=[r,{type:"null"}]},rO=(e,t,n,a)=>{const i=e._zod.def;vn(i.innerType,t,a);const r=t.seen.get(e);r.ref=i.innerType},sO=(e,t,n,a)=>{const i=e._zod.def;vn(i.innerType,t,a);const r=t.seen.get(e);r.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},lO=(e,t,n,a)=>{const i=e._zod.def;vn(i.innerType,t,a);const r=t.seen.get(e);r.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},cO=(e,t,n,a)=>{const i=e._zod.def;vn(i.innerType,t,a);const r=t.seen.get(e);r.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},dO=(e,t,n,a)=>{const i=e._zod.def,r=i.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?r?i.out:i.in:i.out;vn(s,t,a);const c=t.seen.get(e);c.ref=s},uO=(e,t,n,a)=>{const i=e._zod.def;vn(i.innerType,t,a);const r=t.seen.get(e);r.ref=i.innerType,n.readOnly=!0},vI=(e,t,n,a)=>{const i=e._zod.def;vn(i.innerType,t,a);const r=t.seen.get(e);r.ref=i.innerType},mO=(e,t,n,a)=>{const i=e._zod.innerType;vn(i,t,a);const r=t.seen.get(e);r.ref=i},pO=ve("ZodISODateTime",(e,t)=>{cM.init(e,t),cn.init(e,t)});function nn(e){return gj(pO,e)}const fO=ve("ZodISODate",(e,t)=>{dM.init(e,t),cn.init(e,t)});function hO(e){return vj(fO,e)}const gO=ve("ZodISOTime",(e,t)=>{uM.init(e,t),cn.init(e,t)});function vO(e){return bj(gO,e)}const bO=ve("ZodISODuration",(e,t)=>{mM.init(e,t),cn.init(e,t)});function yO(e){return yj(bO,e)}const bI=(e,t)=>{Jk.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>eE(e,n)},flatten:{value:n=>XT(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Fh,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Fh,2)}},isEmpty:{get(){return e.issues.length===0}}})},SO=ve("ZodError",bI),Fa=ve("ZodError",bI,{Parent:Error}),xO=av(Fa),kO=iv(Fa),IO=cm(Fa),wO=dm(Fa),_O=aE(Fa),CO=iE(Fa),RO=oE(Fa),PO=rE(Fa),AO=sE(Fa),TO=lE(Fa),EO=cE(Fa),MO=dE(Fa),Zy=new WeakMap;function zc(e,t,n){const a=Object.getPrototypeOf(e);let i=Zy.get(a);if(i||(i=new Set,Zy.set(a,i)),!i.has(t)){i.add(t);for(const r in n){const s=n[r];Object.defineProperty(a,r,{configurable:!0,enumerable:!1,get(){const c=s.bind(this);return Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:!0,value:c}),c},set(c){Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:!0,value:c})}})}}}const on=ve("ZodType",(e,t)=>(an.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:ju(e,"input"),output:ju(e,"output")}}),e.toJSONSchema=zj(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,a)=>xO(e,n,a,{callee:e.parse}),e.safeParse=(n,a)=>IO(e,n,a),e.parseAsync=async(n,a)=>kO(e,n,a,{callee:e.parseAsync}),e.safeParseAsync=async(n,a)=>wO(e,n,a),e.spa=e.safeParseAsync,e.encode=(n,a)=>_O(e,n,a),e.decode=(n,a)=>CO(e,n,a),e.encodeAsync=async(n,a)=>RO(e,n,a),e.decodeAsync=async(n,a)=>PO(e,n,a),e.safeEncode=(n,a)=>AO(e,n,a),e.safeDecode=(n,a)=>TO(e,n,a),e.safeEncodeAsync=async(n,a)=>EO(e,n,a),e.safeDecodeAsync=async(n,a)=>MO(e,n,a),zc(e,"ZodType",{check(...n){const a=this.def;return this.clone(Wo(a,{checks:[...a.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,a){return Go(this,n,a)},brand(){return this},register(n,a){return n.add(this,a),this},refine(n,a){return this.check(k2(n,a))},superRefine(n,a){return this.check(I2(n,a))},overwrite(n){return this.check(nl(n))},optional(){return e0(this)},exactOptional(){return c2(this)},nullable(){return t0(this)},nullish(){return e0(t0(this))},nonoptional(n){return h2(this,n)},array(){return p(this)},or(n){return ht([this,n])},and(n){return o2(this,n)},transform(n){return n0(this,wI(n))},default(n){return m2(this,n)},prefault(n){return f2(this,n)},catch(n){return v2(this,n)},pipe(n){return n0(this,n)},readonly(){return S2(this)},describe(n){const a=this.clone();return Wl.add(a,{description:n}),a},meta(...n){if(n.length===0)return Wl.get(this);const a=this.clone();return Wl.add(a,n[0]),a},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return Wl.get(e)?.description},configurable:!0}),e)),yI=ve("_ZodString",(e,t)=>{ov.init(e,t),on.init(e,t),e._zod.processJSONSchema=(a,i,r)=>Fj(e,a,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,zc(e,"_ZodString",{regex(...a){return this.check(Cj(...a))},includes(...a){return this.check(Aj(...a))},startsWith(...a){return this.check(Tj(...a))},endsWith(...a){return this.check(Ej(...a))},min(...a){return this.check(Mu(...a))},max(...a){return this.check(mI(...a))},length(...a){return this.check(pI(...a))},nonempty(...a){return this.check(Mu(1,...a))},lowercase(a){return this.check(Rj(a))},uppercase(a){return this.check(Pj(a))},trim(){return this.check(jj())},normalize(...a){return this.check(Mj(...a))},toLowerCase(){return this.check(Oj())},toUpperCase(){return this.check($j())},slugify(){return this.check(Nj())}})}),jO=ve("ZodString",(e,t)=>{ov.init(e,t),yI.init(e,t),e.email=n=>e.check(ZM(OO,n)),e.url=n=>e.check(ej($O,n)),e.jwt=n=>e.check(hj(ZO,n)),e.emoji=n=>e.check(tj(NO,n)),e.guid=n=>e.check(Ky(Yy,n)),e.uuid=n=>e.check(uI(Gl,n)),e.uuidv4=n=>e.check(YM(Gl,n)),e.uuidv6=n=>e.check(QM(Gl,n)),e.uuidv7=n=>e.check(XM(Gl,n)),e.nanoid=n=>e.check(nj(DO,n)),e.guid=n=>e.check(Ky(Yy,n)),e.cuid=n=>e.check(aj(HO,n)),e.cuid2=n=>e.check(ij(LO,n)),e.ulid=n=>e.check(oj(qO,n)),e.base64=n=>e.check(mj(WO,n)),e.base64url=n=>e.check(pj(GO,n)),e.xid=n=>e.check(rj(UO,n)),e.ksuid=n=>e.check(sj(zO,n)),e.ipv4=n=>e.check(lj(BO,n)),e.ipv6=n=>e.check(cj(FO,n)),e.cidrv4=n=>e.check(dj(VO,n)),e.cidrv6=n=>e.check(uj(KO,n)),e.e164=n=>e.check(fj(JO,n)),e.datetime=n=>e.check(nn(n)),e.date=n=>e.check(hO(n)),e.time=n=>e.check(vO(n)),e.duration=n=>e.check(yO(n))});function o(e){return JM(jO,e)}const cn=ve("ZodStringFormat",(e,t)=>{sn.init(e,t),yI.init(e,t)}),OO=ve("ZodEmail",(e,t)=>{eM.init(e,t),cn.init(e,t)}),Yy=ve("ZodGUID",(e,t)=>{QE.init(e,t),cn.init(e,t)}),Gl=ve("ZodUUID",(e,t)=>{XE.init(e,t),cn.init(e,t)});function mm(e){return uI(Gl,e)}const $O=ve("ZodURL",(e,t)=>{tM.init(e,t),cn.init(e,t)}),NO=ve("ZodEmoji",(e,t)=>{nM.init(e,t),cn.init(e,t)}),DO=ve("ZodNanoID",(e,t)=>{aM.init(e,t),cn.init(e,t)}),HO=ve("ZodCUID",(e,t)=>{iM.init(e,t),cn.init(e,t)}),LO=ve("ZodCUID2",(e,t)=>{oM.init(e,t),cn.init(e,t)}),qO=ve("ZodULID",(e,t)=>{rM.init(e,t),cn.init(e,t)}),UO=ve("ZodXID",(e,t)=>{sM.init(e,t),cn.init(e,t)}),zO=ve("ZodKSUID",(e,t)=>{lM.init(e,t),cn.init(e,t)}),BO=ve("ZodIPv4",(e,t)=>{pM.init(e,t),cn.init(e,t)}),FO=ve("ZodIPv6",(e,t)=>{fM.init(e,t),cn.init(e,t)}),VO=ve("ZodCIDRv4",(e,t)=>{hM.init(e,t),cn.init(e,t)}),KO=ve("ZodCIDRv6",(e,t)=>{gM.init(e,t),cn.init(e,t)}),WO=ve("ZodBase64",(e,t)=>{vM.init(e,t),cn.init(e,t)}),GO=ve("ZodBase64URL",(e,t)=>{yM.init(e,t),cn.init(e,t)}),JO=ve("ZodE164",(e,t)=>{SM.init(e,t),cn.init(e,t)}),ZO=ve("ZodJWT",(e,t)=>{kM.init(e,t),cn.init(e,t)}),SI=ve("ZodNumber",(e,t)=>{oI.init(e,t),on.init(e,t),e._zod.processJSONSchema=(a,i,r)=>Vj(e,a,i),zc(e,"ZodNumber",{gt(a,i){return this.check(Gy(a,i))},gte(a,i){return this.check(xf(a,i))},min(a,i){return this.check(xf(a,i))},lt(a,i){return this.check(Wy(a,i))},lte(a,i){return this.check(Sf(a,i))},max(a,i){return this.check(Sf(a,i))},int(a){return this.check(Qy(a))},safe(a){return this.check(Qy(a))},positive(a){return this.check(Gy(0,a))},nonnegative(a){return this.check(xf(0,a))},negative(a){return this.check(Wy(0,a))},nonpositive(a){return this.check(Sf(0,a))},multipleOf(a,i){return this.check(Jy(a,i))},step(a,i){return this.check(Jy(a,i))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function d(e){return Sj(SI,e)}const YO=ve("ZodNumberFormat",(e,t)=>{IM.init(e,t),SI.init(e,t)});function Qy(e){return xj(YO,e)}const QO=ve("ZodBoolean",(e,t)=>{wM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Kj(e,n,a)});function w(e){return kj(QO,e)}const XO=ve("ZodNull",(e,t)=>{_M.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Wj(e,n,a)});function al(e){return Ij(XO,e)}const e2=ve("ZodUnknown",(e,t)=>{CM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Jj()});function ie(){return wj(e2)}const t2=ve("ZodNever",(e,t)=>{RM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Gj(e,n,a)});function xI(e){return _j(t2,e)}const n2=ve("ZodArray",(e,t)=>{PM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>eO(e,n,a,i),e.element=t.element,zc(e,"ZodArray",{min(n,a){return this.check(Mu(n,a))},nonempty(n){return this.check(Mu(1,n))},max(n,a){return this.check(mI(n,a))},length(n,a){return this.check(pI(n,a))},unwrap(){return this.element}})});function p(e,t){return Dj(n2,e,t)}const kI=ve("ZodObject",(e,t)=>{TM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>tO(e,n,a,i),At(e,"shape",()=>t.shape),zc(e,"ZodObject",{keyof(){return v(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:ie()})},loose(){return this.clone({...this._zod.def,catchall:ie()})},strict(){return this.clone({...this._zod.def,catchall:xI()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return WT(this,n)},safeExtend(n){return GT(this,n)},merge(n){return JT(this,n)},pick(n){return VT(this,n)},omit(n){return KT(this,n)},partial(...n){return ZT(_I,this,n[0])},required(...n){return YT(CI,this,n[0])}})});function l(e,t){const n={type:"object",shape:e??{},...et(t)};return new kI(n)}function kf(e,t){return new kI({type:"object",shape:e,catchall:xI(),...et(t)})}const II=ve("ZodUnion",(e,t)=>{lI.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>nO(e,n,a,i),e.options=t.options});function ht(e,t){return new II({type:"union",options:e,...et(t)})}const a2=ve("ZodDiscriminatedUnion",(e,t)=>{II.init(e,t),EM.init(e,t)});function lt(e,t,n){return new a2({type:"union",options:t,discriminator:e,...et(n)})}const i2=ve("ZodIntersection",(e,t)=>{MM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>aO(e,n,a,i)});function o2(e,t){return new i2({type:"intersection",left:e,right:t})}const Xy=ve("ZodRecord",(e,t)=>{jM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>iO(e,n,a,i),e.keyType=t.keyType,e.valueType=t.valueType});function ae(e,t,n){return!t||!t._zod?new Xy({type:"record",keyType:o(),valueType:e,...et(t)}):new Xy({type:"record",keyType:e,valueType:t,...et(n)})}const Kh=ve("ZodEnum",(e,t)=>{OM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(a,i,r)=>Zj(e,a,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(a,i)=>{const r={};for(const s of a)if(n.has(s))r[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Kh({...t,checks:[],...et(i),entries:r})},e.exclude=(a,i)=>{const r={...t.entries};for(const s of a)if(n.has(s))delete r[s];else throw new Error(`Key ${s} not found in enum`);return new Kh({...t,checks:[],...et(i),entries:r})}});function v(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e;return new Kh({type:"enum",entries:n,...et(t)})}const r2=ve("ZodLiteral",(e,t)=>{$M.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Yj(e,n,a),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function b(e,t){return new r2({type:"literal",values:Array.isArray(e)?e:[e],...et(t)})}const s2=ve("ZodTransform",(e,t)=>{NM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Xj(e,n),e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new Fk(e.constructor.name);n.addIssue=r=>{if(typeof r=="string")n.issues.push(hc(r,n.value,t));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(hc(s))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(r=>(n.value=r,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function wI(e){return new s2({type:"transform",transform:e})}const _I=ve("ZodOptional",(e,t)=>{cI.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>vI(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function e0(e){return new _I({type:"optional",innerType:e})}const l2=ve("ZodExactOptional",(e,t)=>{DM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>vI(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function c2(e){return new l2({type:"optional",innerType:e})}const d2=ve("ZodNullable",(e,t)=>{HM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>oO(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function t0(e){return new d2({type:"nullable",innerType:e})}const u2=ve("ZodDefault",(e,t)=>{LM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>sO(e,n,a,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function m2(e,t){return new u2({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Wk(t)}})}const p2=ve("ZodPrefault",(e,t)=>{qM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>lO(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function f2(e,t){return new p2({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Wk(t)}})}const CI=ve("ZodNonOptional",(e,t)=>{UM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>rO(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function h2(e,t){return new CI({type:"nonoptional",innerType:e,...et(t)})}const g2=ve("ZodCatch",(e,t)=>{zM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>cO(e,n,a,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function v2(e,t){return new g2({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const RI=ve("ZodPipe",(e,t)=>{dI.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>dO(e,n,a,i),e.in=t.in,e.out=t.out});function n0(e,t){return new RI({type:"pipe",in:e,out:t})}const b2=ve("ZodPreprocess",(e,t)=>{RI.init(e,t),BM.init(e,t)}),y2=ve("ZodReadonly",(e,t)=>{FM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>uO(e,n,a,i),e.unwrap=()=>e._zod.def.innerType});function S2(e){return new y2({type:"readonly",innerType:e})}const x2=ve("ZodLazy",(e,t)=>{VM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>mO(e,n,a,i),e.unwrap=()=>e._zod.def.getter()});function PI(e){return new x2({type:"lazy",getter:e})}const AI=ve("ZodCustom",(e,t)=>{KM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,i)=>Qj(e,n)});function If(e,t){return Hj(AI,(()=>!0),t)}function k2(e,t={}){return Lj(AI,e,t)}function I2(e,t){return qj(e,t)}function Vo(e){const t=PI(()=>ht([o(e),d(),w(),al(),p(t),ae(o(),t)]));return t}function w2(e,t){return new b2({type:"pipe",in:wI(e),out:t})}const Yn={custom:"custom"},_2=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),C2=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function R2(e){const t=typeof e=="string"?new TextEncoder().encode(e):e,n=Math.ceil((t.byteLength+9)/64)*64,a=new Uint8Array(n);a.set(t),a[t.byteLength]=128;const i=t.byteLength*8,r=new DataView(a.buffer);r.setUint32(n-8,Math.floor(i/4294967296),!1),r.setUint32(n-4,i>>>0,!1);const s=new Uint32Array(_2),c=new Uint32Array(64);for(let m=0;m<n;m+=64){for(let R=0;R<16;R+=1)c[R]=r.getUint32(m+R*4,!1);for(let R=16;R<64;R+=1){const $=c[R-15],O=c[R-2],j=bi($,7)^bi($,18)^$>>>3,I=bi(O,17)^bi(O,19)^O>>>10;c[R]=c[R-16]+j+c[R-7]+I>>>0}let u=s[0],h=s[1],g=s[2],S=s[3],k=s[4],C=s[5],A=s[6],M=s[7];for(let R=0;R<64;R+=1){const $=k&C^~k&A,O=u&h^u&g^h&g,j=bi(u,2)^bi(u,13)^bi(u,22),I=bi(k,6)^bi(k,11)^bi(k,25),P=M+I+$+C2[R]+c[R]>>>0,E=j+O>>>0;M=A,A=C,C=k,k=S+P>>>0,S=g,g=h,h=u,u=P+E>>>0}s[0]=s[0]+u>>>0,s[1]=s[1]+h>>>0,s[2]=s[2]+g>>>0,s[3]=s[3]+S>>>0,s[4]=s[4]+k>>>0,s[5]=s[5]+C>>>0,s[6]=s[6]+A>>>0,s[7]=s[7]+M>>>0}return Array.from(s,m=>m.toString(16).padStart(8,"0")).join("")}function bi(e,t){return e>>>t|e<<32-t}const P2=2e3,TI=25e7,T=o().trim().min(1).max(240),D=o().regex(/^[a-f0-9]{64}$/),he=o().datetime({offset:!0}),Mn=ae(o(),ie()).default({}),V=l({id:T,contentHash:D}).strict(),Zt=V.extend({revision:d().int().positive()}).strict(),gn=l({id:T,path:o().trim().min(1).max(P2).refine(E2),contentHash:D,sizeBytes:d().int().nonnegative().max(TI),mediaType:o().trim().min(1).max(200),visibility:v(["policy","verifier","host_private"])}).strict(),Ia=l({id:T,contentHash:D,mediaType:o().trim().min(1).max(200).nullable().default(null),sizeBytes:d().int().nonnegative().max(TI).nullable().default(null)}).strict(),Bc=v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function A2(e){return`${JSON.stringify(Wh(e),null,2)}
66
+ `}function rv(e){return R2(e)}function st(e){return rv(A2(e))}function T2(e,t){const{contentHash:n,...a}=e,i=st(a);if(n!==i)throw new Error(`${t} contentHash is ${n}; expected ${i}.`)}function E2(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function Wh(e){return Array.isArray(e)?e.map(Wh):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Wh(n)]))}const pm=l({provider:T,model:T,revision:o().trim().min(1).max(500).nullable().default(null),artifactHash:D.nullable().default(null),tokenizerRevision:o().trim().min(1).max(500).nullable().default(null),chatTemplateHash:D.nullable().default(null)}).strict(),sv=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],jr=v(sv),bn=l({providerId:jr,modelId:o().trim().min(1).max(300)}),fm=v(["active","preview","planned","deprecated"]),EI=v(["openpond-account","openpond-managed","codex-login","chatgpt-subscription","local-byok","hosted-byok","custom"]),M2=v(["none","local_secret","env","openpond_account","codex_login","chatgpt_subscription","hosted"]),a0=l({connected:w().default(!1),source:M2.default("none"),redacted:o().nullable().default(null),lastValidatedAt:o().nullable().default(null),lastError:o().nullable().default(null)}),Gh=l({hostedOpChat:w().default(!1),localRuntime:w().default(!0),localByok:w().default(!1),hostedByok:w().default(!1)}),j2=v(["hosted","provider","manual","none"]),Jh=l({chatCompletions:w().default(!0),streaming:w().default(!0),modelDiscovery:j2.default("none"),toolCalling:w().default(!1),reasoning:w().default(!1),imageInput:w().default(!1),structuredOutput:w().default(!1)}),O2=v(["hosted","provider","curated","manual","cache"]),Zh=l({streaming:w().default(!0),toolCalling:w().default(!1),reasoning:w().default(!1),reasoningEfforts:p(v(["off","low","medium","high","xhigh","max"])).default([]),vision:w().default(!1),structuredOutput:w().default(!1)}),$2=l({id:o().trim().min(1).max(300),providerId:jr,displayName:o().trim().min(1).max(300),contextWindow:d().int().positive().nullable().default(null),outputLimit:d().int().positive().nullable().default(null),lifecycleStatus:fm.default("active"),source:O2,capabilities:Zh.default(()=>Zh.parse({})),raw:ae(o(),ie()).optional()}),N2=l({providerId:jr,models:p($2).default([]),fetchedAt:o().nullable().default(null),lastError:o().nullable().default(null),source:v(["none","hosted","provider","curated","manual"]).default("none")}),D2=l({enabled:w().default(!1),baseUrl:o().trim().min(1).max(2048).nullable().default(null),defaultModel:o().trim().min(1).max(300).nullable().default(null),modelOverrides:p(o().trim().min(1).max(300)).max(500).default([]),updatedAt:o().nullable().default(null)}),H2=l({enabled:w().optional(),baseUrl:o().trim().min(1).max(2048).nullable().optional(),defaultModel:o().trim().min(1).max(300).nullable().optional(),modelOverrides:p(o().trim().min(1).max(300)).max(500).optional()}),L2=l({id:o().trim().min(1).max(300),displayName:o().trim().min(1).max(300),contextWindow:d().int().positive().nullable().optional(),outputLimit:d().int().positive().nullable().optional(),lifecycleStatus:fm.optional(),capabilities:Zh.partial().optional()}),q2=l({id:jr,displayName:o().trim().min(1).max(160),lifecycleStatus:fm.default("active"),credentialModes:p(EI).default([]),routing:Gh,capabilities:Jh,defaultEnabled:w().optional(),defaultBaseUrl:o().trim().min(1).max(2048).nullable().optional(),defaultModel:o().trim().min(1).max(300).nullable().optional(),modelCacheSource:v(["none","hosted","provider","curated","manual"]),models:p(L2).default([])});l({version:b(1).default(1),generatedAt:o().datetime(),providers:p(q2)});const U2=l({id:jr,displayName:o().trim().min(1).max(160),lifecycleStatus:fm.default("active"),credentialModes:p(EI).default([]),routing:Gh.default(()=>Gh.parse({})),capabilities:Jh.default(()=>Jh.parse({})),credential:a0.default(()=>a0.parse({})),enabled:w().default(!1),available:w().default(!1),defaultModel:o().trim().min(1).max(300).nullable().default(null),modelIds:p(o().trim().min(1).max(300)).max(1e3).default([]),lastError:o().nullable().default(null)}),i0=l({version:b(1).default(1),providers:ae(o(),D2).default({}),statuses:ae(o(),U2).default({}),modelCaches:ae(o(),N2).default({}),updatedAt:o().nullable().default(null)});l({providers:ae(o(),H2).optional()});l({source:v(["local_secret","env"]).default("local_secret"),value:o().min(1).max(2e4).optional(),envVar:o().trim().min(1).max(160).optional()}).superRefine((e,t)=>{e.source==="env"&&!e.envVar&&t.addIssue({code:"custom",path:["envVar"],message:"envVar is required when provider credential source is env."}),e.source==="local_secret"&&!e.value&&t.addIssue({code:"custom",path:["value"],message:"value is required when provider credential source is local_secret."})});l({source:v(["local_secret","env","chatgpt_subscription"]).optional()});l({modelId:o().trim().min(1).max(300).optional(),baseUrl:o().trim().min(1).max(2048).optional()});l({query:o().trim().max(200).optional(),refresh:w().default(!1),limit:d().int().positive().max(500).default(100)});l({query:o().trim().max(200).optional(),force:w().default(!1)});const z2=["coding","research","review","test","docs","planner","summarizer"];v(z2);const il=o().trim().min(1).max(80).regex(/^[a-z][a-z0-9_-]*$/),MI=v(["none","worktree","copy_on_write"]),jI=v(["read_only","workspace_write","full_tools"]),OI=v(["disabled","parent_scoped"]),hm=v(["manual","balanced","proactive"]),B2=v(["queued","running","completed","failed","cancelled","needs_resume"]),$I=["subagent.started","subagent.reported","subagent.completed","subagent.progress","subagent.failed","subagent.cancelled","subagent.cleanup","subagent.workspace_retained","subagent.workspace_retention_expiring","subagent.archived","subagent.message"];v($I);const F2=[{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"}],lv=l({id:il,enabled:w().default(!0),modelRef:bn.nullable().default(null),isolationMode:MI.default("none"),maxConcurrentRuns:d().int().min(1).max(16).default(1),toolPolicy:jI.default("read_only"),background:w().default(!0),peerMessages:OI.default("parent_scoped")}),gc=l({enabled:w().default(!0),workspaceDefaultsVersion:b(1).default(1),toolDefaultsVersion:b(1).default(1),delegationMode:hm.default("manual"),defaultModelRef:bn.nullable().default(null),roles:p(lv).max(64).default(()=>HI()),maxConcurrentRuns:d().int().min(1).max(32).default(4),maxConcurrentRunsPerProvider:d().int().min(1).max(32).nullable().default(2),maxConcurrentRunsPerWorkspaceTarget:d().int().min(1).max(32).nullable().default(1)}).transform(e=>({...e,roles:t$(e.roles)})),nc=l({kind:v(["session","turn","file","diff","artifact"]),id:o().trim().min(1).max(500),label:o().trim().min(1).max(500)}),V2=l({kind:v(["retain_with_parent"]).default("retain_with_parent"),messageRetentionDays:d().int().min(1).max(3650).nullable().default(null),artifactRetentionDays:d().int().min(1).max(3650).nullable().default(null),cleanupAfterExpiry:w().default(!1)}).default(()=>({kind:"retain_with_parent",messageRetentionDays:null,artifactRetentionDays:null,cleanupAfterExpiry:!1})),K2=v(["orient","edit","validate","report"]),W2=l({command:o().trim().min(1).max(2e3),status:v(["passed","failed","unknown"]).default("unknown"),exitCode:d().int().nullable().default(null),outputSummary:o().trim().max(5e3).nullable().default(null),startedAt:o().nullable().default(null),completedAt:o().nullable().default(null)}),G2=l({phase:K2.default("orient"),inspectedFiles:p(o().trim().min(1).max(1e3)).max(500).default([]),inspectedResources:p(o().trim().min(1).max(1e3)).max(500).default([]),repeatedSearches:p(o().trim().min(1).max(1e3)).max(200).default([]),repeatedReads:p(o().trim().min(1).max(1e3)).max(200).default([]),repeatedCommands:p(o().trim().min(1).max(1e3)).max(200).default([]),changedFiles:p(o().trim().min(1).max(1e3)).max(500).default([]),patchRefs:p(nc).max(100).default([]),validationAttempts:p(W2).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})),J2=l({summary:o().trim().max(2e4).default(""),findings:p(o().trim().min(1).max(5e3)).max(200).default([]),artifacts:p(nc).max(200).default([]),patchRef:nc.nullable().default(null),diffRef:nc.nullable().default(null),testsRun:p(o().trim().min(1).max(2e3)).max(100).default([]),blockers:p(o().trim().min(1).max(5e3)).max(100).default([]),confidence:v(["low","medium","high"]).nullable().default(null),followUpNeeded:w().default(!1)}),NI=l({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:il,objective:o().trim().min(1).max(5e4),modelRef:bn.nullable().default(null),isolationMode:MI.default("none"),toolPolicy:jI.default("read_only"),background:w().default(!0),peerMessages:OI.default("parent_scoped"),status:B2.default("queued"),progress:G2,evidenceRetention:V2,createdAt:o(),startedAt:o().nullable().default(null),completedAt:o().nullable().default(null),updatedAt:o().nullable().default(null),error:o().nullable().default(null),report:J2.nullable().default(null),metadata:ae(o(),ie()).optional().default({})}),DI=v(["cleanup","archive","cleanup_and_archive"]);l({action:DI,reason:o().trim().min(1).max(2e3).nullable().default(null)});l({action:DI,run:NI,workspaceCleanup:ae(o(),ie()).nullable().default(null),sessionArchive:ae(o(),ie()).nullable().default(null),nextStep:o()});const Z2=v(["question","answer","handoff","artifact","status","blocker"]),Y2=v(["normal","interrupt"]),Q2=l({inputIds:p(o()).default([]),status:v(["pending","delivered","undelivered"]).default("pending"),deliveredRunIds:p(o().trim().min(1).max(200)).max(200).default([]),acknowledgedRunIds:p(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:p(o().trim().min(1).max(200)).max(200).default([]),wakeInterruptedRunIds:p(o().trim().min(1).max(200)).max(200).default([]),wakeDeferredRunIds:p(o().trim().min(1).max(200)).max(200).default([]),reason:o().trim().min(1).max(1e3).nullable().default(null)}),X2=l({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:il.nullable().default(null),kind:Z2,priority:Y2.optional(),body:o().trim().min(1).max(5e4),refs:p(nc).max(100).default([]),delivery:Q2.optional(),createdAt:o()});function HI(){return F2.map(e=>lv.parse({id:e.id,toolPolicy:e.defaultToolPolicy}))}function e$(){return gc.parse({})}function t$(e){const t=HI(),n=new Map(t.map(i=>[i.id,i])),a=[];for(const i of e??[]){const r=lv.parse(i);n.has(r.id)?n.set(r.id,r):a.push(r)}return[...t.map(i=>n.get(i.id)??i),...a]}const n$=v(["task.inbox","task.input","task.wait","session.started","session.title.updated","turn.started","assistant.delta","assistant.reasoning.delta","tool.started","tool.completed","skill.selected","skill.loaded","skill.load_failed","user_question.asked","user_question.answered","user_question.dismissed","approval.requested","approval.resolved","command.output","workspace_action","workspace_action_result","workspace.diff","create_improve.updated","session.context.updated","session.compaction.started","session.compaction.completed","session.compaction.failed","goal.continuation.started","goal.continuation.skipped","goal.continuation.failed","harness.refiner.queued","harness.refiner.started","harness.refiner.completed","harness.refiner.failed","turn.completed","turn.failed","turn.interrupted","session.closed",...$I,"diagnostic"]),o0=l({id:o(),sequence:d().int().positive().optional(),sessionId:o().optional(),turnId:o().optional(),name:n$,timestamp:o(),source:v(["ui_button","chat_action","terminal_command","hook","provider","server"]).optional(),action:o().optional(),appId:o().nullable().optional(),args:ae(o(),ie()).optional(),status:v(["started","completed","failed","pending"]).optional(),output:o().optional(),error:o().optional(),relatedDeploymentId:o().optional(),data:ie().optional()}),a$=l({id:o().trim().min(1).max(80),label:o().trim().min(1).max(160),description:o().trim().max(500).nullable().optional().default(null)}),i$=l({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:p(a$).max(5).default([]),allowFreeform:w().default(!0),status:v(["pending","answered","dismissed"]),answer:l({optionId:o().trim().min(1).nullable(),text:o().max(4e3)}).nullable(),createdAt:o(),answeredAt:o().nullable()}),o$=l({questionId:o().trim().min(1),action:v(["answer","dismiss"]),optionId:o().trim().min(1).nullable().optional().default(null),text:o().trim().max(4e3).optional().default("")});l({kind:v(["session","project","draft"]),id:o().trim().min(1).max(300)});v(["unknown","idle","running","success","failed"]);v(["none","idle","running","success","failed","unknown"]);function r$(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Vn={},Ud={},Mo={},r0;function Fc(){if(r0)return Mo;r0=1;function e(s){return typeof s>"u"||s===null}function t(s){return typeof s=="object"&&s!==null}function n(s){return Array.isArray(s)?s:e(s)?[]:[s]}function a(s,c){if(c){const m=Object.keys(c);for(let u=0,h=m.length;u<h;u+=1){const g=m[u];s[g]=c[g]}}return s}function i(s,c){let m="";for(let u=0;u<c;u+=1)m+=s;return m}function r(s){return s===0&&Number.NEGATIVE_INFINITY===1/s}return Mo.isNothing=e,Mo.isObject=t,Mo.toArray=n,Mo.repeat=i,Mo.isNegativeZero=r,Mo.extend=a,Mo}var wf,s0;function Vc(){if(s0)return wf;s0=1;function e(n,a){let i="";const r=n.reason||"(unknown reason)";return n.mark?(n.mark.name&&(i+='in "'+n.mark.name+'" '),i+="("+(n.mark.line+1)+":"+(n.mark.column+1)+")",!a&&n.mark.snippet&&(i+=`
67
+
68
+ `+n.mark.snippet),r+" "+i):r}function t(n,a){Error.call(this),this.name="YAMLException",this.reason=n,this.mark=a,this.message=e(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t.prototype.toString=function(a){return this.name+": "+e(this,a)},wf=t,wf}var _f,l0;function s$(){if(l0)return _f;l0=1;const e=Fc();function t(i,r,s,c,m){let u="",h="";const g=Math.floor(m/2)-1;return c-r>g&&(u=" ... ",r=c-g+u.length),s-c>g&&(h=" ...",s=c+g-h.length),{str:u+i.slice(r,s).replace(/\t/g,"→")+h,pos:c-r+u.length}}function n(i,r){return e.repeat(" ",r-i.length)+i}function a(i,r){if(r=Object.create(r||null),!i.buffer)return null;r.maxLength||(r.maxLength=79),typeof r.indent!="number"&&(r.indent=1),typeof r.linesBefore!="number"&&(r.linesBefore=3),typeof r.linesAfter!="number"&&(r.linesAfter=2);const s=/\r?\n|\r|\0/g,c=[0],m=[];let u,h=-1;for(;u=s.exec(i.buffer);)m.push(u.index),c.push(u.index+u[0].length),i.position<=u.index&&h<0&&(h=c.length-2);h<0&&(h=c.length-1);let g="";const S=Math.min(i.line+r.linesAfter,m.length).toString().length,k=r.maxLength-(r.indent+S+3);for(let A=1;A<=r.linesBefore&&!(h-A<0);A++){const M=t(i.buffer,c[h-A],m[h-A],i.position-(c[h]-c[h-A]),k);g=e.repeat(" ",r.indent)+n((i.line-A+1).toString(),S)+" | "+M.str+`
69
+ `+g}const C=t(i.buffer,c[h],m[h],i.position,k);g+=e.repeat(" ",r.indent)+n((i.line+1).toString(),S)+" | "+C.str+`
70
+ `,g+=e.repeat("-",r.indent+S+3+C.pos)+`^
71
+ `;for(let A=1;A<=r.linesAfter&&!(h+A>=m.length);A++){const M=t(i.buffer,c[h+A],m[h+A],i.position-(c[h]-c[h+A]),k);g+=e.repeat(" ",r.indent)+n((i.line+A+1).toString(),S)+" | "+M.str+`
72
+ `}return g.replace(/\n$/,"")}return _f=a,_f}var Cf,c0;function ta(){if(c0)return Cf;c0=1;const e=Vc(),t=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],n=["scalar","sequence","mapping"];function a(r){const s={};return r!==null&&Object.keys(r).forEach(function(c){r[c].forEach(function(m){s[String(m)]=c})}),s}function i(r,s){if(s=s||{},Object.keys(s).forEach(function(c){if(t.indexOf(c)===-1)throw new e('Unknown option "'+c+'" is met in definition of "'+r+'" YAML type.')}),this.options=s,this.tag=r,this.kind=s.kind||null,this.resolve=s.resolve||function(){return!0},this.construct=s.construct||function(c){return c},this.instanceOf=s.instanceOf||null,this.predicate=s.predicate||null,this.represent=s.represent||null,this.representName=s.representName||null,this.defaultStyle=s.defaultStyle||null,this.multi=s.multi||!1,this.styleAliases=a(s.styleAliases||null),n.indexOf(this.kind)===-1)throw new e('Unknown kind "'+this.kind+'" is specified for "'+r+'" YAML type.')}return Cf=i,Cf}var Rf,d0;function LI(){if(d0)return Rf;d0=1;const e=Vc(),t=ta();function n(r,s){const c=[];return r[s].forEach(function(m){let u=c.length;c.forEach(function(h,g){h.tag===m.tag&&h.kind===m.kind&&h.multi===m.multi&&(u=g)}),c[u]=m}),c}function a(){const r={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function s(c){c.multi?(r.multi[c.kind].push(c),r.multi.fallback.push(c)):r[c.kind][c.tag]=r.fallback[c.tag]=c}for(let c=0,m=arguments.length;c<m;c+=1)arguments[c].forEach(s);return r}function i(r){return this.extend(r)}return i.prototype.extend=function(s){let c=[],m=[];if(s instanceof t)m.push(s);else if(Array.isArray(s))m=m.concat(s);else if(s&&(Array.isArray(s.implicit)||Array.isArray(s.explicit)))s.implicit&&(c=c.concat(s.implicit)),s.explicit&&(m=m.concat(s.explicit));else throw new e("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");c.forEach(function(h){if(!(h instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(h.loadKind&&h.loadKind!=="scalar")throw new e("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(h.multi)throw new e("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),m.forEach(function(h){if(!(h instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.")});const u=Object.create(i.prototype);return u.implicit=(this.implicit||[]).concat(c),u.explicit=(this.explicit||[]).concat(m),u.compiledImplicit=n(u,"implicit"),u.compiledExplicit=n(u,"explicit"),u.compiledTypeMap=a(u.compiledImplicit,u.compiledExplicit),u},Rf=i,Rf}var Pf,u0;function qI(){if(u0)return Pf;u0=1;const e=ta();return Pf=new e("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),Pf}var Af,m0;function UI(){if(m0)return Af;m0=1;const e=ta();return Af=new e("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),Af}var Tf,p0;function zI(){if(p0)return Tf;p0=1;const e=ta();return Tf=new e("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),Tf}var Ef,f0;function BI(){if(f0)return Ef;f0=1;const e=LI();return Ef=new e({explicit:[qI(),UI(),zI()]}),Ef}var Mf,h0;function FI(){if(h0)return Mf;h0=1;const e=ta();function t(i){if(i===null)return!0;const r=i.length;return r===1&&i==="~"||r===4&&(i==="null"||i==="Null"||i==="NULL")}function n(){return null}function a(i){return i===null}return Mf=new e("tag:yaml.org,2002:null",{kind:"scalar",resolve:t,construct:n,predicate:a,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"},empty:function(){return""}},defaultStyle:"lowercase"}),Mf}var jf,g0;function VI(){if(g0)return jf;g0=1;const e=ta();function t(i){if(i===null)return!1;const r=i.length;return r===4&&(i==="true"||i==="True"||i==="TRUE")||r===5&&(i==="false"||i==="False"||i==="FALSE")}function n(i){return i==="true"||i==="True"||i==="TRUE"}function a(i){return Object.prototype.toString.call(i)==="[object Boolean]"}return jf=new e("tag:yaml.org,2002:bool",{kind:"scalar",resolve:t,construct:n,predicate:a,represent:{lowercase:function(i){return i?"true":"false"},uppercase:function(i){return i?"TRUE":"FALSE"},camelcase:function(i){return i?"True":"False"}},defaultStyle:"lowercase"}),jf}var Of,v0;function KI(){if(v0)return Of;v0=1;const e=Fc(),t=ta();function n(u){return u>=48&&u<=57||u>=65&&u<=70||u>=97&&u<=102}function a(u){return u>=48&&u<=55}function i(u){return u>=48&&u<=57}function r(u){if(u===null)return!1;const h=u.length;let g=0,S=!1;if(!h)return!1;let k=u[g];if((k==="-"||k==="+")&&(k=u[++g]),k==="0"){if(g+1===h)return!0;if(k=u[++g],k==="b"){for(g++;g<h;g++){if(k=u[g],k!=="0"&&k!=="1")return!1;S=!0}return S&&isFinite(s(u))}if(k==="x"){for(g++;g<h;g++){if(!n(u.charCodeAt(g)))return!1;S=!0}return S&&isFinite(s(u))}if(k==="o"){for(g++;g<h;g++){if(!a(u.charCodeAt(g)))return!1;S=!0}return S&&isFinite(s(u))}}for(;g<h;g++){if(!i(u.charCodeAt(g)))return!1;S=!0}return S?isFinite(s(u)):!1}function s(u){let h=u,g=1,S=h[0];if((S==="-"||S==="+")&&(S==="-"&&(g=-1),h=h.slice(1),S=h[0]),h==="0")return 0;if(S==="0"){if(h[1]==="b")return g*parseInt(h.slice(2),2);if(h[1]==="x")return g*parseInt(h.slice(2),16);if(h[1]==="o")return g*parseInt(h.slice(2),8)}return g*parseInt(h,10)}function c(u){return s(u)}function m(u){return Object.prototype.toString.call(u)==="[object Number]"&&u%1===0&&!e.isNegativeZero(u)}return Of=new t("tag:yaml.org,2002:int",{kind:"scalar",resolve:r,construct:c,predicate:m,represent:{binary:function(u){return u>=0?"0b"+u.toString(2):"-0b"+u.toString(2).slice(1)},octal:function(u){return u>=0?"0o"+u.toString(8):"-0o"+u.toString(8).slice(1)},decimal:function(u){return u.toString(10)},hexadecimal:function(u){return u>=0?"0x"+u.toString(16).toUpperCase():"-0x"+u.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),Of}var $f,b0;function WI(){if(b0)return $f;b0=1;const e=Fc(),t=ta(),n=new RegExp("^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),a=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function i(u){return u===null||!n.test(u)?!1:isFinite(parseFloat(u,10))?!0:a.test(u)}function r(u){let h=u.toLowerCase();const g=h[0]==="-"?-1:1;return"+-".indexOf(h[0])>=0&&(h=h.slice(1)),h===".inf"?g===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:h===".nan"?NaN:g*parseFloat(h,10)}const s=/^[-+]?[0-9]+e/;function c(u,h){if(isNaN(u))switch(h){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===u)switch(h){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===u)switch(h){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(e.isNegativeZero(u))return"-0.0";const g=u.toString(10);return s.test(g)?g.replace("e",".e"):g}function m(u){return Object.prototype.toString.call(u)==="[object Number]"&&(u%1!==0||e.isNegativeZero(u))}return $f=new t("tag:yaml.org,2002:float",{kind:"scalar",resolve:i,construct:r,predicate:m,represent:c,defaultStyle:"lowercase"}),$f}var Nf,y0;function GI(){return y0||(y0=1,Nf=BI().extend({implicit:[FI(),VI(),KI(),WI()]})),Nf}var Df,S0;function JI(){return S0||(S0=1,Df=GI()),Df}var Hf,x0;function ZI(){if(x0)return Hf;x0=1;const e=ta(),t=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),n=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function a(s){return s===null?!1:t.exec(s)!==null||n.exec(s)!==null}function i(s){let c=0,m=null,u=t.exec(s);if(u===null&&(u=n.exec(s)),u===null)throw new Error("Date resolve error");const h=+u[1],g=+u[2]-1,S=+u[3];if(!u[4])return new Date(Date.UTC(h,g,S));const k=+u[4],C=+u[5],A=+u[6];if(u[7]){for(c=u[7].slice(0,3);c.length<3;)c+="0";c=+c}if(u[9]){const R=+u[10],$=+(u[11]||0);m=(R*60+$)*6e4,u[9]==="-"&&(m=-m)}const M=new Date(Date.UTC(h,g,S,k,C,A,c));return m&&M.setTime(M.getTime()-m),M}function r(s){return s.toISOString()}return Hf=new e("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:a,construct:i,instanceOf:Date,represent:r}),Hf}var Lf,k0;function YI(){if(k0)return Lf;k0=1;const e=ta();function t(n){return n==="<<"||n===null}return Lf=new e("tag:yaml.org,2002:merge",{kind:"scalar",resolve:t}),Lf}var qf,I0;function QI(){if(I0)return qf;I0=1;const e=ta(),t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
73
+ \r`;function n(s){if(s===null)return!1;let c=0;const m=s.length,u=t;for(let h=0;h<m;h++){const g=u.indexOf(s.charAt(h));if(!(g>64)){if(g<0)return!1;c+=6}}return c%8===0}function a(s){const c=s.replace(/[\r\n=]/g,""),m=c.length,u=t;let h=0;const g=[];for(let k=0;k<m;k++)k%4===0&&k&&(g.push(h>>16&255),g.push(h>>8&255),g.push(h&255)),h=h<<6|u.indexOf(c.charAt(k));const S=m%4*6;return S===0?(g.push(h>>16&255),g.push(h>>8&255),g.push(h&255)):S===18?(g.push(h>>10&255),g.push(h>>2&255)):S===12&&g.push(h>>4&255),new Uint8Array(g)}function i(s){let c="",m=0;const u=s.length,h=t;for(let S=0;S<u;S++)S%3===0&&S&&(c+=h[m>>18&63],c+=h[m>>12&63],c+=h[m>>6&63],c+=h[m&63]),m=(m<<8)+s[S];const g=u%3;return g===0?(c+=h[m>>18&63],c+=h[m>>12&63],c+=h[m>>6&63],c+=h[m&63]):g===2?(c+=h[m>>10&63],c+=h[m>>4&63],c+=h[m<<2&63],c+=h[64]):g===1&&(c+=h[m>>2&63],c+=h[m<<4&63],c+=h[64],c+=h[64]),c}function r(s){return Object.prototype.toString.call(s)==="[object Uint8Array]"}return qf=new e("tag:yaml.org,2002:binary",{kind:"scalar",resolve:n,construct:a,predicate:r,represent:i}),qf}var Uf,w0;function XI(){if(w0)return Uf;w0=1;const e=ta(),t=Object.prototype.hasOwnProperty,n=Object.prototype.toString;function a(r){if(r===null)return!0;const s=[],c=r;for(let m=0,u=c.length;m<u;m+=1){const h=c[m];let g=!1;if(n.call(h)!=="[object Object]")return!1;let S;for(S in h)if(t.call(h,S))if(!g)g=!0;else return!1;if(!g)return!1;if(s.indexOf(S)===-1)s.push(S);else return!1}return!0}function i(r){return r!==null?r:[]}return Uf=new e("tag:yaml.org,2002:omap",{kind:"sequence",resolve:a,construct:i}),Uf}var zf,_0;function e1(){if(_0)return zf;_0=1;const e=ta(),t=Object.prototype.toString;function n(i){if(i===null)return!0;const r=i,s=new Array(r.length);for(let c=0,m=r.length;c<m;c+=1){const u=r[c];if(t.call(u)!=="[object Object]")return!1;const h=Object.keys(u);if(h.length!==1)return!1;s[c]=[h[0],u[h[0]]]}return!0}function a(i){if(i===null)return[];const r=i,s=new Array(r.length);for(let c=0,m=r.length;c<m;c+=1){const u=r[c],h=Object.keys(u);s[c]=[h[0],u[h[0]]]}return s}return zf=new e("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:n,construct:a}),zf}var Bf,C0;function t1(){if(C0)return Bf;C0=1;const e=ta(),t=Object.prototype.hasOwnProperty;function n(i){if(i===null)return!0;const r=i;for(const s in r)if(t.call(r,s)&&r[s]!==null)return!1;return!0}function a(i){return i!==null?i:{}}return Bf=new e("tag:yaml.org,2002:set",{kind:"mapping",resolve:n,construct:a}),Bf}var Ff,R0;function cv(){return R0||(R0=1,Ff=JI().extend({implicit:[ZI(),YI()],explicit:[QI(),XI(),e1(),t1()]})),Ff}var P0;function l$(){if(P0)return Ud;P0=1;const e=Fc(),t=Vc(),n=s$(),a=cv(),i=Object.prototype.hasOwnProperty,r=1,s=2,c=3,m=4,u=1,h=2,g=3,S=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,k=/[\x85\u2028\u2029]/,C=/[,\[\]{}]/,A=/^(?:!|!!|![0-9A-Za-z-]+!)$/,M=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function R(f){return Object.prototype.toString.call(f)}function $(f){return f===10||f===13}function O(f){return f===9||f===32}function j(f){return f===9||f===32||f===10||f===13}function I(f){return f===44||f===91||f===93||f===123||f===125}function P(f){if(f>=48&&f<=57)return f-48;const U=f|32;return U>=97&&U<=102?U-97+10:-1}function E(f){return f===120?2:f===117?4:f===85?8:0}function L(f){return f>=48&&f<=57?f-48:-1}function z(f){switch(f){case 48:return"\0";case 97:return"\x07";case 98:return"\b";case 116:return" ";case 9:return" ";case 110:return`
74
+ `;case 118:return"\v";case 102:return"\f";case 114:return"\r";case 101:return"\x1B";case 32:return" ";case 34:return'"';case 47:return"/";case 92:return"\\";case 78:return"…";case 95:return" ";case 76:return"\u2028";case 80:return"\u2029";default:return""}}function H(f){return f<=65535?String.fromCharCode(f):String.fromCharCode((f-65536>>10)+55296,(f-65536&1023)+56320)}function J(f,U,Y){U==="__proto__"?Object.defineProperty(f,U,{configurable:!0,enumerable:!0,writable:!0,value:Y}):f[U]=Y}const X=new Array(256),de=new Array(256);for(let f=0;f<256;f++)X[f]=z(f)?1:0,de[f]=z(f);function je(f,U){this.input=f,this.filename=U.filename||null,this.schema=U.schema||a,this.onWarning=U.onWarning||null,this.legacy=U.legacy||!1,this.json=U.json||!1,this.listener=U.listener||null,this.maxDepth=typeof U.maxDepth=="number"?U.maxDepth:100,this.maxTotalMergeKeys=typeof U.maxTotalMergeKeys=="number"?U.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=f.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.depth=0,this.totalMergeKeys=0,this.firstTabInLine=-1,this.documents=[],this.anchorMapTransactions=[]}function we(f,U){const Y={name:f.filename,buffer:f.input.slice(0,-1),position:f.position,line:f.line,column:f.position-f.lineStart};return Y.snippet=n(Y),new t(U,Y)}function te(f,U){throw we(f,U)}function Me(f,U){f.onWarning&&f.onWarning.call(null,we(f,U))}function Se(f,U,Y){const ge=f.anchorMapTransactions;if(ge.length!==0){const se=ge[ge.length-1];i.call(se,U)||(se[U]={existed:i.call(f.anchorMap,U),value:f.anchorMap[U]})}f.anchorMap[U]=Y}function oe(f){f.anchorMapTransactions.push(Object.create(null))}function be(f){const U=f.anchorMapTransactions.pop(),Y=f.anchorMapTransactions;if(Y.length===0)return;const ge=Y[Y.length-1],se=Object.keys(U);for(let G=0,_=se.length;G<_;G+=1){const W=se[G];i.call(ge,W)||(ge[W]=U[W])}}function re(f){const U=f.anchorMapTransactions.pop(),Y=Object.keys(U);for(let ge=Y.length-1;ge>=0;ge-=1){const se=U[Y[ge]];se.existed?f.anchorMap[Y[ge]]=se.value:delete f.anchorMap[Y[ge]]}}function ue(f){return{position:f.position,line:f.line,lineStart:f.lineStart,lineIndent:f.lineIndent,firstTabInLine:f.firstTabInLine,tag:f.tag,anchor:f.anchor,kind:f.kind,result:f.result}}function ke(f,U){f.position=U.position,f.line=U.line,f.lineStart=U.lineStart,f.lineIndent=U.lineIndent,f.firstTabInLine=U.firstTabInLine,f.tag=U.tag,f.anchor=U.anchor,f.kind=U.kind,f.result=U.result}const Le={YAML:function(U,Y,ge){U.version!==null&&te(U,"duplication of %YAML directive"),ge.length!==1&&te(U,"YAML directive accepts exactly one argument");const se=/^([0-9]+)\.([0-9]+)$/.exec(ge[0]);se===null&&te(U,"ill-formed argument of the YAML directive");const G=parseInt(se[1],10),_=parseInt(se[2],10);G!==1&&te(U,"unacceptable YAML version of the document"),U.version=ge[0],U.checkLineBreaks=_<2,_!==1&&_!==2&&Me(U,"unsupported YAML version of the document")},TAG:function(U,Y,ge){let se;ge.length!==2&&te(U,"TAG directive accepts exactly two arguments");const G=ge[0];se=ge[1],A.test(G)||te(U,"ill-formed tag handle (first argument) of the TAG directive"),i.call(U.tagMap,G)&&te(U,'there is a previously declared suffix for "'+G+'" tag handle'),M.test(se)||te(U,"ill-formed tag prefix (second argument) of the TAG directive");try{se=decodeURIComponent(se)}catch{te(U,"tag prefix is malformed: "+se)}U.tagMap[G]=se}};function Ie(f,U,Y,ge){if(U<Y){const se=f.input.slice(U,Y);if(ge)for(let G=0,_=se.length;G<_;G+=1){const W=se.charCodeAt(G);W===9||W>=32&&W<=1114111||te(f,"expected valid JSON character")}else S.test(se)&&te(f,"the stream contains non-printable characters");f.result+=se}}function le(f,U,Y,ge){e.isObject(Y)||te(f,"cannot merge mappings; the provided source object is unacceptable");const se=Object.keys(Y);for(let G=0,_=se.length;G<_;G+=1){const W=se[G];f.maxTotalMergeKeys!==-1&&++f.totalMergeKeys>f.maxTotalMergeKeys&&te(f,"merge keys exceeded maxTotalMergeKeys ("+f.maxTotalMergeKeys+")"),i.call(U,W)||(J(U,W,Y[W]),ge[W]=!0)}}function xe(f,U,Y,ge,se,G,_,W,ne){if(Array.isArray(se)){se=Array.prototype.slice.call(se);for(let Z=0,ce=se.length;Z<ce;Z+=1)Array.isArray(se[Z])&&te(f,"nested arrays are not supported inside keys"),typeof se=="object"&&R(se[Z])==="[object Object]"&&(se[Z]="[object Object]")}if(typeof se=="object"&&R(se)==="[object Object]"&&(se="[object Object]"),se=String(se),U===null&&(U={}),ge==="tag:yaml.org,2002:merge")if(Array.isArray(G))for(let Z=0,ce=G.length;Z<ce;Z+=1)le(f,U,G[Z],Y);else le(f,U,G,Y);else!f.json&&!i.call(Y,se)&&i.call(U,se)&&(f.line=_||f.line,f.lineStart=W||f.lineStart,f.position=ne||f.position,te(f,"duplicated mapping key")),J(U,se,G),delete Y[se];return U}function Ue(f){const U=f.input.charCodeAt(f.position);U===10?f.position++:U===13?(f.position++,f.input.charCodeAt(f.position)===10&&f.position++):te(f,"a line break is expected"),f.line+=1,f.lineStart=f.position,f.firstTabInLine=-1}function Ze(f,U,Y){let ge=0,se=f.input.charCodeAt(f.position);for(;se!==0;){for(;O(se);)se===9&&f.firstTabInLine===-1&&(f.firstTabInLine=f.position),se=f.input.charCodeAt(++f.position);if(U&&se===35)do se=f.input.charCodeAt(++f.position);while(se!==10&&se!==13&&se!==0);if($(se))for(Ue(f),se=f.input.charCodeAt(f.position),ge++,f.lineIndent=0;se===32;)f.lineIndent++,se=f.input.charCodeAt(++f.position);else break}return Y!==-1&&ge!==0&&f.lineIndent<Y&&Me(f,"deficient indentation"),ge}function it(f){let U=f.position,Y=f.input.charCodeAt(U);return!!((Y===45||Y===46)&&Y===f.input.charCodeAt(U+1)&&Y===f.input.charCodeAt(U+2)&&(U+=3,Y=f.input.charCodeAt(U),Y===0||j(Y)))}function at(f,U){U===1?f.result+=" ":U>1&&(f.result+=e.repeat(`
75
+ `,U-1))}function Ne(f,U,Y){let ge,se,G,_,W,ne;const Z=f.kind,ce=f.result;let pe=f.input.charCodeAt(f.position);if(j(pe)||I(pe)||pe===35||pe===38||pe===42||pe===33||pe===124||pe===62||pe===39||pe===34||pe===37||pe===64||pe===96)return!1;if(pe===63||pe===45){const fe=f.input.charCodeAt(f.position+1);if(j(fe)||Y&&I(fe))return!1}for(f.kind="scalar",f.result="",ge=se=f.position,G=!1;pe!==0;){if(pe===58){const fe=f.input.charCodeAt(f.position+1);if(j(fe)||Y&&I(fe))break}else if(pe===35){const fe=f.input.charCodeAt(f.position-1);if(j(fe))break}else{if(f.position===f.lineStart&&it(f)||Y&&I(pe))break;if($(pe))if(_=f.line,W=f.lineStart,ne=f.lineIndent,Ze(f,!1,-1),f.lineIndent>=U){G=!0,pe=f.input.charCodeAt(f.position);continue}else{f.position=se,f.line=_,f.lineStart=W,f.lineIndent=ne;break}}G&&(Ie(f,ge,se,!1),at(f,f.line-_),ge=se=f.position,G=!1),O(pe)||(se=f.position+1),pe=f.input.charCodeAt(++f.position)}return Ie(f,ge,se,!1),f.result?!0:(f.kind=Z,f.result=ce,!1)}function We(f,U){let Y,ge,se=f.input.charCodeAt(f.position);if(se!==39)return!1;for(f.kind="scalar",f.result="",f.position++,Y=ge=f.position;(se=f.input.charCodeAt(f.position))!==0;)if(se===39)if(Ie(f,Y,f.position,!0),se=f.input.charCodeAt(++f.position),se===39)Y=f.position,f.position++,ge=f.position;else return!0;else $(se)?(Ie(f,Y,ge,!0),at(f,Ze(f,!1,U)),Y=ge=f.position):f.position===f.lineStart&&it(f)?te(f,"unexpected end of the document within a single quoted scalar"):(f.position++,O(se)||(ge=f.position));te(f,"unexpected end of the stream within a single quoted scalar")}function qe(f,U){let Y,ge,se,G=f.input.charCodeAt(f.position);if(G!==34)return!1;for(f.kind="scalar",f.result="",f.position++,Y=ge=f.position;(G=f.input.charCodeAt(f.position))!==0;){if(G===34)return Ie(f,Y,f.position,!0),f.position++,!0;if(G===92){if(Ie(f,Y,f.position,!0),G=f.input.charCodeAt(++f.position),$(G))Ze(f,!1,U);else if(G<256&&X[G])f.result+=de[G],f.position++;else if((se=E(G))>0){let _=se,W=0;for(;_>0;_--)G=f.input.charCodeAt(++f.position),(se=P(G))>=0?W=(W<<4)+se:te(f,"expected hexadecimal character");f.result+=H(W),f.position++}else te(f,"unknown escape sequence");Y=ge=f.position}else $(G)?(Ie(f,Y,ge,!0),at(f,Ze(f,!1,U)),Y=ge=f.position):f.position===f.lineStart&&it(f)?te(f,"unexpected end of the document within a double quoted scalar"):(f.position++,O(G)||(ge=f.position))}te(f,"unexpected end of the stream within a double quoted scalar")}function q(f,U){let Y=!0,ge,se,G;const _=f.tag;let W;const ne=f.anchor;let Z,ce,pe,fe;const Ae=Object.create(null);let Ce,He,Pe,Xe=f.input.charCodeAt(f.position);if(Xe===91)Z=93,fe=!1,W=[];else if(Xe===123)Z=125,fe=!0,W={};else return!1;for(f.anchor!==null&&Se(f,f.anchor,W),Xe=f.input.charCodeAt(++f.position);Xe!==0;){if(Ze(f,!0,U),Xe=f.input.charCodeAt(f.position),Xe===Z)return f.position++,f.tag=_,f.anchor=ne,f.kind=fe?"mapping":"sequence",f.result=W,!0;if(Y?Xe===44&&te(f,"expected the node content, but found ','"):te(f,"missed comma between flow collection entries"),He=Ce=Pe=null,ce=pe=!1,Xe===63){const ut=f.input.charCodeAt(f.position+1);j(ut)&&(ce=pe=!0,f.position++,Ze(f,!0,U))}ge=f.line,se=f.lineStart,G=f.position,nt(f,U,r,!1,!0),He=f.tag,Ce=f.result,Ze(f,!0,U),Xe=f.input.charCodeAt(f.position),(pe||f.line===ge)&&Xe===58&&(ce=!0,Xe=f.input.charCodeAt(++f.position),Ze(f,!0,U),nt(f,U,r,!1,!0),Pe=f.result),fe?xe(f,W,Ae,He,Ce,Pe,ge,se,G):ce?W.push(xe(f,null,Ae,He,Ce,Pe,ge,se,G)):W.push(Ce),Ze(f,!0,U),Xe=f.input.charCodeAt(f.position),Xe===44?(Y=!0,Xe=f.input.charCodeAt(++f.position)):Y=!1}te(f,"unexpected end of the stream within a flow collection")}function N(f,U){let Y,ge=u,se=!1,G=!1,_=U,W=0,ne=!1,Z,ce=f.input.charCodeAt(f.position);if(ce===124)Y=!1;else if(ce===62)Y=!0;else return!1;for(f.kind="scalar",f.result="";ce!==0;)if(ce=f.input.charCodeAt(++f.position),ce===43||ce===45)u===ge?ge=ce===43?g:h:te(f,"repeat of a chomping mode identifier");else if((Z=L(ce))>=0)Z===0?te(f,"bad explicit indentation width of a block scalar; it cannot be less than one"):G?te(f,"repeat of an indentation width identifier"):(_=U+Z-1,G=!0);else break;if(O(ce)){do ce=f.input.charCodeAt(++f.position);while(O(ce));if(ce===35)do ce=f.input.charCodeAt(++f.position);while(!$(ce)&&ce!==0)}for(;ce!==0;){for(Ue(f),f.lineIndent=0,ce=f.input.charCodeAt(f.position);(!G||f.lineIndent<_)&&ce===32;)f.lineIndent++,ce=f.input.charCodeAt(++f.position);if(!G&&f.lineIndent>_&&(_=f.lineIndent),$(ce)){W++;continue}if(!G&&_===0&&te(f,"missing indentation for block scalar"),f.lineIndent<_){ge===g?f.result+=e.repeat(`
76
+ `,se?1+W:W):ge===u&&se&&(f.result+=`
77
+ `);break}Y?O(ce)?(ne=!0,f.result+=e.repeat(`
78
+ `,se?1+W:W)):ne?(ne=!1,f.result+=e.repeat(`
79
+ `,W+1)):W===0?se&&(f.result+=" "):f.result+=e.repeat(`
80
+ `,W):f.result+=e.repeat(`
81
+ `,se?1+W:W),se=!0,G=!0,W=0;const pe=f.position;for(;!$(ce)&&ce!==0;)ce=f.input.charCodeAt(++f.position);Ie(f,pe,f.position,!1)}return!0}function F(f,U){const Y=f.tag,ge=f.anchor,se=[];let G=!1;if(f.firstTabInLine!==-1)return!1;f.anchor!==null&&Se(f,f.anchor,se);let _=f.input.charCodeAt(f.position);for(;_!==0&&(f.firstTabInLine!==-1&&(f.position=f.firstTabInLine,te(f,"tab characters must not be used in indentation")),_===45);){const W=f.input.charCodeAt(f.position+1);if(!j(W))break;if(G=!0,f.position++,Ze(f,!0,-1)&&f.lineIndent<=U){se.push(null),_=f.input.charCodeAt(f.position);continue}const ne=f.line;if(nt(f,U,c,!1,!0),se.push(f.result),Ze(f,!0,-1),_=f.input.charCodeAt(f.position),(f.line===ne||f.lineIndent>U)&&_!==0)te(f,"bad indentation of a sequence entry");else if(f.lineIndent<U)break}return G?(f.tag=Y,f.anchor=ge,f.kind="sequence",f.result=se,!0):!1}function ee(f,U,Y){let ge,se,G,_;const W=f.tag,ne=f.anchor,Z={},ce=Object.create(null);let pe=null,fe=null,Ae=null,Ce=!1,He=!1;if(f.firstTabInLine!==-1)return!1;f.anchor!==null&&Se(f,f.anchor,Z);let Pe=f.input.charCodeAt(f.position);for(;Pe!==0;){!Ce&&f.firstTabInLine!==-1&&(f.position=f.firstTabInLine,te(f,"tab characters must not be used in indentation"));const Xe=f.input.charCodeAt(f.position+1),ut=f.line;if((Pe===63||Pe===58)&&j(Xe))Pe===63?(Ce&&(xe(f,Z,ce,pe,fe,null,se,G,_),pe=fe=Ae=null),He=!0,Ce=!0,ge=!0):Ce?(Ce=!1,ge=!0):te(f,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),f.position+=1,Pe=Xe;else{if(se=f.line,G=f.lineStart,_=f.position,!nt(f,Y,s,!1,!0))break;if(f.line===ut){for(Pe=f.input.charCodeAt(f.position);O(Pe);)Pe=f.input.charCodeAt(++f.position);if(Pe===58)Pe=f.input.charCodeAt(++f.position),j(Pe)||te(f,"a whitespace character is expected after the key-value separator within a block mapping"),Ce&&(xe(f,Z,ce,pe,fe,null,se,G,_),pe=fe=Ae=null),He=!0,Ce=!1,ge=!1,pe=f.tag,fe=f.result;else if(He)te(f,"can not read an implicit mapping pair; a colon is missed");else return f.tag=W,f.anchor=ne,!0}else if(He)te(f,"can not read a block mapping entry; a multiline key may not be an implicit key");else return f.tag=W,f.anchor=ne,!0}if((f.line===ut||f.lineIndent>U)&&(Ce&&(se=f.line,G=f.lineStart,_=f.position),nt(f,U,m,!0,ge)&&(Ce?fe=f.result:Ae=f.result),Ce||(xe(f,Z,ce,pe,fe,Ae,se,G,_),pe=fe=Ae=null),Ze(f,!0,-1),Pe=f.input.charCodeAt(f.position)),(f.line===ut||f.lineIndent>U)&&Pe!==0)te(f,"bad indentation of a mapping entry");else if(f.lineIndent<U)break}return Ce&&xe(f,Z,ce,pe,fe,null,se,G,_),He&&(f.tag=W,f.anchor=ne,f.kind="mapping",f.result=Z),He}function me(f){let U=!1,Y=!1,ge,se,G=f.input.charCodeAt(f.position);if(G!==33)return!1;f.tag!==null&&te(f,"duplication of a tag property"),G=f.input.charCodeAt(++f.position),G===60?(U=!0,G=f.input.charCodeAt(++f.position)):G===33?(Y=!0,ge="!!",G=f.input.charCodeAt(++f.position)):ge="!";let _=f.position;if(U){do G=f.input.charCodeAt(++f.position);while(G!==0&&G!==62);f.position<f.length?(se=f.input.slice(_,f.position),G=f.input.charCodeAt(++f.position)):te(f,"unexpected end of the stream within a verbatim tag")}else{for(;G!==0&&!j(G);)G===33&&(Y?te(f,"tag suffix cannot contain exclamation marks"):(ge=f.input.slice(_-1,f.position+1),A.test(ge)||te(f,"named tag handle cannot contain such characters"),Y=!0,_=f.position+1)),G=f.input.charCodeAt(++f.position);se=f.input.slice(_,f.position),C.test(se)&&te(f,"tag suffix cannot contain flow indicator characters")}se&&!M.test(se)&&te(f,"tag name cannot contain such characters: "+se);try{se=decodeURIComponent(se)}catch{te(f,"tag name is malformed: "+se)}return U?f.tag=se:i.call(f.tagMap,ge)?f.tag=f.tagMap[ge]+se:ge==="!"?f.tag="!"+se:ge==="!!"?f.tag="tag:yaml.org,2002:"+se:te(f,'undeclared tag handle "'+ge+'"'),!0}function $e(f){let U=f.input.charCodeAt(f.position);if(U!==38)return!1;f.anchor!==null&&te(f,"duplication of an anchor property"),U=f.input.charCodeAt(++f.position);const Y=f.position;for(;U!==0&&!j(U)&&!I(U);)U=f.input.charCodeAt(++f.position);return f.position===Y&&te(f,"name of an anchor node must contain at least one character"),f.anchor=f.input.slice(Y,f.position),!0}function ze(f){let U=f.input.charCodeAt(f.position);if(U!==42)return!1;U=f.input.charCodeAt(++f.position);const Y=f.position;for(;U!==0&&!j(U)&&!I(U);)U=f.input.charCodeAt(++f.position);f.position===Y&&te(f,"name of an alias node must contain at least one character");const ge=f.input.slice(Y,f.position);return i.call(f.anchorMap,ge)||te(f,'unidentified alias "'+ge+'"'),f.result=f.anchorMap[ge],Ze(f,!0,-1),!0}function tt(f,U,Y,ge){const se=ue(f);return oe(f),ke(f,U),f.tag=null,f.anchor=null,f.kind=null,f.result=null,ee(f,Y,ge)&&f.kind==="mapping"?(be(f),!0):(re(f),ke(f,se),!1)}function nt(f,U,Y,ge,se){let G,_,W=1,ne=!1,Z=!1,ce=null,pe,fe,Ae;f.depth>=f.maxDepth&&te(f,"nesting exceeded maxDepth ("+f.maxDepth+")"),f.depth+=1,f.listener!==null&&f.listener("open",f),f.tag=null,f.anchor=null,f.kind=null,f.result=null;const Ce=G=_=m===Y||c===Y;if(ge&&Ze(f,!0,-1)&&(ne=!0,f.lineIndent>U?W=1:f.lineIndent===U?W=0:f.lineIndent<U&&(W=-1)),W===1)for(;;){const He=f.input.charCodeAt(f.position),Pe=ue(f);if(ne&&(He===33&&f.tag!==null||He===38&&f.anchor!==null)||!me(f)&&!$e(f))break;ce===null&&(ce=Pe),Ze(f,!0,-1)?(ne=!0,_=Ce,f.lineIndent>U?W=1:f.lineIndent===U?W=0:f.lineIndent<U&&(W=-1)):_=!1}if(_&&(_=ne||se),W===1||m===Y)if(r===Y||s===Y?fe=U:fe=U+1,Ae=f.position-f.lineStart,W===1)if(_&&(F(f,Ae)||ee(f,Ae,fe))||q(f,fe))Z=!0;else{const He=f.input.charCodeAt(f.position);ce!==null&&Ce&&!_&&He!==124&&He!==62&&tt(f,ce,ce.position-ce.lineStart,fe)||G&&N(f,fe)||We(f,fe)||qe(f,fe)?Z=!0:ze(f)?(Z=!0,(f.tag!==null||f.anchor!==null)&&te(f,"alias node should not have any properties")):Ne(f,fe,r===Y)&&(Z=!0,f.tag===null&&(f.tag="?")),f.anchor!==null&&Se(f,f.anchor,f.result)}else W===0&&(Z=_&&F(f,Ae));if(f.tag===null)f.anchor!==null&&Se(f,f.anchor,f.result);else if(f.tag==="?"){f.result!==null&&f.kind!=="scalar"&&te(f,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+f.kind+'"');for(let He=0,Pe=f.implicitTypes.length;He<Pe;He+=1)if(pe=f.implicitTypes[He],pe.resolve(f.result)){f.result=pe.construct(f.result),f.tag=pe.tag,f.anchor!==null&&Se(f,f.anchor,f.result);break}}else if(f.tag!=="!"){if(i.call(f.typeMap[f.kind||"fallback"],f.tag))pe=f.typeMap[f.kind||"fallback"][f.tag];else{pe=null;const He=f.typeMap.multi[f.kind||"fallback"];for(let Pe=0,Xe=He.length;Pe<Xe;Pe+=1)if(f.tag.slice(0,He[Pe].tag.length)===He[Pe].tag){pe=He[Pe];break}}pe||te(f,"unknown tag !<"+f.tag+">"),f.result!==null&&pe.kind!==f.kind&&te(f,"unacceptable node kind for !<"+f.tag+'> tag; it should be "'+pe.kind+'", not "'+f.kind+'"'),pe.resolve(f.result,f.tag)?(f.result=pe.construct(f.result,f.tag),f.anchor!==null&&Se(f,f.anchor,f.result)):te(f,"cannot resolve a node with !<"+f.tag+"> explicit tag")}return f.listener!==null&&f.listener("close",f),f.depth-=1,f.tag!==null||f.anchor!==null||Z}function mt(f){const U=f.position;let Y=!1,ge;for(f.version=null,f.checkLineBreaks=f.legacy,f.tagMap=Object.create(null),f.anchorMap=Object.create(null);(ge=f.input.charCodeAt(f.position))!==0&&(Ze(f,!0,-1),ge=f.input.charCodeAt(f.position),!(f.lineIndent>0||ge!==37));){Y=!0,ge=f.input.charCodeAt(++f.position);let se=f.position;for(;ge!==0&&!j(ge);)ge=f.input.charCodeAt(++f.position);const G=f.input.slice(se,f.position),_=[];for(G.length<1&&te(f,"directive name must not be less than one character in length");ge!==0;){for(;O(ge);)ge=f.input.charCodeAt(++f.position);if(ge===35){do ge=f.input.charCodeAt(++f.position);while(ge!==0&&!$(ge));break}if($(ge))break;for(se=f.position;ge!==0&&!j(ge);)ge=f.input.charCodeAt(++f.position);_.push(f.input.slice(se,f.position))}ge!==0&&Ue(f),i.call(Le,G)?Le[G](f,G,_):Me(f,'unknown document directive "'+G+'"')}if(Ze(f,!0,-1),f.lineIndent===0&&f.input.charCodeAt(f.position)===45&&f.input.charCodeAt(f.position+1)===45&&f.input.charCodeAt(f.position+2)===45?(f.position+=3,Ze(f,!0,-1)):Y&&te(f,"directives end mark is expected"),nt(f,f.lineIndent-1,m,!1,!0),Ze(f,!0,-1),f.checkLineBreaks&&k.test(f.input.slice(U,f.position))&&Me(f,"non-ASCII line breaks are interpreted as content"),f.documents.push(f.result),f.position===f.lineStart&&it(f)){f.input.charCodeAt(f.position)===46&&(f.position+=3,Ze(f,!0,-1));return}f.position<f.length-1&&te(f,"end of the stream or a document separator is expected")}function vt(f,U){f=String(f),U=U||{},f.length!==0&&(f.charCodeAt(f.length-1)!==10&&f.charCodeAt(f.length-1)!==13&&(f+=`
82
+ `),f.charCodeAt(0)===65279&&(f=f.slice(1)));const Y=new je(f,U),ge=f.indexOf("\0");for(ge!==-1&&(Y.position=ge,te(Y,"null byte is not allowed in input")),Y.input+="\0";Y.input.charCodeAt(Y.position)===32;)Y.lineIndent+=1,Y.position+=1;for(;Y.position<Y.length-1;)mt(Y);return Y.documents}function Oe(f,U,Y){U!==null&&typeof U=="object"&&typeof Y>"u"&&(Y=U,U=null);const ge=vt(f,Y);if(typeof U!="function")return ge;for(let se=0,G=ge.length;se<G;se+=1)U(ge[se])}function Ye(f,U){const Y=vt(f,U);if(Y.length!==0){if(Y.length===1)return Y[0];throw new t("expected a single document in the stream, but found more")}}return Ud.loadAll=Oe,Ud.load=Ye,Ud}var Vf={},A0;function c$(){if(A0)return Vf;A0=1;const e=Fc(),t=Vc(),n=cv(),a=Object.prototype.toString,i=Object.prototype.hasOwnProperty,r=65279,s=9,c=10,m=13,u=32,h=33,g=34,S=35,k=37,C=38,A=39,M=42,R=44,$=45,O=58,j=61,I=62,P=63,E=64,L=91,z=93,H=96,J=123,X=124,de=125,je={};je[0]="\\0",je[7]="\\a",je[8]="\\b",je[9]="\\t",je[10]="\\n",je[11]="\\v",je[12]="\\f",je[13]="\\r",je[27]="\\e",je[34]='\\"',je[92]="\\\\",je[133]="\\N",je[160]="\\_",je[8232]="\\L",je[8233]="\\P";const we=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],te=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function Me(_,W){if(W===null)return{};const ne={},Z=Object.keys(W);for(let ce=0,pe=Z.length;ce<pe;ce+=1){let fe=Z[ce],Ae=String(W[fe]);fe.slice(0,2)==="!!"&&(fe="tag:yaml.org,2002:"+fe.slice(2));const Ce=_.compiledTypeMap.fallback[fe];Ce&&i.call(Ce.styleAliases,Ae)&&(Ae=Ce.styleAliases[Ae]),ne[fe]=Ae}return ne}function Se(_){let W,ne;const Z=_.toString(16).toUpperCase();if(_<=255)W="x",ne=2;else if(_<=65535)W="u",ne=4;else if(_<=4294967295)W="U",ne=8;else throw new t("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+W+e.repeat("0",ne-Z.length)+Z}const oe=1,be=2;function re(_){this.schema=_.schema||n,this.indent=Math.max(1,_.indent||2),this.noArrayIndent=_.noArrayIndent||!1,this.skipInvalid=_.skipInvalid||!1,this.flowLevel=e.isNothing(_.flowLevel)?-1:_.flowLevel,this.styleMap=Me(this.schema,_.styles||null),this.sortKeys=_.sortKeys||!1,this.lineWidth=_.lineWidth||80,this.noRefs=_.noRefs||!1,this.noCompatMode=_.noCompatMode||!1,this.condenseFlow=_.condenseFlow||!1,this.quotingType=_.quotingType==='"'?be:oe,this.forceQuotes=_.forceQuotes||!1,this.replacer=typeof _.replacer=="function"?_.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function ue(_,W){const ne=e.repeat(" ",W);let Z=0,ce="";const pe=_.length;for(;Z<pe;){let fe;const Ae=_.indexOf(`
83
+ `,Z);Ae===-1?(fe=_.slice(Z),Z=pe):(fe=_.slice(Z,Ae+1),Z=Ae+1),fe.length&&fe!==`
84
+ `&&(ce+=ne),ce+=fe}return ce}function ke(_,W){return`
85
+ `+e.repeat(" ",_.indent*W)}function Le(_,W){for(let ne=0,Z=_.implicitTypes.length;ne<Z;ne+=1)if(_.implicitTypes[ne].resolve(W))return!0;return!1}function Ie(_){return _===u||_===s}function le(_){return _>=32&&_<=126||_>=161&&_<=55295&&_!==8232&&_!==8233||_>=57344&&_<=65533&&_!==r||_>=65536&&_<=1114111}function xe(_){return le(_)&&_!==r&&_!==m&&_!==c}function Ue(_,W,ne){const Z=xe(_),ce=Z&&!Ie(_);return(ne?Z:Z&&_!==R&&_!==L&&_!==z&&_!==J&&_!==de)&&_!==S&&!(W===O&&!ce)||xe(W)&&!Ie(W)&&_===S||W===O&&ce}function Ze(_){return le(_)&&_!==r&&!Ie(_)&&_!==$&&_!==P&&_!==O&&_!==R&&_!==L&&_!==z&&_!==J&&_!==de&&_!==S&&_!==C&&_!==M&&_!==h&&_!==X&&_!==j&&_!==I&&_!==A&&_!==g&&_!==k&&_!==E&&_!==H}function it(_){return!Ie(_)&&_!==O}function at(_,W){const ne=_.charCodeAt(W);let Z;return ne>=55296&&ne<=56319&&W+1<_.length&&(Z=_.charCodeAt(W+1),Z>=56320&&Z<=57343)?(ne-55296)*1024+Z-56320+65536:ne}function Ne(_){return/^\n* /.test(_)}const We=1,qe=2,q=3,N=4,F=5;function ee(_,W,ne,Z,ce,pe,fe,Ae){let Ce,He=0,Pe=null,Xe=!1,ut=!1;const fn=Z!==-1;let jt=-1,dn=Ze(at(_,0))&&it(at(_,_.length-1));if(W||fe)for(Ce=0;Ce<_.length;He>=65536?Ce+=2:Ce++){if(He=at(_,Ce),!le(He))return F;dn=dn&&Ue(He,Pe,Ae),Pe=He}else{for(Ce=0;Ce<_.length;He>=65536?Ce+=2:Ce++){if(He=at(_,Ce),He===c)Xe=!0,fn&&(ut=ut||Ce-jt-1>Z&&_[jt+1]!==" ",jt=Ce);else if(!le(He))return F;dn=dn&&Ue(He,Pe,Ae),Pe=He}ut=ut||fn&&Ce-jt-1>Z&&_[jt+1]!==" "}return!Xe&&!ut?dn&&!fe&&!ce(_)?We:pe===be?F:qe:ne>9&&Ne(_)?F:fe?pe===be?F:qe:ut?N:q}function me(_,W,ne,Z,ce){_.dump=(function(){if(W.length===0)return _.quotingType===be?'""':"''";if(!_.noCompatMode&&(we.indexOf(W)!==-1||te.test(W)))return _.quotingType===be?'"'+W+'"':"'"+W+"'";const pe=_.indent*Math.max(1,ne),fe=_.lineWidth===-1?-1:Math.max(Math.min(_.lineWidth,40),_.lineWidth-pe),Ae=Z||_.flowLevel>-1&&ne>=_.flowLevel;function Ce(He){return Le(_,He)}switch(ee(W,Ae,_.indent,fe,Ce,_.quotingType,_.forceQuotes&&!Z,ce)){case We:return W;case qe:return"'"+W.replace(/'/g,"''")+"'";case q:return"|"+$e(W,_.indent)+ze(ue(W,pe));case N:return">"+$e(W,_.indent)+ze(ue(tt(W,fe),pe));case F:return'"'+mt(W)+'"';default:throw new t("impossible error: invalid scalar style")}})()}function $e(_,W){const ne=Ne(_)?String(W):"",Z=_[_.length-1]===`
86
+ `,pe=Z&&(_[_.length-2]===`
87
+ `||_===`
88
+ `)?"+":Z?"":"-";return ne+pe+`
89
+ `}function ze(_){return _[_.length-1]===`
90
+ `?_.slice(0,-1):_}function tt(_,W){const ne=/(\n+)([^\n]*)/g;let Z=(function(){let Ae=_.indexOf(`
91
+ `);return Ae=Ae!==-1?Ae:_.length,ne.lastIndex=Ae,nt(_.slice(0,Ae),W)})(),ce=_[0]===`
92
+ `||_[0]===" ",pe,fe;for(;fe=ne.exec(_);){const Ae=fe[1],Ce=fe[2];pe=Ce[0]===" ",Z+=Ae+(!ce&&!pe&&Ce!==""?`
93
+ `:"")+nt(Ce,W),ce=pe}return Z}function nt(_,W){if(_===""||_[0]===" ")return _;const ne=/ [^ ]/g;let Z,ce=0,pe,fe=0,Ae=0,Ce="";for(;Z=ne.exec(_);)Ae=Z.index,Ae-ce>W&&(pe=fe>ce?fe:Ae,Ce+=`
94
+ `+_.slice(ce,pe),ce=pe+1),fe=Ae;return Ce+=`
95
+ `,_.length-ce>W&&fe>ce?Ce+=_.slice(ce,fe)+`
96
+ `+_.slice(fe+1):Ce+=_.slice(ce),Ce.slice(1)}function mt(_){let W="",ne=0;for(let Z=0;Z<_.length;ne>=65536?Z+=2:Z++){ne=at(_,Z);const ce=je[ne];!ce&&le(ne)?(W+=_[Z],ne>=65536&&(W+=_[Z+1])):W+=ce||Se(ne)}return W}function vt(_,W,ne){let Z="";const ce=_.tag;for(let pe=0,fe=ne.length;pe<fe;pe+=1){let Ae=ne[pe];_.replacer&&(Ae=_.replacer.call(ne,String(pe),Ae)),(Y(_,W,Ae,!1,!1)||typeof Ae>"u"&&Y(_,W,null,!1,!1))&&(Z!==""&&(Z+=","+(_.condenseFlow?"":" ")),Z+=_.dump)}_.tag=ce,_.dump="["+Z+"]"}function Oe(_,W,ne,Z){let ce="";const pe=_.tag;for(let fe=0,Ae=ne.length;fe<Ae;fe+=1){let Ce=ne[fe];_.replacer&&(Ce=_.replacer.call(ne,String(fe),Ce)),(Y(_,W+1,Ce,!0,!0,!1,!0)||typeof Ce>"u"&&Y(_,W+1,null,!0,!0,!1,!0))&&((!Z||ce!=="")&&(ce+=ke(_,W)),_.dump&&c===_.dump.charCodeAt(0)?ce+="-":ce+="- ",ce+=_.dump)}_.tag=pe,_.dump=ce||"[]"}function Ye(_,W,ne){let Z="";const ce=_.tag,pe=Object.keys(ne);for(let fe=0,Ae=pe.length;fe<Ae;fe+=1){let Ce="";Z!==""&&(Ce+=", "),_.condenseFlow&&(Ce+='"');const He=pe[fe];let Pe=ne[He];_.replacer&&(Pe=_.replacer.call(ne,He,Pe)),Y(_,W,He,!1,!1)&&(_.dump.length>1024&&(Ce+="? "),Ce+=_.dump+(_.condenseFlow?'"':"")+":"+(_.condenseFlow?"":" "),Y(_,W,Pe,!1,!1)&&(Ce+=_.dump,Z+=Ce))}_.tag=ce,_.dump="{"+Z+"}"}function f(_,W,ne,Z){let ce="";const pe=_.tag,fe=Object.keys(ne);if(_.sortKeys===!0)fe.sort();else if(typeof _.sortKeys=="function")fe.sort(_.sortKeys);else if(_.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let Ae=0,Ce=fe.length;Ae<Ce;Ae+=1){let He="";(!Z||ce!=="")&&(He+=ke(_,W));const Pe=fe[Ae];let Xe=ne[Pe];if(_.replacer&&(Xe=_.replacer.call(ne,Pe,Xe)),!Y(_,W+1,Pe,!0,!0,!0))continue;const ut=_.tag!==null&&_.tag!=="?"||_.dump&&_.dump.length>1024;ut&&(_.dump&&c===_.dump.charCodeAt(0)?He+="?":He+="? "),He+=_.dump,ut&&(He+=ke(_,W)),Y(_,W+1,Xe,!0,ut)&&(_.dump&&c===_.dump.charCodeAt(0)?He+=":":He+=": ",He+=_.dump,ce+=He)}_.tag=pe,_.dump=ce||"{}"}function U(_,W,ne){const Z=ne?_.explicitTypes:_.implicitTypes;for(let ce=0,pe=Z.length;ce<pe;ce+=1){const fe=Z[ce];if((fe.instanceOf||fe.predicate)&&(!fe.instanceOf||typeof W=="object"&&W instanceof fe.instanceOf)&&(!fe.predicate||fe.predicate(W))){if(ne?fe.multi&&fe.representName?_.tag=fe.representName(W):_.tag=fe.tag:_.tag="?",fe.represent){const Ae=_.styleMap[fe.tag]||fe.defaultStyle;let Ce;if(a.call(fe.represent)==="[object Function]")Ce=fe.represent(W,Ae);else if(i.call(fe.represent,Ae))Ce=fe.represent[Ae](W,Ae);else throw new t("!<"+fe.tag+'> tag resolver accepts not "'+Ae+'" style');_.dump=Ce}return!0}}return!1}function Y(_,W,ne,Z,ce,pe,fe){_.tag=null,_.dump=ne,U(_,ne,!1)||U(_,ne,!0);const Ae=a.call(_.dump),Ce=Z;Z&&(Z=_.flowLevel<0||_.flowLevel>W);const He=Ae==="[object Object]"||Ae==="[object Array]";let Pe,Xe;if(He&&(Pe=_.duplicates.indexOf(ne),Xe=Pe!==-1),(_.tag!==null&&_.tag!=="?"||Xe||_.indent!==2&&W>0)&&(ce=!1),Xe&&_.usedDuplicates[Pe])_.dump="*ref_"+Pe;else{if(He&&Xe&&!_.usedDuplicates[Pe]&&(_.usedDuplicates[Pe]=!0),Ae==="[object Object]")Z&&Object.keys(_.dump).length!==0?(f(_,W,_.dump,ce),Xe&&(_.dump="&ref_"+Pe+_.dump)):(Ye(_,W,_.dump),Xe&&(_.dump="&ref_"+Pe+" "+_.dump));else if(Ae==="[object Array]")Z&&_.dump.length!==0?(_.noArrayIndent&&!fe&&W>0?Oe(_,W-1,_.dump,ce):Oe(_,W,_.dump,ce),Xe&&(_.dump="&ref_"+Pe+_.dump)):(vt(_,W,_.dump),Xe&&(_.dump="&ref_"+Pe+" "+_.dump));else if(Ae==="[object String]")_.tag!=="?"&&me(_,_.dump,W,pe,Ce);else{if(Ae==="[object Undefined]")return!1;if(_.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+Ae)}if(_.tag!==null&&_.tag!=="?"){let ut=encodeURI(_.tag[0]==="!"?_.tag.slice(1):_.tag).replace(/!/g,"%21");_.tag[0]==="!"?ut="!"+ut:ut.slice(0,18)==="tag:yaml.org,2002:"?ut="!!"+ut.slice(18):ut="!<"+ut+">",_.dump=ut+" "+_.dump}}return!0}function ge(_,W){const ne=[],Z=[];se(_,ne,Z);const ce=Z.length;for(let pe=0;pe<ce;pe+=1)W.duplicates.push(ne[Z[pe]]);W.usedDuplicates=new Array(ce)}function se(_,W,ne){if(_!==null&&typeof _=="object"){const Z=W.indexOf(_);if(Z!==-1)ne.indexOf(Z)===-1&&ne.push(Z);else if(W.push(_),Array.isArray(_))for(let ce=0,pe=_.length;ce<pe;ce+=1)se(_[ce],W,ne);else{const ce=Object.keys(_);for(let pe=0,fe=ce.length;pe<fe;pe+=1)se(_[ce[pe]],W,ne)}}}function G(_,W){W=W||{};const ne=new re(W);ne.noRefs||ge(_,ne);let Z=_;return ne.replacer&&(Z=ne.replacer.call({"":Z},"",Z)),Y(ne,0,Z,!0,!0)?ne.dump+`
97
+ `:""}return Vf.dump=G,Vf}var T0;function d$(){if(T0)return Vn;T0=1;const e=l$(),t=c$();function n(a,i){return function(){throw new Error("Function yaml."+a+" is removed in js-yaml 4. Use yaml."+i+" instead, which is now safe by default.")}}return Vn.Type=ta(),Vn.Schema=LI(),Vn.FAILSAFE_SCHEMA=BI(),Vn.JSON_SCHEMA=GI(),Vn.CORE_SCHEMA=JI(),Vn.DEFAULT_SCHEMA=cv(),Vn.load=e.load,Vn.loadAll=e.loadAll,Vn.dump=t.dump,Vn.YAMLException=Vc(),Vn.types={binary:QI(),float:WI(),map:zI(),null:FI(),pairs:e1(),set:t1(),timestamp:ZI(),bool:VI(),int:KI(),merge:YI(),omap:XI(),seq:UI(),str:qI()},Vn.safeLoad=n("safeLoad","load"),Vn.safeLoadAll=n("safeLoadAll","loadAll"),Vn.safeDump=n("safeDump","dump"),Vn}var u$=d$();const m$=r$(u$),{Type:Sne,Schema:xne,FAILSAFE_SCHEMA:kne,JSON_SCHEMA:Ine,CORE_SCHEMA:wne,DEFAULT_SCHEMA:_ne,load:Cne,loadAll:Rne,dump:Pne,YAMLException:Ane,types:Tne,safeLoad:Ene,safeLoadAll:Mne,safeDump:jne}=m$,dv=3e3,uv=9999,One="openpond.yaml",p$=["google","github","x"],mv=new Set([22,2222,2375,2376,3108,5900,5901,6080,7818]),E0=p(o().trim().min(1).max(1e3)).max(50),vc=o().trim().min(1).max(4096).refine(o1,{message:"path must be a relative workspace path"}),f$=o().trim().min(1).max(500).refine(e=>!e.includes("\0")&&!/\s/.test(e),"image ref must be a single OCI reference"),h$=o().trim().regex(/^sha256:[0-9a-f]{64}$/i),n1=o().trim().min(1).max(500).refine(e=>e.startsWith("/")&&!e.includes("\0"),"workspaceRoot must be an absolute guest path"),g$=l({ref:f$,digest:h$.optional(),registrySecretRef:o().trim().min(1).max(500).optional(),platform:b("linux/amd64").optional(),workspaceRoot:n1.optional()}).strict(),v$=l({context:vc.default("."),path:vc.default("Dockerfile"),target:o().trim().min(1).max(191).optional(),buildArgs:ae(o().max(191),o().max(500)).optional(),registrySecretRefs:p(o().trim().min(1).max(500)).max(10).optional(),platform:b("linux/amd64").optional(),workspaceRoot:n1.optional()}).strict(),b$=l({base:o().trim().min(1).max(120).optional(),snapshot:o().trim().min(1).max(191).optional(),image:g$.optional(),dockerfile:v$.optional()}).strict().superRefine((e,t)=>{[e.base,e.snapshot,e.image,e.dockerfile].filter(Boolean).length!==1&&t.addIssue({code:Yn.custom,message:"runtime must declare exactly one of base, snapshot, image, or dockerfile"})}),a1=l({cpu:d().positive().max(8).optional(),memoryGb:d().positive().max(32).optional(),diskGb:d().positive().max(100).optional()}).strict(),y$=l({provider:v(p$),scopes:p(o().trim().min(1).max(200)).max(100).default([]),capabilities:p(o().trim().min(1).max(200)).max(100).default([])}).strict(),S$=l({models:p(o().trim().min(1).max(200)).max(100).default([]),scopes:p(o().trim().min(1).max(200)).max(100).default([])}).strict(),x$=l({opchat:S$.optional()}).catchall(ae(o(),ie())).default({}),k$=l({name:o().trim().regex(/^[A-Za-z_][A-Za-z0-9_-]*$/).max(63).optional(),mountPath:o().trim().min(1).max(256).optional(),storageGb:d().int().positive().max(100).optional(),deleteOnSandboxDelete:w().optional()}).strict(),I$=l({port:d().int().min(dv).max(uv).refine(e=>!mv.has(e),{message:"preview port is reserved"}),protocol:b("http").default("http"),label:o().trim().min(1).max(80).optional(),access:v(["private","public"]).default("private"),path:o().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"preview path must start with /"}).default("/")}).strict(),i1=l({command:o().trim().min(1).max(1e3),cwd:vc.optional(),timeoutSeconds:d().int().positive().max(86400).optional(),requiresStart:w().default(!1),ports:p(I$).max(20).default([]),artifactPaths:p(vc).max(100).default([])}).strict(),M0=i1.extend({name:o().trim().min(1).max(80)}).strict(),w$=l({name:o().trim().min(1).max(80).optional(),service:o().trim().min(1).max(80).optional(),port:d().int().min(dv).max(uv).refine(e=>!mv.has(e),{message:"app MCP port is reserved"}),path:o().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"app MCP path must start with /"}).default("/mcp")}).strict(),_$=l({name:o().trim().min(1).max(80).optional(),port:d().int().min(dv).max(uv).refine(e=>!mv.has(e),{message:"validation probe port is reserved"}),path:o().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"validation probe path must start with /"}).default("/"),expectedStatus:d().int().min(100).max(599).default(200)}).strict(),C$=ae(o(),ie()).refine(e=>e.type==="object","input schema must be a JSON schema object"),R$=l({name:o().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),required:w().default(!1),secret:w().default(!0),description:o().trim().max(500).optional()}).strict(),Kf=o().trim().min(1).max(120),P$=l({name:o().trim().min(1).max(120),description:o().trim().max(500).optional(),cron:o().trim().min(1).max(500).optional(),rate:o().trim().min(1).max(500).optional(),once:Kf.optional(),scheduleType:v(["rate","cron","once"]).optional(),scheduleExpression:o().trim().min(1).max(500).optional(),timezone:o().trim().min(1).max(100).optional(),enabled:w().default(!0),startAt:Kf.optional(),endAt:Kf.optional(),maxRuns:d().int().positive().nullable().optional(),runtimePolicy:v(["run_and_stop","run_and_archive","run_and_delete","use_existing_running"]).default("run_and_stop"),action:o().trim().min(1).max(120).optional(),actionName:o().trim().min(1).max(120).optional(),command:o().trim().min(1).max(2e3).optional(),target:l({kind:v(["start","action","service","command"]).optional(),name:o().trim().min(1).max(120).optional(),actionName:o().trim().min(1).max(120).optional(),command:o().trim().min(1).max(2e3).optional(),requiresStart:w().optional()}).strict().optional(),requiresStart:w().optional(),budget:l({maxUsd:o().trim().min(1).max(40).optional()}).strict().optional(),resources:a1.optional(),quotas:ae(o(),ie()).optional(),lifecycle:ae(o(),ie()).optional(),retentionPolicy:ae(o(),ie()).optional(),env:p(l({name:o().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),value:o().optional(),secretRef:o().optional()}).strict()).max(100).optional(),integrationLeases:p(ae(o(),ie())).max(20).optional(),metadata:ae(o(),ie()).optional()}).strict().superRefine((e,t)=>{[e.cron,e.rate,e.once,e.scheduleExpression].filter(c=>typeof c=="string"&&c.trim()).length!==1&&t.addIssue({code:Yn.custom,path:["scheduleExpression"],message:"schedule must declare exactly one of cron, rate, once, or scheduleExpression"}),e.scheduleExpression&&!e.scheduleType&&t.addIssue({code:Yn.custom,path:["scheduleType"],message:"scheduleType is required with scheduleExpression"});const a=e.command??e.target?.command??null,i=e.target?.name??null,r=e.actionName??e.action??e.target?.actionName??(e.target?.kind==="action"?i:null),s=e.target?.kind??(a?"command":"action");s==="action"&&!r&&t.addIssue({code:Yn.custom,path:["action"],message:"schedule action target is required"}),s==="service"&&!i&&t.addIssue({code:Yn.custom,path:["target","name"],message:"schedule service target name is required"}),s==="command"&&!a&&t.addIssue({code:Yn.custom,path:["command"],message:"schedule command target is required"})}),A$=l({schemaVersion:b(1),name:o().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9-]*[a-z0-9]$/),version:o().trim().min(1).max(40),useCase:o().trim().min(1).max(80),description:o().trim().min(1).max(500),runtime:b$,resources:a1.optional(),setup:l({commands:E0.default([])}).strict().default({commands:[]}),validation:l({commands:E0.min(1),probes:p(_$).max(20).default([])}).strict(),start:i1,actions:p(M0).max(20).default([]),services:p(M0).max(20).default([]),schedules:p(P$).max(20).default([]),mcp:l({endpoints:p(w$).max(10).default([])}).strict().default({endpoints:[]}),volumes:p(k$).max(5).default([]),integrations:l({requiredLeases:p(y$).max(20).default([])}).strict().default({requiredLeases:[]}),permissions:x$,inputs:l({schema:C$.default({type:"object"}),env:p(R$).max(100).default([])}).strict().default({schema:{type:"object"},env:[]}),artifacts:l({paths:p(vc).max(100).default([])}).strict().default({paths:[]}),network:l({egress:v(["restricted","allow","block"]).default("restricted")}).strict().default({egress:"restricted"})}).strict().superRefine((e,t)=>{E$(e,t),pv(t,e.volumes.flatMap(n=>n.name?[n.name]:[]),"volume names must be unique","volumes"),M$(e,t),j$(e,t),O$(e,t),$$(e,t)}),T$=l({path:o(),message:o(),code:o()});function $ne(e){return[{kind:"start",name:"start",...e.start,artifactPaths:Gf(e.start,e)},...e.actions.map(t=>({kind:"action",name:t.name,command:t.command,cwd:t.cwd,timeoutSeconds:t.timeoutSeconds,requiresStart:t.requiresStart,ports:t.ports,artifactPaths:Gf(t,e)})),...e.services.map(t=>({kind:"service",name:t.name,command:t.command,cwd:t.cwd,timeoutSeconds:t.timeoutSeconds,requiresStart:t.requiresStart,ports:t.ports,artifactPaths:Gf(t,e)}))]}function o1(e){return!e.includes("\0")&&!e.startsWith("/")&&!e.split(/[\\/]+/).some(t=>t===".."||t==="")}function pv(e,t,n,a){const i=new Set;for(const r of t){if(i.has(r)){e.addIssue({code:Yn.custom,path:[a],message:n});return}i.add(r)}}function E$(e,t){const n=["start",...e.actions.map(a=>a.name),...e.services.map(a=>a.name)];pv(t,n,"start, action, and service names must be unique","actions")}function M$(e,t){const n=Wf(e.inputs.schema.properties),a=new Set(e.volumes.map(i=>i.name).filter(i=>!!i));for(const[i,r]of Object.entries(n)){const s=Wf(r),c=Wf(s["x-openpond-upload"]??s.xOpenPondUpload),m=typeof c.targetPath=="string"&&c.targetPath.trim()?c.targetPath.trim():typeof c.path=="string"&&c.path.trim()?c.path.trim():"";if(!m)continue;const u=m.replace(/^workspace\//,"").replace(/^\/+/,"").replace(/\/+$/,"");if(!o1(u)){t.addIssue({code:Yn.custom,path:["inputs","schema","properties",i,"x-openpond-upload","targetPath"],message:"upload target must be a relative workspace path"});continue}const h=u.split("/");h[0]==="volumes"&&(!h[1]||!a.has(h[1]))&&t.addIssue({code:Yn.custom,path:["inputs","schema","properties",i,"x-openpond-upload","targetPath"],message:"upload target references an undeclared volume"})}}function j$(e,t){pv(t,e.inputs.env.map(n=>n.name),"env input names must be unique","inputs")}function O$(e,t){const n=new Map(e.services.map(i=>[i.name,new Set(i.ports.map(r=>r.port))])),a=new Set([...e.start.ports.map(i=>i.port),...e.services.flatMap(i=>i.ports.map(r=>r.port))]);for(const[i,r]of e.mcp.endpoints.entries()){if(r.service){const s=n.get(r.service);if(!s){t.addIssue({code:Yn.custom,path:["mcp","endpoints",i,"service"],message:`app MCP service does not exist: ${r.service}`});continue}s.has(r.port)||t.addIssue({code:Yn.custom,path:["mcp","endpoints",i,"port"],message:`app MCP port ${r.port} is not declared on service ${r.service}`});continue}a.has(r.port)||t.addIssue({code:Yn.custom,path:["mcp","endpoints",i,"port"],message:`app MCP port ${r.port} is not declared on start or services`})}}function $$(e,t){const n=new Set(e.actions.map(i=>i.name)),a=new Set(e.services.map(i=>i.name));for(const[i,r]of e.schedules.entries()){const s=r.command??r.target?.command??null;if(r.target?.kind==="command"||s)continue;const c=r.actionName??r.action??r.target?.actionName??(r.target?.kind==="action"?r.target?.name:null);if(c&&!n.has(c)&&t.addIssue({code:Yn.custom,path:["schedules",i,"action"],message:`schedule action target does not exist: ${c}`}),r.target?.kind==="service"){const m=r.target.name??"";m&&!a.has(m)&&t.addIssue({code:Yn.custom,path:["schedules",i,"target","name"],message:`schedule service target does not exist: ${m}`})}}}function Wf(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Gf(e,t){return e.artifactPaths.length>0?e.artifactPaths:t.artifacts.paths}const N$=l({id:o(),name:o(),description:o().nullable(),scheduleType:o(),scheduleExpression:o(),enabled:w(),rawEnabled:w().optional(),syncStatus:o().nullable(),syncError:o().nullable().optional(),startAt:o().nullable(),endAt:o().nullable(),maxRuns:d().nullable(),executionCount:d().nullable(),lifecycleStatus:o().nullable(),lifecycleReason:o().nullable(),lastExecutionAt:o().nullable().optional(),lastExecutionStatus:o().nullable().optional(),lastRunNowAt:o().nullable().optional(),lastRunNowStatus:o().nullable().optional(),updatedAt:o(),deploymentId:o(),isProduction:w().optional(),payload:ie().optional()}).passthrough(),D$=l({total:d().int().nonnegative(),active:d().int().nonnegative(),paused:d().int().nonnegative(),enabled:d().int().nonnegative().optional(),disabled:d().int().nonnegative().optional(),nextRunAt:o().nullable().optional(),lastRunAt:o().nullable().optional(),schedules:p(N$).optional().default([]),truncated:w().optional()}).passthrough(),Jf=l({name:o(),kind:v(["start","action","service"]),command:o(),cwd:o().nullable(),timeoutSeconds:d().nullable(),requiresStart:w(),ports:p(l({port:d(),protocol:o(),label:o().nullable(),access:o(),path:o()}).passthrough()).default([]),artifactPaths:p(o()).default([])}).passthrough(),H$=l({schemaVersion:b(1),source:b("openpond.yaml"),manifestName:o(),manifestVersion:o(),manifestUseCase:o(),manifestDescription:o(),manifestPath:o(),manifestHash:o(),inputSchema:ae(o(),ie()).default({}),env:p(l({name:o(),required:w(),secret:w(),description:o().nullable()}).passthrough()).default([]),start:Jf,actions:p(Jf).default([]),services:p(Jf).default([]),defaultActionName:o().nullable(),updatedAt:o()}).passthrough(),L$=l({id:o(),name:o(),description:o().nullable(),visibility:o().nullable().optional(),gitOwner:o().nullable().optional(),gitRepo:o().nullable().optional(),gitHost:o().nullable().optional(),defaultBranch:o().nullable().optional(),sandbox:w().optional().default(!1),sandboxActionRegistry:H$.nullable().optional(),sandboxManifestHash:o().nullable().optional(),sandboxManifestPath:o().nullable().optional(),sandboxManifestSyncedAt:o().nullable().optional(),sandboxManifestError:o().nullable().optional(),updatedAt:o().nullable().optional(),latestDeployment:l({id:o().optional(),status:o().optional(),deploymentDomain:o().nullable().optional(),createdAt:o().optional(),isProduction:w().nullable().optional(),gitBranch:o().nullable().optional()}).nullable().optional(),scheduleSummary:D$.nullable().optional()}),q$=l({detected:w(),rootPath:o(),manifestPath:o(),manifestHash:o().nullable().optional().default(null),manifest:ae(o(),ie()).nullable().optional().default(null),normalizedManifest:A$.nullable().optional().default(null),valid:w().optional().default(!1),diagnostics:p(T$).optional().default([])}),U$=l({appId:o(),appName:o(),gitOwner:o().nullable(),gitRepo:o().nullable(),gitHost:o().nullable(),defaultBranch:o().nullable(),linkedAt:o()}),r1=l({teamId:o(),projectId:o(),projectSlug:o().nullable().optional().default(null),projectName:o().nullable().optional().default(null),sourceRepoUrl:o().nullable().optional().default(null),defaultBranch:o().nullable().optional().default(null),lastUploadedCommit:o().nullable().optional().default(null),lastUploadTransport:v(["git_head","snapshot","api_source_upload"]).nullable().optional().default(null),manifestPath:o().nullable().optional().default(null),manifestHash:o().nullable().optional().default(null),syncedAt:o().nullable().optional().default(null),linkedAt:o()}),z$=v(["github_repo","internal_repo","template","manual"]),B$=l({id:o(),teamId:o(),name:o(),slug:o().nullable().optional().default(null),sourceType:z$.optional().default("manual"),sourceLabel:o().nullable().optional().default(null),defaultBranch:o().nullable().optional().default(null),internalRepoPath:o().nullable().optional().default(null),manifestPath:o().nullable().optional().default(null),manifestHash:o().nullable().optional().default(null),syncedAt:o().nullable().optional().default(null),organizationName:o().nullable().optional().default(null),organizationSlug:o().nullable().optional().default(null),createdAt:o().nullable().optional().default(null),updatedAt:o().nullable().optional().default(null)}),F$=l({id:o(),name:o(),path:o(),workspacePath:o(),repoPath:o().nullable(),source:v(["folder","git"]),sourceFolders:p(o().min(1)).min(1).optional(),hiddenFromDefaultSidebar:w().optional(),sandboxTemplate:q$.nullable().optional().default(null),linkedOpenPondApp:U$.nullable().optional().default(null),linkedSandboxProject:r1.nullable().optional().default(null),preferredSandboxAgentId:o().nullable().optional().default(null),createdAt:o(),updatedAt:o()});l({path:o().trim().min(1).optional(),sourceFolders:p(o().trim().min(1)).min(1).optional(),primaryFolder:o().trim().min(1).optional(),name:o().trim().min(1).max(120).optional(),createNew:w().optional(),baseDirectory:o().trim().min(1).max(4096).optional()}).superRefine((e,t)=>{if(e.createNew){(e.path||e.sourceFolders||e.primaryFolder)&&t.addIssue({code:"custom",message:"A new folder cannot be combined with existing source folders."}),e.name?.trim()||t.addIssue({code:"custom",path:["name"],message:"Project name is required when creating a new project."});return}e.path&&e.sourceFolders&&t.addIssue({code:"custom",message:"Use either path or source folders."}),!e.path?.trim()&&!e.sourceFolders?.length&&t.addIssue({code:"custom",path:["path"],message:"Project path is required."}),e.sourceFolders?.length&&!e.name?.trim()&&t.addIssue({code:"custom",path:["name"],message:"Project name is required."}),e.primaryFolder&&!e.sourceFolders?.length&&t.addIssue({code:"custom",path:["primaryFolder"],message:"Primary folder requires source folders."})});l({linkedSandboxProject:r1.nullable().optional(),preferredSandboxAgentId:o().nullable().optional(),hiddenFromDefaultSidebar:w().optional()});const V$=["connected_app_search","connected_app_read","connected_app_write"],Zf="https://openpond.ai",fv=["slack","google","github","turnkey","x","microsoft_teams","mcp"],hv={slack:[Xt("slack.channel.bind","Bind channels","Bind Slack channels or threads to OpenPond profiles.","setup",!1),Xt("slack.message.ingest","Ingest messages","Ingest Slack channel or thread activity into OpenPond context.","setup",!1)],microsoft_teams:[Xt("microsoft_teams.channel.bind","Bind channels","Bind Teams channels or chats to OpenPond profiles.","setup",!1),Xt("microsoft_teams.message.ingest","Ingest messages","Ingest Teams channel or chat activity into OpenPond context.","setup",!1)],google:[Xt("google.drive.file.read","Read Drive files","Find and read Google Drive files.","read",!0),Xt("google.drive.file.write","Write Drive files","Create or update approved Google Drive files.","write",!0),Xt("google.docs.read","Read Docs","Read Google Docs content and structure.","read",!0),Xt("google.docs.write","Edit Docs","Apply approved Google Docs edits.","write",!0),Xt("google.comments.read","Read comments","Read Google file comments.","read",!0),Xt("google.comments.write","Write comments","Create or resolve approved Google comments.","write",!0)],github:[Xt("github.repo.read","Read repositories","Read repository metadata and file context.","read",!0),Xt("github.issue.read","Read issues","Read GitHub issues and comments.","read",!0),Xt("github.issue.write","Update issues","Create or update approved GitHub issue content.","write",!0),Xt("github.pull_request.read","Read pull requests","Read pull request metadata, diffs, checks, and reviews.","read",!0),Xt("github.pull_request.write","Update pull requests","Create approved comments or pull request updates.","write",!0)],turnkey:[Xt("turnkey.wallets.read","Read Agent Wallet","Read the connected OpenPond Agent Wallet address and metadata.","read",!0),Xt("turnkey.balances.read","Read wallet balances","Read balances for the connected OpenPond Agent Wallet.","read",!0),Xt("turnkey.activities.read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.","read",!0)],x:[Xt("x.profile.read","Read profile","Read the connected X profile.","read",!0),Xt("x.search.read","Search X","Search public X posts when granted.","read",!0),Xt("x.mentions.read","Read mentions","Read mentions for the connected X account.","read",!0),Xt("x.post.write","Post","Create approved X posts.","write",!0),Xt("x.reply.write","Reply","Create approved X replies.","write",!0)],mcp:[Xt("mcp.tool.discover","Discover tools","Discover team-scoped MCP tools.","tooling",!1),Xt("mcp.tool.call","Call tools","Call approved MCP tools through the team endpoint.","tooling",!1)]},gv={slack:[],microsoft_teams:[],google:[zt("google.drive.search","search","Search Drive","Search Google Drive files by grounded query.",["google.drive.file.read"]),zt("google.drive.read_file","read","Read Drive file","Read Drive file metadata or exported content by stable ref.",["google.drive.file.read"],{requiredKeys:["ref"]}),zt("google.docs.read","read","Read Google Doc","Read Google Docs content and structure by stable ref.",["google.docs.read"],{requiredKeys:["ref"]}),zt("google.comments.read","read","Read comments","Read comments for a grounded Google file ref.",["google.comments.read"],{requiredKeys:["ref"]}),zt("google.docs.update","write","Update Google Doc","Apply an explicitly approved Google Docs edit and return readback verification.",["google.docs.write"],{requiredKeys:["ref","patch"]}),zt("google.comments.create","write","Create comment","Create an explicitly approved Google file comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","body"]}),zt("google.comments.resolve","write","Resolve comment","Resolve an explicitly approved Google comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","commentId"]})],github:[zt("github.repo.search","search","Search repositories","Search accessible repositories by owner, name, or topic.",["github.repo.read"]),zt("github.issue.search","search","Search issues","Search accessible GitHub issues.",["github.issue.read"]),zt("github.pull_request.search","search","Search pull requests","Search accessible GitHub pull requests.",["github.pull_request.read"]),zt("github.repo.read","read","Read repository","Read grounded repository metadata or file context.",["github.repo.read"],{requiredKeys:["ref"]}),zt("github.issue.read","read","Read issue","Read a grounded GitHub issue and comments.",["github.issue.read"],{requiredKeys:["ref"]}),zt("github.pull_request.read","read","Read pull request","Read a grounded pull request, checks, reviews, or diff summary.",["github.pull_request.read"],{requiredKeys:["ref"]}),zt("github.issue.create","write","Create issue","Create an explicitly approved GitHub issue and return readback verification.",["github.issue.write"],{requiredKeys:["repo","title","body"]}),zt("github.issue.comment","write","Comment on issue","Create an explicitly approved GitHub issue comment and return readback verification.",["github.issue.write"],{requiredKeys:["ref","body"]}),zt("github.issue.update","write","Update issue","Apply an explicitly approved issue metadata/content update and return readback verification.",["github.issue.write"],{requiredKeys:["ref"]}),zt("github.pull_request.comment","write","Comment on pull request","Create an explicitly approved pull request comment and return readback verification.",["github.pull_request.write"],{requiredKeys:["ref","body"]}),zt("github.pull_request.update","write","Update pull request","Apply an explicitly approved pull request metadata update and return readback verification.",["github.pull_request.write"],{requiredKeys:["ref"]})],turnkey:[zt("turnkey.wallets.read","read","Read Agent Wallet","Read the address and metadata for the connected OpenPond Agent Wallet.",["turnkey.wallets.read"]),zt("turnkey.balances.read","read","Read wallet balances","Read supported-network balances for the connected OpenPond Agent Wallet.",["turnkey.balances.read"]),zt("turnkey.activities.read","read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.",["turnkey.activities.read"])],x:[zt("x.profile.read","read","Read profile","Read the connected X account profile.",["x.profile.read"]),zt("x.post.read","read","Read post","Read a public X post by stable ref, status URL, or post id.",["x.search.read"],{requiredKeys:["ref"]}),zt("x.search.posts","search","Search recent posts","Search public X posts from the X recent-search window by grounded query.",["x.search.read"]),zt("x.mentions.search","search","Search mentions","Search mentions for the connected X account.",["x.mentions.read"]),zt("x.mention.read","read","Read mention","Read a grounded mention or post ref.",["x.mentions.read"],{requiredKeys:["ref"]}),zt("x.post.create","write","Create post","Create an explicitly approved X post and return readback verification.",["x.post.write"],{requiredKeys:["text"]}),zt("x.reply.create","write","Create reply","Create an explicitly approved X reply and return readback verification.",["x.reply.write"],{requiredKeys:["inReplyToRef","text"]})],mcp:[]},K$={google:["# Google Connected App","","Use Google only through server-provided connected app tools. Never ask for or infer OAuth tokens.","Before reading or editing, identify the exact Drive file, Doc, Sheet, Slide, or comment thread. If the target is ambiguous, ask a short clarification or search first.","Use only declared Google operation ids: google.drive.search, google.drive.read_file, google.docs.read, google.comments.read, google.docs.update, google.comments.create, google.comments.resolve.","For writes, require explicit user intent, summarize the planned change, and verify the target identity before applying updates.","After a write, read back the changed object or relevant range and report the result with the provider file name or stable reference.","Prefer narrow reads over broad Drive scans. Do not expose private file ids unless the tool result already presents them as stable refs."].join(`
98
+ `),github:["# GitHub Connected App","","Use GitHub only through server-provided connected app tools. Repository, issue, and pull request identity must be grounded before action.","Use only declared GitHub operation ids: github.repo.search, github.issue.search, github.pull_request.search, github.repo.read, github.issue.read, github.pull_request.read, github.issue.create, github.issue.comment, github.issue.update, github.pull_request.comment, github.pull_request.update.","For reads, name the owner/repo and issue or pull request number when available. If several targets match, ask or inspect before proceeding.","For writes, require explicit user intent and avoid destructive repository changes. Create issues only when the user clearly asks to submit or file a new issue. Prefer comments, labels, or metadata updates unless a stronger operation is clearly requested.","Do not claim CI, review, branch, or PR state changed until a tool result confirms it.","Keep local workspace git operations separate from connected GitHub operations unless the user explicitly asks to bridge them."].join(`
99
+ `),turnkey:["# Turnkey Agent Wallet Connected App","","Use Turnkey only through server-provided connected app tools. Never ask for, expose, or infer API keys, P-256 credentials, wallet private keys, or lease material.","Use only declared Turnkey read operation ids: turnkey.wallets.read, turnkey.balances.read, and turnkey.activities.read.","Turnkey connected-app access is read-only. Do not claim that a transaction was created, signed, approved, rejected, or sent.","Use turnkey.wallets.read for the Agent Wallet address and metadata, turnkey.balances.read for supported-network balances, and turnkey.activities.read for recent Turnkey activity.","Report the wallet address and network with balance results, and distinguish an empty balance from a failed provider read."].join(`
100
+ `),x:["# X Connected App","","Use X only through server-provided connected app tools. Distinguish profile, recent search, mention, post, and reply operations.","Use only declared X operation ids: x.profile.read, x.post.read, x.search.posts, x.mentions.search, x.mention.read, x.post.create, x.reply.create.","For x.com, twitter.com, or stable status URLs, first parse the status/post id and read the post with connected_app_read using operation x.post.read and ref set to the original URL, stable ref, or id. Do not open a browser before trying the X connector.","Use x.search.posts for discovery, related public posts, replies, quote-post searches, and conversation scans. It uses X API recent search, so report zero-result searches as zero recent public posts returned by X.","For conversation or reply collection, dedupe by returned post id/ref. Do not repeat the same search call unless the result exposes a usable cursor or next token; if pagination is unavailable, state that coverage is limited to returned recent-search results.","Reads can summarize recent public posts, connected-account profile details, and mentions when the capability is available.","Writes require explicit user intent for the exact post or reply. Do not publish drafts, jokes, endorsements, or replies unless the user clearly approves the content.","Before posting or replying, preserve account identity, quote the proposed content in summary form, and respect provider limits and policy boundaries.","After a write, verify the returned post or reply ref before reporting success."].join(`
101
+ `),microsoft_teams:["# Microsoft Teams Connected App","","Microsoft Teams is currently an ingestion/native binding surface only. Do not expose Teams OAuth reads, replies, file operations, or sandbox leases.","Native Teams setup can bind chats or channels to OpenPond profiles and ingest activity into OpenPond context.","If the user asks for Teams actions beyond ingestion or binding status, explain that the connector is not available yet rather than inventing tool access."].join(`
102
+ `),slack:["# Slack Connected App","","Slack is currently an ingestion/native binding surface only. Do not expose Slack OAuth reads, replies, file operations, or sandbox leases.","Native Slack setup can bind channels or threads to OpenPond profiles and ingest activity into OpenPond context.","If the user asks for Slack actions beyond ingestion or binding status, explain that the connector is not available yet rather than inventing tool access."].join(`
103
+ `),mcp:["# OpenPond MCP Connected App","","Use OpenPond MCP only through server-provided tool discovery and call paths. Do not invent MCP tools or endpoints.","Treat MCP as team-scoped tooling, not an OAuth connector. Tool availability must come from server-confirmed discovery results.","Before calling an MCP tool, match the requested operation to the tool name, description, input schema, and allowed team context.","For writes or side effects, require explicit user intent and report only confirmed tool results."].join(`
104
+ `)},Nne=fv.map(e=>{const t=l1(e),n=K$[e];return{...t,provider:e,body:n,sourceHash:`connected-app-skill:${e}:${mN(n)}`,charCount:n.length}});function W$(e){const t=vv(e.provider);if(!t)return{ok:!1,error:`Connected app provider is not supported: ${e.provider}`};if(!t.leasePolicy.leaseable)return{ok:!1,error:`Connected app provider ${e.provider} is not leaseable for cloud connector execution.`};const n=sN(e.operation);if(e.toolName!==n)return{ok:!1,error:`Connected app tool ${e.toolName} does not match ${e.operation} operation.`};const a=e.operation==="write"?"write":"read",i=new Set(t.capabilities.filter(c=>c.access===a&&c.leaseable).map(c=>c.id)),r=e.capabilityIds.filter(c=>!i.has(c));if(r.length>0)return{ok:!1,error:`Connected app capability ${r[0]} is not allowed for ${e.provider} ${e.operation}.`};const s=J$(e);return s.ok?{ok:!0,request:e}:s}function G$(e){const t=vm(e);return t?gv[t]:[]}function J$(e){const t=X$(e.args),n=G$(e.provider).filter(s=>s.operation===e.operation);if(n.length===0)return{ok:!1,error:`Connected app provider ${e.provider} does not declare ${e.operation} operations.`};if(!t)return e.operation==="write"?{ok:!1,error:`Connected app ${e.provider} write calls require a provider operation id.`}:{ok:!0,request:e};const a=n.find(s=>s.id===t);if(!a)return{ok:!1,error:`Connected app operation ${t} is not allowed for ${e.provider} ${e.operation}.`};const i=e.capabilityIds.filter(s=>!a.capabilityIds.includes(s));if(i.length>0)return{ok:!1,error:`Connected app operation ${a.id} does not allow capability ${i[0]}.`};const r=tN(e.args,e.operation);for(const s of a.input?.requiredKeys??[]){const c=r[s];if(c==null||typeof c=="string"&&!c.trim())return{ok:!1,error:`Connected app operation ${a.id} requires input.${s}.`}}return{ok:!0,request:e}}const Z$=[{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"}],gm=Z$,Y$=fv.map(e=>{const t=gm.filter(a=>a.providerFamily===e),n=t[0];return{id:e,label:ac(e),shortLabel:n.shortLabel,category:n.category,icon:n.icon,description:n.description,setupSurfaces:t,capabilities:hv[e],skills:oN(e),tools:rN(e),operations:gv[e],leasePolicy:lN(e)}});function s1(e){const t=Q$(e);return t?gm.find(n=>n.id===t)??null:null}function vv(e){const t=vm(e);return t?Y$.find(n=>n.id===t)??null:null}function Dne(e){const t=s1(e.appId),n=aN(e.baseUrl),a=t?.kind==="mcp"?"/sandboxes/mcp":"/sandboxes/apps",i=new URL(a,n);t?.kind!=="mcp"&&i.searchParams.set("app",t?.deepLinkAppId??e.appId);const r=e.teamId?.trim();return r&&i.searchParams.set("teamId",r),i.toString()}function Q$(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":gm.some(n=>n.id===t)?t:null:null}function vm(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":fv.includes(t)?t:s1(t)?.providerFamily??null:null}function Yf(e={}){const t=cN(e.connections??[]);return gm.map(n=>{const a=vv(n.providerFamily),i=n.statusSource==="integration_connection"?t.filter(c=>c.provider===n.providerFamily):[],r=i.some(c=>c.status==="active"),s=dN(n,r);return{...n,providerLabel:a.label,setupSurfaceLabel:iN(n.setupSurface),status:s,statusLabel:uN(n,s,i),connections:i,connected:r,capabilities:j0(n,a.capabilities),capabilityLabels:j0(n,a.capabilities).map(c=>c.label),leasePolicy:a.leasePolicy}})}function Xt(e,t,n,a,i){return{id:e,label:t,description:n,access:a,leaseable:i}}function zt(e,t,n,a,i,r){return{id:e,operation:t,label:n,description:a,capabilityIds:i,...r?{input:r}:{},requiresReadback:t==="write",requiresRuntimeLease:!1}}function X$(e){return eN(e.operation)}function eN(e){return typeof e=="string"&&e.trim()?e.trim():null}function tN(e,t){return t==="write"?nN(e.input)?e.input:{}:e}function nN(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function aN(e){const t=e?.trim();if(!t)return Zf;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?Zf:(n.pathname="/",n.search="",n.hash="",n.toString())}catch{return Zf}}function ac(e){return e==="microsoft_teams"?"Microsoft Teams":e==="mcp"?"OpenPond MCP":e==="x"?"X":e[0].toUpperCase()+e.slice(1)}function iN(e){return e==="native_bot"?"Native app":e==="oauth_connector"?"OAuth connector":e==="wallet_connector"?"Wallet connector":"MCP endpoint"}function oN(e){return[l1(e)]}function l1(e){return{name:`${e}-connected-app`,description:`Use ${ac(e)} safely through connected app tools.`,path:`integration_skills/${e}.md`}}function rN(e){if(e==="mcp")return[];const t=hv[e],n=gv[e],a=t.filter(s=>s.access==="read").map(s=>s.id),i=t.filter(s=>s.access==="write").map(s=>s.id),r=[];return n.some(s=>s.operation==="search")&&r.push({name:"connected_app_search",description:`Search ${ac(e)} through a server-owned connected app connector.`,capabilityIds:a,write:!1}),n.some(s=>s.operation==="read")&&r.push({name:"connected_app_read",description:`Read a grounded ${ac(e)} object through a server-owned connected app connector.`,capabilityIds:a,write:!1}),i.length>0&&n.some(s=>s.operation==="write")&&r.push({name:"connected_app_write",description:`Perform an explicitly approved ${ac(e)} write through a server-owned connected app connector.`,capabilityIds:i,write:!0}),r}function sN(e){return e==="search"?"connected_app_search":e==="read"?"connected_app_read":"connected_app_write"}function lN(e){const t=hv[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 j0(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 cN(e){return e.flatMap(t=>{const n=vm(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 dN(e,t){return e.statusSource==="integration_connection"?t?"connected":"disconnected":"setup_available"}function uN(e,t,n){if(t==="connected"){const a=n.filter(i=>i.status==="active").length;return a>1?`${a} connected`:"Connected"}return t==="disconnected"?"Not connected":e.statusSource==="native_binding"?"Bot setup":"Configure"}function mN(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 pN=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),fN=v(["search","read","write"]),hN=v(V$);l({provider:pN,operation:fN,toolName:hN,sessionId:o().trim().min(1).max(200),turnId:o().trim().min(1).max(200),toolCallId:o().trim().min(1).max(300),userPrompt:o().max(2e5),connectionIds:p(o().trim().min(1).max(300)).min(1).max(8),capabilityIds:p(o().trim().min(1).max(200)).min(1).max(64),args:ae(o(),ie()).default({})}).strict().superRefine((e,t)=>{const n=W$(e);n.ok||t.addIssue({code:Yn.custom,message:n.error})});l({ok:w(),output:o().nullable().optional(),data:ie().optional()}).strict();const gN="local_path:";function c1(e){return`${gN}${e.trim()}`}l({appId:o(),source:v(["openpond","github","local_git","local_folder","unknown"]),workspacePath:o(),repoPath:o(),initialized:w(),remoteUrl:o().nullable(),expectedRemoteUrl:o().nullable(),currentBranch:o().nullable(),headCommit:o().nullable().optional().default(null),upstreamBranch:o().nullable().optional().default(null),ahead:d().int().nonnegative().optional().default(0),behind:d().int().nonnegative().optional().default(0),diverged:w().optional().default(!1),linkedSourceHeadCommit:o().nullable().optional().default(null),aheadOfLinkedSource:d().int().nonnegative().optional().default(0),behindLinkedSource:d().int().nonnegative().optional().default(0),divergedFromLinkedSource:w().optional().default(!1),linkedSourceComparisonError:o().nullable().optional().default(null),lastFetchAt:o().nullable().optional().default(null),defaultBranch:o().nullable(),branches:p(o()),dirty:w(),changedFilesCount:d(),untrackedFilesCount:d(),error:o().nullable(),updatedAt:o()});const vN=l({path:o(),status:o(),additions:d(),deletions:d(),patch:o(),content:o().nullable().optional().default(null)}),bN=l({appId:o(),repoPath:o(),initialized:w(),dirty:w(),filesChanged:d(),additions:d(),deletions:d(),repoFiles:p(o()).optional().default([]),files:p(vN),error:o().nullable(),updatedAt:o()});l({branch:o().trim().min(1).max(160)});l({path:o().trim().min(1),content:o()});const O0=l({line:d().int().nonnegative(),character:d().int().nonnegative()}),yN=l({start:O0,end:O0}),SN=l({path:o(),range:yN,severity:v(["error","warning","info","hint"]),message:o(),source:o().nullable().optional().default(null),code:o().nullable().optional().default(null)}),d1=l({id:o(),root:o(),status:v(["connected","unavailable","error"]),message:o().nullable().optional().default(null)});l({path:o().trim().min(1),content:o().optional(),waitForDiagnostics:w().optional().default(!0)});l({appId:o(),path:o(),diagnostics:p(SN),servers:p(d1),updatedAt:o()});const xN=l({operation:v(["hover","definition","references","documentSymbol"]),path:o().trim().min(1),content:o().optional(),line:d().int().nonnegative().optional(),character:d().int().nonnegative().optional()});l({appId:o(),operation:xN.shape.operation,path:o(),results:ie(),servers:p(d1),updatedAt:o()});const kN=l({pinned:w().optional(),archived:w().optional(),order:d().optional()}),IN=ae(o(),kN),u1=v(["local","sandbox"]),wN=v(["pinned","saved_for_later"]),m1=l({id:o().min(1),workspaceKind:u1,workspaceId:o().min(1),workspaceName:o().min(1),path:o().min(1),status:wN,order:d().int().nonnegative().nullable().default(null),sourceSessionId:o().min(1).nullable().default(null),available:w().default(!0),createdAt:o().min(1),updatedAt:o().min(1)});l({items:p(m1)});l({workspaceKind:u1,workspaceId:o().trim().min(1),workspaceName:o().trim().min(1),path:o().trim().min(1),status:v(["pinned","saved_for_later","none"]),order:d().int().nonnegative().nullable().optional(),sourceSessionId:o().trim().min(1).nullable().optional()});v(["pin","save_for_later","remove","list"]);function _N(e){let t=e.trim().replaceAll("\\","/");if(t=t.replace(/^(?:workspace|sandbox):file:/,""),t=t.replace(/^\/workspace\/app\//,""),t=t.replace(/^\.\//,""),!t||t.startsWith("/"))throw new Error("File path must be relative to the workspace.");const n=t.split("/").filter(a=>a&&a!==".");if(n.some(a=>a===".."))throw new Error("File path cannot leave the workspace.");if(n.length===0)throw new Error("File path is required.");return n.join("/")}function Hne(e){return["sidebar-file",e.workspaceKind,encodeURIComponent(e.workspaceId),encodeURIComponent(_N(e.path))].join(":")}const CN=l({id:o(),name:o(),type:o(),status:o(),isActive:w().nullable(),price:o().nullable(),currency:o().nullable(),credits:o().nullable()}).passthrough(),RN=l({reachable:w(),authenticated:w().nullable(),apiBase:o(),latencyMs:d(),status:d().nullable(),service:o().nullable(),checkedAt:o(),error:o().nullable()}),PN=l({id:o().nullable(),email:o().nullable(),name:o().nullable(),handle:o().nullable(),image:o().nullable(),timezone:o().nullable(),isAdmin:w().nullable(),isVerified:w().nullable(),dailyAgentAppId:o().nullable(),dailyAgentDeploymentId:o().nullable(),credits:o().nullable()}),AN=l({handle:o(),baseUrl:o().nullable().optional()}),TN=l({state:v(["signed_out","signed_in","loading","switching","auth_error"]),activeProfile:AN.nullable(),label:o(),email:o().nullable(),avatarUrl:o().nullable(),environment:o().nullable(),baseUrl:o().nullable(),apiBaseUrl:o().nullable(),chatApiBaseUrl:o().nullable().optional().default(null),creditsLabel:o().nullable(),profile:PN.nullable(),products:p(CN),apiHealth:RN.nullable(),accounts:p(l({handle:o(),baseUrl:o().nullable(),apiBaseUrl:o().nullable().optional().default(null),chatApiBaseUrl:o().nullable().optional(),environment:o().nullable(),isActive:w(),authHealth:v(["signed_out","signed_in","auth_error","unknown"]),displayLabel:o().nullable(),email:o().nullable().optional().default(null),avatarUrl:o().nullable(),apiKeyHint:o().nullable().optional(),apiKeyAccess:l({ownerType:v(["user","team","organization","service"]).nullable(),teamId:o().nullable(),scopes:p(o())}).nullable().optional().default(null)})),error:o().nullable()}),$0=l({asOf:o().nullable(),refreshing:w(),lastRefreshError:o().nullable(),source:v(["fresh","cache","empty"])}),EN=l({available:w(),binaryPath:o().nullable(),version:o().nullable(),authHealth:v(["unknown","signed_in","signed_out","auth_error"]),account:l({type:o(),email:o().nullable(),planType:o().nullable(),label:o().nullable()}).nullable().default(null),appServer:l({status:v(["idle","starting","ready","error"]),lastError:o().nullable()})}),bv="gpt-5.6-sol",zs="openpond-chat",_r="openpond",bc=zs,yv="default",Sv="high",bm="ask",ol=jr,xv=v(["default","auto-review","full-access"]),Kc=v(["ask","full-access","disabled"]),ym=v(["off","low","medium","high","xhigh","max"]),Wc=v(["sandbox_app","local_project","sandbox","sandbox_template"]);v(["openpond"]);const MN=v(["provider_usage","provider_tokenizer","model_family","heuristic"]),jN=l({provider:ol,model:o().min(1),usedTokens:d().int().nonnegative(),maxContextTokens:d().int().positive(),usableContextTokens:d().int().positive(),percentFull:d().min(0).max(100),source:MN,updatedAtEventId:o().nullable()}),Yh=l({pinned:w().default(!1),projects:w().default(!1),cloudProjects:w().default(!1),chats:w().default(!1),savedForLater:w().default(!0)}),ON=v(["auto","off"]),$N=v(["typescript","python","rust"]),p1=v(["auto","disabled","custom"]),Wi=l({mode:p1.default("auto"),customCommand:o().trim().max(4096).default("")}),Ou=l({languageServers:ON.default("auto"),diagnosticsWhileEditing:w().default(!0),checkOnSave:w().default(!0),languages:l({typescript:Wi.optional().default(()=>Wi.parse({})),python:Wi.optional().default(()=>Wi.parse({})),rust:Wi.optional().default(()=>Wi.parse({}))}).optional().default(()=>({typescript:Wi.parse({}),python:Wi.parse({}),rust:Wi.parse({})}))}),NN=l({language:$N,label:o(),mode:p1,status:v(["found","missing","disabled","error"]),command:o().nullable(),message:o().nullable()});l({settings:Ou,languages:p(NN),updatedAt:o()});const DN=l({id:o(),root:o(),status:v(["starting","connected","unavailable","error"]),message:o().nullable().optional().default(null),openedDocuments:d().int().nonnegative(),pendingRequests:d().int().nonnegative(),lastUsedAt:o(),stderrTail:o()});l({clients:p(DN),maxClients:d().int().positive(),idleTimeoutMs:d().int().positive(),updatedAt:o()});const Qh=l({autoEnabled:w().default(!0),triggerPercent:d().int().min(50).max(95).default(85),summaryModel:v(["same_model"]).default("same_model")}),Xh=l({defaultModelRef:bn.nullable().default(null),creationMode:v(["defaults","customize"]).default("customize"),autoApproveEvidence:w().default(!1)}),N0=l({defaultChatProvider:ol.default(_r),defaultChatModel:o().min(1).default(bc),defaultChatModelRef:bn.nullable().optional(),subagents:gc.optional().default(()=>gc.parse({})),codexPermissionMode:xv.default(yv),codexReasoningEffort:ym.default(Sv),openPondCommandAccessMode:Kc.default(bm),defaultBranchPrefix:o().trim().max(48).default("feat/"),defaultNewProjectDirectory:o().trim().max(4096).default(""),defaultTeamId:o().trim().max(191).nullable().default(null),advancedWorkspaceControls:w().default(!1),steerActiveResponses:w().default(!0),contextCompaction:Qh.optional().default(()=>Qh.parse({})),training:Xh.optional().default(()=>Xh.parse({})),sidebarWidth:d().int().min(244).max(560).default(332),diffPanelWidth:d().int().min(320).max(2400).default(560),sidebarSectionsCollapsed:Yh.optional().default(()=>Yh.parse({})),editor:Ou.optional().default(()=>Ou.parse({}))}),HN="default",f1=[{id:"default",name:"Balanced",source:"built_in",description:"Clear, useful, and concise.",content:`You are OpenPond Chat, a clear and useful AI assistant.
105
+ Be concise, accurate, and direct.
106
+ Do not use emojis.
107
+ Ask only when missing information would materially change the answer.
108
+ Prioritize practical next steps.`},{id:"pragmatic",name:"Pragmatic",source:"built_in",description:"Direct, practical, and engineering-minded.",content:`You are a pragmatic AI assistant with strong engineering judgment.
109
+ Be direct, concrete, and outcome-focused.
110
+ Do not use emojis.
111
+ Prefer simple working solutions over clever abstractions.
112
+ Call out weak assumptions plainly.`},{id:"friendly",name:"Friendly",source:"built_in",description:"Warm, conversational, and approachable.",content:`You are a friendly AI assistant.
113
+ Use a warm, conversational tone without filler.
114
+ Do not use emojis.
115
+ Explain decisions clearly and keep the user moving.
116
+ Be patient when clarifying tradeoffs.`},{id:"formal",name:"Formal",source:"built_in",description:"Polished, careful, and professional.",content:`You are a formal AI assistant.
117
+ Use precise, professional language.
118
+ Do not use emojis.
119
+ Structure answers clearly and avoid casual phrasing.
120
+ State uncertainty and assumptions explicitly.`},{id:"technical",name:"Technical",source:"built_in",description:"Precise, detailed, and implementation-focused.",content:`You are a technical AI assistant.
121
+ Prioritize correctness, implementation detail, and edge cases.
122
+ Do not use emojis.
123
+ Use concise explanations, but include necessary specifics.
124
+ Surface risks, constraints, and verification steps.`}],kv=o().trim().min(1).max(120),LN=l({id:kv,name:o(),source:v(["built_in","custom"]).default("custom"),description:o(),content:o()}),D0=l({activeTemplateId:kv.default(HN),customized:w().default(!1),soul:o(),soulPath:o().nullable(),updatedAt:o().nullable(),templates:p(LN).default(()=>[...f1])}),qN=l({id:o(),host:o(),port:d(),startedAt:o(),storePath:o(),version:o(),runtimeVersion:o()}),Iv=v(["chat","work","development"]);v(["chat","models","console","development"]);const UN="work",Ge=o().trim().min(1).nullable(),Va=ae(o(),ie()).default({}),zN=v(["direct_prompt_create","context_backed_create","create_as_agent","workflow_suggestion","local_extend","hosted_create","local_import","direct_prompt_improve","context_backed_improve","hosted_improve","lab_create","lab_improve","training"]),h1=v(["/create","/edit","openpond extend","create_as_agent","suggest_workflow","local_import","lab_create","lab_improve","training"]),BN=v(["create","improve","import","promote"]),FN=v(["planning","awaiting_questions","awaiting_plan_approval","paused","applying_source","running_checks","evaluating","awaiting_promotion","opening_pull_request","pull_request_open","reconciling_release","released","rejected","ready","ready_local","pushing_hosted","running_hosted_checks","published_hosted","blocked","failed","cancelled"]),zd=v(["always_require_plan_approval","approval_already_granted"]);v(["local_profile","hosted_profile","promote_local_to_hosted","managed_artifact"]);const VN=lt("kind",[l({kind:b("local"),sourceAuthority:b("local_profile"),activeProfile:o().trim().min(1).nullable(),repoPath:Ge,sourcePath:Ge,localHead:Ge,confirmationPolicy:zd.default("always_require_plan_approval")}),l({kind:b("hosted"),sourceAuthority:b("hosted_profile"),teamId:Ge,projectId:Ge,activeProfile:o().trim().min(1).nullable(),sourceRef:Ge,baseSha:Ge,confirmationPolicy:zd.default("always_require_plan_approval")}),l({kind:b("promote_local_to_hosted"),sourceAuthority:b("promote_local_to_hosted"),teamId:Ge,projectId:Ge,activeProfile:o().trim().min(1).nullable(),repoPath:Ge,sourcePath:Ge,localHead:Ge,hostedHead:Ge,sourceRef:Ge,confirmationPolicy:zd.default("always_require_plan_approval")}),l({kind:b("managed_artifact"),sourceAuthority:b("managed_artifact"),activeProfile:o().trim().min(1).nullable(),confirmationPolicy:zd.default("always_require_plan_approval")})]),KN=l({id:Ge,kind:v(["user","system","automation"]).default("user"),label:Ge}),WN=l({profileId:o().trim().min(1),conversationId:Ge,originTurnId:Ge,projectId:Ge,targetProject:l({id:Ge,name:Ge,workspacePath:Ge,sourceRef:Ge,baseSha:Ge}).nullable()}),Jl=l({messageIds:p(o().trim().min(1)).default([]),conversationExcerpts:p(l({messageId:Ge,role:o().trim().min(1).nullable(),excerpt:o().trim().min(1),reason:o().trim().min(1).nullable()})).default([]),attachments:p(l({id:Ge,name:o().trim().min(1),mediaType:Ge,ref:Ge})).default([]),apps:p(l({id:o().trim().min(1),name:o().trim().min(1),connectionId:Ge,required:w().default(!1)})).default([]),tools:p(l({name:o().trim().min(1),inputSummary:Ge,outputSummary:Ge,artifactRefs:p(o().trim().min(1)).default([]),sideEffects:p(o().trim().min(1)).default([])})).default([]),signalRefs:p(o().trim().min(1)).default([]),evalRefs:p(o().trim().min(1)).default([]),targetRepoAssumptions:p(o().trim().min(1)).default([])}),us={id:Ge,displayName:Ge},wv=lt("kind",[l({kind:b("unselected"),...us}),l({kind:b("agent"),...us,defaultActionKey:Ge}),l({kind:b("skill"),...us,skillName:Ge}),l({kind:b("extension"),...us,slot:Ge}),l({kind:b("model"),...us,trainingPlanId:Ge,trainingJobId:Ge,artifactId:Ge}),l({kind:b("configuration"),...us,key:Ge})]),eg=v(["agent","skill","extension","model","configuration"]),GN=l({schemaVersion:b("openpond.createImprove.evidenceSnapshot.v1"),id:o().trim().min(1),contentHash:o().trim().min(8),consent:l({status:v(["granted","denied","revoked"]),scope:v(["metadata_only","selected_turns","full_session","direct_intent"]),reviewedBy:Ge,reviewedAt:o().trim().min(1)}),sources:p(l({kind:v(["signal","conversation","direct_correction","manual_intent","artifact"]),id:o().trim().min(1),sourceHash:o().trim().min(8),excerptRef:Ge})).min(1),reviewerIntent:o().trim().min(1),createdAt:o().trim().min(1),metadata:Va}),g1=l({schemaVersion:b("openpond.createImprove.tasksetRef.v1"),id:o().trim().min(1),revision:d().int().positive(),contentHash:o().trim().min(8),evidenceSnapshotIds:p(o().trim().min(1)).min(1),policyBoundary:l({policyVisibleFields:p(o().trim().min(1)).default([]),privilegedFields:p(o().trim().min(1)).default([]),hiddenGraderRefs:p(o().trim().min(1)).default([]),connectedAppScopes:p(o().trim().min(1)).default([])}),targetRecommendation:l({kind:eg,rationale:p(o().trim().min(1)).min(1),confidence:d().min(0).max(1)}),authoringSplitRefs:p(o().trim().min(1)).default([]),privateSplitRefs:p(o().trim().min(1)).default([]),approvedBy:Ge,approvedAt:o().trim().min(1),metadata:Va}),JN=l({kind:v(["npm_package","runtime_tool","setup_command","secret","integration","volume","target_project","external_service"]),name:o().trim().min(1),status:v(["declared","required","blocked","satisfied"]).default("declared"),detail:Ge,metadata:Va}),ZN=l({mode:v(["chat","direct_action","chat_and_direct_actions"]),label:o().trim().min(1),detail:o().trim().min(1),defaultActionKey:Ge,directActionHint:Ge,artifactPolicy:o().trim().min(1)}),YN=l({schemaVersion:b("openpond.createImprove.plan.v1"),id:o().trim().min(1),runId:o().trim().min(1),status:v(["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:l({key:Ge,label:Ge,required:w().default(!0)}),sourcePlan:p(l({path:o().trim().min(1),operation:v(["create","update","delete","inspect"]),reason:o().trim().min(1)})).default([]),requirements:p(JN).default([]),checks:p(l({name:o().trim().min(1),command:o().trim().min(1),required:w().default(!0)})).default([]),approvalId:Ge,approvedAt:Ge,editedFromPlanId:Ge,metadata:Va,createdAt:o().trim().min(1),updatedAt:o().trim().min(1)}),QN=l({id:o().trim().min(1),label:o().trim().min(1),value:o().trim().min(1),description:Ge,metadata:Va}),XN=l({value:o().trim().min(1),label:Ge,detail:Ge,answeredAt:o().trim().min(1),metadata:Va}),eD=l({id:o().trim().min(1),kind:v(["single_choice","free_text"]).default("single_choice"),title:o().trim().min(1),prompt:o().trim().min(1),required:w().default(!0),status:v(["pending","answered","skipped"]).default("pending"),options:p(QN).default([]),answer:XN.nullable().default(null),metadata:Va}),tD=l({schemaVersion:b("openpond.createImprove.workflowCapture.v1"),id:o().trim().min(1),runId:o().trim().min(1),command:h1,objective:o().trim().min(1),conversationExcerpts:Jl.shape.conversationExcerpts,attachments:Jl.shape.attachments,apps:Jl.shape.apps,tools:Jl.shape.tools,sideEffects:p(o().trim().min(1)).default([]),profileActions:p(o().trim().min(1)).default([]),externalProviders:p(o().trim().min(1)).default([]),environmentVariables:p(o().trim().min(1)).default([]),files:p(o().trim().min(1)).default([]),schedules:p(o().trim().min(1)).default([]),webhooks:p(o().trim().min(1)).default([]),channelTargets:p(o().trim().min(1)).default([]),outputArtifacts:p(o().trim().min(1)).default([]),targetRepoAssumptions:p(o().trim().min(1)).default([]),traceRefs:p(o().trim().min(1)).default([]),metadata:Va,createdAt:o().trim().min(1)}),v1=l({provider:b("github"),number:d().int().positive(),url:o().url(),state:v(["open","merged","closed"]),baseBranch:o().trim().min(1),headBranch:o().trim().min(1),mergeCommit:Ge,openedAt:o().trim().min(1),updatedAt:o().trim().min(1)}),nD=l({baseBranch:o().trim().min(1),baseCommit:o().trim().min(1),branch:o().trim().min(1),headCommit:Ge,remoteName:o().trim().min(1).default("origin"),remoteUrl:Ge,worktreePath:Ge,changedPaths:p(o().trim().min(1)).default([]),diffStat:Ge,pullRequest:v1.nullable().default(null)}),aD=l({id:o().trim().min(1),target:wv,status:v(["draft","authored","checking","evaluated","accepted","rejected","failed"]),git:nD.nullable().default(null),parentCandidateId:Ge.default(null),tasksetRef:g1.nullable().default(null),authoringModelRef:Ge.default(null),allowedPaths:p(o().trim().min(1)).default([]),sourceRefs:p(o().trim().min(1)).default([]),artifactRefs:p(o().trim().min(1)).default([]),checkRefs:p(o().trim().min(1)).default([]),evaluationReceiptRefs:p(o().trim().min(1)).default([]),createdAt:o().trim().min(1),updatedAt:o().trim().min(1),metadata:Va}),iD=l({id:o().trim().min(1),candidateId:Ge,target:wv,evaluatorKind:v(["agent_sdk","taskset","extension","skill","configuration","checks"]).default("checks"),subject:v(["active","candidate","post_release","standalone"]).default("standalone"),sourceCommit:Ge.default(null),sourceBranch:Ge.default(null),tasksetId:Ge.default(null),tasksetHash:Ge.default(null),taskAttemptRefs:p(o().trim().min(1)).default([]),status:v(["pending","passed","failed","blocked"]),publishGate:v(["passed","failed","not_applicable"]).default("not_applicable"),summaryCounts:l({total:d().int().nonnegative(),passed:d().int().nonnegative(),failed:d().int().nonnegative()}).nullable().default(null),evalRefs:p(o().trim().min(1)).default([]),artifactRefs:p(o().trim().min(1)).default([]),summary:Ge,createdAt:o().trim().min(1),metadata:Va}),oD=l({mode:v(["foreground","background"]).default("background"),pauseAllowed:w().default(!0),cancellationAllowed:w().default(!0)}),rD=l({mode:v(["single","bounded","until_evals_pass"]).default("single"),maximumAttempts:d().int().min(1).max(20).default(1),currentAttempt:d().int().min(0).max(20).default(0)}),sD=l({kind:v(["candidate_authoring","local_apply","hosted_turn","training_job","evaluation","pull_request","release"]),id:o().trim().min(1),status:Ge,metadata:Va}),lD=l({status:v(["not_requested","pending","released","rejected","rolled_back"]),profileCommit:Ge,profileTag:Ge,releaseReceiptRef:Ge,pullRequest:v1.nullable().default(null),updatedAt:Ge}),Gc=l({schemaVersion:b("openpond.createImprove.run.v1"),id:o().trim().min(1),revision:d().int().nonnegative(),operation:BN,surface:zN,command:h1,objective:o().trim().min(1),state:FN,adapter:VN,actor:KN,scope:WN,context:Jl,target:wv,evidenceSnapshots:p(GN).default([]),tasksetRef:g1.nullable().default(null),targetSelection:l({status:v(["open","recommended","confirmed"]),preselectedKind:eg.nullable(),confirmedKind:eg.nullable()}).nullable().default(null),plan:YN.nullable(),workflowCapture:tD.nullable(),executionPolicy:oD.default({mode:"background",pauseAllowed:!0,cancellationAllowed:!0}),iterationPolicy:rD.default({mode:"single",maximumAttempts:1,currentAttempt:0}),approvalIds:p(o().trim().min(1)).default([]),questionIds:p(o().trim().min(1)).default([]),questions:p(eD).default([]),candidates:p(aD).default([]),evaluationReceipts:p(iD).default([]),checkRefs:p(o().trim().min(1)).default([]),sourceRefs:p(o().trim().min(1)).default([]),externalExecutionRefs:p(sD).default([]),localProfileCommit:Ge,hostedSourceCommit:Ge,hostedSourceRef:Ge,releaseOutcome:lD.default({status:"not_requested",profileCommit:null,profileTag:null,releaseReceiptRef:null,pullRequest:null,updatedAt:null}),blockedReason:Ge,appliedActionIds:p(o().trim().min(1)).max(200).default([]),metadata:Va,createdAt:o().trim().min(1),updatedAt:o().trim().min(1)}),yi={runId:o().trim().min(1),expectedRevision:d().int().nonnegative(),actionId:o().trim().min(1)};lt("type",[l({...yi,type:b("answer_question"),questionId:o().trim().min(1),value:o().trim().min(1)}),l({...yi,type:b("approve_plan")}),l({...yi,type:b("revise_plan"),revision:o().trim().min(1)}),l({...yi,type:b("cancel"),reason:Ge.optional().default(null)}),l({...yi,type:b("pause")}),l({...yi,type:b("resume")}),l({...yi,type:b("open_pull_request"),candidateId:o().trim().min(1)}),l({...yi,type:b("apply_candidate"),candidateId:o().trim().min(1)}),l({...yi,type:b("reject_candidate"),candidateId:o().trim().min(1),reason:Ge.optional().default(null)}),l({...yi,type:b("reconcile_pull_request"),candidateId:o().trim().min(1)})]);l({schemaVersion:b("openpond.createImprove.runList.v1"),runs:p(Gc),generatedAt:o().trim().min(1)});function Lne(e){const t=ZN.safeParse(e?.actionShape);return t.success?t.data:null}const Ni=l({source:v(["local","github","openpond_git"]),repositoryId:o().trim().min(1),profileId:o().trim().min(1)}),cD=l({ref:Ni,revision:o().nullable(),sourceHash:o()}),rl=ae(o(),ie()).default({}),Na=d().int().nonnegative(),Sm=o().trim().min(1).max(1e5),b1=l({kind:v(["personal","team"]),id:T}).strict(),dD=l({name:T,release:V.nullable(),revision:Na}).strict();l({schemaVersion:b("openpond.harnessWorkspace.v1"),id:T,ownerScope:b1,name:o().trim().min(1).max(240),location:v(["local","hosted"]),sourceRevision:o().trim().min(1).max(500),revision:Na,dirty:w(),currentChannel:dD,createdAt:he,updatedAt:he,metadata:rl}).strict();const Bs=v(["runtime","memory","prompt","skill","agent","product","taskset","training"]),y1=v(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),S1=l({id:T,route:Bs,operation:v(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),content:o().max(1e6).nullable(),contentHash:D.nullable(),effects:p(y1).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=st(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),x1=l({workspaceId:T,revision:Na,sourceRevision:o().trim().min(1).max(500),channelRevision:Na}).strict(),ao=l({id:T,revision:Na,contentHash:D}).strict(),uD=l({schemaVersion:b("openpond.harnessTurnSnapshot.v1"),workspaceId:T,workspaceRevision:Na,sourceRevision:o().trim().min(1).max(500),channelName:T,channelRevision:Na,harnessRelease:V,toolCatalogHash:D.nullable().optional(),overlay:ao.nullable().optional().default(null)}).strict(),mD=l({schemaVersion:b("openpond.harnessRunOverlay.v1"),id:T,runId:T,baseHarnessRelease:V,workspace:x1,revision:Na,status:v(["active","frozen","abandoned"]),edits:p(S1).max(1e3),createdAt:he,updatedAt:he,metadata:rl}).strict();mD.extend({contentHash:D}).strict();const k1=l({kind:v(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:T,contentHash:D.nullable()}).strict(),I1=l({id:T,kind:v(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:Sm,required:w()}).strict(),pD=l({schemaVersion:b("openpond.harnessImprovementProposal.v1"),id:T,overlay:ao,baseHarnessRelease:V,expectedWorkspace:x1,requestedScope:v(["personal","team","global"]),route:Bs,risk:v(["low","review","restricted"]),effects:p(y1).min(1).max(20),evidence:p(k1).min(1).max(1e3),edits:p(S1).min(1).max(1e3),validationPlan:p(I1).min(1).max(100),expectedOutcome:Sm,createdAt:he,metadata:rl}).strict().superRefine((e,t)=>{const n=new Set(e.effects);for(const[a,i]of e.edits.entries()){i.route!==e.route&&t.addIssue({code:"custom",message:"every edit route must match the proposal route",path:["edits",a,"route"]});for(const r of i.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"]})});pD.extend({contentHash:D}).strict();const fD=l({schemaVersion:b("openpond.harnessTargetedValidationReceipt.v1"),id:T,proposal:V,validationId:T,kind:I1.shape.kind,status:v(["passed","failed","blocked","skipped"]),summary:Sm,evidenceRefs:p(k1).max(1e3),createdAt:he,metadata:rl}).strict();fD.extend({contentHash:D}).strict();const hD=v(["advanced","retained","conflict","rolled_back"]),gD=l({schemaVersion:b("openpond.harnessAdvanceReceipt.v1"),id:T,workspaceId:T,ownerScope:b1,proposal:V.nullable(),expectedWorkspaceRevision:Na,observedWorkspaceRevision:Na,previousChannelRevision:Na,nextChannelRevision:Na,previousRelease:V.nullable(),nextRelease:V.nullable(),validationReceipts:p(V).max(100),decision:hD,reason:Sm,rollbackOf:V.nullable(),createdAt:he,metadata:rl}).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"]})});gD.extend({contentHash:D}).strict();const vD=l({schemaVersion:b("openpond.harnessOverlayMergeReceipt.v1"),id:T,workspaceId:T,baseHarnessRelease:V,leftOverlay:ao,rightOverlay:ao,decision:v(["merged","conflict"]),mergedOverlay:ao.nullable(),conflictTargets:p(o().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:b(!0),createdAt:he,metadata:rl}).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"]})});vD.extend({contentHash:D}).strict();const io=o().trim().min(1).max(1e5),bD=v(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),yD=v(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),w1=v(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),_v=l({kind:v(["personal","team"]),id:T}).strict(),_1=l({policy:V,state:v(["authorized","revoked","deleted","expired"]),checkedAt:he}).strict(),yc=l({evidence:V,kind:w1,sourceRef:T,sourcePolicy:_1,occurrenceKey:D,occurredAt:he}).strict(),SD=l({evidence:V,sourcePolicy:_1.nullable(),reason:v(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),H0=l({cursor:D,throughCreatedAt:he}).strict(),xD=l({fingerprint:D,recurrenceFamily:o().trim().min(1).max(1e3),statement:io,candidateDisposition:v(["observe","confirm"]).optional(),independentOccurrences:d().int().positive().max(1e6),unresolvedOccurrences:d().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),C1=v(["harness","runtime","product","retrieval","tools","evaluation","model"]),kD=l({layer:C1,status:v(["not_applicable","unresolved","resolved","blocked"]),reason:io,evidenceRefs:p(V).max(1e3)}).strict(),ID=l({schemaVersion:b("openpond.harnessEvaluationReviewReceipt.v1"),id:T,ownerScope:_v,workspaceRef:T,harnessRelease:V,previousWatermark:H0.nullable(),nextWatermark:H0,selectedEvidence:p(yc).max(1e4),excludedEvidence:p(SD).max(1e4),claim:xD.nullable(),classification:bD,triage:p(kD).max(16),reason:io,nextAuthority:yD,maxEstimatedCostUsd:d().finite().nonnegative(),tasksetProposal:V.nullable(),evaluation:V.nullable(),trainingQualification:V.nullable(),policyVersion:T,createdAt:he,metadata:Mn}).strict().superRefine((e,t)=>{const n=e.selectedEvidence.map(a=>`${a.evidence.id}:${a.evidence.contentHash}`);new Set(n).size!==n.length&&t.addIssue({code:"custom",message:"selected review evidence must be unique",path:["selectedEvidence"]}),e.selectedEvidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"selected review evidence must be authorized at review time",path:["selectedEvidence"]}),e.classification==="no_action"?(e.nextAuthority!=="none"&&t.addIssue({code:"custom",message:"no-action review receipts require no next authority",path:["nextAuthority"]}),(e.tasksetProposal||e.evaluation||e.trainingQualification)&&t.addIssue({code:"custom",message:"no-action review receipts cannot carry downstream refs"})):(!e.claim||e.selectedEvidence.length===0)&&t.addIssue({code:"custom",message:"actionable review receipts require a claim and selected evidence"}),e.classification==="runtime"&&e.nextAuthority!=="runtime_service"&&t.addIssue({code:"custom",message:"runtime classifications route to runtime-service authority",path:["nextAuthority"]}),e.classification==="product"&&e.nextAuthority!=="product_team"&&t.addIssue({code:"custom",message:"product classifications route to product-team authority",path:["nextAuthority"]}),e.classification==="taskset"&&e.nextAuthority!=="human_review"&&t.addIssue({code:"custom",message:"Taskset classifications require human review"}),e.classification==="model_improvement"&&(!e.evaluation||!e.trainingQualification||!["human_review","training_system"].includes(e.nextAuthority))&&t.addIssue({code:"custom",message:"model-improvement classifications require Evaluation and qualification refs plus explicit authority"})});ID.extend({contentHash:D}).strict();l({id:T,evidence:V,kind:w1,sourceRef:T,occurredAt:he,payload:ae(o(),ie())}).strict();const wD=l({schemaVersion:b("openpond.harnessEvaluationReviewModelDecision.v2"),decision:b("no_action"),reason:io,ignoredEvidence:p(l({id:T,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),_D=l({schemaVersion:b("openpond.harnessEvaluationReviewModelDecision.v2"),decision:b("review"),classification:v(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:p(T).min(1).max(1e3),ignoredEvidence:p(l({id:T,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:o().trim().min(1).max(1e3),statement:io,triageLayer:C1,expectedOutcome:io,counterevidence:o().trim().max(1e4),confidence:d().min(0).max(1),candidateDisposition:v(["observe","confirm"]).nullable(),reason:io}).strict().superRefine((e,t)=>{e.classification==="harness_maintenance"!==(e.candidateDisposition!==null)&&t.addIssue({code:"custom",message:"Harness maintenance requires a candidate disposition; external routes require null",path:["candidateDisposition"]})}),CD=l({schemaVersion:b("openpond.harnessEvaluationReviewModelDecision.v2"),decision:b("resolve_candidate"),candidateId:T,candidateFingerprint:D,selectedEvidenceIds:p(T).min(1).max(1e3),ignoredEvidence:p(l({id:T,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:d().min(0).max(1),reason:io}).strict();lt("decision",[wD,_D,CD]);l({schemaVersion:b("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:p(T).min(1).max(50),reason:io}).strict();const Jc=l({name:o().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:o().trim().min(1).max(2e3),inputSchema:ae(o(),ie()),inputSchemaHash:D,sideEffect:v(["read","write"]),timeoutMs:d().int().positive().max(36e5)}).strict(),Cv=l({id:T,required:w(),scopes:p(o().trim().min(1).max(500)).max(100).default([]),portability:v(["portable","host_adapter","local_only","hosted_only"])}).strict(),RD=l({portable:w(),blockers:p(o().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:p(T).max(1e4),hostPrivateAssetRefs:p(T).max(1e4)}).strict(),PD=l({schemaVersion:b("openpond.agentSnapshot.v2"),id:T,sourceRelease:V.nullable(),instructions:p(gn).max(1e4),skills:p(gn).max(1e4),agents:p(gn).max(1e4),toolDeclarations:p(Jc).max(200),capabilityRequirements:p(Cv).max(200),dependencyLock:gn,portability:RD,metadata:Mn}).strict(),AD=PD.extend({contentHash:D}).strict(),R1=l({create:b(!0),reset:b(!0),step:b(!0),collect:b(!0),destroy:b(!0),resetScope:v(["task","attempt"])}).strict(),P1=l({visibleEvidence:p(T).max(1e3),privilegedEvidence:p(T).max(1e3),privateVerifierIsolation:w()}).strict(),TD=l({schemaVersion:b("openpond.harnessRelease.v2"),id:T,agentSnapshot:V,program:gn,tools:p(Jc).max(200),lifecycle:R1,graderInterface:P1,files:p(gn).max(1e5),metadata:Mn}).strict(),ED=TD.extend({contentHash:D}).strict(),MD=l({id:T,turn:d().int().nonnegative(),kind:v(["message","tool_call","terminal"]),name:T.nullable(),arguments:ae(o(),ie()),content:o().max(1e6).nullable()}).strict(),jD=l({actionId:T,turn:d().int().nonnegative(),terminal:w(),output:ae(o(),ie()),artifactRefs:p(Ia).max(1e5)}).strict(),OD=l({sequence:d().int().nonnegative(),type:v(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:D,metadata:Mn}).strict();l({schemaVersion:b("openpond.harnessTrace.v1"),manifest:V,taskId:T,seed:o().trim().min(1).max(500),events:p(OD).max(1e6),actions:p(MD).max(1e5),observations:p(jD).max(1e5),terminal:w(),failureClass:Bc.nullable(),output:ae(o(),ie()),contentHash:D}).strict();const xm=o().trim().min(1).max(1e5),Zc=ae(o(),ie()).default({}),$D=v(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),A1=l({kind:$D,eventSequence:d().int().nonnegative(),occurredAt:he}).strict(),T1=l({id:T,sequence:d().int().nonnegative().nullable(),contentHash:D}).strict(),ND=v(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),DD=v(["open","recovered","terminal"]),HD=l({name:o().trim().min(1).max(500),invocationKey:D}).strict(),LD=l({schemaVersion:b("openpond.improvementObservation.v1"),id:T,runRef:T,turnId:T,harnessRelease:V,overlay:ao.nullable(),eventRefs:p(T1).min(1).max(100),kind:ND,state:DD,tool:HD.nullable(),deterministicClass:o().trim().min(1).max(500).nullable(),summary:xm,createdAt:he,metadata:Zc}).strict().superRefine((e,t)=>{new Set(e.eventRefs.map(n=>n.id)).size!==e.eventRefs.length&&t.addIssue({code:"custom",message:"observation event refs must be unique",path:["eventRefs"]}),["tool_failure","retry","recovery","completion_detour"].includes(e.kind)&&e.tool===null&&t.addIssue({code:"custom",message:`${e.kind} observations require a tool identity`,path:["tool"]})});LD.extend({contentHash:D}).strict();const qD=l({schemaVersion:b("openpond.refinementTriggerPolicy.v1"),maxEstimatedCostUsd:d().finite().nonnegative(),cooldownMs:d().int().nonnegative(),maxPendingPlans:d().int().min(1).max(100),maxEvidenceEvents:d().int().min(1).max(1e3),maxProposalEdits:d().int().min(1).max(1e3),maxProposalBytes:d().int().min(1).max(1e7)}).strict(),UD=v(["no_action","route_deterministically","queue_refiner"]),zD=l({schemaVersion:b("openpond.refinementTriggerDecision.v1"),id:T,runRef:T,turnId:T,harnessRelease:V,overlay:ao.nullable(),observations:p(V).max(100),decision:UD,deterministicRoute:Bs.nullable(),suggestedRoutes:p(Bs).max(8),reason:xm,deduplicationKey:D,policy:qD,estimatedMaxCostUsd:d().finite().nonnegative(),pendingPlanCount:d().int().nonnegative(),boundary:A1,cooldownUntil:he.nullable(),createdAt:he,metadata:Zc}).strict().superRefine((e,t)=>{e.estimatedMaxCostUsd>e.policy.maxEstimatedCostUsd&&t.addIssue({code:"custom",message:"estimated Refiner cost exceeds the trigger policy budget",path:["estimatedMaxCostUsd"]}),e.pendingPlanCount>e.policy.maxPendingPlans&&t.addIssue({code:"custom",message:"pending plan count exceeds the trigger policy limit",path:["pendingPlanCount"]}),e.observations.length>e.policy.maxEvidenceEvents&&t.addIssue({code:"custom",message:"trigger observations exceed the evidence budget",path:["observations"]}),e.decision==="route_deterministically"&&e.deterministicRoute===null&&t.addIssue({code:"custom",message:"deterministic decisions require a route",path:["deterministicRoute"]}),e.decision!=="route_deterministically"&&e.deterministicRoute!==null&&t.addIssue({code:"custom",message:"only deterministic decisions may declare a deterministic route",path:["deterministicRoute"]}),e.decision==="no_action"&&e.suggestedRoutes.length>0&&t.addIssue({code:"custom",message:"no-action decisions cannot suggest routes",path:["suggestedRoutes"]}),e.decision!=="no_action"&&e.observations.length===0&&t.addIssue({code:"custom",message:"actionable trigger decisions require observations",path:["observations"]})});zD.extend({contentHash:D}).strict();const BD=v(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),FD=l({schemaVersion:b("openpond.improvementRouteDecision.v1"),id:T,trigger:V,route:Bs,authority:BD,automatic:w(),reason:xm,createdAt:he,metadata:Zc}).strict().superRefine((e,t)=>{e.automatic&&["human_review","evaluation_system","training_system"].includes(e.authority)&&t.addIssue({code:"custom",message:`${e.authority} routes cannot be marked automatic`,path:["automatic"]}),e.route==="training"&&e.automatic&&e.authority!=="training_system"&&t.addIssue({code:"custom",message:"automatic training routes require training-system authority",path:["authority"]})});FD.extend({contentHash:D}).strict();const VD=l({schemaVersion:b("openpond.harnessRefinerOutcome.v1"),id:T,trigger:V,decision:v(["no_action","proposed"]),proposal:V.nullable(),reason:xm,evidenceRefs:p(V).max(100),estimatedCostUsd:d().finite().nonnegative(),createdAt:he,metadata:Zc}).strict().superRefine((e,t)=>{e.decision==="proposed"!=(e.proposal!==null)&&t.addIssue({code:"custom",message:"proposed Refiner outcomes require a proposal; no-action outcomes cannot include one",path:["proposal"]})});VD.extend({contentHash:D}).strict();const KD=v(["applied","retained","declined","conflict","rolled_back"]),WD=l({schemaVersion:b("openpond.improvementApplyReceipt.v1"),id:T,proposal:V,beforeOverlay:ao,afterOverlay:ao.nullable(),decision:KD,boundary:A1,validationRefs:p(V).max(100),outcomeEvidenceRefs:p(T1).max(1e3),rollbackOf:V.nullable(),createdAt:he,metadata:Zc}).strict().superRefine((e,t)=>{e.decision==="applied"!=(e.afterOverlay!==null)&&t.addIssue({code:"custom",message:"applied receipts require an after-overlay; other decisions cannot include one",path:["afterOverlay"]}),e.decision==="rolled_back"!=(e.rollbackOf!==null)&&t.addIssue({code:"custom",message:"only rollback receipts require rollbackOf",path:["rollbackOf"]})});WD.extend({contentHash:D}).strict();const GD=v(["memory","prompt","skill","agent"]),JD=v(["runtime","product","taskset","training"]),ZD=l({id:o().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:o().trim().min(1).max(1e4)}).strict(),E1=l({schemaVersion:b("openpond.refinerReviewProfile.v1"),id:o().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),version:o().trim().min(1).max(120),name:o().trim().min(1).max(200),objective:o().trim().min(1).max(1e4),instructions:p(ZD).max(100),allowedProposalRoutes:p(GD).max(4),allowedExternalRoutes:p(JD).max(4)}).strict().superRefine((e,t)=>{const n=e.instructions.map(a=>a.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",message:"instruction IDs must be unique",path:["instructions"]}),new Set(e.allowedProposalRoutes).size!==e.allowedProposalRoutes.length&&t.addIssue({code:"custom",message:"proposal routes must be unique",path:["allowedProposalRoutes"]}),new Set(e.allowedExternalRoutes).size!==e.allowedExternalRoutes.length&&t.addIssue({code:"custom",message:"external routes must be unique",path:["allowedExternalRoutes"]})}),L0=l({schemaVersion:b("openpond.refinerRelease.v1"),id:o().trim().min(1).max(240),coreVersion:o().trim().min(1).max(120),coreHash:D,profile:E1,profileHash:D,composedPromptHash:D,createdAt:he,contentHash:D}).strict(),YD=l({schemaVersion:b("openpond.refinerBinding.v1"),channel:b("active"),revision:d().int().nonnegative(),release:V,updatedAt:he}).strict(),QD=l({schemaVersion:b("openpond.refinerTransitionReceipt.v1"),id:o().trim().min(1).max(240),operation:v(["initialize","update","activate","rollback"]),bindingChanged:w(),previousRelease:V.nullable(),nextRelease:V,actor:o().trim().min(1).max(240),reason:o().trim().min(1).max(1e4),authoringSkillHash:D.nullable(),validation:l({valid:w(),messages:p(o().max(2e3)).max(100)}).strict(),createdAt:he,contentHash:D}).strict(),XD=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v1"),decision:b("no_action"),reason:o().trim().min(1).max(1e4)}).strip(),eH=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v1"),decision:b("route"),route:v(["runtime","product","taskset","training"]),summary:o().trim().min(1).max(2e3),expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strip(),tH=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v1"),decision:b("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),createContent:o().min(1).max(2e4).nullable(),find:o().min(1).max(8e3).nullable(),replace:o().max(8e3).nullable(),expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strip().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),nH=lt("decision",[XD,eH,tH]),aH=nH,Rv=l({kind:v(["single_deterministic","recurrent_independent"]),supportingEvidenceIds:p(o().trim().min(1).max(2e3)).min(1).max(100),counterevidence:p(o().trim().min(1).max(2e3)).max(20)}).strict().superRefine((e,t)=>{new Set(e.supportingEvidenceIds).size!==e.supportingEvidenceIds.length&&t.addIssue({code:"custom",message:"supporting evidence IDs must be unique",path:["supportingEvidenceIds"]}),e.kind==="recurrent_independent"&&e.supportingEvidenceIds.length<2&&t.addIssue({code:"custom",message:"recurrent independent evidence requires at least two supplied incidents",path:["supportingEvidenceIds"]})}),iH=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v2"),decision:b("no_action"),reason:o().trim().min(1).max(1e4)}).strict(),oH=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v2"),decision:b("route"),route:v(["runtime","product","taskset","training"]),summary:o().trim().min(1).max(2e3),evidenceBasis:Rv,expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strict(),rH=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v2"),decision:b("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),evidenceBasis:Rv,createContent:o().min(1).max(2e4).nullable(),find:o().min(1).max(8e3).nullable(),replace:o().max(8e3).nullable(),expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strict().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),M1=lt("decision",[iH,oH,rH]);ht([aH,M1]);const Pv=l({memory:w(),prompt:w(),skill:w(),agent:w()}).strict(),j1=v(["memory","instruction","skill","agent"]),q0=l({path:o().trim().min(1).max(2e3),kind:j1,content:o().max(6e4),loaded:w()}).strict(),U0=l({path:o().trim().min(1).max(2e3),kind:j1,loaded:w()}).strict(),sH=l({capabilities:Pv,trigger:ae(o(),ie()),observations:p(ae(o(),ie())).max(20),admissibleEvidenceIds:p(o().trim().min(1).max(2e3)).max(1e4),reviewPacket:l({currentTurn:l({id:o().trim().min(1).max(2e3),status:o().trim().min(1).max(100).nullable(),error:o().max(2100).nullable(),prompt:o().max(8100).nullable(),assistantOutput:o().max(8100).nullable(),assistantOutputLinkCount:d().int().nonnegative()}).strict(),priorConversation:p(l({turnId:o().trim().min(1).max(2e3),status:o().trim().min(1).max(100).nullable(),prompt:o().max(3100).nullable(),assistantOutput:o().max(3100).nullable()}).strict()).max(3),timeline:p(ae(o(),ie())).max(60),artifacts:p(ae(o(),ie())).max(30),artifactDiagnostics:p(ae(o(),ie())).max(20),executionProfile:l({modelRequestCount:d().int().nonnegative(),failedModelRequestCount:d().int().nonnegative(),promptTokens:d().int().nonnegative(),completionTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),toolFailureCount:d().int().nonnegative(),retryCount:d().int().nonnegative(),recoveryCount:d().int().nonnegative()}).strict(),priorIncidents:p(ae(o(),ie())).max(3),truncation:l({timelineEventCount:d().int().nonnegative(),includedTimelineEventCount:d().int().nonnegative(),timelineTruncated:w()}).strict()}).strict(),runtimeActivation:l({admittedRelease:V,currentRelease:V,rebasedOntoCurrent:w(),admittedSourceFiles:p(q0).max(100),admittedSourceCatalog:p(U0).max(1e3)}).strict(),sourceFiles:p(q0).max(100),sourceCatalog:p(U0).max(1e3),additionalEvidence:ie().nullable().optional()}).strict(),lH=l({id:o().trim().min(1).max(240),revision:d().int().nonnegative(),contentHash:D}).strict();l({schemaVersion:b("openpond.hostedHarnessRefinerRequest.v2"),requestId:o().trim().min(1).max(240),idempotencyKey:o().trim().min(1).max(240),evidenceHash:D,harness:l({admittedRelease:V,currentRelease:V,overlay:lH,workspace:l({id:o().trim().min(1).max(240),revision:d().int().nonnegative(),sourceRevision:D,channelRevision:d().int().nonnegative()}).strict(),capabilities:Pv}).strict(),evidence:sH}).strict();const cH=l({promptTokens:d().int().nonnegative(),completionTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative()}).strict();l({schemaVersion:b("openpond.hostedHarnessRefinerResponse.v2"),requestId:o().trim().min(1).max(240),evidenceHash:D,admittedRelease:V,currentRelease:V,decision:M1,serviceRevision:o().trim().min(1).max(240),usage:cH}).strict();const dH=o().trim().min(1).max(2e3),Av=o().trim().min(1).max(1e5),uH=v(["create","update","delete"]),mH=v(["memory","prompt","skill","agent"]),pH=v(["runtime","product","taskset","training"]),fH=v(["no_action","routed","applied","retained","failed"]),hH=v(["not_applicable","pending","passed","rejected","failed"]),gH=v(["not_applicable","pending","passed","failed"]),vH=l({schemaVersion:b("openpond.harnessRefinerActivityReceipt.v1"),id:T,runRef:T,turnId:T,result:fH,decision:v(["no_action","route","propose"]).nullable(),route:Bs.nullable(),operation:uH.nullable(),target:o().trim().min(1).max(2e3).nullable(),summary:dH,evidenceBasis:Rv.nullable(),critiqueStatus:hH,validationStatus:gH,trigger:V,outcome:V.nullable(),proposal:V.nullable(),applyReceipt:V.nullable(),inputHarness:V,outputHarness:V.nullable(),createdAt:he}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?z0(t,e,{decision:"no_action",route:null,operation:null,target:null,evidenceBasis:null,proposal:null,applyReceipt:null,outputHarness:null,critiqueStatus:"not_applicable",validationStatus:"not_applicable"}):e.result==="routed"?((e.decision!=="route"||!pH.safeParse(e.route).success||e.operation!==null||e.target!==null||e.evidenceBasis===null||e.proposal!==null||e.applyReceipt!==null||e.outputHarness!==null)&&t.addIssue({code:"custom",message:"routed activity requires an external route and evidence basis without proposal state"}),z0(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!mH.safeParse(e.route).success||e.operation===null||e.target===null||e.evidenceBasis===null||e.proposal===null||e.applyReceipt===null)&&t.addIssue({code:"custom",message:"applied and retained activity requires complete proposal state"}),e.result==="applied"&&e.outputHarness===null&&t.addIssue({code:"custom",message:"applied activity requires the advanced Harness release",path:["outputHarness"]}),e.result==="applied"&&(e.critiqueStatus!=="passed"||e.validationStatus!=="passed")&&t.addIssue({code:"custom",message:"applied activity requires passed critique and validation"}),e.result==="retained"&&e.outputHarness!==null&&t.addIssue({code:"custom",message:"retained activity cannot report a new Harness release",path:["outputHarness"]})):(e.decision!==null||e.route!==null||e.operation!==null||e.target!==null||e.evidenceBasis!==null||e.outcome!==null||e.proposal!==null||e.applyReceipt!==null||e.outputHarness!==null)&&t.addIssue({code:"custom",message:"failed activity cannot claim a decision, route, proposal, or release transition"}),e.result!=="failed"&&e.outcome===null&&t.addIssue({code:"custom",message:"terminal Refiner decisions require an outcome reference",path:["outcome"]})});vH.extend({contentHash:D}).strict();const bH=v(["unresolved","confirmed","resolved","rejected","expired"]),yH=l({kind:v(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:Av,evidenceRefs:p(V).max(1e3),resolvedAt:he}).strict(),SH=l({schemaVersion:b("openpond.harnessRefinementCandidate.v1"),id:T,ownerScope:_v,workspaceRef:T,fingerprint:D,recurrenceFamily:o().trim().min(1).max(1e3),statement:Av,status:bH,occurrences:p(yc).max(1e3),counterevidence:p(yc).max(1e3),sourceReviews:p(V).min(1).max(100),relatedHarnessReleases:p(V).max(100),firstSeenAt:he,lastSeenAt:he,lastReviewedAt:he,expiresAt:he,resolution:yH.nullable(),createdAt:he,updatedAt:he}).strict().superRefine((e,t)=>{hr(t,e.occurrences,"occurrences"),hr(t,e.counterevidence,"counterevidence"),hr(t,e.sourceReviews,"sourceReviews"),hr(t,e.relatedHarnessReleases,"relatedHarnessReleases");const n=new Set(e.occurrences.map(i=>i.occurrenceKey));e.counterevidence.some(i=>n.has(i.occurrenceKey))&&t.addIssue({code:"custom",message:"supporting occurrences and counterevidence must be disjoint",path:["counterevidence"]});const a=e.status==="unresolved"||e.status==="confirmed";a&&e.occurrences.length===0&&t.addIssue({code:"custom",message:"actionable candidates require at least one supporting occurrence",path:["occurrences"]}),a&&[...e.occurrences,...e.counterevidence].some(i=>i.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"actionable candidates may contain only currently authorized evidence",path:["occurrences"]}),a!==(e.resolution===null)&&t.addIssue({code:"custom",message:"only resolved, rejected, or expired candidates require a resolution",path:["resolution"]}),e.status==="expired"&&e.resolution?.kind!=="expired"&&t.addIssue({code:"custom",message:"expired candidates require an expired resolution",path:["resolution","kind"]}),e.status==="rejected"&&e.resolution&&!["manual_rejection","source_revoked"].includes(e.resolution.kind)&&t.addIssue({code:"custom",message:"rejected candidates require a rejection or revocation resolution",path:["resolution","kind"]}),e.status==="resolved"&&e.resolution&&!["applied_change","later_success"].includes(e.resolution.kind)&&t.addIssue({code:"custom",message:"resolved candidates require applied-change or later-success evidence",path:["resolution","kind"]}),_H(t,e)});SH.extend({contentHash:D}).strict();const xH=v(["created","merged","rejected","expired","reopened","resolved"]),kH=l({schemaVersion:b("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:T,candidateId:T,decision:xH,beforeCandidate:V.nullable(),afterCandidate:V,review:V,addedEvidence:p(yc).max(1e3),removedEvidence:p(V).max(1e3),reason:Av,createdAt:he}).strict().superRefine((e,t)=>{e.decision==="created"!=(e.beforeCandidate===null)&&t.addIssue({code:"custom",message:"only candidate creation omits the previous candidate reference",path:["beforeCandidate"]}),e.beforeCandidate&&e.beforeCandidate.contentHash===e.afterCandidate.contentHash&&t.addIssue({code:"custom",message:"candidate lifecycle transitions must change candidate content",path:["afterCandidate"]}),["created","reopened"].includes(e.decision)&&e.addedEvidence.length===0&&t.addIssue({code:"custom",message:`${e.decision} candidate transitions require added evidence`,path:["addedEvidence"]}),e.addedEvidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"candidate transitions may add only authorized evidence",path:["addedEvidence"]}),hr(t,e.addedEvidence,"addedEvidence"),hr(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>tg(a)));e.addedEvidence.some(a=>n.has(tg(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});kH.extend({contentHash:D}).strict();const IH=l({schemaVersion:b("openpond.harnessCrossRunRefinementRequest.v1"),id:T,ownerScope:_v,workspaceRef:T,candidate:V,candidateFingerprint:D,review:V,admittedHarness:V,evidence:p(yc).min(1).max(1e3),capabilities:Pv,deduplicationKey:D,createdAt:he}).strict().superRefine((e,t)=>{e.evidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"cross-run refinement requires currently authorized evidence",path:["evidence"]}),hr(t,e.evidence,"evidence"),Object.values(e.capabilities).some(Boolean)||t.addIssue({code:"custom",message:"cross-run refinement requires at least one available Harness capability",path:["capabilities"]});const n=wH(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});IH.extend({contentHash:D}).strict();function wH(e){return st({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function z0(e,t,n){for(const[a,i]of Object.entries(n))t[a]!==i&&e.addIssue({code:"custom",message:`${a} must be ${String(i)}`,path:[a]})}function hr(e,t,n){const a=t.map(i=>tg(i));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function tg(e){if(!e||typeof e!="object"||Array.isArray(e))return String(e);const t=e;if(typeof t.occurrenceKey=="string")return t.occurrenceKey;const n=t.evidence;if(n&&typeof n=="object"&&!Array.isArray(n)){const a=n;return`${String(a.id)}:${String(a.contentHash)}`}return`${String(t.id)}:${String(t.contentHash)}`}function _H(e,t){const n=[["firstSeenAt",t.firstSeenAt],["lastSeenAt",t.lastSeenAt],["lastReviewedAt",t.lastReviewedAt],["updatedAt",t.updatedAt],["expiresAt",t.expiresAt]];for(let a=1;a<n.length;a+=1){const i=n[a-1],r=n[a];Date.parse(i[1])<=Date.parse(r[1])||e.addIssue({code:"custom",message:`${r[0]} must not precede ${i[0]}`,path:[r[0]]})}Date.parse(t.createdAt)>Date.parse(t.updatedAt)&&e.addIssue({code:"custom",message:"updatedAt must not precede createdAt",path:["updatedAt"]})}const CH=25*1024*1024,RH=l({path:gn.shape.path,base64:o().max(Math.ceil(CH/3)*4)}).strict(),O1=l({schemaVersion:b("openpond.harnessSourcePackage.v1"),agentSnapshot:AD,harnessRelease:ED,files:p(RH).max(1e4)}).strict();O1.extend({contentHash:D}).strict();O1.extend({schemaVersion:b("openpond.harnessPolicySourcePackage.v1"),contentHash:D}).strict();l({schemaVersion:b("openpond.harnessSourceSelection.v1"),mode:v(["taskset_owned","selected_release"]),harnessRelease:V,sourcePackageHash:D.nullable()}).strict().superRefine((e,t)=>{e.mode==="selected_release"!=(e.sourcePackageHash!==null)&&t.addIssue({code:"custom",path:["sourcePackageHash"],message:"Only a selected release binds a source package."})});l({path:o().min(1).max(2e3),offset:d().int().nonnegative().default(0),length:d().int().positive().max(65536).default(16384)}).strict();const $1=o().regex(/^[a-z][a-z0-9_-]{0,119}$/),N1=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"),PH=l({id:$1,label:o().trim().min(1).max(240),description:o().max(4e3),inputSchema:ae(o(),ie()),invocation:lt("kind",[l({kind:b("instructions"),instructions:o().min(1).max(1e5).refine(e=>!!e.trim())}).strict(),l({kind:b("agent_action"),actionId:o().trim().min(1).max(240)}).strict()]),skillPaths:p(N1).max(100)}).strict();l({schemaVersion:b("openpond.profileWorkflows.v1"),workflows:p(PH).max(1e3)}).strict();const AH=l({id:o().trim().min(1).max(240),agentId:o().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:o().trim().min(1).max(240),inputSchema:ae(o(),ie())}).strict();l({schemaVersion:b("openpond.profileWorkflowActions.v1"),actions:p(AH).max(200)}).strict();const TH=l({schemaVersion:b("openpond.profileWorkflowBinding.v1"),profileId:o().trim().min(1).max(240),sourceRevision:o().trim().min(1).max(240),harnessRelease:V,catalogHash:D,workflowId:$1}).strict(),EH=l({schemaVersion:b("openpond.profileComponentBinding.v1"),profileId:o().trim().min(1).max(240),sourceRevision:o().trim().min(1).max(240),harnessRelease:V,target:lt("kind",[l({kind:b("profile")}).strict(),l({kind:b("skill"),skillPath:N1}).strict(),l({kind:b("agent_action"),actionId:o().trim().min(1).max(240)}).strict()])}).strict(),Tv=Symbol.for("yaml.alias"),MH=Symbol.for("yaml.document"),Ir=Symbol.for("yaml.map"),D1=Symbol.for("yaml.pair"),Ev=Symbol.for("yaml.scalar"),Yc=Symbol.for("yaml.seq"),Di=Symbol.for("yaml.node.type"),sl=e=>!!e&&typeof e=="object"&&e[Di]===Tv,km=e=>!!e&&typeof e=="object"&&e[Di]===MH,H1=e=>!!e&&typeof e=="object"&&e[Di]===Ir,Un=e=>!!e&&typeof e=="object"&&e[Di]===D1,En=e=>!!e&&typeof e=="object"&&e[Di]===Ev,Mv=e=>!!e&&typeof e=="object"&&e[Di]===Yc;function xa(e){if(e&&typeof e=="object")switch(e[Di]){case Ir:case Yc:return!0}return!1}function Kn(e){if(e&&typeof e=="object")switch(e[Di]){case Tv:case Ir:case Ev:case Yc:return!0}return!1}const L1=e=>(En(e)||xa(e))&&!!e.anchor,ur=Symbol("break visit"),jH=Symbol("skip children"),ic=Symbol("remove node");function Im(e,t){const n=OH(t);km(e)?ks(null,e.contents,n,Object.freeze([e]))===ic&&(e.contents=null):ks(null,e,n,Object.freeze([]))}Im.BREAK=ur;Im.SKIP=jH;Im.REMOVE=ic;function ks(e,t,n,a){const i=$H(e,t,n,a);if(Kn(i)||Un(i))return NH(e,a,i),ks(e,i,n,a);if(typeof i!="symbol"){if(xa(t)){a=Object.freeze(a.concat(t));for(let r=0;r<t.items.length;++r){const s=ks(r,t.items[r],n,a);if(typeof s=="number")r=s-1;else{if(s===ur)return ur;s===ic&&(t.items.splice(r,1),r-=1)}}}else if(Un(t)){a=Object.freeze(a.concat(t));const r=ks("key",t.key,n,a);if(r===ur)return ur;r===ic&&(t.key=null);const s=ks("value",t.value,n,a);if(s===ur)return ur;s===ic&&(t.value=null)}}return i}function OH(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function $H(e,t,n,a){if(typeof n=="function")return n(e,t,a);if(H1(t))return n.Map?.(e,t,a);if(Mv(t))return n.Seq?.(e,t,a);if(Un(t))return n.Pair?.(e,t,a);if(En(t))return n.Scalar?.(e,t,a);if(sl(t))return n.Alias?.(e,t,a)}function NH(e,t,n){const a=t[t.length-1];if(xa(a))a.items[e]=n;else if(Un(a))e==="key"?a.key=n:a.value=n;else if(km(a))a.contents=n;else{const i=sl(a)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}function q1(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){const n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(n)}return!0}function Zl(e,t,n,a){if(a&&typeof a=="object")if(Array.isArray(a))for(let i=0,r=a.length;i<r;++i){const s=a[i],c=Zl(e,a,String(i),s);c===void 0?delete a[i]:c!==s&&(a[i]=c)}else if(a instanceof Map)for(const i of Array.from(a.keys())){const r=a.get(i),s=Zl(e,a,i,r);s===void 0?a.delete(i):s!==r&&a.set(i,s)}else if(a instanceof Set)for(const i of Array.from(a)){const r=Zl(e,a,i,i);r===void 0?a.delete(i):r!==i&&(a.delete(i),a.add(r))}else for(const[i,r]of Object.entries(a)){const s=Zl(e,a,i,r);s===void 0?delete a[i]:s!==r&&(a[i]=s)}return e.call(t,n,a)}function si(e,t,n){if(Array.isArray(e))return e.map((a,i)=>si(a,String(i),n));if(e&&typeof e.toJSON=="function"){if(!n||!L1(e))return e.toJSON(t,n);const a={aliasCount:0,count:1,res:void 0};n.anchors.set(e,a),n.onCreate=r=>{a.res=r,delete n.onCreate};const i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e=="bigint"&&!n?.keep?Number(e):e}class jv{constructor(t){Object.defineProperty(this,Di,{value:t})}clone(){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:n,maxAliasCount:a,onAnchor:i,reviver:r}={}){if(!km(t))throw new TypeError("A document argument is required");const s={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof a=="number"?a:100},c=si(this,"",s);if(typeof i=="function")for(const{count:m,res:u}of s.anchors.values())i(u,m);return typeof r=="function"?Zl(r,{"":c},"",c):c}}class DH extends jv{constructor(t){super(Tv),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let a;n?.aliasResolveCache?a=n.aliasResolveCache:(a=[],Im(t,{Node:(r,s)=>{(sl(s)||L1(s))&&a.push(s)}}),n&&(n.aliasResolveCache=a));let i;for(const r of a){if(r===this)break;r.anchor===this.source&&(i=r)}return i}toJSON(t,n){if(!n)return{source:this.source};const{anchors:a,doc:i,maxAliasCount:r}=n,s=this.resolve(i,n);if(!s){const m=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(m)}let c=a.get(s);if(c||(si(s,null,n),c=a.get(s)),c?.res===void 0){const m="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(m)}if(r>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=mu(i,s,a)),c.count*c.aliasCount>r)){const m="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(m)}return c.res}toString(t,n,a){const i=`*${this.source}`;if(t){if(q1(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){const r=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(r)}if(t.implicitKey)return`${i} `}return i}}function mu(e,t,n){if(sl(t)){const a=t.resolve(e),i=n&&a&&n.get(a);return i?i.count*i.aliasCount:0}else if(xa(t)){let a=0;for(const i of t.items){const r=mu(e,i,n);r>a&&(a=r)}return a}else if(Un(t)){const a=mu(e,t.key,n),i=mu(e,t.value,n);return Math.max(a,i)}return 1}const U1=e=>!e||typeof e!="function"&&typeof e!="object";class mn extends jv{constructor(t){super(Ev),this.value=t}toJSON(t,n){return n?.keep?this.value:si(this.value,t,n)}toString(){return String(this.value)}}mn.BLOCK_FOLDED="BLOCK_FOLDED";mn.BLOCK_LITERAL="BLOCK_LITERAL";mn.PLAIN="PLAIN";mn.QUOTE_DOUBLE="QUOTE_DOUBLE";mn.QUOTE_SINGLE="QUOTE_SINGLE";function HH(e,t,n){return n.find(a=>a.identify?.(e)&&!a.format)}function $u(e,t,n){if(km(e)&&(e=e.contents),Kn(e))return e;if(Un(e)){const g=n.schema[Ir].createNode?.(n.schema,null,n);return g.items.push(e),g}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());const{aliasDuplicateObjects:a,onAnchor:i,onTagObj:r,schema:s,sourceObjects:c}=n;let m;if(a&&e&&typeof e=="object"){if(m=c.get(e),m)return m.anchor??(m.anchor=i(e)),new DH(m.anchor);m={anchor:null,node:null},c.set(e,m)}let u=HH(e,t,s.tags);if(!u){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){const g=new mn(e);return m&&(m.node=g),g}u=e instanceof Map?s[Ir]:Symbol.iterator in Object(e)?s[Yc]:s[Ir]}r&&(r(u),delete n.onTagObj);const h=u?.createNode?u.createNode(n.schema,e,n):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(n.schema,e,n):new mn(e);return u.default||(h.tag=u.tag),m&&(m.node=h),h}function B0(e,t,n){let a=n;for(let i=t.length-1;i>=0;--i){const r=t[i];if(typeof r=="number"&&Number.isInteger(r)&&r>=0){const s=[];s[r]=a,a=s}else a=new Map([[r,a]])}return $u(a,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}const LH=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done;class z1 extends jv{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){const n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(a=>Kn(a)||Un(a)?a.clone(t):a),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(LH(t))this.add(n);else{const[a,...i]=t,r=this.get(a,!0);if(xa(r))r.addIn(i,n);else if(r===void 0&&this.schema)this.set(a,B0(this.schema,i,n));else throw new Error(`Expected YAML collection at ${a}. Remaining path: ${i}`)}}deleteIn(t){const[n,...a]=t;if(a.length===0)return this.delete(n);const i=this.get(n,!0);if(xa(i))return i.deleteIn(a);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${a}`)}getIn(t,n){const[a,...i]=t,r=this.get(a,!0);return i.length===0?!n&&En(r)?r.value:r:xa(r)?r.getIn(i,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!Un(n))return!1;const a=n.value;return a==null||t&&En(a)&&a.value==null&&!a.commentBefore&&!a.comment&&!a.tag})}hasIn(t){const[n,...a]=t;if(a.length===0)return this.has(n);const i=this.get(n,!0);return xa(i)?i.hasIn(a):!1}setIn(t,n){const[a,...i]=t;if(i.length===0)this.set(a,n);else{const r=this.get(a,!0);if(xa(r))r.setIn(i,n);else if(r===void 0&&this.schema)this.set(a,B0(this.schema,i,n));else throw new Error(`Expected YAML collection at ${a}. Remaining path: ${i}`)}}}const qH=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Sc(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const Is=(e,t,n)=>e.endsWith(`
125
+ `)?Sc(n,t):n.includes(`
126
+ `)?`
127
+ `+Sc(n,t):(e.endsWith(" ")?"":" ")+n,B1="flow",ng="block",pu="quoted";function wm(e,t,n="flow",{indentAtStart:a,lineWidth:i=80,minContentWidth:r=20,onFold:s,onOverflow:c}={}){if(!i||i<0)return e;i<r&&(r=0);const m=Math.max(1+r,1+i-t.length);if(e.length<=m)return e;const u=[],h={};let g=i-t.length;typeof a=="number"&&(a>i-Math.max(2,r)?u.push(0):g=i-a);let S,k,C=!1,A=-1,M=-1,R=-1;n===ng&&(A=F0(e,A,t.length),A!==-1&&(g=A+m));for(let O;O=e[A+=1];){if(n===pu&&O==="\\"){switch(M=A,e[A+1]){case"x":A+=3;break;case"u":A+=5;break;case"U":A+=9;break;default:A+=1}R=A}if(O===`
128
+ `)n===ng&&(A=F0(e,A,t.length)),g=A+t.length+m,S=void 0;else{if(O===" "&&k&&k!==" "&&k!==`
129
+ `&&k!==" "){const j=e[A+1];j&&j!==" "&&j!==`
130
+ `&&j!==" "&&(S=A)}if(A>=g)if(S)u.push(S),g=S+m,S=void 0;else if(n===pu){for(;k===" "||k===" ";)k=O,O=e[A+=1],C=!0;const j=A>R+1?A-2:M-1;if(h[j])return e;u.push(j),h[j]=!0,g=j+m,S=void 0}else C=!0}k=O}if(C&&c&&c(),u.length===0)return e;s&&s();let $=e.slice(0,u[0]);for(let O=0;O<u.length;++O){const j=u[O],I=u[O+1]||e.length;j===0?$=`
131
+ ${t}${e.slice(0,I)}`:(n===pu&&h[j]&&($+=`${e[j]}\\`),$+=`
132
+ ${t}${e.slice(j+1,I)}`)}return $}function F0(e,t,n){let a=t,i=t+1,r=e[i];for(;r===" "||r===" ";)if(t<i+n)r=e[++t];else{do r=e[++t];while(r&&r!==`
133
+ `);a=t,i=t+1,r=e[i]}return a}const _m=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Cm=e=>/^(%|---|\.\.\.)/m.test(e);function UH(e,t,n){if(!t||t<0)return!1;const a=t-n,i=e.length;if(i<=a)return!1;for(let r=0,s=0;r<i;++r)if(e[r]===`
134
+ `){if(r-s>a)return!0;if(s=r+1,i-s<=a)return!1}return!0}function oc(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:a}=t,i=t.options.doubleQuotedMinMultiLineLength,r=t.indent||(Cm(e)?" ":"");let s="",c=0;for(let m=0,u=n[m];u;u=n[++m])if(u===" "&&n[m+1]==="\\"&&n[m+2]==="n"&&(s+=n.slice(c,m)+"\\ ",m+=1,c=m,u="\\"),u==="\\")switch(n[m+1]){case"u":{s+=n.slice(c,m);const h=n.substr(m+2,4);switch(h){case"0000":s+="\\0";break;case"0007":s+="\\a";break;case"000b":s+="\\v";break;case"001b":s+="\\e";break;case"0085":s+="\\N";break;case"00a0":s+="\\_";break;case"2028":s+="\\L";break;case"2029":s+="\\P";break;default:h.substr(0,2)==="00"?s+="\\x"+h.substr(2):s+=n.substr(m,6)}m+=5,c=m+1}break;case"n":if(a||n[m+2]==='"'||n.length<i)m+=1;else{for(s+=n.slice(c,m)+`
135
+
136
+ `;n[m+2]==="\\"&&n[m+3]==="n"&&n[m+4]!=='"';)s+=`
137
+ `,m+=2;s+=r,n[m+2]===" "&&(s+="\\"),m+=1,c=m+1}break;default:m+=1}return s=c?s+n.slice(c):n,a?s:wm(s,r,pu,_m(t,!1))}function ag(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
138
+ `)||/[ \t]\n|\n[ \t]/.test(e))return oc(e,t);const n=t.indent||(Cm(e)?" ":""),a="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
139
+ ${n}`)+"'";return t.implicitKey?a:wm(a,n,B1,_m(t,!1))}function ws(e,t){const{singleQuote:n}=t.options;let a;if(n===!1)a=oc;else{const i=e.includes('"'),r=e.includes("'");i&&!r?a=ag:r&&!i?a=oc:a=n?ag:oc}return a(e,t)}let ig;try{ig=new RegExp(`(^|(?<!
140
+ ))
141
+ +(?!
142
+ |$)`,"g")}catch{ig=/\n+(?!\n|$)/g}function fu({comment:e,type:t,value:n},a,i,r){const{blockQuote:s,commentString:c,lineWidth:m}=a.options;if(!s||/\n[\t ]+$/.test(n))return ws(n,a);const u=a.indent||(a.forceBlockIndent||Cm(n)?" ":""),h=s==="literal"?!0:s==="folded"||t===mn.BLOCK_FOLDED?!1:t===mn.BLOCK_LITERAL?!0:!UH(n,m,u.length);if(!n)return h?`|
143
+ `:`>
144
+ `;let g,S;for(S=n.length;S>0;--S){const I=n[S-1];if(I!==`
145
+ `&&I!==" "&&I!==" ")break}let k=n.substring(S);const C=k.indexOf(`
146
+ `);C===-1?g="-":n===k||C!==k.length-1?(g="+",r&&r()):g="",k&&(n=n.slice(0,-k.length),k[k.length-1]===`
147
+ `&&(k=k.slice(0,-1)),k=k.replace(ig,`$&${u}`));let A=!1,M,R=-1;for(M=0;M<n.length;++M){const I=n[M];if(I===" ")A=!0;else if(I===`
148
+ `)R=M;else break}let $=n.substring(0,R<M?R+1:M);$&&(n=n.substring($.length),$=$.replace(/\n+/g,`$&${u}`));let j=(A?u?"2":"1":"")+g;if(e&&(j+=" "+c(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!h){const I=n.replace(/\n+/g,`
149
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let P=!1;const E=_m(a,!0);s!=="folded"&&t!==mn.BLOCK_FOLDED&&(E.onOverflow=()=>{P=!0});const L=wm(`${$}${I}${k}`,u,ng,E);if(!P)return`>${j}
150
+ ${u}${L}`}return n=n.replace(/\n+/g,`$&${u}`),`|${j}
151
+ ${u}${$}${n}${k}`}function zH(e,t,n,a){const{type:i,value:r}=e,{actualString:s,implicitKey:c,indent:m,indentStep:u,inFlow:h}=t;if(c&&r.includes(`
152
+ `)||h&&/[[\]{},]/.test(r))return ws(r,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(r))return c||h||!r.includes(`
153
+ `)?ws(r,t):fu(e,t,n,a);if(!c&&!h&&i!==mn.PLAIN&&r.includes(`
154
+ `))return fu(e,t,n,a);if(Cm(r)){if(m==="")return t.forceBlockIndent=!0,fu(e,t,n,a);if(c&&m===u)return ws(r,t)}const g=r.replace(/\n+/g,`$&
155
+ ${m}`);if(s){const S=A=>A.default&&A.tag!=="tag:yaml.org,2002:str"&&A.test?.test(g),{compat:k,tags:C}=t.doc.schema;if(C.some(S)||k?.some(S))return ws(r,t)}return c?g:wm(g,m,B1,_m(t,!1))}function BH(e,t,n,a){const{implicitKey:i,inFlow:r}=t,s=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)});let{type:c}=e;c!==mn.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(s.value)&&(c=mn.QUOTE_DOUBLE);const m=h=>{switch(h){case mn.BLOCK_FOLDED:case mn.BLOCK_LITERAL:return i||r?ws(s.value,t):fu(s,t,n,a);case mn.QUOTE_DOUBLE:return oc(s.value,t);case mn.QUOTE_SINGLE:return ag(s.value,t);case mn.PLAIN:return zH(s,t,n,a);default:return null}};let u=m(c);if(u===null){const{defaultKeyType:h,defaultStringType:g}=t.options,S=i&&h||g;if(u=m(S),u===null)throw new Error(`Unsupported default string type ${S}`)}return u}function FH(e,t){const n=Object.assign({blockQuote:!0,commentString:qH,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t);let a;switch(n.collectionStyle){case"block":a=!1;break;case"flow":a=!0;break;default:a=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:a,options:n}}function VH(e,t){if(t.tag){const i=e.filter(r=>r.tag===t.tag);if(i.length>0)return i.find(r=>r.format===t.format)??i[0]}let n,a;if(En(t)){a=t.value;let i=e.filter(r=>r.identify?.(a));if(i.length>1){const r=i.filter(s=>s.test);r.length>0&&(i=r)}n=i.find(r=>r.format===t.format)??i.find(r=>!r.format)}else a=t,n=e.find(i=>i.nodeClass&&a instanceof i.nodeClass);if(!n){const i=a?.constructor?.name??(a===null?"null":typeof a);throw new Error(`Tag not resolved for ${i} value`)}return n}function KH(e,t,{anchors:n,doc:a}){if(!a.directives)return"";const i=[],r=(En(e)||xa(e))&&e.anchor;r&&q1(r)&&(n.add(r),i.push(`&${r}`));const s=e.tag??(t.default?null:t.tag);return s&&i.push(a.directives.tagString(s)),i.join(" ")}function Nu(e,t,n,a){if(Un(e))return e.toString(t,n,a);if(sl(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i;const r=Kn(e)?e:t.doc.createNode(e,{onTagObj:m=>i=m});i??(i=VH(t.doc.schema.tags,r));const s=KH(r,i,t);s.length>0&&(t.indentAtStart=(t.indentAtStart??0)+s.length+1);const c=typeof i.stringify=="function"?i.stringify(r,t,n,a):En(r)?BH(r,t,n,a):r.toString(t,n,a);return s?En(r)||c[0]==="{"||c[0]==="["?`${s} ${c}`:`${s}
156
+ ${t.indent}${c}`:c}function WH({key:e,value:t},n,a,i){const{allNullValues:r,doc:s,indent:c,indentStep:m,options:{commentString:u,indentSeq:h,simpleKeys:g}}=n;let S=Kn(e)&&e.comment||null;if(g){if(S)throw new Error("With simple keys, key nodes cannot have comments");if(xa(e)||!Kn(e)&&typeof e=="object"){const E="With simple keys, collection cannot be used as a key value";throw new Error(E)}}let k=!g&&(!e||S&&t==null&&!n.inFlow||xa(e)||(En(e)?e.type===mn.BLOCK_FOLDED||e.type===mn.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!k&&(g||!r),indent:c+m});let C=!1,A=!1,M=Nu(e,n,()=>C=!0,()=>A=!0);if(!k&&!n.inFlow&&M.length>1024){if(g)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");k=!0}if(n.inFlow){if(r||t==null)return C&&a&&a(),M===""?"?":k?`? ${M}`:M}else if(r&&!g||t==null&&k)return M=`? ${M}`,S&&!C?M+=Is(M,n.indent,u(S)):A&&i&&i(),M;C&&(S=null),k?(S&&(M+=Is(M,n.indent,u(S))),M=`? ${M}
157
+ ${c}:`):(M=`${M}:`,S&&(M+=Is(M,n.indent,u(S))));let R,$,O;Kn(t)?(R=!!t.spaceBefore,$=t.commentBefore,O=t.comment):(R=!1,$=null,O=null,t&&typeof t=="object"&&(t=s.createNode(t))),n.implicitKey=!1,!k&&!S&&En(t)&&(n.indentAtStart=M.length+1),A=!1,!h&&m.length>=2&&!n.inFlow&&!k&&Mv(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let j=!1;const I=Nu(t,n,()=>j=!0,()=>A=!0);let P=" ";if(S||R||$){if(P=R?`
158
+ `:"",$){const E=u($);P+=`
159
+ ${Sc(E,n.indent)}`}I===""&&!n.inFlow?P===`
160
+ `&&O&&(P=`
161
+
162
+ `):P+=`
163
+ ${n.indent}`}else if(!k&&xa(t)){const E=I[0],L=I.indexOf(`
164
+ `),z=L!==-1,H=n.inFlow??t.flow??t.items.length===0;if(z||!H){let J=!1;if(z&&(E==="&"||E==="!")){let X=I.indexOf(" ");E==="&"&&X!==-1&&X<L&&I[X+1]==="!"&&(X=I.indexOf(" ",X+1)),(X===-1||L<X)&&(J=!0)}J||(P=`
165
+ ${n.indent}`)}}else(I===""||I[0]===`
166
+ `)&&(P="");return M+=P+I,n.inFlow?j&&a&&a():O&&!j?M+=Is(M,n.indent,u(O)):A&&i&&i(),M}function GH(e,t){(e==="debug"||e==="warn")&&console.warn(t)}const Bd="<<",Qf={identify:e=>e===Bd||typeof e=="symbol"&&e.description===Bd,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new mn(Symbol(Bd)),{addToJSMap:F1}),stringify:()=>Bd},JH=(e,t)=>(Qf.identify(t)||En(t)&&(!t.type||t.type===mn.PLAIN)&&Qf.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===Qf.tag&&n.default);function F1(e,t,n){const a=V1(e,n);if(Mv(a))for(const i of a.items)Xf(e,t,i);else if(Array.isArray(a))for(const i of a)Xf(e,t,i);else Xf(e,t,a)}function Xf(e,t,n){const a=V1(e,n);if(!H1(a))throw new Error("Merge sources must be maps or map aliases");const i=a.toJSON(null,e,Map);for(const[r,s]of i)t instanceof Map?t.has(r)||t.set(r,s):t instanceof Set?t.add(r):Object.prototype.hasOwnProperty.call(t,r)||Object.defineProperty(t,r,{value:s,writable:!0,enumerable:!0,configurable:!0});return t}function V1(e,t){return e&&sl(t)?t.resolve(e.doc,e):t}function K1(e,t,{key:n,value:a}){if(Kn(n)&&n.addToJSMap)n.addToJSMap(e,t,a);else if(JH(e,n))F1(e,t,a);else{const i=si(n,"",e);if(t instanceof Map)t.set(i,si(a,i,e));else if(t instanceof Set)t.add(i);else{const r=ZH(n,i,e),s=si(a,r,e);r in t?Object.defineProperty(t,r,{value:s,writable:!0,enumerable:!0,configurable:!0}):t[r]=s}}return t}function ZH(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(Kn(e)&&n?.doc){const a=FH(n.doc,{});a.anchors=new Set;for(const r of n.anchors.keys())a.anchors.add(r.anchor);a.inFlow=!0,a.inStringifyKey=!0;const i=e.toString(a);if(!n.mapKeyWarned){let r=JSON.stringify(i);r.length>40&&(r=r.substring(0,36)+'..."'),GH(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${r}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return i}return JSON.stringify(t)}function Ov(e,t,n){const a=$u(e,void 0,n),i=$u(t,void 0,n);return new oo(a,i)}class oo{constructor(t,n=null){Object.defineProperty(this,Di,{value:D1}),this.key=t,this.value=n}clone(t){let{key:n,value:a}=this;return Kn(n)&&(n=n.clone(t)),Kn(a)&&(a=a.clone(t)),new oo(n,a)}toJSON(t,n){const a=n?.mapAsMap?new Map:{};return K1(n,a,this)}toString(t,n,a){return t?.doc?WH(this,t,n,a):JSON.stringify(this)}}function W1(e,t,n){return(t.inFlow??e.flow?QH:YH)(e,t,n)}function YH({comment:e,items:t},n,{blockItemPrefix:a,flowChars:i,itemIndent:r,onChompKeep:s,onComment:c}){const{indent:m,options:{commentString:u}}=n,h=Object.assign({},n,{indent:r,type:null});let g=!1;const S=[];for(let C=0;C<t.length;++C){const A=t[C];let M=null;if(Kn(A))!g&&A.spaceBefore&&S.push(""),Du(n,S,A.commentBefore,g),A.comment&&(M=A.comment);else if(Un(A)){const $=Kn(A.key)?A.key:null;$&&(!g&&$.spaceBefore&&S.push(""),Du(n,S,$.commentBefore,g))}g=!1;let R=Nu(A,h,()=>M=null,()=>g=!0);M&&(R+=Is(R,r,u(M))),g&&M&&(g=!1),S.push(a+R)}let k;if(S.length===0)k=i.start+i.end;else{k=S[0];for(let C=1;C<S.length;++C){const A=S[C];k+=A?`
167
+ ${m}${A}`:`
168
+ `}}return e?(k+=`
169
+ `+Sc(u(e),m),c&&c()):g&&s&&s(),k}function QH({items:e},t,{flowChars:n,itemIndent:a}){const{indent:i,indentStep:r,flowCollectionPadding:s,options:{commentString:c}}=t;a+=r;const m=Object.assign({},t,{indent:a,inFlow:!0,type:null});let u=!1,h=0;const g=[];for(let C=0;C<e.length;++C){const A=e[C];let M=null;if(Kn(A))A.spaceBefore&&g.push(""),Du(t,g,A.commentBefore,!1),A.comment&&(M=A.comment);else if(Un(A)){const $=Kn(A.key)?A.key:null;$&&($.spaceBefore&&g.push(""),Du(t,g,$.commentBefore,!1),$.comment&&(u=!0));const O=Kn(A.value)?A.value:null;O?(O.comment&&(M=O.comment),O.commentBefore&&(u=!0)):A.value==null&&$?.comment&&(M=$.comment)}M&&(u=!0);let R=Nu(A,m,()=>M=null);u||(u=g.length>h||R.includes(`
170
+ `)),C<e.length-1?R+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(u||(u=g.reduce(($,O)=>$+O.length+2,2)+(R.length+2)>t.options.lineWidth)),u&&(R+=",")),M&&(R+=Is(R,a,c(M))),g.push(R),h=g.length}const{start:S,end:k}=n;if(g.length===0)return S+k;if(!u){const C=g.reduce((A,M)=>A+M.length+2,2);u=t.options.lineWidth>0&&C>t.options.lineWidth}if(u){let C=S;for(const A of g)C+=A?`
171
+ ${r}${i}${A}`:`
172
+ `;return`${C}
173
+ ${i}${k}`}else return`${S}${s}${g.join(" ")}${s}${k}`}function Du({indent:e,options:{commentString:t}},n,a,i){if(a&&i&&(a=a.replace(/^\n+/,"")),a){const r=Sc(t(a),e);n.push(r.trimStart())}}function gr(e,t){const n=En(t)?t.value:t;for(const a of e)if(Un(a)&&(a.key===t||a.key===n||En(a.key)&&a.key.value===n))return a}class gs extends z1{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Ir,t),this.items=[]}static from(t,n,a){const{keepUndefined:i,replacer:r}=a,s=new this(t),c=(m,u)=>{if(typeof r=="function")u=r.call(n,m,u);else if(Array.isArray(r)&&!r.includes(m))return;(u!==void 0||i)&&s.items.push(Ov(m,u,a))};if(n instanceof Map)for(const[m,u]of n)c(m,u);else if(n&&typeof n=="object")for(const m of Object.keys(n))c(m,n[m]);return typeof t.sortMapEntries=="function"&&s.items.sort(t.sortMapEntries),s}add(t,n){let a;Un(t)?a=t:!t||typeof t!="object"||!("key"in t)?a=new oo(t,t?.value):a=new oo(t.key,t.value);const i=gr(this.items,a.key),r=this.schema?.sortMapEntries;if(i){if(!n)throw new Error(`Key ${a.key} already set`);En(i.value)&&U1(a.value)?i.value.value=a.value:i.value=a.value}else if(r){const s=this.items.findIndex(c=>r(a,c)<0);s===-1?this.items.push(a):this.items.splice(s,0,a)}else this.items.push(a)}delete(t){const n=gr(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){const i=gr(this.items,t)?.value;return(!n&&En(i)?i.value:i)??void 0}has(t){return!!gr(this.items,t)}set(t,n){this.add(new oo(t,n),!0)}toJSON(t,n,a){const i=a?new a:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(i);for(const r of this.items)K1(n,i,r);return i}toString(t,n,a){if(!t)return JSON.stringify(this);for(const i of this.items)if(!Un(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),W1(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:a,onComment:n})}}class G1 extends z1{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Yc,t),this.items=[]}add(t){this.items.push(t)}delete(t){const n=Fd(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){const a=Fd(t);if(typeof a!="number")return;const i=this.items[a];return!n&&En(i)?i.value:i}has(t){const n=Fd(t);return typeof n=="number"&&n<this.items.length}set(t,n){const a=Fd(t);if(typeof a!="number")throw new Error(`Expected a valid index, not ${t}.`);const i=this.items[a];En(i)&&U1(n)?i.value=n:this.items[a]=n}toJSON(t,n){const a=[];n?.onCreate&&n.onCreate(a);let i=0;for(const r of this.items)a.push(si(r,String(i++),n));return a}toString(t,n,a){return t?W1(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:a,onComment:n}):JSON.stringify(this)}static from(t,n,a){const{replacer:i}=a,r=new this(t);if(n&&Symbol.iterator in Object(n)){let s=0;for(let c of n){if(typeof i=="function"){const m=n instanceof Set?c:String(s++);c=i.call(n,m,c)}r.items.push($u(c,void 0,a))}}return r}}function Fd(e){let t=En(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}function XH(e,t,n){const{replacer:a}=n,i=new G1(e);i.tag="tag:yaml.org,2002:pairs";let r=0;if(t&&Symbol.iterator in Object(t))for(let s of t){typeof a=="function"&&(s=a.call(t,String(r++),s));let c,m;if(Array.isArray(s))if(s.length===2)c=s[0],m=s[1];else throw new TypeError(`Expected [key, value] tuple: ${s}`);else if(s&&s instanceof Object){const u=Object.keys(s);if(u.length===1)c=u[0],m=s[c];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else c=s;i.items.push(Ov(c,m,n))}return i}class $v extends G1{constructor(){super(),this.add=gs.prototype.add.bind(this),this.delete=gs.prototype.delete.bind(this),this.get=gs.prototype.get.bind(this),this.has=gs.prototype.has.bind(this),this.set=gs.prototype.set.bind(this),this.tag=$v.tag}toJSON(t,n){if(!n)return super.toJSON(t);const a=new Map;n?.onCreate&&n.onCreate(a);for(const i of this.items){let r,s;if(Un(i)?(r=si(i.key,"",n),s=si(i.value,r,n)):r=si(i,"",n),a.has(r))throw new Error("Ordered maps must not include duplicate keys");a.set(r,s)}return a}static from(t,n,a){const i=XH(t,n,a),r=new this;return r.items=i.items,r}}$v.tag="tag:yaml.org,2002:omap";class Nv extends gs{constructor(t){super(t),this.tag=Nv.tag}add(t){let n;Un(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new oo(t.key,null):n=new oo(t,null),gr(this.items,n.key)||this.items.push(n)}get(t,n){const a=gr(this.items,t);return!n&&Un(a)?En(a.key)?a.key.value:a.key:a}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);const a=gr(this.items,t);a&&!n?this.items.splice(this.items.indexOf(a),1):!a&&n&&this.items.push(new oo(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,a){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,a);throw new Error("Set items must all have null values")}static from(t,n,a){const{replacer:i}=a,r=new this(t);if(n&&Symbol.iterator in Object(n))for(let s of n)typeof i=="function"&&(s=i.call(n,s,s)),r.items.push(Ov(s,null,a));return r}}Nv.tag="tag:yaml.org,2002:set";new Set("0123456789ABCDEFabcdef");new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");new Set(",[]{}");new Set(` ,[]{}
174
+ \r `);const Hu=o().min(1).max(2e3).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.startsWith("/")&&e.split("/").every(t=>t!==""&&t!=="."&&t!==".."),"source paths must be portable relative paths");o().regex(/^[a-z][a-z0-9_-]{0,119}$/);const eL={type:"object",properties:{},additionalProperties:!1};l({name:o().trim().min(1).max(240).optional(),description:o().max(4e3).optional(),skillPaths:p(Hu).max(100).optional(),assetPaths:p(Hu).max(100).optional()}).strict();l({actionId:o().trim().min(1).max(240),name:o().trim().min(1).max(240),description:o().max(4e3).default(""),inputSchema:ae(o(),ie()).default(eL),skillPaths:p(Hu).max(100).default([]),assetPaths:p(Hu).max(100).default([])}).strict();const J1=v(["openpond.lab"]),xc=l({id:o(),experience:Iv.default(UN),provider:ol,modelRef:bn.nullable().optional(),openPondCommandAccessMode:Kc.default(bm),systemKind:J1.nullable().optional(),hiddenFromDefaultSidebar:w().optional(),parentSessionId:o().nullable().optional(),parentTurnId:o().nullable().optional(),subagentRunId:o().nullable().optional(),subagentRoleId:il.nullable().optional(),subagentDelegationMode:hm.nullable().optional(),title:o(),appId:o().nullable(),appName:o().nullable(),workspaceKind:Wc.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:Ni.nullable().optional(),profileWorkflowBinding:TH.nullable().optional(),profileComponentBinding:EH.nullable().optional(),metadata:ae(o(),ie()).optional(),cwd:o().nullable(),codexThreadId:o().nullable(),createdAt:o(),updatedAt:o(),status:v(["idle","active","failed","closed"]),runtimeSeconds:d().int().nonnegative().optional(),runtimeRunningSince:o().nullable().optional(),pinned:w(),savedForLater:w().optional(),archived:w(),order:d()});l({id:o(),sessionId:o(),providerTurnId:o().nullable(),modelRef:bn.nullable().optional(),prompt:o(),startedAt:o(),completedAt:o().nullable(),status:v(["in_progress","completed","failed","interrupted"]),error:o().nullable(),metadata:ae(o(),ie()).optional().default({}),createImproveRun:Gc.nullable().optional().default(null),profileSnapshot:cD.nullable().optional(),harnessSnapshot:uD.nullable().optional()});const tL=l({id:o(),sessionId:o(),turnId:o().nullable(),providerRequestId:ht([o(),d()]),kind:v(["command","file_change","permissions","user_input","create_plan","subagent_patch_apply","legacy_exec","legacy_patch"]),title:o(),detail:o(),status:v(["pending","accepted","accepted_for_session","declined","cancelled"]),createdAt:o()}),nL=l({key:v(["files","diffs","checks","deploys","sources","schedules","tool_runs","logs","app_config"]),label:o(),status:v(["placeholder","available","error"]),summary:o()}),Z1=l({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:ht([o().trim().max(191),ae(o(),ie())]).optional().nullable(),outputSchema:ht([o().trim().max(191),ae(o(),ie())]).optional().nullable(),approvalPolicy:ae(o(),ie()).optional().nullable(),artifactPolicy:ae(o(),ie()).optional().nullable(),setupRequirements:p(ae(o(),ie())).optional(),mcp:ae(o(),ie()).optional().nullable(),schedulePolicy:ae(o(),ie()).optional().nullable(),trace:ae(o(),ie()).optional().nullable(),implementation:ae(o(),ie()).optional().nullable(),invokesModel:w().optional()}),aL=l({command:v(["inspect","build","validate","eval","traces","run"]),status:v(["passed","failed"]),checkedAt:o(),exitCode:d().nullable().optional(),sourceHead:o().nullable().optional()}),iL=l({id:o(),name:o(),path:o(),enabled:w()}),oL=l({name:o(),description:o(),path:o(),scope:b("profile"),enabled:w(),sourcePath:o(),charCount:d(),sourceHash:o(),validationStatus:v(["valid","warning","error"]),validationMessages:p(o()),resourceFiles:p(o()).optional().default([])}),rL=l({id:o(),name:o(),path:o(),agentId:o().nullable(),sourcePath:o()}),Y1=l({path:o(),originalPath:o().nullable().optional(),indexStatus:o().nullable(),worktreeStatus:o().nullable(),status:o(),category:v(["added","modified","deleted","renamed","untracked","changed"])}),sL=l({isRepo:w(),branch:o().nullable(),head:o().nullable(),shortHead:o().nullable(),dirty:w(),upstream:o().nullable(),ahead:d().nullable(),behind:d().nullable(),remoteUrl:o().nullable(),files:p(Y1),fileCount:d().int().nonnegative().optional(),error:o().nullable()}),lL=l({actionCount:d(),generatedAt:o().nullable(),manifestPath:o().nullable(),registryPath:o().nullable(),stale:w(),error:o().nullable()}),cL=l({skillCount:d(),generatedAt:o().nullable(),stale:w(),error:o().nullable()}),V0=l({ref:o(),source:v(["action_catalog","source_upload_metadata"]),actionId:o().nullable(),kind:o().nullable(),label:o(),status:o(),required:w(),blocking:w()}),dL=l({status:v(["ready","setup_required","blocked"]),requirementCount:d(),blockingCount:d(),optionalMissingCount:d(),readyCount:d(),requirements:p(V0),blockingRequirements:p(V0)}),uL=l({changedAgents:p(o()),newAgents:p(o()),deletedAgents:p(o()),changedSkills:p(o()).optional().default([]),changedActions:p(o()),changedExtensions:p(o()),setupChanges:p(o()),envRequirementChanges:p(o()),files:p(Y1),fileCount:d().int().nonnegative().optional()}),mL=l({status:o(),agentId:o().nullable().optional(),deployPlanStatus:o().nullable().optional(),canRun:w().nullable().optional(),canDeploy:w().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),manifestPath:o().nullable().optional(),setupCommands:p(o()).optional(),validationCommands:p(o()).optional(),requiredChecks:p(o()).optional(),evalNames:p(o()).optional(),blockedReasons:p(o()).optional(),staleReasons:p(o()).optional(),runtimeId:o().nullable().optional(),sandboxId:o().nullable().optional(),traceArtifactRefs:p(o()).optional(),evalResultArtifactRefs:p(o()).optional(),validatorArtifactRefs:p(o()).optional(),checkedAt:o().nullable().optional(),error:o().nullable().optional()}),pL=l({status:o(),agentId:o().nullable().optional(),runtimeAgentId:o().nullable().optional(),projectId:o().nullable().optional(),sourceRoot:o().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),manifestPath:o().nullable().optional(),manifestSyncedAt:o().nullable().optional(),fileCount:d().nullable().optional(),totalBytes:d().nullable().optional(),generatedManifestPath:o().nullable().optional(),synthesizedOpenPondYaml:w().nullable().optional(),uploadMetadataPath:o().nullable().optional(),setupCommands:p(o()).optional(),validationCommands:p(o()).optional(),materializedAt:o().nullable().optional(),error:o().nullable().optional()}),fL=l({status:o(),agentId:o().nullable().optional(),snapshotId:o().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),manifestPath:o().nullable().optional(),buildStatus:o().nullable().optional(),validationStatus:o().nullable().optional(),evalStatus:o().nullable().optional(),publishedAt:o().nullable().optional(),error:o().nullable().optional()}),hL=l({status:o(),agentId:o().nullable().optional(),runId:o().nullable().optional(),runtimeId:o().nullable().optional(),sandboxId:o().nullable().optional(),sourceRef:o().nullable().optional(),sourceCommitSha:o().nullable().optional(),manifestHash:o().nullable().optional(),setupGateStatus:o().nullable().optional(),setupRequirementRefs:p(o()).optional(),artifactRefs:p(o()).optional(),traceArtifactRefs:p(o()).optional(),evalArtifactRefs:p(o()).optional(),startedAt:o().nullable().optional(),completedAt:o().nullable().optional(),error:o().nullable().optional()}),gL=l({teamId:o().nullable(),projectId:o().nullable(),sourceRef:o().nullable(),sourceCommitSha:o().nullable(),lastPushedAt:o().nullable(),lastPushedLocalHead:o().nullable(),lastPushedHostedHead:o().nullable(),promotionStatus:o().nullable().optional().default(null),hostedRunStatus:o().nullable().optional().default(null),hostedRunAgentId:o().nullable().optional().default(null),hostedRunId:o().nullable().optional().default(null),hostedRunAt:o().nullable().optional().default(null),hostedSourceMaterialization:pL.nullable().optional().default(null),hostedSourceCheck:mL.nullable().optional().default(null),hostedPublish:fL.nullable().optional().default(null),hostedRun:hL.nullable().optional().default(null)}),vL=l({state:v(["none","ready","dirty","pending_commit","error"]),message:o(),agentCount:d(),actionCount:d(),defaultAction:o().nullable(),checkFresh:w(),checkStaleReason:o().nullable(),localHead:o().nullable(),hostedHead:o().nullable()}),Q1=l({mode:v(["none","local"]),repoPath:o().nullable(),activeProfile:o().nullable(),sourcePath:o().nullable(),manifestPath:o().nullable(),agents:p(iL),skills:p(oL).optional().default([]),evals:p(rL).optional().default([]),git:sL.nullable(),catalog:lL,skillCatalog:cL.optional().default({skillCount:0,generatedAt:null,stale:!0,error:null}),actionCatalog:p(Z1),sourceSetupRequirements:p(ae(o(),ie())),setupGate:dL,diff:uL,hosted:gL.nullable(),summary:vL,lastCheck:aL.nullable(),error:o().nullable()}),bL=l({ref:Ni,name:o(),repoPath:o(),sourcePath:o().nullable(),state:Q1}),yL=l({lastUsed:Ni.nullable(),profiles:p(bL)});function SL(){return{lastUsed:null,profiles:[]}}function xL(){return{mode:"none",repoPath:null,activeProfile:null,sourcePath:null,manifestPath:null,agents:[],skills:[],evals:[],git:null,catalog:{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!0,error:null},skillCatalog:{skillCount:0,generatedAt:null,stale:!0,error:null},actionCatalog:[],sourceSetupRequirements:[],setupGate:{status:"ready",requirementCount:0,blockingCount:0,optionalMissingCount:0,readyCount:0,requirements:[],blockingRequirements:[]},diff:{changedAgents:[],newAgents:[],deletedAgents:[],changedSkills:[],changedActions:[],changedExtensions:[],setupChanges:[],envRequirementChanges:[],files:[]},hosted:null,summary:{state:"none",message:"No active OpenPond profile.",agentCount:0,actionCount:0,defaultAction:null,checkFresh:!1,checkStaleReason:"No active profile.",localHead:null,hostedHead:null},lastCheck:null,error:null}}const kL=l({name:o(),description:o(),path:o(),sourcePath:o(),enabled:w(),charCount:d().int().nonnegative(),sourceHash:o(),validationStatus:v(["valid","error"]),validationMessages:p(o()),resourceFiles:p(o()),updatedAt:o().nullable()}),IL=v(["codex","profile","extension"]);l({skillName:o(),scope:IL,path:o(),byteSize:d().int().nonnegative(),isBinary:w(),content:o().nullable()});const wL=[{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"]}],_L=l({name:o(),description:o(),relativePath:o(),sourcePath:o(),charCount:d().int().nonnegative(),sourceHash:o(),resourceFiles:p(o()),validationStatus:v(["valid","error"]),validationMessages:p(o())}),X1=l({id:o(),source:b("github"),owner:o(),repo:o(),repositoryUrl:o().url(),requestedRef:o(),resolvedCommit:o(),sourcePath:o(),readmePath:o().nullable(),installedAt:o(),updatedAt:o(),packageHash:o(),skills:p(_L),validationStatus:v(["valid","error"]),validationMessages:p(o())});X1.omit({installedAt:!0,updatedAt:!0,sourcePath:!0}).extend({sourcePath:al()});const CL=l({rootPath:o(),registryPath:o(),extensions:p(X1),error:o().nullable()});l({source:o().trim().min(1),ref:o().trim().min(1).optional()});const RL=l({latestSequence:d().int().nonnegative(),oldestSequence:d().int().nonnegative(),totalEvents:d().int().nonnegative(),limit:d().int().nonnegative(),hasMoreBefore:w()});l({server:qN,account:TN,codex:EN,configuration:l({rawRevision:o(),effectiveRevision:o(),sources:p(l({layer:o(),path:o(),revision:o()})),provenance:ae(o(),l({layer:o(),path:o(),revision:o()}))}).optional(),preferences:N0.optional().default(()=>N0.parse({})),providers:i0.optional().default(()=>i0.parse({})),personalization:D0.optional().default(()=>D0.parse({soul:f1[0].content,soulPath:null,updatedAt:null})),apps:p(L$),localProjects:p(F$).optional().default([]),cloudProjects:p(B$).optional().default([]),profile:Q1.optional().default(xL),profileLibrary:yL.optional().default(SL),codexPersonalSkills:p(kL).optional().default([]),extensionCatalog:CL.optional().default({rootPath:"",registryPath:"",extensions:[],error:null}),codexHistorySessions:p(xc).optional().default([]),sidebarAppPreferences:IN,sidebarFileBookmarks:p(m1).optional().default([]),appsError:o().nullable(),appsMeta:$0,accountMeta:$0,sessions:p(xc),events:p(o0),eventWindow:RL.optional(),approvals:p(tL),placeholders:p(nL),diagnostics:p(o0)});const Dv=v(["openpond_hosted","local_byok","codex_app_server","unknown"]),ew=v(["provider_usage","codex_context_usage","missing"]),PL=v(["provider_usage_body","provider_response_headers"]),AL=v(["chat_turn","tool_loop","slash_command","create_improve_planner","harness_refiner","context_compaction","subagent","codex_context","other"]),TL=v(["foreground","tool_loop","compaction","subagent","refiner","other"]),tw=v(["user_facing","background","system"]),nw=v(["started","completed","failed","interrupted"]),Hv=v(["composer_selection","prompt_parse","server_parser","model_tool","api"]),aw=v(["chat","settings","goal","create_improve","compaction","system"]),iw=v(["direct_chat","tool_loop","slash_command","planner","summary","scan","subagent","other"]),EL=l({surface:aw,workflowKind:iw,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:Hv.nullable().default(null),appId:o().trim().min(1).nullable().default(null),workspaceKind:Wc.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:d().int().nonnegative().nullable().default(null)}),ML=l({surface:aw.optional(),workflowKind:iw.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:Hv.nullable().optional()}).strict(),Or=o().trim().min(1).max(160),jL=l({id:o().trim().min(1),requestId:o().trim().min(1),requestOrdinal:d().int().nonnegative(),sessionId:o().trim().min(1).nullable(),turnId:o().trim().min(1).nullable(),provider:Or,model:o().trim().min(1),route:Dv,source:ew,requestKind:AL,visibility:tw,status:nw,startedAt:o().trim().min(1),completedAt:o().trim().min(1).nullable(),durationMs:d().int().nonnegative().nullable(),firstTokenMs:d().int().nonnegative().nullable(),promptTokens:d().int().nonnegative().nullable(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheTelemetrySource:PL.nullable(),completionTokens:d().int().nonnegative().nullable(),totalTokens:d().int().nonnegative().nullable(),errorType:o().trim().min(1).max(160).nullable(),errorMessage:o().trim().min(1).max(2e3).nullable(),attribution:EL}),ow=l({from:o().trim().min(1),to:o().trim().min(1),bucket:v(["day","all_time"])}),Lv=ht([b("all"),tw]),qv=v(["all","started","completed","failed","interrupted","missing"]),OL=l({range:v(["7d","30d","90d","all"]).default("30d"),visibility:Lv.default("all"),status:qv.default("all"),provider:Or.optional(),model:o().trim().min(1).optional()});OL.extend({sessionId:o().trim().min(1).optional(),turnId:o().trim().min(1).optional(),limit:d().int().positive().max(500).default(100)});l({sessionId:o().trim().min(1)});const $r=l({requests:d().int().nonnegative(),promptTokens:d().int().nonnegative().nullable(),cacheTelemetryRequests:d().int().nonnegative(),cacheHitRequests:d().int().nonnegative(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheHitRate:d().min(0).max(1).nullable(),cacheRequestHitRate:d().min(0).max(1).nullable(),cacheTelemetryCoverage:d().min(0).max(1),completionTokens:d().int().nonnegative().nullable(),totalTokens:d().int().nonnegative().nullable(),averageLatencyMs:d().nonnegative().nullable(),p95LatencyMs:d().nonnegative().nullable(),averageFirstTokenMs:d().nonnegative().nullable(),p95FirstTokenMs:d().nonnegative().nullable(),failures:d().int().nonnegative(),failureRate:d().nonnegative(),firstSeenAt:o().trim().min(1),lastSeenAt:o().trim().min(1)}),$L=$r.extend({provider:Or,model:o().trim().min(1),route:Dv}),NL=$r.extend({sessionId:o().trim().min(1),title:o().trim().min(1).nullable(),workspaceKind:Wc.nullable(),workspaceId:o().trim().min(1).nullable()}),DL=$r.extend({commandName:o().trim().min(1),commandSource:Hv.nullable()}),HL=$r.extend({route:Dv}),LL=$r.extend({status:nw}),qL=$r.extend({source:ew}),UL=$r.extend({cohort:TL}),zL=l({date:o().trim().min(1),totalTokens:d().int().nonnegative(),requests:d().int().nonnegative(),models:p(l({provider:Or,model:o().trim().min(1),totalTokens:d().int().nonnegative(),requests:d().int().nonnegative()}))}),BL=l({requests:d().int().nonnegative(),completedRequests:d().int().nonnegative(),failedRequests:d().int().nonnegative(),missingUsageRequests:d().int().nonnegative(),promptTokens:d().int().nonnegative().nullable(),cacheTelemetryRequests:d().int().nonnegative(),cacheHitRequests:d().int().nonnegative(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheHitRate:d().min(0).max(1).nullable(),cacheRequestHitRate:d().min(0).max(1).nullable(),cacheTelemetryCoverage:d().min(0).max(1),completionTokens:d().int().nonnegative().nullable(),totalTokens:d().int().nonnegative().nullable(),averageLatencyMs:d().nonnegative().nullable(),p95LatencyMs:d().nonnegative().nullable(),averageFirstTokenMs:d().nonnegative().nullable(),p95FirstTokenMs:d().nonnegative().nullable(),failureRate:d().nonnegative(),activeModelCount:d().int().nonnegative(),peakDailyTokens:d().int().nonnegative(),longestRequestMs:d().int().nonnegative().nullable(),activeDays:d().int().nonnegative(),currentStreakDays:d().int().nonnegative(),longestStreakDays:d().int().nonnegative()});l({generatedAt:o().trim().min(1),range:ow,filters:l({visibility:Lv,status:qv,provider:Or.nullable(),model:o().trim().min(1).nullable()}),totals:BL,daily:p(zL),models:p($L),threads:p(NL),commands:p(DL),routes:p(HL),statuses:p(LL),sources:p(qL),cohorts:p(UL)});l({generatedAt:o().trim().min(1),range:ow,filters:l({visibility:Lv,status:qv,provider:Or.nullable(),model:o().trim().min(1).nullable(),sessionId:o().trim().min(1).nullable(),turnId:o().trim().min(1).nullable()}),limit:d().int().positive(),hasMore:w(),records:p(jL)});const FL=l({turnId:o().trim().min(1),requests:d().int().nonnegative(),cacheTelemetryRequests:d().int().nonnegative(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheHitRate:d().min(0).max(1).nullable(),cacheTelemetryCoverage:d().min(0).max(1),providers:p(Or)});l({generatedAt:o().trim().min(1),sessionId:o().trim().min(1),turns:p(FL)});const VL=v(["usage_spike","model_usage_spike","latency_regression","failure_cluster","missing_usage_frames"]);l({type:VL,title:o().trim().min(1),summary:o().trim().min(1),severity:v(["nit","concern","blocker"]),payload:ae(o(),ie()).default({})});const KL=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),WL=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),GL=v(["native_bot","oauth_connector","wallet_connector","mcp_endpoint"]),JL=l({kind:b("integration"),provider:KL,appIds:p(WL).min(1).max(4),setupSurfaces:p(GL).min(1).max(4),connectionIds:p(o().trim().min(1)).max(8).optional(),capabilities:p(o().trim().min(1)).max(64).optional()}).strict(),vr={maxAttachments:10,maxAttachmentBytes:12*1024*1024,maxAttachmentBase64Chars:Math.ceil(12*1024*1024*4/3)+16,maxTextChars:2e5},ZL=v(["image","text","file"]),YL=l({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)}),QL=l({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)}),rw=l({id:o().trim().min(1),name:o().trim().min(1).max(240),mediaType:o().trim().min(1).max(160),sizeBytes:d().int().nonnegative().max(vr.maxAttachmentBytes),kind:ZL,lineCount:d().int().nonnegative().max(vr.maxAttachmentBytes+1).optional(),relativePath:o().trim().min(1).max(1024).optional(),text:o().max(vr.maxTextChars).optional(),contentsBase64:o().max(vr.maxAttachmentBase64Chars).optional()}),XL=rw.omit({text:!0,contentsBase64:!0}).extend({imagePreview:YL.optional(),filePreview:QL.optional()});l({experience:Iv.optional(),provider:ol.default(_r),modelRef:bn.optional(),openPondCommandAccessMode:Kc.optional(),systemKind:J1.nullable().optional(),hiddenFromDefaultSidebar:w().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:il.nullable().optional(),subagentDelegationMode:hm.nullable().optional(),appId:o().nullable().optional(),appName:o().nullable().optional(),workspaceKind:Wc.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:Ni.nullable().optional(),profileWorkflowBinding:xc.shape.profileWorkflowBinding,profileComponentBinding:xc.shape.profileComponentBinding,metadata:ae(o(),ie()).optional(),cwd:o().nullable().optional(),title:o().optional(),autoTitlePrompt:o().trim().min(1).max(2e4).optional()});l({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()});l({branch:o().trim().min(1).max(120).optional()});l({prompt:o().min(1),workflowInput:ie().optional(),metadata:ae(o(),ie()).optional(),usageAttribution:ML.optional().nullable(),cwd:o().nullable().optional(),model:o().nullable().optional(),modelRef:bn.optional(),mentionedAppIds:p(o().trim().min(1)).max(8).optional(),mentionedConnectedApps:p(JL).max(8).optional(),openPondActionCatalog:p(Z1).max(100).optional(),attachments:p(rw).max(vr.maxAttachments).optional(),createImproveRun:Gc.optional().nullable(),approvalPolicy:v(["untrusted","on-failure","on-request","never"]).default("on-request"),sandbox:v(["read-only","workspace-write","danger-full-access"]).default("workspace-write"),codexPermissionMode:xv.default("default"),codexReasoningEffort:ym.optional()});l({prompt:o().min(1),error:o().min(1),target:v(["cloud_workspace","hybrid_sandbox"])});l({reason:v(["manual"]).default("manual"),model:o().nullable().optional(),modelRef:bn.optional()});l({experience:Iv.optional(),provider:ol.optional(),modelRef:bn.nullable().optional(),openPondCommandAccessMode:Kc.optional(),pinned:w().optional(),savedForLater:w().optional(),archived:w().optional(),order:d().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:il.nullable().optional(),subagentDelegationMode:hm.nullable().optional(),appId:o().nullable().optional(),appName:o().nullable().optional(),workspaceKind:Wc.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:Ni.nullable().optional(),metadata:ae(o(),ie()).optional(),cwd:o().nullable().optional()});l({command:o().trim().min(1),cwd:o().trim().min(1).max(4096).nullable().optional(),timeoutSeconds:d().int().min(1).max(3600).optional()});l({appIds:p(o()).min(1)});l({expectedRevision:o().optional(),defaultChatProvider:ol.optional(),defaultChatModel:o().min(1).optional(),defaultChatModelRef:bn.nullable().optional(),subagents:gc.optional(),codexPermissionMode:xv.optional(),codexReasoningEffort:ym.optional(),openPondCommandAccessMode:Kc.optional(),defaultBranchPrefix:o().trim().max(48).optional(),defaultNewProjectDirectory:o().trim().max(4096).optional(),defaultTeamId:o().trim().max(191).nullable().optional(),advancedWorkspaceControls:w().optional(),steerActiveResponses:w().optional(),contextCompaction:Qh.optional(),training:Xh.optional(),sidebarWidth:d().int().min(244).max(560).optional(),diffPanelWidth:d().int().min(320).max(2400).optional(),sidebarSectionsCollapsed:Yh.optional(),editor:Ou.optional()});l({message:o().trim().min(1).max(4e3),surface:o().trim().min(1).max(120).default("app"),stack:o().max(12e3).nullable().optional(),context:ae(o(),ie()).optional()}).strict();l({activeTemplateId:kv,templateName:o().trim().min(1).max(80),soul:o().trim().min(1).max(8e3),saveAsNew:w().optional().default(!1)});l({decision:v(["accept","acceptForSession","decline","cancel"])});l({branch:o().trim().min(1).max(240).nullable().optional(),surface:v(["desktop","terminal"])});l({handle:o().min(1),baseUrl:o().nullable().optional()});l({handle:o().min(1),baseUrl:o().nullable().optional()});l({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:w().optional()});l({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:w().optional()});l({appId:o(),exists:w(),configPath:o().nullable().optional(),envVar:o().nullable(),toolName:o().nullable(),version:ht([o(),d()]).nullable(),source:v(["hosted_env","local_file","defaults","missing"]),currentConfig:ae(o(),ie()).nullable(),defaults:ae(o(),ie()).nullable(),schema:ae(o(),ie()).nullable(),error:o().nullable().optional(),updatedAt:o()}).passthrough();const Lu=v(["create_sandbox_template_scaffold","resource_read","resource_search","list_files","read_files","search_files","preview_write_files","preview_write_file","preview_edit_file","preview_delete_file","write_files","write_file","edit_file","delete_file","workspace_status","validate_sandbox_template","build_sandbox_template","run_sandbox_template","git_init","git_status","git_diff","git_fetch","git_commit","git_push","publish_openpond_repo","sandbox_create","sandbox_templates","sandbox_template_launch","sandbox_status","sandbox_start","sandbox_list_files","sandbox_read_file","sandbox_search_files","sandbox_upload_file","sandbox_write_file","sandbox_edit_file","sandbox_delete_file","sandbox_mkdir","sandbox_move_file","sandbox_exec","sandbox_git_status","sandbox_git_diff","sandbox_git_export_patch","sandbox_git_apply_patch_local","sandbox_git_branch","sandbox_git_commit","sandbox_git_pull","sandbox_git_push","sandbox_preserve_source","sandbox_promote_source","sandbox_run_action","sandbox_open_port","sandbox_snapshot_catalog","sandbox_snapshot_create","sandbox_snapshot_update","sandbox_snapshot_validate","sandbox_snapshot_publish","sandbox_replays","sandbox_replay_start","sandbox_replay_get","sandbox_replay_logs","sandbox_replay_artifacts","sandbox_replay_cancel","sandbox_logs","sandbox_receipts","sandbox_prepare_agent","sandbox_save_agent_package","sandbox_save_output","work_agent_package_install","work_output_delete","work_output_read","sandbox_schedule_create","sandbox_stop"]);l({action:Lu,args:ae(o(),ie()).optional().default({}),source:v(["ui_button","chat_action","terminal_command","hook"]).default("chat_action")});l({ok:w(),action:Lu,appId:o().nullable().optional(),output:o(),data:ie().optional()});const Qc=l({id:o().trim().min(1).max(200),title:o().trim().min(1).max(240),sourceTaskId:o().trim().min(1).max(200),sourceTurnId:o().trim().min(1).max(200),revision:d().int().positive().default(1),createdAt:o().datetime()}),Xc=l({kind:v(["structural","visual","test","user_review"]),status:v(["passed","failed","not_run"]),label:o().trim().min(1).max(240),detail:o().trim().max(4e3).nullable().optional(),ref:o().trim().max(4096).nullable().optional()}),sw=l({kind:b("local"),path:o().trim().min(1).max(4096),deviceId:o().trim().min(1).max(200)}),lw=l({kind:b("managed"),fileId:o().trim().min(1).max(200),downloadPath:o().trim().min(1).max(4096)}),eq=l({kind:b("external"),provider:o().trim().min(1).max(120),resourceId:o().trim().min(1).max(500),url:o().url().nullable()}),cw=Qc.extend({kind:b("file"),contentType:o().trim().min(1).max(200),sizeBytes:d().int().nonnegative(),sha256:o().regex(/^[a-f0-9]{64}$/),location:lt("kind",[sw,lw,eq]),validation:p(Xc).max(32).default([])}),tq=Qc.extend({kind:b("source_change"),projectId:o().trim().min(1).max(200),ref:o().trim().min(1).max(500),url:o().url().nullable(),validation:p(Xc).max(32).default([])}),nq=Qc.extend({kind:b("deployment"),deploymentId:o().trim().min(1).max(200),url:o().url(),validation:p(Xc).max(32).default([])}),aq=Qc.extend({kind:b("external_resource"),provider:o().trim().min(1).max(120),resourceId:o().trim().min(1).max(500),url:o().url(),contentType:o().trim().min(1).max(200).nullable(),validation:p(Xc).max(32).default([])}),dw=l({id:o().trim().min(1).max(191),label:o().trim().min(1).max(160).nullable(),description:o().trim().max(1e3).nullable(),inputSchema:ae(o(),ie()).nullable(),outputSchema:ae(o(),ie()).nullable(),schedulePolicy:ae(o(),ie()).nullable()}),uw=l({base:o().trim().min(1).max(200),resources:ae(o(),ie()),modelPolicy:ae(o(),ie()).nullable(),setup:ae(o(),ie()).nullable()}),iq=l({id:o().trim().min(1).max(200),kind:v(["sdk_validation","sdk_eval"]),status:v(["passed","failed"]),summary:o().trim().min(1).max(2e3),artifactPath:o().trim().min(1).max(4096),artifactSha256:o().regex(/^[a-f0-9]{64}$/)}),oq=l({path:o().trim().min(1).max(4096),sizeBytes:d().int().nonnegative(),sha256:o().regex(/^[a-f0-9]{64}$/),contentsBase64:o()});l({schema:b("openpond.agent-package.v1"),agentId:o().trim().min(1).max(191),versionId:o().trim().min(1).max(200),digest:o().regex(/^[a-f0-9]{64}$/),title:o().trim().min(1).max(240),source:l({files:p(oq).min(1).max(1e3),totalSizeBytes:d().int().nonnegative()}),manifest:ae(o(),ie()),actions:p(dw).min(1).max(256),runtimeRequirements:uw,receipts:p(iq).min(2).max(64)});const rq=Qc.extend({kind:b("agent_package"),agentId:o().trim().min(1).max(191),versionId:o().trim().min(1).max(200),digest:o().regex(/^[a-f0-9]{64}$/),packageFileId:o().trim().min(1).max(200),manifestFileId:o().trim().min(1).max(200),actions:p(dw).min(1).max(256),runtimeRequirements:uw,validationReceiptIds:p(o().trim().min(1).max(200)).min(1).max(32),evalReceiptIds:p(o().trim().min(1).max(200)).min(1).max(32),sourceFileCount:d().int().positive(),sourceSizeBytes:d().int().nonnegative(),location:lt("kind",[sw,lw]),validation:p(Xc).max(32).default([])}),qne=lt("kind",[cw,tq,nq,aq,rq]);l({outputs:p(cw)});const sq=v(["sandbox_template","sandbox","generic_git","plain_folder"]),lq=v(["sandbox_template"]).nullable();l({productKind:sq,actions:l({files:w(),git:w(),sandboxRuntime:w(),sandboxTemplate:w()}),checks:l({validate:Lu.nullable(),build:Lu.nullable(),postEdit:lq}),ui:l({showSandboxTemplateActions:w(),showSandboxRuntimeActions:w()})});const cq=l({id:o(),name:o(),dnsName:o().nullable(),os:o().nullable(),online:w(),active:w(),isSelf:w(),tailscaleIps:p(o()),lastSeen:o().nullable()}),dq=l({installed:w(),running:w(),version:o().nullable(),backendState:o().nullable(),tailnetName:o().nullable(),magicDnsSuffix:o().nullable(),machineName:o().nullable(),dnsName:o().nullable(),authUrl:o().nullable(),tailscaleIps:p(o()),health:p(o()),error:o().nullable(),peers:p(cq)}),uq=l({enabled:w(),reachable:w(),targetUrl:o().nullable(),httpsUrl:o().nullable(),httpsHost:o().nullable(),httpsPort:d().nullable(),setupUrl:o().nullable(),configText:o().nullable(),error:o().nullable()}),mq=l({localUrl:o(),localWebUrl:o(),remoteUrl:o().nullable(),remoteWebUrl:o().nullable(),tokenHash:o(),tailscaleUpCommand:o(),serveCommand:o(),disableCommand:o(),operatorCommand:o(),webUiAvailable:w(),updatedAt:o(),tailscale:dq,serve:uq});l({message:o(),status:mq});const mw=v(["github","openpond_git"]),pw=v(["private","public"]),pq=v(["actions","workflows","instructions","prompts","goals","evals","examples","tasksets","extensions"]),fq=l({agentIds:p(o().trim().min(1)).max(100),skillNames:p(o().trim().min(1)).max(200),optionalContent:p(pq).max(20).default([])}),fw=l({provider:mw,owner:o().trim().min(1).max(191).nullable().optional(),repository:o().trim().min(1).max(191),visibility:pw.default("private")}),hq=l({ref:Ni,selection:fq,target:fw}),gq=l({path:o(),sizeBytes:d().int().nonnegative(),category:o()});l({sourceHash:o(),sourceRevision:o().nullable(),clean:w(),blockedReasons:p(o()),warnings:p(o()),files:p(gq),excludedFiles:p(o()),target:fw,replacesExisting:w()});hq.extend({expectedSourceHash:o().trim().min(1),confirmed:b(!0)});l({provider:mw,owner:o(),repository:o(),visibility:pw,remoteUrl:o(),webUrl:o(),revision:o()});const vq=v(["cron","rate"]),hw=v(["queued","running","succeeded","failed","skipped"]),Uv=l({id:o(),localProjectId:o(),localProjectName:o(),agentRootPath:o(),agentName:o(),scheduleName:o(),scheduleType:vq,scheduleExpression:o(),timezone:o().nullable(),targetAction:o(),input:ae(o(),ie()).optional().default({}),enabledByDefault:w(),enabled:w(),sourceHash:o(),manifestHash:o().nullable(),agentVersionId:o().nullable().optional(),agentPackageDigest:o().nullable().optional(),nextRunAt:o().nullable(),lastRunAt:o().nullable(),lastRunStatus:hw.nullable(),lastRunId:o().nullable(),lastError:o().nullable(),createdAt:o(),updatedAt:o()}),gw=l({id:o(),scheduleId:o(),definitionSnapshot:Uv.optional(),configurationSnapshot:ae(o(),ie()).optional(),inputSnapshot:ae(o(),ie()).optional(),localProjectId:o(),scheduleName:o(),scheduledFor:o(),trigger:v(["schedule","manual"]),status:hw,targetAction:o(),agentVersionId:o().nullable().optional(),agentPackageDigest:o().nullable().optional(),startedAt:o().nullable(),completedAt:o().nullable(),exitCode:d().int().nullable(),stdout:o().nullable(),stderr:o().nullable(),result:ae(o(),ie()).nullable(),traceArtifactRef:o().nullable(),error:o().nullable(),createdAt:o(),updatedAt:o()});l({schedules:p(Uv),scheduler:l({running:w(),nextTickAt:o().nullable(),lastSyncAt:o().nullable(),scanRunning:w()})});l({runs:p(gw)});l({enabled:w().optional()});l({input:ae(o(),ie()).optional()});l({schedule:Uv,run:gw});const bq=v(["sunday","monday","tuesday","wednesday","thursday","friday","saturday"]),ll=l({version:b(1),kind:v(["once","daily","weekdays","weekly","monthly"]),timeZone:o().trim().min(1).max(100),startDate:o().regex(/^\d{4}-\d{2}-\d{2}$/),localTime:o().regex(/^([01]\d|2[0-3]):([0-5]\d)$/),weekdays:p(bq).min(1).max(7).optional(),dayOfMonth:d().int().min(1).max(31).optional(),end:lt("kind",[l({kind:b("never")}),l({kind:b("on_date"),date:o().regex(/^\d{4}-\d{2}-\d{2}$/)}),l({kind:b("after_occurrences"),occurrences:d().int().min(1).max(1e5)})])}).superRefine((e,t)=>{e.kind==="weekly"&&!e.weekdays?.length&&t.addIssue({code:"custom",message:"Weekly recurrence requires at least one weekday.",path:["weekdays"]}),e.kind==="monthly"&&e.dayOfMonth===void 0&&t.addIssue({code:"custom",message:"Monthly recurrence requires a day of month.",path:["dayOfMonth"]})}),yq=l({id:o(),expression:o().nullable(),timeZone:o(),recurrence:ll.nullable(),configurationVersion:d().int(),enabled:w(),nextRunAt:o().nullable(),lastTriggeredAt:o().nullable(),delivery:ae(o(),ie()).default({})}),Sq=l({id:o(),definitionKey:o(),version:d().int(),name:o(),prompt:o(),modelId:o(),schedules:p(yq)}),xq=l({id:o(),definitionId:o(),scheduleId:o().nullable(),definitionName:o(),definitionVersion:d().int(),conversationId:o(),triggerKind:v(["manual","schedule","webhook","retry"]),status:o(),notificationStatus:o(),deliveryStatus:o(),deliveryError:o().nullable(),createdAt:o()});l({definitions:p(Sq),runs:p(xq),asOf:o(),webBaseUrl:o().url().optional()});l({clientRequestId:o().trim().min(1).max(191),sourceTurnId:o().trim().min(1).max(191).nullable().optional(),targetSessionId:o().trim().min(1).max(191).nullable().optional(),name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:ll,modelId:o().trim().min(1).max(191).default("openpond-chat")});ht([l({enabled:w()}),l({name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:ll})]);const vw=v(["queued","running","succeeded","failed"]),bw=l({id:o(),sessionId:o(),sessionTitle:o(),sourceTurnId:o().nullable(),name:o(),prompt:o(),profileRef:Ni.optional(),profileWorkflowId:o().optional(),profileMigrationError:o().nullable().optional(),recurrence:ll,enabled:w(),nextRunAt:o().nullable(),lastRunAt:o().nullable(),lastRunStatus:vw.nullable(),lastRunId:o().nullable(),lastError:o().nullable(),scheduledRunCount:d().int().nonnegative(),createdAt:o(),updatedAt:o()}),kq=l({definitionSnapshot:bw.optional(),configurationSnapshot:ae(o(),ie()).optional(),id:o(),workflowId:o(),sessionId:o(),scheduledFor:o(),trigger:v(["schedule","manual"]),status:vw,turnId:o().nullable(),error:o().nullable(),createdAt:o(),startedAt:o().nullable(),completedAt:o().nullable(),updatedAt:o()});l({sessionId:o().trim().min(1).max(191),sourceTurnId:o().trim().min(1).max(191).nullable().optional(),name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:ll});ht([l({enabled:w()}),l({name:o().trim().min(1).max(180),prompt:o().trim().min(1).max(2e4),recurrence:ll})]);l({workflows:p(bw),runs:p(kq),asOf:o()});const zv=ae(o(),ie());l({userId:o(),role:v(["owner","admin","member"]),name:o(),handle:o().nullable(),image:o().nullable()});const Iq=l({userId:o(),role:v(["owner","admin","member"]),name:o(),handle:o().nullable(),image:o().nullable(),lastReadSequence:d().int().nonnegative()}),wq=l({id:o(),messageId:o(),refType:v(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:o(),preview:zv,createdAt:o()}),yw=l({id:o(),messageId:o().nullable(),clientAttachmentId:o(),kind:b("image"),name:o(),mediaType:v(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:d().int().positive(),status:v(["pending","ready","failed"]),createdAt:o(),readyAt:o().nullable()});l({attachment:yw,uploadUrl:o().url().nullable(),uploadHeaders:ae(o(),o()),expiresAt:o().nullable()});l({url:o().url(),expiresAt:o()});const Bv=l({id:o(),threadId:o(),teamId:o(),clientRequestId:o().nullable(),authorType:v(["user","agent","system"]),authorUserId:o().nullable(),authorAgentId:o().nullable(),sequence:d().int().nonnegative(),kind:v(["text","system","command_result"]),body:o(),metadata:zv,editedAt:o().nullable(),deletedAt:o().nullable(),createdAt:o(),refs:p(wq),attachments:p(yw)}),_q=l({id:o(),teamId:o(),kind:v(["general","dm","group","channel"]),title:o().nullable(),createdByUserId:o(),lastMessageId:o().nullable(),lastMessageSequence:d().int().nonnegative(),lastMessageAt:o(),createdAt:o(),updatedAt:o(),unreadCount:d().int().nonnegative(),pinnedAt:o().nullable(),mutedAt:o().nullable(),archivedAt:o().nullable(),participants:p(Iq),lastMessage:Bv.nullable()});l({thread:_q,messages:p(Bv),hasMoreBefore:w()});l({threadId:o(),mutedAt:o().nullable()});const Cq=v(["pending","running","completed","failed","interrupted","cancelled"]),K0=l({id:o(),conversationId:o(),threadId:o(),teamId:o(),requestedByUserId:o(),executorUserId:o().nullable(),providerId:o(),modelId:o(),clientRequestId:o(),baseMessageSequence:d().int().nonnegative(),status:Cq,partialBody:o().nullable(),userMessageId:o(),assistantMessageId:o().nullable(),errorCode:o().nullable(),cancelledByUserId:o().nullable(),leaseExpiresAt:o().nullable(),heartbeatAt:o().nullable(),createdAt:o(),updatedAt:o()}),Rq=l({id:o(),conversationId:o(),sequence:d().int().nonnegative(),role:v(["user","assistant","system","action"]),body:o(),createdByUserId:o().nullable(),createdAt:o()});l({conversationId:o(),parentThreadId:o(),parentMessageId:o(),teamId:o(),title:o().nullable(),providerId:o().nullable(),modelId:o(),createdByUserId:o(),messages:p(Rq),turns:p(K0),activeTurn:K0.nullable(),createdAt:o(),updatedAt:o()});const Sw=l({id:d().int().nonnegative(),teamId:o(),threadId:o(),conversationId:o().nullable(),type:v(["thread.created","message.created","message.updated","message.deleted","read.updated","ai_thread.created","ai_turn.updated"]),payload:zv,createdAt:o()});l({events:p(Sw),cursor:d().int().nonnegative(),hasMore:w()});l({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 Fv=ae(o(),ie()),La=o().nullable(),Pq=v(["draft","published","archived"]),Vv=v(["owner","admin","member"]),xw=v(["active","left"]),kw=v(["mentions","all","none"]),Iw=v(["public_preview","members"]),Aq=v(["members","admins"]),Tq=l({canPreview:w(),canJoin:w(),canLeave:w(),canRead:w(),canPost:w(),canUpload:w(),canMention:w(),canManage:w(),requiresRulesAcceptance:w(),currentRulesVersionId:o().nullable()}),ww=l({id:o(),communityId:o(),version:d().int().positive(),title:o(),requiresReacceptance:w(),publishedAt:o()}),Eq=ww.extend({bodyMarkdown:o(),contentHash:o()}),Mq=l({role:Vv,status:xw,notificationMode:kw}),jq=l({id:o(),communityId:o(),userId:o(),role:Vv,status:xw,notificationMode:kw,joinedAt:o(),leftAt:La,createdAt:o(),updatedAt:o()}),_w=l({id:o(),slug:o(),displayName:o(),description:o(),imageUrl:o().nullable(),status:Pq,visibility:v(["public","private"]),joinPolicy:v(["open","closed"]),historyVisibility:Iw,featuredAt:La,publishedAt:La,archivedAt:La,memberCount:d().int().nonnegative(),membership:Mq.nullable(),capabilities:Tq,currentRules:ww.nullable()});l({items:p(_w),nextCursor:o().nullable()});const Cw=l({lastReadSequence:d().int().nonnegative(),lastReadAt:La.optional(),mutedAt:La,pinnedAt:La}),Kv=l({id:o(),communityId:o(),chatThreadId:o().nullable(),slug:o(),displayName:o(),topic:o(),position:d().int().nonnegative(),visibility:Iw,postingPolicy:Aq,isDefault:w(),archivedAt:La,lastMessageSequence:d().int().nonnegative(),unreadCount:d().int().nonnegative(),readState:Cw.nullable()});_w.omit({currentRules:!0}).extend({currentRules:Eq.nullable(),channels:p(Kv),previewMessageLimit:d().int().positive()});const Oq=l({id:o(),messageId:o(),refType:v(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:o(),preview:Fv,createdAt:o()}),Rw=l({id:o(),messageId:o().nullable(),clientAttachmentId:o(),kind:b("image"),name:o(),mediaType:v(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:d().int().positive(),status:v(["pending","ready","failed"]),createdAt:o(),readyAt:La});l({attachment:Rw,uploadUrl:o().url().nullable(),uploadHeaders:ae(o(),o()),expiresAt:La});l({url:o().url(),expiresAt:o()});const Pw=l({id:o(),threadId:o(),teamId:al(),clientRequestId:o().nullable(),authorType:v(["user","agent","system"]),authorUserId:o().nullable(),authorAgentId:o().nullable(),sequence:d().int().nonnegative(),kind:v(["text","system","command_result"]),body:o(),metadata:Fv,editedAt:La,deletedAt:La,createdAt:o(),refs:p(Oq),attachments:p(Rw)});l({messages:p(Pw),hasMoreBefore:w(),channelId:o(),readState:Cw.omit({lastReadAt:!0}).nullable(),preview:w()});const $q=l({userId:o(),handle:o().nullable(),name:o().nullable(),role:Vv});l({items:p($q),nextCursor:o().nullable()});const Aw=l({id:d().int().nonnegative(),communityId:o(),channelId:o(),threadId:o(),type:v(["thread.created","message.created","message.updated","message.deleted","read.updated"]),payload:Fv,createdAt:o()});l({events:p(Aw),cursor:d().int().nonnegative(),hasMore:w()});l({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)});l({membership:jq,channels:p(Kv)});l({channels:p(Kv)});var kc=o().trim().min(1).max(500),Nq=o().regex(/^[a-f0-9]{64}$/),qu=l({id:kc,revision:d().int().positive(),contentHash:Nq}).strict(),Dq=l({schemaVersion:b("openpond.hostedTasksetSummary.v1"),id:kc,teamId:kc,release:qu,name:o().min(1).max(500),description:o().max(2e4),taskCount:d().int().nonnegative(),buildIntent:o().min(1).max(100),methodHint:o().min(1).max(100).nullable(),packageBytes:d().int().nonnegative().nullable(),storedBytes:d().int().nonnegative().nullable(),createdAt:o().datetime({offset:!0})}).strict();l({afterId:o().trim().min(1).max(2e3).optional(),limit:d().int().min(1).max(100).default(30),modelProjectId:kc.optional(),projectId:kc.optional(),search:o().trim().max(100).optional(),sort:v(["id","name","updated"]).default("id")}).strict();l({items:p(Dq).max(100),nextCursor:o().trim().min(1).max(2e3).nullable()}).strict();l({code:o().min(1),message:o().min(1)}).strict();const Hq=l({candidateId:o().min(1).max(240),frozenRevision:d().int().positive(),frozenHash:o().regex(/^[a-f0-9]{64}$/),harnessRelease:V,protectedClosureHash:o().regex(/^[a-f0-9]{64}$/)}).strict(),W0=o().trim().min(1).max(240),Lq=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."),ed=l({schemaVersion:b("openpond.tasksetMetricPolicy.v1"),primaryMetric:W0,aggregation:v(["mean_score","pass_rate","weighted_mean","custom"]),missingReward:v(["zero","exclude"]),taskWeights:ae(W0,d().positive().max(1e6)).optional(),customAggregator:l({module:Lq,exportName:o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),contentHash:D,timeoutMs:d().int().positive().max(3e5),networkPolicy:b("none")}).strict().nullable()}).strict().superRefine((e,t)=>{e.aggregation==="custom"!=(e.customAggregator!==null)&&t.addIssue({code:"custom",path:["customAggregator"],message:"Only custom aggregation requires a content-hashed module."}),(e.aggregation==="weighted_mean"?!e.taskWeights||!Object.keys(e.taskWeights).length:e.taskWeights!==void 0)&&t.addIssue({code:"custom",path:["taskWeights"],message:"Only weighted means require explicit positive task weights."})}),qq=l({schemaVersion:b("openpond.tasksetMetricResult.v1"),runManifest:V,tasksetRelease:V,policy:ed,policyHash:D,receiptRefs:p(V).min(1).max(1e6),includedCount:d().int().nonnegative(),missingRewardCount:d().int().nonnegative(),excludedCount:d().int().nonnegative(),value:d().min(0).max(1).nullable()}).strict(),Wv=qq.extend({contentHash:D}).strict(),Yt=T,Do=D,Tw=l({id:Yt,revision:d().int().positive(),contentHash:Do}).strict(),Gv=l({kind:b("owner_attested_local"),ownerActorId:Yt,teamId:Yt,executionHash:Do,configurationHash:Do,retainedAttemptHash:Do,traceHash:Do,publicationCutoffHash:Do}).strict(),Uq=Gv.omit({publicationCutoffHash:!0,kind:!0}).extend({kind:b("native_local")}).strict(),zq=l({origin:Gv,executionId:Yt,receiptId:Yt,taskId:Yt,targetId:Yt,familyKey:Yt,split:v(["train","validation","test","frozen_eval"]),input:ae(o(),ie()),policyVisibleContext:ae(o(),ie()),output:o().nullable(),error:o().nullable(),events:p(ae(o(),ie())).max(1e3),coverage:l({sourceEventCount:d().int().nonnegative().max(2e4),publishedEventCount:d().int().nonnegative().max(1e3),traceLimited:w(),artifactsIncluded:b(!1)}).strict()}).strict().superRefine((e,t)=>{(e.events.length!==e.coverage.publishedEventCount||e.coverage.sourceEventCount<e.events.length||e.coverage.traceLimited!==e.coverage.sourceEventCount>e.events.length)&&t.addIssue({code:"custom",message:"Publication coverage must describe its actual retained event population."}),st(e.events)!==e.origin.publicationCutoffHash&&t.addIssue({code:"custom",message:"Published trace cutoff changed."})}),Bq=l({schemaVersion:b("openpond.humanLocalEvidenceExport.v1"),actorId:Yt,scope:Yt,projectId:Yt,dataset:Tw,graderId:Yt,compiledGraderHash:Do,attempts:p(zq).min(1).max(2),sealedAt:he}).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."})}),Fq=Bq.safeExtend({contentHash:Do}).strict().superRefine((e,t)=>{const{contentHash:n,...a}=e;st(a)!==n&&t.addIssue({code:"custom",message:"Local evidence export bytes changed."})}),Ew=l({endpoint:b("export_local"),scope:Yt,projectId:Yt,graderId:Yt,selections:p(l({executionId:Yt,receiptId:Yt}).strict()).min(1).max(2)}).strict(),Vq=l({endpoint:b("publish_local"),scope:Yt,projectId:Yt,operationId:Yt,audience:p(Yt).max(100),workspaceVisible:w(),evidence:Fq}).strict(),Kq=Ew.omit({endpoint:!0}).extend({endpoint:b("share_local"),operationId:Yt,audience:p(Yt).max(100),workspaceVisible:w()}).strict(),Wq=l({endpoint:b("local_publications"),scope:Yt,executionId:Yt}).strict(),Gq=l({endpoint:b("revoke_local"),scope:Yt,publication:Tw}).strict();var Mw=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Jq=Mw((e,t)=>{"use strict";t.exports=function n(a,i){if(a===i)return!0;if(a&&i&&typeof a=="object"&&typeof i=="object"){if(a.constructor!==i.constructor)return!1;var r,s,c;if(Array.isArray(a)){if(r=a.length,r!=i.length)return!1;for(s=r;s--!==0;)if(!n(a[s],i[s]))return!1;return!0}if(a.constructor===RegExp)return a.source===i.source&&a.flags===i.flags;if(a.valueOf!==Object.prototype.valueOf)return a.valueOf()===i.valueOf();if(a.toString!==Object.prototype.toString)return a.toString()===i.toString();if(c=Object.keys(a),r=c.length,r!==Object.keys(i).length)return!1;for(s=r;s--!==0;)if(!Object.prototype.hasOwnProperty.call(i,c[s]))return!1;for(s=r;s--!==0;){var m=c[s];if(!n(a[m],i[m]))return!1}return!0}return a!==a&&i!==i}}),Zq=Mw(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var t=Jq();t.code='require("ajv/dist/runtime/equal").default',e.default=t}),G0=qt,J0={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"}}},Yq=Object.prototype.hasOwnProperty,Qq=Zq().default,Ct={validate:qt};function Sa(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:i=e,dynamicAnchors:r={}}={}){let s=null,c=0,m=Sa.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),c===0)if(e&&typeof e=="object"&&!Array.isArray(e))for(let h in e){let g=c;Ct.validate(e[h],{instancePath:t+"/"+h.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:e,parentDataProperty:h,rootData:i,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=g===c;if(!u)break}else return Sa.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"object"}}],!1;return Sa.errors=s,c===0}Sa.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};function On(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:i=e,dynamicAnchors:r={}}={}){let s=null,c=0,m=On.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),c===0)if(Array.isArray(e)){if(e.length>32)return On.errors=[{instancePath:t,schemaPath:"#/maxItems",keyword:"maxItems",params:{limit:32}}],!1;if(e.length<1)return On.errors=[{instancePath:t,schemaPath:"#/minItems",keyword:"minItems",params:{limit:1}}],!1;{var u=!0;let h=e.length;for(let g=0;g<h;g++){let S=c;Ct.validate(e[g],{instancePath:t+"/"+g,parentData:e,parentDataProperty:g,rootData:i,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=S===c;if(!u)break}}}else return On.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return On.errors=s,c===0}On.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};var Xq={enum:["array","boolean","integer","null","number","object","string"]};function _i(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:i=e,dynamicAnchors:r={}}={}){let s=null,c=0,m=_i.evaluated;return m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),e==="array"||e==="boolean"||e==="integer"||e==="null"||e==="number"||e==="object"||e==="string"?(_i.errors=s,c===0):(_i.errors=[{instancePath:t,schemaPath:"#/enum",keyword:"enum",params:{allowedValues:Xq.enum}}],!1)}_i.evaluated={dynamicProps:!1,dynamicItems:!1};function Ut(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:i=e,dynamicAnchors:r={}}={}){let s=null,c=0,m=Ut.evaluated;return m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),typeof e=="number"&&!(e%1)&&!isNaN(e)&&isFinite(e)?typeof e=="number"&&isFinite(e)&&(e<0||isNaN(e))?(Ut.errors=[{instancePath:t,schemaPath:"#/minimum",keyword:"minimum",params:{comparison:">=",limit:0}}],!1):(Ut.errors=s,c===0):(Ut.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"integer"}}],!1)}Ut.evaluated={dynamicProps:!1,dynamicItems:!1};function $a(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:i=e,dynamicAnchors:r={}}={}){let s=null,c=0,m=$a.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),c===0)if(Array.isArray(e)){var u=!0;let h=e.length;for(let g=0;g<h;g++){let S=c;if(typeof e[g]!="string")return $a.errors=[{instancePath:t+"/"+g,schemaPath:"#/items/type",keyword:"type",params:{type:"string"}}],!1;var u=S===c;if(!u)break}if(u){let g=e.length,S;if(g>1){let k={};for(;g--;){let C=e[g];if(typeof C=="string"){if(typeof k[C]=="number")return S=k[C],$a.errors=[{instancePath:t,schemaPath:"#/uniqueItems",keyword:"uniqueItems",params:{i:g,j:S}}],!1;k[C]=g}}}}}else return $a.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return $a.errors=s,c===0}$a.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};function qt(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:i=e,dynamicAnchors:r={}}={}){let s=null,c=0,m=qt.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),!(e&&typeof e=="object"&&!Array.isArray(e))&&typeof e!="boolean")return qt.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:J0.type}}],!1;if(c===0&&e&&typeof e=="object"&&!Array.isArray(e)){let k=c;for(let C in e)if(!Yq.call(J0.properties,C))return qt.errors=[{instancePath:t,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:C}}],!1;if(k===c){if(e.$schema!==void 0){let C=c;if(e.$schema!=="https://json-schema.org/draft/2020-12/schema")return qt.errors=[{instancePath:t+"/$schema",schemaPath:"#/properties/%24schema/const",keyword:"const",params:{allowedValue:"https://json-schema.org/draft/2020-12/schema"}}],!1;var u=C===c}else var u=!0;if(u){if(e.$ref!==void 0){let A=c;if(typeof e.$ref!="string")return qt.errors=[{instancePath:t+"/$ref",schemaPath:"#/properties/%24ref/type",keyword:"type",params:{type:"string"}}],!1;var u=A===c}else var u=!0;if(u){if(e.$comment!==void 0){let M=c;if(typeof e.$comment!="string")return qt.errors=[{instancePath:t+"/$comment",schemaPath:"#/properties/%24comment/type",keyword:"type",params:{type:"string"}}],!1;var u=M===c}else var u=!0;if(u){if(e.$defs!==void 0){let R=c;Sa(e.$defs,{instancePath:t+"/$defs",parentData:e,parentDataProperty:"$defs",rootData:i,dynamicAnchors:r})||(s=s===null?Sa.errors:s.concat(Sa.errors),c=s.length);var u=R===c}else var u=!0;if(u){if(e.properties!==void 0){let $=c;Sa(e.properties,{instancePath:t+"/properties",parentData:e,parentDataProperty:"properties",rootData:i,dynamicAnchors:r})||(s=s===null?Sa.errors:s.concat(Sa.errors),c=s.length);var u=$===c}else var u=!0;if(u){if(e.dependentSchemas!==void 0){let O=c;Sa(e.dependentSchemas,{instancePath:t+"/dependentSchemas",parentData:e,parentDataProperty:"dependentSchemas",rootData:i,dynamicAnchors:r})||(s=s===null?Sa.errors:s.concat(Sa.errors),c=s.length);var u=O===c}else var u=!0;if(u){if(e.allOf!==void 0){let j=c;On(e.allOf,{instancePath:t+"/allOf",parentData:e,parentDataProperty:"allOf",rootData:i,dynamicAnchors:r})||(s=s===null?On.errors:s.concat(On.errors),c=s.length);var u=j===c}else var u=!0;if(u){if(e.anyOf!==void 0){let I=c;On(e.anyOf,{instancePath:t+"/anyOf",parentData:e,parentDataProperty:"anyOf",rootData:i,dynamicAnchors:r})||(s=s===null?On.errors:s.concat(On.errors),c=s.length);var u=I===c}else var u=!0;if(u){if(e.oneOf!==void 0){let P=c;On(e.oneOf,{instancePath:t+"/oneOf",parentData:e,parentDataProperty:"oneOf",rootData:i,dynamicAnchors:r})||(s=s===null?On.errors:s.concat(On.errors),c=s.length);var u=P===c}else var u=!0;if(u){if(e.prefixItems!==void 0){let E=c;On(e.prefixItems,{instancePath:t+"/prefixItems",parentData:e,parentDataProperty:"prefixItems",rootData:i,dynamicAnchors:r})||(s=s===null?On.errors:s.concat(On.errors),c=s.length);var u=E===c}else var u=!0;if(u){if(e.items!==void 0){let L=c;Ct.validate(e.items,{instancePath:t+"/items",parentData:e,parentDataProperty:"items",rootData:i,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=L===c}else var u=!0;if(u){if(e.additionalProperties!==void 0){let z=c;Ct.validate(e.additionalProperties,{instancePath:t+"/additionalProperties",parentData:e,parentDataProperty:"additionalProperties",rootData:i,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=z===c}else var u=!0;if(u){if(e.not!==void 0){let H=c;Ct.validate(e.not,{instancePath:t+"/not",parentData:e,parentDataProperty:"not",rootData:i,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=H===c}else var u=!0;if(u){if(e.if!==void 0){let J=c;Ct.validate(e.if,{instancePath:t+"/if",parentData:e,parentDataProperty:"if",rootData:i,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=J===c}else var u=!0;if(u){if(e.then!==void 0){let X=c;Ct.validate(e.then,{instancePath:t+"/then",parentData:e,parentDataProperty:"then",rootData:i,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=X===c}else var u=!0;if(u){if(e.else!==void 0){let de=c;Ct.validate(e.else,{instancePath:t+"/else",parentData:e,parentDataProperty:"else",rootData:i,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=de===c}else var u=!0;if(u){if(e.contains!==void 0){let je=c;Ct.validate(e.contains,{instancePath:t+"/contains",parentData:e,parentDataProperty:"contains",rootData:i,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=je===c}else var u=!0;if(u){if(e.unevaluatedProperties!==void 0){let we=c;Ct.validate(e.unevaluatedProperties,{instancePath:t+"/unevaluatedProperties",parentData:e,parentDataProperty:"unevaluatedProperties",rootData:i,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=we===c}else var u=!0;if(u){if(e.unevaluatedItems!==void 0){let te=c;Ct.validate(e.unevaluatedItems,{instancePath:t+"/unevaluatedItems",parentData:e,parentDataProperty:"unevaluatedItems",rootData:i,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=te===c}else var u=!0;if(u){if(e.propertyNames!==void 0){let Me=c;Ct.validate(e.propertyNames,{instancePath:t+"/propertyNames",parentData:e,parentDataProperty:"propertyNames",rootData:i,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=Me===c}else var u=!0;if(u){if(e.type!==void 0){let Se=e.type,oe=c,be=c,re=!1,ue=c;_i(Se,{instancePath:t+"/type",parentData:e,parentDataProperty:"type",rootData:i,dynamicAnchors:r})||(s=s===null?_i.errors:s.concat(_i.errors),c=s.length);var g=ue===c;re=re||g;let ke=c;if(c===ke)if(Array.isArray(Se))if(Se.length<1){let Ie={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/minItems",keyword:"minItems",params:{limit:1}};s===null?s=[Ie]:s.push(Ie),c++}else{var h=!0;let Ie=Se.length;for(let le=0;le<Ie;le++){let xe=c;_i(Se[le],{instancePath:t+"/type/"+le,parentData:Se,parentDataProperty:le,rootData:i,dynamicAnchors:r})||(s=s===null?_i.errors:s.concat(_i.errors),c=s.length);var h=xe===c;if(!h)break}if(h){let le=Se.length,xe;if(le>1){e:for(;le--;)for(xe=le;xe--;)if(Qq(Se[le],Se[xe])){let Ue={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/uniqueItems",keyword:"uniqueItems",params:{i:le,j:xe}};s===null?s=[Ue]:s.push(Ue),c++;break e}}}}else{let Ie={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/type",keyword:"type",params:{type:"array"}};s===null?s=[Ie]:s.push(Ie),c++}var g=ke===c;if(re=re||g,re)c=be,s!==null&&(be?s.length=be:s=null);else{let Ie={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf",keyword:"anyOf",params:{}};return s===null?s=[Ie]:s.push(Ie),c++,qt.errors=s,!1}var u=oe===c}else var u=!0;if(u){if(e.enum!==void 0){let oe=e.enum,be=c;if(c===be)if(Array.isArray(oe)){if(oe.length<1)return qt.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/minItems",keyword:"minItems",params:{limit:1}}],!1}else return qt.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/type",keyword:"type",params:{type:"array"}}],!1;var u=be===c}else var u=!0;if(u){if(e.title!==void 0){let be=c;if(typeof e.title!="string")return qt.errors=[{instancePath:t+"/title",schemaPath:"#/properties/title/type",keyword:"type",params:{type:"string"}}],!1;var u=be===c}else var u=!0;if(u){if(e.description!==void 0){let re=c;if(typeof e.description!="string")return qt.errors=[{instancePath:t+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type:"string"}}],!1;var u=re===c}else var u=!0;if(u){if(e.examples!==void 0){let ue=c;if(!Array.isArray(e.examples))return qt.errors=[{instancePath:t+"/examples",schemaPath:"#/properties/examples/type",keyword:"type",params:{type:"array"}}],!1;var u=ue===c}else var u=!0;if(u){if(e.readOnly!==void 0){let ke=c;if(typeof e.readOnly!="boolean")return qt.errors=[{instancePath:t+"/readOnly",schemaPath:"#/properties/readOnly/type",keyword:"type",params:{type:"boolean"}}],!1;var u=ke===c}else var u=!0;if(u){if(e.writeOnly!==void 0){let Le=c;if(typeof e.writeOnly!="boolean")return qt.errors=[{instancePath:t+"/writeOnly",schemaPath:"#/properties/writeOnly/type",keyword:"type",params:{type:"boolean"}}],!1;var u=Le===c}else var u=!0;if(u){if(e.deprecated!==void 0){let Ie=c;if(typeof e.deprecated!="boolean")return qt.errors=[{instancePath:t+"/deprecated",schemaPath:"#/properties/deprecated/type",keyword:"type",params:{type:"boolean"}}],!1;var u=Ie===c}else var u=!0;if(u){if(e.multipleOf!==void 0){let le=e.multipleOf,xe=c;if(c===xe)if(typeof le=="number"&&isFinite(le)){if(le<=0||isNaN(le))return qt.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/exclusiveMinimum",keyword:"exclusiveMinimum",params:{comparison:">",limit:0}}],!1}else return qt.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/type",keyword:"type",params:{type:"number"}}],!1;var u=xe===c}else var u=!0;if(u){if(e.maximum!==void 0){let xe=e.maximum,Ue=c;if(!(typeof xe=="number"&&isFinite(xe)))return qt.errors=[{instancePath:t+"/maximum",schemaPath:"#/properties/maximum/type",keyword:"type",params:{type:"number"}}],!1;var u=Ue===c}else var u=!0;if(u){if(e.exclusiveMaximum!==void 0){let Ue=e.exclusiveMaximum,Ze=c;if(!(typeof Ue=="number"&&isFinite(Ue)))return qt.errors=[{instancePath:t+"/exclusiveMaximum",schemaPath:"#/properties/exclusiveMaximum/type",keyword:"type",params:{type:"number"}}],!1;var u=Ze===c}else var u=!0;if(u){if(e.minimum!==void 0){let Ze=e.minimum,it=c;if(!(typeof Ze=="number"&&isFinite(Ze)))return qt.errors=[{instancePath:t+"/minimum",schemaPath:"#/properties/minimum/type",keyword:"type",params:{type:"number"}}],!1;var u=it===c}else var u=!0;if(u){if(e.exclusiveMinimum!==void 0){let it=e.exclusiveMinimum,at=c;if(!(typeof it=="number"&&isFinite(it)))return qt.errors=[{instancePath:t+"/exclusiveMinimum",schemaPath:"#/properties/exclusiveMinimum/type",keyword:"type",params:{type:"number"}}],!1;var u=at===c}else var u=!0;if(u){if(e.maxLength!==void 0){let at=c;Ut(e.maxLength,{instancePath:t+"/maxLength",parentData:e,parentDataProperty:"maxLength",rootData:i,dynamicAnchors:r})||(s=s===null?Ut.errors:s.concat(Ut.errors),c=s.length);var u=at===c}else var u=!0;if(u){if(e.minLength!==void 0){let Ne=c;Ut(e.minLength,{instancePath:t+"/minLength",parentData:e,parentDataProperty:"minLength",rootData:i,dynamicAnchors:r})||(s=s===null?Ut.errors:s.concat(Ut.errors),c=s.length);var u=Ne===c}else var u=!0;if(u){if(e.maxItems!==void 0){let We=c;Ut(e.maxItems,{instancePath:t+"/maxItems",parentData:e,parentDataProperty:"maxItems",rootData:i,dynamicAnchors:r})||(s=s===null?Ut.errors:s.concat(Ut.errors),c=s.length);var u=We===c}else var u=!0;if(u){if(e.minItems!==void 0){let qe=c;Ut(e.minItems,{instancePath:t+"/minItems",parentData:e,parentDataProperty:"minItems",rootData:i,dynamicAnchors:r})||(s=s===null?Ut.errors:s.concat(Ut.errors),c=s.length);var u=qe===c}else var u=!0;if(u){if(e.maxContains!==void 0){let q=c;Ut(e.maxContains,{instancePath:t+"/maxContains",parentData:e,parentDataProperty:"maxContains",rootData:i,dynamicAnchors:r})||(s=s===null?Ut.errors:s.concat(Ut.errors),c=s.length);var u=q===c}else var u=!0;if(u){if(e.minContains!==void 0){let N=c;Ut(e.minContains,{instancePath:t+"/minContains",parentData:e,parentDataProperty:"minContains",rootData:i,dynamicAnchors:r})||(s=s===null?Ut.errors:s.concat(Ut.errors),c=s.length);var u=N===c}else var u=!0;if(u){if(e.maxProperties!==void 0){let F=c;Ut(e.maxProperties,{instancePath:t+"/maxProperties",parentData:e,parentDataProperty:"maxProperties",rootData:i,dynamicAnchors:r})||(s=s===null?Ut.errors:s.concat(Ut.errors),c=s.length);var u=F===c}else var u=!0;if(u){if(e.minProperties!==void 0){let ee=c;Ut(e.minProperties,{instancePath:t+"/minProperties",parentData:e,parentDataProperty:"minProperties",rootData:i,dynamicAnchors:r})||(s=s===null?Ut.errors:s.concat(Ut.errors),c=s.length);var u=ee===c}else var u=!0;if(u){if(e.uniqueItems!==void 0){let me=c;if(typeof e.uniqueItems!="boolean")return qt.errors=[{instancePath:t+"/uniqueItems",schemaPath:"#/properties/uniqueItems/type",keyword:"type",params:{type:"boolean"}}],!1;var u=me===c}else var u=!0;if(u){if(e.required!==void 0){let $e=c;$a(e.required,{instancePath:t+"/required",parentData:e,parentDataProperty:"required",rootData:i,dynamicAnchors:r})||(s=s===null?$a.errors:s.concat($a.errors),c=s.length);var u=$e===c}else var u=!0;if(u){if(e.dependentRequired!==void 0){let ze=e.dependentRequired,tt=c;if(c===tt)if(ze&&typeof ze=="object"&&!Array.isArray(ze))for(let mt in ze){let vt=c;$a(ze[mt],{instancePath:t+"/dependentRequired/"+mt.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:ze,parentDataProperty:mt,rootData:i,dynamicAnchors:r})||(s=s===null?$a.errors:s.concat($a.errors),c=s.length);var S=vt===c;if(!S)break}else return qt.errors=[{instancePath:t+"/dependentRequired",schemaPath:"#/properties/dependentRequired/type",keyword:"type",params:{type:"object"}}],!1;var u=tt===c}else var u=!0;if(u){if(e.contentEncoding!==void 0){let tt=c;if(typeof e.contentEncoding!="string")return qt.errors=[{instancePath:t+"/contentEncoding",schemaPath:"#/properties/contentEncoding/type",keyword:"type",params:{type:"string"}}],!1;var u=tt===c}else var u=!0;if(u)if(e.contentMediaType!==void 0){let tt=c;if(typeof e.contentMediaType!="string")return qt.errors=[{instancePath:t+"/contentMediaType",schemaPath:"#/properties/contentMediaType/type",keyword:"type",params:{type:"string"}}],!1;var u=tt===c}else var u=!0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}return qt.errors=s,c===0}qt.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};const Z0="https://json-schema.org/draft/2020-12/schema",eU=1048576,tU=32768,nU=new Set(["properties","$defs","dependentSchemas"]),aU=new Set(["allOf","anyOf","oneOf","prefixItems"]),iU=new Set(["items","additionalProperties","not","if","then","else","contains","unevaluatedProperties","unevaluatedItems","propertyNames"]);function Hi(e,t=eU){const n=[{value:e,depth:0}],a=new Set;let i=0;for(;n.length;){const r=n.pop();if(r.exit){a.delete(r.value);continue}if(++i>1e5||r.depth>48)throw new Error("task_json_complexity_exceeded");if(r.value===null||typeof r.value=="string"||typeof r.value=="boolean"||typeof r.value=="number"&&Number.isFinite(r.value))continue;if(typeof r.value!="object")throw new Error("task_json_value_invalid");if(a.has(r.value))throw new Error("task_json_cycle");a.add(r.value),n.push({...r,exit:!0});const s=Object.getPrototypeOf(r.value);if(!Array.isArray(r.value)&&s!==Object.prototype&&s!==null)throw new Error("task_json_object_invalid");if(Object.getOwnPropertySymbols(r.value).length)throw new Error("task_json_symbol_invalid");if(Object.hasOwn(r.value,"toJSON"))throw new Error("task_json_serializer_invalid");if(Array.isArray(r.value)&&(r.value.length>1e4||Object.keys(r.value).length!==r.value.length))throw new Error("task_json_array_invalid");for(const[c,m]of Object.entries(Object.getOwnPropertyDescriptors(r.value))){if(m.get||m.set)throw new Error("task_json_accessor_invalid");if(Array.isArray(r.value)&&c!=="length"&&(!/^(0|[1-9]\d*)$/u.test(c)||Number(c)>=r.value.length))throw new Error("task_json_array_invalid");m.enumerable&&n.push({value:m.value,depth:r.depth+1})}}if(new TextEncoder().encode(JSON.stringify(e)).byteLength>t)throw new Error("task_json_size_exceeded")}function Jv(e){try{return oU(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 oU(e){if(Hi(e,tU),Yl(e,e,new Set,0,{remaining:2048}),!G0(e)){const t=G0.errors?.[0];throw new Error(`Task schema ${t?.instancePath||"/"} violates ${t?.keyword??"schema"}.`)}}function Yl(e,t,n,a,i){if(--i.remaining<0)throw new Error("Task schema reference expansion exceeds the validation budget.");if(typeof e=="boolean")return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error("A task schema must be an object or boolean.");if(a>24||n.has(e))throw new Error("Recursive or deeply nested task schemas are not supported.");const r=new Set(n).add(e),s=e;if(s.$schema!==void 0&&s.$schema!==Z0)throw new Error(`Task schemas must use ${Z0}.`);for(const[c,m]of Object.entries(s))if(c==="$ref"){if(typeof m!="string"||!m.startsWith("#/$defs/"))throw new Error("Task schema references must be local JSON pointers into $defs.");let u=t;for(const h of m.slice(2).split("/")){if(/~(?![01])/u.test(h))throw new Error("Invalid task schema JSON pointer.");const g=h.replaceAll("~1","/").replaceAll("~0","~");if(!u||typeof u!="object"||!Object.hasOwn(u,g))throw new Error(`Task schema reference ${m} is missing.`);u=u[g]}Yl(u,t,r,a+1,i)}else if(nU.has(c)){if(!m||typeof m!="object"||Array.isArray(m))throw new Error(`Invalid schema map ${c}.`);for(const u of Object.values(m))Yl(u,t,r,a+1,i)}else if(aU.has(c)){if(!Array.isArray(m)||m.length>32)throw new Error(`Schema ${c} must contain at most 32 alternatives.`);for(const u of m)Yl(u,t,r,a+1,i)}else iU.has(c)&&Yl(m,t,r,a+1,i)}const jw=l({taskId:T,input:ae(o(),ie()),policyVisibleContext:ae(o(),ie()),expectedOutput:ae(o(),ie()).nullable().optional(),tags:p(T).max(100).optional()}).strict(),Fs=l({schemaVersion:b("openpond.humanTaskProposal.v1"),tasks:p(jw).min(1).max(1e3),contentHash:D}).strict().superRefine((e,t)=>{const{contentHash:n,...a}=e;n!==st(a)&&t.addIssue({code:"custom",message:"Task proposal content hash differs."}),new Set(e.tasks.map(i=>i.taskId)).size!==e.tasks.length&&t.addIssue({code:"custom",message:"Each task may be proposed once."});try{Hi(e,1048576)}catch{t.addIssue({code:"custom",message:"Task proposal exceeds retained data bounds."})}}),Y0=l({schemaVersion:b("openpond.humanTaskProposal.v1"),tasks:p(jw).min(1).max(1e3),contentHash:D,referenceRedacted:b(!0).optional()}).strict().superRefine((e,t)=>{e.referenceRedacted?e.tasks.some(n=>n.expectedOutput!==void 0)&&t.addIssue({code:"custom",message:"Redacted proposals cannot include reference outputs."}):Fs.safeParse(e).success||t.addIssue({code:"custom",message:"Task proposal integrity differs."})});function Une(e){const t={schemaVersion:"openpond.humanTaskProposal.v1",tasks:e};return Fs.parse({...t,contentHash:st(t)})}const Fe=T,_n=l({id:Fe,revision:d().int().positive(),contentHash:D}).strict(),rU=lt("kind",[l({id:Fe,label:o().trim().min(1).max(500),instructions:o().max(2e4),required:w(),allowAbstain:w(),requireRationale:w().optional(),anchors:p(l({value:ht([d(),o(),w()]),description:o().min(1).max(2e3)}).strict()).max(100).optional(),kind:b("score"),minimum:d().finite(),maximum:d().finite(),step:d().positive().finite()}).strict().refine(e=>e.minimum<e.maximum&&e.step<=e.maximum-e.minimum,"Use an increasing raw score range and a step within that range."),l({id:Fe,label:o().trim().min(1).max(500),instructions:o().max(2e4),required:w(),allowAbstain:w(),requireRationale:w().optional(),anchors:p(l({value:ht([d(),o(),w()]),description:o().min(1).max(2e3)}).strict()).max(100).optional(),kind:b("category"),options:p(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."),l({id:Fe,label:o().trim().min(1).max(500),instructions:o().max(2e4),required:w(),allowAbstain:w(),requireRationale:w().optional(),anchors:p(l({value:ht([d(),o(),w()]),description:o().min(1).max(2e3)}).strict()).max(100).optional(),kind:b("boolean")}).strict(),l({id:Fe,label:o().trim().min(1).max(500),instructions:o().max(2e4),required:w(),allowAbstain:w(),requireRationale:w().optional(),anchors:p(l({value:ht([d(),o(),w()]),description:o().min(1).max(2e3)}).strict()).max(100).optional(),kind:b("text"),minimumLength:d().int().nonnegative().max(2e4).optional(),maximumLength:d().int().positive().max(2e4)}).strict(),l({id:Fe,label:o().trim().min(1).max(500),instructions:o().max(2e4),required:w(),allowAbstain:w(),requireRationale:w().optional(),anchors:p(l({value:ht([d(),o(),w()]),description:o().min(1).max(2e3)}).strict()).max(100).optional(),kind:b("preference"),requireStrength:w().optional(),allowTie:w()}).strict()]),Rm=l({schemaVersion:b("openpond.humanForm.v1"),mode:v(["individual","pairwise"]),instructions:o().max(2e4),criteria:p(rU).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 i=new Set;n.anchors?.forEach((r,s)=>{const c=r.value,m=n.kind==="score"?typeof c=="number"&&Number.isFinite(c)&&c>=n.minimum&&c<=n.maximum&&Math.abs((c-n.minimum)/n.step-Math.round((c-n.minimum)/n.step))<1e-8:n.kind==="category"?typeof c=="string"&&n.options.includes(c):n.kind==="boolean"?typeof c=="boolean":n.kind==="preference"?["A","B",...n.allowTie?["tie"]:[]].includes(String(c)):typeof c=="string",u=JSON.stringify(c);(!m||i.has(u))&&t.addIssue({code:"custom",path:["criteria",a,"anchors",s,"value"],message:"Each anchor must describe a unique valid raw value."}),i.add(u)})}),new Set(e.criteria.map(n=>n.id)).size!==e.criteria.length&&t.addIssue({code:"custom",path:["criteria"],message:"Criterion IDs must be unique."}),e.mode==="individual"&&e.criteria.some(n=>n.kind==="preference")&&t.addIssue({code:"custom",path:["criteria"],message:"Preferences require an explicit pair."})}),sU=l({localSource:ht([Gv,Uq]).optional(),recordedSource:l({id:Fe,snapshotHash:D,boundaryId:Fe,boundaryRevisionHash:D}).strict().optional(),experimentId:Fe,attemptId:Fe,taskId:Fe,targetId:Fe,output:_n,trace:_n.nullable(),familyKey:Fe,split:v(["train","validation","test","frozen_eval"])}).strict(),Zv=l({publication:_n.optional(),dataset:_n,grader:_n,graderBinding:l({id:Fe,version:o().min(1).max(100),contentHash:D}).strict(),rubric:_n,attempts:p(sU).max(2),taskIds:p(Fe).min(1).max(1e3).optional()}).strict().superRefine((e,t)=>{!e.attempts.length&&!e.taskIds?.length&&t.addIssue({code:"custom",message:"Select retained attempts or exact tasks."}),e.taskIds&&new Set(e.taskIds).size!==e.taskIds.length&&t.addIssue({code:"custom",path:["taskIds"],message:"Select each task once."}),e.attempts.length===2&&(e.attempts[0].attemptId===e.attempts[1].attemptId||e.attempts[0].taskId!==e.attempts[1].taskId||e.attempts[0].familyKey!==e.attempts[1].familyKey||e.attempts[0].split!==e.attempts[1].split)&&t.addIssue({code:"custom",path:["attempts"],message:"A/B review requires distinct attempts of the same task, family and split."})}),Vs=l({criterionId:Fe,value:ht([d().finite(),w(),o().max(2e4),al()]),abstain:w(),note:o().max(2e4),strength:v(["slight","moderate","strong"]).optional()}).strict(),Ow=l({approval:v(["none","manager"]),minimumRaters:d().int().min(1).max(100),managerIds:p(Fe).max(100),reviewerIds:p(Fe).max(100),queueClaim:w(),teamVisible:w(),distinctManager:w().optional(),independentRaters:w().optional(),blindPair:w().optional()}).strict().superRefine((e,t)=>{e.approval==="none"&&e.minimumRaters!==1&&t.addIssue({code:"custom",path:["minimumRaters"],message:"Multi-rater review requires explicit adjudication."})}),$w=l({taskProposal:Fs.optional(),id:Fe,revision:d().int().positive(),actorId:Fe,generation:d().int().positive(),evidenceHash:D,formHash:D,answers:p(Vs).max(100),note:o().max(2e4),submittedAt:he,supersedes:Fe.nullable(),contentHash:D}).strict(),Ql=l({taskProposalHash:D.optional(),id:Fe,revision:d().int().positive(),actorId:Fe,outcome:v(["accept","reject","request_changes"]),submissions:p(l({id:Fe,contentHash:D}).strict()).min(1).max(100),answers:p(Vs).max(100),note:o().max(2e4),decidedAt:he,contentHash:D}).strict(),Uu=l({schemaVersion:b("openpond.humanReview.v1"),id:Fe,revision:d().int().positive(),scope:Fe,projectId:Fe,createdBy:Fe,kind:v(["author","execute","grade"]),dueAt:he.optional(),title:o().trim().min(1).max(500),authorPublication:l({proposalHash:D,dataset:_n,operationId:Fe,publishedBy:Fe,publishedAt:he}).strict().nullable(),evidence:Zv,form:Rm,policy:Ow,status:v(["queued","assigned","in_progress","submitted","returned","accepted","rejected","cancelled"]),assigneeId:Fe.nullable(),generation:d().int().positive(),drafts:p(l({taskProposal:Fs.optional(),actorId:Fe,generation:d().int().positive(),answers:p(Vs).max(100),note:o().max(2e4),updatedAt:he}).strict()).max(100),submissions:p($w).max(1e3),decisions:p(Ql).max(1e3),audit:p(l({actorId:Fe,action:v(["claim","reassign","cancel"]),priorAssigneeId:Fe.nullable(),assigneeId:Fe.nullable(),generation:d().int().positive(),note:o().max(2e4),occurredAt:he}).strict()).max(1e3),execution:l({executionId:Fe.nullable(),operationId:Fe,boundBy:Fe,configurationHash:D,generation:d().int().positive(),result:_n.nullable()}).strict().nullable(),createdAt:he,updatedAt:he,contentHash:D}).strict(),Si={operationId:Fe,id:Fe,expectedRevision:d().int().nonnegative()},lU=lt("action",[l({...Si,action:b("create"),projectId:Fe,kind:Uu.shape.kind,title:Uu.shape.title,dueAt:he.optional(),evidence:Zv,form:Rm,policy:Ow,assigneeId:Fe.nullable()}).strict(),l({...Si,action:b("claim")}).strict(),l({...Si,action:b("bind_author_publication"),proposalHash:D,dataset:_n}).strict(),l({...Si,action:b("reserve_execution"),generation:d().int().positive(),runOperationId:Fe,configurationHash:D}).strict(),l({...Si,action:b("bind_execution"),generation:d().int().positive(),executionId:Fe,runOperationId:Fe,configurationHash:D}).strict(),l({...Si,action:b("reassign"),assigneeId:Fe.nullable(),note:o().trim().min(1).max(2e4)}).strict(),l({...Si,action:b("cancel"),note:o().max(2e4)}).strict(),l({...Si,action:b("save_draft"),taskProposal:Fs.optional(),generation:d().int().positive(),answers:p(Vs).max(100),note:o().max(2e4)}).strict(),l({...Si,action:b("submit"),taskProposal:Fs.optional(),generation:d().int().positive(),evidenceHash:D,formHash:D,executionResult:_n.optional(),answers:p(Vs).max(100),note:o().max(2e4)}).strict(),l({...Si,action:b("decide"),taskProposalHash:D.optional(),outcome:Ql.shape.outcome,submissions:Ql.shape.submissions,answers:Ql.shape.answers,note:Ql.shape.note}).strict()]),cU=lt("endpoint",[l({endpoint:b("command"),scope:Fe,command:lU}).strict(),l({endpoint:b("get"),scope:Fe,id:Fe,revision:d().int().positive().optional()}).strict(),l({endpoint:b("inbox"),scope:Fe,projectId:Fe.optional(),view:v(["mine","team","approval"]),status:v(["active","history"]),afterId:Fe.optional(),limit:d().int().min(1).max(100)}).strict()]),Nw=Uu.omit({evidence:!0,drafts:!0,submissions:!0}).extend({drafts:p(Uu.shape.drafts.element.omit({taskProposal:!0}).extend({taskProposal:Y0.optional()})).max(100),submissions:p($w.omit({taskProposal:!0}).extend({taskProposal:Y0.optional()})).max(1e3),evidence:Zv.nullable(),evidenceHash:D,formHash:D,permissions:l({owner:w(),manager:w(),reviewer:w(),claim:w()}).strict()}).strict(),dU=l({items:p(Nw).max(100),nextCursor:Fe.nullable(),actionCount:d().int().nonnegative(),approvalAvailable:w()}).strict(),Dw=l({endpoint:b("snapshot"),scope:Fe,projectId:Fe,graderId:Fe,selections:p(l({executionId:Fe,receiptId:Fe}).strict()).min(1).max(2)}).strict(),uU=l({endpoint:b("snapshot_tasks"),scope:Fe,projectId:Fe,graderId:Fe,dataset:_n,taskIds:p(Fe).min(1).max(1e3).optional(),all:b(!0).optional()}).strict().refine(e=>!!e.all!=!!e.taskIds,"Choose an exact selected task list or the server-frozen full Dataset."),mU=l({endpoint:b("inspect"),scope:Fe,id:Fe,slot:d().int().min(0).max(1).optional(),afterId:o().min(1).max(500).optional()}).strict(),pU=l({endpoint:b("results"),scope:Fe,executionId:Fe,selection:p(_n).max(1e4).optional()}).strict(),fU=l({endpoint:b("members"),scope:Fe}).strict(),hU=l({endpoint:b("execute"),scope:Fe,id:Fe,expectedRevision:d().int().positive(),generation:d().int().positive(),operationId:Fe,configuration:ie()}).strict(),gU=l({endpoint:b("execution"),scope:Fe,id:Fe,action:v(["status","result","cancel"])}).strict(),vU=Dw.omit({endpoint:!0}).extend({endpoint:b("publish_evidence"),operationId:Fe,audience:p(Fe).max(100),workspaceVisible:w()}).strict(),bU=l({endpoint:b("publication_access"),scope:Fe,projectId:Fe}).strict(),yU=l({endpoint:b("revoke_publication"),scope:Fe,publication:_n}).strict(),SU=l({endpoint:b("publish_author"),scope:Fe,id:Fe,expectedRevision:d().int().positive(),operationId:Fe,proposalHash:D,workspaceId:Fe.optional(),expectedWorkspaceRevision:d().int().positive().optional()}).strict(),xU=l({endpoint:b("author_tasks"),scope:Fe,id:Fe,includeReference:b(!0).optional()}).strict(),kU=l({endpoint:b("graders"),scope:Fe,projectId:Fe,dataset:_n}).strict(),zne=p(l({id:Fe,name:o(),version:o(),contentHash:D,mode:v(["individual","pairwise"])}).strict()).max(1e3),IU=ht([Gq,Wq,Ew,Vq,Kq,bU,SU,xU,kU,vU,yU,hU,gU,cU,Dw,uU,mU,pU,fU]),wU=p(l({origin:b("owner_attested_local").optional(),coverage:l({sourceEventCount:d().int().nonnegative(),publishedEventCount:d().int().nonnegative(),traceLimited:w(),artifactsIncluded:b(!1)}).strict().optional(),reviewId:Fe,reviewRevision:d().int().positive(),evidenceHash:D,slot:o(),input:ie(),output:ie(),error:o().nullable(),events:p(ae(o(),ie())),eventCount:d().int().nonnegative(),evidenceLimited:w(),nextEventCursor:o().nullable(),slotIndex:d().int().nonnegative(),executionId:Fe.optional(),receiptId:Fe.optional()}).strict()).max(1e3),Ka=v(["train","validation","test","frozen_eval"]),_U=l({path:o().trim().min(1).max(2e3).refine(RU),mediaType:o().trim().min(1).max(200),schemaRef:gn.nullable().default(null),maxBytes:d().int().positive().max(25e7).nullable().default(null),metadata:Mn}).strict(),CU=l({policyVisibleFields:p(T).max(1e3).default([]),privilegedFields:p(T).max(1e3).default([]),hiddenGraderRefs:p(T).max(1e3).default([]),connectedAppScopes:p(T).max(100).default([])}).strict(),Hw=l({protocolVersion:b("openpond.environment.v1"),kind:v(["text","agent","work","custom_program"]),entrypoint:o().trim().min(1).max(1e3),stateful:w(),deterministicSeeds:w(),lifecycle:p(v(["create","reset","step","collect","destroy"])).min(5).max(5),networkPolicy:v(["none","declared_read_only","declared_scoped"]),defaultTimeoutMs:d().int().positive().max(36e5)}).strict(),Pm=l({id:T,version:o().trim().min(1).max(100),weight:d().nonnegative().max(1e3).default(1),hardGate:w().default(!1),rewardEligible:w().default(!1),privileged:w().default(!1)}),Lw=Pm.extend({kind:v(["content","schema","artifact","runtime_event","state"]),config:ae(o(),ie())}).strict(),qw=Pm.extend({kind:b("model_judge"),rubricRef:gn,calibrationStatus:v(["pending","passed","failed"]),model:l({providerId:T,modelId:T,revision:o().trim().min(1).max(500).nullable()}).strict().optional(),temperature:d().min(0).max(2).optional()}).strict(),Uw=v(["isolated_javascript","sandbox_process"]),zw=Pm.extend({kind:b("custom_verifier"),runtime:Uw.optional(),verifierRef:gn,exportName:o().trim().min(1).max(240).optional(),timeoutMs:d().int().positive().max(3e5),networkPolicy:b("none")}).strict(),Bw=Pm.extend({kind:b("human"),rubricRef:gn,reviewerRole:o().trim().min(1).max(500),form:Rm.optional()}).strict(),Fw=ht([Lw,qw,zw,Bw]),Yv=l({id:T,clusterKey:T,split:Ka,input:ae(o(),ie()),expectedOutput:ae(o(),ie()).nullable(),policyVisibleContext:ae(o(),ie()).default({}),privilegedContextRef:T.nullable(),artifactRefs:p(gn).max(1e3).default([]),requiredOutputs:p(_U).max(1e3).optional(),tags:p(T).max(100).default([])}).strict(),Vw=l({schemaVersion:b("openpond.tasksetRelease.v2"),id:T,revision:d().int().positive(),policy:CU,environment:Hw,environmentRelease:l({id:T,contentHash:D}).strict().optional(),tools:p(Jc).max(200),capabilities:p(Cv).max(200),tasks:p(Yv).min(1).max(1e6),graders:p(Fw).min(1).max(1e3),verifierSetRelease:l({id:T,contentHash:D}).strict().optional(),metrics:ed.optional(),metadata:Mn}).strict(),Kw=Vw.extend({contentHash:D}).strict();function RU(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}const PU=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."),Qv=lt("kind",[l({kind:b("profile")}).strict(),l({kind:b("workflow"),workflowId:T}).strict(),l({kind:b("skill"),skillPath:PU}).strict(),l({kind:b("agent_action"),actionId:T}).strict()]),AU=l({taskId:T,seed:o().min(1).max(500),fixtureId:T.nullable()}).strict(),Q0=o().min(1).max(200).refine(e=>!["__proto__","prototype","constructor"].includes(e),"Use an ordinary field name."),X0=v(["input","output","expectedOutput","evaluatorContext"]),TU=p(l({graderId:T,fields:p(l({destination:X0,path:p(Q0).min(1).max(20),source:X0,sourcePath:p(Q0).max(20)}).strict()).max(100)}).strict()).max(100),EU=l({execution:V,originalEvidence:V,members:p(l({caseId:T,seed:o().min(1).max(500),fixtureId:D,sourceId:T,snapshotHash:D,boundaryRevisionHash:D}).strict()).min(1).max(500)}).strict(),MU=l({release:V.extend({revision:ht([d().int().positive(),o().min(1).max(200)])}).strict(),feedbackKey:o().min(1).max(240),configurationHash:D,output:v(["boolean","score","category"]),categories:p(o().min(1).max(120)).max(50)}).strict(),jU=l({schemaVersion:b("openpond.profileExternalDatasetBinding.v1"),dataset:V.extend({revision:d().int().positive()}).strict(),packageHash:D,profileId:T,target:Qv,declaredProfileCatalogHash:D.nullable(),protectedProfileClosureHash:D,recordedOrigin:EU.optional(),gradingSource:l({pass:V,evidence:V}).strict().optional(),split:Ka,population:p(AU).min(1).max(1e4),evaluators:p(MU).min(1).max(100),fieldMappingsHash:D,fieldMappings:TU,environmentHash:D,privateDatasetClosureHash:D,criterion:l({minimumPassRate:d().min(0).max(1),requireComplete:w()}).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."}),st(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."})}),Ko=jU.safeExtend({contentHash:D}).strict();function og(e){const t=Ko.parse(e),{contentHash:n,...a}=t;if(st(a)!==n)throw new Error("External Dataset binding integrity failed.");return t}const Ww=l({id:T,label:o().trim().min(1).max(240),description:o().max(4e3),target:Qv,tasksetRelease:V,split:Ka,taskIds:p(T).min(1).max(1e5),seeds:p(o().trim().min(1).max(500)).min(1).max(100),criterion:l({minimumPassRate:d().min(0).max(1),requireComplete:w()}).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."})}),Gw=l({id:T,label:o().trim().min(1).max(240),scope:v(["component","profile"]),definitionIds:p(T).min(1).max(1e3)}).strict();l({schemaVersion:b("openpond.profileEvaluations.v1"),definitions:p(Ww).max(1e3),suites:p(Gw).max(100)}).strict();const Ks=l({profileId:T,sourceRevision:o().trim().min(1).max(240),harnessRelease:V,catalogHash:D,definitionId:T,definitionHash:D,target:Qv,environmentHash:D,externalDatasetBinding:Ko.optional(),sourceCandidate:Hq.optional()}).strict();class Xv extends Error{code;status;constructor(t,n=422,a){super(a?`${t}: ${a}`:t),this.code=t,this.status=n,this.name="LearningDomainError"}}const OU=l({schemaVersion:b("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:D,responseHash:D,inputTokens:d().int().nonnegative().nullable(),outputTokens:d().int().nonnegative().nullable(),costUsd:d().finite().nonnegative().nullable()}).strict(),$U=l({schemaVersion:b("openpond.graderEvidence.v1"),graderId:T,graderVersion:o().trim().min(1).max(100),status:v(["scored","pending","unavailable","failed"]).optional(),score:d().min(0).max(1).nullable(),passed:w(),rewardEligible:w(),failureClass:Bc.nullable(),feedback:p(o().max(2e4)).max(1e3),visibleEvidenceRefs:p(T).max(1e4),privilegedEvidenceRefs:p(T).max(1e4),modelJudgeReceipt:OU.optional()}).strict(),Jw=$U.extend({contentHash:D}).strict(),NU=l({score:d().min(0).max(1).nullable(),passed:w(),rewardEligible:w(),failureClass:Bc.nullable(),gradingStatus:v(["scored","pending","unscorable","not_configured"])}).strict(),Zw=NU.extend({schemaVersion:b("openpond.taskGrade.v1"),taskHash:D,evidenceHash:D,graderSetHash:D,components:p(Jw).max(1e3),contentHash:D}).strict(),Vd={id:!0,version:!0,weight:!0,hardGate:!0,rewardEligible:!0,privileged:!0},Am=o().regex(/^[a-z][a-z0-9_]{0,79}$/);function Bne(e){return e.feedbackKey??`reward_${st(e.id).slice(0,24)}`}const DU=ht([Lw.omit(Vd),qw.omit(Vd),zw.omit(Vd),Bw.omit(Vd),l({kind:b("learned_model"),modelVersion:V,inputContract:gn}).strict()]),Yw=l({schemaVersion:b("openpond.rewardRelease.v1"),id:T,revision:d().int().positive(),name:o().trim().min(1).max(500),description:o().max(1e4),feedbackKey:Am.optional(),implementation:DU,rawScore:l({minimum:d().finite(),maximum:d().finite()}).strict(),assets:p(gn).max(1e3),fixtureSetRef:gn.optional(),calibrationCheckRef:V.extend({revision:d().int().positive()}).optional()}).strict().superRefine((e,t)=>{if(e.fixtureSetRef&&(e.fixtureSetRef.visibility!=="verifier"||!e.assets.some(n=>st(n)===st(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=Jv(e.implementation.config.jsonSchema);n.valid||t.addIssue({code:"custom",path:["implementation","config","jsonSchema"],message:n.issues[0].message})}}),Tm=Yw.safeExtend({contentHash:D}).strict(),cl=V.extend({revision:d().int().positive()}).strict(),HU=lt("kind",[l({kind:b("identity")}).strict(),l({kind:b("linear"),minimum:d().finite(),maximum:d().finite(),direction:v(["higher","lower"])}).strict()]),LU=l({graderId:T,reward:cl,role:v(["training","evaluation"]),normalization:HU,weight:d().nonnegative().max(1e3),required:w(),hardGate:w(),privileged:w(),fixtureRefs:p(V).max(1e3)}).strict(),qU=l({schemaVersion:b("openpond.rewardBinding.v1"),id:T,revision:d().int().positive(),name:o().trim().min(1).max(500).optional(),description:o().max(1e4).optional(),recipeRef:cl.optional(),sources:p(LU).max(100),aggregation:b("weighted_mean"),unscorable:b("exclude_optional_require_all_required")}).strict().superRefine((e,t)=>{new Set(e.sources.map(n=>n.graderId)).size!==e.sources.length&&t.addIssue({code:"custom",path:["sources"],message:"Bound grader identities must be unique."}),e.sources.length&&!e.sources.some(n=>n.weight>0)&&t.addIssue({code:"custom",path:["sources"],message:"A configured binding needs at least one positively weighted source."});for(const[n,a]of e.sources.entries())a.hardGate&&!a.required&&t.addIssue({code:"custom",path:["sources",n],message:"A hard gate must be required."}),a.normalization.kind==="linear"&&a.normalization.minimum>=a.normalization.maximum&&t.addIssue({code:"custom",path:["sources",n,"normalization"],message:"Linear normalization requires minimum < maximum."})}),Em=qU.safeExtend({contentHash:D}).strict(),UU=l({graderId:T,reward:cl,role:v(["training","evaluation"]),status:v(["scored","pending","unavailable","failed"]),rawScore:d().finite().nullable(),normalizedScore:d().min(0).max(1).nullable(),passed:w().nullable(),evidenceHashes:p(D).max(1e3),graderEvidence:Jw.optional(),message:o().max(2e4).nullable()}).strict(),zU=l({schemaVersion:b("openpond.rewardComposition.v1"),binding:cl,taskHash:D,outputHash:D,results:p(UU).max(100),training:l({status:v(["scored","pending","unscorable","not_configured"]),score:d().min(0).max(1).nullable(),passed:w().nullable()}).strict(),evaluation:l({status:v(["scored","pending","unscorable","not_configured"]),score:d().min(0).max(1).nullable(),passed:w().nullable()}).strict()}).strict(),Ic=zU.extend({contentHash:D}).strict();function Fne(e){Hi(e);const t=Yw.parse(e);return Tm.parse({...t,contentHash:st(t)})}const td=l({harnessRelease:V,agentSnapshot:V,sourcePackageHash:D}).strict(),eh=o().trim().min(1).max(200),eb=l({sessionId:eh,turnId:eh,source:td,admissionHash:D,modelConfigurationHash:D,traceHash:D,runtimeEventRefs:p(eh).max(1e4),startedAt:he,completedAt:he,outputHash:D,partialOutputAvailable:w()}).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."})}),BU=l({schemaVersion:b("openpond.nativeHarnessExperimentAttempt.v1"),taskId:o().min(1).max(500),status:v(["completed","cancelled","timed_out","policy_failure"]),output:o().max(8388608).nullable(),error:o().max(2e3).nullable(),messages:p(ie()).max(4002),collected:w(),environmentCleanupComplete:b(!0),snapshot:al(),native:eb}).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!==st(e.output))&&t.addIssue({code:"custom",path:["native","outputHash"],message:"Native output differs from its retained evidence."})});BU.extend({contentHash:D}).strict();const Qw=d().finite().nonnegative(),Xw=lt("kind",[l({kind:b("model"),modelId:T,configurationHash:D}).strict(),l({kind:b("harness"),source:Ks,model:l({modelId:T,configurationHash:D}).strict()}).strict(),l({kind:b("agent"),source:td,model:l({modelId:T,configurationHash:D}).strict()}).strict(),l({kind:b("fixture"),configurationHash:D}).strict()]),e_=l({release:V.extend({revision:ht([d().int().positive(),o().trim().min(1).max(200)])}).strict(),feedbackKey:Am,configurationHash:D.optional(),output:v(["boolean","score","category"]),categories:p(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."})}),tb=l({caseId:T,seed:o().trim().min(1).max(500),fixtureId:T.nullable()}).strict();function wc(e){const t=tb.parse(e);return JSON.stringify([t.caseId,t.seed,t.fixtureId])}function FU(e,t,n){return`human-projection-${st({originalManifest:e,selectionHash:t,rulesHash:n}).slice(0,48)}`}const VU=l({schemaVersion:b("openpond.experimentManifest.v1"),id:T,name:o().trim().min(1).max(500),teamId:T,operationId:T,maximumCostUsd:Qw.nullable(),dataset:V.extend({revision:d().int().positive()}).strict(),target:Xw,execution:l({packageHash:D,runtimeTargetHash:D,metricPolicyHash:D,compatibility:l({protocol:b("openpond.evaluation-execution.v1"),targetKind:v(["model","agent","harness","fixture"])}).strict().optional()}).strict().optional(),lineage:l({definition:V.extend({revision:d().int().positive()}).strict().nullable(),execution:V,scoringPassId:T.nullable(),humanProjection:l({originalManifest:V,selectionHash:D,rulesHash:D}).strict().optional()}).strict().optional(),evaluators:p(e_).max(100),population:p(tb).min(1).max(1e4),createdAt:he}).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!==FU(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."})}),ro=VU.extend({contentHash:D}).strict(),KU=l({feedbackKey:Am,evaluator:e_.shape.release,status:v(["scored","unavailable","failed","pending"]),value:ht([w(),d().finite(),o().max(500)]).nullable(),passed:w().nullable().optional(),reasoning:o().max(2e4).nullable(),evidenceRefs:p(Ia).max(1e3)}).strict(),WU=l({inputTokens:d().int().nonnegative().nullable(),outputTokens:d().int().nonnegative().nullable(),totalTokens:d().int().nonnegative().nullable(),costUsd:Qw.nullable(),latencyMs:d().finite().nonnegative().nullable()}).strict().superRefine((e,t)=>{e.inputTokens!==null&&e.outputTokens!==null&&e.totalTokens!==null&&e.totalTokens<e.inputTokens+e.outputTokens&&t.addIssue({code:"custom",path:["totalTokens"],message:"Total tokens cannot be less than input plus output."})}),GU=l({identity:tb,status:v(["completed","failed","cancelled","unavailable"]),output:ie().nullable(),error:l({code:T,message:o().max(2e3)}).strict().nullable(),feedback:p(KU).max(100),usage:WU,traceRef:Ia.nullable(),startedAt:he.nullable(),completedAt:he.nullable()}).strict(),t_=l({schemaVersion:b("openpond.experimentResult.v1"),manifest:V,status:v(["completed","failed","cancelled"]),cases:p(GU).min(1).max(1e4),completedAt:he}).strict(),so=t_.extend({contentHash:D}).strict();function JU(e,t){ro.parse(t),T2(t,"Experiment manifest");const n=t_.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)),i=new Set,r=new Map(t.evaluators.map(s=>[s.feedbackKey,s]));for(const s of n.cases){const c=wc(s.identity);if(!a.has(c)||i.has(c))throw new Error("Experiment result has an unexpected or repeated case.");i.add(c);const m=new Set;for(const u of s.feedback){const h=r.get(u.feedbackKey);if(!h||m.has(u.feedbackKey)||u.evaluator.id!==h.release.id||u.evaluator.contentHash!==h.release.contentHash||u.evaluator.revision!==h.release.revision)throw new Error("Experiment feedback differs from its pinned evaluator.");if(m.add(u.feedbackKey),u.status==="scored"){if(u.value===null||typeof u.value!=={boolean:"boolean",score:"number",category:"string"}[h.output]||h.output==="category"&&!h.categories.includes(u.value)||h.output==="score"&&(u.value<0||u.value>1))throw new Error("Experiment feedback value violates its output contract.")}else if(u.value!==null||u.passed!==null&&u.passed!==void 0)throw new Error("Unscored experiment feedback cannot claim a value or pass decision.")}}if(i.size!==a.size)throw new Error("Experiment result omits admitted cases.");return so.parse({...n,contentHash:st(n)})}function wr(e){const t=ro.parse(e.manifest),n=so.parse(e.result),{contentHash:a,...i}=n;if(st(i)!==a)throw new Error("Experiment result integrity failed.");return JU(i,t),{manifest:t,result:n}}function ZU(e,t){for(const g of[e,t])wr(g);const n=[];e.manifest.teamId!==t.manifest.teamId&&n.push("different_workspace"),(e.manifest.dataset.id!==t.manifest.dataset.id||e.manifest.dataset.contentHash!==t.manifest.dataset.contentHash||e.manifest.dataset.revision!==t.manifest.dataset.revision)&&n.push("different_dataset_version"),e.manifest.target.kind!==t.manifest.target.kind&&n.push("different_target_kind");const a=g=>{const S=g.execution;if(!S?.compatibility)return S??null;const{runtimeTargetHash:k,...C}=S;return C};if(st(a(e.manifest))!==st(a(t.manifest))&&n.push("different_execution_contract"),e.manifest.target.kind==="harness"&&t.manifest.target.kind==="harness"){const g=e.manifest.target.source,S=t.manifest.target.source;(g.profileId!==S.profileId||st(g.target)!==st(S.target))&&n.push("different_component");const k=e.manifest.execution?.compatibility&&t.manifest.execution?.compatibility&&e.manifest.execution.packageHash===t.manifest.execution.packageHash;g.environmentHash!==S.environmentHash&&!k&&n.push("different_environment"),(g.definitionId!==S.definitionId||g.definitionHash!==S.definitionHash)&&n.push("different_evaluation_definition")}const i=g=>[...g.evaluators].sort((S,k)=>S.feedbackKey.localeCompare(k.feedbackKey));st(i(e.manifest))!==st(i(t.manifest))&&n.push("different_evaluators");const r=new Map(e.result.cases.map(g=>[wc(g.identity),g])),s=new Map(t.result.cases.map(g=>[wc(g.identity),g])),c=[...new Set([...r.keys(),...s.keys()])].sort();(r.size!==s.size||c.some(g=>!r.has(g)||!s.has(g)))&&n.push("different_population");const m=n.length===0,u=c.map(g=>{const S=r.get(g)??null,k=s.get(g)??null,C=new Map(S?.feedback.map(M=>[M.feedbackKey,M])??[]),A=new Map(k?.feedback.map(M=>[M.feedbackKey,M])??[]);return{identity:(S??k).identity,baseline:S,candidate:k,feedback:e.manifest.evaluators.map(M=>{const R=C.get(M.feedbackKey),$=A.get(M.feedbackKey),O=m?!S||!k?"missing_case":S.status!=="completed"||k.status!=="completed"||S.error||k.error?"case_not_completed":!R||!$||R.status!=="scored"||$.status!=="scored"?"feedback_unavailable":M.output==="category"?"categorical_feedback":null:"incompatible_experiments",j=L=>typeof L?.value=="boolean"?Number(L.value):typeof L?.value=="number"?L.value:null,I=O?null:j(R),P=O?null:j($),E=L=>O?null:typeof L?.value=="boolean"?L.value:L?.passed??null;return{feedbackKey:M.feedbackKey,eligible:O===null,reason:O,baseline:I,candidate:P,delta:I===null||P===null?null:P-I,baselinePassed:E(R),candidatePassed:E($)}})}}),h=e.manifest.evaluators.map((g,S)=>{const k=u.map(j=>j.feedback[S]).filter(j=>j.eligible),C=j=>k.length?k.reduce((I,P)=>I+P[j],0)/k.length:null,A=C("baseline"),M=C("candidate"),R=j=>k.length&&k.every(I=>I[j]!==null)?k.reduce((I,P)=>I+Number(P[j]),0)/k.length:null,$=R("baselinePassed"),O=R("candidatePassed");return{feedbackKey:g.feedbackKey,eligibleCount:k.length,excludedCount:u.length-k.length,baseline:A,candidate:M,delta:A===null||M===null?null:M-A,baselinePassRate:$,candidatePassRate:O,passRateDelta:$===null||O===null?null:O-$}});return{comparable:m,reasons:n,cases:u,metrics:h}}const $o=o().trim().min(1).max(200),Xl=o().regex(/^[a-f0-9]{64}$/),YU=l({id:$o,contentHash:Xl}).strict(),Mm=l({schemaVersion:b("openpond.trainingHandoffOrigin.v1"),teamId:$o,projectId:$o.nullable(),configurationId:$o,source:l({executionId:$o,passId:$o.nullable(),manifestHash:Xl,resultHash:Xl}).strict(),dataset:l({id:$o,revision:d().int().positive(),contentHash:Xl}).strict(),target:Xw,graders:p(l({feedbackKey:$o,evaluator:YU,expectedCount:d().int().positive(),scoredCount:d().int().nonnegative(),score:d().finite().nullable()}).strict()).max(100),contentHash:Xl}).strict(),QU=l({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:d().int().nonnegative().nullable(),outputTokens:d().int().nonnegative().nullable(),costUsd:d().finite().nonnegative().nullable()}).strict(),XU=l({id:T,requestHash:D,reservedUsd:d().finite().positive(),status:v(["reserved","settled","not_dispatched"]),response:QU.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."})}),n_=l({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(),Jt=ae(o(),Vo()),yt=cl,jo=o().max(2e3).refine(e=>e===""||e.startsWith("/")&&!/~(?![01])/u.test(e),"Use an RFC 6901 JSON pointer."),ez=l({schemaVersion:b("openpond.taskDefinition.v1"),id:T,revision:d().int().positive(),name:o().trim().min(1).max(500),description:o().max(1e4),instructions:o().trim().min(1).max(2e4),category:v(["structured","question_answering","coding","tool_workflow","custom"]),familyNamespace:T,inputSchema:ae(o(),ie()),outputSchema:ae(o(),ie()),requiredOutputs:Yv.shape.requiredOutputs,contextRequirements:p(o().trim().min(1).max(2e3)).max(100).optional(),rewardBinding:yt,harness:V.nullable(),execution:Vw.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 i=Jv(a);i.valid||t.addIssue({code:"custom",path:[n],message:i.issues[0].message})}!!e.execution.environmentRelease!=!!e.execution.verifierSetRelease&&t.addIssue({code:"custom",path:["execution"],message:"Bind both the environment and verifier-set releases."})}),nd=ez.safeExtend({contentHash:D}).strict(),tz=l({schemaVersion:b("openpond.taskSourceMapping.v1"),exampleId:jo,attemptId:jo,occurredAt:jo,input:jo,observedOutput:jo.nullable(),expected:jo.nullable(),evaluatorContext:jo.nullable(),familyKey:jo,split:Ka}).strict(),nz=l({modelId:T,packageHash:D,taskset:yt,batch:yt,rewardBinding:yt}).strict(),az=l({schemaVersion:b("openpond.learningSource.v1"),id:T,revision:d().int().positive(),name:o().trim().min(1).max(500),kind:v(["direct","benchmark","work","opentelemetry","provider"]),taskDefinition:yt,enabled:w(),allowedSplits:p(Ka).min(1).max(4),mapping:tz.nullable(),adapterVersion:o().trim().min(1).max(200).nullable(),reviewOrigin:nz.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."})}),jm=az.safeExtend({contentHash:D}).strict(),iz=l({schemaVersion:b("openpond.taskExample.v1"),sourceId:T,idempotencyKey:T,taskDefinition:yt,exampleId:T,attemptId:T,occurredAt:he,familyKey:T.nullable(),split:Ka,input:Jt,observedOutput:Jt.nullable(),expected:Jt.nullable(),evaluatorContext:Jt.nullable(),assets:p(gn).max(1e3),requiredOutputs:Yv.shape.requiredOutputs,provenance:l({sourceRecordRef:o().max(2e3).nullable(),mappingHash:D.nullable()}).strict()}).strict(),oz=l({schemaVersion:b("openpond.taskEvidence.v1"),id:T,revision:d().int().positive(),source:yt,submission:iz,supersedes:yt.nullable(),correctionFeedbackId:T.nullable(),receivedAt:he}).strict(),Om=oz.extend({contentHash:D}).strict(),rz=l({schemaVersion:b("openpond.taskRating.v1"),criteria:o().trim().min(1).max(2e4),scale:l({minimum:d().finite(),maximum:d().finite()}).strict(),score:d().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."})}),sz=l({schemaVersion:b("openpond.taskFeedback.v1"),sourceId:T,idempotencyKey:T,exampleId:T,attemptId:T,expectedEvidenceHash:D.nullable(),occurredAt:he,kind:v(["outcome","target_correction","ground_truth_correction","input_correction","family_resolution"]),value:Jt,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=rz.safeParse(e.value);if(!n.success)for(const a of n.error.issues)t.addIssue({code:"custom",path:["value",...a.path],message:a.message})}),a_=l({schemaVersion:b("openpond.taskFeedbackRecord.v1"),id:T,submission:sz,status:v(["pending_example","pending_review","applied","superseded","rejected"]),evidence:yt.nullable(),createdAt:he,revision:d().int().positive(),submittedBy:l({id:T,role:v(["editor","reviewer","source"]),sourceId:T.nullable()}).strict().nullable().default(null),review:l({actorId:T,decision:yt.nullable(),note:o().max(2e4),resolvedAt:he}).strict().nullable().default(null)}).strict(),lz=l({schemaVersion:b("openpond.taskAdmissionDecision.v1"),id:T,revision:d().int().positive(),evidence:yt,supersedes:yt.nullable(),actor:l({kind:v(["human","qualified_policy"]),id:T,policy:yt.nullable()}).strict(),evidenceValidity:v(["valid","invalid","pending"]),taskAdmissibility:v(["approved","rejected","pending"]),observedQuality:v(["passed","failed","unscored","unavailable"]),targetApproval:v(["approved","rejected","pending","not_required"]),approvedTarget:Jt.nullable(),grade:Ic.nullable(),targetGrade:Ic.nullable(),note:o().max(2e4),decidedAt:he}).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."})}),nb=lz.safeExtend({contentHash:D}).strict(),cz=l({schemaVersion:b("openpond.taskBatch.v1"),id:T,revision:b(1),taskDefinition:yt,rewardBinding:yt,purpose:v(["supervised_training","reward_training","evaluation"]),examples:p(l({evidence:yt,decision:yt,familyKey:T,inputHash:D,split:Ka}).strict()).min(1).max(1e4),sealedAt:he,sealedBy:T}).strict().superRefine((e,t)=>{new Set(e.examples.map(a=>a.evidence.id)).size!==e.examples.length&&t.addIssue({code:"custom",path:["examples"],message:"Each evidence identity can occur only once in a batch."});const n=new Map;for(const[a,i]of e.examples.entries()){e.purpose==="evaluation"==(i.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:${i.familyKey}`,`input:${i.inputHash}`])n.has(r)&&n.get(r)!==i.split&&t.addIssue({code:"custom",path:["examples",a],message:"A task family or identical input cannot cross splits."}),n.set(r,i.split)}}),ab=cz.safeExtend({contentHash:D}).strict(),dz=l({origin:Mm.optional(),schemaVersion:b("openpond.learningPolicy.v1"),id:T,revision:d().int().positive(),modelProjectId:T,executionOwner:v(["local","hosted"]),enabled:w(),sources:p(yt).min(1).max(100),taskDefinition:yt,rewardBinding:yt,admission:l({mode:v(["human","qualified_automatic"]),qualification:V.nullable(),minimumApprovedExamples:d().int().positive().max(1e5)}).strict(),trigger:lt("kind",[l({kind:b("manual")}).strict(),l({kind:b("approved_count")}).strict(),l({kind:b("schedule"),intervalSeconds:d().int().min(60).max(31536e3)}).strict(),n_.extend({kind:b("nightly")}).strict(),l({kind:b("upstream_accepted"),modelProjectId:T}).strict()]),trainingParent:V,teacher:V.nullable(),training:l({method:v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),recipe:V,retentionEvaluation:V,replayBatches:p(V).max(100)}).strict(),limits:l({maxIterationSpendUsd:d().positive().max(1e5),maxDailySpendUsd:d().positive().max(1e6),cooldownSeconds:d().int().nonnegative().max(31536e3),maxRetries:d().int().nonnegative().max(10),maxBatchExamples:d().int().positive().max(1e4),maxBacklogExamples:d().int().positive().max(1e6)}).strict(),automation:l({collect:w(),train:w(),accept:w(),serve:w()}).strict(),acceptance:l({minimumScore:d().min(0).max(1),maximumRetentionRegression:d().min(0).max(1),requireImprovement:w(),rollbackVersion:V.nullable()}).strict()}).strict().superRefine((e,t)=>{e.admission.mode==="qualified_automatic"&&!e.admission.qualification&&t.addIssue({code:"custom",path:["admission"],message:"Automatic admission requires qualification evidence."}),e.automation.serve&&!e.automation.accept&&t.addIssue({code:"custom",path:["automation"],message:"Automatic serving requires configured acceptance."}),e.automation.accept&&!e.acceptance.rollbackVersion&&t.addIssue({code:"custom",path:["acceptance"],message:"Automatic acceptance requires a rollback version."}),e.trigger.kind==="upstream_accepted"&&e.trigger.modelProjectId===e.modelProjectId&&t.addIssue({code:"custom",path:["trigger"],message:"A model cannot trigger itself through upstream acceptance."}),e.limits.maxBatchExamples<e.admission.minimumApprovedExamples&&t.addIssue({code:"custom",path:["limits"],message:"The batch limit must permit the minimum approved example count."}),e.limits.maxDailySpendUsd<e.limits.maxIterationSpendUsd&&t.addIssue({code:"custom",path:["limits"],message:"Daily spend must permit the iteration budget."})}),i_=dz.safeExtend({contentHash:D}).strict(),ib=l({iterationId:T,iterationRevision:d().int().positive(),candidate:V,decision:yt,decidedAt:he}).strict(),uz=v(["waiting_for_data","waiting_for_review","ready","dispatching","training","evaluating","candidate_ready","accepted","rejected","paused","failed","cancelling","cancelled","completed_without_candidate"]),o_=l({schemaVersion:b("openpond.learningIteration.v1"),id:T,revision:d().int().positive(),policy:yt,status:uz,triggerIdentity:T,batch:yt.nullable(),sourceWatermarks:ae(T,d().int().nonnegative()),trainingParent:V,trainingParentSelection:ib.nullable().optional(),teacher:V.nullable(),upstreamEvent:V.nullable(),trainingJob:V.nullable(),evaluationJob:V.nullable(),candidateVersion:V.nullable(),candidateDecision:yt.nullable().default(null),candidateDecisionAt:he.nullable().optional(),dispatchId:T,retryCount:d().int().nonnegative(),spendUsd:d().nonnegative(),failure:l({code:T,message:o().max(2e4)}).strict().nullable(),createdAt:he,updatedAt:he}).strict(),mz=l({schemaVersion:b("openpond.taskGradeRun.v1"),id:T,revision:d().int().positive(),evidence:yt,binding:yt,target:v(["observed","proposed_target"]),output:Jt,status:v(["queued","running","completed","failed","cancelling","cancelled"]),composition:Ic.nullable(),leaseOwner:T.nullable(),leaseExpiresAt:he.nullable(),attemptCount:d().int().nonnegative(),timeoutMs:d().int().min(100).max(3e5),maximumSpendUsd:d().nonnegative().max(1e3),judgeCalls:p(XU).max(1e4).optional(),requestedBy:T.optional(),failure:o().max(2e4).nullable(),createdAt:he,updatedAt:he}).strict();ht([nd,Tm,Em,jm,Om,a_,nb,ab,i_,o_,mz]);function pz(e){return yt.parse({id:e.id,revision:e.revision,contentHash:e.contentHash})}function Vne(e,t){return e.id===t.id&&e.revision===t.revision&&e.contentHash===t.contentHash}function Kne(e){return Hi(e,16777216),{...e,contentHash:st(e)}}function Wne(e){const{contentHash:t,...n}=e;if(Hi(n,16777216),st(n)!==t)throw new Xv("learning_content_hash_mismatch",422)}const r_=l({schemaVersion:b("openpond.learningTextAsset.v1"),id:T,revision:b(1),asset:gn,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!==rv(e.text)&&t.addIssue({code:"custom",path:["asset","contentHash"],message:"Asset source does not match its SHA-256."})}),$m=r_.safeExtend({contentHash:D}).strict();function Gne(e){Hi(e);const{text:t,...n}=e,a=rv(t),i=`asset-${a}-${st(n).slice(0,16)}`,r=r_.parse({schemaVersion:"openpond.learningTextAsset.v1",id:i,revision:1,asset:{...n,id:i,contentHash:a,sizeBytes:new TextEncoder().encode(t).byteLength},text:t});return $m.parse({...r,contentHash:st(r)})}function Jne(e,t){const{contentHash:n,...a}=$m.parse(e);if(st(a)!==n||st(a.asset)!==st(t))throw new Xv("learning_asset_reference_mismatch",409);return a.text}const fz=lt("kind",[l({kind:b("manual"),identity:T}).strict(),l({kind:b("schedule"),scheduledAt:he}).strict(),l({kind:b("approved_count"),checkedAt:he}).strict()]),hz=l({schemaVersion:b("openpond.learningChain.v1"),id:T,revision:d().int().positive(),modelProjectId:T,activeIterationId:T.nullable(),acceptedParent:ib.nullable().optional(),latestIterationId:T,lastReservedAt:he.nullable(),updatedAt:he}).strict(),s_=l({eligible:d().int().nonnegative(),awaitingReview:d().int().nonnegative(),excluded:d().int().nonnegative(),consumed:d().int().nonnegative()}).strict(),Zne=l({schemaVersion:b("openpond.learningConsumption.v1"),id:T,revision:b(1),chainId:T,iterationId:T,evidence:yt,decision:yt,reservedAt:he}).strict(),Yne=l({schemaVersion:b("openpond.learningIterationReservation.v1"),id:T,revision:d().int().positive(),chainId:T,iterationId:T,policy:yt,trigger:fz,requestHash:D,outcome:v(["reserved","waiting_for_data","waiting_for_review"]),counts:s_,budget:l({maximumSpendUsd:d().nonnegative(),reservedSpendUsd:d().nonnegative(),settledSpendUsd:d().nonnegative(),settledAt:he.nullable()}).strict(),createdAt:he,updatedAt:he}).strict(),ai={bytes:5*1024*1024,records:1e3,files:100,messages:2e3},l_=v(["json","jsonl","csv","hermes","openclaw"]),gz=l({path:o().min(1).max(500),text:o()}).strict(),ob=l({id:o().min(1).max(200),familyKey:o().min(1).max(200),split:Ka,kind:v(["task","attempt"]),input:Jt,observedOutput:Jt.nullable(),expected:Jt.nullable(),sourceId:o().min(1).max(2e3),sourceHash:o().length(64),occurredAt:o().datetime().nullable(),metadata:Jt,warnings:p(o().max(2e3)).max(100),needsContext:w()}).strict(),c_=l({schemaVersion:b("openpond.taskIntakePreview.v1"),format:l_,contentHash:o().length(64),records:p(ob).max(ai.records),issues:p(l({file:o(),row:d().int().positive().nullable(),message:o()}).strict()).max(1e3)}).strict();function zu(e,t){return`${e}-${st(t)}`}function d_(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 vz=l({policy:yt,modelProjectId:T,inspectedAt:he,chain:hz.nullable(),trainingParent:l({reference:V,selection:ib.nullable()}).strict().nullable().default(null),counts:s_.nullable(),minimumApprovedExamples:d().int().positive(),canReserve:w(),blockers:p(l({code:o().min(1).max(200),message:o().min(1).max(2e4)}).strict()).max(20),cooldownUntil:he.nullable(),budget:l({reservedSpendUsd:d().nonnegative(),settledSpendUsd:d().nonnegative(),committedSpendUsd:d().nonnegative(),maximumIterationSpendUsd:d().nonnegative(),maximumDailySpendUsd:d().nonnegative()}).strict()}).strict();function bz(e){const t=[];let n=[],a="",i=!1,r=!1;const s=()=>{n.push(a),a="",r=!1},c=()=>{if(s(),n.some(h=>h.length)&&t.push(n),n=[],t.length>ai.records+1)throw new Error("CSV exceeds the 1,000-record limit.")};for(let h=0;h<e.length;h++){const g=e[h];if(i)g==='"'&&e[h+1]==='"'?(a+='"',h++):g==='"'?(i=!1,r=!0):a+=g;else if(g===",")s();else if(g===`
175
+ `||g==="\r")g==="\r"&&e[h+1]===`
176
+ `&&h++,c();else if(g==='"'&&!a&&!r)i=!0;else{if(r||g==='"')throw new Error("CSV has an invalid quoted field.");a+=g}}if(i)throw new Error("CSV has an unterminated quoted field.");(a||n.length||r)&&c();const m=t.shift()?.map(h=>h.trim().replace(/^\uFEFF/u,""));if(!m?.includes("instruction"))throw new Error("CSV requires an instruction column.");const u=new Set(["instruction","context","reference","labels","id","familyKey","split"]);if(m.some(h=>!u.has(h))||new Set(m).size!==m.length)throw new Error("CSV has duplicate or unsupported columns. Use instruction, context, reference, labels, id, familyKey and split.");return t.map((h,g)=>{if(h.length!==m.length)throw new Error(`CSV record ${g+2} has a different number of columns from its header.`);return Object.fromEntries(m.map((S,k)=>[S,h[k]]).filter(([,S])=>S!==""))})}function Qne(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 u_(e){return e.startsWith("\uFEFF")?e.slice(1):e}const m_=l({role:o().min(1),content:Vo().nullable().optional()}).catchall(Vo()),yz=l({id:o().min(1),messages:p(m_).min(1).max(ai.messages),lineage_session_ids:p(o()).optional(),parent_session_id:o().nullable().optional()}).catchall(Vo());function Sz(e){const t=yz.parse(e),n=t.lineage_session_ids?.[0]??t.parent_session_id??t.id,{messages:a,segments:i,...r}=t;return p_("hermes",t.id,n,t.messages,{sourceHash:st(e),metadata:{session:r},warnings:["Imported session context and tools need review before this can become an executable task."]})}const xz=l({traceSchema:b("openclaw-trajectory"),schemaVersion:b(1),traceId:o().min(1),sessionId:o().min(1),leafId:o().nullable(),eventCount:d().int().nonnegative(),warnings:p(Jt).optional()}).catchall(Vo()),kz=l({traceSchema:b("openclaw-trajectory"),schemaVersion:b(1),traceId:o(),sessionId:o(),seq:d().int().nonnegative(),type:o(),ts:o()}).catchall(Vo()),Iz=l({header:Jt.nullable(),leafId:o().nullable(),entries:p(l({id:o().min(1),type:o().min(1),parentId:o().nullable().optional(),message:m_.optional()}).catchall(Vo())).max(ai.messages)}).strict();function wz(e){const t=c=>{const m=e.find(u=>u.path===c);if(!m)throw new Error(`OpenClaw bundle is missing ${c}.`);return u_(m.text)},n=xz.parse(JSON.parse(t("manifest.json"))),a=Iz.parse(JSON.parse(t("session-branch.json")));if(a.leafId!==n.leafId)throw new Error("OpenClaw manifest and session branch identify different leaves.");const i=t("events.jsonl").split(/\r?\n/u).filter(c=>c.trim()).map(c=>kz.parse(JSON.parse(c)));if(i.length!==n.eventCount||i.some(c=>c.traceId!==n.traceId||c.sessionId!==n.sessionId))throw new Error("OpenClaw events do not match the manifest identity or count.");if(a.header&&a.header.id!==n.sessionId)throw new Error("OpenClaw session header does not match the manifest.");const r=new Set;for(const[c,m]of a.entries.entries()){if(r.has(m.id))throw new Error("OpenClaw branch contains duplicate entry IDs.");if(c&&m.parentId!==a.entries[c-1].id)throw new Error("OpenClaw branch is incomplete or out of order.");r.add(m.id)}if(a.entries.length&&a.entries.at(-1).id!==a.leafId)throw new Error("OpenClaw branch does not reach its declared leaf.");const s=a.entries.filter(c=>c.type==="message"&&c.message).map(c=>({...c.message,entryId:c.id,timestamp:typeof c.timestamp=="string"?c.timestamp:typeof c.message.timestamp=="number"?new Date(c.message.timestamp).toISOString():null}));return p_("openclaw",n.sessionId,n.sessionId,s,{sourceHash:st(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 p_(e,t,n,a,i){const r=a.flatMap((c,m)=>c.role==="user"?[m]:[]);if(!r.length)throw new Error("This history contains no user request. Supply a session with its request context.");let s=0;return r.map((c,m)=>{const u=r[m+1]??a.length,h=a.slice(c+1,u),g=h.filter(A=>A.role==="assistant").at(-1),S=a[c],k=S.entryId??S.message_id??S.id??st({start:c,request:S}),C={id:zu(e,[t,k]),familyKey:zu(e,n),split:"train",kind:"attempt",input:{request:S.content??null,messages:a.slice(0,c+1)},observedOutput:g?{response:g.content??null,messages:h}:null,expected:null,sourceId:`${e}:${t}:${String(k)}`,sourceHash:i.sourceHash,occurredAt:d_(g?.timestamp??S.timestamp),metadata:i.metadata,warnings:[...i.warnings,...g?[]:["No assistant response was recorded for this request."]],needsContext:!0};if(Hi(C),s+=new TextEncoder().encode(JSON.stringify(C)).length,s>ai.bytes)throw new Error("Expanded history exceeds the 5 MiB preview limit. Export a smaller session selection.");return ob.parse(C)})}const _z=l({instruction:o().trim().min(1).max(1e5),context:ht([o(),Jt]).optional(),reference:ht([o(),Jt]).optional(),labels:ht([o(),p(o()),Jt]).optional(),id:o().min(1).max(200).optional(),familyKey:o().min(1).max(200).optional(),split:Ka.optional()}).strict(),Cz=l({input:Jt,observedOutput:Jt.nullable().optional(),expectedOutput:Jt.nullable().optional(),id:o().min(1).max(200).optional(),familyKey:o().min(1).max(200).optional(),split:Ka.optional(),occurredAt:o().datetime().optional(),labels:Jt.optional()}).strict();function Rz(e){const t=l_.parse(e.format),n=p(gz).min(1).max(ai.files).parse(e.files);if(n.reduce((u,h)=>u+new TextEncoder().encode(h.text).length,0)>ai.bytes)throw new Error("Import exceeds the 5 MiB size limit.");if(n.some(u=>u.path.startsWith("/")||u.path.includes("\\")||u.path.split("/").some(h=>!h||h==="."||h===".."))||new Set(n.map(u=>u.path)).size!==n.length)throw new Error("Import contains an unsafe or duplicate file path.");const a=[],i=[],r=new Map,s=new Map;let c=0;function m(u,h,g){try{const S=g();if(a.length+S.length>ai.records)throw new Error("Import exceeds the 1,000-record limit.");const k=new Map(r),C=new Map(s);let A=0;for(const M of S){Hi(M);const R=st(M),$=k.get(M.id);if($&&$!==R)throw new Error("The same record identity has different content in this upload.");$||(A+=new TextEncoder().encode(JSON.stringify(M)).length),k.set(M.id,R);for(const O of[`family:${M.familyKey}`,`input:${st(M.input)}`]){if(C.has(O)&&C.get(O)!==M.split)throw new Error("The same task family or request occurs in different splits.");C.set(O,M.split)}}if(c+A>ai.bytes*2)throw new Error("Expanded import exceeds the 10 MiB preview limit. Select fewer source files.");for(const M of S)r.has(M.id)||a.push(M),r.set(M.id,st(M));for(const[M,R]of C)s.set(M,R);c+=A}catch(S){i.push({file:u,row:h,message:S instanceof SO?`Unsupported record fields or values (${S.issues.slice(0,3).map(k=>k.path.join(".")||"record").join(", ")}).`:S instanceof SyntaxError?"Invalid JSON.":S instanceof Error?S.message:"Invalid import record."})}}if(t==="openclaw")m("manifest.json",null,()=>wz(n));else for(const u of n){const h=u_(u.text);if(t==="jsonl"||t==="hermes"){for(const[g,S]of h.split(/\r?\n/u).entries())if(S.trim()){if(i.length>=ai.records)break;m(u.path,g+1,()=>t==="hermes"?Sz(JSON.parse(S)):[eS(JSON.parse(S))])}}else{let g;try{const S=t==="csv"?bz(h):JSON.parse(h);g=Array.isArray(S)?S:[S]}catch(S){m(u.path,null,()=>{throw S});continue}if(g.length>ai.records){m(u.path,null,()=>{throw new Error("Import exceeds the 1,000-record limit.")});continue}g.forEach((S,k)=>m(u.path,k+(t==="csv"?2:1),()=>[eS(S)]))}}return c_.parse({schemaVersion:"openpond.taskIntakePreview.v1",format:t,contentHash:st({format:t,files:n}),records:a,issues:i.slice(0,1e3)})}function eS(e){const t=ht([_z,Cz]).parse(e),n="instruction"in t,a=n?{instruction:t.instruction,...t.context===void 0?{}:{context:t.context}}:t.input,i=n?t.reference===void 0?null:typeof t.reference=="string"?{text:t.reference}:t.reference:t.expectedOutput??null,r=n?null:t.observedOutput??null,s=t.familyKey??zu("family",a),c=t.id??zu("task",{input:a,expected:i,observedOutput:r});return ob.parse({id:c,familyKey:s,split:t.split??"train",kind:r?"attempt":"task",input:a,expected:i,observedOutput:r,sourceId:c,sourceHash:st(e),occurredAt:n?null:d_(t.occurredAt),metadata:t.labels===void 0?{}:{importedLabels:t.labels,labelOrigin:"unverified_import"},warnings:[],needsContext:!1})}const _c=o().trim().min(1).max(240),Ho=o().regex(/^[a-f0-9]{64}$/),Pz=l({id:_c,name:o().trim().min(1).max(200),required:w(),role:v(["quality","retention","diagnostic"]).optional(),unit:o().trim().min(1).max(80).optional(),baselineReuse:l({maximumAgeSeconds:d().int().positive().max(31536e3),qualification:V}).strict().optional(),dataset:V,evaluator:V,executionHash:Ho,populationHash:Ho,metric:_c,direction:v(["higher","lower"]),minimumCoverage:d().positive().max(1),threshold:d().finite(),maximumRegression:d().finite().nonnegative(),maximumSpendUsd:d().finite().positive()}).strict().superRefine((e,t)=>{e.role==="diagnostic"&&e.required&&t.addIssue({code:"custom",message:"Diagnostic checks cannot be required acceptance gates."})}),f_=l({schemaVersion:b("openpond.acceptancePlan.v1"),id:_c,revision:d().int().positive(),checks:p(Pz).min(1).max(100),maximumSpendUsd:d().finite().positive()}).strict().superRefine((e,t)=>{new Set(e.checks.map(n=>n.id)).size!==e.checks.length&&t.addIssue({code:"custom",message:"Acceptance check IDs must be unique."}),e.checks.some(n=>n.required)||t.addIssue({code:"custom",message:"An acceptance plan needs at least one required check."}),e.checks.reduce((n,a)=>n+a.maximumSpendUsd,0)>e.maximumSpendUsd+1e-9&&t.addIssue({code:"custom",message:"Check budgets exceed the total plan budget."})}),h_=f_.safeExtend({contentHash:Ho});function Xne(e){const t=f_.parse(e);return{...t,contentHash:st(t)}}const Az=l({runId:_c,artifact:V,checkHash:Ho,populationHash:Ho,scoredPopulationHash:Ho,executionHash:Ho,evaluator:V,metric:_c,expectedCount:d().int().positive(),scoredCount:d().int().nonnegative(),score:d().finite().nullable(),status:v(["pending","running","completed","failed","cancelled"]),evidenceHash:Ho}).strict().superRefine((e,t)=>{e.scoredCount>e.expectedCount&&t.addIssue({code:"custom",message:"Scored count exceeds declared population."}),e.scoredCount===0!=(e.score===null)&&t.addIssue({code:"custom",message:"Scores require a nonempty scored population."})}),Lo=o().trim().min(1).max(240),rb=o().regex(/^[a-f0-9]{64}$/),Bu=nn(),tS=d().finite().nonnegative(),Tz=new Set(["completed","failed","cancelled","budget_exhausted"]),Ez=l({schemaVersion:b("openpond.acceptanceGroupManifest.v1"),id:Lo,teamId:Lo,trainingJob:V,baseline:V,candidate:V,plan:h_,maximumParallelAttempts:d().int().min(1).max(8),createdAt:Bu}).strict().superRefine((e,t)=>{e.plan.checks.some(n=>!n.role||!n.unit)&&t.addIssue({code:"custom",message:"Durable acceptance checks require explicit roles and score units."})}),Mz=Ez.safeExtend({contentHash:rb}),jz=l({id:Lo,checkId:Lo,subject:v(["baseline","candidate"]),ordinal:d().int().positive(),dispatchId:Lo,state:v(["queued","dispatching","running","grading","cleaning","completed","failed","cancelled","budget_exhausted"]),artifact:V,checkHash:rb,measurement:Az.nullable(),executionReceipt:V.nullable(),reusedFrom:l({group:V,attemptId:Lo}).strict().nullable(),spendUsd:tS,reservedUsd:tS,cleanupComplete:w(),accountingComplete:w(),failureCode:Lo.nullable(),createdAt:Bu,updatedAt:Bu}).strict().superRefine((e,t)=>{Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&t.addIssue({code:"custom",message:"Attempt timestamps are reversed."}),Tz.has(e.state)&&(!e.cleanupComplete||!e.accountingComplete||e.reservedUsd!==0)&&t.addIssue({code:"custom",message:"Terminal attempts require cleanup and settled accounting."}),e.state==="completed"&&(e.measurement?.status!=="completed"||!e.executionReceipt)&&t.addIssue({code:"custom",message:"Completed attempts require retained measurement and execution receipts."}),e.reusedFrom&&(e.subject!=="baseline"||e.state!=="completed"||e.spendUsd!==0)&&t.addIssue({code:"custom",message:"Only completed baselines may reuse retained evidence without new spend."})}),Oz=l({schemaVersion:b("openpond.acceptanceGroupSnapshot.v1"),manifest:Mz,revision:d().int().positive(),state:v(["queued","running","blocked","cancelling","cleaning","completed","failed","cancelled","budget_exhausted"]),attempts:p(jz).max(2e3),failureCode:Lo.nullable(),updatedAt:Bu}).strict(),$z=Oz.extend({contentHash:rb});var Cr=yt.shape.id,Cc=o().regex(/^[a-f0-9]{64}$/),Nz=l({scopeId:Cr,modelId:Cr}).strict(),Dz=l({schemaVersion:b("openpond.modelTasksetAuthoring.v1"),owner:Nz,root:yt,parent:yt}).strict(),eae=l({schemaVersion:b("openpond.modelTasksetDraftRequest.v1"),operationId:Cr,modelId:Cr,expectedModelRevision:d().int().positive(),sourcePackageHash:Cc}).strict(),Hz=l({schemaVersion:b("openpond.modelTasksetDraftPreparation.v1"),draftId:Cr,requestHash:Cc,sourcePackageHash:Cc,sourceTasksetRef:yt,tasksetId:Cr,tasksetRevision:d().int().positive(),lineage:Dz,authoringGraph:b("bound").optional()}).strict(),ad=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."),g_=l({path:ad,sizeBytes:d().int().nonnegative(),writable:w()}).strict(),v_=l({encoding:v(["utf8","base64"]),data:o().max(8e6)}).strict(),Lz=g_.extend({contentHash:Cc,content:v_}).strict();l({draftId:Cr,expectedDraftRevision:d().int().positive(),path:ad,expectedFileHash:Cc.nullable(),content:v_.nullable()}).strict();var qz=n_.extend({mode:v(["nightly","approved_count"]),minimumTasks:d().int().min(1).max(1e4),maximumSpendUsd:d().positive().max(1e5),maximumDailySpendUsd:d().positive().max(1e6)}).strict().superRefine((e,t)=>{e.maximumDailySpendUsd<e.maximumSpendUsd&&t.addIssue({code:"custom",path:["maximumDailySpendUsd"],message:"The daily budget must cover one update."})}),Uz=67108864,rg=524288,ec=class extends Error{code;constructor(e,t){super(t),this.name="OpenPondProtocolError",this.code=e}};function sb(e){return JSON.stringify(sg(e))}function zz(e){return new TextEncoder().encode(sb(e)).byteLength}async function Bz(e){const t=new TextEncoder().encode(sb(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 Fz(e,t,n){const a=zz(e);if(a>t)throw new ec("payload_too_large",`${n} is ${a} bytes; the maximum is ${t} bytes.`)}function sg(e){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new ec("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=>sg(t));if(typeof e=="object"){const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)throw new ec("non_json_value","Canonical JSON accepts only plain objects.");const n={};for(const a of Object.keys(e).sort()){const i=e[a];if(i===void 0||typeof i=="function"||typeof i=="symbol")throw new ec("non_json_value",`Canonical JSON cannot contain ${typeof i} at ${a}.`);n[a]=sg(i)}return n}throw new ec("non_json_value",`Canonical JSON cannot contain ${typeof e}.`)}var Dt=o().trim().min(1).max(500),Ri=o().regex(/^[a-f0-9]{64}$/),qa=o().datetime({offset:!0}),Tt=l({id:Dt,contentHash:Ri}).strict(),ea=Tt.extend({revision:d().int().positive()}).strict(),Nr=l({schemaVersion:b("openpond.baseModelPreference.v1"),modelId:Dt,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:Dt.nullable(),source:v(["managed","local","builtin"])}).strict(),b_=v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),y_=l({schemaVersion:o().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:b_,parameterization:v(["lora","full"])}).catchall(ie()),Vz=l({profileProjectId:Dt,sourceRevision:o().regex(/^[a-f0-9]{40,64}$/),harnessRelease:Tt}).strict(),Kz=l({profileProjectId:Dt,sourceRevision:o().regex(/^[a-f0-9]{40,64}$/),catalogHash:Ri,definitionId:Dt,harnessRelease:Tt,tasksetRelease:Tt}).strict(),S_=l({tasksetRef:ea.nullable().default(null),evaluationTasksetRef:ea.nullable().optional(),profileSource:Vz.nullable().optional(),profileEvaluation:Kz.nullable().optional(),rewardBindingRef:ea.nullable().optional(),tasksetRelease:Tt.nullable().default(null),harnessRelease:Tt.nullable().default(null),baseModel:Nr.nullable().default(null),method:b_.nullable().default(null),destinationId:Dt.nullable().default(null),managedRolloutPlacement:v(["local","remote"]).default("remote"),managedGpuPlacementObjective:v(["fast","balanced","economical"]).default("balanced"),managedGpuRequirement:v(["any","h100_hbm3"]).default("any"),runPreset:v(["small","standard","custom","small_experiment"]).nullable().default(null),recipe:y_.nullable().default(null),preferredMaximumSpendUsd:d().nonnegative().nullable().default(null),preferredRetentionDays:d().int().nonnegative().nullable().default(null)}).strict(),lb=S_.omit({managedGpuRequirement:!0}),Wz=l({schemaVersion:b("openpond.hostedModelProjectLink.v1"),apiOrigin:o().url().refine(e=>new URL(e).origin===e,"Use a canonical API origin.").nullable().default(null),teamId:Dt,projectId:Dt,portableProjectId:Dt,revision:d().int().positive(),etag:Ri,syncedSourceRevision:d().int().positive(),syncedAt:qa,tasksets:p(l({localTasksetId:Dt,localTasksetHash:Ri.nullable().default(null),releaseId:Dt,releaseRevision:d().int().positive(),releaseHash:Ri,packageHash:Ri.nullable().default(null),hostedTasksetId:Dt,syncedAt:qa}).strict()).max(1e4).default([])}).strict(),Gz=l({localTasksetId:Dt,releaseId:Dt,releaseRevision:d().int().positive(),releaseHash:Ri,state:v(["syncing","synced","sync_failed"]),hostedTasksetId:Dt.nullable().default(null),lastAttemptAt:qa,syncedAt:qa.nullable().default(null),lastError:o().trim().min(1).max(5e3).nullable().default(null)}).strict(),x_=l({schemaVersion:b("openpond.modelProject.v2"),id:Dt,profileId:Dt,revision:d().int().positive().default(1),name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:Nr.nullable(),defaultDestinationId:Dt.nullable(),trainingSetup:S_,hosted:Wz.nullable().default(null),tasksetSyncs:p(Gz).max(1e4).default([]),createdAt:qa,updatedAt:qa}).strict(),k_=x_.pick({id:!0,profileId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,trainingSetup:!0}),Jz=l({schemaVersion:b("openpond.modelProjectSave.v1"),operationId:Dt,expectedRevision:d().int().nonnegative(),project:k_,learning:qz.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."})}),I_=l({schemaVersion:b("openpond.modelProjectConfigurationCheck.v1"),configurationHash:Ri,projectId:Dt,expectedRevision:d().int().nonnegative(),checkedAt:qa,canSave:w(),deferred:p(v(["base_model","taskset"])).max(2),findings:p(l({code:Dt,severity:v(["error","warning"]),message:o().min(1).max(5e3),field:o().min(1).max(500).nullable()}).strict()).max(100)}).strict();l({id:Dt,name:o().min(1).max(500),available:w(),preference:Nr}).strict();function Zz(e){try{Hi(e,rg)}catch{throw new e4(400,{schemaVersion:"openpond.modelProjectApiError.v2",code:"model_configuration_json_invalid",message:"Model configuration must be bounded JSON data.",retryable:!1,requestId:null,details:{}})}return Jz.parse(e)}async function Yz(e,t,n){Hi(e,rg);const a=k_.parse(e);Fz(a,rg,"Model configuration");const i=await Bz({project:a,expectedRevision:t});return Zz({schemaVersion:"openpond.modelProjectSave.v1",operationId:`model-save:${i}`,expectedRevision:t,project:a})}var Qz=l({schemaVersion:b("openpond.hostedModelProjectSync.v2"),portableProjectId:Dt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:Nr.nullable(),defaultDestinationId:Dt.nullable(),trainingSetup:lb,sourceRevision:d().int().positive(),sourceUpdatedAt:qa,expectedEtag:Ri.nullable().default(null)}).strict(),Nm=l({id:Dt,teamId:Dt,portableProjectId:Dt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:Nr.nullable(),defaultDestinationId:Dt.nullable(),trainingSetup:lb,sourceRevision:d().int().positive(),sourceUpdatedAt:qa,revision:d().int().positive(),etag:Ri,createdAt:qa,updatedAt:qa}).strict(),Xz=l({kind:v(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:Tt,role:o().trim().min(1).max(200).nullable().default(null),updatedAt:qa}).strict();l({project:Nm,resources:p(Xz).max(1e4),jobCount:d().int().nonnegative(),latestJobIds:p(Dt).max(100)}).strict();l({schemaVersion:b("openpond.modelProjectApiError.v2"),code:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3),retryable:w().default(!1),requestId:o().trim().min(1).max(500).nullable().default(null),details:ae(o(),ie()).default({})}).strict();var e4=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}},t4=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),n4=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function a4(e){const t=typeof e=="string"?new TextEncoder().encode(e):e,n=Math.ceil((t.byteLength+9)/64)*64,a=new Uint8Array(n);a.set(t),a[t.byteLength]=128;const i=t.byteLength*8,r=new DataView(a.buffer);r.setUint32(n-8,Math.floor(i/4294967296),!1),r.setUint32(n-4,i>>>0,!1);const s=new Uint32Array(t4),c=new Uint32Array(64);for(let m=0;m<n;m+=64){for(let R=0;R<16;R+=1)c[R]=r.getUint32(m+R*4,!1);for(let R=16;R<64;R+=1){const $=c[R-15],O=c[R-2],j=xi($,7)^xi($,18)^$>>>3,I=xi(O,17)^xi(O,19)^O>>>10;c[R]=c[R-16]+j+c[R-7]+I>>>0}let u=s[0],h=s[1],g=s[2],S=s[3],k=s[4],C=s[5],A=s[6],M=s[7];for(let R=0;R<64;R+=1){const $=k&C^~k&A,O=u&h^u&g^h&g,j=xi(u,2)^xi(u,13)^xi(u,22),I=xi(k,6)^xi(k,11)^xi(k,25),P=M+I+$+n4[R]+c[R]>>>0,E=j+O>>>0;M=A,A=C,C=k,k=S+P>>>0,S=g,g=h,h=u,u=P+E>>>0}s[0]=s[0]+u>>>0,s[1]=s[1]+h>>>0,s[2]=s[2]+g>>>0,s[3]=s[3]+S>>>0,s[4]=s[4]+k>>>0,s[5]=s[5]+C>>>0,s[6]=s[6]+A>>>0,s[7]=s[7]+M>>>0}return Array.from(s,m=>m.toString(16).padStart(8,"0")).join("")}function xi(e,t){return e>>>t|e<<32-t}var i4=2e3,w_=25e7,Ke=o().trim().min(1).max(240),Qe=o().regex(/^[a-f0-9]{64}$/),Rt=o().datetime({offset:!0}),Dm=ae(o(),ie()).default({}),De=l({id:Ke,contentHash:Qe}).strict(),o4=De.extend({revision:d().int().positive()}).strict(),to=l({id:Ke,path:o().trim().min(1).max(i4).refine(l4),contentHash:Qe,sizeBytes:d().int().nonnegative().max(w_),mediaType:o().trim().min(1).max(200),visibility:v(["policy","verifier","host_private"])}).strict(),r4=l({id:Ke,contentHash:Qe,mediaType:o().trim().min(1).max(200).nullable().default(null),sizeBytes:d().int().nonnegative().max(w_).nullable().default(null)}).strict(),__=v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function s4(e){return`${JSON.stringify(lg(e),null,2)}
177
+ `}function C_(e){return a4(e)}function Pt(e){return C_(s4(e))}function tae(e,t){const{contentHash:n,...a}=e,i=Pt(a);if(n!==i)throw new Error(`${t} contentHash is ${n}; expected ${i}.`)}function l4(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function lg(e){return Array.isArray(e)?e.map(lg):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,lg(n)]))}var c4=v(["memory","prompt","skill","agent"]),d4=v(["runtime","product","taskset","training"]),u4=l({id:o().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:o().trim().min(1).max(1e4)}).strict(),m4=l({schemaVersion:b("openpond.refinerReviewProfile.v1"),id:o().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),version:o().trim().min(1).max(120),name:o().trim().min(1).max(200),objective:o().trim().min(1).max(1e4),instructions:p(u4).max(100),allowedProposalRoutes:p(c4).max(4),allowedExternalRoutes:p(d4).max(4)}).strict().superRefine((e,t)=>{const n=e.instructions.map(a=>a.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",message:"instruction IDs must be unique",path:["instructions"]}),new Set(e.allowedProposalRoutes).size!==e.allowedProposalRoutes.length&&t.addIssue({code:"custom",message:"proposal routes must be unique",path:["allowedProposalRoutes"]}),new Set(e.allowedExternalRoutes).size!==e.allowedExternalRoutes.length&&t.addIssue({code:"custom",message:"external routes must be unique",path:["allowedExternalRoutes"]})});l({schemaVersion:b("openpond.refinerRelease.v1"),id:o().trim().min(1).max(240),coreVersion:o().trim().min(1).max(120),coreHash:Qe,profile:m4,profileHash:Qe,composedPromptHash:Qe,createdAt:Rt,contentHash:Qe}).strict();l({schemaVersion:b("openpond.refinerBinding.v1"),channel:b("active"),revision:d().int().nonnegative(),release:De,updatedAt:Rt}).strict();l({schemaVersion:b("openpond.refinerTransitionReceipt.v1"),id:o().trim().min(1).max(240),operation:v(["initialize","update","activate","rollback"]),bindingChanged:w(),previousRelease:De.nullable(),nextRelease:De,actor:o().trim().min(1).max(240),reason:o().trim().min(1).max(1e4),authoringSkillHash:Qe.nullable(),validation:l({valid:w(),messages:p(o().max(2e3)).max(100)}).strict(),createdAt:Rt,contentHash:Qe}).strict();var p4=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v1"),decision:b("no_action"),reason:o().trim().min(1).max(1e4)}).strip(),f4=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v1"),decision:b("route"),route:v(["runtime","product","taskset","training"]),summary:o().trim().min(1).max(2e3),expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strip(),h4=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v1"),decision:b("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),createContent:o().min(1).max(2e4).nullable(),find:o().min(1).max(8e3).nullable(),replace:o().max(8e3).nullable(),expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strip().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),g4=lt("decision",[p4,f4,h4]),v4=g4,cb=l({kind:v(["single_deterministic","recurrent_independent"]),supportingEvidenceIds:p(o().trim().min(1).max(2e3)).min(1).max(100),counterevidence:p(o().trim().min(1).max(2e3)).max(20)}).strict().superRefine((e,t)=>{new Set(e.supportingEvidenceIds).size!==e.supportingEvidenceIds.length&&t.addIssue({code:"custom",message:"supporting evidence IDs must be unique",path:["supportingEvidenceIds"]}),e.kind==="recurrent_independent"&&e.supportingEvidenceIds.length<2&&t.addIssue({code:"custom",message:"recurrent independent evidence requires at least two supplied incidents",path:["supportingEvidenceIds"]})}),b4=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v2"),decision:b("no_action"),reason:o().trim().min(1).max(1e4)}).strict(),y4=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v2"),decision:b("route"),route:v(["runtime","product","taskset","training"]),summary:o().trim().min(1).max(2e3),evidenceBasis:cb,expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strict(),S4=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v2"),decision:b("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),evidenceBasis:cb,createContent:o().min(1).max(2e4).nullable(),find:o().min(1).max(8e3).nullable(),replace:o().max(8e3).nullable(),expectedOutcome:o().trim().min(1).max(1e4),reason:o().trim().min(1).max(1e4)}).strict().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),R_=lt("decision",[b4,y4,S4]);ht([v4,R_]);var db=l({memory:w(),prompt:w(),skill:w(),agent:w()}).strict(),P_=v(["memory","instruction","skill","agent"]),nS=l({path:o().trim().min(1).max(2e3),kind:P_,content:o().max(6e4),loaded:w()}).strict(),aS=l({path:o().trim().min(1).max(2e3),kind:P_,loaded:w()}).strict(),x4=l({capabilities:db,trigger:ae(o(),ie()),observations:p(ae(o(),ie())).max(20),admissibleEvidenceIds:p(o().trim().min(1).max(2e3)).max(1e4),reviewPacket:l({currentTurn:l({id:o().trim().min(1).max(2e3),status:o().trim().min(1).max(100).nullable(),error:o().max(2100).nullable(),prompt:o().max(8100).nullable(),assistantOutput:o().max(8100).nullable(),assistantOutputLinkCount:d().int().nonnegative()}).strict(),priorConversation:p(l({turnId:o().trim().min(1).max(2e3),status:o().trim().min(1).max(100).nullable(),prompt:o().max(3100).nullable(),assistantOutput:o().max(3100).nullable()}).strict()).max(3),timeline:p(ae(o(),ie())).max(60),artifacts:p(ae(o(),ie())).max(30),artifactDiagnostics:p(ae(o(),ie())).max(20),executionProfile:l({modelRequestCount:d().int().nonnegative(),failedModelRequestCount:d().int().nonnegative(),promptTokens:d().int().nonnegative(),completionTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),toolFailureCount:d().int().nonnegative(),retryCount:d().int().nonnegative(),recoveryCount:d().int().nonnegative()}).strict(),priorIncidents:p(ae(o(),ie())).max(3),truncation:l({timelineEventCount:d().int().nonnegative(),includedTimelineEventCount:d().int().nonnegative(),timelineTruncated:w()}).strict()}).strict(),runtimeActivation:l({admittedRelease:De,currentRelease:De,rebasedOntoCurrent:w(),admittedSourceFiles:p(nS).max(100),admittedSourceCatalog:p(aS).max(1e3)}).strict(),sourceFiles:p(nS).max(100),sourceCatalog:p(aS).max(1e3),additionalEvidence:ie().nullable().optional()}).strict(),k4=l({id:o().trim().min(1).max(240),revision:d().int().nonnegative(),contentHash:Qe}).strict();l({schemaVersion:b("openpond.hostedHarnessRefinerRequest.v2"),requestId:o().trim().min(1).max(240),idempotencyKey:o().trim().min(1).max(240),evidenceHash:Qe,harness:l({admittedRelease:De,currentRelease:De,overlay:k4,workspace:l({id:o().trim().min(1).max(240),revision:d().int().nonnegative(),sourceRevision:Qe,channelRevision:d().int().nonnegative()}).strict(),capabilities:db}).strict(),evidence:x4}).strict();var I4=l({promptTokens:d().int().nonnegative(),completionTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative()}).strict();l({schemaVersion:b("openpond.hostedHarnessRefinerResponse.v2"),requestId:o().trim().min(1).max(240),evidenceHash:Qe,admittedRelease:De,currentRelease:De,decision:R_,serviceRevision:o().trim().min(1).max(240),usage:I4}).strict();const A_=l({adapterId:T,placement:v(["local","remote","colocated","provider_native"]),runtimeVersion:o().trim().min(1).max(200),capabilityReceipt:D}).strict(),T_=l({maxTurns:d().int().positive().max(1e5),timeoutMs:d().int().positive().max(864e5),maxOutputBytes:d().int().positive().max(25e7),maximumSpendUsd:d().nonnegative().nullable()}).strict(),w4=l({schemaVersion:b("openpond.runManifest.v1"),id:T,harnessRelease:V,tasksetRelease:V,model:pm,runtimeTarget:A_,limits:T_,approval:l({id:T,contentHash:D}).strict().nullable(),createdAt:he,metadata:Mn}).strict();w4.extend({contentHash:D}).strict();const _4=l({schemaVersion:b("openpond.attemptReceipt.v1"),id:T,runManifest:V,taskId:T,seed:o().trim().min(1).max(500),terminal:w(),failureClass:Bc.nullable(),outputHash:D.nullable(),traceHash:D,artifactRefs:p(Ia).max(1e5),graderEvidenceRefs:p(Ia).max(1e4),startedAt:he,completedAt:he,latencyMs:d().int().nonnegative(),costUsd:d().nonnegative().nullable(),legacyAttemptRef:T.nullable().default(null),metadata:Mn}).strict(),C4=_4.extend({contentHash:D}).strict(),R4=l({schemaVersion:b("openpond.evaluationResult.v1"),id:T,runManifest:V,harnessRelease:V,tasksetRelease:V,model:pm,receiptRefs:p(V).min(1).max(1e6),attemptCount:d().int().positive(),rewardEligibleCount:d().int().nonnegative(),terminalCount:d().int().nonnegative(),meanScore:d().min(0).max(1).nullable(),failureCounts:ae(Bc,d().int().nonnegative()),authoredMetric:Wv.optional(),metadata:Mn}).strict(),P4=R4.extend({contentHash:D}).strict(),A4=l({schemaVersion:b("openpond.harnessCompatibility.v1"),id:T,baseHarnessRelease:V,candidateHarnessRelease:V,tasksetRelease:V,environmentHash:D,toolContractHash:D,policyHash:D,graderInterfaceHash:D,metadata:Mn}).strict();A4.extend({contentHash:D}).strict();const ub=v(["scored","unscorable"]),Hm=v(["policy","environment","collector","verifier","provider","host","user","scheduler"]),E_=v(["completed","policy_failure","incomplete_output","task_deadline","environment_failure","collector_failure","verifier_failure","provider_failure","host_failure","infrastructure_timeout","cancelled"]),T4=l({schemaVersion:b("openpond.environmentRelease.v1"),id:T,revision:d().int().positive(),contract:Hw,actionSchemaRef:gn.nullable(),observationSchemaRef:gn.nullable(),stateSchemaRef:gn.nullable(),artifactCollection:l({maxArtifacts:d().int().positive().max(1e5),maxTotalBytes:d().int().positive().max(1e10)}).strict(),adapterConformanceHashes:ae(T,D),metadata:Mn}).strict(),mb=T4.extend({contentHash:D}).strict(),E4=v(["collected","missing","skipped","failed"]),iS=v(["not_requested","passed","failed"]),M4=l({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:Ia.nullable(),status:E4,parseStatus:iS,schemaStatus:iS,errorCode:T.nullable(),failureOwner:Hm.nullable(),evidenceRefs:p(Ia).max(1e4),metadata:Mn}).strict(),j4=l({schemaVersion:b("openpond.artifactManifest.v1"),id:T,attemptRef:V,entries:p(M4).max(1e5),createdAt:he,metadata:Mn}).strict();j4.extend({contentHash:D}).strict();const O4=l({schemaVersion:b("openpond.verifierSetRelease.v1"),id:T,revision:d().int().positive(),graders:p(Fw).min(1).max(1e3),isolation:l({processBoundary:v(["same_process","isolated_process","container"]),networkPolicy:b("none"),defaultTimeoutMs:d().int().positive().max(3e5)}).strict(),calibrationReceiptRefs:p(V).max(1e4),metadata:Mn}).strict(),pb=O4.extend({contentHash:D}).strict(),$4=l({verifierId:T,verifierVersion:o().trim().min(1).max(100),status:ub,rawScore:d().finite().nullable(),normalizedScore:d().min(0).max(1).nullable(),weight:d().nonnegative().max(1e3),passed:w(),hardGate:w(),rewardEligible:w(),rewardContribution:d().min(0).max(1).nullable(),failureOwner:Hm.nullable(),feedback:p(o().max(2e4)).max(1e3),visibleEvidenceRefs:p(Ia).max(1e4),privilegedEvidenceRefs:p(Ia).max(1e4),metadata:Mn}).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"]})}),M_=l({schemaVersion:b("openpond.rewardReceipt.v1"),id:T,attemptRef:V,verifierSetRef:V,artifactManifestRef:V,status:ub,reward:d().min(0).max(1).nullable(),learningEligible:w(),passed:w(),outcomeClass:E_,failureOwner:Hm.nullable(),components:p($4).min(1).max(1e4),visibleEvidenceRefs:p(Ia).max(1e5),privilegedEvidenceRefs:p(Ia).max(1e5),supersedes:V.nullable(),createdAt:he,metadata:Mn}).strict();function j_(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"]})}M_.superRefine(j_);M_.extend({contentHash:D}).strict().superRefine(j_);const N4=lt("kind",[l({kind:b("model"),model:pm,configurationHash:D}).strict(),l({kind:b("fixture")}).strict()]),D4=lt("kind",[l({kind:b("taskset"),environmentRelease:V,verifierSetRelease:V,policyHash:D}).strict(),l({kind:b("harness"),harnessRelease:V}).strict()]),O_=l({receiptId:T,taskId:T,seed:o().trim().min(1).max(500),fixtureId:T.nullable()}).strict(),H4=l({schemaVersion:b("openpond.tasksetRunManifest.v1"),id:T,tasksetRelease:V,packageHash:D,execution:D4,profileEvaluation:Ks.optional(),policy:N4,gradingRole:b("evaluation"),metricPolicy:ed,population:p(O_).min(1).max(1e5),runtimeTarget:A_,limits:T_,createdAt:he,metadata:Mn}).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."})}),Lm=H4.safeExtend({contentHash:D}),L4=l({schemaVersion:b("openpond.profileEvaluationComparison.v1"),id:T,tasksetRelease:V,populationHash:D,environmentHash:D,metricPolicyHash:D,limitsHash:D,members:p(l({runManifest:V,metricResultHash:D,source:Ks,policy:Lm.shape.policy,score:d().min(0).max(1).nullable()}).strict()).min(2).max(100),createdAt:he}).strict(),q4=L4.extend({contentHash:D}).strict(),U4=l({profileId:T,sourceRevision:o().trim().min(1).max(240),harnessRelease:V}).strict(),z4=l({kind:v(["run","suite","comparison"]),id:T,contentHash:D}).strict(),B4=l({schemaVersion:b("openpond.profileEvaluationReport.v1"),id:T,createdAt:he,testedSources:p(U4).min(1).max(100),tasksetReleases:p(V).min(1).max(100),metricPolicyHashes:p(D).min(1).max(100),modelConfigurationHashes:p(D).min(1).max(100),evidence:p(z4).min(1).max(100),summary:l({totalChecks:d().int().nonnegative(),passedChecks:d().int().nonnegative(),failedChecks:d().int().nonnegative(),unscoredChecks:d().int().nonnegative(),meanScore:d().min(0).max(1).nullable()}).strict()}).strict().superRefine((e,t)=>{const{summary:n}=e;n.passedChecks+n.failedChecks+n.unscoredChecks!==n.totalChecks&&t.addIssue({code:"custom",path:["summary"],message:"Report check counts must add up."}),new Set(e.evidence.map(({kind:a,id:i})=>`${a}:${i}`)).size!==e.evidence.length&&t.addIssue({code:"custom",path:["evidence"],message:"Report evidence must be unique."})}),F4=B4.safeExtend({contentHash:D}),V4=l({schemaVersion:b("openpond.profileEvaluationSuiteRun.v1"),id:T,suiteId:T,suiteHash:D,catalogHash:D,profileId:T,sourceRevision:o().trim().min(1).max(240),harnessRelease:V,members:p(l({definitionId:T,runManifest:V,runHash:D,passed:w(),score:d().min(0).max(1).nullable()}).strict()).min(1).max(1e3),passed:w(),createdAt:he,completedAt:he}).strict(),K4=V4.extend({contentHash:D}).strict(),$_=l({schemaVersion:b("openpond.optimizerTrainingSample.v1"),tokenIds:p(d().int().nonnegative()).min(2).max(32768),mask:p(w()).min(2).max(32768),logprobs:p(d().finite()).min(2).max(32768),temperatures:p(d().positive().finite()).min(2).max(32768),envName:o().trim().min(1).max(200),modelRequestId:o().trim().min(1).max(1e3),promptTokenCount:d().int().positive(),completionTokenCount:d().int().positive(),servedPolicyVersion:d().int().nonnegative()}).strict().superRefine((e,t)=>{const n=e.tokenIds.length;for(const[a,i]of[["mask",e.mask],["logprobs",e.logprobs],["temperatures",e.temperatures]])i.length!==n&&t.addIssue({code:"custom",path:[a],message:`${a} must align with tokenIds`});e.promptTokenCount+e.completionTokenCount!==n&&t.addIssue({code:"custom",path:["completionTokenCount"],message:"prompt and completion token counts must span tokenIds"}),e.mask.filter(a=>!a).length!==e.promptTokenCount&&t.addIssue({code:"custom",path:["mask"],message:"promptTokenCount must equal the non-trainable mask count"}),e.mask.filter(Boolean).length!==e.completionTokenCount&&t.addIssue({code:"custom",path:["mask"],message:"completionTokenCount must equal the trainable mask count"})}),W4=l({id:T,environmentRelease:V,status:v(["completed","failed","timed_out","cancelled"]),startedAt:he,completedAt:he,traceRefs:p(Ia).max(1e4),metadata:Mn}).strict(),G4=l({receiptRef:V,status:ub,value:d().min(0).max(1).nullable(),learningEligible:w(),passed:w(),outcomeClass:E_,failureOwner:Hm.nullable(),components:ae(T,d().min(0).max(1).nullable())}).strict(),N_=l({schemaVersion:b("openpond.canonicalRolloutRecord.v1"),id:T,attemptRef:V,artifactManifestRef:V,tasksetRelease:V,environmentRelease:V,verifierSetRelease:V,harnessRelease:V,taskId:T,split:Ka,model:pm,seed:o().trim().min(1).max(500),reward:G4,traceRef:Ia,optimizerSample:$_.nullable(),environmentExecutions:p(W4).min(1).max(1e5),startedAt:he,completedAt:he,metadata:Mn}).strict();function D_(e,t){e.reward.status==="scored"&&(e.reward.value===null||!e.reward.learningEligible)&&t.addIssue({code:"custom",path:["reward","status"],message:"A scored rollout requires a numeric, learning-eligible reward."}),e.reward.status==="unscorable"&&(e.reward.value!==null||e.reward.learningEligible)&&t.addIssue({code:"custom",path:["reward","status"],message:"An unscorable rollout has no reward and cannot be learning-eligible."})}N_.superRefine(D_);l({...N_.shape,contentHash:D}).strict().superRefine(D_);const J4=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."),H_=ht([al(),o().max(262144),d().finite(),l({integer:J4}).strict(),l({blobBase64:o().max(349528).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}).strict()]),oS=o().min(1).max(128).refine(e=>!e.includes("\0")),Z4=l({tables:p(l({name:oS,columns:p(l({name:oS,type:v(["INTEGER","REAL","TEXT","BLOB"])}).strict()).min(1).max(128),rows:p(p(H_).max(128)).max(4096)}).strict()).max(64)}).strict().superRefine((e,t)=>{const n=new Set;for(const[a,i]of e.tables.entries()){const r=i.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(i.columns.map(s=>s.name.toLowerCase())).size!==i.columns.length&&t.addIssue({code:"custom",path:["tables",a,"columns"],message:"Column names must be unique."}),i.rows.some(s=>s.length!==i.columns.length)&&t.addIssue({code:"custom",path:["tables",a,"rows"],message:"Each row must match the declared columns."})}}),rS=l({schemaVersion:b("openpond.sqlExecution.v1"),snapshot:Z4,sql:o().min(1).max(65536).refine(e=>!e.includes("\0")),maxRows:d().int().min(1).max(4096),maxResultBytes:d().int().min(256).max(262144)}).strict();lt("status",[l({status:b("completed"),columns:p(o()).max(128),rows:p(p(H_).max(128)).max(4096)}).strict(),l({status:b("rejected"),code:v(["invalid_query","multiple_statements","result_too_large","memory_limit"])}).strict()]);const Kd=l({scope:v(["input","initialState","state","arguments"]),path:p(o().min(1).max(256)).max(16)}).strict(),sS={id:o().min(1).max(128),operation:v(["step","collect"]),toolName:o().min(1).max(500).optional(),timeoutMs:d().int().min(1).max(2e4)},Y4=lt("kind",[l({...sS,kind:b("sqlite.v1"),sql:Kd,snapshot:Kd,maxRows:rS.shape.maxRows,maxResultBytes:rS.shape.maxResultBytes}).strict(),l({...sS,kind:b("javascript.v1"),source:Kd,cases:Kd,exportName:o().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/).max(128),maxCases:d().int().min(1).max(32),maxResultBytes:d().int().min(256).max(262144)}).strict()]).superRefine((e,t)=>{e.operation==="step"!=(e.toolName!==void 0)&&t.addIssue({code:"custom",path:["toolName"],message:"Only step services require a declared tool name."}),e.operation==="collect"&&(e.kind==="sqlite.v1"?[e.sql,e.snapshot]:[e.source,e.cases]).some(a=>a.scope==="arguments")&&t.addIssue({code:"custom",message:"Collection has no tool arguments."})}),Q4=l({schemaVersion:b("openpond.javascriptEnvironment.v1"),id:o().trim().min(1).max(500),revision:d().int().positive(),module:gn.refine(e=>e.visibility==="host_private","Environment code belongs to the execution owner."),tools:p(Jc).min(1).max(200),maxSteps:d().int().min(1).max(1e3),maxStateBytes:d().int().min(1).max(1048576),maxObservationBytes:d().int().min(1).max(262144),operationTimeoutMs:d().int().min(1).max(3e4),executionServices:p(Y4).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,i)=>{Jv(a.inputSchema).valid||t.addIssue({code:"custom",path:["tools",i,"inputSchema"],message:"Environment tools require a supported JSON schema."}),a.inputSchemaHash!==st(a.inputSchema)&&t.addIssue({code:"custom",path:["tools",i,"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,i)=>{const r=e.tools.find(s=>s.name===a.toolName);a.operation==="step"&&!r&&t.addIssue({code:"custom",path:["executionServices",i,"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",i,"timeoutMs"],message:"Service budgets must leave time for the authored controller."})})}),X4=Q4.safeExtend({contentHash:o().regex(/^[a-f0-9]{64}$/)});v(["create","reset","step","collect","destroy"]);l({state:ae(o(),ie()),observation:ae(o(),ie())}).strict();o().regex(/^[a-f0-9]{64}$/);var eB=l({environment:mb,verifierSet:pb,javascript:X4}).strict();l({actions:p(l({name:o().min(1).max(64),arguments:ae(o(),ie())}).strict()).max(1e3)}).strict();var tB=l({environment:mb,verifierSet:pb}).strict(),nB=l({scopeId:o().trim().min(1).max(500),modelId:o().trim().min(1).max(500)}).strict();l({schemaVersion:b("openpond.modelTasksetDerivation.v1"),owner:nB,root:ea,parent:ea}).strict();var aB=l({taskset:Kw,taskDefinition:nd,rewardBinding:Em,rewards:p(Tm).min(1).max(100),assets:p($m).max(1e3),executionResources:tB.optional(),execution:eB.optional(),instructionMode:b("per_task").optional()}).strict(),iB=l({batch:ab,evidence:p(Om).min(1).max(1e4),decisions:p(nb).min(1).max(1e4),sources:p(jm).min(1).max(1e4),assets:p($m).max(1e3)}).strict(),oB=64*1024*1024,rB=l({asset:to,base64:o().max(Math.ceil(oB/3)*4)}).strict(),sB=aB.omit({taskset:!0,executionResources:!0}),lB=l({schemaVersion:b("openpond.tasksetPackage.v1"),taskset:Kw,environment:mb,verifierSet:pb,files:p(rB).max(1e4),modelResources:sB.optional(),learningResources:iB.optional()}).strict(),Rr=lB.extend({contentHash:o().regex(/^[a-f0-9]{64}$/)}).strict(),Ci=o().trim().min(1).max(500),hu=o().regex(/^[a-f0-9]{64}$/),cB=Qz.pick({portableProjectId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,sourceRevision:!0,sourceUpdatedAt:!0}).extend({trainingSetup:lb.omit({tasksetRef:!0,rewardBindingRef:!0,tasksetRelease:!0})}).strict();l({schemaVersion:b("openpond.tasksetPackagePublication.v1"),operationId:Ci,modelProjectId:Ci,expectedProjectEtag:hu.nullable(),name:o().trim().min(1).max(200),description:o().max(5e3),buildIntent:v(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),methodHint:v(["sft","dpo","grpo","ppo"]).nullable(),package:Rr,modelConfiguration:cB.optional(),evaluationPackage:Rr.optional(),selection:v(["select","attach"]).optional()}).strict().refine(e=>e.selection!=="attach"||e.modelConfiguration===void 0,"Attachment-only publication cannot replace Model configuration.").refine(e=>!e.evaluationPackage||e.modelConfiguration!==void 0&&e.modelConfiguration.trainingSetup.evaluationTasksetRef!=null&&Pt(e.modelConfiguration.trainingSetup.evaluationTasksetRef)===Pt(pz(e.evaluationPackage.taskset)),"Evaluation package must match the selected immutable evaluation in Model configuration.");l({schemaVersion:b("openpond.tasksetPackageReceipt.v1"),teamId:Ci,modelProjectId:Ci,operationId:Ci,taskset:qu,packageHash:hu,hostedTasksetId:Ci,projectEtag:hu,project:Nm.optional(),selection:v(["select","attach"]).optional(),evaluation:l({taskset:qu,packageHash:hu,hostedTasksetId:Ci}).strict().optional()}).strict();l({schemaVersion:b("openpond.tasksetPackageReadback.v1"),teamId:Ci,modelProjectId:Ci,package:Rr}).strict();l({schemaVersion:b("openpond.tasksetReleasePackageReadback.v1"),teamId:Ci,release:qu,package:Rr}).strict();l({provider:Ke,model:Ke,revision:o().trim().min(1).max(500).nullable().default(null),artifactHash:Qe.nullable().default(null),tokenizerRevision:o().trim().min(1).max(500).nullable().default(null),chatTemplateHash:Qe.nullable().default(null)}).strict();var dB=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],uB=v(dB),fb=l({providerId:uB,modelId:o().trim().min(1).max(300)}),L_=l({name:o().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:o().trim().min(1).max(2e3),inputSchema:ae(o(),ie()),inputSchemaHash:Qe,sideEffect:v(["read","write"]),timeoutMs:d().int().positive().max(36e5)}).strict(),mB=l({id:Ke,required:w(),scopes:p(o().trim().min(1).max(500)).max(100).default([]),portability:v(["portable","host_adapter","local_only","hosted_only"])}).strict(),pB=l({portable:w(),blockers:p(o().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:p(Ke).max(1e4),hostPrivateAssetRefs:p(Ke).max(1e4)}).strict(),fB=l({schemaVersion:b("openpond.agentSnapshot.v2"),id:Ke,sourceRelease:De.nullable(),instructions:p(to).max(1e4),skills:p(to).max(1e4),agents:p(to).max(1e4),toolDeclarations:p(L_).max(200),capabilityRequirements:p(mB).max(200),dependencyLock:to,portability:pB,metadata:Dm}).strict(),hB=fB.extend({contentHash:Qe}).strict(),gB=l({create:b(!0),reset:b(!0),step:b(!0),collect:b(!0),destroy:b(!0),resetScope:v(["task","attempt"])}).strict(),vB=l({visibleEvidence:p(Ke).max(1e3),privilegedEvidence:p(Ke).max(1e3),privateVerifierIsolation:w()}).strict(),bB=l({schemaVersion:b("openpond.harnessRelease.v2"),id:Ke,agentSnapshot:De,program:to,tools:p(L_).max(200),lifecycle:gB,graderInterface:vB,files:p(to).max(1e5),metadata:Dm}).strict(),yB=bB.extend({contentHash:Qe}).strict(),SB=l({id:Ke,turn:d().int().nonnegative(),kind:v(["message","tool_call","terminal"]),name:Ke.nullable(),arguments:ae(o(),ie()),content:o().max(1e6).nullable()}).strict(),xB=l({actionId:Ke,turn:d().int().nonnegative(),terminal:w(),output:ae(o(),ie()),artifactRefs:p(r4).max(1e5)}).strict(),kB=l({sequence:d().int().nonnegative(),type:v(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:Qe,metadata:Dm}).strict();l({schemaVersion:b("openpond.harnessTrace.v1"),manifest:De,taskId:Ke,seed:o().trim().min(1).max(500),events:p(kB).max(1e6),actions:p(SB).max(1e5),observations:p(xB).max(1e5),terminal:w(),failureClass:__.nullable(),output:ae(o(),ie()),contentHash:Qe}).strict();var IB=25*1024*1024,wB=l({path:to.shape.path,base64:o().max(Math.ceil(IB/3)*4)}).strict(),q_=l({schemaVersion:b("openpond.harnessSourcePackage.v1"),agentSnapshot:hB,harnessRelease:yB,files:p(wB).max(1e4)}).strict();q_.extend({contentHash:Qe}).strict();var nae=q_.extend({schemaVersion:b("openpond.harnessPolicySourcePackage.v1"),contentHash:Qe}).strict();l({schemaVersion:b("openpond.harnessSourceSelection.v1"),mode:v(["taskset_owned","selected_release"]),harnessRelease:De,sourcePackageHash:Qe.nullable()}).strict().superRefine((e,t)=>{e.mode==="selected_release"!=(e.sourcePackageHash!==null)&&t.addIssue({code:"custom",path:["sourcePackageHash"],message:"Only a selected release binds a source package."})});var lo=o().trim().min(1).max(1e5),_B=v(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),CB=v(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),U_=v(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),hb=l({kind:v(["personal","team"]),id:Ke}).strict(),z_=l({policy:De,state:v(["authorized","revoked","deleted","expired"]),checkedAt:Rt}).strict(),Rc=l({evidence:De,kind:U_,sourceRef:Ke,sourcePolicy:z_,occurrenceKey:Qe,occurredAt:Rt}).strict(),RB=l({evidence:De,sourcePolicy:z_.nullable(),reason:v(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),lS=l({cursor:Qe,throughCreatedAt:Rt}).strict(),PB=l({fingerprint:Qe,recurrenceFamily:o().trim().min(1).max(1e3),statement:lo,candidateDisposition:v(["observe","confirm"]).optional(),independentOccurrences:d().int().positive().max(1e6),unresolvedOccurrences:d().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),B_=v(["harness","runtime","product","retrieval","tools","evaluation","model"]),AB=l({layer:B_,status:v(["not_applicable","unresolved","resolved","blocked"]),reason:lo,evidenceRefs:p(De).max(1e3)}).strict(),TB=l({schemaVersion:b("openpond.harnessEvaluationReviewReceipt.v1"),id:Ke,ownerScope:hb,workspaceRef:Ke,harnessRelease:De,previousWatermark:lS.nullable(),nextWatermark:lS,selectedEvidence:p(Rc).max(1e4),excludedEvidence:p(RB).max(1e4),claim:PB.nullable(),classification:_B,triage:p(AB).max(16),reason:lo,nextAuthority:CB,maxEstimatedCostUsd:d().finite().nonnegative(),tasksetProposal:De.nullable(),evaluation:De.nullable(),trainingQualification:De.nullable(),policyVersion:Ke,createdAt:Rt,metadata:Dm}).strict().superRefine((e,t)=>{const n=e.selectedEvidence.map(a=>`${a.evidence.id}:${a.evidence.contentHash}`);new Set(n).size!==n.length&&t.addIssue({code:"custom",message:"selected review evidence must be unique",path:["selectedEvidence"]}),e.selectedEvidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"selected review evidence must be authorized at review time",path:["selectedEvidence"]}),e.classification==="no_action"?(e.nextAuthority!=="none"&&t.addIssue({code:"custom",message:"no-action review receipts require no next authority",path:["nextAuthority"]}),(e.tasksetProposal||e.evaluation||e.trainingQualification)&&t.addIssue({code:"custom",message:"no-action review receipts cannot carry downstream refs"})):(!e.claim||e.selectedEvidence.length===0)&&t.addIssue({code:"custom",message:"actionable review receipts require a claim and selected evidence"}),e.classification==="runtime"&&e.nextAuthority!=="runtime_service"&&t.addIssue({code:"custom",message:"runtime classifications route to runtime-service authority",path:["nextAuthority"]}),e.classification==="product"&&e.nextAuthority!=="product_team"&&t.addIssue({code:"custom",message:"product classifications route to product-team authority",path:["nextAuthority"]}),e.classification==="taskset"&&e.nextAuthority!=="human_review"&&t.addIssue({code:"custom",message:"Taskset classifications require human review"}),e.classification==="model_improvement"&&(!e.evaluation||!e.trainingQualification||!["human_review","training_system"].includes(e.nextAuthority))&&t.addIssue({code:"custom",message:"model-improvement classifications require Evaluation and qualification refs plus explicit authority"})});TB.extend({contentHash:Qe}).strict();l({id:Ke,evidence:De,kind:U_,sourceRef:Ke,occurredAt:Rt,payload:ae(o(),ie())}).strict();var EB=l({schemaVersion:b("openpond.harnessEvaluationReviewModelDecision.v2"),decision:b("no_action"),reason:lo,ignoredEvidence:p(l({id:Ke,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),MB=l({schemaVersion:b("openpond.harnessEvaluationReviewModelDecision.v2"),decision:b("review"),classification:v(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:p(Ke).min(1).max(1e3),ignoredEvidence:p(l({id:Ke,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:o().trim().min(1).max(1e3),statement:lo,triageLayer:B_,expectedOutcome:lo,counterevidence:o().trim().max(1e4),confidence:d().min(0).max(1),candidateDisposition:v(["observe","confirm"]).nullable(),reason:lo}).strict().superRefine((e,t)=>{e.classification==="harness_maintenance"!==(e.candidateDisposition!==null)&&t.addIssue({code:"custom",message:"Harness maintenance requires a candidate disposition; external routes require null",path:["candidateDisposition"]})}),jB=l({schemaVersion:b("openpond.harnessEvaluationReviewModelDecision.v2"),decision:b("resolve_candidate"),candidateId:Ke,candidateFingerprint:Qe,selectedEvidenceIds:p(Ke).min(1).max(1e3),ignoredEvidence:p(l({id:Ke,reason:o().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:d().min(0).max(1),reason:lo}).strict();lt("decision",[EB,MB,jB]);l({schemaVersion:b("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:p(Ke).min(1).max(50),reason:lo}).strict();var dl=ae(o(),ie()).default({}),Da=d().int().nonnegative(),qm=o().trim().min(1).max(1e5),F_=l({kind:v(["personal","team"]),id:Ke}).strict(),OB=l({name:Ke,release:De.nullable(),revision:Da}).strict();l({schemaVersion:b("openpond.harnessWorkspace.v1"),id:Ke,ownerScope:F_,name:o().trim().min(1).max(240),location:v(["local","hosted"]),sourceRevision:o().trim().min(1).max(500),revision:Da,dirty:w(),currentChannel:OB,createdAt:Rt,updatedAt:Rt,metadata:dl}).strict();var Ws=v(["runtime","memory","prompt","skill","agent","product","taskset","training"]),V_=v(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),K_=l({id:Ke,route:Ws,operation:v(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),content:o().max(1e6).nullable(),contentHash:Qe.nullable(),effects:p(V_).min(1).max(20)}).strict().superRefine((e,t)=>{if(e.operation==="delete"){(e.content!==null||e.contentHash!==null)&&t.addIssue({code:"custom",message:"delete edits cannot include replacement content",path:["content"]});return}if(e.content===null||e.contentHash===null){t.addIssue({code:"custom",message:"create and update edits require content and contentHash",path:["content"]});return}const n=Pt(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),W_=l({workspaceId:Ke,revision:Da,sourceRevision:o().trim().min(1).max(500),channelRevision:Da}).strict(),co=l({id:Ke,revision:Da,contentHash:Qe}).strict();l({schemaVersion:b("openpond.harnessTurnSnapshot.v1"),workspaceId:Ke,workspaceRevision:Da,sourceRevision:o().trim().min(1).max(500),channelName:Ke,channelRevision:Da,harnessRelease:De,toolCatalogHash:Qe.nullable().optional(),overlay:co.nullable().optional().default(null)}).strict();var $B=l({schemaVersion:b("openpond.harnessRunOverlay.v1"),id:Ke,runId:Ke,baseHarnessRelease:De,workspace:W_,revision:Da,status:v(["active","frozen","abandoned"]),edits:p(K_).max(1e3),createdAt:Rt,updatedAt:Rt,metadata:dl}).strict();$B.extend({contentHash:Qe}).strict();var G_=l({kind:v(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:Ke,contentHash:Qe.nullable()}).strict(),J_=l({id:Ke,kind:v(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:qm,required:w()}).strict(),NB=l({schemaVersion:b("openpond.harnessImprovementProposal.v1"),id:Ke,overlay:co,baseHarnessRelease:De,expectedWorkspace:W_,requestedScope:v(["personal","team","global"]),route:Ws,risk:v(["low","review","restricted"]),effects:p(V_).min(1).max(20),evidence:p(G_).min(1).max(1e3),edits:p(K_).min(1).max(1e3),validationPlan:p(J_).min(1).max(100),expectedOutcome:qm,createdAt:Rt,metadata:dl}).strict().superRefine((e,t)=>{const n=new Set(e.effects);for(const[a,i]of e.edits.entries()){i.route!==e.route&&t.addIssue({code:"custom",message:"every edit route must match the proposal route",path:["edits",a,"route"]});for(const r of i.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"]})});NB.extend({contentHash:Qe}).strict();var DB=l({schemaVersion:b("openpond.harnessTargetedValidationReceipt.v1"),id:Ke,proposal:De,validationId:Ke,kind:J_.shape.kind,status:v(["passed","failed","blocked","skipped"]),summary:qm,evidenceRefs:p(G_).max(1e3),createdAt:Rt,metadata:dl}).strict();DB.extend({contentHash:Qe}).strict();var HB=v(["advanced","retained","conflict","rolled_back"]),LB=l({schemaVersion:b("openpond.harnessAdvanceReceipt.v1"),id:Ke,workspaceId:Ke,ownerScope:F_,proposal:De.nullable(),expectedWorkspaceRevision:Da,observedWorkspaceRevision:Da,previousChannelRevision:Da,nextChannelRevision:Da,previousRelease:De.nullable(),nextRelease:De.nullable(),validationReceipts:p(De).max(100),decision:HB,reason:qm,rollbackOf:De.nullable(),createdAt:Rt,metadata:dl}).strict().superRefine((e,t)=>{const n=e.nextChannelRevision===e.previousChannelRevision+1;["advanced","rolled_back"].includes(e.decision)!==n&&t.addIssue({code:"custom",message:"only successful advancement or rollback increments the channel revision",path:["nextChannelRevision"]}),e.decision==="rolled_back"&&e.rollbackOf===null&&t.addIssue({code:"custom",message:"rollback receipts require rollbackOf",path:["rollbackOf"]}),e.decision!=="rolled_back"&&e.rollbackOf!==null&&t.addIssue({code:"custom",message:"rollbackOf is only valid for rollback receipts",path:["rollbackOf"]})});LB.extend({contentHash:Qe}).strict();var qB=l({schemaVersion:b("openpond.harnessOverlayMergeReceipt.v1"),id:Ke,workspaceId:Ke,baseHarnessRelease:De,leftOverlay:co,rightOverlay:co,decision:v(["merged","conflict"]),mergedOverlay:co.nullable(),conflictTargets:p(o().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:b(!0),createdAt:Rt,metadata:dl}).strict().superRefine((e,t)=>{e.decision==="merged"!=(e.mergedOverlay!==null)&&t.addIssue({code:"custom",message:"merged decisions require a merged overlay; conflicts cannot provide one",path:["mergedOverlay"]}),e.decision==="conflict"!=e.conflictTargets.length>0&&t.addIssue({code:"custom",message:"conflict decisions require conflict targets and merged decisions cannot include them",path:["conflictTargets"]})});qB.extend({contentHash:Qe}).strict();var Um=o().trim().min(1).max(1e5),id=ae(o(),ie()).default({}),UB=v(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),Z_=l({kind:UB,eventSequence:d().int().nonnegative(),occurredAt:Rt}).strict(),Y_=l({id:Ke,sequence:d().int().nonnegative().nullable(),contentHash:Qe}).strict(),zB=v(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),BB=v(["open","recovered","terminal"]),FB=l({name:o().trim().min(1).max(500),invocationKey:Qe}).strict(),VB=l({schemaVersion:b("openpond.improvementObservation.v1"),id:Ke,runRef:Ke,turnId:Ke,harnessRelease:De,overlay:co.nullable(),eventRefs:p(Y_).min(1).max(100),kind:zB,state:BB,tool:FB.nullable(),deterministicClass:o().trim().min(1).max(500).nullable(),summary:Um,createdAt:Rt,metadata:id}).strict().superRefine((e,t)=>{new Set(e.eventRefs.map(n=>n.id)).size!==e.eventRefs.length&&t.addIssue({code:"custom",message:"observation event refs must be unique",path:["eventRefs"]}),["tool_failure","retry","recovery","completion_detour"].includes(e.kind)&&e.tool===null&&t.addIssue({code:"custom",message:`${e.kind} observations require a tool identity`,path:["tool"]})});VB.extend({contentHash:Qe}).strict();var KB=l({schemaVersion:b("openpond.refinementTriggerPolicy.v1"),maxEstimatedCostUsd:d().finite().nonnegative(),cooldownMs:d().int().nonnegative(),maxPendingPlans:d().int().min(1).max(100),maxEvidenceEvents:d().int().min(1).max(1e3),maxProposalEdits:d().int().min(1).max(1e3),maxProposalBytes:d().int().min(1).max(1e7)}).strict(),WB=v(["no_action","route_deterministically","queue_refiner"]),GB=l({schemaVersion:b("openpond.refinementTriggerDecision.v1"),id:Ke,runRef:Ke,turnId:Ke,harnessRelease:De,overlay:co.nullable(),observations:p(De).max(100),decision:WB,deterministicRoute:Ws.nullable(),suggestedRoutes:p(Ws).max(8),reason:Um,deduplicationKey:Qe,policy:KB,estimatedMaxCostUsd:d().finite().nonnegative(),pendingPlanCount:d().int().nonnegative(),boundary:Z_,cooldownUntil:Rt.nullable(),createdAt:Rt,metadata:id}).strict().superRefine((e,t)=>{e.estimatedMaxCostUsd>e.policy.maxEstimatedCostUsd&&t.addIssue({code:"custom",message:"estimated Refiner cost exceeds the trigger policy budget",path:["estimatedMaxCostUsd"]}),e.pendingPlanCount>e.policy.maxPendingPlans&&t.addIssue({code:"custom",message:"pending plan count exceeds the trigger policy limit",path:["pendingPlanCount"]}),e.observations.length>e.policy.maxEvidenceEvents&&t.addIssue({code:"custom",message:"trigger observations exceed the evidence budget",path:["observations"]}),e.decision==="route_deterministically"&&e.deterministicRoute===null&&t.addIssue({code:"custom",message:"deterministic decisions require a route",path:["deterministicRoute"]}),e.decision!=="route_deterministically"&&e.deterministicRoute!==null&&t.addIssue({code:"custom",message:"only deterministic decisions may declare a deterministic route",path:["deterministicRoute"]}),e.decision==="no_action"&&e.suggestedRoutes.length>0&&t.addIssue({code:"custom",message:"no-action decisions cannot suggest routes",path:["suggestedRoutes"]}),e.decision!=="no_action"&&e.observations.length===0&&t.addIssue({code:"custom",message:"actionable trigger decisions require observations",path:["observations"]})});GB.extend({contentHash:Qe}).strict();var JB=v(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),ZB=l({schemaVersion:b("openpond.improvementRouteDecision.v1"),id:Ke,trigger:De,route:Ws,authority:JB,automatic:w(),reason:Um,createdAt:Rt,metadata:id}).strict().superRefine((e,t)=>{e.automatic&&["human_review","evaluation_system","training_system"].includes(e.authority)&&t.addIssue({code:"custom",message:`${e.authority} routes cannot be marked automatic`,path:["automatic"]}),e.route==="training"&&e.automatic&&e.authority!=="training_system"&&t.addIssue({code:"custom",message:"automatic training routes require training-system authority",path:["authority"]})});ZB.extend({contentHash:Qe}).strict();var YB=l({schemaVersion:b("openpond.harnessRefinerOutcome.v1"),id:Ke,trigger:De,decision:v(["no_action","proposed"]),proposal:De.nullable(),reason:Um,evidenceRefs:p(De).max(100),estimatedCostUsd:d().finite().nonnegative(),createdAt:Rt,metadata:id}).strict().superRefine((e,t)=>{e.decision==="proposed"!=(e.proposal!==null)&&t.addIssue({code:"custom",message:"proposed Refiner outcomes require a proposal; no-action outcomes cannot include one",path:["proposal"]})});YB.extend({contentHash:Qe}).strict();var QB=v(["applied","retained","declined","conflict","rolled_back"]),XB=l({schemaVersion:b("openpond.improvementApplyReceipt.v1"),id:Ke,proposal:De,beforeOverlay:co,afterOverlay:co.nullable(),decision:QB,boundary:Z_,validationRefs:p(De).max(100),outcomeEvidenceRefs:p(Y_).max(1e3),rollbackOf:De.nullable(),createdAt:Rt,metadata:id}).strict().superRefine((e,t)=>{e.decision==="applied"!=(e.afterOverlay!==null)&&t.addIssue({code:"custom",message:"applied receipts require an after-overlay; other decisions cannot include one",path:["afterOverlay"]}),e.decision==="rolled_back"!=(e.rollbackOf!==null)&&t.addIssue({code:"custom",message:"only rollback receipts require rollbackOf",path:["rollbackOf"]})});XB.extend({contentHash:Qe}).strict();var eF=o().trim().min(1).max(2e3),gb=o().trim().min(1).max(1e5),tF=v(["create","update","delete"]),nF=v(["memory","prompt","skill","agent"]),aF=v(["runtime","product","taskset","training"]),iF=v(["no_action","routed","applied","retained","failed"]),oF=v(["not_applicable","pending","passed","rejected","failed"]),rF=v(["not_applicable","pending","passed","failed"]),sF=l({schemaVersion:b("openpond.harnessRefinerActivityReceipt.v1"),id:Ke,runRef:Ke,turnId:Ke,result:iF,decision:v(["no_action","route","propose"]).nullable(),route:Ws.nullable(),operation:tF.nullable(),target:o().trim().min(1).max(2e3).nullable(),summary:eF,evidenceBasis:cb.nullable(),critiqueStatus:oF,validationStatus:rF,trigger:De,outcome:De.nullable(),proposal:De.nullable(),applyReceipt:De.nullable(),inputHarness:De,outputHarness:De.nullable(),createdAt:Rt}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?cS(t,e,{decision:"no_action",route:null,operation:null,target:null,evidenceBasis:null,proposal:null,applyReceipt:null,outputHarness:null,critiqueStatus:"not_applicable",validationStatus:"not_applicable"}):e.result==="routed"?((e.decision!=="route"||!aF.safeParse(e.route).success||e.operation!==null||e.target!==null||e.evidenceBasis===null||e.proposal!==null||e.applyReceipt!==null||e.outputHarness!==null)&&t.addIssue({code:"custom",message:"routed activity requires an external route and evidence basis without proposal state"}),cS(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!nF.safeParse(e.route).success||e.operation===null||e.target===null||e.evidenceBasis===null||e.proposal===null||e.applyReceipt===null)&&t.addIssue({code:"custom",message:"applied and retained activity requires complete proposal state"}),e.result==="applied"&&e.outputHarness===null&&t.addIssue({code:"custom",message:"applied activity requires the advanced Harness release",path:["outputHarness"]}),e.result==="applied"&&(e.critiqueStatus!=="passed"||e.validationStatus!=="passed")&&t.addIssue({code:"custom",message:"applied activity requires passed critique and validation"}),e.result==="retained"&&e.outputHarness!==null&&t.addIssue({code:"custom",message:"retained activity cannot report a new Harness release",path:["outputHarness"]})):(e.decision!==null||e.route!==null||e.operation!==null||e.target!==null||e.evidenceBasis!==null||e.outcome!==null||e.proposal!==null||e.applyReceipt!==null||e.outputHarness!==null)&&t.addIssue({code:"custom",message:"failed activity cannot claim a decision, route, proposal, or release transition"}),e.result!=="failed"&&e.outcome===null&&t.addIssue({code:"custom",message:"terminal Refiner decisions require an outcome reference",path:["outcome"]})});sF.extend({contentHash:Qe}).strict();var lF=v(["unresolved","confirmed","resolved","rejected","expired"]),cF=l({kind:v(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:gb,evidenceRefs:p(De).max(1e3),resolvedAt:Rt}).strict(),dF=l({schemaVersion:b("openpond.harnessRefinementCandidate.v1"),id:Ke,ownerScope:hb,workspaceRef:Ke,fingerprint:Qe,recurrenceFamily:o().trim().min(1).max(1e3),statement:gb,status:lF,occurrences:p(Rc).max(1e3),counterevidence:p(Rc).max(1e3),sourceReviews:p(De).min(1).max(100),relatedHarnessReleases:p(De).max(100),firstSeenAt:Rt,lastSeenAt:Rt,lastReviewedAt:Rt,expiresAt:Rt,resolution:cF.nullable(),createdAt:Rt,updatedAt:Rt}).strict().superRefine((e,t)=>{br(t,e.occurrences,"occurrences"),br(t,e.counterevidence,"counterevidence"),br(t,e.sourceReviews,"sourceReviews"),br(t,e.relatedHarnessReleases,"relatedHarnessReleases");const n=new Set(e.occurrences.map(i=>i.occurrenceKey));e.counterevidence.some(i=>n.has(i.occurrenceKey))&&t.addIssue({code:"custom",message:"supporting occurrences and counterevidence must be disjoint",path:["counterevidence"]});const a=e.status==="unresolved"||e.status==="confirmed";a&&e.occurrences.length===0&&t.addIssue({code:"custom",message:"actionable candidates require at least one supporting occurrence",path:["occurrences"]}),a&&[...e.occurrences,...e.counterevidence].some(i=>i.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"actionable candidates may contain only currently authorized evidence",path:["occurrences"]}),a!==(e.resolution===null)&&t.addIssue({code:"custom",message:"only resolved, rejected, or expired candidates require a resolution",path:["resolution"]}),e.status==="expired"&&e.resolution?.kind!=="expired"&&t.addIssue({code:"custom",message:"expired candidates require an expired resolution",path:["resolution","kind"]}),e.status==="rejected"&&e.resolution&&!["manual_rejection","source_revoked"].includes(e.resolution.kind)&&t.addIssue({code:"custom",message:"rejected candidates require a rejection or revocation resolution",path:["resolution","kind"]}),e.status==="resolved"&&e.resolution&&!["applied_change","later_success"].includes(e.resolution.kind)&&t.addIssue({code:"custom",message:"resolved candidates require applied-change or later-success evidence",path:["resolution","kind"]}),hF(t,e)});dF.extend({contentHash:Qe}).strict();var uF=v(["created","merged","rejected","expired","reopened","resolved"]),mF=l({schemaVersion:b("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:Ke,candidateId:Ke,decision:uF,beforeCandidate:De.nullable(),afterCandidate:De,review:De,addedEvidence:p(Rc).max(1e3),removedEvidence:p(De).max(1e3),reason:gb,createdAt:Rt}).strict().superRefine((e,t)=>{e.decision==="created"!=(e.beforeCandidate===null)&&t.addIssue({code:"custom",message:"only candidate creation omits the previous candidate reference",path:["beforeCandidate"]}),e.beforeCandidate&&e.beforeCandidate.contentHash===e.afterCandidate.contentHash&&t.addIssue({code:"custom",message:"candidate lifecycle transitions must change candidate content",path:["afterCandidate"]}),["created","reopened"].includes(e.decision)&&e.addedEvidence.length===0&&t.addIssue({code:"custom",message:`${e.decision} candidate transitions require added evidence`,path:["addedEvidence"]}),e.addedEvidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"candidate transitions may add only authorized evidence",path:["addedEvidence"]}),br(t,e.addedEvidence,"addedEvidence"),br(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>cg(a)));e.addedEvidence.some(a=>n.has(cg(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});mF.extend({contentHash:Qe}).strict();var pF=l({schemaVersion:b("openpond.harnessCrossRunRefinementRequest.v1"),id:Ke,ownerScope:hb,workspaceRef:Ke,candidate:De,candidateFingerprint:Qe,review:De,admittedHarness:De,evidence:p(Rc).min(1).max(1e3),capabilities:db,deduplicationKey:Qe,createdAt:Rt}).strict().superRefine((e,t)=>{e.evidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"cross-run refinement requires currently authorized evidence",path:["evidence"]}),br(t,e.evidence,"evidence"),Object.values(e.capabilities).some(Boolean)||t.addIssue({code:"custom",message:"cross-run refinement requires at least one available Harness capability",path:["capabilities"]});const n=fF(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});pF.extend({contentHash:Qe}).strict();function fF(e){return Pt({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function cS(e,t,n){for(const[a,i]of Object.entries(n))t[a]!==i&&e.addIssue({code:"custom",message:`${a} must be ${String(i)}`,path:[a]})}function br(e,t,n){const a=t.map(i=>cg(i));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function cg(e){if(!e||typeof e!="object"||Array.isArray(e))return String(e);const t=e;if(typeof t.occurrenceKey=="string")return t.occurrenceKey;const n=t.evidence;if(n&&typeof n=="object"&&!Array.isArray(n)){const a=n;return`${String(a.id)}:${String(a.contentHash)}`}return`${String(t.id)}:${String(t.contentHash)}`}function hF(e,t){const n=[["firstSeenAt",t.firstSeenAt],["lastSeenAt",t.lastSeenAt],["lastReviewedAt",t.lastReviewedAt],["updatedAt",t.updatedAt],["expiresAt",t.expiresAt]];for(let a=1;a<n.length;a+=1){const i=n[a-1],r=n[a];Date.parse(i[1])<=Date.parse(r[1])||e.addIssue({code:"custom",message:`${r[0]} must not precede ${i[0]}`,path:[r[0]]})}Date.parse(t.createdAt)>Date.parse(t.updatedAt)&&e.addIssue({code:"custom",message:"updatedAt must not precede createdAt",path:["updatedAt"]})}l({path:o().min(1).max(2e3),offset:d().int().nonnegative().default(0),length:d().int().positive().max(65536).default(16384)}).strict();var Q_=o().regex(/^[a-z][a-z0-9_-]{0,119}$/),X_=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"),gF=l({id:Q_,label:o().trim().min(1).max(240),description:o().max(4e3),inputSchema:ae(o(),ie()),invocation:lt("kind",[l({kind:b("instructions"),instructions:o().min(1).max(1e5).refine(e=>!!e.trim())}).strict(),l({kind:b("agent_action"),actionId:o().trim().min(1).max(240)}).strict()]),skillPaths:p(X_).max(100)}).strict();l({schemaVersion:b("openpond.profileWorkflows.v1"),workflows:p(gF).max(1e3)}).strict();var vF=l({id:o().trim().min(1).max(240),agentId:o().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:o().trim().min(1).max(240),inputSchema:ae(o(),ie())}).strict();l({schemaVersion:b("openpond.profileWorkflowActions.v1"),actions:p(vF).max(200)}).strict();l({schemaVersion:b("openpond.profileWorkflowBinding.v1"),profileId:o().trim().min(1).max(240),sourceRevision:o().trim().min(1).max(240),harnessRelease:De,catalogHash:Qe,workflowId:Q_}).strict();l({schemaVersion:b("openpond.profileComponentBinding.v1"),profileId:o().trim().min(1).max(240),sourceRevision:o().trim().min(1).max(240),harnessRelease:De,target:lt("kind",[l({kind:b("profile")}).strict(),l({kind:b("skill"),skillPath:X_}).strict(),l({kind:b("agent_action"),actionId:o().trim().min(1).max(240)}).strict()])}).strict();var Fu=o().min(1).max(2e3).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.startsWith("/")&&e.split("/").every(t=>t!==""&&t!=="."&&t!==".."),"source paths must be portable relative paths");o().regex(/^[a-z][a-z0-9_-]{0,119}$/);var bF={type:"object",properties:{},additionalProperties:!1};l({name:o().trim().min(1).max(240).optional(),description:o().max(4e3).optional(),skillPaths:p(Fu).max(100).optional(),assetPaths:p(Fu).max(100).optional()}).strict();l({actionId:o().trim().min(1).max(240),name:o().trim().min(1).max(240),description:o().max(4e3).default(""),inputSchema:ae(o(),ie()).default(bF),skillPaths:p(Fu).max(100).default([]),assetPaths:p(Fu).max(100).default([])}).strict();const yF="openpond.connectedEvidence.v1",SF="connected-evidence-1",Wd={files:100,sourceBytes:32*1024*1024,events:1e5,sessions:1e3,boundaries:5e3},ri=o().min(1).max(500),rc=o().regex(/^[a-f0-9]{64}$/),xF=o().datetime().nullable(),Gd=d().int().nonnegative().nullable(),eC=v(["native_chat","native_work","codex","claude_code","hermes","openclaw"]),kF=l({invocationId:ri,inputTokens:Gd,outputTokens:Gd,cachedInputTokens:Gd,totalTokens:Gd,provenance:v(["billed_invocation","reported_invocation","reported_cumulative"])}).strict(),dS=l({id:ri,sequence:d().int().nonnegative(),occurredAt:xF,kind:v(["message","tool_call","tool_result","compaction","artifact","terminal","usage","unknown"]),role:v(["user","assistant","system","tool"]).nullable(),callId:ri.nullable(),parentId:ri.nullable(),content:Vo(),usage:kF.nullable()}).strict(),IF=l({id:ri,familyKey:ri,projection:v(["turn","conversation"]),requestEventId:ri,start:d().int().nonnegative(),end:d().int().positive(),inputHash:rc,outputHash:rc.nullable(),revisionHash:rc,terminal:v(["completed","failed","cancelled","unknown"]),coverage:l({answer:w(),context:v(["retained","compacted","unknown"]),process:v(["retained","partial","absent"]),artifacts:v(["retained","references_only","absent"]),replay:b("unavailable"),gaps:p(o().max(500)).max(100)}).strict()}).strict();l({schemaVersion:b(yF),normalizerVersion:b(SF),origin:eC,sessionId:ri,branchId:ri.nullable(),parentSessionId:ri.nullable(),exporterVersion:o().max(200).nullable(),sourceFiles:p(l({path:ri,contentHash:rc,sizeBytes:d().int().nonnegative()}).strict()).max(Wd.files),events:p(dS).max(Wd.events),unmappedEvents:p(dS).max(Wd.events),boundaries:p(IF).max(Wd.boundaries),warnings:p(o().max(500)).max(100),contentHash:rc}).strict();const wF=l({schemaVersion:b("openpond.humanResultView.v1"),executionId:o().min(1),executionHash:o().regex(/^[a-f0-9]{64}$/),selection:p(_n).max(1e4),coverage:l({pending:d().int().nonnegative(),submitted:d().int().nonnegative(),accepted:d().int().nonnegative(),rejected:d().int().nonnegative(),cancelled:d().int().nonnegative()}).strict(),results:p(l({review:_n,decision:_n.nullable(),attemptIds:p(o().min(1)).min(1).max(2),mode:v(["individual","pairwise"]),origin:v(["hosted_retained","recorded_evidence","owner_attested_local","native_local"]),status:v(["pending","submitted","accepted","rejected","cancelled"]),grader:_n,answers:p(Vs).max(100)}).strict()).max(1e4)}).strict(),uS=wF.extend({contentHash:o().regex(/^[a-f0-9]{64}$/)}).strict(),Vu=o().regex(/^[a-f0-9]{64}$/),Pc=o().min(1).max(240),Jd={feedbackKey:Pc,criterionId:Pc},_F=lt("kind",[l({...Jd,kind:b("normalized_score"),minimum:d().finite(),maximum:d().finite(),passThreshold:d().min(0).max(1).optional()}).strict(),l({...Jd,kind:b("boolean")}).strict(),l({...Jd,kind:b("category")}).strict(),l({...Jd,kind:b("preference_score"),tieScore:d().min(0).max(1).nullable()}).strict()]),mS=l({execution:V,resultHash:Vu,reviews:p(l({review:_n,decision:_n}).strict()).min(1).max(1e4)}).strict(),tC=l({rules:p(_F).min(1).max(100),baseline:mS,candidate:mS}).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."})}),pS=l({manifest:ro,result:so}).strict(),fS=l({id:Pc,manifestHash:Vu,resultHash:Vu}).strict(),CF=l({schemaVersion:b("openpond.humanComparisonProjection.v1"),teamId:Pc,projectId:Pc,selections:tC,original:l({baseline:fS,candidate:fS}).strict(),humanResults:l({baseline:uS,candidate:uS}).strict(),baseline:pS,candidate:pS}).strict(),dg=CF.extend({contentHash:Vu}).strict();function th(e){throw new Xv(e,409)}function RF(e,t){const n=dg.parse(e),{contentHash:a,...i}=n;a!==st(i)&&th("human_comparison_projection_invalid");for(const r of["baseline","candidate"]){const s=wr(n[r]),c=s.manifest.lineage,m=c?.humanProjection,u=n.original[r],h=n.selections[r];(!c||!m||m.originalManifest.id!==u.id||m.originalManifest.contentHash!==u.manifestHash||m.selectionHash!==st(h)||m.rulesHash!==st(n.selections.rules)||st(c.execution)!==st(h.execution)||s.manifest.teamId!==n.teamId||n.humanResults[r].contentHash!==h.resultHash)&&th("human_comparison_projection_lineage_changed");const{contentHash:g,...S}=n.humanResults[r];(st(S)!==g||S.executionId!==h.execution.id||S.executionHash!==h.execution.contentHash||st(S.selection)!==st(h.reviews.map(k=>k.review)))&&th("human_comparison_human_result_changed")}return n}var PF=l({schemaVersion:b("openpond.connectedDatasetSource.v1"),kind:b("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:v(["pending","approved","review","blocked"]),secretScanStatus:v(["pending","passed","blocked"]),piiScanStatus:v(["pending","passed","review","blocked"]),origin:eC,sourceId:o().min(1).max(500),sessionId:o().min(1).max(500),normalizerVersion:o().min(1).max(200),projection:v(["turn","conversation"]),ownerUserId:o().min(1).max(500),purpose:b("recorded_evaluation"),metadata:ae(o(),ie()).default({})}).strict(),Ua=o().trim().min(1).max(240),uo=o().trim().min(1),Fo=o().trim().min(8).max(256),nC=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."),Jo=v(["train","validation","test","frozen_eval"]),AF=l({name:o().trim().min(1).max(500),semanticRole:v(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),logicalType:v(["string","integer","float","boolean","json","messages"]),nullable:w(),policy:v(["visible","privileged","metadata"])}),TF=l({schemaVersion:b("openpond.datasetSemanticSchema.v1"),fields:p(AF).min(1).max(1e4),schemaHash:Fo}),EF=l({id:Ua,split:Jo,path:nC,contentHash:Fo,schemaHash:Fo,sizeBytes:d().int().nonnegative(),rowCount:d().int().positive(),rowGroupCount:d().int().positive()}),vb=l({schemaVersion:b("openpond.datasetArtifact.v1"),id:Ua,tasksetId:Ua,tasksetRevision:d().int().positive(),contentHash:Fo,format:b("parquet"),schema:TF,shards:p(EF).min(1).max(1e5),rowCount:d().int().positive(),splitCounts:ae(Jo,d().int().nonnegative()),sourceReceiptRefs:p(Ua).min(1).max(1e5),mappingHash:Fo,qualityReportHash:Fo,createdAt:uo}),MF=l({schemaVersion:b("openpond.datasetArtifactSummary.v1"),artifactId:Ua,tasksetId:Ua,tasksetRevision:d().int().positive(),format:b("parquet"),rowCount:d().int().positive(),splitCounts:ae(Jo,d().int().nonnegative()),sizeBytes:d().int().nonnegative(),contentHash:Fo,available:w(),unavailableReason:o().trim().min(1).max(2e3).nullable(),createdAt:uo}),jF=l({schemaVersion:b("openpond.datasetCatalogItem.v1"),tasksetId:Ua,tasksetRevision:d().int().positive(),artifactId:Ua.nullable(),name:o().trim().min(1).max(500),status:v(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),storageKind:v(["inline","parquet"]),rowCount:d().int().nonnegative(),splitCounts:ae(Jo,d().int().nonnegative()),sizeBytes:d().int().nonnegative().nullable(),available:w(),unavailableReason:o().trim().min(1).max(2e3).nullable(),createdAt:uo,updatedAt:uo});l({schemaVersion:b("openpond.datasetCatalog.v1"),profileId:Ua,datasets:p(jF),generatedAt:uo});l({schemaVersion:b("openpond.datasetArtifactRegistry.v1"),manifest:vb,profileId:Ua,storageRoot:o().trim().min(1).max(4e3),relativeManifestPath:nC,available:w(),unavailableReason:o().trim().min(1).max(2e3).nullable(),verifiedAt:uo.nullable(),createdAt:uo,updatedAt:uo});l({split:Jo.nullable().default(null),cursor:o().trim().min(1).max(2e3).nullable().default(null),limit:d().int().min(1).max(100).default(25),columns:p(o().trim().min(1).max(500)).max(100).default([])});l({schemaVersion:b("openpond.datasetRowPage.v1"),tasksetId:Ua,tasksetRevision:d().int().positive(),artifactHash:Fo,split:Jo.nullable(),rows:p(ae(o(),ie())).max(100),nextCursor:o().max(2e3).nullable(),totalRows:d().int().nonnegative(),returnedRows:d().int().nonnegative()});var OF=l({schemaVersion:b("openpond.datasetStorageSettings.v1"),datasetStorePath:o().trim().min(1).max(4e3),updatedAt:uo}),$F=l({id:Ua,label:o().trim().min(1).max(500),path:o().trim().min(1).max(4e3),datasetStorePath:o().trim().min(1).max(4e3),kind:v(["local","network","removable","cache"]),configured:w(),mounted:w(),writable:w(),totalBytes:d().int().nonnegative().nullable(),freeBytes:d().int().nonnegative().nullable()});l({schemaVersion:b("openpond.datasetStorageState.v1"),settings:OF,storageRoots:p($F)});l({datasetStorePath:o().trim().min(1).max(4e3)});var Os=o().trim().min(1).max(240),NF=o().trim().min(1),Gs=o().trim().min(8).max(256),DF=ae(o(),ie()).default({}),HF=o().trim().min(7).max(256),LF=v(["pending","approved","review","blocked"]),zm=l({id:Os,profileId:Os,title:o().trim().min(1).max(500),sourceHash:Gs,occurredAt:NF,licensingStatus:LF,secretScanStatus:v(["pending","passed","blocked"]),piiScanStatus:v(["pending","passed","review","blocked"]),metadata:DF}),qF=zm.extend({schemaVersion:b("openpond.huggingFaceDatasetSource.v1"),kind:b("huggingface"),repositoryId:o().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:o().url().max(2e3),revision:HF,configuration:o().trim().min(1).max(500),upstreamSplits:p(o().trim().min(1).max(500)).min(1).max(1e3),gated:w(),private:w(),declaredLicense:o().trim().min(1).max(500).nullable(),sourceFileHashes:p(Gs).min(1).max(1e5)}),UF=zm.extend({schemaVersion:b("openpond.uploadedFileDatasetSource.v1"),kind:b("uploaded_file"),originalFileNames:p(o().trim().min(1).max(500)).min(1).max(1e3),mediaTypes:p(o().trim().min(1).max(200)).min(1).max(1e3),sourceFileHashes:p(Gs).min(1).max(1e3),totalBytes:d().int().nonnegative(),parserVersion:o().trim().min(1).max(200)}),zF=zm.extend({schemaVersion:b("openpond.generatedDatasetSource.v1"),kind:b("generated"),generatorId:Os,generatorVersion:o().trim().min(1).max(200),seed:d().int(),generatorHash:Gs}),BF=zm.extend({schemaVersion:b("openpond.learningBatchDatasetSource.v1"),kind:b("learning_batch"),batch:l({id:Os,revision:d().int().positive(),contentHash:Gs}).strict(),taskDefinition:l({id:Os,revision:d().int().positive(),contentHash:Gs}).strict(),admittedBy:Os}),FF=lt("kind",[qF,UF,zF,BF]),VF=l({schemaVersion:b("openpond.harnessActionBinding.v1"),actionId:Ke,modelToolName:o().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:o().trim().min(1).max(1e3),inputSchema:ae(o(),ie()),actionSchemaHash:Qe,agentRelease:De,implementationHash:Qe,runtimeBindingId:Ke,capabilityReceiptHash:Qe,sideEffect:v(["read","write"]),studentVisible:w(),timeoutMs:d().int().positive().max(36e5),episodeArgumentBindings:p(l({argument:Ke,source:b("case_id")}).strict()).max(20).default([])}).strict(),Et=o().trim().min(1).max(240),bb=o().trim().min(1),KF=o().trim().min(8).max(256),yb=o().trim().regex(/^[a-f0-9]{64}$/),WF=o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),di=ae(o(),ie()).default({}),Bm=Et.nullable();function od(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function GF(e){const t=e.trim();return t.length>0&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")}var Js=Jo,aC=v(["general","benchmark"]),iC=l({schemaVersion:b("openpond.tasksetBenchmark.v1"),definitionId:Et,releaseId:Et,releaseHash:yb,managedReleasePath:o().trim().min(1).max(1e3).refine(od,"Benchmark release paths must remain relative."),adaptationSplit:Js,evaluationSplit:Js,primaryMetric:v(["foreground_tokens","success_rate","latency_ms","cost_usd"]),qualityGate:v(["none","non_regression","all_pass"]),source:v(["builtin","imported"]),metadata:di}),oC=l({schemaVersion:b("openpond.tasksetPreferenceComparisonBinding.v1"),releaseId:Et,releaseHash:yb,publishedAt:bb,metadata:di}),JF=l({status:v(["pending","granted","denied","revoked"]),scope:v(["metadata_only","selected_turns","full_session"]),grantedBy:Bm,grantedAt:bb.nullable(),purpose:b("task_authoring_and_evaluation")}),rC=l({schemaVersion:b("openpond.trainingSource.v1"),id:Et,profileId:Et,sessionId:Et,turnIds:p(Et).max(1e3).default([]),workspaceId:Bm,sourceHash:KF,clusterKey:Et,title:o().trim().min(1).max(500),occurredAt:bb,consent:JF,connectedAppIds:p(Et).max(100).default([]),secretScanStatus:v(["pending","passed","blocked"]),piiScanStatus:v(["pending","passed","review","blocked"]),licensingStatus:v(["pending","approved","review","blocked"]),metadata:di}),sC=ht([rC,FF,PF]),Sb=l({policyVisibleFields:p(Et).max(1e3).default([]),privilegedFields:p(Et).max(1e3).default([]),hiddenGraderRefs:p(Et).max(100).default([]),connectedAppScopes:p(Et).max(100).default([])}),ZF=l({id:Et,sourceRefId:Et,artifactRef:o().trim().min(1).max(4e3).refine(od,"Task asset references must be safe relative paths."),fileName:o().trim().min(1).max(500).refine(GF,"Task asset file names must not contain path separators."),mediaType:o().trim().min(1).max(200),sha256:yb,sizeBytes:d().int().nonnegative().max(25e7),split:Js,metadata:di}),YF=l({path:o().trim().min(1).max(1e3).refine(od,"Required output paths must stay inside the Work output directory."),mediaType:o().trim().min(1).max(200),schemaRef:Et.nullable().optional(),maxBytes:d().int().positive().max(1e7).optional(),metadata:di}),Fm=l({schemaVersion:b("openpond.taskData.v1"),id:Et,clusterKey:Et,split:Js,input:ae(o(),ie()),expectedOutput:ae(o(),ie()).nullable(),policyVisibleContext:ae(o(),ie()).default({}),privilegedContextRef:Bm,sourceRefs:p(Et).min(1).max(100),assets:p(ZF).max(1e3).optional(),resourceRefs:p(Et).max(1e3).optional(),requiredOutputs:p(YF).max(100).optional(),tags:p(Et).max(100).default([]),metadata:di}),QF=l({id:Et,kind:v(["file","catalog","configuration","code_module"]),path:o().trim().min(1).max(1e3).refine(od,"Environment resource paths must remain relative."),mediaType:o().trim().min(1).max(200).nullable().optional(),visibility:v(["policy_visible","policy_hidden","privileged"]),required:w(),metadata:di}),ul=l({id:Et,taskId:Bm,sourceRefs:p(Et).min(1).max(100),artifactRef:Et,approved:w(),confidence:d().min(0).max(1),metadata:di}),lC=ul.extend({kind:b("demonstration"),prompt:o().max(1e5).nullable().default(null),response:o().max(2e5).nullable().default(null)}),cC=ul.extend({kind:b("preference"),prompt:o().max(1e5),chosen:o().max(2e5),rejected:o().max(2e5),rationale:o().max(1e5).nullable().default(null)}),dC=ul.extend({kind:b("correction"),original:o().max(2e5),corrected:o().max(2e5),rationale:o().max(1e5).nullable().default(null)}),uC=ul.extend({kind:b("feedback"),feedback:o().max(1e5),polarity:v(["positive","negative","mixed","neutral"])}),mC=ul.extend({kind:b("reward"),task:o().max(1e5),rules:p(l({id:Et,points:d().finite(),condition:o().trim().min(1).max(1e5)})).min(1).max(1e3),otherwisePoints:d().finite(),executable:w()}),pC=ul.extend({kind:b("label"),labelKind:b("rubric"),task:o().max(1e5),criteria:p(l({id:Et,label:o().trim().min(1).max(500),description:o().trim().min(1).max(1e5)})).min(1).max(1e3),calibrationExamples:l({positive:o().trim().min(1).max(2e5),negative:o().trim().min(1).max(2e5),boundary:o().trim().min(1).max(2e5)})});lt("kind",[lC,cC,dC,uC,mC,pC]);var fC=l({demonstrations:p(lC).max(1e5).default([]),preferences:p(cC).max(1e5).default([]),corrections:p(dC).max(1e5).default([]),feedback:p(uC).max(1e5).default([]),rewards:p(mC).max(1e5).default([]),labels:p(pC).max(1e5).default([])}),hC=l({protocolVersion:b("openpond.taskEnvironment.v1"),kind:v(["chat","agent","program","stateful_harness","work"]),entrypoint:o().trim().min(1).max(1e3),stateful:w(),deterministicSeeds:w(),toolNames:p(Et).max(200).default([]),actionBindings:p(VF).max(200).optional(),lifecycle:p(v(["create","reset","step","grade","cleanup"])).min(1),defaultTimeoutMs:d().int().positive().max(36e5),networkPolicy:v(["none","declared_read_only","declared_scoped"]),resources:p(QF).max(1e4).optional(),metadata:di}),xb=l({schemaVersion:b("openpond.tasksetCapabilities.v1"),taskKind:v(["chat","single_agent","multi_agent","custom_program"]),supportedSignals:p(v(["demonstration","preference","correction","feedback","reward","label"])),compatibleMethods:p(v(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"])),rewardKinds:p(v(["none","exact","deterministic","model_judge","human"])),requiresTools:w(),requiresState:w(),requiresPrivilegedGrading:w(),environmentPlacements:p(v(["local","remote","colocated","provider_native"])),exportable:w(),portabilityBlockers:p(o().trim().min(1).max(2e3)).default([])}),Vm=l({id:Et,version:o().trim().min(1).max(100),label:o().trim().min(1).max(500),weight:d().min(0).max(1e3).default(1),hardGate:w().default(!1),rewardEligible:w().default(!1),privileged:w().default(!1),metadata:di}),XF=Vm.extend({kind:v(["content","schema","file","diff","test","runtime_event","state"]),config:ae(o(),ie())}),e5=Vm.extend({kind:b("model_judge"),rubric:o().trim().min(1).max(5e4),judge:fb,calibrationFixtureRefs:p(Et).min(1).max(500),calibrationStatus:v(["pending","passed","failed"]),temperature:d().min(0).max(2).default(0)}),t5=Vm.extend({kind:b("human"),form:Rm.optional(),rubric:o().trim().min(1).max(5e4),reviewerRole:o().trim().min(1).max(500)}),n5=Vm.extend({kind:b("custom_verifier"),runtime:Uw.optional(),module:o().trim().min(1).max(1e3).refine(od,"Custom verifier modules must use a safe relative path."),exportName:WF,timeoutMs:d().int().positive().max(3e5),networkPolicy:b("none")}),Km=ht([XF,e5,t5,n5]),kb=v(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]),gC=l({id:Et,taskId:Et,label:kb,output:ae(o(),ie()),infrastructureError:o().trim().min(1).max(1e4).nullable(),expectedPassed:w(),expectedRewardEligible:w(),metadata:di}),Pi=o().trim().min(1).max(240),Ac=o().trim().min(1),Ku=o().trim().min(8).max(256),vC=ae(o(),ie()).default({}),a5=Pi.nullable(),i5=["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"],o5=v(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),bC=v(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),Gn=o().trim().max(1e5),yC=lt("kind",[l({kind:b("demonstrations"),behavior:Gn,examples:p(l({id:Pi,prompt:Gn,response:Gn})).max(1e3).default([])}),l({kind:b("preferences"),preference:Gn,pairs:p(l({id:Pi,prompt:Gn,chosen:Gn,rejected:Gn,rationale:Gn})).max(1e3).default([])}),l({kind:b("verifiable_reward"),task:Gn,rules:p(l({id:Pi,points:d().finite(),condition:Gn})).max(1e3).default([]),otherwisePoints:d().finite().default(0)}),l({kind:b("rubric"),task:Gn,criteria:p(l({id:Pi,label:o().trim().max(500),description:Gn})).max(1e3).default([]),positiveExample:Gn,negativeExample:Gn,boundaryExample:Gn})]),r5=l({path:o().trim().min(1).max(1e3),role:v(["environment","verifier","fixture"]),content:o().max(25e4)}),SC=l({primaryMethod:v(["sft","dpo","grpo","ppo","sdft","opsd","sdpo"]),bootstrap:l({method:b("sft"),purpose:b("trajectory_bootstrap"),demonstrationRefs:p(Pi).min(1).max(1e5),limitations:p(o().trim().min(1).max(5e3)).min(1).max(100)}).nullable()}),xC=v(["taskset_not_ready","demonstrations_missing","preference_pairs_missing","preference_pairs_invalid","executable_reward_missing","reward_not_calibrated","reward_model_missing","value_model_required","frozen_eval_missing"]),s5=l({method:v(["sft","dpo","grpo","ppo"]),status:v(["recommended","compatible","needs_dataset_work"]),reasonCodes:p(xC).default([]),reasons:p(o().trim().min(1).max(5e3)).default([])}),hS=l({code:Pi,message:o().trim().min(1).max(5e3),path:o().trim().max(2e3).nullable()}),kC=l({schemaVersion:b("openpond.tasksetReadiness.v1"),tasksetId:Pi,tasksetHash:Ku,ready:w(),recommendedMethod:v(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),trainingPath:SC.nullable().default(null),methodReadiness:p(s5).default([]),compatibleDestinationClasses:p(v(["export","custom","hosted_managed"])),blockers:p(hS).default([]),advisories:p(hS).default([]),warnings:p(o().trim().min(1).max(5e3)).default([]),generatedAt:Ac}),IC=l({attempt:d().int().positive(),summary:o().trim().min(1).max(5e3),createdAt:Ac}),l5=l({schemaVersion:b("openpond.taskAuthoringProvenance.v1"),model:fb.nullable(),modelConfig:vC,skillHash:Ku,promptTemplateVersion:o().trim().min(1).max(200),buildIntent:bC.default("demonstrations"),buildSpecification:yC.nullable().default(null),evidenceHashes:p(Ku).max(1e5),tasksetSdkVersion:o().trim().min(1).max(100),sourceCommit:o().trim().min(1).max(256).nullable(),repairHistory:p(IC).max(1e3),createdAt:Ac}),Tc=l({schemaVersion:b("openpond.taskset.v1"),id:Pi,revision:d().int().positive().default(1),profileId:Pi,profileRelease:o4.nullable().optional(),createImproveRunId:a5.default(null),name:o().trim().min(1).max(500),objective:o().trim().max(2e4),purpose:aC.default("general"),benchmark:iC.nullable().default(null),preferenceComparison:oC.nullable().default(null),status:o5,sourceRefs:p(sC).min(1).max(1e5),datasetArtifact:vb.nullable().optional(),policy:Sb,environment:hC,capabilities:xb,metrics:ed.optional(),tasks:p(Fm).max(1e6),graders:p(Km).min(1).max(1e3),graderFixtures:p(gC).max(1e5),learningSignals:fC,authoringProvenance:l5,readiness:kC.nullable(),contentHash:Ku,createdAt:Ac,updatedAt:Ac,metadata:vC}).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 wC(e){return e.schemaVersion==="openpond.trainingSource.v1"}function c5(e,t={}){const n=Tc.safeParse(e);if(!n.success)return{valid:!1,taskset:null,computedHash:null,issues:n.error.issues.map(s=>({code:"schema_invalid",severity:"error",message:s.message,path:s.path.join(".")}))};const a=n.data,i=[];p5(a,i),u5(a,i),f5(a,i),g5(a,i),v5(a,i),d5(a,i,t),b5(a,i),y5(a.capabilities,i,a),h5(a,i);const r=_C(a);return a.contentHash!==r&&i.push({code:"content_hash_mismatch",severity:"error",message:`Taskset contentHash is ${a.contentHash}, expected ${r}.`,path:"contentHash"}),{valid:!i.some(s=>s.severity==="error"),taskset:a,computedHash:r,issues:i}}function d5(e,t,n){!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 a=new Set(e.tasks.map(r=>r.id)),i=new Set(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]);for(const r of e.graderFixtures)!e.datasetArtifact&&!a.has(r.taskId)&&t.push({code:"grader_fixture_task_missing",severity:"warning",message:`Fixture ${r.id} references a task outside this Taskset revision (${r.taskId}).`,path:`graderFixtures.${r.id}.taskId`}),i.delete(r.label),r.label==="infrastructure_failure"&&!r.infrastructureError&&t.push({code:"infrastructure_fixture_error_missing",severity:"error",message:`Infrastructure fixture ${r.id} must declare an infrastructure error.`,path:`graderFixtures.${r.id}.infrastructureError`});for(const r of i)t.push({code:"grader_fixture_missing",severity:"warning",message:`Taskset does not include the optional ${r} grader calibration fixture.`,path:"graderFixtures"})}function u5(e,t){const n=e.datasetArtifact;if(!n)return;(n.tasksetId!==e.id||n.tasksetRevision!==e.revision)&&t.push({code:"dataset_artifact_taskset_mismatch",severity:"error",message:"Dataset artifact identity does not match its Taskset revision.",path:"datasetArtifact"});const a=Object.values(n.splitCounts).reduce((m,u)=>m+u,0),i=n.shards.reduce((m,u)=>m+u.rowCount,0);(a!==n.rowCount||i!==n.rowCount)&&t.push({code:"dataset_artifact_row_count_mismatch",severity:"error",message:"Dataset artifact row, split, and shard counts do not agree.",path:"datasetArtifact.rowCount"});const r=new Map;for(const m of n.shards)r.set(m.split,(r.get(m.split)??0)+m.rowCount);for(const[m,u]of Object.entries(n.splitCounts))(r.get(m)??0)!==u&&t.push({code:"dataset_artifact_split_count_mismatch",severity:"error",message:`Dataset artifact ${m} shard counts do not match its manifest.`,path:`datasetArtifact.splitCounts.${m}`});const{contentHash:s,...c}=n;Pt(c)!==n.contentHash&&t.push({code:"dataset_artifact_hash_mismatch",severity:"error",message:"Dataset artifact manifest content hash is invalid.",path:"datasetArtifact.contentHash"})}function m5(e){return _C(e)}function _C(e){const{contentHash:t,status:n,readiness:a,updatedAt:i,...r}=e;return Pt(r)}function p5(e,t){for(const[n,a]of e.sourceRefs.entries())wC(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 f5(e,t){const n=new Map;for(const i of e.tasks){const r=n.get(i.clusterKey)??new Set;r.add(i.split),n.set(i.clusterKey,r)}for(const[i,r]of n)r.size>1&&t.push({code:"split_cluster_contamination",severity:"error",message:`Source cluster ${i} appears in multiple splits: ${[...r].join(", ")}.`,path:"tasks"});(e.datasetArtifact?e.datasetArtifact.splitCounts.frozen_eval??0:e.tasks.filter(i=>i.split==="frozen_eval").length)===0&&t.push({code:"frozen_eval_missing",severity:"warning",message:"Add an independent test example before training.",path:"tasks"})}function h5(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(i5),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 i=new Map(e.sourceRefs.map(r=>[r.id,r]));for(const[r,s]of e.tasks.entries()){const c=new Set,m=new Set;for(const[h,g]of(s.assets??[]).entries()){const S=`tasks.${r}.assets.${h}`;c.has(g.id)&&t.push({code:"work_asset_duplicate_id",severity:"error",message:`Task ${s.id} repeats asset id ${g.id}.`,path:`${S}.id`}),m.has(g.fileName)&&t.push({code:"work_asset_duplicate_name",severity:"error",message:`Task ${s.id} repeats staged file name ${g.fileName}.`,path:`${S}.fileName`}),c.add(g.id),m.add(g.fileName),s.sourceRefs.includes(g.sourceRefId)||t.push({code:"work_asset_task_source_missing",severity:"error",message:`Asset ${g.id} references source ${g.sourceRefId} outside task ${s.id}.`,path:`${S}.sourceRefId`});const k=i.get(g.sourceRefId);k?"sourceFileHashes"in k&&!k.sourceFileHashes.includes(g.sha256)&&t.push({code:"work_asset_hash_unregistered",severity:"error",message:`Asset ${g.id} hash is not registered by source ${g.sourceRefId}.`,path:`${S}.sha256`}):t.push({code:"work_asset_source_missing",severity:"error",message:`Asset ${g.id} references missing source ${g.sourceRefId}.`,path:`${S}.sourceRefId`}),k&&"kind"in k&&k.kind==="uploaded_file"&&!k.originalFileNames.includes(g.fileName)&&t.push({code:"work_asset_name_unregistered",severity:"error",message:`Asset ${g.id} file name is not registered by source ${g.sourceRefId}.`,path:`${S}.fileName`}),k&&"kind"in k&&k.kind==="uploaded_file"&&!k.mediaTypes.includes(g.mediaType)&&t.push({code:"work_asset_media_type_unregistered",severity:"error",message:`Asset ${g.id} media type is not registered by source ${g.sourceRefId}.`,path:`${S}.mediaType`}),g.split!==s.split&&t.push({code:"work_asset_split_mismatch",severity:"error",message:`Asset ${g.id} is assigned to ${g.split}, not task split ${s.split}.`,path:`${S}.split`})}const u=new Set;for(const[h,g]of(s.requiredOutputs??[]).entries()){const S=g.path.replaceAll("\\","/"),k=`tasks.${r}.requiredOutputs.${h}.path`;u.has(S)&&t.push({code:"work_output_duplicate_path",severity:"error",message:`Task ${s.id} repeats required output path ${S}.`,path:k}),u.add(S)}(s.requiredOutputs??[]).length===0&&t.push({code:"work_output_missing",severity:"error",message:`Work task ${s.id} must declare at least one required output.`,path:`tasks.${r}.requiredOutputs`})}}function g5(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 v5(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 b5(e,t){const n=new Set(e.tasks.map(i=>i.id)),a=new Set(e.sourceRefs.map(i=>i.id));for(const i of[...e.learningSignals.demonstrations,...e.learningSignals.preferences,...e.learningSignals.corrections,...e.learningSignals.feedback,...e.learningSignals.rewards,...e.learningSignals.labels])i.taskId&&!e.datasetArtifact&&!n.has(i.taskId)&&t.push({code:"learning_signal_task_missing",severity:"error",message:`Signal ${i.id} references missing task ${i.taskId}.`,path:`learningSignals.${i.kind}.${i.id}.taskId`}),i.sourceRefs.some(r=>!a.has(r))&&t.push({code:"learning_signal_source_missing",severity:"error",message:`Signal ${i.id} references a source outside the Dataset.`,path:`learningSignals.${i.kind}.${i.id}.sourceRefs`});for(const i of e.learningSignals.preferences)i.chosen.trim()===i.rejected.trim()&&t.push({code:"preference_pair_identical",severity:"error",message:`Preference ${i.id} has identical chosen and rejected responses.`,path:`learningSignals.preferences.${i.id}`});for(const i of e.learningSignals.rewards)i.executable||t.push({code:"reward_not_executable",severity:"warning",message:`Reward ${i.id} is a reviewed specification but has no executable verifier yet.`,path:`learningSignals.rewards.${i.id}.executable`})}function y5(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 _s=o().trim().min(1).max(240),gS=o().trim().min(1),S5=o().trim().min(8).max(256),x5=o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),k5=ae(o(),ie()).default({});function vS(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}var CC=Fm.extend({sourceRefs:p(_s).max(100).default([])}),RC=v(["draft","validating","needs_review","published"]),I5=l({enabled:w(),candidateCount:d().int().min(2).max(4),minimumSamples:d().int().min(1).max(1e4).default(100),allowTies:w(),allowRejectAll:w(),rubric:o().trim().max(5e4),criteria:p(l({id:_s,label:o().trim().min(1).max(500),description:o().trim().max(1e4),weight:d().nonnegative().max(1e3)})).max(100)}),w5=l({mode:v(["text","structured_json","artifacts"]),jsonSchema:ae(o(),ie()).nullable(),renderer:l({module:o().trim().min(1).max(1e3).refine(vS,"Renderer modules must use a safe relative path."),exportName:x5,configRef:o().trim().min(1).max(1e3).refine(vS,"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"]})}),Ba=l({schemaVersion:b("openpond.tasksetDraft.v1"),id:_s,revision:d().int().positive(),profileId:_s,modelScope:l({modelId:_s,expectedModelRevision:d().int().positive(),source:Hz.optional()}).strict().nullable().default(null),name:o().trim().max(500),objective:o().trim().max(2e4),purpose:aC.default("general"),benchmark:iC.nullable().default(null),preferenceComparison:oC.nullable().default(null),status:RC,sourceRefs:p(sC).max(1e5).default([]),datasetArtifact:vb.nullable().optional(),policy:Sb,environment:hC,output:w5.default({mode:"text",jsonSchema:null,renderer:null}),capabilities:xb,metrics:ed,review:I5,tasks:p(CC).max(1e6).default([]),graders:p(Km).max(1e3).default([]),graderFixtures:p(gC).max(1e5).default([]),learningSignals:fC,publishedTasksetRef:l({id:_s,revision:d().int().positive(),contentHash:S5}).nullable(),createdAt:gS,updatedAt:gS,metadata:k5}).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"]})}),_5=6e6,C5=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 R5(e){const t=ad.parse(e);return!C5.has(t)&&!t.startsWith("source-artifacts/")}function bS(e,t){const n=R5(e);if(t.byteLength>_5)throw new Error("Taskset draft file content is invalid or exceeds 6 MB.");let a;try{const i=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t);a=/[\u0000-\u0008\u000e-\u001f]/.test(i)?yS(t):{encoding:"utf8",data:i}}catch{a=yS(t)}return{path:e,writable:n,content:a,sizeBytes:t.byteLength,contentHash:C_(t)}}function yS(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 SS=64*1024*1024,PC=o().regex(/^[a-f0-9]{64}$/),P5=l({path:ad,contentHash:PC,sizeBytes:d().int().nonnegative().max(SS),base64:o().max(SS)}).strict(),A5=l({schemaVersion:b("openpond.tasksetDraftWorkspace.v1"),draft:Ba,files:p(P5).max(1e4)}).strict(),aae=A5.extend({contentHash:PC}).strict(),xS=class extends Error{issues;constructor(e){super(e.map(t=>t.message).join(`
178
+ `)),this.name="TasksetDraftPublishError",this.issues=e}};function T5(e){const t=[];e.name.trim()||t.push({code:"name_missing",message:"Name is required.",path:"name"}),e.objective.trim()||t.push({code:"objective_missing",message:"Objective is required.",path:"objective"}),!e.datasetArtifact&&e.tasks.length===0&&t.push({code:"tasks_missing",message:"Add at least one task or Dataset artifact.",path:"tasks"}),e.graders.length===0&&t.push({code:"graders_missing",message:"Add at least one grader.",path:"graders"}),e.graderFixtures.length===0&&t.push({code:"grader_fixtures_missing",message:"Add grader fixtures before publishing.",path:"graderFixtures"});const n=new Set(e.sourceRefs.map(a=>a.id));for(const a of e.tasks)for(const i of a.sourceRefs)n.has(i)||t.push({code:"task_source_missing",message:`Task ${a.id} references missing source ${i}.`,path:`tasks.${a.id}.sourceRefs`});return t}function iae(e){const t=Ba.parse(e.draft),n=e.now??new Date().toISOString(),a=T5(t);if(a.length)throw new xS(a);const i=t.modelScope?.source;if(i&&e.tasksetId&&e.tasksetId!==i.tasksetId)throw new Error("Taskset draft publication differs from its prepared identity.");const r=i?.tasksetId||e.tasksetId?.trim()||t.publishedTasksetRef?.id||t.id.replace(/-draft$/,""),s=i?.tasksetRevision??(t.publishedTasksetRef?.id===r?t.publishedTasksetRef.revision+1:1),c=t.sourceRefs.length?t.sourceRefs:[E5(t,r,n)],m=c[0].id,u=t.tasks.map(O=>Fm.parse({...O,sourceRefs:O.sourceRefs.length?O.sourceRefs:[m],metadata:{exampleOrigin:"expert_authored",...O.metadata}})),h=t.capabilities.compatibleMethods.find(O=>O!=="none"&&O!=="retrieval")??null,g=M5(t),S=t.graders.filter(O=>O.rewardEligible&&O.weight>0&&O.kind!=="human"),k=h===null&&g==="verifiable_reward"&&S.length>0,C=h??(k?"grpo":null),A=Tc.parse({schemaVersion:"openpond.taskset.v1",id:r,revision:s,profileId:t.profileId,profileRelease:null,createImproveRunId:null,name:t.name,objective:t.objective,purpose:t.purpose,benchmark:t.benchmark,preferenceComparison:t.preferenceComparison,status:"needs_review",sourceRefs:c,datasetArtifact:t.datasetArtifact??null,policy:t.policy,environment:t.environment,capabilities:k?{...t.capabilities,compatibleMethods:["grpo"],rewardKinds:[...new Set(S.map(O=>O.kind==="model_judge"?"model_judge":"deterministic"))]}:t.capabilities,metrics:t.metrics,tasks:u,graders:t.graders,graderFixtures:t.graderFixtures,learningSignals:t.learningSignals,authoringProvenance:{schemaVersion:"openpond.taskAuthoringProvenance.v1",model:null,modelConfig:{},skillHash:Pt("openpond-taskset-draft-authoring-v1"),promptTemplateVersion:"taskset-draft-v1",buildIntent:g,buildSpecification:null,evidenceHashes:c.map(O=>O.sourceHash),tasksetSdkVersion:"draft-v1",sourceCommit:null,repairHistory:[],createdAt:n},readiness:null,contentHash:"00000000",createdAt:s===1?t.createdAt:n,updatedAt:n,metadata:{...t.metadata,...i?{modelTasksetAuthoring:i.lineage}:{},tasksetReviewPolicy:t.review,tasksetOutputContract:t.output,...e.sourcePackageHash?{sourcePackageHash:e.sourcePackageHash}:{},...C?{trainingMethod:C}:{},diagnosis:{schemaVersion:"openpond.capabilityDiagnosis.v1",summary:t.objective,stableBehavior:[t.objective],changingKnowledge:[],requiredContext:[],requiredTools:t.environment.toolNames,intervention:C==="dpo"?"preference":C==="grpo"||C==="ppo"?"grpo_rft":C==="sft"?"sft":"no_training",trainingEligible:C!==null,rationale:C?[`The author selected ${C.toUpperCase()} compatibility.`]:["The Taskset is currently configured for evaluation only."],confidence:1}}}),M=Tc.parse({...A,contentHash:m5(A)}),$=c5(M).issues.filter(O=>O.severity==="error");if($.length)throw new xS($.map(O=>({code:O.code,message:O.message,path:O.path})));return M}function E5(e,t,n){const a=Pt({draftId:e.id,draftRevision:e.revision,tasks:e.tasks});return{schemaVersion:"openpond.generatedDatasetSource.v1",kind:"generated",id:`source-${t}`,profileId:e.profileId,title:`${e.name} manual authoring`,sourceHash:a,occurredAt:n,licensingStatus:"approved",secretScanStatus:"passed",piiScanStatus:"passed",generatorId:"openpond-taskset-draft",generatorVersion:"1",seed:0,generatorHash:a,metadata:{draftId:e.id,draftRevision:e.revision}}}function M5(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 $s=o().regex(/^[a-f0-9]{64}$/),AC=l({providerId:b("claude-code"),configurationHash:$s,executableHash:$s,version:o().regex(/^2\.\d+\.\d+$/),capabilityHash:$s,maximumRequestCostUsd:d().finite().positive().max(1e4),requestTimeoutMs:d().int().min(1e3).max(3e5),maximumTurns:d().int().min(1).max(100),holdOpen:w()}).strict();l({id:o().min(1).max(200),receiptId:o().min(1).max(200),sessionId:mm(),operationId:o().min(1).max(200),action:v(["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 j5=l({provider:b("claude-code"),sessionId:mm(),requestId:o().min(1).max(200),modelId:o().min(1).max(500),runtime:AC,sourceHash:$s,outputHash:$s,traceHash:$s,runtimeEventRefs:p(o().min(1).max(200)).min(1).max(2e4),eventCount:d().int().positive().max(2e4),startedAt:nn(),completedAt:nn(),cleanupComplete:b(!0)}).strict().superRefine((e,t)=>{(e.runtimeEventRefs.length!==e.eventCount||new Set(e.runtimeEventRefs).size!==e.eventCount)&&t.addIssue({code:"custom",message:"Process event references must match the exact retained trace population."})}),Wm=l({id:o().trim().min(1).max(240),revision:d().int().positive(),contentHash:o().regex(/^[a-f0-9]{64}$/),targetId:o().trim().min(1).max(240).nullable()}).strict(),O5=p(l({role:v(["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."})}),TC=l({schemaVersion:b("openpond.experimentAttemptGrade.v1"),selectionHash:o().regex(/^[a-f0-9]{64}$/),grades:p(Zw).min(1).max(100),score:d().min(0).max(1).nullable(),passed:w(),rewardEligible:w(),gradingStatus:v(["scored","pending","unscorable","not_configured"]),failureClass:__.nullable(),contentHash:o().regex(/^[a-f0-9]{64}$/)}).strict().superRefine((e,t)=>{const{contentHash:n,...a}=e;Pt(a)!==n&&t.addIssue({code:"custom",message:"Experiment grading integrity failed."});const i=e.grades.flatMap(r=>r.components);(i.length!==e.grades.length||new Set(i.map(r=>r.graderId)).size!==i.length)&&t.addIssue({code:"custom",message:"Each selected criterion requires exactly one distinct grader result."});for(const r of e.grades){const{contentHash:s,...c}=r;Pt(c)!==s&&t.addIssue({code:"custom",message:"A retained criterion changed."});for(const m of r.components){const{contentHash:u,...h}=m;Pt(h)!==u&&t.addIssue({code:"custom",message:"A retained grader result changed."})}}}),tn=o().trim().min(1).max(200),yr=o().regex(/^[a-f0-9]{64}$/),EC=lt("kind",[l({kind:b("hosted_chat"),modelId:tn,localRuntime:ht([l({providerId:b("custom-openai-compatible"),configurationHash:yr,maximumRequestCostUsd:d().finite().positive().max(1e4),requestTimeoutMs:d().int().min(1e3).max(3e5)}).strict(),AC]).optional(),candidate:l({artifactId:tn,contentHash:yr,preparationId:tn,dispatchId:tn,baseProfileId:tn,workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/)}).strict().optional(),harness:td.optional(),messages:O5.optional(),maxOutputTokens:d().int().min(1).max(4096).default(1024),temperature:d().min(0).max(2).default(0),topP:d().gt(0).max(1).default(1)}).strict(),l({kind:b("fixture"),fixtureId:tn}).strict()]),$5=l({schemaVersion:b("openpond.modelStarterAttemptRequest.v1"),operationId:tn,teamId:tn,modelProjectId:tn.nullable(),project:Wm.optional(),taskset:ea,taskId:tn,environmentSeed:d().int().min(0).max(2147483647).default(0),policy:EC}).strict();l({modelProjectId:tn.nullable(),taskset:ea,afterTaskId:tn.optional(),limit:d().int().min(1).max(100).default(25)}).strict();l({modelProjectId:tn.nullable(),taskset:ea,available:w(),unavailableReason:o().max(1e3).nullable(),models:p(l({id:tn,name:o().max(500)}).strict()).max(200),tasks:p(l({id:tn,split:Ka,inputPreview:o().max(500),fixtures:p(l({id:tn,label:o().max(200)}).strict()).max(1e3)}).strict()).max(100),nextCursor:tn.nullable()}).strict();var Ib=l({schemaVersion:b("openpond.modelStarterAttemptSummary.v1"),id:tn,revision:d().int().positive(),request:$5,status:v(["queued","running","cancelling","completed","failed","cancelled"]),policySnapshot:l({modelId:tn,provider:tn,upstreamModelId:o().min(1).max(500),configurationHash:yr}).strict().nullable(),createdAt:nn(),startedAt:nn().nullable(),completedAt:nn().nullable(),cleanupComplete:w(),resultAvailable:w(),score:d().min(0).max(1).nullable(),gradingStatus:v(["not_started","pending","scored","unscorable","not_configured"]).default("not_started"),passed:w().nullable(),outputPreview:o().max(500).nullable(),error:l({code:tn,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."})});l({modelProjectId:tn,afterId:tn.optional(),limit:d().int().min(1).max(100).default(25)}).strict();l({items:p(Ib).max(100),nextCursor:tn.nullable()}).strict();l({schemaVersion:b("openpond.modelStarterAttemptResult.v1"),attempt:Ib,output:o().max(1048576).nullable(),messages:p(ae(o(),ie())).max(4002),composition:Ic.nullable(),grade:Zw.nullable().optional(),experimentGrade:TC.nullable().optional(),environment:l({status:v(["completed","budget_exhausted","cancelled","timed_out","policy_failure","environment_failure"]),collected:w(),definition:ea,initialStateHash:yr.nullable(),finalStateHash:yr.nullable(),attemptHash:yr}).strict(),native:eb.optional(),providerRequestIds:p(tn).max(1001),contentHash:yr}).strict().superRefine((e,t)=>{const n=e.attempt.request.policy.kind==="hosted_chat"?e.attempt.request.policy.harness:void 0;!!n!=!!e.native&&t.addIssue({code:"custom",path:["native"],message:"Standalone Harness results require their exact native evidence."}),e.native&&(!n||Pt(n)!==Pt(e.native.source)||e.native.modelConfigurationHash!==e.attempt.policySnapshot?.configurationHash||e.environment.initialStateHash!==null||e.environment.finalStateHash!==null||e.environment.status==="completed"&&(!e.environment.collected||e.output===null||e.native.partialOutputAvailable||e.native.outputHash!==Pt(e.output)))&&t.addIssue({code:"custom",path:["native"],message:"Native evidence differs from the admitted source, model or output."}),e.experimentGrade&&((e.grade||e.composition)&&t.addIssue({code:"custom",message:"Selected Experiment grading cannot claim another grade population."}),(!["completed","failed"].includes(e.attempt.status)||!e.attempt.resultAvailable||e.attempt.score!==e.experimentGrade.score||e.attempt.gradingStatus!==e.experimentGrade.gradingStatus||e.attempt.passed!==(e.experimentGrade.score===null?null:e.experimentGrade.passed))&&t.addIssue({code:"custom",message:"Experiment grading differs from its retained attempt summary."})),e.grade&&(e.composition&&t.addIssue({code:"custom",path:["grade"],message:"An ordinary grade cannot also claim a Reward composition."}),(!["completed","failed"].includes(e.attempt.status)||!e.attempt.resultAvailable||e.attempt.score!==e.grade.score||e.attempt.gradingStatus!==e.grade.gradingStatus||e.attempt.passed!==(e.grade.score===null?null:e.grade.passed))&&t.addIssue({code:"custom",path:["grade"],message:"Ordinary grade differs from its terminal attempt summary."}))});var ms=o().trim().min(1).max(240),nh=o().regex(/^[a-f0-9]{64}$/),MC=l({kind:b("hosted_harness"),modelId:ms,candidate:l({artifactId:ms,contentHash:nh,preparationId:ms,dispatchId:ms,baseProfileId:ms,workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/)}).strict().optional(),sourceCandidate:Ks.shape.sourceCandidate,reasoningEffort:v(["off","low","medium","high","xhigh","max"]).optional(),profileRepositoryId:ms,source:Ks,modelConfigurationHash:nh,packageHash:nh,externalDatasetBinding:Ko.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."})}),oi=o().trim().min(1).max(200),jC=o().regex(/^[a-f0-9]{64}$/),N5=lt("kind",[EC.options[0],l({kind:b("fixture")}).strict(),MC]),ml=l({schemaVersion:b("openpond.modelTasksetRunRequest.v1"),operationId:oi,teamId:oi,modelProjectId:oi.nullable(),name:o().trim().min(1).max(200).optional(),project:Wm.optional(),taskset:ea,policy:N5,population:p(O_).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=>sb([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."})}),OC=l({schemaVersion:b("openpond.modelTasksetRunSummary.v1"),id:oi,revision:d().int().positive(),teamId:oi,modelProjectId:oi.nullable(),name:o().trim().min(1).max(200).optional(),project:Wm.optional(),operationId:oi,taskset:ea,policyKind:v(["hosted_chat","fixture","hosted_harness"]),manifestHash:jC,status:v(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:d().int().min(1).max(1e4),counts:l({pending:d().int().nonnegative(),running:d().int().nonnegative(),completed:d().int().nonnegative(),failed:d().int().nonnegative(),cancelled:d().int().nonnegative()}).strict(),createdAt:nn(),startedAt:nn().nullable(),completedAt:nn().nullable(),cleanupComplete:w(),resultAvailable:w(),score:d().min(0).max(1).nullable(),metricName:o().min(1).max(240),error:l({code:oi,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."})}),$C=l({summary:OC,request:ml,manifest:Lm,policySnapshot:Ib.shape.policySnapshot}).strict();l({modelProjectId:oi.optional(),projectId:Wm.shape.id.optional(),afterId:oi.optional(),limit:d().int().min(1).max(100).default(25)}).strict();l({items:p(OC).max(100),nextCursor:oi.nullable()}).strict();l({schemaVersion:b("openpond.modelTasksetRunResult.v1"),run:$C,receipts:p(C4).min(1).max(1e4),metric:Wv.nullable(),contentHash:jC}).strict();var NC=o().min(1).max(200).refine(e=>!["__proto__","prototype","constructor"].includes(e),"Use an ordinary field name."),D5=p(NC).min(1).max(20),kS=v(["input","output","expectedOutput","evaluatorContext"]),H5=l({destination:kS,path:D5,source:kS,sourcePath:p(NC).max(20)}).strict(),wb=p(H5).max(100).superRefine((e,t)=>{for(const[n,a]of e.entries())e.slice(0,n).some(i=>i.destination===a.destination&&(IS(i.path,a.path)||IS(a.path,i.path)))&&t.addIssue({code:"custom",path:[n,"path"],message:"Mapped destination paths must not overlap."})});function IS(e,t){return e.length<=t.length&&e.every((n,a)=>n===t[a])}var Qn=o().trim().min(1).max(200),Pr=o().regex(/^[a-f0-9]{64}$/),rd=l({id:Qn,revision:d().int().positive(),contentHash:Pr}).strict(),Mi=l({id:Qn,version:o().min(1).max(200),contentHash:Pr,name:o().trim().min(1).max(500).optional(),feedbackKey:Am,release:rd.nullable(),mappings:wb.optional()}).strict(),_b=l({id:Qn,version:o().min(1).max(200),contentHash:Pr,mappings:wb}).strict(),Cb=l({operationId:Qn,id:Qn.optional(),expectedRevision:d().int().nonnegative(),request:ml,maximumCostUsd:d().finite().positive().max(1e4),graders:p(_b).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."})}),L5=l({schemaVersion:b("openpond.experimentDefinition.v1"),id:Qn,teamId:Qn,revision:d().int().positive(),request:ml,maximumCostUsd:d().finite().positive().max(1e4),graders:p(Mi).min(1).max(100),createdAt:nn(),updatedAt:nn()}).strict();L5.extend({contentHash:Pr});l({operationId:Qn,definition:rd}).strict();l({projectId:Qn.optional(),datasetHash:Pr.optional(),search:o().trim().max(200).optional(),status:v(["queued","running","cancelling","completed","failed","cancelled"]).optional(),afterId:Qn.optional(),limit:d().int().min(1).max(100).default(30)}).strict();l({definition:rd.nullable(),configurationHash:Pr.optional(),admissionRequestHash:Pr.optional(),sourceExperimentId:Qn.optional(),maximumCostUsd:d().finite().positive().max(1e4),graders:p(Mi).min(1).max(100)}).strict().superRefine((e,t)=>{e.definition===null&&(!e.configurationHash||!e.admissionRequestHash)&&t.addIssue({code:"custom",path:["configurationHash"],message:"A flat Experiment requires its sealed configuration hash."})});l({operationId:Qn,profileRepositoryId:Qn,definitionId:Qn,modelId:Qn,reasoningEffort:v(["off","low","medium","high","xhigh","max"]).optional(),maximumCostUsd:d().finite().positive().max(1e4),externalDatasetBinding:Ko.optional(),sourceCandidate:MC.shape.sourceCandidate}).strict();l({request:ml,manifest:Lm,maximumCostUsd:d().finite().positive().max(1e4),graders:p(Mi).min(1).max(100)}).strict();var wS=o().trim().min(1).max(200),sd=l({operationId:wS,request:ml,maximumCostUsd:d().finite().positive().max(1e4),graders:p(_b).min(1).max(100).optional(),sourceExperimentId:wS.optional()}).strict().superRefine((e,t)=>{e.request.name||t.addIssue({code:"custom",path:["request","name"],message:"Name this Experiment before starting it."}),e.operationId!==e.request.operationId&&t.addIssue({code:"custom",path:["request","operationId"],message:"Use one operation identity for this Experiment."}),Math.round(e.maximumCostUsd*1e6)<1&&t.addIssue({code:"custom",path:["maximumCostUsd"],message:"The spending cap must be at least $0.000001."}),e.graders&&new Set(e.graders.map(n=>n.id)).size!==e.graders.length&&t.addIssue({code:"custom",path:["graders"],message:"Select each grader once."})}),Bt=o().trim().min(1).max(200),Ai=o().regex(/^[a-f0-9]{64}$/),Wu=l({id:Bt,contentHash:Ai}).strict(),oae=l({available:w(),reason:o().max(1e3).nullable(),origin:Mm.nullable()}).strict(),DC=l({schemaVersion:b("openpond.postTrainingAttachment.v1"),binding:l({kind:v(["preparation","policy"]),id:Bt,revision:d().int().positive(),contentHash:Ai}).strict(),projectId:Bt.nullable(),automatic:w(),maximumSpendUsd:d().finite().positive().max(1e4),experiments:p(l({id:Bt,configuration:sd}).strict()).min(1).max(20),acceptancePlan:h_.nullable()}).strict().superRefine((e,t)=>{if(new Set(e.experiments.map(n=>n.id)).size!==e.experiments.length&&t.addIssue({code:"custom",message:"Attach each evaluation once."}),e.experiments.reduce((n,a)=>n+a.configuration.maximumCostUsd,0)>e.maximumSpendUsd+1e-9&&t.addIssue({code:"custom",message:"Attached evaluation budgets exceed the total approved budget."}),e.experiments.some(n=>(n.configuration.request.project?.id??null)!==e.projectId)&&t.addIssue({code:"custom",message:"Attached experiments must use the training Project."}),e.acceptancePlan){const n=new Set(e.acceptancePlan.checks.map(i=>i.id));e.acceptancePlan.checks.some(i=>!e.experiments.some(r=>r.id===i.id))&&t.addIssue({code:"custom",message:"Select the frozen Experiment for each acceptance check."}),e.acceptancePlan.maximumSpendUsd+e.experiments.filter(i=>!n.has(i.id)).reduce((i,r)=>i+r.configuration.maximumCostUsd,0)>e.maximumSpendUsd+1e-9&&t.addIssue({code:"custom",message:"Paired acceptance and diagnostic ceilings exceed the approved evaluation budget."})}});function rae(e){const{modelId:t,candidate:n,...a}=e.request.policy.kind==="fixture"?{modelId:null,candidate:null,...e.request.policy}:e.request.policy;return"modelConfigurationHash"in a&&delete a.modelConfigurationHash,{dataset:{id:e.request.taskset.id,contentHash:e.request.taskset.contentHash},populationHash:Pt(e.request.population.map(i=>({caseId:i.taskId,seed:i.seed,fixtureId:i.fixtureId}))),executionHash:Pt({settings:a,graders:e.graders??null})}}var q5=l({baseline:Wu,checks:p(l({id:Bt,sourceRunId:Bt,sourceManifestHash:Ai,targetConfigurationHash:Ai,executionHash:Ai,populationHash:Ai,evaluator:Wu,feedbackKey:Bt,output:v(["boolean","score"]),unit:o().min(1).max(80)}).strict()).min(1).max(100)}).strict(),U5=v(["waiting_for_training","ready","preparing","queued","running","cleaning","completed","failed","blocked","cancelled","budget_exhausted"]),z5=l({schemaVersion:b("openpond.postTrainingSummary.v1"),id:Bt,teamId:Bt,jobId:Bt,revision:d().int().positive(),planHash:Ai,automatic:w(),candidate:Wu.nullable(),state:U5,total:d().int().positive(),completed:d().int().nonnegative(),failed:d().int().nonnegative(),requiredOutcome:v(["none","pending","passed","failed","blocked"]),reason:o().max(500).nullable(),groupId:Bt.nullable(),experimentIds:p(Bt).max(20),updatedAt:nn()}).strict().superRefine((e,t)=>{e.completed+e.failed>e.total&&t.addIssue({code:"custom",message:"Evaluation totals are inconsistent."}),["preparing","queued","running","cleaning","completed"].includes(e.state)&&!e.candidate&&t.addIssue({code:"custom",message:"Evaluation execution requires the exact trained candidate."})}),sae=l({operationId:Bt,expectedRevision:d().int().positive(),planHash:Ai}).strict();l({operationId:Bt,attachment:DC}).strict();l({id:Bt,teamId:Bt,ownerUserId:Bt,attachment:DC,qualification:q5.nullable(),contentHash:Ai,createdAt:nn()}).strict();function lae(e){return!!(e&&["preparing","queued","running","cleaning"].includes(e.state))}var cae=l({teamId:Bt,actorId:Bt,projectId:Bt.nullable(),configuration:Nm,batches:p(ab).max(1e4),sources:p(jm).max(1e4),definitions:p(nd).max(1e4),experiments:p(l({id:Bt,name:o().max(500),configuration:sd,graders:p(l({feedbackKey:Bt,name:o().max(500),ref:Wu}).strict()).max(100)}).strict()).max(1e4)}).strict();v(["prepare","start","cancel","publish","attach"]);var dae=l({teamId:Bt,actorId:Bt,configuration:Nm,policy:i_,inspection:vz,iterations:p(l({iteration:o_,evals:z5.nullable()}).strict()).max(100),nextCursor:Bt.nullable()}).strict(),uae=l({id:Bt,expectedRevision:d().int().positive(),policyHash:Ai,operationId:Bt,action:v(["pause","resume","reserve","cancel-iteration","retry-iteration"]),iterationId:Bt.optional(),iterationRevision:d().int().positive().optional()}).strict(),Ns=o().trim().min(1).max(240),B5=Tt.extend({revision:d().int().positive()}).strict(),F5=B5.extend({teamId:Ns,jobId:Ns,plan:Tt,baseline:Tt,candidate:Tt,state:$z.shape.state,updatedAt:o().datetime()}).strict();l({schemaVersion:b("openpond.trainingAcceptanceGroupPage.v1"),teamId:Ns,jobId:Ns,groups:p(F5).max(100),nextCursor:Ns.nullable()}).strict();l({cursor:Ns.optional(),limit:d().int().min(1).max(100).default(25)}).strict();var Ha=o().trim().min(1).max(191),Ec=o().regex(/^[a-f0-9]{64}$/),V5=l({schemaVersion:b("openpond.trainingPreparationRequest.v1"),teamId:Ha,operationId:Ha,projectId:Ha.nullable(),configuration:l({id:Ha,expectedRevision:d().int().positive(),expectedEtag:Ec}).strict(),origin:Mm.optional(),batch:ea,name:o().trim().min(1).max(191),maximumSpendUsd:d().finite().positive().max(1e6)}).strict(),K5=l({schemaVersion:b("openpond.trainingPreparationPlan.v1"),id:Ha,creatorUserId:Ha,request:V5,requestHash:Ec,source:PI(()=>LC),submissionHash:Ec,createdAt:o().datetime({offset:!0})}).strict(),W5=K5.extend({contentHash:Ec}).strict(),G5=l({schemaVersion:b("openpond.trainingPreparationReceipt.v1"),plan:W5,revision:d().int().positive(),state:v(["prepared","submitted","cancelled"]),jobId:Ha.nullable()}).strict().superRefine((e,t)=>{e.state==="submitted"!=!!e.jobId&&t.addIssue({code:"custom",path:["jobId"],message:"Only submitted preparations identify a job."})});l({teamId:Ha,planHash:Ec,expectedRevision:d().int().positive()}).strict();l({projectId:Ha.optional(),state:v(["prepared","submitted","cancelled"]).optional(),afterId:Ha.optional(),limit:d().int().min(1).max(100).default(25)}).strict();l({schemaVersion:b("openpond.trainingPreparationPage.v1"),teamId:Ha,items:p(G5).max(100),nextCursor:Ha.nullable()}).strict();l({schemaVersion:b("openpond.trainingHarnessSourcePublication.v1"),harnessRelease:De,sourcePackageHash:o().regex(/^[a-f0-9]{64}$/),sizeBytes:d().int().positive().max(Uz)}).strict();p(l({id:o().trim().min(1)}).catchall(ie())).min(1).max(1e3);l({binding:Em,rewards:p(Tm).min(1).max(100)}).strict();var J5=l({id:o().trim().min(1),clusterKey:o().trim().min(1),split:v(["train","validation","frozen_eval"])}).passthrough();l({schemaVersion:b("openpond.trainingEvaluationSource.v1"),taskset:ea,tasks:p(J5).min(1).max(1e4),assets:p(l({path:o().trim().min(1).max(2e3),sha256:o().regex(/^[a-f0-9]{64}$/),sizeBytes:d().int().nonnegative(),encoding:b("base64"),content:o().max(32*1024*1024)}).strict()).max(1e4)}).strict().superRefine((e,t)=>{const n=new Set;e.tasks.forEach((a,i)=>{a.split==="train"&&t.addIssue({code:"custom",path:["tasks",i,"split"],message:"Evaluation sources require held-out tasks."}),n.has(a.id)&&t.addIssue({code:"custom",path:["tasks",i,"id"],message:"Evaluation task identities must be unique."}),n.add(a.id)})});var qn=o().trim().min(1).max(500),ka=o().regex(/^[a-f0-9]{64}$/),li=o().datetime({offset:!0});l({schemaVersion:b("openpond.trainingInputArtifactUpload.v2"),kind:v(["portable_training_bundle","reward_model_dataset"]),idempotencyKey:o().trim().min(1).max(500),sourceManifest:Tt,payload:ie(),contentHash:ka}).strict();l({schemaVersion:b("openpond.trainingInputArtifact.v2"),kind:v(["portable_training_bundle","reward_model_dataset"]),sourceManifest:Tt,artifactRef:o().trim().min(1).max(2e3),contentHash:ka,sizeBytes:d().int().positive(),createdAt:li}).strict();var HC=v(["reward_model_train","policy_optimize"]),Z5=v(["queued","admitting","provisioning","running","stopping","cancelling","succeeded","failed","cancelled"]),Y5=l({id:qn,version:o().trim().min(1).max(200).nullable().default(null),required:w().default(!0)}).strict(),LC=l({origin:Mm.optional(),modelProject:l({id:qn,portableProjectId:qn,revision:d().int().positive(),contentHash:ka}).strict(),harnessRunManifest:Tt,harnessRelease:Tt,taskset:ea,tasksetRelease:Tt,evaluation:l({taskset:ea,dataset:Tt}).strict().nullable().optional(),dataset:Tt,evidenceSets:p(Tt).max(1e4)}).strict(),Q5=l({kind:b("reward_model_train"),baseModel:Nr,preferenceDatasetRelease:Tt,processorRelease:Tt,recipe:l({schemaVersion:b("openpond.rewardModelRecipe.v1"),method:b("reward_model"),parameterization:b("lora_with_scalar_head")}).catchall(ie())}).strict(),X5=l({kind:b("deterministic"),grader:Tt,composer:Tt.nullable().default(null)}).strict(),e3=l({kind:b("learned_reward"),rewardModelVersion:Tt,qualificationReport:Tt.nullable().default(null),evaluationReferences:p(Tt).max(1e3).default([]),scorerArtifact:l({artifactRef:o().trim().min(1).max(2e3),contentHash:ka,executionReceipt:Tt}).strict(),processorRelease:Tt,rewardComposerRelease:Tt}).strict(),t3=l({kind:b("policy_optimize"),baseModel:Nr,recipe:y_,rewardSource:lt("kind",[X5,e3]),resumeFrom:Tt.nullable().default(null)}).strict(),n3=lt("kind",[Q5,t3]),a3=l({approvalHash:ka,approvedAt:li,exportApproved:w(),maximumSpendUsd:d().nonnegative(),retentionDays:d().int().nonnegative().nullable(),region:o().trim().min(1).max(200).nullable().default(null)}).strict();l({schemaVersion:b("openpond.trainingJobSubmission.v2"),idempotencyKey:o().trim().min(1).max(500),name:o().trim().min(1).max(200),source:LC,job:n3,requestedCapabilities:p(Y5).max(1e3),placementObjective:v(["fast","balanced","economical"]),budget:l({maximumSpendUsd:d().nonnegative(),maximumWallSeconds:d().int().positive()}).strict(),approval:a3,contentHash:ka}).strict().superRefine((e,t)=>{e.approval.maximumSpendUsd!==e.budget.maximumSpendUsd&&t.addIssue({code:"custom",path:["approval","maximumSpendUsd"],message:"Approved spend must equal the immutable Job budget."})});var i3=l({schemaVersion:b("openpond.trainingJob.v2"),id:qn,teamId:qn,kind:HC,modelProjectId:qn,portableProjectId:qn,sourceProjectRevision:d().int().positive(),submissionHash:ka,state:Z5,phase:o().trim().min(1).max(200),version:d().int().nonnegative(),progress:d().min(0).max(1),rolloutProgress:l({groupsCompleted:d().int().nonnegative(),groupsTarget:d().int().nonnegative(),optimizerUpdatesApplied:d().int().nonnegative(),optimizerUpdatesSkipped:d().int().nonnegative()}).strict(),accruedSpendUsd:d().nonnegative(),terminalReason:o().trim().min(1).max(5e3).nullable(),createdAt:li,updatedAt:li,completedAt:li.nullable()}).strict();l({schemaVersion:b("openpond.trainingJobPage.v2"),jobs:p(i3).max(1e3),nextCursor:o().trim().min(1).max(2e3).nullable()}).strict();var mae=l({schemaVersion:b("openpond.trainingJobEvent.v2"),id:qn,jobId:qn,sequence:d().int().nonnegative(),type:qn,phase:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3).nullable(),data:ae(o(),ie()).default({}),createdAt:li}).strict();l({schemaVersion:b("openpond.trainingJobLog.v2"),jobId:qn,sequence:d().int().nonnegative(),level:v(["debug","info","warning","error"]),message:o().max(2e4),createdAt:li}).strict();l({expectedVersion:d().int().nonnegative()}).strict();var o3=l({schemaVersion:b("openpond.trainingJobOutput.v2"),id:qn,jobId:qn,kind:v(["checkpoint","adapter","scorer","metrics","evaluation","trace","receipt"]),artifactRef:o().trim().min(1).max(2e3),contentHash:ka,sizeBytes:d().int().nonnegative(),metadata:ae(o(),ie()).default({}),createdAt:li}).strict(),r3=l({schemaVersion:b("openpond.trainingExecutionReceipt.v2"),id:qn,teamId:qn,jobId:qn,submissionHash:ka,manifestHash:ka,recipeHash:ka,capabilityHash:ka,runtimeRelease:Tt,inputs:p(Tt).max(1e4),outputs:p(Tt).max(1e4),spendUsd:d().nonnegative(),durationSeconds:d().nonnegative(),cleanupComplete:w(),issuer:qn,issuedAt:li,signature:o().trim().min(1).max(1e4).nullable()}).strict(),pae=l({schemaVersion:b("openpond.trainingJobOutputs.v2"),outputs:p(o3).max(1e4),receipt:r3.nullable()}).strict();l({schemaVersion:b("openpond.trainingApiError.v2"),code:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3),retryable:w().default(!1),requestId:o().trim().min(1).max(500).nullable().default(null),details:ae(o(),ie()).default({})}).strict();l({schemaVersion:b("openpond.trainingCapabilities.v2"),capabilityHash:ka,jobKinds:p(HC),methods:p(o().trim().min(1).max(200)),placements:p(v(["local","remote","colocated","provider_native"])),controls:l({cancel:w(),stopAfterGroup:w(),resumeFromCheckpoint:w()}).strict(),limits:l({maximumSpendUsd:d().nonnegative(),maximumWallSeconds:d().int().positive(),maximumArtifactBytes:d().int().positive()}).strict(),checkedAt:li,expiresAt:li}).strict();var ji=Ba.shape.id,ci=d().int().positive(),Ar=o().regex(/^[a-f0-9]{64}$/),Dr={teamId:ji,modelId:ji};l({schemaVersion:b("openpond.tasksetDraftCreate.v1"),operationId:ji,modelId:ji,expectedModelRevision:ci,name:Ba.shape.name}).strict();l({schemaVersion:b("openpond.tasksetDraftSourceDescriptor.v1"),...Dr,expectedModelRevision:ci,sourcePackageHash:Ar}).strict();l({schemaVersion:b("openpond.tasksetDraftReadback.v1"),...Dr,draft:Ba,workspaceHash:Ar,projectEtag:Ar}).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 s3=l({id:ji,revision:ci,name:Ba.shape.name,status:RC,updatedAt:Ba.shape.updatedAt,sourceTasksetRef:yt.nullable()}).strict();l({schemaVersion:b("openpond.tasksetDraftList.v1"),...Dr,drafts:p(s3).max(100),nextCursor:o().min(1).max(2e3).nullable()}).strict();l({expectedDraftRevision:ci,draft:Ba}).strict();l({expectedDraftRevision:ci,expectedModelRevision:ci}).strict();var l3=l({expectedDraftRevision:ci,expectedWorkspaceHash:Ar}).strict();l({schemaVersion:b("openpond.tasksetDraftValidation.v1"),...Dr,draftId:ji,draftRevision:ci,workspaceHash:Ar,valid:w(),issues:p(l({code:o().min(1),severity:v(["warning","error"]),message:o(),path:o().nullable()}).strict()),packageHash:Ar.nullable(),tasksetRef:yt.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.");l3.extend({operationId:ji,expectedPackageHash:Ar,expectedTasksetRef:yt}).strict();l({schemaVersion:b("openpond.tasksetDraftFileList.v1"),...Dr,draftId:ji,draftRevision:ci,files:p(g_).max(10020)}).strict();l({schemaVersion:b("openpond.tasksetDraftFileReadback.v1"),...Dr,draftId:ji,draftRevision:ci,file:Lz}).strict();l({schemaVersion:b("openpond.tasksetDraftDeletion.v1"),...Dr,draftId:ji,revision:ci,deleted:b(!0)}).strict();Ba.shape.id;d().int().positive();var no=o().trim().min(1).max(500),c3=l({projectId:no.optional(),tasksetId:no.optional(),draftId:no.optional(),taskId:no.optional(),query:o().trim().max(1e3).default(""),split:v(["train","validation","test","frozen_eval"]).optional(),after:o().min(1).max(2e3).optional(),limit:d().int().min(1).max(100).default(30)}).strict(),d3=l({id:no,method:v(["code","judge","human"]),required:w()}),qC=l({tasksetId:no,tasksetName:o(),tasksetRevision:d().int().positive(),tasksetHash:o(),taskId:no,ordinal:d().int().nonnegative(),title:o(),description:o(),split:o(),scoring:p(d3),configuration:v(["configured","needs_reward","needs_checks"]),draftId:no.nullable().default(null),modelId:no.nullable().default(null)}),u3=l({items:p(qC).max(100),nextCursor:o().nullable()});function fae(e,t){if(Rz({format:e.format,files:t}).contentHash!==e.contentHash)throw new Error("The source files differ from the import preview.");const n=`private/intake/${e.contentHash}`,a=t.map((r,s)=>({file:r,path:`${n}/${String(s).padStart(4,"0")}.txt`})),i={schemaVersion:"openpond.taskIntakeSources.v1",format:e.format,previewHash:e.contentHash,files:a.map(({file:r,path:s})=>({originalPath:r.path,retainedPath:s}))};return[...a.map(({file:r,path:s})=>bS(s,new TextEncoder().encode(r.text))),bS(`${n}/manifest.json`,new TextEncoder().encode(JSON.stringify(i)))]}function hae(e,t,n){const a=c_.parse(t);if(!n.length||new Set(n).size!==n.length)throw new Error("Select unique task records to import.");const i=[...e.tasks];for(const s of n){const c=a.records.find(h=>h.id===s);if(!c||c.kind!=="task"||c.needsContext)throw new Error("Recorded attempts and incomplete histories must be imported into Labeling for review.");const m=CC.parse({schemaVersion:"openpond.taskData.v1",id:c.id,clusterKey:c.familyKey,split:c.split,input:c.input,expectedOutput:c.expected,privilegedContextRef:null,metadata:{intake:{format:a.format,uploadHash:a.contentHash,sourceId:c.sourceId,sourceHash:c.sourceHash,metadata:c.metadata}}}),u=i.find(h=>h.id===m.id);if(u&&Pt(u)!==Pt(m))throw new Error(`Task ${m.id} already exists with different content. Import will not replace saved edits.`);u||i.push(m)}const r=new Map;for(const s of i)for(const c of[`family:${s.clusterKey}`,`input:${Pt(s.input)}`]){if(r.has(c)&&r.get(c)!==s.split)throw new Error("The imported task family or request already occurs in another split.");r.set(c,s.split)}return Ba.parse({...e,tasks:i})}const ua=o().trim().min(1).max(240),zo=o().trim().min(1),UC=ae(o(),ie()).default({}),zC=v(["nominated","needs_review","approved_for_creation","creating","needs_task_review","baselining","ready_for_export","rejected","dismissed","retired","blocked"]),BC=v(["no_training","prompting","retrieval","sft","preference","grpo_rft","sdft_opsd","sdpo","agentic_rl"]),m3=l({id:ua,kind:v(["repeated_success","accepted_correction","agent_action_recurrence","outcome_linked_change","frontier_cost","expert_label","runtime_feedback"]),sourceRefIds:p(ua).min(1).max(1e4),occurredAt:zo,signature:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(5e3),confidence:d().min(0).max(1),consented:w(),metadata:UC}),p3=l({frequency:d().min(0).max(1),businessValue:d().min(0).max(1),frontierCost:d().min(0).max(1),signalQuality:d().min(0).max(1),verifiability:d().min(0).max(1),repeatability:d().min(0).max(1),privacyRisk:d().min(0).max(1),overall:d().min(0).max(1)}),f3=l({tactic:BC,eligible:w(),reasons:p(o().trim().min(1).max(5e3)).min(1).max(100),blockers:p(o().trim().min(1).max(5e3)).max(100).default([]),requiredSignals:p(o().trim().min(1).max(500)).max(100).default([]),generatedBy:v(["decision_table","baseline_reassessment"])}),FC=l({schemaVersion:b("openpond.taskCandidate.v1"),id:ua,profileId:ua,status:zC,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:p(m3).min(1).max(1e5),scorecard:p3,recommendation:f3,mergedIntoId:ua.nullable(),createdAt:zo,updatedAt:zo,metadata:UC}),Gm=l({schemaVersion:b("openpond.taskMinerConfig.v1"),enabled:w().default(!1),localOnly:w().default(!0),observationWindowDays:d().int().min(1).max(365).default(30),minimumRecurrence:d().int().min(2).max(100).default(3),clustering:b("hybrid_deterministic_first").default("hybrid_deterministic_first"),consentRequired:w().default(!0)});l({items:p(FC),generatedAt:zo,config:Gm});l({status:zC.optional(),mergeIntoId:ua.nullable().optional()});l({profileId:ua,sourceIds:p(ua).max(1e5).default([]),sessionIds:p(ua).max(1e5).default([]),config:Gm.optional()});const h3=l({schemaVersion:b("openpond.taskMinerRun.v1"),id:ua,profileId:ua,status:v(["queued","running","cancelling","cancelled","succeeded","failed"]),config:Gm,sourceIds:p(ua).max(1e5),sessionIds:p(ua).max(1e5).default([]),progress:l({stage:v(["queued","ingesting","preparing","clustering","persisting","complete"]),processedSources:d().int().nonnegative(),totalSources:d().int().nonnegative(),candidatesFound:d().int().nonnegative(),skippedSources:d().int().nonnegative().default(0)}),candidateIds:p(ua).max(1e5),cancelRequested:w(),error:o().trim().min(1).max(2e4).nullable(),createdAt:zo,startedAt:zo.nullable(),completedAt:zo.nullable(),updatedAt:zo});var g3=l({id:Ke,purpose:o().trim().min(1).max(500),audience:v(["orchestrator","environment","privileged_scorer","trainer","infrastructure"]),required:w(),ttlSeconds:d().int().positive().max(86400),scopes:p(o().trim().min(1).max(500)).max(100).default([])}).strict(),v3=l({declarationId:Ke,leaseRef:o().trim().min(8).max(1e3),audience:g3.shape.audience,expiresAt:Rt}).strict(),Rb=l({adapterId:Ke,placement:v(["local","remote","colocated","provider_native"]),capabilityReceipt:Qe,runtimeVersion:o().trim().min(1).max(200),dataPlane:l({provider:Ke,dataPlaneId:Ke,cellId:Ke,runnerPoolId:Ke,runtimeImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/),capabilityReceipt:Qe}).strict().nullable()}).strict(),Pb=l({adapterId:Ke,kind:v(["local","ssh","managed","custom"]),deviceOrPool:o().trim().min(1).max(1e3),capabilityReceipt:Qe,provider:Ke.nullable()}).strict(),Ab=l({adapterId:Ke,workerVersion:o().trim().min(1).max(200),workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/).nullable(),upstreamRevision:o().trim().min(1).max(500),capabilityReceipt:Qe}).strict(),b3=l({schemaVersion:b("openpond.harnessRunManifest.v1"),id:Ke,harnessRelease:De,datasetRelease:De,evidenceSets:p(De).max(1e4),model:l({source:o().trim().min(1).max(200),revision:o().trim().min(1).max(500),artifactHash:Qe.nullable(),tokenizerRevision:o().trim().min(1).max(500),chatTemplateHash:Qe}).strict(),recipe:l({method:o().trim().min(1).max(100),version:o().trim().min(1).max(200),configHash:Qe}).strict(),runtimeTarget:Rb,computeTarget:Pb,engine:Ab,resolvedBundleHash:Qe,secretLeaseRefs:p(v3).max(1e3),approval:l({approvalHash:Qe,approvedAt:Rt,maximumSpendUsd:d().nonnegative().nullable()}).strict(),createdAt:Rt}).strict(),y3=b3.extend({contentHash:Qe}).strict(),S3=l({schemaVersion:b("openpond.resolvedTrainingBundle.v1"),projection:b("trainer"),harnessRelease:De,datasetRelease:De,evidenceSetRelease:De.nullable(),files:p(l({path:o().trim().min(1).max(2e3),sha256:Qe,sizeBytes:d().int().nonnegative()}).strict()).max(1e5)}).strict();S3.extend({contentHash:Qe}).strict();var VC=l({name:b("adamw").default("adamw"),weightDecay:d().nonnegative().max(1).default(0),beta1:d().positive().lt(1).default(.9),beta2:d().positive().lt(1).default(.999),epsilon:d().positive().max(.01).default(1e-8)}).strict().default({name:"adamw",weightDecay:0,beta1:.9,beta2:.999,epsilon:1e-8});const bt=o().trim().min(1).max(240),pa=o().trim().min(1),Zs=o().trim().min(8).max(256),Tb=ae(o(),ie()).default({}),Ti=bt.nullable(),x3=v(["slash_train","session_menu","bulk_selection","training_page","task_candidate"]),k3=v(["defaults","customize"]),I3=v(["automated","manual"]);l({schemaVersion:b("openpond.trainingSourceEstimate.v1"),sessionId:bt,messageCount:d().int().nonnegative(),estimatedTokens:d().int().nonnegative(),textBytes:d().int().nonnegative()});l({query:o().max(500).default(""),offset:d().int().nonnegative().default(0),limit:d().int().min(1).max(100).default(20),candidates:p(l({sessionId:bt,title:o().trim().min(1).max(500),updatedAt:pa})).max(500).default([])});const w3=l({sessionId:bt,title:o().trim().min(1).max(500),updatedAt:pa,snippet:o().max(2e3).nullable()});l({schemaVersion:b("openpond.trainingChatSearchResult.v1"),query:o(),offset:d().int().nonnegative(),limit:d().int().positive(),total:d().int().nonnegative(),hasMore:w(),indexedChats:d().int().nonnegative(),totalChats:d().int().nonnegative(),indexing:w(),entries:p(w3)});const Eb=v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]),_3=l({graderId:bt.nullable(),path:o().trim().min(1).max(1e3),language:v(["javascript","typescript","python","json","text"]),content:o().max(2e6),sha256:Zs,declaredSha256:Zs.nullable(),integrity:v(["verified","unverified","mismatch"])}),C3=l({protocolVersion:o().trim().min(1).max(200),module:o().trim().min(1).max(1e3),moduleSha256:Zs,command:p(o().max(2e3)).max(100),cwd:o().trim().min(1).max(4e3),maxTurns:d().int().positive().max(100)});l({schemaVersion:b("openpond.tasksetGraderDetails.v1"),taskset:Zt,sourceTasksetId:bt,graders:p(Km).max(1e3),runtime:C3.nullable(),sources:p(_3).max(1e3),unavailableReason:o().max(2e3).nullable()});const R3=l({id:bt,taskIndex:d().int().nonnegative(),label:kb,output:ae(o(),ie()),infrastructureError:o().trim().min(1).max(1e4).nullable(),expectedPassed:w(),expectedRewardEligible:w(),metadata:Tb}),P3=l({schemaVersion:b("openpond.taskAttempt.v1"),id:bt,tasksetId:bt,taskId:bt,split:Js,attempt:d().int().nonnegative(),seed:d().int(),modelRef:bn.nullable(),startedAt:pa,completedAt:pa,output:ae(o(),ie()),runtimeEventRefs:p(bt).max(1e4).default([]),artifactRefs:p(bt).max(1e4).default([]),privilegedOutcomeRef:Ti,infrastructureError:o().trim().min(1).max(1e4).nullable(),costUsd:d().nonnegative().nullable(),latencyMs:d().int().nonnegative(),userInterventions:d().int().nonnegative().default(0),metadata:Tb}),A3=l({schemaVersion:b("openpond.taskAttemptArtifact.v1"),id:bt,tasksetId:bt,taskId:bt,attemptId:bt,kind:v(["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:Zs,sizeBytes:d().int().nonnegative(),createdAt:pa,metadata:Tb}),T3=l({graderId:bt,graderVersion:o().trim().min(1).max(100),score:d().min(0).max(1).nullable(),passed:w(),hardGate:w(),rewardEligible:w(),feedback:o().trim().max(2e4).nullable(),evidenceRefs:p(bt).max(1e4).default([]),judge:bn.nullable().optional().default(null),calibrationStatus:v(["not_applicable","pending","passed","failed"])}),E3=l({schemaVersion:b("openpond.gradeResult.v1"),id:bt,attemptId:bt,graderSetHash:Zs,score:d().min(0).max(1).nullable(),passed:w(),components:p(T3).min(1).max(1e3),failureClass:Eb.nullable(),feedback:p(o().trim().min(1).max(2e4)).max(1e3).default([]),rewardEligible:w(),rewardComposition:Ic.optional(),createdAt:pa});v(["stable_hash_top_n","rft_easy_curriculum_v1"]);const M3=l({schemaVersion:b("openpond.graderAuditReport.v1"),id:bt,tasksetId:bt,tasksetHash:Zs,fixtureRefs:p(bt).min(1).max(1e5),gradeRefs:p(bt).min(1).max(1e5),passed:w(),hackingChecksPassed:w(),leakageChecksPassed:w(),infrastructureSafetyPassed:w(),failures:p(l({fixtureId:bt,label:kb,gradeId:bt,reason:o().trim().min(1).max(5e3)})).max(1e5),createdAt:pa}),j3=l({schemaVersion:b("openpond.capabilityDiagnosis.v1"),summary:o().trim().min(1).max(1e4),stableBehavior:p(o().trim().min(1).max(5e3)).max(100).default([]),changingKnowledge:p(o().trim().min(1).max(5e3)).max(100).default([]),requiredContext:p(o().trim().min(1).max(5e3)).max(100).default([]),requiredTools:p(bt).max(100).default([]),intervention:BC,trainingEligible:w(),rationale:p(o().trim().min(1).max(5e3)).min(1).max(100),confidence:d().min(0).max(1)}),O3=l({id:bt,sourceId:bt,sourceTurnId:Ti,split:Js,origin:v(["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)}),$3=l({schemaVersion:b("openpond.taskDesignProposal.v1"),id:bt,name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),diagnosis:j3.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:xb.shape.taskKind,sourceIds:p(bt).min(1).max(1e5),assumptions:p(o().trim().min(1).max(5e3)).max(1e3),successCriteria:p(o().trim().min(1).max(5e3)).min(1).max(1e3),proposedGraders:p(Km).max(1e3).default([]),graderFixtures:p(R3).max(1e5).default([]),generatedFiles:p(r5).max(1e3).default([]),proposedExamples:p(O3).max(1e5).default([]),proposedMethod:kC.shape.recommendedMethod,trainingPath:SC.nullable().default(null),policy:Sb,warnings:p(o().trim().min(1).max(5e3)).default([]),createdAt:pa}),N3=5;function gae(e,t="New model"){const n=e?.trim().split(/\s+/).filter(Boolean)??[];return n.length===0?t:n.slice(0,N3).join(" ")}const ld=l({schemaVersion:b("openpond.baseModelPreference.v1"),modelId:bt,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:Ti,source:v(["managed","local","builtin"])}),D3=l({schemaVersion:b("openpond.taskCreationRequest.v1"),id:bt,profileId:bt,surface:x3,mode:k3,entryMode:I3.default("manual"),resourceIntent:v(["workproduct","dataset"]).default("workproduct"),buildIntent:bC.default("demonstrations"),buildSpecification:yC.nullable().default(null),objective:o().trim().min(1).max(2e4).nullable(),methodHint:v(["sft","dpo","grpo","ppo"]).nullable().default(null),preferredBaseModelId:bt.nullable().default(null),preferredBaseModel:ld.nullable().default(null),sourceIds:p(bt).max(1e5),candidateId:Ti,analysisModel:bn.nullable(),analysisReasoningEffort:ym.nullable().default(null),createImproveRunId:Ti.default(null),targetIntent:l({kind:v(["agent","skill","extension","model","configuration"]).nullable(),id:Ti,displayName:o().trim().min(1).max(500).nullable(),operation:v(["create","improve"])}).default({kind:"model",id:null,displayName:null,operation:"create"}),disclosure:l({status:v(["not_required","pending","approved","declined"]),content:b("raw_excerpts"),sourceIds:p(bt).max(1e5),providerModel:bn.nullable(),approvalId:Ti,approvedAt:pa.nullable()}).default({status:"not_required",content:"raw_excerpts",sourceIds:[],providerModel:null,approvalId:null,approvedAt:null}),createdAt:pa}),KC=l({schemaVersion:b("openpond.taskCreationSnapshot.v1"),id:bt,request:D3,state:v(["planning","awaiting_disclosure_approval","awaiting_questions","recommendation_ready","awaiting_materialization_approval","materializing","validating","ready","blocked","failed","cancelled"]),proposal:$3.nullable(),materializedTasksetId:Ti,disclosureApprovalId:Ti,materializationApprovalId:Ti,blockingQuestions:p(l({id:bt,kind:v(["objective","consent","success_signal","privacy_licensing","interpretation"]),prompt:o().trim().min(1).max(5e3),answer:o().trim().min(1).max(2e4).nullable()})).default([]),transcript:p(l({id:bt,role:v(["user","assistant","system","tool"]),text:o().max(1e5),createdAt:pa})).max(1e4).default([]),repairHistory:p(IC).max(1e3).default([]),blockedReason:o().trim().min(1).max(1e4).nullable(),createdAt:pa,updatedAt:pa});l({schemaVersion:b("openpond.taskCreationTranscript.v1"),creationId:bt,profileId:bt,messages:KC.shape.transcript,updatedAt:pa});const Cs=o().trim().min(1).max(240),gu=o().trim().min(1),ug=o().trim().min(8).max(256),WC=ae(o(),ie()).default({}),H3=v(["created","inspecting","awaiting_source_review","awaiting_mapping","awaiting_materialization_approval","materializing","validating","ready","cancelling","cancelled","failed"]),GC=l({schemaVersion:b("openpond.huggingFaceDatasetLocator.v1"),repositoryId:o().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:o().url().max(2e3),requestedRevision:o().trim().min(1).max(256).nullable()}),L3=l({path:o().trim().min(1).max(1e3),logicalType:o().trim().min(1).max(500),nullable:w(),sampleValues:p(ie()).max(5)}),q3=l({configuration:o().trim().min(1).max(500),split:o().trim().min(1).max(500),rowCount:d().int().nonnegative().nullable(),sizeBytes:d().int().nonnegative().nullable()}),U3=l({schemaVersion:b("openpond.huggingFaceDatasetInspection.v1"),id:Cs,locator:GC,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:w(),private:w(),configurations:p(o().trim().min(1).max(500)).min(1).max(1e3),splits:p(q3).min(1).max(1e4),columns:p(L3).min(1).max(1e4),previewRows:p(ae(o(),ie())).max(25),sourceFiles:p(l({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:d().int().nonnegative().nullable(),contentHash:ug.nullable()})).max(1e5),inspectedAt:gu,metadata:WC}),z3=v(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),B3=l({sourcePath:o().trim().min(1).max(1e3),target:z3,transform:v(["identity","string","json","messages","numeric","math_final_answer"]),policy:v(["visible","privileged","metadata"]),required:w()}),JC=l({schemaVersion:b("openpond.datasetImportMapping.v1"),sourceSchemaHash:ug,configuration:o().trim().min(1).max(500),upstreamSplits:p(o().trim().min(1).max(500)).min(1).max(1e3),preset:v(["prompt_only","prompt_completion","messages","preference","prompt_expected_answer","prompt_privileged_solution","prompt_feedback"]),bindings:p(B3).min(1).max(1e4),nullPolicy:v(["reject","drop","preserve"]),invalidRowPolicy:v(["reject_import","drop_with_receipt"]),splitPolicy:l({seed:d().int(),assignments:ae(o(),Jo),validationPercent:d().min(0).max(100),frozenEvalPercent:d().min(0).max(100)}),importerVersion:o().trim().min(1).max(200),mappingHash:ug}),F3=l({phase:v(["idle","metadata","download","mapping","parquet_write","verification","publish"]),completedBytes:d().int().nonnegative(),totalBytes:d().int().nonnegative().nullable(),completedRows:d().int().nonnegative(),totalRows:d().int().nonnegative().nullable(),message:o().trim().min(1).max(2e3).nullable()}),V3=l({schemaVersion:b("openpond.datasetImportJob.v1"),id:Cs,profileId:Cs,sourceKind:v(["huggingface","uploaded_file"]),status:H3,locator:GC.nullable(),inspection:U3.nullable(),mapping:JC.nullable(),progress:F3,targetStorageRoot:o().trim().min(1).max(4e3).nullable(),tasksetId:Cs.nullable(),tasksetRevision:d().int().positive().nullable(),artifactId:Cs.nullable(),error:o().trim().min(1).max(2e4).nullable(),cancellationRequested:w(),createdAt:gu,updatedAt:gu,completedAt:gu.nullable(),metadata:WC});l({profileId:Cs,url:o().trim().min(1).max(2e3)});l({name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),mapping:JC,targetStorageRoot:o().trim().min(1).max(4e3).nullable(),licenseApproved:w().default(!1)});var sc=o().trim().min(1).max(200),mg=l({operationId:sc,execution:De,executionKind:b("recorded_evidence").optional(),graders:p(cl).min(1).max(100),maximumCostUsd:d().finite().min(1e-6).max(1e4),mappings:p(l({graderId:sc,fields:wb}).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."})}),K3=l({schemaVersion:b("openpond.experimentScoringPass.v1"),id:sc,teamId:sc,revision:d().int().positive(),request:mg,graders:p(Mi).min(1).max(100),status:v(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:d().int().min(1).max(1e4),counts:l({pending:d().int().nonnegative(),running:d().int().nonnegative(),scored:d().int().nonnegative(),unavailable:d().int().nonnegative(),failed:d().int().nonnegative(),cancelled:d().int().nonnegative()}).strict(),resultAvailable:w(),createdAt:nn(),startedAt:nn().nullable(),completedAt:nn().nullable(),error:l({code:sc,message:o().max(2e3)}).strict().nullable()}).strict();K3.extend({contentHash:o().regex(/^[a-f0-9]{64}$/)});var ZC=l({sourcePass:De,graders:mg.shape.graders,mappings:mg.shape.mappings,maximumCostUsd:d().finite().positive().max(1e4)}).strict(),YC=l({externalDatasetBinding:Ko,scoring:ZC.optional(),modelId:o().min(1).max(300),maximumCostUsd:d().finite().positive().max(1e4)}).strict(),Mb=l({source:v(["local","github","openpond_git"]),repositoryId:o().trim().min(1),profileId:o().trim().min(1)}).strict(),$t=o().min(1).max(240),ra=o().regex(/^[a-f0-9]{64}$/),lc=l({schemaVersion:b("openpond.experimentImprovement.v1"),id:$t,operationId:$t,requestHash:ra,actorId:$t,teamId:$t,projectId:$t.nullable(),ownerWorkspaceId:$t,ownerRevision:d().int().nonnegative(),ownerSourceRevision:o().min(1).max(500),baseRelease:De,profileRef:Mb,baseProfileSourceRevision:o().min(1).max(500),evidence:l({manifest:ro,result:so}).strict(),component:l({kind:v(["skill","workflow","agent","instruction"]),path:o().min(1).max(2e3),workflowId:$t.optional()}).strict(),mode:v(["manual","llm_assisted"]),status:v(["draft","authoring_queued","authoring","frozen","testing","ready_for_review","adopting","accepted","rolled_back","declined","failed","cancelled"]),revision:d().int().positive(),limits:l({maximumCostUsd:d().finite().positive(),maximumAuthoringSteps:d().int().min(1).max(500),maximumDurationMs:d().int().min(1e3).max(864e5)}).strict(),authoringSteps:d().int().nonnegative().max(500),work:l({sessionId:$t,turnId:$t,revision:d().int().positive(),startedAt:o().datetime()}).strict().nullable(),frozen:l({release:De,sourceRevision:o().min(1).max(500),profileSourceRevision:o().min(1).max(500),authoringHash:ra,partitionHash:ra,executableSourceHash:ra,protectedClosureHash:ra,candidateRevision:d().int().positive(),diff:p(l({path:o(),before:ra.nullable(),after:ra.nullable()}).strict()).max(1e4)}).strict().nullable(),test:l({recipe:YC,recipeHash:o().regex(/^[a-f0-9]{64}$/),baselineOperationId:o(),candidateOperationId:o(),cancelRequestedAt:o().datetime().nullable(),dispatching:l({kind:v(["baseline","candidate"]),token:$t,pid:d().int().positive(),processStart:o().nullable(),startedAt:o().datetime()}).strict().nullable()}).strict().nullable(),comparison:l({baseline:l({manifest:ro,result:so}).strict(),candidate:l({manifest:ro,result:so}).strict(),frozenHash:ra,humanProjection:dg.optional()}).strict().nullable(),adoptionIntent:l({operationId:$t,expectedOwnerRevision:d().int().nonnegative(),frozenHash:ra,humanProjection:dg.optional()}).strict().nullable(),acceptance:De.nullable(),rollback:De.nullable(),error:o().max(2e3).nullable(),createdAt:o().datetime(),updatedAt:o().datetime(),contentHash:ra}).strict();function vae(e){const t=lc.parse(e),{contentHash:n,...a}=t;if(Pt(a)!==n)throw new Error("Improvement state integrity failed.");if(wr(t.evidence),t.evidence.manifest.teamId!==t.teamId||t.evidence.result.status!=="completed"||!t.evidence.result.cases.some(i=>i.status==="completed"))throw new Error("Improvement requires usable completed owner evidence.");if(t.test&&(Pt(t.test.recipe)!==t.test.recipeHash||og(t.test.recipe.externalDatasetBinding).profileId!==t.profileRef.profileId))throw new Error("The test recipe changed its exact selected Profile.");if(t.comparison?.humanProjection){const i=RF(t.comparison.humanProjection);if(i.teamId!==t.teamId||i.projectId!==t.projectId||Pt(i.baseline)!==Pt(t.comparison.baseline)||Pt(i.candidate)!==Pt(t.comparison.candidate))throw new Error("Human comparison projection differs from its exact owner evidence.")}if(t.comparison&&(wr(t.comparison.baseline),wr(t.comparison.candidate),!t.frozen||t.comparison.frozenHash!==Pt(t.frozen)||!ZU(t.comparison.baseline,t.comparison.candidate).comparable))throw new Error("Improvement comparison is not bound to a comparable frozen candidate.");if(t.status==="ready_for_review"&&(!t.frozen||!t.comparison))throw new Error("Improvement is missing qualification.");if(t.status==="adopting"&&(!t.adoptionIntent||!t.frozen||t.adoptionIntent.frozenHash!==Pt(t.frozen)))throw new Error("Improvement adoption intent is not bound to its tested revision.");if(t.status==="accepted"&&(!t.acceptance||!t.comparison||!t.frozen))throw new Error("Improvement acceptance is missing its exact qualification receipt.");if(t.status==="rolled_back"&&(!t.acceptance||!t.rollback))throw new Error("Profile rollback is missing its durable owner receipt.");return t}var bae=l({states:p(lc).max(50),nextCursor:$t.nullable()}).strict(),W3=l({operationId:$t,ownerWorkspaceId:$t,expectedOwnerRevision:d().int().nonnegative(),baseRelease:De,profileRef:Mb,profileSourceRevision:o().min(1).max(500),projectId:$t.nullable(),evidence:De,component:lc.shape.component,mode:lc.shape.mode,limits:lc.shape.limits}).strict(),yae=lt("operation",[l({operation:b("list"),limit:d().int().min(1).max(50).default(30),cursor:$t.optional()}).strict(),l({operation:b("options"),evidence:De}).strict(),l({operation:b("start"),request:W3}).strict(),l({operation:v(["read","humanComparisonOptions"]),id:$t}).strict(),l({operation:b("instructions"),id:$t}).strict(),l({operation:b("edit"),id:$t,revision:d().int().positive(),expectedFileHash:ra,text:o().max(25e4)}).strict(),l({operation:b("mode"),id:$t,revision:d().int().positive(),mode:v(["manual","llm_assisted"])}).strict(),l({operation:b("author"),id:$t,revision:d().int().positive(),modelId:$t,prompt:o().min(1).max(2e4)}).strict(),l({operation:v(["freeze","finishAuthoring","useCandidate","discard","cancel","rollback"]),id:$t,revision:d().int().positive()}).strict(),l({operation:b("test"),id:$t,revision:d().int().positive(),recipe:YC}).strict(),l({operation:b("compare"),id:$t,revision:d().int().positive(),baseline:De,candidate:De,humanSelections:tC.optional()}).strict()]),QC=l({teamId:$t,evidence:De,scoring:ZC.optional(),profiles:p(l({id:ra,name:o(),profileRef:Mb,ownerWorkspaceId:$t,ownerRevision:d().int().nonnegative(),baseRelease:De,profileSourceRevision:o(),components:p(l({kind:v(["skill","instruction","agent","workflow"]),path:o(),agentId:o().optional(),workflowId:o().optional(),label:o(),binding:Ko}).strict()).max(500)}).strict()).max(100)}).strict(),G3=l({candidateId:$t,actorId:$t,teamId:$t,projectId:$t.nullable(),candidateRevision:d().int().positive(),recipeHash:ra,baseline:l({manifest:ro,result:so}).strict(),candidate:l({manifest:ro,result:so}).strict(),contentHash:ra}).strict();function Sae(e){const t=G3.parse(e),{contentHash:n,...a}=t;if(Pt(a)!==n)throw new Error("Accepted Human discovery integrity failed.");for(const i of[t.baseline,t.candidate])if(wr(i),i.manifest.teamId!==t.teamId||i.manifest.lineage?.humanProjection)throw new Error("Discovery must retain original owner evidence.");return t}var en=o().trim().min(1).max(240),Ei=o().regex(/^[a-f0-9]{64}$/),jb=l({schemaVersion:b("openpond.advancedRefinerEvaluation.v1"),operationId:en,actorId:en,teamId:en,projectId:en.nullable(),mode:v(["review_quality","downstream_adaptation"]),profileRef:l({source:v(["local","github","openpond_git"]),repositoryId:en,profileId:en}).strict(),sourceRevision:o().min(1).max(500),baselineRelease:De,refinerRelease:De,evidence:De,externalDatasetBinding:Ko,adaptationDatasetBinding:Ko,privateClosureHash:Ei,adaptationTaskIds:p(en).min(1).max(1e4),holdoutTaskIds:p(en).min(1).max(1e4),adaptationSplit:v(["train","validation","test","frozen_eval"]),holdoutSplit:v(["train","validation","test","frozen_eval"]),environmentPolicy:lt("kind",[l({kind:b("resettable"),environmentHash:Ei}).strict(),l({kind:b("frozen_observations"),environmentHash:Ei}).strict()]),maximumCostUsd:d().finite().positive().max(1e4),maximumDurationMs:d().int().min(1e3).max(864e5),maximumModelSteps:d().int().min(1).max(1e3),contentHash:Ei}).strict();function xae(e){const t=jb.parse(e),{contentHash:n,...a}=t;if(Pt(a)!==n)throw new Error("Advanced Refiner evaluation admission changed.");const i=og(t.externalDatasetBinding);if(i.profileId!==t.profileRef.profileId||i.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=og(t.adaptationDatasetBinding);if(r.profileId!==i.profileId||r.packageHash!==i.packageHash||Pt(r.dataset)!==Pt(i.dataset)||Pt(r.target)!==Pt(i.target)||r.protectedProfileClosureHash!==i.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||i.split!==t.holdoutSplit)throw new Error("Advanced split policies differ from their exact admitted recipes.");const s=new Set(i.population.map(m=>m.taskId)),c=new Set(r.population.map(m=>m.taskId));if(t.holdoutTaskIds.some(m=>!s.has(m))||t.adaptationTaskIds.some(m=>!c.has(m)))throw new Error("Advanced evaluation selected cases outside its exact Dataset recipe.");return t}var J3=l({pin:jb,modelId:en,profileId:en,model:fb,seed:d().int(),reasoningEffort:v(["none","off","low","medium","high","xhigh","max"]).nullable()}).strict(),Z3=lt("operation",[l({operation:b("start"),request:J3}).strict(),l({operation:v(["read","cancel","resume"]),id:en}).strict(),l({operation:b("list")}).strict()]),Y3=l({taskId:en,sourceCaseHash:Ei,reviewSessionId:en,reviewTurnId:en,inputHarness:De,trigger:De,decision:v(["no_action","route_deterministically","queue_refiner"]),outcome:De.nullable(),proposal:De.nullable(),validations:p(De).max(100),grade:l({id:en,contentHash:Ei,score:d().min(0).max(1).nullable(),passed:w(),failureClass:o().nullable()}).strict(),resetComplete:w()}).strict(),Q3=l({schemaVersion:b("openpond.advancedRefinerReviewReceipt.v1"),id:en,runId:en,pinHash:Ei,ownerActorId:en,teamId:en,privateClosureHash:Ei,refinerRelease:De,cases:p(Y3).min(1).max(1e4),reviewScore:d().min(0).max(1).nullable(),completedCases:d().int().nonnegative(),noActionCases:d().int().nonnegative(),routedCases:d().int().nonnegative(),proposalCases:d().int().nonnegative(),costUsd:d().finite().nonnegative().nullable(),cleanupComplete:w(),createdAt:o().datetime(),contentHash:Ei}).strict(),_S=QC.shape.profiles.element,kae=QC.extend({profiles:p(_S.extend({components:p(_S.shape.components.element.extend({adaptationSplits:p(l({split:v(["train","validation","test","frozen_eval"]),taskIds:p(en)})),environmentHash:Ei,resettable:w(),reviewQuality:w()}))})),refinerReleases:p(De),activeRefiner:De.nullable(),models:p(l({id:en,profileId:en,name:o(),location:v(["local","hosted"])}))}),X3=l({operation:b("prepare"),evidence:De,profileOptionId:en,componentLabel:en,mode:v(["review_quality","downstream_adaptation"]),adaptationSplit:v(["train","validation","test","frozen_eval"]),operationId:en,refinerRelease:De,maximumCostUsd:d().positive(),maximumDurationMs:d().int().positive(),maximumModelSteps:d().int().positive()}).strict();ht([Z3,X3,l({operation:b("options"),evidence:De}).strict()]);var e6=l({modelRequests:d().int().nonnegative(),knownSpendUsd:d().nonnegative(),totalSpendUsd:d().nonnegative().nullable(),heldUsd:d().nonnegative(),uncertainRequests:d().int().nonnegative()}).strict();const Oo=T.nullable(),Gi=d().int().nonnegative(),t6=o().regex(/^[a-f0-9]{40}$/),n6=l({name:o().trim().min(1).max(160),startedAt:he,completedAt:he,durationMs:d().nonnegative(),clock:v(["monotonic","provider","wall"]),outcome:v(["succeeded","failed","cancelled"])}).strict(),a6=l({schemaVersion:b("openpond.correlatedTelemetryReceipt.v1"),stage:v(["training","evaluation","deployment","inference"]),correlation:l({modelRunId:Oo,modelVersionId:Oo,policyVersion:Gi.nullable(),taskId:Oo,rolloutGroupId:Oo,providerResourceId:Oo,deploymentId:Oo,inferenceRequestId:Oo}).strict(),spans:p(n6).max(1e4),usage:l({promptTokens:Gi.nullable(),generatedTokens:Gi.nullable(),gpuSeconds:d().nonnegative().nullable(),workerActiveSeconds:d().nonnegative().nullable(),optimizerSteps:Gi.nullable(),rolloutGroups:Gi.nullable(),successfulTrajectories:Gi.nullable(),failedTrajectories:Gi.nullable(),peakGpuMemoryBytes:Gi.nullable(),peakGpuUtilizationPercent:d().min(0).max(100).nullable()}).strict(),resource:l({provider:T,resourceIds:p(T).max(1e3),gpuType:o().trim().min(1).max(300).nullable(),gpuCount:Gi.nullable(),baseProfileId:Oo,baseRepository:o().trim().min(1).max(512).nullable(),baseRevision:t6.nullable(),adapterContentHash:D.nullable()}).strict(),cost:l({currency:b("USD"),providerReportedUsd:d().nonnegative().nullable(),quotedHourlyUsd:d().nonnegative().nullable(),estimatedUsd:d().nonnegative().nullable(),methodologyVersion:o().trim().min(1).max(160),pricingInputs:ae(o().trim().min(1).max(160),d().finite()),unitEstimates:ae(o().trim().min(1).max(160),d().nonnegative())}).strict(),recordedAt:he,contentHash:D}).strict(),Cn=o().trim().min(1).max(240),mo=o().regex(/^[a-f0-9]{64}$/),qo=o().datetime({offset:!0}),Tn=l({id:Cn,contentHash:mo}).strict(),i6=Tn.extend({revision:d().int().positive()}).strict(),XC=l({providerId:Cn,modelId:o().trim().min(1).max(300)}).strict(),Jm=v(["correction","sibling_verification","cumulative_known","development","retained","frozen_final","training_eligible"]),o6=l({taskId:Cn,taskContentHash:mo,panelRole:Jm,passLabel:Cn.nullable(),optimizerEligible:w(),criticalInvariantIds:p(Cn).max(100).default([])}).strict().superRefine((e,t)=>{e.optimizerEligible!==(e.panelRole==="correction")&&t.addIssue({code:"custom",path:["optimizerEligible"],message:"Only correction cases may be optimizer eligible."})}),r6=l({schemaVersion:b("openpond.continualBenchIssuePacket.v1"),id:Cn,revision:d().int().positive(),contentHash:mo,familyId:Cn,familyLabel:o().trim().min(1).max(500),severity:v(["low","medium","high","critical"]),cases:p(o6).min(2).max(1e4),duplicateEvidence:Tn,leakageEvidence:Tn,priorExposureEvidence:Tn,observedAt:qo,reviewedAt:qo,queuedAt:qo.nullable(),runAt:qo.nullable(),createdBy:Cn,createdAt:qo}).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."})}),s6=l({id:Cn,role:Jm,passLabel:Cn.nullable(),taskset:i6,familyIds:p(Cn).min(1).max(1e5),taskCount:d().int().positive().max(1e6),sealedAt:qo}).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."})}),ah=lt("kind",[l({kind:b("base_model"),id:Cn,revision:o().trim().min(1).max(500),contentHash:mo}).strict(),l({kind:b("model_version"),id:Cn,contentHash:mo}).strict(),l({kind:b("external_reference"),id:Cn,model:XC,providerRevision:o().trim().min(1).max(500),contentHash:mo}).strict()]),l6=l({scheduleEntryId:Cn,ordinal:d().int().nonnegative(),label:Cn,role:v(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),parentRule:v(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),trainableRank:d().int().positive().max(1024),correctionPanelIds:p(Cn).min(1).max(1e3),optimizerGroupsPerTask:d().int().positive().max(1e3),trajectoriesPerGroup:d().int().min(4).max(1e3)}).strict(),c6=l({revision:d().int().positive(),requireAllAttemptsTerminal:b(!0),criticalCorrectionPassRate:d().min(0).max(1),siblingPassRate:d().min(0).max(1),behavioralRetentionRate:d().min(0).max(1),maximumRetainedRegressionPoints:d().min(0).max(100),blockCriticalPriorRegression:w(),authorizedClaims:p(v(["systems_complete","correction_absorbed","issue_generalized","continually_current","frontier_pareto_result"])).min(1).max(5)}).strict(),d6=l({schemaVersion:b("openpond.continualBenchmarkProtocol.v1"),id:Cn,revision:d().int().positive(),contentHash:mo,ownerId:Cn,createdAt:qo,sealedAt:qo,creationReceipt:Tn,predecessorSeries:l({id:Cn,revision:d().int().positive(),contentHash:mo}).strict().nullable(),scenarioPack:Tn,issueFamilyLedger:Tn,issuePacketRelease:Tn,panels:p(s6).min(6).max(1e4),grader:Tn,judge:l({release:Tn,rubricRelease:Tn,calibrationRelease:Tn,model:XC}).strict().nullable(),policies:l({base:ah,master:ah.nullable(),externalReferences:p(ah).min(1).max(20)}).strict(),invariants:l({systemPromptHash:mo,toolSchema:Tn,application:Tn,harness:Tn,runtime:Tn,workerImage:Tn,autoRefiner:l({enabled:w(),release:Tn.nullable()}).strict()}).strict(),schedule:p(l6).min(1).max(1e3),evaluation:l({seeds:p(d().int()).min(3).max(100),repetitions:d().int().min(3).max(20),powerRule:Tn,pairedBootstrapSamples:d().int().min(1e3).max(1e6),confidenceLevel:b(.95)}).strict(),resources:l({maximumTrainingGpuSeconds:d().int().positive(),maximumEvaluationGpuSeconds:d().int().positive(),maximumProviderSpendUsd:d().positive(),maximumTotalSpendUsd:d().positive(),maximumConcurrentGroups:d().int().positive().max(1e3)}).strict(),currencyThresholds:c6}).strict().superRefine((e,t)=>{const n=e.panels.map(r=>r.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["panels"],message:"Protocol panel ids must be unique."});for(const r of["development","retained","frozen_final","training_eligible"])e.panels.filter(s=>s.role===r).length!==1&&t.addIssue({code:"custom",path:["panels"],message:`A protocol requires exactly one ${r} panel.`});[...e.schedule].sort((r,s)=>r.ordinal-s.ordinal).some((r,s)=>r.ordinal!==s)&&t.addIssue({code:"custom",path:["schedule"],message:"Protocol schedule ordinals must be contiguous from zero."});const i=new Set(n);e.schedule.some(r=>r.correctionPanelIds.some(s=>!i.has(s)))&&t.addIssue({code:"custom",path:["schedule"],message:"Every scheduled correction panel must belong to the protocol."})}),u6=v(["draft","active","completed","archived"]),m6=v(["draft","ready","queued","running","candidate","accepted","rejected","no_signal","failed","cancelled"]),eR=v(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),p6=v(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),f6=v(["seed_taskset","nightly_selection","daily_cohort_union","eligible_task_pool"]),h6=v(["live_client","evaluation_attempt","replay_evidence","manual"]),g6=l({id:T,ordinal:d().int().nonnegative(),label:o().trim().min(1).max(100),role:eR,parentRule:p6,taskSource:f6,trainableRank:d().int().positive().max(1024),minimumTasks:d().int().nonnegative().max(1e5),maximumTasks:d().int().positive().max(1e5)}).strict().superRefine((e,t)=>{e.minimumTasks>e.maximumTasks&&t.addIssue({code:"custom",path:["minimumTasks"],message:"The minimum task count cannot exceed the maximum task count."});const n={seed:{parentRules:["base_model"],taskSource:"seed_taskset"},daily_residual:{parentRules:["previous_release","accepted_daily_head"],taskSource:"nightly_selection"},rank_candidate:{parentRules:["seed_release"],taskSource:"eligible_task_pool"},weekly_rollup:{parentRules:["seed_release","accepted_seed"],taskSource:"daily_cohort_union"},full_refresh:{parentRules:["base_model"],taskSource:"eligible_task_pool"}},{parentRules:a,taskSource:i}=n[e.role];a.includes(e.parentRule)||t.addIssue({code:"custom",path:["parentRule"],message:`${e.role} requires parent rule ${a.join(" or ")}.`}),e.taskSource!==i&&t.addIssue({code:"custom",path:["taskSource"],message:`${e.role} requires task source ${i}.`}),e.ordinal===0&&e.role!=="seed"&&t.addIssue({code:"custom",path:["role"],message:"The first series entry must be the seed."})}),v6=l({id:T,version:d().int().positive(),requireCheckpoint:w(),requireAppliedOptimizerUpdate:w(),minimumCurrentCohortMeanImprovement:d().finite(),maximumRetainedMeanRegression:d().finite().nonnegative(),blockCriticalInvariantRegression:w(),automaticDailyAdvancement:w()}).strict(),b6=l({schemaVersion:b("openpond.modelComparisonSeries.v1"),id:T,profileId:T,modelProjectId:T,name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),status:u6,revision:d().int().positive(),productionBinding:l({role:b("chat_manual"),roleTargetId:T}).strict(),baseModel:l({id:T,revision:o().trim().min(1).max(256)}).strict(),seedTaskset:Zt,eligibleTaskPool:Zt,evaluationTasksets:l({development:Zt,retained:Zt,frozenFinal:Zt}).strict(),grader:V,benchmarkProtocol:d6.nullable().default(null),automaticEvaluation:l({enabled:w()}).strict().default({enabled:!1}),residualProfile:l({profileId:T,serializedEnvelopeRank:d().int().positive().max(1024),maximumEnabledRank:d().int().positive().max(1024),topology:b("uniform_block_masked")}).strict(),schedule:p(g6).min(1).max(1e3),scheduleSealedAt:he.nullable(),advancementPolicy:v6,executionPolicy:l({startWhenReady:b(!1)}).strict(),acceptedSeedEntryId:T.nullable(),acceptedDailyHeadEntryId:T.nullable(),promotedBindingId:T.nullable(),createdBy:T,createdAt:he,updatedAt:he}).strict().superRefine((e,t)=>{[...e.schedule].sort((m,u)=>m.ordinal-u.ordinal).some((m,u)=>m.ordinal!==u)&&t.addIssue({code:"custom",path:["schedule"],message:"Schedule ordinals must be unique and contiguous from zero."}),(new Set(e.schedule.map(m=>m.id)).size!==e.schedule.length||new Set(e.schedule.map(m=>m.label)).size!==e.schedule.length)&&t.addIssue({code:"custom",path:["schedule"],message:"Schedule ids and labels must be unique."}),e.residualProfile.maximumEnabledRank>e.residualProfile.serializedEnvelopeRank&&t.addIssue({code:"custom",path:["residualProfile"],message:"Maximum enabled rank cannot exceed the serialized envelope."});const a=Object.values(e.evaluationTasksets);new Set(a.map(m=>`${m.id}:${m.revision}:${m.contentHash}`)).size!==a.length&&t.addIssue({code:"custom",path:["evaluationTasksets"],message:"Development, retained, and frozen-final cohorts require distinct immutable Taskset releases."});const i=e.schedule.find(m=>m.role==="seed");if(!i||e.schedule.filter(m=>m.role==="seed").length!==1){t.addIssue({code:"custom",path:["schedule"],message:"A series requires exactly one seed entry."});return}const r=e.schedule.filter(m=>m.role==="rank_candidate");r.length===1&&t.addIssue({code:"custom",path:["schedule"],message:"A causal rank comparison requires at least two rank candidates."}),new Set(r.map(m=>m.trainableRank)).size!==r.length&&t.addIssue({code:"custom",path:["schedule"],message:"Causal rank candidates must use distinct trainable ranks."}),[i.trainableRank+e.schedule.filter(m=>m.role==="daily_residual").reduce((m,u)=>m+u.trainableRank,0),...e.schedule.filter(m=>m.role==="weekly_rollup").map(m=>i.trainableRank+m.trainableRank),...e.schedule.filter(m=>m.role==="rank_candidate").map(m=>i.trainableRank+m.trainableRank),...e.schedule.filter(m=>m.role==="full_refresh").map(m=>m.trainableRank)].some(m=>m>e.residualProfile.maximumEnabledRank)&&t.addIssue({code:"custom",path:["schedule"],message:"A declared branch exceeds the maximum enabled rank."})}),tR=l({source:h6,taskIds:p(T).min(1).max(1e5),observedFrom:he,observedTo:he,reviewedAt:he,reviewedBy:T,sourceTaskset:Zt}).strict(),y6=tR.extend({derivedFamilyKeys:p(T).min(1).max(1e5),familyDerivation:l({algorithm:T,sourceTasksetHash:D}).strict(),selectionHash:D}).strict(),nR=lt("kind",[l({kind:b("base_model"),id:T,revision:o().trim().min(1).max(256)}).strict(),l({kind:b("model_version"),id:T,contentHash:D}).strict()]),S6=l({id:T,branchOrdinal:d().int().nonnegative(),rank:d().int().positive().max(1024),offsetStart:d().int().nonnegative(),offsetEnd:d().int().positive(),optimizationRole:v(["frozen","trainable"]),artifactLineageId:T.nullable()}).strict().superRefine((e,t)=>{e.offsetEnd-e.offsetStart!==e.rank&&t.addIssue({code:"custom",path:["offsetEnd"],message:"Block offsets must span exactly the declared rank."})}),x6=l({disposition:v(["advance","hold","no_signal"]),policy:l({id:T,version:d().int().positive()}).strict(),reasonCodes:p(T).min(1).max(100),summary:o().trim().min(1).max(5e3),decidedBy:T,decidedAt:he}).strict(),k6=l({evaluationRunId:T,modelVersionId:T,taskset:Zt,grader:V,cohortRole:v(["current","correction","sibling_verification","cumulative_known","development","retained","prior_disclosed","frozen_final"]),panelId:T.nullable().default(null),protocol:l({id:T,revision:d().int().positive(),contentHash:D}).strict().nullable().default(null)}).strict(),I6=l({attemptOrdinal:d().int().positive(),trainingPlanId:T.nullable(),modelRunId:T.nullable(),terminalStatus:v(["failed","cancelled"]),queuedAt:he.nullable(),startedAt:he.nullable(),completedAt:he}).strict(),Ys=l({seriesId:T,entryId:T,scheduleEntryId:T,ordinal:d().int().nonnegative(),releaseHash:D}).strict(),w6=l({schemaVersion:b("openpond.modelComparisonSeriesEntry.v1"),id:T,seriesId:T,profileId:T,modelProjectId:T,scheduleEntryId:T,releaseHash:D,ordinal:d().int().nonnegative(),label:o().trim().min(1).max(100),role:eR,branch:v(["daily","rank_candidate","weekly_rollup","full_refresh"]),status:m6,parent:nR,taskset:Zt,sourceTasksets:p(Zt).min(1).max(1e3),taskSelection:y6.nullable(),trainableRank:d().int().positive().max(1024),serializedEnvelopeRank:d().int().positive().max(1024),enabledCumulativeRank:d().int().positive().max(1024),trainableBlockId:T,residualBlocks:p(S6).min(1).max(1024),attemptOrdinal:d().int().positive().default(1),priorRunAttempts:p(I6).max(100).default([]),trainingPlanId:T.nullable(),modelRunId:T.nullable(),modelVersionId:T.nullable(),evaluations:p(k6).max(1e5),decision:x6.nullable(),promotionBindingId:T.nullable(),queuedAt:he.nullable(),startedAt:he.nullable(),completedAt:he.nullable(),createdAt:he,updatedAt:he}).strict().superRefine((e,t)=>{const n=[...e.residualBlocks].sort((s,c)=>s.offsetStart-c.offsetStart);n.some((s,c)=>s.offsetStart!==(c===0?0:n[c-1].offsetEnd))&&t.addIssue({code:"custom",path:["residualBlocks"],message:"Residual block offsets must be contiguous from zero."});const a=n.at(-1)?.offsetEnd??0;(a!==e.enabledCumulativeRank||a>e.serializedEnvelopeRank)&&t.addIssue({code:"custom",path:["enabledCumulativeRank"],message:"Enabled rank must match the block inventory and fit the envelope."});const i=e.residualBlocks.filter(s=>s.optimizationRole==="trainable");(i.length!==1||i[0]?.id!==e.trainableBlockId||i[0]?.rank!==e.trainableRank)&&t.addIssue({code:"custom",path:["trainableBlockId"],message:"Exactly one block must be trainable during the Run and match trainableRank."});const r=e.priorRunAttempts.map(s=>s.attemptOrdinal);(e.priorRunAttempts.length!==e.attemptOrdinal-1||r.some((s,c)=>s!==c+1))&&t.addIssue({code:"custom",path:["priorRunAttempts"],message:"Prior Run attempts must be a contiguous history before the active attempt."})});l({seriesId:T,scheduleEntryId:T,taskSelection:tR.nullable(),expectedSeriesRevision:d().int().positive()}).strict();const _6=v(["base_reference","lora_adapter"]),aR=l({baseModel:l({source:b("huggingface"),repoId:T,revision:o().regex(/^[a-f0-9]{40}$/),configHash:D,tokenizerHash:D,licenseId:T,gated:w()}).strict(),processor:l({repository:T,revision:o().regex(/^[a-f0-9]{40}$/),configHash:D}).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."})}),C6=l({schemaVersion:b("openpond.modelVersion.v1"),id:T,modelId:T,profileId:T,version:d().int().nonnegative(),kind:_6,status:v(["available","failed"]),baseModel:ld,taskset:Zt,comparisonSeriesEntry:Ys.nullable().optional(),evaluationTasksetRef:Zt.nullable().optional(),releaseGraph:l({resolvedBundleHash:D,profileRelease:Zt,harnessRelease:V,agentRelease:V.nullable(),grader:l({id:T,contentHash:D}).strict()}).strict(),artifactLineageId:T.nullable(),adapterStatus:v(["not_trained","trained"]),createdAt:he,contentHash:D}).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."})}),R6=l({schemaVersion:b("openpond.rewardModelVersion.v1"),id:T,modelId:T,profileId:T,version:d().int().positive(),role:b("reward"),status:v(["available","failed"]),scope:v(["synthetic_smoke","human_preference"]),baseModel:ld,runtime:aR.nullable().default(null),taskset:Zt,preferenceDatasetRelease:V,releaseGraph:l({resolvedBundleHash:D,profileRelease:Zt,harnessRelease:V,grader:l({id:T,contentHash:D}).strict()}).strict(),artifacts:l({checkpoint:V.extend({objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:p(l({path:o().trim().min(1).max(512),sizeBytes:d().int().positive(),sha256:D}).strict()).min(4).max(128)}).strict(),adapter:V,scalarHead:V,bucketHead:V.nullable(),processorRelease:V}).strict(),qualificationReport:V.nullable(),createdAt:he,contentHash:D}).strict(),P6=l({schemaVersion:b("openpond.rewardModelRunReceipt.v1"),provider:T,providerRunId:T,resolvedBundleHash:D,finalCheckpoint:V.extend({objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/)}).strict(),adapter:V,scalarHead:V,bucketHead:V.nullable(),processorRelease:V,optimizerEvidence:V,managedExecutionReceipt:V.nullable().default(null),parameterDeltaHash:D,cleanup:l({computeReleased:w(),providerTerminalObserved:w()}).strict(),contentHash:D}).strict(),A6=w2(e=>{if(!e||typeof e!="object"||Array.isArray(e))return e;const t=e;if(t.tasksetRelease!==void 0)return e;const n=t.taskset;if(!n||typeof n!="object"||Array.isArray(n))return e;const a=n;return typeof a.id!="string"||typeof a.contentHash!="string"?e:{...t,tasksetRelease:{id:a.id,contentHash:a.contentHash}}},l({schemaVersion:b("openpond.rewardModelRun.v1"),id:T,rewardModelId:T,rewardModelVersionId:T.nullable(),profileId:T,role:b("reward"),scope:v(["synthetic_smoke","human_preference"]),status:v(["prepared","running","succeeded","failed","cancelled"]),taskset:Zt,tasksetRelease:V,preferenceDatasetRelease:V,recipeRelease:V,destinationId:T,quote:l({maximumSpendUsd:d().positive(),hourlyCostUsd:d().nonnegative().nullable()}).strict(),managedRunId:T.nullable(),progress:l({completedSteps:d().int().nonnegative(),totalSteps:d().int().positive(),latestLoss:d().finite().nullable()}).strict(),receipt:P6.nullable(),qualificationReport:V.nullable(),accruedSpendUsd:d().nonnegative().nullable(),failureOwner:v(["authoring","admission","provider","runner","artifact","qualification","cleanup"]).nullable(),failure:o().trim().min(1).max(5e3).nullable(),startedAt:he,completedAt:he.nullable(),updatedAt:he}).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."})}),T6=l({schemaVersion:b("openpond.modelRunReceipt.v1"),provider:T,providerRunId:T,assignmentHash:D,resultHash:D,transcriptHash:D,traceHash:D.nullable(),resolvedBundleHash:D,artifactPath:o().trim().min(1).max(2e3),cleanup:l({computeReleased:w(),tunnelClosed:w()}).strict(),telemetry:a6.nullable().default(null),contentHash:D}).strict(),No=l({inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),costUsd:d().nonnegative().nullable()}).strict(),CS=o().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),Ob=l({phase:v(["baseline","adaptation","candidate_adaptation","candidate"]),taskId:T,attemptId:T,sessionId:T.nullable(),turnId:T.nullable(),passed:w(),score:d().min(0).max(1).nullable(),failureClass:Eb.nullable(),inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),latencyMs:d().int().nonnegative(),costUsd:d().nonnegative().nullable(),startedAt:he}).strict(),RS=l({targetTaskCount:d().int().nonnegative(),comparedTaskCount:d().int().nonnegative(),passedTaskCount:d().int().nonnegative(),failedTaskCount:d().int().nonnegative(),lowerTaskCount:d().int().nonnegative(),higherTaskCount:d().int().nonnegative(),unchangedTaskCount:d().int().nonnegative()}).strict(),iR=l({target:b("all_tasks_lower"),targetTaskCount:d().int().nonnegative(),comparedTaskCount:d().int().nonnegative(),passedTaskCount:d().int().nonnegative(),failedTaskCount:d().int().nonnegative(),lowerTaskCount:d().int().nonnegative(),higherTaskCount:d().int().nonnegative(),unchangedTaskCount:d().int().nonnegative(),baselineTokens:d().int().nonnegative(),refinedTokens:d().int().nonnegative(),tokenDelta:d().int(),tokenDeltaPercent:d().finite().nullable(),complete:w(),passed:w(),cohorts:l({adaptation:RS,heldOut:RS}).strict()}).strict(),$b=l({baseline:No,adaptation:No,candidateAdaptation:No,candidate:No,refiner:No,grader:No}).strict(),E6=l({usage:$b,observedSpendUsd:d().nonnegative(),attempts:p(Ob).max(1e4)}).strict(),M6=l({id:T,contentHash:D,artifactPath:o().trim().min(1).max(2e3)}).strict(),j6=l({schemaVersion:b("openpond.modelEvaluationReceipt.v1"),benchmarkId:T,resultManifest:l({id:T,contentHash:D,artifactPath:o().trim().min(1).max(2e3)}).strict(),stages:l({baseline:V,adaptation:V,refiner:V,candidateAdaptation:V,candidate:V,comparison:V}).strict(),usage:$b,quality:l({baselinePassRate:d().min(0).max(1),candidatePassRate:d().min(0).max(1),adaptationBaselinePassRate:d().min(0).max(1),adaptationCandidatePassRate:d().min(0).max(1),adaptationCandidatePassed:w(),heldOutCandidatePassed:w(),passed:w()}).strict(),foregroundTokenDelta:d().int(),foregroundTokenDeltaPercent:d().finite().nullable(),taskEfficiency:iR.optional(),efficiency:l({grossForegroundTokenSavings:d().int(),overheadTokens:d().int().nonnegative(),firstPassNetTokenSavings:d().int(),breakEvenReuseCount:d().int().nonnegative().nullable(),amortizedTokenSavings:d().int(),amortizedReuseCount:d().int().positive()}).strict(),budget:l({maximumSpendUsd:d().nonnegative(),observedSpendUsd:d().nonnegative(),enforced:w()}).strict(),evidenceSnapshot:V,lineage:l({adaptationEvidenceHash:D,refinerInputHash:D,refinerOutcomeHash:D,validationHash:D,applyReceiptHash:D,candidateRelease:V,valid:w()}).strict(),invalidReasons:p(o().trim().min(1).max(2e3)).max(100),attempts:p(Ob).max(1e4).default([]),terminalClassification:v(["improved","no_improvement","regressed","inconclusive","cancelled","infrastructure_failure"]),profileGit:l({ref:o().trim().min(1).max(2e3),commit:CS,baseCommit:CS}).strict().nullable(),contentHash:D}).strict(),O6=l({schemaVersion:b("openpond.modelEvaluationStopReceipt.v1"),benchmarkId:T,terminalClassification:b("inconclusive"),stopReason:v(["candidate_harness_unchanged","candidate_lineage_invalid"]),reason:o().trim().min(1).max(5e3),stoppedAfter:b("refiner"),baselineHarness:V,candidateHarness:V,refiner:l({id:T,contentHash:D,outcomeCount:d().int().nonnegative()}).strict(),usage:$b,budget:l({maximumSpendUsd:d().nonnegative(),observedSpendUsd:d().nonnegative(),enforced:w()}).strict(),evidenceSnapshot:V,attempts:p(Ob).max(1e4),contentHash:D}).strict(),PS=l({level:b(.95),lower:d().finite(),upper:d().finite()}).strict().superRefine((e,t)=>{e.lower>e.upper&&t.addIssue({code:"custom",message:"A confidence interval's lower bound cannot exceed its upper bound."})}),$6=l({schemaVersion:b("openpond.modelComparisonBenchmarkReceipt.v1"),benchmarkId:b("model-comparison"),target:l({kind:v(["base_model","model_version","external_reference"]),label:o().trim().min(1).max(300),modelVersionId:T.nullable(),model:bn.nullable()}).strict(),taskset:Zt,grader:V,sampling:l({seeds:p(d().int()).min(1).max(100),repetitions:d().int().positive().max(20)}).strict(),deterministic:l({attemptedTaskCount:d().int().nonnegative(),completedTaskCount:d().int().nonnegative(),passedTaskCount:d().int().nonnegative(),failedTaskCount:d().int().nonnegative(),meanScore:d().finite().nullable(),passRate:d().min(0).max(1).nullable(),passRateCi95:PS.nullable()}).strict(),judge:l({judgeModel:bn,judgeRelease:V,rubricRelease:V,calibrationRelease:V,score:d().min(0).max(100),scoreCi95:PS,comparisonCount:d().int().positive(),wins:d().int().nonnegative(),ties:d().int().nonnegative(),losses:d().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:p(l({attemptId:T.nullable().default(null),taskId:T,seed:d().int(),repetition:d().int().nonnegative(),status:v(["succeeded","failed"]),deterministicScore:d().finite().nullable(),passed:w().nullable(),judgeScore:d().min(0).max(100).nullable(),judgePreference:v(["win","tie","loss"]).nullable(),transcriptHash:D.nullable(),traceHash:D.nullable(),transcriptArtifact:l({artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3)}).strict().nullable().default(null),traceArtifact:l({artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3)}).strict().nullable().default(null),latencyMs:d().int().nonnegative().nullable().default(null),failureClass:Eb.nullable()}).strict()).max(1e5),usage:l({policy:No.nullable(),judge:No.nullable(),observedSpendUsd:d().nonnegative().nullable(),evaluationGpuSeconds:d().nonnegative().nullable().default(null)}).strict(),managedServing:l({jobId:T,terminalState:v(["completed","cancelled","failed","budget_exhausted"]),sourcePolicyVersion:d().int().nonnegative(),sourceAdapterSha256:D.nullable(),servedPolicyVersion:d().int().nonnegative().nullable(),servedAdapterSha256:D.nullable(),accruedSpendUsd:d().nonnegative(),cleanupAttestationHash:D,resourceCount:d().int().nonnegative(),activeResourceCount:b(0)}).strict().nullable().default(null),evidenceSnapshot:l({id:T,contentHash:D,artifactPath:o().trim().min(1).max(2e3)}).strict(),completedAt:he,contentHash:D}).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."})}),N6=l({advancedEvaluation:jb.optional(),benchmarkId:b("harness-refiner"),model:bn,upstreamModel:l({providerId:T,modelId:o().trim().min(1).max(300),revision:o().trim().min(1).max(300),pricing:l({version:o().trim().min(1).max(300),source:o().trim().min(1).max(300),effectiveAt:he,inputUsdPerMillionTokens:d().nonnegative(),cachedInputUsdPerMillionTokens:d().nonnegative(),outputUsdPerMillionTokens:d().nonnegative()}).strict().optional()}).strict(),reasoningEffort:o().trim().min(1).max(100).nullable(),seeds:p(d().int()).min(1).max(100),repetitions:d().int().positive().max(20),maximumSpendUsd:d().nonnegative(),attemptPlan:p(l({stage:v(["baseline","adaptation","candidate_adaptation","candidate"]),split:o().trim().min(1).max(100),taskIds:p(T).min(1).max(1e5),attemptCount:d().int().positive()}).strict()).length(4)}).strict(),D6=l({benchmarkId:b("model-comparison"),target:l({kind:v(["base_model","model_version","external_reference"]),label:o().trim().min(1).max(300),modelVersionId:T.nullable(),model:bn.nullable()}).strict(),grader:V,judge:l({model:bn,release:V,rubricRelease:V,calibrationRelease:V,referenceLabel:o().trim().min(1).max(300)}).strict().nullable(),seeds:p(d().int()).min(1).max(100),repetitions:d().int().positive().max(20),maximumSpendUsd:d().nonnegative(),series:l({id:T,protocol:l({id:T,revision:d().int().positive(),contentHash:D}).strict()}).strict().nullable().default(null),panel:l({id:T,role:v(["correction","sibling_verification","cumulative_known","development","retained","frozen_final"]),passLabel:T.nullable()}).strict().nullable().default(null),comparisonPair:l({entryId:T,parent:nR,candidateModelVersionId:T}).strict().nullable().default(null),attemptPlan:p(l({stage:b("comparison"),split:o().trim().min(1).max(100),taskIds:p(T).min(1).max(1e5),attemptCount:d().int().positive()}).strict()).length(1)}).strict(),H6=ht([N6,D6]),L6=l({schemaVersion:b("openpond.modelRun.v1"),id:T,modelId:T,modelVersionId:T.nullable(),profileId:T,kind:v(["rollout_smoke","training","evaluation"]),status:v(["prepared","running","succeeded","failed","cancelled"]),method:v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]).nullable(),destinationId:T.nullable(),taskset:Zt,comparisonSeriesEntry:Ys.nullable().optional(),evaluationTasksetRef:Zt.nullable().optional(),harnessRelease:V.nullable().optional(),quote:l({maximumSpendUsd:d().nonnegative(),hourlyCostUsd:d().nonnegative().nullable()}).strict().nullable(),evaluation:H6.nullable().default(null),evaluationProgress:l({stage:v(["baseline","adaptation","refiner","candidate_adaptation","candidate","comparison"]),completedAttempts:d().int().nonnegative(),totalAttempts:d().int().positive(),accounting:E6.nullable().default(null),advancedAccounting:e6.optional(),evidenceSnapshot:M6.nullable().default(null)}).strict().nullable().default(null),reward:l({raw:d(),components:ae(o(),d())}).strict().nullable(),receipt:ht([T6,j6,O6,$6,Q3]).nullable(),adapterArtifactLineageId:T.nullable(),failure:o().trim().min(1).max(5e3).nullable(),startedAt:he,completedAt:he.nullable(),updatedAt:he}).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 Iae(e){const t=new Map;for(const C of e.attempts){const A=`${C.phase}\0${C.taskId}`,M=t.get(A);(!M||C.startedAt>M.startedAt||C.startedAt===M.startedAt&&C.attemptId>M.attemptId)&&t.set(A,C)}const n=[...t.values()],a=[["adaptation","adaptation","candidate_adaptation"],["held_out","baseline","candidate"]].flatMap(([C,A,M])=>{const R=new Map(n.filter($=>$.phase===M).map($=>[$.taskId,$]));return n.filter($=>$.phase===A).flatMap($=>{const O=R.get($.taskId);return O?[{cohort:C,taskId:$.taskId,baseline:$,refined:O,tokenDelta:O.totalTokens-$.totalTokens}]:[]})}),i=new Set(n.filter(C=>C.phase==="baseline"||C.phase==="adaptation").map(C=>C.taskId)).size,r=e.targetTaskCount??i;if(!Number.isInteger(r)||r<0)throw new Error("Benchmark task-efficiency target must be a non-negative integer.");const s={adaptation:new Set(n.filter(C=>C.phase==="adaptation").map(C=>C.taskId)).size,held_out:new Set(n.filter(C=>C.phase==="baseline").map(C=>C.taskId)).size},c=(C,A)=>({targetTaskCount:A,comparedTaskCount:C.length,passedTaskCount:C.filter(M=>M.tokenDelta<0).length,failedTaskCount:C.filter(M=>M.tokenDelta>=0).length,lowerTaskCount:C.filter(M=>M.tokenDelta<0).length,higherTaskCount:C.filter(M=>M.tokenDelta>0).length,unchangedTaskCount:C.filter(M=>M.tokenDelta===0).length}),m=c(a,r),u=a.reduce((C,A)=>C+A.baseline.totalTokens,0),h=a.reduce((C,A)=>C+A.refined.totalTokens,0),g=h-u,S=a.length===r;return{summary:iR.parse({target:"all_tasks_lower",...m,baselineTokens:u,refinedTokens:h,tokenDelta:g,tokenDeltaPercent:u>0?g/u*100:null,complete:S,passed:S&&m.passedTaskCount===r,cohorts:{adaptation:c(a.filter(C=>C.cohort==="adaptation"),s.adaptation),heldOut:c(a.filter(C=>C.cohort==="held_out"),s.held_out)}}),pairs:a}}const q6=v(["measuring","up_to_date","needs_attention"]),U6=v(["fixed","retained","regressed","unresolved","unavailable"]),AS=l({evaluationRunId:T,attemptKey:T,artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3),transcriptHash:D.nullable(),traceHash:D.nullable()}).strict(),pg=l({level:b(.95),lower:d().finite(),upper:d().finite()}).strict(),z6=l({panelId:T,panelRole:Jm,passLabel:T.nullable(),taskset:Zt,attempted:d().int().nonnegative(),available:d().int().nonnegative(),passed:d().int().nonnegative(),strictSuccess:d().min(0).max(1).nullable(),strictSuccessCi95:pg.nullable(),judgeScore:d().min(0).max(100).nullable(),judgeScoreCi95:pg.nullable()}).strict(),B6=l({schemaVersion:b("openpond.modelCurrencySnapshot.v1"),id:T,contentHash:D,seriesId:T,protocol:l({id:T,revision:d().int().positive(),contentHash:D}).strict(),entryId:T,passLabel:T,parent:lt("kind",[l({kind:b("base_model"),id:T,revision:o().trim().min(1).max(500)}).strict(),l({kind:b("model_version"),id:T,contentHash:D}).strict()]),candidate:l({kind:b("model_version"),id:T,contentHash:D}).strict(),sources:l({evaluationRunIds:p(T).max(1e5),attemptIds:p(T).max(1e6),tasksets:p(Zt).max(1e4),grader:V,judge:V.nullable(),calibration:V.nullable()}).strict(),matches:p(l({key:T,panelId:T,panelRole:Jm,taskId:T,issueFamilyId:T,seed:d().int(),repetition:d().int().nonnegative(),classification:U6,parentPassed:w().nullable(),candidatePassed:w().nullable(),parentAttempt:AS.nullable(),candidateAttempt:AS.nullable()}).strict()).max(1e6),taskIds:l({fixed:p(T).max(1e6),retained:p(T).max(1e6),regressed:p(T).max(1e6),unresolved:p(T).max(1e6),unavailable:p(T).max(1e6)}).strict(),panels:p(z6).max(1e4),metrics:l({knownIssueCoverage:d().min(0).max(1).nullable(),issueFamilyGeneralization:d().min(0).max(1).nullable(),behavioralRetention:d().min(0).max(1).nullable(),currentAcquisitionDelta:d().finite().nullable(),retainedDeltaPoints:d().finite().nullable(),frontierStrictDelta:d().finite().nullable(),pairedPValue:d().min(0).max(1).nullable(),wins:d().int().nonnegative(),ties:d().int().nonnegative(),losses:d().int().nonnegative()}).strict(),statistics:l({matchedAttemptCount:d().int().nonnegative(),strictDelta:d().finite().nullable(),strictDeltaCi95:pg.nullable(),exactPairedBinaryPValue:d().min(0).max(1).nullable(),pairedBootstrapSamples:d().int().positive()}).strict(),criteria:l({allRequiredAttemptsTerminal:w(),criticalCorrectionPassRate:d().min(0).max(1).nullable(),siblingPassRate:d().min(0).max(1).nullable(),behavioralRetentionRate:d().min(0).max(1).nullable(),retainedRegressionPoints:d().finite().nullable(),criticalPriorRegressionCount:d().int().nonnegative(),thresholdRelease:V}).strict(),efficiency:l({inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),costUsd:d().nonnegative().nullable(),latencyMs:d().int().nonnegative(),tokensPerSuccess:d().nonnegative().nullable(),throughputPerHour:d().nonnegative().nullable(),gpuSeconds:d().nonnegative().nullable()}).strict(),invariants:l({systemPromptHash:D,toolSchema:V,application:V,harness:V,runtime:V,grader:V,autoRefinerEnabled:w()}).strict(),evidenceState:q6,evidenceReasons:p(T).max(100),projectedAt:he}).strict(),vu=lt("kind",[l({kind:b("base_model"),id:T,revision:o().trim().min(1).max(500),label:o().trim().min(1).max(300)}).strict(),l({kind:b("model_version"),id:T,label:o().trim().min(1).max(300)}).strict(),l({kind:b("captured_model"),id:T,label:o().trim().min(1).max(300)}).strict()]),cc=ht([l({source:b("evaluation_run").default("evaluation_run"),evaluationRunId:T,attemptId:T,modelLabel:o().trim().min(1).max(300).nullable().default(null),modelVersionId:T.nullable().default(null),reward:d().finite().nullable(),components:ae(o(),d().finite()).default({})}).strict(),l({source:b("imported_response"),modelLabel:o().trim().min(1).max(300),modelVersionId:T.nullable().default(null),response:ie().refine(e=>e!==void 0,"An imported model response is required."),reward:d().finite().nullable().default(null),components:ae(o(),d().finite()).default({})}).strict()]),F6=ht([l({taskId:T,target:vu,attempt:cc}).strict(),l({taskId:T,target:v(["base","current"]).default("current"),attempt:cc}).strict(),l({taskId:T,target:v(["base","current"]).default("current"),evaluationRunId:T,attemptId:T,reward:d().finite().nullable(),components:ae(o(),d().finite()).default({})}).strict().transform(({taskId:e,target:t,...n})=>({taskId:e,target:t,attempt:{source:"evaluation_run",modelLabel:null,modelVersionId:null,...n}}))]);l({schemaVersion:b("openpond.continualLearningDailyBatchManifest.v1"),id:T,seriesId:T,scheduleEntryId:T,dayOrdinal:d().int().positive().max(1e4),sourceTaskset:Zt,taskIds:p(T).min(1).max(1e3),observedAttempts:p(F6).max(1e3).default([]),sourceFileName:o().trim().min(1).max(500).nullable().default(null),availableAt:he}).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}:${W6(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 V6=l({schemaVersion:b("openpond.continualLearningDailyBatch.v1"),id:T,seriesId:T,scheduleEntryId:T,dayOrdinal:d().int().positive().max(1e4),label:o().trim().min(1).max(100),runMode:v(["automatic","manual"]).optional(),source:v(["json_upload","sealed_fixture"]),sourceFileName:o().trim().min(1).max(500).nullable(),sourceTaskset:Zt,tasks:p(l({taskId:T,taskContentHash:D,familyKey:T,disposition:v(["include","defer","exclude"]).nullable(),oracleReview:v(["pending","confirmed","needs_correction"]),note:o().trim().max(2e3),observedAttempt:cc.nullable(),baselineAttempt:cc.nullable().default(null),responses:p(l({target:vu,attempt:cc}).strict()).max(100).default([]),stagedAt:he.nullable().default(null),queuedEntry:Ys.nullable().default(null)}).strict()).min(1).max(1e3),intakeEvaluation:l({status:v(["awaiting","running","ready","failed"]),requestedTargets:p(v(["base","current"])).max(2).default(["base","current"]),requestedPolicies:p(vu).max(100).default([]),runs:p(l({target:vu,runId:T}).strict()).max(100).default([]),baselineRunId:T.nullable(),currentRunId:T.nullable(),currentPolicy:lt("kind",[l({kind:b("base_model"),id:T}).strict(),l({kind:b("model_version"),id:T}).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:v(["pending","reviewed","queued"]),queuedEntry:Ys.nullable(),reviewedBy:T.nullable(),reviewedAt:he.nullable(),availableAt:he,revision:d().int().positive(),createdAt:he,updatedAt:he}).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,i]of e.tasks.entries()){const r=i.responses.map(s=>oR(s.target));new Set(r).size!==r.length&&t.addIssue({code:"custom",path:["tasks",a,"responses"],message:"A task cannot repeat a model response target."})}const n=e.tasks.every(a=>a.disposition!==null&&a.oracleReview!=="pending"&&(a.oracleReview!=="needs_correction"||a.note.length>0));e.status!=="pending"&&!n&&t.addIssue({code:"custom",path:["tasks"],message:"Every task requires a decision and oracle review before the day completes."}),e.status==="queued"!=(e.queuedEntry!==null)&&t.addIssue({code:"custom",path:["queuedEntry"],message:"Only a queued day carries an exact series-entry reference."}),e.status==="pending"&&(e.reviewedAt!==null||e.reviewedBy!==null)&&t.addIssue({code:"custom",path:["reviewedAt"],message:"A pending day cannot carry reviewer completion identity."}),e.status!=="pending"&&(e.reviewedAt===null||e.reviewedBy===null)&&t.addIssue({code:"custom",path:["reviewedAt"],message:"Reviewed identity is required after a day review completes."})}),K6=l({schemaVersion:b("openpond.continualBenchIssueReview.v1"),id:T,seriesId:T,scheduleEntryId:T,passLabel:T,packet:r6,splitManifest:l({id:T,contentHash:D}).strict(),decisions:p(l({taskId:T,disposition:v(["include","defer","exclude"]).nullable(),note:o().trim().max(2e3)}).strict()).min(2).max(1e4),status:v(["pending","reviewed","queued"]),queuedEntry:Ys.nullable(),reviewedBy:T.nullable(),reviewedAt:he.nullable(),revision:d().int().positive(),createdAt:he,updatedAt:he}).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 i=e.decisions.every(r=>r.disposition!==null&&r.note.length>0);e.status!=="pending"&&!i&&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 oR(e){return`${e.kind}:${e.id}`}function W6(e){return typeof e=="string"?e:oR(e)}const ti=o().trim().min(1).max(240),ja=o().trim().min(8).max(256),rR=v(["grpo","dapo","gspo-token"]),Mc=l({id:ti,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:ja}),G6=l({maxRollouts:d().int().positive().max(1e6),maxEnvironmentExecutions:d().int().positive().max(1e6),maxInputTokens:d().int().positive(),maxOutputTokens:d().int().positive(),maxOptimizerSteps:d().int().positive().max(1e6),wallTimeMs:d().int().positive(),maximumCostUsd:d().nonnegative().nullable()}),J6=l({method:b("grpo"),groupSize:d().int().min(2).max(128),normalization:b("group_standardized"),advantageEpsilon:d().positive().max(.01).default(1e-8),loss:rR,clipRange:d().positive().max(1).default(.2),iterations:d().int().min(2).max(16).default(2),microbatchSize:d().int().positive().max(128).default(1),gradientAccumulationSteps:d().int().positive().max(128).default(1),adamw:VC}),sR=l({method:b("ppo"),valueModel:Mc,gamma:d().min(0).max(1),gaeLambda:d().min(0).max(1),policyClip:d().positive().max(1),valueClip:d().positive().max(10),valueLossCoefficient:d().nonnegative().max(10),ppoEpochs:d().int().positive().max(100),minibatchSize:d().int().positive().max(1e5)}),Z6=lt("method",[J6,sR]),lR=l({rewardModelVersion:l({id:ti,contentHash:ja}).strict(),qualificationReport:l({id:ti,contentHash:ja}).strict().nullable().default(null),evaluationReferences:p(l({id:ti,contentHash:ja}).strict()).max(1e3).default([]),checkpoint:l({id:ti,contentHash:ja,objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:p(l({path:o().trim().min(1).max(512),sizeBytes:d().int().positive(),sha256:ja}).strict()).min(4).max(128)}).strict(),runtime:aR,processorRelease:l({id:ti,contentHash:ja}).strict(),rewardComposerRelease:l({id:ti,contentHash:ja}).strict(),executionReceipt:l({id:ti,contentHash:ja}).strict()}).strict(),cR=l({schemaVersion:b("openpond.policyOptimization.v1"),policyModel:Mc,referenceModel:Mc,dataset:l({tasksetId:ti,tasksetHash:ja,split:b("train"),selectionStrategy:v(["stable_hash_top_n","rft_easy_curriculum_v1"]),selectionSeed:d().int(),maxExamples:d().int().positive().max(1e5)}),sampler:l({temperature:d().min(0).max(2),topP:d().min(0).max(1),maxOutputTokens:d().int().positive().max(32768),maxTurns:d().int().positive().max(1e3),concurrency:d().int().positive().max(1e3)}),environment:l({id:ti,version:o().trim().min(1).max(256),toolContractHash:ja}),reward:l({graderId:ti,graderHash:ja,learnedPreference:lR.nullable().default(null)}),kl:l({coefficient:d().nonnegative().nullable(),referenceConstraint:b("fixed_reference")}),budgets:G6,checkpointEverySteps:d().int().positive(),seed:d().int(),evaluationSplit:b("frozen_eval"),optimizer:Z6}),Ee=o().trim().min(1).max(240),Mt=o().trim().min(1),gt=o().trim().min(8).max(256),cd=ae(o(),ie()).default({}),dR=l({schemaVersion:b("openpond.localModelChatConfiguration.v1").default("openpond.localModelChatConfiguration.v1"),profile:v(["efficient","full_harness","custom"]).default("efficient"),systemPromptMode:v(["lean","full_harness","custom"]).default("lean"),customSystemPrompt:o().max(2e4).nullable().default(null),contextWindowTokens:d().int().min(128).max(32768).default(1024),maxOutputTokens:d().int().min(1).max(512).default(64),temperature:d().min(0).max(2).default(0),repetitionPenalty:d().min(.5).max(2).default(1.1),noRepeatNgramSize:d().int().min(0).max(10).default(3),compaction:v(["off","when_needed"]).default("when_needed"),keepWarmSeconds:d().int().min(0).max(3600).default(300),updatedAt:Mt.nullable().default(null)}),Y6=dR.parse({}),Q6=l({schemaVersion:b("openpond.managedAdapterServingProjection.v1"),teamId:Ee.nullable().default(null),source:b("sandbox_managed_rl"),sourceRef:Ee,canonicalArtifactId:Ee.nullable(),canonicalArtifactState:v(["imported_unvalidated","evaluating","promotable","rejected","deleted"]).nullable(),canonicalDeploymentId:Ee.nullable(),canonicalDeploymentState:v(["requested","deploying","ready","degraded","deleting","deleted","failed"]).nullable(),state:v(["pending","imported","ready","failed"]),customerBindingAllowed:w().default(!1),artifactContentHash:gt.nullable().default(null),baseProfileId:Ee.nullable().default(null),publishedAt:Mt.nullable(),lastSyncedAt:Mt,lastError:o().trim().min(1).max(5e3).nullable()});function wae(e){const t=e.managedServing;return!!(t?.source==="sandbox_managed_rl"&&t.canonicalArtifactState==="promotable"&&t.customerBindingAllowed)}function uR(e){return e.state==="ready"&&e.canonicalArtifactState==="promotable"&&e.canonicalDeploymentState==="ready"&&e.customerBindingAllowed&&!!e.teamId&&!!e.canonicalArtifactId&&!!e.canonicalDeploymentId}function _ae(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"&&uR(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_customer_binding",evaluationArtifactId:null,canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null}function Cae(e){const t=e.managedServing;return t?uR(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_serving",canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null:{kind:"source_artifact",canonicalArtifactId:null,canonicalDeploymentId:null}}const Nb="openpond.crossSystemOperations.v1",Rae="1.0.0",mR="openpond.crossSystemTools.v1",X6=["search_crm","query_billing","search_support","run_python"],eV=v(["train","validation","frozen_eval"]),tV=v(["easy","medium","hard"]),nV=v(["renewal_risk_v2"]);v(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]);l({seed:d().int().nonnegative(),split:eV,difficulty:tV,scenarioProfile:nV.optional()});const ih={anyOf:[{type:"string",minLength:1,maxLength:256},{type:"null"}],default:null},oh={type:"integer",minimum:1,maximum:50,default:25},pR=[{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:ih,limit:oh}}},{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:ih,limit:oh}}},{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:ih,limit:oh}}},{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}}}}],dd=pV({schemaVersion:mR,tools:pR}),aV=[`Use only the four registered synthetic Cross-System Operations tools. Contract ${dd}.`,"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(" "),iV=15;function oV(e="auto"){return[aV,"LOCAL TOOL PROTOCOL (strict):","Use only the registered functions below. Never invent, rename, or call any other tool.","For one tool call, output exactly one JSON object and no prose:",'{"type":"tool_call","name":"registered_name","arguments":{}}',"Tool results arrive as exactly one JSON object:",'{"type":"tool_result","name":"registered_name","ok":true,"result":{},"error":null}','After one tool result, either call one registered tool again or answer normally. A JSON final may use {"type":"final","content":"..."}.',`Tool choice: ${JSON.stringify(e)}. Maximum tool turns: ${iV}.`,`Registered tool signatures: ${pR.map(rV).join("; ")}`].join(`
179
+ `)}oV();function rV(e){const t=Gu(e.parameters),n=Gu(t.properties),a=fR(t.required),i=Object.fromEntries(a.map(r=>[r,bu(n[r])]));return`${e.name}(${JSON.stringify(i)})`}function bu(e){const t=Gu(e),n=fg(t.anyOf);if(n.length)return n.map(bu).join("|");const a=fg(t.enum);if(a.length)return a.join("|");if(t.type==="array")return[bu(t.items)];if(t.type==="object"){const i=Gu(t.properties),r=fR(t.required);return Object.fromEntries(r.map(s=>[s,bu(i[s])]))}return typeof t.type=="string"?t.type:"unknown"}function Gu(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function fg(e){return Array.isArray(e)?e:[]}function fR(e){return fg(e).filter(t=>typeof t=="string")}const Ju=v(X6),sV=lt("kind",[l({kind:b("model"),turn:d().int().nonnegative(),content:o().max(1e5)}),l({kind:b("tool_call"),turn:d().int().nonnegative(),callId:o().trim().min(1).max(240),name:Ju,arguments:ae(o(),ie())}),l({kind:b("tool_result"),turn:d().int().nonnegative(),callId:o().trim().min(1).max(240),name:Ju,ok:w(),result:ie(),rows:d().int().nonnegative(),bytes:d().int().nonnegative(),durationMs:d().int().nonnegative(),error:o().trim().min(1).max(2e4).nullable()}),l({kind:b("final"),turn:d().int().nonnegative(),content:o().max(1e5)})]),lV=l({schemaVersion:b(Nb),id:o().trim().min(1).max(240),worldId:o().trim().min(1).max(240),taskId:o().trim().min(1).max(240),toolContractHash:b(dd),modelRef:l({providerId:o().trim().min(1),modelId:o().trim().min(1)}).nullable(),status:v(["completed","budget_exhausted","cancelled","infrastructure_failure"]),steps:p(sV).max(1e3),startedAt:o().trim().min(1),completedAt:o().trim().min(1),infrastructureError:o().trim().min(1).max(2e4).nullable(),metadata:ae(o(),ie()).default({})}),cV=l({schemaVersion:b(Nb),trajectoryId:o().trim().min(1).max(240),outcome:v(["correct","incorrect","parse_failure","budget_exhausted","tool_schema_violation","infrastructure_failure","cancelled"]),reward:d().min(0).max(1.15).nullable(),rewardEligible:w(),exactAnswer:w(),components:l({exactAnswer:d().min(0).max(1),efficiency:d().min(0).max(.1),conciseOutput:d().min(0).max(.05)}),metrics:l({toolCalls:d().int().nonnegative(),rowsRead:d().int().nonnegative(),bytesRead:d().int().nonnegative(),consecutiveRetrievalCalls:d().int().nonnegative(),wallTimeMs:d().int().nonnegative(),parseFailures:d().int().nonnegative(),budgetExhausted:w()}),parsedAnswer:ie().nullable(),feedback:p(o().trim().min(1).max(5e3)).max(100)}),dV=l({id:o().trim().min(1).max(240),type:b("function"),function:l({name:Ju,arguments:o().max(2e4)})}),hR=l({role:v(["system","user","assistant","tool"]),content:o().max(2e5).nullable(),tool_call_id:o().trim().min(1).max(240).optional(),tool_calls:p(dV).max(4).optional()});l({schemaVersion:b(Nb),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:b(dd),approval:l({status:b("approved"),approvedBy:o().trim().min(1).max(240),approvedAt:o().trim().min(1)}),messages:p(hR).min(3).max(1e3)});const uV=l({tasksetTaskId:o().trim().min(1).max(240),environmentTaskId:o().trim().min(1).max(240),family:v(["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:p(Ju).min(1).max(100),toolCallCount:d().int().positive(),messageCount:d().int().min(3),reward:d().min(0).max(1.15),messages:p(hR).min(3).max(1e3)}),mV=l({status:b("approved"),approvedBy:o().trim().min(1).max(240),approvedAt:o().trim().min(1),previewHash:o().trim().min(8).max(256),trajectoryCount:d().int().positive()});l({schemaVersion:b("openpond.crossSystemExpertBootstrapPreview.v1"),tasksetId:o().trim().min(1).max(240),tasksetHash:o().trim().min(8).max(256),tasksetRevision:d().int().positive(),previewHash:o().trim().min(8).max(256),toolContractHash:b(dd),status:v(["ready_for_review","approved"]),approval:mV.nullable(),tasks:p(uV).min(1).max(100)});function pV(e){const t=hg(e);let n=2166136261,a=2654435769;for(let i=0;i<t.length;i+=1){const r=t.charCodeAt(i);n=Math.imul(n^r,16777619),a=Math.imul(a^r,2246822507)}return`${mR}:${TS(n)}${TS(a)}`}function hg(e){return Array.isArray(e)?`[${e.map(hg).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${hg(n)}`).join(",")}}`:JSON.stringify(e)}function TS(e){return(e>>>0).toString(16).padStart(8,"0")}const fV=l({schemaVersion:b("openpond.singleTurnPolicyTrajectory.v1"),id:Ee,taskId:Ee,status:v(["completed","infrastructure_failure"]),promptHash:gt,responseText:o().max(2e6),infrastructureError:o().trim().min(1).max(1e4).nullable(),startedAt:Mt,completedAt:Mt,metadata:cd}),hV=l({schemaVersion:b("openpond.ppoTrajectory.v1"),id:Ee,taskId:Ee,policyModelId:Ee,referenceModelId:Ee,valueModelId:Ee,steps:p(l({index:d().int().nonnegative(),observationHash:gt,actionTokenIds:p(d().int().nonnegative()).min(1),terminated:w(),truncated:w(),reward:d(),policyLogProbability:d(),referenceLogProbability:d(),valuePrediction:d(),return:d(),advantage:d(),mask:d().min(0).max(1)})).min(1).max(1e5),createdAt:Mt}),gV=l({schemaVersion:b("openpond.exactAnswerVerifierResult.v1"),outcome:v(["correct","incorrect","parse_failure","infrastructure_failure"]),graderSetHash:gt,score:d().min(0).max(1).nullable(),passed:w(),rewardEligible:w(),expectedAnswerHash:gt,extractedAnswer:o().max(2e4).nullable(),feedback:p(o().trim().min(1).max(2e4)).max(1e3)}),vV=l({schemaVersion:b("openpond.rolloutTrajectoryReceipt.v1"),id:Ee,jobId:Ee,planId:Ee,tasksetId:Ee,tasksetHash:gt,taskId:Ee,split:b("train"),correlationId:Ee,provider:Ee,providerTrace:l({invocationId:Ee,experimentId:Ee,rolloutId:Ee,runId:Ee,rowId:Ee}),optimizerMethod:v(["grpo","ppo"]).default("grpo"),evidenceLevels:l({requested:v(["trajectory","aggregate","provider_reported"]),observed:v(["trajectory","aggregate","provider_reported"]),providerReported:v(["trajectory","aggregate","provider_reported"])}).default({requested:"trajectory",observed:"trajectory",providerReported:"provider_reported"}),budgetUsage:l({rollouts:d().int().nonnegative(),environmentExecutions:d().int().nonnegative(),inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),optimizerSteps:d().int().nonnegative(),costUsd:d().nonnegative()}).default({rollouts:0,environmentExecutions:0,inputTokens:0,outputTokens:0,optimizerSteps:0,costUsd:0}),environment:l({id:Ee,version:o().trim().min(1).max(256),worldId:Ee,worldHash:gt,toolContractHash:gt}),policy:l({modelId:Ee,checkpointId:Ee.nullable(),completionParametersHash:gt}),status:v(["received","running","succeeded","failed"]),failureClass:v(["policy_failure","parse_failure","tool_schema_violation","budget_exhausted","cancelled","environment_failure","infrastructure_failure"]).nullable(),reward:l({eligible:w(),raw:d().min(0).max(1.15).nullable(),normalized:d().min(0).max(1).nullable(),components:ae(o(),d())}),trajectory:ht([lV,fV,hV]).nullable(),verifier:ht([cV,gV]).nullable(),providerStatus:ae(o(),ie()).default({}),receivedAt:Mt,startedAt:Mt.nullable(),completedAt:Mt.nullable(),updatedAt:Mt}),Pae="dataset-exact-answer",Aae="dataset-exact-answer-v1",Tae="no-tools-v1",Zo=v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),Zm=v(["lora","full"]),Hr=v(["openpond_managed"]),bV=l({schemaVersion:b("openpond.sftRecipe.v1"),method:b("sft"),parameterization:b("lora"),baseModel:l({id:Ee,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:gt}),dataset:l({trainSplit:b("train"),validationSplit:v(["validation","frozen_eval"]),completionOnly:w(),maxSequenceLength:d().int().positive().max(32768),maxExamples:d().int().positive().max(1e5).default(1e3),selectionStrategy:b("stable_hash_top_n").default("stable_hash_top_n"),selectionSeed:d().int().default(17)}),lora:l({rank:d().int().positive().max(256),alpha:d().positive().max(1024),dropout:d().min(0).max(1),targetModules:p(Ee).min(1).max(100)}),optimizer:l({learningRate:d().positive(),epochs:d().positive().max(100),maxSteps:d().int().positive().max(1e6),batchSize:d().int().positive().max(1e4),gradientAccumulationSteps:d().int().positive().max(1e4),seed:d().int()}),resourceLimits:l({cpuThreads:d().int().positive().max(256),memoryBytes:d().int().positive(),wallTimeMs:d().int().positive()})});l({id:Ee,input:ae(o(),ie()),expectedOutput:ae(o(),ie()),tags:p(Ee).max(100).default([])});l({id:Ee,prompt:o().min(1).max(5e5),chosen:o().min(1).max(5e5),rejected:o().min(1).max(5e5),sourceRefs:p(Ee).min(1).max(1e4)});l({id:Ee,input:ae(o(),ie()),tags:p(Ee).max(100).default([])});l({schemaVersion:b("openpond.rewardModelRecipe.v1"),method:b("reward_model"),parameterization:b("lora_with_scalar_head"),runScope:v(["synthetic_smoke","human_preference"]),baseModel:l({id:Ee,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),processorRevision:o().trim().min(1).max(256),chatTemplateHash:gt}).strict(),tasksetRelease:V,preferenceDatasetRelease:V,processorRelease:V,input:l({kind:b("structured_text"),serialization:v(["scenario_input_and_candidate_json_v1","visible_agent_trajectory_v1"]),maxCharacters:d().int().positive().max(5e5)}).strict().default({kind:"structured_text",serialization:"scenario_input_and_candidate_json_v1",maxCharacters:32e3}),lora:l({rank:d().int().positive().max(256),alpha:d().positive().max(1024),dropout:d().min(0).max(1),targetModules:p(Ee).min(1).max(100)}).strict(),heads:l({scalar:b("pooled_hidden_state_linear"),bucket:v(["none","three_class"]).default("three_class")}).strict(),loss:l({ranking:b("bradley_terry"),rankingWeight:d().positive(),bucketWeight:d().nonnegative(),tieWeight:d().nonnegative()}).strict(),optimizer:l({learningRate:d().positive(),maxSteps:d().int().positive().max(1e5),batchSize:d().int().positive().max(1e4),gradientAccumulationSteps:d().int().positive().max(1e4),seed:d().int(),checkpointEverySteps:d().int().positive().max(1e5)}).strict(),resourceLimits:l({wallTimeMs:d().int().positive().max(1440*60*1e3),maxExamples:d().int().positive().max(1e5),maxInputCharacters:d().int().positive().max(5e5).default(32e3),maxImagePixels:d().int().positive().max(1e8).optional(),maximumSpendUsd:d().nonnegative().max(1e5)}).strict()}).superRefine((e,t)=>{e.runScope==="synthetic_smoke"&&(e.optimizer.maxSteps>100||e.resourceLimits.maximumSpendUsd>10)&&t.addIssue({code:"custom",path:["resourceLimits"],message:"Synthetic-smoke Reward Model runs are limited to 100 steps and USD 10."})});const yV=l({schemaVersion:b("openpond.rftRecipe.v1"),method:b("grpo"),parameterization:b("lora"),baseModel:l({id:Ee,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:gt}),dataset:l({trainSplit:b("train"),validationSplit:v(["validation","frozen_eval"]),maxPromptTokens:d().int().positive().max(32768),maxExamples:d().int().positive().max(1e5).default(1e3),selectionStrategy:v(["stable_hash_top_n","rft_easy_curriculum_v1"]).default("stable_hash_top_n")}),lora:l({rank:d().int().positive().max(256)}),rollout:l({groupSize:d().int().min(2).max(64),concurrency:d().int().positive().max(32),maxTurns:d().int().positive().max(100),maxOutputTokens:d().int().positive().max(8192),temperature:d().min(0).max(2),topP:d().positive().max(1),seed:d().int()}),optimizer:l({learningRate:d().positive(),maxSteps:d().int().positive().max(1e5),clipRange:d().positive().max(1).default(.2),iterations:d().int().min(2).max(16).default(2),microbatchSize:d().int().positive().max(64).default(1),gradientAccumulationSteps:d().int().positive().max(64).default(1),advantageEpsilon:d().positive().max(.01).default(1e-8),adamw:VC}),loss:l({method:rR.default("grpo"),klBeta:d().min(0).nullable().default(null)}).default({method:"grpo",klBeta:null}),reward:l({graderId:Ee,graderHash:gt,environmentId:Ee,environmentVersion:o().trim().min(1).max(256),toolContractHash:gt,learnedPreference:lR.nullable().optional()}),resourceLimits:l({wallTimeMs:d().int().positive().max(1440*60*1e3),maxGpuSeconds:d().int().positive().max(10800).optional(),maxRollouts:d().int().positive().max(1e5),maxPayloadBytes:d().int().positive().max(10*1024*1024)}),policyOptimization:cR.nullable().default(null),continuation:l({schemaVersion:b("openpond.crossJobContinuationRequest.v1"),parentArtifact:V,sourceArtifact:l({jobId:Ee,artifactId:Ee,checkpointId:Ee,contentHash:gt}).strict(),optimizerMode:v(["continue","reset"])}).strict().optional()}),SV=l({schemaVersion:b("openpond.dpoRecipe.v1"),method:b("dpo"),parameterization:b("lora"),policyModel:Mc,referenceModel:Mc,dataset:l({trainSplit:b("train"),validationSplit:v(["validation","frozen_eval"]),maxPairs:d().int().positive().max(1e5),maxPromptTokens:d().int().positive().max(32768),maxCompletionTokens:d().int().positive().max(32768),selectionStrategy:b("stable_hash_top_n"),selectionSeed:d().int()}),lora:l({rank:d().int().positive().max(256),alpha:d().positive().max(1024),dropout:d().min(0).max(1),targetModules:p(Ee).min(1).max(100)}),loss:l({variant:b("sigmoid"),beta:d().positive().max(10),labelSmoothing:d().min(0).max(.5).default(0)}),optimizer:l({learningRate:d().positive(),epochs:d().positive().max(100),maxSteps:d().int().positive().max(1e6),batchSize:d().int().positive().max(1e4),gradientAccumulationSteps:d().int().positive().max(1e4),seed:d().int()}),referenceLogprobs:l({cacheSchemaVersion:b("openpond.dpoReferenceLogprobs.v1"),cacheKey:gt,invalidationHash:gt}),resourceLimits:l({cpuThreads:d().int().positive().max(256),memoryBytes:d().int().positive(),wallTimeMs:d().int().positive()})}),xV=l({schemaVersion:b("openpond.ppoRecipe.v1"),method:b("ppo"),parameterization:b("lora"),policyOptimization:cR.extend({optimizer:sR}),lora:l({rank:d().int().positive().max(256),alpha:d().positive().max(1024),dropout:d().min(0).max(1),targetModules:p(Ee).min(1).max(100)}),valueHead:l({initialization:b("policy_hidden_state_linear"),optimizerLearningRate:d().positive(),artifactName:b("value_head.safetensors")}),policyLearningRate:d().positive(),resume:l({checkpointId:Ee.nullable(),policyHash:gt,referenceHash:gt,valueModelHash:gt,optimizerStateHash:gt.nullable()}),resourceLimits:l({cpuThreads:d().int().positive().max(256),memoryBytes:d().int().positive(),wallTimeMs:d().int().positive()})}),kV=l({schemaVersion:b("openpond.unsupportedRecipe.v1"),method:Zo.exclude(["sft","dpo","grpo","ppo"]),parameterization:Zm,unsupportedReason:o().trim().min(1).max(5e3)}),gR=ht([bV,SV,yV,xV,kV]),IV=l({schemaVersion:b("openpond.trainingDestinationCapabilities.v1"),destinationId:Hr,available:w(),methods:p(Zo),parameterizations:p(Zm),modelAllowlist:p(Ee).default([]),maxDatasetBytes:d().int().nonnegative().nullable(),environmentPlacements:p(v(["none","local","remote","colocated","provider_native"])),nonProduction:w(),unavailableReason:o().trim().min(1).max(5e3).nullable(),checkedAt:Mt}),wV=l({destinationId:Hr,available:w(),methods:p(Zo),parameterizations:p(Zm),nonProduction:w(),unavailableReason:o().trim().min(1).max(5e3).nullable()}),_V=l({schemaVersion:b("openpond.baseModelCandidate.v1"),selectionKey:Ee,label:o().trim().min(1).max(500),sourceLabel:o().trim().min(1).max(500),preference:ld,available:w(),nonProduction:w(),unavailableReason:o().trim().min(1).max(5e3).nullable(),methods:p(Zo),executionOptions:p(wV).min(1)}),CV=l({code:Ee,severity:v(["warning","error"]),path:o().trim().max(2e3).nullable(),message:o().trim().min(1).max(5e3)}),RV=l({schemaVersion:b("openpond.trainingCompatibility.v1"),compatible:w(),destinationId:Hr,tasksetId:Ee,recipeMethod:Zo,issues:p(CV),checkedAt:Mt}),PV=ht([xC,v(["destination_unavailable","destination_method_unsupported","destination_model_unsupported","destination_parameterization_unsupported","experimental_destination"])]);l({method:Zo,state:v(["recommended","compatible","needs_dataset_work","destination_unavailable","experimental_destination"]),reasonCodes:p(PV).default([]),reasons:p(o().trim().min(1).max(5e3)).default([]),destinationId:Hr.nullable().default(null)});v(["small","standard","custom","small_experiment"]);const AV=x_,vR=l({schemaVersion:b("openpond.trainingPlan.v1"),id:Ee,modelId:Ee,tasksetId:Ee,tasksetHash:gt,comparisonSeriesEntry:Ys.nullable().optional(),evaluationTasksetRef:Zt.nullable().optional(),harnessRelease:V.nullable().optional(),modelImprovementQualification:V.nullable().optional(),destinationId:Hr,recipe:gR,environmentPlacement:v(["none","local","remote","colocated","provider_native"]),compatibility:RV,dataPolicy:l({exportApproved:w(),approvedSourceIds:p(Ee),retentionDays:d().int().nonnegative().nullable(),region:o().trim().min(1).max(200).nullable()}),estimatedCostUsd:d().nonnegative().nullable(),createdAt:Mt,contentHash:gt}),TV=l({path:o().trim().min(1).max(2e3),sha256:gt,sizeBytes:d().int().nonnegative(),role:v(["manifest","task_data","grader","environment","recipe","policy","provenance"])}),Db=l({schemaVersion:b("openpond.trainingBundle.v1"),id:Ee,planId:Ee,tasksetId:Ee,tasksetHash:gt,recipeHash:gt,files:p(TV).min(1).max(1e6),totalSizeBytes:d().int().nonnegative(),sourceIds:p(Ee),excludedSourceIds:p(Ee),containsRawChats:b(!1),containsSecrets:b(!1),containsHiddenGraderAssets:b(!1),createdAt:Mt,contentHash:gt});l({schemaVersion:b("openpond.trainingBundleExport.v1"),manifest:Db,files:p(l({path:o().trim().min(1).max(2e3),sha256:gt,sizeBytes:d().int().nonnegative(),encoding:b("base64"),content:o()})).min(1),contentHash:gt});l({schemaVersion:b("openpond.trainingPreparedStart.v1"),plan:vR,bundle:Db,approvalActor:Ee.nullable(),preparedAt:Mt});l({schemaVersion:b("openpond.trainingApproval.v1"),evaluationTasksetRef:Zt.nullable().optional(),id:Ee,planId:Ee,bundleHash:gt,harnessRelease:V.nullable().optional(),modelImprovementQualification:V.nullable().optional(),destinationId:Hr,modelId:Ee,method:Zo,parameterization:Zm,maximumCostUsd:d().nonnegative().nullable(),approvedBy:Ee,approvedAt:Mt});l({schemaVersion:b("openpond.trainingJobSourceSnapshot.v1"),evaluationTasksetRef:Zt.nullable().optional(),modelProjectId:Ee,sourceProjectRevision:d().int().positive(),profileId:Ee,taskset:l({id:Ee,revision:d().int().positive(),contentHash:gt}).strict(),tasksetRelease:V,harnessRelease:V,baseModel:ld,method:Zo}).strict();const EV=v(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),bR=l({schemaVersion:b("openpond.trainingJob.v1"),id:Ee,planId:Ee,bundleHash:gt,approvalId:Ee,destinationId:Hr,status:EV,nonProduction:w(),workerPid:d().int().positive().nullable(),startedAt:Mt.nullable(),completedAt:Mt.nullable(),error:o().trim().min(1).max(2e4).nullable(),createdAt:Mt,updatedAt:Mt,metadata:cd}),MV=l({schemaVersion:b("openpond.trainingJobEvent.v1"),id:Ee,jobId:Ee,sequence:d().int().nonnegative(),type:v(["queued","start","progress","metric","checkpoint","cancel","complete","failure","reconcile"]),timestamp:Mt,payload:cd}),jV=l({schemaVersion:b("openpond.sftStepMetric.v1"),step:d().int().nonnegative(),maxSteps:d().int().positive(),timestamp:Mt,epoch:d().nonnegative().nullable(),loss:d().nullable(),learningRate:d().nonnegative().nullable(),gradientNorm:d().nonnegative().nullable(),entropy:d().nonnegative().nullable(),meanTokenAccuracy:d().min(0).max(1).nullable(),preferenceAccuracy:d().min(0).max(1).nullable().default(null),preferenceMargin:d().nullable().default(null),chosenReward:d().nullable().default(null),rejectedReward:d().nullable().default(null),chosenLogProbability:d().nullable().default(null),rejectedLogProbability:d().nullable().default(null),reward:d().nullable().default(null),policyLoss:d().nullable().default(null),advantageLoss:d().nullable().default(null),inputTokensSeen:d().int().nonnegative().nullable(),memoryBytes:d().int().nonnegative().nullable(),elapsedSeconds:d().nonnegative().nullable()}),OV=l({schemaVersion:b("openpond.policyOptimizationMetric.v1"),method:v(["grpo","ppo"]),step:d().int().nonnegative(),timestamp:Mt,learningRate:d().nonnegative().nullable().default(null),policyLoss:d().nullable(),valueLoss:d().nullable(),gradientNorm:d().nonnegative().nullable().default(null),meanReward:d().nullable(),meanReturn:d().nullable(),kl:d().nullable(),behaviorPolicyKlPreUpdate:d().nonnegative().nullable().default(null),entropy:d().nullable(),policyClipFraction:d().min(0).max(1).nullable(),behaviorPolicyClipFractionPreUpdate:d().min(0).max(1).nullable().default(null),valueClipFraction:d().min(0).max(1).nullable(),explainedVariance:d().nullable(),rolloutLearnerLag:d().int().nonnegative().nullable(),inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),environmentExecutions:d().int().nonnegative(),trajectoryCount:d().int().nonnegative().nullable().default(null),costUsd:d().nonnegative().nullable()}),$V=l({schemaVersion:b("openpond.managedTrainingRunEvidence.v2"),provider:Ee,providerRunId:Ee,state:Ee,progress:l({targetOptimizerSteps:d().int().nonnegative(),committedOptimizerSteps:d().int().nonnegative(),skippedOptimizerSteps:d().int().nonnegative()}),reward:l({finalMean:d().nullable(),variance:d().nonnegative().nullable(),minimum:d().nullable(),maximum:d().nullable(),distinctValueCount:d().int().nonnegative(),noSignalGroupCount:d().int().nonnegative(),trajectoryCount:d().int().nonnegative(),eligibleTrajectoryCount:d().int().nonnegative()}),usage:l({inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),environmentExecutions:d().int().nonnegative()}),resource:l({provider:Ee,gpuType:o().trim().min(1).max(300).nullable(),gpuCount:d().int().nonnegative().nullable(),hourlyCostUsd:d().nonnegative().nullable(),durationSeconds:d().nonnegative().nullable(),gpuSeconds:d().nonnegative().nullable()}),cost:l({totalUsd:d().nonnegative().nullable()}),checkpoint:l({id:Ee,policyVersion:d().int().nonnegative(),sha256:gt.nullable(),sizeBytes:d().int().nonnegative().nullable()}).nullable(),movement:l({adapterDeltaNorm:d().nonnegative().nullable()}),evaluations:p(l({reference:l({id:Ee,contentHash:gt}).nullable().optional(),kind:v(["baseline","candidate"]),policyVersion:d().int().nonnegative(),taskCount:d().int().nonnegative().nullable().optional(),targetTaskCount:d().int().nonnegative().nullable().optional(),score:d().nullable(),threshold:d().nullable(),passed:w().nullable()})),canonicalPublication:l({state:Ee.nullable(),artifactId:Ee.nullable()}),syncedAt:Mt}),ES=l({count:d().int().nonnegative(),scoredCount:d().int().nonnegative(),meanScore:d().min(0).max(1).nullable(),passedCount:d().int().nonnegative(),passRate:d().min(0).max(1).nullable()}),MS=l({status:v(["scored","unavailable"]),score:d().min(0).max(1).nullable(),passed:w(),rewardEligible:w(),failureClass:v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:p(o().trim().min(1).max(2e4)).max(1e3),components:p(l({graderId:Ee,score:d().min(0).max(1).nullable(),passed:w(),feedback:o().trim().max(2e4).nullable()})).max(1e3)}),NV=l({taskId:Ee,input:ae(o(),ie()),baseOutput:ae(o(),ie()).nullable(),trainedOutput:ae(o(),ie()).nullable(),baseGrade:MS.nullable(),trainedGrade:MS.nullable()}),DV=l({schemaVersion:b("openpond.trainingEvaluationSummary.v1"),jobId:Ee,tasksetId:Ee,base:ES,trained:ES,meanScoreDelta:d().min(-1).max(1).nullable(),examples:p(NV).max(1e6)});l({schemaVersion:b("openpond.trainingRunDetail.v1"),job:bR,events:p(MV),stepMetrics:p(jV),policyMetrics:p(OV).default([]),managedEvidence:$V.nullable().default(null),evaluation:DV.nullable(),generatedAt:Mt});const HV=l({schemaVersion:b("openpond.trainingArtifact.v1"),id:Ee,jobId:Ee,kind:v(["adapter","checkpoint","metrics","log","manifest","evaluation"]),path:o().trim().min(1).max(4e3),sha256:gt,sizeBytes:d().int().nonnegative(),baseModelId:Ee.nullable(),baseModelRevision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:gt.nullable(),nonProduction:w(),createdAt:Mt,metadata:cd}),LV=l({schemaVersion:b("openpond.modelArtifactLineage.v1"),id:Ee,modelId:Ee,artifactId:Ee,jobId:Ee,tasksetId:Ee,tasksetHash:gt,graderHash:gt,planHash:gt,bundleHash:gt,recipeHash:gt,workerVersion:o().trim().min(1).max(256),trainerVersion:o().trim().min(1).max(256),importedAt:Mt,frozenEvaluationArtifactId:Ee.nullable(),promotable:w(),pinned:w().default(!1),status:v(["imported","rejected"]).default("imported"),rejectedAt:Mt.nullable().default(null),rejectionReason:o().trim().min(1).max(5e3).nullable().default(null),chatConfiguration:dR.default(Y6),managedServing:Q6.nullable().default(null)}),qV=v(["chat_manual","agent","extension","authoring_optimizer"]),UV=l({schemaVersion:b("openpond.modelBinding.v1"),id:Ee,profileId:Ee,role:qV,roleTargetId:Ee,modelArtifactLineageId:Ee,tasksetId:Ee,evaluationArtifactId:Ee.nullable(),status:v(["active","rolled_back"]),priorBindingId:Ee.nullable(),rollbackTargetBindingId:Ee.nullable(),promotedBy:Ee,promotedAt:Mt,rolledBackAt:Mt.nullable(),metadata:cd});l({schemaVersion:b("openpond.trainingActivity.v1"),profileId:Ee,active:w(),activeCounts:l({jobs:d().int().nonnegative(),creations:d().int().nonnegative(),minerRuns:d().int().nonnegative(),datasetImports:d().int().nonnegative()}),revision:gt,generatedAt:Mt});l({schemaVersion:b("openpond.tasksetOperationalState.v1"),tasksetId:Ee,attempts:p(P3),artifacts:p(A3),grades:p(E3),evaluationResults:p(P4).default([]),generatedAt:Mt});const zV=l({schemaVersion:b("openpond.trainingState.v1"),profileId:Ee,sources:p(rC),creations:p(KC),tasksetDrafts:p(Ba).default([]),tasksets:p(Tc),benchmarkRuns:p(If()).default([]),benchmarkComparisons:p(If()).default([]),datasetImports:p(V3).default([]),datasetArtifacts:p(MF).default([]),graderAuditReports:p(M3),evaluationResults:p(If()).default([]),candidates:p(FC),minerConfig:Gm,minerRuns:p(h3).default([]),modelProjects:p(AV).default([]),modelVersions:p(C6).default([]),modelRuns:p(L6).default([]),comparisonSeries:p(b6).default([]),comparisonSeriesEntries:p(w6).default([]),modelCurrencySnapshots:p(B6).default([]),continualBenchIssueReviews:p(K6).default([]),continualLearningDailyBatches:p(V6).default([]),rewardModelVersions:p(R6).default([]),rewardModelRuns:p(A6).default([]),modelTasksets:p(Tc).default([]),plans:p(vR),bundles:p(Db),jobs:p(bR),artifacts:p(HV),models:p(LV),rolloutReceipts:p(vV).default([]),modelBindings:p(UV).default([]),destinations:p(IV),baseModelCandidates:p(_V).default([]),activityRevision:gt.optional(),generatedAt:Mt}),BV=v(["trajectory","reward","demonstration","preference","correction","critique","targeted_feedback","grader_evidence","infrastructure_failure"]),FV=l({datasetRelease:V,harnessRelease:V,evidenceSetRelease:V.nullable(),profileRelease:V.nullable(),model:l({source:o().trim().min(1).max(200),revision:o().trim().min(1).max(500),artifactHash:D.nullable()}).strict(),environmentHash:D,graderHash:D,toolContractHash:D,verificationReceiptHash:D.nullable()}).strict(),yo=l({schemaVersion:b("openpond.learningSignal.v1"),id:T,taskId:T.nullable(),episodeId:T.nullable(),policyVersion:d().int().nonnegative().nullable(),lineage:FV,approved:w(),verifier:v(["deterministic","model_judge","human","none"]),createdAt:he,contentHash:D,metadata:ae(o(),ie()).default({})}).strict(),VV=yo.extend({kind:b("trajectory"),payload:l({traceRef:o().trim().min(1).max(2e3),traceHash:D,terminal:w(),failureClass:v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),optimizerSample:$_.nullable().optional()}).strict()}).strict(),KV=yo.extend({kind:b("reward"),payload:l({reward:d().finite(),components:ae(o(),d().finite()),eligible:w(),graderEvidenceRefs:p(T).max(1e3)}).strict()}).strict(),WV=yo.extend({kind:b("demonstration"),payload:l({prompt:o().max(5e5),response:o().max(1e6)}).strict()}).strict(),GV=yo.extend({kind:b("preference"),payload:l({prompt:o().max(5e5),chosen:o().max(1e6),rejected:o().max(1e6),rationale:o().max(5e5).nullable()}).strict()}).strict(),JV=yo.extend({kind:b("correction"),payload:l({original:o().max(1e6),corrected:o().max(1e6),rationale:o().max(5e5).nullable()}).strict()}).strict(),ZV=yo.extend({kind:b("critique"),payload:l({response:o().max(1e6),critique:o().max(5e5),severity:v(["note","warning","error"])}).strict()}).strict(),YV=yo.extend({kind:b("targeted_feedback"),payload:l({turnIndex:d().int().nonnegative(),target:v(["reasoning","tool","answer","policy"]),feedback:o().max(5e5)}).strict()}).strict(),QV=yo.extend({kind:b("grader_evidence"),payload:l({graderId:T,score:d().finite().nullable(),passed:w(),privilegedArtifactRefs:p(o().trim().min(1).max(2e3))}).strict()}).strict(),XV=yo.extend({kind:b("infrastructure_failure"),approved:b(!1),verifier:b("none"),payload:l({code:T,phase:T,retryable:w(),rewardEligible:b(!1)}).strict()}).strict(),yR=lt("kind",[VV,KV,WV,GV,JV,ZV,YV,QV,XV]);l({schemaVersion:b("openpond.learningSignalBatch.v1"),manifestId:T,manifestHash:D,sequence:d().int().nonnegative(),signals:p(yR).min(1).max(1e5),contentHash:D}).strict();const eK=l({id:T,turn:d().int().nonnegative(),kind:v(["message","tool_call","terminal"]),name:T.nullable(),arguments:ae(o(),ie()),content:o().max(1e6).nullable(),contentHash:D}).strict(),tK=l({actionId:T,turn:d().int().nonnegative(),terminal:w(),output:ae(o(),ie()),artifactRefs:p(o().trim().min(1).max(2e3)),contentHash:D}).strict(),nK=l({sequence:d().int().nonnegative(),type:v(["created","reset","action","observation","terminal","graded","feedback","failure","collected","destroyed"]),timestamp:he,payloadHash:D,metadata:ae(o(),ie()).default({})}).strict(),jS=l({graderId:T,graderVersion:o().trim().min(1).max(200),score:d().finite().nullable(),passed:w(),rewardEligible:w(),failureClass:v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:p(o().max(5e5)),visibleEvidenceRefs:p(o().trim().min(1).max(2e3)),privilegedEvidenceRefs:p(o().trim().min(1).max(2e3)),contentHash:D}).strict();l({schemaVersion:b("openpond.harnessRunTrace.v1"),manifest:V,taskId:T,seed:o().trim().min(1).max(500),events:p(nK).max(1e6),actions:p(eK).max(1e5),observations:p(tK).max(1e5),graderEvidence:p(jS).max(1e4),learningSignals:p(yR).max(1e5),terminal:w(),failureClass:jS.shape.failureClass,artifactHash:D,contentHash:D}).strict();const aK=o().trim().min(1).max(2e3).refine(e=>{const t=e.replaceAll("\\","/");return!t.startsWith("/")&&!t.includes("\0")&&!t.split("/").some(n=>!n||n==="."||n==="..")},"path must be a safe relative path"),iK=v(["instruction","skill","skill_resource","agent","workflow","dependency_lock","program","asset"]),oK=l({id:T,kind:iK,path:aK,parentId:T.nullable(),mediaType:o().trim().min(1).max(200),visibility:v(["policy","verifier","host_private"]),portability:v(["portable","local_only"])}).strict().superRefine((e,t)=>{e.kind==="skill_resource"!=(e.parentId!==null)&&t.addIssue({code:"custom",message:"only Skill resources require parentId",path:["parentId"]})});l({schemaVersion:b("openpond.harnessSourceManifest.v1"),name:o().trim().min(1).max(240),files:p(oK).min(2).max(1e5),toolDeclarations:p(Jc).max(200),capabilityRequirements:p(Cv).max(200),lifecycle:R1,graderInterface:P1,runtimeProtocol:o().trim().min(1).max(500),metadata:ae(o(),ie()).default({})}).strict().superRefine((e,t)=>{const n=new Set,a=new Map,i=new Set;for(const[r,s]of e.files.entries())n.has(s.id)&&t.addIssue({code:"custom",message:"file ids must be unique",path:["files",r,"id"]}),i.has(s.path)&&t.addIssue({code:"custom",message:"file paths must be unique",path:["files",r,"path"]}),n.add(s.id),a.set(s.id,s.kind),i.add(s.path);for(const[r,s]of e.files.entries())s.parentId&&!n.has(s.parentId)?t.addIssue({code:"custom",message:"parentId must reference a declared Skill",path:["files",r,"parentId"]}):s.parentId&&a.get(s.parentId)!=="skill"&&t.addIssue({code:"custom",message:"parentId must reference a primary Skill file",path:["files",r,"parentId"]});e.files.filter(r=>r.kind==="dependency_lock").length!==1&&t.addIssue({code:"custom",message:"exactly one dependency lock is required",path:["files"]}),e.files.filter(r=>r.kind==="program").length!==1&&t.addIssue({code:"custom",message:"exactly one Harness program is required",path:["files"]})});l({rootPath:o(),sourcePath:o(),binding:YD,currentRelease:L0,releases:p(L0),transitions:p(QD)}).strict();l({profile:E1,activate:w().default(!0),reason:o().trim().min(1).max(1e4),actor:o().trim().min(1).max(240).default("local-user"),authoringSkillHash:o().regex(/^[a-f0-9]{64}$/).nullable().default(null)}).strict();l({release:V,reason:o().trim().min(1).max(1e4),actor:o().trim().min(1).max(240).default("local-user")}).strict();const rK=l({schemaVersion:b("openpond.trainingEngineCapabilities.v1"),adapterId:T,available:w(),methods:p(o().trim().min(1).max(100)),signalKinds:p(BV),modelFamilies:p(o().trim().min(1).max(200)),precisions:p(v(["fp32","fp16","bf16","tf32","int8","int4"])),topologies:p(o().trim().min(1).max(200)),workerProtocolVersion:o().trim().min(1).max(200),upstreamRevision:o().trim().min(1).max(500),workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/).nullable().default(null),capabilityReceipt:D,checkedAt:he,unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict(),sK=l({schemaVersion:b("openpond.computeTargetCapabilities.v1"),adapterId:T,kind:v(["local","ssh","managed","custom"]),provider:T.nullable(),available:w(),devices:p(l({id:T,kind:v(["cpu","gpu","accelerator"]),vendor:o().trim().min(1).max(200),name:o().trim().min(1).max(500),memoryBytes:d().int().nonnegative().nullable(),runtime:o().trim().min(1).max(200)}).strict()),supportsWorkerImages:w(),supportsArtifactTransfer:w(),supportsCancellation:w(),capabilityReceipt:D,checkedAt:he,unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict(),lK=l({schemaVersion:b("openpond.harnessRuntimeCapabilities.v1"),adapterId:T,available:w(),placements:p(v(["local","remote","colocated","provider_native"])),lifecycle:p(v(["create","reset","step","grade","collect","destroy"])),deterministicReplay:w(),privilegedIsolation:w(),capabilityReceipt:D,checkedAt:he,unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict();l({schemaVersion:b("openpond.resolvedTrainingPlan.v1"),manifest:y3,recipe:gR,runtime:Rb,compute:Pb,engine:Ab,execution:l({trainingPlanId:T,approvalId:T}).strict().nullable(),maximumSpendUsd:d().nonnegative().nullable(),approvalHash:D,contentHash:D}).strict().superRefine((e,t)=>{const n=[["runtime",e.runtime,e.manifest.runtimeTarget],["compute",e.compute,e.manifest.computeTarget],["engine",e.engine,e.manifest.engine]];for(const[a,i,r]of n)JSON.stringify(i)!==JSON.stringify(r)&&t.addIssue({code:"custom",path:[a],message:`${a} must exactly match the Harness Run Manifest`});e.recipe.method!==e.manifest.recipe.method&&t.addIssue({code:"custom",path:["recipe","method"],message:"Recipe method must match the Harness Run Manifest"}),e.approvalHash!==e.manifest.approval.approvalHash&&t.addIssue({code:"custom",path:["approvalHash"],message:"Approval hash must match the Harness Run Manifest"}),e.maximumSpendUsd!==e.manifest.approval.maximumSpendUsd&&t.addIssue({code:"custom",path:["maximumSpendUsd"],message:"Maximum spend must match the Harness Run Manifest"})});l({schemaVersion:b("openpond.adapterValidationReceipt.v1"),adapterId:T,valid:w(),issues:p(l({code:T,path:o().trim().max(2e3).nullable(),message:o().trim().min(1).max(5e3)}).strict()),capabilityReceipt:D,planHash:D,createdAt:he,contentHash:D}).strict();l({runId:T,adapterId:T,protocolVersion:v(["openpond.training.v2","adapter.native.v1"]).default("adapter.native.v1"),routeFamily:v(["training_v2","adapter_native"]).default("adapter_native"),routeId:T.optional(),providerJobId:o().trim().min(1).max(1e3).nullable(),tenantId:T.optional(),leaseId:T.nullable(),manifestHash:D.optional(),inputBundleHash:D.optional(),createdAt:he}).strict();l({runId:T,state:v(["queued","preparing","running","cancelling","cancelled","succeeded","failed"]),phase:o().trim().min(1).max(200),progress:d().min(0).max(1).nullable(),rolloutProgress:l({groupsCompleted:d().int().nonnegative(),groupsTarget:d().int().nonnegative(),optimizerUpdatesApplied:d().int().nonnegative(),optimizerUpdatesSkipped:d().int().nonnegative()}).strict().optional(),updatedAt:he,errorCode:T.nullable()}).strict();l({runId:T,manifestHash:D,artifacts:p(l({kind:v(["checkpoint","adapter","metrics","trace","evaluation","receipt"]),objectRef:o().trim().min(1).max(2e3),sha256:D,sizeBytes:d().int().nonnegative(),metadata:ae(o(),ie()).optional()}).strict()),contentHash:D}).strict();const gg=v(["ready","model_download_required","compute_setup_required","provider_managed","unsupported"]),cK=l({id:T,label:o().trim().min(1).max(500),description:o().trim().min(1).max(2e3),destinationId:T,computeAdapterId:T,runtimeAdapterId:T,engineAdapterId:T,methods:p(o().trim().min(1).max(100)),capabilityPills:p(o().trim().min(1).max(100)),executionMode:v(["local_worker","provider_native"]),approvalPolicy:l({providerId:jr,providerLabel:o().trim().min(1).max(200),settingsActionLabel:o().trim().min(1).max(500).nullable(),exportApprovalRequired:w(),exportDescription:o().trim().min(1).max(2e3).nullable(),preparationRequired:w(),minimumSpendUsd:d().nonnegative(),maximumSpendUsd:d().positive(),defaultMaximumSpendUsd:d().positive(),minimumRetentionDays:d().int().positive(),maximumRetentionDays:d().int().positive(),defaultRetentionDays:d().int().positive(),methodRequirement:o().trim().min(1).max(2e3).nullable()}).strict().nullable(),limits:l({maximumSequenceLength:d().int().positive(),maximumOutputTokens:d().int().positive(),maximumTrainingExamples:d().int().positive().nullable()}).strict(),defaults:l({loraRank:d().int().positive(),maxSteps:d().int().positive(),rolloutGroupSize:d().int().min(2).max(32),rolloutConcurrency:d().int().positive().max(32),rolloutOutputTokens:d().int().positive()}).strict(),available:w(),unavailableReason:o().trim().min(1).max(5e3).nullable()}).strict(),dK=l({selectionKey:T,label:o().trim().min(1).max(500),source:v(["local","builtin","huggingface","managed","search"]),modelId:o().trim().min(1).max(1e3),revision:o().trim().min(1).max(500).nullable(),tokenizerRevision:o().trim().min(1).max(500).nullable(),chatTemplateHash:D.nullable(),modelAssetId:T.nullable(),expectedBytes:d().int().nonnegative().nullable(),cached:w(),known:w(),searchResolved:w(),computeAdapterIds:p(T),engineAdapterIds:p(T),preparationState:gg,reason:o().trim().min(1).max(5e3).nullable(),compatibilities:p(l({targetId:T,methods:p(o().trim().min(1).max(100)),state:gg,reason:o().trim().min(1).max(5e3).nullable()}).strict())}).strict();l({schemaVersion:b("openpond.trainingCatalog.v1"),models:p(dK).max(1e5),engines:p(rK),compute:p(sK),runtimes:p(lK),targets:p(cK),generatedAt:he,contentHash:D}).strict();l({schemaVersion:b("openpond.trainingPreparationPlan.v1"),modelRunId:T,state:gg,reason:o().trim().min(1).max(5e3).nullable(),runtime:Rb.nullable(),compute:Pb.nullable(),engine:Ab.nullable(),downloads:p(l({kind:b("model"),label:o().trim().min(1).max(500),expectedBytes:d().int().nonnegative(),digest:o().trim().min(8).max(500),cached:w(),state:v(["ready","required","downloading","cancelled","failed"]),progress:d().min(0).max(1).nullable(),cancellable:w(),diskImpactBytes:d().int().nonnegative()}).strict()),dataMovement:p(l({direction:v(["upload","download","none"]),label:o().trim().min(1).max(500),bytes:d().int().nonnegative().nullable()}).strict()),quoteUsd:d().nonnegative().nullable(),maximumSpendUsd:d().nonnegative().nullable(),retentionDays:d().int().nonnegative().nullable(),sideEffectsStarted:b(!1),contentHash:D}).strict();const Hb=32e3,uK=v(["steer","message","followup","queued","result"]),mK=v(["pending","included","resolved","cancelled","rejected"]),SR=l({id:o().min(1),sequence:d().int().nonnegative(),sessionId:o().min(1),senderSessionId:o().min(1).nullable(),senderKind:v(["user","task","runtime"]),kind:uK,body:o().trim().min(1).max(Hb),payload:ae(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:p(o()),state:mK,revision:d().int().positive(),createdAt:o(),updatedAt:o(),error:o().nullable()}).strict();l({expectedTurnId:o().trim().min(1),idempotencyKey:o().trim().min(1).max(200),prompt:o().trim().min(1).max(Hb)}).strict();lt("action",[l({action:b("resume"),expectedRevision:d().int().positive()}).strict(),l({action:b("cancel"),expectedRevision:d().int().positive()}).strict(),l({action:b("edit"),expectedRevision:d().int().positive(),body:o().trim().min(1).max(Hb)}).strict(),l({action:b("steer"),expectedRevision:d().int().positive(),expectedTurnId:o().trim().min(1)}).strict()]);const pK=l({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:d().int().nonnegative(),deadline:o(),state:v(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:o(),updatedAt:o()}).strict();l({sessionId:o(),activeTurnId:o().nullable(),acceptingInput:w(),paused:w(),inputs:p(SR),waits:p(pK)});var xR=o().regex(/^[a-f0-9]{64}$/),fK=l({request:ml,maximumCostUsd:d().finite().positive().max(1e4),graders:p(Mi).min(1).max(100),admissionRequestHash:xR.optional(),sourceExperimentId:o().trim().min(1).max(200).optional()}).strict(),hK=fK.extend({configurationHash:xR}).strict();$C.extend({configuration:hK}).strict();var Eae=l({teamId:o().trim().min(1).max(240),items:p(l({name:o().trim().min(1).max(500),source:td,ready:w(),reason:o().min(1).max(2e3).nullable()}).strict()).max(8),nextCursor:o().min(1).max(8192).nullable()}).strict();o().trim().min(1).max(200);var ql=o().trim().min(1).max(500),kR=o().regex(/^[a-f0-9]{64}$/),gK=l({schemaVersion:b("openpond.experimentCaseInspection.v1"),teamId:ql,executionId:ql,manifestHash:kR,receiptId:ql,taskId:ql,seed:o().min(1),input:ae(o(),ie()).nullable(),output:ie().nullable(),error:o().nullable(),events:p(ae(o(),ie())).max(25),nextEventCursor:ql.nullable(),eventCount:d().int().nonnegative()}).strict();gK.extend({contentHash:kR}).strict();function vK(e){return JSON.stringify(e.release?["reward",e.release.id,e.release.revision,e.release.contentHash,e.feedbackKey]:["dataset",e.id,e.version,e.contentHash,e.feedbackKey])}function bK(e){const t=new Map;for(const n of e){const a=vK(n),i=t.get(a);i?i.aliases.push(n):t.set(a,{key:a,grader:n,aliases:[n]})}return[...t.values()]}function Mae(e){const t=bK(e),n=new Map;for(const a of t){const i=n.get(a.grader.feedbackKey);if(i&&i!==a.key)throw new Error(`Different selected grader releases use feedback key "${a.grader.feedbackKey}". Select one, or publish graders with distinct feedback keys.`);n.set(a.grader.feedbackKey,a.key);const r=JSON.stringify(a.grader.mappings??[]);if(a.aliases.some(s=>JSON.stringify(s.mappings??[])!==r))throw new Error(`Aliases of grader "${a.grader.feedbackKey}" have different field mappings. Select one alias and review its mappings.`)}return t.map(a=>a.grader)}var Sr=o().trim().min(1).max(240),jae=l({profileRef:l({source:v(["local","github","openpond_git"]),repositoryId:Sr,profileId:Sr}).strict(),sourceRevision:o().min(1).max(500),harnessRelease:De,catalogHash:o().regex(/^[a-f0-9]{64}$/).nullable(),definitions:p(Ww).max(1e3),suites:p(Gw).max(100),runs:p(l({profileRef:l({source:v(["local","github","openpond_git"]),repositoryId:Sr,profileId:Sr}).strict(),manifest:Lm,metric:Wv,gradeRefs:p(De),receiptRefs:p(De),passRate:d().min(0).max(1),passed:w(),completedAt:nn(),contentHash:o().regex(/^[a-f0-9]{64}$/)}).strict()).max(1e3),comparisons:p(q4).max(1e3),suiteRuns:p(K4).max(1e3),reports:p(F4).max(1e3)}).strict();l({teamId:Sr,profileRepositoryId:Sr,trainingProjectId:Sr.optional()}).strict();var Zu=yt.shape.id,yK=l({schemaVersion:b("openpond.modelBatchReviewInspection.v1"),packageHash:o().regex(/^[a-f0-9]{64}$/),definition:nd,binding:Em,evidence:p(Om).min(1).max(1e4),decisions:p(nb).min(1).max(1e4)}).strict(),Oae=l({schemaVersion:b("openpond.modelBatchReviewRequest.v1"),operationId:Zu,modelId:Zu,expectedModelRevision:d().int().positive(),tasksetRef:yt,rewardBindingRef:yt.nullable(),definition:l({name:o().trim().min(1).max(500).optional(),instructions:o().trim().min(1).max(2e4).optional(),inputSchema:Jt.optional(),outputSchema:Jt.optional(),requiredOutputs:nd.shape.requiredOutputs}).strict(),examples:p(l({evidence:yt,input:Jt.optional(),expected:Jt.nullable().optional(),evaluatorContext:Jt.nullable().optional(),proposedTarget:Jt.nullable().optional()}).strict()).max(1e4)}).strict(),SK=l({schemaVersion:b("openpond.modelBatchReviewReceipt.v1"),operationId:Zu,modelId:Zu,source:jm,evidence:p(Om).min(1).max(1e4),proposals:p(a_).max(1e4)}).strict();p(l({asset:to,sourcePath:o().min(1)}).strict()).max(1e4);l({draft:Ba,filePaths:p(l({assetId:o().min(1),paths:p(ad).min(1).max(1e4)}).strict()).max(1e4)}).strict();const pn=o().trim().min(1).max(200),Xn=o().regex(/^[a-f0-9]{64}$/),IR=v(["queued","running","cancelling","completed","failed","cancelled","interrupted"]),wR=l({providerId:v(["openpond","custom-openai-compatible","claude-code"]),modelId:o().trim().min(1).max(500),configurationHash:Xn,maxOutputTokens:d().int().positive().max(262144),temperature:d().min(0).max(2).optional(),topP:d().positive().max(1).optional(),messages:p(l({role:v(["system","user","assistant"]),content:o().max(262144)}).strict()).max(200)}).strict();l({configuration:Cb,package:Rr}).strict();l({configuration:Cb,expectedPackageHash:Xn.optional()}).strict();l({schemaVersion:b("openpond.localExperimentDefinition.v1"),location:b("local"),id:pn,teamId:pn,ownerActorId:pn,revision:d().int().positive(),configuration:Cb,model:wR,packageHash:Xn,graders:p(Mi).min(1).max(100),availableGraders:p(Mi).min(1).max(1e3),createdAt:nn(),updatedAt:nn(),contentHash:Xn}).strict();l({operationId:pn,definition:rd}).strict();l({teamId:pn,id:pn}).strict();l({teamId:pn,projectId:pn.optional(),status:IR.optional(),datasetHash:Xn.optional(),search:o().max(100).optional(),afterId:pn.optional(),limit:d().int().min(1).max(100).default(30)}).strict();const Lb=l({schemaVersion:b("openpond.localExperimentExecution.v1"),location:b("local"),id:pn,teamId:pn,ownerActorId:pn,operationId:pn,definition:rd,kind:v(["target","scoring"]),executionHash:Xn,sourceExecution:l({id:pn,executionHash:Xn}).strict().nullable(),packageHash:Xn,maximumCostUsd:d().finite().positive(),status:IR,createdAt:nn(),completedAt:nn().nullable(),counts:l({pending:d().int().nonnegative(),running:d().int().nonnegative(),completed:d().int().nonnegative(),failed:d().int().nonnegative(),cancelled:d().int().nonnegative(),unknown:d().int().nonnegative()}).strict(),usage:l({knownCostUsd:d().finite().nonnegative(),costUsd:d().finite().nonnegative().nullable(),heldUsd:d().finite().nonnegative(),uncertainRequests:d().int().nonnegative()}).strict(),cleanupComplete:w(),error:o().max(2e3).nullable()}).strict(),xK=Lb.omit({definition:!0});function qb(e,t){e.kind==="scoring"!=(e.sourceExecution!==null)&&t.addIssue({code:"custom",message:"Only retained scoring passes name an original execution."}),["completed","failed","cancelled","interrupted"].includes(e.status)&&(!e.completedAt||e.counts.pending||e.counts.running)&&t.addIssue({code:"custom",message:"Terminal local execution requires complete population accounting."}),["completed","cancelled"].includes(e.status)&&!e.cleanupComplete&&t.addIssue({code:"custom",message:"Successful completion or cancellation requires confirmed local transport cleanup."}),e.usage.uncertainRequests>0&&e.usage.costUsd!==null&&t.addIssue({code:"custom",message:"Uncertain provider charges cannot claim a measured total."})}Lb.superRefine(qb);const ud=xK.superRefine(qb);l({configuration:sd,package:Rr}).strict();const $ae=l({configuration:sd,expectedPackageHash:o().regex(/^[a-f0-9]{64}$/).optional()}).strict(),OS=l({configuration:sd,model:wR,packageHash:o().regex(/^[a-f0-9]{64}$/),graders:p(Mi).min(1).max(100),availableGraders:p(Mi).min(1).max(1e3),retainedConfigurationHash:o().regex(/^[a-f0-9]{64}$/).optional(),configurationHash:o().regex(/^[a-f0-9]{64}$/)}).strict().superRefine((e,t)=>{const{configurationHash:n,...a}=e;st(a)!==n&&t.addIssue({code:"custom",message:"Local configuration snapshot bytes changed."})}),{definition:Nae,...kK}=Lb.shape,Ub=l({...kK,kind:b("target"),...OS.shape}).strict().superRefine((e,t)=>{const n={configuration:e.configuration,model:e.model,packageHash:e.packageHash,graders:e.graders,availableGraders:e.availableGraders,...e.retainedConfigurationHash?{retainedConfigurationHash:e.retainedConfigurationHash}:{},configurationHash:e.configurationHash};qb(e,t),OS.safeParse(n).success||t.addIssue({code:"custom",message:"Local Experiment configuration changed."}),(e.operationId!==e.configuration.operationId||e.teamId!==e.configuration.request.teamId||e.maximumCostUsd!==e.configuration.maximumCostUsd)&&t.addIssue({code:"custom",message:"Local Experiment differs from its sealed admission."})}),Dae=l({items:p(Ub).max(100),nextCursor:o().nullable()}).strict();l({teamId:o().min(1).max(200),id:o().min(1).max(200),configurationHash:o().regex(/^[a-f0-9]{64}$/).optional()}).strict();const IK=l({operationId:pn,execution:l({id:pn,executionHash:Xn}).strict(),graderPackage:Rr,graders:p(_b).min(1).max(100),maximumCostUsd:d().finite().positive().max(1e4)}).strict(),Hae=IK.omit({graderPackage:!0}),wK=eb,_K=l({sessionId:pn,turnId:pn,source:Ks,profileRef:Ni,admissionHash:Xn,modelConfigurationHash:Xn,traceHash:Xn,runtimeEventRefs:p(pn).max(1e4),startedAt:nn(),completedAt:nn(),outputHash:Xn,partialOutputAvailable:w()}).strict(),_R=l({receiptId:pn,taskId:pn,seed:o(),status:v(["pending","running","completed","failed","cancelled","unknown"]),input:ae(o(),ie()),policyVisibleContext:ae(o(),ie()),output:o().nullable(),messages:p(ie()).max(4002),grade:TC.nullable(),error:o().nullable(),native:wK.optional(),profileNative:_K.optional(),externalProcess:j5.optional()}).strict(),Lae=l({execution:ht([Ub,ud]),cases:p(_R).max(1e4),contentHash:Xn}).strict(),CK=l({items:p(l({sequence:d().int().positive(),type:o().min(1),payload:ie()}).strict()).max(500),nextCursor:d().int().positive().nullable()}).strict(),qae=l({location:b("local"),execution:ht([Ub,ud]),case:_R,trace:CK}).strict(),Uae=l({items:p(ud).max(100),nextCursor:pn.nullable()}).strict(),zae=l({execution:ud,graders:p(Mi).min(1).max(100),graderPackageHash:Xn}).strict(),$S=l({execution:ud,manifest:ro,result:so}).strict().superRefine((e,t)=>{try{if(wr(e),e.manifest.id!==e.execution.id||e.manifest.teamId!==e.execution.teamId||e.manifest.lineage?.execution.id!==(e.execution.sourceExecution?.id??e.execution.id)||e.manifest.lineage.execution.contentHash!==(e.execution.sourceExecution?.executionHash??e.execution.executionHash)||e.manifest.lineage.scoringPassId!==(e.execution.kind==="scoring"?e.execution.id:null)||e.manifest.maximumCostUsd!==e.execution.maximumCostUsd)throw new Error("Portable evidence differs from its retained local execution.")}catch(n){t.addIssue({code:"custom",message:n instanceof Error?n.message:"Local portable evidence verification failed."})}}),Bae=l({location:b("local"),baseline:$S,candidate:$S}).strict(),ps=o().trim().min(1).max(240),rh=o().regex(/^[a-f0-9]{64}$/),Fae=l({location:b("local"),harnesses:p(l({id:ps,name:o().max(500),source:td}).strict()).max(100),profiles:p(l({id:ps,name:o().max(500),profileRef:Ni,sourceRevision:o().min(1).max(500),harnessRelease:l({id:ps,contentHash:rh}).strict(),definitionId:ps,definitionHash:rh,taskset:l({id:ps,revision:d().int().positive(),contentHash:rh}).strict(),taskCount:d().int().nonnegative(),taskIds:p(ps).max(1e4),seeds:p(o()).max(1e4)}).strict()).max(100)}).strict(),RK=l({id:mm(),action:v(["advanced-refiner-start","experiment-evaluation-schedule"]),intentHash:o().regex(/^[a-f0-9]{64}$/),createdAt:nn(),reviewedIntent:ie().nullable(),command:ie().nullable(),phase:v(["reviewed","dispatching"]).nullable(),recoveryReady:w()}).strict().superRefine((e,t)=>{e.recoveryReady!==(e.reviewedIntent!==null&&e.command!==null&&e.phase!==null)&&t.addIssue({code:"custom",message:"Only the actual retained intent and command admit automatic recovery."})}),Vae=l({items:p(RK).max(100),nextCursor:mm().nullable()}).strict();function PK(e,t,n){const a=new Headers;a.set("Accept","text/event-stream"),a.set("Authorization",`Bearer ${e.token}`);const i=new URL(`${e.serverUrl.replace(/\/$/,"")}/v1/events`);return n!==void 0&&Number.isSafeInteger(n)&&n>0&&i.searchParams.set("afterSequence",String(n)),{url:i.toString(),init:{headers:a,signal:t}}}function AK(e){return Math.min(500*2**Math.max(0,e),1e4)}async function TK(e,t,n,a){CR(e);const i=e.body.getReader(),r=new TextDecoder;let s="";for(;!a?.aborted;){const{done:c,value:m}=await i.read();if(c){s+=r.decode();break}s+=r.decode(m,{stream:!0});let u=s.indexOf(`
180
+
181
+ `);for(;u>=0;){const h=s.slice(0,u);s=s.slice(u+2),DS(h,t,n),u=s.indexOf(`
182
+
183
+ `)}}!a?.aborted&&s.trim()&&DS(s,t,n)}function CR(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 EK(e,t,n,a,i={}){const r=new AbortController,s=i.fetchImpl??fetch,c=i.reconnectDelayMs??AK;let m=NS(i.afterSequence),u=!1;return(async()=>{let h=0;for(;!r.signal.aborted;)try{const g=PK(e,r.signal,m),S=await s(g.url,g.init);if(CR(S),u=!0,h=0,await TK(S,k=>{const C=NS(k.sequence);C>0&&C<=m||(C>0&&(m=C),t(k))},a,r.signal),u=!1,r.signal.aborted)break;throw new Error("event stream ended")}catch(g){if(u=!1,r.signal.aborted)break;n(g),await MK(c(h),r.signal),h+=1}})().catch(()=>{}),{close(){r.abort()},isOpen(){return u}}}function NS(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:0}function DS(e,t,n){let a="message";const i=[];for(const r of e.split(`
184
+ `))r.startsWith(":")||(r.startsWith("event: ")&&(a=r.slice(7).trim()),r.startsWith("data: ")&&i.push(r.slice(6)));if(a==="ready"){n?.();return}if(!(a!=="runtime"||i.length===0))try{t(JSON.parse(i.join(`
185
+ `)))}catch{}}async function MK(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 jK extends Error{constructor(t,n){super(t),this.status=n,this.name="ApiRequestError"}status}function HS(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 LS=new WeakMap,qS=new WeakMap,Zd=new WeakMap;let OK=0;async function B(e,t,n){if(t==="/v1/preferences"&&typeof n?.body=="string"){const i=(Zd.get(e)??Promise.resolve()).catch(()=>{}).then(()=>US(e,t,n));Zd.set(e,i);try{return await i}finally{Zd.get(e)===i&&Zd.delete(e)}}return US(e,t,n)}async function US(e,t,n){const a=++OK;if(t==="/v1/preferences"&&typeof n?.body=="string"){const m=LS.get(e);if(!m)throw new Error("Reload settings before saving so changes can be checked against the current file.");n={...n,body:JSON.stringify({expectedRevision:m,...JSON.parse(n.body)})}}const i=new Headers(n?.headers);i.set("Content-Type","application/json"),i.set("Authorization",`Bearer ${e.token}`);const r=await fetch(`${e.serverUrl}${t}`,{...n,headers:i});if(!r.ok){const m=await r.json().catch(()=>({})),u=m&&typeof m=="object"&&"error"in m?String(m.error):r.statusText;throw new jK(u,r.status)}if(r.status===204)return;const s=await r.json(),c=s?.configuration?.rawRevision??(t==="/v1/preferences"?s?.rawRevision:void 0);return typeof c=="string"&&a>=(qS.get(e)??0)&&(LS.set(e,c),qS.set(e,a)),s}function Kae(e){const t=new URL("/v1/terminal",e.serverUrl);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function Wae(e){return["openpond-terminal",`openpond-token.${NK(e.token)}`]}function $K(e){const t=new TextEncoder().encode(e);let n="";for(let a=0;a<t.length;a+=32768){const i=t.subarray(a,a+32768);n+=String.fromCharCode(...i)}return btoa(n)}function NK(e){return $K(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function DK(e){const t=atob(e),n=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)n[a]=t.charCodeAt(a);return new TextDecoder().decode(n)}const HK={teamInvitations:e=>B(e,"/v1/team-invitations"),decideTeamInvitation:(e,t,n)=>B(e,`/v1/team-invitations/${t}`,{method:"POST",body:JSON.stringify({token:n})}),organizations:e=>B(e,"/v1/organizations"),createOrganization:(e,t)=>B(e,"/v1/organizations",{method:"POST",body:JSON.stringify(t)}),updateOrganization:(e,t,n)=>B(e,`/v1/organizations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),organizationMembers:(e,t)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/members`),upsertOrganizationMember:(e,t,n)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify(n)}),organizationMcpServer:(e,t)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`),generateOrganizationMcpServer:(e,t,n)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`,{method:"POST",body:JSON.stringify(n)}),setOrganizationMcpServerStatus:(e,t,n)=>B(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server/${n}`,{method:"POST"})},LK={taskInbox:(e,t)=>B(e,`/v1/sessions/${encodeURIComponent(t)}/inbox`),steerTurn:(e,t,n)=>B(e,`/v1/sessions/${encodeURIComponent(t)}/turns/steer`,{method:"POST",body:JSON.stringify(n)}),queueTaskInput:(e,t,n,a)=>B(e,`/v1/sessions/${encodeURIComponent(t)}/inbox`,{method:"POST",body:JSON.stringify({input:n,idempotencyKey:a})}),updateTaskInput:(e,t,n,a)=>B(e,`/v1/sessions/${encodeURIComponent(t)}/inbox/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)}),sendTurn:(e,t,n)=>B(e,`/v1/sessions/${t}/turns`,{method:"POST",body:JSON.stringify(n)}),runSessionCommand:(e,t,n)=>B(e,`/v1/sessions/${encodeURIComponent(t)}/commands`,{method:"POST",body:JSON.stringify(n)}),recordPreflightTurnFailure:(e,t,n)=>B(e,`/v1/sessions/${t}/preflight-turns/failure`,{method:"POST",body:JSON.stringify(n)}),listCreateImproveRuns:(e,t={})=>B(e,`/v1/create-improve-runs?${qK(t).toString()}`),getCreateImproveRun:(e,t)=>B(e,`/v1/create-improve-runs/${encodeURIComponent(t)}`),getCreateImproveCandidateDiff:(e,t,n)=>B(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/candidates/${encodeURIComponent(n)}/diff`),applyCreateImproveAction:(e,t,n)=>B(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/actions`,{method:"POST",body:JSON.stringify(n)}),interruptTurn:(e,t,n)=>B(e,`/v1/sessions/${t}/turns/interrupt`,{method:"POST",body:JSON.stringify({reason:n})}),compactSession:(e,t,n={reason:"manual"})=>B(e,`/v1/sessions/${t}/compact`,{method:"POST",body:JSON.stringify(n)}),workspaceTool:(e,t,n)=>B(e,`/v1/sessions/${t}/workspace-tools`,{method:"POST",body:JSON.stringify(n)}),ensureCloudWorkspaceReady:(e,t,n)=>B(e,`/v1/sessions/${encodeURIComponent(t)}/workspace/ensure-ready`,{method:"POST",body:JSON.stringify(n)})};function qK(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 UK={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)),B(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${a.toString()}`)},sandboxUploadFile:(e,t,n)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/files`,{method:"POST",body:JSON.stringify(n)}),preserveSandboxSource:(e,t,n={})=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/preserve-source`,{method:"POST",body:JSON.stringify(n)}),sandboxDownloadFile:async(e,t,n,a={})=>{const i=new URLSearchParams({path:n});a.offsetBytes!==void 0&&i.set("offsetBytes",String(a.offsetBytes)),a.maxBytes!==void 0&&i.set("maxBytes",String(a.maxBytes));const r=await B(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${i.toString()}`);return{...r,contents:r.file.isBinary?"":DK(r.file.contentsBase64)}}},zK={sandboxGitStatus:(e,t)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/status`),sandboxGitDiff:(e,t,n)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/diff`,{method:"POST",body:JSON.stringify(n)})},BK={connectedAppStatus:(e,t={})=>{const n=HS(t);return n.set("status",t.status??"all"),B(e,`/v1/connected-apps/status${n.size>0?`?${n.toString()}`:""}`)},integrationConnections:(e,t={})=>{const n=HS(t);return t.status&&n.set("status",t.status),B(e,`/v1/integrations/connections${n.size>0?`?${n.toString()}`:""}`)},sandboxIntegrationLeases:(e,t)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`),attachSandboxIntegrationConnection:(e,t,n)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"POST",body:JSON.stringify(n)}),removeSandboxIntegrationLease:(e,t,n)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"DELETE",body:JSON.stringify({leaseId:n})})},FK={listSandboxProjects:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return B(e,`/v1/sandbox-projects?${n.toString()}`)},getSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`)},getSandboxProjectWorkspace:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/workspace?${a.toString()}`)},upsertSandboxProject:(e,t)=>B(e,"/v1/sandbox-projects",{method:"POST",body:JSON.stringify(t)}),syncSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/sync?${a.toString()}`,{method:"POST"})},uploadSandboxProjectSource:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId}),{teamId:i,...r}=n;return B(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 B(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`,{method:"DELETE"})},listSandboxAgents:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return B(e,`/v1/sandbox-agents?${n.toString()}`)},upsertSandboxAgent:(e,t)=>B(e,"/v1/sandbox-agents",{method:"POST",body:JSON.stringify(t)}),runSandboxAgent:(e,t,n)=>B(e,`/v1/sandbox-agents/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n)}),runProfileAction:(e,t)=>B(e,"/v1/profile/run",{method:"POST",body:JSON.stringify(t)})},VK={sandbox:(e,t)=>B(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},KK={...BK,...FK,...VK,...zK,...UK},WK={communities:(e,t)=>{const n=new URLSearchParams;return t&&n.set("cursor",t),B(e,`/v1/communities${n.size?`?${n}`:""}`)},communityPreview:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/preview`),communityRules:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/rules/current`),joinCommunity:(e,t,n)=>B(e,`/v1/communities/${encodeURIComponent(t)}/join`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),acceptCommunityRules:(e,t,n)=>B(e,`/v1/communities/${encodeURIComponent(t)}/rules/accept`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),leaveCommunity:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/leave`,{method:"POST",body:"{}"}),communityChannels:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels`),communityMessages:(e,t,n,a={})=>{const i=new URLSearchParams;return a.beforeSequence!=null&&i.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&i.set("limit",String(a.limit)),B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages${i.size?`?${i}`:""}`)},sendCommunityMessage:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages`,{method:"POST",body:JSON.stringify(a)}),editCommunityMessage:(e,t,n,a,i)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify({body:i})}),deleteCommunityMessage:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"DELETE",body:"{}"}),markCommunityRead:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/read`,{method:"POST",body:JSON.stringify({sequence:a})}),setCommunityChannelMuted:(e,t,n,a)=>B(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)),B(e,`/v1/communities/${encodeURIComponent(t)}/members/search${a.size?`?${a}`:""}`)},updateCommunityNotifications:(e,t,n)=>B(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)),B(e,`/v1/communities/${encodeURIComponent(t)}/events${a.size?`?${a}`:""}`)},communityRealtimeSession:(e,t)=>B(e,`/v1/communities/${encodeURIComponent(t)}/realtime-session`),uploadCommunityAttachment:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/upload`,{method:"POST",body:JSON.stringify({attachment:a})}),communityAttachmentDownload:(e,t,n,a)=>B(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/${encodeURIComponent(a)}/download`)},zb="openpond-app-server-url",jc="openpond-app-token",GK=750;function RR(){return window.location.protocol!=="http:"&&window.location.protocol!=="https:"?null:window.location.origin&&window.location.origin!=="null"?window.location.origin:null}function vg(e){const t=e.getItem(zb)?.trim(),n=e.getItem(jc)?.trim();return t&&n?{serverUrl:t,token:n}:null}function Yu(e){if(!e)return null;try{const t="__openpond_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function fs(e,t){e.setItem(zb,t.serverUrl),e.setItem(jc,t.token)}function zS(e,t){const n=vg(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(zb),e.removeItem(jc))}function JK(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function ZK(){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()||RR();return!a||!n?null:{serverUrl:a,token:n}}function YK(){window.location.hash&&window.history.replaceState(null,"",`${window.location.pathname}${window.location.search}`)}function Yd(e,t){t&&(e.some(n=>n.serverUrl===t.serverUrl&&n.token===t.token)||e.push(t))}function QK(){const e=[],t=Yu(window.sessionStorage),n=Yu(window.localStorage),a=RR(),i=t?.getItem(jc)??n?.getItem(jc);return Yd(e,null),Yd(e,a&&i?{serverUrl:a,token:i.trim()}:null),Yd(e,t?vg(t):null),Yd(e,n?vg(n):null),e}async function sh(e){const t=new AbortController,n=window.setTimeout(()=>t.abort(),GK);try{const a=await fetch(`${e}/health`,{signal:t.signal}),i=await a.json().catch(()=>null);return a.ok&&i?.server==="openpond-app-server"}catch{return!1}finally{window.clearTimeout(n)}}async function XK(){if(window.openpond)return window.openpond.getConnection();const e=Yu(window.sessionStorage),t=Yu(window.localStorage),n=ZK();if(n&&await sh(n.serverUrl))return t&&fs(t,n),e&&fs(e,n),YK(),{...n,platform:navigator.platform};const a=JK();if(a&&await sh(a.serverUrl))return t&&fs(t,a),e&&fs(e,a),{...a,platform:navigator.platform};const i=QK();for(const r of i){if(await sh(r.serverUrl))return t&&fs(t,r),e&&fs(e,r),{...r,platform:navigator.platform};e&&zS(e,r),t&&zS(t,r)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const Q={...WK,bootstrap:e=>B(e,"/v1/bootstrap?refreshCodex=1"),localProjectActions:(e,t)=>B(e,`/v1/projects/${encodeURIComponent(t)}/actions`),extensionCatalog:e=>B(e,"/v1/extensions"),extensionPreview:(e,t)=>B(e,"/v1/extensions/preview",{method:"POST",body:JSON.stringify(t)}),extensionAdd:(e,t)=>B(e,"/v1/extensions",{method:"POST",body:JSON.stringify(t)}),extensionUpdate:(e,t,n={})=>B(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}/update`,{method:"POST",body:JSON.stringify(n)}),extensionUpdateAll:e=>B(e,"/v1/extensions/update-all",{method:"POST"}),extensionRemove:(e,t)=>B(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}`,{method:"DELETE"}),skillSourceFile:(e,t,n,a)=>B(e,`/v1/skills/${t}/${encodeURIComponent(n)}/source?path=${encodeURIComponent(a)}`),teamChatMembers:(e,t)=>B(e,`/v1/team-chat/members?teamId=${encodeURIComponent(t)}`),teamChatAgents:(e,t)=>B(e,`/v1/team-chat/agents?teamId=${encodeURIComponent(t)}`),teamChatThreads:(e,t)=>B(e,`/v1/team-chat/threads?teamId=${encodeURIComponent(t)}`),teamChatRealtimeSession:(e,t)=>B(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)),B(e,`/v1/team-chat/events?${a.toString()}`)},teamChatGeneral:(e,t)=>B(e,"/v1/team-chat/threads/general",{method:"POST",body:JSON.stringify({teamId:t})}),teamChatDm:(e,t,n)=>B(e,"/v1/team-chat/threads/dm",{method:"POST",body:JSON.stringify({teamId:t,otherUserId:n})}),teamChatThread:(e,t,n,a={})=>{const i=new URLSearchParams({teamId:t});return a.beforeSequence!=null&&i.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&i.set("limit",String(a.limit)),B(e,`/v1/team-chat/threads/${encodeURIComponent(n)}?${i.toString()}`)},uploadTeamChatAttachment:(e,t,n)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/attachments/upload`,{method:"POST",body:JSON.stringify(n)}),teamChatAttachmentDownload:(e,t,n)=>B(e,`/v1/team-chat/attachments/${encodeURIComponent(n)}/download?teamId=${encodeURIComponent(t)}`),sendTeamChatMessage:(e,t,n)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages`,{method:"POST",body:JSON.stringify(n)}),createTeamChatAgentRun:(e,t,n)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/agent-runs`,{method:"POST",body:JSON.stringify(n)}),teamChatAgentConversation:(e,t,n)=>B(e,`/v1/team-chat/agent-runs/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),editTeamChatMessage:(e,t,n,a)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)}),deleteTeamChatMessage:(e,t,n,a)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"DELETE",body:JSON.stringify({teamId:a})}),markTeamChatRead:(e,t,n,a)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/read`,{method:"POST",body:JSON.stringify({teamId:n,sequence:a})}),setTeamChatThreadMuted:(e,t,n,a)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/mute`,{method:"POST",body:JSON.stringify({teamId:n,muted:a})}),createTeamChatAiThread:(e,t,n)=>B(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/ai-threads`,{method:"POST",body:JSON.stringify(n)}),teamChatAiThread:(e,t,n)=>B(e,`/v1/team-chat/ai-threads/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),sendTeamChatAiTurn:(e,t,n)=>B(e,`/v1/team-chat/ai-threads/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),executeTeamChatAiTurn:(e,t,n)=>B(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute`,{method:"POST",body:JSON.stringify({teamId:n})}),cancelTeamChatAiTurnExecution:(e,t,n)=>B(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute/cancel`,{method:"POST",body:JSON.stringify({teamId:n})}),usage:(e,t={})=>{const n=BS(t),a=n.size?`?${n.toString()}`:"";return B(e,`/v1/usage${a}`)},usageRecords:(e,t={})=>{const n=BS(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 B(e,`/v1/usage/records${a}`)},usageTurnCache:(e,t)=>B(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 B(e,`/v1/events/page${a}`)},workOutputs:e=>B(e,"/v1/work/outputs"),harnessHistory:e=>B(e,"/v1/harness"),refinerHistory:e=>B(e,"/v1/refiner"),updateRefinerProfile:(e,t)=>B(e,"/v1/refiner/update",{method:"POST",body:JSON.stringify(t)}),activateRefinerRelease:(e,t)=>B(e,"/v1/refiner/activate",{method:"POST",body:JSON.stringify(t)}),rollbackRefinerRelease:(e,t)=>B(e,"/v1/refiner/rollback",{method:"POST",body:JSON.stringify(t)}),updateHarnessBackgroundReview:(e,t)=>B(e,"/v1/harness/background-review",{method:"POST",body:JSON.stringify(t)}),reviewHarnessEvaluation:(e,t)=>B(e,"/v1/harness/evaluation-review",{method:"POST",body:JSON.stringify(t)}),updateHarnessEvaluationReviewSchedule:(e,t)=>B(e,"/v1/harness/evaluation-review/settings",{method:"POST",body:JSON.stringify(t)}),harnessReleaseDiff:(e,t)=>B(e,"/v1/harness/diff",{method:"POST",body:JSON.stringify(t)}),rollbackHarness:(e,t)=>B(e,"/v1/harness/rollback",{method:"POST",body:JSON.stringify(t)}),reviewHarnessProposal:(e,t)=>B(e,"/v1/harness/review",{method:"POST",body:JSON.stringify(t)}),runSubagentLifecycleAction:(e,t,n)=>B(e,`/v1/subagents/${encodeURIComponent(t)}/lifecycle`,{method:"POST",body:JSON.stringify(n)}),trainingState:(e,t)=>B(e,`/v1/training?profileId=${encodeURIComponent(t)}`),trainingActivity:(e,t)=>B(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),B(e,`/v1/training/catalog${a.size?`?${a.toString()}`:""}`)},datasetCatalog:(e,t)=>B(e,`/v1/training/datasets?profileId=${encodeURIComponent(t)}`),trainingRunDetail:(e,t,n={})=>B(e,`/v1/training/jobs/${encodeURIComponent(t)}/detail?evaluation=${n.includeEvaluation===!1?"false":"true"}`),candidateReview:(e,t,n=!1,a="models")=>B(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision?refresh=${n}`),recordCandidateReview:(e,t,n,a="models")=>B(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision`,{method:"POST",body:JSON.stringify(n)}),candidateReviewHistory:(e,t,n,a="models")=>B(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision-history?decisionId=${encodeURIComponent(n.id)}&decisionHash=${n.contentHash}`),trainingEvaluationTasks:async(e,t,n,a)=>{const i=new URLSearchParams({limit:"25"});return a&&i.set("cursor",a),B(e,`/v1/training/jobs/${encodeURIComponent(t)}/evaluations/${encodeURIComponent(n.id)}/tasks?${i}`)},trainingRequest:(e,t,n,a="POST")=>B(e,`/v1/training${t}`,{method:a,body:a==="GET"||a==="DELETE"?void 0:JSON.stringify(n)}),datasetStorageState:e=>B(e,"/v1/settings/dataset-storage"),updateDatasetStorage:(e,t)=>B(e,"/v1/settings/dataset-storage",{method:"PATCH",body:JSON.stringify({datasetStorePath:t})}),hostedSavedWork:e=>B(e,"/v1/saved-work"),createHostedSavedWork:(e,t)=>B(e,"/v1/saved-work",{method:"POST",body:JSON.stringify(t)}),updateHostedSavedWork:(e,t,n)=>B(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteHostedSavedWork:(e,t)=>B(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"DELETE"}),runHostedSavedWork:(e,t,n)=>B(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 B(e,`/v1/chat-workflows${n}`)},createChatWorkflow:(e,t)=>B(e,"/v1/chat-workflows",{method:"POST",body:JSON.stringify(t)}),updateChatWorkflow:(e,t,n)=>B(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteChatWorkflow:(e,t)=>B(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"DELETE"}),runChatWorkflow:(e,t)=>B(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 B(e,`/v1/local-agent-schedules${a}`)},syncLocalAgentSchedules:e=>B(e,"/v1/local-agent-schedules/sync",{method:"POST",body:JSON.stringify({})}),patchLocalAgentSchedule:(e,t,n)=>B(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),runLocalAgentSchedule:(e,t,n={})=>B(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 i=a.size?`?${a.toString()}`:"";return B(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/runs${i}`)},refreshOpenPondAccounts:e=>B(e,"/v1/openpond/accounts/refresh",{method:"POST",body:JSON.stringify({})}),refreshOpenPondAccount:e=>B(e,"/v1/openpond/account?refresh=1"),loadMoreOpenPondApps:(e,t)=>B(e,`/v1/openpond/apps/more?offset=${encodeURIComponent(String(t.offset))}&limit=${encodeURIComponent(String(t.limit))}`),switchOpenPondAccount:(e,t)=>B(e,"/v1/openpond/accounts/switch",{method:"POST",body:JSON.stringify(t)}),removeOpenPondAccount:(e,t)=>B(e,"/v1/openpond/accounts",{method:"DELETE",body:JSON.stringify(t)}),signOutOpenPondAccount:e=>B(e,"/v1/openpond/accounts/logout",{method:"POST",body:JSON.stringify({})}),saveOpenPondAccount:(e,t)=>B(e,"/v1/openpond/accounts/login",{method:"POST",body:JSON.stringify(t)}),updateOpenPondAccountConfig:(e,t)=>B(e,"/v1/openpond/accounts/config",{method:"PATCH",body:JSON.stringify(t)}),savePreferences:(e,t)=>B(e,"/v1/preferences",{method:"PATCH",body:JSON.stringify(t)}),saveProviderSettings:(e,t)=>B(e,"/v1/providers",{method:"PATCH",body:JSON.stringify(t)}),providerSettings:e=>B(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 i=a.size?`?${a.toString()}`:"";return B(e,`/v1/providers/${encodeURIComponent(t)}/models${i}`)},refreshProviderModels:(e,t,n)=>B(e,`/v1/providers/${encodeURIComponent(t)}/models`,{method:"POST",body:JSON.stringify(n)}),saveProviderCredential:(e,t,n)=>B(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"PUT",body:JSON.stringify(n)}),deleteProviderCredential:(e,t,n)=>B(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"DELETE",body:JSON.stringify(n)}),startOpenAiSubscriptionAuth:(e,t)=>B(e,"/v1/providers/openai/subscription-auth",{method:"POST",body:JSON.stringify(t)}),validateProviderCredential:(e,t,n)=>B(e,`/v1/providers/${encodeURIComponent(t)}/validate`,{method:"POST",body:JSON.stringify(n)}),savePersonalization:(e,t)=>B(e,"/v1/personalization",{method:"PATCH",body:JSON.stringify(t)}),recordClientDiagnostic:(e,t)=>B(e,"/v1/diagnostics/client",{method:"POST",body:JSON.stringify(t)}),profileCurrent:e=>B(e,"/v1/profile"),profileCatalog:e=>B(e,"/v1/profile/catalog"),profileWorkflows:e=>B(e,"/v1/profile/workflows"),profileEvaluations:e=>B(e,"/v1/profile/evaluations"),profileEvaluationDiscovery:(e,t,n)=>B(e,"/v1/profile/evaluations/discover",{method:"POST",body:JSON.stringify({profileRef:t}),signal:n}),profileEvaluationPrepare:(e,t)=>B(e,"/v1/profile/evaluations/prepare",{method:"POST",body:JSON.stringify(t)}),profileEvaluationRun:(e,t)=>B(e,"/v1/profile/evaluations/run",{method:"POST",body:JSON.stringify(t)}),profileEvaluationRunSuite:(e,t)=>B(e,"/v1/profile/evaluations/run-suite",{method:"POST",body:JSON.stringify(t)}),profileEvaluationCompare:(e,t)=>B(e,"/v1/profile/evaluations/compare",{method:"POST",body:JSON.stringify({id:`comparison-${crypto.randomUUID()}`,runIds:t})}),profileEvaluationSaveReport:(e,t,n)=>B(e,"/v1/profile/evaluations/reports",{method:"POST",body:JSON.stringify({id:`report-${crypto.randomUUID()}`,evidenceKind:t,evidenceId:n})}),profileSelect:(e,t)=>B(e,"/v1/profile/select",{method:"POST",body:JSON.stringify({ref:t})}),profileRemove:(e,t)=>B(e,"/v1/profile/remove",{method:"POST",body:JSON.stringify({ref:t})}),profilePublicationPreview:(e,t)=>B(e,"/v1/profile/publication/preview",{method:"POST",body:JSON.stringify(t)}),profilePublicationPublish:(e,t)=>B(e,"/v1/profile/publication/publish",{method:"POST",body:JSON.stringify(t)}),profileInstall:(e,t)=>B(e,"/v1/profile/install",{method:"POST",body:JSON.stringify(t)}),profileUpdate:(e,t)=>B(e,"/v1/profile/update",{method:"POST",body:JSON.stringify({ref:t})}),profileInit:(e,t)=>B(e,"/v1/profile/init",{method:"POST",body:JSON.stringify(t)}),profileLoad:(e,t)=>B(e,"/v1/profile/load",{method:"POST",body:JSON.stringify(t)}),profileCheck:(e,t)=>B(e,"/v1/profile/check",{method:"POST",body:JSON.stringify(t)}),profileAgentRename:(e,t,n)=>B(e,`/v1/profile/agents/${encodeURIComponent(t)}/name`,{method:"PATCH",body:JSON.stringify(n)}),profileCommit:(e,t)=>B(e,"/v1/profile/commit",{method:"POST",body:JSON.stringify(t)}),profilePush:(e,t)=>B(e,"/v1/profile/push",{method:"POST",body:JSON.stringify(t)}),workspaceLspSettingsStatus:e=>B(e,"/v1/lsp/settings-status"),workspaceLspRuntimeStatus:e=>B(e,"/v1/lsp/status"),restartWorkspaceLsp:e=>B(e,"/v1/lsp/restart",{method:"POST"}),remoteAccess:e=>B(e,"/v1/remote-access"),enableRemoteAccess:e=>B(e,"/v1/remote-access/enable",{method:"POST"}),disableRemoteAccess:e=>B(e,"/v1/remote-access/disable",{method:"POST"}),voiceTranscriptionStatus:(e,t={})=>B(e,"/v1/audio/transcriptions/status",{signal:t.signal}),transcribeVoice:(e,t,n={})=>B(e,"/v1/audio/transcriptions",{method:"POST",body:JSON.stringify(t),signal:n.signal}),createSession:(e,t)=>B(e,"/v1/sessions",{method:"POST",body:JSON.stringify(t)}),patchSession:(e,t,n)=>B(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 i=a.size?`?${a.toString()}`:"";return B(e,`/v1/codex-history/${encodeURIComponent(t)}${i}`)},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"),B(e,`/v1/codex-history/${encodeURIComponent(t)}?${a.toString()}`)},sendCodexHistoryTurn:(e,t,n)=>B(e,`/v1/codex-history/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),interruptCodexHistoryTurn:(e,t)=>B(e,`/v1/codex-history/${encodeURIComponent(t)}/turns/interrupt`,{method:"POST"}),patchSidebarAppPreference:(e,t,n)=>B(e,`/v1/sidebar/apps/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),reorderSidebarApps:(e,t)=>B(e,"/v1/sidebar/apps/reorder",{method:"POST",body:JSON.stringify(t)}),sidebarFiles:e=>B(e,"/v1/sidebar/files"),patchSidebarFile:(e,t)=>B(e,"/v1/sidebar/files",{method:"PATCH",body:JSON.stringify(t)}),workspaceStatus:(e,t,n=!1,a={})=>B(e,`/v1/workspaces/${encodeURIComponent(t)}${n?"?ensure=1":""}`,{signal:a.signal}),createWorkspaceBranch:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/branches`,{method:"POST",body:JSON.stringify(n)}),checkoutWorkspaceBranch:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/branch`,{method:"PATCH",body:JSON.stringify(n)}),workspaceDiff:(e,t,n={})=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/diff`,{signal:n.signal}),workspaceFile:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`),saveWorkspaceFile:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/file`,{method:"PATCH",body:JSON.stringify(n)}),signWorkspaceImageUrl:(e,t)=>B(e,"/v1/assets/workspace-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalImageUrl:(e,t)=>B(e,"/v1/assets/local-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalVideoUrl:(e,t)=>B(e,"/v1/assets/local-video-url",{method:"POST",body:JSON.stringify(t)}),signChatAttachmentImageUrl:(e,t)=>B(e,"/v1/assets/chat-attachment-image-url",{method:"POST",body:JSON.stringify(t)}),chatAttachmentFile:(e,t)=>B(e,"/v1/assets/chat-attachment-file",{method:"POST",body:JSON.stringify(t)}),workspaceLspTouch:(e,t,n,a={})=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/touch`,{method:"POST",body:JSON.stringify(n),signal:a.signal}),workspaceLspAction:(e,t,n)=>B(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/action`,{method:"POST",body:JSON.stringify(n)}),workspaceTemplateConfig:(e,t)=>B(e,`/v1/openpond/apps/${encodeURIComponent(t)}/template-config`),...HK,...KK,createLocalProject:(e,t)=>B(e,"/v1/projects",{method:"POST",body:JSON.stringify(t)}),updateLocalProjectAgentSetup:(e,t,n)=>B(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),uploadLocalProjectCloudSource:(e,t,n)=>B(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 i=a.toString()?`?${a.toString()}`:"";return B(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source/preview${i}`)},deleteLocalProject:(e,t)=>B(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"DELETE"}),gitAvailability:e=>B(e,"/v1/system/git"),installMacOSCommandLineTools:e=>B(e,"/v1/system/git/install-command-line-tools",{method:"POST",body:JSON.stringify({})}),...LK,resolveApproval:(e,t,n)=>B(e,`/v1/approvals/${t}`,{method:"POST",body:JSON.stringify(n)})};function BS(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 e9=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),t9=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),FS=e=>{const t=t9(e);return t.charAt(0).toUpperCase()+t.slice(1)},PR=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),n9=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var a9={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const i9=y.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:i="",children:r,iconNode:s,...c},m)=>y.createElement("svg",{ref:m,...a9,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:PR("lucide",i),...!r&&!n9(c)&&{"aria-hidden":"true"},...c},[...s.map(([u,h])=>y.createElement(u,h)),...Array.isArray(r)?r:[r]]));const dt=(e,t)=>{const n=y.forwardRef(({className:a,...i},r)=>y.createElement(i9,{ref:r,iconNode:t,className:PR(`lucide-${e9(FS(e))}`,`lucide-${e}`,a),...i}));return n.displayName=FS(e),n};const o9=[["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"}]],r9=dt("activity",o9);const s9=[["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"}]],l9=dt("archive-restore",s9);const c9=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],d9=dt("arrow-left",c9);const u9=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],AR=dt("bookmark",u9);const m9=[["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"}]],TR=dt("bookmark-x",m9);const p9=[["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"}]],VS=dt("book-open-text",p9);const f9=[["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"}]],Qd=dt("boxes",f9);const h9=[["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"}]],g9=dt("calendar-clock",h9);const v9=[["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"}]],ER=dt("chart-column-stacked",v9);const b9=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Yi=dt("check",b9);const y9=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],yu=dt("circle-check",y9);const S9=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],bo=dt("chevron-down",S9);const x9=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Tr=dt("chevron-right",x9);const k9=[["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"}]],I9=dt("circle-alert",k9);const w9=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],Ym=dt("cloud",w9);const _9=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],C9=dt("credit-card",_9);const R9=[["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"}]],P9=dt("download",R9);const A9=[["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"}]],lh=dt("external-link",A9);const T9=[["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"}]],E9=dt("file-output",T9);const M9=[["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"}]],Bb=dt("file-text",M9);const j9=[["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"}]],MR=dt("folder",j9);const O9=[["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"}]],jR=dt("folder-git-2",O9);const $9=[["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"}]],N9=dt("git-branch",$9);const D9=[["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"}]],H9=dt("github",D9);const L9=[["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"}]],OR=dt("earth",L9);const q9=[["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"}]],U9=dt("circle-question-mark",q9);const z9=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],B9=dt("list-filter",z9);const F9=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],V9=dt("loader-circle",F9);const K9=[["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"}]],W9=dt("maximize-2",K9);const G9=[["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"}]],Qm=dt("message-square",G9);const J9=[["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"}]],md=dt("ellipsis",J9);const Z9=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],$R=dt("panel-left",Z9);const Y9=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],bg=dt("panel-right",Y9);const Q9=[["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"}]],Fb=dt("pin",Q9);const X9=[["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"}]],Vb=dt("pin-off",X9);const eW=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],tW=dt("plus",eW);const nW=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],aW=dt("power",nW);const iW=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],oW=dt("search",iW);const rW=[["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"}]],NR=dt("settings",rW);const sW=[["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"}]],DR=dt("shapes",sW);const lW=[["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"}]],KS=dt("shield",lW);const cW=[["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"}]],Xm=dt("square-pen",cW);const dW=[["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"}]],HR=dt("square-terminal",dW);const uW=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],WS=dt("user-round",uW);const mW=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],pd=dt("x",mW);function pW({platform:e}){return!ep()||Kb(e)?null:x.jsxs("div",{className:"window-controls","aria-label":"Window controls",children:[x.jsx("button",{type:"button",className:"window-control minimize",title:"Minimize",onClick:()=>{ch("minimize")},children:x.jsx(bo,{size:14})}),x.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{ch("toggleMaximize")},children:x.jsx(W9,{size:12})}),x.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{ch("close")},children:x.jsx(pd,{size:13})})]})}function Kb(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")}function ep(){if(typeof window>"u")return!1;const e=window.openpond;return!!(e?.minimizeWindow||e?.toggleMaximizeWindow||e?.closeWindow)}async function ch(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 fW=[["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"}]],hW=dt("house",fW);const gW=[["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"}]],LR=dt("inbox",gW);function vW({value:e,options:t,disabled:n,compact:a,className:i,icon:r,placement:s="bottom",label:c,tooltip:m,searchable:u=!1,floating:h=!1,onChange:g}){const[S,k]=y.useState(!1),[C,A]=y.useState(""),M=y.useRef(null),[R,$]=y.useState();y.useLayoutEffect(()=>{if(!S||!h)return;function P(){const E=M.current?.getBoundingClientRect();if(!E)return;const L=window.innerHeight-E.bottom-12,z=E.top-12,H=L<180&&z>L;$({position:"fixed",left:Math.max(12,E.left),width:Math.min(E.width,window.innerWidth-24),minWidth:0,maxWidth:"calc(100vw - 24px)",right:"auto",top:H?"auto":E.bottom+5,bottom:H?window.innerHeight-E.top+5:"auto",maxHeight:Math.max(80,Math.min(320,H?z-5:L-5)),overflowY:"auto",zIndex:1e3})}return P(),window.addEventListener("resize",P),window.addEventListener("scroll",P,!0),()=>{window.removeEventListener("resize",P),window.removeEventListener("scroll",P,!0)}},[S,h]);const O=t.find(P=>P.value===e)??t[0],j=C.trim().toLowerCase(),I=j?t.filter(P=>[P.label,P.shortLabel,P.description].some(E=>E?.toLowerCase().includes(j))):t;return y.useEffect(()=>{if(!S){A("");return}function P(L){M.current?.contains(L.target)||k(!1)}function E(L){L.key==="Escape"&&k(!1)}return document.addEventListener("pointerdown",P),document.addEventListener("keydown",E),()=>{document.removeEventListener("pointerdown",P),document.removeEventListener("keydown",E)}},[S]),x.jsxs("div",{className:`dropdown-select ${i??""} ${a?"compact":""} ${s==="top"?"open-up":""}`,"data-tooltip":m,ref:M,children:[x.jsxs("button",{type:"button",className:`dropdown-trigger ${S?"active":""}`,disabled:n,"aria-label":c,"aria-haspopup":"menu","aria-expanded":S,onClick:()=>k(P=>!P),children:[r,x.jsx("span",{children:O?.shortLabel??O?.label??e}),x.jsx(bo,{size:14})]}),S&&x.jsxs("div",{className:"dropdown-menu",role:"menu",style:h?R:void 0,children:[u?x.jsxs("label",{className:"dropdown-search",onClick:P=>P.stopPropagation(),children:[x.jsxs("span",{className:"sr-only",children:["Search ",c]}),x.jsx("input",{autoFocus:!0,placeholder:`Search ${c.toLowerCase()}`,value:C,onChange:P=>A(P.target.value)})]}):null,I.map(P=>x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":P.value===e,disabled:P.disabled,className:[P.value===e?"selected":"",P.separatorBefore?"separator-before":"",P.icon?"with-icon":""].filter(Boolean).join(" "),onClick:()=>{P.disabled||(g(P.value),A(""),k(!1))},children:[x.jsxs("span",{children:[P.icon==="plus"?x.jsx(tW,{size:13}):null,x.jsx("span",{children:P.label})]}),P.description&&x.jsx("small",{children:P.description})]},P.value)),I.length?null:x.jsx("div",{className:"dropdown-empty",children:"No matches"})]})]})}const bW=[{destination:"walkthroughs",icon:VS,label:"Walkthroughs"},{destination:"external",icon:VS,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:Bb,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:C9,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:OR,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:H9,label:"GitHub",url:"https://github.com/openpond/openpond"},{destination:"external",icon:Qm,label:"Submit issue",url:"https://github.com/openpond/openpond/issues/new/choose"}];function yW({onOpenWalkthroughs:e,walkthroughsActive:t}){const[n,a]=y.useState(!1),i=y.useRef(null);return y.useEffect(()=>{if(!n)return;function r(c){i.current?.contains(c.target)||a(!1)}function s(c){c.key==="Escape"&&a(!1)}return document.addEventListener("pointerdown",r),document.addEventListener("keydown",s),()=>{document.removeEventListener("pointerdown",r),document.removeEventListener("keydown",s)}},[n]),x.jsxs("div",{className:"sidebar-help-menu",ref:i,children:[x.jsx("button",{"aria-expanded":n,"aria-haspopup":"menu","aria-label":"Open docs and help menu",className:`sidebar-icon sidebar-help-trigger ${t?"active":""}`,"data-tooltip":"Help",onClick:()=>a(r=>!r),type:"button",children:x.jsx(U9,{size:17})}),n?x.jsx("div",{className:"sidebar-help-popover",role:"menu","aria-label":"Help",children:bW.map(r=>{const s=r.icon,c=x.jsxs(x.Fragment,{children:[x.jsx(s,{size:15}),x.jsx("span",{children:r.label})]});return r.destination==="walkthroughs"?x.jsx("button",{"aria-current":t?"page":void 0,className:"sidebar-help-item",onClick:()=>{a(!1),e()},role:"menuitem",type:"button",children:c},r.label):x.jsx("a",{className:"sidebar-help-item",href:r.url,onClick:m=>{m.preventDefault(),a(!1),SW(r.url)},rel:"noreferrer",role:"menuitem",target:"_blank",children:c},r.label)})}):null]})}async function SW(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const Gae=[{value:"chat",label:"Chat"},{value:"work",label:"Work"}],dh=[{value:"chat",label:"Chat",description:"Chat and complete tasks"},{value:"models",label:"Models",description:"Evaluate, train, and serve models"},{value:"console",label:"Console",description:"Manage models and workspace resources"}];function qR(e){return e==="chat"?"New chat":"New task"}const yg=["get-started","home","inbox","models","datasets","graders","experiments","tasks","tasksets","labeling","rewards","evaluations","runs","versions","serving"],xW={"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"},kW={tasks:["drafts"],tasksets:["drafts","formats","batches"],rewards:["scorers","combined"],evaluations:["results","review","comparisons"],runs:["series","new"]},IW={datasets:["tasks","experiments","graders","versions"],graders:["overview","checks","usage","versions"],experiments:["overview","cases","compare","configuration"],tasksets:["overview","tasks","reward","attempts","releases"],rewards:["definition","usage","evidence"],evaluations:["overview","comparison","activity"],runs:["details","metrics","evaluation","rollouts","activity","artifacts"],versions:["overview","metrics","evaluation","rollouts","activity","artifacts"]};function ma(e="models",t=null,n={}){return e==="evaluations"&&n.collection==="review"?ma("labeling",t,{...n,collection:"default"}):{page:e,modelId:["get-started","home","inbox","datasets","graders","experiments"].includes(e)?null:t,collection:e==="evaluations"?"results":"default",resourceId:null,detailTab:null,query:"",after:null,...n}}function Oc(e){const t=e.pathname.split("/").filter(Boolean);if(t[0]!=="models"&&t[0]!=="console")return null;let n;try{n=t.slice(1).map(decodeURIComponent)}catch{return null}if(n.some(X=>!X.trim()||X.length>2e3||X.includes("\0")))return null;const a=n[0]&&!yg.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 i=n.shift(),r=i??"models";if(!yg.includes(r)||i==="models"||a&&r==="get-started")return null;let s=r==="evaluations"?"results":"default";if(kW[r]?.includes(n[0]))s=n.shift();else if(r==="evaluations"&&n.length)return null;if(r==="experiments"&&n[0]==="history")return null;const c=n.shift()??null,m=n.shift()??null;if(n.length||m&&!c||(r==="models"||r==="get-started"||r==="home")&&c)return null;if(s==="drafts"||s==="new"){if(!c||m)return null}else if(s!=="series"){if(["review","formats","batches","comparisons","scorers","combined"].includes(s)){if(m)return null}else if(m&&!IW[r]?.includes(m))return null}if(r==="serving"&&m)return null;const u=new URLSearchParams(e.search??"");if([...u.keys()].some(X=>!["model","q","after","source","project","pass","dataset","revision","hash","sort","location","kind","review_source","review_snapshot","review_boundary","review_revision"].includes(X))||[...u.keys()].some(X=>u.getAll(X).length!==1))return null;const h=["review_source","review_snapshot","review_boundary","review_revision"],g=h.some(X=>u.has(X));if(g&&(r!=="datasets"||c||u.get("location")==="local"||h.some(X=>!u.get(X))||[u.get("review_source"),u.get("review_boundary")].some(X=>!X.trim()||X.length>500||X.includes("\0"))||[u.get("review_snapshot"),u.get("review_revision")].some(X=>!/^[a-f0-9]{64}$/.test(X))))return null;const S=g?{id:u.get("review_source"),snapshotHash:u.get("review_snapshot"),boundaryId:u.get("review_boundary"),boundaryRevisionHash:u.get("review_revision")}:void 0,k=u.get("sort");if(k!==null&&(r!=="datasets"||!["id","name","updated"].includes(k)))return null;const C=u.has("revision")?Number(u.get("revision")):void 0,A=u.get("hash")??void 0,M=["datasets","graders"].includes(r);if((C!==void 0||A!==void 0)&&(!c||!M||!Number.isSafeInteger(C)||C<=0||!/^[a-f0-9]{64}$/.test(A??"")))return null;const R=u.get("source");if(R!==null&&(r!=="labeling"&&(r!=="evaluations"||s!=="review")||!R.trim()||R.length>500)||u.has("dataset")&&(r!=="datasets"||!c||u.get("dataset")!=="release"))return null;const $=["home","inbox","datasets","graders","experiments"].includes(r),O=r==="runs"&&!!(c?.startsWith("hosted-run:")||c?.startsWith("hosted-policy:")),j=u.get("location");if(j!==null&&(!$||!["local","hosted"].includes(j)))return null;const I=u.get("kind");if(I!==null&&(r!=="experiments"||!c||j==="local"||I!=="recorded_evidence")||t[0]==="console"&&!$)return null;const P=u.get("project")==="all"?null:u.get("project"),E=u.get("pass");if([P,E].some(X=>X!==null&&(!X.trim()||X.length>240))||!$&&!O&&(P||E)||r!=="experiments"&&E||($||O)&&a||E&&!c)return null;const L=u.get("model");if($&&L!==null||a&&L&&a!==L)return null;const z=a??L;if(r==="get-started"&&u.size!==0)return null;const H=u.get("q")??"",J=u.get("after");return z!==null&&(!z.trim()||z.length>500)||H.length>1e3||J!==null&&(!J.trim()||J.length>2e3)?null:ma(r,z,{...S?{reviewSource:S}:{},collection:s,resourceId:c,detailTab:m,query:H,after:J,...I?{executionKind:"recorded_evidence"}:{},...j?{executionLocation:j}:{},...k?{sort:k}:{},...C!==void 0?{revision:C,contentHash:A}:{},...u.get("dataset")==="release"?{datasetKind:"release"}:{},...t[0]==="console"?{area:"console"}:{},...$||O?{...u.has("project")?{projectId:P}:{},...u.has("pass")?{passId:E}:{}}:{},...R!==null?{sourceId:R}:{}})}function tp(e){const t=[e.area==="console"?"/console":"/models"];if(e.modelId&&t.push(encodeURIComponent(e.modelId)),e.page==="evaluations"&&e.collection==="review")return tp(ma("labeling",e.modelId,{collection:"default",resourceId:e.resourceId,sourceId:e.sourceId,query:e.query,after:e.after}));e.page==="evaluations"?t.push("runs",e.collection==="comparisons"?"comparisons":"evaluations"):(e.page!=="models"&&t.push(e.page),e.collection!=="default"&&t.push(e.collection)),e.resourceId&&t.push(encodeURIComponent(e.resourceId)),e.resourceId&&e.detailTab&&t.push(encodeURIComponent(e.detailTab));const n=new URLSearchParams;return e.page==="datasets"&&!e.resourceId&&e.reviewSource&&(n.set("review_source",e.reviewSource.id),n.set("review_snapshot",e.reviewSource.snapshotHash),n.set("review_boundary",e.reviewSource.boundaryId),n.set("review_revision",e.reviewSource.boundaryRevisionHash)),e.executionLocation&&n.set("location",e.executionLocation),e.projectId?n.set("project",e.projectId):e.projectId===null&&["home","inbox","datasets","graders","experiments"].includes(e.page)&&n.set("project","all"),e.page==="datasets"&&e.resourceId&&e.datasetKind==="release"&&n.set("dataset","release"),e.page==="datasets"&&e.sort&&n.set("sort",e.sort),e.revision!==void 0&&e.contentHash&&e.resourceId&&["datasets","graders"].includes(e.page)&&(n.set("revision",String(e.revision)),n.set("hash",e.contentHash)),e.passId&&n.set("pass",e.passId),e.page==="experiments"&&e.resourceId&&e.executionKind&&n.set("kind",e.executionKind),e.query&&n.set("q",e.query),e.after&&n.set("after",e.after),(e.page==="labeling"||e.page==="evaluations"&&e.collection==="review")&&e.sourceId&&n.set("source",e.sourceId),`${t.join("/")}${n.size?`?${n}`:""}`}function wW(e,t){return ma(e.page,t,{...e.area?{area:e.area}:{},...["home","inbox","datasets","graders","experiments"].includes(e.page)&&e.projectId!==void 0?{projectId:e.projectId}:{},collection:e.collection==="new"||e.collection==="drafts"?"default":e.collection})}function Jae(e,t,n=null){return{...e,resourceId:t,detailTab:n,after:null,...t!==e.resourceId?{revision:void 0,contentHash:void 0}:{}}}const Qu=new Set,Sg=new Set,_W=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"]),xg={apps:"/apps",outputs:"/outputs",projects:"/projects",scheduled:"/workflows","get-started":"/get-started"};let kg=!1,Ig="",Su=null,UR=null,$c="",ni=0,Ul=null,dc=!1,uh=null,xu=!1;function Wb(e){const t=Oc(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&&_W.has(n[1])){const i=Gb(new URLSearchParams(e.search??"").get("returnTo"));return{kind:"settings",section:n[1],...i?{returnTo:i}:{}}}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(xg).find(i=>xg[i]===e.pathname);return a?{kind:"view",view:a}:null}function zR(e){if(e.kind==="models")return tp(e.route);if(e.kind==="models_unavailable")return`${e.pathname}${e.search}`;if(e.kind==="settings"){const t=Gb(e.returnTo??null);return`/settings/${e.section}${t?`?${new URLSearchParams({returnTo:t})}`:""}`}return e.kind==="chat"?e.sessionId?`/chat/${encodeURIComponent(e.sessionId)}`:"/chat/new":xg[e.view]}function CW(e){const t=e?.kind==="settings"?Gb(e.returnTo??null):null;if(t){const n=new URL(t,"https://local.openpond.invalid"),a=Oc(n);if(a)return{kind:"models",route:a}}return{kind:"chat",sessionId:null}}function Gb(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=Oc(t);return n?tp(n):null}function fd(){return`${window.location.pathname}${window.location.search}`}function Jb(){if(typeof window>"u")return;const e=kg?$c:fd();e!==Ig&&(Ig=e,Su=Wb(new URL(e,window.location.origin)),UR=Su?.kind==="models"?Su.route:null)}function BR(){Ig="",Jb();for(const e of Sg)e()}async function Zb(e){if(xu)return!1;xu=!0;try{for(const t of[...Qu].reverse())if(!await t(e))return!1;return!0}finally{xu=!1}}function Yb(e){return{...window.history.state,openpondNavigationIndex:e}}async function RW(){const e=fd(),t=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:ni-1;if(Ul&&t===ni){const a=Ul;Ul=null,a();return}if(uh===t||Qu.size===0){uh=null,$c=e,ni=t,window.history.replaceState(Yb(ni),"",e),BR();return}if(t===ni)return;if(dc||xu){Ul??=()=>{},window.history.go(ni-t);return}dc=!0;const n=t-ni;try{await new Promise(a=>{Ul=a,window.history.go(-n)}),await Zb(e)&&(uh=t,window.history.go(n))}finally{dc=!1}}function Qb(){if(kg||typeof window>"u")return;const e=Wb(window.location);$c=e?zR(e):fd(),ni=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:0,window.history.replaceState(Yb(ni),"",$c),window.addEventListener("popstate",RW),kg=!0}function FR(e){return Sg.add(e),Qb(),()=>{Sg.delete(e)}}function Zae(e){return Qu.add(e),Qb(),()=>{Qu.delete(e)}}async function Yae(e){!dc&&await Zb(fd())&&e()}function PW(){return y.useSyncExternalStore(FR,()=>(Jb(),UR),()=>null)}function AW(){return y.useSyncExternalStore(FR,()=>(Jb(),Su),()=>null)}async function ln(e,t="push"){if(typeof window>"u"||(Qb(),dc))return!1;if(e.kind==="settings"&&!e.returnTo){const a=Wb(window.location),i=a?.kind==="models"?tp(a.route):a?.kind==="settings"?a.returnTo:void 0;i&&(e={...e,returnTo:i})}const n=zR(e);return fd()===n?!0:await Zb(n)?(t==="push"&&ni++,window.history[t==="replace"?"replaceState":"pushState"](Yb(ni),"",n),$c=n,BR(),!0):!1}function po(e,t="push"){return ln({kind:"models",route:e},t)}function TW({experience:e="work",beginNewChat:t}){return x.jsx("div",{className:"sidebar-new-task",children:x.jsxs("button",{className:"nav-command nav-command-new-task",type:"button",onClick:()=>{ln({kind:"chat",sessionId:null}),t(null)},children:[x.jsx(Xm,{size:18}),x.jsx("span",{children:qR(e)})]})})}function EW({productArea:e="chat",setSectionMenuOpen:t,setSelectedAppId:n,setSelectedProjectId:a,setSelectedSessionId:i,setView:r,view:s,modelProjects:c=[],modelTrainingActivityByProjectId:m={}}){const u=PW(),h=u?.modelId??null,g=u?.page??"models";function S(){n(null),a(null),i(null),t(null)}async function k(R){await po(ma(R,["home","inbox","datasets","graders","experiments"].includes(R)?null:h,{...e==="console"?{area:"console"}:{},...u?.projectId!==void 0?{projectId:u.projectId}:{}}))&&(S(),r("labs"))}async function C(R){await po(wW(u??ma(),R||null))&&(S(),r("labs"))}async function A(R){await ln({kind:"view",view:R})&&(S(),r(R))}const M=h?m[h]??null:null;return x.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[e!=="chat"?x.jsxs(x.Fragment,{children:[["home","inbox","datasets","graders","experiments"].includes(g)?null:x.jsxs("div",{className:"sidebar-model-project-picker",children:[x.jsx("span",{className:"sidebar-nav-group-label",children:"Model"}),x.jsx(vW,{label:"Model",searchable:c.length>8,value:h??"",options:[{value:"",label:"All models"},...h&&!c.some(R=>R.id===h)?[{value:h,label:"Unavailable model",disabled:!0}]:[],...c.map(R=>({value:R.id,label:R.name}))],onChange:R=>{C(R)}})]}),yg.filter(R=>e==="console"?["home","inbox","datasets","graders","experiments"].includes(R):R!=="home"&&R!=="tasksets"&&R!=="evaluations").map(R=>{const $={"get-started":Qd,home:hW,inbox:LR,models:r9,datasets:Qd,graders:KS,experiments:yu,tasks:Qd,tasksets:Qd,labeling:yu,rewards:KS,evaluations:yu,runs:ER,versions:N9,serving:Ym}[R];return x.jsxs("button",{className:`nav-command ${s==="labs"&&(g===R||R==="runs"&&g==="evaluations")?"active":""}`,"aria-current":s==="labs"&&(g===R||R==="runs"&&g==="evaluations")?"page":void 0,type:"button",onClick:()=>{k(R)},children:[x.jsx($,{size:16}),x.jsx("span",{children:xW[R]}),R==="runs"&&M?x.jsx("span",{className:"sidebar-running-dot","aria-label":M.label}):null]},R)})]}):null,e==="chat"?x.jsxs(x.Fragment,{children:[x.jsxs("button",{className:`nav-command nav-command-prominent ${s==="scheduled"?"active":""}`,"aria-label":"Workflows",type:"button",onClick:()=>{A("scheduled")},children:[x.jsx(g9,{size:18}),x.jsx("span",{children:"Workflows"})]}),x.jsxs("button",{className:`nav-command nav-command-prominent ${s==="outputs"?"active":""}`,"aria-label":"Outputs",type:"button",onClick:()=>{A("outputs")},children:[x.jsx(E9,{size:18}),x.jsx("span",{children:"Outputs"})]}),x.jsxs("button",{className:`nav-command nav-command-prominent ${s==="apps"?"active":""}`,"aria-label":"Apps",type:"button",onClick:()=>{A("apps")},children:[x.jsx(DR,{size:18}),x.jsx("span",{children:"Apps"})]}),x.jsxs("button",{className:`nav-command nav-command-prominent ${s==="projects"?"active":""}`,"aria-label":"Projects",type:"button",onClick:()=>{A("projects")},children:[x.jsx(jR,{size:18}),x.jsx("span",{children:"Projects"})]})]}):null]})}function MW({setSectionMenuOpen:e,setSelectedAppId:t,setSelectedProjectId:n,setSelectedSessionId:a,setView:i,view:r}){function s(){t(null),n(null),a(null),e(null),i("get-started"),ln({kind:"view",view:"get-started"})}return x.jsx("nav",{className:"sidebar-utility-nav","aria-label":"Resources",children:x.jsx(yW,{onOpenWalkthroughs:s,walkthroughsActive:r==="get-started"})})}const VR=kf({chatMode:v(["chat","work"]).optional(),notificationMode:v(["all","direct_mentions","none"]).optional(),learningNoticeDismissed:w().optional(),sidebarVisibility:kf({showCodexChats:w(),onlyRunningTasks:w()}).optional(),scheduledWorkView:v(["calendar","list"]).optional(),editorControlsVisible:w().optional(),voiceNoticeAcknowledged:w().optional(),lessonProgress:ae(o().min(1).max(200),kf({completed:w(),currentTime:d().finite().nonnegative(),duration:d().finite().positive(),updatedAt:d().finite().nonnegative()})).refine(e=>Object.keys(e).length<=200,"Too many lessons").optional()}),wg={"openpond:last-chat-task-mode":"chatMode","openpond.team-chat.notification-mode":"notificationMode","openpond.sidebar.continuous-learning.dismissed.v1":"learningNoticeDismissed","openpond.sidebar-task-visibility.v1":"sidebarVisibility","openpond.scheduled-work.view.v1":"scheduledWorkView","openpond.workspace.editorControlsVisible":"editorControlsVisible","openpond.voice.setupNoticeAcknowledged":"voiceNoticeAcknowledged","openpond.post-training-progress.v1":"lessonProgress"},_g=new Set;let uc=null,fo=null,ii={},Nc={},mh=!1,ku=0,Ds=null,GS=0;const jW="openpond-client-choices-changed";function Xb(){_g.forEach(e=>e()),typeof window<"u"&&window.dispatchEvent(new Event(jW))}function OW(){return Ds}function $W(e){return _g.add(e),()=>{_g.delete(e)}}function hd(e){const t=y.useRef(e);t.current=e,y.useEffect(()=>$W(()=>t.current()),[])}async function JS(e){const t=++GS,n=await B(e,"/v1/configuration");if(n.clientState?.revision===null){const i=NW();if(Object.keys(i.patch).length){n.clientState=await B(e,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n.clientState.owner,patch:i.patch,importOnly:!0})});for(const r of i.keys)try{window.localStorage.removeItem(r)}catch{}}}if(t!==GS)return;const a=uc?.serverUrl!==e.serverUrl||uc?.token!==e.token||fo?.owner!==n.clientState?.owner;a&&(ku++,ii={},Nc={},Ds=null),uc=e,(a||(n.clientState?.revision??0)>=(fo?.revision??0))&&(fo=n.clientState),Xb()}async function ey(){if(mh||!uc||!fo||!Object.keys(ii).length)return;mh=!0;const e=ii,t=uc,n=fo.owner,a=ku;ii={},Nc=e;try{const i=await B(t,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n,patch:e})});a===ku&&(fo=i,Ds=null)}catch(i){a===ku&&(ii={...e,...ii},Ds=`Preference changes have not been saved. ${i instanceof Error?i.message:String(i)}`)}finally{Nc={},mh=!1,Xb(),!Ds&&Object.keys(ii).length&&ey()}}function Qae(){Ds=null,ey()}const gd={getItem(e){const t=wg[e];if(!t)return null;const n={...fo?.value,...Nc,...ii}[t];return n===void 0?null:typeof n=="string"?n:JSON.stringify(n)},setItem(e,t){if(!fo)return;const n=wg[e];if(!n)throw new Error("Unregistered client preference.");let a;try{a=JSON.parse(t)}catch{a=t}const i=VR.parse({[n]:a});JSON.stringify({...fo.value,...Nc,...ii}[n])!==JSON.stringify(i[n])&&(ii={...ii,...i},Xb(),ey())}};function NW(){const e={},t=[];if(typeof window>"u")return{patch:e,keys:t};for(const[n,a]of Object.entries(wg))try{const i=window.localStorage.getItem(n);if(i===null)continue;let r;try{r=JSON.parse(i)}catch{r=i}const s=VR.safeParse({[a]:r});s.success&&(Object.assign(e,s.data),t.push(n))}catch{}return{patch:e,keys:t}}const Iu=5,Hn=15,Cg=10,Ot={defaultChatProvider:_r,subagents:e$(),codexPermissionMode:yv,codexReasoningEffort:Sv,openPondCommandAccessMode:bm,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:""}}}},Xae={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},KR=[{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"}],ph=[{value:"openpond",label:"OpenPond Chat"},{value:"codex",label:"OpenAI Codex",description:"Codex login"}],DW=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],HW=["openpond","codex",...DW],WR=new Set(HW),GR=[{value:bv,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"}],eie=[{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."}],Rg=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],LW=[{value:"off",label:"Off"},...Rg,{value:"max",label:"Max"}],tie=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],nie=[{value:"auto",label:"Auto",description:"Use installed language servers when available."},{value:"off",label:"Off",description:"Disable editor language servers."}],aie=[{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 ty(e){return e.kind==="local"}function qW(e){return e.kind==="cloud"}function wt(e,t){return`${e}:${t}`}function JR(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),i=t.slice(n+1);return(a==="local"||a==="cloud")&&i?{kind:a,id:i}:{kind:"local",id:t}}function xr(e){return`${e.type}:${e.id}`}function Xu(e){const t=e.currentTarget.getBoundingClientRect();return e.clientY<t.top+t.height/2?"before":"after"}function em(e,t,n,a="before"){if(t===n)return e;const i=e.filter(s=>s!==t),r=i.indexOf(n);return r===-1?e:(i.splice(a==="after"?r+1:r,0,t),i)}function ZS(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function UW(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),i=new Set(a.map(r=>r.key));return[...a,...e.filter(r=>!i.has(r.key))]}function ny(e,t){return e?.statuses?.[t]??null}function ZR(e,t){return e?.providers?.[t]??null}function ay(e,t){return e?.modelCaches?.[t]??null}function zW(e){const t=[e.contextWindow?`${Math.round(e.contextWindow/1e3)}K context`:"",e.capabilities.reasoning?"reasoning":"",e.source].filter(Boolean);return{value:e.id,label:e.displayName||e.id,description:t.join(" · ")||void 0}}function BW(e){return e==="openpond"?KR:e==="codex"||e==="openai"?GR:[]}function FW(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 iie(e){return WR.has(e)}function Pg(e,t={}){if(!e)return t.localOnly,ph;const n=t.includeUnavailable??!1,a=t.enabledOnly??!1,i=[];for(const r of sv){if(!WR.has(r)||t.localOnly&&r==="openpond")continue;const s=ny(e,r);s&&(!n&&(r==="codex"&&!s.available&&!s.credential.connected||r!=="openpond"&&r!=="codex"&&!s.enabled)||a&&r!=="openpond"&&!s.enabled||a&&r==="codex"&&!s.available&&!s.credential.connected||i.push({value:r,label:r==="openpond"?"OpenPond Chat":s.displayName,description:r==="openpond"?void 0:s.available?"Connected":s.credential.connected?"Configured":s.routing.localByok?"Set up key":s.enabled?"Enabled":void 0}))}return i.length>0?i:ph}function Dc(e,t){const a=(ay(t,e)?.models??[]).filter(c=>e!=="openpond"||c.id!==zs).map(zW),i=ZR(t,e),r=[...i?.modelOverrides??[],i?.defaultModel].filter(c=>!!c?.trim()&&(e!=="openpond"||c!==zs)).map(c=>({value:c,label:c})),s=e==="openpond"&&a.length>0?[]:BW(e);return FW([...a,...r,...s])}function YR(e,t,n){if(e!=="openpond")return Rg;const a=ay(n,e)?.models.find(r=>r.id===t)?.capabilities;if(!a?.reasoningEfforts.length)return Rg;const i=new Set(a.reasoningEfforts);return LW.filter(r=>i.has(r.value))}function VW(e,t,n){const a=YR(e,t,n),i=e==="openpond"&&(t==="gpt-6-luna"||t==="gpt-6-sol"||t==="claude-opus-5-5")?"medium":"high";return a.some(r=>r.value===i)?i:a[0]?.value??"high"}function KW(e,t,n,a){return YR(e,t,a).some(i=>i.value===n)?n:VW(e,t,a)}function WW(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const i=ay(n,e)?.models.find(r=>r.id===a);return i?!!i.capabilities.reasoning:Dc(e,n).some(r=>r.value===a&&/\breasoning\b/i.test(r.description??""))}function tm(e,t){const n=ZR(t,e)?.defaultModel?.trim();if(n)return n;const a=ny(t,e)?.defaultModel?.trim();if(a)return a;const i=Dc(e,t)[0]?.value?.trim();return i||(e==="codex"?bv:e==="openpond"?zs:"")}function Yo(e,t,n){const a=t?.trim();if(e==="codex"&&(a==="codex-default"||a==="gpt-5.5"))return bv;const i=Dc(e,n);return a&&i.some(r=>r.value===a)||a&&e!=="codex"&&i.length===0&&!n?a:tm(e,n)}function QR(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:Yo(n,e.modelRef?.modelId,t)}}function iy(e,t,n){return Yo(e,t,n)||void 0}function ei(e,t,n){const a=iy(e,t,n);return a?{providerId:e,modelId:a}:void 0}function YS(e){return e==="full-access"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function Oa(e){const t=e?.defaultChatProvider??Ot.defaultChatProvider;return{defaultChatProvider:t,defaultChatModel:Yo(t,e?.defaultChatModel),subagents:gc.parse(e?.subagents??Ot.subagents),codexPermissionMode:e?.codexPermissionMode??Ot.codexPermissionMode,codexReasoningEffort:e?.codexReasoningEffort??Ot.codexReasoningEffort,openPondCommandAccessMode:e?.openPondCommandAccessMode??Ot.openPondCommandAccessMode,defaultBranchPrefix:XR(e?.defaultBranchPrefix),defaultNewProjectDirectory:e?.defaultNewProjectDirectory??Ot.defaultNewProjectDirectory,defaultTeamId:e?.defaultTeamId?.trim()||null,advancedWorkspaceControls:e?.advancedWorkspaceControls??Ot.advancedWorkspaceControls,steerActiveResponses:e?.steerActiveResponses??Ot.steerActiveResponses,contextCompaction:{autoEnabled:e?.contextCompaction?.autoEnabled??Ot.contextCompaction.autoEnabled,triggerPercent:e?.contextCompaction?.triggerPercent??Ot.contextCompaction.triggerPercent,summaryModel:e?.contextCompaction?.summaryModel??Ot.contextCompaction.summaryModel},training:{defaultModelRef:e?.training?.defaultModelRef??Ot.training.defaultModelRef,creationMode:e?.training?.creationMode??Ot.training.creationMode,autoApproveEvidence:e?.training?.autoApproveEvidence??Ot.training.autoApproveEvidence},sidebarWidth:e?.sidebarWidth??Ot.sidebarWidth,diffPanelWidth:e?.diffPanelWidth??Ot.diffPanelWidth,sidebarSectionsCollapsed:{pinned:e?.sidebarSectionsCollapsed?.pinned??Ot.sidebarSectionsCollapsed.pinned,projects:e?.sidebarSectionsCollapsed?.projects??Ot.sidebarSectionsCollapsed.projects,cloudProjects:e?.sidebarSectionsCollapsed?.cloudProjects??Ot.sidebarSectionsCollapsed.cloudProjects,chats:e?.sidebarSectionsCollapsed?.chats??Ot.sidebarSectionsCollapsed.chats,savedForLater:e?.sidebarSectionsCollapsed?.savedForLater??Ot.sidebarSectionsCollapsed.savedForLater},editor:{languageServers:e?.editor?.languageServers??Ot.editor.languageServers,diagnosticsWhileEditing:e?.editor?.diagnosticsWhileEditing??Ot.editor.diagnosticsWhileEditing,checkOnSave:e?.editor?.checkOnSave??Ot.editor.checkOnSave,languages:{typescript:{mode:e?.editor?.languages?.typescript?.mode??Ot.editor.languages.typescript.mode,customCommand:e?.editor?.languages?.typescript?.customCommand??Ot.editor.languages.typescript.customCommand},python:{mode:e?.editor?.languages?.python?.mode??Ot.editor.languages.python.mode,customCommand:e?.editor?.languages?.python?.customCommand??Ot.editor.languages.python.customCommand},rust:{mode:e?.editor?.languages?.rust?.mode??Ot.editor.languages.rust.mode,customCommand:e?.editor?.languages?.rust?.customCommand??Ot.editor.languages.rust.customCommand}}}}}function XR(e){const t=e?.trim()??Ot.defaultBranchPrefix;if(!t)return"";const a=t.toLowerCase().replace(/[^a-z0-9._/-]+/g,"-").replace(/\/{2,}/g,"/").replace(/^-+/,"").slice(0,48).split("/").map(i=>i.replace(/^-+|-+$/g,"")).filter(Boolean).join("/");return a?`${a}/`:""}function oie(e,t){return e==="openpond"?"OpenPond Chat":ny(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function rie(e,t,n){if(n){const a=Dc(n,t).find(i=>i.value===e);if(a)return a.label}if(t)for(const a of sv){const i=Dc(a,t).find(r=>r.value===e);if(i)return i.label}return[...KR,...GR].find(a=>a.value===e)?.label??e}function GW(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function JW(e){return e.experience==="chat"?"Chat":"Work"}const oy="taskDraft";function eP(e){if(e?.experience!=="work")return null;const t=e.metadata?.[oy];if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t.prompt;return typeof n=="string"&&n.trim()?n:null}function Hc(e){return eP(e)!==null}function ZW(e){return(e.split(/\r?\n/u).map(n=>n.trim()).find(Boolean)||"Task draft").slice(0,64)}function fh(e,t,n=new Date().toISOString()){const a={version:1,prompt:t,savedAt:n};return{...e??{},[oy]:a}}function YW(e){const t={...e??{}};return delete t[oy],t}function Rs(e){const t=Xd(e.metadata?.trainingTasksetId)??Xd(e.metadata?.tasksetId);return t?{id:t,name:Xd(e.metadata?.trainingTasksetName)??Xd(e.metadata?.tasksetName)??QW(t)}:null}function QW(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 Xd(e){return typeof e=="string"&&e.trim()?e.trim():null}const XW="codex_history_";function Vt(e){return!!e?.startsWith(XW)}function tP(e){const t=[],n=new Set;for(const a of e)for(const i of[a.workspacePath,a.path]){const r=np(i);if(!r)continue;const s=`${a.id}:${r}`;n.has(s)||(n.add(s),t.push({projectId:a.id,path:r}))}return t.sort((a,i)=>i.path.length-a.path.length)}function e8(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=nP(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"||!aP(e))return null;const i=np(e.cwd);if(!i)return null;for(const r of n)if(ry(i,r.path))return r.projectId;return null}function QS(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return wt("local",e.localProjectId);if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return wt("local",e.workspaceId);if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const r=nP(e.cwd,n);if(r)return wt("local",r)}if(e.cloudProjectId&&a.has(e.cloudProjectId))return wt("cloud",e.cloudProjectId);if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!aP(e))return null;const i=np(e.cwd);if(!i)return null;for(const r of n)if(ry(i,r.path))return wt("local",r.projectId);return null}function nP(e,t){const n=np(e);if(!n)return null;for(const a of t)if(ry(n,a.path))return a.projectId;return null}function aP(e){return e.workspaceKind==="local_project"||e.provider==="codex"||Vt(e.id)}function np(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 ry(e,t){const n=XS(e),a=XS(t);return n===a||n.startsWith(`${a}/`)}function XS(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}const ex=[{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"}],t8=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function tx(e){const t=[];if(e.filter==="done")t.push(...e.doneSessions.filter(i=>!Rs(i)));else if(e.filter==="all")t.push(...e.activeSessions.filter(i=>!Rs(i)),...e.doneSessions.filter(i=>!Rs(i)));else if(e.filter==="tasksets")t.push(...e.activeSessions.filter(i=>nx(i,e.selectedTasksetId)),...e.doneSessions.filter(i=>nx(i,e.selectedTasksetId)));else for(const i of e.activeSessions)Rs(i)||(e.filter==="active"?i.savedForLater||t.push(i):e.filter==="in_progress"?!i.savedForLater&&e.inProgressSessionIds.has(i.id)&&t.push(i):e.filter==="pinned"?i.pinned&&!i.savedForLater&&t.push(i):e.filter==="saved_for_later"&&i.savedForLater&&t.push(i));const n=t.filter(i=>wu(i,{inProgressSessionIds:e.inProgressSessionIds,onlyRunningTasks:e.onlyRunningTasks,showCodexChats:e.showCodexChats})),a=e.previewSessionIds?new Map(e.previewSessionIds.map((i,r)=>[i,r])):null;return e.sort==="recent"?n.sort((i,r)=>ix(i,r,a)):n.sort((i,r)=>{const s=a?.get(i.id),c=a?.get(r.id);if(s!==void 0||c!==void 0){if(s===void 0)return 1;if(c===void 0)return-1;if(s!==c)return s-c}return i.order!==r.order?i.order-r.order:ix(i,r)})}function wu(e,t){return t.showCodexChats===!1&&(e.provider==="codex"||Vt(e.id))?!1:!t.onlyRunningTasks||t.inProgressSessionIds.has(e.id)}function nx(e,t){const n=Rs(e);return!!(n&&(!t||n.id===t))}function n8(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 ax(e,t,n){const a=new Set(t);let i=0;return e.map(r=>{if(!a.has(r))return r;const s=n[i];return i+=1,s??r})}function ix(e,t,n=null){const a=mc(e),i=mc(t);if(a!==i)return a?-1:1;if(a&&i){const s=n?.get(e.id),c=n?.get(t.id);if(s!==void 0||c!==void 0){if(s===void 0)return 1;if(c===void 0)return-1;if(s!==c)return s-c}if(e.order!==t.order)return e.order-t.order}const r=Date.parse(t.updatedAt)-Date.parse(e.updatedAt);return r!==0?r:e.title.localeCompare(t.title)}function mc(e){return e.pinned&&!e.savedForLater&&!e.archived}const eu={showCodexChats:!0,onlyRunningTasks:!1},iP="openpond.sidebar-task-visibility.v1";function ox(e=oP()){try{const t=e?.getItem(iP);if(!t)return eu;const n=JSON.parse(t);return{showCodexChats:typeof n.showCodexChats=="boolean"?n.showCodexChats:eu.showCodexChats,onlyRunningTasks:typeof n.onlyRunningTasks=="boolean"?n.onlyRunningTasks:eu.onlyRunningTasks}}catch{return eu}}function rx(e,t=oP()){try{t?.setItem(iP,JSON.stringify(e))}catch{}}function oP(){return typeof window>"u"?null:gd}function rP(e){return`${e.kind}:${e.id}`}function Lc(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function a8(e){return{kind:"session",id:e}}function i8(e){return{kind:"project",id:e}}function o8(e){return{kind:"draft",id:e}}function r8(e){return e.selectedSessionId?a8(e.selectedSessionId):e.selectedProjectId?i8(e.selectedProjectId):o8(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function s8(e){if(!e.previousScope||e.previousScope.kind!=="draft"||e.activeScope.kind!=="session")return[...e.tabs];if(Lc(e.previousScope,e.activeScope))return[...e.tabs];const t=e.now??Date.now();return e.tabs.map(n=>Lc(n.scope,e.previousScope)?{...n,scope:e.activeScope,updatedAt:t}:n)}function sie(e,t){return e.filter(n=>Lc(n.scope,t))}function lie(e,t){return!!(e&&Lc(e.scope,t))}function l8(e){const t={};for(const n of e){const a=rP(n.scope),i=t[a]??{scope:n.scope,tabCount:0,runningCount:0,failedCount:0,lastExitCode:null,status:"none"};i.tabCount+=1,n.commandStatus==="running"&&(i.runningCount+=1),(n.commandStatus==="failed"||n.status==="error")&&(i.failedCount+=1),n.lastExitCode!==null&&(i.lastExitCode=n.lastExitCode),i.status=d8(i.status,n.status,n.commandStatus),t[a]=i}return t}function c8(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 d8(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 sP(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"],i=m8(e),r=t?.linkedCloudSourceKnown===!1&&!!e.headCommit;return i?a.push(i):r?a.push("upload required"):e.diverged?(e.ahead>0&&a.push(Bo("ahead",e.ahead)),e.behind>0&&a.push(Bo("behind",e.behind)),a.push("diverged")):(e.ahead>0&&a.push(Bo("ahead",e.ahead)),e.behind>0&&a.push(Bo("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 lP(e,t,n,a={}){const i=e?.linkedSandboxProject??null;if(!i?.projectId&&!t)return"upload required";if(i?.projectId&&a.cloudLinkTrusted===!1)return"uploaded to a different account";const r=i?.defaultBranch??t?.defaultBranch??"main",s=i?.manifestHash??null,c=e?.sandboxTemplate?.manifestHash??null,m=i?.syncedAt??t?.syncedAt??null,u=!!(s&&c&&s!==c),h=!!(i?.projectId&&n?.headCommit&&!i.lastUploadedCommit),g=p8(n);return g?`${r} / ${g}`:h?`${r} / upload required`:`${r} / ${u||!m?"needs sync":"setup ready"}`}function u8(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=[],i=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"),i>0&&a.push(cP(i)),t.linkedSourceHeadCommit&&t.headCommit&&t.linkedSourceHeadCommit!==t.headCommit&&t.linkedSourceComparisonError&&i===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 m8(e){return e.linkedSourceHeadCommit?e.divergedFromLinkedSource?"diverged":e.aheadOfLinkedSource>0?Bo("local ahead",e.aheadOfLinkedSource):e.behindLinkedSource>0?Bo("cloud ahead",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"sync unknown":null:null}function p8(e){return e?.linkedSourceHeadCommit?e.dirty?"local dirty files not in cloud":e.divergedFromLinkedSource?"diverged from local":e.aheadOfLinkedSource>0?Bo("cloud behind local",e.aheadOfLinkedSource):e.behindLinkedSource>0?Bo("cloud ahead local",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"source check unavailable":"synced":null}function Bo(e,t){return`${e} by ${cP(t)}`}function cP(e){return`${e} commit${e===1?"":"s"}`}function f8({size:e=14,className:t}){return x.jsxs("svg",{className:["lucide lucide-cloud-upload",t??""].filter(Boolean).join(" "),xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[x.jsx("path",{d:"M12 13v8"}),x.jsx("path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"}),x.jsx("path",{d:"m8 17 4-4 4 4"})]})}function dP({kind:e,linkedCloud:t=!1,open:n=!1,className:a,baseSize:i=15}){const r=e==="cloud"?"cloud":n?"folder-open":"folder";return x.jsx("span",{className:["project-kind-icon",e,t?"linked-cloud":"",a??""].filter(Boolean).join(" "),"aria-hidden":"true",children:x.jsxs("svg",{className:`lucide lucide-${r} project-kind-icon-svg`,xmlns:"http://www.w3.org/2000/svg",width:i,height:i,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e==="cloud"?x.jsx(v8,{}):n?x.jsx(g8,{}):x.jsx(h8,{}),t&&e==="local"?x.jsx(b8,{}):null]})})}function h8(){return x.jsx("path",{className:"project-kind-icon-base",d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}function g8(){return x.jsx("path",{className:"project-kind-icon-base",d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"})}function v8(){return x.jsx("path",{className:"project-kind-icon-base",d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"})}function b8(){return x.jsxs("g",{className:"project-kind-icon-cloud-badge",children:[x.jsx("circle",{cx:"18",cy:"17",r:"5"}),x.jsx("path",{d:"M20.4 18.6h-4.2a2.2 2.2 0 1 1 2.08-2.9h.88a1.45 1.45 0 1 1 1.24 2.9Z"})]})}var Ag=eT();function y8({title:e,pinned:t,savedForLater:n,archived:a,onRename:i,onTogglePin:r,onToggleSaveForLater:s,onDockRight:c,onArchive:m}){const u=y.useRef(null),h=y.useRef(null),[g,S]=y.useState(null),k=[...i?[{label:"Rename",Icon:Xm,action:i}]:[],{label:t?"Unpin":"Pin",Icon:t?Vb:Fb,action:r},...s?[{label:n?"Return to active":"Save for later",Icon:n?TR:AR,action:s}]:[],...c?[{label:"Open in right panel",Icon:bg,action:c}]:[],{label:a?"Reopen":"Mark done",Icon:a?l9:Yi,action:m}];function C(A=!1){S(null),A&&u.current?.focus()}return y.useEffect(()=>{if(!g)return;h.current?.querySelector("button")?.focus();const A=R=>{!h.current?.contains(R.target)&&!u.current?.contains(R.target)&&S(null)},M=()=>S(null);return document.addEventListener("pointerdown",A),window.addEventListener("resize",M),()=>{document.removeEventListener("pointerdown",A),window.removeEventListener("resize",M)}},[g]),x.jsxs(x.Fragment,{children:[x.jsx("div",{className:`sidebar-row-actions sidebar-task-menu-trigger${g?" is-open":""}`,children:x.jsx("button",{ref:u,type:"button",className:"sidebar-row-action","aria-label":`More actions for task ${e}`,"aria-haspopup":"menu","aria-expanded":!!g,draggable:!1,onDoubleClick:A=>A.stopPropagation(),onClick:A=>{if(A.stopPropagation(),g){C(!0);return}const M=A.currentTarget.getBoundingClientRect();S({left:Math.max(8,Math.min(M.right-192,window.innerWidth-200)),top:Math.max(8,Math.min(M.bottom+4,window.innerHeight-(k.length*32+17)))})},children:x.jsx(md,{size:16})})}),g&&Ag.createPortal(x.jsx("div",{ref:h,role:"menu","aria-label":`Actions for ${e}`,className:"sidebar-task-menu",style:g,onClick:A=>A.stopPropagation(),onDoubleClick:A=>A.stopPropagation(),onBlur:A=>{A.currentTarget.contains(A.relatedTarget)||C()},onKeyDown:A=>{A.stopPropagation();const M=Array.from(A.currentTarget.querySelectorAll("button")),R=M.indexOf(document.activeElement);if(A.key==="Escape"&&(A.preventDefault(),C(!0)),["ArrowDown","ArrowUp","Home","End"].includes(A.key)){A.preventDefault();const $=A.key==="Home"?0:A.key==="End"?M.length-1:(R+(A.key==="ArrowDown"?1:-1)+M.length)%M.length;M[$]?.focus()}},children:k.map(({label:A,Icon:M,action:R},$)=>x.jsxs("button",{type:"button",role:"menuitem",className:$===k.length-1?"task-menu-done":void 0,onClick:()=>{C(!0),R()},children:[x.jsx(M,{size:15}),A]},A))}),document.body)]})}function S8({session:e,onSave:t,onClose:n}){const[a,i]=y.useState(e.title),r=y.useRef(null);y.useEffect(()=>{const m=r.current;m&&(m.focus(),m.select())},[]),y.useEffect(()=>{function m(u){u.key==="Escape"&&n()}return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[n]);function s(){const m=a.trim();m&&(t(m),n())}function c(m){m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),s())}return x.jsx("div",{className:"git-dialog-backdrop rename-chat-backdrop",role:"presentation",onMouseDown:n,children:x.jsxs("section",{className:"git-dialog rename-chat-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"rename-chat-title",onMouseDown:m=>m.stopPropagation(),children:[x.jsx("h2",{id:"rename-chat-title",children:"Rename chat"}),x.jsx("textarea",{ref:r,className:"rename-chat-input",value:a,rows:1,maxLength:200,onChange:m=>i(m.target.value),onKeyDown:c,"aria-label":"Chat title"}),x.jsxs("div",{className:"git-dialog-footer",children:[x.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:n,children:"Cancel"}),x.jsx("button",{type:"button",className:"git-dialog-primary",autoFocus:!0,onClick:s,disabled:!a.trim(),children:"Save"})]})]})})}const x8=24;function k8({title:e}){const t=y.useRef(e),[n,a]=y.useState(e);return y.useEffect(()=>{const i=t.current;if(t.current=e,!e){a("");return}if(i||window.matchMedia("(prefers-reduced-motion: reduce)").matches){a(e);return}const r=Array.from(e);let s=0;a("");const c=window.setInterval(()=>{s+=1,a(r.slice(0,s).join("")),s>=r.length&&window.clearInterval(c)},x8);return()=>window.clearInterval(c)},[e]),x.jsx("span",{className:"sidebar-task-title-text","aria-label":e||"New task",children:n||"New task"})}const I8=2650,w8=304,_8=260,C8=new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}),R8=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit"}),P8=new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"});function A8(){return{animationDelay:`${-(Date.now()%I8)}ms`}}function T8(e){const t=e.currentTarget,n=t.firstElementChild;if(!(n instanceof HTMLElement))return;const a=Math.max(0,n.scrollWidth-t.clientWidth),i=a>2;t.dataset.overflowing=String(i),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 hh({label:e,actions:t,actionsVisible:n=!1,className:a,titleAccessory:i,children:r,collapsed:s=!1,titleActive:c=!1,onTitleClick:m,onToggleCollapsed:u}){return x.jsxs("section",{className:["sidebar-section",a,n?"actions-visible":""].filter(Boolean).join(" "),children:[x.jsxs("div",{className:"section-header",children:[x.jsxs("div",{className:"section-title-row",children:[m?x.jsxs("div",{className:"section-title-combo",children:[x.jsx("button",{type:"button",className:`section-title-link${c?" active":""}`,onClick:m,children:x.jsx("span",{children:e})}),u&&x.jsx("button",{type:"button",className:"section-chevron-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:u,children:s?x.jsx(Tr,{size:13}):x.jsx(bo,{size:13})})]}):u?x.jsxs("button",{type:"button",className:"section-title-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:u,children:[x.jsx("span",{children:e}),s?x.jsx(Tr,{size:13}):x.jsx(bo,{size:13})]}):x.jsx("span",{children:e}),i]}),t&&x.jsx("div",{className:"section-actions",children:t})]}),!s&&x.jsx("div",{className:"sidebar-section-body",children:r})]})}function sx({children:e,expanded:t=!1,onClick:n}){return x.jsx("button",{type:"button",className:"sidebar-show-more",onClick:n,children:e??(t?"Show less":"Show more")})}function gh({session:e,selected:t,icon:n,archived:a=!1,hideIcon:i=!1,nested:r=!1,dragging:s,placeholder:c,running:m,goalRuntime:u,subagentRuntime:h,terminalIndicator:g,projectLabel:S,ariaDescribedBy:k,childSessionCount:C=0,childSessionsExpanded:A=!1,onSelect:M,onToggleChildSessions:R,onTogglePin:$,onToggleSaveForLater:O,onDockRight:j,onArchive:I,onDragStart:P,onDragEnd:E,onDragOver:L,onDrop:z,onRename:H}){const[J,X]=y.useState(!1),de=u?.status==="queued",je=u?.tone==="active"&&!de,we=(h?.activeCount??0)>0,te=C>0&&!!R,Me=i&&!te,Se=we||je||!de&&(m??e.status==="active"),oe=we&&h?h.label:je&&u?M8(u):"Running",be=["sidebar-task-row",Hc(e)?"is-draft":"",Se?"has-running-dot":""].filter(Boolean).join(" "),re=y.useMemo(A8,[]),ue=x.jsx(y8,{title:e.title,pinned:!!e.pinned,savedForLater:!!e.savedForLater,archived:a,onRename:H?()=>X(!0):void 0,onTogglePin:$,onToggleSaveForLater:O,onDockRight:j,onArchive:I}),ke=x.jsxs(sy,{selected:t,dataSessionId:e.id,dragging:s,iconless:Me,nested:r,placeholder:c,className:be||void 0,ariaExpanded:te?A:void 0,ariaDescribedBy:k,onSelect:M,onDragStart:P,onDragEnd:E,onDragOver:L,onDrop:z,onDoubleClick:H?()=>X(!0):void 0,children:[Me?null:te?x.jsx("button",{type:"button",className:"sidebar-child-toggle","data-tooltip":A?"Hide subagent conversations":"Show subagent conversations","aria-label":`${A?"Hide":"Show"} ${C} subagent ${C===1?"conversation":"conversations"}`,"aria-expanded":A,onClick:Ie=>{Ie.stopPropagation(),R?.()},children:A?x.jsx(bo,{size:13}):x.jsx(Tr,{size:13})}):n??x.jsx(Qm,{size:15}),x.jsx("span",{className:"row-label-shell",title:S||void 0,children:x.jsx("span",{className:"sidebar-session-title-line",children:x.jsx("span",{className:"row-label sidebar-task-title","data-overflowing":"false",onPointerEnter:T8,children:x.jsx(k8,{title:e.title})})})}),x.jsxs("div",{className:"row-meta",children:[x.jsxs("span",{className:"row-meta-status",children:[g?x.jsx(uP,{indicator:g}):null,Se?x.jsx("span",{className:`sidebar-running-dot${we?" subagent":je?" goal":""}`,style:re,"aria-label":oe}):null]}),ue]})]}),Le=J&&H?x.jsx(S8,{session:e,onSave:Ie=>H(e,Ie),onClose:()=>X(!1)}):null;return x.jsxs(x.Fragment,{children:[ke,Le]})}function E8({file:e,selected:t=!1,placeholder:n,onSelect:a,onTogglePin:i,onToggleSaveForLater:r,onDragStart:s,onDragEnd:c,onDragOver:m,onDrop:u}){const h=e.path.split("/").at(-1)??e.path,g=`${e.workspaceName} · ${e.path}`;return x.jsxs(sy,{selected:t,placeholder:n,className:`sidebar-file-row actions-2${e.available?"":" unavailable"}`,onSelect:a,onDragStart:s,onDragEnd:c,onDragOver:m,onDrop:u,children:[e.available?x.jsx(Bb,{size:15}):x.jsx(I9,{size:15}),x.jsx("span",{className:"row-label-shell",title:g,children:x.jsx("span",{className:"row-label",children:h})}),x.jsx("div",{className:"row-meta",children:x.jsxs("div",{className:"sidebar-row-actions",children:[x.jsx(nm,{label:e.status==="pinned"?"Unpin file":"Pin file",onClick:i,children:e.status==="pinned"?x.jsx(Vb,{size:13}):x.jsx(Fb,{size:13})}),x.jsx(nm,{label:e.status==="saved_for_later"?"Remove from Save for later":"Save file for later",onClick:r,children:e.status==="saved_for_later"?x.jsx(TR,{size:13}):x.jsx(AR,{size:13})})]})})]})}function M8(e){return e.actionLabel}function j8({kind:e="local",project:t,pinned:n=!1,selected:a,expanded:i=!1,disclosure:r=!0,workspaceState:s,cloudLinkTrusted:c=!0,cloudLinkWarning:m=null,placeholder:u,terminalIndicator:h,onSelect:g,onNewChat:S,onMoveToCloud:k,onWorkspaceTargetSelect:C,onTogglePin:A,onRemove:M,onDragStart:R,onDragEnd:$,onDragOver:O,onDrop:j}){const[I,P]=y.useState(!1),E=y.useRef(null),[L,z]=y.useState({}),H=!!k||!!M,J=e==="local"&&c!==!1&&!!t.linkedSandboxProject?.projectId,X=y.useCallback(()=>{if(typeof window>"u")return;const we=E.current?.getBoundingClientRect();if(!we)return;const te=Math.max(12,window.innerWidth-w8-12),Me=Math.max(12,window.innerHeight-_8),Se=Math.max(12,Math.min(we.right+10,te)),oe=Math.max(12,Math.min(we.top-4,Me)),be={"--sidebar-project-locations-left":`${Math.round(Se)}px`,"--sidebar-project-locations-top":`${Math.round(oe)}px`};z(re=>re["--sidebar-project-locations-left"]===be["--sidebar-project-locations-left"]&&re["--sidebar-project-locations-top"]===be["--sidebar-project-locations-top"]?re:be)},[]),de=y.useCallback(()=>{X(),g()},[g,X]);function je(){P(!1)}return x.jsxs("div",{ref:E,className:["sidebar-project-row-shell",I?"project-menu-open":""].filter(Boolean).join(" "),onFocusCapture:X,onPointerEnter:X,children:[x.jsxs(sy,{selected:a,placeholder:u,className:["sidebar-project-row",I?"project-menu-open":""].filter(Boolean).join(" "),ariaExpanded:r?i:void 0,onSelect:de,onDragStart:R,onDragEnd:$,onDragOver:O,onDrop:j,children:[x.jsx(dP,{kind:e,linkedCloud:J,open:e==="local"&&i,className:"sidebar-row-icon",baseSize:15}),x.jsx("span",{className:"row-label-shell",children:x.jsxs("span",{className:"sidebar-project-title-line",children:[x.jsx("span",{className:"row-label",children:t.name}),x.jsx(O8,{value:t.updatedAt}),r?x.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:i?x.jsx(bo,{size:13}):x.jsx(Tr,{size:13})}):null]})}),x.jsxs("div",{className:"row-meta",children:[x.jsx("span",{className:"row-meta-status",children:h?x.jsx(uP,{indicator:h}):null}),x.jsxs("div",{className:"sidebar-row-actions",children:[x.jsx(nm,{label:n?"Unpin project":"Pin project",onClick:A,children:n?x.jsx(Vb,{size:13}):x.jsx(Fb,{size:13})}),H&&x.jsx(G8,{open:I,onToggleOpen:()=>P(we=>!we)}),x.jsx(nm,{label:"New task",onClick:S,children:x.jsx(Xm,{size:13})})]})]})]}),x.jsx(N8,{kind:e,project:t,workspaceState:s,cloudLinkTrusted:c,cloudLinkWarning:m,onWorkspaceTargetSelect:C,style:L}),I&&x.jsx(J8,{onClose:je,onMoveToCloud:k?()=>{je(),k()}:void 0,onRemove:()=>{je(),M()}})]})}function O8({value:e}){const t=$8(e);if(!t||!e)return null;const n=new Date(e);return x.jsx("time",{className:"sidebar-row-updated-at",dateTime:e,title:`Last updated ${P8.format(n)}`,children:t})}function $8(e,t=new Date){if(!e)return null;const n=new Date(e);if(Number.isNaN(n.getTime()))return null;const a=R8.format(n);return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()?a:`${C8.format(n)} ${a}`}function uP({indicator:e}){return x.jsx("span",{className:`sidebar-terminal-indicator ${e.status}`,"data-tooltip":e.label,"aria-label":e.label,title:e.label,children:x.jsx(HR,{size:13})})}function N8({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:i,onWorkspaceTargetSelect:r,style:s}){const c=L8(e,t,n,a,i);return x.jsxs("aside",{className:"sidebar-project-locations-popover","aria-label":`${t.name} status`,style:s,children:[x.jsx("div",{className:"sidebar-project-locations-title",children:t.name}),x.jsx("div",{className:"sidebar-project-location-list",children:c.map(m=>{const u=["sidebar-project-location-row",m.tone??"",m.actionTarget?"clickable":""].filter(Boolean).join(" "),h=x.jsxs(x.Fragment,{children:[x.jsx("span",{className:["sidebar-project-location-icon",m.key].filter(Boolean).join(" "),"aria-hidden":"true",children:m.icon}),x.jsx("span",{className:"sidebar-project-location-copy",children:x.jsx(D8,{value:m.value})})]});return m.actionTarget?x.jsx("button",{type:"button",className:u,"data-workspace-target":m.actionTarget,disabled:m.disabled||!r,title:m.disabledReason??void 0,onClick:g=>{g.stopPropagation(),!m.disabled&&r?.(m.actionTarget)},children:h},m.key):x.jsx("div",{className:u,children:h},m.key)})})]})}function D8({value:e}){const t=H8(e);return x.jsxs("span",{className:"sidebar-project-location-value","aria-label":e,children:[t.branch?x.jsxs(x.Fragment,{children:[x.jsx("span",{className:"sidebar-project-location-branch",children:t.branch}),x.jsx("span",{className:"sidebar-project-location-separator","aria-hidden":"true",children:"/"})]}):null,x.jsx("span",{className:"sidebar-project-location-status",children:t.status})]})}function H8(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function L8(e,t,n,a=!0,i=null){return e==="cloud"?U8(t):q8(t,n,a,i)}function q8(e,t,n=!0,a=null){const i=z8(e,t,n),r=B8(t),s=V8(e,n),c=n===!1&&a;return[{key:"local",value:i,tone:r?"attention":"local",icon:e.source==="git"?x.jsx(jR,{size:13}):x.jsx(MR,{size:13}),actionTarget:"local"},{key:"cloud",value:c||(s?K8(e,t,n):"not in cloud"),tone:c?"attention":"cloud",icon:x.jsx(Ym,{size:13}),actionTarget:s?"cloud":"upload_cloud"}]}function U8(e){return[{key:"cloud",value:W8(e),tone:e.syncedAt?"cloud":"attention",icon:x.jsx(Ym,{size:13}),actionTarget:"cloud"}]}function z8(e,t,n){const a=F8(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?sP(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function B8(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function F8(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function V8(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function K8(e,t,n){return lP(e,null,t,{cloudLinkTrusted:n})}function W8(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function G8({open:e,onToggleOpen:t}){return x.jsx("button",{type:"button",className:`sidebar-row-action ${e?"active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-haspopup":"menu","aria-expanded":e,onClick:n=>{n.stopPropagation(),t()},children:x.jsx(md,{size:13})})}function J8({onClose:e,onMoveToCloud:t,onRemove:n}){return x.jsxs(x.Fragment,{children:[x.jsx("button",{type:"button",className:"sidebar-project-menu-backdrop","aria-label":"Close project actions",onClick:a=>{a.stopPropagation(),e()}}),x.jsxs("div",{className:"section-menu-popover sidebar-project-row-popover",role:"menu",children:[t&&x.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),t()},children:[x.jsx(f8,{size:13}),x.jsx("span",{children:"Move to Cloud"})]}),x.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),n()},children:[x.jsx(pd,{size:13}),x.jsx("span",{children:"Remove from Projects"})]})]})]})}function sy({children:e,className:t,dataSessionId:n,dragging:a,iconless:i=!1,nested:r=!1,placeholder:s=!1,selected:c,ariaExpanded:m,ariaDescribedBy:u,onSelect:h,onDragStart:g,onDragEnd:S,onDragOver:k,onDrop:C,onDoubleClick:A}){const M=!!g;return x.jsx("div",{className:["sidebar-row",t??"",c?"selected":"",a?"dragging":"",i?"iconless":"",r?"nested":"",s?"placeholder":""].filter(Boolean).join(" "),draggable:M,"data-session-id":n,role:"button",tabIndex:0,"aria-expanded":m,"aria-describedby":u,onClick:h,onDoubleClick:A,onKeyDown:R=>{R.target===R.currentTarget&&(R.key==="Enter"||R.key===" ")&&(R.preventDefault(),h())},onDragStart:g,onDragEnd:S,onDragEnter:R=>{k&&(R.preventDefault(),R.dataTransfer.dropEffect="move",k(R))},onDragOver:R=>{k&&(R.preventDefault(),R.dataTransfer.dropEffect="move",k(R))},onDrop:R=>{C&&(R.preventDefault(),C(R))},children:e})}function nm({children:e,label:t,onClick:n}){return x.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":t,"aria-label":t,onClick:a=>{a.stopPropagation(),n()},children:e})}function Z8({filter:e,groupByProject:t,noun:n,onFilterChange:a,onGroupByProjectChange:i,onOnlyRunningTasksChange:r,onShowCodexChatsChange:s,onTasksetChange:c,onSortChange:m,onlyRunningTasks:u,openMenu:h,setOpenMenu:g,showCodexChats:S,sort:k,selectedTasksetId:C,tasksets:A}){const M=y.useRef(null),[R,$]=y.useState(!1),j=A.find(E=>E.id===C)?.name??ex.find(E=>E.value===e)?.label??"Active",I=h==="tasks-filter",P=h==="chats";return y.useEffect(()=>{if(!I&&!P)return;function E(L){M.current?.contains(L.target)||g(null)}return document.addEventListener("pointerdown",E),()=>document.removeEventListener("pointerdown",E)},[I,g,P]),x.jsxs("div",{className:"sidebar-task-list-controls",ref:M,children:[x.jsxs("div",{className:"section-menu",children:[x.jsx("button",{type:"button",className:`section-icon ${P?"active":""}`,"aria-label":`${n==="tasks"?"Task":"Chat"} list options`,"aria-haspopup":"menu","aria-expanded":P,onClick:()=>g(E=>E==="chats"?null:"chats"),children:x.jsx(md,{size:14})}),P?x.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":`${n==="tasks"?"Task":"Chat"} list options`,children:[x.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":S,onClick:()=>s(!S),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:S?x.jsx(Yi,{size:13}):null}),x.jsx("span",{children:"Show Codex chats, including pinned"})]}),x.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":u,onClick:()=>r(!u),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:u?x.jsx(Yi,{size:13}):null}),x.jsxs("span",{children:["Only running ",n,", including pinned"]})]}),n==="tasks"?x.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":t,onClick:()=>i(!t),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:t?x.jsx(Yi,{size:13}):null}),x.jsx("span",{children:"Group by project"})]}):null,t8.map(E=>x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":k===E.value,onClick:()=>{m(E.value),g(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:k===E.value?x.jsx(Yi,{size:13}):null}),x.jsx("span",{children:E.label})]},E.value))]}):null]}),x.jsxs("div",{className:"section-menu",children:[x.jsx("button",{type:"button",className:`section-icon ${I?"active":""}`,"aria-label":`Filter ${n}: ${j}`,"aria-haspopup":"menu","aria-expanded":I,onClick:()=>g(E=>E==="tasks-filter"?null:"tasks-filter"),children:x.jsx(B9,{size:14})}),I?x.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${n}`,children:ex.map(E=>x.jsxs(y.Fragment,{children:[E.value==="tasksets"?x.jsxs("button",{type:"button",role:"menuitem","aria-expanded":R,onClick:()=>$(L=>!L),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:R?x.jsx(bo,{size:13}):x.jsx(Tr,{size:13})}),x.jsx("span",{children:E.label})]}):x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e===E.value,onClick:()=>{a(E.value),g(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e===E.value?x.jsx(Yi,{size:13}):null}),x.jsx("span",{children:E.label})]}),E.value==="tasksets"&&R?x.jsxs(x.Fragment,{children:[x.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&!C,onClick:()=>{c(null),g(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&!C?x.jsx(Yi,{size:13}):null}),x.jsx("span",{children:"All Tasksets"})]}),A.map(L=>x.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&C===L.id,onClick:()=>{c(L.id),g(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&C===L.id?x.jsx(Yi,{size:13}):null}),x.jsx("span",{children:L.name}),x.jsx("span",{className:"section-menu-option-count","aria-hidden":"true",children:L.chatCount})]},L.id))]}):null]},E.value))}):null]})]})}function Y8({onAddProject:e,onViewProjects:t}){const[n,a]=y.useState(!1),i=y.useRef(null),r=y.useRef(null);return y.useEffect(()=>{if(!n)return;i.current?.querySelector('[role="menuitem"]')?.focus();const s=c=>{i.current?.contains(c.target)||a(!1)};return document.addEventListener("pointerdown",s),()=>document.removeEventListener("pointerdown",s)},[n]),x.jsxs(x.Fragment,{children:[x.jsxs("div",{className:"section-menu",ref:i,onKeyDown:s=>{s.key==="Escape"&&(s.stopPropagation(),a(!1),r.current?.focus())},children:[x.jsx("button",{ref:r,type:"button",className:`section-icon${n?" active":""}`,"aria-label":"Project options","aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(s=>!s),children:x.jsx(md,{size:14})}),n?x.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":"Project options",children:[x.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),t()},children:"View all projects"}),x.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),e()},children:"Add project"})]}):null]}),x.jsx("button",{type:"button",className:"section-icon",onClick:e,"aria-label":"Add project",title:"Add project",children:"+"})]})}const Q8=240,X8=36;function eG(e,t,n=!1){const a=Math.max(12,t.width-Q8-12),i=Math.max(12,t.height-X8-(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,i)))}px`}}function tG({detail:e,onClose:t}){if(y.useEffect(()=>{if(!e||typeof window>"u")return;const i=c=>{c.key==="Escape"&&t()};let r=!1;const s=window.requestAnimationFrame(()=>{window.addEventListener("scroll",t,!0),r=!0});return window.addEventListener("keydown",i),()=>{window.cancelAnimationFrame(s),window.removeEventListener("keydown",i),r&&window.removeEventListener("scroll",t,!0)}},[e,t]),!e)return null;const n=new Date(e.updatedAt),a=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(n);return x.jsxs("aside",{id:e.descriptionId,className:"sidebar-task-detail-popover",style:e.style,role:"tooltip","aria-label":`Last updated for ${e.title}`,children:[x.jsx("time",{dateTime:e.updatedAt,children:a}),e.folderName?x.jsxs("div",{className:"sidebar-task-detail-folder",children:[x.jsx(MR,{size:13,"aria-hidden":"true"}),x.jsx("span",{children:e.folderName})]}):null]})}function nG({children:e,expanded:t,groupKey:n,kind:a,label:i,onToggle:r,onNewTask:s,onOpenProject:c,onRemoveProject:m,project:u}){const h=`sidebar-task-group-${n.replace(/[^a-zA-Z0-9_-]/g,"-")}`,g=a==="draft"?Bb:Qm,[S,k]=y.useState(!1),C=!!(s||c||m);return x.jsxs("section",{className:"sidebar-task-project-group",children:[x.jsxs("div",{className:`sidebar-task-project-group-header-shell${S?" menu-open":""}`,children:[x.jsxs("button",{type:"button",className:"sidebar-task-project-group-header","aria-controls":h,"aria-expanded":t,onClick:()=>{k(!1),r()},children:[u?x.jsx(dP,{kind:u.kind,linkedCloud:!!(u.kind==="local"&&u.project.linkedSandboxProject?.projectId),open:u.kind==="local"&&t,className:"sidebar-task-project-group-icon",baseSize:14}):x.jsx(g,{className:"sidebar-task-project-group-icon",size:14,"aria-hidden":"true"}),x.jsx("span",{className:"sidebar-task-project-group-name",children:i}),x.jsx("span",{className:"sidebar-task-project-group-caret","aria-hidden":"true",children:t?x.jsx(bo,{size:13}):x.jsx(Tr,{size:13})})]}),u&&C?x.jsxs("div",{className:"sidebar-task-project-group-actions",children:[c||m?x.jsx("button",{type:"button",className:`sidebar-row-action${S?" active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-expanded":S,"aria-haspopup":"menu",onClick:()=>k(A=>!A),children:x.jsx(md,{size:13})}):null,s?x.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":"New task","aria-label":"New task",onClick:s,children:x.jsx(Xm,{size:13})}):null]}):null,S?x.jsxs(x.Fragment,{children:[x.jsx("button",{type:"button",className:"sidebar-task-project-group-menu-backdrop","aria-label":"Close project actions",onClick:()=>k(!1)}),x.jsxs("div",{className:"section-menu-popover sidebar-task-project-group-menu",role:"menu",children:[c?x.jsx("button",{type:"button",role:"menuitem",onClick:()=>{k(!1),c()},children:x.jsx("span",{children:"Open project"})}):null,m?x.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{k(!1),m()},children:[x.jsx(pd,{size:13}),x.jsx("span",{children:"Remove from Projects"})]}):null]})]}):null]}),t?x.jsx("div",{id:h,className:"sidebar-task-project-group-content",children:e}):null]})}const aG={},iG=new Map,oG=new Map;function rG(e,t){return Math.min(Math.max(e,Hn)+Cg,t)}function sG(e,t){const n=Math.max(Hn,Math.min(e,t));if(n<=Hn)return Hn;const a=Math.ceil((n-Hn)/Cg);return Math.max(Hn,Hn+(a-1)*Cg)}function lG(e,t){const n=new Map;for(const a of e){const i=t(a),r=n.get(i.key);r?r.sessions.push(a):n.set(i.key,{...i,sessions:[a]})}return[...n.values()]}function cG({activeSessions:e,archiveSession:t,archivedSessions:n,chatRowsVisibleCount:a,childSessionRowsByParentId:i={},cloudProjectRows:r,beginProjectChat:s,onAddProject:c,commitTaskDrop:m,commitTaskPreviewDrop:u,dockSessionRight:h,experience:g="work",goalRuntimeBySessionId:S=iG,localProjectRows:k,openSidebarFile:C,pinnedCollapsed:A,pinnedRows:M,previewTaskDrop:R,previewPinnedDrop:$,projectRows:O,renameSession:j,restoreSession:I,runningSessionIds:P,sectionMenuOpen:E,selectedProjectId:L,selectedSessionId:z,setChatRowsVisibleCount:H,setSectionMenuOpen:J,setSelectedAppId:X,setSelectedProjectId:de,setSelectedSessionId:je,setView:we,sidebarProjectIdBySessionId:te,startTaskDrag:Me,startPinnedDrag:Se,subagentRuntimeBySessionId:oe=oG,taskDragSessionId:be,taskPreviewSessionIds:re,terminalSummaries:ue=aG,toggleSessionPinned:ke,toggleSessionSavedForLater:Le,view:Ie,clearTaskDrag:le,removeProject:xe,toggleProjectPinned:Ue,onTogglePinnedCollapsed:Ze,setSidebarFileStatus:it,commitPinnedDrop:at,commitPinnedPreviewDrop:Ne,clearSidebarDrag:We,dragItem:qe}){const[q,N]=y.useState("active"),[F,ee]=y.useState("recent"),[me,$e]=y.useState(!0);y.useEffect(()=>{g!=="chat"&&$e(!0)},[g]);const[ze,tt]=y.useState({work:!1,chat:!0}),[nt,mt]=y.useState({work:!1,chat:!1}),vt=g==="chat"?"chat":"work",Oe=ze[vt],[Ye,f]=y.useState(ox);hd(()=>f(ox()));const{onlyRunningTasks:U,showCodexChats:Y}=Ye,[ge,se]=y.useState(null),[G,_]=y.useState(()=>new Set),[W,ne]=y.useState(()=>new Map),[Z,ce]=y.useState(null);y.useEffect(()=>{L&&tt(K=>K[vt]?{...K,[vt]:!1}:K)},[vt,L]);const pe=g==="chat"?"chats":"tasks",fe=O??[...k,...r],Ae=y.useMemo(()=>new Map(fe.map(K=>[K.id,K.project.name])),[fe]),Ce=y.useMemo(()=>new Map(fe.map(K=>[K.id,K])),[fe]),He=y.useMemo(()=>{const K=new Set(P);for(const Be of e){const _e=S.get(Be.id),Ve=oe.get(Be.id);(_e?.tone==="active"&&_e.status!=="queued"||(Ve?.activeCount??0)>0||Ht(Be.id)?.status==="running")&&K.add(Be.id)}return K},[e,S,P,oe,ue]),Pe=y.useMemo(()=>tx({activeSessions:e,doneSessions:n,filter:"all",inProgressSessionIds:He,sort:"manual"}),[e,n,He]),Xe=y.useMemo(()=>tx({activeSessions:e,doneSessions:n,filter:q,inProgressSessionIds:He,onlyRunningTasks:U,selectedTasksetId:ge,previewSessionIds:re,showCodexChats:Y,sort:F}),[e,n,He,U,ge,Y,q,re,F]),ut=y.useMemo(()=>{const K=new Map;for(const Be of[...e,...n]){if(!wu(Be,{inProgressSessionIds:He,onlyRunningTasks:U,showCodexChats:Y}))continue;const _e=Rs(Be);if(!_e)continue;const Ve=K.get(_e.id);Ve?Ve.chatCount+=1:K.set(_e.id,{..._e,chatCount:1})}return[...K.values()].sort((Be,_e)=>Be.name.localeCompare(_e.name))},[e,n,He,U,Y]),fn=y.useMemo(()=>M.filter(K=>K.type!=="session"||wu(K.session,{inProgressSessionIds:He,onlyRunningTasks:U,showCodexChats:Y})),[He,U,M,Y]),jt=y.useMemo(()=>Xe.filter(K=>!mc(K)),[Xe]),dn=y.useMemo(()=>jt.slice(0,Math.max(Hn,a)),[a,jt]),yn=y.useMemo(()=>{const K=lG(dn,Be=>{if(Hc(Be))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const _e=te[Be.id],Ve=St(Be)??"Work";return{key:_e?`project:${_e}`:`projectless:${Ve}`,label:Ve,projectId:_e??null,project:_e?Ce.get(_e)??null:null,kind:_e?"project":"projectless"}});for(const Be of fe)K.some(_e=>_e.projectId===Be.id)||K.push({key:`project:${Be.id}`,label:Be.project.name,projectId:Be.id,project:Be,kind:"project",sessions:[]});return K},[fe,Ae,Ce,te,dn]),Sn=dn.length<jt.length,Qt=dn.length>Hn,Wa=y.useMemo(()=>new Set(yn.filter(K=>K.sessions.some(Be=>Be.id===z||He.has(Be.id))).map(K=>K.key)),[yn,He,z]),wa=Pe.filter(K=>!mc(K)).map(K=>K.id),zn=dn.map(K=>K.id),$n=JSON.stringify(Object.entries(i).filter(([K,Be])=>Be.length>0&&(oe.get(K)?.activeCount??0)>0).flatMap(([K,Be])=>Be.map(_e=>[K,_e.id])).sort(([K,Be],[_e,Ve])=>K.localeCompare(_e)||Be.localeCompare(Ve)));y.useEffect(()=>{const K=JSON.parse($n);if(K.length===0)return;const Be=new Set(K.map(([_e])=>_e));_(_e=>[...Be].every(Ve=>_e.has(Ve))?_e:new Set([..._e,...Be]))},[$n]);function Ht(K){return c8(ue[rP({kind:"session",id:K})])}function St(K){if(Hc(K))return"Draft";const Be=te[K.id];return Be?Ae.get(Be)??K.workspaceName??"Project":JW(K)}function xn(K){ln({kind:"chat",sessionId:K.id}),je(K.id);const Be=te[K.id]??null;X(Be?null:K.appId),de(Be),we("chat")}function xt(K){return(i[K.id]??[]).filter(Be=>wu(Be,{inProgressSessionIds:He,onlyRunningTasks:U,showCodexChats:Y}))}function Nt(K,Be){return G.has(K.id)||Be.some(_e=>_e.id===z)}function _a(K){_(Be=>{const _e=new Set(Be);return _e.has(K)?_e.delete(K):_e.add(K),_e})}function Ft(K){const Be=xt(K);return Be.length===0||!Nt(K,Be)?null:x.jsx("div",{className:"sidebar-child-session-group",children:Be.map(_e=>x.jsx(gh,{session:_e,selected:Ie==="chat"&&z===_e.id,hideIcon:!0,nested:!0,running:He.has(_e.id),goalRuntime:S.get(_e.id)??null,subagentRuntime:oe.get(_e.id)??null,terminalIndicator:Ht(_e.id),projectLabel:St(K),onSelect:()=>xn(_e),onTogglePin:()=>ke(_e),onToggleSaveForLater:()=>Le(_e),onDockRight:()=>h(_e),onArchive:()=>_e.archived?I(_e):t(_e),onRename:j},_e.id))})}function kn(K,Be){if(typeof window>"u")return;const _e=mc(K)?St(K):null;ce({descriptionId:`sidebar-task-detail-${K.id}`,sessionId:K.id,title:K.title,updatedAt:K.updatedAt,folderName:_e,style:eG(Be.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight},!!_e)})}function rt(K,Be={}){const _e=K.archived,Ve=be===K.id,It=xt(K),na="sidebar-session-group",In=F==="manual"?{onDragStart:Je=>Me(Je,{allSessionIds:wa,visibleSessionIds:zn,sessionId:K.id}),onDragEnd:le,onDragOver:Je=>{Ve||R(Je,K.id)},onDrop:Je=>{Ve?u():m(Je,K.id)}}:{};return x.jsxs("div",{className:na,onPointerEnter:Je=>kn(K,Je.currentTarget),onPointerLeave:()=>ce(null),onFocusCapture:Je=>kn(K,Je.currentTarget),onBlurCapture:Je=>{Je.currentTarget.contains(Je.relatedTarget)||ce(null)},children:[x.jsx(gh,{session:K,selected:!_e&&Ie==="chat"&&z===K.id,archived:_e,hideIcon:!0,placeholder:Ve,running:He.has(K.id),goalRuntime:S.get(K.id)??null,subagentRuntime:oe.get(K.id)??null,terminalIndicator:Ht(K.id),projectLabel:Be.projectLabel===void 0?St(K):Be.projectLabel,metadataPresentation:Be.metadataPresentation,ariaDescribedBy:Z?.sessionId===K.id?Z.descriptionId:void 0,childSessionCount:It.length,childSessionsExpanded:Nt(K,It),onToggleChildSessions:()=>_a(K.id),onSelect:()=>{ce(null),_e&&I(K),xn(K)},onTogglePin:()=>ke(K),onToggleSaveForLater:()=>Le(K),onDockRight:()=>h(K),onArchive:()=>_e?I(K):t(K),onRename:j,...In}),Ve?null:Ft(K)]},K.id)}function jn(K){K!=="tasksets"&&se(null),N(K),H(Hn)}function ui(K){se(K),N("tasksets"),H(Hn)}function mi(K){ee(K),H(Hn)}function ha(){H(K=>rG(K,jt.length))}function Ca(){H(K=>sG(K,jt.length))}function Bn(K){const Be={id:K.id,type:K.type};return{onDragStart:_e=>Se(_e,Be),onDragEnd:We,onDragOver:_e=>$(_e,Be),onDrop:_e=>{qe?.id===K.id&&qe.type===K.type?Ne():at(_e,Be)}}}function Li(K){const Be=Bn(K),_e=qe?.id===K.id&&qe.type===K.type;if(K.type==="project"){const It=K.item;return x.jsx(j8,{kind:It.kind,project:It.project,pinned:!0,selected:Ie==="chat"&&L===It.id,expanded:!1,disclosure:!1,placeholder:_e,onSelect:()=>{X(null),de(It.id),je(null),we("chat")},onNewChat:()=>s(It.id),onTogglePin:()=>Ue(It),onRemove:()=>xe(It),...Be},K.key)}if(K.type==="file")return x.jsx(E8,{file:K.file,placeholder:_e,onSelect:()=>C(K.file),onTogglePin:()=>it(K.file,"none"),onToggleSaveForLater:()=>it(K.file,"saved_for_later"),...Be},K.key);const Ve=K.session;return x.jsx("div",{onPointerEnter:It=>kn(Ve,It.currentTarget),onPointerLeave:()=>ce(null),onFocusCapture:It=>kn(Ve,It.currentTarget),onBlurCapture:It=>{It.currentTarget.contains(It.relatedTarget)||ce(null)},children:x.jsx(gh,{ariaDescribedBy:Z?.sessionId===Ve.id?Z.descriptionId:void 0,session:Ve,selected:Ie==="chat"&&z===Ve.id,hideIcon:!0,placeholder:_e,running:He.has(Ve.id),goalRuntime:S.get(Ve.id)??null,subagentRuntime:oe.get(Ve.id)??null,terminalIndicator:Ht(Ve.id),projectLabel:St(Ve),metadataPresentation:"flyout",onSelect:()=>{ce(null),xn(Ve)},onTogglePin:()=>ke(Ve),onToggleSaveForLater:()=>Le(Ve),onDockRight:()=>h(Ve),onArchive:()=>t(Ve),onRename:j,...Be})},K.key)}function Ga(K){const Be=Wa.has(K.key)||W.get(K.key)!==!1;return x.jsx(nG,{expanded:Be,groupKey:K.key,kind:K.kind,label:K.label,onToggle:()=>{ne(_e=>{const Ve=new Map(_e);return Ve.set(K.key,!Be),Ve})},onNewTask:K.project?()=>s(K.project.id):void 0,onOpenProject:K.project?()=>{X(null),de(K.project.id),je(null),we("chat")}:void 0,onRemoveProject:K.project?()=>xe(K.project):void 0,project:K.project,children:K.sessions.map(_e=>rt(_e,{metadataPresentation:"flyout",projectLabel:K.label}))},K.key)}return x.jsxs("div",{className:"sidebar-sections",children:[fn.length>0?x.jsx(hh,{label:"Pinned",className:"sidebar-pinned-section",collapsed:A,onToggleCollapsed:Ze,children:fn.map(Li)}):null,x.jsx(hh,{label:"Projects",className:`sidebar-projects-section${g!=="chat"?" development":""}`,collapsed:Oe,onToggleCollapsed:()=>tt(K=>({...K,[vt]:!K[vt]})),actions:x.jsx(Y8,{onAddProject:c,onViewProjects:()=>{(async()=>await ln({kind:"view",view:"projects"})&&(X(null),de(null),je(null),we("projects")))()}}),children:yn.filter(K=>K.kind==="project").map(K=>Ga(g==="chat"||!me?{...K,sessions:[]}:K))}),x.jsxs(hh,{label:g==="chat"?"Chat":"Work",className:"sidebar-task-section sidebar-ordinary-section",collapsed:nt[vt],onToggleCollapsed:()=>mt(K=>({...K,[vt]:!K[vt]})),actionsVisible:E==="chats"||E==="tasks-filter"||q!=="active"||U||!Y,actions:x.jsx(Z8,{filter:q,groupByProject:me,noun:pe,onFilterChange:jn,onGroupByProjectChange:$e,onOnlyRunningTasksChange:K=>{f(Be=>{const _e={...Be,onlyRunningTasks:K};return rx(_e),_e}),H(Hn)},onShowCodexChatsChange:K=>{f(Be=>{const _e={...Be,showCodexChats:K};return rx(_e),_e}),H(Hn)},onTasksetChange:ui,onSortChange:mi,onlyRunningTasks:U,openMenu:E,setOpenMenu:J,showCodexChats:Y,sort:F,selectedTasksetId:ge,tasksets:ut}),children:[(g==="chat"||!me?dn:dn.filter(K=>!te[K.id])).map(K=>rt(K)),jt.length===0&&fn.length===0?x.jsx("div",{className:"empty-row",children:n8(q,pe)}):null,jt.length>Hn&&(Sn||Qt)?x.jsxs("div",{className:"sidebar-pagination-controls","aria-label":`Showing ${dn.length} of ${jt.length} ${pe}`,children:[Sn?x.jsx(sx,{onClick:ha,children:"Show more"}):null,Qt?x.jsx(sx,{onClick:Ca,children:"Show less"}):null]}):null]}),x.jsx(tG,{detail:Z,onClose:()=>ce(null)})]})}const dG="/";function da(e){return`${dG}${e.replace(/^\.?\//,"")}`}const uG=da("openpond-icon.png"),mG=da("openpond-wordlogo-white.png"),cie=da("tutorials/what-is-an-openpond-agent-poster.png"),die=da("tutorials/what-is-an-openpond-agent.vtt"),uie=da("tutorials/how-to-make-an-agent-poster.png"),mie=da("tutorials/how-to-make-an-agent.vtt");function pie(e){return da(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function fie(e){return da(`tutorials/how-to-make-an-agent-${e}.vtt`)}const lx={github:da("connected-apps/github.svg"),google:da("connected-apps/google.svg"),microsoft_teams:da("connected-apps/microsoft.svg"),mcp:da("connected-apps/openpond-mcp.svg"),slack:da("connected-apps/slack.svg"),x:da("connected-apps/x.svg")};function hie(e){return lx[e]??lx.mcp}function pG({value:e,onChange:t}){const[n,a]=y.useState(!1),i=y.useRef(null),r=y.useRef(null),s=y.useRef(null),c=y.useRef(null),m=dh.find(S=>S.value===e)??dh[0];y.useEffect(()=>{if(!n)return;const S=C=>{C.target instanceof Node&&!i.current?.contains(C.target)&&a(!1)},k=()=>a(!1);return window.addEventListener("pointerdown",S),window.addEventListener("blur",k),()=>{window.removeEventListener("pointerdown",S),window.removeEventListener("blur",k)}},[n]),y.useLayoutEffect(()=>{n&&c.current&&cx(s.current,c.current),c.current=null},[n]);const u=S=>{if(n){cx(s.current,S);return}c.current=S,a(!0)},h=S=>{S.key==="ArrowDown"?(S.preventDefault(),u("first")):S.key==="ArrowUp"&&(S.preventDefault(),u("last"))},g=S=>{const k=mP(s.current),C=k.findIndex(R=>R===document.activeElement);if(S.key==="Escape"){S.preventDefault(),a(!1),r.current?.focus();return}if(S.key==="Home"||S.key==="End"){S.preventDefault(),k[S.key==="Home"?0:k.length-1]?.focus();return}if(S.key!=="ArrowDown"&&S.key!=="ArrowUp")return;S.preventDefault();const A=S.key==="ArrowDown"?1:-1,M=C<0?0:(C+A+k.length)%k.length;k[M]?.focus()};return x.jsxs("div",{className:"sidebar-experience-menu",ref:i,children:[x.jsxs("button",{ref:r,type:"button",className:"sidebar-wordmark-button sidebar-experience-trigger","aria-label":`OpenPond product: ${m.label}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>{c.current=null,a(S=>!S)},onKeyDown:h,children:[x.jsx("img",{className:"sidebar-wordmark",src:mG,alt:""}),x.jsx("span",{className:"sidebar-experience-label",children:m.label}),x.jsx(bo,{size:13,"aria-hidden":"true"})]}),n?x.jsx("div",{ref:s,className:"sidebar-experience-popover",role:"menu","aria-label":"Choose product",onKeyDown:g,children:dh.map(S=>{const k=S.value===e;return x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":k,className:k?"active":"","data-product-area":S.value,onClick:()=>{a(!1),k||t(S.value)},children:[x.jsxs("span",{children:[x.jsx("strong",{children:S.label}),x.jsx("small",{children:S.description})]}),k?x.jsx(Yi,{size:14,"aria-hidden":"true"}):null]},S.value)})}):null]})}function mP(e){return e?Array.from(e.querySelectorAll('[role="menuitemradio"]')):[]}function cx(e,t){const n=mP(e);(t==="first"?n[0]:n.at(-1))?.focus()}function fG(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function hG(e){const t=e?.accounts.find(s=>s.isActive)??null,n=e?.profile??null,a=e?.activeProfile?.handle??null;return{label:(e?.state==="signed_in"?fG(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 gG({account:e,open:t,organizations:n,selectedTeamId:a,onOpenActivity:i,onOpenChange:r,onOpenSettings:s,onSelectTeam:c,onLogOut:m}){const[u,h]=y.useState(null),[g,S]=y.useState(!1),k=y.useRef(null),C=y.useMemo(()=>hG(e),[e]),A=C.label.trim().slice(0,1).toUpperCase(),M=n.find(R=>R.teamId===a)??n[0]??null;return y.useEffect(()=>{if(!t)return;function R(O){k.current?.contains(O.target)||r(!1)}function $(O){O.key==="Escape"&&r(!1)}return document.addEventListener("pointerdown",R),document.addEventListener("keydown",$),()=>{document.removeEventListener("pointerdown",R),document.removeEventListener("keydown",$)}},[r,t]),x.jsxs("div",{className:"user-auth-footer",ref:k,children:[x.jsxs("button",{type:"button",className:`user-auth-trigger ${t?"active":""}`,"aria-haspopup":"menu","aria-expanded":t,"aria-label":`${C.label} account menu`,onClick:()=>r(!t),children:[x.jsx("span",{className:"user-auth-avatar","aria-hidden":"true",children:C.image?x.jsx("img",{src:C.image,alt:""}):A?x.jsx("span",{children:A}):x.jsx(WS,{size:16})}),x.jsx("span",{className:"user-auth-name",children:C.label})]}),t?x.jsxs("div",{className:"user-auth-menu",role:"menu","aria-label":"Account",children:[x.jsxs("div",{className:"user-auth-menu-header",children:[x.jsx("span",{className:"user-auth-menu-avatar","aria-hidden":"true",children:C.image?x.jsx("img",{src:C.image,alt:""}):A?x.jsx("span",{children:A}):x.jsx(WS,{size:17})}),x.jsx("span",{className:"user-auth-menu-identity",children:x.jsx("strong",{children:C.label})})]}),n.length>0&&c?x.jsxs("label",{className:"user-auth-team-picker",children:[x.jsx(DR,{size:15,"aria-hidden":"true"}),x.jsx("span",{className:"user-auth-team-picker-label",children:"Team"}),x.jsx("select",{"aria-label":"Active team",disabled:u!==null,value:M?.teamId??"",onChange:async R=>{const $=R.currentTarget.value;h($);try{await c($)}catch{}finally{h(null)}},children:n.map(R=>x.jsx("option",{value:R.teamId,children:R.displayName},R.teamId))})]}):null,x.jsx("div",{className:"user-auth-menu-divider"}),i?x.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{r(!1),i()},children:[x.jsx(ER,{size:15}),x.jsx("span",{children:"Activity"})]}):null,x.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{r(!1),s()},children:[x.jsx(NR,{size:15}),x.jsx("span",{children:"Settings"})]}),e?.state==="signed_in"&&m?x.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",disabled:g,onClick:async()=>{S(!0);try{await m(),r(!1)}catch{}finally{S(!1)}},children:[x.jsx(aW,{size:15}),x.jsx("span",{children:g?"Logging out…":"Log out"})]}):null]}):null]})}function dx(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 vG(e,t){const n=dx(e),a=dx(t);if(!n||!a)return!1;for(let i=0;i<a.length;i+=1){if(a[i]>n[i])return!0;if(a[i]<n[i])return!1}return!1}function pP(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")?"mac":t==="linux"||t.includes("linux")?"linux":null}function bG(e){const t=e?.toLowerCase()??"";return t==="arm64"||t==="aarch64"?"arm64":t==="x64"||t==="x86_64"||t==="amd64"?"x64":null}function yG(e,t,n){const a=pP(t),i=bG(n);if(a==="mac"){const r=e.filter(s=>/-mac-.*\.zip$/i.test(s.name));return i==="arm64"?r.find(s=>/-mac-arm64\.zip$/i.test(s.name))??null:i==="x64"?r.find(s=>/-mac-x64\.zip$/i.test(s.name))??r.find(s=>/-mac-universal\.zip$/i.test(s.name))??null:r.find(s=>/-mac-universal\.zip$/i.test(s.name))??r.find(s=>/-mac-arm64\.zip$/i.test(s.name))??r[0]??null}if(a==="linux"){const r=e.filter(s=>/\.AppImage$/i.test(s.name));return i==="arm64"?r.find(s=>/(?:arm64|aarch64).*\.AppImage$/i.test(s.name))??null:i==="x64"?r.find(s=>/(?:x86_64|x64|amd64).*\.AppImage$/i.test(s.name))??r[0]??null:r[0]??null}return null}function SG(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(!vG(e.currentVersion,a))return null;const i=typeof t.html_url=="string"?t.html_url:"",s=(Array.isArray(t.assets)?t.assets:[]).flatMap(m=>{if(!m||typeof m!="object")return[];const u=m;return typeof u.name!="string"||typeof u.browser_download_url!="string"?[]:[{name:u.name,downloadUrl:u.browser_download_url}]}),c=yG(s,e.platform,e.arch);return!c||!i?null:{version:a,releaseUrl:i,assetName:c.name,downloadUrl:c.downloadUrl}}const xG=3600*1e3,kG="https://api.github.com/repos/openpond/openpond/releases/latest";function IG(e){const[t,n]=y.useState({status:"idle",update:null,lastCheckedAt:null}),a=e.currentVersion?.trim()??"",i=e.platform??"",r=e.arch??"",s=e.enabled&&!!a&&!!pP(i);return y.useEffect(()=>{if(!s){n({status:"idle",update:null,lastCheckedAt:null});return}let c=!1;async function m(){n(h=>({...h,status:h.update?"available":"checking"}));try{const h=await fetch(kG,{headers:{Accept:"application/vnd.github+json"}});if(!h.ok)throw new Error(`GitHub release check failed: ${h.status}`);const g=await h.json(),S=SG({payload:g,currentVersion:a,platform:i,arch:r});if(c)return;n({status:S?"available":"current",update:S,lastCheckedAt:Date.now()})}catch{if(c)return;n(h=>({status:h.update?"available":"error",update:h.update,lastCheckedAt:Date.now()}))}}m();const u=window.setInterval(()=>{m()},xG);return()=>{c=!0,window.clearInterval(u)}},[r,a,s,i]),t}const fP="openpond.sidebar.continuous-learning.dismissed.v1";function ux(e=hP()){if(!e)return!1;try{return e.getItem(fP)==="true"}catch{return!1}}function wG(e=hP()){if(e)try{e.setItem(fP,"true")}catch{}}function hP(){return typeof window>"u"?null:gd}function _G({connection:e,onOpenSettings:t}){const[n,a]=y.useState(null),[i,r]=y.useState(ux);hd(()=>r(ux()));const s=y.useCallback(async()=>{if(!e){a(null);return}try{a(await Q.harnessHistory(e))}catch{a(null)}},[e]);if(y.useEffect(()=>{s()},[s]),i||!e||!n?.workspace)return null;const c=n.evaluationReviewSchedule,m=c.activityEnabled?`${c.activityBatchSize} outcomes${c.enabled?` + ${c.cadence}`:""}`:c.enabled?c.cadence:"Manual";return x.jsxs("section",{className:"sidebar-learning-notice","aria-label":"Continuous learning",children:[x.jsxs("header",{children:[x.jsx("strong",{children:"Continuous learning"}),x.jsxs("div",{className:"sidebar-learning-notice-actions",children:[x.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Open Continuous learning settings",onClick:t,type:"button",children:x.jsx(NR,{size:14})}),x.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{r(!0),wG()},type:"button",children:x.jsx(pd,{size:14})})]})]}),x.jsxs("div",{className:"sidebar-learning-status",children:[x.jsx("strong",{children:"Refiner"}),x.jsx("span",{children:n.backgroundReview.enabled?"On":"Off"})]}),x.jsxs("div",{className:"sidebar-learning-status",children:[x.jsx("strong",{children:"Continuous Review"}),x.jsx("span",{children:m})]})]})}function CG(e){const[t,n]=y.useState(!1),{beginNewChat:a,arch:i,currentVersion:r,experience:s,productArea:c,onProductAreaChange:m,onSidebarResizeStart:u,platform:h,setSectionMenuOpen:g,setSelectedAppId:S,setSelectedProjectId:k,setSelectedSessionId:C,setSidebarOpen:A,setView:M,view:R,modelProjects:$,modelTrainingActivityByProjectId:O}=e,j=y.useCallback(L=>{n(!1),g(L)},[g]),I=y.useCallback(L=>{n(L),L&&g(null)},[g]),P=IG({currentVersion:r,platform:h,arch:i,enabled:ep()}),E=P.status==="available"?P.update:null;return x.jsxs("aside",{className:"sidebar",children:[x.jsxs("div",{className:"sidebar-toolbar",children:[x.jsx("button",{className:"sidebar-icon","aria-label":"Hide sidebar",onClick:()=>A(!1),children:x.jsx($R,{size:16})}),x.jsx(pG,{value:c,onChange:m}),E&&x.jsxs("button",{type:"button",className:"sidebar-update-pill",title:`Download OpenPond ${E.version}: ${E.assetName}`,"aria-label":`Download OpenPond ${E.version}`,onClick:()=>{RG(E.downloadUrl)},children:[x.jsx(P9,{size:14}),x.jsx("span",{children:"Update"})]})]}),c!=="chat"?null:x.jsx(TW,{experience:s,beginNewChat:a}),x.jsxs("div",{className:"sidebar-scroll",children:[c==="chat"&&e.account?.activeProfile&&e.onOpenPonder?x.jsxs("button",{type:"button",className:"sidebar-ponder-entry",onClick:e.onOpenPonder,children:[x.jsx("span",{"aria-hidden":"true",children:"✦"})," Ponder Pal"]}):null,x.jsx(EW,{productArea:c,setSectionMenuOpen:j,setSelectedAppId:S,setSelectedProjectId:k,setSelectedSessionId:C,setView:M,view:R,modelProjects:$,modelTrainingActivityByProjectId:O}),c!=="chat"?null:x.jsx(cG,{...e,setSectionMenuOpen:j})]}),x.jsxs("div",{className:"sidebar-bottom-stack",children:[c!=="chat"?null:x.jsx(_G,{connection:e.connection,onOpenSettings:()=>{g(null),ln({kind:"settings",section:"harness"})}}),x.jsxs("div",{className:"sidebar-footer-row",children:[x.jsx(gG,{account:e.account,open:t,organizations:e.organizations,selectedTeamId:e.teamChatOrganization?.teamId??null,onOpenChange:I,onOpenActivity:()=>{g(null),ln({kind:"settings",section:"usage"})},onOpenSettings:()=>{g(null),ln({kind:"settings",section:"account"})},onSelectTeam:e.onSelectTeam,onLogOut:e.onLogOut}),x.jsx(MW,{setSectionMenuOpen:j,setSelectedAppId:S,setSelectedProjectId:k,setSelectedSessionId:C,setView:M,view:R})]})]}),x.jsx("div",{className:"sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",onPointerDown:u})]})}async function RG(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-update",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const PG=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function gP(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?vP(a)?"Couldn’t connect to OpenPond.":a:t}function vP(e){const t=e.trim();return PG.some(n=>n.test(t))}const bP=y.createContext(null);function mx({children:e,showToast:t}){return x.jsx(bP.Provider,{value:t,children:e})}function AG(){return y.useContext(bP)}function px(e,t={}){const n=AG(),a=y.useRef(null),i=t.enabled??!0,r=t.fallback??"Something went wrong.",s=t.prefix?.trim()??"",c=e==null||e===""?null:`${s}${s?": ":""}${gP(e,r)}`;y.useEffect(()=>{if(!i||!c){a.current=null;return}a.current!==c&&(a.current=c,n?.(c,"error"))},[i,c,n])}function TG({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(px(e?.previewError,{prefix:"Upload preview"}),px(e?.error,{prefix:"Cloud setup"}),!e)return null;const i=e.status==="uploading",r=e.status==="ready",s=e.status==="error",c=e.projectKind==="cloud",m=e.preview??null;return x.jsx("div",{className:"git-dialog-backdrop",role:"presentation",children:x.jsxs("section",{className:"git-dialog cloud-setup-dialog",role:"dialog","aria-modal":"true","aria-label":"Set up Cloud coding",children:[x.jsx("button",{className:"git-dialog-close",disabled:i,type:"button",onClick:t,"aria-label":"Close Cloud setup",title:"Close",children:x.jsx(pd,{size:14})}),x.jsx("div",{className:"git-dialog-icon",children:r?x.jsx(yu,{size:18}):x.jsx(Ym,{size:18})}),x.jsx("h2",{children:r?"Cloud repo ready":"Set up Cloud coding"}),x.jsx("p",{children:r?"Your source is ready in OpenPond Git. Finish by creating the Cloud sandbox environment.":c?"This Cloud Project is ready for a sandbox environment.":"OpenPond will upload tracked and unignored files into OpenPond Git, then send you to the Cloud sandbox setup page."}),x.jsxs("div",{className:"cloud-setup-summary",children:[x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Project"}),x.jsx("strong",{children:e.projectName})]}),x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Source"}),x.jsx("strong",{children:c?"OpenPond Git":"Local project upload"})]}),x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Branch"}),x.jsx("strong",{children:m?.branch??e.branch??"main"})]}),!c&&x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Cloud project"}),x.jsx("strong",{children:m?.targetProjectId??e.cloudProjectId??"New on upload"})]})]}),!r&&!c&&x.jsx("div",{className:"cloud-setup-upload-preview",role:"status","aria-live":"polite",children:e.previewLoading?x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:"Calculating upload preview"}),x.jsx("span",{children:"Checking tracked and unignored files before anything is pushed."})]}):e.previewError?x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:"Preview unavailable"}),x.jsx("span",{children:"Close and reopen setup to try the preview again."})]}):m?x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:m.initializedEmptyProject?"Will initialize an empty project":`Will upload ${m.fileCount} files`}),x.jsx("span",{children:fx({byteCount:m.byteCount,skippedCount:m.skippedCount,headCommit:m.headCommit,targetProjectName:m.targetProjectName})})]}):x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:"Upload preview pending"}),x.jsx("span",{children:"File count, byte count, and skipped files will appear here before upload."})]})}),i&&x.jsxs("div",{className:"cloud-setup-progress",role:"status","aria-live":"polite",children:[x.jsx(V9,{className:"cloud-setup-spinner",size:16}),x.jsx("span",{children:"Uploading source to OpenPond Git..."})]}),r&&e.upload&&x.jsxs("div",{className:"cloud-setup-upload-result",children:[x.jsx("strong",{children:e.upload.initializedEmptyProject?"Initialized empty project":`Uploaded ${e.upload.fileCount} files`}),x.jsx("span",{children:fx({byteCount:e.upload.byteCount,skippedCount:e.upload.skippedCount,headCommit:e.upload.headCommit,targetProjectName:e.upload.branch})})]}),r&&e.setupUrl&&x.jsxs("div",{className:"cloud-setup-next",children:[e.projectUrl?x.jsxs("span",{children:["Your repo is ready here:"," ",x.jsxs("a",{href:e.projectUrl,target:"_blank",rel:"noreferrer",onClick:u=>vh(u,e.projectUrl,n,{newTab:!0}),children:["Project page",x.jsx(lh,{size:13})]})]}):x.jsx("span",{children:"Your repo is ready. Next step:"}),x.jsxs("a",{href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:u=>vh(u,e.setupUrl,n),children:["Setup the Cloud sandbox",x.jsx(lh,{size:13})]})]}),x.jsxs("div",{className:"git-dialog-footer",children:[x.jsx("button",{className:"git-dialog-secondary",disabled:i,type:"button",onClick:t,children:r?"Done":"Cancel"}),r?e.setupUrl?x.jsxs("a",{className:"git-dialog-primary cloud-setup-primary-link",href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:u=>vh(u,e.setupUrl,n),children:["Open setup",x.jsx(lh,{size:13})]}):null:x.jsx("button",{className:"git-dialog-primary",disabled:i,type:"button",onClick:a,children:i?"Uploading":s?"Try again":c?"Show setup link":"Upload source"})]})]})})}function vh(e,t,n,a={}){!t||!n||(e.preventDefault(),n(t,a))}function EG(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 fx({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const i=[EG(e),`${t} skipped`],r=MG(n);return r&&i.push(`local ${r}`),i.push(a),i.join(" · ")}function MG(e){const t=e?.trim();return t?t.slice(0,7):null}const jG=y.lazy(()=>Er(()=>import("./CommandMenu-D9BimyPx.js"),__vite__mapDeps([0,1,2,3])).then(e=>({default:e.CommandMenu}))),OG=y.lazy(()=>Er(()=>import("./SettingsView-Kh14f463.js"),__vite__mapDeps([4,1,2,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21])).then(e=>({default:e.SettingsView}))),$G=y.lazy(()=>Er(()=>import("./NewProjectDialog-i_wvIBw-.js"),__vite__mapDeps([22,1,2,8,13,23])).then(e=>({default:e.NewProjectDialog}))),NG=y.lazy(()=>Er(()=>import("./WorkspaceGitDialogs-Dyx4Rbiy.js"),__vite__mapDeps([24,1,2,11,12,25,21])).then(e=>({default:e.CommitDialog}))),DG=y.lazy(()=>Er(()=>import("./WorkspaceGitDialogs-Dyx4Rbiy.js"),__vite__mapDeps([24,1,2,11,12,25,21])).then(e=>({default:e.BranchDialog})));function HG({payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:i,onError:r,onToast:s,onBack:c,onOpenSourceSession:m,onStartRefinerAuthoring:u,onAcceptEvaluationReview:h,onOpenSkill:g,onOpenExtension:S,teamChatCurrentUserId:k,teamChatEnabled:C,teamChatNotificationMode:A,teamChatThreads:M,onTeamChatNotificationModeChange:R,onTeamChatThreadMuteChange:$,diffPanelWidth:O,diffPanelResizing:j,diffPanelExpanded:I,onDiffPanelResizeStart:P,onDiffPanelExpandedChange:E}){return x.jsx(y.Suspense,{fallback:null,children:x.jsx(OG,{payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:i,onError:r,onToast:s,onBack:c,onOpenSourceSession:m,onStartRefinerAuthoring:u,onAcceptEvaluationReview:h,onOpenSkill:g,onOpenExtension:S,teamChatCurrentUserId:k,teamChatEnabled:C,teamChatNotificationMode:A,teamChatThreads:M,onTeamChatNotificationModeChange:R,onTeamChatThreadMuteChange:$,diffPanelWidth:O,diffPanelResizing:j,diffPanelExpanded:I,onDiffPanelResizeStart:P,onDiffPanelExpandedChange:E})})}function LG({activeSessions:e,branchDialogName:t,branchDialogOpen:n,commitDialogOpen:a,commitDraft:i,commitIncludeUnstaged:r,commitMessage:s,commitNextStep:c,canPublishOpenPondProject:m,expandProject:u,newProjectBusy:h,newProjectDialogOpen:g,newProjectDirectory:S,newProjectMode:k,newProjectName:C,newProjectPath:A,projectRows:M,query:R,searchOpen:$,visibleWorkspaceDiff:O,visibleWorkspaceState:j,workspaceBusy:I,appDispatch:P,beginNewChat:E,openDefaultsSettingsFromBranchDialog:L,setBranchDialogName:z,setBranchDialogOpen:H,setCommitDialogOpen:J,setCommitDraft:X,setCommitIncludeUnstaged:de,setCommitMessage:je,setCommitNextStep:we,setNewProjectDialogOpen:te,setNewProjectName:Me,setNewProjectPath:Se,setQuery:oe,setSearchOpen:be,submitCommitDialog:re,submitCreateWorkspaceBranch:ue,submitNewProjectDialog:ke}){return x.jsxs(x.Fragment,{children:[$&&x.jsx(y.Suspense,{fallback:null,children:x.jsx(jG,{open:$,query:R,projects:M,sessions:e,onQueryChange:oe,onClose:()=>{be(!1),oe("")},onNewChat:()=>{be(!1),oe(""),E()},onOpenProject:Le=>{P({type:"selectProject",projectId:Le.id}),P({type:"patch",patch:{searchOpen:!1,query:""}}),u(Le.id)},onOpenSession:Le=>{P({type:"selectSession",sessionId:Le.id,appId:Le.appId,projectId:Le.workspaceKind==="local_project"&&Le.workspaceId?wt("local",Le.workspaceId):null}),P({type:"patch",patch:{searchOpen:!1,query:""}})}})}),g&&x.jsx(y.Suspense,{fallback:null,children:x.jsx($G,{open:g,mode:k,name:C,path:A,directory:S,busy:h,onNameChange:Me,onPathChange:Se,onClose:()=>{h||te(!1)},onSubmit:ke})}),a&&x.jsx(y.Suspense,{fallback:null,children:x.jsx(NG,{open:a,branch:j?.currentBranch??null,filesChanged:O?.filesChanged??j?.changedFilesCount??0,additions:O?.additions??0,deletions:O?.deletions??0,message:s,includeUnstaged:r,nextStep:c,draft:i,busy:I,canPush:!!j?.remoteUrl,canPublish:m,onMessageChange:je,onIncludeUnstagedChange:de,onNextStepChange:we,onDraftChange:X,onClose:()=>{I||J(!1)},onSubmit:re})}),n&&x.jsx(y.Suspense,{fallback:null,children:x.jsx(DG,{open:n,branchName:t,busy:I,onBranchNameChange:z,onSetPrefix:L,onClose:()=>{I||H(!1)},onSubmit:ue})})]})}function yP({toast:e,onDismiss:t}){if(!e)return null;const n=!!(e.actionLabel&&e.onAction);return x.jsxs("div",{className:`app-toast ${e.tone} ${e.placement??"bottom-right"}`,role:e.tone==="error"?"alert":"status","aria-live":"polite",children:[x.jsx("span",{className:"app-toast-message",children:e.message}),n&&x.jsx("div",{className:"app-toast-actions",children:x.jsx("button",{type:"button","aria-label":e.actionLabel,onClick:()=>{t(),e.onAction?.()},children:e.actionLabel})})]})}async function tu(e,t,n){if(t.scope!==e.scope)throw new Error("Review workspace changed. Reload the assignment.");return B(e.connection,`/v1/human-review?location=${e.location}`,{method:"POST",body:JSON.stringify(IU.parse(t)),signal:n})}function hx(e,t,n){const a=Nw.parse(e);if(a.scope!==t.scope||a.id!==n)throw new Error("Review response identity differs from the requested assignment.");return a}const qG={inbox:async(e,t,n)=>UG(await tu(e,{...t,endpoint:"inbox",scope:e.scope},n),e),get:async(e,t,n)=>hx(await tu(e,{endpoint:"get",scope:e.scope,id:t},n),e,t),inspect:async(e,t,n,a,i)=>zG(await tu(e,{endpoint:"inspect",scope:e.scope,id:t,...n===void 0?{}:{slot:n},...a?{afterId:a}:{}},i),t),command:async(e,t)=>hx(await tu(e,{endpoint:"command",scope:e.scope,command:t}),e,t.id)};function UG(e,t){const n=dU.parse(e);if(n.items.some(a=>a.scope!==t.scope))throw new Error("Inbox response belongs to another workspace.");return n}function zG(e,t){const n=wU.parse(e);if(n.some(a=>a.reviewId!==t))throw new Error("Evidence response belongs to another assignment.");return n}function BG({context:e,onOpen:t}){const[n,a]=y.useState(null);return y.useEffect(()=>{const i=new AbortController;let r=0;async function s(){const m=++r;try{const u=await qG.inbox(e,{view:"mine",status:"active",limit:1},i.signal);!i.signal.aborted&&m===r&&a(u.actionCount)}catch{!i.signal.aborted&&m===r&&a(null)}}a(null),s();const c=window.setInterval(()=>{document.visibilityState==="visible"&&s()},15e3);return window.addEventListener("human-review-changed",s),()=>{i.abort(),window.clearInterval(c),window.removeEventListener("human-review-changed",s)}},[e.scope,e.actorId,e.location,e.connection]),x.jsxs("button",{type:"button",className:"evaluation-panel-icon","aria-label":n?`Inbox, ${n} actions`:"Inbox",onClick:t,children:[x.jsx(LR,{size:16}),n?x.jsx("span",{children:n}):null]})}function FG({summary:e,scopeKey:t,loading:n,error:a,onRetry:i,onSelect:r}){const[s,c]=y.useState(!1),m=y.useRef(null),u=e?.scopeKey===t?e:null,h=!!(u&&u.counts.training+u.counts.experiments>0),g=k=>new Intl.NumberFormat(void 0,{notation:"compact",maximumFractionDigits:1}).format(k),S=a?u?"Activity reconnecting":"Activity unavailable":n&&!u?"Checking activity":h?"Active work":"No active work";return y.useEffect(()=>{if(!s)return;const k=A=>{m.current?.contains(A.target)||c(!1)},C=A=>{A.key==="Escape"&&(c(!1),m.current?.querySelector("button")?.focus())};return document.addEventListener("pointerdown",k),document.addEventListener("keydown",C),()=>{document.removeEventListener("pointerdown",k),document.removeEventListener("keydown",C)}},[s]),x.jsxs("div",{className:"execution-activity",ref:m,children:[x.jsxs("button",{className:"execution-activity-trigger",type:"button","aria-expanded":s,"aria-controls":"execution-activity-list","aria-label":`${S}${u?`: ${u.counts.training} training, ${u.counts.experiments} experiments`:""}`,onClick:()=>c(k=>!k),children:[x.jsx("span",{"aria-hidden":"true",className:`execution-activity-ring${h?" is-active":""}`}),u?x.jsxs(x.Fragment,{children:[x.jsxs("span",{className:"execution-activity-training",children:[g(u.counts.training)," training"]}),x.jsxs("span",{className:"execution-activity-experiments",children:[g(u.counts.experiments)," experiments"]})]}):x.jsx("span",{children:S})]}),x.jsxs("div",{id:"execution-activity-list",className:"execution-activity-list",hidden:!s,children:[x.jsx("p",{className:"execution-activity-scope",children:"Activity in the selected workspace and Project"}),a?x.jsxs("p",{role:"status",children:[S,". ",x.jsx("button",{type:"button",onClick:i,children:"Retry"})]}):null,x.jsx("ul",{children:u?.items.map(k=>x.jsx("li",{children:x.jsxs("button",{type:"button",onClick:()=>r(k),children:[x.jsx("span",{children:k.name}),x.jsxs("small",{children:[k.kind==="training"?"Training":"Experiment"," ",k.phase.replaceAll("_"," ")]})]})},`${k.kind}:${k.location}:${k.id}`))}),u?.items.length?null:x.jsx("p",{role:"status",children:S}),u?.hasMore?x.jsx("p",{children:"Counts include all active work."}):null]})]})}function VG({connection:e,teamId:t,actorId:n,projectId:a}){const i=JSON.stringify([t,n,a]),r=Bk({queryKey:["workspace-execution-activity",e?.serverUrl,i],enabled:!!(e&&t&&n),staleTime:4e3,refetchInterval:8e3,queryFn:({signal:c})=>B(e,`/v1/training/execution-activity?${new URLSearchParams({teamId:t,...a?{projectId:a}:{}})}`,{signal:c})});if(!e||!t||!n)return null;const s=()=>{po(ma("inbox",null,{area:"console",projectId:a}))};return x.jsxs(x.Fragment,{children:[x.jsx(FG,{summary:r.data??null,scopeKey:i,loading:r.isPending,error:r.error?.message??null,onRetry:()=>{r.refetch()},onSelect:c=>{if(c.kind==="experiment"){const m=c.href?Oc(new URL(c.href,"https://native.openpond.invalid")):null;po(m?{...m,executionLocation:c.location}:ma("experiments",null,{area:"console",resourceId:c.id,projectId:a,executionLocation:c.location}))}else{const m=c.href?Oc(new URL(c.href,"https://native.openpond.invalid")):null;po(c.location==="local"&&m?m:ma("runs",null,{resourceId:`hosted-run:${c.id}`}))}}}),x.jsx(BG,{context:{connection:e,scope:t,actorId:n,location:"hosted"},onOpen:s})]})}const vd=y.createContext(null);function KG({children:e}){const[t,n]=y.useState(null),[a,i]=y.useState(null),[r,s]=y.useState(null),c=y.useMemo(()=>({title:t,actions:a,activity:r,setTitle:n,setActions:i,setActivity:s}),[t,a,r]);return x.jsx(vd.Provider,{value:c,children:e})}function gie({children:e}){return x.jsx(vd.Provider,{value:null,children:e})}function WG({children:e,className:t=""}){const n=y.useContext(vd);return x.jsx("div",{ref:n?.setTitle,className:`page-chrome-title-target ${t}`,children:e?x.jsx("div",{className:"page-chrome-fallback",children:e}):null})}function GG({className:e=""}){const t=y.useContext(vd);return x.jsx("div",{ref:t?.setActions,className:e})}function vie({title:e,actions:t,fallback:n,children:a}){const i=y.useContext(vd);return i?x.jsxs(x.Fragment,{children:[i.title?Ag.createPortal(x.jsx("div",{className:"page-chrome-title",children:e}),i.title):null,i.actions&&t?Ag.createPortal(t,i.actions):null,a]}):n??x.jsxs("header",{children:[e,t]})}async function JG(e){if(!e)return!1;try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch(t){console.warn("Clipboard write failed",t)}try{const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="fixed",t.style.left="-1000px",t.style.top="-1000px",document.body.appendChild(t),t.select();const n=document.execCommand("copy");return t.remove(),n}catch(t){return console.warn("Clipboard fallback failed",t),!1}}function ZG({activeView:e,onDiscoverCommunities:t,onOpenTeamChat:n}){return x.jsxs("div",{className:"titlebar-collaboration-actions",children:[x.jsx("button",{type:"button",className:`titlebar-icon${e==="team"?" active":""}`,"aria-label":"Team chat",title:"Team chat",onClick:n,children:x.jsx(Qm,{size:16})}),x.jsx("button",{type:"button",className:`titlebar-icon${e==="community"?" active":""}`,"aria-label":"Discover communities",title:"Discover communities",onClick:t,children:x.jsx(OR,{size:16})})]})}const YG=y.lazy(()=>Er(()=>import("./WorkspaceEnvironmentMenu-BiFTPWtC.js"),__vite__mapDeps([26,1,2,17,23,5,12,27,25,28])).then(e=>({default:e.WorkspaceEnvironmentMenu})));function QG({sidebarOpen:e,title:t,conversationId:n,breadcrumbs:a,backAction:i,workspaceName:r,workspaceId:s,busy:c,workspaceState:m,workspaceKind:u,selectedApp:h,selectedProject:g,workspaceDiff:S,managedWorkspace:k,workspaceBusy:C,defaultTeamId:A,activityActorId:M,activityProjectId:R,showDiffControls:$,diffPanelOpen:O,terminalOpen:j,rightSidebarAvailable:I=!1,rightSidebarOpen:P=!1,onToggleDiffPanel:E,onToggleRightSidebar:L,onOpenSearch:z,onToggleTerminal:H,onRunTerminalCommand:J,onWorkspaceToolAction:X,onOpenCommitDialog:de,onWorkspaceBranchChange:je,onWorkspaceBranchCreate:we,connection:te,onBootstrap:Me,onOpenSandboxWorkspace:Se,onShowSidebar:oe,onOpenTeamChat:be,onDiscoverCommunities:re,collaborationView:ue=null,platform:ke,showWorkspaceControls:Le=!0}){const Ie=S?.filesChanged??0,le=ep()&&!Kb(ke),xe=!!(be||re)||Le||I||le,[Ue,Ze]=y.useState(null);y.useEffect(()=>{if(!Ue)return;const Ne=()=>Ze(null);return window.addEventListener("pointerdown",Ne),window.addEventListener("blur",Ne),window.addEventListener("resize",Ne),()=>{window.removeEventListener("pointerdown",Ne),window.removeEventListener("blur",Ne),window.removeEventListener("resize",Ne)}},[Ue]);const it=Ne=>{Ne.preventDefault(),Ne.stopPropagation();const We=190,qe=n?76:42;Ze({x:Math.min(Ne.clientX,window.innerWidth-We-8),y:Math.min(Ne.clientY,window.innerHeight-qe-8)})},at=Ne=>{JG(Ne),Ze(null)};return x.jsxs("header",{className:"app-titlebar",children:[x.jsxs("div",{className:"titlebar-left",children:[!e&&x.jsx("button",{className:"titlebar-icon",title:"Show sidebar",onClick:oe,children:x.jsx($R,{size:16})}),i?x.jsx("button",{className:"titlebar-icon",type:"button","aria-label":i.label,title:i.label,onClick:i.onSelect,children:x.jsx(d9,{size:16})}):null,x.jsx(WG,{children:a?.length?x.jsx("nav",{className:"titlebar-breadcrumbs","aria-label":"Breadcrumb",children:a.map((Ne,We)=>{const qe=We===a.length-1;return x.jsxs("div",{className:"titlebar-breadcrumb-item",children:[Ne.onSelect&&!qe?x.jsx("button",{type:"button",onClick:Ne.onSelect,children:Ne.label}):x.jsx("strong",{children:Ne.label}),!qe&&x.jsx(Tr,{size:14})]},`${Ne.label}-${We}`)})}):x.jsxs("div",{className:"titlebar-title",children:[x.jsx("strong",{className:"titlebar-copy-target",title:"Double-click to select; right-click for copy options",onContextMenu:it,children:t}),r&&x.jsx("span",{children:r})]})})]}),xe&&x.jsxs("div",{className:"titlebar-right",children:[x.jsx(GG,{className:"page-chrome-actions"}),x.jsx(VG,{connection:te,teamId:A??null,actorId:M??null,projectId:R??null}),x.jsx(ZG,{activeView:ue,onDiscoverCommunities:re,onOpenTeamChat:be}),Le&&x.jsxs("div",{className:"titlebar-actions",children:[x.jsx(y.Suspense,{fallback:null,children:x.jsx(YG,{mode:"topbar",busy:c,workspaceState:m,workspaceId:s,workspaceKind:u,selectedApp:h,selectedProject:g,workspaceBusy:C,defaultTeamId:A,workspaceDiff:S,managedWorkspace:k,showDiffControls:$,diffPanelOpen:O,onToggleDiffPanel:E,onRunTerminalCommand:J,onWorkspaceToolAction:X,onOpenCommitDialog:de,onWorkspaceBranchChange:je,onWorkspaceBranchCreate:we,connection:te,onBootstrap:Me,onOpenSandboxWorkspace:Se})}),x.jsx("button",{type:"button",className:"titlebar-icon",title:"Search chats and projects","aria-label":"Search chats and projects",onClick:z,children:x.jsx(oW,{size:16})}),x.jsx("button",{type:"button",className:`titlebar-icon ${j?"active":""}`,title:`${j?"Hide":"Show"} terminal`,"aria-label":`${j?"Hide":"Show"} terminal`,"aria-pressed":j,onClick:H,children:x.jsx(HR,{size:16})}),$&&x.jsx("button",{type:"button",className:`topbar-diff-button ${P?"active":""}`,title:`${P?"Hide":"Show"} sidebar${Ie?`, ${Ie} changed files`:""}`,"aria-label":`${P?"Hide":"Show"} sidebar`,"aria-pressed":P,onClick:E,children:x.jsx(bg,{size:16})})]}),I&&L&&!$?x.jsx("div",{className:"titlebar-actions",children:x.jsx("button",{type:"button",className:`topbar-diff-button ${P?"active":""}`,title:`${P?"Hide":"Show"} sidebar`,"aria-label":`${P?"Hide":"Show"} sidebar`,"aria-pressed":P,onClick:L,children:x.jsx(bg,{size:16})})}):null,x.jsx(pW,{platform:ke})]}),Ue&&x.jsxs("div",{className:"titlebar-copy-menu",role:"menu","aria-label":"Conversation title actions",style:{left:Ue.x,top:Ue.y},onPointerDown:Ne=>Ne.stopPropagation(),children:[x.jsx("button",{type:"button",role:"menuitem",onClick:()=>at(t),children:"Copy title"}),n&&x.jsx("button",{type:"button",role:"menuitem",onClick:()=>at(n),children:"Copy conversation ID"})]})]})}function XG(){const[e,t]=y.useState(null),n=y.useRef(null),a=y.useCallback(r=>new Promise(s=>{n.current?.resolve(!1);const c={...r,cancelLabel:r.cancelLabel??"Cancel",tone:r.tone??"default",resolve:s};n.current=c,t(c)}),[]),i=y.useCallback(r=>{const s=n.current;n.current=null,t(null),s?.resolve(r)},[]);return{confirmAction:a,confirmDialog:e,resolveConfirmDialog:i}}function e7({state:e,onResolve:t}){const n=y.useId(),a=y.useId();if(y.useEffect(()=>{if(!e)return;function r(s){s.key==="Escape"&&t(!1)}return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[t,e]),!e)return null;const i=e.tone==="danger"?"git-dialog-primary danger":"git-dialog-primary";return x.jsx("div",{className:"git-dialog-backdrop",role:"presentation",onMouseDown:()=>t(!1),children:x.jsxs("section",{className:"git-dialog project-confirm-dialog",role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":a,onMouseDown:r=>r.stopPropagation(),children:[x.jsx("h2",{id:n,children:e.title}),x.jsx("p",{id:a,children:e.body}),x.jsxs("div",{className:"git-dialog-footer",children:[x.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:()=>t(!1),children:e.cancelLabel}),x.jsx("button",{type:"button",className:i,autoFocus:!0,onClick:()=>t(!0),children:e.confirmLabel})]})]})})}function t7(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=XG();return{confirmProjectAction:y.useCallback(i=>e({tone:"danger",...i}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function n7({state:e,onResolve:t}){return x.jsx(e7,{state:e,onResolve:t})}const am=new Map,a7=(e,t,n)=>{const a=am.get(e)??{commits:0,maxActualDurationMs:0,totalActualDurationMs:0};a.commits+=1,a.maxActualDurationMs=Math.max(a.maxActualDurationMs,n),a.totalActualDurationMs+=n,am.set(e,a)};function i7({children:e,id:t}){return x.jsx(y.Profiler,{id:t,onRender:a7,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...am.entries()].map(([e,t])=>[e,{...t}])),reset:()=>am.clear()});const o7=y.lazy(()=>Er(()=>import("./MainPane-CUqMVG9-.js").then(e=>e.o),__vite__mapDeps([29,1,2,11,30,7,27,8,5])).then(e=>({default:e.MainPane})));function r7({className:e,style:t,sidebar:n,topBar:a,mainPane:i,cloudSetup:r,projectConfirm:s,lazyPanels:c,toast:m}){return x.jsx(KG,{children:x.jsxs("div",{className:e,style:t,children:[x.jsx(i7,{id:"sidebar",children:x.jsx(CG,{...n})}),x.jsxs("div",{className:"content-shell",children:[x.jsx(QG,{...a}),x.jsx(y.Suspense,{fallback:x.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:x.jsx(o7,{...i})})]}),x.jsx(TG,{...r}),x.jsx(n7,{...s}),x.jsx(LG,{...c}),x.jsx(yP,{...m})]})})}function s7({settings:e,toast:t}){return x.jsxs(x.Fragment,{children:[x.jsx(HG,{...e}),x.jsx(yP,{...t})]})}const _u="OpenPond".split("");function l7({visibleLetterCount:e=_u.length}){const t=_u.slice(0,Math.max(0,Math.min(e,_u.length)));return x.jsxs("div",{className:"app-splash-lockup",children:[x.jsx("div",{className:"app-splash-mark",children:x.jsx("img",{alt:"OpenPond",className:"app-splash-logo",decoding:"async",src:uG})}),x.jsx("span",{"aria-hidden":"true",className:`app-splash-wordmark${t.length>0?" is-visible":""}`,children:t.map((n,a)=>x.jsx("span",{className:"app-splash-letter",children:n},`${n}-${a}`))})]})}const bh=_u.length,c7=520,d7=240;function gx(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function u7({startup:e}){const[t,n]=y.useState(()=>gx()?bh:0);return y.useEffect(()=>{if(gx()){n(bh);return}const a=Array.from({length:bh},(i,r)=>window.setTimeout(()=>n(r+1),c7+d7*r));return()=>{a.forEach(i=>window.clearTimeout(i))}},[]),x.jsxs("main",{className:"app-splash","aria-busy":"true","aria-label":e.label,role:"status",children:[x.jsx(l7,{visibleLetterCount:t}),x.jsx("span",{className:"app-splash-status",children:e.label})]})}const ly=5e3;function Xi(e,t){if(e.length===0)return t;if(t.length===0)return e;const n=new Set,a=[];for(const i of[...e,...t])n.has(i.id)||(n.add(i.id),a.push(i));return a}function Qi(e,t,n=ly){return Cu(Xi(e,t),n)}function Cu(e,t=ly){return e.length<=t?e:e.slice(e.length-t)}function m7(e,t,n){return n.length===0?e:{...e,[t]:Xi(e[t]??[],n)}}function p7(e,t){if(t.length===0)return Cu(e);if(e.length===0)return Cu(t);const n=new Map;let a=0;for(const i of[...e,...t])n.has(i.id)||n.set(i.id,{event:i,index:a}),a+=1;return Cu([...n.values()].sort((i,r)=>h7(i,r)).map(({event:i})=>i))}function im(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 f7(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function h7(e,t){const n=e.event.sequence,a=t.event.sequence;if(typeof n=="number"&&typeof a=="number"){const s=n-a;if(s!==0)return s}const i=Date.parse(e.event.timestamp),r=Date.parse(t.event.timestamp);if(Number.isFinite(i)&&Number.isFinite(r)){const s=i-r;if(s!==0)return s}return e.index-t.index}function vx(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 g7(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function bx(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 v7(e){return e==="codex"}function b7(e){return e==="openpond"}function SP(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=jN.safeParse(n.data);if(a.success)return a.data}return null}function xP(e){if(e.snapshot&&e.snapshot.provider===e.provider){const n=e.snapshot.usedTokens,a=e.snapshot.maxContextTokens,i=Math.min(100,Math.round(e.snapshot.percentFull)),r=`${i}% full`,s=`${vx(n)} / ${vx(a)} tokens used`;return{usedTokens:n,maxTokens:a,percent:i,summary:r,tokensLabel:s,detail:bx(e.preferences,i),tooltip:`Context window: ${r} ${s}. ${bx(e.preferences,i)}`,tone:g7(i)}}if(v7(e.provider)){const n="Context is managed by Codex app-server.";return{usedTokens:0,maxTokens:null,percent:null,summary:"Managed externally",tokensLabel:"Codex app-server",detail:n,tooltip:`Context window: ${n}`,tone:"unknown"}}if(!b7(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 cy(e){let t=!1;const n=kP(e);for(let a=e.length-1;a>=0;a-=1){const i=e[a];if(y7(i)){t=!0;continue}const r=Qs(i?.data);if(!(i?.name!=="diagnostic"||!r)){if(r.kind==="thread_goal_cleared")return null;if(r.kind==="thread_goal"){const s=dy(Qs(r.goal),sa(r.provider),n);if(s){const c=qc(s);return t&&c.tone==="active"?null:c}}if(r.kind==="goal_context"){const s=wP(i.output??"",sa(r.provider)??"codex",n);if(s){const c=qc(s);return t&&c.tone==="active"?null:c}}}}return null}function om(e){const t=kP(e);for(let n=e.length-1;n>=0;n-=1){const a=e[n],i=Qs(a?.data);if(!(a?.name!=="diagnostic"||!i)){if(i.kind==="thread_goal_cleared"&&i.synthetic!==!0)return null;if(i.kind==="thread_goal"){const r=dy(Qs(i.goal),sa(i.provider),t);if(!r)continue;const s=qc(r);return s.tone==="active"?s:null}if(i.kind==="goal_context"){const r=wP(a.output??"",sa(i.provider)??"codex",t);if(!r)continue;const s=qc(r);return s.tone==="active"?s:null}}}return null}function yh(e){const t=Qs(Qs(e)?.codexGoalRuntime),n=dy(t,sa(t?.provider)??"codex");if(!n)return null;const a=qc(n);return a.tone==="active"?a:null}function y7(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function qc(e){const t=_P(e.status),n=PP(e.timeUsedSeconds),a=`Goal ${n}`,i=e.tokensUsed===null?null:e.tokenBudget===null?`${Sh(e.tokensUsed)} tokens`:`${Sh(e.tokensUsed)} / ${Sh(e.tokenBudget)} tokens`,r=i?`${e.statusLabel} · ${i}`: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: ${AP(e.timeUsedSeconds)}. ${r}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function S7(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=IP(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,i=PP(a);return{...e,timeUsedSeconds:a,timeLabel:i,label:`Goal ${i}`,tooltip:`Goal runtime: ${AP(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function dy(e,t=null,n=null){if(!e)return null;const a=sa(e.objective)??"Active goal",i=sa(e.status)??"active";if((Tg(t)??Tg(sa(e.provider)))!=="codex")return null;const s=n??sa(e.updatedAt)??sa(e.updated_at)??null,c=hs(e.timeUsedSeconds)??hs(e.time_used_seconds)??0,m=sa(e.activeSinceAt)??sa(e.active_since_at),u=_P(i).tone==="active"?IP(m??sa(e.createdAt)??sa(e.created_at),s):0,h=m?c+u:Math.max(c,u),g=hs(e.tokensUsed)??hs(e.tokens_used),S=hs(e.tokenBudget)??hs(e.token_budget);return{objective:a,status:i,statusLabel:RP(i),timeUsedSeconds:Math.max(0,Math.floor(h)),tokensUsed:g===null?null:Math.max(0,Math.floor(g)),tokenBudget:S===null?null:Math.max(0,Math.floor(S)),observedAt:s}}function kP(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 IP(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 wP(e,t=null,n=null){if(!e.trim()||Tg(t)!=="codex")return null;const a=CP(e,"Status")??"active",i=zl(e,"Tokens used"),r=zl(e,"Token budget"),s=zl(e,"Time used seconds")??zl(e,"Time spent pursuing goal")??zl(e,"Elapsed seconds")??0;return{objective:yx(e,"objective")??yx(e,"untrusted_objective")??"Active goal",status:a,statusLabel:RP(a),timeUsedSeconds:Math.max(0,Math.floor(s)),tokensUsed:i,tokenBudget:r,observedAt:n}}function _P(e){switch(x7(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 x7(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function CP(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^\\s*-?\\s*${n}:\\s*(.+?)\\s*$`,"im").exec(e)?.[1]?.trim()||null}function zl(e,t){const n=CP(e,t);if(!n)return null;const a=n.replace(/,/g,""),i=/-?\d+(?:\.\d+)?/.exec(a);if(!i)return null;const r=Number(i[0]);return Number.isFinite(r)?r:null}function yx(e,t){return new RegExp(`<${t}>\\s*([\\s\\S]*?)\\s*<\\/${t}>`,"i").exec(e)?.[1]?.trim()||null}function RP(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function PP(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 AP(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 Sh(e){if(e<1e3)return String(e);if(e>=1e6){const n=e/1e6;return n<10?`${Sx(n,2)}M`:n<100?`${Sx(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 Sx(e,t){return e.toFixed(t).replace(/\.?0+$/,"")}function Qs(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function sa(e){return typeof e=="string"&&e.trim()?e.trim():null}function Tg(e){return e?.trim().toLowerCase()||null}function hs(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const k7=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),I7=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function Eg(e){const t=TP(e);return t?R7(t):null}function TP(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=C7(M7(n.data));if(a)return a}return null}function w7(e){if(e.events)return TP(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 _7(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 C7(e){const t=Gc.safeParse(e?.createImproveRun);return t.success?t.data:null}function R7(e){const t=P7(e);if(!t)return null;const n=A7(e.createdAt,e.updatedAt),a=e.blockedReason??T7(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:E7(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function P7(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return k7.has(t)?{tone:"active",actionLabel:`${n} running`}:I7.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 A7(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 T7(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function E7(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 M7(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function EP(e,t){if(!t)return null;const n=new Map,a=[];for(const j of e){if(!j.name.startsWith("subagent."))continue;const I=$7(j);I&&a.push(I);const P=O7(j);P?.parentSessionId===t&&n.set(P.id,P)}if(n.size===0)return null;const i=[...n.values()].sort((j,I)=>vs(I).localeCompare(vs(j))),r=i.filter(j=>j.status==="queued"||j.status==="running"),s=i.filter(j=>j.status==="completed"),c=i.filter(j=>j.status==="failed"),m=i.filter(j=>j.status==="cancelled"),u=i.filter(j=>j.status==="needs_resume"),h=[...s,...c,...m].sort((j,I)=>vs(I).localeCompare(vs(j))),g=i.reduce((j,I)=>{const P=Xs(I.metadata?.usage);return j.totalTokens+=au(P?.totalTokens),j.promptTokens+=au(P?.promptTokens),j.completionTokens+=au(P?.completionTokens),j.requestCount+=au(P?.requestCount),j},{totalTokens:0,promptTokens:0,completionTokens:0,requestCount:0}),S=i.flatMap(j=>MP([...j.report?.blockers??[],j.error,j.progress.currentBlocker]).map(I=>({runId:j.id,roleId:j.roleId,status:j.status,message:I}))),k=i.flatMap(j=>jP([...j.report?.artifacts??[],j.report?.patchRef,j.report?.diffRef,...j.progress.patchRefs]).map(I=>({...I,runId:j.id,roleId:j.roleId}))),C=h.map(j=>j7(j,a)),A=i[0]??null,M=A?{runId:A.id,roleId:A.roleId,status:A.status,message:A.progress.latestMeaningfulActivity||A.report?.summary||A.objective,updatedAt:vs(A)}:null,R=r.length>0?`${r.length} ${r.length===1?"child":"children"} running`:`${h.length} ${h.length===1?"child":"children"} finished`,$=[r.length?`${r.length} active`:null,s.length?`${s.length} completed`:null,c.length?`${c.length} failed`:null,m.length?`${m.length} cancelled`:null,u.length?`${u.length} paused`:null].filter(Boolean).join(" · "),O=M?`${H7(M.roleId)}: ${M.message}`:"";return{sessionId:t,runs:i,activeRuns:r,completedRuns:s,failedRuns:c,cancelledRuns:m,needsResumeRuns:u,terminalRuns:h,latestRun:A,latestMeaningfulUpdate:M,activeCount:r.length,completedCount:s.length,failedCount:c.length,cancelledCount:m.length,needsResumeCount:u.length,terminalCount:h.length,usage:g,blockers:S,evidenceRefs:k,finalResults:C,testsRunCount:i.reduce((j,I)=>j+I.progress.validationAttempts.length,0),label:R,tooltip:[$,O].filter(Boolean).join(". ")}}function j7(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:jP([...e.report?.artifacts??[],e.report?.patchRef,e.report?.diffRef]),testsRun:e.report?.testsRun??[],validationAttempts:e.progress.validationAttempts.map(n=>n.command),blockers:MP([...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:N7(e),updatedAt:vs(e)}}function O7(e){const t=Xs(e.data),n=[t?.run,Xs(t?.message)?.run];for(const a of n){const i=NI.safeParse(a);if(i.success)return i.data}return null}function $7(e){const t=X2.safeParse(Xs(e.data)?.message);return t.success?t.data:null}function N7(e){const t=Xs(Xs(e.metadata?.workspaceHandoff)?.workspaceRetention);return t?.status!=="retained"?null:{status:"retained",reason:nu(t.reason),retainedAt:nu(t.retainedAt),expiresAt:nu(t.expiresAt),retentionDays:D7(t.retentionDays),trigger:nu(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function vs(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function MP(e){return[...new Set(e.map(t=>t?.trim()).filter(t=>!!t))]}function jP(e){const t=new Map;for(const n of e)n&&t.set(`${n.kind}:${n.id}`,n);return[...t.values()]}function Xs(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function nu(e){return typeof e=="string"&&e.trim()?e.trim():null}function au(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function D7(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function H7(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const Mg=[];function jg(e,t){return OP(e,t,null)}function OP(e,t,n){const a=n&&B7(n.events,e)?q7(n.indexes,n.events.length,e):L7(e),i=z7(t);return{...a,...i}}function L7(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 U7(t)}function q7(e,t,n){const a=new Map(e.eventsBySessionId),i=new Map(e.latestContextUsageBySessionId),r=new Map(e.latestGoalRuntimeBySessionId),s=new Map(e.latestSubagentRuntimeBySessionId),c=new Set(e.activeGoalSessionIds),m=new Set(e.activeSubagentSessionIds),u=new Set;for(let h=t;h<n.length;h+=1){const g=n[h];if(!g.sessionId)continue;if(u.has(g.sessionId)){a.get(g.sessionId).push(g);continue}const S=a.get(g.sessionId);a.set(g.sessionId,S?[...S,g]:[g]),u.add(g.sessionId)}for(const h of u){const g=a.get(h)??Mg,S=SP(g);S?i.set(h,S):i.delete(h);const k=NP(g);k?(r.set(h,k),k.tone==="active"?c.add(h):c.delete(h)):(r.delete(h),c.delete(h));const C=EP(g,h);C?(s.set(h,C),$P({sessionEvents:g,sessionId:h,latestGoalRuntimeBySessionId:r,activeGoalSessionIds:c}),C.activeCount>0?m.add(h):m.delete(h)):(s.delete(h),m.delete(h))}return{eventsBySessionId:a,latestContextUsageBySessionId:i,latestGoalRuntimeBySessionId:r,latestSubagentRuntimeBySessionId:s,activeGoalSessionIds:c,activeSubagentSessionIds:m}}function U7(e){const t=new Map,n=new Map,a=new Map,i=new Set,r=new Set;for(const[s,c]of e){const m=SP(c);m&&t.set(s,m);const u=NP(c);u&&(n.set(s,u),u.tone==="active"&&i.add(s))}for(const[s,c]of e){const m=EP(c,s);m&&(a.set(s,m),$P({sessionEvents:c,sessionId:s,latestGoalRuntimeBySessionId:n,activeGoalSessionIds:i}),m.activeCount>0&&r.add(s))}return{eventsBySessionId:e,latestContextUsageBySessionId:t,latestGoalRuntimeBySessionId:n,latestSubagentRuntimeBySessionId:a,activeGoalSessionIds:i,activeSubagentSessionIds:r}}function $P(e){if(e.latestGoalRuntimeBySessionId.has(e.sessionId))return;const t=om(e.sessionEvents);t&&(e.latestGoalRuntimeBySessionId.set(e.sessionId,t),t.tone==="active"&&e.activeGoalSessionIds.add(e.sessionId))}function NP(e){return Eg(e)??cy(e)??om(e)}function z7(e){const t=new Map,n=new Map,a=new Map,i=new Map;for(const r of e){t.set(r.id,r);const s=n.get(r.status);if(s?s.push(r):n.set(r.status,[r]),r.status!=="pending")continue;const c=a.get(r.sessionId);c?c.push(r):a.set(r.sessionId,[r]);const m=i.get(r.sessionId);(!m||xx(r.createdAt)>xx(m.createdAt))&&i.set(r.sessionId,r)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:i}}function B7(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 bd(e,t){return t?e.eventsBySessionId.get(t)??Mg:Mg}function DP(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function HP(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function F7(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function V7(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function xx(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function K7(e,t){return e?.conversationId===t}function W7(e,t){return e?.id===t?null:e}function G7(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("/"),i=a>=0?n.relativePath.slice(0,a):"";for(const r of n.resourceFiles)t.add(i?`${i}/${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 J7(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function bie(e,t){return e.profiles.find(n=>J7(n.ref)===t)?.ref??null}function Z7(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function yie(e,t){return e.profiles.find(n=>Z7(n.ref,t))?.state??null}function Y7(e,t){const n=new Map(wL.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 i of a.skills)i.validationStatus!=="valid"||n.has(i.name)||n.set(i.name,{name:i.name,description:i.description,path:i.relativePath,scope:"profile",enabled:!0,sourcePath:a.sourcePath,charCount:i.charCount,sourceHash:i.sourceHash,validationStatus:"valid",validationMessages:[],resourceFiles:i.resourceFiles});return[...n.values()].sort((a,i)=>a.name.localeCompare(i.name))}function Q7(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 Sie(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 LP="openpond:last-chat-task-mode";function X7(e,t){return e==="labs"?"models":"chat"}function eJ(e){try{return e.getItem(LP)==="work"?"work":"chat"}catch{return"chat"}}function uy(){if(typeof window>"u")return"chat";try{return eJ(gd)}catch{return"chat"}}function tJ(e,t){try{e.setItem(LP,t==="chat"?"chat":"work")}catch{}}function nJ(e){if(!(typeof window>"u"))try{tJ(gd,e)}catch{}}const aJ="uploaded to a different account";function qP(e,t){const n=e?.linkedSandboxProject??null;if(!n?.projectId||!n.teamId)return{state:"none",linked:null,cloudProject:null};const a=t?.find(i=>i.id===n.projectId&&i.teamId===n.teamId)??null;return a?{state:"confirmed",linked:n,cloudProject:a}:{state:"different_account",linked:n,cloudProject:null}}function za(e,t){const n=qP(e,t);return n.state==="confirmed"?n.cloudProject:null}function iJ(e,t){return qP(e,t).state==="different_account"?aJ:null}function Oi(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function UP(e={}){return{...e,workspaceTarget:"hybrid"}}function oJ(e={}){return{...e,workspaceTarget:"local"}}function $i(e){return e?.metadata?.workspaceTarget==="hybrid"}function rJ(e){return!!(e&&e.provider==="openpond"&&e.workspaceKind==="local_project"&&e.cloudProjectId&&e.title.trim().endsWith(" Cloud"))}function zP({cloudProjects:e,selectedCloudProject:t,selectedProject:n}){const a=n?.linkedSandboxProject??null,i=e?za(n,e):null,r=t?.id??i?.id??(e?null:a?.projectId??null),s=t?.teamId??i?.teamId??(e?null:a?.teamId??null);return!r||!s?{kind:"missing_cloud_project",message:"Upload/sync this Project to Cloud before using Hybrid."}:{kind:"ready",cloudProjectId:r,cloudTeamId:s,cwd:n?.workspacePath??null,localProjectId:n?.id??null,workspaceName:t?.name??i?.name??a?.projectName??n?.name??"Hybrid workspace"}}function BP({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:UP(),cwd:n.cwd,title:a}}function sJ(e){return y.useEffect(()=>{const t=eP(e.selectedSession);!t||e.composerDraftStore.getSnapshot()||e.composerDraftStore.set(t)},[e.composerDraftStore,e.selectedSession?.id]),y.useCallback(async t=>{const n=t.trim();if(!e.connection||!n||e.activeExperience==="chat")return!1;const a=ZW(n);try{let i;const r=e.selectedSession;if(r&&Hc(r))i=await Q.patchSession(e.connection,r.id,{title:a,metadata:fh(r.metadata,n)}),e.setSessions(s=>s.map(c=>c.id===i.id?i:c));else{const s=r?.metadata?.workspaceTarget==="hybrid"?"hybrid":r?.metadata?.workspaceTarget==="local"?"local":null,c=r?.provider??(e.selectedCloudProject?"openpond":e.activeProvider),m=r?.modelRef??(c==="openpond"?{providerId:"openpond",modelId:zs}:{providerId:c,modelId:e.activeModel}),u=s?{workspaceTarget:s}:!r&&e.workspaceTarget==="local"?{workspaceTarget:"local"}:{};let h;if(!r&&e.workspaceTarget==="hybrid"){const g=zP({cloudProjects:e.cloudProjects,selectedCloudProject:e.selectedCloudProject,selectedProject:e.selectedProject});if(g.kind!=="ready")throw new Error(g.message);const S=BP({modelRef:m,provider:c,target:g,title:a});h={...S,experience:"work",metadata:fh(S.metadata,n)}}else h={experience:"work",provider:c,modelRef:m,openPondCommandAccessMode:r?.openPondCommandAccessMode??e.activeOpenPondCommandAccessMode,appId:r?.appId??null,appName:r?.appName??null,workspaceKind:r?.workspaceKind??(e.selectedCloudProject?"sandbox":e.selectedProject?"local_project":void 0),workspaceId:r?.workspaceId??e.selectedCloudProject?.id??e.selectedProject?.id??null,workspaceName:r?.workspaceName??e.selectedCloudProject?.name??e.selectedProject?.name??null,localProjectId:r?.localProjectId??e.selectedProject?.id??null,cloudProjectId:r?.cloudProjectId??e.selectedCloudProject?.id??null,cloudTeamId:r?.cloudTeamId??e.selectedCloudProject?.teamId??null,cwd:r?.cwd??e.selectedProject?.workspacePath??null,metadata:fh(u,n),title:a};i=await Q.createSession(e.connection,h),e.setSessions(g=>[i,...g])}return e.composerDraftStore.set(""),e.setMentionedAppId(null),e.setSelectedSessionId(null),e.setView("chat"),e.requestComposerFocus(),e.showToast("Task draft saved.","success"),!0}catch(i){return e.showToast(i instanceof Error?i.message:"Could not save task draft.","error"),!1}},[e.activeExperience,e.activeModel,e.activeOpenPondCommandAccessMode,e.activeProvider,e.cloudProjects,e.composerDraftStore,e.connection,e.requestComposerFocus,e.selectedCloudProject,e.selectedProject,e.selectedSession,e.setMentionedAppId,e.setSelectedSessionId,e.setSessions,e.setView,e.showToast,e.workspaceTarget])}const lJ=[];function cJ({primary:e,secondary:t}){const[n,a]=y.useState(null),i=y.useRef(new Set),[r,s]=y.useState(!1),[c,m]=y.useState(null),u=AW(),h=u?.kind==="models"&&["home","inbox","datasets","graders","experiments"].includes(u.route.page),{composerDraftStore:g,appDispatch:S,pendingTerminalCommand:k,setPendingTerminalCommand:C,terminalTabs:A,setTerminalTabs:M,trainingDetailTasksetId:R,setTrainingDetailTasksetId:$,mentionedAppId:O,setMentionedAppId:j,cloudSetupDialog:I,setCloudSetupDialog:P,rightPanelTabRequest:E,workspaceDiffPanelViewState:L,mainComposerFocusRequestId:z,requestMainComposerFocus:H,projectConfirmDialog:J,resolveProjectConfirmDialog:X,query:de,searchOpen:je,archivedChatsOpen:we,sectionMenuOpen:te,cloudProjectsExpanded:Me,sidebarOpen:Se,view:oe,selectedAppId:be,selectedProjectId:re,selectedSessionId:ue,codexPermissionMode:ke,codexReasoningEffort:Le,busy:Ie,diffPanelOpen:le,diffPanelExpanded:xe,rightPanelMode:Ue,activeExperience:Ze,changeNewExperience:it,terminalOpen:at,settingsSection:Ne,newProjectDialogOpen:We,newProjectMode:qe,newProjectName:q,newProjectPath:N,newProjectBusy:F,commitDialogOpen:ee,commitMessage:me,commitIncludeUnstaged:$e,commitNextStep:ze,commitDraft:tt,branchDialogOpen:nt,branchDialogName:mt,toast:vt,labDetailNavigation:Oe,setQuery:Ye,setSearchOpen:f,setArchivedChatsOpen:U,setSectionMenuOpen:Y,setCloudProjectsExpanded:ge,setChatRowsVisibleCount:se,setSidebarOpen:G,setView:_,setSelectedAppId:W,setSelectedProjectId:ne,setSelectedSessionId:Z,setPrompt:ce,setDraftProvider:pe,setDraftModel:fe,setDraftExperience:Ae,setDiffPanelOpen:Ce,setDiffPanelExpanded:He,setRightPanelMode:Pe,setTerminalOpen:Xe,setSettingsSection:ut,setNewProjectDialogOpen:fn,setNewProjectName:jt,setNewProjectPath:dn,setCommitDialogOpen:yn,setCommitMessage:Sn,setCommitIncludeUnstaged:Qt,setCommitNextStep:Wa,setCommitDraft:wa,setBranchDialogOpen:zn,setBranchDialogName:$n,setError:Ht,showToast:St,applyBootstrapPayload:xn,bootstrap:xt,connection:Nt,startup:_a,training:Ft,pinnedCollapsed:kn,cloudProjectsCollapsed:rt,chatsCollapsed:jn,savedForLaterCollapsed:ui,sidebarWidth:mi,sidebarResizing:ha,diffPanelWidth:Ca,diffPanelResizing:Bn,togglePinnedCollapsed:Li,toggleCloudProjectsCollapsed:Ga,toggleChatsCollapsed:K,toggleSavedForLaterCollapsed:Be,startSidebarResize:_e,startDiffPanelResize:Ve,selectedApp:It,selectedCloudProject:na,selectedProject:In,selectedProjectLinkedApp:Je,selectedSession:Rn,sidebarSessions:ft,runtimeIndexes:Nn,runtimeEventStore:Ja,chatMentionApps:So,connectedAppMentions:Ra,pendingApproval:xo,pendingChatUserMessages:Xo,account:qi,activeModel:Fn,activeProvider:Pa,appDefaults:aa,startMessage:ko,organizations:er,teamChatOrganization:Io,teamChatTeamId:wo,teamChat:_t,publishTeamProfileAgent:pl,communitySidebar:tr,communityView:fl,teamAiThreadId:Lr,toggleTeamAiSidebar:hl,activeOpenPondCommandAccessMode:Ui,viewWorkspaceAppId:gl,viewWorkspaceId:qr,viewWorkspaceKind:Ur,viewWorkspaceName:zr,selectedActionCatalog:vl,expandedProjectIds:bl,expandProject:pi,toggleProjectExpanded:yl,changeCodexPermissionMode:Br,changeCodexReasoningEffort:Fr,changeOpenPondCommandAccessMode:_o,resolveApproval:Vr,beginNewChat:ga,beginNewChatWithTrainingModel:Sl,dismissTrainingChatHandoff:nr,trainingChatHandoff:zi,selectTrainingChatTaskForComposer:ia,chatHistoryLoadStates:xl,loadMoreSelectedChatHistory:kl,selectedPagedSessionEvents:Pn,activeSessions:Co,archivedSessions:Aa,pinnedSessions:Za,savedForLaterSessions:ar,savedForLaterFiles:Ro,sidebarFileBookmarks:Il,setSidebarFileStatus:Kr,setSessions:ir,projectRows:Bi,localProjectRows:Po,cloudProjectRows:Ao,projectSessionRowsByProjectId:Wr,childSessionRowsByParentId:Gr,sidebarProjectIdBySessionId:Ta,chatRows:Ea,visibleChatRows:Jr,chatRowsVisibleCount:or,sessionEvents:fi,goalRuntime:rr,subagentRuntime:Fi,visibleChatMessages:Zr,activeTerminalScope:Yr,terminalSummaries:Qr,runningSessionIds:wl,selectedSessionRunning:Xr,sidebarGoalRuntimeBySessionId:es,sidebarSubagentRuntimeBySessionId:_l,taskDragSessionId:To,taskPreviewSessionIds:ts,startTaskDrag:sr,clearTaskDrag:hi,previewTaskDrop:Cl,commitTaskDrop:Rl,commitTaskPreviewDrop:Pl,dragItem:Al,startPinnedDrag:gi,clearSidebarDrag:ns,previewPinnedDrop:Tl,commitPinnedDrop:El,commitPinnedPreviewDrop:Ml,commandProjectRows:va,contextWindowStatus:as,pinnedRows:jl,workspaceBusy:pt,diffBusy:rn,visibleWorkspaceState:oa,visibleWorkspaceDiff:hn,refreshVisibleWorkspaceDiff:Dn,managedWorkspace:ba,canSyncActiveWorkspace:dp,canPublishOpenPondProject:up,projectTarget:mp,workspaceTarget:Sd}=e,{title:pp,browserConversationId:lr,handleWorkspaceDiffPanelViewStateChange:xd,openSessionInChat:is,changeProjectTarget:fp,submitNewProjectDialog:hp,changeWorkspaceBranch:gp,openCommitDialog:vp,openCreateWorkspaceBranchDialog:bp,openDefaultsSettingsFromBranchDialog:yp,runWorkspaceTool:Sp,submitCommitDialog:xp,submitCreateWorkspaceBranch:kp,syncWorkspaceLocally:Ip,answerCreateImproveQuestion:kd,applyCreateImproveCandidate:wp,approveCreateImproveRun:_p,cancelCreateImproveRun:Cp,changeDraftProvider:Ol,openCreateImprovePullRequest:Id,reconcileCreateImprovePullRequest:Rp,rejectCreateImproveCandidate:Pp,pauseCreateImproveRun:wd,resumeCreateImproveRun:_d,reviseCreateImproveRun:Ap,stopTurn:os,archiveSession:Tp,restoreSession:Cd,renameSession:Ep,toggleSessionPinned:$l,toggleProjectPinned:Rd,toggleSessionSavedForLater:Pd,moveProjectToCloud:Mp,startCloudSetupUpload:Ad,changeWorkspaceTarget:jp,sendPromptFromMainComposer:Op,openSandboxWorkspace:Td,openCloudProjectDialog:$p,openExistingProjectPathDialog:Ed,openUrlInBrowserPanel:Np,showBrowserPanel:Dp,showChangesPanel:Hp,showGoalSidebarTab:Eo,rightChatTrainingLaunchRequest:Md,setRightChatTrainingLaunchRequest:Lp,closeRightChatPanel:qp,openRightChatPanel:Nl,rightChatPanelViews:Up,showRightChatPanel:zp,showRightPanelDiffTab:Bp,submitRightChatPrompt:Fp,activateRightChatPanel:Vp,updateRightChatModel:Kp,updateRightChatPrompt:Wp,updateRightChatProvider:Gp,updateRightChatScrollState:Jp,openProfileSettings:Zp,diagnosticEvents:Yp,toggleRightSidebar:jd,removeProject:Qp}=t,Ya=xt?.account.activeProfile&&xt?.preferences.defaultTeamId?`${xt.account.activeProfile.handle}:${xt.preferences.defaultTeamId}`:null;y.useEffect(()=>{if(!(!Ya||oe!=="chat"||u?.kind!=="chat"||u.sessionId||ue||i.current.has(Ya))){i.current.add(Ya);try{const Te=localStorage.getItem(`openpond:ponder-mode:v1:${Ya}`);(Te==="clean"||Te==="activity")&&a(Te)}catch{}}},[Ya,u,oe,ue]),y.useEffect(()=>{if(!(!Ya||!i.current.has(Ya)))try{localStorage.setItem(`openpond:ponder-mode:v1:${Ya}`,n??"off")}catch{}},[Ya,n]);const rs=y.useCallback(Te=>{W(null),ne(Te),Z(null),_("chat"),pi(Te),H()},[pi,H,W,ne,Z,_]),Xp=y.useCallback((Te=null)=>{a(null);const ct=ue?Ta[ue]??null:null;if(!Te&&ct){rs(ct);return}ga(Te)},[ga,rs,ue,Ta]),ef=y.useCallback(async Te=>{if(!(!Nt||!xt))try{const ct=await Q.savePreferences(Nt,{defaultTeamId:Te});xn({...xt,preferences:ct.preferences})}catch(ct){const Lt=ct instanceof Error?ct.message:String(ct);throw Ht(Lt),St("Could not switch teams","error"),ct}},[xn,xt,Nt,Ht,St]),tf=y.useCallback(async()=>{if(Nt)try{const Te=await Q.signOutOpenPondAccount(Nt);xn(Te);const ct=await Q.savePreferences(Nt,{defaultTeamId:null});xn({...Te,preferences:ct.preferences}),St("Logged out","success")}catch(Te){const ct=Te instanceof Error?Te.message:String(Te);throw Ht(ct),St("Could not log out","error"),Te}},[xn,Nt,Ht,St]),Dl=wo??aa.defaultTeamId??null,nf=y.useMemo(()=>Bi.filter(Te=>Te.kind==="local"||Dl!==null&&Te.project.teamId===Dl),[Bi,Dl]),af=y.useMemo(()=>{const Te={};for(const ct of Co){const Lt=Ta[ct.id];Lt&&(Te[Lt]=(Te[Lt]??0)+1)}for(const ct of Po){if(ct.kind!=="local")continue;const Lt=ct.project.linkedSandboxProject?.projectId;if(!Lt||!ct.cloudLinkTrusted)continue;const Ma=wt("cloud",Lt);Te[ct.id]=(Te[ct.id]??0)+(Te[Ma]??0)}return Te},[Co,Po,Ta]),[Od,Vi]=y.useState(null),[ss,ls]=y.useState(null),of=Y7(xt?.profile,xt?.extensionCatalog),[cr,Hl]=y.useState(null),[cs,Ll]=y.useState(null),[vi,$d]=y.useState(null),rf=y.useCallback(()=>{W(null),ne(null),Z(null),Y(null),_("team")},[Y,W,ne,Z,_]),sf=y.useCallback(()=>{W(null),ne(null),Z(null),Y(null),tr.discoverCommunities()},[tr.discoverCommunities,Y,W,ne,Z]),lf=sJ({activeExperience:Ze,activeModel:Fn,activeOpenPondCommandAccessMode:Ui,activeProvider:Pa,cloudProjects:xt?.cloudProjects??lJ,composerDraftStore:g,connection:Nt,requestComposerFocus:H,selectedCloudProject:na,selectedProject:In,selectedSession:Rn,setMentionedAppId:j,setSelectedSessionId:Z,setSessions:ir,setView:_,showToast:St,workspaceTarget:Sd.value}),cf=y.useCallback(async Te=>{if(!Nt)throw new Error("OpenPond is not connected.");let ct=Pa,Lt=Fn;ct==="codex"&&(ct=Pg(xt?.providers,{enabledOnly:!0}).find(An=>An.value!=="codex")?.value??_r,Lt=tm(ct,xt?.providers)??bc);const Ma=ft.find(An=>An.id===Te.sourceSessionId),Ki=await Q.createSession(Nt,{experience:Te.target,provider:ct,modelRef:{providerId:ct,modelId:Lt},openPondCommandAccessMode:Ui,appId:null,appName:null,workspaceId:null,workspaceName:null,localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,title:`Continue ${Ma?.title??"task"}`.slice(0,120),metadata:{experienceHandoff:Q7({sourceTaskId:Te.sourceSessionId,sourceExperience:Ma?.experience??null,targetExperience:Te.target,sourceMessageIds:Te.sourceMessageIds??[],sourceContext:Te.sourceContext,output:Te.output})}});return ir(An=>[Ki,...An]),Ae(Te.target),pe(ct),fe(Lt),g.set(Te.prompt),ln({kind:"chat",sessionId:Ki.id}),S({type:"selectSession",sessionId:Ki.id,appId:null,projectId:null}),W(null),ne(null),Xe(!1),_("chat"),Pe("home"),Ce(Te.target==="work"),He(!1),Ki},[Fn,Ui,Pa,S,xt?.providers,g,Nt,He,Ce,Ae,fe,pe,Pe,W,ne,ir,Xe,_,ft]),df=y.useCallback(Te=>{Hl(Te),Ll(null),ga(null),G(!0)},[ga,G]),uf=y.useCallback(Te=>{ga(null),Ae("work"),g.set(`$openpond-refiner-authoring ${Te}`),_("chat"),G(!0)},[ga,g,Ae,G,_]),Nd=y.useCallback(Te=>{Ll(G7(Te)),Hl(null),ga(null),G(!0)},[ga,G]);y.useEffect(()=>{!cr&&!cs||oe!=="chat"||ue||re||be||(Vi(cr),ls(cs),Hl(null),Ll(null),Pe("home"),He(!1),Ce(!0))},[cr,cs,be,re,ue,He,Ce,Pe,oe]),y.useEffect(()=>{!Od&&!ss||oe==="chat"&&le&&Ue==="home"||(Vi(null),ls(null))},[le,ss,Od,Ue,oe]);const Dd=y.useCallback(()=>{Vi(null),ls(null),He(!1),Ce(!1)},[He,Ce]),mf=y.useCallback(Te=>{let ct;if(Te.workspaceKind==="local"){const Lt=wt("local",Te.workspaceId);ct=`draft:${Lt}`,W(null),ne(Lt),Z(null),pi(Lt),_("chat")}else{const Lt=ft.find(Ma=>Ma.id===Te.sourceSessionId||Ma.workspaceId===Te.workspaceId);if(!Lt){St("This saved file's cloud chat is no longer available.","error");return}ct=Lt.id,is(Lt.id)}Pe("changes"),Ce(!0),$d({id:Date.now(),conversationId:ct,file:Te}),Te.available||St(`File unavailable: ${Te.path}`,"error")},[pi,is,Ce,Pe,W,ne,Z,_,St,ft]);y.useEffect(()=>{if(!K7(vi,lr))return;const Te=window.setTimeout(()=>{Pe("changes"),Ce(!0),$d(ct=>W7(ct,vi.id))},0);return()=>window.clearTimeout(Te)},[lr,Ce,Pe,vi]);const pf=u?.kind==="models"&&u.route.area==="console"?"console":X7(oe);y.useEffect(()=>{if(u){if(u.kind==="models"||u.kind==="models_unavailable"){oe!=="labs"&&_("labs");return}if(u.kind==="settings"){W(null),ne(null),Z(null),ut(u.section),oe!=="settings"&&_("settings");return}if(u.kind==="view"){W(null),ne(null),Z(null),oe!==u.view&&_(u.view);return}u.sessionId!==null&&(a(null),W(null),ne(null)),Z(u.sessionId),oe!=="chat"&&_("chat")}},[u,W,ne,Z,ut,_,oe]);const ff=y.useCallback(Te=>{if(Y(null),W(null),ne(null),Z(null),Te==="models"||Te==="console"){po(Te==="console"?ma("datasets",null,{area:"console"}):ma()),_("labs");return}Te==="chat"&&ln({kind:"chat",sessionId:null}),it(uy())},[it,ln,Y,W,ne,Z,_]),hf=y.useCallback(async(Te,ct)=>{const Lt=await Ft.actions.acceptHarnessReview(Te,ct,{providerId:Pa,modelId:Fn},Le);return Lt?($(Lt.materializedTasksetId??null),po(ma()),_("labs"),!0):(St("Taskset review could not be opened.","error"),!1)},[Fn,Pa,Le,po,ma,$,_,St,Ft.actions]);if(!_a.ready)return x.jsx(u7,{startup:_a});if(oe==="settings")return x.jsx(mx,{showToast:St,children:x.jsx(s7,{settings:{payload:xt,connection:Nt,diagnostics:Yp,initialSection:Ne,onPayload:xn,onError:Ht,onToast:St,onOpenSourceSession:is,onStartRefinerAuthoring:uf,onAcceptEvaluationReview:hf,onOpenSkill:df,onOpenExtension:Nd,teamChatCurrentUserId:_t.currentUserId,teamChatEnabled:wo!==null,teamChatNotificationMode:_t.notificationMode,teamChatThreads:_t.threads,onTeamChatNotificationModeChange:_t.setNotificationMode,onTeamChatThreadMuteChange:_t.setThreadMuted,diffPanelWidth:Ca,diffPanelResizing:Bn,diffPanelExpanded:xe,onDiffPanelResizeStart:Ve,onDiffPanelExpandedChange:He,onBack:()=>{const Te=CW(u);ln(Te),_(Te.kind==="models"?"labs":"chat"),G(!0)}},toast:{toast:vt,onDismiss:()=>S({type:"field",key:"toast",value:null})}})});const ot=ep(),Kt=Nt?.platform??navigator.platform,Wt=ot&&Kb(Kt),Gt=Yr,Qa=oa?.initialized?oa.repoPath:Rn?.cwd??null,gf={"--sidebar-width":`${mi}px`,"--diff-panel-width":`${Ca}px`},WA=oe==="chat"&&Ze!=="chat"||oe==="labs"||oe==="scheduled"&&r||oe==="team"&&!!Lr,GA=["app-shell",Wt?"platform-macos":"",Se?"sidebar-open":"sidebar-closed",ha?"sidebar-resizing":"",Bn?"diff-panel-resizing":""].filter(Boolean).join(" "),vf=ue?xl[ue]:null,JA=ue?vf?.cursorSequence??f7(Qi(Pn,bd(Nn,ue))):null,ZA=!!ue&&!!Nt&&(Vt(ue)?!0:!!xt?.eventWindow?.hasMoreBefore&&!!JA)&&(vf?.hasMore??!0),YA=!!vf?.loading,QA=(()=>{const Te=Ft.payload;if(!Te)return{};const ct=new Map(Te.plans.map(An=>[An.id,An])),Lt=new Set(["queued","starting","running","cancelling","reconciling"]),Ma={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},Ki={};for(const An of[...Te.modelRuns].sort((Xa,ds)=>ds.updatedAt.localeCompare(Xa.updatedAt))){if(An.kind==="evaluation"||!["prepared","running"].includes(An.status))continue;const Xa=Te.jobs.filter(bf=>bf.metadata.modelRunId===An.id).sort((bf,XA)=>XA.updatedAt.localeCompare(bf.updatedAt))[0];if(Xa&&!Lt.has(Xa.status))continue;const ds=Xa?.status??(An.status==="prepared"?"starting":"running");Ki[An.modelId]={label:Ma[ds]??"Running",status:ds}}for(const An of[...Te.jobs].sort((Xa,ds)=>ds.updatedAt.localeCompare(Xa.updatedAt))){if(!Lt.has(An.status))continue;const Xa=ct.get(An.planId)?.modelId;!Xa||Ki[Xa]||(Ki[Xa]={label:Ma[An.status]??"Active",status:An.status})}return Ki})();return x.jsx(mx,{showToast:St,children:x.jsx(r7,{className:GA,style:gf,sidebar:{onOpenPonder:()=>{ln({kind:"chat",sessionId:null}),Z(null),_("chat"),a("activity")},productArea:pf,modelProjects:(Ft.payload?.modelProjects??[]).filter(Te=>Te.hosted===null||Te.hosted.teamId===(aa.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:QA,onProductAreaChange:ff,experience:Ze,view:oe,selectedAppId:be,selectedProjectId:re,selectedSessionId:ue,selectedTeamThreadId:_t.selectedThreadId,teamChatEnabled:wo!==null,organizations:er,teamChatOrganization:Io,teamChatLoading:_t.loading,currentUserId:_t.currentUserId,teamMembers:_t.members,teamThreads:_t.threads,...tr,account:qi,connection:Nt,profile:xt?.profile,pinnedCollapsed:kn,cloudProjectsCollapsed:rt,chatsCollapsed:jn,savedForLaterCollapsed:ui,archivedChatsOpen:we,cloudProjectsExpanded:Me,sectionMenuOpen:te,dragItem:Al,taskDragSessionId:To,taskPreviewSessionIds:ts,activeSessions:Co,archivedSessions:Aa,pinnedRows:jl,pinnedSessions:Za,savedForLaterSessions:ar,savedForLaterFiles:Ro,projectRows:Bi,localProjectRows:Po,cloudProjectRows:Ao,projectSessionRowsByProjectId:Wr,childSessionRowsByParentId:Gr,sidebarProjectIdBySessionId:Ta,terminalSummaries:Qr,runningSessionIds:wl,goalRuntimeBySessionId:es,subagentRuntimeBySessionId:_l,visibleChatRows:Jr,chatRows:Ea,chatRowsVisibleCount:or,expandedProjectIds:bl,currentVersion:xt?.server.version??null,platform:Kt,arch:Nt?.arch??null,onSidebarResizeStart:_e,setSidebarOpen:G,setView:_,setSelectedAppId:W,setSelectedProjectId:ne,setSelectedSessionId:Z,setSearchOpen:f,setSectionMenuOpen:Y,setSettingsSection:ut,onSelectTeam:ef,onLogOut:tf,onTogglePinnedCollapsed:Li,onToggleCloudProjectsCollapsed:Ga,onToggleChatsCollapsed:K,onToggleSavedForLaterCollapsed:Be,setArchivedChatsOpen:U,setCloudProjectsExpanded:ge,setChatRowsVisibleCount:se,beginNewChat:Xp,beginProjectChat:rs,onAddProject:Ed,dockSessionRight:Nl,selectTeamThread:Te=>{_("team"),_t.selectThread(Te)},openTeamDm:Te=>{_("team"),_t.openDm(Te)},toggleSessionPinned:$l,toggleProjectPinned:Rd,toggleSessionSavedForLater:Pd,openSidebarFile:mf,setSidebarFileStatus:(Te,ct)=>{Kr(Te,ct)},archiveSession:Tp,restoreSession:Cd,renameSession:Ep,removeProject:Qp,expandProject:pi,toggleProjectExpanded:yl,startPinnedDrag:gi,clearSidebarDrag:ns,previewPinnedDrop:Tl,commitPinnedDrop:El,commitPinnedPreviewDrop:Ml,startTaskDrag:sr,clearTaskDrag:hi,previewTaskDrop:Cl,commitTaskDrop:Rl,commitTaskPreviewDrop:Pl},topBar:{sidebarOpen:Se,title:oe==="chat"&&n?"Ponder Pal":pp,backAction:Oe.backAction,breadcrumbs:Oe.breadcrumbs,conversationId:oe==="chat"?ue:null,workspaceName:zr,workspaceId:qr,busy:Ie,workspaceState:oa,workspaceKind:Ur,selectedApp:Je??It,selectedProject:In,workspaceDiff:hn,managedWorkspace:ba,workspaceBusy:pt,defaultTeamId:aa.defaultTeamId,activityActorId:xt?.account.profile?.id??null,activityProjectId:u?.kind==="models"?u.route.projectId??null:null,showDiffControls:oe==="chat"&&Ze==="development",diffPanelOpen:le,terminalOpen:at,rightSidebarAvailable:WA,rightSidebarOpen:oe==="labs"&&h?c?.open??!1:oe==="scheduled"?r:le,onToggleDiffPanel:jd,onToggleRightSidebar:oe==="labs"&&h?c?.toggle:oe==="scheduled"?()=>s(Te=>!Te):oe==="team"&&Lr?hl:jd,onOpenSearch:()=>{Y(null),f(!0)},onToggleTerminal:()=>Xe(Te=>!Te),onRunTerminalCommand:Te=>{C({id:Date.now(),scope:Gt,command:Te}),Xe(!0)},onWorkspaceToolAction:Sp,onOpenCommitDialog:vp,onWorkspaceBranchChange:gp,onWorkspaceBranchCreate:bp,connection:Nt,onBootstrap:xn,onOpenSandboxWorkspace:Td,onShowSidebar:()=>G(!0),onOpenTeamChat:rf,onDiscoverCommunities:sf,collaborationView:oe==="team"||oe==="community"?oe:null,platform:Kt,showWorkspaceControls:oe!=="team"&&oe!=="community"&&oe!=="labs"&&oe!=="scheduled"&&oe!=="outputs"&&oe!=="projects"&&(Ze==="development"||Ze==="work"&&!!(In||Rn?.localProjectId||Rn?.cloudProjectId||Rn?.workspaceKind==="local_project"))},mainPane:{ponderMode:n,onPonderModeChange:a,experience:Ze,onNewExperienceChange:it,view:oe,teamChat:{currentUserId:_t.currentUserId,members:_t.members,agents:_t.agents,profile:xt?.profile??null,teamId:wo,teamName:Io?.displayName??null,detail:_t.detail,aiThread:_t.aiThread,agentConversation:_t.agentConversation,loading:_t.loading,busy:_t.busy,error:_t.error,connection:Nt,providerSettings:xt?.providers??null,provider:Pa,model:Fn,codexPermissionMode:ke,codexReasoningEffort:Le,openPondCommandAccessMode:Ui,contextWindowStatus:as,showToast:St,onProviderChange:Ol,onModelChange:fe,onCodexPermissionModeChange:Br,onCodexReasoningEffortChange:Fr,onOpenPondCommandAccessModeChange:_o,onOpenProviderSettings:()=>{ut("providers"),_("settings"),ln({kind:"settings",section:"providers"})},onSendMessage:_t.sendMessage,onPublishProfileAgent:pl,onOpenAiThread:async Te=>{await _t.openAiThread(Te),Pe("chat"),Ce(!0)},onOpenAgentConversation:async Te=>{await _t.openAgentConversation(Te),Pe("chat"),Ce(!0)},onCloseAiThread:()=>Ce(!1),onCloseAgentConversation:()=>{_t.closeAgentConversation(),Ce(!1)},onSendAgentTurn:_t.sendAgentTurn,onSendAiTurn:_t.sendAiTurn,onStopAiTurn:_t.stopAiTurn,onEditMessage:_t.editMessage,onDeleteMessage:_t.deleteMessage,onRetryMessage:_t.retryMessage,onDismissFailedMessage:_t.dismissFailedMessage,onLoadMoreMessages:_t.loadMoreMessages,onRetryLoad:_t.refresh},community:fl,bootstrap:xt,runtimeEvents:fi,chatMessages:Zr,pendingUserMessage:ue?Xo[ue]??null:null,contextWindowStatus:as,goalRuntime:rr,subagentRuntime:Fi,selectedSessionId:ue,composerDraftStore:g,mainComposerFocusRequestId:z,labCloseDetailRequestId:Oe.closeDetailRequestId,labCloseDetailKind:Oe.closeDetailKind,sideChatTrainingLaunchRequest:Md,onSideChatTrainingLaunchHandled:Te=>Lp(ct=>ct?.id===Te?null:ct),mentionApps:So,connectedAppMentions:Ra,profileSkills:of,selectedMentionAppId:O,busy:Ie,turnRunning:Xr,activeProvider:Pa,activeModel:Fn,codexPermissionMode:ke,codexReasoningEffort:Le,openPondCommandAccessMode:Ui,pendingApproval:xo,activeWorkspaceAppId:gl,activeWorkspaceId:qr,activeWorkspaceKind:Ur,projectTarget:mp,actionCatalog:vl,workspaceTarget:Sd,connection:Nt,workspaceName:zr,workspaceState:oa,workspaceDiff:hn,workspaceBusy:pt,diffBusy:rn,forceChatThread:!!ue,diffPanelOpen:le,diffPanelExpanded:xe,rightPanelMode:Ue,rightPanelTabRequest:E,rightChatPanels:Up,runtimeEventStore:Ja,nativeSkillSidebar:Od,extensionSkillSidebar:ss,workspaceDiffPanelViewState:L,sidebarFileOpenRequest:vi,sidebarFileBookmarks:Il,onSetSidebarFileStatus:(Te,ct)=>{Kr(Te,ct)},browserConversationId:lr,terminalScope:Gt,terminalTabs:A,terminalCwd:Qa,pendingTerminalCommand:k,terminalOpen:at,onToggleTerminal:()=>Xe(Te=>!Te),onWorkspaceDiffPanelViewStateChange:xd,training:Ft,trainingSessions:ft,trainingChatHandoff:zi,trainingDetailTasksetId:R,onTrainingDetailTasksetIdChange:$,onTrainingChatTaskSelect:ia,onTrainingChatHandoffDismiss:nr,onOpenSession:is,onExperienceHandoff:cf,cloudProjects:xt?.cloudProjects??[],projects:nf,projectsAccountBaseUrl:qi?.baseUrl??qi?.activeProfile?.baseUrl??null,projectsTeamName:Io?.displayName??null,projectTaskCounts:af,onNewCloudProject:$p,onNewLocalProject:Ed,onNewProjectTask:Te=>rs(Te.id),onToggleProjectPinned:Rd,onUploadLocalProject:Mp,chatHistoryHasMore:ZA,chatHistoryLoading:YA,onDiffPanelResizeStart:Ve,onToggleDiffPanelExpanded:()=>He(Te=>!Te),onShowDiffPanel:Hp,onShowBrowserPanel:Dp,onShowFilesPanel:()=>Bp("files"),onShowGoalSidebarTab:Eo,onShowTrainingDraftPanel:()=>{Pe("training"),Ce(!0)},onShowRightChatPanel:zp,onAddRightChat:()=>Nl(null),onOpenRightChatForSession:(Te,ct)=>{const Lt=ct??ft.find(Ma=>Ma.id===Te)??null;Lt&&Nl(Lt,{preserveView:!0})},onLabDetailOpenChange:Oe.onDetailOpenChange,evaluationSidebarActive:oe==="labs"&&h,onEvaluationSidebarControl:m,scheduledDetailOpen:r,onScheduledDetailOpenChange:s,onTerminalTabsChange:M,onCloseRightChatPanel:qp,onCloseNativeSkillSidebar:Dd,onActivateRightChatPanel:Vp,onRightChatModelChange:Kp,onRightChatPromptChange:Wp,onRightChatScrollStateChange:Jp,onRightChatProviderChange:Gp,onSubmitRightChat:Fp,onStopRightChat:Te=>os(Te),onCloseTerminal:()=>Xe(!1),onLoadMoreChatHistory:kl,canSyncWorkspace:dp,startMessage:ko,onPayload:xn,onError:Ht,setView:_,onOpenProfileSettings:Zp,onOpenProviderSettings:()=>{ln({kind:"settings",section:"providers"})},onOpenTrainingSettings:()=>{ln({kind:"settings",section:"training"})},onOpenDatasetStorageSettings:()=>{ln({kind:"settings",section:"dataset-storage"})},changeDraftProvider:Ol,changeProjectTarget:fp,changeWorkspaceTarget:jp,setDraftProvider:pe,setDraftModel:fe,onBeginNewChatWithModel:Sl,changeCodexPermissionMode:Br,changeCodexReasoningEffort:Fr,changeOpenPondCommandAccessMode:_o,resolveApproval:Vr,answerCreateImproveQuestion:kd,applyCreateImproveCandidate:wp,approveCreateImproveRun:_p,cancelCreateImproveRun:Cp,openCreateImprovePullRequest:Id,reconcileCreateImprovePullRequest:Rp,rejectCreateImproveCandidate:Pp,pauseCreateImproveRun:wd,resumeCreateImproveRun:_d,reviseCreateImproveRun:Ap,setMentionedAppId:j,showToast:St,onSaveTaskDraft:lf,sendPrompt:Op,stopTurn:Te=>os(void 0,Te),syncWorkspaceLocally:Ip,refreshWorkspaceDiff:Dn},cloudSetup:{state:I,onClose:()=>P(null),onOpenBrowserUrl:Np,onStart:()=>{Ad()}},projectConfirm:{state:J,onResolve:X},lazyPanels:{activeSessions:Co,branchDialogName:mt,branchDialogOpen:nt,commitDialogOpen:ee,commitDraft:tt,commitIncludeUnstaged:$e,commitMessage:me,commitNextStep:ze,canPublishOpenPondProject:up,connection:Nt,expandProject:pi,newProjectBusy:F,newProjectDialogOpen:We,newProjectDirectory:aa.defaultNewProjectDirectory,newProjectMode:qe,newProjectName:q,newProjectPath:N,projectRows:va,query:de,searchOpen:je,visibleWorkspaceDiff:hn,visibleWorkspaceState:oa,workspaceBusy:pt,appDispatch:S,beginNewChat:()=>ga(null),openDefaultsSettingsFromBranchDialog:yp,setBranchDialogName:$n,setBranchDialogOpen:zn,setCommitDialogOpen:yn,setCommitDraft:wa,setCommitIncludeUnstaged:Qt,setCommitMessage:Sn,setCommitNextStep:Wa,setNewProjectDialogOpen:fn,setNewProjectName:jt,setNewProjectPath:dn,setPrompt:ce,setQuery:Ye,setSearchOpen:f,submitCommitDialog:xp,submitCreateWorkspaceBranch:kp,submitNewProjectDialog:hp},toast:{toast:vt,onDismiss:()=>S({type:"field",key:"toast",value:null})}})})}const Ps=new Map,Ru=new Map;function Og(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(i=>i.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 dJ(e){const t=e?.trim();if(!t)return null;const n=Ps.get(t);return n?.updatedAt?n.organizations:null}function uJ(e,t){const n=e?.trim();if(n){Ps.set(n,{organizations:t,promise:null,updatedAt:Date.now()});for(const a of Ru.get(n)??[])a()}}function mJ(e,t){const n=e?.trim();if(!n)return()=>{};const a=Ru.get(n)??new Set;return a.add(t),Ru.set(n,a),()=>{a.delete(t),a.size===0&&Ru.delete(n)}}function kx(e){const t=e.accountKey?.trim();if(!t)return Promise.resolve([]);const n=Ps.get(t);if(!e.force){if(n?.updatedAt)return Promise.resolve(n.organizations);if(n?.promise)return n.promise}const a=e.fetchOrganizations().then(i=>(uJ(t,i),i)).catch(i=>{const r=Ps.get(t);throw r?.promise===a&&Ps.set(t,{organizations:r.organizations,promise:null,updatedAt:r.updatedAt}),i});return Ps.set(t,{organizations:n?.organizations??[],promise:a,updatedAt:n?.updatedAt??0}),a}const xie="openpond.config.json";function kie(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function FP(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function xh(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function Iie(e,t=null){const n=fJ(e.openFilePaths.map(i=>wx(i,t)).filter(Boolean)),a=e.selectedPath&&wx(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function Ix(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 wx(e,t=null){let n=pJ(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 i=a.split("/").filter(Boolean).at(-1);return i&&n.startsWith(`${i}/`)&&(n=n.slice(i.length+1)),n}function wie(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function _ie(e){return{path:e,status:"unchanged",additions:0,deletions:0,patch:"",content:null}}function Cie(e,t){const n=_x(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const i=_x(a);return!!(i&&i.startsWith(`${n}/`))})}function Rie(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function Pie(e){return/\.(?:doc|docx|pdf)$/i.test(e)}function pJ(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 fJ(e){return Array.from(new Set(e))}function _x(e){const n=e.replace(/\\/g,"/").replace(/^\.\/+/,"").split("/").filter(Boolean);return n.length===0?null:n.join("/")}function hJ(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",i=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"",r=e.apiBaseUrl??t?.apiBaseUrl??"",s=e.chatApiBaseUrl??t?.chatApiBaseUrl??"";return[n?`profile:${n}`:"profile:unknown",a,i,r,s].join("|")}function VP(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function gJ(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n)}function ap(e){const t=e,n=t.teamId||t.id||"";if(!n)return null;const a=t.displayName||t.name||n,i=t.workspaceKind==="personal"||t.isPersonalDefault===!0||t.kind==="personal_default"||t.name?.trim().toLowerCase()==="personal";return{teamId:n,slug:t.slug||VP(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:i?"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:i,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 vJ(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 bJ(e,t){const n=e.filter(i=>i.status==="active"&&i.workspaceKind==="shared"),a=t?.trim()??"";if(a){const i=n.find(r=>r.teamId===a);if(i)return i}return n.find(i=>i.role==="owner")??n.find(i=>i.role==="admin")??n[0]??null}function yJ(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function SJ({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const xJ=[{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 kJ(...e){return yJ(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function IJ(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return kJ(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function wJ({bootstrap:e,draftModel:t,draftProvider:n,selectedApp:a,selectedAppId:i,selectedCloudProject:r,selectedProject:s,selectedSession:c,selectedSessionId:m,selectedSessionLinkedProject:u}){const h=c?.workspaceKind==="local_project"?c.workspaceId??null:u?.id??null,g=Vt(m)&&!c,S=c?Oi(c.workspaceKind):!1,k=$i(c),C=c?rJ(c):!1,A=c?.cwd&&(!S||k)?c1(c.cwd):null,M=e?.providers??null,R=za(s,e?.cloudProjects??[]),$=SJ({draftProvider:n,hasSelectedCloudProject:!!r,selectedSessionHybridWorkspace:k}),O=Yo($,t,M),j=Oa(e?.preferences),I=g?null:c?S?c.workspaceKind??"sandbox":C?"sandbox":h?"local_project":c.workspaceKind??(c.appId?"sandbox_app":A?"local_project":null):r?"sandbox":s?"local_project":i?"sandbox_app":null,P=g?null:c?S&&!k||C?null:h||(c.workspaceId??c.appId??A):r?null:s?.id??i,E=g?null:c?S?c.workspaceId??null:C?null:h??c.workspaceId??c.appId??A:r?null:s?.id??i,L=e?.account??null,z=!e||L?.state==="loading"||L?.state==="switching",H=!z&&L?.state==="signed_out",J=z?null:H?"Sign in":L?.label??L?.activeProfile?.handle??"Account",X=IJ(L),de=X?`Welcome, ${X}`:"Welcome",je=c?.workspaceName??c?.appName??r?.name??s?.name??a?.name??null,we=Oi(I)?"cloud":"local",te=s?.name??u?.name??(c?.workspaceKind==="local_project"?c.workspaceName:null)??"Local workspace",Me=(we==="cloud"?je:null)??r?.name??R?.name??s?.name??"Cloud workspace",Se=!!(r?.id||R?.id||c?.cloudProjectId||we==="cloud");return{account:L,accountLabel:J,accountPending:z,accountSignedOut:H,activeModel:O,activeProvider:$,activeWorkspaceAppId:P,activeWorkspaceId:E,activeWorkspaceKind:I,activeWorkspaceLocation:we,appDefaults:j,cloudLinked:Se,cloudTargetName:Me,localTargetName:te,selectedCodexHistoryPending:g,selectedSessionCloudWorkspace:S,selectedSessionLocalPathWorkspaceId:A,selectedSessionPendingCloudStart:C,selectedSessionProjectId:h,startMessage:de,workspaceName:je}}function _J({accountPending:e,accountSignedOut:t,activeWorkspaceLocation:n,bootstrap:a,busy:i,cloudLinked:r,selectedCloudProject:s,selectedProject:c,selectedSession:m,pendingWorkspaceTarget:u,workspaceStates:h,workspaceBusy:g}){const S=za(c,a?.cloudProjects??[]),C=!!!c?.linkedSandboxProject?.projectId||!!S,A=y.useMemo(()=>{const E=(a?.localProjects??[]).map(J=>({value:`local:${J.id}`,label:J.name,detail:J.workspacePath,kind:"local"})),L=(a?.cloudProjects??[]).map(J=>({value:`cloud:${J.id}`,label:J.name,detail:J.organizationName??J.sourceLabel??"OpenPond Cloud",kind:"cloud"})),z=c?`local:${c.id}`:s?`cloud:${s.id}`:"none",H=[...E,...L].find(J=>J.value===z)??null;return{value:z,label:H?.label??"Select Project",detail:H?.detail??"Choose a project for local or cloud work",busy:g||i,options:[...E,...L,...xJ,{value:"none",label:"Don't work in a project",detail:"General chat without project files",kind:"none"}]}},[a?.cloudProjects,a?.localProjects,i,s,c,g]),M=!!(r||c),R=!!(s?.id||S?.id||m?.cloudProjectId||$i(m)),$=c?h[c.id]??null:null,O=sP($,{branch:c?.linkedSandboxProject?.defaultBranch??null,path:c?.workspacePath??m?.cwd??null,linkedCloudSourceKnown:c?.linkedSandboxProject?.projectId&&C?!!c.linkedSandboxProject.lastUploadedCommit||!$?.headCommit:!0}),j=lP(c,s??S,$,{cloudLinkTrusted:C}),I=u8(c,$,{cloudLinkTrusted:C}),P=y.useMemo(()=>{const E={value:"local",label:c?"Local checkout":"Local",detail:c?"Use the selected checkout on this machine.":"Use an app-managed task workspace on this machine.",stateNote:c?O:"App-managed local task workspace",disabled:!1,disabledReason:null},L={value:"hybrid",label:"Hybrid",detail:"Use your selected model with hosted sandbox edits.",stateNote:R?j:"upload required",disabled:e||t||!R,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||s?j:"Projectless hosted task",disabled:e||t,disabledReason:t?"Add an OpenPond account before using Cloud.":e?"Checking OpenPond account.":null},H={value:"upload_cloud",label:"Upload/sync to cloud",detail:"Push local source to OpenPond Git before cloud work.",stateNote:I,disabled:e||t||!c,disabledReason:t?"Add an OpenPond account before uploading source.":"Select a local Project before uploading source."},J=n==="cloud"?"local":"cloud",X=J==="local"?E:z;let de=n==="cloud"?z:E;return u==="cloud"?de=z:u==="local"?de=E:($i(m)||u==="hybrid")&&(de=L),{value:de.value,label:de.label,detail:de.stateNote||de.detail,busy:g,action:{...X,label:J==="cloud"?"Hosted":c?"Local checkout":"Check out locally"},uploadAction:c?H:null,options:[E,L,z]}},[n,e,t,r,M,j,R,O,u,c,m,I,g]);return{projectTarget:A,workspaceTarget:P}}function Wn(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}function KP(e){return Wn(e.name||e.gitRepo||e.id)}function Aie(e){return`@${KP(e)}`}function WP(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Wn(t[1]??"")).filter(Boolean)}function CJ(e,t){const n=WP(e);if(n.length===0)return!1;const a=new Set([Wn(t.id),KP(t),t.gitRepo?Wn(t.gitRepo):""].filter(Boolean));return n.some(i=>a.has(i))}function GP(e){return e.filter(t=>t.sandbox)}function RJ(e,t){const n=WP(e);if(n.length===0)return null;const a=new Map;for(const i of n){const r=t.find(s=>{const c=Wn(s.id),m=Wn(s.name),u=s.gitRepo?Wn(s.gitRepo):"";return i===c||i===m||i===u});r&&a.set(r.id,r)}return a.size===1?Array.from(a.values())[0]??null:null}function Tie(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 i=n.slice(a.index).indexOf("@");return i<0?null:{query:Wn(a[1]??""),start:a.index+i}}function PJ(e){return new Set(e.map(t=>t.id))}function Cx(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function AJ({bootstrap:e,codexHistorySessions:t,selectedProjectId:n,selectedSessionId:a,selectedAppId:i,sessions:r}){const s=y.useMemo(()=>e?.apps.find(H=>H.id===i)??null,[e?.apps,i]),c=y.useMemo(()=>new Map((e?.localProjects??[]).map(H=>[H.id,H])),[e?.localProjects]),m=y.useMemo(()=>new Map((e?.cloudProjects??[]).map(H=>[H.id,H])),[e?.cloudProjects]),u=y.useMemo(()=>JR(n),[n]),h=y.useMemo(()=>u?.kind==="local"?c.get(u.id)??null:null,[c,u]),g=y.useMemo(()=>u?.kind==="cloud"?m.get(u.id)??null:null,[m,u]),S=y.useMemo(()=>PJ(e?.apps??[]),[e?.apps]),k=y.useMemo(()=>GP(e?.apps??[]),[e?.apps]),C=y.useMemo(()=>{const H=[];for(const J of e?.localProjects??[]){const X=Cx(J,S);X&&H.push([X.appId,J.id])}return new Map(H)},[e?.localProjects,S]),A=y.useMemo(()=>new Set((e?.localProjects??[]).map(H=>H.id)),[e?.localProjects]),M=y.useMemo(()=>tP(e?.localProjects??[]),[e?.localProjects]),R=y.useRef([]),$=y.useMemo(()=>TJ(r,t,R.current),[t,r]),O=y.useMemo(()=>$.find(H=>H.id===a)??null,[$,a]),j=y.useMemo(()=>{if(!O)return null;if(O.localProjectId)return c.get(O.localProjectId)??null;if(O.workspaceKind==="local_project")return O.workspaceId?c.get(O.workspaceId)??null:null;const H=e8(O,A,M);if(H)return c.get(H)??null;if(!O.appId)return null;const J=C.get(O.appId);return J?c.get(J)??null:null},[C,c,A,M,O]),I=y.useMemo(()=>O?.cloudProjectId?m.get(O.cloudProjectId)??null:null,[m,O]),P=h??j,E=g??I,L=y.useMemo(()=>Cx(P,S),[S,P]),z=y.useMemo(()=>L?e?.apps.find(H=>H.id===L.appId)??null:null,[e?.apps,L]);return{cloudProjectById:m,currentAppIds:S,linkedProjectByAppId:C,localProjectById:c,mentionableSandboxApps:k,selectedApp:s,selectedCloudProject:E,selectedProject:P,selectedProjectLinkedApp:z,selectedProjectLinkedOpenPondApp:L,selectedSession:O,selectedSessionLinkedProject:j,sidebarSessions:$}}function TJ(e,t,n){const a=new Map;for(const u of e){const h=Rx(u);a.set(h,u)}for(const u of t){const h=Rx(u),g=a.get(h);a.set(h,g?EJ(g,u):u)}const i=Array.from(a.entries());if(!n)return i.sort((u,h)=>Px(u[1],h[1])).map(u=>u[1]);const r=[],s=new Set;for(const u of n){const h=a.get(u);h&&(r.push([u,h]),s.add(u))}const m=[...i.filter(([u])=>!s.has(u)).sort((u,h)=>Px(u[1],h[1])),...r];return n.splice(0,n.length,...m.map(([u])=>u)),m.map(u=>u[1])}function EJ(e,t){return{...e,metadata:MJ(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:jJ(e.updatedAt,t.updatedAt)}}function Rx(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function Px(e,t){const n=Ax(t)-Ax(e);return n!==0?n:e.title.localeCompare(t.title)}function MJ(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function jJ(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 Ax(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 OJ(e){return!!(e&&Oi(e.workspaceKind)&&!$i(e)&&e.provider!=="openpond")}function $J(e,t){const n=QR(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function NJ({activeWorkspaceId:e,activeWorkspaceKind:t,appDispatch:n,connection:a,expandProject:i,linkedProjectByAppId:r,providerSettings:s,selectedAppId:c,selectedSession:m,selectedSessionId:u,selectedSessionProjectId:h,setDiffPanelExpanded:g,setDraftModel:S,setDraftProvider:k,setError:C,setSelectedAppId:A,setSelectedProjectId:M,setSessions:R,setTerminalOpen:$,toast:O}){const j=y.useRef(null);y.useEffect(()=>{if(!c)return;const I=h??(u?null:r.get(c)??null);if(!I)return;const P=wt("local",I);A(null),M(P),i(P)},[i,r,c,u,h,A,M]),y.useEffect(()=>{if(!O||O.persistent)return;const I=window.setTimeout(()=>{n({type:"clearToast",toastId:O.id})},O.durationMs??(O.tone==="error"?7e3:3500));return()=>window.clearTimeout(I)},[n,O]),y.useEffect(()=>{function I(P){(P.metaKey||P.ctrlKey)&&P.key==="`"&&(P.preventDefault(),$(E=>!E))}return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[$]),y.useEffect(()=>{g(!1)},[e,t,g]),y.useEffect(()=>{if(!u){j.current=null;return}if(!m||m.id!==u)return;const I=$J(m,s);if(j.current===I)return;j.current=I;const P=QR(m,s);k(P.provider),S(P.model)},[s,m,u,S,k]),y.useEffect(()=>{!a||!m||!OJ(m)||Q.patchSession(a,m.id,{provider:"openpond"}).then(I=>{R(P=>P.map(E=>E.id===I.id?I:E)),k("openpond"),S(P=>Yo("openpond",P))}).catch(I=>{C(I instanceof Error?I.message:String(I))})},[a,m,S,k,C,R])}function DJ({connection:e,setError:t}){return y.useCallback(async(n,a)=>{if(!e){const i=new Error("OpenPond App server is not connected.");throw t(i.message),i}t(null);try{await Q.resolveApproval(e,n,{decision:a})}catch(i){const r=i instanceof Error?i.message:String(i);throw t(r),i}},[e,t])}function HJ({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:i,pinnedProjects:r,projectRows:s,visibleProjectRows:c}){const m=y.useMemo(()=>UW(a,i),[a,i]),u=y.useMemo(()=>xP({provider:e,snapshot:n,preferences:t}),[e,t,n]),h=y.useMemo(()=>Array.from(new Set([...r,...c].filter(ty).map(S=>S.project.id))),[r,c]);return{commandProjectRows:y.useMemo(()=>s,[s]),contextWindowStatus:u,pinnedRows:m,sidebarWorkspaceAppIds:h}}function LJ({appDispatch:e,expandProject:t,linkedProjectByAppId:n,requestComposerFocus:a,onBeginNewChat:i,setMentionedAppId:r}){return y.useCallback((s=null)=>{i?.();const c=s?.id?n.get(s.id)??null:null;if(c){const m=wt("local",c);r(null),e({type:"selectProject",projectId:m}),t(m),a();return}r(null),e({type:"beginNewChat",appId:s?.id??null}),a()},[e,t,n,i,a,r])}const JP={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 Eie(e){return`@${e.token}`}function qJ(e){return`@${VJ(e)}`}function UJ(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 i=a[0],r=bs(a.flatMap(g=>g.capabilities.map(S=>S.id))),s=bs(a.flatMap(g=>g.capabilityLabels)),c=bs(a.flatMap(g=>g.connections.map(S=>S.id).filter(WJ))),m=bs(a.map(g=>g.id)),u=bs(a.map(g=>g.setupSurface)),h=FJ(n);return{provider:n,label:i.providerLabel,detail:s.length>0?s.slice(0,4).join(", "):i.description,token:h,tokens:BJ(a),ref:{kind:"integration",provider:n,appIds:m,setupSurfaces:u,...c.length>0?{connectionIds:c}:{},...r.length>0?{capabilities:r}:{}}}})}function Mie(e,t){const n=Wn(t);return e.filter(a=>n?a.tokens.some(i=>i.includes(n)):!0).slice(0,8)}function zJ(e,t){const n=KJ(e);if(n.length===0)return[];const a=new Map;for(const i of n){const r=t.find(s=>s.tokens.includes(i));r&&a.set(r.provider,r)}return Array.from(a.values())}function jie(e,t){if(t.length===0)return[];const n=[];for(const a of e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)){const i=a[1]??"",r=Wn(i);if(!r)continue;const s=t.find(g=>g.tokens.includes(r));if(!s)continue;const m=(a[0]??"").indexOf("@");if(m<0||typeof a.index!="number")continue;const u=a.index+m,h=`@${i}`;n.push({detail:s.detail,displayText:qJ(s),end:u+h.length,label:s.label,provider:s.provider,start:u,text:h})}return n}function BJ(e){return bs(e.flatMap(t=>[...JP[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map(Wn).filter(Boolean))}function FJ(e){return Wn(JP[e][0]??e)}function VJ(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function KJ(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Wn(t[1]??"")).filter(Boolean)}function bs(e){return Array.from(new Set(e))}function WJ(e){return typeof e=="string"&&e.length>0}function GJ({bootstrap:e,connectedAppRows:t,mentionableSandboxApps:n,runtimeIndexes:a,selectedApp:i,selectedCloudProject:r,selectedProject:s,selectedSession:c,selectedSessionId:m}){const u=y.useMemo(()=>{const C=new Map;for(const A of e?.cloudProjects??[]){const M=C.get(A.teamId)??[];M.push(A.id),C.set(A.teamId,M)}return C},[e?.cloudProjects]),g=!!(c||i||s||r)?[]:n,S=y.useMemo(()=>UJ(t),[t]),k=y.useMemo(()=>V7(a,m),[a,m]);return{chatMentionApps:g,cloudProjectIdsByTeam:u,connectedAppMentions:S,pendingApproval:k}}function JJ({connection:e,setBootstrap:t,setCodexPermissionMode:n,setCodexReasoningEffort:a,setError:i}){const r=y.useCallback(c=>{if(!e){i("Connect to OpenPond before saving preferences.");return}Q.savePreferences(e,{codexPermissionMode:c}).then(m=>{n(m.preferences.codexPermissionMode),a(m.preferences.codexReasoningEffort),t(u=>u&&{...u,preferences:m.preferences})}).catch(m=>{i(m instanceof Error?m.message:String(m))})},[e,t,n,a,i]),s=y.useCallback(c=>{if(!e){i("Connect to OpenPond before saving preferences.");return}Q.savePreferences(e,{codexReasoningEffort:c}).then(m=>{n(m.preferences.codexPermissionMode),a(m.preferences.codexReasoningEffort),t(u=>u&&{...u,preferences:m.preferences})}).catch(m=>{i(m instanceof Error?m.message:String(m))})},[e,t,n,a,i]);return{changeCodexPermissionMode:r,changeCodexReasoningEffort:s}}const ZJ=6e4;function my(e,t){if(!e)return t;const n=QJ(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 YP(e,n)?e:n}function YJ(e,t){const n=my(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&YP(e,a)?e:a}function tc(e,t){let n=!1,a=!1;const i=e.map(r=>{if(r.id!==t.id)return r;n=!0;const s=my(r,t);return s!==r&&(a=!0),s});return n?a?i:e:[t,...e]}function ip(e,t){let n=!1,a=!1;const i=e.map(r=>{if(r.id!==t.id)return r;n=!0;const s=YJ(r,t);return s!==r&&(a=!0),s});return n?a?i:e:[t,...e]}function $g(e,t,n,a=Date.now()){const i=new Map(e.map(r=>[r.id,r]));return t.map(r=>{const s=i.get(r.id);if(s&&n){const c=eZ(s,r,n,a);if(c)return c}return my(s,r)})}function Tx(e,t,n,a=Date.now()){const i=new Map(e.map(u=>[u.id,u])),r=new Map($g(e,t,n,a).map(u=>[u.id,u])),s=new Set(i.keys()),c=t.filter(u=>!s.has(u.id)).map(u=>r.get(u.id)??u),m=e.map(u=>{const h=r.get(u.id);return h||(ZP(u,t)?u:null)}).filter(u=>!!u);return[...c,...m]}function ZP(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=XJ(t);return a===null||n>=a}function Ex(e,t,n,a=Date.now()){const i=new Map(t.map(r=>[r.id,r]));for(const r of n){const s=i.get(r.id);s&&(QP(s,r)||(e[r.id]=a))}}function QJ(e,t){const n=Date.parse(e),a=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(a)&&n>a}function YP(e,t){return JSON.stringify(e)===JSON.stringify(t)}function XJ(e){let t=null;for(const n of e){const a=Date.parse(n.updatedAt);Number.isFinite(a)&&(t=t===null?a:Math.max(t,a))}return t}function eZ(e,t,n,a){const i=n[t.id];return i===void 0?null:a-i>ZJ||QP(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function QP(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const XP=800,tZ=5e3,Mx=5e4,nZ=16,aZ=3e4,ca=new Map;function iZ(e,t){return ca.get(tA(e,t))?.payload??null}async function eA(e,t,n={}){const a=tA(e,t),i=ca.get(a),r=n.limit??XP,s=n.tail??!0;if(i?.promise)return i.promise;if(!n.force&&s&&i?.payload&&Date.now()-i.fetchedAt<=aZ)return jx(a,i),i.payload;const c=!!(n.force&&s&&i?.payload),m=c?i?.payload?.events.at(-1)?.id:void 0,u=Q.codexHistoryThreadIncremental(e,t,{afterEventId:m,limit:r,revision:c?i?.revision:void 0,tail:s}).then(h=>{const g=ca.get(a)?.payload??i?.payload;if(h.unchanged){if(!g)throw new Error("Codex history revision matched without a cached thread.");return ca.set(a,{fetchedAt:Date.now(),payload:g,revision:h.revision}),jx(a,ca.get(a)),g}const S={session:h.session,events:h.events},k=s&&g&&!h.reset?{...S,events:oZ(g.events,S.events)}:S;return ca.set(a,{fetchedAt:Date.now(),payload:k,revision:h.revision}),Ox(),k}).catch(h=>{throw ca.get(a)?.promise===u&&ca.delete(a),h});return ca.set(a,{fetchedAt:i?.fetchedAt??0,payload:i?.payload,promise:u,revision:i?.revision}),Ox(),u}function tA(e,t){return`${e.serverUrl}
186
+ ${e.token}
187
+ ${t}`}function jx(e,t){ca.delete(e),ca.set(e,t)}function Ox(){for(;ca.size>nZ;){const e=ca.keys().next().value;if(!e)return;ca.delete(e)}}function oZ(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 rZ=500,sZ=2500,lZ=15e3;function cZ(e){return e.active?rZ:e.surface==="thread"?sZ:lZ}function py(e,t){return!t||e.session.status==="active"?e:{...e,session:{...e.session,status:"active"}}}function dZ(e={}){const t={cachedPayload:e.cachedPayload??iZ,clearTimer:e.clearTimer??(u=>globalThis.clearTimeout(u)),loadPayload:e.loadPayload??eA,now:e.now??Date.now,setTimer:e.setTimer??((u,h)=>globalThis.setTimeout(u,h))},n=new Map;let a=1;function i(u){const h=mZ(u.connection,u.sessionId);let g=n.get(h);g||(g={connection:u.connection,disposed:!1,inFlight:null,latestPayload:t.cachedPayload(u.connection,u.sessionId),nextRefreshAt:null,sessionId:u.sessionId,subscribers:new Map,timer:null},n.set(h,g));const S=a++;return g.subscribers.set(S,u),g.latestPayload&&u.onPayload(g.latestPayload),r(g,0),()=>{const k=n.get(h);if(k){if(k.subscribers.delete(S),k.subscribers.size>0){r(k,c(k));return}k.disposed=!0,m(k),n.delete(h)}}}function r(u,h){if(u.disposed||u.subscribers.size===0||u.inFlight)return;const g=t.now()+Math.max(0,h);u.timer&&u.nextRefreshAt!==null&&u.nextRefreshAt<=g||(m(u),u.nextRefreshAt=g,u.timer=t.setTimer(()=>{u.timer=null,u.nextRefreshAt=null,s(u)},Math.max(0,h)))}async function s(u){if(u.disposed||u.subscribers.size===0||u.inFlight)return;const h=t.loadPayload(u.connection,u.sessionId,{force:!!u.latestPayload});u.inFlight=h;try{const g=await h;if(u.disposed||g===u.latestPayload)return;u.latestPayload=g;for(const S of u.subscribers.values())S.onPayload(g)}catch(g){if(u.disposed)return;for(const S of u.subscribers.values())S.onError?.(g)}finally{u.inFlight===h&&(u.inFlight=null),u.disposed||r(u,c(u))}}function c(u){const h=[...u.subscribers.values()],g=h.some(k=>k.locallyActive||k.reportedActive)||u.latestPayload?.session.status==="active"||cy(u.latestPayload?.events??[])?.tone==="active",S=h.some(k=>k.surface==="thread")?"thread":"sidebar";return cZ({active:g,surface:S})}function m(u){u.timer&&t.clearTimer(u.timer),u.timer=null,u.nextRefreshAt=null}return{subscribe:i}}const uZ=dZ();function fy(e){return uZ.subscribe(e)}function mZ(e,t){return`${e.serverUrl}
188
+ ${e.token}
189
+ ${t}`}function pZ({connection:e,selectedSessionId:t,selectedSessionLocallyActive:n,selectedSessionStatus:a,setCodexHistorySessions:i,setError:r}){const[s,c]=y.useState({events:[],sessionId:null}),m=Vt(t)?t:null,u=m&&s.sessionId===m?s.events:[],h=y.useCallback(g=>{c(S=>{if(!m)return{events:[],sessionId:null};const k=S.sessionId===m?S.events:[];return{events:typeof g=="function"?g(k):g,sessionId:m}})},[m]);return y.useEffect(()=>{if(!e||!m){c(k=>k.sessionId===null&&k.events.length===0?k:{events:[],sessionId:null});return}r(k=>k==="Session not found"?null:k);const g=n;return fy({connection:e,locallyActive:g,onError:k=>r(k instanceof Error?k.message:String(k)),onPayload:k=>{const C=py(k,g);c(A=>A.sessionId!==m?{events:C.events,sessionId:m}:{events:Qi(A.events,C.events),sessionId:m}),r(A=>A==="Session not found"?null:A),i(A=>ip(A,C.session))},reportedActive:a==="active",sessionId:m,surface:"thread"})},[e,m,n,a,i,r]),{codexHistoryEvents:u,setCodexHistoryEvents:h}}function nA(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 fZ({connection:e,appPreferences:t,sessions:n,pinnedItems:a,setAppPreferences:i,setCodexHistorySessions:r,setSessions:s,sidebarFileBookmarks:c,setSidebarFileBookmarks:m,setError:u}){const[h,g]=y.useState(null),[S,k]=y.useState(null),C=y.useRef(null),A=y.useRef(null);function M(P,E){P.dataTransfer.effectAllowed="move",P.dataTransfer.setData("text/plain",`${E.type}:${E.id}`),nA(P);const L=a.map(z=>z.key);C.current=E,A.current=L,g(E),k(L)}function R(){C.current=null,A.current=null,g(null),k(null)}function $(P,E){const L=C.current;if(!L)return;const z=Xu(P),H=A.current??a.map(X=>X.key),J=em(H,xr(L),xr(E),z);ZS(H,J)||(A.current=J,k(J))}function O(P){if(!e)return;const E=a.map(we=>we.key),L=new Set(E),z=[...P.filter(we=>L.has(we)),...E.filter(we=>!P.includes(we))];if(ZS(E,z))return;const H=t,J=new Map(n.map(we=>[we.id,we])),X=c,de=new Map(a.map(we=>[we.key,we]));i(we=>{const te={...we};return z.forEach((Me,Se)=>{const oe=de.get(Me);oe?.type==="project"&&(te[oe.id]={...te[oe.id]??{},pinned:!0,archived:!1,order:Se})}),te});const je=we=>{const te=new Map(we.map(oe=>[oe.id,oe])),Me=z.map((oe,be)=>{const re=de.get(oe),ue=re?.type==="session"?te.get(re.id):null;return ue?{...ue,order:be}:null}).filter(oe=>!!oe),Se=new Map(Me.map(oe=>[oe.id,oe]));return we.map(oe=>Se.get(oe.id)??oe)};s(je),r(je),m(we=>{const te=new Map;return z.forEach((Me,Se)=>{const oe=de.get(Me);oe?.type==="file"&&te.set(oe.id,Se)}),we.map(Me=>{const Se=te.get(Me.id);return Se===void 0?Me:{...Me,order:Se}})}),Promise.all(z.map((we,te)=>{const Me=de.get(we);return Me?Me.type==="project"?Q.patchSidebarAppPreference(e,Me.id,{pinned:!0,archived:!1,order:te}):Me.type==="session"?Q.patchSession(e,Me.id,{order:te}):Q.patchSidebarFile(e,{workspaceKind:Me.file.workspaceKind,workspaceId:Me.file.workspaceId,workspaceName:Me.file.workspaceName,path:Me.file.path,status:"pinned",order:te,sourceSessionId:Me.file.sourceSessionId}):Promise.resolve(null)})).catch(we=>{u(we instanceof Error?we.message:String(we)),i(H);const te=Me=>Me.map(Se=>J.get(Se.id)??Se);s(te),r(te),m(X)})}function j(P,E){const L=C.current;if(L){const z=A.current??a.map(J=>J.key),H=em(z,xr(L),xr(E),Xu(P));O(H)}R()}function I(){C.current&&O(A.current??a.map(E=>E.key)),R()}return{dragItem:h,pinnedPreviewKeys:S,startPinnedDrag:M,clearSidebarDrag:R,previewPinnedDrop:$,commitPinnedDrop:j,commitPinnedPreviewDrop:I}}function hZ({connection:e,sessions:t,setCodexHistorySessions:n,setError:a,setSessions:i}){const[r,s]=y.useState(null),[c,m]=y.useState(null),u=y.useRef(null),h=y.useRef(null);function g(R,$){R.dataTransfer.effectAllowed="move",R.dataTransfer.setData("text/plain",`session:${$.sessionId}`),nA(R),u.current=$,h.current=$.visibleSessionIds,s($.sessionId),m($.visibleSessionIds)}function S(R,$){const O=u.current;if(!O)return;const j=h.current??O.visibleSessionIds,I=em(j,O.sessionId,$,Xu(R));gZ(j,I)||(h.current=I,m(I))}function k(){u.current=null,h.current=null,s(null),m(null)}function C(R,$){const O=u.current;if(!O){k();return}const j=h.current??O.visibleSessionIds,I=em(j,O.sessionId,$,Xu(R));M(ax(O.allSessionIds,O.visibleSessionIds,I)),k()}function A(){const R=u.current;R&&M(ax(R.allSessionIds,R.visibleSessionIds,h.current??R.visibleSessionIds)),k()}function M(R){const $=new Map(R.map((P,E)=>[P,E])),O=new Map(t.map(P=>[P.id,P.order])),j=R.filter((P,E)=>O.get(P)!==E);if(j.length===0)return;const I=P=>P.map(E=>{const L=$.get(E.id);return L===void 0||L===E.order?E:{...E,order:L}});i(I),n(I),e&&Promise.all(j.map(P=>Q.patchSession(e,P,{order:$.get(P)}))).catch(P=>{const E=L=>L.map(z=>{const H=O.get(z.id);return H===void 0||H===z.order?z:{...z,order:H}});i(E),n(E),a(P instanceof Error?P.message:String(P))})}return{clearTaskDrag:k,commitTaskDrop:C,commitTaskPreviewDrop:A,previewTaskDrop:S,startTaskDrag:g,taskDragSessionId:r,taskPreviewSessionIds:c}}function gZ(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function $x({afterMessageId:e=null,attachments:t,content:n,sessionId:a}){const i=new Date().toISOString(),r=`pending_user_${a}_${i}_${Math.random().toString(36).slice(2,8)}`,s=vZ(t);return{id:r,role:"user",content:n,sessionId:a,afterMessageId:e,timestamp:i,turnId:r,...s.length>0?{attachments:s}:{}}}function aA(e,t){return!t||iA(e,t)?e:[...e,t]}function iA(e,t){const n=t.afterMessageId?e.findIndex(r=>r.id===t.afterMessageId):-1,a=n>=0?n+1:0,i=Date.parse(t.timestamp);for(let r=a;r<e.length;r+=1){const s=e[r];if(s.role!=="user"||s.content!==t.content)continue;if(n>=0||!t.afterMessageId)return!0;const c=Date.parse(s.timestamp);if(!Number.isFinite(i)||!Number.isFinite(c)||c>=i)return!0}return!1}function vZ(e){return e.map(({contentsBase64:t,text:n,...a})=>a)}function ye(e,t){if(!e)return null;for(const n of t){const a=e[n];if(typeof a=="string"&&a.trim())return a}return null}function Qo(e){const t=e.trim();if(!t||!t.startsWith("{")&&!t.startsWith("["))return null;try{return JSON.parse(t)}catch{return null}}function Re(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ho(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(t(a))return a}return null}function bZ(e,t,n){if(t.name==="workspace_action_result"){const a=ho(e,i=>i.role==="assistant"&&i.turnId===t.turnId&&i.actionRun?.actionName===n.actionName);if(a?.actionRun){a.id=t.id,a.timestamp=t.timestamp,a.actionRun={...a.actionRun,...n,refs:Ng([...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 yZ(e){if(e.name!=="workspace_action"&&e.name!=="workspace_action_result")return null;const t=Re(e.data),n=Re(e.args),a=ye(n,["actionName"])??ye(Re(n?.input),["actionName"])??kh(t)??kh(Re(t?.run))??kh(Re(t?.agentRun));if(!(e.action==="sandbox_run_action"||e.action==="profile_run_action"||!!a||t?.openPondActionRun===!0||t?.openPondProfileActionRun===!0)||!a)return null;const r=Re(t?.run)??Re(t?.agentRun),s=Re(r?.metadata),c=Re(t?.actionSummary)??Re(r?.actionSummary)??Re(s?.actionSummary),m=Re(t?.action)??c??Re(s?.selectedAction)??null,u=Re(t?.responseSummary)??Re(r?.responseSummary)??Re(s?.responseSummary),h=Re(t?.sourceSummary)??Re(r?.sourceSummary)??Re(s?.sourceSummary),g=Re(t?.traceSummary)??Re(r?.traceSummary)??Re(s?.traceSummary),S=Re(t?.evalSummary)??Re(r?.evalSummary)??Re(s?.evalSummary),k=Ng([...Ji("artifact",t?.artifactRefs,"Artifact"),...Ji("artifact",m?.artifactRefs,"Artifact"),...Ji("artifact",c?.artifactRefs,"Artifact"),...Ji("artifact",u?.artifactRefs,"Artifact"),...Ji("trace",t?.traceArtifactRefs,"Trace"),...Ji("trace",g?.artifactRefs,"Trace"),...Ji("eval",t?.evalResultArtifactRefs,"Eval"),...Ji("eval",S?.artifactRefs,"Eval"),...Ji("output",t?.outputRefs,"Output")]),C=ye(h,["sourceRef","ref"]);return C&&k.push({id:Dg("source",C),kind:"source",label:"Source",target:C}),{actionName:a,title:ye(m,["label","title","name"])??ye(s,["selectedActionLabel"])??_Z(a),status:SZ(e,u,r),responseText:ye(u,["text","summary","message"])??(e.name==="workspace_action_result"&&e.output?.trim()||null),runId:ye(r,["id","runId"])??ye(t,["runId","agentRunId"])??null,projectId:ye(r,["projectId"])??ye(t,["projectId"])??ye(n,["projectId"])??null,agentId:ye(r,["agentId"])??ye(t,["agentId"])??ye(n,["agentId"])??null,agentName:ye(Re(m?.implementation),["agentName"])??ye(m,["agentName"])??ye(s,["selectedAgentName"])??null,sandboxId:ye(r,["sandboxId"])??ye(t,["sandboxId"])??ye(Re(t?.sandbox),["id"])??ye(Re(t?.createdSandbox),["id"])??ye(n,["sandboxId"])??null,runtimeId:ye(r,["runtimeId"])??ye(t,["runtimeId"])??null,implementationType:ye(t,["implementationType"])??ye(m,["implementationType","type","kind"])??ye(Re(m?.implementation),["type","kind"])??ye(s,["implementationType"])??(e.action==="profile_run_action"||t?.openPondProfileActionRun===!0?"openpond-profile-action":null),sourceRef:C,manifestHash:ye(h,["manifestHash"])??ye(t,["manifestHash"])??ye(s,["manifestHash"])??null,refs:Ng(k),childCalls:kZ(t,r,s)}}function kh(e){return e?ye(e,["actionName","name"])??ye(Re(e.action),["actionName","name"])??ye(Re(e.actionSummary),["actionName","name"])??ye(Re(e.selectedEntrypoint),["name"]):null}function SZ(e,t,n){if(e.status==="failed")return"failed";const a=ye(t,["status"]);if(a==="failed")return"failed";if(a==="running"||a==="pending")return a;if(a==="available"||e.status==="completed")return"completed";const i=ye(n,["status"]);return i==="failed"?"failed":i==="succeeded"||i==="completed"?"completed":i==="queued"||i==="running"||i==="runtime_created"?"running":e.status==="pending"?"pending":e.status==="started"||e.name==="workspace_action"?"running":"unknown"}function Ji(e,t,n){return(Array.isArray(t)?t:t?[t]:[]).flatMap(i=>{const r=xZ(e,i,n);return r?[r]:[]})}function xZ(e,t,n){if(typeof t=="string"&&t.trim()){const s=t.trim();return{id:Dg(e,s),kind:e,label:n,target:s}}const a=Re(t);if(!a)return null;const i=ye(a,["url","webUrl","artifactPath","path","ref"])??ye(Re(a.artifact),["url","webUrl","path","ref"]);if(!i)return null;const r=ye(a,["label","title","name","type","kind"])??n;return{id:Dg(e,i),kind:e,label:r,target:i}}function Ng(e){const t=new Set,n=[];for(const a of e){const i=`${a.kind}:${a.target}`;t.has(i)||(t.add(i),n.push(a))}return n}function Dg(e,t){return`${e}:${t}`}function kZ(e,t,n){return[e?.childCalls,e?.childRuns,e?.implementationCalls,t?.childCalls,t?.childRuns,n?.childCalls,n?.childRuns].flatMap(i=>IZ(i)).slice(0,6)}function IZ(e){return(Array.isArray(e)?e:e?[e]:[]).flatMap((n,a)=>{const i=Re(n);if(!i)return[];const r=ye(i,["id","runId","callId"])??`child_${a+1}`,s=ye(i,["label","title","actionName","name","tool"])??ye(Re(i.action),["label","name"])??"Implementation call",c=ye(i,["detail","summary","runId","sandboxId","runtimeId"])??null;return[{id:r,label:s,status:wZ(i),detail:c}]})}function wZ(e){const t=ye(e,["status","state"]);return t==="running"||t==="completed"||t==="failed"||t==="pending"?t:t==="succeeded"?"completed":"unknown"}function _Z(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}const CZ=new Set([".avif",".gif",".jpeg",".jpg",".png",".webp"]);function oA(e){if(!e)return!1;const t=e.split("?")[0]?.split("#")[0]??e,n=t.lastIndexOf(".");return n<0?!1:CZ.has(t.slice(n).toLowerCase())}function rA(e){return e.split("/").filter(Boolean).pop()??e}function RZ(e){if(!Lg(e))return;const t=Re(e.data),a=(typeof t?.openpondImagePreviewPath=="string"?t.openpondImagePreviewPath:null)??kr(e.data)??kr(e.args)??kr(e.output);if(!(!a||!oA(a)))return{path:a,appId:e.appId??null,title:rA(a)}}function PZ(e){if(e.name!=="tool.completed"&&e.name!=="workspace_action_result")return[];const t=[],n=new Set;return Hg(e.data,t,n),t.slice(0,12)}function Hg(e,t,n,a=0){if(a>7||e==null)return;if(Array.isArray(e)){for(const c of e)Hg(c,t,n,a+1);return}const i=Re(e);if(!i)return;const r=ye(i,["path","artifactRef"]),s=ye(i,["contentType","mimeType"]);r&&s&&!n.has(r)&&(n.add(r),t.push({path:r,title:ye(i,["title","name"])??rA(r),contentType:s,sizeBytes:typeof i.sizeBytes=="number"?i.sizeBytes:null}));for(const c of Object.values(i))Hg(c,t,n,a+1)}function Lg(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return!1;const t=Re(e.data);return typeof t?.openpondImagePreviewPath=="string"&&t.openpondImagePreviewPath.trim()?!0:[e.output,e.action,ye(t,["tool","toolName","tool_name","name","functionName","function_name","command"]),ye(Re(t?.input),["tool","toolName","tool_name","name"]),ye(Re(t?.arguments),["tool","toolName","tool_name","name"]),ye(Re(t?.args),["tool","toolName","tool_name","name"])].filter(a=>!!a).some(a=>a.toLowerCase().includes("view_image"))}function kr(e,t=0,n=""){if(t>5||e==null)return null;if(typeof e=="string"){if(Ih(n)&&oA(e.trim()))return e.trim();const i=Qo(e);if(i!==null){const r=kr(i,t+1,n);if(r)return r}return AZ(e)}if(Array.isArray(e)){for(const i of e){const r=kr(i,t+1,n);if(r)return r}return null}const a=Re(e);if(!a)return null;for(const[i,r]of Object.entries(a)){if(!Ih(i))continue;const s=kr(r,t+1,i);if(s)return s}for(const[i,r]of Object.entries(a)){if(Ih(i))continue;const s=kr(r,t+1,i);if(s)return s}return null}function Ih(e){return/^(path|filePath|filepath|imagePath|image|localPath|uri|url)$/i.test(e)}function AZ(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 TZ(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=MZ(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 EZ(e){if(e.action!=="connected_app_search"&&e.action!=="connected_app_read"&&e.action!=="connected_app_write")return null;const t=sA(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 MZ(e){return sA(e).providerLabel}function sA(e){const t=Re(e.args),n=Re(e.data),a=Re(n?.result),i=vm(ye(t,["provider"])??ye(a,["provider"])??ye(n,["provider"])??void 0),r=ye(a,["providerLabel"])??ye(n,["providerLabel"])??(i?vv(i)?.label:null)??"connected app",s=ye(t,["operation"]),c=ye(a,["operation"])??ye(n,["operation"]),m=wh(t?.capabilityIds)||wh(a?.capabilityIds)||wh(n?.capabilityIds);return{providerLabel:r,providerOperation:s,operation:c,capabilityCount:m}}function wh(e){return Array.isArray(e)?e.length:0}function lA(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()||_h(a)}}return t==="<turn_aborted>"?{kind:"turn_aborted",text:_h("turn_aborted")}:t==="<goal_context>"?{kind:"goal_context",text:_h("goal_context")}:null}function _h(e){return e==="turn_aborted"?"The previous turn was interrupted.":"Goal context updated."}function op(e){return e.name==="diagnostic"&&Re(e.data)?.kind==="goal_context"}const jZ="Steered by user";function OZ(e){return e?.trim().toLowerCase()===jZ.toLowerCase()}function $Z(e,t){if(!t.turnId)return;qZ(e,t.turnId);const n=NZ(t);if(!n)return;const a=LZ(e,t.turnId);if(a){a.refinerActivity=n;return}const i={id:`${t.id}:work-refiner`,role:"activity_group",activities:[],timestamp:t.timestamp,turnId:t.turnId,traceState:"completed",traceStartedAt:t.timestamp,traceCompletedAt:t.timestamp,refinerActivity:n},r=e.findIndex(s=>s.role==="assistant"&&s.turnId===t.turnId);r>=0?e.splice(r,0,i):e.push(i)}function NZ(e){const t=Re(e.data),n=Re(t?.activity);return n?DZ(n,e):HZ(e,t)}function Oie(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 · ${FZ(e.route??"external")} issue routed`;const t=e.result==="applied"?"Applied":"Needs review";return`Refiner · ${e.summary} — ${t}`}function DZ(e,t){const n=wi(e.state,["running","completed","failed"]);if(!n)return null;const a=n==="failed"?"failed":wi(e.result,["no_action","routed","applied","retained"]),i=Zn(e.reason)??t.output??t.error??null;return{state:n,visibility:wi(e.visibility,["always","material_only"])??"material_only",result:n==="running"?null:a,workspaceId:Zn(e.workspaceId),decision:wi(e.decision,["no_action","route","propose"]),route:Zn(e.route),operation:wi(e.operation,["create","update","delete"]),target:Zn(e.target),summary:Zn(e.summary)??cA(n,a),expectedOutcome:Zn(e.expectedOutcome),reason:i,evidenceBasis:UZ(e.evidenceBasis),critiqueStatus:wi(e.critiqueStatus,["not_applicable","pending","passed","rejected","failed"])??(n==="running"?"pending":"not_applicable"),validationStatus:wi(e.validationStatus,["not_applicable","pending","passed","failed"])??(n==="running"?"pending":"not_applicable"),validations:zZ(e.validationReceipts),edits:BZ(e.edits),refs:{trigger:Ii(e.trigger),outcome:Ii(e.outcome),proposal:Ii(e.proposal),applyReceipt:Ii(e.applyReceipt),advanceReceipt:Ii(e.advanceReceipt),inputHarness:Ii(e.inputHarness),outputHarness:Ii(e.outputHarness)}}}function HZ(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",i=Re(t?.outcome),r=Re(t?.proposal),s=i?.routed===!0,c=Zn(t?.workspaceAdvance),m=n?"failed":a?r?c==="advanced"||/\bapplied\b/i.test(e.output??"")?"applied":"retained":s?"routed":"no_action":null;return{state:n?"failed":a?"completed":"running",visibility:"material_only",result:m,workspaceId:null,decision:r?"propose":s?"route":a?"no_action":null,route:Zn(i?.route),operation:null,target:null,summary:cA(n?"failed":a?"completed":"running",m),expectedOutcome:null,reason:e.output??e.error??null,evidenceBasis:null,critiqueStatus:r?"passed":"not_applicable",validationStatus:r?"pending":"not_applicable",validations:[],edits:[],refs:{trigger:Ii(t?.trigger),outcome:Ii(i),proposal:Ii(r),applyReceipt:null,advanceReceipt:null,inputHarness:null,outputHarness:null}}}function LZ(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(i=>i.subagentMessage))return a}return null}function qZ(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 UZ(e){const t=Re(e),n=wi(t?.kind,["single_deterministic","recurrent_independent"]);return!t||!n?null:{kind:n,supportingEvidenceIds:Nx(t.supportingEvidenceIds),counterevidence:Nx(t.counterevidence)}}function zZ(e){return Array.isArray(e)?e.flatMap(t=>{const n=Re(t),a=Zn(n?.id),i=wi(n?.status,["passed","failed","blocked","skipped"]),r=Zn(n?.summary);return a&&i&&r?[{id:a,status:i,summary:r}]:[]}):[]}function BZ(e){return Array.isArray(e)?e.flatMap(t=>{const n=Re(t),a=Zn(n?.id),i=wi(n?.operation,["create","update","delete"]),r=Zn(n?.target),s=Zn(n?.summary);return!a||!i||!r||!s?[]:[{id:a,operation:i,target:r,summary:s,content:typeof n?.content=="string"?n.content:null}]}):[]}function Ii(e){const t=Re(e),n=Zn(t?.id),a=Zn(t?.contentHash);return n&&a?`${n} · ${a.slice(0,12)}`:null}function Nx(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()):[]}function Zn(e){return typeof e=="string"&&e.trim()?e.trim():null}function wi(e,t){return typeof e=="string"&&t.includes(e)?e:null}function cA(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 FZ(e){return e.length>0?`${e[0].toUpperCase()}${e.slice(1)}`:e}const Dx=64*1024,Hx=8*1024;function Lx(e,t){const n=dA(t);if(n.subagentMessage){e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId});return}const a=VZ(e,t.turnId);if(a){a.activities=GZ(a.activities??[],t,n),a.timestamp=t.timestamp;return}Pu(e,t),e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId,traceState:"running",traceStartedAt:t.timestamp})}function Pu(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];a.role!=="activity_group"||a.activities?.some(i=>i.subagentMessage)||a.traceState==="running"&&(a.traceState="settled",a.traceCompletedAt=t.timestamp)}}function VZ(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(i=>i.subagentMessage))return a}return null}function qg(e,t,n){if(!t.turnId)return;const a=e.filter(c=>c.role==="activity_group"&&c.turnId===t.turnId&&!c.activities?.some(m=>m.subagentMessage)),i=a.filter(c=>c.traceState==="running"),r=i.length>0?i:a.length>0?[a[a.length-1]]:[];for(const c of r)c.traceState=n;const s=r.at(-1);s&&(s.traceCompletedAt=t.timestamp,s.timestamp=t.timestamp)}function KZ(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 i=a.activities?.filter(r=>r.controlKind!=="turn_aborted")??[];i.length!==a.activities?.length&&(i.length===0?e.splice(n,1):a.activities=i)}qg(e,t,"interrupted"),!OZ(t.output)&&e.push({id:t.id,role:"status_divider",content:WZ(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"interruption",statusState:"failed",statusTone:"danger"})}function WZ(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 GZ(e,t,n=dA(t)){const a=[...e];return iY(a,t,n)||tY(a,t,n)||nY(a,t,n)||aY(a,t,n)?a:[...a,n]}function JZ(e){return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"}function ZZ(e,t){const n={id:t.id,role:"status_divider",content:YZ(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"compaction",statusState:QZ(t),statusTone:XZ(t)};if(t.name!=="session.compaction.started"){const a=ho(e,i=>i.role==="status_divider"&&i.statusKind==="compaction"&&i.statusState==="running"&&i.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 YZ(e){const t=eY(e);return e.name==="session.compaction.started"?t==="auto"?"Auto compacting context":"Compacting context":e.name==="session.compaction.completed"?t==="auto"?"Auto compacted context":"Compacted context":t==="auto"?"Auto compaction failed":"Context compaction failed"}function QZ(e){return e.name==="session.compaction.started"?"running":e.name==="session.compaction.completed"?"completed":"failed"}function XZ(e){return e.name==="session.compaction.failed"?"danger":e.name==="session.compaction.completed"?"success":"info"}function eY(e){return Re(e.data)?.reason==="auto"?"auto":"manual"}function dA(e){const t=RZ(e),n=e.name==="assistant.reasoning.delta"?"reasoning":fY(e),a=hY(e),i=bY(e),r=vY(e),s=yY(e),c=SY(e),m=PZ(e);return{id:e.id,label:c?c.direction==="received"?"Child message received":"Child message sent":sY(e),content:c?.summary??cY(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:hy(e)??void 0}:{},...n&&e.name==="command.output"?{detail:Ug(e)}:{},...n==="command"?{terminal:CY(e)}:{},...r?{meta:r}:{},...i?{receipt:i}:{},...s?{openSession:s}:{},...c?{subagentMessage:c}:{},state:rY(e),...t?{imagePreview:t}:{},...m.length>0?{artifacts:m}:{}}}function tY(e,t,n){if(t.name==="tool.completed"){const a=qx(e,t);if(!a)return!1;const i=RY(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,...i!==null?{durationMs:i}:{}};const r=Ug(t);return r&&r!==a.content&&(a.detail=rm(a.detail,r)),!0}if(t.name==="command.output"){const a=qx(e,t);if(!a)return!1;const i=Ug(t);return i&&(a.detail=rm(a.detail,i)),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 nY(e,t,n){if(t.name!=="tool.completed"||n.kind==="command")return!1;const a=hy(t),i=ho(e,s=>s.state==="running"&&s.kind!=="command"&&(a?s.callId===a:!!t.action&&s.action===t.action));if(!i)return!1;const r=n.content.trim();return i.id=n.id,i.label=n.label,i.timestamp=n.timestamp,i.state=n.state,r&&r!==i.content.trim()&&(i.content.trim()===i.action?i.content=r:i.detail=rm(i.detail,r)),n.detail&&(i.detail=rm(i.detail,n.detail)),i.meta=n.meta,i.receipt=n.receipt,i.imagePreview=n.imagePreview??i.imagePreview,i.artifacts=n.artifacts,!0}function aY(e,t,n){if(t.name!=="workspace_action_result")return!1;const a=oY(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 iY(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 qx(e,t){const n=hy(t);if(n){const a=ho(e,i=>i.kind==="command"&&i.callId===n);if(a)return a}return ho(e,a=>a.kind==="command")}function oY(e,t){const n=t.action??"",a=uA[n]??{started:"Running workspace action"};return ho(e,i=>i.state==="running"&&i.label===a.started&&i.kind!=="command"&&!i.controlKind)}function rY(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 sY(e){if(e.name==="assistant.reasoning.delta")return ye(Re(e.data),["kind"])==="commentary"?"Update":"Reasoning";if(op(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(Lg(e)&&e.name==="tool.started")return"Reading image";if(Lg(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=TZ(e);if(t)return t;const n=uY(e);if(n)return n;const a=dY(e);return a||(e.name==="skill.selected"?"Selected skill":e.name==="skill.loaded"?"Loaded skill":e.name==="skill.load_failed"?"Skill load failed":e.name==="tool.started"?"Started":e.name==="tool.completed"?"Ran":e.name==="command.output"?"Output":e.name==="workspace_action"||e.name==="workspace_action_result"?lY(e):e.name==="approval.requested"?"Approval requested":e.name==="session.compaction.started"?"Compacting context":e.name==="session.compaction.completed"?"Compacted conversation context":e.name==="session.compaction.failed"?"Context compaction failed":e.name.replace("."," "))}const uA={workspace_status:{started:"Checking workspace",completed:"Checked workspace"},resource_search:{started:"Searching resources",completed:"Searched resources"},resource_read:{started:"Reading resource",completed:"Read resource"},list_files:{started:"Listing files",completed:"Listed files"},read_files:{started:"Reading files",completed:"Read files"},search_files:{started:"Searching files",completed:"Searched files"},preview_write_files:{started:"Previewing files",completed:"Previewed files"},preview_write_file:{started:"Previewing file",completed:"Previewed file"},preview_edit_file:{started:"Previewing edit",completed:"Previewed edit"},preview_delete_file:{started:"Previewing delete",completed:"Previewed delete"},write_files:{started:"Editing files",completed:"Edited files",failed:"File checks failed"},write_file:{started:"Editing file",completed:"Edited file",failed:"File checks failed"},edit_file:{started:"Editing file",completed:"Edited file",failed:"File checks failed"},delete_file:{started:"Deleting file",completed:"Deleted file",failed:"File checks failed"},validate_sandbox_template:{started:"Validating template",completed:"Validated template",failed:"Template validation failed"},build_sandbox_template:{started:"Building template",completed:"Built template",failed:"Template build failed"},run_sandbox_template:{started:"Running sandbox template",pending:"Sandbox template log",completed:"Ran sandbox template",failed:"Sandbox template failed"},git_status:{started:"Checking git status",completed:"Checked git status"},git_fetch:{started:"Fetching git",completed:"Fetched git",failed:"Git fetch failed"},git_commit:{started:"Committing changes",completed:"Committed changes",failed:"Commit failed"},git_push:{started:"Pushing changes",completed:"Pushed changes",failed:"Push failed"},publish_openpond_repo:{started:"Publishing to OpenPond",completed:"Published to OpenPond",failed:"Publish failed"},upload_cloud_source:{started:"Uploading source",completed:"Uploaded source",failed:"Upload failed"},sandbox_create:{started:"Starting sandbox",completed:"Started sandbox",failed:"Sandbox start failed"},sandbox_status:{started:"Checking sandbox",completed:"Checked sandbox",failed:"Sandbox status failed"},sandbox_list_files:{started:"Listing sandbox files",completed:"Listed sandbox files",failed:"Sandbox file list failed"},sandbox_read_file:{started:"Reading sandbox file",completed:"Read sandbox file",failed:"Sandbox file read failed"},sandbox_search_files:{started:"Searching sandbox files",completed:"Searched sandbox files",failed:"Sandbox search failed"},sandbox_run_action:{started:"Running sandbox action",completed:"Ran sandbox action",failed:"Sandbox action failed"},sandbox_upload_file:{started:"Uploading file",completed:"Uploaded file",failed:"Upload failed"},sandbox_write_file:{started:"Writing sandbox file",completed:"Wrote sandbox file",failed:"Write failed"},sandbox_edit_file:{started:"Editing sandbox file",completed:"Edited sandbox file",failed:"Edit failed"},sandbox_delete_file:{started:"Deleting sandbox file",completed:"Deleted sandbox file",failed:"Delete failed"},sandbox_mkdir:{started:"Creating sandbox directory",completed:"Created sandbox directory",failed:"Directory create failed"},sandbox_move_file:{started:"Moving sandbox file",completed:"Moved sandbox file",failed:"Move failed"},sandbox_exec:{started:"Running sandbox command",completed:"Ran sandbox command",failed:"Sandbox command failed"},sandbox_git_status:{started:"Checking sandbox git",completed:"Checked sandbox git"},sandbox_git_diff:{started:"Reading sandbox diff",completed:"Read sandbox diff"},sandbox_git_export_patch:{started:"Exporting sandbox patch",completed:"Exported sandbox patch",failed:"Patch export failed"},sandbox_git_apply_patch_local:{started:"Applying sandbox patch locally",completed:"Applied locally",failed:"Apply locally failed"},sandbox_git_branch:{started:"Switching sandbox branch",completed:"Switched sandbox branch",failed:"Branch failed"},sandbox_git_commit:{started:"Committing sandbox changes",completed:"Committed sandbox changes",failed:"Commit failed"},sandbox_git_pull:{started:"Pulling sandbox changes",completed:"Pulled sandbox changes",failed:"Pull failed"},sandbox_git_push:{started:"Pushing sandbox changes",completed:"Pushed sandbox changes",failed:"Push failed"},sandbox_preserve_source:{started:"Preserving sandbox source",completed:"Preserved sandbox source",failed:"Preserve failed"},sandbox_promote_source:{started:"Promoting sandbox source",completed:"Promoted sandbox source",failed:"Promote failed"},sandbox_logs:{started:"Reading sandbox logs",completed:"Read sandbox logs",failed:"Sandbox logs failed"},sandbox_receipts:{started:"Reading sandbox receipts",completed:"Read sandbox receipts",failed:"Sandbox receipts failed"},sandbox_stop:{started:"Stopping sandbox",completed:"Stopped sandbox",failed:"Sandbox stop failed"},file_change:{started:"Editing files",completed:"Edited files"}};function lY(e){const t=e.action??"",n=uA[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 cY(e,t){if(e.name==="assistant.reasoning.delta")return e.output??"";if(t)return t.path;const n=lA(e.output??"");if(n)return n.text;if(op(e)||e.name==="turn.interrupted")return e.output??e.error??"";const a=mY(e);if(a)return a;const i=pY(e);if(i)return i;const r=EZ(e);if(r)return r;const s=mA(e);if(s)return s;if(e.name==="command.output")return fA(e.output??"");if(e.name==="tool.started"||e.name==="tool.completed"){const c=e.data;if(c&&typeof c=="object"){const m=c.command;if(typeof m=="string"&&m.trim())return m;const u=c.tool;if(typeof u=="string"&&u.trim())return u;const h=c.type;if(typeof h=="string"&&h.trim())return h}}return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"?e.error??e.output??"":e.output??e.action??""}function dY(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 uY(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 mY(e){if(!e.action?.startsWith("openpond_browser_"))return null;const t=Re(Re(e.data)?.result),n=ye(t,["output"]);if(n)return n;const a=Re(Qo(e.output??"")),i=ye(a,["output"]);if(i)return i;const r=Re(e.args),s=ye(r,["url"]);return s||(e.action==="openpond_browser_type"?"Text redacted":e.error??e.output??e.action)}function pY(e){if(e.action!=="openpond_create_improve")return null;const t=Re(Re(e.data)?.result),n=ye(t,["nextStep"]);if(n)return n;const a=Re(Qo(e.output??"")),i=ye(a,["output"]);if(i)return i;const r=Re(e.args),s=ye(r,["reason"]);if(s)return s;const c=ye(r,["objective"]);return c||(e.error??null)}function fY(e){if(e.name==="command.output")return"command";if(e.name!=="tool.started"&&e.name!=="tool.completed")return;const t=Re(e.data),n=ye(t,["type"]),a=ye(t,["tool","toolName","tool_name","name","functionName","function_name"]);if(e.action==="commandExecution"||n==="commandExecution"||mA(e)||a&&/(^|[._-])exec_command$/i.test(a))return"command"}function hY(e){if(e.name==="turn.interrupted")return"turn_aborted";if(op(e))return"goal_context"}function mA(e){const t=Re(e.data),n=ye(t,["type"]),a=ye(t,["tool","toolName","tool_name","name","functionName","function_name"]),i=Re(t?.result),r=Re(Qo(e.output??"")),s=Re(r?.data),c=ye(t,["command","cmd"])??ye(Re(t?.input),["command","cmd"])??ye(Re(t?.arguments),["command","cmd"])??ye(Re(t?.args),["command","cmd"])??gY(ye(t,["arguments","args","input"]))??ye(Re(e.args),["command","cmd"])??ye(i,["command","cmd"])??ye(s,["command","cmd"]);return c||e.name==="tool.started"&&(e.action==="commandExecution"||n==="commandExecution"||/(^|[._-])exec_command$/i.test(a??""))&&e.output?.trim()||null}function gY(e){if(!e)return null;const t=Qo(e),n=Re(t);return ye(n,["command","cmd"])}function hy(e){const t=Re(e.data);return ye(t,["callId","call_id","toolCallId","tool_call_id","id","itemId","item_id"])}function vY(e){const t=Re(e.data);if(!t)return null;const n=[],a=Re(t.workspaceToolTiming),i=typeof a?.durationMs=="number"?a.durationMs:null;i!==null&&n.push(IY(i));const r=Re(t.workspaceExecutionTarget),s=ye(r,["target"]);if(s==="sandbox"){const u=r?.hybrid===!0,h=ye(r,["sandboxId","workspaceId"]);n.push(`${u?"Hybrid ":""}sandbox${h?` ${Ux(h)}`:""}`)}else s==="local"&&n.push("local workspace");const c=Re(t.sourcePreservation);if(c?.attempted===!0)if(c.ok!==!0)n.push("checkpoint failed");else if(c.preserved===!0){const u=ye(c,["preservedSha"]);n.push(u?`checkpoint ${_Y(u)}`:"checkpoint saved")}else n.push("checkpoint clean");const m=pA(t);return m&&(n.push(`receipt ${Ux(m.id)}`),n.push(`${wY(m.totalUsd)} ${m.status}`)),n.length>0?n.join(" · "):null}function bY(e){const t=pA(Re(e.data));return t?{id:t.id,status:t.status,totalUsd:t.totalUsd}:void 0}function yY(e){if(!e.name.startsWith("subagent."))return;const t=Re(e.data),n=Re(t?.run),a=ye(t,["childSessionId"])??ye(n,["childSessionId"]);if(!a)return;const i=ye(n,["roleId"])??ye(t,["roleId"]),r=ye(n,["status"])??ye(t,["status"]);return{sessionId:a,label:"Open conversation",...i?{roleId:i}:{},...r?{status:r}:{}}}function SY(e){if(e.name!=="subagent.message")return;const t=Re(e.data),n=Re(t?.message);if(!n)return;const a=ye(n,["id"]),i=ye(n,["kind"]),r=ye(n,["fromRunId"]),s=ye(n,["body"]);if(!a||!i||!r||!s)return;const c=Re(t?.delivery??n.delivery),m=Re(t?.modelRef),u=ye(m,["providerId"]),h=ye(m,["modelId"]),S=ye(c,["deliveredParentSessionId"])===e.sessionId&&!r.startsWith("parent:")?"received":"sent",k=Array.isArray(n.refs)?n.refs.flatMap(C=>{const A=Re(C),M=ye(A,["kind"]),R=ye(A,["id"]),$=ye(A,["label"]);return M&&R&&$?[{kind:M,id:R,label:$}]:[]}):[];return{direction:S,summary:xY(s),body:s,messageId:a,kind:i,fromRunId:r,toRunId:ye(n,["toRunId"]),toRole:ye(n,["toRole"]),childSessionId:ye(t,["childSessionId"]),roleId:ye(t,["roleId"]),modelRef:u&&h?{providerId:u,modelId:h}:null,deliveryStatus:ye(c,["status"]),wakeReason:ye(c,["wakeParentReason"]),createdAt:ye(n,["createdAt"]),refs:k}}function xY(e){const t=e.replace(/\s+/g," ").trim();if(!t)return"No message body";const n=/^(.*?[.!?])(?:\s|$)/.exec(t)?.[1]??t;return kY(n,96)}function kY(e,t){if(e.length<=t)return e;const n=e.slice(0,t-1),a=n.lastIndexOf(" "),i=a>=Math.floor(t*.55)?a:t-1;return`${n.slice(0,i).trimEnd()}...`}function pA(e){const t=Re(e?.sandbox),n=Array.isArray(t?.receipts)?t.receipts:[];for(let a=n.length-1;a>=0;a-=1){const i=Re(n[a]),r=ye(i,["id"]),s=ye(i,["status"]),c=ye(i,["totalUsd","retailTotalUsd"]);if(r&&s&&c)return{id:r,status:s,totalUsd:c}}return null}function IY(e){return e<1e3?`${Math.max(0,Math.round(e))} ms`:e<1e4?`${(e/1e3).toFixed(1)} s`:`${Math.round(e/1e3)} s`}function wY(e){const t=e.trim();return t.startsWith("$")?t:`$${t}`}function _Y(e){return e.length>12?e.slice(0,12):e}function Ux(e){const t=e.trim();return t.length<=14?t:`${t.slice(0,6)}...${t.slice(-4)}`}function fA(e){let t=e.replace(/\r\n/g,`
190
+ `).trim();if(!t)return"";const n=PY(t);if(n!==null)return Hs(n);const a=`
191
+ Output:
192
+ `,i=t.indexOf(a);return i>=0&&AY(t.slice(0,i))&&(t=t.slice(i+a.length).trim()),t=t.replace(/^Total output lines: \d+\n\n/,""),Hs(t.trim())}function Ug(e){const t=fA(e.output??"");if(t)return t;const n=Re(Re(e.data)?.result);return n?Hs(hA(n)):""}function CY(e){const t=Re(e.data),n=Re(t?.result),a=Re(Qo(e.output??"")),i=Re(a?.data),r=Re(t?.workspaceToolTiming),s=[n?.exitCode,i?.exitCode,t?.exitCode].find(m=>typeof m=="number"),c=r?.durationMs;return{...typeof s=="number"?{exitCode:s}:{},...typeof c=="number"?{durationMs:c}:{}}}function RY(e,t){const n=Date.parse(t)-Date.parse(e);return Number.isFinite(n)&&n>0?n:null}function PY(e){const t=Re(Qo(e)),n=typeof t?.action=="string"?t.action:"";if(!t||typeof t.ok!="boolean"||!n||typeof t.output!="string")return null;const a=Re(t.data);return a?hA(a,ye(t,["output"])):typeof t.output=="string"?t.output.trim():""}function hA(e,t=null){const n=ye(e,["stdout"])?.replace(/\r\n/g,`
193
+ `).trimEnd()??"",a=ye(e,["stderr"])?.replace(/\r\n/g,`
194
+ `).trimEnd()??"",i=[n,a].filter(Boolean);return i.length>0?i.join(`
195
+ `):t?.replace(/\r\n/g,`
196
+ `).trim()??""}function AY(e){return/^(Chunk ID|Exit code):/m.test(e)&&/Wall time:/m.test(e)}function rm(e,t){const n=e??"";if(!n)return Hs(t);if(n===t||n.includes(t))return n;if(t.includes(n))return Hs(t);const a=n.endsWith(`
197
+ `)||t.startsWith(`
198
+ `)?"":`
199
+ `;return Hs(`${n}${a}${t}`)}function Hs(e){if(e.length<=Dx)return e;const t=`
200
+
201
+ … output omitted from live view; full output remains in task history …
202
+
203
+ `,n=Math.max(0,Dx-Hx-t.length);return`${e.slice(0,Hx)}${t}${e.slice(-n)}`}const TY=/\bopenpond\s+opchat\b/i,EY=/\b(?:50[0-9]|52[0-9]|53[0-9])\b|bad\s+gateway|gateway\s+timeout|service\s+unavailable/i;function gA(e){const t=e?.trim()||"Turn failed";return TY.test(t)&&EY.test(t)?"Server connection lost. Retry your message.":t}function MY(e,t){if((iu(t,"code")??iu(t,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const a=t&&typeof t=="object"?t.error:null;if(a&&typeof a=="object"&&(iu(a,"code")??iu(a,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const i=e??"";return/\bopchat_quota_exceeded\b/i.test(i)||/OpChat token allowance is exhausted/i.test(i)?"opchat_quota_exceeded":null}function iu(e,t){if(!e||typeof e!="object")return null;const a=e[t];return typeof a=="string"&&a.trim()?a.trim():null}function jY(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 i=OY(a.activities??[]);if(i.length===0){a.deliverables=void 0;continue}const r=t.get(a.turnId)??"",s=r?$Y(i,r):[];if(s.length>0){a.deliverables=s;continue}a.deliverables=n.has(a.turnId)?[i[i.length-1]]:void 0}}function OY(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 i of a.artifacts??[])t.has(i.path)||(n.delete(i.path),n.set(i.path,i));return[...n.values()]}function $Y(e,t){const n=vA(t);return e.filter(a=>NY(a).some(i=>t.includes(i)||n.includes(i)))}function NY(e){const t=new Set;for(const n of[e.path,e.title,DY(e.path)]){const a=n.trim();a&&(t.add(a),t.add(vA(a)))}return[...t]}function DY(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).at(-1)??e}function vA(e){try{return decodeURIComponent(e)}catch{return e}}const bA=8;function HY(e){if(e.name!=="tool.completed"||e.status==="failed")return[];if(e.action!=="web_search"&&e.action!=="web_fetch")return[];const t=Bg(e.data),n=e.output?Bg(Qo(e.output)):null;return LY(t??n)}function zg(e,t){if(t.length===0)return e;const n=[],a=new Set;for(const i of[...e??[],...t]){const r=yA(i.url);if(!(!r||a.has(r))&&(a.add(r),n.push(i),n.length>=bA))break}return n.length>0?n:void 0}function Bg(e,t=0){if(t>5)return null;const n=Re(e);if(!n)return null;const a=Array.isArray(n.results)?n.results:Array.isArray(n.items)?n.items:ye(n,["url"])?[n]:null;if(a)return{provider:ye(n,["provider"]),results:a};for(const i of["result","data","output"]){const r=Bg(n[i],t+1);if(r)return r}return null}function LY(e){if(!e)return[];const t=[],n=new Set;for(let a=0;a<e.results.length;a+=1){const i=qY(e.results[a],a,e.provider);if(!i)continue;const r=yA(i.url);if(!(!r||n.has(r))&&(n.add(r),t.push(i),t.length>=bA))break}return t}function qY(e,t,n){const a=Re(e);if(!a)return null;const i=ye(a,["url","href"]);if(!i||!UY(i))return null;const r=ye(a,["title"])??zx(i)??`Source ${t+1}`;return{id:ye(a,["id"])??`source_${t+1}`,title:r,url:i,sourceName:ye(a,["sourceName","source_name","source"])??zx(i),snippet:ye(a,["snippet","description"]),provider:n,faviconUrl:zY(ye(a,["faviconUrl","favicon_url","iconUrl","icon_url"]))??BY(i),publishedAt:ye(a,["publishedAt","published_at"]),updatedAt:ye(a,["updatedAt","updated_at"])}}function UY(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function yA(e){try{const t=new URL(e);return t.hash="",t.toString()}catch{return null}}function zY(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 BY(e){try{return new URL("/favicon.ico",e).toString()}catch{return null}}function zx(e){try{return new URL(e).hostname.replace(/^www\./i,"")}catch{return null}}const Bx=new WeakMap;function rp(e){const t=Bx.get(e);if(t)return t;const n=FY(e);return Bx.set(e,n),n}function FY(e){const t=[],n=new Set,a=new Map;for(const i of e){if(i.name==="task.input"){const r=SR.safeParse(Re(i.data)?.input);r.success&&r.data.senderKind==="user"&&r.data.kind==="steer"&&!n.has(r.data.id)&&(n.add(r.data.id),t.push({id:`task-input:${r.data.id}`,role:"user",content:r.data.body,timestamp:i.timestamp,turnId:r.data.turnId??void 0}));continue}if(i.name==="turn.started"){Pu(t,i),VY(t,i);const r=JY(i.args);if(r){const s=lA(r);if(s){Lx(t,{...i,name:s.kind==="turn_aborted"?"turn.interrupted":"diagnostic",output:s.text,data:{...Re(i.data)??{},kind:s.kind}});continue}t.push({id:i.id,role:"user",content:r,attachments:ZY(i.args),timestamp:i.timestamp,turnId:i.turnId});const c=Vx(i.args);c&&t.push({id:`${i.id}:create-improve`,role:"assistant",timestamp:i.timestamp,turnId:i.turnId,createImproveRun:c})}continue}if(i.name==="create_improve.updated"){const r=Vx(i.data);if(!r)continue;const s=ho(t,c=>c.turnId===i.turnId&&!!c.createImproveRun);s?(s.createImproveRun=r,s.timestamp=i.timestamp):t.push({id:`${i.id}:create-improve`,role:"assistant",timestamp:i.timestamp,turnId:i.turnId,createImproveRun:r});continue}if(i.name==="assistant.delta"){const r=i.output??"";if(!r)continue;Pu(t,i);const s=t[t.length-1];if(s?.role==="assistant"&&s.turnId===i.turnId&&!s.createImproveRun)s.content=`${s.content??""}${r}`,s.timestamp=i.timestamp,s.sources=zg(s.sources,Fx(a,i.turnId)??[]);else{const c=Fx(a,i.turnId);t.push({id:i.id,role:"assistant",content:r,timestamp:i.timestamp,turnId:i.turnId,...c?.length?{sources:c}:{}})}continue}if(i.name==="assistant.reasoning.delta"){const r=i.output??"";if(!r)continue;Pu(t,i);const s=t[t.length-1];s?.role==="assistant"&&s.turnId===i.turnId&&s.reasoningContent!==void 0&&!s.createImproveRun?(s.reasoningContent=`${s.reasoningContent}${r}`,s.timestamp=i.timestamp):s?.role==="assistant"&&s.turnId===i.turnId&&!s.reasoningContent&&!s.createImproveRun?(s.reasoningContent=r,s.timestamp=i.timestamp):t.push({id:i.id,role:"assistant",reasoningContent:r,timestamp:i.timestamp,turnId:i.turnId});continue}if(i.name==="user_question.asked"){const r=Re(i.data),s=i$.safeParse(r?.question);if(!s.success)continue;t.push({id:i.id,role:"assistant",timestamp:i.timestamp,turnId:i.turnId,userQuestion:s.data});continue}if(i.name==="user_question.answered"||i.name==="user_question.dismissed"){const r=Re(i.data),s=o$.safeParse(r?.resolution);if(!s.success)continue;const c=ho(t,m=>m.userQuestion?.id===s.data.questionId);if(!c?.userQuestion||c.userQuestion.status!=="pending")continue;c.userQuestion={...c.userQuestion,status:s.data.action==="answer"?"answered":"dismissed",answer:s.data.action==="answer"?{optionId:s.data.optionId,text:s.data.text}:null,answeredAt:i.timestamp},c.timestamp=i.timestamp;continue}if(i.name==="turn.completed"){qg(t,i,"completed");continue}if(i.name==="turn.failed"){qg(t,i,"failed");const r=i.error??"Turn failed",s=MY(r,i.data);t.push({id:i.id,role:"error",content:gA(r),...s?{errorKind:s}:{},timestamp:i.timestamp,turnId:i.turnId});continue}if(i.name==="turn.interrupted"){KZ(t,i);continue}if(JZ(i)){ZZ(t,i);continue}if(i.name.startsWith("harness.refiner.")){$Z(t,i);continue}if(i.name==="tool.started"||i.name==="tool.completed"||i.name==="skill.selected"||i.name==="skill.loaded"||i.name==="skill.load_failed"||i.name==="command.output"||i.name==="workspace_action"||i.name==="workspace_action_result"||i.name==="approval.requested"||i.name.startsWith("subagent.")||op(i)){if(WY(i))continue;const r=yZ(i);if(r){bZ(t,i,r);continue}const s=HY(i);s.length>0&&KY(t,a,i.turnId,s),Lx(t,i)}if(i.name==="workspace.diff"){const r=GY(i.data);if(!r||r.filesChanged===0)continue;const s=ho(t,c=>c.role==="assistant"&&c.turnId===i.turnId);s&&(s.changeSummary=r,s.timestamp=i.timestamp)}}return jY(t),t}function VY(e,t){if(Re(t.args)?.interactionKind!=="steer")return;const n=e.at(-1);n?.role==="status_divider"&&n.statusKind==="interruption"&&n.content==="Stopped by user"&&e.pop()}function KY(e,t,n,a){if(!n)return;const i=e[e.length-1];if(i?.role!=="assistant"||i.turnId!==n){t.set(n,zg(t.get(n),a));return}i.sources=zg(i.sources,a)}function Fx(e,t){if(!t)return;const n=e.get(t);return n&&e.delete(t),n}function WY(e){if(e.name!=="approval.requested")return!1;if(e.action==="create_plan")return!0;const t=Re(e.data),n=Re(t?.approval);return t?.kind==="create_plan"||n?.kind==="create_plan"}function GY(e){const t=bN.safeParse(e);return t.success?t.data:null}function JY(e){if(!e||typeof e!="object"||!("prompt"in e))return"";const t=e.prompt;return typeof t=="string"?t:""}function ZY(e){if(!e||typeof e!="object"||!("attachments"in e))return;const t=XL.array().safeParse(e.attachments);return t.success&&t.data.length>0?t.data:void 0}function Vx(e){const t=Re(e);if(!t)return null;const n=Gc.safeParse(t.createImproveRun);return n.success?n.data:null}function $ie(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 i=Math.floor(a/60);return i<48?`${i}h`:`${Math.floor(i/24)}d`}function Nie(e){const t=SA(e);return t?t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):""}function Die(e){const t=SA(e);return t?t.toLocaleString():""}function SA(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function YY(e){const{chatMessages:t,runtimeIndexes:n,selectedSessionId:a}=e,[i,r]=y.useState({}),s=y.useCallback(m=>{r(u=>({...u,[m.sessionId]:m}))},[]);y.useEffect(()=>{r(m=>{let u=m;for(const[h,g]of Object.entries(m)){const S=rp(bd(n,h));iA(S,g)&&(u===m&&(u={...m}),delete u[h])}return u})},[n]);const c=y.useMemo(()=>aA(t,a?i[a]:null),[t,i,a]);return{pendingChatUserMessages:i,recordPendingChatUserMessage:s,visibleChatMessages:c}}function QY({connection:e,selectedSession:t,setBootstrap:n,setError:a,setOpenPondCommandAccessMode:i,setSessions:r}){return{changeOpenPondCommandAccessMode:y.useCallback((c,m=t)=>{if(!e){a("Connect to OpenPond before saving preferences.");return}const u=m?.provider==="codex"?null:m;Q.savePreferences(e,{openPondCommandAccessMode:c}).then(h=>{i(h.preferences.openPondCommandAccessMode),n(g=>g&&{...g,preferences:h.preferences})}).catch(h=>{a(h instanceof Error?h.message:String(h))}),u&&Q.patchSession(e,u.id,{openPondCommandAccessMode:c}).then(h=>{r(g=>g.map(S=>S.id===h.id?h:S))}).catch(h=>{a(h instanceof Error?h.message:String(h))})},[e,t,n,a,i,r])}}function XY({localProjects:e,cloudProjects:t,sessions:n,runtimeIndexes:a,appPreferences:i,selectedSessionId:r,selectedProjectId:s,archivedChatsOpen:c,projectsExpanded:m,chatRowsVisibleCount:u,sidebarFileBookmarks:h=[]}){const g=y.useMemo(()=>e.filter(le=>!le.hiddenFromDefaultSidebar),[e]),S=y.useMemo(()=>n.filter(le=>!le.archived&&Kx(le)),[n]),k=y.useMemo(()=>S.filter(le=>le.pinned),[S]),C=y.useMemo(()=>S.filter(le=>!!le.savedForLater),[S]),A=y.useMemo(()=>n.filter(le=>le.archived&&Kx(le)),[n]),M=y.useMemo(()=>new Set(e.map(le=>le.id)),[e]),R=y.useMemo(()=>new Set(t.map(le=>le.id)),[t]),$=y.useMemo(()=>tP(e),[e]),O=y.useMemo(()=>{const le={};for(const xe of[...S,...A]){const Ue=QS(xe,M,$,R);Ue&&(le[xe.id]=Ue)}return le},[S,A,R,M,$]),j=y.useMemo(()=>S.filter(le=>!le.pinned&&!le.savedForLater&&!le.appId&&!O[le.id]),[S,O]),I=y.useMemo(()=>A.filter(le=>!le.appId&&!QS(le,M,$,R)),[A,R,M,$]),P=y.useMemo(()=>{const le={};for(const xe of S){if(xe.pinned||xe.savedForLater)continue;const Ue=O[xe.id];if(!Ue)continue;const Ze=le[Ue];Ze?Ze.push(xe):le[Ue]=[xe]}return le},[S,O]),E=y.useMemo(()=>{const le={};for(const xe of n){if(xe.archived||!xA(xe))continue;const Ue=le[xe.parentSessionId];Ue?Ue.push(xe):le[xe.parentSessionId]=[xe]}for(const xe of Object.values(le))xe.sort((Ue,Ze)=>Date.parse(Ze.updatedAt)-Date.parse(Ue.updatedAt));return le},[n]),L=y.useMemo(()=>g.map((le,xe)=>{const Ue=wt("local",le.id),Ze=iJ(le,t);return{id:Ue,kind:"local",project:le,pinned:!!i[Ue]?.pinned,order:i[Ue]?.order??xe,cloudLinkTrusted:!Ze,cloudLinkWarning:Ze}}).sort(Ch),[i,t,g]),z=y.useMemo(()=>t.map((le,xe)=>{const Ue=wt("cloud",le.id);return{id:Ue,kind:"cloud",project:le,pinned:!!i[Ue]?.pinned,order:i[Ue]?.order??xe,cloudLinkTrusted:!0,cloudLinkWarning:null}}).sort(Ch),[i,t]),H=y.useMemo(()=>new Set(g.map(le=>za(le,t)?.id??null).filter(le=>!!le)),[t,g]),J=y.useMemo(()=>z.filter(le=>!H.has(le.project.id)),[z,H]),X=y.useMemo(()=>[...L,...J].sort(Ch),[J,L]),de=y.useMemo(()=>X.filter(le=>le.pinned),[X]),je=y.useMemo(()=>h.filter(le=>le.status==="pinned"),[h]),we=y.useMemo(()=>h.filter(le=>le.status==="saved_for_later"),[h]),te=X,Me=y.useMemo(()=>eQ(te,m,s),[te,m,s]),Se=y.useMemo(()=>[...de.map(le=>({type:"project",key:xr({type:"project",id:le.id}),id:le.id,item:le,order:le.order})),...k.map(le=>({type:"session",key:xr({type:"session",id:le.id}),id:le.id,session:le,order:le.order})),...je.map((le,xe)=>({type:"file",key:xr({type:"file",id:le.id}),id:le.id,file:le,order:le.order??de.length+k.length+xe}))].sort((le,xe)=>{if(le.order!==xe.order)return le.order-xe.order;if(le.type!==xe.type){const it={project:0,session:1,file:2};return it[le.type]-it[xe.type]}const Ue=le.type==="project"?le.item.project.name:le.type==="session"?le.session.title:le.file.path,Ze=xe.type==="project"?xe.item.project.name:xe.type==="session"?xe.session.title:xe.file.path;return Ue.localeCompare(Ze)}),[je,de,k]),oe=y.useMemo(()=>c?[...j,...I]:j,[c,I,j]),be=y.useMemo(()=>oe.slice(0,Math.max(Hn,u)),[oe,u]),re=y.useMemo(()=>bd(a,r),[a,r]),ue=y.useMemo(()=>rp(re),[re]),ke=DP(a,r),Le=HP(a,r),Ie=F7(a,r);return{activeSessions:S,pinnedSessions:k,savedForLaterSessions:C,pinnedFiles:je,savedForLaterFiles:we,chatSessions:j,archivedSessions:A,pinnedProjects:de,pinnedItems:Se,projectRows:te,localProjectRows:L,visibleProjectRows:Me,cloudProjectRows:J,projectSessionRowsByProjectId:P,childSessionRowsByParentId:E,sidebarProjectIdBySessionId:O,chatRows:oe,visibleChatRows:be,sessionEvents:re,chatMessages:ue,contextUsage:ke,goalRuntime:Le,subagentRuntime:Ie}}function Kx(e){return xA(e)?!1:e.hiddenFromDefaultSidebar?e.metadata?.benchmarkRuntime==="desktop_local_work":!0}function xA(e){return!!(e.parentSessionId&&e.subagentRunId)}function Ch(e,t){return e.pinned!==t.pinned?e.pinned?-1:1:e.order!==t.order?e.order-t.order:e.project.name.localeCompare(t.project.name)}function eQ(e,t,n){if(t||e.length<=Iu)return e;const a=e.slice(0,Iu);if(!n||a.some(r=>r.id===n))return a;const i=e.find(r=>r.id===n);return i?[...a.slice(0,Iu-1),i]:a}function tQ(e){return e.name==="turn.completed"||e.name==="turn.failed"||e.name==="turn.interrupted"}function kA(e){let t=-1,n=null;for(let a=e.length-1;a>=0;a-=1){const i=e[a];if(i?.name==="turn.started"){t=a,n=i.turnId??null;break}}if(t===-1)return"none";for(let a=e.length-1;a>t;a-=1){const i=e[a];if(!(!i||!tQ(i))&&!(n&&i.turnId&&i.turnId!==n))return i.name==="turn.completed"?"completed":"blocked"}return"pending"}function Wx(e,t){if(e.systemKind)return!1;const n=bd(t,e.id);if(n.length===0)return!1;const a=kA(n);return a==="pending"||a==="none"&&IA(n)==="pending"}function Gx(e,t){if(e.systemKind||e.status!=="active")return!1;const n=bd(t,e.id);if(n.length===0)return!0;const a=kA(n);return a==="pending"||a==="none"&&IA(n)!=="terminal"}function IA(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 nQ({goalRuntime:e,goalRuntimeBySessionId:t,runtimeIndexes:n,selectedSession:a,selectedSessionId:i,sidebarSessions:r,subagentRuntimeBySessionId:s}){const c=y.useMemo(()=>new Map(r.map(S=>[S.id,S])),[r]),m=y.useMemo(()=>{const S=new Set;for(const[k,C]of t??[]){const A=c.get(k);C.tone==="active"&&!A?.systemKind&&S.add(k)}for(const k of n.activeGoalSessionIds)c.get(k)?.systemKind||S.add(k);return i&&!a?.systemKind&&e?.tone==="active"&&S.add(i),S},[e,t,n,a,i,c]),u=y.useMemo(()=>{const S=new Set(m);for(const[k,C]of s??[]){const A=c.get(k);C.activeCount>0&&!A?.systemKind&&S.add(k)}for(const k of n.activeSubagentSessionIds)c.get(k)?.systemKind||S.add(k);for(const k of r)k.systemKind||Wx(k,n)&&S.add(k.id);return a&&Wx(a,n)&&S.add(a.id),S},[m,n,a,r,c,s]),h=y.useMemo(()=>{const S=new Set(u);for(const k of r)Gx(k,n)&&S.add(k.id);return a&&Gx(a,n)&&S.add(a.id),S},[u,n,a,r]),g=!!(a&&!a.systemKind&&u.has(a.id));return{runningSessionIds:h,selectedSessionRunning:g}}const aQ=1e3;function iQ(e){const[t,n]=y.useState(()=>new Date().toISOString());return y.useEffect(()=>{if(!e)return;const a=()=>n(new Date().toISOString());a();const i=window.setInterval(a,aQ);return()=>window.clearInterval(i)},[e]),t}function oQ(e){const{codexHistoryEvents:t,codexHistorySessions:n,connection:a,expandedProjectIds:i,goalRuntime:r,locallyActiveCodexHistorySessionIds:s,pinnedSessions:c,savedForLaterSessions:m,projectSessionRowsByProjectId:u,rightChatHistoryEvents:h,runtimeIndexes:g,selectedSession:S,selectedSessionId:k,serverId:C,setCodexHistorySessions:A,sidebarSessions:M,subagentRuntime:R,visibleChatRows:$,visibleProjectRows:O}=e,[j,I]=y.useState({});y.useEffect(()=>{I({})},[C]);const P=y.useMemo(()=>{const oe=[],be=new Set,re=ke=>{!ke||ke.id===k||!Vt(ke.id)||be.has(ke.id)||(be.add(ke.id),oe.push(ke.id))};for(const ke of n)(ke.status==="active"||s.has(ke.id))&&re(ke);const ue=oe.length;for(const ke of O)for(const Le of(u[ke.id]??[]).slice(0,2))re(Le);for(const ke of i)for(const Le of(u[ke]??[]).slice(0,Iu))re(Le);for(const ke of c)re(ke);for(const ke of m)re(ke);for(const ke of $)re(ke);return[...oe.slice(0,ue),...oe.slice(ue,ue+8)].join(`
204
+ `)},[n,i,s,c,m,u,k,$,O]),E=y.useCallback(oe=>{I(be=>be[oe.session.id]===oe.events?be:{...be,[oe.session.id]:oe.events}),A(be=>ip(be,oe.session))},[A]),L=y.useMemo(()=>{if(!P)return"";const oe=new Set(P.split(`
205
+ `).filter(Boolean));return M.filter(be=>oe.has(be.id)&&be.status==="active").map(be=>be.id).join(`
206
+ `)},[P,M]),z=y.useMemo(()=>P?P.split(`
207
+ `).filter(oe=>s.has(oe)).join(`
208
+ `):"",[P,s]);y.useEffect(()=>{!S||!k||!Vt(k)||t.length===0||E({session:S,events:t})},[E,t,S,k]),y.useEffect(()=>{if(!a||!P)return;const oe=a,be=P.split(`
209
+ `).filter(Boolean),re=new Set(L.split(`
210
+ `).filter(Boolean)),ue=new Set(z.split(`
211
+ `).filter(Boolean)),ke=be.map(Le=>fy({connection:oe,locallyActive:ue.has(Le),onPayload:Ie=>E(py(Ie,ue.has(Le))),reportedActive:re.has(Le),sessionId:Le,surface:"sidebar"}));return()=>ke.forEach(Le=>Le())},[E,L,z,P,a]);const H=y.useMemo(()=>new Map(M.map(oe=>[oe.id,oe])),[M]),J=y.useMemo(()=>{const oe=new Map(g.latestGoalRuntimeBySessionId);for(const be of M){const re=be.status==="active"?yh(be.metadata):null;re&&oe.set(be.id,re)}for(const be of[j,h])for(const[re,ue]of Object.entries(be)){const ke=H.get(re),Le=ke?.status==="active"?yh(ke.metadata):null,Ie=Eg(ue)??cy(ue)??(ke?.status==="active"?om(ue)??Le:null);Ie?oe.set(re,Ie):oe.delete(re)}if(k)if(r)oe.set(k,r);else if(S?.status==="active"&&t.length>0){const be=Eg(t)??om(t)??yh(S.metadata);be?oe.set(k,be):oe.delete(k)}else(!Vt(k)||t.length>0)&&oe.delete(k);return oe},[t.length,j,r,h,g.latestGoalRuntimeBySessionId,S?.status,S?.metadata,k,H,M]),X=y.useMemo(()=>[...J.values()].some(oe=>oe.tone==="active"&&!!oe.observedAt),[J]),de=iQ(X),je=y.useMemo(()=>X?new Map([...J].map(([oe,be])=>[oe,S7(be,de)??be])):J,[J,de,X]),we=k?je.get(k)??r:r,te=y.useMemo(()=>{const oe=new Map(g.latestSubagentRuntimeBySessionId);return k&&(R?oe.set(k,R):oe.delete(k)),oe},[g.latestSubagentRuntimeBySessionId,k,R]),{runningSessionIds:Me,selectedSessionRunning:Se}=nQ({goalRuntime:we,goalRuntimeBySessionId:je,runtimeIndexes:g,selectedSession:S,selectedSessionId:k,sidebarSessions:M,subagentRuntimeBySessionId:te});return{goalRuntime:we,runningSessionIds:Me,selectedSessionRunning:Se,sidebarGoalRuntimeBySessionId:je,sidebarSubagentRuntimeBySessionId:te}}function rQ({searchOpen:e,sectionMenuOpen:t,setSectionMenuOpen:n,setSearchOpen:a,setQuery:i}){y.useEffect(()=>{const r=s=>{if((s.metaKey||s.ctrlKey)&&s.key.toLowerCase()==="k"){s.preventDefault(),n(null),a(c=>!c);return}if(s.key==="Escape"&&e){s.preventDefault(),a(!1),i(""),n(null);return}s.key==="Escape"&&t&&(s.preventDefault(),n(null))};return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[e,t,i,a,n])}function sQ({afterSequence:e,appendEvents:t,connection:n,setApprovals:a,setSessions:i,setError:r,onDisconnected:s}){y.useEffect(()=>{if(!n?.token||e===null)return;const c=n;let m=null,u=[],h=null,g=null,S=!1;const k=new Map;let C=0;const A=16;function M(){m!==null&&(window.clearTimeout(m),m=null)}function R(){r(H=>H==="Event stream disconnected"?null:H)}function $(){h=null;const H=u;if(u=[],H.length===0)return;C=Date.now(),t(H);const J=lQ(H);J.length>0&&i(X=>J.reduce(tc,X)),a(X=>{let de=X;for(const je of H)if(je.name==="approval.requested"&&je.data&&(de=[je.data,...de]),je.name==="approval.resolved"&&je.data&&typeof je.data=="object"){const we=je.data;we.approvalId&&(de=de.filter(te=>te.id!==we.approvalId))}return de})}function O(){const H=Date.now()-C;if(H>=A){h!==null&&(window.clearTimeout(h),h=null),$();return}h===null&&(h=window.setTimeout($,A-H))}function j(H){I(H),u.push(H),O()}function I(H){if(!(!H.sessionId||!H.name.startsWith("harness.refiner."))){if(H.name==="harness.refiner.completed"||H.name==="harness.refiner.failed"){k.delete(H.sessionId);return}(H.name==="harness.refiner.queued"||H.name==="harness.refiner.started")&&(k.set(H.sessionId,typeof H.sequence=="number"?H.sequence:0),P())}}function P(){g!==null||k.size===0||(g=window.setTimeout(()=>{g=null,E()},1e3))}async function E(){if(!(S||k.size===0)){S=!0;try{await Promise.all([...k].map(async([H,J])=>{const X=await Q.runtimeEventsPage(c,{sessionId:H,afterSequence:J,limit:100});for(const de of X.events){const je=de.event;k.set(H,Math.max(k.get(H)??0,de.sequence)),j(je)}}))}catch{}finally{S=!1,P()}}}function L(){h!==null&&(window.clearTimeout(h),h=null),$()}document.addEventListener("visibilitychange",L);const z=EK(n,H=>{M(),R(),j(H)},()=>{M(),m=window.setTimeout(()=>{z.isOpen()||(r("Event stream disconnected"),s?.())},2e3)},()=>{M(),R(),window.dispatchEvent(new Event("openpond-runtime-connected"))},{afterSequence:e});return()=>{M(),h!==null&&window.clearTimeout(h),g!==null&&window.clearTimeout(g),h=null,g=null,u=[],document.removeEventListener("visibilitychange",L),z.close()}},[e,t,n,s,a,r,i])}function lQ(e){const t=new Map;for(const n of e){const a=n.data;if(!a||typeof a!="object"||Array.isArray(a))continue;const i=n.name==="session.started"||n.name==="session.title.updated"?"session":n.name==="subagent.started"||n.name==="subagent.failed"?"childSession":null;if(!i)continue;const r=xc.safeParse(a[i]);r.success&&t.set(r.data.id,r.data)}return[...t.values()]}function Rh(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function cQ(e){return typeof e=="string"&&e.trim()?e.trim():null}function dQ(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.name!=="create_improve.updated")continue;const a=Rh(n.data),i=Rh(a?.createImproveRun);if(i?.state!=="ready_local"&&i?.state!=="released"||Rh(i.adapter)?.kind!=="local")continue;const s=cQ(i.id)??n.id;return[n.sessionId??"global",n.turnId??"turn",s].join(":")}return null}const uQ=332,Jx=244,Zx=560,mQ=560,Yx=320,Qx=2400,pQ=440;function Ph(e){const t=typeof window>"u"?Zx:Math.min(Zx,Math.max(Jx,window.innerWidth-420));return Math.min(t,Math.max(Jx,Math.round(e)))}function Ah(e){const t=typeof window>"u"?Qx:Math.min(Qx,Math.max(Yx,window.innerWidth-pQ));return Math.min(t,Math.max(Yx,Math.round(e)))}function fQ(e,t){return!!(e&&e.serverUrl===t.serverUrl&&e.token===t.token&&e.platform===t.platform)}const As=new Map;function gy(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function wA(e,t){const n=gy(e,t);if(!n)return null;const a=As.get(n);return a?.updatedAt?a.agents:null}function hQ(e,t,n){const a=gy(e,n);a&&As.set(a,{agents:t,promise:null,updatedAt:Date.now()})}function vy(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=gy(t,e.accountKey);if(!n)return Promise.resolve([]);const a=As.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.agents);if(a?.promise)return a.promise}const i=e.fetchAgents(t).then(r=>(hQ(t,r,e.accountKey),r)).catch(r=>{const s=As.get(n);throw s?.promise===i&&As.set(n,{agents:s.agents,promise:null,updatedAt:s.updatedAt}),r});return As.set(n,{agents:a?.agents??[],promise:i,updatedAt:a?.updatedAt??0}),i}const gQ=6e4,vQ=6e4,bQ=6e4,by=["pinned","projects","cloudProjects","chats","savedForLater"];function yQ(e,t,n,a=Date.now()){for(const i of IQ(t,n))_A(t[i],n[i])||(e[i]=a)}function SQ(e,t,n,a=Date.now()){const i={...t};for(const[r,s]of Object.entries(n)){if(a-s>gQ){delete n[r];continue}const c=_Q(e,r),m=e[r];!c||_A(m,t[r])||(i[r]=m)}return i}function xQ(e,t,n,a=Date.now()){for(const i of by)t[i]!==n[i]&&(e[i]=a)}function kQ(e,t,n,a=Date.now()){const i={...t};for(const r of by){const s=n[r];if(s!==void 0){if(a-s>vQ){delete n[r];continue}if(e[r]===t[r]){delete n[r];continue}i[r]=e[r]}}return wQ(e,i)?e:i}function Xx(e,t,n=Date.now()){return e===t?null:{value:t,changedAt:n}}function ek(e,t,n=Date.now()){return t?n-t.changedAt>bQ?{value:e,localChange:null}:e===t.value?{value:e,localChange:t}:{value:t.value,localChange:t}:{value:e,localChange:null}}function IQ(e,t){return new Set([...Object.keys(e),...Object.keys(t)])}function _A(e,t){return e?.pinned===t?.pinned&&e?.archived===t?.archived&&e?.order===t?.order}function wQ(e,t){return by.every(n=>e[n]===t[n])}function _Q(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const CQ=5e4,Uo="\0openpond-unscoped-runtime-events",ki=[];class RQ{perSessionLimit;totalLimit;entries=new Map;eventKeyById=new Map;listenersByKey=new Map;allListeners=new Set;summaryListeners=new Set;retainedKeys=new Set;allEventsSnapshot=ki;summaryEventsSnapshot=ki;clock=0;eventCount=0;constructor(t={}){if(this.perSessionLimit=ak(t.perSessionLimit??ly,"perSessionLimit"),this.totalLimit=ak(t.totalLimit??CQ,"totalLimit"),this.totalLimit<this.perSessionLimit)throw new Error("totalLimit must be greater than or equal to perSessionLimit")}append(t){if(t.length===0)return nk();const n=new Map;let a=0;for(const u of t){if(this.eventKeyById.has(u.id)){a+=1;continue}const h=u.sessionId||Uo,g=n.get(h);g?g.push(u):n.set(h,[u]),this.eventKeyById.set(u.id,h)}if(n.size===0)return{...nk(),duplicateEventCount:a};const i=new Set;let r=0,s=0,c=!1;for(const[u,h]of n){h.some(ik)&&(c=!0);const g=this.entries.get(u),S=g?.snapshot.events??ki,k=Math.max(0,Math.min(S.length,this.perSessionLimit-h.length)),C=h.length>this.perSessionLimit?h.slice(h.length-this.perSessionLimit):h,A=k===S.length?S:S.slice(S.length-k),M=A.length===0?C:[...A,...C],R=S.slice(0,S.length-A.length);R.some(ik)&&(c=!0);for(const j of R)this.eventKeyById.delete(j.id);for(const j of h.slice(0,h.length-C.length))this.eventKeyById.delete(j.id);const O={eventIds:new Set(M.map(j=>j.id)),lastTouched:++this.clock,retained:g?.retained??this.retainedKeys.has(u),snapshot:{events:M,latestSequence:im(M),revision:(g?.snapshot.revision??0)+1}};this.entries.set(u,O),this.eventCount+=M.length-S.length,r+=C.length,s+=R.length+h.length-C.length,i.add(u)}const m=this.enforceTotalLimit(i);return s+=m,this.publish(i,c||m>0),AQ({acceptedEventCount:r,duplicateEventCount:a,evictedEventCount:s,changedKeys:i})}mergeBootstrap(t){const n=PQ(t),a=new Set([...this.entries.keys(),...n.keys()]),i=[];for(const r of a){const s=n.get(r)??ki,c=this.entries.get(r)?.snapshot.events??ki;i.push(...p7(s,c))}return this.replace(i)}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=ki,this.summaryEventsSnapshot=ki;const i=this.append(t);for(const m of this.retainedKeys){const u=this.entries.get(m);u&&(u.retained=!0)}const r=this.eventKeyById;let s=0;for(const m of n)r.has(m)||(s+=1);const c=new Set([...a].filter(m=>!this.entries.has(m)));return c.size>0&&this.publish(c,!0),{...i,evictedEventCount:i.evictedEventCount+s,changedSessionIds:new Set([...i.changedSessionIds,...[...c].filter(m=>m!==Uo)]),unscopedEventsChanged:i.unscopedEventsChanged||c.has(Uo)}}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=ki,this.summaryEventsSnapshot=ki,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??tk:tk;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(TQ),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!==Uo&&a.retained&&(t+=1);return{eventCount:this.eventCount,retainedSessionCount:t,sessionCount:this.entries.size-(this.entries.has(Uo)?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[i,r]=a,s=this.eventCount-this.totalLimit;if(!r.retained||r.snapshot.events.length<=s){n+=r.snapshot.events.length,this.removeEntry(i),t.add(i);continue}const c=r.snapshot.events.slice(0,s),m=r.snapshot.events.slice(s);for(const u of c)this.eventKeyById.delete(u.id);r.eventIds=new Set(m.map(u=>u.id)),r.snapshot={events:m,latestSequence:im(m),revision:r.snapshot.revision+1},this.eventCount-=c.length,n+=c.length,t.add(i)}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 i of this.listenersByKey.get(a)??[])i();for(const a of this.allListeners)a();if(n)for(const a of this.summaryListeners)a()}}}const tk=Object.freeze({events:ki,latestSequence:null,revision:0});function PQ(e){const t=new Map;for(const n of e){const a=n.sessionId||Uo,i=t.get(a);i?i.push(n):t.set(a,[n])}return t}function AQ(e){return{acceptedEventCount:e.acceptedEventCount,duplicateEventCount:e.duplicateEventCount,evictedEventCount:e.evictedEventCount,changedSessionIds:new Set([...e.changedKeys].filter(t=>t!==Uo)),unscopedEventsChanged:e.changedKeys.has(Uo)}}function nk(){return{acceptedEventCount:0,duplicateEventCount:0,evictedEventCount:0,changedSessionIds:new Set,unscopedEventsChanged:!1}}function TQ(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 ak(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function ik(e){return e.name!=="assistant.delta"&&e.name!=="assistant.reasoning.delta"&&e.name!=="command.output"}const EQ=256,MQ=15e3,jQ=5e3,OQ=3e4;class $Q{constructor(t={}){this.options=t}options;entries=new Map;connection=null;accountScope=null;generation=0;activateConnection(t){NQ(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,DQ(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 i=this.now(),r=this.entries.get(t);if(r?.state==="loading"&&!this.expired(r,i))return r.promise;if(r?.state==="failed"&&!this.expired(r,i))return Promise.resolve(null);const s=this.generation,c=n().then(m=>this.generation!==s?null:(this.entries.set(t,{state:"ready",url:m.url,expiresAt:m.expiresAt,lastAccessedAt:this.now()}),this.prune(),m.url)).catch(()=>{if(this.generation!==s)return null;const m=this.now();return this.entries.set(t,{state:"failed",expiresAt:m+(this.options.failureTtlMs??jQ),lastAccessedAt:m}),this.prune(),null});return this.entries.set(t,{state:"loading",promise:c,expiresAt:i+(this.options.loadingTtlMs??OQ),lastAccessedAt:i}),this.prune(),c}clear(){this.generation+=1,this.entries.clear()}size(){return this.prune(),this.entries.size}prune(){const t=this.now();for(const[a,i]of this.entries)this.expired(i,t)&&this.entries.delete(a);const n=this.options.maxEntries??EQ;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??MQ:0;return t.expiresAt<=n+a}now(){return(this.options.now??Date.now)()}}const ok=new $Q;function Hie(e,t,...n){return[t,e.serverUrl,...n].join("\0")}function NQ(e,t){return e?.serverUrl===t?.serverUrl&&e?.token===t?.token&&e?.platform===t?.platform}function DQ(e,t,n){e.delete(t),e.set(t,n)}const HQ={connecting:"Connecting to OpenPond",account:"Loading account",team:"Loading default team",ready:"Ready"};function LQ(e){return{label:HQ[e],ready:e==="ready",stage:e}}const qQ=650,UQ=1200,zQ=6e4;function BQ(e){const{setDraftModel:t,setDraftProvider:n,setCodexPermissionMode:a,setCodexReasoningEffort:i,setOpenPondCommandAccessMode:r,setError:s,setSelectedAppId:c,setSelectedProjectId:m,setSelectedSessionId:u}=e,[h,g]=y.useState(null),[S,k]=y.useState(null),[C]=y.useState(()=>new RQ),A=y.useSyncExternalStore(C.subscribeSummary,C.getSummaryEvents,C.getSummaryEvents),M=y.useCallback(N=>{const F=C.getAllEvents(),ee=typeof N=="function"?N(F):N;ee!==F&&C.replace(ee)},[C]),R=y.useCallback(N=>{C.append(N)},[C]),[$,O]=y.useState(null),[j,I]=y.useState([]),[P,E]=y.useState([]),[L,z]=y.useState([]),[H,J]=y.useState({}),[X,de]=y.useState("connecting"),je=Og(S?.account),we=y.useRef({}),te=y.useRef({}),Me=y.useRef({}),Se=y.useRef([]),oe=y.useRef([]),be=y.useRef(null),re=y.useRef(null),ue=y.useRef(!1),ke=y.useRef(Date.now()),Le=y.useRef(null),Ie=y.useRef(null);y.useEffect(()=>{ok.activateConnection(h),ok.activateAccountScope(je)},[h,je]);const le=y.useCallback(N=>{ue.current||de(N)},[]),xe=y.useCallback(N=>{J(F=>{const ee=typeof N=="function"?N(F):N;return yQ(we.current,F,ee),ee})},[]),Ue=y.useCallback(N=>{I(F=>{const ee=typeof N=="function"?N(F):N;return Ex(te.current,F,ee),Se.current=ee,ee})},[]),Ze=y.useCallback(N=>{E(F=>{const ee=typeof N=="function"?N(F):N;return Ex(Me.current,F,ee),oe.current=ee,ee})},[]),it=y.useCallback(()=>{if(ue.current||Le.current!==null)return;const N=()=>{Le.current=null,!ue.current&&(ue.current=!0,de("ready"))},F=Date.now()-ke.current,ee=FQ(F);if(ee===0){N();return}Le.current=window.setTimeout(N,ee)},[]);y.useEffect(()=>()=>{Le.current!==null&&window.clearTimeout(Le.current)},[]);const at=y.useCallback(N=>{const F=be.current,ee=!F||F===N.server.id;be.current=N.server.id,O(me=>me?.serverId===N.server.id?me:{afterSequence:N.eventWindow?.latestSequence??im(N.events)??0,serverId:N.server.id}),k(N),ee?C.mergeBootstrap(N.events):C.replace(N.events),I(me=>{const $e=ee?Tx(me,N.sessions,te.current):$g(me,N.sessions,te.current);return Se.current=$e,$e}),E(me=>{const $e=ee?Tx(me,N.codexHistorySessions??[],Me.current):$g(me,N.codexHistorySessions??[],Me.current);return oe.current=$e,$e}),z(N.approvals),J(me=>SQ(me,N.sidebarAppPreferences,we.current)),c(me=>me&&N.apps.some($e=>$e.id===me)?me:null),m(me=>{if(!me)return null;const $e=JR(me);return $e?.kind==="local"&&N.localProjects.some(ze=>ze.id===$e.id)?wt("local",$e.id):$e?.kind==="cloud"&&(N.cloudProjects??[]).some(ze=>ze.id===$e.id)?wt("cloud",$e.id):N.localProjects.some(ze=>ze.id===me)?wt("local",me):(N.cloudProjects??[]).some(ze=>ze.id===me)?wt("cloud",me):null}),u(me=>{if(!me)return null;const $e=[...N.sessions,...N.codexHistorySessions??[]];if($e.some(tt=>tt.id===me&&!tt.archived))return me;if(!ee)return null;const ze=Se.current.find(tt=>tt.id===me)??oe.current.find(tt=>tt.id===me)??null;return ze&&!ze.archived&&ZP(ze,$e)?me:null})},[C,c,m,u]),Ne=y.useCallback(N=>{k(F=>F&&{...F,preferences:N.preferences})},[]);y.useEffect(()=>{const N=Oa(S?.preferences);n(N.defaultChatProvider),t(N.defaultChatModel)},[S?.preferences.defaultChatProvider,S?.preferences.defaultChatModel,t,n]),y.useEffect(()=>{a(Oa(S?.preferences).codexPermissionMode)},[S?.preferences.codexPermissionMode,a]),y.useEffect(()=>{i(Oa(S?.preferences).codexReasoningEffort)},[S?.preferences.codexReasoningEffort,i]),y.useEffect(()=>{r(Oa(S?.preferences).openPondCommandAccessMode)},[S?.preferences.openPondCommandAccessMode,r]),y.useEffect(()=>{if(!h||!S){re.current=null;return}if(S.account.state!=="signed_in"){re.current=null,it();return}const N=Og(S.account);if(!N){re.current=null,it();return}it(),le("team");const F=S.preferences.defaultTeamId?.trim()??"",ee=VQ(N,F,S.accountMeta.asOf??"initial");if(re.current===ee)return;re.current=ee;let me=!1;const $e=ze=>vy({teamId:ze,accountKey:N,fetchAgents:async tt=>(await Q.listSandboxAgents(h,{teamId:tt})).agents}).catch(()=>{!me&&re.current===ee&&(re.current=null)});return kx({accountKey:N,force:!0,fetchOrganizations:()=>rk(h)}).then(async ze=>{if(me)return;if(ze.length===0){it();return}if(!!F&&ze.some(mt=>mt.teamId===F)){await $e(F),it();return}const nt=vJ(ze)?.teamId;if(!nt){it();return}if(F){s("The configured default team is unavailable for this account. Select an available team in account settings."),it();return}await $e(nt),me||it()}).catch(ze=>{me||(re.current=null,s(ze instanceof Error?ze.message:String(ze)),it())}),()=>{me=!0}},[at,Ne,S?.account,S?.accountMeta.asOf,S?.preferences.defaultTeamId,it,h,le,s]),y.useEffect(()=>{if(!h||!je)return;let N=!1;const F=()=>{N||(N=!0,kx({accountKey:je,force:!0,fetchOrganizations:()=>rk(h)}).catch(()=>{}).finally(()=>{N=!1}))},ee=()=>{document.visibilityState==="visible"&&F()},me=window.setInterval(F,zQ);return window.addEventListener("focus",F),document.addEventListener("visibilitychange",ee),()=>{window.clearInterval(me),window.removeEventListener("focus",F),document.removeEventListener("visibilitychange",ee)}},[h,je]),hd(()=>{const N=OW();s(N||(F=>F?.startsWith("Preference changes have not been saved.")?null:F))}),y.useEffect(()=>{h&&JS(h).catch(N=>s(String(N)))},[h,je,s]);const We=y.useCallback(async()=>{le("connecting"),O(null);const N=await XK();g(ee=>fQ(ee,N)?ee:N),le("account");const F=await Q.bootstrap(N);await JS(N),at(F),it(),s(ee=>ee&&(vP(ee)||ee==="Event stream disconnected")?null:ee)},[at,it,le,s]);y.useEffect(()=>{let N=!1,F=null;const ee=async me=>{try{await We()}catch($e){if(N)return;s($e instanceof Error?$e.message:String($e));const ze=Math.min(5e3,750+me*750);F=window.setTimeout(()=>{ee(me+1)},ze)}};return ee(0),()=>{N=!0,F!==null&&window.clearTimeout(F)}},[We,s]);const qe=y.useCallback(()=>{We().catch(()=>{})},[We]);sQ({afterSequence:$?.afterSequence??null,appendEvents:R,connection:h,setApprovals:z,setSessions:Ue,setError:s,onDisconnected:qe}),y.useEffect(()=>{if(!h||!S){Ie.current=null;return}const N=dQ(A);!N||Ie.current===N||(Ie.current=N,Q.profileCurrent(h).then(F=>{k(ee=>ee&&{...ee,profile:F})}).catch(F=>{Ie.current=null,s(F instanceof Error?F.message:String(F))}))},[S,h,A,s]);const q=y.useCallback(()=>{h&&Q.refreshOpenPondAccount(h).then(({account:N,accountMeta:F})=>{k(ee=>ee&&{...ee,account:N,accountMeta:F})}).catch(N=>s(N instanceof Error?N.message:String(N)))},[h,s]);return{appPreferences:H,applyBootstrapPayload:at,approvals:L,bootstrap:S,codexHistorySessions:P,connection:h,events:A,runtimeEventStore:C,refreshOpenPondAccount:q,sessions:j,startup:LQ(X),setAppPreferences:xe,setBootstrap:k,setCodexHistorySessions:Ze,setEvents:M,setSessions:Ue}}async function rk(e){return(await Q.organizations(e)).organizations.map(ap).filter(n=>!!n).filter(n=>n.status==="active")}function FQ(e){return e>=UQ?0:Math.max(0,qQ-e)}function VQ(e,t,n){return`${e}::${t||"none"}::${n}`}function KQ({appDispatch:e,error:t,setErrorState:n}){const a=y.useRef(null),i=y.useRef(null),r=y.useRef(null),s=y.useRef(0),c=y.useCallback((u,h="info",g={})=>{const S=Date.now()+ ++s.current;return e({type:"showToast",toast:{id:S,message:u,tone:h,...g}}),S},[e]),m=y.useCallback(u=>{const h=i.current,g=typeof u=="function"?u(h):u;if(Object.is(h,g))return;if(i.current=g,n(g),!g){r.current!==null&&(e({type:"clearToast",toastId:r.current}),r.current=null);return}r.current=c(WQ(g),"error");const S=a.current;S&&Q.recordClientDiagnostic(S,{message:g,surface:"app",context:{href:window.location.href}}).catch(k=>{console.warn("Unable to record client diagnostic.",k)})},[e,n,c]);return y.useEffect(()=>{i.current=t,!(t||r.current===null)&&(e({type:"clearToast",toastId:r.current}),r.current=null)},[e,t]),{connectionRef:a,setError:m,showToast:c}}function WQ(e){return gP(e)}const GQ={query:"",searchOpen:!1,archivedChatsOpen:!1,sectionMenuOpen:null,projectsExpanded:!1,cloudProjectsExpanded:!1,chatRowsVisibleCount:Hn,sidebarOpen:!0,view:"chat",selectedAppId:null,selectedProjectId:null,selectedSessionId:null,prompt:"",promptDrafts:{},draftProvider:_r,draftModel:bc,draftExperience:"chat",codexPermissionMode:yv,codexReasoningEffort:Sv,openPondCommandAccessMode:bm,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 yy(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:`new-${e.draftExperience}`}function sm(e,t,n){if(!n){if(!(t in e))return e;const{[t]:a,...i}=e;return i}return e[t]===n?e:{...e,[t]:n}}function JQ(e){return sm(e.promptDrafts,yy(e),e.prompt)}function Bl(e,t,n={}){const a={...e,...t},i=yy(a),r=JQ(e),s=n.clearSelectedDraft?sm(r,i,""):n.preserveCurrentPrompt?sm(r,i,e.prompt):r;return{...e,...t,promptDrafts:s,prompt:n.clearSelectedDraft?"":n.preserveCurrentPrompt?e.prompt:s[i]??""}}function ZQ(e){return e==="draftExperience"||e==="selectedAppId"||e==="selectedProjectId"||e==="selectedSessionId"}function YQ(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 i=String(a);return{...e,prompt:i,promptDrafts:sm(e.promptDrafts,yy(e),i)}}return ZQ(t.key)?Bl(e,{[t.key]:a}):{...e,[t.key]:a}}case"patch":return{...e,...t.patch};case"selectApp":return Bl(e,{selectedAppId:t.appId,selectedProjectId:null,selectedSessionId:null,view:"chat"});case"selectProject":return Bl(e,{selectedAppId:null,selectedProjectId:t.projectId,selectedSessionId:null,view:"chat"},{preserveCurrentPrompt:!0});case"selectSession":{const n=t.projectId??null;return Bl(e,{selectedSessionId:t.sessionId,selectedAppId:n?null:t.appId??null,selectedProjectId:n,view:"chat"})}case"beginNewChat":return Bl(e,{selectedSessionId:null,selectedAppId:t.appId,selectedProjectId:null,error:null,view:"chat"});case"openCommitDialog":return{...e,commitMessage:"",commitIncludeUnstaged:!0,commitNextStep:t.nextStep,commitDraft:!0,commitDialogOpen:!0,error:null,view:"chat"};case"openBranchDialog":return{...e,branchDialogName:t.branchName,branchDialogOpen:!0,error:null,view:"chat"};case"showToast":return{...e,toast:t.toast};case"clearToast":return e.toast?.id===t.toastId?{...e,toast:null}:e;default:return e}}function kt(e,t){return n=>e({type:"field",key:t,value:n})}function QQ(e){return{setQuery:kt(e,"query"),setSearchOpen:kt(e,"searchOpen"),setArchivedChatsOpen:kt(e,"archivedChatsOpen"),setSectionMenuOpen:kt(e,"sectionMenuOpen"),setProjectsExpanded:kt(e,"projectsExpanded"),setCloudProjectsExpanded:kt(e,"cloudProjectsExpanded"),setChatRowsVisibleCount:kt(e,"chatRowsVisibleCount"),setSidebarOpen:kt(e,"sidebarOpen"),setView:kt(e,"view"),setSelectedAppId:kt(e,"selectedAppId"),setSelectedProjectId:kt(e,"selectedProjectId"),setSelectedSessionId:kt(e,"selectedSessionId"),setPrompt:kt(e,"prompt"),setDraftProvider:kt(e,"draftProvider"),setDraftModel:kt(e,"draftModel"),setDraftExperience:kt(e,"draftExperience"),setCodexPermissionMode:kt(e,"codexPermissionMode"),setCodexReasoningEffort:kt(e,"codexReasoningEffort"),setOpenPondCommandAccessMode:kt(e,"openPondCommandAccessMode"),setBusy:kt(e,"busy"),setDiffPanelOpen:kt(e,"diffPanelOpen"),setDiffPanelExpanded:kt(e,"diffPanelExpanded"),setRightPanelMode:kt(e,"rightPanelMode"),setRightChatPanels:kt(e,"rightChatPanels"),setTerminalOpen:kt(e,"terminalOpen"),setSyncingWorkspaceAppId:kt(e,"syncingWorkspaceAppId"),setSettingsSection:kt(e,"settingsSection"),setNewProjectDialogOpen:kt(e,"newProjectDialogOpen"),setNewProjectMode:kt(e,"newProjectMode"),setNewProjectName:kt(e,"newProjectName"),setNewProjectPath:kt(e,"newProjectPath"),setNewProjectBusy:kt(e,"newProjectBusy"),setCommitDialogOpen:kt(e,"commitDialogOpen"),setCommitMessage:kt(e,"commitMessage"),setCommitIncludeUnstaged:kt(e,"commitIncludeUnstaged"),setCommitNextStep:kt(e,"commitNextStep"),setCommitDraft:kt(e,"commitDraft"),setBranchDialogOpen:kt(e,"branchDialogOpen"),setBranchDialogName:kt(e,"branchDialogName"),setToast:kt(e,"toast"),setError:kt(e,"error")}}function Fl(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:"new-chat"}function XQ(e={selectedAppId:null,selectedProjectId:null,selectedSessionId:null}){let t=e,n="";const a=new Map,i=new Set,r=u=>{if(!Object.is(n,u)){n=u;for(const h of i)h()}},s=()=>{const u=Fl(t);n?a.set(u,n):a.delete(u)},c=(u,h={})=>{const g=n;s(),t={...t,...u};const S=Fl(t);if(h.clear&&a.delete(S),h.preserveCurrentDraft){g?a.set(S,g):a.delete(S),r(g);return}r(h.clear?"":a.get(S)??"")},m={getScopeKey:()=>Fl(t),getSnapshot:()=>n,subscribe(u){return i.add(u),()=>i.delete(u)},set:u=>m.setForScope(Fl(t),u),setForScope(u,h){const g=Fl(t),S=u===g?n:a.get(u)??"",k=typeof h=="function"?h(S):h;Object.is(S,k)||(k?a.set(u,k):a.delete(u),u===g&&r(k))},applyAppAction(u){if(u.type==="field"){if(u.key==="prompt"){m.set(u.value);return}if(u.key==="selectedAppId"||u.key==="selectedProjectId"||u.key==="selectedSessionId"){const h=t[u.key],g=typeof u.value=="function"?u.value(h):u.value;Object.is(h,g)||c({[u.key]:g})}return}if(u.type==="patch"){const h={};"selectedAppId"in u.patch&&(h.selectedAppId=u.patch.selectedAppId),"selectedProjectId"in u.patch&&(h.selectedProjectId=u.patch.selectedProjectId),"selectedSessionId"in u.patch&&(h.selectedSessionId=u.patch.selectedSessionId),Object.keys(h).length>0&&c(h),"prompt"in u.patch&&typeof u.patch.prompt=="string"&&m.set(u.patch.prompt);return}if(u.type==="selectApp"){c({selectedAppId:u.appId,selectedProjectId:null,selectedSessionId:null});return}if(u.type==="selectProject"){c({selectedAppId:null,selectedProjectId:u.projectId,selectedSessionId:null},{preserveCurrentDraft:!0});return}if(u.type==="selectSession"){const h=u.projectId??null;c({selectedSessionId:u.sessionId,selectedAppId:h?null:u.appId??null,selectedProjectId:h});return}u.type==="beginNewChat"&&c({selectedSessionId:null,selectedAppId:u.appId,selectedProjectId:null})}};return m}function Lie(e){return y.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot)}function eX(e){return{...e,draftExperience:uy()}}function tX(){const[e,t]=y.useReducer(YQ,GQ,eX),[n]=y.useState(()=>XQ()),a=y.useCallback(r=>{n.applyAppAction(r),t(r)},[n]),i=y.useMemo(()=>({...QQ(a),setPrompt:n.set}),[n,a]);return hd(()=>i.setDraftExperience(uy())),{composerDraftStore:n,dispatch:a,setters:i,state:e}}function nX(e){return!!(e&&e.includes("Git is required for OpenPond app workspaces")&&e.includes("Command Line Tools"))}function aX(e){const{connection:t,events:n,showToast:a}=e,i=y.useRef(new Set),r=y.useCallback(async()=>{if(t)try{const c=await Q.installMacOSCommandLineTools(t);a(c.message,"info")}catch(c){a(c instanceof Error?c.message:String(c),"error")}},[t,a]),s=y.useCallback((c="OpenPond needs Git to create and sync local projects.")=>{a(c,"error",{actionLabel:"Install Tools",onAction:()=>{r()},persistent:!0})},[a,r]);y.useEffect(()=>{if(!t)return;let c=!1;return Q.gitAvailability(t).then(m=>{c||m.ok||m.installAction!=="macos_command_line_tools"||s("OpenPond needs Git before it can create local projects.")}).catch(()=>{}),()=>{c=!0}},[t,s]),y.useEffect(()=>{for(const c of n){if(i.current.has(c.id))continue;const m=c.error??c.output??null;c.name==="workspace_action_result"&&c.status==="failed"&&nX(m)&&(i.current.add(c.id),s("OpenPond needs Git before it can update this project."))}},[n,s])}function iX({connection:e,preferences:t,sidebarOpen:n,diffPanelExpanded:a,setBootstrap:i,setError:r}){const[s,c]=y.useState(()=>Oa().sidebarSectionsCollapsed),m=y.useRef(s),u=y.useRef({}),h=y.useRef(null),g=y.useRef(null),[S,k]=y.useState(uQ),[C,A]=y.useState(!1),[M,R]=y.useState(mQ),[$,O]=y.useState(!1),{pinned:j,projects:I,cloudProjects:P,chats:E,savedForLater:L}=s;y.useEffect(()=>{if(C)return;const re=Ph(Oa(t).sidebarWidth),ue=ek(re,h.current);h.current=ue.localChange,k(ue.value)},[t,C]),y.useEffect(()=>{if($)return;const re=Ah(Oa(t).diffPanelWidth),ue=ek(re,g.current);g.current=ue.localChange,R(ue.value)},[$,t]),y.useEffect(()=>{const re=Oa(t).sidebarSectionsCollapsed;c(ue=>{const ke=kQ(ue,re,u.current);return m.current=ke,ke})},[t]);const z=y.useCallback(re=>{i(ue=>ue&&{...ue,preferences:re.preferences})},[i]),H=y.useCallback(async re=>{if(e&&Ph(Oa(t).sidebarWidth)!==re)try{z(await Q.savePreferences(e,{sidebarWidth:re}))}catch(ue){r(ue instanceof Error?ue.message:String(ue))}},[e,t,r,z]),J=y.useCallback(async re=>{if(e&&Ah(Oa(t).diffPanelWidth)!==re)try{z(await Q.savePreferences(e,{diffPanelWidth:re}))}catch(ue){r(ue instanceof Error?ue.message:String(ue))}},[e,t,r,z]),X=y.useCallback(async re=>{if(!e)return;const ue=Oa(t).sidebarSectionsCollapsed;if(!oX(ue,re))try{z(await Q.savePreferences(e,{sidebarSectionsCollapsed:re}))}catch(ke){r(ke instanceof Error?ke.message:String(ke))}},[e,t,r,z]),de=y.useCallback(re=>{const ue=m.current;xQ(u.current,ue,re),m.current=re,c(re),X(re)},[X]),je=y.useCallback(()=>{const re=m.current;de({...re,pinned:!re.pinned})},[de]),we=y.useCallback(()=>{const re=m.current;de({...re,projects:!re.projects})},[de]),te=y.useCallback(()=>{const re=m.current;de({...re,cloudProjects:!re.cloudProjects})},[de]),Me=y.useCallback(()=>{const re=m.current;de({...re,chats:!re.chats})},[de]),Se=y.useCallback(()=>{const re=m.current;de({...re,savedForLater:!re.savedForLater})},[de]),oe=y.useCallback(re=>{if(!n)return;re.preventDefault();const ue=re.clientX,ke=S;let Le=ke;A(!0);function Ie(xe){Le=Ph(ke+xe.clientX-ue),k(Le)}function le(){window.removeEventListener("pointermove",Ie),window.removeEventListener("pointerup",le);const xe=Xx(ke,Le);xe&&(h.current=xe),A(!1),H(Le)}window.addEventListener("pointermove",Ie),window.addEventListener("pointerup",le,{once:!0})},[H,n,S]),be=y.useCallback(re=>{if(a)return;re.preventDefault();const ue=re.clientX,ke=M;let Le=ke;O(!0);function Ie(xe){Le=Ah(ke-(xe.clientX-ue)),R(Le)}function le(){window.removeEventListener("pointermove",Ie),window.removeEventListener("pointerup",le);const xe=Xx(ke,Le);xe&&(g.current=xe),O(!1),J(Le)}window.addEventListener("pointermove",Ie),window.addEventListener("pointerup",le,{once:!0})},[a,M,J]);return{pinnedCollapsed:j,projectsCollapsed:I,cloudProjectsCollapsed:P,chatsCollapsed:E,savedForLaterCollapsed:L,sidebarWidth:S,sidebarResizing:C,diffPanelWidth:M,diffPanelResizing:$,togglePinnedCollapsed:je,toggleProjectsCollapsed:we,toggleCloudProjectsCollapsed:te,toggleChatsCollapsed:Me,toggleSavedForLaterCollapsed:Se,startSidebarResize:oe,startDiffPanelResize:be}}function oX(e,t){return e.pinned===t.pinned&&e.projects===t.projects&&e.cloudProjects===t.cloudProjects&&e.chats===t.chats&&e.savedForLater===t.savedForLater}function rX(e){const[t,n]=y.useState({id:0,kind:null}),[a,i]=y.useState(null),r=y.useCallback((u=null)=>{n(h=>({id:h.id+1,kind:u}))},[]),s=y.useCallback(u=>{i(u)},[]),c=null,m=y.useMemo(()=>{if(e)return sX(a,r)},[e,a,r]);return{backAction:c,breadcrumbs:m,closeDetailKind:t.kind,closeDetailRequestId:t.id,onDetailOpenChange:s}}function sX(e,t){return e?[{label:e.rootLabel??"Models",onSelect:()=>t(null)},{label:e.kindLabel,onSelect:e.kindOnSelect??(()=>t(e.kind))},...e.workproductLabel?[{label:e.workproductLabel,onSelect:e.workproductOnSelect}]:[],...e.segments]:[{label:"Models"}]}const sk=new WeakMap,Fg=new WeakMap;function lX(e){if(!e)return"disconnected";let t=sk.get(e);return(!t||t.serverUrl!==e.serverUrl||t.token!==e.token)&&(t={serverUrl:e.serverUrl,token:e.token,id:crypto.randomUUID()},sk.set(e,t)),t.id}function qie(e,t){return Fg.set(e,t),e}function Uie(e){if(!e)return["learning","disconnected"];let t=Fg.get(e);return t||(t=["learning",crypto.randomUUID()],Fg.set(e,t)),t}function cX(e,t,n){return{inspectModelBatch:async a=>{if(!e)throw new Error("Connect to OpenPond to inspect this batch.");return yK.parse(await Q.trainingRequest(e,"/models/batch-review/inspect",{profileId:t,modelId:a},"POST"))},beginModelBatchReview:async a=>{const i=await n(a);return i?SK.parse(i):null}}}function dX(e,t,n,a){async function i(r,s){if(!e)throw new Error("Connect to OpenPond to load tasks.");const c=c3.parse(s),m=new URLSearchParams({profileId:t});for(const[u,h]of Object.entries(c))h!==void 0&&m.set(u,String(h));return Q.trainingRequest(e,`${r}?${m}`,{},"GET")}return{taskInventory:async(r={})=>u3.parse(await i("/tasks",r)),taskInventoryDetail:async r=>{const s=await i("/tasks/detail",r);return{item:qC.parse(s.item),task:Fm.parse(s.task)}},tasksetDraftFiles:async r=>{if(!e)return null;try{return await Q.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(r)}/files?${new URLSearchParams({profileId:t})}`,{},"GET")}catch(s){return a(s),null}},tasksetDraftFile:async(r,s)=>{if(!e)return null;try{return await Q.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(r)}/file?${new URLSearchParams({profileId:t,path:s})}`,{},"GET")}catch(c){return a(c),null}},saveTasksetDraftFile:r=>n("save-taskset-draft-file",`/taskset-drafts/${encodeURIComponent(r.draftId)}/file`,{profileId:t,...r},"PATCH"),inspectTasksetDraftSource:(r,s)=>n("inspect-taskset-draft-source","/taskset-drafts/source",{profileId:t,modelId:r,expectedModelRevision:s}),createTasksetDraftFromSource:r=>n("create-taskset-draft","/taskset-drafts",{profileId:t,sourceRequest:r}),createTasksetDraft:(r="",s)=>n("create-taskset-draft","/taskset-drafts",{profileId:t,name:r,modelId:s??null}),importTasksetDraftPackage:r=>n("import-taskset-draft-package","/taskset-drafts/import",{packagePath:r,profileId:t}),saveTasksetDraft:r=>n("save-taskset-draft",`/taskset-drafts/${encodeURIComponent(r.id)}`,r,"PUT"),tasksetDraftWorkspace:async r=>{if(!e)return null;try{return await Q.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(r)}/workspace`,{},"GET")}catch(s){return a(s),null}},publishTasksetDraft:(r,s)=>n("publish-taskset-draft",`/taskset-drafts/${encodeURIComponent(r)}/publish`,{modelId:s??null}),refreshTasksetDraftModel:(r,s)=>n("refresh-taskset-draft-model",`/taskset-drafts/${encodeURIComponent(r.id)}/model-revision`,{expectedDraftRevision:r.revision,expectedModelRevision:s}),deleteTasksetDraft:r=>n("delete-taskset-draft",`/taskset-drafts/${encodeURIComponent(r)}`,{},"DELETE")}}function CA(e,t){return Yz({id:e.id,profileId:e.profileId,name:e.name,objective:e.objective,defaultBaseModel:e.defaultBaseModel,defaultDestinationId:e.defaultDestinationId,trainingSetup:e.trainingSetup},t)}async function uX(e,t,n){if(!e)throw new Error("Connect to the execution owner to check this configuration.");const a=await CA(t,n);return I_.parse(await Q.trainingRequest(e,"/models/check",a,"POST"))}function mX(e,t){return{listModelStarters:async(n,a=!1)=>{if(!e)throw new Error("Connect to OpenPond to browse model starters.");return Q.trainingRequest(e,`/model-starters?limit=30${n?`&afterId=${encodeURIComponent(n)}`:""}${a?"&fresh=true":""}`,{},"GET")},previewModelStarter:async n=>{if(!e)throw new Error("Connect to OpenPond to preview a starter.");return Q.trainingRequest(e,"/model-starters/preview",{id:n.id,revision:n.revision,contentHash:n.contentHash})},checkModelStarter:async n=>{if(!e)throw new Error("Connect to OpenPond to check this starter.");return I_.parse(await Q.trainingRequest(e,"/model-starters/check",n))},createModelFromStarter:n=>t("create-model-from-starter","/model-starters/create",n)}}const lk=1e4,ck=3e4;function pX(e){const{connection:t,profileId:n}=e,a=Ek(),i=lX(t),r=y.useMemo(()=>["training",i,n],[i,n]),s=y.useCallback(async()=>zV.parse(await Q.trainingState(t,n)),[t,n]),c=Bk({queryKey:r,queryFn:s,enabled:!!t}),m=c.data??null,u=!!t&&c.isPending,[h,g]=y.useState(null),[S,k]=y.useState(null),C=y.useRef(null);C.current=m?.activityRevision??null;const A=y.useCallback(async()=>{if(!t)return null;try{const I=await a.fetchQuery({queryKey:r,queryFn:s,staleTime:0});return k(null),I}catch(I){return k(Zi(I)),null}},[t,a,r,s]),M=y.useCallback(async()=>(await a.cancelQueries({queryKey:r,exact:!0}),await a.invalidateQueries({queryKey:r,exact:!0,refetchType:"none"}),await a.invalidateQueries({queryKey:["task-inventory",i,n]}),A()),[a,r,i,n,A]),R=y.useCallback(async(I,P,E,L="POST",z={})=>{if(!t)return null;z.silent||g(I);try{const H=await Q.trainingRequest(t,P,E,L);return await M(),z.silent||k(null),H}catch(H){return z.silent||k(Zi(H)),null}finally{z.silent||g(null)}},[t,M]),$=m?[m.jobs.some(I=>["queued","starting","running","cancelling","reconciling"].includes(I.status)),m.creations.some(I=>["planning","materializing","validating"].includes(I.state)),m.minerRuns.some(I=>["queued","running","cancelling"].includes(I.status)),m.datasetImports.some(I=>["inspecting","materializing","validating","cancelling"].includes(I.status))].some(Boolean):!1;y.useEffect(()=>{if(!t)return;let I=!0,P=null;const E=$?lk:ck,L=async()=>{let z=E;try{const H=await Q.trainingActivity(t,n);z=H.active?lk:ck,(C.current===null||C.current!==H.revision)&&await A()}catch(H){k(Zi(H))}I&&(P=window.setTimeout(()=>{L()},z))};return P=window.setTimeout(()=>{L()},E),()=>{I=!1,P!==null&&window.clearTimeout(P)}},[t,$,n,A]);const O=y.useMemo(()=>({...mX(t,R),saveComparisonSeries:I=>R("save-comparison-series","/comparison-series",{series:I}),saveContinualBenchIssueReview:I=>R("save-continual-support-issue-review","/continual-support/issue-reviews",{review:I},"PUT"),importContinualLearningDailyBatch:(I,P="json_upload")=>R("import-continual-learning-daily-batch","/continual-learning/daily-batches/import",{manifest:I,source:P}),saveContinualLearningDailyBatch:I=>R("save-continual-learning-daily-batch","/continual-learning/daily-batches",{batch:I},"PUT"),generateContinualLearningResponses:I=>R("generate-continual-learning-responses","/continual-learning/responses",I),sealComparisonSeries:(I,P)=>R("seal-comparison-series",`/comparison-series/${encodeURIComponent(I)}/seal`,{expectedRevision:P}),archiveComparisonSeries:(I,P)=>R("archive-comparison-series",`/comparison-series/${encodeURIComponent(I)}/archive`,{expectedRevision:P}),queueComparisonRelease:I=>R("queue-comparison-release",`/comparison-series/${encodeURIComponent(I.seriesId)}/releases`,I),startComparisonEvaluation:I=>R("start-comparison-evaluation",`/comparison-series-entries/${encodeURIComponent(I.entryId)}/evaluations`,I),loadComparisonAttemptEvidence:I=>t?Q.trainingRequest(t,`/model-runs/${encodeURIComponent(I.runId)}/attempts/${encodeURIComponent(I.attemptId)}/evidence?kind=${I.kind}`,{},"GET"):Promise.resolve(null),linkComparisonRun:I=>R("link-comparison-run",`/comparison-series-entries/${encodeURIComponent(I.entryId)}/run`,I,"PATCH"),decideComparisonEntry:I=>R("decide-comparison-entry",`/comparison-series-entries/${encodeURIComponent(I.entryId)}/decision`,I),recordComparisonPromotion:I=>R("record-comparison-promotion",`/comparison-series-entries/${encodeURIComponent(I.entryId)}/promotion`,I),checkModelProject:(I,P=I.revision)=>uX(t,I,P),...cX(t,n,I=>R("begin-model-batch-review","/models/batch-review",{profileId:n,request:I})),saveModelProject:async(I,P=I.revision)=>R("save-model-project","/models",await CA(I,P),"PUT"),listHostedModelProjects:async(I={})=>{if(!t)return null;I.silent||g("list-hosted-model-projects");try{const P=await Q.trainingRequest(t,`/hosted-model-projects?profileId=${encodeURIComponent(n)}&refresh=${I.refresh===!0}`,{},"GET");return I.silent||k(null),P}catch(P){return I.silent||k(Zi(P)),null}finally{I.silent||g(P=>P==="list-hosted-model-projects"?null:P)}},openHostedModelProject:(I,P,E,L={})=>R(`open-hosted-model-project:${I}`,`/hosted-model-projects/${encodeURIComponent(I)}/open`,{profileId:n,teamId:P,apiOrigin:E},"POST",L),pullHostedModelProject:I=>R(`pull-hosted-model-project:${I}`,`/hosted-model-projects/${encodeURIComponent(I)}/pull`,{profileId:n}),syncModelProject:I=>R("sync-model-project",`/models/${encodeURIComponent(I)}/sync`,{}),publishModelProjectTaskset:(I,P)=>R("publish-model-project-taskset",`/models/${encodeURIComponent(I)}/tasksets/${encodeURIComponent(P)}/publish`,{}),createScorer:(I,P,E)=>R("create-scorer","/scorers",{grader:I,tasksetId:P,modelProjectId:E??null}),prepareLearningBatch:I=>R("prepare-learning-batch","/learning-batches/prepare",{profileId:n,batchId:I}),...dX(t,n,R,I=>k(Zi(I))),tasksetGraderDetails:async I=>{if(!t)return null;try{return await Q.trainingRequest(t,`/tasksets/${encodeURIComponent(I)}/graders`,{},"GET")}catch(P){return k(Zi(P)),null}},inspectHuggingFaceDataset:I=>R("inspect-huggingface-dataset","/dataset-imports/huggingface/inspect",{profileId:n,url:I}),materializeDatasetImport:(I,P)=>R("materialize-dataset-import",`/dataset-imports/${encodeURIComponent(I)}/materialize`,P),cancelDatasetImport:I=>R("cancel-dataset-import",`/dataset-imports/${encodeURIComponent(I)}/cancel`,{}),datasetRows:(I,P={})=>{if(!t)return Promise.resolve(null);const E=new URLSearchParams;P.split&&E.set("split",P.split),P.cursor&&E.set("cursor",P.cursor),E.set("limit",String(P.limit??25));for(const L of P.columns??[])E.append("column",L);return Q.trainingRequest(t,`/tasksets/${encodeURIComponent(I)}/rows?${E}`,{},"GET")},addSource:(I,P)=>R("add-source","/sources",{profileId:n,sessionId:I,turnIds:P}),addSources:I=>R("add-sources","/sources/batch",{profileId:n,sessionIds:I}),estimateSources:I=>t?Q.trainingRequest(t,"/sources/estimate",{sessionIds:I}):Promise.resolve([]),searchChats:(I,P,E=0,L=20)=>t?Q.trainingRequest(t,"/sources/search",{query:I,candidates:P,offset:E,limit:L}):Promise.resolve({schemaVersion:"openpond.trainingChatSearchResult.v1",query:I,offset:E,limit:L,total:0,hasMore:!1,indexedChats:0,totalChats:0,indexing:!1,entries:[]}),removeSource:I=>R("remove-source",`/sources/${encodeURIComponent(I)}`,{},"DELETE"),deleteTaskset:I=>R("delete-model",`/tasksets/${encodeURIComponent(I)}`,{},"DELETE"),runBenchmark:(I,P,E,L)=>R(`run-benchmark-${P}`,`/tasksets/${encodeURIComponent(I)}/benchmark-runs`,{phase:P,model:E,reasoningEffort:L,seeds:[17],repetitions:1}),startHarnessRefinerBenchmark:(I,P,E)=>R("run-harness-refiner-benchmark",`/models/${encodeURIComponent(I)}/harness-refiner-benchmark`,{profileId:n,model:P,reasoningEffort:E,maximumSpendUsd:10}),acceptHarnessReview:(I,P,E=null,L=null)=>R("accept-harness-review","/harness-reviews/accept",{profileId:n,workspaceId:I,reviewRef:P,analysisModel:E,analysisReasoningEffort:L}),startCreation:(I,P={})=>R("create-taskset","/task-creations",{profileId:n,sourceIds:I,surface:P.surface??"training_page",mode:P.mode??"defaults",entryMode:P.entryMode??"manual",resourceIntent:P.resourceIntent??"workproduct",buildIntent:P.buildIntent??"demonstrations",buildSpecification:P.buildSpecification??null,objective:P.objective??null,methodHint:P.methodHint??null,preferredBaseModelId:P.preferredBaseModel?.modelId??null,preferredBaseModel:P.preferredBaseModel??null,candidateId:P.candidateId??null,analysisModel:P.analysisModel??null,analysisReasoningEffort:P.analysisReasoningEffort??null,createImproveRunId:P.createImproveRunId??null,targetIntent:P.targetIntent??{kind:"model",id:null,displayName:null,operation:"create"}}),createModelFromTaskset:(I,P)=>R("create-model","/models/from-taskset",{profileId:n,tasksetId:I,preferredBaseModelId:P.modelId,preferredBaseModel:P}),scanBaseModels:async()=>{if(!t)return null;g("scan-base-models");try{const I=await A();return k(null),I}catch(I){return k(Zi(I)),null}finally{g(null)}},approveDisclosure:(I,P)=>R("approve-disclosure",`/task-creations/${encodeURIComponent(I)}/disclosure`,{approved:P}),retryCreation:I=>R("retry-creation",`/task-creations/${encodeURIComponent(I)}/retry`,{}),answerQuestions:(I,P)=>R("answer-questions",`/task-creations/${encodeURIComponent(I)}/questions`,{answers:P}),materialize:(I,P)=>R("materialize",`/task-creations/${encodeURIComponent(I)}/materialize`,{approved:P}),chatCreation:(I,P)=>R("task-creator-chat",`/task-creations/${encodeURIComponent(I)}/chat`,{message:P}),renameCreation:(I,P)=>R("rename-creation",`/task-creations/${encodeURIComponent(I)}/name`,{name:P},"PATCH"),cancelCreation:I=>R("cancel-creation",`/task-creations/${encodeURIComponent(I)}/cancel`,{}),runMiner:(I=[],P=[],E)=>R("run-miner","/miner/run",{profileId:n,sourceIds:I,sessionIds:P,config:E}),cancelMinerRun:I=>R("cancel-miner-run",`/miner/runs/${encodeURIComponent(I)}/cancel`,{}),configureMiner:I=>R("configure-miner","/miner/config",{profileId:n,config:I},"PUT"),patchCandidate:(I,P)=>R("candidate",`/candidates/${encodeURIComponent(I)}`,P,"PATCH"),createCandidate:(I,P,E,L)=>R("create-candidate",`/candidates/${encodeURIComponent(I)}/create`,{mode:P,analysisModel:E??null,analysisReasoningEffort:L??null}),auditGraders:I=>R("audit-graders","/audit-graders",{tasksetId:I}),executeTasksetAttempt:(I,P,E)=>R("execute-taskset-attempt",`/tasksets/${encodeURIComponent(I)}/attempts`,{taskId:P,model:E,seed:17,attempt:0,sampling:{maxOutputTokens:4096,temperature:0,topP:1}}),materializeSyntheticPreferenceCollection:I=>R("materialize-synthetic-preference-collection",`/tasksets/${encodeURIComponent(I.tasksetId)}/synthetic-preference-collection`,I),tasksetOperationalState:I=>t?Q.trainingRequest(t,`/tasksets/${encodeURIComponent(I)}/operations`,{},"GET"):Promise.resolve(null),calibrateJudges:I=>R("calibrate-judges","/calibrate-judges",{tasksetId:I}),nextPreferenceComparison:(I,P)=>R("next-preference-comparison",`/tasksets/${encodeURIComponent(I)}/preference-comparisons/next`,{reviewerKey:P}),submitPreferenceComparison:I=>R("submit-preference-comparison",`/tasksets/${encodeURIComponent(I.tasksetId)}/preference-comparisons/${encodeURIComponent(I.assignmentId)}/submit`,I),submitSyntheticFixturePreference:I=>R("submit-synthetic-fixture-preference",`/tasksets/${encodeURIComponent(I.tasksetId)}/preference-comparisons/${encodeURIComponent(I.assignmentId)}/fixture-submit`,{...I,id:crypto.randomUUID()}),listPreferenceDatasets:I=>t?Q.trainingRequest(t,`/tasksets/${encodeURIComponent(I)}/preference-datasets`,{},"GET"):Promise.resolve(null),materializePreferenceDataset:I=>R("materialize-preference-dataset",`/tasksets/${encodeURIComponent(I.tasksetId)}/preference-datasets`,{...I,id:`preference-dataset-${crypto.randomUUID()}`,revision:1}),launchRewardModelRun:I=>R("launch-reward-model-run",`/tasksets/${encodeURIComponent(I.tasksetId)}/reward-model-runs`,{...I,id:`reward-model-run-${crypto.randomUUID()}`}),learnedPreferenceRewardBinding:I=>R("learned-preference-reward-binding",`/tasksets/${encodeURIComponent(I.tasksetId)}/learned-preference-reward-binding`,I),retryRewardModelQualification:I=>R("retry-reward-model-qualification",`/reward-model-runs/${encodeURIComponent(I.runId)}/retry-qualification`,I),cancelRewardModelRun:I=>R("cancel-reward-model-run",`/reward-model-runs/${encodeURIComponent(I)}/cancel`,{}),markPreferenceComparisonUnreviewable:I=>R("mark-preference-comparison-unreviewable",`/tasksets/${encodeURIComponent(I.tasksetId)}/preference-comparisons/${encodeURIComponent(I.assignmentId)}/unreviewable`,I),preferenceCalibrationStatus:(I,P,E)=>{if(!t)return Promise.resolve(null);const L=new URLSearchParams({reviewerKey:P});return E&&L.set("comparisonReleaseId",E),Q.trainingRequest(t,`/tasksets/${encodeURIComponent(I)}/preference-comparisons/calibration/status?${L}`,{},"GET")},startPreferenceCalibrationBatch:I=>R("start-preference-calibration-batch",`/tasksets/${encodeURIComponent(I.tasksetId)}/preference-comparisons/calibration/batches`,{...I,id:crypto.randomUUID()}),syncPreferenceCalibrationBatch:I=>R("sync-preference-calibration-batch",`/tasksets/${encodeURIComponent(I.tasksetId)}/preference-comparisons/calibration/batches/${encodeURIComponent(I.jobId)}/sync`,I),reviewPreferenceComparisonWithModel:I=>R("review-preference-comparison-with-model",`/tasksets/${encodeURIComponent(I.tasksetId)}/preference-comparisons/${encodeURIComponent(I.assignmentId)}/model-review`,{...I,id:crypto.randomUUID()}),runNextPreferenceCalibrationReview:I=>R("run-next-preference-calibration-review",`/tasksets/${encodeURIComponent(I.tasksetId)}/preference-comparisons/calibration/model-reviews/next`,{...I,id:crypto.randomUUID()}),savePreferenceCalibration:I=>R("save-preference-calibration",`/tasksets/${encodeURIComponent(I.tasksetId)}/preference-comparisons/calibration/report`,{...I,id:crypto.randomUUID()}),preferenceArtifactUrl:async I=>{if(!t)return null;const P=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(I)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!P.ok)throw new Error(await P.text());return URL.createObjectURL(await P.blob())},readiness:I=>R("readiness","/readiness",{tasksetId:I}),previewExpertBootstrap:I=>R("preview-expert-bootstrap",`/tasksets/${encodeURIComponent(I)}/expert-bootstrap/preview`,{}),approveExpertBootstrap:(I,P)=>R("approve-expert-bootstrap",`/tasksets/${encodeURIComponent(I)}/expert-bootstrap/approve`,{previewHash:P}),createPlan:I=>R("create-plan","/plans",{...I,tasksetId:I.tasksetId}),buildBundle:I=>R("build-bundle","/bundles",{planId:I}),approveTraining:(I,P)=>R("approve-training","/approvals",{planId:I,bundleId:P}),launch:(I,P)=>R("launch","/launch",{planId:I,approvalId:P}),prepareTraining:I=>R("prepare-training","/prepare",I),prepareModelRun:(I,P)=>R("prepare-model-run",`/model-projects/${encodeURIComponent(I)}/training/prepare`,P),startModelRun:(I,P)=>R("start-model-run",`/model-projects/${encodeURIComponent(I)}/training/start`,P),startPreparedTraining:I=>R("start-prepared-training","/start/prepared",I),startTraining:I=>R("start-training","/start",I),cancelJob:I=>R("cancel-job",`/jobs/${encodeURIComponent(I)}/cancel`,{}),retryModelRunCollection:I=>R("retry-model-run-collection",`/model-runs/${encodeURIComponent(I)}/retry-collection`,{}),cancelModelRun:I=>R("cancel-model-run",`/model-runs/${encodeURIComponent(I)}/cancel`,{}),rejectModel:(I,P)=>R("reject-model",`/models/${encodeURIComponent(I)}/reject`,{reason:P}),bindModel:(I,P,E)=>R("bind-model",`/models/${encodeURIComponent(I)}/bind`,{profileId:n,role:P,roleTargetId:E,promotedBy:n}),rollbackModelBinding:I=>R("rollback-model-binding",`/bindings/${encodeURIComponent(I)}/rollback`,{rolledBackBy:n}),updateModelConfiguration:(I,P)=>R("update-model-configuration",`/models/${encodeURIComponent(I)}/configuration`,P,"PATCH",{silent:!0}),setModelPinned:(I,P)=>R("pin-model-version",`/models/${encodeURIComponent(I)}/pin`,{pinned:P},"PATCH"),downloadArtifact:async I=>{if(!t)return!1;g("download-artifact");try{const P=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(I)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!P.ok)throw new Error(await P.text());const E=P.headers.get("content-disposition")??"",L=/filename="([^"]+)"/.exec(E)?.[1]??"openpond-model-artifact",z=URL.createObjectURL(await P.blob()),H=document.createElement("a");return H.href=z,H.download=L,H.click(),URL.revokeObjectURL(z),!0}catch(P){return k(Zi(P)),!1}finally{g(null)}},downloadModelPackage:async I=>j(`/models/${encodeURIComponent(I)}/download`,`${I}.openpond-lora.tar`),downloadBundle:async I=>j(`/bundles/${encodeURIComponent(I)}/download`,"openpond-model-improvement-bundle.json")}),[t,R,n,A]);async function j(I,P){if(!t)return!1;g("download-bundle");try{const E=await fetch(`${t.serverUrl}/v1/training${I}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!E.ok)throw new Error(await E.text());const L=E.headers.get("content-disposition")??"",z=/filename="([^"]+)"/.exec(L)?.[1]??P,H=URL.createObjectURL(await E.blob()),J=document.createElement("a");return J.href=H,J.download=z,J.click(),URL.revokeObjectURL(H),!0}catch(E){return k(Zi(E)),!1}finally{g(null)}}return{connection:t,payload:m,loading:u,busyAction:h,error:S??c.error?.message??null,refresh:A,actions:O}}function Zi(e){return e instanceof Error?e.message:String(e)}function zie({modelId:e,taskset:t}){const n=t.metadata.toolContractHash===dd?"cross_system":t.environment.kind==="stateful_harness"&&t.environment.actionBindings?.length?"harness":null,a=n?vX(t,n):[];return{model:{providerId:"openpond",modelId:e},tasksetId:t.id,tasksetName:t.name,taskRuntime:n,sourceProjectId:bX(t),tasks:a,selectedTaskIndex:0,sessionId:null}}function Bie(e){return{model:{providerId:"openpond",modelId:e.modelId},tasksetId:e.tasksetId,tasksetName:e.modelName,taskRuntime:null,sourceProjectId:null,tasks:[],selectedTaskIndex:0,sessionId:null}}function ys(e){return e?.tasks.length?e.tasks[AA(e,e.selectedTaskIndex)]??null:null}function RA(e,t){return{...e,selectedTaskIndex:AA(e,t)}}function fX(e){return RA(e,e.selectedTaskIndex+1)}function hX(e,t,n){if(!e||PA(e,n))return null;const a=ys(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 PA(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 gX({model:e,connection:t,loadBootstrap:n,applyBootstrap:a}){e.providerId!=="openpond"||!t||a(await n(t))}function vX(e,t){const n=new Set;return e.tasks.flatMap(a=>{const i=t==="cross_system"?a.metadata.taskId:a.metadata.caseId,r=typeof i=="string"?i.trim():"",s=typeof a.input.prompt=="string"?a.input.prompt.trim():"";return!r||!s||n.has(r)?[]:(n.add(r),[{authoredTaskId:a.id,generatedTaskId:r,prompt:s,split:a.split}])})}function bX(e){const t=new Set(e.sourceRefs.filter(wC).flatMap(n=>{const a=n.workspaceId?.trim();return a?[a]:[]}));return t.size===1?t.values().next().value??null:null}function AA(e,t){return e.tasks.length?Math.max(0,Math.min(Math.trunc(t),e.tasks.length-1)):0}function yX({activeModel:e,activeProvider:t,applyBootstrapPayload:n,beginNewChat:a,composerDraftStore:i,connection:r,requestComposerFocus:s,selectedLocalProjectId:c,selectedSessionId:m,selectLocalProject:u,setDraftModel:h,setDraftProvider:g,setError:S,view:k}){const[C,A]=y.useState(null),M=y.useCallback(E=>{E.sourceProjectId?u(E.sourceProjectId):a(null)},[a,u]),R=y.useCallback(E=>{if(!C)return;const L={...RA(C,E),sessionId:C.sessionId?null:C.sessionId},z=ys(L);A(L),z&&(C.sessionId&&M(L),i.set(z.prompt),s())},[M,i,C,s]),$=y.useCallback(()=>{const E=ys(C);E&&i.getSnapshot().trim()===E.prompt.trim()&&i.set(""),A(null)},[i,C]),O=y.useCallback(E=>{const L=E.model;gX({model:L,connection:r,loadBootstrap:Q.bootstrap,applyBootstrap:n}).then(()=>{const z={...E,selectedTaskIndex:0,sessionId:null};g(L.providerId),h(L.modelId),A(z.tasks.length?z:null),M(z);const H=ys(z);H&&i.set(H.prompt)}).catch(S)},[n,M,i,r,h,g,S]),j=y.useCallback(E=>{const L=!!(C&&C.model.providerId===t&&C.model.modelId===e);return{active:L,error:L?PA(C,c):null,metadata:L?hX(C,E,c):null}},[e,t,C,c]),I=y.useCallback(E=>{A(L=>L&&{...L,sessionId:E})},[]),P=y.useCallback(()=>{if(!C)return;const E={...fX(C),sessionId:null},L=ys(E);A(E),L&&(M(E),i.set(L.prompt),s())},[M,i,C,s]);return y.useEffect(()=>{const E=ys(C);!E||k!=="chat"||m||i.set(L=>L.trim()?L:E.prompt)},[i,C,c,m,k]),y.useEffect(()=>{C&&m&&C.sessionId!==m&&A(null)},[C?.sessionId,m]),{advanceAfterTurn:P,begin:O,bindSession:I,dismiss:$,handoff:C,prepareTurn:j,selectTask:R}}const Vl=[],Th=500;function SX(e){const{approvals:t,codexHistoryEvents:n,connection:a,latestServerSequence:i,runtimeIndexes:r,runtimeEventStore:s,selectedSessionId:c,serverId:m,setCodexHistoryEvents:u,setCodexHistorySessions:h,setError:g}=e,[S,k]=y.useState({}),[C,A]=y.useState({}),M=y.useRef(new Set);y.useEffect(()=>{k({}),A({}),M.current.clear()},[m]);const R=y.useCallback(async()=>{if(!a||!c||M.current.has(c))return!1;const P=C[c];if(P?.hasMore===!1)return!1;if(Vt(c)){const z=Math.max(P?.totalMatchingEvents??0,n.length,XP),H=Math.min(Mx,Math.max(tZ,z*2));M.current.add(c),A(J=>({...J,[c]:{cursorSequence:null,hasMore:!0,loading:!0,totalMatchingEvents:J[c]?.totalMatchingEvents??n.length}}));try{const J=await eA(a,c,{force:!0,limit:H,tail:!1});return u(J.events),h(X=>ip(X,J.session)),A(X=>({...X,[c]:{cursorSequence:null,hasMore:J.events.length>=H&&H<Mx,loading:!1,totalMatchingEvents:H}})),J.events.length>n.length}catch(J){return g(J instanceof Error?J.message:String(J)),A(X=>({...X,[c]:{cursorSequence:null,hasMore:X[c]?.hasMore??!0,loading:!1,totalMatchingEvents:X[c]?.totalMatchingEvents??n.length}})),!1}finally{M.current.delete(c)}}const E=Xi(S[c]??Vl,s.getSessionEvents(c)),L=P?.cursorSequence??xX(E);if(!L)return!1;M.current.add(c),A(z=>({...z,[c]:{cursorSequence:z[c]?.cursorSequence??L,hasMore:z[c]?.hasMore??!0,loading:!0,totalMatchingEvents:z[c]?.totalMatchingEvents??null}}));try{const z=await Q.runtimeEventsPage(a,{sessionId:c,beforeSequence:L,limit:Th}),H=z.events.map(J=>J.event);return k(J=>({...J,[c]:Xi(H,J[c]??Vl)})),A(J=>({...J,[c]:{cursorSequence:z.previousSequence,hasMore:z.hasMore,loading:!1,totalMatchingEvents:z.totalMatchingEvents}})),H.length>0}catch(z){return g(z instanceof Error?z.message:String(z)),A(H=>({...H,[c]:{cursorSequence:H[c]?.cursorSequence??L,hasMore:H[c]?.hasMore??!0,loading:!1,totalMatchingEvents:H[c]?.totalMatchingEvents??null}})),!1}finally{M.current.delete(c)}},[C,n.length,a,S,s,c,u,h,g]),$=c?S[c]??Vl:Vl,O=y.useMemo(()=>s.getSessionEvents(c).length,[s,c]),j=y.useRef(null);y.useEffect(()=>{if(!a||!c||Vt(c)||M.current.has(c)||$.length>0||O>0)return;const P=i;if(!P)return;const E=c,L=P+1;M.current.add(E),A(z=>({...z,[E]:{cursorSequence:z[E]?.cursorSequence??L,hasMore:z[E]?.hasMore??!0,loading:!0,totalMatchingEvents:z[E]?.totalMatchingEvents??null}})),Q.runtimeEventsPage(a,{sessionId:E,beforeSequence:L,limit:Th}).then(z=>{const H=z.events.map(J=>J.event);k(J=>({...J,[E]:Xi(H,J[E]??Vl)})),A(J=>({...J,[E]:{cursorSequence:z.previousSequence,hasMore:z.hasMore,loading:!1,totalMatchingEvents:z.totalMatchingEvents}}))}).catch(z=>{g(z instanceof Error?z.message:String(z)),A(H=>({...H,[E]:{cursorSequence:H[E]?.cursorSequence??L,hasMore:H[E]?.hasMore??!0,loading:!1,totalMatchingEvents:H[E]?.totalMatchingEvents??null}}))}).finally(()=>{M.current.delete(E)})},[i,a,$.length,O,c,g]),y.useEffect(()=>{if(!a||!c||Vt(c)||M.current.has(c)||!i)return;const P=Xi($,s.getSessionEvents(c)),E=im(P);if(!E||E>=i)return;const L=`${c}:${E}:${i}`;if(j.current===L)return;j.current=L;let z=!1;return Q.runtimeEventsPage(a,{sessionId:c,afterSequence:E,limit:Th}).then(H=>{if(z)return;const J=H.events.map(X=>X.event);J.length!==0&&k(X=>m7(X,c,J))}).catch(H=>{z||(j.current=null,g(H instanceof Error?H.message:String(H)))}),()=>{z=!0}},[i,a,s,$,c,g]);const I=y.useMemo(()=>Vt(c)?jg(n,[]):!c||$.length===0?r:jg(Xi($,s.getSessionEvents(c)),t),[t,n,r,$,c]);return{chatHistoryLoadStates:C,loadMoreSelectedChatHistory:R,selectedPagedSessionEvents:$,selectedRuntimeIndexes:I}}function xX(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function kX(e,t){const n=y.useRef(null);return y.useMemo(()=>{const a=OP(e,t,n.current);return n.current={events:e,indexes:a},a},[t,e])}function Ts(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Eh(e){return Array.isArray(e)?e.filter(t=>!!Ts(t)):[]}function mr(e){return typeof e=="string"&&e.trim()?e.trim():null}function dk(e){return mr(e)??Ts(e)}function IX(e){if(!e)return[];const t=Ts(e.sandboxActionRegistry),n=Ts(e.sandboxManifest),a=new Map;for(const i of[...Eh(n?.actionCatalog),...Eh(t?.actions),...Eh(n?.actions)]){const r=mr(i.id)??mr(i.name);if(!r)continue;const s=a.get(r);a.set(r,{id:r,name:mr(i.name)??s?.name??r,label:mr(i.label)??s?.label??wX(r),description:mr(i.description)??s?.description??null,visibility:mr(i.visibility)??s?.visibility??"default",inputSchema:dk(i.inputSchema)??s?.inputSchema??null,outputSchema:dk(i.outputSchema)??s?.outputSchema??null,implementation:Ts(i.implementation)??s?.implementation??null,mcp:Ts(i.mcp)??s?.mcp??null,invokesModel:typeof i.invokesModel=="boolean"?i.invokesModel:s?.invokesModel})}return Array.from(a.values()).filter(i=>i.visibility!=="internal"&&i.visibility!=="debug")}function wX(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}function TA(e){if(e.selectedCloudProject)return{id:e.selectedCloudProject.id,teamId:e.selectedCloudProject.teamId,name:e.selectedCloudProject.name,selectionKey:wt("cloud",e.selectedCloudProject.id),localProjectId:null};const t=e.selectedProject?.linkedSandboxProject??null;if(!t?.projectId||!t.teamId)return null;const n=e.cloudProjects?za(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:wt("cloud",n?.id??t.projectId),localProjectId:e.selectedProject?.id??null}}const EA="openpond-agent",MA="openpond-profile-action";function sp(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function eo(e){return typeof e=="string"&&e.trim()?e.trim():null}function Sy(e){return e.displayPrompt&&/(?:^|\s)@[A-Za-z0-9_-]+/.test(e.displayPrompt)?"mention":"slash"}function _X(e){const t=sp(e),n=eo(t?.scope);return n!=="entire_manifest"&&n!=="start"&&n!=="action"&&n!=="service"&&n!=="schedule"?null:{scope:n,name:eo(t?.name)}}function CX(e){const t=eo(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 RX(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:EA,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 PX(e){const t=sp(e.implementation);if(t?.type!==EA)return null;const n=eo(t.agentId),a=eo(t.teamId),i=eo(t.projectId),r=_X(t.selectedEntrypoint),s=CX(t.workflowMode);return!n||!a||!i||!r||!s?null:{agentId:n,agentName:eo(t.agentName)??e.label??e.name??e.id,teamId:a,projectId:i,projectName:eo(t.projectName),selectedEntrypoint:r,workflowMode:s}}function AX(e,t={}){const n=t.agentName?.trim()||null;return{...e,implementation:{...sp(e.implementation)??{},type:MA,actionId:e.id,...n?{agentName:n}:{}},invokesModel:e.invokesModel??!0}}function TX(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=>AX(n,{agentName:n.agentId?t.get(n.agentId):null}))}function Fie(e){return!!(e&&xy(e))}function Vie(e){return!!(e&&xy(e)&&e.sourceActionId==="chat")}function xy(e){const t=sp(e.implementation);if(t?.type!==MA)return null;const n=eo(t.actionId)??e.id;return n?{actionId:n,actionLabel:e.label??e.name??n}:null}function EX({action:e,attachments:t=[],displayPrompt:n,prompt:a,sessionId:i}){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:Sy({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{},...i?{sessionId:i}:{}}}}function MX({action:e,attachments:t=[],displayPrompt:n,prompt:a,teamId:i}){return{teamId:i,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:Sy({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}}}}function jX({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:Sy({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}},workflowMode:e.workflowMode}}const Es=new Map;function ky(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function OX(e,t){const n=ky(e,t);if(!n)return null;const a=Es.get(n);return a?.updatedAt?a.projects:null}function $X(e,t,n){const a=ky(e,n);a&&Es.set(a,{projects:t,promise:null,updatedAt:Date.now()})}function NX(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=ky(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Es.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.projects);if(a?.promise)return a.promise}const i=e.fetchProjects(t).then(r=>($X(t,r,e.accountKey),r)).catch(r=>{const s=Es.get(n);throw s?.promise===i&&Es.set(n,{projects:s.projects,promise:null,updatedAt:s.updatedAt}),r});return Es.set(n,{projects:a?.projects??[],promise:i,updatedAt:a?.updatedAt??0}),i}function Mh(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 DX({cloudProjectById:e,cloudProjects:t,connection:n,defaultTeamId:a,accountScopeKey:i,localProjects:r,profile:s,selectedCloudProject:c,selectedProject:m,reportError:u}){const[h,g]=y.useState(null),[S,k]=y.useState([]),[C,A]=y.useState([]),M=y.useMemo(()=>{const E=new Set;a&&E.add(a);for(const L of t)E.add(L.teamId);for(const L of r){const z=t.find(H=>H.id===L.linkedSandboxProject?.projectId&&H.teamId===L.linkedSandboxProject?.teamId);z?.teamId&&E.add(z.teamId)}return[...E].sort()},[t,a,r]),R=M.join("\0"),$=y.useMemo(()=>TA({cloudProjects:t,selectedCloudProject:c,selectedProject:m}),[t,c,m]);y.useEffect(()=>{if(!n||M.length===0){A([]);return}let E=!1;const L=M.flatMap(z=>wA(z,i)??[]);return A(Mh(L)),Promise.all(M.map(z=>vy({teamId:z,accountKey:i,fetchAgents:async H=>(await Q.listSandboxAgents(n,{teamId:H})).agents}))).then(z=>{E||A(Mh(z.flat()))}).catch(()=>{E||A(Mh(L))}),()=>{E=!0}},[i,n,R]),y.useEffect(()=>{if(!n||!$){g(null);return}const E=OX($.teamId,i);E&&g(E.find(z=>z.id===$.id)??null);let L=!1;return NX({teamId:$.teamId,accountKey:i,fetchProjects:async z=>(await Q.listSandboxProjects(n,{teamId:z})).projects}).then(z=>{L||g(z.find(H=>H.id===$.id)??null)}).catch(()=>{L||g(null)}),()=>{L=!0}},[i,n,$?.id,$?.teamId]),y.useEffect(()=>{if(!n||!m){k([]);return}let E=!1;return Q.localProjectActions(n,m.id).then(L=>{E||k(L.actions)}).catch(L=>{E||(k([]),u?.(`Could not load Project Actions for ${m.name}: ${L instanceof Error?L.message:String(L)}`))}),()=>{E=!0}},[n,u,m?.id,m?.name,m?.updatedAt]);const O=y.useMemo(()=>{const E=new Map;for(const L of IX(h))E.set(L.id,L);for(const L of S)E.set(L.id,L);return[...E.values()]},[S,h]),j=y.useMemo(()=>TX(s),[s]),I=y.useMemo(()=>[...C.map(E=>RX(E,e.get(E.projectId)?.name??null)),...j,...O],[e,j,O,C]);return{openPondActionCatalog:y.useMemo(()=>[...j,...O],[j,O]),selectedActionCatalog:I,selectedProjectActionCatalog:O}}function HX({selectedProjectId:e}){const[t,n]=y.useState(()=>new Set),a=y.useCallback(r=>{n(s=>{if(s.has(r))return s;const c=new Set(s);return c.add(r),c})},[]),i=y.useCallback(r=>{n(s=>{const c=new Set(s);return c.has(r)?c.delete(r):c.add(r),c})},[]);return y.useEffect(()=>{e&&a(e)},[a,e]),{expandedProjectIds:t,expandProject:a,toggleProjectExpanded:i,setExpandedProjectIds:n}}function LX(){const e=new Map;function t(i,r){const s=e.get(i);if(s)return s.consumers+=1,n(i,s,!0);const c=new AbortController,m={controller:c,consumers:1,settled:!1,promise:Promise.resolve().then(()=>r(c.signal)).finally(()=>{m.settled=!0,e.get(i)===m&&e.delete(i)})};return e.set(i,m),n(i,m,!1)}function n(i,r,s){let c=!1;return{key:i,promise:r.promise,shared:s,release:()=>{c||(c=!0,r.consumers=Math.max(0,r.consumers-1),r.consumers===0&&!r.settled&&r.controller.abort())}}}function a(){for(const i of e.values())i.consumers=0,i.settled||i.controller.abort()}return{request:t,cancelAll:a,inFlightCount:()=>e.size}}function jh(e,t,n){return`workspace-status:${e.serverUrl}:${t}:${n?"ensure":"read"}`}function qX(e,t){return`workspace-diff:${e.serverUrl}:${t}`}function Oh(e){return e instanceof Error&&e.name==="AbortError"}function UX({connection:e,activeWorkspaceAppId:t,view:n,shouldLoadWorkspaceDiff:a,sidebarWorkspaceAppIds:i,setError:r}){const[s,c]=y.useState(null),[m,u]=y.useState({}),[h,g]=y.useState(null),[S,k]=y.useState(!1),[C,A]=y.useState(!1),M=y.useRef(new Set),R=y.useRef(new Set),$=y.useRef(LX()),O=t?m[t]??(s?.appId===t?s:null):null,j=h?.appId===t?h:null,I=n==="chat"||n==="labs",P=y.useCallback(z=>{M.current.add(z.appId),c(z),u(H=>({...H,[z.appId]:z}))},[]),E=y.useCallback(async(z,H=!1)=>{if(!e||!z)return c(null),null;k(!0);const J=$.current.request(jh(e,z,H),X=>Q.workspaceStatus(e,z,H,{signal:X}));try{const X=await J.promise;return P(X),H&&X.error?r(`Workspace sync failed: ${X.error}`):H&&r(null),X}catch(X){return Oh(X)||(c(null),r(X instanceof Error?X.message:String(X))),null}finally{J.release(),k(!1)}},[e,P,r]),L=y.useCallback(async(z=t,H={})=>{if(!e||!z)return g(null),null;H.silent||A(!0);const J=$.current.request(qX(e,z),X=>Q.workspaceDiff(e,z,{signal:X}));try{const X=await J.promise;return g(X),X}catch(X){return Oh(X)||(g(null),r(X instanceof Error?X.message:String(X))),null}finally{J.release(),H.silent||A(!1)}},[t,e,r]);return y.useEffect(()=>{if(!e||!t||!I){c(null),g(null),k(!1);return}let z=!1;const H=$.current.request(jh(e,t,!1),J=>Q.workspaceStatus(e,t,!1,{signal:J}));return k(!0),H.promise.then(J=>{z||(P(J),J.initialized||g(X=>X?.appId===J.appId?null:X))}).catch(J=>{Oh(J)||z||(c(null),r(J instanceof Error?J.message:String(J)))}).finally(()=>{H.release(),z||k(!1)}),()=>{z=!0,H.release()}},[t,e,P,r,I]),y.useEffect(()=>{if(!e||!t||!I){g(null);return}if(!O?.initialized){O&&!O.initialized&&g(z=>z?.appId===t?null:z);return}a&&L(t)},[t,e,L,a,I,O?.dirty,O?.initialized]),y.useEffect(()=>{if(!e||i.length===0)return;const z=i.filter(X=>!M.current.has(X)&&!R.current.has(X));if(z.length===0)return;z.forEach(X=>R.current.add(X));let H=!1;const J=z.map(X=>({appId:X,request:$.current.request(jh(e,X,!1),de=>Q.workspaceStatus(e,X,!1,{signal:de}))}));return Promise.all(J.map(({appId:X,request:de})=>de.promise.then(je=>({appId:X,state:je})).catch(()=>({appId:X,state:null})).finally(()=>{de.release(),R.current.delete(X)}))).then(X=>{if(!H)for(const de of X)de.state&&P(de.state)}),()=>{H=!0,J.forEach(({appId:X,request:de})=>{de.release(),R.current.delete(X)})}},[e,P,i]),y.useEffect(()=>()=>$.current.cancelAll(),[]),{workspaceState:s,workspaceStates:m,workspaceDiff:h,workspaceBusy:S,diffBusy:C,visibleWorkspaceState:O,visibleWorkspaceDiff:j,rememberWorkspaceState:P,refreshWorkspace:E,refreshWorkspaceDiff:L,setWorkspaceBusy:k}}const zX=1,BX=15e3,FX=15e3,jA=5*6e4,VX=5e3,KX=1e4;function OA(e,t=(a,i)=>new WebSocket(a,i),n={}){const a=new WX(e,t,n.reconnectDelayMs??GX);return a.open(),{close:()=>a.close()}}class WX{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=jA;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===zX)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-${JX(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."))},BX))},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 i=typeof a.type=="string"?a.type:"";if(i==="connection_ack"){this.connectionAckTimer&&clearTimeout(this.connectionAckTimer),this.connectionAckTimer=null,this.keepAliveTimeoutMs=YX(a.connectionTimeoutMs),this.lastKeepAliveAt=Date.now(),this.startKeepAliveMonitor(),this.subscribe(t);return}if(i==="ka"){this.lastKeepAliveAt=Date.now();return}if(i==="subscribe_success"){const r=typeof a.id=="string"?a.id:"";if(!this.subscriptionChannels.has(r))return;this.acknowledgedSubscriptions.add(r),this.markReadyWhenSubscribed();return}if(i==="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(i==="connection_error"||i==="subscribe_error"){const r=QX(a);if(this.reportError(r),i==="connection_error")this.failConnection(r,!1);else{const s=typeof a.id=="string"?a.id:"";this.subscriptionChannels.delete(s),this.acknowledgedSubscriptions.delete(s),this.markReadyWhenSubscribed()}}}subscribe(t){const n={Authorization:this.input.authorizationToken,host:new URL(this.input.httpUrl).host};for(const a of Array.from(new Set(this.input.channels))){const i=ZX();this.subscriptionChannels.set(i,a),t.send(JSON.stringify({type:"subscribe",id:i,channel:a,authorization:n}))}this.subscriptionAckTimer=setTimeout(()=>{this.failConnection(new Error("Team chat realtime subscription acknowledgement timed out."))},FX)}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."))},VX)}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 GX(e){const t=Math.min(KX,500*2**Math.min(e,5));return Math.max(100,Math.floor(Math.random()*t))}function JX(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 ZX(){return globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`}function YX(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:jA}function QX(e){const n=(Array.isArray(e.errors)?e.errors:[])[0];if(n&&typeof n=="object"){const a=n,i=typeof a.errorType=="string"?a.errorType:"RealtimeError",r=typeof a.message=="string"?a.message:"Request failed";return new Error(`${i}: ${r}`)}return new Error("Team chat realtime request failed.")}function XX(e,t,n){const a=[`/team-chat/users/${e.session.userId}/${e.session.teamId}`,...Array.from(new Set(e.threadIds)).map(i=>`/team-chat/threads/${i}`)];return OA({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:a,onEvent:i=>{const r=Sw.safeParse(i);r.success&&e.onEvent(r.data)},onReady:e.onReady,onError:e.onError},t,n)}function eee(e){return e.refs.find(t=>t.refType==="message_reply")??null}function tee(e){return{id:e.id,authorType:e.authorType,authorUserId:e.authorUserId,authorAgentId:e.authorAgentId,body:e.body,deleted:!!e.deletedAt}}function Kie(e,t){const n=eee(e);if(!n)return null;const a=t.get(n.refId);return a?tee(a):aee(n)}function nee(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 Wie(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 Gie(e){return e.deleted?"Message deleted":e.body.replace(/\s+/g," ").trim()||"Attachment"}function aee(e){const t=e.preview;return{id:e.refId,authorType:iee(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 iee(e){return e==="agent"||e==="system"?e:"user"}function uk(e,t,n){return n===t.conversationId?{...e,aiThread:t}:e}function oee(e,t){return!e||e.thread.id!==t.thread.id?t:{...t,messages:yd([...e.messages,...t.messages]),hasMoreBefore:e.messages.length>t.messages.length?e.hasMoreBefore:t.hasMoreBefore}}function $h(e,t){const n=Array.from(t.values()).filter(i=>i.threadId===e.thread.id);if(n.length===0)return e;let a=e.thread;for(const i of n)a=el(a,i,"message.created",!0,i.authorUserId);return{...e,thread:a,messages:yd([...e.messages,...n])}}function ree(e,t){const n=new Set(e.map(i=>i.lastMessage?.clientRequestId).filter(i=>!!i)),a=new Map;for(const i of t.values()){if(i.clientRequestId&&n.has(i.clientRequestId))continue;const r=a.get(i.threadId)??[];r.push(i),a.set(i.threadId,r)}return e.map(i=>{let r=i;for(const s of a.get(i.id)??[])r=el(r,s,"message.created",!0,s.authorUserId);return r}).sort((i,r)=>r.lastMessageAt.localeCompare(i.lastMessageAt))}function Nh(e,t,n){for(const a of e)!a.clientRequestId||a.id.startsWith("pending:")||(t.delete(a.clientRequestId),n.delete(a.clientRequestId))}function Dh(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,deliveryStatus:n}})}function mk(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,uploadProgress:n}})}function yd(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,i)=>a.sequence!==i.sequence?a.sequence-i.sequence:a.createdAt.localeCompare(i.createdAt))}function $A(e){return e.type!=="message.created"&&e.type!=="message.updated"&&e.type!=="message.deleted"?null:Bv.safeParse(e.payload.message).data??null}function NA(e,t,n){const a=$A(t);if(a){const i=e.selectedThreadId===a.threadId,r=e.detail?.thread.id===a.threadId?{...e.detail,thread:el(e.detail.thread,a,t.type,i,n),messages:yd([...e.detail.messages,a])}:e.detail,c=e.threads.some(m=>m.id===a.threadId)?e.threads.map(m=>m.id===a.threadId?el(m,a,t.type,i,n):m).sort((m,u)=>u.lastMessageAt.localeCompare(m.lastMessageAt)):e.threads;return{...e,detail:r,threads:c,error:null}}if(t.type==="read.updated"){const i=typeof t.payload.userId=="string"?t.payload.userId:null,r=Number(t.payload.sequence);if(!i||!Number.isSafeInteger(r)||r<0)return e;const s=c=>({...c,participants:c.participants.map(m=>m.userId===i?{...m,lastReadSequence:Math.max(m.lastReadSequence,r)}:m)});return{...e,threads:e.threads.map(c=>c.id===t.threadId?s(c):c),detail:e.detail?.thread.id===t.threadId?{...e.detail,thread:s(e.detail.thread)}:e.detail}}return e}function el(e,t,n,a,i){const r=n==="message.created",s=t.sequence>=e.lastMessageSequence;return{...e,lastMessageId:s?t.id:e.lastMessageId,lastMessageSequence:Math.max(e.lastMessageSequence,t.sequence),lastMessageAt:s?t.createdAt:e.lastMessageAt,updatedAt:s?t.createdAt:e.updatedAt,lastMessage:s?t:e.lastMessage,unreadCount:a||t.authorUserId===i?0:r?e.unreadCount+1:e.unreadCount}}function see(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:nee(e.replyToMessage),createdAt:t}]:[],attachments:e.attachments.map(a=>({id:a.id,messageId:null,clientAttachmentId:a.id,kind:"image",name:a.name,mediaType:a.mediaType,sizeBytes:a.sizeBytes,status:"pending",createdAt:t,readyAt:null}))}}function lee(e,t){const n=e.detail?.thread.id===t.threadId?{...e.detail,thread:el(e.detail.thread,t,"message.created",!0,t.authorUserId),messages:yd([...e.detail.messages,t])}:e.detail;return{...e,detail:n,threads:e.threads.map(a=>a.id===t.threadId?el(a,t,"message.created",!0,t.authorUserId):a).sort((a,i)=>i.lastMessageAt.localeCompare(a.lastMessageAt)),error:null}}function pk(e,t,n){return NA(e,{teamId:t.teamId,threadId:t.threadId,type:"message.created",payload:{message:t},createdAt:t.createdAt},n)}function cee(e,t){return Vg(e,t,"failed")}function Vg(e,t,n){const a=i=>i.clientRequestId===t&&i.id.startsWith("pending:")?{...i,metadata:{...i.metadata,deliveryStatus:n}}:i;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(i=>({...i,lastMessage:i.lastMessage?a(i.lastMessage):null}))}}function fk(e,t,n){const a=i=>i.clientRequestId===t&&i.id.startsWith("pending:")?{...i,metadata:{...i.metadata,uploadProgress:n}}:i;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(i=>({...i,lastMessage:i.lastMessage?a(i.lastMessage):null}))}}function dee(e,t){const n=e.detail?.messages.filter(r=>r.id!==t)??[],a=n.at(-1)??null,i=e.detail?{...e.detail,thread:e.detail.thread.lastMessageId===t?hk(e.detail.thread,a):e.detail.thread,messages:n}:null;return{...e,detail:i,threads:e.threads.map(r=>r.lastMessageId===t?hk(r,a):r)}}function uee(e){if(e.length>vr.maxAttachments)return null;const t=[];for(const n of e){if(n.kind!=="image"||!mee(n.mediaType)||!n.contentsBase64||n.sizeBytes<=0||n.sizeBytes>vr.maxAttachmentBytes)return null;t.push({...n,kind:"image",mediaType:n.mediaType,contentsBase64:n.contentsBase64})}return t}function hk(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 mee(e){return e==="image/png"||e==="image/jpeg"||e==="image/webp"||e==="image/gif"}const pee={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 fee(e){const t=e instanceof Error?e.message:String(e),n=t.trim().toLowerCase();for(const[a,i]of Object.entries(pee))if(n.includes(a))return i;return n.includes("event stream ended")?"Team chat realtime disconnected. Messages will continue to refresh automatically.":gA(t)}const DA="openpond.team-chat.notification-mode";function HA(){try{return typeof window>"u"?null:gd}catch{return null}}function gk(e=HA()){const t=e?.getItem(DA);return t==="direct_mentions"||t==="none"?t:"all"}function hee(e,t=HA()){try{t?.setItem(DA,e)}catch{}}function gee(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 vee(e){const t=e.message.authorUserId?e.members.find(s=>s.userId===e.message.authorUserId)?.name??"Team member":e.message.authorType==="agent"?"Agent":"Team",n=e.thread.title?.trim()||(e.thread.kind==="general"?"general":"conversation"),a=e.thread.kind==="dm"?t:`${t} in #${n}`,r=e.message.body.replace(/\s+/g," ").trim()||(e.message.attachments.length===1?"Sent an image":e.message.attachments.length>1?`Sent ${e.message.attachments.length} images`:"New message");return{eventId:e.eventId,threadId:e.message.threadId,title:a,body:r.length>160?`${r.slice(0,157)}…`:r}}const vk={members:[],agents:[],threads:[],selectedThreadId:null,detail:null,aiThread:null,agentConversation:null,loading:!1,busy:!1,error:null};function ou(e,t){return e.map(n=>n.id===t&&n.unreadCount!==0?{...n,unreadCount:0}:n)}function ru(e){return!e||e.thread.unreadCount===0?e:{...e,thread:{...e.thread,unreadCount:0}}}function bee(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedAgentId:e.conversation.agent.id,conversationId:e.conversation.conversationId}}function yee(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedActionKey:e.selectedActionKey,approvalId:e.approvalId??null}}async function bk(e,t=Q.markTeamChatRead){return e.lastMessageSequence<=0?!1:t(e.connection,e.threadId,e.teamId,e.lastMessageSequence).then(()=>!0,()=>!1)}function See(e){const[t,n]=y.useState(vk),a=y.useRef(t);a.current=t;const[i,r]=y.useState(gk);hd(()=>r(gk()));const[s,c]=y.useState(null),m=y.useRef(null),u=y.useRef(null),h=y.useRef(0),g=y.useRef(new Map),S=y.useRef(new Map),k=y.useRef(0),C=y.useRef(null),A=y.useRef(0),M=y.useRef(new Set),R=y.useRef(0),$=y.useRef(!1),O=y.useRef(new Map),j=y.useRef(new Map),[I,P]=y.useState(null),[E,L]=y.useState(null),z=y.useCallback(q=>{r(q),hee(q)},[]),H=y.useCallback(q=>{c(N=>N?.eventId===q?null:N)},[]),J=y.useCallback(async()=>{if(!e.connection||!e.teamId)return[];const q=await Q.teamChatThreads(e.connection,e.teamId),N=ree(q.threads,O.current);return n(F=>({...F,threads:N})),N},[e.connection,e.teamId]),X=y.useCallback(async()=>{if(!e.connection||!e.teamId)return{members:[],agents:[]};const[q,N]=await Promise.all([Q.teamChatMembers(e.connection,e.teamId),Q.teamChatAgents(e.connection,e.teamId)]);return n(F=>({...F,members:q.members,agents:N.agents})),{members:q.members,agents:N.agents}},[e.connection,e.teamId]),de=y.useCallback(async q=>{const N=q??m.current;if(!e.connection||!e.teamId||!N)return null;const F=(S.current.get(N)??0)+1;S.current.set(N,F);const ee=await Q.teamChatThread(e.connection,e.teamId,N);Nh(ee.messages,O.current,j.current);const me=$h(ee,O.current);return S.current.get(N)!==F||(n($e=>$e.selectedThreadId===N?{...$e,threads:ou($e.threads,N),detail:ru(oee($e.detail,me))}:$e),m.current===N&&me.thread.lastMessageSequence>0&&await Q.markTeamChatRead(e.connection,N,e.teamId,me.thread.lastMessageSequence).catch(()=>{})),me},[e.connection,e.teamId]),je=y.useCallback(async q=>{const N=q??u.current;if(!e.connection||!e.teamId||!N)return null;const F=(g.current.get(N)??0)+1;g.current.set(N,F);const ee=await Q.teamChatAiThread(e.connection,e.teamId,N);return g.current.get(N)===F&&u.current===N&&n(me=>uk(me,ee,u.current)),ee},[e.connection,e.teamId]),we=y.useCallback(async q=>{const N=q??C.current;if(!e.connection||!e.teamId||!N)return null;const F=await Q.teamChatAgentConversation(e.connection,e.teamId,N);return n(ee=>ee.agentConversation?.run.id===N?{...ee,agentConversation:F}:ee),F},[e.connection,e.teamId]);y.useEffect(()=>{m.current=t.selectedThreadId},[t.selectedThreadId]),y.useEffect(()=>{C.current=t.agentConversation?.run.id??null},[t.agentConversation?.run.id]),y.useEffect(()=>{const q=t.agentConversation?.run.status;if(!q||!["pending","queued","running"].includes(q))return;const N=window.setInterval(()=>{we().catch(F=>{n(ee=>({...ee,error:wn(F)}))})},2500);return()=>window.clearInterval(N)},[we,t.agentConversation?.run.status]),y.useEffect(()=>{if(!e.connection||!e.teamId||!e.currentUserId){n(vk),P(null),L(null),j.current.clear(),O.current.clear(),S.current.clear(),g.current.clear(),k.current+=1,c(null),M.current.clear(),R.current=0,A.current=0;return}let q=!1;return u.current=null,h.current+=1,k.current+=1,P(null),L(null),j.current.clear(),O.current.clear(),M.current.clear(),R.current=0,n(N=>({...N,aiThread:null,agentConversation:null,loading:!0,error:null})),(async()=>{try{const N=await Q.teamChatEvents(e.connection,e.teamId);if(q)return;A.current=N.cursor;const F=Q.teamChatMembers(e.connection,e.teamId),ee=Q.teamChatAgents(e.connection,e.teamId),me=await Q.teamChatGeneral(e.connection,e.teamId),[$e,ze,tt]=await Promise.all([F,ee,Q.teamChatThreads(e.connection,e.teamId)]);if(q)return;const nt=m.current&&tt.threads.some(Oe=>Oe.id===m.current)?m.current:me.thread.id,mt=nt===me.thread.id?me:await Q.teamChatThread(e.connection,e.teamId,nt);if(q)return;const vt=ru(mt);n(Oe=>({...Oe,members:$e.members,agents:ze.agents,threads:ou(tt.threads,nt),selectedThreadId:nt,detail:vt,loading:!1,error:null})),bk({connection:e.connection,teamId:e.teamId,threadId:nt,lastMessageSequence:vt?.thread.lastMessageSequence??0}),L(e.teamId)}catch(N){if(q)return;n(F=>({...F,loading:!1,error:wn(N)}))}})(),()=>{q=!0}},[e.connection,e.currentUserId,e.refreshToken,e.teamId]);const te=y.useCallback(q=>{if(M.current.has(q.id))return;if(M.current.add(q.id),M.current.size>2e3){const F=M.current.values().next().value;typeof F=="number"&&M.current.delete(F)}const N=$A(q);if(N&&q.type==="message.created"){const F=a.current,ee=F.threads.find($e=>$e.id===N.threadId)??(F.detail?.thread.id===N.threadId?F.detail.thread:null),me=$e=>{q.id<=R.current||gee({mode:i,currentUserId:e.currentUserId,message:N,thread:$e})&&(R.current=q.id,c(vee({eventId:q.id,message:N,thread:$e,members:F.members})))};ee?me(ee):J().then($e=>{const ze=$e.find(tt=>tt.id===N.threadId);ze&&me(ze)}).catch(()=>{})}N?.clientRequestId&&!N.id.startsWith("pending:")&&(O.current.delete(N.clientRequestId),j.current.delete(N.clientRequestId)),n(F=>NA(F,q,e.currentUserId)),q.type==="thread.created"&&J().catch(F=>{n(ee=>({...ee,error:wn(F)}))}),(q.type==="ai_thread.created"||q.type==="ai_turn.updated")&&(de(q.threadId).catch(F=>{n(ee=>({...ee,error:wn(F)}))}),q.conversationId===u.current&&je(q.conversationId).catch(F=>{n(ee=>({...ee,error:wn(F)}))})),N&&q.type==="message.created"&&m.current===N.threadId&&N.authorUserId!==e.currentUserId&&e.connection&&e.teamId&&Q.markTeamChatRead(e.connection,N.threadId,e.teamId,N.sequence).catch(()=>{})},[e.connection,e.currentUserId,e.teamId,i,je,de,J]),Me=y.useCallback(async()=>{if(!(!e.connection||!e.teamId||$.current)){$.current=!0;try{let q=!0;for(;q;){const N=await Q.teamChatEvents(e.connection,e.teamId,{after:A.current,limit:250});for(const F of N.events)te(F);A.current=N.cursor,q=N.hasMore}}finally{$.current=!1}}},[te,e.connection,e.teamId]);y.useEffect(()=>{if(!e.connection||!e.teamId||E!==e.teamId)return;let q=!1,N=null;const F=async()=>{try{const ee=await Q.teamChatRealtimeSession(e.connection,e.teamId);if(q||(await Me(),q))return;P(ee);const me=Math.max(3e4,new Date(ee.expiresAt).getTime()-Date.now()-3e4);N=window.setTimeout(()=>{F()},me)}catch{q||(Me().catch(()=>{}),N=window.setTimeout(()=>{F()},1e4))}};return F(),()=>{q=!0,N!==null&&window.clearTimeout(N),P(null)}},[Me,e.connection,e.teamId,E]);const Se=t.threads.map(q=>q.id).sort().join(",");y.useEffect(()=>{if(!I)return;const q=XX({session:I,threadIds:Se?Se.split(","):[],onEvent:te,onReady:()=>{Me().catch(N=>{n(F=>({...F,error:wn(N)}))})},onError:()=>{Me().catch(()=>{})}});return()=>{q.close()}},[te,Me,I,Se]),y.useEffect(()=>{if(!e.connection||!e.teamId||E!==e.teamId)return;const q=window.setInterval(()=>{Me().catch(()=>{})},15e3);return()=>window.clearInterval(q)},[Me,e.connection,e.teamId,E]);const oe=y.useCallback(async q=>{if(!e.connection||!e.teamId)return;const N=k.current+1;k.current=N;const F=m.current!==q;m.current=q,F&&(h.current+=1,u.current=null),n(ee=>({...ee,threads:ou(ee.threads,q),selectedThreadId:q,detail:ee.detail?.thread.id===q?ru(ee.detail):null,aiThread:F?null:ee.aiThread,agentConversation:F?null:ee.agentConversation,loading:!0,error:null}));try{const ee=await Q.teamChatThread(e.connection,e.teamId,q);if(k.current!==N||m.current!==q)return;Nh(ee.messages,O.current,j.current);const me=$h(ee,O.current);n($e=>({...$e,threads:ou($e.threads,q),detail:ru(me),loading:!1})),await Q.markTeamChatRead(e.connection,q,e.teamId,me.thread.lastMessageSequence).catch(()=>{})}catch(ee){if(k.current!==N)return;n(me=>({...me,loading:!1,error:wn(ee)}))}},[e.connection,e.teamId]),be=y.useCallback(async q=>{if(!e.connection||!e.teamId)return null;const N=k.current+1;k.current=N,n(F=>({...F,busy:!0,error:null}));try{const F=await Q.teamChatDm(e.connection,e.teamId,q);if(k.current!==N)return null;Nh(F.messages,O.current,j.current);const ee=$h(F,O.current),me=m.current!==ee.thread.id;return m.current=ee.thread.id,me&&(h.current+=1,u.current=null),n($e=>({...$e,selectedThreadId:ee.thread.id,detail:ee,aiThread:me?null:$e.aiThread,agentConversation:me?null:$e.agentConversation,busy:!1})),await bk({connection:e.connection,teamId:e.teamId,threadId:ee.thread.id,lastMessageSequence:ee.thread.lastMessageSequence}),await J(),ee}catch(F){return k.current!==N||n(ee=>({...ee,busy:!1,error:wn(F)})),null}},[e.connection,e.teamId,J]),re=y.useCallback(async()=>{const q=t.detail,N=q?.messages[0]?.sequence;if(!e.connection||!e.teamId||!q||!q.hasMoreBefore||N==null)return!1;n(F=>({...F,loading:!0,error:null}));try{const F=await Q.teamChatThread(e.connection,e.teamId,q.thread.id,{beforeSequence:N,limit:50});return n(ee=>{if(ee.detail?.thread.id!==q.thread.id)return ee;const me=[...F.messages,...ee.detail.messages];return{...ee,loading:!1,detail:{...ee.detail,messages:yd(me),hasMoreBefore:F.hasMoreBefore}}}),!0}catch(F){return n(ee=>({...ee,loading:!1,error:wn(F)})),!1}},[e.connection,e.teamId,t.detail]),ue=y.useCallback(async q=>{const N=m.current,F=uee(q.attachments??[]);if(!F)return n($e=>({...$e,error:"Team chat supports up to 10 PNG, JPEG, WebP, or GIF images per message."})),!1;if(!e.connection||!e.teamId||!N||!q.body.trim()&&F.length===0)return!1;if(q.replyToMessage&&(q.replyToMessage.threadId!==N||q.replyToMessage.teamId!==e.teamId||q.replyToMessage.id.startsWith("pending:")||q.replyToMessage.deletedAt))return n($e=>({...$e,error:"That message is no longer available to reply to."})),!1;if(q.useModel){if(F.length>0)return n(ze=>({...ze,error:"Images can be sent to the team thread with Use model turned off."})),!1;const $e=h.current;n(ze=>({...ze,busy:!0,error:null}));try{const ze=await Q.createTeamChatAiThread(e.connection,N,{teamId:e.teamId,body:q.body.trim(),clientRequestId:crypto.randomUUID(),providerId:q.providerId,modelId:q.modelId}),tt=h.current===$e&&m.current===N;return tt&&(h.current+=1,u.current=ze.conversationId),n(nt=>({...nt,aiThread:tt?ze:nt.aiThread})),ze.activeTurn&&await Q.executeTeamChatAiTurn(e.connection,ze.activeTurn.id,e.teamId),await Promise.all([de(N),J()]),n(nt=>({...nt,busy:!1})),!0}catch(ze){return n(tt=>({...tt,busy:!1,error:wn(ze)})),!1}}const ee=crypto.randomUUID();if(q.selectedActionKey){if(F.length>0)return n($e=>({...$e,error:"Agent invocations do not support image attachments yet."})),!1;n($e=>({...$e,busy:!0,error:null}));try{return await Q.createTeamChatAgentRun(e.connection,N,yee({teamId:e.teamId,body:q.body,clientRequestId:ee,selectedActionKey:q.selectedActionKey,approvalId:q.approvalId})),await Promise.all([de(N),J()]),n($e=>({...$e,busy:!1})),!0}catch($e){return n(ze=>({...ze,busy:!1,error:wn($e)})),!1}}j.current.set(ee,{inputs:F,uploaded:null});const me=see({clientRequestId:ee,threadId:N,teamId:e.teamId,userId:e.currentUserId,body:q.body.trim(),mentionUserIds:q.mentionUserIds??[],attachments:F,replyToMessage:q.replyToMessage,sequence:(t.detail?.thread.lastMessageSequence??0)+1});O.current.set(ee,me),n($e=>lee($e,me));try{const $e=[];for(const[nt,mt]of F.entries())$e.push(await Q.uploadTeamChatAttachment(e.connection,N,{teamId:e.teamId,attachment:mt})),mk(O.current,ee,`${nt+1} of ${F.length}`),n(vt=>fk(vt,ee,`${nt+1} of ${F.length}`));const ze=j.current.get(ee);ze&&(ze.uploaded=$e);const tt=await Q.sendTeamChatMessage(e.connection,N,{teamId:e.teamId,body:q.body.trim(),clientRequestId:ee,mentionUserIds:q.mentionUserIds,attachmentIds:$e.map(nt=>nt.id),replyToMessageId:q.replyToMessage?.id??null});return j.current.delete(ee),O.current.delete(ee),n(nt=>pk(nt,tt,e.currentUserId)),!0}catch($e){return Dh(O.current,ee,"failed"),n(ze=>({...cee(ze,ee),error:wn($e)})),!1}},[e.connection,e.currentUserId,e.teamId,de,J,t.detail?.thread.lastMessageSequence]),ke=y.useCallback(async q=>{if(!(!e.connection||!e.teamId)){h.current+=1,u.current=q,n(N=>({...N,aiThread:N.aiThread?.conversationId===q?N.aiThread:null,busy:!0,error:null}));try{const N=await Q.teamChatAiThread(e.connection,e.teamId,q);if(u.current!==q)return;n(F=>({...F,aiThread:N,busy:!1}))}catch(N){if(u.current!==q)return;n(F=>({...F,busy:!1,error:wn(N)}))}}},[e.connection,e.teamId]),Le=y.useCallback(async q=>{if(!(!e.connection||!e.teamId)){C.current=q,n(N=>({...N,busy:!0,error:null}));try{const N=await Q.teamChatAgentConversation(e.connection,e.teamId,q);n(F=>({...F,agentConversation:N,busy:!1}))}catch(N){n(F=>({...F,busy:!1,error:wn(N)}))}}},[e.connection,e.teamId]),Ie=y.useCallback(()=>{C.current=null,n(q=>({...q,agentConversation:null}))},[]),le=y.useCallback(async q=>{const N=m.current,F=t.agentConversation;if(!e.connection||!e.teamId||!N||!F||!q.body.trim())return!1;n(ee=>({...ee,busy:!0,error:null}));try{const ee=await Q.createTeamChatAgentRun(e.connection,N,bee({teamId:e.teamId,body:q.body,clientRequestId:q.clientRequestId,conversation:F}));C.current=ee.run.id;const[me]=await Promise.all([Q.teamChatAgentConversation(e.connection,e.teamId,ee.run.id),de(N),J()]);return n($e=>({...$e,agentConversation:me,busy:!1})),!0}catch(ee){return n(me=>({...me,busy:!1,error:wn(ee)})),!1}},[e.connection,e.teamId,de,J,t.agentConversation]),xe=y.useCallback(()=>{h.current+=1,u.current=null,n(q=>({...q,aiThread:null}))},[]),Ue=y.useCallback(async q=>{const N=u.current;if(!e.connection||!e.teamId||!N||!q.body.trim())return!1;n(F=>({...F,busy:!0,error:null}));try{const F=await Q.sendTeamChatAiTurn(e.connection,N,{teamId:e.teamId,body:q.body.trim(),clientRequestId:crypto.randomUUID(),providerId:q.providerId,modelId:q.modelId});return n(ee=>({...uk(ee,F,u.current),busy:!1})),F.activeTurn&&await Q.executeTeamChatAiTurn(e.connection,F.activeTurn.id,e.teamId),!0}catch(F){return n(ee=>({...ee,busy:!1,error:wn(F)})),!1}},[e.connection,e.teamId]),Ze=y.useCallback(async()=>{const q=t.aiThread?.activeTurn?.id;return!e.connection||!e.teamId||!q?!1:(await Q.cancelTeamChatAiTurnExecution(e.connection,q,e.teamId)).cancelled},[e.connection,e.teamId,t.aiThread?.activeTurn?.id]),it=y.useCallback(async(q,N)=>{if(!e.connection||!e.teamId)return!1;try{return await Q.editTeamChatMessage(e.connection,q.threadId,q.id,{teamId:e.teamId,body:N}),await de(q.threadId),!0}catch(F){return n(ee=>({...ee,error:wn(F)})),!1}},[e.connection,e.teamId,de]),at=y.useCallback(async q=>{if(!e.connection||!e.teamId)return!1;try{return await Q.deleteTeamChatMessage(e.connection,q.threadId,q.id,e.teamId),await de(q.threadId),!0}catch(N){return n(F=>({...F,error:wn(N)})),!1}},[e.connection,e.teamId,de]),Ne=y.useCallback(async q=>{if(!e.connection||!e.teamId||!q.clientRequestId||!q.id.startsWith("pending:"))return!1;const N=Array.isArray(q.metadata.mentionUserIds)?q.metadata.mentionUserIds.filter(me=>typeof me=="string"):[],F=j.current.get(q.clientRequestId),ee=q.refs.find(me=>me.refType==="message_reply");Dh(O.current,q.clientRequestId,"sending"),n(me=>Vg(me,q.clientRequestId,"sending"));try{let me=F?.uploaded??[];if(F&&!F.uploaded){me=[];for(const[ze,tt]of F.inputs.entries())me.push(await Q.uploadTeamChatAttachment(e.connection,q.threadId,{teamId:e.teamId,attachment:tt})),mk(O.current,q.clientRequestId,`${ze+1} of ${F.inputs.length}`),n(nt=>fk(nt,q.clientRequestId,`${ze+1} of ${F.inputs.length}`));F.uploaded=me}const $e=await Q.sendTeamChatMessage(e.connection,q.threadId,{teamId:e.teamId,body:q.body,clientRequestId:q.clientRequestId,mentionUserIds:N,attachmentIds:me.map(ze=>ze.id),replyToMessageId:ee?.refId??null});return j.current.delete(q.clientRequestId),O.current.delete(q.clientRequestId),n(ze=>pk(ze,$e,e.currentUserId)),!0}catch(me){return Dh(O.current,q.clientRequestId,"failed"),n($e=>({...Vg($e,q.clientRequestId,"failed"),error:wn(me)})),!1}},[e.connection,e.currentUserId,e.teamId]),We=y.useCallback(q=>{q.id.startsWith("pending:")&&(q.clientRequestId&&j.current.delete(q.clientRequestId),q.clientRequestId&&O.current.delete(q.clientRequestId),n(N=>dee(N,q.id)))},[]),qe=y.useCallback(async(q,N)=>{if(!e.connection||!e.teamId)return!1;try{const F=await Q.setTeamChatThreadMuted(e.connection,q,e.teamId,N),ee=me=>me.id===F.threadId?{...me,mutedAt:F.mutedAt}:me;return n(me=>({...me,threads:me.threads.map(ee),detail:me.detail?.thread.id===F.threadId?{...me.detail,thread:ee(me.detail.thread)}:me.detail,error:null})),!0}catch(F){return n(ee=>({...ee,error:wn(F)})),!1}},[e.connection,e.teamId]);return{...t,currentUserId:e.currentUserId,notificationMode:i,incomingNotification:s,setNotificationMode:z,dismissIncomingNotification:H,setThreadMuted:qe,selectThread:oe,openDm:be,loadMoreMessages:re,sendMessage:ue,openAiThread:ke,openAgentConversation:Le,closeAgentConversation:Ie,sendAgentTurn:le,closeAiThread:xe,sendAiTurn:Ue,stopAiTurn:Ze,editMessage:it,deleteMessage:at,retryMessage:Ne,dismissFailedMessage:We,refreshDirectory:X,refresh:async()=>{await Promise.all([X(),J(),de(),je(),we()])}}}function wn(e){return fee(e)}const LA="local-profile-agent";function Jie(e){const t=e.profile;if(!t||t.mode!=="local")return e.hostedActions;const n=new Set(e.hostedActions.flatMap(s=>{const c=s.implementation;return c?.type!=="openpond-agent"||c.profileName!==t.activeProfile?[]:[pr(c.agentName),pr(s.name),pr(s.label)].filter(Boolean)})),a=t.hosted?.teamId===e.teamId?t.hosted.hostedSourceMaterialization:null,i=new Set(e.hostedActions.map(s=>s.implementation?.agentId).filter(s=>typeof s=="string")),r=t.agents.flatMap(s=>s.enabled?a?.agentId===s.id&&!!(a.runtimeAgentId&&i.has(a.runtimeAgentId))||n.has(pr(s.name))||n.has(pr(s.id))?[]:[Iee(t,s)]:[]);return[...e.hostedActions,...r]}function Zie(e){return e?.implementation?.type===LA}function Yie(e){const t=e.implementation?.profileAgentId;return typeof t=="string"&&t.trim()?t.trim():null}function xee(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 kee(e,t){const n=t.runtimeAgentId?.trim()??"",a=t.profileName?.trim()??"",i=pr(t.agentName);return e.find(r=>{const s=r.implementation;return s?.type!=="openpond-agent"?!1:n&&typeof s.agentId=="string"&&s.agentId===n?!0:!!(a&&s.profileName===a&&i&&[s.agentName,r.name,r.label].some(c=>pr(c)===i))})??null}function Iee(e,t){return{id:`local-profile:${e.activeProfile??"default"}:${t.id}:chat`,name:t.name,label:t.name,description:wee(e),approvalPolicy:{required:!1,risk:"write"},setupRequirements:e.setupGate.blockingRequirements,invokesModel:!0,implementation:{type:LA,profileAgentId:t.id,profileName:e.activeProfile??"default"}}}function wee(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 pr(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""):""}const yk=5;function _ee(e){return y.useCallback(async t=>{if(!e.connection||!e.teamId)throw new Error("Connect OpenPond to a Team before publishing an agent.");const n=await Q.profileCheck(e.connection,{kind:"all"}),a=xee(n,t);if(a)throw new Error(a);const i=n?.agents.find(u=>u.id===t);if(!i)throw new Error(`Profile agent not found: ${t}`);const s=(await Q.profilePush(e.connection,{teamId:e.teamId,ensureHosted:!0,hostedSourceAgentId:t,message:null})).localProfile?.hosted?.hostedSourceMaterialization,c=s?.agentId===t?s.runtimeAgentId:null;e.applyBootstrapPayload(await Q.bootstrap(e.connection));let m=null;for(let u=0;u<yk;u+=1){const h=await e.refreshDirectory();if(m=kee(h.agents,{runtimeAgentId:c,profileName:n.activeProfile,agentName:i.name}),m)break;u<yk-1&&await Cee(200*(u+1))}if(!m)throw new Error(`${i.name} was published, but the Team agent directory has not refreshed yet. Retry the mention in a moment.`);return m},[e.applyBootstrapPayload,e.connection,e.refreshDirectory,e.teamId])}function Cee(e){return new Promise(t=>{setTimeout(t,e)})}function Ree(e){y.useEffect(()=>{if(!e.notification)return;const{eventId:t,threadId:n,title:a,body:i}=e.notification;e.showToast(`${a}: ${i}`,"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 Pee(e){const{connection:t,refreshToken:n=null}=e,[a,i]=y.useState([]),[r,s]=y.useState(null),[c,m]=y.useState(null),[u,h]=y.useState(null),[g,S]=y.useState(!1),[k,C]=y.useState(!1),[A,M]=y.useState(!1),[R,$]=y.useState(null),[O,j]=y.useState(null),[I,P]=y.useState(null),[E,L]=y.useState(0),z=y.useRef(0),H=y.useMemo(()=>a.find(re=>re.id===c)??null,[a,c]),J=y.useCallback(async()=>{if(!t)return!1;S(!0),$(null);try{const re=await Q.communities(t);return i(re.items),s(re.nextCursor),m(ue=>ue&&re.items.some(ke=>ke.id===ue)?ue:null),!0}catch(re){return $(Au(re)),!1}finally{S(!1)}},[t]),X=y.useCallback(async()=>{if(!t||!r||g)return!1;S(!0),$(null);try{const re=await Q.communities(t,r);return i(ue=>Aee(ue,re.items)),s(re.nextCursor),!0}catch(re){return $(Au(re)),!1}finally{S(!1)}},[t,g,r]),de=y.useCallback(async re=>{if(!t)return null;const ue=++z.current;C(!0),j(null);try{const ke=await Q.communityPreview(t,re.slug);return z.current===ue&&h(ke),ke}catch(ke){return z.current===ue&&j(Au(ke)),null}finally{z.current===ue&&C(!1)}},[t]),je=y.useCallback(re=>{const ue=a.find(ke=>ke.id===re);ue&&(m(ue.id),h(ke=>ke?.id===ue.id?ke:null),P(null),de(ue))},[a,de]),we=y.useCallback(()=>{z.current+=1,m(null),h(null),j(null),P(null)},[]);y.useEffect(()=>{if(!t){i([]),h(null),m(null);return}J()},[t,J,n]),y.useEffect(()=>{!H||u?.id===H.id||k||de(H)},[de,u?.id,k,H]);const te=y.useCallback(async()=>{const re=H;await J(),re&&await de(re)},[de,J,H]),Me=y.useCallback(async()=>{if(!t||!u?.currentRules||A)return!1;M(!0),P(null);try{return await Q.joinCommunity(t,u.id,u.currentRules.id),L(re=>re+1),await te(),!0}catch(re){const ue=su(re);return P(ue),ue.kind==="rules_stale"&&await te(),!1}finally{M(!1)}},[t,A,u,te]),Se=y.useCallback(async()=>{if(!t||!u?.currentRules||A)return!1;M(!0),P(null);try{return await Q.acceptCommunityRules(t,u.id,u.currentRules.id),L(re=>re+1),await te(),!0}catch(re){const ue=su(re);return P(ue),ue.kind==="rules_stale"&&await te(),!1}finally{M(!1)}},[t,A,u,te]),oe=y.useCallback(async()=>{if(!t||!u||A)return!1;M(!0),P(null);try{return await Q.leaveCommunity(t,u.id),L(re=>re+1),await te(),!0}catch(re){return P(su(re)),!1}finally{M(!1)}},[t,A,u,te]),be=y.useCallback(async re=>{if(!t||!u||A)return!1;M(!0),P(null);try{return await Q.updateCommunityNotifications(t,u.id,re),i(ue=>ue.map(ke=>ke.id===u.id&&ke.membership?{...ke,membership:{...ke.membership,notificationMode:re}}:ke)),h(ue=>ue?.id===u.id&&ue.membership?{...ue,membership:{...ue.membership,notificationMode:re}}:ue),!0}catch(ue){return P(su(ue)),!1}finally{M(!1)}},[t,A,u]);return{items:a,nextCursor:r,selectedCommunityId:c,selectedSummary:H,preview:u,discoveryLoading:g,previewLoading:k,membershipBusy:A,discoveryError:R,previewError:O,membershipError:I,membershipVersion:E,refresh:J,loadMore:X,showDiscovery:we,selectCommunity:je,join:Me,acceptRules:Se,leave:oe,updateNotifications:be,clearMembershipError:()=>P(null)}}function Aee(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 Au(e){return e instanceof Error?e.message:String(e)}function su(e){const t=Au(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 Tee(e,t,n){return OA({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:[e.session.channel],onEvent:a=>{const i=Aw.safeParse(a);i.success&&e.onEvent(i.data)},onReady:e.onReady,onError:e.onError},t,n)}function Eee(e){const{connection:t,preview:n,currentUserId:a,membershipVersion:i}=e,r=n?.id??null,s=n?.membership?.status==="active",c=!n?.capabilities.requiresRulesAcceptance,[m,u]=y.useState([]),[h,g]=y.useState(null),[S,k]=y.useState({}),[C,A]=y.useState([]),[M,R]=y.useState(!1),[$,O]=y.useState(!1),[j,I]=y.useState(!1),[P,E]=y.useState(!1),[L,z]=y.useState(null),[H,J]=y.useState(null),[X,de]=y.useState(null),[je,we]=y.useState(null),[te,Me]=y.useState(!1),[Se,oe]=y.useState(null),[be,re]=y.useState(null),ue=y.useRef(null),ke=y.useRef([]),Le=y.useRef("mentions"),Ie=y.useRef(0),le=y.useRef({}),xe=y.useRef(new Set),Ue=y.useMemo(()=>m.find(Oe=>Oe.id===h)??null,[m,h]),Ze=h?S[h]??null:null;y.useEffect(()=>{ue.current=h},[h]),y.useEffect(()=>{ke.current=m},[m]),y.useEffect(()=>{Le.current=n?.membership?.notificationMode??"mentions"},[n?.membership?.notificationMode]);const it=y.useCallback(async()=>{if(!t||!r)return!1;R(!0),z(null);try{const Oe=await Q.communityChannels(t,r);return u(Oe.channels),g(Ye=>Ye&&Oe.channels.some(f=>f.id===Ye)?Ye:Oe.channels.find(f=>f.isDefault)?.id??Oe.channels[0]?.id??null),Me(!1),!0}catch(Oe){const Ye=ya(Oe);return z(Ye),Kl(Ye)&&Me(!0),!1}finally{R(!1)}},[r,t]),at=y.useCallback(async Oe=>{if(!t||!r)return!1;const Ye=++Ie.current;O(!0),J(null);try{const f=await Q.communityMessages(t,r,Oe,{limit:50});return Ye!==Ie.current?!1:(k(U=>({...U,[Oe]:{items:f.messages,hasMoreBefore:f.hasMoreBefore,preview:f.preview}})),Me(!1),!0)}catch(f){if(Ye!==Ie.current)return!1;const U=ya(f);return J(U),Kl(U)&&Me(!0),!1}finally{Ye===Ie.current&&O(!1)}},[r,t]);y.useEffect(()=>{u(n?.channels??[]),k({}),g(n?.channels.find(Oe=>Oe.isDefault)?.id??n?.channels[0]?.id??null),z(null),J(null),de(null),Me(!1),xe.current.clear(),r&&it()},[r,it,i]),y.useEffect(()=>{h&&at(h)},[at,h]);const Ne=y.useCallback(async(Oe,Ye)=>{if(!t||!r||!s||!c||Ye<=0)return!1;if((le.current[Oe]??0)>=Ye)return!0;le.current[Oe]=Ye;try{const f=await Q.markCommunityRead(t,r,Oe,Ye);return u(U=>U.map(Y=>Y.id===Oe?{...Y,unreadCount:0,readState:Y.readState?{...Y.readState,lastReadSequence:f.sequence,lastReadAt:new Date().toISOString()}:{lastReadSequence:f.sequence,lastReadAt:new Date().toISOString(),mutedAt:null,pinnedAt:null}}:Y)),!0}catch(f){const U=ya(f);return Kl(U)&&Me(!0),!1}},[r,t,s,c]);y.useEffect(()=>{const Oe=Ze?.items.at(-1)?.sequence??0;h&&Oe>0&&Ne(h,Oe)},[Ne,h,Ze?.items]);const We=y.useCallback(Oe=>{if(Oe.communityId!==r||xe.current.has(Oe.id))return;xe.current.add(Oe.id);const Ye=Pw.safeParse(Oe.payload.message);if(Ye.success&&Oe.type!=="read.updated"){const f=Ye.data;if(k(U=>{const Y=U[Oe.channelId];if(!Y)return U;const se=Y.items.some(G=>G.id===f.id)?Y.items.map(G=>G.id===f.id?f:G):[...Y.items,f].sort((G,_)=>G.sequence-_.sequence);return{...U,[Oe.channelId]:{...Y,items:se}}}),u(U=>U.map(Y=>Y.id===Oe.channelId?{...Y,lastMessageSequence:Math.max(Y.lastMessageSequence,f.sequence),unreadCount:ue.current===Oe.channelId||f.authorUserId===a?0:Math.max(Y.unreadCount+(Oe.type==="message.created"?1:0),0)}:Y)),Oe.type==="message.created"&&f.authorUserId!==a){const U=ke.current.find(se=>se.id===Oe.channelId),Y=Mee(f).includes(a??""),ge=Le.current;!U?.readState?.mutedAt&&(ge==="all"||ge==="mentions"&&Y)&&re({communityId:Oe.communityId,channelId:Oe.channelId,message:f})}ue.current===Oe.channelId&&Ne(Oe.channelId,f.sequence);return}Oe.type==="read.updated"&&Oe.payload.userId===a&&it()},[r,a,it,Ne]);y.useEffect(()=>{if(!t||!r||!s||!c)return;let Oe=!1,Ye=null;return de(null),Promise.all([Q.communityRealtimeSession(t,r),Q.communityEvents(t,r)]).then(async([f,U])=>{if(Oe)return;const Y=async()=>{let se=U.cursor;for(;;){const G=await Q.communityEvents(t,r,{after:se,limit:200});if(Oe)return;for(const _ of G.events)We(_);if(se=G.cursor,!G.hasMore)return}},ge=Tee({session:f,onEvent:We,onReady:()=>{de(null),Y().catch(se=>de(ya(se)))},onError:se=>de(ya(se))});Ye=()=>ge.close(),await Y()}).catch(f=>{if(!Oe){const U=ya(f);de(U),Kl(U)&&Me(!0)}}),()=>{Oe=!0,Ye?.()}},[We,r,t,s,i,c]);const qe=y.useCallback(async()=>{if(!t||!r||!h||j)return!1;const Oe=S[h],Ye=Oe?.items[0]?.sequence;if(!Oe?.hasMoreBefore||Ye==null)return!1;I(!0),J(null);try{const f=await Q.communityMessages(t,r,h,{beforeSequence:Ye,limit:50});return k(U=>{const Y=U[h]??Oe,ge=new Set(Y.items.map(se=>se.id));return{...U,[h]:{...Y,items:[...f.messages.filter(se=>!ge.has(se.id)),...Y.items],hasMoreBefore:f.hasMoreBefore}}}),!0}catch(f){return J(ya(f)),!1}finally{I(!1)}},[r,t,S,j,h]),q=y.useCallback(async Oe=>{if(!t||!r||!h||P)return!1;E(!0),we(null),oe(null);try{const Ye=await Promise.all(Oe.attachments.map(U=>Q.uploadCommunityAttachment(t,r,h,U))),f=await Q.sendCommunityMessage(t,r,h,{body:Oe.body,clientRequestId:Oe.clientRequestId,mentionUserIds:Oe.mentionUserIds,attachmentIds:Ye.map(U=>U.id),replyToMessageId:Oe.replyToMessageId});return k(U=>{const Y=U[h]??{items:[],hasMoreBefore:!1,preview:!1};return Y.items.some(ge=>ge.id===f.id)?U:{...U,[h]:{...Y,items:[...Y.items,f]}}}),await Ne(h,f.sequence),!0}catch(Ye){const f=ya(Ye);return we(f),oe({...Oe,message:f}),Kl(f)&&Me(!0),!1}finally{E(!1)}},[r,t,Ne,h,P]),N=y.useCallback(Oe=>q({body:Oe.body,clientRequestId:crypto.randomUUID(),mentionUserIds:Oe.mentionUserIds??[],attachments:Oe.attachments??[],replyToMessageId:Oe.replyToMessageId??null}),[q]),F=y.useCallback(async(Oe,Ye)=>{if(!t||!r||!h)return!1;we(null);try{const f=await Q.editCommunityMessage(t,r,h,Oe,Ye);return Sk(k,h,f),!0}catch(f){return we(ya(f)),!1}},[r,t,h]),ee=y.useCallback(async Oe=>{if(!t||!r||!h)return!1;we(null);try{const Ye=await Q.deleteCommunityMessage(t,r,h,Oe);return Sk(k,h,Ye),!0}catch(Ye){return we(ya(Ye)),!1}},[r,t,h]),me=y.useCallback(async(Oe,Ye)=>{if(!t||!r)return!1;we(null);try{const f=await Q.setCommunityChannelMuted(t,r,Oe,Ye);return u(U=>U.map(Y=>Y.id===Oe&&Y.readState?{...Y,readState:{...Y.readState,mutedAt:f.mutedAt}}:Y)),!0}catch(f){return we(ya(f)),!1}},[r,t]),$e=y.useCallback(async(Oe="")=>{if(!t||!r||!s)return[];try{const Ye=await Q.searchCommunityMembers(t,r,{query:Oe,limit:50});return A(f=>jee(f,Ye.items)),Ye.items}catch(Ye){return we(ya(Ye)),[]}},[r,t,s]);y.useEffect(()=>{s&&c?$e():A([])},[s,c,$e]);const ze=y.useCallback(async Oe=>{if(!t||!r||!h)return!1;try{const Ye=await Q.communityAttachmentDownload(t,r,h,Oe);return window.open(Ye.url,"_blank","noopener,noreferrer"),!0}catch(Ye){return we(ya(Ye)),!1}},[r,t,h]),tt=y.useCallback(()=>h?at(h):Promise.resolve(!1),[at,h]),nt=y.useCallback(()=>Se?q(Se):Promise.resolve(!1),[Se,q]),mt=y.useCallback(()=>oe(null),[]),vt=y.useCallback(()=>re(null),[]);return{channels:m,selectedChannelId:h,selectedChannel:Ue,messages:Ze?.items??[],hasMoreBefore:Ze?.hasMoreBefore??!1,previewMode:Ze?.preview??!s,members:C,channelsLoading:M,messagesLoading:$,olderMessagesLoading:j,sending:P,channelsError:L,messagesError:H,realtimeError:X,actionError:je,lostMembership:te,failedSend:Se,incomingNotification:be,selectChannel:g,loadChannels:it,loadMessages:tt,loadOlder:qe,sendMessage:N,retrySend:nt,dismissFailedSend:mt,editMessage:F,deleteMessage:ee,setMuted:me,searchMembers:$e,downloadAttachment:ze,dismissIncomingNotification:vt}}function Sk(e,t,n){e(a=>{const i=a[t];return i?{...a,[t]:{...i,items:i.items.map(r=>r.id===n.id?n:r)}}:a})}function Mee(e){const t=e.metadata.mentionUserIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function jee(e,t){const n=new Map(e.map(a=>[a.userId,a]));for(const a of t)n.set(a.userId,a);return[...n.values()].slice(-200)}function Kl(e){return e.includes("community_membership_required")||e.includes("community_rules")}function ya(e){return e instanceof Error?e.message:String(e)}function Oee(e){const t=Pee({connection:e.connection,refreshToken:e.refreshToken}),n=Eee({connection:e.connection,preview:t.preview,currentUserId:e.currentUserId,membershipVersion:t.membershipVersion}),a=n.incomingNotification,i=t.items,r=n.channels,s=t.selectCommunity,c=n.selectChannel,m=n.dismissIncomingNotification,{setView:u,showToast:h}=e,g=y.useCallback(()=>{t.showDiscovery(),u("community")},[t.showDiscovery,u]),S=y.useCallback(C=>{t.selectCommunity(C),u("community")},[t.selectCommunity,u]),k=y.useCallback(C=>{n.selectChannel(C),u("community")},[n.selectChannel,u]);return y.useEffect(()=>{if(!a)return;const C=i.find(M=>M.id===a.communityId),A=r.find(M=>M.id===a.channelId);h(`${C?.displayName??"Community"} · #${A?.displayName??"channel"}: ${a.message.body.slice(0,120)||"New message"}`,"info",{actionLabel:"View",onAction:()=>{s(a.communityId),c(a.channelId),u("community")},placement:"top-right"}),m()},[r,i,m,a,c,s,u,h]),{communities:t,chat:n,sidebar:{communityItems:t.items,communityChannels:n.channels,communityLoading:t.discoveryLoading,communityError:t.discoveryError,selectedCommunityId:t.selectedCommunityId,selectedCommunityChannelId:n.selectedChannelId,discoverCommunities:g,selectCommunity:S,selectCommunityChannel:k},view:{communities:t,chat:n,currentUserId:e.currentUserId}}}const $ee=[];function Nee(e){const t=y.useCallback(a=>mJ(e,a),[e]),n=y.useCallback(()=>dJ(e)??$ee,[e]);return y.useSyncExternalStore(t,n,n)}function Dee(e){const[t,n]=y.useState(()=>Yf());return y.useEffect(()=>{let a=!0;return e?(Q.connectedAppStatus(e,{status:"all"}).then(i=>{a&&n(i.apps)}).catch(i=>{console.warn("Unable to load connected app mention status.",i),a&&n(Yf())}),()=>{a=!1}):(n(Yf()),()=>{a=!1})},[e]),t}function Hee(){const{composerDraftStore:e,dispatch:t,setters:n,state:a}=tX(),[i,r]=y.useState(null),[s,c]=y.useState([]),[m,u]=y.useState(null),[h,g]=y.useState(null),[S,k]=y.useState([]),[C,A]=y.useState(null),[M,R]=y.useState(null),[$,O]=y.useState(FP),[j,I]=y.useState({}),[P,E]=y.useState(()=>new Set),L=y.useCallback((ot,Kt)=>{E(Wt=>{if(Wt.has(ot)===Kt)return Wt;const Gt=new Set(Wt);return Kt?Gt.add(ot):Gt.delete(ot),Gt})},[]),[z,H]=y.useState(0),[J,X]=y.useState(null),de=y.useRef(null),{confirmProjectAction:je,projectConfirmDialog:we,resolveProjectConfirmDialog:te}=t7(),{query:Me,searchOpen:Se,archivedChatsOpen:oe,sectionMenuOpen:be,projectsExpanded:re,cloudProjectsExpanded:ue,chatRowsVisibleCount:ke,sidebarOpen:Le,view:Ie,selectedAppId:le,selectedProjectId:xe,selectedSessionId:Ue,draftProvider:Ze,draftModel:it,draftExperience:at,codexPermissionMode:Ne,codexReasoningEffort:We,openPondCommandAccessMode:qe,busy:q,diffPanelOpen:N,diffPanelExpanded:F,rightPanelMode:ee,rightChatPanels:me,terminalOpen:$e,settingsSection:ze,newProjectDialogOpen:tt,newProjectMode:nt,newProjectName:mt,newProjectPath:vt,newProjectBusy:Oe,commitDialogOpen:Ye,commitMessage:f,commitIncludeUnstaged:U,commitNextStep:Y,commitDraft:ge,branchDialogOpen:se,branchDialogName:G,toast:_,error:W}=a,ne=rX(Ie==="labs"),{setQuery:Z,setSearchOpen:ce,setArchivedChatsOpen:pe,setSectionMenuOpen:fe,setProjectsExpanded:Ae,setCloudProjectsExpanded:Ce,setChatRowsVisibleCount:He,setSidebarOpen:Pe,setView:Xe,setSelectedAppId:ut,setSelectedProjectId:fn,setSelectedSessionId:jt,setPrompt:dn,setDraftProvider:yn,setDraftModel:Sn,setDraftExperience:Qt,setCodexPermissionMode:Wa,setCodexReasoningEffort:wa,setOpenPondCommandAccessMode:zn,setDiffPanelOpen:$n,setDiffPanelExpanded:Ht,setRightPanelMode:St,setRightChatPanels:xn,setTerminalOpen:xt,setSyncingWorkspaceAppId:Nt,setSettingsSection:_a,setNewProjectDialogOpen:Ft,setNewProjectMode:kn,setNewProjectName:rt,setNewProjectPath:jn,setNewProjectBusy:ui,setCommitDialogOpen:mi,setCommitMessage:ha,setCommitIncludeUnstaged:Ca,setCommitNextStep:Bn,setCommitDraft:Li,setBranchDialogOpen:Ga,setBranchDialogName:K,setError:Be}=n,{connectionRef:_e,setError:Ve,showToast:It}=KQ({appDispatch:t,error:W,setErrorState:Be}),{appPreferences:na,applyBootstrapPayload:In,bootstrap:Je,codexHistorySessions:Rn,connection:ft,events:Nn,runtimeEventStore:Ja,approvals:So,sessions:Ra,startup:xo,setAppPreferences:Xo,setBootstrap:qi,setCodexHistorySessions:Fn,setEvents:Pa,setSessions:aa}=BQ({setDraftModel:Sn,setDraftProvider:yn,setCodexPermissionMode:Wa,setCodexReasoningEffort:wa,setOpenPondCommandAccessMode:zn,setError:Ve,setSelectedAppId:ut,setSelectedProjectId:fn,setSelectedSessionId:jt});_e.current=ft,y.useEffect(()=>{Je&&k(Je.sidebarFileBookmarks??[])},[Je?.sidebarFileBookmarks]);const ko=y.useMemo(()=>[...Nn].reverse().find(ot=>ot.name==="tool.completed"&&ot.action==="manage_sidebar_file")??null,[Nn]),er=y.useRef(null);y.useEffect(()=>{!ft||!ko||er.current===ko.id||(er.current=ko.id,Q.sidebarFiles(ft).then(ot=>k(ot.items)).catch(ot=>Ve(ot instanceof Error?ot.message:String(ot))))},[ft,ko,Ve]);const Io=y.useCallback(async(ot,Kt)=>{if(!ft)return;const Wt=S;k(Gt=>Kt==="none"?Gt.filter(Qa=>Qa.id!==ot.id):Gt.some(Qa=>Qa.id===ot.id)?Gt.map(Qa=>Qa.id===ot.id?{...Qa,status:Kt}:Qa):[...Gt,{...ot,status:Kt}]);try{const Gt=await Q.patchSidebarFile(ft,{workspaceKind:ot.workspaceKind,workspaceId:ot.workspaceId,workspaceName:ot.workspaceName,path:ot.path,status:Kt,sourceSessionId:ot.sourceSessionId});k(Gt.items)}catch(Gt){k(Wt),Ve(Gt instanceof Error?Gt.message:String(Gt))}},[ft,Ve,S]),wo=Dee(ft),_t=pX({connection:ft,profileId:Je?.profile?.activeProfile??"default"}),{pinnedCollapsed:pl,projectsCollapsed:tr,cloudProjectsCollapsed:fl,chatsCollapsed:Lr,savedForLaterCollapsed:hl,sidebarWidth:Ui,sidebarResizing:gl,diffPanelWidth:qr,diffPanelResizing:Ur,togglePinnedCollapsed:zr,toggleProjectsCollapsed:vl,toggleCloudProjectsCollapsed:bl,toggleChatsCollapsed:pi,toggleSavedForLaterCollapsed:yl,startSidebarResize:Br,startDiffPanelResize:Fr}=iX({connection:ft,preferences:Je?.preferences,sidebarOpen:Le,diffPanelExpanded:F,setBootstrap:qi,setError:Ve}),{cloudProjectById:_o,linkedProjectByAppId:Vr,localProjectById:ga,mentionableSandboxApps:Sl,selectedApp:nr,selectedCloudProject:zi,selectedProject:ia,selectedProjectLinkedApp:xl,selectedProjectLinkedOpenPondApp:kl,selectedSession:Pn,selectedSessionLinkedProject:Co,sidebarSessions:Aa}=AJ({bootstrap:Je,codexHistorySessions:Rn,selectedAppId:le,selectedProjectId:xe,selectedSessionId:Ue,sessions:Ra}),Za=Pn?.experience??at;y.useEffect(()=>{nJ(Za)},[Za]);const ar=y.useMemo(()=>GW(Aa,Za),[Za,Aa]),Ro=kX(Nn,So),{chatMentionApps:Il,connectedAppMentions:Kr,pendingApproval:ir}=GJ({bootstrap:Je,connectedAppRows:wo,mentionableSandboxApps:Sl,runtimeIndexes:Ro,selectedApp:nr,selectedCloudProject:zi,selectedProject:ia,selectedSession:Pn,selectedSessionId:Ue}),{codexHistoryEvents:Bi,setCodexHistoryEvents:Po}=pZ({connection:ft,selectedSessionId:Ue,selectedSessionLocallyActive:!!(Ue&&P.has(Ue)),selectedSessionStatus:Pn?.status,setCodexHistorySessions:Fn,setError:Ve}),{account:Ao,accountPending:Wr,accountSignedOut:Gr,activeModel:Ta,activeProvider:Ea,activeWorkspaceAppId:Jr,activeWorkspaceId:or,activeWorkspaceKind:fi,activeWorkspaceLocation:rr,appDefaults:Fi,cloudLinked:Zr,selectedCodexHistoryPending:Yr,selectedSessionProjectId:Qr,startMessage:wl,workspaceName:Xr}=wJ({bootstrap:Je,draftModel:it,draftProvider:Ze,selectedApp:nr,selectedAppId:le,selectedCloudProject:zi,selectedProject:ia,selectedSession:Pn,selectedSessionId:Ue,selectedSessionLinkedProject:Co}),es=y.useMemo(()=>hJ(Je?.account??null),[Je?.account]),_l=y.useMemo(()=>Og(Je?.account??null),[Je?.account]),To=Nee(_l),ts=y.useMemo(()=>bJ(To,Fi.defaultTeamId),[Fi.defaultTeamId,To]),sr=ts?.teamId??null,hi=See({connection:ft,teamId:sr,currentUserId:Ao?.profile?.id??null,refreshToken:Je?.accountMeta.asOf??null}),Cl=_ee({connection:ft,teamId:sr,applyBootstrapPayload:In,refreshDirectory:hi.refreshDirectory});Ree({notification:hi.incomingNotification,dismiss:hi.dismissIncomingNotification,selectThread:hi.selectThread,setView:Xe,showToast:It});const{communities:Rl,sidebar:Pl,view:Al}=Oee({connection:ft,currentUserId:Ao?.profile?.id??null,refreshToken:Je?.accountMeta.asOf??null,setView:Xe,showToast:It}),gi=hi.aiThread?.conversationId??null,ns=Ie==="team"&&!!gi&&N&&ee==="chat";y.useEffect(()=>{if(Ie==="team"){if(gi){St("chat"),$n(!0);return}ee==="chat"&&$n(!1)}},[ee,$n,St,gi,Ie]);const Tl=y.useCallback(()=>{if(gi){if(ns){$n(!1);return}St("chat"),$n(!0)}},[$n,St,ns,gi]),El=y.useMemo(()=>za(ia,Je?.cloudProjects??[]),[Je?.cloudProjects,ia]),Ml=Pn?.provider==="codex"?qe:Pn?.openPondCommandAccessMode??qe,va=Jr,as=or,jl=fi,pt=Xr,{openPondActionCatalog:rn,selectedActionCatalog:oa}=DX({cloudProjectById:_o,cloudProjects:Je?.cloudProjects??[],connection:ft,defaultTeamId:Fi.defaultTeamId,accountScopeKey:es,localProjects:Je?.localProjects??[],profile:Je?.profile,selectedCloudProject:zi,selectedProject:ia,reportError:Ve}),{expandedProjectIds:hn,expandProject:Dn,toggleProjectExpanded:ba,setExpandedProjectIds:dp}=HX({selectedProjectId:xe});NJ({activeWorkspaceId:or,activeWorkspaceKind:fi,appDispatch:t,connection:ft,expandProject:Dn,linkedProjectByAppId:Vr,providerSettings:Je?.providers??null,selectedAppId:le,selectedSession:Pn,selectedSessionId:Ue,selectedSessionProjectId:Qr,setDiffPanelExpanded:Ht,setDraftModel:Sn,setDraftProvider:yn,setError:Ve,setSelectedAppId:ut,setSelectedProjectId:fn,setSessions:aa,setTerminalOpen:xt,toast:_});const{changeCodexPermissionMode:up,changeCodexReasoningEffort:mp}=JJ({connection:ft,setBootstrap:qi,setCodexPermissionMode:Wa,setCodexReasoningEffort:wa,setError:Ve}),{changeOpenPondCommandAccessMode:Sd}=QY({connection:ft,selectedSession:Pn,setBootstrap:qi,setError:Ve,setOpenPondCommandAccessMode:zn,setSessions:aa}),pp=DJ({connection:ft,setError:Ve}),lr=y.useCallback(()=>{H(ot=>ot+1)},[]),xd=LJ({appDispatch:t,expandProject:Dn,linkedProjectByAppId:Vr,requestComposerFocus:lr,onBeginNewChat:()=>{ln({kind:"chat",sessionId:null}),X(null),Qt(ot=>ot==="development"?"work":ot)},setMentionedAppId:g}),is=y.useCallback(ot=>{const Kt=wt("local",ot);t({type:"selectProject",projectId:Kt}),Dn(Kt)},[t,Dn]),{advanceAfterTurn:fp,begin:hp,bindSession:gp,dismiss:vp,handoff:bp,prepareTurn:yp,selectTask:Sp}=yX({activeModel:Ta,activeProvider:Ea,applyBootstrapPayload:In,beginNewChat:xd,composerDraftStore:e,connection:ft,requestComposerFocus:lr,selectedLocalProjectId:ia?.id??null,selectedSessionId:Ue,selectLocalProject:is,setDraftModel:Sn,setDraftProvider:yn,setError:Ve,view:Ie});aX({connection:ft,events:Nn,showToast:It}),rQ({searchOpen:Se,sectionMenuOpen:be,setSectionMenuOpen:fe,setSearchOpen:ce,setQuery:Z}),y.useEffect(()=>{I({})},[Je?.server.id]);const{chatHistoryLoadStates:xp,loadMoreSelectedChatHistory:kp,selectedPagedSessionEvents:Ip,selectedRuntimeIndexes:kd}=SX({approvals:So,codexHistoryEvents:Bi,connection:ft,latestServerSequence:Je?.eventWindow?.latestSequence,runtimeIndexes:Ro,runtimeEventStore:Ja,selectedSessionId:Ue,serverId:Je?.server.id,setCodexHistoryEvents:Po,setCodexHistorySessions:Fn,setError:Ve}),{activeSessions:wp,archivedSessions:_p,pinnedProjects:Cp,pinnedSessions:Ol,savedForLaterSessions:Id,pinnedFiles:Rp,savedForLaterFiles:Pp,pinnedItems:wd,projectRows:_d,localProjectRows:Ap,visibleProjectRows:os,cloudProjectRows:Tp,projectSessionRowsByProjectId:Cd,childSessionRowsByParentId:Ep,sidebarProjectIdBySessionId:$l,chatRows:Rd,visibleChatRows:Pd,sessionEvents:Mp,chatMessages:Ad,contextUsage:jp,goalRuntime:Op,subagentRuntime:Td}=XY({localProjects:Je?.localProjects??[],cloudProjects:Je?.cloudProjects??[],sessions:ar,runtimeIndexes:kd,appPreferences:na,selectedSessionId:Ue,selectedProjectId:xe,archivedChatsOpen:oe,projectsExpanded:re,chatRowsVisibleCount:ke,sidebarFileBookmarks:S}),$p=y.useCallback(ot=>{Qt(ot);const Kt=[...ar].filter(Wt=>ot==="work"?Wt.experience==="work"||Wt.experience==="development":Wt.experience===ot).sort((Wt,Gt)=>Gt.updatedAt.localeCompare(Wt.updatedAt))[0]??[...Aa].filter(Wt=>Wt.experience===ot).sort((Wt,Gt)=>Gt.updatedAt.localeCompare(Wt.updatedAt))[0]??null;if(Kt)t({type:"selectSession",sessionId:Kt.id,appId:ot!=="chat"?Kt.appId:null,projectId:ot!=="chat"?$l[Kt.id]??null:null});else if(t({type:"beginNewChat",appId:null}),ot==="chat"&&Ea==="codex"){const Wt=Pg(Je?.providers,{enabledOnly:!0}).find(Gt=>Gt.value!=="codex")?.value??_r;yn(Wt),Sn(tm(Wt,Je?.providers)??bc)}ot==="chat"&&(xt(!1),Ht(!1),St("home")),Xe("chat")},[t,Ea,Je?.providers,ar,Ht,Qt,Sn,yn,St,xt,Xe,$l,Aa]),Ed=y.useCallback(ot=>{const Kt=e.getSnapshot();if(Qt(ot),(Ue||le||xe)&&(t({type:"beginNewChat",appId:null}),Kt&&e.set(Kt)),ot==="chat"&&Ea==="codex"){const Wt=Pg(Je?.providers,{enabledOnly:!0}).find(Gt=>Gt.value!=="codex")?.value??_r;yn(Wt),Sn(tm(Wt,Je?.providers)??bc)}ot==="chat"&&(xt(!1),Ht(!1),St("home")),Xe("chat")},[Ea,t,Je?.providers,e,le,xe,Ue,Ht,Qt,Sn,yn,St,xt,Xe]),{pendingChatUserMessages:Np,recordPendingChatUserMessage:Dp,visibleChatMessages:Hp}=YY({chatMessages:Ad,runtimeIndexes:kd,selectedSessionId:Ue}),Eo=y.useMemo(()=>r8({selectedAppId:le,selectedProjectId:xe,selectedSessionId:Ue}),[le,xe,Ue]),Md=y.useRef(null);y.useEffect(()=>{const ot=Md.current;Md.current=Eo,!(!ot||ot.kind!=="draft"||Eo.kind!=="session")&&(Lc(ot,Eo)||c(Kt=>{const Wt=s8({tabs:Kt,previousScope:ot,activeScope:Eo});return Wt.some((Qa,gf)=>Qa!==Kt[gf])?Wt:Kt}))},[Eo]);const Lp=y.useMemo(()=>l8(s),[s]),{goalRuntime:qp,runningSessionIds:Nl,selectedSessionRunning:Up,sidebarGoalRuntimeBySessionId:zp,sidebarSubagentRuntimeBySessionId:Bp}=oQ({codexHistoryEvents:Bi,codexHistorySessions:Rn,connection:ft,expandedProjectIds:hn,goalRuntime:Op,locallyActiveCodexHistorySessionIds:P,pinnedSessions:Ol,savedForLaterSessions:Id,projectSessionRowsByProjectId:Cd,rightChatHistoryEvents:j,runtimeIndexes:Ro,selectedSession:Pn,selectedSessionId:Ue,serverId:Je?.server.id,setCodexHistorySessions:Fn,sidebarSessions:Aa,subagentRuntime:Td,visibleChatRows:Pd,visibleProjectRows:os}),{dragItem:Fp,pinnedPreviewKeys:Vp,startPinnedDrag:Kp,clearSidebarDrag:Wp,previewPinnedDrop:Gp,commitPinnedDrop:Jp,commitPinnedPreviewDrop:Zp}=fZ({connection:ft,appPreferences:na,sessions:Aa,pinnedItems:wd,setAppPreferences:Xo,setCodexHistorySessions:Fn,setSessions:aa,sidebarFileBookmarks:S,setSidebarFileBookmarks:k,setError:Ve}),{clearTaskDrag:Yp,commitTaskDrop:jd,commitTaskPreviewDrop:Qp,previewTaskDrop:Ya,startTaskDrag:rs,taskDragSessionId:Xp,taskPreviewSessionIds:ef}=hZ({connection:ft,sessions:Aa,setCodexHistorySessions:Fn,setError:Ve,setSessions:aa}),{commandProjectRows:tf,contextWindowStatus:Dl,pinnedRows:nf,sidebarWorkspaceAppIds:af}=HJ({activeProvider:Ea,contextCompaction:Fi.contextCompaction,contextUsage:jp,pinnedItems:wd,pinnedPreviewKeys:Vp??[],pinnedProjects:Cp,projectRows:_d,visibleProjectRows:os}),Vi=!!(va&&(Ie==="chat"||Ie==="labs")&&(Ye||N&&(ee==="changes"||ee==="goal"))),{workspaceStates:ss,workspaceBusy:ls,diffBusy:of,visibleWorkspaceState:cr,visibleWorkspaceDiff:Hl,rememberWorkspaceState:cs,refreshWorkspace:Ll,refreshWorkspaceDiff:vi,setWorkspaceBusy:$d}=UX({connection:ft,activeWorkspaceAppId:va,view:Ie,shouldLoadWorkspaceDiff:Vi,sidebarWorkspaceAppIds:af,setError:Ve});de.current=cs;const rf=y.useCallback((ot=va)=>!ot||ot!==va||!Vi?Promise.resolve(null):vi(ot),[vi,Vi,va]),sf=y.useCallback(async(ot={})=>{!va||!Vi||await vi(va,ot)},[vi,Vi,va]),lf=!1,cf=!!(Pn?.provider==="codex"&&Pn.cwd&&!Oi(Pn.workspaceKind)),df=!!(cr&&!cr.initialized&&fi!=="local_project"&&Ea!=="codex"&&!cf&&!Yr),uf=fi==="local_project"&&!!ia?.sandboxTemplate?.detected&&!ia?.linkedOpenPondApp?.appId,[Nd,Dd]=y.useState(null),[mf,pf]=y.useState(null),{projectTarget:ff,workspaceTarget:hf}=_J({accountPending:Wr,accountSignedOut:Gr,activeWorkspaceLocation:rr,bootstrap:Je,busy:q,cloudLinked:Zr,selectedCloudProject:zi,selectedProject:ia,selectedSession:Pn,pendingWorkspaceTarget:Nd,workspaceStates:ss,workspaceBusy:ls});return y.useEffect(()=>{Dd(null)},[Pn?.id]),{composerDraftStore:e,appDispatch:t,pendingTerminalCommand:i,setPendingTerminalCommand:r,terminalTabs:s,setTerminalTabs:c,trainingDetailTasksetId:m,setTrainingDetailTasksetId:u,mentionedAppId:h,setMentionedAppId:g,cloudSetupDialog:C,setCloudSetupDialog:A,rightPanelTabRequest:M,setRightPanelTabRequest:R,workspaceDiffPanelViewState:$,setWorkspaceDiffPanelViewState:O,rightChatHistoryEvents:j,setRightChatHistoryEvents:I,locallyActiveCodexHistorySessionIds:P,setCodexHistoryTurnLocallyActive:L,mainComposerFocusRequestId:z,requestMainComposerFocus:lr,draftSubagentDelegationMode:J,setDraftSubagentDelegationMode:X,confirmProjectAction:je,projectConfirmDialog:we,resolveProjectConfirmDialog:te,query:Me,searchOpen:Se,archivedChatsOpen:oe,sectionMenuOpen:be,projectsExpanded:re,cloudProjectsExpanded:ue,sidebarOpen:Le,view:Ie,selectedAppId:le,selectedProjectId:xe,selectedSessionId:Ue,draftProvider:Ze,draftModel:it,draftExperience:at,activeExperience:Za,changeExperience:$p,changeNewExperience:Ed,codexPermissionMode:Ne,codexReasoningEffort:We,openPondCommandAccessMode:qe,busy:q,diffPanelOpen:N,diffPanelExpanded:F,rightPanelMode:ee,rightChatPanels:me,terminalOpen:$e,settingsSection:ze,newProjectDialogOpen:tt,newProjectMode:nt,newProjectName:mt,newProjectPath:vt,newProjectBusy:Oe,commitDialogOpen:Ye,commitMessage:f,commitIncludeUnstaged:U,commitNextStep:Y,commitDraft:ge,branchDialogOpen:se,branchDialogName:G,toast:_,error:W,labDetailNavigation:ne,setQuery:Z,setSearchOpen:ce,setArchivedChatsOpen:pe,setSectionMenuOpen:fe,setProjectsExpanded:Ae,setCloudProjectsExpanded:Ce,setChatRowsVisibleCount:He,setSidebarOpen:Pe,setView:Xe,setSelectedAppId:ut,setSelectedProjectId:fn,setSelectedSessionId:jt,setPrompt:dn,setDraftProvider:yn,setDraftModel:Sn,setDraftExperience:Qt,setDiffPanelOpen:$n,setDiffPanelExpanded:Ht,setRightPanelMode:St,setRightChatPanels:xn,setTerminalOpen:xt,setSyncingWorkspaceAppId:Nt,setSettingsSection:_a,setNewProjectDialogOpen:Ft,setNewProjectMode:kn,setNewProjectName:rt,setNewProjectPath:jn,setNewProjectBusy:ui,setCommitDialogOpen:mi,setCommitMessage:ha,setCommitIncludeUnstaged:Ca,setCommitNextStep:Bn,setCommitDraft:Li,setBranchDialogOpen:Ga,setBranchDialogName:K,setError:Ve,showToast:It,appPreferences:na,applyBootstrapPayload:In,approvals:So,bootstrap:Je,connection:ft,events:Nn,runtimeEventStore:Ja,sessions:Ra,startup:xo,setAppPreferences:Xo,setCodexHistorySessions:Fn,setEvents:Pa,setSessions:aa,training:_t,pinnedCollapsed:pl,projectsCollapsed:tr,cloudProjectsCollapsed:fl,chatsCollapsed:Lr,savedForLaterCollapsed:hl,sidebarWidth:Ui,sidebarResizing:gl,diffPanelWidth:qr,diffPanelResizing:Ur,togglePinnedCollapsed:zr,toggleProjectsCollapsed:vl,toggleCloudProjectsCollapsed:bl,toggleChatsCollapsed:pi,toggleSavedForLaterCollapsed:yl,startSidebarResize:Br,startDiffPanelResize:Fr,cloudProjectById:_o,localProjectById:ga,selectedApp:nr,selectedCloudProject:zi,selectedProject:ia,selectedProjectLinkedApp:xl,selectedProjectLinkedOpenPondApp:kl,selectedSession:Pn,sidebarSessions:Aa,runtimeIndexes:Ro,chatMentionApps:Il,connectedAppMentions:Kr,pendingApproval:ir,codexHistoryEvents:Bi,setCodexHistoryEvents:Po,account:Ao,accountPending:Wr,accountSignedOut:Gr,activeModel:Ta,activeProvider:Ea,activeWorkspaceAppId:Jr,activeWorkspaceId:or,activeWorkspaceKind:fi,activeWorkspaceLocation:rr,appDefaults:Fi,selectedSessionProjectId:Qr,startMessage:wl,workspaceName:Xr,accountScopeKey:es,organizations:To,teamChatOrganization:ts,teamChatTeamId:sr,teamChat:hi,publishTeamProfileAgent:Cl,communities:Rl,communitySidebar:Pl,communityView:Al,teamAiThreadId:gi,toggleTeamAiSidebar:Tl,selectedProjectConfirmedCloudProject:El,activeOpenPondCommandAccessMode:Ml,viewWorkspaceAppId:va,viewWorkspaceId:as,viewWorkspaceKind:jl,viewWorkspaceName:pt,openPondActionCatalog:rn,selectedActionCatalog:oa,expandedProjectIds:hn,expandProject:Dn,toggleProjectExpanded:ba,setExpandedProjectIds:dp,changeCodexPermissionMode:up,changeCodexReasoningEffort:mp,changeOpenPondCommandAccessMode:Sd,resolveApproval:pp,beginNewChat:xd,advanceTrainingModelChatAfterTurn:fp,beginNewChatWithTrainingModel:hp,bindTrainingModelChatSession:gp,dismissTrainingChatHandoff:vp,trainingChatHandoff:bp,prepareTrainingModelChatTurn:yp,selectTrainingChatTaskForComposer:Sp,chatHistoryLoadStates:xp,loadMoreSelectedChatHistory:kp,selectedPagedSessionEvents:Ip,activeSessions:wp,archivedSessions:_p,pinnedSessions:Ol,savedForLaterSessions:Id,pinnedFiles:Rp,savedForLaterFiles:Pp,sidebarFileBookmarks:S,setSidebarFileStatus:Io,projectRows:_d,localProjectRows:Ap,visibleProjectRows:os,cloudProjectRows:Tp,projectSessionRowsByProjectId:Cd,childSessionRowsByParentId:Ep,sidebarProjectIdBySessionId:$l,chatRows:Rd,visibleChatRows:Pd,chatRowsVisibleCount:ke,sessionEvents:Mp,chatMessages:Ad,goalRuntime:qp,subagentRuntime:Td,pendingChatUserMessages:Np,recordPendingChatUserMessage:Dp,visibleChatMessages:Hp,activeTerminalScope:Eo,terminalSummaries:Lp,runningSessionIds:Nl,selectedSessionRunning:Up,sidebarGoalRuntimeBySessionId:zp,sidebarSubagentRuntimeBySessionId:Bp,taskDragSessionId:Xp,taskPreviewSessionIds:ef,startTaskDrag:rs,clearTaskDrag:Yp,previewTaskDrop:Ya,commitTaskDrop:jd,commitTaskPreviewDrop:Qp,dragItem:Fp,startPinnedDrag:Kp,clearSidebarDrag:Wp,previewPinnedDrop:Gp,commitPinnedDrop:Jp,commitPinnedPreviewDrop:Zp,commandProjectRows:tf,contextWindowStatus:Dl,pinnedRows:nf,workspaceStates:ss,workspaceBusy:ls,diffBusy:of,visibleWorkspaceState:cr,visibleWorkspaceDiff:Hl,rememberWorkspaceState:cs,refreshWorkspace:Ll,refreshWorkspaceDiff:vi,setWorkspaceBusy:$d,refreshWorkspaceDiffWhenNeeded:rf,refreshVisibleWorkspaceDiff:sf,managedWorkspace:lf,canSyncActiveWorkspace:df,canPublishOpenPondProject:uf,pendingWorkspaceTarget:Nd,setPendingWorkspaceTarget:Dd,pendingSidebarWorkspaceTarget:mf,setPendingSidebarWorkspaceTarget:pf,projectTarget:ff,workspaceTarget:hf}}const Lee=/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})(?::\d+)?(?:[/?#].*)?$/i,qee=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+(?:[:/?#].*)?$/i;function Uee(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)?lu(n,new Set(["http:","https:"])):/^file:\/\//i.test(n)?t.explicitFile?lu(n,new Set(["file:"])):null:Lee.test(n)?lu(`http://${n}`,new Set(["http:"])):qee.test(n)?lu(`https://${n}`,new Set(["https:"])):null}function lu(e,t){try{const n=new URL(e);return t.has(n.protocol)?n.toString():null}catch{return null}}async function zee(e){const t=Uee(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 Bee="openpond-coding-core-v1",Fee="feature";function Kg(e){const t=new URL("/sandboxes",Iy(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",Fee),t.searchParams.set("runtimeProfileId",Bee),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 Qie(e){const t=e.organizationSlug?.trim(),n=t?`/sandboxes/${encodeURIComponent(t)}/billing`:"/sandboxes/billing",a=new URL(n,Iy(e.accountBaseUrl));return!t&&e.teamId?.trim()&&a.searchParams.set("teamId",e.teamId.trim()),a.toString()}function xk(e){const t=e.organizationSlug?.trim(),n=e.projectSlug?.trim();return!t||!n?null:new URL(`/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,Iy(e.accountBaseUrl)).toString()}function Iy(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 Vee({account:e,browserConversationId:t,cloudProjectById:n,cloudProjects:a,diffPanelOpen:i,rightPanelMode:r,selectedProjectId:s,setDiffPanelOpen:c,setNewProjectDialogOpen:m,setNewProjectMode:u,setNewProjectName:h,setRightPanelMode:g}){const S=y.useCallback(()=>{g("changes"),c(!0)},[c,g]),k=y.useCallback(()=>{if(i&&r==="changes"){c(!1);return}S()},[i,r,c,S]),C=y.useCallback(()=>{g("browser"),c(!0)},[c,g]),A=y.useCallback(()=>{g("goal"),c(!0)},[c,g]),M=y.useCallback((j,I)=>{zee({conversationId:t,href:j,explicitFile:I?.explicitFile,newTab:I?.newTab}).then(P=>{P&&C()})},[t,C]),R=y.useCallback(()=>{u("cloud"),h(""),m(!0)},[m,u,h]),$=y.useCallback(j=>{const I=n.get(j);I&&M(Kg({accountBaseUrl:e?.baseUrl??e?.activeProfile?.baseUrl??null,teamId:I.teamId,projectId:I.id,projectName:I.name,baseBranch:I.defaultBranch,source:"openpond-app"}),{newTab:!0})},[e,n,M]);return{createCloudEnvironmentFromSidebar:y.useCallback(()=>{const j=s?.startsWith("cloud:")?s.slice(6):a[0]?.id??null;if(j){$(j);return}R()},[a,R,s,$]),openCloudProjectDialog:R,openUrlInBrowserPanel:M,showBrowserPanel:C,showChangesPanel:S,showGoalSidebarTab:A,toggleChangesPanel:k}}function Kee(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 Wee({browserConversationId:e,sessionIds:t,onOpenSession:n,onShowBrowserPanel:a}){y.useEffect(()=>window.openpond?.browser?.onRevealRequest?.(r=>{const s=Kee({currentConversationId:e,requestConversationId:r.conversationId,sessionIds:t});s.reveal&&(s.sessionIdToOpen&&n(s.sessionIdToOpen),a())}),[e,n,a,t])}const Gee="chat",Jee=["help me","please","can you","could you","make","create","build"],Zee=new Set(["a","an","and","for","from","i","me","my","of","our","please","produce","summary","the","to","with"]);function kk(e){const t=Hh(e.label);if(t&&!Wg(t))return Ik(t);const n=Hh(e.name);if(n&&!Wg(n))return Ik(n);const a=Hh(e.actionId)?.replace(/\.chat$/i,"")??"";return Yee(a||t||"Profile Agent")}function Wg(e){return e.trim().toLowerCase()===Gee}function Yee(e){const t=Qee(e.replace(/\.chat$/i,"").replace(/[._-]+/g," ").replace(/\s+/g," ").trim()),a=t.toLowerCase().split(/\s+/).map(i=>i.replace(/[^a-z0-9]/g,"")).filter(i=>i&&!Zee.has(i)).slice(0,3);return qA(a.length?a.join(" "):t||e)}function Ik(e){return qA(e).split(/\s+/).slice(0,4).join(" ")}function Qee(e){let t=e.trim();for(const n of Jee)if(t.toLowerCase().startsWith(`${n} `)){t=t.slice(n.length).trim();break}return t}function Hh(e){return typeof e=="string"&&e.trim()?e.trim():null}function qA(e){return e.replace(/[._-]+/g," ").replace(/\s+/g," ").trim().replace(/\b[a-z0-9]/gi,t=>t.toUpperCase())}const Xee="openpond-profile-action";function ete(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function cu(e){return typeof e=="string"&&e.trim()?e.trim():null}function tte(e){const t=ete(e.implementation);if(t?.type!==Xee)return null;const n=cu(t.actionId)??e.id;if(e.sourceActionId!=="chat"&&n!=="chat"&&!n.endsWith(".chat"))return null;const a=cu(e.label);if(a&&!Wg(a))return kk({label:a,description:e.description});const i=cu(t.agentName)??cu(e.name);return kk({actionId:n,description:e.description,name:i})}function nte(e){const t=tte(e);return t||e.label?.trim()||e.name?.trim()||e.id}function UA(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 ate=new Set(["action","agent","chat","customer","default","filter","items","open","openpond","profile","run","summarize","track","workflow"]);function zA(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function tl(e){return typeof e=="string"&&e.trim()?e.trim():null}function Ms(e,t,n={}){const a=tl(t)?Wn(String(t)):"";a&&(!n.generic&&ate.has(a)||e.add(a))}function du(e,t){const n=tl(t);if(n)for(const a of n.split(/[.:/\\\s]+/g))Ms(e,a)}function ite(e,t){const n=tl(t);if(n)for(const a of n.split(/[^A-Za-z0-9_-]+/g))a.length<4||Ms(e,a)}function BA(e){const t=new Set,n=zA(e.implementation),a=tl(n?.actionId);return Ms(t,e.id,{generic:!0}),du(t,e.id),Ms(t,a,{generic:!0}),du(t,a),Ms(t,e.name,{generic:!0}),du(t,e.name),Ms(t,e.label,{generic:!0}),du(t,e.label),ite(t,e.description),t}function ote(e){const t=zA(e.implementation);return[e.id,e.name??"",e.label??"",e.description??"",tl(t?.actionId)??"",tl(t?.agentName)??"",UA(e),...Array.from(BA(e))].join(" ").toLowerCase()}function Xie(e,t,n=8){const a=Wn(t);return e.length===0?[]:e.filter(i=>a?ote(i).includes(a):!0).slice(0,n)}function rte(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Wn(t[1]??"")).filter(Boolean)}function ste(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`(^|\\s)@${n}(?=\\s|$)`,"g"),"$1").replace(/\s+/g," ").trim()}function lte(e,t){const n=rte(e);if(n.length===0||t.length===0)return null;const a=new Map;for(const r of n)for(const s of t)BA(s).has(r)&&a.set(s.id,{action:s,mention:r});if(a.size!==1)return null;const i=Array.from(a.values())[0];return{action:i.action,mention:i.mention,prompt:ste(e,i.mention)}}function eoe(e){return nte(e)}function toe(e){return e.description||UA(e)}const wy=[{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 cte(e){return wy.filter(t=>t.id!=="goal"||e==="codex")}function FA(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 noe(e,t){return cte(e).filter(n=>FA(n,t))}const dte=new Set(wy.map(e=>e.id));function aoe(e){return e.subcommands?.length?e.subcommands.join(", "):e.description}function ute(e){return[e.id,e.command,e.label,e.description].join(" ")}function mte(e){return(e.subcommands??[]).flatMap(t=>[t,`${e.id} ${t}`,`${e.command} ${t}`]).join(" ")}function pte(e){const t=/^\/([a-z][a-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(e.trim());if(!t)return null;const n=t[1];return dte.has(n)?{command:n,args:t[2]?.trim()??""}:null}function fte(e){const t=e.trim();if(!t.startsWith("!"))return null;const n=t.slice(1).trim();return n?{command:n}:null}function ioe({commands:e=wy,prompt:t,limit:n=10}){if(!t.startsWith("/"))return[];const a=t.slice(1).trim().toLowerCase();if(!a)return e.slice(0,n);const i=e.filter(c=>c.id.startsWith(a));if(i.length>0)return i.slice(0,n);const r=e.filter(c=>ute(c).toLowerCase().includes(a));return(r.length>0?r:e.filter(c=>mte(c).toLowerCase().includes(a))).slice(0,n)}function ooe(e){return e==="owner"?"Owner":e==="admin"?"Admin":"Member"}function lp(e){return e?.role==="owner"||e?.role==="admin"}function roe(e){const t=cp(e.organizations,e.defaultTeamId),n=lp(t),a=e.localProject??null;if(!a)return hte("Open a local project to set up an Agent.");const i=gte(a,e.projects),r=vte(a,i,e.agents),s=!!a.sandboxTemplate?.detected,c=t&&!n?"Ask an owner or admin to connect this project.":null;return s?i?bte(a,i)?uu({state:"needs_sync",actionLabel:"Sync Project",project:i,agent:r,canManage:n,actionBlockedReason:c}):r?{state:"ready",actionLabel:"Run Agent",canAct:!0,reason:null,project:i,agent:r}:uu({state:"needs_agent",actionLabel:"Create Agent",project:i,agent:null,canManage:n,actionBlockedReason:c}):uu({state:"needs_project",actionLabel:"Connect Project",project:null,agent:null,canManage:n,actionBlockedReason:c}):uu({state:"missing_config",actionLabel:"Add Agent config",project:i,agent:r,canManage:n,actionBlockedReason:c})}function uu(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 hte(e){return{state:"blocked",actionLabel:"Ask admin",canAct:!1,reason:e,project:null,agent:null}}function cp(e,t){if(e.length===0)return null;const n=t?.trim()??"";if(n){const a=e.find(i=>i.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 gte(e,t){const n=e.linkedSandboxProject;return n?.projectId?t.find(a=>a.id===n.projectId)??null:null}function vte(e,t,n){if(!t)return null;const a=e.preferredSandboxAgentId;if(a){const i=n.find(r=>r.id===a&&r.projectId===t.id);if(i)return i}return n.find(i=>i.projectId===t.id)??null}function bte(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 dr=e=>e.slice(0,2e4);function yte({model:e,provider:t,providerSettings:n}){return{model:iy(t,e,n),modelRef:ei(t,e,n)}}function Ste(e,t){return e.some(n=>n.id===t.id)?e:[...e,t]}function xte(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 kte(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 wk({action:e,prompt:t,runPayload:n,sessionId:a}){const i=new Date().toISOString(),r=`openpond_action_${n.run.id}`,s=n.run.status==="failed"?"failed":n.run.status==="succeeded"?"completed":"started";return[{id:`${r}_user`,sessionId:a,turnId:r,name:"turn.started",timestamp:i,source:"chat_action",args:{prompt:t}},{id:`${r}_result`,sessionId:a,turnId:r,name:"workspace_action_result",timestamp:n.run.updatedAt??i,source:"chat_action",action:"sandbox_run_action",appId:null,status:s,output:s==="completed"?`Ran ${e.label??e.name??e.id}`:`Started ${e.label??e.name??e.id}`,data:{openPondActionRun:!0,action:{name:e.id,label:e.label??e.name??e.id,implementation:e.implementation},agent:n.agent,run:n.run,sandbox:n.sandbox??null,actionSummary:n.run.actionSummary??null,responseSummary:n.run.responseSummary??null,traceSummary:n.run.traceSummary??null,evalSummary:n.run.evalSummary??null,sourceSummary:n.run.sourceSummary??null}}]}function Ite({applyBootstrapPayload:e,connection:t,codexPermissionMode:n,codexReasoningEffort:a,openPondCommandAccessMode:i,draftModel:r,draftProvider:s,experience:c,expandProject:m,ensureCloudSessionReady:u,getPrompt:h,bootstrap:g,chatMessages:S,apps:k,connectedAppMentions:C,mentionedAppId:A,refreshWorkspace:M,refreshWorkspaceDiff:R,selectedApp:$,selectedActionCatalog:O,openPondActionCatalog:j,cloudProjects:I,accountScopeKey:P,selectedCloudProject:E,selectedProject:L,selectedProjectLinkedOpenPondApp:z,selectedSession:H,workspaceTarget:J,subagentDelegationMode:X,setDraftModel:de,setDraftProvider:je,setError:we,setPrompt:te,setMentionedAppId:Me,setCodexHistoryEvents:Se,setCodexHistorySessions:oe,onCodexHistoryTurnActivityChange:be,onCodexHistoryTurnPayload:re,onPendingUserMessage:ue,setEvents:ke,setSelectedAppId:Le,setSelectedProjectId:Ie,setSelectedSessionId:le,setSessions:xe,setView:Ue,setWorkspaceBusy:Ze}){function it(G){Q.bootstrap(G).then(e).catch(_=>{console.warn("[chat] Message was accepted, but the post-send bootstrap refresh failed.",_);const W=_ instanceof Error?_.message:String(_);we(`Message sent, but the chat list could not refresh: ${W}`)})}const at=y.useRef(new Set),Ne=g?.providers??null;function We(G,_){return G==="codex"?void 0:_}function qe(G){return!!(G&&G.provider!=="codex"&&(G.workspaceKind==="local_project"&&G.cwd?.trim()||(G.workspaceKind==="sandbox"||G.workspaceKind==="sandbox_template"||G.workspaceKind==="sandbox_app")&&G.workspaceId))}function q(G){je(G),de(_=>Yo(G,_,Ne)),Ue("chat")}async function N(G,_){return(wA(_,P)??await vy({teamId:_,accountKey:P,fetchAgents:async Z=>(await Q.listSandboxAgents(t,{teamId:Z})).agents})).find(Z=>Z.projectId===G)??null}async function F(){if(!t)throw new Error("OpenPond App server is not connected.");if(g?.account.state!=="signed_in")throw new Error("Add an OpenPond account before syncing a Project to Cloud.");const G=await Q.organizations(t),_=cp(G.organizations.map(ap).filter(W=>!!W).filter(W=>W.status==="active"),g?.preferences.defaultTeamId??null);if(!_)throw new Error("Add an OpenPond account before syncing a Project to Cloud.");if(!lp(_))throw new Error(`You need owner or admin access to create projects in ${_.displayName}.`);return _}async function ee(G){if(!t)return!1;const _=L;if(!_)throw new Error("Select a local Project before using /sync-cloud.");const W=await F(),ne=_.linkedSandboxProject?.defaultBranch?.trim()||"main",Z=wt("local",_.id),ce=za(_,I),pe=await Q.createSession(t,{provider:"openpond",modelRef:ei("openpond",zs,Ne),openPondCommandAccessMode:We("openpond",i),appId:null,appName:null,workspaceKind:"local_project",workspaceId:_.id,workspaceName:_.name,localProjectId:_.id,cloudProjectId:ce?.id??null,cloudTeamId:ce?.teamId??null,cwd:_.workspacePath,title:`Sync ${_.name} to Cloud`});xe(fe=>[pe,...fe]),G.onSessionCreated?.(pe),G.selectSession&&(le(pe.id),Ie(Z),Le(null),Ue("chat"),m(Z)),G.clearPromptForTurn(),Ze(!0);try{const fe=await Q.uploadLocalProjectCloudSource(t,_.id,{teamId:W.teamId,projectName:_.name,branch:ne,chatSessionId:pe.id,displayPrompt:G.displayPrompt});return e(fe.bootstrap),m(Z),m(wt("cloud",fe.project.id)),!0}catch(fe){const Ae=await Q.bootstrap(t).catch(()=>null);throw Ae&&e(Ae),fe}finally{Ze(!1)}}async function me(G){if(!t||G.providerForTurn==="codex"||G.selectedSessionForTurn?.provider==="codex")return!1;let _=qe(G.selectedSessionForTurn)?G.selectedSessionForTurn:null;if(!_&&G.selectedSessionForTurn)throw new Error("Select a project to use this.");if(!_)if(E){const ne=wt("cloud",E.id),Z=G.providerForTurn;_=await Q.createSession(t,{provider:Z,modelRef:ei(Z,G.modelForTurnValue,Ne),openPondCommandAccessMode:We(Z,G.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:E.id,workspaceName:E.name,localProjectId:null,cloudProjectId:E.id,cloudTeamId:E.teamId,cwd:null,autoTitlePrompt:dr(G.command)}),xe(ce=>[_,...ce]),G.onSessionCreated?.(_),G.selectSession&&(le(_.id),Ie(ne),Le(null),Ue("chat"),m(ne))}else{const ne=L;if(!ne)throw new Error("Select a project to use this.");const Z=za(ne,I),ce=wt("local",ne.id),pe=G.providerForTurn;_=await Q.createSession(t,{provider:pe,modelRef:ei(pe,G.modelForTurnValue,Ne),openPondCommandAccessMode:We(pe,G.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"local_project",workspaceId:ne.id,workspaceName:ne.name,localProjectId:ne.id,cloudProjectId:Z?.id??null,cloudTeamId:Z?.teamId??null,cwd:ne.workspacePath,autoTitlePrompt:dr(G.command)}),xe(fe=>[_,...fe]),G.onSessionCreated?.(_),G.selectSession&&(le(_.id),Ie(ce),Le(null),Ue("chat"),m(ce))}if(!_)throw new Error("Select a project to use this.");G.clearPromptForTurn();const W=await Q.runSessionCommand(t,_.id,{command:G.command,cwd:_.cwd});return xe(ne=>tc(ne,W.session)),ke(ne=>Qi(ne,W.events)),!0}async function $e(G=[],_=null,W,ne={}){const Z=W??h();let ce=Z.trim()||(G.length>0?"Please review the attached files.":"");if(!t||!ce)return!1;const pe=ne.displayPrompt?.trim()||ce,fe=ne.provider??s,Ae=ne.model??r,Ce=ne.openPondCommandAccessMode??i,He=ne.session!==void 0,Pe=He?ne.session??null:H,Xe=ne.experience??Pe?.experience??c,ut=Xe==="development"||Xe==="work"&&(Pe?.workspaceKind==="local_project"||!!Pe?.localProjectId||!!Pe?.cloudProjectId||!He&&!!(L||E||$||J==="hybrid"||J==="local")),fn=He||!ut?null:$,jt=He||!ut?null:L,dn=He||!ut?null:E,yn=He||!ut?null:z,Sn=!He&&ut&&J==="hybrid",Qt=ne.selectSession??!0,Wa=ne.chatMessages??S,wa=ne.session!==void 0?null:A,zn=ne.clearPrompt===void 0?()=>{te(""),Me(null)}:ne.clearPrompt,$n=_?null:lte(ce,O),Ht=_??$n?.action??null,St=$n?.prompt||ce,xn=ut&&!Ht?fte(ce):null,xt=Ht||xn?null:pte(ce),Nt=xt&&!FA({id:xt.command},Xe)?xt:null,_a=ne.usageAttribution??(xt?{surface:"chat",workflowKind:"slash_command",commandName:`/${xt.command}`,commandSource:"prompt_parse"}:void 0);we(null);let Ft=null,kn=null;try{if(!ut&&fe==="codex")throw new Error("The Codex provider requires repository-aware Work.");if(Nt)throw new Error(`/${Nt.command} isn't available in ${Xe}.`);if(xn&&fe!=="codex"&&Pe?.provider!=="codex"){if(G.length>0)throw new Error("Direct commands do not accept attachments.");return await me({command:xn.command,clearPromptForTurn:zn,modelForTurnValue:Ae,onSessionCreated:ne.onSessionCreated,openPondCommandAccessModeForTurn:Ce,providerForTurn:fe,selectedSessionForTurn:Pe,selectSession:Qt})}if(!He&&xt?.command==="sync-cloud")return await ee({clearPromptForTurn:zn,displayPrompt:pe,onSessionCreated:ne.onSessionCreated,selectSession:Qt});if(Ht){const K=PX(Ht);if(K){let Je=Pe;if(!Je||Je.cloudProjectId!==K.projectId){Je=await Q.createSession(t,{provider:"openpond",modelRef:ei("openpond",Ae,Ne),openPondCommandAccessMode:We("openpond",Ce),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:K.projectId,workspaceName:K.projectName??K.agentName,localProjectId:null,cloudProjectId:K.projectId,cloudTeamId:K.teamId,cwd:null,autoTitlePrompt:dr(pe)}),xe(Ja=>[Je,...Ja]),ne.onSessionCreated?.(Je),Qt&&le(Je.id);const Nn=wt("cloud",K.projectId);Qt&&Ie(Nn),Qt&&m(Nn)}const Rn=await Q.runSandboxAgent(t,K.agentId,jX({agent:K,attachments:G,displayPrompt:pe,prompt:St})),ft=await Q.bootstrap(t);return e(ft),zn(),ke(Nn=>Qi(Nn,wk({action:Ht,prompt:pe,runPayload:Rn,sessionId:Je.id}))),!0}const Be=xy(Ht);if(Be){let Je=Pe;(!Je||Je.provider!=="openpond")&&(Je=await Q.createSession(t,{provider:"openpond",modelRef:ei("openpond",Ae,Ne),openPondCommandAccessMode:We("openpond",Ce),appId:null,appName:null,workspaceId:null,workspaceName:"OpenPond profile",localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,autoTitlePrompt:dr(pe)}),xe(ft=>[Je,...ft]),ne.onSessionCreated?.(Je),Qt&&le(Je.id)),await Q.runProfileAction(t,EX({action:Be,attachments:G,displayPrompt:pe,prompt:St,sessionId:Je.id}));const Rn=await Q.bootstrap(t);return e(Rn),zn(),!0}const _e=TA({cloudProjects:I,selectedCloudProject:E,selectedProject:L});if(!_e)throw new Error("Select a Project linked to an OpenPond Cloud Project before running an action.");let Ve=Pe;(!Ve||Ve.cloudProjectId!==_e.id)&&(Ve=await Q.createSession(t,{provider:"openpond",modelRef:ei("openpond",Ae,Ne),openPondCommandAccessMode:We("openpond",Ce),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:_e.id,workspaceName:_e.name,localProjectId:_e.localProjectId,cloudProjectId:_e.id,cloudTeamId:_e.teamId,cwd:null,autoTitlePrompt:dr(pe)}),xe(Je=>[Ve,...Je]),ne.onSessionCreated?.(Ve),Qt&&(le(Ve.id),Ie(_e.selectionKey),m(_e.selectionKey)));const It=await N(_e.id,_e.teamId);if(!It)throw new Error("No OpenPond Agent is available for this Project.");zn();const na=await Q.runSandboxAgent(t,It.id,MX({action:Ht,attachments:G,displayPrompt:pe,prompt:St,teamId:_e.teamId})),In=await Q.bootstrap(t);return e(In),ke(Je=>Qi(Je,wk({action:Ht,prompt:pe,runPayload:na,sessionId:Ve.id}))),!0}let rt=Pe;if(rt&&Vt(rt.id)){kn=$x({afterMessageId:Wa.at(-1)?.id??null,attachments:G,content:ce,sessionId:rt.id}),zn(),Ft=rt.id,at.current.add(Ft),ue?.(kn),be?.(Ft,!0);const K=xte(rt.id,ce),Be=Ve=>{(!He||H?.id===rt.id)&&Se(It=>Ste(It,Ve)),ne.onCodexHistoryOptimisticEvent?.(Ve)};Be(K),oe(Ve=>Ve.map(It=>It.id===rt.id?{...It,status:"active"}:It));const _e=await Q.sendCodexHistoryTurn(t,rt.id,{prompt:ce,attachments:G.length>0?G:void 0,model:iy("codex",Ae,Ne),modelRef:ei("codex",Ae,Ne),...YS(n),codexPermissionMode:n,codexReasoningEffort:a}).catch(Ve=>{throw Be(kte(K,Ve)),Ve});return(!He||H?.id===rt.id)&&Se(Ve=>Qi(Ve,_e.events)),oe(Ve=>tc(Ve,_e.session)),re?.(_e),it(t),!0}const ui=(wa?k.find(K=>K.id===wa&&CJ(Z,K)&&K.sandbox)??null:null)??RJ(Z,GP(k)),mi=Xe==="chat"?[]:zJ(Z,C).map(K=>K.ref);if(!rt){const K=yn?.appId??fn?.id??null,Be=yn?.appName??fn?.name??null,_e=dn,Ve=He?null:za(jt,I),It=Sn?zP({cloudProjects:I,selectedCloudProject:_e,selectedProject:jt}):null;if(It?.kind==="missing_cloud_project")throw new Error(It.message);const na=It?.kind==="ready",In=na?fe:_e?"openpond":fe,Je=ei(In,Ae,Ne),Rn=We(In,Ce),ft=na?BP({modelRef:Je,provider:In,target:It,title:ce.slice(0,64)}):null;rt=await Q.createSession(t,ft?{...ft,subagentDelegationMode:X,metadata:{...ft.metadata,...ne.sessionMetadata??{}},...Rn?{openPondCommandAccessMode:Rn}:{},autoTitlePrompt:dr(ce)}:{experience:Xe,provider:In,modelRef:Je,subagentDelegationMode:X,...Rn?{openPondCommandAccessMode:Rn}:{},appId:K,appName:Be,workspaceKind:_e?"sandbox":jt?"local_project":fn?"sandbox_app":void 0,workspaceId:jt?.id??(fn?K:void 0),workspaceName:_e?.name??jt?.name??Be,localProjectId:jt?.id??null,cloudProjectId:_e?.id??Ve?.id??null,cloudTeamId:_e?.teamId??Ve?.teamId??null,...!_e&&!jt&&!fn&&J==="local"?{metadata:{...oJ(),...ne.sessionMetadata??{}}}:{cwd:jt?jt.workspacePath:null,...ne.sessionMetadata?{metadata:ne.sessionMetadata}:{}},autoTitlePrompt:dr(ce)}),xe(Nn=>[rt,...Nn]),ne.onSessionCreated?.(rt),Qt&&(le(rt.id),_e&&Ie(wt("cloud",_e.id)),rt.workspaceKind==="local_project"&&rt.workspaceId&&m(wt("local",rt.workspaceId)),_e&&m(wt("cloud",_e.id)))}if(_k(rt)&&Oi(rt.workspaceKind)&&rt.provider!=="openpond"&&!$i(rt))throw new Error("Cloud workspaces use OpenPond Chat. Switch to Local to use local providers.");if(_k(rt)&&Oi(rt.workspaceKind)&&u)try{rt=await u(rt)}catch(K){const Be=K instanceof Error?K.message:String(K);throw await Q.recordPreflightTurnFailure(t,rt.id,{prompt:ce,error:Be,target:$i(rt)?"hybrid_sandbox":"cloud_workspace"}).then(e).catch(()=>{}),K}kn=$x({afterMessageId:Wa.at(-1)?.id??null,attachments:G,content:ce,sessionId:rt.id}),zn(),Ft=rt.id,at.current.add(Ft),ue?.(kn),xe(K=>K.map(Be=>Be.id===Ft?{...Be,status:"active"}:Be));const ha=fe,Ca=yte({provider:ha,model:Ae,providerSettings:Ne}),Bn=WW(ha,Ca.model??Ae,Ne),Li=ha==="codex"?YS(n):{approvalPolicy:"on-request",sandbox:"workspace-write"};await Q.sendTurn(t,rt.id,{prompt:ce,metadata:ne.turnMetadata,attachments:G.length>0?G:void 0,mentionedAppIds:ui?[ui.id]:void 0,mentionedConnectedApps:mi.length>0?mi:void 0,openPondActionCatalog:j.length>0?j:void 0,usageAttribution:_a,...Ca,...Li,codexPermissionMode:ha==="codex"?n:"default",codexReasoningEffort:Bn?KW(ha,Ca.model??Ae,a,Ne):void 0}),it(t);const Ga=rt.workspaceId??rt.appId;return Ga&&rt.workspaceKind!=="sandbox"&&rt.workspaceKind!=="sandbox_template"&&M(Ga,!1).then(K=>{K?.initialized&&R(Ga)}),!0}catch(rt){return we(rt instanceof Error?rt.message:String(rt)),!1}finally{Ft&&at.current.delete(Ft),Ft&&Vt(Ft)&&be?.(Ft,!1),Ft&&(Vt(Ft)?oe(rt=>rt.map(jn=>jn.id===Ft&&jn.status==="active"?{...jn,status:"idle"}:jn)):xe(rt=>rt.map(jn=>jn.id===Ft&&jn.status==="active"?{...jn,status:"idle"}:jn)))}}async function ze(G,_){const W=at.current.values().next().value??null,ne=G??H?.id??W;if(!t||!ne)return!1;if(we(null),Vt(ne))try{const Z=await Q.interruptCodexHistoryTurn(t,ne);if(!Z.interrupted){if(Z.reason==="no_active_openpond_turn"){const pe=await Q.codexHistoryThread(t,ne,{tail:!0}),fe={...pe.session,status:"idle"};return H?.id===ne&&Se(Ae=>Qi(Ae,pe.events)),oe(Ae=>tc(Ae,fe)),we("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 we("This Codex history turn is still starting. Try stopping it again in a moment."),!1}const ce=await Q.codexHistoryThread(t,ne,{tail:!0});return H?.id===ne&&Se(pe=>Qi(pe,ce.events)),oe(pe=>tc(pe,ce.session)),!0}catch(Z){const ce=Z instanceof Error?Z.message:String(Z);return we(ce==="Not found"?"OpenPond could not find this Codex history session, so it cannot interrupt it here.":ce),!1}try{await Q.interruptTurn(t,ne,_);const Z=await Q.bootstrap(t);return e(Z),!0}catch(Z){return we(Z instanceof Error?Z.message:String(Z)),!1}}async function tt(G,_){if(!t){we("OpenPond App server is not connected.");return}we(null),await Q.applyCreateImproveAction(t,G.id,{..._,runId:G.id,expectedRevision:G.revision,actionId:`web:${_.type}:${crypto.randomUUID()}`});const W=await Q.bootstrap(t);e(W)}async function nt(G){await tt(G.run,{type:"approve_plan"})}async function mt(G){await tt(G.run,{type:"cancel",reason:null})}async function vt(G,_){await tt(G.run,{type:"revise_plan",revision:_})}async function Oe(G,_,W){await tt(G.run,{type:"answer_question",questionId:_,value:W})}async function Ye(G){await tt(G.run,{type:"pause"})}async function f(G){await tt(G.run,{type:"resume"})}async function U(G,_){await tt(G.run,{type:"open_pull_request",candidateId:_})}async function Y(G,_){await tt(G.run,{type:"apply_candidate",candidateId:_})}async function ge(G,_){await tt(G.run,{type:"reject_candidate",candidateId:_,reason:null})}async function se(G,_){await tt(G.run,{type:"reconcile_pull_request",candidateId:_})}return{answerCreateImproveQuestion:Oe,approveCreateImproveRun:nt,applyCreateImproveCandidate:Y,cancelCreateImproveRun:mt,changeDraftProvider:q,openCreateImprovePullRequest:U,pauseCreateImproveRun:Ye,reconcileCreateImprovePullRequest:se,rejectCreateImproveCandidate:ge,resumeCreateImproveRun:f,reviseCreateImproveRun:vt,sendPrompt:$e,stopTurn:ze}}function _k(e){return e.experience==="development"||e.experience==="work"&&(e.workspaceKind==="local_project"||!!e.localProjectId||!!e.cloudProjectId||e.metadata?.workspaceTarget==="local")}async function wte({branch:e,connection:t,session:n}){if(!Oi(n.workspaceKind))return{sandbox:null,session:n,status:"already_running"};const a=await Q.ensureCloudWorkspaceReady(t,n.id,{branch:e,surface:"desktop"});return{bootstrap:await Q.bootstrap(t),output:a.output,sandbox:null,session:a.session,status:a.status}}function _te(e){return $i(e)?"Preparing Hybrid sandbox...":"Starting Cloud workspace..."}function Cte(e,t){if(e==="already_running")return null;const n=$i(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 Rte(e,t){return!e.cloudProjectId||!e.cloudTeamId?!0:t.some(n=>n.id===e.cloudProjectId&&n.teamId===e.cloudTeamId)}function Pte({applyBootstrapPayload:e,cloudProjects:t,connection:n,localProjectById:a,selectedCloudProject:i,selectedProject:r,setWorkspaceBusy:s,showToast:c,visibleWorkspaceState:m}){return y.useCallback(async u=>{if(!n)throw new Error("OpenPond App server is not connected.");const h=r??(u.localProjectId?a.get(u.localProjectId)??null:null);if(u.cloudProjectId&&u.cloudTeamId&&!Rte(u,t))throw new Error("This Cloud session belongs to a different OpenPond account. Sync or select a Project in the current account.");u.workspaceId||c(_te(u),"info"),s(!0);try{const g=await wte({branch:r?.linkedSandboxProject?.defaultBranch??i?.defaultBranch??m?.currentBranch??null,connection:n,localProject:h,session:u,source:$i(u)?"openpond-app-hybrid-chat-preflight":"openpond-app-cloud-chat-preflight"});g.bootstrap&&e(g.bootstrap);const S=Cte(g.status,u);return S&&c(S,"success"),g.session}finally{s(!1)}},[e,t,n,a,i,r,s,c,m?.currentBranch])}function Ate(){return{diffPanelOpen:!1,diffPanelExpanded:!1,rightPanelMode:"changes",rightChatPanels:[]}}function Tte(e){return{diffPanelOpen:e.diffPanelOpen,diffPanelExpanded:e.diffPanelExpanded,rightPanelMode:e.rightPanelMode,rightChatPanels:e.rightChatPanels}}function Ck(e){return{...e,rightChatPanels:e.rightChatPanels.map(t=>({...t}))}}function Ete(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 i=t.rightChatPanels[a];return!!(i&&n.id===i.id&&n.activationVersion===i.activationVersion&&n.sessionId===i.sessionId&&n.prompt===i.prompt&&n.provider===i.provider&&n.model===i.model&&n.scrollTop===i.scrollTop&&n.stickyToBottom===i.stickyToBottom)})}function Mte(e){return`${e.conversationId}\0${e.workspaceSourceKey||"none"}`}function jte(e){const{appDispatch:t,diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:i,rightPanelMode:r,selectedAppId:s,selectedCloudProject:c,selectedProjectId:m,selectedSession:u,selectedSessionId:h,setWorkspaceDiffPanelViewState:g,view:S,viewWorkspaceAppId:k,viewWorkspaceId:C,viewWorkspaceKind:A,workspaceDiffPanelViewState:M}=e,R=y.useRef(new Map),$=y.useRef(new Map),O=y.useRef(null),j=y.useRef(null),I=h??`draft:${m??s??c?.id??"general"}`,P=y.useMemo(()=>C?`${A??"workspace"}:${C}`:k?`app:${k}`:u?.cwd&&!Oi(u.workspaceKind)?`cwd:${u.cwd}`:"none",[u?.cwd,u?.workspaceKind,S,k,C,A]),E=Mte({conversationId:I,workspaceSourceKey:P}),L=y.useMemo(()=>Tte({diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:i,rightPanelMode:r}),[n,a,i,r]);y.useEffect(()=>{const H=O.current;H&&R.current.set(H,Ck(L))},[I,L]),y.useEffect(()=>{if(O.current===I)return;O.current=I;const J=R.current.get(I)??Ate();Ete(L,J)||t({type:"patch",patch:Ck(J)})},[I,L]),y.useEffect(()=>{const H=j.current;H&&$.current.set(H,xh(M))},[E,M]),y.useEffect(()=>{if(j.current===E)return;j.current=E;const J=$.current.get(E)??FP();g(X=>Ix(X,J)?X:xh(J))},[E]);const z=y.useCallback(H=>{g(J=>Ix(J,H)?J:xh(H))},[]);return{browserConversationId:I,handleWorkspaceDiffPanelViewStateChange:z}}function Ote({account:e,accountPending:t,accountSignedOut:n,activeWorkspaceKind:a,activeWorkspaceLocation:i,appDispatch:r,applyBootstrapPayload:s,busy:c,cloudSetupDialog:m,cloudProjects:u,connection:h,defaultTeamId:g,expandProject:S,localProjectById:k,selectedCloudProject:C,selectedProject:A,selectedSession:M,selectedSessionProjectId:R,setCloudSetupDialog:$,setDiffPanelOpen:O,setError:j,setSessions:I,setWorkspaceBusy:P,showToast:E,visibleWorkspaceState:L,workspaceBusy:z}){const H=e?.baseUrl??e?.activeProfile?.baseUrl??null,J=y.useCallback(async(te,Me)=>{if(h)try{const Se=await Q.previewLocalProjectCloudSource(h,te.id,{branch:Me});$(oe=>!oe||oe.status!=="confirm"||oe.localProjectId!==te.id||oe.branch!==Me?oe:{...oe,branch:Se.preview.branch,cloudProjectId:Se.preview.targetProjectId,preview:Se.preview,previewLoading:!1,previewError:null})}catch(Se){const oe=Se instanceof Error?Se.message:String(Se);$(be=>!be||be.status!=="confirm"||be.localProjectId!==te.id||be.branch!==Me?be:{...be,preview:null,previewLoading:!1,previewError:oe})}},[h,$]),X=y.useCallback(async()=>{const te=m;if(!te||te.status==="uploading")return;if(te.projectKind==="cloud"){$(be=>be&&{...be,status:"ready",error:null});return}if(!h){$(be=>be&&{...be,status:"error",error:"OpenPond App server is not connected."});return}const Me=te.localProjectId??"",Se=k.get(Me);if(!Se){$(be=>be&&{...be,status:"error",error:"Project is no longer available."});return}P(!0);const oe=za(Se,u);$(be=>be&&{...be,status:"uploading",error:null,previewLoading:!1});try{const be=await Q.organizations(h),re=cp(be.organizations.map(ap).filter(Ue=>!!Ue).filter(Ue=>Ue.status==="active"),g);if(!re)throw new Error("Add an OpenPond account before creating a Cloud environment.");if(!lp(re))throw new Error(`You need owner or admin access to create projects in ${re.displayName}.`);const ue=te.branch||Se.linkedSandboxProject?.defaultBranch||"main",ke=wt("local",Se.id),Le=await Q.createSession(h,{provider:"openpond",appId:null,appName:null,workspaceKind:"local_project",workspaceId:Se.id,workspaceName:Se.name,localProjectId:Se.id,cloudProjectId:oe?.id??null,cloudTeamId:oe?.teamId??null,cwd:Se.workspacePath,title:`Sync ${Se.name} to Cloud`});I(Ue=>[Le,...Ue]),r({type:"selectSession",sessionId:Le.id,projectId:ke}),S(ke);const Ie=await Q.uploadLocalProjectCloudSource(h,Se.id,{teamId:re.teamId,projectName:Se.name,branch:ue,chatSessionId:Le.id,displayPrompt:`/sync-cloud ${Se.name}`});s(Ie.bootstrap),S(ke),S(wt("cloud",Ie.project.id));const le=Kg({accountBaseUrl:H,teamId:Ie.project.teamId,projectId:Ie.project.id,projectName:Ie.project.name,baseBranch:Ie.upload.branch,localProjectId:Se.id,source:"openpond-app"}),xe=xk({accountBaseUrl:H,organizationSlug:Ie.project.organizationSlug,projectSlug:Ie.project.slug});$({status:"ready",localProjectId:Se.id,cloudProjectId:Ie.project.id,teamId:Ie.project.teamId,projectName:Ie.project.name,projectKind:"local",projectUrl:xe,setupUrl:le,branch:Ie.upload.branch,preview:te.preview??null,previewLoading:!1,previewError:null,upload:{branch:Ie.upload.branch,headCommit:Ie.upload.headCommit,fileCount:Ie.upload.fileCount,byteCount:Ie.upload.byteCount,skippedCount:Ie.upload.skippedCount,initializedEmptyProject:Ie.upload.initializedEmptyProject},error:null}),E("Source uploaded to OpenPond Git. Cloud setup link is ready.","success")}catch(be){const re=be instanceof Error?be.message:String(be),ue=h?await Q.bootstrap(h).catch(()=>null):null;ue&&s(ue),j(re),$(ke=>ke&&{...ke,status:"error",error:re})}finally{P(!1)}},[H,r,s,m,u,h,g,S,k,$,j,I,P,E]),de=y.useCallback((te,Me)=>{if(!h){E("OpenPond App server is not connected.","error");return}if(t){E("Checking OpenPond account. Try again in a moment.","info");return}if(n){E("Add an OpenPond account before using Cloud.","error");return}const Se=Me||te.linkedSandboxProject?.defaultBranch||"main";$({status:"confirm",localProjectId:te.id,projectName:te.name,projectKind:"local",projectUrl:null,setupUrl:null,branch:Se,preview:null,previewLoading:!0,previewError:null,upload:null,error:null}),J(te,Se)},[t,n,h,J,$,E]),je=y.useCallback(async te=>{if(te===i||z||c)return;if(j(null),te==="upload_cloud"){if(!A){E("Select a local Project before uploading source.","error");return}de(A,L?.currentBranch??null);return}if(te==="local"){const oe=M?.localProjectId??A?.id??R??null,be=oe?k.get(oe)??null:null;if(!be){E("No linked local workspace for this Cloud chat.","error");return}if(Oi(a)&&!window.confirm("Switch to Local? Cloud changes will stay in the hosted workspace until you preserve or export them."))return;const re=wt("local",be.id);r({type:"selectProject",projectId:re}),S(re),O(!1),E(`Switched to Local: ${be.name}`,"info");return}if(!h){E("OpenPond App server is not connected.","error");return}if(t){E("Checking OpenPond account. Try again in a moment.","info");return}if(n){E("Add an OpenPond account before using Cloud.","error");return}if(C){$({status:"ready",cloudProjectId:C.id,teamId:C.teamId,projectName:C.name,projectKind:"cloud",projectUrl:xk({accountBaseUrl:H,organizationSlug:C.organizationSlug,projectSlug:C.slug}),setupUrl:Kg({accountBaseUrl:H,teamId:C.teamId,projectId:C.id,projectName:C.name,baseBranch:C.defaultBranch,source:"openpond-app"}),branch:C.defaultBranch??"main",preview:null,previewLoading:!1,previewError:null,upload:null,error:null});return}const Me=A;if(!Me){E("Select a Project before Cloud coding.","error");return}const Se=L?.currentBranch||Me.linkedSandboxProject?.defaultBranch||"main";de(Me,Se)},[H,t,n,a,i,r,c,h,u,S,k,de,C,A,M,R,$,O,j,E,L?.currentBranch,z]),we=y.useCallback(te=>{ty(te)&&de(te.project)},[de]);return{changeWorkspaceTarget:je,moveProjectToCloud:we,openCloudSetupForLocalProject:de,startCloudSetupUpload:X}}function $te({advanceTrainingTurn:e,bindTrainingSession:t,composerDraftStore:n,onSessionCreated:a,onSubmitted:i,prepareTrainingTurn:r,sendPrompt:s,setMentionedAppId:c,showToast:m}){return y.useCallback(async(u=[],h=null,g,S={})=>{const k=g??n.getSnapshot(),C=r(k);if(C.active&&k.trim()&&!C.metadata)return m(C.error??"Load the selected generated Taskset question before sending, or close the generated-question handoff to write a normal prompt.","error"),!1;const A=await s(u,h,g,{clearPrompt:S.preservePrompt?()=>{}:void 0,displayPrompt:S.displayPrompt,onSessionCreated:M=>{a(M),C.metadata&&t(M.id)},turnMetadata:C.metadata||S.turnMetadata?{...C.metadata??{},...S.turnMetadata??{}}:void 0,sessionMetadata:C.metadata?{trainingTasksetId:C.metadata.trainingTasksetId,trainingTasksetName:C.metadata.trainingTasksetName}:void 0});return A&&await i?.(),A&&C.metadata&&e(),A},[e,t,n,a,i,r,s,c,m])}function Nte({appDispatch:e,connection:t,sessions:n,setDiffPanelOpen:a,setRightPanelMode:i,setSessions:r,setView:s}){return y.useCallback(async c=>{if(!t)return;const m=n.find(g=>!g.archived&&g.workspaceKind==="sandbox"&&g.workspaceId===c.sandboxId);if(m){e({type:"selectSession",sessionId:m.id,appId:null,projectId:null}),i("changes"),a(!0),s("chat");return}const u=c.name??`Sandbox ${c.sandboxId.slice(0,8)}`,h=await Q.createSession(t,{provider:"openpond",appId:null,appName:null,workspaceKind:"sandbox",workspaceId:c.sandboxId,workspaceName:u,cwd:null,title:u});r(g=>[h,...g]),e({type:"selectSession",sessionId:h.id,appId:null,projectId:null}),i("changes"),a(!0),s("chat")},[e,t,n,a,i,r,s])}function Dte({connection:e,defaultTeamId:t,sessions:n,selectedProjectId:a,confirmProjectAction:i,applyBootstrapPayload:r,expandProject:s,setExpandedProjectIds:c,setSelectedAppId:m,setSelectedProjectId:u,setSelectedSessionId:h,setError:g,setView:S,showToast:k}){function C(O){const j=wt("local",O.id);m(null),u(j),h(null),S("chat"),s(j)}async function A(O){if(!e)return!1;g(null);try{const j=await Q.createLocalProject(e,O);return r(j.bootstrap),C(j.project),k(j.created===!1?`Opened ${j.project.name}`:`Created ${j.project.name}`,"success"),!0}catch(j){const I=j instanceof Error?j.message:String(j);return g(I),k(I,"error"),!1}}async function M(O){if(!e)return!1;const j=O.trim();if(!j)return!1;g(null);try{const I=await Q.createLocalProject(e,{createNew:!0,name:j});return r(I.bootstrap),C(I.project),k(`Created ${I.project.name}`,"success"),!0}catch(I){return g(I instanceof Error?I.message:String(I)),k("Project could not be created","error"),!1}}async function R(O){if(!e)return!1;const j=O.trim();if(!j)return!1;g(null);try{const I=await Q.organizations(e),P=cp(I.organizations.map(ap).filter(J=>!!J).filter(J=>J.status==="active"),t);if(!P)throw new Error("Add an OpenPond account before creating a Cloud Project.");if(!lp(P))throw new Error(`You need owner or admin access to create projects in ${P.displayName}.`);const E=`${VP(j)}-${Date.now().toString(36)}`;let L=(await Q.upsertSandboxProject(e,{teamId:P.teamId,name:j,sourceType:"internal_repo",normalizedSourceIdentity:E,internalRepoPath:E,defaultBranch:"main",sourceConfig:{sourceType:"internal_repo",sourceValue:E},metadata:{source:"openpond-app-new-cloud-project"}})).project;L=(await Q.uploadSandboxProjectSource(e,L.id,{teamId:P.teamId,branch:"main",commitMessage:"Initialize cloud project",entries:[{path:"README.md",type:"file",contentsBase64:gJ(`# ${j}
212
+
213
+ Created in OpenPond Cloud.
214
+ `)}]})).project;const z=await Q.bootstrap(e);r(z);const H=wt("cloud",L.id);return m(null),u(H),h(null),S("chat"),s(H),k(`Created Cloud Project: ${L.name}`,"success"),!0}catch(I){const P=I instanceof Error?I.message:String(I);return g(P),k(P,"error"),!1}}async function $(O){if(!e)return;if(qW(O)){const E=`Archive ${O.project.name} in OpenPond Cloud?`;if(!(i?await i({title:"Archive Cloud Project",body:`${O.project.name} will be archived in OpenPond Cloud. Existing task history stays available through Cloud history.`,confirmLabel:"Archive project"}):window.confirm(E)))return;g(null);try{await Q.archiveSandboxProject(e,O.project.id,{teamId:O.project.teamId}),r(await Q.bootstrap(e)),c(z=>{const H=new Set(z);return H.delete(O.id),H}),a===O.id&&(u(null),h(null)),k(`Archived ${O.project.name}`,"success")}catch(z){g(z instanceof Error?z.message:String(z)),k("Cloud Project could not be archived","error")}return}if(!ty(O))return;const j=O.project,I=`Remove ${j.name} from Projects? The folder will not be deleted.`;if(i?await i({title:"Remove Project",body:`${j.name} will be removed from the sidebar. The folder and files on disk will not be deleted.`,confirmLabel:"Remove project"}):window.confirm(I)){g(null);try{const E=await Q.deleteLocalProject(e,j.id);r(E),c(L=>{const z=new Set(L);return z.delete(O.id),z}),a===O.id&&(u(null),h(L=>{const z=n.find(H=>H.id===L);return z?.workspaceKind==="local_project"&&z.workspaceId===j.id?null:L})),k(`Removed ${j.name}`,"success")}catch(E){g(E instanceof Error?E.message:String(E)),k("Project could not be removed","error")}}}return{createCloudProjectFromScratch:R,createProjectFromScratch:M,createProjectCollection:A,removeProject:$}}function Hte({appDispatch:e,busy:t,cloudProjectById:n,createCloudProjectFromScratch:a,createProjectFromScratch:i,createProjectCollection:r,expandProject:s,localProjectById:c,onCreateCloudEnvironment:m,onNewCloudProject:u,onNewLocalProject:h,onUseExistingFolderPath:g,newProjectBusy:S,newProjectMode:k,newProjectName:C,projectTargetValue:A,setDiffPanelOpen:M,setDraftModel:R,setDraftProvider:$,setError:O,setNewProjectBusy:j,setNewProjectDialogOpen:I,setNewProjectName:P,setNewProjectPath:E,showToast:L,workspaceBusy:z}){const H=y.useCallback(X=>{if(X===A||t||z)return;if(O(null),X==="action:new-local-project"){h();return}if(X==="action:add-local-project"){g();return}if(X==="action:add-local-project-path"){g();return}if(X==="action:new-cloud-project"){u();return}if(X==="action:create-cloud-environment"){m();return}if(X==="none"){e({type:"selectProject",projectId:null}),M(!1),L("Started a chat without project files.","info");return}const de=X.indexOf(":"),je=de>=0?X.slice(0,de):"",we=de>=0?X.slice(de+1):"";if(je==="local"){const te=c.get(we);if(!te){L("Project is no longer available.","error");return}const Me=wt("local",te.id);e({type:"selectProject",projectId:Me}),s(Me),M(!1);return}if(je==="cloud"){const te=n.get(we);if(!te){L("Cloud Project is no longer available.","error");return}const Me=wt("cloud",te.id);e({type:"selectProject",projectId:Me}),s(Me),$("openpond"),R(Se=>Yo("openpond",Se)),M(!1)}},[e,t,n,s,c,m,u,h,g,A,M,R,$,O,L,z]),J=y.useCallback(async X=>{const de=C.trim();if(!S){if(k==="existing-local"?!X?.name.trim()||!X.sourceFolders.length:!de)return!1;j(!0);try{const je=k==="cloud"?await a(de):k==="existing-local"?await r(X):await i(de);return je&&(I(!1),P(""),E("")),!!je}finally{j(!1)}}},[a,i,r,S,k,C,j,I,P,E]);return{changeProjectTarget:H,submitNewProjectDialog:J}}function Lte(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 soe(e){return e.reduce((t,n)=>!t||n.activationVersion>=t.activationVersion?n:t,null)}function qte(e,t){const n=Math.max(0,...e.map(r=>r.activationVersion))+1;let a=!1;const i=e.map(r=>r.id!==t?r:(a=!0,{...r,activationVersion:n}));return a?i:[...e]}function Ute(e,t){const n=Math.max(0,...e.map(r=>r.activationVersion))+1;let a=!1;const i=e.map(r=>r.sessionId!==t.sessionId?r:(a=!0,{...r,activationVersion:n,prompt:t.prompt??r.prompt}));return a?i:[...e]}function VA(e){return!!(e.parentSessionId&&e.subagentRunId)}function zte(e){const t=e.sessions.filter(VA);return{knownSessionIds:new Set(t.map(n=>n.id)),newSessions:t.filter(n=>!e.knownSessionIds.has(n.id))}}function Bte(e,t){const n=new Set(e.map(i=>i.sessionId).filter(Boolean)),a=t.filter(VA).filter(i=>!n.has(i.id)).map(i=>({id:`right-subagent-${i.id}`,activationVersion:1,sessionId:i.id,prompt:"",provider:i.provider,model:i.modelRef?.modelId??"",scrollTop:0,stickyToBottom:!0}));return a.length>0?[...e,...a]:e}const Rk="openpond/openpond",Fte="github.issue.write";function Vte(e){return e.some(t=>t.provider==="github"&&(t.ref.capabilities??[]).includes(Fte))}function loe(e){return[`Title: ${e.title.trim()}`,"","Description:",e.description.trim()].join(`
215
+ `)}function Kte(e){const t=e.trim();return[`@github Submit this request as a new GitHub issue in ${Rk}.`,`Use the GitHub connected app write operation github.issue.create with input.repo set to ${Rk}, 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:
216
+ ${t}`].join(`
217
+ `)}function Wte(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(`
218
+
219
+ `),requiresInstructions:!0};case"train":return{kind:"open_training",objective:n||null};case"submit-issue":return{kind:"send_prompt",prompt:Kte(n),requiresInstructions:!0};case"sync-cloud":return{kind:"send_prompt",prompt:`/sync-cloud ${n}`,requiresInstructions:!1}}}const Pk=[];function Gte(e){const{approvals:t,codexHistoryEvents:n,contextCompaction:a,pendingChatUserMessages:i,rightChatHistoryEvents:r,rightChatPanels:s,runningSessionIds:c,selectedSessionId:m,sidebarSessions:u}=e;return y.useMemo(()=>{const h=new Map(u.map(S=>[S.id,S])),g=Jte(t);return s.map(S=>{const k=S.sessionId?h.get(S.sessionId)??null:null,C=Vt(S.sessionId),A=C?(S.sessionId?r[S.sessionId]:void 0)??(S.sessionId===m?n:Pk):Pk,M=jg(A,[]),R=S.sessionId?g.get(S.sessionId)??null:null,$=!!(k&&c.has(k.id)),O=C?w7({events:A}):null,j=k?.cwd??null,I=k?.appId??k?.localProjectId??(k?.workspaceKind==="local_project"?k.workspaceId??null:null)??(k?.cwd&&!Oi(k.workspaceKind)?c1(k.cwd):null),P=S.sessionId?i[S.sessionId]??null:null;return{...S,session:k,title:_7(O,k?.title??"New task"),messages:C?aA(rp(A),P):[],createImproveRun:O,contextWindowStatus:xP({provider:S.provider,snapshot:DP(M,S.sessionId),preferences:a}),goalRuntime:HP(M,S.sessionId),pendingApproval:R,running:$,workspaceRootPath:j,activeWorkspaceAppId:I,pendingUserMessage:P,runtimeSource:C?"history":"live"}})},[t,n,a,i,r,s,c,m,u])}function Jte(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 Zte(e){const{applyPayload:t,connection:n,locallyActiveSessionIds:a,panels:i,sessions:r,setError:s}=e,c=y.useMemo(()=>{const h=new Set,g=[];for(const S of i)!Vt(S.sessionId)||!S.sessionId||h.has(S.sessionId)||(h.add(S.sessionId),g.push(S.sessionId));return g.join(`
220
+ `)},[i]),m=y.useMemo(()=>{if(!c)return"";const h=new Set(c.split(`
221
+ `).filter(Boolean));return r.filter(g=>h.has(g.id)&&g.status==="active").map(g=>g.id).join(`
222
+ `)},[c,r]),u=y.useMemo(()=>c?c.split(`
223
+ `).filter(h=>a.has(h)).join(`
224
+ `):"",[a,c]);y.useEffect(()=>{if(!n||!c)return;const h=c.split(`
225
+ `).filter(Boolean),g=new Set(m.split(`
226
+ `).filter(Boolean)),S=new Set(u.split(`
227
+ `).filter(Boolean)),k=h.map(C=>fy({connection:n,locallyActive:S.has(C),onError:A=>s(A instanceof Error?A.message:String(A)),onPayload:A=>t(py(A,S.has(C))),reportedActive:g.has(C),sessionId:C,surface:"thread"}));return()=>k.forEach(C=>C())},[m,t,n,u,c,s])}const Ak=[];function Yte(e){const{activeModel:t,activeProvider:n,approvals:a,applyRightCodexHistoryPayload:i,codexHistoryEvents:r,connectedAppMentions:s,connection:c,contextCompaction:m,openLabTraining:u,locallyActiveCodexHistorySessionIds:h,openPondCommandAccessMode:g,pendingChatUserMessages:S,providerSettings:k,rightChatHistoryEvents:C,rightChatPanels:A,rightPanelMode:M,runtimeIndexes:R,runtimeEventStore:$,runningSessionIds:O,selectedSession:j,selectedSessionId:I,sendPrompt:P,setDiffPanelOpen:E,setError:L,setRightChatHistoryEvents:z,setRightChatPanels:H,setRightPanelMode:J,setRightPanelTabRequest:X,setView:de,showChangesPanel:je,showToast:we,sidebarSessions:te,startupReady:Me}=e,Se=y.useRef(null),oe=y.useRef(new Map),be=y.useRef(new Set);y.useEffect(()=>{if(!c)return;const Ne=A.flatMap(We=>We.sessionId&&!Vt(We.sessionId)?[We.sessionId]:[]);for(const We of Ne)Object.hasOwn(C,We)||be.current.has(We)||(be.current.add(We),Q.runtimeEventsPage(c,{sessionId:We,beforeSequence:Number.MAX_SAFE_INTEGER,limit:500}).then(qe=>{const q=qe.events.map(N=>N.event);z(N=>({...N,[We]:Xi(N[We]??Ak,q)}))}).catch(qe=>{L(qe instanceof Error?qe.message:String(qe))}).finally(()=>{be.current.delete(We)}))},[c,C,A,L,z]);const re=y.useCallback(Ne=>{X(We=>({id:(We?.id??0)+1,tab:Ne})),je()},[je]),ue=y.useCallback((Ne=null,We={})=>{const qe=Ne?.id?A.find(N=>N.sessionId===Ne.id)??null:null;if(qe)return H(N=>Ute(N,{sessionId:Ne.id,prompt:We.prompt})),E(!0),J("chat"),We.preserveView||de("chat"),qe.id;const q=Lte({sessionId:Ne?.id??null,provider:Ne?.provider??n,model:Ne?.modelRef?.modelId??t,prompt:We.prompt});return H(N=>[...N,q]),E(!0),J("chat"),We.preserveView||de("chat"),q.id},[t,n,A,E,H,J,de]);y.useEffect(()=>{if(!Me)return;const Ne=Se.current;if(!Ne){Se.current=new Set(te.filter(N=>!!(N.parentSessionId&&N.subagentRunId)).map(N=>N.id));return}const We=zte({sessions:te,knownSessionIds:Ne});Se.current=We.knownSessionIds;for(const N of We.newSessions)oe.current.set(N.id,N);const qe=j?.parentSessionId??j?.id??null;if(!qe)return;const q=[...oe.current.values()].filter(N=>N.parentSessionId===qe);if(q.length!==0){for(const N of q)oe.current.delete(N.id);H(N=>Bte(N,q)),E(!0),J("chat")}},[j?.id,j?.parentSessionId,E,H,J,te,Me]);const ke=y.useCallback(()=>{if(A.length===0){ue(null);return}E(!0),J("chat"),de("chat")},[ue,A.length,E,J,de]),Le=y.useCallback(Ne=>{const We=A.length<=1&&A.some(q=>q.id===Ne),qe=()=>{H(q=>q.filter(N=>N.id!==Ne))};if(We&&M==="chat"){if(re("files"),typeof window>"u"){qe();return}window.requestAnimationFrame(qe);return}qe()},[A,M,H,re]),Ie=y.useCallback((Ne,We)=>{H(qe=>qe.map(q=>q.id===Ne?{...q,prompt:We}:q))},[H]),le=y.useCallback(Ne=>{H(We=>qte(We,Ne))},[H]),xe=y.useCallback((Ne,We)=>{H(qe=>qe.map(q=>q.id===Ne?{...q,...We}:q))},[H]),Ue=y.useCallback((Ne,We)=>{H(qe=>qe.map(q=>q.id===Ne?{...q,model:We}:q))},[H]),Ze=y.useCallback((Ne,We)=>{H(qe=>qe.map(q=>q.id===Ne?{...q,provider:We,model:Yo(We,q.model,k)}:q))},[k,H]);Zte({applyPayload:i,connection:c,locallyActiveSessionIds:h,panels:A,sessions:te,setError:L});const it=Gte({approvals:a,codexHistoryEvents:r,contextCompaction:m,pendingChatUserMessages:S,rightChatHistoryEvents:C,rightChatPanels:A,runningSessionIds:O,selectedSessionId:I,sidebarSessions:te}),at=y.useCallback(async(Ne,We=[],qe=null,q=null,N={})=>{const F=A.find(vt=>vt.id===Ne);if(!F)return!1;const ee=N.promptOverride??F.prompt,me=q?Wte(q,ee):null;if(me?.kind==="open_training")return We.length>0?(we("/train uses this chat; add other chats from Models.","error"),!1):(u({objective:me.objective,sessionId:F.sessionId}),N.preservePrompt||Ie(Ne,""),!0);if(q&&me?.kind==="send_prompt"&&me.requiresInstructions&&!ee.trim())return we(`Add instructions after ${q.command}.`,"info"),!1;if(q&&We.length>0)return we(`${q.command} tasks do not accept attachments yet. Add file context in the task thread.`,"error"),!1;if(q?.id==="submit-issue"&&!Vte(s))return we("Connect the GitHub app before using /submit-issue.","error"),!1;const $e=F.sessionId?te.find(vt=>vt.id===F.sessionId)??null:null,ze=F.provider==="codex"?g:$e?.openPondCommandAccessMode??g,tt=me?.kind==="send_prompt"?me.prompt:ee,nt=Vt(F.sessionId)?(F.sessionId?C[F.sessionId]:void 0)??(F.sessionId===I?r:Ak):$.getSessionEvents(F.sessionId),mt=Vt(F.sessionId)&&F.sessionId?vt=>{const Oe=F.sessionId;z(Ye=>({...Ye,[Oe]:Xi(Ye[Oe]??nt,[vt])}))}:void 0;return P(We,qe,tt,{session:$e,selectSession:!1,provider:F.provider,model:F.model,openPondCommandAccessMode:ze,chatMessages:rp(nt),displayPrompt:N.displayPrompt,turnMetadata:N.turnMetadata,usageAttribution:q?.id==="submit-issue"?{surface:"chat",workflowKind:"slash_command",commandName:q.command,commandSource:"composer_selection"}:void 0,onCodexHistoryOptimisticEvent:mt,clearPrompt:N.preservePrompt?()=>{}:()=>Ie(Ne,""),onSessionCreated:vt=>{H(Oe=>Oe.map(Ye=>Ye.id===Ne?{...Ye,sessionId:vt.id,provider:vt.provider,model:vt.modelRef?.modelId??Ye.model}:Ye))}})},[r,s,C,A,R,$,I,u,g,P,H,de,te,we,Ie]);return{activateRightChatPanel:le,closeRightChatPanel:Le,openRightChatPanel:ue,rightChatPanelViews:it,showRightChatPanel:ke,showRightPanelDiffTab:re,submitRightChatPrompt:at,updateRightChatModel:Ue,updateRightChatPrompt:Ie,updateRightChatProvider:Ze,updateRightChatScrollState:xe}}function Qte(e){const{appPreferences:t,connection:n,selectedSessionId:a,setAppPreferences:i,setCodexHistorySessions:r,setError:s,setSelectedSessionId:c,setSessions:m}=e;async function u(R,$){if(!n)return;const O=t[R]??{},j={...O,...$,archived:$.pinned?!1:$.archived??O.archived};i(I=>({...I,[R]:j}));try{const I=await Q.patchSidebarAppPreference(n,R,$);i(P=>({...P,[R]:I}))}catch(I){s(I instanceof Error?I.message:String(I)),i(P=>({...P,[R]:O}))}}function h(R){u(R.id,{pinned:!R.pinned,archived:!1})}async function g(R,$){if(!n)return;const O=Vt(R.id)?r:m,j={...R,...$};O(I=>I.some(P=>P.id===R.id)?I.map(P=>P.id===R.id?j:P):[j,...I]);try{const I=await Q.patchSession(n,R.id,$);O(P=>P.some(E=>E.id===I.id)?P.map(E=>E.id===I.id?I:E):[I,...P])}catch(I){s(I instanceof Error?I.message:String(I)),O(P=>P.map(E=>E.id===R.id?R:E))}}function S(R){g(R,{pinned:!1,savedForLater:!R.savedForLater,archived:!1})}function k(R){g(R,{pinned:!R.pinned,savedForLater:!1,archived:!1})}function C(R){g(R,{pinned:!1,savedForLater:!1,archived:!0}),a===R.id&&c(null)}function A(R){g(R,{archived:!1})}function M(R,$){const O=$.trim();!O||O===R.title||g(R,{title:O})}return{archiveSession:C,renameSession:M,restoreSession:A,toggleProjectPinned:h,toggleSessionPinned:k,toggleSessionSavedForLater:S}}function Xte(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,72)||"new-branch"}function ene({connection:e,activeWorkspaceAppId:t,appDefaults:n,bootstrap:a,branchDialogName:i,commitIncludeUnstaged:r,commitMessage:s,commitNextStep:c,draftModel:m,draftProvider:u,cloudProjects:h,selectedApp:g,selectedProject:S,selectedProjectLinkedOpenPondApp:k,selectedSession:C,sessions:A,title:M,visibleWorkspaceDiff:R,visibleWorkspaceState:$,workspaceBusy:O,workspaceName:j,appDispatch:I,applyBootstrapPayload:P,expandProject:E,refreshWorkspace:L,refreshWorkspaceDiff:z,rememberWorkspaceState:H,setBranchDialogOpen:J,setCommitDialogOpen:X,setError:de,setSessions:je,setSettingsSection:we,setSyncingWorkspaceAppId:te,setView:Me,setWorkspaceBusy:Se,showToast:oe}){function be(){return`${XR(n.defaultBranchPrefix)}${Xte(j??M??"new-branch")}`}function re(){return j?`Update ${j}`:(R?.filesChanged??$?.changedFilesCount??0)===1?"Update workspace file":"Update workspace files"}function ue(qe="commit"){I({type:"openCommitDialog",nextStep:qe})}function ke(){I({type:"openBranchDialog",branchName:be()})}function Le(){O||J(!1),we("configuration"),Me("settings"),ln({kind:"settings",section:"configuration"})}async function Ie(qe){if(!(!e||!t)){Se(!0),de(null);try{const q=await Q.checkoutWorkspaceBranch(e,t,{branch:qe});H(q),q.initialized&&z(t)}catch(q){de(q instanceof Error?q.message:String(q))}finally{Se(!1)}}}async function le(){if(!e||!t)return;const qe=i.trim();if(qe){Se(!0),de(null);try{const q=await Q.createWorkspaceBranch(e,t,{branch:qe});H(q),q.initialized&&z(t),J(!1),oe(`Checked out ${qe}`,"success")}catch(q){de(q instanceof Error?q.message:String(q))}finally{Se(!1)}}}async function xe(qe){te(qe);const q=a?.apps.find(N=>N.id===qe)?.name??a?.localProjects.find(N=>N.id===qe)?.name??"Workspace";try{const N=await L(qe,!0);N?.initialized&&qe===t&&z(qe),N?.initialized&&!N.error?oe(`${q} synced locally`,"success"):N?.error&&oe("Workspace sync failed","error")}finally{te(N=>N===qe?null:N)}}async function Ue(){t&&await xe(t)}async function Ze(qe,q,N={}){if(!e)return null;const F=C&&!Vt(C.id)?C:null;if(ine(q,F,N)||F&&tne(F,S,g))return F;const ee=F?await it(F):null;if(ee)return ee;const me=nne(A,S,g);if(me){const nt=me.workspaceKind==="local_project"&&me.workspaceId?wt("local",me.workspaceId):null;return I({type:"selectSession",sessionId:me.id,appId:me.appId,projectId:nt}),me.workspaceKind==="local_project"&&me.workspaceId&&E(wt("local",me.workspaceId)),me}const $e=za(S,h),ze=await Q.createSession(e,{provider:u,modelRef:ei(u,m,a?.providers??null),appId:k?.appId??g?.id??null,appName:k?.appName??g?.name??null,workspaceKind:S?"local_project":g?"sandbox_app":void 0,workspaceId:S?.id??g?.id??null,workspaceName:S?.name??g?.name??null,localProjectId:S?.id??null,cloudProjectId:$e?.id??null,cloudTeamId:$e?.teamId??null,cwd:S?S.workspacePath:null,title:qe});je(nt=>[ze,...nt]);const tt=ze.workspaceKind==="local_project"&&ze.workspaceId?wt("local",ze.workspaceId):null;return I({type:"selectSession",sessionId:ze.id,appId:ze.appId,projectId:tt}),ze.workspaceKind==="local_project"&&ze.workspaceId&&E(wt("local",ze.workspaceId)),ze}async function it(qe){if(!e||!S||!k?.appId||Vt(qe.id)||qe.workspaceKind==="local_project"||qe.appId!==k.appId)return null;const q=za(S,h),N=await Q.patchSession(e,qe.id,{appId:k.appId,appName:k.appName,workspaceKind:"local_project",workspaceId:S.id,workspaceName:S.name,localProjectId:S.id,cloudProjectId:q?.id??null,cloudTeamId:q?.teamId??null,cwd:S.workspacePath});return je(F=>F.map(ee=>ee.id===N.id?N:ee)),I({type:"selectSession",sessionId:N.id,appId:N.appId,projectId:wt("local",S.id)}),E(wt("local",S.id)),N}async function at(qe,q={}){if(!e)return null;const N=await Ze(j?`${j} workspace`:"Workspace action",qe,q);if(!N)return null;const F=await Q.workspaceTool(e,N.id,{action:qe,args:q,source:"ui_button"});oe(F.output,F.ok?"success":"error"),P(await Q.bootstrap(e));const ee=F.appId??ane(N);return ee&&(await L(ee,!1))?.initialized&&await z(ee),F}async function Ne(qe,q={}){if(qe==="git_commit"&&typeof q.message!="string")return ue("commit"),null;Se(!0),de(null);try{return await at(qe,q)}catch(N){return de(N instanceof Error?N.message:String(N)),null}finally{Se(!1)}}async function We(){const qe=s.trim()||re(),q=c==="commit_publish",N=q&&!!$?.remoteUrl;if(!(N&&!window.confirm("Replace the current origin remote with the new OpenPond repo after committing?"))){Se(!0),de(null);try{if(!(await at("git_commit",{message:qe,includeUnstaged:r}))?.ok||c==="commit_push"&&!(await at("git_push",{runChecks:!1}))?.ok||q&&!(await at("publish_openpond_repo",{replaceOrigin:N}))?.ok)return;X(!1)}catch(F){de(F instanceof Error?F.message:String(F))}finally{Se(!1)}}}return{changeWorkspaceBranch:Ie,openCommitDialog:ue,openCreateWorkspaceBranchDialog:ke,openDefaultsSettingsFromBranchDialog:Le,runWorkspaceTool:Ne,submitCommitDialog:We,submitCreateWorkspaceBranch:le,syncWorkspaceLocally:Ue,syncWorkspaceLocallyForApp:xe}}function tne(e,t,n){return!t&&!n?!0:KA(e,t,n)}function nne(e,t,n){if(!t&&!n)return null;let a=null,i=Number.NEGATIVE_INFINITY;for(const r of e){if(r.archived||!KA(r,t,n))continue;const s=Date.parse(r.updatedAt),c=Number.isFinite(s)?s:0;(!a||c>i)&&(a=r,i=c)}return a}function KA(e,t,n){return t?e.workspaceKind==="local_project"&&e.workspaceId===t.id:n?e.appId===n.id||e.workspaceId===n.id:!1}function ane(e){return e.workspaceKind==="sandbox"?e.localProjectId??null:e.workspaceId??e.appId??null}function ine(e,t,n={}){return(one(e)||sne(e,n))&&rne(t)}function one(e){return e.startsWith("sandbox_")?e!=="sandbox_create"&&e!=="sandbox_templates"&&e!=="sandbox_template_launch":!1}function rne(e){return e?.workspaceKind==="sandbox"||e?.workspaceKind==="sandbox_template"}function sne(e,t){if(e!=="sandbox_create")return!1;const n=t.runtime;return!!(n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.runtimeId=="string"&&n.runtimeId.trim())}function lne(e,t){return e.kind==="general"?"# general":e.title?e.title:e.participants.find(a=>a.userId!==t)?.name??"Direct message"}const cne=[];function dne(e){const{composerDraftStore:t,appDispatch:n,mentionedAppId:a,setMentionedAppId:i,cloudSetupDialog:r,setCloudSetupDialog:s,setRightPanelTabRequest:c,workspaceDiffPanelViewState:m,setWorkspaceDiffPanelViewState:u,rightChatHistoryEvents:h,setRightChatHistoryEvents:g,locallyActiveCodexHistorySessionIds:S,setCodexHistoryTurnLocallyActive:k,draftSubagentDelegationMode:C,setDraftSubagentDelegationMode:A,confirmProjectAction:M,view:R,selectedAppId:$,selectedProjectId:O,selectedSessionId:j,draftProvider:I,draftModel:P,activeExperience:E,codexPermissionMode:L,codexReasoningEffort:z,openPondCommandAccessMode:H,busy:J,diffPanelOpen:X,diffPanelExpanded:de,rightPanelMode:je,rightChatPanels:we,newProjectMode:te,newProjectName:Me,newProjectBusy:Se,commitMessage:oe,commitIncludeUnstaged:be,commitNextStep:re,branchDialogName:ue,setSectionMenuOpen:ke,setView:Le,setSelectedAppId:Ie,setSelectedProjectId:le,setSelectedSessionId:xe,setPrompt:Ue,setDraftProvider:Ze,setDraftModel:it,setDiffPanelOpen:at,setRightPanelMode:Ne,setRightChatPanels:We,setSyncingWorkspaceAppId:qe,setSettingsSection:q,setNewProjectDialogOpen:N,setNewProjectMode:F,setNewProjectName:ee,setNewProjectPath:me,setNewProjectBusy:$e,setCommitDialogOpen:ze,setBranchDialogOpen:tt,setError:nt,showToast:mt,appPreferences:vt,applyBootstrapPayload:Oe,approvals:Ye,bootstrap:f,connection:U,events:Y,runtimeEventStore:ge,sessions:se,startup:G,setAppPreferences:_,setCodexHistorySessions:W,setEvents:ne,setSessions:Z,cloudProjectById:ce,localProjectById:pe,selectedApp:fe,selectedCloudProject:Ae,selectedProject:Ce,selectedProjectLinkedOpenPondApp:He,selectedSession:Pe,sidebarSessions:Xe,runtimeIndexes:ut,connectedAppMentions:fn,codexHistoryEvents:jt,setCodexHistoryEvents:dn,account:yn,accountPending:Sn,accountSignedOut:Qt,activeModel:Wa,activeProvider:wa,activeWorkspaceAppId:zn,activeWorkspaceKind:$n,activeWorkspaceLocation:Ht,appDefaults:St,selectedSessionProjectId:xn,workspaceName:xt,accountScopeKey:Nt,teamChat:_a,communities:Ft,selectedProjectConfirmedCloudProject:kn,activeOpenPondCommandAccessMode:rt,viewWorkspaceAppId:jn,viewWorkspaceId:ui,viewWorkspaceKind:mi,openPondActionCatalog:ha,selectedActionCatalog:Ca,expandProject:Bn,setExpandedProjectIds:Li,advanceTrainingModelChatAfterTurn:Ga,bindTrainingModelChatSession:K,prepareTrainingModelChatTurn:Be,chatMessages:_e,pendingChatUserMessages:Ve,recordPendingChatUserMessage:It,runningSessionIds:na,workspaceBusy:In,visibleWorkspaceState:Je,visibleWorkspaceDiff:Rn,rememberWorkspaceState:ft,refreshWorkspace:Nn,setWorkspaceBusy:Ja,refreshWorkspaceDiffWhenNeeded:So,setPendingWorkspaceTarget:Ra,pendingSidebarWorkspaceTarget:xo,setPendingSidebarWorkspaceTarget:Xo,projectTarget:qi,workspaceTarget:Fn}=e,Pa=R==="apps"?"Apps":R==="get-started"?"Walkthroughs":R==="labs"?"Models":R==="scheduled"?"Workflows":R==="outputs"?"Outputs":R==="projects"?"Projects":R==="team"?_a.detail?lne(_a.detail.thread,_a.currentUserId):"Team Chat":R==="community"?Ft.preview?.displayName??"Communities":Pe?.title??qR(E),{browserConversationId:aa,handleWorkspaceDiffPanelViewStateChange:ko}=jte({appDispatch:n,diffPanelExpanded:de,diffPanelOpen:X,rightChatPanels:we,rightPanelMode:je,selectedAppId:$,selectedCloudProject:Ae,selectedProjectId:O,selectedSession:Pe,selectedSessionId:j,setWorkspaceDiffPanelViewState:u,view:R,viewWorkspaceAppId:jn,viewWorkspaceId:ui,viewWorkspaceKind:mi,workspaceDiffPanelViewState:m}),er=y.useCallback(pt=>{ln({kind:"chat",sessionId:pt}),xe(pt),Ie(null),le(null),Le("chat")},[Ie,le,xe,Le]),Io=y.useCallback(()=>{F("existing-local"),ee(""),me(""),N(!0)},[N,F,ee,me]),wo=y.useCallback(()=>{F("local"),ee(""),me(""),N(!0)},[N,F,ee,me]),{createCloudProjectFromScratch:_t,createProjectFromScratch:pl,createProjectCollection:tr,removeProject:fl}=Dte({connection:U,defaultTeamId:St.defaultTeamId,sessions:se,selectedProjectId:O,confirmProjectAction:M,applyBootstrapPayload:Oe,expandProject:Bn,setExpandedProjectIds:Li,setSelectedAppId:Ie,setSelectedProjectId:le,setSelectedSessionId:xe,setError:nt,setView:Le,showToast:mt}),{changeWorkspaceBranch:Lr,openCommitDialog:hl,openCreateWorkspaceBranchDialog:Ui,openDefaultsSettingsFromBranchDialog:gl,runWorkspaceTool:qr,submitCommitDialog:Ur,submitCreateWorkspaceBranch:zr,syncWorkspaceLocally:vl}=ene({connection:U,activeWorkspaceAppId:zn,appDefaults:St,bootstrap:f,branchDialogName:ue,commitIncludeUnstaged:be,commitMessage:oe,commitNextStep:re,draftModel:P,draftProvider:I,cloudProjects:f?.cloudProjects??[],selectedApp:fe,selectedProject:Ce,selectedProjectLinkedOpenPondApp:He,selectedSession:Pe,sessions:se,title:Pa,visibleWorkspaceDiff:Rn,visibleWorkspaceState:Je,workspaceBusy:In,workspaceName:xt,appDispatch:n,applyBootstrapPayload:Oe,expandProject:Bn,refreshWorkspace:Nn,refreshWorkspaceDiff:So,rememberWorkspaceState:ft,setBranchDialogOpen:tt,setCommitDialogOpen:ze,setError:nt,setSessions:Z,setSettingsSection:q,setSyncingWorkspaceAppId:qe,setView:Le,setWorkspaceBusy:Ja,showToast:mt}),bl=Pte({applyBootstrapPayload:Oe,cloudProjects:f?.cloudProjects??[],connection:U,localProjectById:pe,selectedCloudProject:Ae,selectedProject:Ce,setWorkspaceBusy:Ja,showToast:mt,visibleWorkspaceState:Je}),pi=f?.preferences.subagents.delegationMode??"manual",yl=Pe?.subagentDelegationMode??C,Br=!!(E==="development"&&f?.preferences.subagents.enabled&&wa!=="codex"&&!Vt(j)&&!Pe?.subagentRunId),Fr=y.useCallback(pt=>{if(!Pe){A(pt);return}if(!U||Vt(Pe.id)||Pe.subagentRunId)return;const rn=Pe.id,oa=Pe.subagentDelegationMode??null;Z(hn=>hn.map(Dn=>Dn.id===rn?{...Dn,subagentDelegationMode:pt}:Dn)),Q.patchSession(U,rn,{subagentDelegationMode:pt}).then(hn=>{Z(Dn=>Dn.map(ba=>ba.id===hn.id?hn:ba))}).catch(hn=>{Z(Dn=>Dn.map(ba=>ba.id===rn?{...ba,subagentDelegationMode:oa}:ba)),nt(hn instanceof Error?hn.message:String(hn))})},[U,Pe,nt,Z]),_o=y.useCallback(pt=>{g(rn=>rn[pt.session.id]===pt.events?rn:{...rn,[pt.session.id]:pt.events}),W(rn=>ip(rn,pt.session))},[W]),{answerCreateImproveQuestion:Vr,applyCreateImproveCandidate:ga,approveCreateImproveRun:Sl,cancelCreateImproveRun:nr,changeDraftProvider:zi,openCreateImprovePullRequest:ia,reconcileCreateImprovePullRequest:xl,rejectCreateImproveCandidate:kl,pauseCreateImproveRun:Pn,resumeCreateImproveRun:Co,reviseCreateImproveRun:Aa,sendPrompt:Za,stopTurn:ar}=Ite({applyBootstrapPayload:Oe,bootstrap:f,chatMessages:_e,connection:U,codexPermissionMode:L,codexReasoningEffort:z,openPondCommandAccessMode:rt,draftModel:P,draftProvider:I,experience:E,expandProject:Bn,getPrompt:t.getSnapshot,apps:f?.apps??[],connectedAppMentions:fn,mentionedAppId:a,ensureCloudSessionReady:bl,refreshWorkspace:Nn,refreshWorkspaceDiff:So,selectedApp:fe,selectedActionCatalog:Ca,openPondActionCatalog:ha,cloudProjects:f?.cloudProjects??[],accountScopeKey:Nt,selectedCloudProject:Ae,selectedProject:Ce,selectedProjectLinkedOpenPondApp:He,selectedSession:Pe,sessions:se,workspaceTarget:Fn.value,subagentDelegationMode:Pe?.subagentDelegationMode??C,setDraftModel:it,setDraftProvider:Ze,setError:nt,setPrompt:Ue,setMentionedAppId:i,setCodexHistoryEvents:dn,setCodexHistorySessions:W,onCodexHistoryTurnActivityChange:k,onCodexHistoryTurnPayload:_o,onPendingUserMessage:It,setEvents:ne,setSelectedAppId:Ie,setSelectedProjectId:le,setSelectedSessionId:xe,setSessions:Z,setView:Le,setWorkspaceBusy:Ja}),{archiveSession:Ro,restoreSession:Il,renameSession:Kr,toggleProjectPinned:ir,toggleSessionPinned:Bi,toggleSessionSavedForLater:Po}=Qte({appPreferences:vt,connection:U,selectedSessionId:j,setAppPreferences:_,setCodexHistorySessions:W,setError:nt,setSelectedSessionId:xe,setSessions:Z}),{changeWorkspaceTarget:Ao,moveProjectToCloud:Wr,startCloudSetupUpload:Gr}=Ote({account:yn,accountPending:Sn,accountSignedOut:Qt,activeWorkspaceKind:$n,activeWorkspaceLocation:Ht,appDispatch:n,applyBootstrapPayload:Oe,busy:J,cloudSetupDialog:r,cloudProjects:f?.cloudProjects??[],connection:U,defaultTeamId:St.defaultTeamId,expandProject:Bn,localProjectById:pe,selectedCloudProject:Ae,selectedProject:Ce,selectedSession:Pe,selectedSessionProjectId:xn,setCloudSetupDialog:s,setDiffPanelOpen:at,setError:nt,setSessions:Z,setWorkspaceBusy:Ja,showToast:mt,visibleWorkspaceState:Je,workspaceBusy:In}),Ta=y.useCallback(async pt=>{if(E==="work"&&!Pe){if(pt==="local"){Ra("local"),mt(Ce?`Next task will use the local ${Ce.name} checkout.`:"Next task will use an app-managed local workspace.","info");return}if(pt==="cloud"&&!Ce&&!Ae){if(Sn){mt("Checking OpenPond account. Try again in a moment.","info");return}if(Qt){mt("Add an OpenPond account before using Hosted.","error");return}Ra("cloud"),mt("Next task will use Hosted without a Project.","info");return}}if(pt==="hybrid"){const rn=Ae?.id??kn?.id??Pe?.cloudProjectId??null,oa=Ae?.teamId??kn?.teamId??Pe?.cloudTeamId??null;if(Sn){mt("Checking OpenPond account. Try again in a moment.","info");return}if(Qt){mt("Add an OpenPond account before using Hybrid.","error");return}if(!rn||!oa){Ra(null),mt("Upload/sync this Project to Cloud before using Hybrid.","error");return}if(Pe&&!Vt(Pe.id)){if($i(Pe))return;if(!U){mt("OpenPond App server is not connected.","error");return}const hn=await Q.patchSession(U,Pe.id,{provider:I,modelRef:ei(I,P,f?.providers??null),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:Ae?.name??kn?.name??Ce?.name??Pe.workspaceName??"Hybrid workspace",localProjectId:Ce?.id??Pe.localProjectId??null,cloudProjectId:rn,cloudTeamId:oa,metadata:UP(Pe.metadata),cwd:Ce?.workspacePath??Pe.cwd??null});Z(Dn=>Dn.map(ba=>ba.id===hn.id?hn:ba)),Ra(null),mt("Hybrid will use your selected model with hosted sandbox edits.","info");return}Ra("hybrid"),mt("Next message will use Hybrid with a hosted sandbox.","info");return}Ra(null),await Ao(pt)},[Sn,Qt,E,f?.providers,Ao,U,P,I,Ae?.id,Ae?.name,Ae?.teamId,Ce?.id,kn?.id,kn?.name,kn?.teamId,Ce?.name,Ce?.workspacePath,Pe,Ra,Z,mt]),Ea=y.useCallback((pt,rn)=>{Ie(null),le(pt),xe(null),Le("chat"),Bn(pt),Xo({projectId:pt,target:rn})},[Bn,Ie,le,xe,Le]);y.useEffect(()=>{if(!xo||R!=="chat"||O!==xo.projectId||j!==null)return;const pt=xo.target;Xo(null),Ta(pt)},[Ta,xo,O,j,R]);const Jr=$te({advanceTrainingTurn:Ga,bindTrainingSession:K,composerDraftStore:t,onSessionCreated:pt=>{xe(pt.id),Le("chat"),ln({kind:"chat",sessionId:pt.id}),A(null)},onSubmitted:async()=>{const pt=Pe;if(!(!U||!pt||!Hc(pt)))try{const rn=await Q.patchSession(U,pt.id,{metadata:YW(pt.metadata)});Z(oa=>oa.map(hn=>hn.id===rn.id?rn:hn))}catch(rn){mt(rn instanceof Error?`Task started, but its Draft label could not be cleared: ${rn.message}`:"Task started, but its Draft label could not be cleared.","error")}},prepareTrainingTurn:Be,sendPrompt:Za,setMentionedAppId:i,showToast:mt}),or=Nte({appDispatch:n,connection:U,sessions:se,setDiffPanelOpen:at,setRightPanelMode:Ne,setSessions:Z,setView:Le}),{createCloudEnvironmentFromSidebar:fi,openCloudProjectDialog:rr,openUrlInBrowserPanel:Fi,showBrowserPanel:Zr,showChangesPanel:Yr,showGoalSidebarTab:Qr}=Vee({account:yn,browserConversationId:aa,cloudProjectById:ce,cloudProjects:f?.cloudProjects??[],diffPanelOpen:X,rightPanelMode:je,selectedProjectId:O,setDiffPanelOpen:at,setNewProjectDialogOpen:N,setNewProjectMode:F,setNewProjectName:ee,setRightPanelMode:Ne}),{changeProjectTarget:wl,submitNewProjectDialog:Xr}=Hte({appDispatch:n,busy:J,cloudProjectById:ce,createCloudProjectFromScratch:_t,createProjectFromScratch:pl,createProjectCollection:tr,expandProject:Bn,localProjectById:pe,newProjectBusy:Se,newProjectMode:te,newProjectName:Me,onCreateCloudEnvironment:fi,onNewCloudProject:rr,onNewLocalProject:wo,onUseExistingFolderPath:Io,projectTargetValue:qi.value,setDiffPanelOpen:at,setDraftModel:it,setDraftProvider:Ze,setError:nt,setNewProjectBusy:$e,setNewProjectDialogOpen:N,setNewProjectName:ee,setNewProjectPath:me,showToast:mt,workspaceBusy:In}),es=y.useMemo(()=>se.map(pt=>pt.id),[se]);Wee({browserConversationId:aa,sessionIds:es,onOpenSession:er,onShowBrowserPanel:Zr});const[_l,To]=y.useState(null),ts=y.useCallback(pt=>{To({id:Date.now(),objective:pt.objective,initialSessionIds:pt.sessionId?[pt.sessionId]:[]}),po(ma()),Le("labs")},[Le]),{activateRightChatPanel:sr,closeRightChatPanel:hi,openRightChatPanel:Cl,rightChatPanelViews:Rl,showRightChatPanel:Pl,showRightPanelDiffTab:Al,submitRightChatPrompt:gi,updateRightChatModel:ns,updateRightChatPrompt:Tl,updateRightChatProvider:El,updateRightChatScrollState:Ml}=Yte({activeModel:Wa,activeProvider:wa,approvals:Ye,applyRightCodexHistoryPayload:_o,codexHistoryEvents:jt,connectedAppMentions:fn,connection:U,contextCompaction:St.contextCompaction,openLabTraining:ts,locallyActiveCodexHistorySessionIds:S,openPondCommandAccessMode:H,pendingChatUserMessages:Ve,providerSettings:f?.providers??null,rightChatHistoryEvents:h,rightChatPanels:we,rightPanelMode:je,runtimeIndexes:ut,runtimeEventStore:ge,runningSessionIds:na,selectedSession:Pe,selectedSessionId:j,sendPrompt:Za,setDiffPanelOpen:at,setError:nt,setRightChatHistoryEvents:g,setRightChatPanels:We,setRightPanelMode:Ne,setRightPanelTabRequest:c,setView:Le,showChangesPanel:Yr,showToast:mt,sidebarSessions:Xe,startupReady:G.ready}),va=y.useCallback(()=>{ke(null),q("profile"),Le("settings"),ln({kind:"settings",section:"profile"})},[ke,q,Le]),as=y.useMemo(()=>Qi(f?.diagnostics??cne,Y.filter(pt=>pt.name==="diagnostic")),[f?.diagnostics,Y]),jl=y.useCallback(()=>{if(X){at(!1);return}if(R==="labs"){Ne("changes"),c({id:Date.now(),tab:"summary"}),at(!0);return}Ne("home"),at(!0)},[X,at,Ne,c,R]);return{title:Pa,browserConversationId:aa,handleWorkspaceDiffPanelViewStateChange:ko,openSessionInChat:er,openExistingProjectPathDialog:Io,removeProject:fl,changeProjectTarget:wl,submitNewProjectDialog:Xr,changeWorkspaceBranch:Lr,openCommitDialog:hl,openCreateWorkspaceBranchDialog:Ui,openDefaultsSettingsFromBranchDialog:gl,runWorkspaceTool:qr,submitCommitDialog:Ur,submitCreateWorkspaceBranch:zr,syncWorkspaceLocally:vl,subagentDelegationDefaultMode:pi,subagentDelegationMode:yl,subagentDelegationAvailable:Br,changeSubagentDelegationMode:Fr,answerCreateImproveQuestion:Vr,applyCreateImproveCandidate:ga,approveCreateImproveRun:Sl,cancelCreateImproveRun:nr,changeDraftProvider:zi,openCreateImprovePullRequest:ia,reconcileCreateImprovePullRequest:xl,rejectCreateImproveCandidate:kl,pauseCreateImproveRun:Pn,resumeCreateImproveRun:Co,reviseCreateImproveRun:Aa,sendPrompt:Za,stopTurn:ar,archiveSession:Ro,restoreSession:Il,renameSession:Kr,toggleProjectPinned:ir,toggleSessionPinned:Bi,toggleSessionSavedForLater:Po,moveProjectToCloud:Wr,startCloudSetupUpload:Gr,changeWorkspaceTarget:Ta,switchProjectWorkspaceTarget:Ea,sendPromptFromMainComposer:Jr,openSandboxWorkspace:or,createCloudEnvironmentFromSidebar:fi,openCloudProjectDialog:rr,openUrlInBrowserPanel:Fi,showBrowserPanel:Zr,showChangesPanel:Yr,showGoalSidebarTab:Qr,rightChatTrainingLaunchRequest:_l,setRightChatTrainingLaunchRequest:To,closeRightChatPanel:hi,openRightChatPanel:Cl,rightChatPanelViews:Rl,showRightChatPanel:Pl,showRightPanelDiffTab:Al,submitRightChatPrompt:gi,activateRightChatPanel:sr,updateRightChatModel:ns,updateRightChatPrompt:Tl,updateRightChatProvider:El,updateRightChatScrollState:Ml,openProfileSettings:va,diagnosticEvents:as,toggleRightSidebar:jl}}const une=HT();function mne(){return x.jsx(tT,{client:une,children:x.jsx(pne,{})})}function pne(){const e=Hee(),t=dne(e);return x.jsx(cJ,{primary:e,secondary:t})}const coe=Object.freeze(Object.defineProperty({__proto__:null,App:mne},Symbol.toStringTag,{value:"Module"}));export{Tie as $,jK as A,VS as B,bo as C,vW as D,tie as E,MR as F,HR as G,Dc as H,tm as I,VW as J,H9 as K,Rk as L,vr as M,wy as N,uG as O,tW as P,Wn as Q,Xie as R,KS as S,KP as T,Mie as U,ioe as V,Yo as W,pd as X,noe as Y,Pg as Z,oie as _,YS as a,Og as a$,CJ as a0,loe as a1,pte as a2,Aie as a3,Eie as a4,Vie as a5,Lie as a6,i7 as a7,ei as a8,w7 as a9,Xi as aA,aA as aB,yie as aC,Y7 as aD,TX as aE,bie as aF,K7 as aG,Fie as aH,AX as aI,Oa as aJ,Oi as aK,FA as aL,Vte as aM,Kte as aN,zee as aO,Sie as aP,qW as aQ,Fb as aR,AR as aS,Qm as aT,$ie as aU,ty as aV,OW as aW,Qae as aX,px as aY,NR as aZ,XG as a_,ys as aa,ok as ab,Hie as ac,kk as ad,Wg as ae,yu as af,N9 as ag,Oie as ah,bg as ai,Ag as aj,JG as ak,rA as al,I9 as am,Xm as an,B9 as ao,oW as ap,OR as aq,Lne as ar,Nie as as,Die as at,Qie as au,C9 as av,U9 as aw,lh as ax,B as ay,Vt as az,FY as b,FP as b$,vJ as b0,ooe as b1,dJ as b2,kx as b3,ap as b4,e7 as b5,vy as b6,XR as b7,P9 as b8,nie as b9,roe as bA,cp as bB,W9 as bC,ma as bD,po as bE,l as bF,o as bG,p as bH,st as bI,vm as bJ,Vb as bK,TR as bL,md as bM,kie as bN,Rie as bO,Pie as bP,wx as bQ,wie as bR,xh as bS,Cie as bT,_ie as bU,Iie as bV,Ix as bW,xie as bX,Ot as bY,_N as bZ,Hne as b_,aie as ba,F2 as bb,Z7 as bc,J7 as bd,jR as be,V9 as bf,sv as bg,iie as bh,rie as bi,aW as bj,ER as bk,Nne as bl,vv as bm,Xae as bn,ep as bo,Kb as bp,ln as bq,pW as br,oA as bs,da as bt,$ne as bu,dv as bv,uv as bw,Qd as bx,One as by,r9 as bz,dt as c,Bne as c$,qne as c0,Gae as c1,Yf as c2,Dne as c3,uie as c4,mie as c5,pie as c6,fie as c7,$W as c8,cie as c9,lt as cA,D as cB,he as cC,v as cD,d as cE,T as cF,cl as cG,Am as cH,LU as cI,ht as cJ,l_ as cK,fz as cL,r_ as cM,ez as cN,Yw as cO,qU as cP,az as cQ,dz as cR,sz as cS,gz as cT,V as cU,w as cV,n_ as cW,Jne as cX,Gne as cY,Rm as cZ,Fne as c_,die as ca,ST as cb,vne as cc,gne as cd,Uc as ce,yf as cf,pc as cg,IT as ch,Ln as ci,la as cj,Nk as ck,DT as cl,yne as cm,SI as cn,jm as co,Wne as cp,Hi as cq,iz as cr,Xv as cs,Vne as ct,Em as cu,nd as cv,yt as cw,Jt as cx,Tm as cy,b as cz,lX as d,DC as d$,UU as d0,XU as d1,Kw as d2,mz as d3,o_ as d4,Yne as d5,Zne as d6,hz as d7,i_ as d8,ab as d9,xI as dA,nn as dB,Eae as dC,Fae as dD,wb as dE,bK as dF,Mae as dG,Oc as dH,Ub as dI,$ae as dJ,Nw as dK,tu as dL,Une as dM,_n as dN,jw as dO,ie as dP,qG as dQ,Zv as dR,uS as dS,zne as dT,wc as dU,vz as dV,Ke as dW,Ka as dX,oae as dY,rae as dZ,Xne as d_,nb as da,a_ as db,Om as dc,$m as dd,pz as de,rz as df,RK as dg,Vae as dh,vie as di,sae as dj,lae as dk,z5 as dl,pae as dm,i3 as dn,mae as dp,Yae as dq,L6 as dr,Z3 as ds,xae as dt,kae as du,Zae as dv,Pt as dw,tae as dx,sd as dy,De as dz,Bk as e,PW as e$,cae as e0,G5 as e1,yae as e2,QC as e3,Sae as e4,C_ as e5,bae as e6,vae as e7,nae as e8,lc as e9,dae as eA,ai as eB,Qne as eC,Rz as eD,Fm as eE,wC as eF,gae as eG,Cae as eH,_ae as eI,wae as eJ,Oae as eK,eae as eL,b_ as eM,Nr as eN,ea as eO,eB as eP,qz as eQ,Iae as eR,$V as eS,dd as eT,Rae as eU,Tae as eV,Aae as eW,Pae as eX,yV as eY,Nm as eZ,xW as e_,YC as ea,ZU as eb,Uae as ec,Lae as ed,zae as ee,Bae as ef,Dae as eg,mm as eh,qae as ei,Hae as ej,ud as ek,qu as el,Yv as em,ae as en,Mi as eo,jae as ep,Ni as eq,Dq as er,Wd as es,ed as et,iae as eu,T5 as ev,qie as ew,Uie as ex,Kne as ey,uae as ez,Tr as f,Jae as f0,fae as f1,hae as f2,tp as f3,zie as f4,Bie as f5,aae as f6,ro as f7,eC as f8,IF as f9,coe as fA,Vo as fa,dS as fb,gie as fc,g9 as fd,xk as fe,Uee as ff,jg as fg,HP as fh,xP as fi,DP as fj,soe as fk,Gie as fl,Kie as fm,Wie as fn,tee as fo,lne as fp,Jie as fq,Zie as fr,Yie as fs,WS as ft,rP as fu,sie as fv,Lc as fw,Kae as fx,Wae as fy,lie as fz,d9 as g,Yi as h,Ym as i,KW as j,jie as k,hie as l,Bb as m,nte as n,eoe as o,aoe as p,UA as q,YR as r,LK as s,toe as t,Ek as u,hd as v,Q as w,gd as x,WW as y,eie as z};