openpond 0.2.59 → 0.2.60

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 (365) hide show
  1. package/README.md +27 -0
  2. package/dist/app-server.d.ts +7 -0
  3. package/dist/app-server.js +1 -1
  4. package/dist/chunks/acp-ARBNMIPT.js +2 -0
  5. package/dist/chunks/acp-agent-53COYDHB.js +21 -0
  6. package/dist/chunks/{actions-command-JJ3CU7J6.js → actions-command-6YSZ7EJS.js} +1 -1
  7. package/dist/chunks/{app-layer-KAUZAHGE.js → app-layer-TVG7KTW6.js} +1 -1
  8. package/dist/chunks/{app-server-connected-apps-SXGZOUJJ.js → app-server-connected-apps-K62M6LCT.js} +1 -1
  9. package/dist/chunks/{app-server-evaluations-N4OMTPCI.js → app-server-evaluations-RM6WXX3H.js} +1 -1
  10. package/dist/chunks/app-server-harness-services-RLKMWOQ4.js +2 -0
  11. package/dist/chunks/app-server-runtime-OKMEHNEU.js +2 -0
  12. package/dist/chunks/apps-YWZL2H34.js +2 -0
  13. package/dist/chunks/{chunk-JUQMSHNR.js → chunk-23P2O7PH.js} +1 -1
  14. package/dist/chunks/{chunk-PF5R6CMP.js → chunk-2GICDASL.js} +1 -1
  15. package/dist/chunks/{chunk-6MI4KKWF.js → chunk-2ITZW2CN.js} +1 -1
  16. package/dist/chunks/chunk-2MMCZHKL.js +2 -0
  17. package/dist/chunks/{chunk-EOBHQ3JT.js → chunk-2PAJCXFC.js} +1 -1
  18. package/dist/chunks/{chunk-GYJQKCEO.js → chunk-2RNCXDJC.js} +1 -1
  19. package/dist/chunks/{chunk-APB2STJK.js → chunk-2SUMZ73C.js} +1 -1
  20. package/dist/chunks/{chunk-DZUN5YWB.js → chunk-3CWRTKHY.js} +1 -1
  21. package/dist/chunks/{chunk-TRQQNFMO.js → chunk-44LWH5U6.js} +1 -1
  22. package/dist/chunks/{chunk-BVQWVIGK.js → chunk-52KIORRX.js} +1 -1
  23. package/dist/chunks/{chunk-TG7P7BSV.js → chunk-5RHYSQZ5.js} +1 -1
  24. package/dist/chunks/{chunk-3QIB5FXI.js → chunk-5ZBLCWEJ.js} +1 -1
  25. package/dist/chunks/{chunk-25JDHAZ5.js → chunk-637UACKH.js} +1 -1
  26. package/dist/chunks/{chunk-VRODAXFS.js → chunk-655DQ6AX.js} +26 -26
  27. package/dist/chunks/{chunk-N4FFQPLR.js → chunk-6GWOVHIG.js} +1 -1
  28. package/dist/chunks/chunk-6HQB3MQO.js +2 -0
  29. package/dist/chunks/{chunk-GOPFFQZU.js → chunk-7LZISGTA.js} +2 -2
  30. package/dist/chunks/{chunk-MMQRHR3V.js → chunk-7RC5WPVT.js} +1 -1
  31. package/dist/chunks/{chunk-H6IW2R22.js → chunk-7YTHEMWI.js} +1 -1
  32. package/dist/chunks/{chunk-PCSIOUHF.js → chunk-A3L74U3W.js} +1 -1
  33. package/dist/chunks/{chunk-XMKCCLGB.js → chunk-A66CSUBJ.js} +1 -1
  34. package/dist/chunks/{chunk-OUVIWDL2.js → chunk-AGVOGPAZ.js} +1 -1
  35. package/dist/chunks/{chunk-U2MAPON2.js → chunk-AW5Q6NXT.js} +1 -1
  36. package/dist/chunks/{chunk-7AVNZF36.js → chunk-B46HZ3MX.js} +1 -1
  37. package/dist/chunks/{chunk-KGNCKIFP.js → chunk-BIPQCJ5V.js} +1 -1
  38. package/dist/chunks/{chunk-776WNDV2.js → chunk-BIQ33JV5.js} +1 -1
  39. package/dist/chunks/{chunk-JFXWI3EN.js → chunk-BK63OQRW.js} +1 -1
  40. package/dist/chunks/{chunk-BO5JZYWG.js → chunk-CFSIU6CW.js} +1 -1
  41. package/dist/chunks/{chunk-WC42WOLG.js → chunk-D3RRUWNN.js} +1 -1
  42. package/dist/chunks/{chunk-X4OSOOSU.js → chunk-D4UX2O45.js} +1 -1
  43. package/dist/chunks/{chunk-GJ2ZJFDD.js → chunk-DG4TYVPF.js} +1 -1
  44. package/dist/chunks/{chunk-QIKWJ2AA.js → chunk-DGIEXZJV.js} +1 -1
  45. package/dist/chunks/{chunk-JMBQYBPI.js → chunk-DIGX56JY.js} +1 -1
  46. package/dist/chunks/{chunk-4GPXTISD.js → chunk-DISNCX6R.js} +1 -1
  47. package/dist/chunks/{chunk-EWOSLZDX.js → chunk-DK7IKI7O.js} +1 -1
  48. package/dist/chunks/{chunk-74IIXVAE.js → chunk-DX7YEUNQ.js} +1 -1
  49. package/dist/chunks/{chunk-523TE4BI.js → chunk-E63VWAQA.js} +1 -1
  50. package/dist/chunks/{chunk-OLDK2LKJ.js → chunk-EL454L26.js} +1 -1
  51. package/dist/chunks/{chunk-WRI4XKSK.js → chunk-ENSB6ZTM.js} +1 -1
  52. package/dist/chunks/{chunk-EAPFMACH.js → chunk-ERJV5BMC.js} +1 -1
  53. package/dist/chunks/{chunk-RNIAFXMB.js → chunk-EXJGCNRS.js} +1 -1
  54. package/dist/chunks/chunk-F5KCCDQM.js +2 -0
  55. package/dist/chunks/{chunk-57TRXBLT.js → chunk-FSQWAANK.js} +1 -1
  56. package/dist/chunks/{chunk-BGJYITVI.js → chunk-G5B3PB5X.js} +1 -1
  57. package/dist/chunks/{chunk-ARLOVWQ3.js → chunk-GAWGIJQG.js} +1 -1
  58. package/dist/chunks/{chunk-ABZ2ZOLU.js → chunk-GGGF5NHJ.js} +1 -1
  59. package/dist/chunks/{chunk-4EDIRCD3.js → chunk-GOYBYYPQ.js} +1 -1
  60. package/dist/chunks/{chunk-H7ATCPPB.js → chunk-H3BSIAQO.js} +1 -1
  61. package/dist/chunks/{chunk-RBZH6A6M.js → chunk-HCEJAOIF.js} +1 -1
  62. package/dist/chunks/{chunk-OPNRWESL.js → chunk-IFQCOSU6.js} +1 -1
  63. package/dist/chunks/{chunk-VGRMAGOK.js → chunk-IJHZBHEK.js} +2 -2
  64. package/dist/chunks/{chunk-GUOLMLZN.js → chunk-ISFIDCIH.js} +1 -1
  65. package/dist/chunks/{chunk-PY6K2JRH.js → chunk-ITKTILKI.js} +1 -1
  66. package/dist/chunks/{chunk-3CDEBKSU.js → chunk-IUBARBGI.js} +1 -1
  67. package/dist/chunks/{chunk-2L5XWJJ5.js → chunk-J24I74EM.js} +1 -1
  68. package/dist/chunks/{chunk-IRV6GWGG.js → chunk-J7QGHA7G.js} +3 -3
  69. package/dist/chunks/{chunk-FAYASU7Z.js → chunk-JGWINTT5.js} +1 -1
  70. package/dist/chunks/{chunk-GL3NX3F3.js → chunk-JHEFWB6O.js} +1 -1
  71. package/dist/chunks/{chunk-V34H7Y2T.js → chunk-JHMS2WXM.js} +2 -2
  72. package/dist/chunks/{chunk-PSGGOZFM.js → chunk-JHR3LF2F.js} +1 -1
  73. package/dist/chunks/{chunk-O4VIXU7A.js → chunk-KGLJU66U.js} +3 -3
  74. package/dist/chunks/{chunk-XEOEKFG6.js → chunk-KJFRCVQC.js} +1 -1
  75. package/dist/chunks/chunk-KNO355LC.js +2 -0
  76. package/dist/chunks/{chunk-BQS7Z4AP.js → chunk-LD7PGREF.js} +2 -2
  77. package/dist/chunks/{chunk-MNC4YUDI.js → chunk-LHA7RQBA.js} +1 -1
  78. package/dist/chunks/{chunk-RZUEVS64.js → chunk-LO3O45IX.js} +1 -1
  79. package/dist/chunks/{chunk-TIHXUKFD.js → chunk-M2SKXY5C.js} +2 -2
  80. package/dist/chunks/{chunk-2IHO4GDJ.js → chunk-M3ZQDPRS.js} +1 -1
  81. package/dist/chunks/{chunk-DPHAN6N3.js → chunk-M4ZF44H5.js} +1 -1
  82. package/dist/chunks/{chunk-Y4OWBBDD.js → chunk-M55H7KVR.js} +1 -1
  83. package/dist/chunks/{chunk-NTB2O4RP.js → chunk-MGKMIRYG.js} +1 -1
  84. package/dist/chunks/{chunk-XJZSIXEO.js → chunk-MJGU2JJ2.js} +2 -2
  85. package/dist/chunks/{chunk-7K7O3CKY.js → chunk-MS37ISA4.js} +2 -2
  86. package/dist/chunks/{chunk-BRORSFJX.js → chunk-NCKXI2VB.js} +11 -11
  87. package/dist/chunks/chunk-NHUUCNAD.js +2 -0
  88. package/dist/chunks/{chunk-2WKUBGIF.js → chunk-O3VP46SE.js} +1 -1
  89. package/dist/chunks/{chunk-EUMXMT3S.js → chunk-O4FBOUNX.js} +1 -1
  90. package/dist/chunks/chunk-O6IFVTZT.js +9 -0
  91. package/dist/chunks/{chunk-ZH3K7LKQ.js → chunk-O7B44IYN.js} +1 -1
  92. package/dist/chunks/{chunk-ZAN4DYLH.js → chunk-OGMDEA3Y.js} +1 -1
  93. package/dist/chunks/{chunk-BL3YH2QU.js → chunk-OKBIWRHC.js} +1 -1
  94. package/dist/chunks/{chunk-FFRFSDBM.js → chunk-ON2RNOCG.js} +1 -1
  95. package/dist/chunks/{chunk-76M2MEHV.js → chunk-ONDCV5QC.js} +1 -1
  96. package/dist/chunks/{chunk-UCPGRPWY.js → chunk-OQ4VGCRG.js} +1 -1
  97. package/dist/chunks/{chunk-GVZLGS2U.js → chunk-OWK7HU5I.js} +1 -1
  98. package/dist/chunks/{chunk-JQKSXCAJ.js → chunk-OY5HC2P6.js} +1 -1
  99. package/dist/chunks/{chunk-T5AACNJI.js → chunk-P7HRF4FM.js} +1 -1
  100. package/dist/chunks/{chunk-7ED24PP6.js → chunk-PCNLC5H3.js} +1 -1
  101. package/dist/chunks/{chunk-ES2ISFJC.js → chunk-PF56N7ZY.js} +1 -1
  102. package/dist/chunks/{chunk-OX3XZKGK.js → chunk-PKALOVHC.js} +2 -2
  103. package/dist/chunks/{chunk-ZCHXGRRU.js → chunk-PR5TYTY4.js} +1 -1
  104. package/dist/chunks/{chunk-Q4TBTRIG.js → chunk-PWK5Z5S3.js} +1 -1
  105. package/dist/chunks/chunk-PXS4SVQG.js +16 -0
  106. package/dist/chunks/{chunk-AY64VY4E.js → chunk-QGOPYQW3.js} +1 -1
  107. package/dist/chunks/{chunk-LPWBIGKW.js → chunk-R7YEURUQ.js} +1 -1
  108. package/dist/chunks/{chunk-ACYFMLWG.js → chunk-RCA6NGVA.js} +2 -2
  109. package/dist/chunks/{chunk-DUURYZOI.js → chunk-RG3NH6YQ.js} +1 -1
  110. package/dist/chunks/{chunk-ATAOHSFR.js → chunk-RJIUOLWY.js} +1 -1
  111. package/dist/chunks/{chunk-37MWETFU.js → chunk-RXE3FYMJ.js} +1 -1
  112. package/dist/chunks/chunk-RYGWCN2R.js +2 -0
  113. package/dist/chunks/{chunk-VYLGI3IH.js → chunk-SFNCAPCJ.js} +1 -1
  114. package/dist/chunks/{chunk-Z4Z5UOZM.js → chunk-SG6JZ7HD.js} +1 -1
  115. package/dist/chunks/{chunk-IFDALGZE.js → chunk-SKRNWRKV.js} +5 -5
  116. package/dist/chunks/{chunk-ANFDRKUU.js → chunk-SLZH4Z6C.js} +1 -1
  117. package/dist/chunks/{chunk-WN3V6KDN.js → chunk-SPDSSMFD.js} +1 -1
  118. package/dist/chunks/{chunk-EQOV34UH.js → chunk-STWRTNRK.js} +1 -1
  119. package/dist/chunks/{chunk-XMWXH7TS.js → chunk-T5J7HIHR.js} +1 -1
  120. package/dist/chunks/{chunk-E72UU4VX.js → chunk-TBUAQWFS.js} +1 -1
  121. package/dist/chunks/{chunk-ZUJ3XUCP.js → chunk-TEPRCBDV.js} +1 -1
  122. package/dist/chunks/{chunk-2G4BEISF.js → chunk-TOFMA2L5.js} +2 -2
  123. package/dist/chunks/{chunk-TKLBP3MM.js → chunk-UFHLLSCE.js} +1 -1
  124. package/dist/chunks/{chunk-BE6SS65L.js → chunk-UJKQLO6B.js} +2 -2
  125. package/dist/chunks/{chunk-O3RF72BT.js → chunk-UZQNFTLR.js} +1 -1
  126. package/dist/chunks/{chunk-F74GBN6K.js → chunk-V2HMWCT6.js} +1 -1
  127. package/dist/chunks/{chunk-6ZFPQYHG.js → chunk-V4KT5FCJ.js} +1 -1
  128. package/dist/chunks/{chunk-TVQAPBLZ.js → chunk-VHSX3JPX.js} +1 -1
  129. package/dist/chunks/{chunk-22VMH6JV.js → chunk-W2SXOGTQ.js} +1 -1
  130. package/dist/chunks/{chunk-PH6IORGZ.js → chunk-WDEO44UN.js} +1 -1
  131. package/dist/chunks/{chunk-LNCHFVHT.js → chunk-WEHBK3MC.js} +1 -1
  132. package/dist/chunks/{chunk-KO3HNMLJ.js → chunk-WGX7WY4N.js} +1 -1
  133. package/dist/chunks/{chunk-CKMSBAI2.js → chunk-WHREO7A2.js} +1 -1
  134. package/dist/chunks/{chunk-N6ENLEMY.js → chunk-WS2ZZBAQ.js} +3 -3
  135. package/dist/chunks/{chunk-DIO5CB6U.js → chunk-WYZWDMMF.js} +1 -1
  136. package/dist/chunks/{chunk-MQULU465.js → chunk-XO3H32KX.js} +1 -1
  137. package/dist/chunks/{chunk-FKJHEZCW.js → chunk-XQBIHPPX.js} +1 -1
  138. package/dist/chunks/chunk-XRKFTPHD.js +2 -0
  139. package/dist/chunks/{chunk-YHHF4Q7Y.js → chunk-XSCIOQYE.js} +1 -1
  140. package/dist/chunks/{chunk-COHMDT7A.js → chunk-XTWEWYK7.js} +7 -7
  141. package/dist/chunks/{chunk-AQD7K4Z5.js → chunk-Y3GIM6WK.js} +1 -1
  142. package/dist/chunks/{chunk-74ZXXBGN.js → chunk-Y54RKLOI.js} +1 -1
  143. package/dist/chunks/{chunk-C37PUHA6.js → chunk-Y777GISF.js} +1 -1
  144. package/dist/chunks/{chunk-PFSMXKTI.js → chunk-YDU3S6UT.js} +1 -1
  145. package/dist/chunks/{chunk-UGL7WF3W.js → chunk-YOZIZYSC.js} +1 -1
  146. package/dist/chunks/{chunk-OSIO7PLX.js → chunk-YQKOB56U.js} +1 -1
  147. package/dist/chunks/chunk-YVNDDNMK.js +3 -0
  148. package/dist/chunks/{chunk-U5FKRYJO.js → chunk-ZAZKJJOT.js} +1 -1
  149. package/dist/chunks/{chunk-2RNQQNB7.js → chunk-ZR7LIMJS.js} +1 -1
  150. package/dist/chunks/{chunk-PQJTYOR2.js → chunk-ZTJOOY2F.js} +1 -1
  151. package/dist/chunks/{chunk-GPVCOEUH.js → chunk-ZTVXRZ6D.js} +1 -1
  152. package/dist/chunks/cli-CNYNXKGQ.js +2 -0
  153. package/dist/chunks/configuration-command-5K7EE2J5.js +2 -0
  154. package/dist/chunks/connected-app-executor-E25XCNAS.js +2 -0
  155. package/dist/chunks/connected-evidence-QNSO5BTF.js +2 -0
  156. package/dist/chunks/connection-Y2KCMBYD.js +2 -0
  157. package/dist/chunks/{continual-WFPIDWPH.js → continual-SOO3QBNQ.js} +1 -1
  158. package/dist/chunks/core-commands-ZTWPYAFQ.js +2 -0
  159. package/dist/chunks/datasets-XPUMWGOC.js +2 -0
  160. package/dist/chunks/desktop-test-HVSW4JHY.js +3 -0
  161. package/dist/chunks/dist-4N6AHWNN.js +2 -0
  162. package/dist/chunks/{dist-OMGUJYPD.js → dist-N6R6VNFD.js} +1 -1
  163. package/dist/chunks/{dist-OGLX76LL.js → dist-QN7WKZ2D.js} +1 -1
  164. package/dist/chunks/{enclave-QS4BUNDU.js → enclave-VURYNILU.js} +1 -1
  165. package/dist/chunks/evaluation-coordination-AOTFPVMS.js +2 -0
  166. package/dist/chunks/experiment-improvements-75CN3VI7.js +2 -0
  167. package/dist/chunks/experiments-AGAHM2AK.js +2 -0
  168. package/dist/chunks/{experiments-VFQGE4HC.js → experiments-DYSHYBGB.js} +1 -1
  169. package/dist/chunks/{extension-JCUA3RWV.js → extension-UT4CSDJF.js} +1 -1
  170. package/dist/chunks/help-KU52CFMW.js +8 -0
  171. package/dist/chunks/host-profile-evaluation-tools-LZDMQCMT.js +2 -0
  172. package/dist/chunks/host-profile-external-dataset-VK3NJHMC.js +2 -0
  173. package/dist/chunks/hosted-app-server-composition-P7V7K7CG.js +2 -0
  174. package/dist/chunks/{hosted-experiment-improvement-42YWXB3P.js → hosted-experiment-improvement-P433KDX2.js} +1 -1
  175. package/dist/chunks/hosted-harness-runtime-Y4DONWPC.js +2 -0
  176. package/dist/chunks/{hosted-profile-candidate-HVVC43XQ.js → hosted-profile-candidate-72MMPN6U.js} +1 -1
  177. package/dist/chunks/hosted-profile-compiler-RXHLK224.js +2 -0
  178. package/dist/chunks/hosted-profile-evaluation-control-LS4DCSDO.js +2 -0
  179. package/dist/chunks/{hosted-profile-evaluation-inspection-BUWLCKCD.js → hosted-profile-evaluation-inspection-3Q6EHO66.js} +1 -1
  180. package/dist/chunks/{hosted-profile-evaluation-preparation-3XLRR6UH.js → hosted-profile-evaluation-preparation-ZD27HNLF.js} +1 -1
  181. package/dist/chunks/{hosted-tasksets-THKM5QY5.js → hosted-tasksets-V2PQZJN4.js} +1 -1
  182. package/dist/chunks/human-review-4FJFINQX.js +2 -0
  183. package/dist/chunks/{import-CBDJ4DME.js → import-GBHSLA3G.js} +1 -1
  184. package/dist/chunks/{learning-ACEVFL5M.js → learning-U3FZL5YB.js} +1 -1
  185. package/dist/chunks/local-harness-improvement-runtime-UP2P7UT4.js +2 -0
  186. package/dist/chunks/local-harness-taskset-review-ZNOKSPJJ.js +2 -0
  187. package/dist/chunks/{local-scope-HVF2GZ5W.js → local-scope-62GWHDXS.js} +1 -1
  188. package/dist/chunks/{model-projects-QPO22JPA.js → model-projects-LQ4C6R3X.js} +1 -1
  189. package/dist/chunks/opchat-Q4PIWPYW.js +3 -0
  190. package/dist/chunks/organizations-TEH6HBQ3.js +2 -0
  191. package/dist/chunks/{profile-Y2MCSOUK.js → profile-SWPVCGTR.js} +1 -1
  192. package/dist/chunks/{profile-training-source-6GOT7AHM.js → profile-training-source-J73ZLNSC.js} +1 -1
  193. package/dist/chunks/project-action-payload-OU3ZPHW7.js +2 -0
  194. package/dist/chunks/project-agent-J7ILCRBS.js +2 -0
  195. package/dist/chunks/{published-experiment-source-5TMGLKDM.js → published-experiment-source-HVHKSYDL.js} +1 -1
  196. package/dist/chunks/refiner-profile-service-E7YU4E3N.js +2 -0
  197. package/dist/chunks/{runtime-QFXCXSVB.js → runtime-LIPHPKKJ.js} +2 -2
  198. package/dist/chunks/sandbox-command-G6KID3OP.js +2 -0
  199. package/dist/chunks/{sandbox-template-XWWPWWNR.js → sandbox-template-MZTMAUFS.js} +1 -1
  200. package/dist/chunks/saved-work-LOUWLF37.js +2 -0
  201. package/dist/chunks/{send-turn-SIXOZUVJ.js → send-turn-UEUEGY5W.js} +1 -1
  202. package/dist/chunks/{src-EZAKCCUV.js → src-7WMZOWZZ.js} +102 -95
  203. package/dist/chunks/{src-6SHCCYEN.js → src-MVAK6D6Y.js} +1 -1
  204. package/dist/chunks/standalone-experiment-turn-owner-YRKEOEJ2.js +2 -0
  205. package/dist/chunks/{store-continual-support-reviews-GDX6CSUU.js → store-continual-support-reviews-FJLLNKCY.js} +1 -1
  206. package/dist/chunks/{store-conversation-serving-W55XMDH4.js → store-conversation-serving-4KWR4IZY.js} +1 -1
  207. package/dist/chunks/{store-create-improve-A7E7CUPZ.js → store-create-improve-JWBJZRAU.js} +1 -1
  208. package/dist/chunks/{store-datasets-HKF3EO7B.js → store-datasets-4N2M6Y3K.js} +2 -2
  209. package/dist/chunks/{store-evaluation-results-645RFBGR.js → store-evaluation-results-OBM4623U.js} +1 -1
  210. package/dist/chunks/{store-harness-memory-VINCZ4GK.js → store-harness-memory-4HUEMRCD.js} +1 -1
  211. package/dist/chunks/{store-harness-refinement-candidates-EA5KFQPH.js → store-harness-refinement-candidates-NMRWMN23.js} +1 -1
  212. package/dist/chunks/store-harness-workspaces-BGONIQDY.js +2 -0
  213. package/dist/chunks/{store-human-review-F5KESW52.js → store-human-review-J75SIZAL.js} +1 -1
  214. package/dist/chunks/store-learned-preference-migration-validation-VLASM4CT.js +2 -0
  215. package/dist/chunks/store-learning-TUCQFBLT.js +2 -0
  216. package/dist/chunks/{store-learning-credentials-WZQJ4HPJ.js → store-learning-credentials-S4RF57NV.js} +1 -1
  217. package/dist/chunks/{store-local-experiments-HWQWNTIU.js → store-local-experiments-LULRLTII.js} +5 -5
  218. package/dist/chunks/{store-model-batch-review-TOCSDVAP.js → store-model-batch-review-SVL4MT6D.js} +1 -1
  219. package/dist/chunks/{store-model-configuration-6543ASY2.js → store-model-configuration-ZHDSM3XM.js} +2 -2
  220. package/dist/chunks/{store-preference-comparison-LV32MHVL.js → store-preference-comparison-YMMCKXS5.js} +1 -1
  221. package/dist/chunks/{store-schedules-VGTEQVKH.js → store-schedules-6Z4QS3NU.js} +1 -1
  222. package/dist/chunks/{store-sidebar-file-bookmarks-53B7QIGS.js → store-sidebar-file-bookmarks-MX6EP6OB.js} +2 -2
  223. package/dist/chunks/{store-sidebar-preferences-YXGEJVUO.js → store-sidebar-preferences-VYREPW26.js} +1 -1
  224. package/dist/chunks/{store-subagents-HRCAK7VZ.js → store-subagents-WGBCRALX.js} +1 -1
  225. package/dist/chunks/{store-task-inbox-WF74W4U2.js → store-task-inbox-43BNZSB7.js} +6 -6
  226. package/dist/chunks/{store-task-inventory-KHCTEZVK.js → store-task-inventory-AEW4POAJ.js} +2 -2
  227. package/dist/chunks/{store-taskset-drafts-3ACG5AVX.js → store-taskset-drafts-DKFO2CYB.js} +1 -1
  228. package/dist/chunks/{store-training-R46WOGXB.js → store-training-6PFFR6ST.js} +1 -1
  229. package/dist/chunks/{store-training-jobs-D4LECE7O.js → store-training-jobs-ANDEBQ67.js} +2 -2
  230. package/dist/chunks/{store-training-models-EQVNXOVB.js → store-training-models-OOI4ZJPX.js} +2 -2
  231. package/dist/chunks/{store-usage-IE2U2FD3.js → store-usage-U72RNW64.js} +1 -1
  232. package/dist/chunks/{store-work-evidence-QQDKM5AQ.js → store-work-evidence-NY5OBATB.js} +1 -1
  233. package/dist/chunks/{taskset-NR2X2UOK.js → taskset-SL3YOXW7.js} +1 -1
  234. package/dist/chunks/{taskset-packages-ONULEIVI.js → taskset-packages-3PCEYYDA.js} +1 -1
  235. package/dist/chunks/{teams-bot-CHUYMD6K.js → teams-bot-IDEF3BMI.js} +1 -1
  236. package/dist/chunks/{training-IDSGYGU2.js → training-57ISIC7U.js} +1 -1
  237. package/dist/chunks/web-search-222Y63QW.js +2 -0
  238. package/dist/chunks/{workspaces-2TJRDM5K.js → workspaces-5DF4H5EX.js} +1 -1
  239. package/dist/cli.js +1 -1
  240. package/dist/index.js +1 -1
  241. package/dist/sandbox-template/manifest.js +1 -1
  242. package/dist/web/assets/{App-CaRMZoxo.css → App-DbYvV_W6.css} +1 -1
  243. package/dist/web/assets/{App-pcwmC4IR.js → App-nzE7JU_O.js} +4 -4
  244. package/dist/web/assets/{AppDialog-CdHad7GT.js → AppDialog-VtNvqbDm.js} +1 -1
  245. package/dist/web/assets/{AppTerminalPanel-CrmoOgd4.js → AppTerminalPanel-BMfKdrrN.js} +2 -2
  246. package/dist/web/assets/{AppsView-0P6cBsD4.js → AppsView-CdWyrDEb.js} +1 -1
  247. package/dist/web/assets/{BrowserSidebar-Cb6edJw6.js → BrowserSidebar-CtOIciOa.js} +1 -1
  248. package/dist/web/assets/{CartesianChart-B2Sxi0lv.js → CartesianChart-u1lvLM30.js} +1 -1
  249. package/dist/web/assets/{CollaborationTabs-PP0AIXhb.js → CollaborationTabs-CaBfDYRW.js} +1 -1
  250. package/dist/web/assets/{CommandMenu-GfQIMe6W.js → CommandMenu-CFW3WJ11.js} +1 -1
  251. package/dist/web/assets/{CommunityView-V6KmMl5n.js → CommunityView-D2EjaeuH.js} +1 -1
  252. package/dist/web/assets/{ComposerCreateImproveStrip-oeVeyhPX.js → ComposerCreateImproveStrip-6wYSJdzv.js} +1 -1
  253. package/dist/web/assets/{ConversationImportsSettings-CuQcvVgE.js → ConversationImportsSettings-BJ4QhF7p.js} +1 -1
  254. package/dist/web/assets/{GetStartedView-2oZ068h_.js → GetStartedView-DBcOwIJn.js} +1 -1
  255. package/dist/web/assets/{HostedModelLearningReview-DLzak_Vf.js → HostedModelLearningReview-BNpK6_W9.js} +1 -1
  256. package/dist/web/assets/{HostedModelLearningSettings-Eca6Pd9R.js → HostedModelLearningSettings-SrsdeeoA.js} +1 -1
  257. package/dist/web/assets/{LabModelVersionDetailPage-DsBblnMp.js → LabModelVersionDetailPage-Cd6bRHt9.js} +1 -1
  258. package/dist/web/assets/{LabSkillSidebar-DDknttrB.js → LabSkillSidebar-CQfvel4w.js} +1 -1
  259. package/dist/web/assets/{LabsRoute-CgNiUHsy.js → LabsRoute-sXLJt1KR.js} +4 -4
  260. package/dist/web/assets/{MainChatThread-yCVg99LU.js → MainChatThread-dlDDK2JM.js} +2 -2
  261. package/dist/web/assets/{MainPane-C86le7UF.js → MainPane-DCz38-qy.js} +4 -4
  262. package/dist/web/assets/{MarkdownText-BBVriBCj.js → MarkdownText-Drjq6-JM.js} +1 -1
  263. package/dist/web/assets/{NativeSkillSidebar-D2uVZkqh.js → NativeSkillSidebar-jncZijt-.js} +1 -1
  264. package/dist/web/assets/{NewExperienceSwitcher-DuD6GScJ.js → NewExperienceSwitcher-DXKzoMaM.js} +1 -1
  265. package/dist/web/assets/{NewProjectDialog-B6XZkJrU.js → NewProjectDialog-DIyjAxJG.js} +1 -1
  266. package/dist/web/assets/{OutputsPage-PUlmcWjv.js → OutputsPage-Dy1cNr3n.js} +1 -1
  267. package/dist/web/assets/{ProjectsPage-DWBRmej6.js → ProjectsPage-D2EeybIv.js} +1 -1
  268. package/dist/web/assets/{RightChatPanelStack-HaCVep4t.js → RightChatPanelStack-4wUL-W9_.js} +1 -1
  269. package/dist/web/assets/{RightSidebarHomePanel-BUtdPb2L.js → RightSidebarHomePanel-Bd_AHUp8.js} +1 -1
  270. package/dist/web/assets/{ScheduledWorkPage-Dg9GkGrT.js → ScheduledWorkPage-BJkSzwz2.js} +1 -1
  271. package/dist/web/assets/{SettingsView-DtldfnV-.js → SettingsView-BhcP72KH.js} +3 -3
  272. package/dist/web/assets/{TeamChatView-C71JX4je.js → TeamChatView-CR0fdicZ.js} +1 -1
  273. package/dist/web/assets/{TerminalOverlay-B4F6Q36s.js → TerminalOverlay-DGrZRZ_3.js} +10 -10
  274. package/dist/web/assets/{TrainingCreationPanel-B9MxFzQx.js → TrainingCreationPanel-BsTG7aFS.js} +1 -1
  275. package/dist/web/assets/{TrainingDraftPanel-7C48sHfC.js → TrainingDraftPanel-ByErrht7.js} +1 -1
  276. package/dist/web/assets/{UsageSettingsSection-CC57FcUB.js → UsageSettingsSection-DeYTJbcM.js} +1 -1
  277. package/dist/web/assets/{WorkSidebarPanel-Cto1usLM.js → WorkSidebarPanel-DcNvEEoy.js} +1 -1
  278. package/dist/web/assets/{WorkspaceDiffPanel-CL7wi3kp.js → WorkspaceDiffPanel-CdPRcYWN.js} +3 -3
  279. package/dist/web/assets/{WorkspaceEnvironmentMenu-zdzSDofs.js → WorkspaceEnvironmentMenu-xUYg-iGn.js} +1 -1
  280. package/dist/web/assets/{WorkspaceGitDialogs-CZSmjnrc.js → WorkspaceGitDialogs-CBViLL3S.js} +1 -1
  281. package/dist/web/assets/{WorkspaceMonacoEditor-TrUDJMKb.js → WorkspaceMonacoEditor-frxie2_S.js} +3 -3
  282. package/dist/web/assets/{agent-connections-4Dza2mDg.js → agent-connections-D7ao-vbU.js} +1 -1
  283. package/dist/web/assets/{arrow-up-right-xKb5kWQJ.js → arrow-up-right-DCWPxdbD.js} +1 -1
  284. package/dist/web/assets/{chunk-P3BRSSRD-BsGTkgyC.js → chunk-P3BRSSRD-B5JXa0Nh.js} +1 -1
  285. package/dist/web/assets/{clipboard-BgjV3aCx.js → clipboard-B-GnMVLp.js} +1 -1
  286. package/dist/web/assets/{cloud-upload-Bw9XUsKQ.js → cloud-upload-DpaGFZ9J.js} +1 -1
  287. package/dist/web/assets/{cssMode-DxsFJGb-.js → cssMode-DJHE7R3W.js} +1 -1
  288. package/dist/web/assets/{folder-open-CbmUjIYS.js → folder-open-B-DFLDFH.js} +1 -1
  289. package/dist/web/assets/{folder-plus-slsst7Ct.js → folder-plus-CPXxPvSH.js} +1 -1
  290. package/dist/web/assets/{git-commit-horizontal-BIS-8MuS.js → git-commit-horizontal-DCTzcivA.js} +1 -1
  291. package/dist/web/assets/{htmlMode-BE4VOrZo.js → htmlMode-DxZVBAYd.js} +1 -1
  292. package/dist/web/assets/index-BojtIRzO.css +1 -0
  293. package/dist/web/assets/{index-DEg0S7Qk.js → index-Di1MU6Xr.js} +2 -2
  294. package/dist/web/assets/{info-5bL9xSSf.js → info-BMxsR_bn.js} +1 -1
  295. package/dist/web/assets/{jsonMode-CYimnBhD.js → jsonMode-CzWoMkpp.js} +1 -1
  296. package/dist/web/assets/{lspLanguageFeatures-CiFuk-P7.js → lspLanguageFeatures-15K7ND6Q.js} +1 -1
  297. package/dist/web/assets/{minimize-2-BGVWKvTg.js → minimize-2-DwUgqXoR.js} +1 -1
  298. package/dist/web/assets/{monaco.contribution-DkLVGT8N.js → monaco.contribution-BBLKjER5.js} +2 -2
  299. package/dist/web/assets/{monaco.contribution-BTY4dJ0f.js → monaco.contribution-DBjvSu8p.js} +2 -2
  300. package/dist/web/assets/{monaco.contribution-DUE3CQph.js → monaco.contribution-DUWvjhIG.js} +2 -2
  301. package/dist/web/assets/{monaco.contribution-C7sMrcos.js → monaco.contribution-w0zfkYLX.js} +2 -2
  302. package/dist/web/assets/{monitor-B5hx_tzp.js → monitor-Ihu5LVYx.js} +1 -1
  303. package/dist/web/assets/{play-pmSO95Qg.js → play-D_YGCdxU.js} +1 -1
  304. package/dist/web/assets/{python-CiZvL3LX.js → python-Q4OuoXYc.js} +1 -1
  305. package/dist/web/assets/{save-CvYL4DUg.js → save-DJYUOhtD.js} +1 -1
  306. package/dist/web/assets/{square-DT_uFOml.js → square-DXtoCBNw.js} +1 -1
  307. package/dist/web/assets/{toggleHighContrast-CrE1_HY0.js → toggleHighContrast-CaNeuWVE.js} +1 -1
  308. package/dist/web/assets/{tsMode-CI_PdZmj.js → tsMode-CJnQ2wmM.js} +1 -1
  309. package/dist/web/assets/{upload-PVi8vC3T.js → upload-fCP3_OEO.js} +1 -1
  310. package/dist/web/assets/{useLocalAgentSchedules-BHJNVf42.js → useLocalAgentSchedules-BFoH_gwZ.js} +1 -1
  311. package/dist/web/assets/{useProviderSettings-CU3zXyie.js → useProviderSettings-2eysgqiA.js} +1 -1
  312. package/dist/web/assets/{useSessionTurnCache-BE7cipLX.js → useSessionTurnCache-DLF5SPD-.js} +1 -1
  313. package/dist/web/assets/{wifi-off-7WiFuOhD.js → wifi-off-DZoiFrRz.js} +1 -1
  314. package/dist/web/assets/{workers-Cv8r4CvM.js → workers-D5nr74M-.js} +1 -1
  315. package/dist/web/assets/{yaml-Bj7mdkV2.js → yaml-CwsoTJmk.js} +1 -1
  316. package/dist/web/index.html +2 -2
  317. package/docs/command-reference.md +12 -0
  318. package/package.json +1 -1
  319. package/dist/chunks/app-server-harness-services-DDFUMNYC.js +0 -2
  320. package/dist/chunks/app-server-runtime-SVB6L26M.js +0 -2
  321. package/dist/chunks/apps-EZB56RHV.js +0 -2
  322. package/dist/chunks/chunk-7UH4YDA7.js +0 -3
  323. package/dist/chunks/chunk-CGWA54LE.js +0 -2
  324. package/dist/chunks/chunk-K44RHALX.js +0 -2
  325. package/dist/chunks/chunk-MFMYWZK2.js +0 -2
  326. package/dist/chunks/chunk-P2RSBSCT.js +0 -2
  327. package/dist/chunks/chunk-QDC4OW3S.js +0 -2
  328. package/dist/chunks/chunk-SF5HJ7PL.js +0 -16
  329. package/dist/chunks/chunk-YBT2NB32.js +0 -2
  330. package/dist/chunks/chunk-YCQSVHCD.js +0 -9
  331. package/dist/chunks/cli-5DFVQL5Y.js +0 -2
  332. package/dist/chunks/configuration-command-JS6U3RMC.js +0 -2
  333. package/dist/chunks/connected-app-executor-UBMGMV76.js +0 -2
  334. package/dist/chunks/connected-evidence-NLAIEVQ3.js +0 -2
  335. package/dist/chunks/connection-NZSD3U5O.js +0 -2
  336. package/dist/chunks/core-commands-U4IBRRY5.js +0 -2
  337. package/dist/chunks/datasets-UX47DTTB.js +0 -2
  338. package/dist/chunks/desktop-test-UUU7PD4P.js +0 -3
  339. package/dist/chunks/dist-W5MJYSPF.js +0 -2
  340. package/dist/chunks/evaluation-coordination-3YQN5JQW.js +0 -2
  341. package/dist/chunks/experiment-improvements-ZRVD2AGY.js +0 -2
  342. package/dist/chunks/experiments-JEB5A2N5.js +0 -2
  343. package/dist/chunks/help-KA4OINP5.js +0 -8
  344. package/dist/chunks/host-profile-evaluation-tools-2URLU5SG.js +0 -2
  345. package/dist/chunks/host-profile-external-dataset-B2AQNSDR.js +0 -2
  346. package/dist/chunks/hosted-app-server-composition-VJQ3FM4I.js +0 -2
  347. package/dist/chunks/hosted-harness-runtime-BM4WONJN.js +0 -2
  348. package/dist/chunks/hosted-profile-compiler-RKDWHYK3.js +0 -2
  349. package/dist/chunks/hosted-profile-evaluation-control-57V24UGU.js +0 -2
  350. package/dist/chunks/human-review-CSYAW4PC.js +0 -2
  351. package/dist/chunks/local-harness-improvement-runtime-3T6E7I5Q.js +0 -2
  352. package/dist/chunks/local-harness-taskset-review-LQPQBALH.js +0 -2
  353. package/dist/chunks/opchat-6ADSONAD.js +0 -3
  354. package/dist/chunks/organizations-GT24ZTCN.js +0 -2
  355. package/dist/chunks/project-action-payload-GHSLE7K3.js +0 -2
  356. package/dist/chunks/project-agent-YYSQIHVE.js +0 -2
  357. package/dist/chunks/refiner-profile-service-ZK7KAFP5.js +0 -2
  358. package/dist/chunks/sandbox-command-U6346TVJ.js +0 -2
  359. package/dist/chunks/saved-work-SWHZ4OLO.js +0 -2
  360. package/dist/chunks/standalone-experiment-turn-owner-LIAQWTGI.js +0 -2
  361. package/dist/chunks/store-harness-workspaces-XUM4Z66X.js +0 -2
  362. package/dist/chunks/store-learned-preference-migration-validation-V27XD4I7.js +0 -2
  363. package/dist/chunks/store-learning-WLG6KFIO.js +0 -2
  364. package/dist/chunks/web-search-BPON7H5N.js +0 -2
  365. package/dist/web/assets/index-erq7hUne.css +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalOverlay-B4F6Q36s.js","assets/index-DEg0S7Qk.js","assets/index-erq7hUne.css","assets/TerminalOverlay-DwBiZLwk.css","assets/CommandMenu-GfQIMe6W.js","assets/CommandMenu-Cb3vNGJr.css","assets/SettingsView-DtldfnV-.js","assets/useProviderSettings-CU3zXyie.js","assets/AppDialog-CdHad7GT.js","assets/save-CvYL4DUg.js","assets/MarkdownText-BBVriBCj.js","assets/useProviderSettings-Cktvzinz.css","assets/folder-open-CbmUjIYS.js","assets/play-pmSO95Qg.js","assets/wifi-off-7WiFuOhD.js","assets/cloud-upload-Bw9XUsKQ.js","assets/git-commit-horizontal-BIS-8MuS.js","assets/useLocalAgentSchedules-BHJNVf42.js","assets/folder-plus-slsst7Ct.js","assets/WorkspaceDiffPanel-CL7wi3kp.js","assets/training-model-data-CKOkpBBL.js","assets/info-5bL9xSSf.js","assets/minimize-2-BGVWKvTg.js","assets/clipboard-BgjV3aCx.js","assets/SettingsView-DjjnCnlb.css","assets/git-dialogs-C-F47S10.css","assets/NewProjectDialog-B6XZkJrU.js","assets/monitor-B5hx_tzp.js","assets/WorkspaceGitDialogs-CZSmjnrc.js","assets/upload-PVi8vC3T.js","assets/WorkspaceEnvironmentMenu-zdzSDofs.js","assets/square-DT_uFOml.js","assets/WorkspaceEnvironmentMenu-DGIFdG3o.css","assets/MainPane-C86le7UF.js","assets/arrow-up-right-xKb5kWQJ.js","assets/MainPane-BIM_UJ3q.css"])))=>i.map(i=>d[i]);
2
- import{r as h,j as g,a as g_,g as f0,_ as fr}from"./index-DEg0S7Qk.js";const h0=h.createContext(void 0),g0=e=>{const t=h.useContext(h0);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},v_=({client:e,children:t})=>(h.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),g.jsx(h0.Provider,{value:e,children:t})),b_={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)};var y_=class{#e=b_;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};const zr=new y_;function S_(e){setTimeout(e,0)}const x_=typeof window>"u"||"Deno"in globalThis;function Yn(){}function k_(e,t){return typeof e=="function"?e(t):e}function v0(e){return typeof e=="number"&&e>=0&&e!==1/0}function b0(e,t){return Math.max(e+(t||0)-Date.now(),0)}function on(e,t){return typeof e=="function"?e(t):e}function Jg(e,t){const{type:n="all",exact:a,fetchStatus:s,predicate:r,queryKey:i,stale:c}=e;if(i){if(a){if(t.queryHash!==Hf(i,t.options))return!1}else if(!ri(t.queryKey,i))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||s&&s!==t.state.fetchStatus||r&&!r(t))}function Qg(e,t){const{exact:n,status:a,predicate:s,mutationKey:r}=e;if(r){if(!t.options.mutationKey)return!1;if(n){if(bc(t.options.mutationKey)!==bc(r))return!1}else if(!ri(t.options.mutationKey,r))return!1}return!(a&&t.state.status!==a||s&&!s(t))}function Hf(e,t){return(t?.queryKeyHashFn||bc)(e)}function bc(e){return JSON.stringify(e,(t,n)=>Np(n)?Object.keys(n).sort().reduce((a,s)=>(a[s]=n[s],a),{}):n)}function ri(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(Array.isArray(e)&&Array.isArray(t)){for(let a=0;a<t.length;a++)if(!ri(e[a],t[a]))return!1;return!0}const n=Object.keys(t);for(const a of n)if(!ri(e[a],t[a]))return!1;return!0}return!1}const w_=Object.prototype.hasOwnProperty;function y0(e,t,n=0){if(e===t)return e;if(n>500)return t;const a=Yg(e)&&Yg(t);if(!a&&!(Np(e)&&Np(t)))return t;const s=(a?e:Object.keys(e)).length,r=a?t:Object.keys(t),i=r.length,c=a?new Array(i):{};let l=0;for(let u=0;u<i;u++){const p=a?u:r[u],f=e[p],S=t[p];if(f===S){c[p]=f,(a?u<s:w_.call(e,p))&&l++;continue}if(f===null||S===null||typeof f!="object"||typeof S!="object"){c[p]=S;continue}const b=y0(f,S,n+1);c[p]=b,b===f&&l++}return s===i&&l===s?e:c}function Hm(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function Yg(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Np(e){if(!Xg(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Xg(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Xg(e){return Object.prototype.toString.call(e)==="[object Object]"}function I_(e){return new Promise(t=>{zr.setTimeout(t,e)})}function Dp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?y0(e,t):t}function __(e,t,n=0){const a=[...e,t];return n&&a.length>n?a.slice(1):a}function C_(e,t,n=0){const a=[t,...e];return n&&a.length>n?a.slice(0,-1):a}const Uf=Symbol();function S0(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Uf?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function x0(e,t){return typeof e=="function"?e(...t):!!e}function R_(e,t,n){let a=!1,s;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(s??=t(),a||(a=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),e}let P_=()=>x_;const qf=()=>P_();var Lc=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},T_=class extends Lc{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}};const Bf=new T_,A_=S_;function E_(){let e=[],t=0,n=c=>{c()},a=c=>{c()},s=A_;const r=c=>{t?e.push(c):s(()=>{n(c)})},i=()=>{const c=e;e=[],c.length&&s(()=>{a(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||i()}return l},batchCalls:c=>(...l)=>{r(()=>{c(...l)})},schedule:r,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{a=c},setScheduler:c=>{s=c}}}const Dn=E_();var j_=class extends Lc{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};const vd=new j_;function M_(e){return Math.min(1e3*2**e,3e4)}function k0(e){return(e??"online")==="online"?vd.isOnline():!0}var Lp=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function w0(e){let t=!1,n=0,a,s="pending",r,i;const c=new Promise((M,E)=>{r=M,i=E});c.catch(Yn);const l=()=>s!=="pending",u=M=>{if(!l()){const E=new Lp(M);C(E),e.onCancel?.(E)}},p=()=>{t=!0},f=()=>{t=!1},S=()=>Bf.isFocused()&&(e.networkMode==="always"||vd.isOnline())&&e.canRun(),b=()=>k0(e.networkMode)&&e.canRun(),w=M=>{l()||(a?.(),s="resolved",r(M))},C=M=>{l()||(a?.(),s="rejected",i(M))},P=()=>new Promise(M=>{a=E=>{(l()||S())&&M(E)},e.onPause?.()}).then(()=>{a=void 0,l()||e.onContinue?.()}),_=()=>{if(l())return;let M;const E=n===0?e.initialPromise:void 0;try{M=E??e.fn()}catch(T){M=Promise.reject(T)}Promise.resolve(M).then(w).catch(T=>{if(l())return;const y=e.retry??(qf()?0:3),I=e.retryDelay??M_,R=typeof I=="function"?I(n,T):I,O=y===!0||typeof y=="number"&&n<y||typeof y=="function"&&y(n,T);if(t||!O){C(T);return}n++,e.onFail?.(n,T),I_(R).then(()=>S()?void 0:P()).then(()=>{t?C(T):_()})})};return{promise:c,status:()=>s,cancel:u,continue:()=>(a?.(),c),cancelRetry:p,continueRetry:f,canStart:b,start:()=>(b()?_():P().then(_),c)}}var I0=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),v0(this.gcTime)&&(this.#e=zr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(qf()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(zr.clearTimeout(this.#e),this.#e=void 0)}};function O_(e){return{onFetch:(t,n)=>{const a=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,r=t.state.data?.pages||[],i=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},l=0;const u=async()=>{let p=!1;const f=w=>{R_(w,()=>t.signal,()=>p=!0)},S=S0(t.options,t.fetchOptions),b=async(w,C,P)=>{if(p)return Promise.reject(t.signal.reason);if(C==null&&w.pages.length)return Promise.resolve(w);const M=(()=>{const I={client:t.client,queryKey:t.queryKey,pageParam:C,direction:P?"backward":"forward",meta:t.options.meta};return f(I),I})(),E=await S(M),{maxPages:T}=t.options,y=P?C_:__;return{pages:y(w.pages,E,T),pageParams:y(w.pageParams,C,T)}};if(s&&r.length){const w=s==="backward",C=w?_0:zp,P={pages:r,pageParams:i};c=await b(P,C(a,P),w)}else{const w=e??r.length;do{const C=l===0?i[0]??a.initialPageParam:zp(a,c);if(l>0&&C==null)break;c=await b(c,C),l++}while(l<w)}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 zp(e,{pages:t,pageParams:n}){const a=t.length-1;return t.length>0?e.getNextPageParam(t[a],t,n[a],n):void 0}function _0(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function o8(e,t){return t?zp(e,t)!=null:!1}function i8(e,t){return!t||!e.getPreviousPageParam?!1:_0(e,t)!=null}var $_=class extends I0{#e;#t;#n;#a;#r;#s;#o;#c;constructor(e){super(),this.#c=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#a=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=tv(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#s?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=tv(this.options);t.data!==void 0&&(this.setState(ev(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#a.remove(this)}setData(e,t){const n=Dp(this.state.data,e,this.options);return this.#i({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#i({type:"setState",state:e})}cancel(e){const t=this.#s?.promise;return this.#s?.cancel(e),t?t.then(Yn).catch(Yn):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>on(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Uf||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>on(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!b0(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#s?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#s?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#a.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){const t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#s&&(this.#c||this.state.fetchStatus==="paused"&&this.state.status==="pending"?this.#s.cancel({revert:!0}):this.#s.cancelRetry()),this.scheduleGc()),this.#a.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#s?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#s)return this.#s.continueRetry(),this.#s.promise}if(e&&this.setOptions(e),!this.options.queryFn){const l=this.observers.find(u=>u.options.queryFn);l&&this.setOptions(l.options)}const n=new AbortController,a=l=>{Object.defineProperty(l,"signal",{enumerable:!0,get:()=>(this.#c=!0,n.signal)})},s=()=>{const l=S0(this.options,t),p=(()=>{const f={client:this.#r,queryKey:this.queryKey,meta:this.meta};return a(f),f})();return this.#c=!1,this.options.persister?this.options.persister(l,p,this):l(p)},i=(()=>{const l={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:s};return a(l),l})();(this.#e==="infinite"?O_(this.options.pages):this.options.behavior)?.onFetch(i,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==i.fetchOptions?.meta)&&this.#i({type:"fetch",meta:i.fetchOptions?.meta});const c=this.#s=w0({initialPromise:t?.initialPromise,fn:i.fetchFn,onCancel:l=>{l instanceof Lp&&l.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(l,u)=>{this.#i({type:"failed",failureCount:l,error:u})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:i.options.retry,retryDelay:i.options.retryDelay,networkMode:i.options.networkMode,canRun:()=>!0});try{const l=await c.start();if(l===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(l),this.#a.config.onSuccess?.(l,this),this.#a.config.onSettled?.(l,this.state.error,this),l}catch(l){if(l instanceof Lp){if(l.silent)return this.#s.promise;if(l.revert){if(this.state.data===void 0)throw l;return this.state.data}}throw this.#i({type:"error",error:l}),this.#a.config.onError?.(l,this),this.#a.config.onSettled?.(this.state.data,l,this),l}finally{this.#s===c&&(this.#s=void 0),this.scheduleGc()}}#i(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...C0(n.data,this.options),fetchMeta:e.meta??null};case"success":const a={...n,...ev(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?a:void 0,a;case"error":const s=e.error;return{...n,error:s,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:s,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),Dn.batch(()=>{this.observers.slice().forEach(n=>{n.onQueryUpdate()}),this.#a.notify({query:this,type:"updated",action:e})})}};function C0(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:k0(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function ev(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function tv(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,a=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?a??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var N_=class extends Lc{#e;#t=void 0;#n=void 0;#a=void 0;#r;#s;#o;#c;#i;#p;#d;#u;#l;#f=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),nv(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Hp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Hp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#x(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof on(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#k(),this.#t.setOptions(this.options),t._defaulted&&!Hm(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const a=this.hasListeners();a&&av(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),a&&(this.#t!==n||on(this.options.enabled,this.#t)!==on(t.enabled,this.#t)||on(this.options.staleTime,this.#t)!==on(t.staleTime,this.#t))&&this.#g();const s=this.#v();a&&(this.#t!==n||on(this.options.enabled,this.#t)!==on(t.enabled,this.#t)||s!==this.#l)&&this.#b(s)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return Hm(this.getCurrentResult(),n)||(this.#a=n,this.#s=this.options,this.#r=this.#t.state),n}getCurrentResult(){return this.#a}trackResult(e,t){return new Proxy(e,{get:(n,a)=>(this.trackProp(a),t?.(a),Reflect.get(n,a))})}trackProp(e){this.#f.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);let a=()=>{},s;const r=new Promise(i=>{s=i,a=this.#e.getQueryCache().subscribe(c=>{c.type==="updated"&&c.query.queryHash===n.queryHash&&n.state.data!==void 0&&(a(),i(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{const i=this.createResult(n,t);return s?.(i),i}).finally(()=>{a()}),r])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#a))}#m(e){this.#k();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Yn)),t}#h(e){return!qf()&&on(this.options.enabled,this.#t)!==!1&&v0(e)}#g(){this.#S();const e=on(this.options.staleTime,this.#t);if(this.#a.isStale||!this.#h(e))return;const t=b0(this.#a.dataUpdatedAt,e)+1;this.#d=zr.setTimeout(()=>{this.#a.isStale||this.updateResult()},t)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#b(e){this.#x(),this.#l=e,!(this.#l===0||!this.#h(this.#l))&&(this.#u=zr.setInterval(()=>{(this.options.refetchIntervalInBackground||Bf.isFocused())&&this.#m()},this.#l))}#y(){this.#g(),this.#b(this.#v())}#S(){this.#d!==void 0&&(zr.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#u!==void 0&&(zr.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const n=this.#t,a=this.options,s=this.#a,r=this.#r,i=this.#s,c=e!==n?e.state:this.#n,{state:l}=e;let u={...l},p=!1,f;if(t._optimisticResults){const y=this.hasListeners(),I=!y&&nv(e,t),R=y&&av(e,n,t,a);(I||R)&&(u={...u,...C0(l.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:S,errorUpdatedAt:b,status:w}=u;f=u.data;let C=!1;if(t.placeholderData!==void 0&&f===void 0&&w==="pending"){let y;s?.isPlaceholderData&&t.placeholderData===i?.placeholderData?(y=s.data,C=!0):y=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,y!==void 0&&(w="success",f=Dp(s?.data,y,t),p=!0)}if(t.select&&f!==void 0&&!C)if(s&&f===r?.data&&t.select===this.#c)f=this.#i;else try{this.#c=t.select,f=t.select(f),f=Dp(s?.data,f,t),this.#i=f,this.#o=null}catch(y){this.#o=y}else f===void 0&&(this.#o=null);this.#o&&(S=this.#o,f=this.#i,b=Date.now(),w="error",p=!1);const P=u.fetchStatus==="fetching",_=w==="pending",M=w==="error",E=_&&P,T=f!==void 0;return{status:w,fetchStatus:u.fetchStatus,isPending:_,isSuccess:w==="success",isError:M,isInitialLoading:E,isLoading:E,data:f,dataUpdatedAt:u.dataUpdatedAt,error:S,errorUpdatedAt:b,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:u.dataUpdateCount>c.dataUpdateCount||u.errorUpdateCount>c.errorUpdateCount,isFetching:P,isRefetching:P&&!_,isLoadingError:M&&!T,isPaused:u.fetchStatus==="paused",isPlaceholderData:p,isRefetchError:M&&T,isStale:Ff(e,t),refetch:this.refetch,isEnabled:on(t.enabled,e)!==!1}}updateResult(){const e=this.#a,t=this.createResult(this.#t,this.options);if(this.#r=this.#t.state,this.#s=this.options,this.#r.data!==void 0&&(this.#p=this.#t),Hm(t,e))return;this.#a=t;const a=(()=>{if(!e)return!0;const{notifyOnChangeProps:s}=this.options,r=typeof s=="function"?s():s;if(r==="all"||!r&&!this.#f.size)return!0;const i=new Set(r??this.#f);return this.options.throwOnError&&i.add("error"),Object.keys(this.#a).some(c=>{const l=c;return this.#a[l]!==e[l]&&i.has(l)})})();Dn.batch(()=>{a&&this.listeners.forEach(s=>{s(this.#a)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}#k(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function D_(e,t){return on(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&on(t.retryOnMount,e)===!1)}function nv(e,t){return D_(e,t)||e.state.data!==void 0&&Hp(e,t,t.refetchOnMount)}function Hp(e,t,n){if(on(t.enabled,e)!==!1&&on(t.staleTime,e)!=="static"){const a=typeof n=="function"?n(e):n;return a==="always"||a!==!1&&Ff(e,t)}return!1}function av(e,t,n,a){return(e!==t||on(a.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ff(e,n)}function Ff(e,t){return on(t.enabled,e)!==!1&&e.isStaleByTime(on(t.staleTime,e))}var L_=class extends I0{#e;#t;#n;#a;constructor(t){super(),this.#e=t.client,this.mutationId=t.mutationId,this.#n=t.mutationCache,this.#t=[],this.state=t.state||z_(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){this.#t.includes(t)||(this.#t.push(t),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#t=this.#t.filter(n=>n!==t),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#a?.continue()??(this.state.status==="pending"?this.execute(this.state.variables):Promise.resolve())}async execute(t){const n=()=>{this.#r({type:"continue"})},a={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},s=this.#a=w0({fn:()=>this.options.mutationFn?this.options.mutationFn(t,a):Promise.reject(new Error("No mutationFn found")),onFail:(c,l)=>{this.#r({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#r({type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),r=this.state.status==="pending",i=!s.canStart();try{if(r)n();else{this.#r({type:"pending",variables:t,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(t,this,a);const l=await this.options.onMutate?.(t,a);l!==this.state.context&&this.#r({type:"pending",context:l,variables:t,isPaused:i})}const c=await s.start();return await this.#n.config.onSuccess?.(c,t,this.state.context,this,a),await this.options.onSuccess?.(c,t,this.state.context,a),await this.#n.config.onSettled?.(c,null,this.state.variables,this.state.context,this,a),await this.options.onSettled?.(c,null,t,this.state.context,a),this.#r({type:"success",data:c}),c}catch(c){try{await this.#n.config.onError?.(c,t,this.state.context,this,a)}catch(l){Promise.reject(l)}try{await this.options.onError?.(c,t,this.state.context,a)}catch(l){Promise.reject(l)}try{await this.#n.config.onSettled?.(void 0,c,this.state.variables,this.state.context,this,a)}catch(l){Promise.reject(l)}try{await this.options.onSettled?.(void 0,c,t,this.state.context,a)}catch(l){Promise.reject(l)}throw this.#r({type:"error",error:c}),c}finally{this.#a===s&&(this.#a=void 0),this.#n.runNext(this)}}#r(t){const n=a=>{switch(t.type){case"failed":return{...a,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...a,isPaused:!0};case"continue":return{...a,isPaused:!1};case"pending":return{...a,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...a,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...a,data:void 0,error:t.error,failureCount:a.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),Dn.batch(()=>{this.#t.forEach(a=>{a.onMutationUpdate(t)}),this.#n.notify({mutation:this,type:"updated",action:t})})}};function z_(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var H_=class extends Lc{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){const a=new L_({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(a),a}add(e){this.#e.add(e);const t=Il(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Il(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const a=n.indexOf(e);a!==-1&&n.splice(a,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Il(e);if(typeof t=="string"){const n=this.#t.get(t)?.find(a=>a.state.status==="pending");return!n||n===e}else return!0}runNext(e){const t=Il(e);return typeof t=="string"?this.#t.get(t)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Dn.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Qg(t,n))}findAll(e={}){return this.getAll().filter(t=>Qg(e,t))}notify(e){Dn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Dn.batch(()=>Promise.all(e.map(t=>t.continue().catch(Yn))))}};function Il(e){return e.options.scope?.id}var U_=class extends Lc{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){const a=t.queryKey,s=t.queryHash??Hf(a,t);let r=this.get(s);return r||(r=new $_({client:e,queryKey:a,queryHash:s,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(a)}),this.add(r)),r}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Dn.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Jg(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Jg(e,n)):t}notify(e){Dn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Dn.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Dn.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},q_=class{#e;#t;#n;#a;#r;#s;#o;#c;constructor(e={}){this.#e=e.queryCache||new U_,this.#t=e.mutationCache||new H_,this.#n=e.defaultOptions||{},this.#a=new Map,this.#r=new Map,this.#s=0}mount(){this.#s++,this.#s===1&&(this.#o=Bf.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#c=vd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#s--,this.#s===0&&(this.#o?.(),this.#o=void 0,this.#c?.(),this.#c=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),a=n.state.data;return a===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(on(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(a))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>[t,n.data])}setQueryData(e,t,n){const a=this.defaultQueryOptions({queryKey:e}),s=this.#e.get(a.queryHash)?.state.data,r=k_(t,s);if(r!==void 0)return this.#e.build(this,a).setData(r,{...n,manual:!0})}setQueriesData(e,t,n){return Dn.batch(()=>this.#e.findAll(e).map(({queryKey:a})=>[a,this.setQueryData(a,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;Dn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return Dn.batch(()=>{const a=n.findAll(e),s=new Set(a);return a.forEach(r=>{r.reset()}),this.refetchQueries({type:"active",predicate:r=>s.has(r)},t)})}cancelQueries(e,t={}){const n={revert:!0,...t},a=Dn.batch(()=>this.#e.findAll(e).map(s=>s.cancel(n)));return Promise.all(a).then(Yn).catch(Yn)}invalidateQueries(e,t={}){return Dn.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},a=Dn.batch(()=>this.#e.findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let r=s.fetch(void 0,n);return n.throwOnError||(r=r.catch(Yn)),s.state.fetchStatus==="paused"?Promise.resolve():r}));return Promise.all(a).then(Yn)}async query(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t),a=n.isStaleByTime(on(t.staleTime,n))?await n.fetch(t):n.state.data,s=t.select;return s?s(a):a}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(on(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Yn).catch(Yn)}infiniteQuery(e){return e._type="infinite",this.query(e)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Yn).catch(Yn)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return vd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#a.set(bc(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(a=>{ri(e,a.queryKey)&&Object.assign(n,a.defaultOptions)}),n}setMutationDefaults(e,t){this.#r.set(bc(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(a=>{ri(e,a.mutationKey)&&Object.assign(n,a.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Hf(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Uf&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};const R0=h.createContext(!1),B_=()=>h.useContext(R0);R0.Provider;function F_(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}const V_=h.createContext(F_()),K_=()=>h.useContext(V_),W_=(e,t,n)=>{const a=n?.state.error&&typeof e.throwOnError=="function"?x0(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||a)&&(t.isReset()||(e.retryOnMount=!1))},G_=e=>{h.useEffect(()=>{e.clearReset()},[e])},Z_=({result:e,errorResetBoundary:t,throwOnError:n,query:a,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&a&&(s&&e.data===void 0||x0(n,[e.error,a])),J_=e=>{if(e.suspense){const n=s=>s==="static"?s:Math.max(s??1e3,1e3),a=e.staleTime;e.staleTime=typeof a=="function"?(...s)=>n(a(...s)):n(a),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Q_=(e,t)=>e?.suspense&&t.isPending,Y_=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function X_(e,t,n){const a=B_(),s=K_(),r=g0(),i=r.defaultQueryOptions(e),c=r.getQueryCache().get(i.queryHash),l=e.subscribed!==!1;i._optimisticResults=a?"isRestoring":l?"optimistic":void 0,J_(i),W_(i,s,c),G_(s);const[u]=h.useState(()=>new t(r,i)),p=u.getOptimisticResult(i),f=!a&&l;if(h.useSyncExternalStore(h.useCallback(S=>{const b=f?u.subscribe(Dn.batchCalls(S)):Yn;return u.updateResult(),b},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),h.useEffect(()=>{u.setOptions(i)},[i,u]),Q_(i,p))throw Y_(i,u,s);if(Z_({result:p,errorResetBoundary:s,throwOnError:i.throwOnError,query:c,suspense:i.suspense}))throw p.error;return i.notifyOnChangeProps?p:u.trackResult(p)}function P0(e,t){return X_(e,N_)}function eC(){return new q_({defaultOptions:{queries:{staleTime:6e4,gcTime:15*6e4,retry:1,refetchOnWindowFocus:!1}}})}const tC=new Set(["turn.started","turn.completed","turn.failed","turn.interrupted","approval.requested","approval.resolved","task.input","task.wait"]);function nC(e){const t={};for(const n of e)n.sessionId&&tC.has(n.name)&&(Date.parse(n.timestamp)>Date.parse(t[n.sessionId]??"")||!t[n.sessionId]&&Number.isFinite(Date.parse(n.timestamp)))&&(t[n.sessionId]=n.timestamp);return t}function aC(e,t,n){return[...new Map(e.map(a=>[a.id,a])).values()].sort((a,s)=>Number(n.has(s.id))-Number(n.has(a.id))||bd(s,t)-bd(a,t)||a.id.localeCompare(s.id))}function bd(e,t){const n=typeof e.metadata?.sidebarActivityAt=="string"?e.metadata.sidebarActivityAt:null;return Math.max(Date.parse(t[e.id]??"")||0,Date.parse(n??e.createdAt)||0)}function sC(e,t,n,a=new Date){const s=c=>`${c.getFullYear()}-${c.getMonth()}-${c.getDate()}`,r=new Date(a);r.setDate(a.getDate()-1);const i=[];for(const c of e){const l=new Date(bd(c,t)),u=n.has(c.id),p=u?"running":s(l);let f=i.at(-1);f?.key!==p&&(f={key:p,label:u||p===s(a)?null:p===s(r)?"Yesterday":l.toLocaleDateString(void 0,{month:"short",day:"numeric",...l.getFullYear()!==a.getFullYear()?{year:"numeric"}:{}}),sessions:[]},i.push(f)),f.sessions.push(c)}return i}function rC(e,t,n){const a=new Headers;a.set("Accept","text/event-stream"),a.set("Authorization",`Bearer ${e.token}`);const s=new URL(`${e.serverUrl.replace(/\/$/,"")}/v1/events`);return n!==void 0&&Number.isSafeInteger(n)&&n>0&&s.searchParams.set("afterSequence",String(n)),{url:s.toString(),init:{headers:a,signal:t}}}function oC(e){return Math.min(500*2**Math.max(0,e),1e4)}async function iC(e,t,n,a){T0(e);const s=e.body.getReader(),r=new TextDecoder;let i="";for(;!a?.aborted;){const{done:c,value:l}=await s.read();if(c){i+=r.decode();break}i+=r.decode(l,{stream:!0});let u=i.indexOf(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalOverlay-DGrZRZ_3.js","assets/index-Di1MU6Xr.js","assets/index-BojtIRzO.css","assets/TerminalOverlay-DwBiZLwk.css","assets/CommandMenu-CFW3WJ11.js","assets/CommandMenu-Cb3vNGJr.css","assets/SettingsView-BhcP72KH.js","assets/useProviderSettings-2eysgqiA.js","assets/AppDialog-VtNvqbDm.js","assets/save-DJYUOhtD.js","assets/MarkdownText-Drjq6-JM.js","assets/useProviderSettings-Cktvzinz.css","assets/folder-open-B-DFLDFH.js","assets/play-D_YGCdxU.js","assets/wifi-off-DZoiFrRz.js","assets/cloud-upload-DpaGFZ9J.js","assets/git-commit-horizontal-DCTzcivA.js","assets/useLocalAgentSchedules-BFoH_gwZ.js","assets/folder-plus-CPXxPvSH.js","assets/WorkspaceDiffPanel-CdPRcYWN.js","assets/training-model-data-CKOkpBBL.js","assets/info-BMxsR_bn.js","assets/minimize-2-DwUgqXoR.js","assets/clipboard-B-GnMVLp.js","assets/SettingsView-DjjnCnlb.css","assets/git-dialogs-C-F47S10.css","assets/NewProjectDialog-DIyjAxJG.js","assets/monitor-Ihu5LVYx.js","assets/WorkspaceGitDialogs-CBViLL3S.js","assets/upload-fCP3_OEO.js","assets/WorkspaceEnvironmentMenu-xUYg-iGn.js","assets/square-DXtoCBNw.js","assets/WorkspaceEnvironmentMenu-DGIFdG3o.css","assets/MainPane-DCz38-qy.js","assets/arrow-up-right-DCWPxdbD.js","assets/MainPane-BIM_UJ3q.css"])))=>i.map(i=>d[i]);
2
+ import{r as h,j as g,a as g_,g as f0,_ as fr}from"./index-Di1MU6Xr.js";const h0=h.createContext(void 0),g0=e=>{const t=h.useContext(h0);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},v_=({client:e,children:t})=>(h.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),g.jsx(h0.Provider,{value:e,children:t})),b_={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)};var y_=class{#e=b_;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};const zr=new y_;function S_(e){setTimeout(e,0)}const x_=typeof window>"u"||"Deno"in globalThis;function Yn(){}function k_(e,t){return typeof e=="function"?e(t):e}function v0(e){return typeof e=="number"&&e>=0&&e!==1/0}function b0(e,t){return Math.max(e+(t||0)-Date.now(),0)}function on(e,t){return typeof e=="function"?e(t):e}function Jg(e,t){const{type:n="all",exact:a,fetchStatus:s,predicate:r,queryKey:i,stale:c}=e;if(i){if(a){if(t.queryHash!==Hf(i,t.options))return!1}else if(!ri(t.queryKey,i))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||s&&s!==t.state.fetchStatus||r&&!r(t))}function Qg(e,t){const{exact:n,status:a,predicate:s,mutationKey:r}=e;if(r){if(!t.options.mutationKey)return!1;if(n){if(bc(t.options.mutationKey)!==bc(r))return!1}else if(!ri(t.options.mutationKey,r))return!1}return!(a&&t.state.status!==a||s&&!s(t))}function Hf(e,t){return(t?.queryKeyHashFn||bc)(e)}function bc(e){return JSON.stringify(e,(t,n)=>Np(n)?Object.keys(n).sort().reduce((a,s)=>(a[s]=n[s],a),{}):n)}function ri(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(Array.isArray(e)&&Array.isArray(t)){for(let a=0;a<t.length;a++)if(!ri(e[a],t[a]))return!1;return!0}const n=Object.keys(t);for(const a of n)if(!ri(e[a],t[a]))return!1;return!0}return!1}const w_=Object.prototype.hasOwnProperty;function y0(e,t,n=0){if(e===t)return e;if(n>500)return t;const a=Yg(e)&&Yg(t);if(!a&&!(Np(e)&&Np(t)))return t;const s=(a?e:Object.keys(e)).length,r=a?t:Object.keys(t),i=r.length,c=a?new Array(i):{};let l=0;for(let u=0;u<i;u++){const p=a?u:r[u],f=e[p],S=t[p];if(f===S){c[p]=f,(a?u<s:w_.call(e,p))&&l++;continue}if(f===null||S===null||typeof f!="object"||typeof S!="object"){c[p]=S;continue}const b=y0(f,S,n+1);c[p]=b,b===f&&l++}return s===i&&l===s?e:c}function Hm(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function Yg(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Np(e){if(!Xg(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Xg(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Xg(e){return Object.prototype.toString.call(e)==="[object Object]"}function I_(e){return new Promise(t=>{zr.setTimeout(t,e)})}function Dp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?y0(e,t):t}function __(e,t,n=0){const a=[...e,t];return n&&a.length>n?a.slice(1):a}function C_(e,t,n=0){const a=[t,...e];return n&&a.length>n?a.slice(0,-1):a}const Uf=Symbol();function S0(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Uf?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function x0(e,t){return typeof e=="function"?e(...t):!!e}function R_(e,t,n){let a=!1,s;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(s??=t(),a||(a=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),e}let P_=()=>x_;const qf=()=>P_();var Lc=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},T_=class extends Lc{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}};const Bf=new T_,A_=S_;function E_(){let e=[],t=0,n=c=>{c()},a=c=>{c()},s=A_;const r=c=>{t?e.push(c):s(()=>{n(c)})},i=()=>{const c=e;e=[],c.length&&s(()=>{a(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||i()}return l},batchCalls:c=>(...l)=>{r(()=>{c(...l)})},schedule:r,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{a=c},setScheduler:c=>{s=c}}}const Dn=E_();var j_=class extends Lc{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};const vd=new j_;function M_(e){return Math.min(1e3*2**e,3e4)}function k0(e){return(e??"online")==="online"?vd.isOnline():!0}var Lp=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function w0(e){let t=!1,n=0,a,s="pending",r,i;const c=new Promise((M,E)=>{r=M,i=E});c.catch(Yn);const l=()=>s!=="pending",u=M=>{if(!l()){const E=new Lp(M);C(E),e.onCancel?.(E)}},p=()=>{t=!0},f=()=>{t=!1},S=()=>Bf.isFocused()&&(e.networkMode==="always"||vd.isOnline())&&e.canRun(),b=()=>k0(e.networkMode)&&e.canRun(),w=M=>{l()||(a?.(),s="resolved",r(M))},C=M=>{l()||(a?.(),s="rejected",i(M))},P=()=>new Promise(M=>{a=E=>{(l()||S())&&M(E)},e.onPause?.()}).then(()=>{a=void 0,l()||e.onContinue?.()}),_=()=>{if(l())return;let M;const E=n===0?e.initialPromise:void 0;try{M=E??e.fn()}catch(T){M=Promise.reject(T)}Promise.resolve(M).then(w).catch(T=>{if(l())return;const y=e.retry??(qf()?0:3),I=e.retryDelay??M_,R=typeof I=="function"?I(n,T):I,O=y===!0||typeof y=="number"&&n<y||typeof y=="function"&&y(n,T);if(t||!O){C(T);return}n++,e.onFail?.(n,T),I_(R).then(()=>S()?void 0:P()).then(()=>{t?C(T):_()})})};return{promise:c,status:()=>s,cancel:u,continue:()=>(a?.(),c),cancelRetry:p,continueRetry:f,canStart:b,start:()=>(b()?_():P().then(_),c)}}var I0=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),v0(this.gcTime)&&(this.#e=zr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(qf()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(zr.clearTimeout(this.#e),this.#e=void 0)}};function O_(e){return{onFetch:(t,n)=>{const a=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,r=t.state.data?.pages||[],i=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},l=0;const u=async()=>{let p=!1;const f=w=>{R_(w,()=>t.signal,()=>p=!0)},S=S0(t.options,t.fetchOptions),b=async(w,C,P)=>{if(p)return Promise.reject(t.signal.reason);if(C==null&&w.pages.length)return Promise.resolve(w);const M=(()=>{const I={client:t.client,queryKey:t.queryKey,pageParam:C,direction:P?"backward":"forward",meta:t.options.meta};return f(I),I})(),E=await S(M),{maxPages:T}=t.options,y=P?C_:__;return{pages:y(w.pages,E,T),pageParams:y(w.pageParams,C,T)}};if(s&&r.length){const w=s==="backward",C=w?_0:zp,P={pages:r,pageParams:i};c=await b(P,C(a,P),w)}else{const w=e??r.length;do{const C=l===0?i[0]??a.initialPageParam:zp(a,c);if(l>0&&C==null)break;c=await b(c,C),l++}while(l<w)}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 zp(e,{pages:t,pageParams:n}){const a=t.length-1;return t.length>0?e.getNextPageParam(t[a],t,n[a],n):void 0}function _0(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function o8(e,t){return t?zp(e,t)!=null:!1}function i8(e,t){return!t||!e.getPreviousPageParam?!1:_0(e,t)!=null}var $_=class extends I0{#e;#t;#n;#a;#r;#s;#o;#c;constructor(e){super(),this.#c=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#a=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=tv(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#s?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=tv(this.options);t.data!==void 0&&(this.setState(ev(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#a.remove(this)}setData(e,t){const n=Dp(this.state.data,e,this.options);return this.#i({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#i({type:"setState",state:e})}cancel(e){const t=this.#s?.promise;return this.#s?.cancel(e),t?t.then(Yn).catch(Yn):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>on(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Uf||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>on(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!b0(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#s?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#s?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#a.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){const t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#s&&(this.#c||this.state.fetchStatus==="paused"&&this.state.status==="pending"?this.#s.cancel({revert:!0}):this.#s.cancelRetry()),this.scheduleGc()),this.#a.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#s?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#s)return this.#s.continueRetry(),this.#s.promise}if(e&&this.setOptions(e),!this.options.queryFn){const l=this.observers.find(u=>u.options.queryFn);l&&this.setOptions(l.options)}const n=new AbortController,a=l=>{Object.defineProperty(l,"signal",{enumerable:!0,get:()=>(this.#c=!0,n.signal)})},s=()=>{const l=S0(this.options,t),p=(()=>{const f={client:this.#r,queryKey:this.queryKey,meta:this.meta};return a(f),f})();return this.#c=!1,this.options.persister?this.options.persister(l,p,this):l(p)},i=(()=>{const l={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:s};return a(l),l})();(this.#e==="infinite"?O_(this.options.pages):this.options.behavior)?.onFetch(i,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==i.fetchOptions?.meta)&&this.#i({type:"fetch",meta:i.fetchOptions?.meta});const c=this.#s=w0({initialPromise:t?.initialPromise,fn:i.fetchFn,onCancel:l=>{l instanceof Lp&&l.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(l,u)=>{this.#i({type:"failed",failureCount:l,error:u})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:i.options.retry,retryDelay:i.options.retryDelay,networkMode:i.options.networkMode,canRun:()=>!0});try{const l=await c.start();if(l===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(l),this.#a.config.onSuccess?.(l,this),this.#a.config.onSettled?.(l,this.state.error,this),l}catch(l){if(l instanceof Lp){if(l.silent)return this.#s.promise;if(l.revert){if(this.state.data===void 0)throw l;return this.state.data}}throw this.#i({type:"error",error:l}),this.#a.config.onError?.(l,this),this.#a.config.onSettled?.(this.state.data,l,this),l}finally{this.#s===c&&(this.#s=void 0),this.scheduleGc()}}#i(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...C0(n.data,this.options),fetchMeta:e.meta??null};case"success":const a={...n,...ev(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?a:void 0,a;case"error":const s=e.error;return{...n,error:s,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:s,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),Dn.batch(()=>{this.observers.slice().forEach(n=>{n.onQueryUpdate()}),this.#a.notify({query:this,type:"updated",action:e})})}};function C0(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:k0(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function ev(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function tv(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,a=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?a??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var N_=class extends Lc{#e;#t=void 0;#n=void 0;#a=void 0;#r;#s;#o;#c;#i;#p;#d;#u;#l;#f=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),nv(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Hp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Hp(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#x(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof on(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#k(),this.#t.setOptions(this.options),t._defaulted&&!Hm(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const a=this.hasListeners();a&&av(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),a&&(this.#t!==n||on(this.options.enabled,this.#t)!==on(t.enabled,this.#t)||on(this.options.staleTime,this.#t)!==on(t.staleTime,this.#t))&&this.#g();const s=this.#v();a&&(this.#t!==n||on(this.options.enabled,this.#t)!==on(t.enabled,this.#t)||s!==this.#l)&&this.#b(s)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return Hm(this.getCurrentResult(),n)||(this.#a=n,this.#s=this.options,this.#r=this.#t.state),n}getCurrentResult(){return this.#a}trackResult(e,t){return new Proxy(e,{get:(n,a)=>(this.trackProp(a),t?.(a),Reflect.get(n,a))})}trackProp(e){this.#f.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);let a=()=>{},s;const r=new Promise(i=>{s=i,a=this.#e.getQueryCache().subscribe(c=>{c.type==="updated"&&c.query.queryHash===n.queryHash&&n.state.data!==void 0&&(a(),i(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{const i=this.createResult(n,t);return s?.(i),i}).finally(()=>{a()}),r])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#a))}#m(e){this.#k();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Yn)),t}#h(e){return!qf()&&on(this.options.enabled,this.#t)!==!1&&v0(e)}#g(){this.#S();const e=on(this.options.staleTime,this.#t);if(this.#a.isStale||!this.#h(e))return;const t=b0(this.#a.dataUpdatedAt,e)+1;this.#d=zr.setTimeout(()=>{this.#a.isStale||this.updateResult()},t)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#b(e){this.#x(),this.#l=e,!(this.#l===0||!this.#h(this.#l))&&(this.#u=zr.setInterval(()=>{(this.options.refetchIntervalInBackground||Bf.isFocused())&&this.#m()},this.#l))}#y(){this.#g(),this.#b(this.#v())}#S(){this.#d!==void 0&&(zr.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#u!==void 0&&(zr.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const n=this.#t,a=this.options,s=this.#a,r=this.#r,i=this.#s,c=e!==n?e.state:this.#n,{state:l}=e;let u={...l},p=!1,f;if(t._optimisticResults){const y=this.hasListeners(),I=!y&&nv(e,t),R=y&&av(e,n,t,a);(I||R)&&(u={...u,...C0(l.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:S,errorUpdatedAt:b,status:w}=u;f=u.data;let C=!1;if(t.placeholderData!==void 0&&f===void 0&&w==="pending"){let y;s?.isPlaceholderData&&t.placeholderData===i?.placeholderData?(y=s.data,C=!0):y=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,y!==void 0&&(w="success",f=Dp(s?.data,y,t),p=!0)}if(t.select&&f!==void 0&&!C)if(s&&f===r?.data&&t.select===this.#c)f=this.#i;else try{this.#c=t.select,f=t.select(f),f=Dp(s?.data,f,t),this.#i=f,this.#o=null}catch(y){this.#o=y}else f===void 0&&(this.#o=null);this.#o&&(S=this.#o,f=this.#i,b=Date.now(),w="error",p=!1);const P=u.fetchStatus==="fetching",_=w==="pending",M=w==="error",E=_&&P,T=f!==void 0;return{status:w,fetchStatus:u.fetchStatus,isPending:_,isSuccess:w==="success",isError:M,isInitialLoading:E,isLoading:E,data:f,dataUpdatedAt:u.dataUpdatedAt,error:S,errorUpdatedAt:b,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:u.dataUpdateCount>c.dataUpdateCount||u.errorUpdateCount>c.errorUpdateCount,isFetching:P,isRefetching:P&&!_,isLoadingError:M&&!T,isPaused:u.fetchStatus==="paused",isPlaceholderData:p,isRefetchError:M&&T,isStale:Ff(e,t),refetch:this.refetch,isEnabled:on(t.enabled,e)!==!1}}updateResult(){const e=this.#a,t=this.createResult(this.#t,this.options);if(this.#r=this.#t.state,this.#s=this.options,this.#r.data!==void 0&&(this.#p=this.#t),Hm(t,e))return;this.#a=t;const a=(()=>{if(!e)return!0;const{notifyOnChangeProps:s}=this.options,r=typeof s=="function"?s():s;if(r==="all"||!r&&!this.#f.size)return!0;const i=new Set(r??this.#f);return this.options.throwOnError&&i.add("error"),Object.keys(this.#a).some(c=>{const l=c;return this.#a[l]!==e[l]&&i.has(l)})})();Dn.batch(()=>{a&&this.listeners.forEach(s=>{s(this.#a)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}#k(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function D_(e,t){return on(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&on(t.retryOnMount,e)===!1)}function nv(e,t){return D_(e,t)||e.state.data!==void 0&&Hp(e,t,t.refetchOnMount)}function Hp(e,t,n){if(on(t.enabled,e)!==!1&&on(t.staleTime,e)!=="static"){const a=typeof n=="function"?n(e):n;return a==="always"||a!==!1&&Ff(e,t)}return!1}function av(e,t,n,a){return(e!==t||on(a.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ff(e,n)}function Ff(e,t){return on(t.enabled,e)!==!1&&e.isStaleByTime(on(t.staleTime,e))}var L_=class extends I0{#e;#t;#n;#a;constructor(t){super(),this.#e=t.client,this.mutationId=t.mutationId,this.#n=t.mutationCache,this.#t=[],this.state=t.state||z_(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){this.#t.includes(t)||(this.#t.push(t),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#t=this.#t.filter(n=>n!==t),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#a?.continue()??(this.state.status==="pending"?this.execute(this.state.variables):Promise.resolve())}async execute(t){const n=()=>{this.#r({type:"continue"})},a={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},s=this.#a=w0({fn:()=>this.options.mutationFn?this.options.mutationFn(t,a):Promise.reject(new Error("No mutationFn found")),onFail:(c,l)=>{this.#r({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#r({type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),r=this.state.status==="pending",i=!s.canStart();try{if(r)n();else{this.#r({type:"pending",variables:t,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(t,this,a);const l=await this.options.onMutate?.(t,a);l!==this.state.context&&this.#r({type:"pending",context:l,variables:t,isPaused:i})}const c=await s.start();return await this.#n.config.onSuccess?.(c,t,this.state.context,this,a),await this.options.onSuccess?.(c,t,this.state.context,a),await this.#n.config.onSettled?.(c,null,this.state.variables,this.state.context,this,a),await this.options.onSettled?.(c,null,t,this.state.context,a),this.#r({type:"success",data:c}),c}catch(c){try{await this.#n.config.onError?.(c,t,this.state.context,this,a)}catch(l){Promise.reject(l)}try{await this.options.onError?.(c,t,this.state.context,a)}catch(l){Promise.reject(l)}try{await this.#n.config.onSettled?.(void 0,c,this.state.variables,this.state.context,this,a)}catch(l){Promise.reject(l)}try{await this.options.onSettled?.(void 0,c,t,this.state.context,a)}catch(l){Promise.reject(l)}throw this.#r({type:"error",error:c}),c}finally{this.#a===s&&(this.#a=void 0),this.#n.runNext(this)}}#r(t){const n=a=>{switch(t.type){case"failed":return{...a,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...a,isPaused:!0};case"continue":return{...a,isPaused:!1};case"pending":return{...a,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...a,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...a,data:void 0,error:t.error,failureCount:a.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),Dn.batch(()=>{this.#t.forEach(a=>{a.onMutationUpdate(t)}),this.#n.notify({mutation:this,type:"updated",action:t})})}};function z_(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var H_=class extends Lc{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){const a=new L_({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(a),a}add(e){this.#e.add(e);const t=Il(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Il(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const a=n.indexOf(e);a!==-1&&n.splice(a,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Il(e);if(typeof t=="string"){const n=this.#t.get(t)?.find(a=>a.state.status==="pending");return!n||n===e}else return!0}runNext(e){const t=Il(e);return typeof t=="string"?this.#t.get(t)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Dn.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Qg(t,n))}findAll(e={}){return this.getAll().filter(t=>Qg(e,t))}notify(e){Dn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Dn.batch(()=>Promise.all(e.map(t=>t.continue().catch(Yn))))}};function Il(e){return e.options.scope?.id}var U_=class extends Lc{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){const a=t.queryKey,s=t.queryHash??Hf(a,t);let r=this.get(s);return r||(r=new $_({client:e,queryKey:a,queryHash:s,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(a)}),this.add(r)),r}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Dn.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Jg(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Jg(e,n)):t}notify(e){Dn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Dn.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Dn.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},q_=class{#e;#t;#n;#a;#r;#s;#o;#c;constructor(e={}){this.#e=e.queryCache||new U_,this.#t=e.mutationCache||new H_,this.#n=e.defaultOptions||{},this.#a=new Map,this.#r=new Map,this.#s=0}mount(){this.#s++,this.#s===1&&(this.#o=Bf.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#c=vd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#s--,this.#s===0&&(this.#o?.(),this.#o=void 0,this.#c?.(),this.#c=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),a=n.state.data;return a===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(on(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(a))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>[t,n.data])}setQueryData(e,t,n){const a=this.defaultQueryOptions({queryKey:e}),s=this.#e.get(a.queryHash)?.state.data,r=k_(t,s);if(r!==void 0)return this.#e.build(this,a).setData(r,{...n,manual:!0})}setQueriesData(e,t,n){return Dn.batch(()=>this.#e.findAll(e).map(({queryKey:a})=>[a,this.setQueryData(a,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;Dn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return Dn.batch(()=>{const a=n.findAll(e),s=new Set(a);return a.forEach(r=>{r.reset()}),this.refetchQueries({type:"active",predicate:r=>s.has(r)},t)})}cancelQueries(e,t={}){const n={revert:!0,...t},a=Dn.batch(()=>this.#e.findAll(e).map(s=>s.cancel(n)));return Promise.all(a).then(Yn).catch(Yn)}invalidateQueries(e,t={}){return Dn.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},a=Dn.batch(()=>this.#e.findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let r=s.fetch(void 0,n);return n.throwOnError||(r=r.catch(Yn)),s.state.fetchStatus==="paused"?Promise.resolve():r}));return Promise.all(a).then(Yn)}async query(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t),a=n.isStaleByTime(on(t.staleTime,n))?await n.fetch(t):n.state.data,s=t.select;return s?s(a):a}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(on(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Yn).catch(Yn)}infiniteQuery(e){return e._type="infinite",this.query(e)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Yn).catch(Yn)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return vd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#a.set(bc(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(a=>{ri(e,a.queryKey)&&Object.assign(n,a.defaultOptions)}),n}setMutationDefaults(e,t){this.#r.set(bc(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(a=>{ri(e,a.mutationKey)&&Object.assign(n,a.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Hf(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Uf&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};const R0=h.createContext(!1),B_=()=>h.useContext(R0);R0.Provider;function F_(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}const V_=h.createContext(F_()),K_=()=>h.useContext(V_),W_=(e,t,n)=>{const a=n?.state.error&&typeof e.throwOnError=="function"?x0(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||a)&&(t.isReset()||(e.retryOnMount=!1))},G_=e=>{h.useEffect(()=>{e.clearReset()},[e])},Z_=({result:e,errorResetBoundary:t,throwOnError:n,query:a,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&a&&(s&&e.data===void 0||x0(n,[e.error,a])),J_=e=>{if(e.suspense){const n=s=>s==="static"?s:Math.max(s??1e3,1e3),a=e.staleTime;e.staleTime=typeof a=="function"?(...s)=>n(a(...s)):n(a),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Q_=(e,t)=>e?.suspense&&t.isPending,Y_=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function X_(e,t,n){const a=B_(),s=K_(),r=g0(),i=r.defaultQueryOptions(e),c=r.getQueryCache().get(i.queryHash),l=e.subscribed!==!1;i._optimisticResults=a?"isRestoring":l?"optimistic":void 0,J_(i),W_(i,s,c),G_(s);const[u]=h.useState(()=>new t(r,i)),p=u.getOptimisticResult(i),f=!a&&l;if(h.useSyncExternalStore(h.useCallback(S=>{const b=f?u.subscribe(Dn.batchCalls(S)):Yn;return u.updateResult(),b},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),h.useEffect(()=>{u.setOptions(i)},[i,u]),Q_(i,p))throw Y_(i,u,s);if(Z_({result:p,errorResetBoundary:s,throwOnError:i.throwOnError,query:c,suspense:i.suspense}))throw p.error;return i.notifyOnChangeProps?p:u.trackResult(p)}function P0(e,t){return X_(e,N_)}function eC(){return new q_({defaultOptions:{queries:{staleTime:6e4,gcTime:15*6e4,retry:1,refetchOnWindowFocus:!1}}})}const tC=new Set(["turn.started","turn.completed","turn.failed","turn.interrupted","approval.requested","approval.resolved","task.input","task.wait"]);function nC(e){const t={};for(const n of e)n.sessionId&&tC.has(n.name)&&(Date.parse(n.timestamp)>Date.parse(t[n.sessionId]??"")||!t[n.sessionId]&&Number.isFinite(Date.parse(n.timestamp)))&&(t[n.sessionId]=n.timestamp);return t}function aC(e,t,n){return[...new Map(e.map(a=>[a.id,a])).values()].sort((a,s)=>Number(n.has(s.id))-Number(n.has(a.id))||bd(s,t)-bd(a,t)||a.id.localeCompare(s.id))}function bd(e,t){const n=typeof e.metadata?.sidebarActivityAt=="string"?e.metadata.sidebarActivityAt:null;return Math.max(Date.parse(t[e.id]??"")||0,Date.parse(n??e.createdAt)||0)}function sC(e,t,n,a=new Date){const s=c=>`${c.getFullYear()}-${c.getMonth()}-${c.getDate()}`,r=new Date(a);r.setDate(a.getDate()-1);const i=[];for(const c of e){const l=new Date(bd(c,t)),u=n.has(c.id),p=u?"running":s(l);let f=i.at(-1);f?.key!==p&&(f={key:p,label:u||p===s(a)?null:p===s(r)?"Yesterday":l.toLocaleDateString(void 0,{month:"short",day:"numeric",...l.getFullYear()!==a.getFullYear()?{year:"numeric"}:{}}),sessions:[]},i.push(f)),f.sessions.push(c)}return i}function rC(e,t,n){const a=new Headers;a.set("Accept","text/event-stream"),a.set("Authorization",`Bearer ${e.token}`);const s=new URL(`${e.serverUrl.replace(/\/$/,"")}/v1/events`);return n!==void 0&&Number.isSafeInteger(n)&&n>0&&s.searchParams.set("afterSequence",String(n)),{url:s.toString(),init:{headers:a,signal:t}}}function oC(e){return Math.min(500*2**Math.max(0,e),1e4)}async function iC(e,t,n,a){T0(e);const s=e.body.getReader(),r=new TextDecoder;let i="";for(;!a?.aborted;){const{done:c,value:l}=await s.read();if(c){i+=r.decode();break}i+=r.decode(l,{stream:!0});let u=i.indexOf(`
3
3
 
4
4
  `);for(;u>=0;){const p=i.slice(0,u);i=i.slice(u+2),rv(p,t,n),u=i.indexOf(`
5
5
 
@@ -107,8 +107,8 @@ Surface risks, constraints, and verification steps.`}],lh=o().trim().min(1).max(
107
107
  `&&p++,c();else if(f==='"'&&!a&&!r)s=!0;else{if(r||f==='"')throw new Error("CSV has an invalid quoted field.");a+=f}}if(s)throw new Error("CSV has an unterminated quoted field.");(a||n.length||r)&&c();const l=t.shift()?.map(p=>p.trim().replace(/^\uFEFF/u,""));if(!l?.includes("instruction"))throw new Error("CSV requires an instruction column.");const u=new Set(["instruction","context","reference","labels","id","familyKey","split"]);if(l.some(p=>!u.has(p))||new Set(l).size!==l.length)throw new Error("CSV has duplicate or unsupported columns. Use instruction, context, reference, labels, id, familyKey and split.");return t.map((p,f)=>{if(p.length!==l.length)throw new Error(`CSV record ${f+2} has a different number of columns from its header.`);return Object.fromEntries(l.map((S,b)=>[S,p[b]]).filter(([,S])=>S!==""))})}function P8(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 ek(e){return e.startsWith("\uFEFF")?e.slice(1):e}const tk=d({role:o().min(1),content:dr().nullable().optional()}).catchall(dr()),T$=d({id:o().min(1),messages:v(tk).min(1).max(Ha.messages),lineage_session_ids:v(o()).optional(),parent_session_id:o().nullable().optional()}).catchall(dr());function A$(e){const t=T$.parse(e),n=t.lineage_session_ids?.[0]??t.parent_session_id??t.id,{messages:a,segments:s,...r}=t;return nk("hermes",t.id,n,t.messages,{sourceHash:Qe(e),metadata:{session:r},warnings:["Imported session context and tools need review before this can become an executable task."]})}const E$=d({traceSchema:x("openclaw-trajectory"),schemaVersion:x(1),traceId:o().min(1),sessionId:o().min(1),leafId:o().nullable(),eventCount:m().int().nonnegative(),warnings:v(Tt).optional()}).catchall(dr()),j$=d({traceSchema:x("openclaw-trajectory"),schemaVersion:x(1),traceId:o(),sessionId:o(),seq:m().int().nonnegative(),type:o(),ts:o()}).catchall(dr()),M$=d({header:Tt.nullable(),leafId:o().nullable(),entries:v(d({id:o().min(1),type:o().min(1),parentId:o().nullable().optional(),message:tk.optional()}).catchall(dr())).max(Ha.messages)}).strict();function O$(e){const t=c=>{const l=e.find(u=>u.path===c);if(!l)throw new Error(`OpenClaw bundle is missing ${c}.`);return ek(l.text)},n=E$.parse(JSON.parse(t("manifest.json"))),a=M$.parse(JSON.parse(t("session-branch.json")));if(a.leafId!==n.leafId)throw new Error("OpenClaw manifest and session branch identify different leaves.");const s=t("events.jsonl").split(/\r?\n/u).filter(c=>c.trim()).map(c=>j$.parse(JSON.parse(c)));if(s.length!==n.eventCount||s.some(c=>c.traceId!==n.traceId||c.sessionId!==n.sessionId))throw new Error("OpenClaw events do not match the manifest identity or count.");if(a.header&&a.header.id!==n.sessionId)throw new Error("OpenClaw session header does not match the manifest.");const r=new Set;for(const[c,l]of a.entries.entries()){if(r.has(l.id))throw new Error("OpenClaw branch contains duplicate entry IDs.");if(c&&l.parentId!==a.entries[c-1].id)throw new Error("OpenClaw branch is incomplete or out of order.");r.add(l.id)}if(a.entries.length&&a.entries.at(-1).id!==a.leafId)throw new Error("OpenClaw branch does not reach its declared leaf.");const i=a.entries.filter(c=>c.type==="message"&&c.message).map(c=>({...c.message,entryId:c.id,timestamp:typeof c.timestamp=="string"?c.timestamp:typeof c.message.timestamp=="number"?new Date(c.message.timestamp).toISOString():null}));return nk("openclaw",n.sessionId,n.sessionId,i,{sourceHash:Qe(e),metadata:{manifest:n,sourceFiles:e.map(c=>c.path)},warnings:["Imported trajectory context and tools need review before this can become an executable task.",...(n.warnings??[]).map(c=>typeof c.message=="string"?c.message.slice(0,2e3):"The source exporter reported incomplete context.")]})}function nk(e,t,n,a,s){const r=a.flatMap((c,l)=>c.role==="user"?[l]:[]);if(!r.length)throw new Error("This history contains no user request. Supply a session with its request context.");let i=0;return r.map((c,l)=>{const u=r[l+1]??a.length,p=a.slice(c+1,u),f=p.filter(C=>C.role==="assistant").at(-1),S=a[c],b=S.entryId??S.message_id??S.id??Qe({start:c,request:S}),w={id:_d(e,[t,b]),familyKey:_d(e,n),split:"train",kind:"attempt",input:{request:S.content??null,messages:a.slice(0,c+1)},observedOutput:f?{response:f.content??null,messages:p}:null,expected:null,sourceId:`${e}:${t}:${String(b)}`,sourceHash:s.sourceHash,occurredAt:Yx(f?.timestamp??S.timestamp),metadata:s.metadata,warnings:[...s.warnings,...f?[]:["No assistant response was recorded for this request."]],needsContext:!0};if(Aa(w),i+=new TextEncoder().encode(JSON.stringify(w)).length,i>Ha.bytes)throw new Error("Expanded history exceeds the 5 MiB preview limit. Export a smaller session selection.");return Mh.parse(w)})}const $$=d({instruction:o().trim().min(1).max(1e5),context:dt([o(),Tt]).optional(),reference:dt([o(),Tt]).optional(),labels:dt([o(),v(o()),Tt]).optional(),id:o().min(1).max(200).optional(),familyKey:o().min(1).max(200).optional(),split:Ga.optional()}).strict(),N$=d({input:Tt,observedOutput:Tt.nullable().optional(),expectedOutput:Tt.nullable().optional(),id:o().min(1).max(200).optional(),familyKey:o().min(1).max(200).optional(),split:Ga.optional(),occurredAt:o().datetime().optional(),labels:Tt.optional()}).strict();function D$(e){const t=Jx.parse(e.format),n=v(I$).min(1).max(Ha.files).parse(e.files);if(n.reduce((u,p)=>u+new TextEncoder().encode(p.text).length,0)>Ha.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(p=>!p||p==="."||p===".."))||new Set(n.map(u=>u.path)).size!==n.length)throw new Error("Import contains an unsafe or duplicate file path.");const a=[],s=[],r=new Map,i=new Map;let c=0;function l(u,p,f){try{const S=f();if(a.length+S.length>Ha.records)throw new Error("Import exceeds the 1,000-record limit.");const b=new Map(r),w=new Map(i);let C=0;for(const P of S){Aa(P);const _=Qe(P),M=b.get(P.id);if(M&&M!==_)throw new Error("The same record identity has different content in this upload.");M||(C+=new TextEncoder().encode(JSON.stringify(P)).length),b.set(P.id,_);for(const E of[`family:${P.familyKey}`,`input:${Qe(P.input)}`]){if(w.has(E)&&w.get(E)!==P.split)throw new Error("The same task family or request occurs in different splits.");w.set(E,P.split)}}if(c+C>Ha.bytes*2)throw new Error("Expanded import exceeds the 10 MiB preview limit. Select fewer source files.");for(const P of S)r.has(P.id)||a.push(P),r.set(P.id,Qe(P));for(const[P,_]of w)i.set(P,_);c+=C}catch(S){s.push({file:u,row:p,message:S instanceof eA?`Unsupported record fields or values (${S.issues.slice(0,3).map(b=>b.path.join(".")||"record").join(", ")}).`:S instanceof SyntaxError?"Invalid JSON.":S instanceof Error?S.message:"Invalid import record."})}}if(t==="openclaw")l("manifest.json",null,()=>O$(n));else for(const u of n){const p=ek(u.text);if(t==="jsonl"||t==="hermes"){for(const[f,S]of p.split(/\r?\n/u).entries())if(S.trim()){if(s.length>=Ha.records)break;l(u.path,f+1,()=>t==="hermes"?A$(JSON.parse(S)):[Wv(JSON.parse(S))])}}else{let f;try{const S=t==="csv"?P$(p):JSON.parse(p);f=Array.isArray(S)?S:[S]}catch(S){l(u.path,null,()=>{throw S});continue}if(f.length>Ha.records){l(u.path,null,()=>{throw new Error("Import exceeds the 1,000-record limit.")});continue}f.forEach((S,b)=>l(u.path,b+(t==="csv"?2:1),()=>[Wv(S)]))}}return Qx.parse({schemaVersion:"openpond.taskIntakePreview.v1",format:t,contentHash:Qe({format:t,files:n}),records:a,issues:s.slice(0,1e3)})}function Wv(e){const t=dt([$$,N$]).parse(e),n="instruction"in t,a=n?{instruction:t.instruction,...t.context===void 0?{}:{context:t.context}}:t.input,s=n?t.reference===void 0?null:typeof t.reference=="string"?{text:t.reference}:t.reference:t.expectedOutput??null,r=n?null:t.observedOutput??null,i=t.familyKey??_d("family",a),c=t.id??_d("task",{input:a,expected:s,observedOutput:r});return Mh.parse({id:c,familyKey:i,split:t.split??"train",kind:r?"attempt":"task",input:a,expected:s,observedOutput:r,sourceId:c,sourceHash:Qe(e),occurredAt:n?null:Yx(t.occurredAt),metadata:t.labels===void 0?{}:{importedLabels:t.labels,labelOrigin:"unverified_import"},warnings:[],needsContext:!1})}var Wr=Ye.shape.id,Cc=o().regex(/^[a-f0-9]{64}$/),L$=d({scopeId:Wr,modelId:Wr}).strict(),z$=d({schemaVersion:x("openpond.modelTasksetAuthoring.v1"),owner:L$,root:Ye,parent:Ye}).strict(),T8=d({schemaVersion:x("openpond.modelTasksetDraftRequest.v1"),operationId:Wr,modelId:Wr,expectedModelRevision:m().int().positive(),sourcePackageHash:Cc}).strict(),H$=d({schemaVersion:x("openpond.modelTasksetDraftPreparation.v1"),draftId:Wr,requestHash:Cc,sourcePackageHash:Cc,sourceTasksetRef:Ye,tasksetId:Wr,tasksetRevision:m().int().positive(),lineage:z$,authoringGraph:x("bound").optional()}).strict(),ou=o().min(1).max(1024).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.includes("\0")&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."||t.startsWith(".env")),"Use a relative Taskset file path without environment files."),ak=d({path:ou,sizeBytes:m().int().nonnegative(),writable:j()}).strict(),sk=d({encoding:k(["utf8","base64"]),data:o().max(8e6)}).strict(),U$=ak.extend({contentHash:Cc,content:sk}).strict();d({draftId:Wr,expectedDraftRevision:m().int().positive(),path:ou,expectedFileHash:Cc.nullable(),content:sk.nullable()}).strict();var q$=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),B$=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),F$=class rk{state=new Uint32Array(q$);pending=new Uint8Array(64);pendingLength=0;byteLength=0;words=new Uint32Array(64);update(t){const n=typeof t=="string"?new TextEncoder().encode(t):t;if(!Number.isSafeInteger(this.byteLength+n.length))throw new RangeError("SHA-256 input is too large");this.byteLength+=n.length;let a=0;if(this.pendingLength){const s=Math.min(64-this.pendingLength,n.length);this.pending.set(n.subarray(0,s),this.pendingLength),this.pendingLength+=s,a+=s,this.pendingLength===64&&(this.compress(this.pending),this.pendingLength=0)}for(;a+64<=n.length;)this.compress(n.subarray(a,a+64)),a+=64;return a<n.length&&(this.pending.set(n.subarray(a)),this.pendingLength=n.length-a),this}clone(){const t=new rk;return t.state.set(this.state),t.pending.set(this.pending),t.pendingLength=this.pendingLength,t.byteLength=this.byteLength,t}digestHex(){const t=this.clone(),n=new Uint8Array(t.pendingLength<56?64:128);n.set(t.pending.subarray(0,t.pendingLength)),n[t.pendingLength]=128;const a=t.byteLength*8,s=new DataView(n.buffer);return s.setUint32(n.length-8,Math.floor(a/4294967296),!1),s.setUint32(n.length-4,a>>>0,!1),t.compress(n.subarray(0,64)),n.length===128&&t.compress(n.subarray(64)),Array.from(t.state,r=>r.toString(16).padStart(8,"0")).join("")}compress(t){const n=new DataView(t.buffer,t.byteOffset,64),a=this.state,s=this.words;for(let b=0;b<16;b+=1)s[b]=n.getUint32(b*4,!1);for(let b=16;b<64;b+=1){const w=s[b-15],C=s[b-2],P=cs(w,7)^cs(w,18)^w>>>3,_=cs(C,17)^cs(C,19)^C>>>10;s[b]=s[b-16]+P+s[b-7]+_>>>0}let r=a[0],i=a[1],c=a[2],l=a[3],u=a[4],p=a[5],f=a[6],S=a[7];for(let b=0;b<64;b+=1){const w=u&p^~u&f,C=r&i^r&c^i&c,P=cs(r,2)^cs(r,13)^cs(r,22),_=cs(u,6)^cs(u,11)^cs(u,25),M=S+_+w+B$[b]+s[b]>>>0,E=P+C>>>0;S=f,f=p,p=u,u=l+M>>>0,l=c,c=i,i=r,r=M+E>>>0}a[0]=a[0]+r>>>0,a[1]=a[1]+i>>>0,a[2]=a[2]+c>>>0,a[3]=a[3]+l>>>0,a[4]=a[4]+u>>>0,a[5]=a[5]+p>>>0,a[6]=a[6]+f>>>0,a[7]=a[7]+S>>>0}};function V$(e){return new F$().update(e).digestHex()}function cs(e,t){return e>>>t|e<<32-t}var K$=2e3,ok=25e7,Cn=o().trim().min(1).max(240),hn=o().regex(/^[a-f0-9]{64}$/),Qp=o().datetime({offset:!0}),A8=ve(o(),ke()).default({}),bt=d({id:Cn,contentHash:hn}).strict(),W$=bt.extend({revision:m().int().positive()}).strict(),Yp=d({id:Cn,path:o().trim().min(1).max(K$).refine(J$),contentHash:hn,sizeBytes:m().int().nonnegative().max(ok),mediaType:o().trim().min(1).max(200),visibility:k(["policy","verifier","host_private"])}).strict(),E8=d({id:Cn,contentHash:hn,mediaType:o().trim().min(1).max(200).nullable().default(null),sizeBytes:m().int().nonnegative().max(ok).nullable().default(null)}).strict(),G$=k(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function Z$(e){return`${JSON.stringify(Xp(e),null,2)}
108
108
  `}function ik(e){return V$(e)}function Ht(e){return ik(Z$(e))}function j8(e,t){const{contentHash:n,...a}=e,s=Ht(a);if(n!==s)throw new Error(`${t} contentHash is ${n}; expected ${s}.`)}function J$(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function Xp(e){return Array.isArray(e)?e.map(Xp):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Xp(n)]))}d({provider:Cn,model:Cn,revision:o().trim().min(1).max(500).nullable().default(null),artifactHash:hn.nullable().default(null),tokenizerRevision:o().trim().min(1).max(500).nullable().default(null),chatTemplateHash:hn.nullable().default(null)}).strict();var Q$=["openpond","codex","claude-code","grok-build","opencode","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],Y$=fS(["acp:",o().regex(/^[a-z0-9][a-z0-9-]{0,100}$/)]),X$=dt([k(Q$),Y$]),Oh=d({providerId:X$,modelId:o().trim().min(1).max(300)}),e2=Fx.extend({mode:k(["nightly","approved_count"]),minimumTasks:m().int().min(1).max(1e4),maximumSpendUsd:m().positive().max(1e5),maximumDailySpendUsd:m().positive().max(1e6)}).strict().superRefine((e,t)=>{e.maximumDailySpendUsd<e.maximumSpendUsd&&t.addIssue({code:"custom",path:["maximumDailySpendUsd"],message:"The daily budget must cover one update."})}),M8=67108864,ef=524288,ic=class extends Error{code;constructor(e,t){super(t),this.name="OpenPondProtocolError",this.code=e}};function $h(e){return JSON.stringify(tf(e))}function t2(e){return new TextEncoder().encode($h(e)).byteLength}async function n2(e){const t=new TextEncoder().encode($h(e)),n=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n),a=>a.toString(16).padStart(2,"0")).join("")}function a2(e,t,n){const a=t2(e);if(a>t)throw new ic("payload_too_large",`${n} is ${a} bytes; the maximum is ${t} bytes.`)}function tf(e){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new ic("non_json_value","Canonical JSON cannot contain a non-finite number.");return Object.is(e,-0)?0:e}if(Array.isArray(e))return e.map(t=>tf(t));if(typeof e=="object"){const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)throw new ic("non_json_value","Canonical JSON accepts only plain objects.");const n={};for(const a of Object.keys(e).sort()){const s=e[a];if(s===void 0||typeof s=="function"||typeof s=="symbol")throw new ic("non_json_value",`Canonical JSON cannot contain ${typeof s} at ${a}.`);n[a]=tf(s)}return n}throw new ic("non_json_value",`Canonical JSON cannot contain ${typeof e}.`)}var jt=o().trim().min(1).max(500),fs=o().regex(/^[a-f0-9]{64}$/),_a=o().datetime({offset:!0}),Gr=d({id:jt,contentHash:fs}).strict(),Fa=Gr.extend({revision:m().int().positive()}).strict(),Gc=d({schemaVersion:x("openpond.baseModelPreference.v1"),modelId:jt,revision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:o().trim().min(8).max(256).nullable(),modelAssetId:jt.nullable(),source:k(["managed","local","builtin"])}).strict(),ck=k(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),s2=d({schemaVersion:o().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:ck,parameterization:k(["lora","full"])}).catchall(ke()),r2=d({profileProjectId:jt,sourceRevision:o().regex(/^[a-f0-9]{40,64}$/),harnessRelease:Gr}).strict(),o2=d({profileProjectId:jt,sourceRevision:o().regex(/^[a-f0-9]{40,64}$/),catalogHash:fs,definitionId:jt,harnessRelease:Gr,tasksetRelease:Gr}).strict(),lk=d({tasksetRef:Fa.nullable().default(null),evaluationTasksetRef:Fa.nullable().optional(),profileSource:r2.nullable().optional(),profileEvaluation:o2.nullable().optional(),rewardBindingRef:Fa.nullable().optional(),tasksetRelease:Gr.nullable().default(null),harnessRelease:Gr.nullable().default(null),baseModel:Gc.nullable().default(null),method:ck.nullable().default(null),destinationId:jt.nullable().default(null),managedRolloutPlacement:k(["local","remote"]).default("remote"),managedGpuPlacementObjective:k(["fast","balanced","economical"]).default("balanced"),managedGpuRequirement:k(["any","h100_hbm3"]).default("any"),runPreset:k(["small","standard","custom","small_experiment"]).nullable().default(null),recipe:s2.nullable().default(null),preferredMaximumSpendUsd:m().nonnegative().nullable().default(null),preferredRetentionDays:m().int().nonnegative().nullable().default(null)}).strict(),dk=lk.omit({managedGpuRequirement:!0}),i2=d({schemaVersion:x("openpond.hostedModelProjectLink.v1"),apiOrigin:o().url().refine(e=>new URL(e).origin===e,"Use a canonical API origin.").nullable().default(null),teamId:jt,projectId:jt,portableProjectId:jt,revision:m().int().positive(),etag:fs,syncedSourceRevision:m().int().positive(),syncedAt:_a,tasksets:v(d({localTasksetId:jt,localTasksetHash:fs.nullable().default(null),releaseId:jt,releaseRevision:m().int().positive(),releaseHash:fs,packageHash:fs.nullable().default(null),hostedTasksetId:jt,syncedAt:_a}).strict()).max(1e4).default([])}).strict(),c2=d({localTasksetId:jt,releaseId:jt,releaseRevision:m().int().positive(),releaseHash:fs,state:k(["syncing","synced","sync_failed"]),hostedTasksetId:jt.nullable().default(null),lastAttemptAt:_a,syncedAt:_a.nullable().default(null),lastError:o().trim().min(1).max(5e3).nullable().default(null)}).strict(),uk=d({schemaVersion:x("openpond.modelProject.v2"),id:jt,profileId:jt,revision:m().int().positive().default(1),name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:Gc.nullable(),defaultDestinationId:jt.nullable(),trainingSetup:lk,hosted:i2.nullable().default(null),tasksetSyncs:v(c2).max(1e4).default([]),createdAt:_a,updatedAt:_a}).strict(),mk=uk.pick({id:!0,profileId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,trainingSetup:!0}),l2=d({schemaVersion:x("openpond.modelProjectSave.v1"),operationId:jt,expectedRevision:m().int().nonnegative(),project:mk,learning:e2.optional()}).strict().superRefine((e,t)=>{e.learning&&e.expectedRevision!==0&&t.addIssue({code:"custom",path:["learning"],message:"Use learning settings to edit an existing Model's policy."})}),pk=d({schemaVersion:x("openpond.modelProjectConfigurationCheck.v1"),configurationHash:fs,projectId:jt,expectedRevision:m().int().nonnegative(),checkedAt:_a,canSave:j(),deferred:v(k(["base_model","taskset"])).max(2),findings:v(d({code:jt,severity:k(["error","warning"]),message:o().min(1).max(5e3),field:o().min(1).max(500).nullable()}).strict()).max(100)}).strict();d({id:jt,name:o().min(1).max(500),available:j(),preference:Gc}).strict();function d2(e){try{Aa(e,ef)}catch{throw new f2(400,{schemaVersion:"openpond.modelProjectApiError.v2",code:"model_configuration_json_invalid",message:"Model configuration must be bounded JSON data.",retryable:!1,requestId:null,details:{}})}return l2.parse(e)}async function u2(e,t,n){Aa(e,ef);const a=mk.parse(e);a2(a,ef,"Model configuration");const s=await n2({project:a,expectedRevision:t});return d2({schemaVersion:"openpond.modelProjectSave.v1",operationId:`model-save:${s}`,expectedRevision:t,project:a})}d({schemaVersion:x("openpond.hostedModelProjectSync.v2"),portableProjectId:jt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:Gc.nullable(),defaultDestinationId:jt.nullable(),trainingSetup:dk,sourceRevision:m().int().positive(),sourceUpdatedAt:_a,expectedEtag:fs.nullable().default(null)}).strict();var m2=d({id:jt,teamId:jt,portableProjectId:jt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:Gc.nullable(),defaultDestinationId:jt.nullable(),trainingSetup:dk,sourceRevision:m().int().positive(),sourceUpdatedAt:_a,revision:m().int().positive(),etag:fs,createdAt:_a,updatedAt:_a}).strict(),p2=d({kind:k(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:Gr,role:o().trim().min(1).max(200).nullable().default(null),updatedAt:_a}).strict();d({project:m2,resources:v(p2).max(1e4),jobCount:m().int().nonnegative(),latestJobIds:v(jt).max(100)}).strict();d({schemaVersion:x("openpond.modelProjectApiError.v2"),code:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3),retryable:j().default(!1),requestId:o().trim().min(1).max(500).nullable().default(null),details:ve(o(),ke()).default({})}).strict();var f2=class extends Error{status;code;retryable;requestId;details;constructor(e,t){super(t.message),this.name="OpenPondModelProjectApiError",this.status=e,this.code=t.code,this.retryable=t.retryable,this.requestId=t.requestId,this.details=t.details}};const h2="openpond.connectedEvidence.v1",g2="connected-evidence-1",jl={files:100,sourceBytes:32*1024*1024,events:1e5,sessions:1e3,boundaries:5e3},fa=o().min(1).max(500),mc=o().regex(/^[a-f0-9]{64}$/),v2=o().datetime().nullable(),Ml=m().int().nonnegative().nullable(),fk=k(["native_chat","native_work","codex","claude_code","hermes","openclaw","opencode","grok_build","pi","oh_my_pi"]),b2=d({invocationId:fa,inputTokens:Ml,outputTokens:Ml,cachedInputTokens:Ml,totalTokens:Ml,provenance:k(["billed_invocation","reported_invocation","reported_cumulative"])}).strict(),Gv=d({id:fa,sequence:m().int().nonnegative(),occurredAt:v2,kind:k(["message","tool_call","tool_result","compaction","artifact","terminal","usage","unknown"]),role:k(["user","assistant","system","tool"]).nullable(),callId:fa.nullable(),parentId:fa.nullable(),content:dr(),usage:b2.nullable()}).strict(),y2=d({id:fa,familyKey:fa,projection:k(["turn","conversation"]),requestEventId:fa,start:m().int().nonnegative(),end:m().int().positive(),inputHash:mc,outputHash:mc.nullable(),revisionHash:mc,terminal:k(["completed","failed","cancelled","unknown"]),coverage:d({answer:j(),context:k(["retained","compacted","unknown"]),process:k(["retained","partial","absent"]),artifacts:k(["retained","references_only","absent"]),replay:x("unavailable"),gaps:v(o().max(500)).max(100)}).strict()}).strict();d({schemaVersion:x(h2),normalizerVersion:x(g2),origin:fk,sessionId:fa,branchId:fa.nullable(),parentSessionId:fa.nullable(),exporterVersion:o().max(200).nullable(),acquisition:d({machineId:fa,sourceInstanceId:fa}).strict().optional(),sourceFiles:v(d({path:fa,contentHash:mc,sizeBytes:m().int().nonnegative()}).strict()).max(jl.files),events:v(Gv).max(jl.events),unmappedEvents:v(Gv).max(jl.events),boundaries:v(y2).max(jl.boundaries),warnings:v(o().max(500)).max(100),contentHash:mc}).strict();const S2=d({schemaVersion:x("openpond.humanResultView.v1"),executionId:o().min(1),executionHash:o().regex(/^[a-f0-9]{64}$/),selection:v(gn).max(1e4),coverage:d({pending:m().int().nonnegative(),submitted:m().int().nonnegative(),accepted:m().int().nonnegative(),rejected:m().int().nonnegative(),cancelled:m().int().nonnegative()}).strict(),results:v(d({review:gn,decision:gn.nullable(),attemptIds:v(o().min(1)).min(1).max(2),mode:k(["individual","pairwise"]),origin:k(["hosted_retained","recorded_evidence","owner_attested_local","native_local"]),status:k(["pending","submitted","accepted","rejected","cancelled"]),grader:gn,answers:v(li).max(100)}).strict()).max(1e4)}).strict(),Zv=S2.extend({contentHash:o().regex(/^[a-f0-9]{64}$/)}).strict(),Cd=o().regex(/^[a-f0-9]{64}$/),Rc=o().min(1).max(240),Ol={feedbackKey:Rc,criterionId:Rc},x2=rt("kind",[d({...Ol,kind:x("normalized_score"),minimum:m().finite(),maximum:m().finite(),passThreshold:m().min(0).max(1).optional()}).strict(),d({...Ol,kind:x("boolean")}).strict(),d({...Ol,kind:x("category")}).strict(),d({...Ol,kind:x("preference_score"),tieScore:m().min(0).max(1).nullable()}).strict()]),Jv=d({execution:re,resultHash:Cd,reviews:v(d({review:gn,decision:gn}).strict()).min(1).max(1e4)}).strict(),hk=d({rules:v(x2).min(1).max(100),baseline:Jv,candidate:Jv}).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."})}),Qv=d({manifest:or,result:ir}).strict(),Yv=d({id:Rc,manifestHash:Cd,resultHash:Cd}).strict(),k2=d({schemaVersion:x("openpond.humanComparisonProjection.v1"),teamId:Rc,projectId:Rc,selections:hk,original:d({baseline:Yv,candidate:Yv}).strict(),humanResults:d({baseline:Zv,candidate:Zv}).strict(),baseline:Qv,candidate:Qv}).strict(),nf=k2.extend({contentHash:Cd}).strict();function Ym(e){throw new Va(e,409)}function w2(e,t){const n=nf.parse(e),{contentHash:a,...s}=n;a!==Qe(s)&&Ym("human_comparison_projection_invalid");for(const r of["baseline","candidate"]){const i=ei(n[r]),c=i.manifest.lineage,l=c?.humanProjection,u=n.original[r],p=n.selections[r];(!c||!l||l.originalManifest.id!==u.id||l.originalManifest.contentHash!==u.manifestHash||l.selectionHash!==Qe(p)||l.rulesHash!==Qe(n.selections.rules)||Qe(c.execution)!==Qe(p.execution)||i.manifest.teamId!==n.teamId||n.humanResults[r].contentHash!==p.resultHash)&&Ym("human_comparison_projection_lineage_changed");const{contentHash:f,...S}=n.humanResults[r];(Qe(S)!==f||S.executionId!==p.execution.id||S.executionHash!==p.execution.contentHash||Qe(S.selection)!==Qe(p.reviews.map(b=>b.review)))&&Ym("human_comparison_human_result_changed")}return n}const gk=d({adapterId:A,placement:k(["local","remote","colocated","provider_native"]),runtimeVersion:o().trim().min(1).max(200),capabilityReceipt:W}).strict(),vk=d({maxTurns:m().int().positive().max(1e5),timeoutMs:m().int().positive().max(864e5),maxOutputBytes:m().int().positive().max(25e7),maximumSpendUsd:m().nonnegative().nullable()}).strict(),I2=d({schemaVersion:x("openpond.runManifest.v1"),id:A,harnessRelease:re,tasksetRelease:re,model:eh,runtimeTarget:gk,limits:vk,approval:d({id:A,contentHash:W}).strict().nullable(),createdAt:Ce,metadata:ha}).strict();I2.extend({contentHash:W}).strict();const _2=d({schemaVersion:x("openpond.attemptReceipt.v1"),id:A,runManifest:re,taskId:A,seed:o().trim().min(1).max(500),terminal:j(),failureClass:Gd.nullable(),outputHash:W.nullable(),traceHash:W,artifactRefs:v(bs).max(1e5),graderEvidenceRefs:v(bs).max(1e4),startedAt:Ce,completedAt:Ce,latencyMs:m().int().nonnegative(),costUsd:m().nonnegative().nullable(),legacyAttemptRef:A.nullable().default(null),metadata:ha}).strict(),C2=_2.extend({contentHash:W}).strict(),R2=d({schemaVersion:x("openpond.evaluationResult.v1"),id:A,runManifest:re,harnessRelease:re,tasksetRelease:re,model:eh,receiptRefs:v(re).min(1).max(1e6),attemptCount:m().int().positive(),rewardEligibleCount:m().int().nonnegative(),terminalCount:m().int().nonnegative(),meanScore:m().min(0).max(1).nullable(),failureCounts:ve(Gd,m().int().nonnegative()),authoredMetric:gx.optional(),metadata:ha}).strict(),P2=R2.extend({contentHash:W}).strict(),T2=d({schemaVersion:x("openpond.harnessCompatibility.v1"),id:A,baseHarnessRelease:re,candidateHarnessRelease:re,tasksetRelease:re,environmentHash:W,toolContractHash:W,policyHash:W,graderInterfaceHash:W,metadata:ha}).strict();T2.extend({contentHash:W}).strict();const bk=k(["scored","unscorable"]),Nh=k(["policy","environment","collector","verifier","provider","host","user","scheduler"]),A2=k(["completed","policy_failure","incomplete_output","task_deadline","environment_failure","collector_failure","verifier_failure","provider_failure","host_failure","infrastructure_timeout","cancelled"]),E2=d({schemaVersion:x("openpond.environmentRelease.v1"),id:A,revision:m().int().positive(),contract:_x,actionSchemaRef:aa.nullable(),observationSchemaRef:aa.nullable(),stateSchemaRef:aa.nullable(),artifactCollection:d({maxArtifacts:m().int().positive().max(1e5),maxTotalBytes:m().int().positive().max(1e10)}).strict(),adapterConformanceHashes:ve(A,W),metadata:ha}).strict(),Dh=E2.extend({contentHash:W}).strict(),j2=k(["collected","missing","skipped","failed"]),Xv=k(["not_requested","passed","failed"]),M2=d({requiredOutputPath:o().trim().min(1).max(2e3).nullable(),collectedPath:o().trim().min(1).max(4e3).nullable(),declaredMediaType:o().trim().min(1).max(200).nullable(),detectedMediaType:o().trim().min(1).max(200).nullable(),artifact:bs.nullable(),status:j2,parseStatus:Xv,schemaStatus:Xv,errorCode:A.nullable(),failureOwner:Nh.nullable(),evidenceRefs:v(bs).max(1e4),metadata:ha}).strict(),O2=d({schemaVersion:x("openpond.artifactManifest.v1"),id:A,attemptRef:re,entries:v(M2).max(1e5),createdAt:Ce,metadata:ha}).strict();O2.extend({contentHash:W}).strict();const $2=d({schemaVersion:x("openpond.verifierSetRelease.v1"),id:A,revision:m().int().positive(),graders:v(Ex).max(1e3),isolation:d({processBoundary:k(["same_process","isolated_process","container"]),networkPolicy:x("none"),defaultTimeoutMs:m().int().positive().max(3e5)}).strict(),calibrationReceiptRefs:v(re).max(1e4),metadata:ha}).strict(),Lh=$2.extend({contentHash:W}).strict(),N2=d({verifierId:A,verifierVersion:o().trim().min(1).max(100),status:bk,rawScore:m().finite().nullable(),normalizedScore:m().min(0).max(1).nullable(),weight:m().nonnegative().max(1e3),passed:j(),hardGate:j(),rewardEligible:j(),rewardContribution:m().min(0).max(1).nullable(),failureOwner:Nh.nullable(),feedback:v(o().max(2e4)).max(1e3),visibleEvidenceRefs:v(bs).max(1e4),privilegedEvidenceRefs:v(bs).max(1e4),metadata:ha}).strict().superRefine((e,t)=>{e.status==="scored"&&e.normalizedScore===null&&t.addIssue({code:"custom",message:"A scored component requires a normalized score.",path:["normalizedScore"]}),e.status==="unscorable"&&(e.normalizedScore!==null||e.rewardEligible)&&t.addIssue({code:"custom",message:"An unscorable component cannot contribute reward.",path:["status"]})}),yk=d({schemaVersion:x("openpond.rewardReceipt.v1"),id:A,attemptRef:re,verifierSetRef:re,artifactManifestRef:re,status:bk,reward:m().min(0).max(1).nullable(),learningEligible:j(),passed:j(),outcomeClass:A2,failureOwner:Nh.nullable(),components:v(N2).min(1).max(1e4),visibleEvidenceRefs:v(bs).max(1e5),privilegedEvidenceRefs:v(bs).max(1e5),supersedes:re.nullable(),createdAt:Ce,metadata:ha}).strict();function Sk(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"]})}yk.superRefine(Sk);yk.extend({contentHash:W}).strict().superRefine(Sk);const D2=rt("kind",[d({kind:x("model"),model:eh,configurationHash:W}).strict(),d({kind:x("fixture")}).strict()]),L2=rt("kind",[d({kind:x("taskset"),environmentRelease:re,verifierSetRelease:re,policyHash:W}).strict(),d({kind:x("harness"),harnessRelease:re}).strict()]),xk=d({receiptId:A,taskId:A,seed:o().trim().min(1).max(500),fixtureId:A.nullable()}).strict(),z2=d({schemaVersion:x("openpond.tasksetRunManifest.v1"),id:A,tasksetRelease:re,packageHash:W,execution:L2,profileEvaluation:Id.optional(),policy:D2,gradingRole:x("evaluation"),metricPolicy:Vc,population:v(xk).min(1).max(1e5),runtimeTarget:gk,limits:vk,createdAt:Ce,metadata:ha}).strict().superRefine((e,t)=>{new Set(e.population.map(n=>n.receiptId)).size!==e.population.length&&t.addIssue({code:"custom",path:["population"],message:"Run receipt identities must be unique."}),e.population.some(n=>n.fixtureId!==null!=(e.policy.kind==="fixture"))&&t.addIssue({code:"custom",path:["population"],message:"Only fixture runs require a fixture identity for every member."}),e.profileEvaluation&&(e.execution.kind!=="harness"||e.execution.harnessRelease.id!==e.profileEvaluation.harnessRelease.id||e.execution.harnessRelease.contentHash!==e.profileEvaluation.harnessRelease.contentHash)&&t.addIssue({code:"custom",path:["profileEvaluation"],message:"Profile evaluation must execute its exact bound Harness release."})}),kk=z2.safeExtend({contentHash:W}),H2=o().regex(/^(0|-?[1-9][0-9]*)$/).max(20).refine(e=>{if(e.length>20||!/^(0|-?[1-9][0-9]*)$/.test(e))return!1;const t=BigInt(e);return t>=-(1n<<63n)&&t<1n<<63n},"SQL integers must fit signed 64-bit storage."),wk=dt([Si(),o().max(262144),m().finite(),d({integer:H2}).strict(),d({blobBase64:o().max(349528).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}).strict()]),eb=o().min(1).max(128).refine(e=>!e.includes("\0")),U2=d({tables:v(d({name:eb,columns:v(d({name:eb,type:k(["INTEGER","REAL","TEXT","BLOB"])}).strict()).min(1).max(128),rows:v(v(wk).max(128)).max(4096)}).strict()).max(64)}).strict().superRefine((e,t)=>{const n=new Set;for(const[a,s]of e.tables.entries()){const r=s.name.toLowerCase();(n.has(r)||r.startsWith("sqlite_"))&&t.addIssue({code:"custom",path:["tables",a,"name"],message:"Table names must be unique and outside SQLite's reserved namespace."}),n.add(r),new Set(s.columns.map(i=>i.name.toLowerCase())).size!==s.columns.length&&t.addIssue({code:"custom",path:["tables",a,"columns"],message:"Column names must be unique."}),s.rows.some(i=>i.length!==s.columns.length)&&t.addIssue({code:"custom",path:["tables",a,"rows"],message:"Each row must match the declared columns."})}}),tb=d({schemaVersion:x("openpond.sqlExecution.v1"),snapshot:U2,sql:o().min(1).max(65536).refine(e=>!e.includes("\0")),maxRows:m().int().min(1).max(4096),maxResultBytes:m().int().min(256).max(262144)}).strict();rt("status",[d({status:x("completed"),columns:v(o()).max(128),rows:v(v(wk).max(128)).max(4096)}).strict(),d({status:x("rejected"),code:k(["invalid_query","multiple_statements","result_too_large","memory_limit"])}).strict()]);const $l=d({scope:k(["input","initialState","state","arguments"]),path:v(o().min(1).max(256)).max(16)}).strict(),nb={id:o().min(1).max(128),operation:k(["step","collect"]),toolName:o().min(1).max(500).optional(),timeoutMs:m().int().min(1).max(2e4)},q2=rt("kind",[d({...nb,kind:x("sqlite.v1"),sql:$l,snapshot:$l,maxRows:tb.shape.maxRows,maxResultBytes:tb.shape.maxResultBytes}).strict(),d({...nb,kind:x("javascript.v1"),source:$l,cases:$l,exportName:o().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/).max(128),maxCases:m().int().min(1).max(32),maxResultBytes:m().int().min(256).max(262144)}).strict()]).superRefine((e,t)=>{e.operation==="step"!=(e.toolName!==void 0)&&t.addIssue({code:"custom",path:["toolName"],message:"Only step services require a declared tool name."}),e.operation==="collect"&&(e.kind==="sqlite.v1"?[e.sql,e.snapshot]:[e.source,e.cases]).some(a=>a.scope==="arguments")&&t.addIssue({code:"custom",message:"Collection has no tool arguments."})}),B2=d({schemaVersion:x("openpond.javascriptEnvironment.v1"),id:o().trim().min(1).max(500),revision:m().int().positive(),module:aa.refine(e=>e.visibility==="host_private","Environment code belongs to the execution owner."),tools:v(BS).min(1).max(200),maxSteps:m().int().min(1).max(1e3),maxStateBytes:m().int().min(1).max(1048576),maxObservationBytes:m().int().min(1).max(262144),operationTimeoutMs:m().int().min(1).max(3e4),executionServices:v(q2).min(1).max(16).optional()}).strict().superRefine((e,t)=>{new Set(e.tools.map(a=>a.name)).size!==e.tools.length&&t.addIssue({code:"custom",path:["tools"],message:"Environment tool names must be unique."}),e.tools.forEach((a,s)=>{wh(a.inputSchema).valid||t.addIssue({code:"custom",path:["tools",s,"inputSchema"],message:"Environment tools require a supported JSON schema."}),a.inputSchemaHash!==Qe(a.inputSchema)&&t.addIssue({code:"custom",path:["tools",s,"inputSchemaHash"],message:"Tool schema identity differs from its declared schema."})});const n=e.executionServices??[];new Set(n.map(a=>a.id)).size!==n.length&&t.addIssue({code:"custom",path:["executionServices"],message:"Execution service identities must be unique."}),n.forEach((a,s)=>{const r=e.tools.find(i=>i.name===a.toolName);a.operation==="step"&&!r&&t.addIssue({code:"custom",path:["executionServices",s,"toolName"],message:"Execution services must target a declared tool."}),a.timeoutMs>=Math.min(e.operationTimeoutMs,r?.timeoutMs??e.operationTimeoutMs)&&t.addIssue({code:"custom",path:["executionServices",s,"timeoutMs"],message:"Service budgets must leave time for the authored controller."})})}),F2=B2.safeExtend({contentHash:o().regex(/^[a-f0-9]{64}$/)});k(["create","reset","step","collect","destroy"]);d({state:ve(o(),ke()),observation:ve(o(),ke())}).strict();var V2=d({schemaVersion:x("openpond.connectedDatasetSource.v1"),kind:x("connected_activity"),id:o().min(1).max(240),profileId:o().min(1).max(240),title:o().min(1).max(500),sourceHash:o().regex(/^[a-f0-9]{64}$/),occurredAt:o().datetime(),licensingStatus:k(["pending","approved","review","blocked"]),secretScanStatus:k(["pending","passed","blocked"]),piiScanStatus:k(["pending","passed","review","blocked"]),origin:fk,sourceId:o().min(1).max(500),sessionId:o().min(1).max(500),normalizerVersion:o().min(1).max(200),projection:k(["turn","conversation"]),ownerUserId:o().min(1).max(500),purpose:x("recorded_evaluation"),metadata:ve(o(),ke()).default({})}).strict(),Ca=o().trim().min(1).max(240),Hs=o().trim().min(1),cr=o().trim().min(8).max(256),Ik=o().trim().min(1).max(1e3).refine(e=>!e.startsWith("/")&&!e.startsWith("\\")&&!e.split(/[\\/]/).includes(".."),"Artifact paths must be relative and stay inside the Dataset."),br=k(["train","validation","test","frozen_eval"]),K2=d({name:o().trim().min(1).max(500),semanticRole:k(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),logicalType:k(["string","integer","float","boolean","json","messages"]),nullable:j(),policy:k(["visible","privileged","metadata"])}),W2=d({schemaVersion:x("openpond.datasetSemanticSchema.v1"),fields:v(K2).min(1).max(1e4),schemaHash:cr}),G2=d({id:Ca,split:br,path:Ik,contentHash:cr,schemaHash:cr,sizeBytes:m().int().nonnegative(),rowCount:m().int().positive(),rowGroupCount:m().int().positive()}),zh=d({schemaVersion:x("openpond.datasetArtifact.v1"),id:Ca,tasksetId:Ca,tasksetRevision:m().int().positive(),contentHash:cr,format:x("parquet"),schema:W2,shards:v(G2).min(1).max(1e5),rowCount:m().int().positive(),splitCounts:ve(br,m().int().nonnegative()),sourceReceiptRefs:v(Ca).min(1).max(1e5),mappingHash:cr,qualityReportHash:cr,createdAt:Hs}),Z2=d({schemaVersion:x("openpond.datasetArtifactSummary.v1"),artifactId:Ca,tasksetId:Ca,tasksetRevision:m().int().positive(),format:x("parquet"),rowCount:m().int().positive(),splitCounts:ve(br,m().int().nonnegative()),sizeBytes:m().int().nonnegative(),contentHash:cr,available:j(),unavailableReason:o().trim().min(1).max(2e3).nullable(),createdAt:Hs}),J2=d({schemaVersion:x("openpond.datasetCatalogItem.v1"),tasksetId:Ca,tasksetRevision:m().int().positive(),artifactId:Ca.nullable(),name:o().trim().min(1).max(500),status:k(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),storageKind:k(["inline","parquet"]),rowCount:m().int().nonnegative(),splitCounts:ve(br,m().int().nonnegative()),sizeBytes:m().int().nonnegative().nullable(),available:j(),unavailableReason:o().trim().min(1).max(2e3).nullable(),createdAt:Hs,updatedAt:Hs});d({schemaVersion:x("openpond.datasetCatalog.v1"),profileId:Ca,datasets:v(J2),generatedAt:Hs});d({schemaVersion:x("openpond.datasetArtifactRegistry.v1"),manifest:zh,profileId:Ca,storageRoot:o().trim().min(1).max(4e3),relativeManifestPath:Ik,available:j(),unavailableReason:o().trim().min(1).max(2e3).nullable(),verifiedAt:Hs.nullable(),createdAt:Hs,updatedAt:Hs});d({split:br.nullable().default(null),cursor:o().trim().min(1).max(2e3).nullable().default(null),limit:m().int().min(1).max(100).default(25),columns:v(o().trim().min(1).max(500)).max(100).default([])});d({schemaVersion:x("openpond.datasetRowPage.v1"),tasksetId:Ca,tasksetRevision:m().int().positive(),artifactHash:cr,split:br.nullable(),rows:v(ve(o(),ke())).max(100),nextCursor:o().max(2e3).nullable(),totalRows:m().int().nonnegative(),returnedRows:m().int().nonnegative()});var Q2=d({schemaVersion:x("openpond.datasetStorageSettings.v1"),datasetStorePath:o().trim().min(1).max(4e3),updatedAt:Hs}),Y2=d({id:Ca,label:o().trim().min(1).max(500),path:o().trim().min(1).max(4e3),datasetStorePath:o().trim().min(1).max(4e3),kind:k(["local","network","removable","cache"]),configured:j(),mounted:j(),writable:j(),totalBytes:m().int().nonnegative().nullable(),freeBytes:m().int().nonnegative().nullable()});d({schemaVersion:x("openpond.datasetStorageState.v1"),settings:Q2,storageRoots:v(Y2)});d({datasetStorePath:o().trim().min(1).max(4e3)});var ti=o().trim().min(1).max(240),X2=o().trim().min(1),di=o().trim().min(8).max(256),eN=ve(o(),ke()).default({}),tN=o().trim().min(7).max(256),nN=k(["pending","approved","review","blocked"]),iu=d({id:ti,profileId:ti,title:o().trim().min(1).max(500),sourceHash:di,occurredAt:X2,licensingStatus:nN,secretScanStatus:k(["pending","passed","blocked"]),piiScanStatus:k(["pending","passed","review","blocked"]),metadata:eN}),aN=iu.extend({schemaVersion:x("openpond.huggingFaceDatasetSource.v1"),kind:x("huggingface"),repositoryId:o().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:o().url().max(2e3),revision:tN,configuration:o().trim().min(1).max(500),upstreamSplits:v(o().trim().min(1).max(500)).min(1).max(1e3),gated:j(),private:j(),declaredLicense:o().trim().min(1).max(500).nullable(),sourceFileHashes:v(di).min(1).max(1e5)}),sN=iu.extend({schemaVersion:x("openpond.uploadedFileDatasetSource.v1"),kind:x("uploaded_file"),originalFileNames:v(o().trim().min(1).max(500)).min(1).max(1e3),mediaTypes:v(o().trim().min(1).max(200)).min(1).max(1e3),sourceFileHashes:v(di).min(1).max(1e3),totalBytes:m().int().nonnegative(),parserVersion:o().trim().min(1).max(200)}),rN=iu.extend({schemaVersion:x("openpond.generatedDatasetSource.v1"),kind:x("generated"),generatorId:ti,generatorVersion:o().trim().min(1).max(200),seed:m().int(),generatorHash:di}),oN=iu.extend({schemaVersion:x("openpond.learningBatchDatasetSource.v1"),kind:x("learning_batch"),batch:d({id:ti,revision:m().int().positive(),contentHash:di}).strict(),taskDefinition:d({id:ti,revision:m().int().positive(),contentHash:di}).strict(),admittedBy:ti}),iN=rt("kind",[aN,sN,rN,oN]),cN=d({schemaVersion:x("openpond.harnessActionBinding.v1"),actionId:Cn,modelToolName:o().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:o().trim().min(1).max(1e3),inputSchema:ve(o(),ke()),actionSchemaHash:hn,agentRelease:bt,implementationHash:hn,runtimeBindingId:Cn,capabilityReceiptHash:hn,sideEffect:k(["read","write"]),studentVisible:j(),timeoutMs:m().int().positive().max(36e5),episodeArgumentBindings:v(d({argument:Cn,source:x("case_id")}).strict()).max(20).default([])}).strict(),wt=o().trim().min(1).max(240),Hh=o().trim().min(1),lN=o().trim().min(8).max(256),Uh=o().trim().regex(/^[a-f0-9]{64}$/),dN=o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),Za=ve(o(),ke()).default({}),cu=wt.nullable();function Zc(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function uN(e){const t=e.trim();return t.length>0&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")}var ui=br,_k=k(["general","benchmark"]),Ck=d({schemaVersion:x("openpond.tasksetBenchmark.v1"),definitionId:wt,releaseId:wt,releaseHash:Uh,managedReleasePath:o().trim().min(1).max(1e3).refine(Zc,"Benchmark release paths must remain relative."),adaptationSplit:ui,evaluationSplit:ui,primaryMetric:k(["foreground_tokens","success_rate","latency_ms","cost_usd"]),qualityGate:k(["none","non_regression","all_pass"]),source:k(["builtin","imported"]),metadata:Za}),Rk=d({schemaVersion:x("openpond.tasksetPreferenceComparisonBinding.v1"),releaseId:wt,releaseHash:Uh,publishedAt:Hh,metadata:Za}),mN=d({status:k(["pending","granted","denied","revoked"]),scope:k(["metadata_only","selected_turns","full_session"]),grantedBy:cu,grantedAt:Hh.nullable(),purpose:x("task_authoring_and_evaluation")}),Pk=d({schemaVersion:x("openpond.trainingSource.v1"),id:wt,profileId:wt,sessionId:wt,turnIds:v(wt).max(1e3).default([]),workspaceId:cu,sourceHash:lN,clusterKey:wt,title:o().trim().min(1).max(500),occurredAt:Hh,consent:mN,connectedAppIds:v(wt).max(100).default([]),secretScanStatus:k(["pending","passed","blocked"]),piiScanStatus:k(["pending","passed","review","blocked"]),licensingStatus:k(["pending","approved","review","blocked"]),metadata:Za}),Tk=dt([Pk,iN,V2]),qh=d({policyVisibleFields:v(wt).max(1e3).default([]),privilegedFields:v(wt).max(1e3).default([]),hiddenGraderRefs:v(wt).max(100).default([]),connectedAppScopes:v(wt).max(100).default([])}),pN=d({id:wt,sourceRefId:wt,artifactRef:o().trim().min(1).max(4e3).refine(Zc,"Task asset references must be safe relative paths."),fileName:o().trim().min(1).max(500).refine(uN,"Task asset file names must not contain path separators."),mediaType:o().trim().min(1).max(200),sha256:Uh,sizeBytes:m().int().nonnegative().max(25e7),split:ui,metadata:Za}),fN=d({path:o().trim().min(1).max(1e3).refine(Zc,"Required output paths must stay inside the Work output directory."),mediaType:o().trim().min(1).max(200),schemaRef:wt.nullable().optional(),maxBytes:m().int().positive().max(1e7).optional(),metadata:Za}),lu=d({schemaVersion:x("openpond.taskData.v1"),id:wt,clusterKey:wt,split:ui,input:ve(o(),ke()),expectedOutput:ve(o(),ke()).nullable(),policyVisibleContext:ve(o(),ke()).default({}),privilegedContextRef:cu,sourceRefs:v(wt).min(1).max(100),assets:v(pN).max(1e3).optional(),resourceRefs:v(wt).max(1e3).optional(),requiredOutputs:v(fN).max(100).optional(),tags:v(wt).max(100).default([]),metadata:Za}),hN=d({id:wt,kind:k(["file","catalog","configuration","code_module"]),path:o().trim().min(1).max(1e3).refine(Zc,"Environment resource paths must remain relative."),mediaType:o().trim().min(1).max(200).nullable().optional(),visibility:k(["policy_visible","policy_hidden","privileged"]),required:j(),metadata:Za}),Ii=d({id:wt,taskId:cu,sourceRefs:v(wt).min(1).max(100),artifactRef:wt,approved:j(),confidence:m().min(0).max(1),metadata:Za}),Ak=Ii.extend({kind:x("demonstration"),prompt:o().max(1e5).nullable().default(null),response:o().max(2e5).nullable().default(null)}),Ek=Ii.extend({kind:x("preference"),prompt:o().max(1e5),chosen:o().max(2e5),rejected:o().max(2e5),rationale:o().max(1e5).nullable().default(null)}),jk=Ii.extend({kind:x("correction"),original:o().max(2e5),corrected:o().max(2e5),rationale:o().max(1e5).nullable().default(null)}),Mk=Ii.extend({kind:x("feedback"),feedback:o().max(1e5),polarity:k(["positive","negative","mixed","neutral"])}),Ok=Ii.extend({kind:x("reward"),task:o().max(1e5),rules:v(d({id:wt,points:m().finite(),condition:o().trim().min(1).max(1e5)})).min(1).max(1e3),otherwisePoints:m().finite(),executable:j()}),$k=Ii.extend({kind:x("label"),labelKind:x("rubric"),task:o().max(1e5),criteria:v(d({id:wt,label:o().trim().min(1).max(500),description:o().trim().min(1).max(1e5)})).min(1).max(1e3),calibrationExamples:d({positive:o().trim().min(1).max(2e5),negative:o().trim().min(1).max(2e5),boundary:o().trim().min(1).max(2e5)})});rt("kind",[Ak,Ek,jk,Mk,Ok,$k]);var Nk=d({demonstrations:v(Ak).max(1e5).default([]),preferences:v(Ek).max(1e5).default([]),corrections:v(jk).max(1e5).default([]),feedback:v(Mk).max(1e5).default([]),rewards:v(Ok).max(1e5).default([]),labels:v($k).max(1e5).default([])}),Dk=d({protocolVersion:x("openpond.taskEnvironment.v1"),kind:k(["chat","agent","program","stateful_harness","work"]),entrypoint:o().trim().min(1).max(1e3),stateful:j(),deterministicSeeds:j(),toolNames:v(wt).max(200).default([]),actionBindings:v(cN).max(200).optional(),lifecycle:v(k(["create","reset","step","grade","cleanup"])).min(1),defaultTimeoutMs:m().int().positive().max(36e5),networkPolicy:k(["none","declared_read_only","declared_scoped"]),resources:v(hN).max(1e4).optional(),metadata:Za}),Bh=d({schemaVersion:x("openpond.tasksetCapabilities.v1"),taskKind:k(["chat","single_agent","multi_agent","custom_program"]),supportedSignals:v(k(["demonstration","preference","correction","feedback","reward","label"])),compatibleMethods:v(k(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"])),rewardKinds:v(k(["none","exact","deterministic","model_judge","human"])),requiresTools:j(),requiresState:j(),requiresPrivilegedGrading:j(),environmentPlacements:v(k(["local","remote","colocated","provider_native"])),exportable:j(),portabilityBlockers:v(o().trim().min(1).max(2e3)).default([])}),du=d({id:wt,version:o().trim().min(1).max(100),label:o().trim().min(1).max(500),weight:m().min(0).max(1e3).default(1),hardGate:j().default(!1),rewardEligible:j().default(!1),privileged:j().default(!1),metadata:Za}),gN=du.extend({kind:k(["content","schema","file","diff","test","runtime_event","state"]),config:ve(o(),ke())}),vN=du.extend({kind:x("model_judge"),rubric:o().trim().min(1).max(5e4),judge:Oh,calibrationFixtureRefs:v(wt).min(1).max(500),calibrationStatus:k(["pending","passed","failed"]),temperature:m().min(0).max(2).default(0)}),bN=du.extend({kind:x("human"),form:Kc.optional(),rubric:o().trim().min(1).max(5e4),reviewerRole:o().trim().min(1).max(500)}),yN=du.extend({kind:x("custom_verifier"),runtime:Px.optional(),module:o().trim().min(1).max(1e3).refine(Zc,"Custom verifier modules must use a safe relative path."),exportName:dN,timeoutMs:m().int().positive().max(3e5),networkPolicy:x("none")}),uu=dt([gN,vN,bN,yN]),Fh=k(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]),Lk=d({id:wt,taskId:wt,label:Fh,output:ve(o(),ke()),infrastructureError:o().trim().min(1).max(1e4).nullable(),expectedPassed:j(),expectedRewardEligible:j(),metadata:Za});o().regex(/^[a-f0-9]{64}$/);var SN=d({environment:Dh,verifierSet:Lh,javascript:F2}).strict();d({actions:v(d({name:o().min(1).max(64),arguments:ve(o(),ke())}).strict()).max(1e3)}).strict();var xN=d({environment:Dh,verifierSet:Lh}).strict(),kN=d({scopeId:o().trim().min(1).max(500),modelId:o().trim().min(1).max(500)}).strict();d({schemaVersion:x("openpond.modelTasksetDerivation.v1"),owner:kN,root:Fa,parent:Fa}).strict();var wN=d({taskset:Mx,taskDefinition:au,rewardBinding:Ph,rewards:v(nu).min(1).max(100),assets:v(ru).max(1e3),executionResources:xN.optional(),execution:SN.optional(),instructionMode:x("per_task").optional()}).strict(),IN=d({batch:Kx,evidence:v(su).min(1).max(1e4),decisions:v(jh).min(1).max(1e4),sources:v(Eh).min(1).max(1e4),assets:v(ru).max(1e3)}).strict(),_N=64*1024*1024,CN=d({asset:Yp,base64:o().max(Math.ceil(_N/3)*4)}).strict();d({schemaVersion:x("openpond.connectedRewardCalibrationProjection.v1"),sourceReward:vr,fixtureSet:Yp,calibrationCheck:Ye,fixture:Xx,fixtureHash:o().regex(/^[a-f0-9]{64}$/),checkResultHash:o().regex(/^[a-f0-9]{64}$/),independentCalibrationTask:x(!0),closureRef:Yp,graderId:o().min(1).max(240).optional()}).strict();var RN=wN.omit({taskset:!0,executionResources:!0}),PN=d({schemaVersion:x("openpond.tasksetPackage.v1"),taskset:Mx,environment:Dh,verifierSet:Lh,files:v(CN).max(1e4),modelResources:RN.optional(),learningResources:IN.optional()}).strict(),O8=PN.extend({contentHash:o().regex(/^[a-f0-9]{64}$/)}).strict(),hs=o().trim().min(1).max(240),Pc=o().trim().min(1),Rd=o().trim().min(8).max(256),zk=ve(o(),ke()).default({}),TN=hs.nullable(),AN=["work_capabilities","work_environment","work_list_files","work_read_file","work_read_document","work_write_file","work_write_docx","work_edit_file","work_delete_file","work_exec","work_save_output","work_stop"],EN=k(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),Hk=k(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),Fn=o().trim().max(1e5),Uk=rt("kind",[d({kind:x("demonstrations"),behavior:Fn,examples:v(d({id:hs,prompt:Fn,response:Fn})).max(1e3).default([])}),d({kind:x("preferences"),preference:Fn,pairs:v(d({id:hs,prompt:Fn,chosen:Fn,rejected:Fn,rationale:Fn})).max(1e3).default([])}),d({kind:x("verifiable_reward"),task:Fn,rules:v(d({id:hs,points:m().finite(),condition:Fn})).max(1e3).default([]),otherwisePoints:m().finite().default(0)}),d({kind:x("rubric"),task:Fn,criteria:v(d({id:hs,label:o().trim().max(500),description:Fn})).max(1e3).default([]),positiveExample:Fn,negativeExample:Fn,boundaryExample:Fn})]),jN=d({path:o().trim().min(1).max(1e3),role:k(["environment","verifier","fixture"]),content:o().max(25e4)}),qk=d({primaryMethod:k(["sft","dpo","grpo","ppo","sdft","opsd","sdpo"]),bootstrap:d({method:x("sft"),purpose:x("trajectory_bootstrap"),demonstrationRefs:v(hs).min(1).max(1e5),limitations:v(o().trim().min(1).max(5e3)).min(1).max(100)}).nullable()}),Bk=k(["taskset_not_ready","demonstrations_missing","preference_pairs_missing","preference_pairs_invalid","executable_reward_missing","reward_not_calibrated","reward_model_missing","value_model_required","frozen_eval_missing"]),MN=d({method:k(["sft","dpo","grpo","ppo"]),status:k(["recommended","compatible","needs_dataset_work"]),reasonCodes:v(Bk).default([]),reasons:v(o().trim().min(1).max(5e3)).default([])}),ab=d({code:hs,message:o().trim().min(1).max(5e3),path:o().trim().max(2e3).nullable()}),Fk=d({schemaVersion:x("openpond.tasksetReadiness.v1"),tasksetId:hs,tasksetHash:Rd,ready:j(),recommendedMethod:k(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),trainingPath:qk.nullable().default(null),methodReadiness:v(MN).default([]),compatibleDestinationClasses:v(k(["export","custom","hosted_managed"])),blockers:v(ab).default([]),advisories:v(ab).default([]),warnings:v(o().trim().min(1).max(5e3)).default([]),generatedAt:Pc}),Vk=d({attempt:m().int().positive(),summary:o().trim().min(1).max(5e3),createdAt:Pc}),ON=d({schemaVersion:x("openpond.taskAuthoringProvenance.v1"),model:Oh.nullable(),modelConfig:zk,skillHash:Rd,promptTemplateVersion:o().trim().min(1).max(200),buildIntent:Hk.default("demonstrations"),buildSpecification:Uk.nullable().default(null),evidenceHashes:v(Rd).max(1e5),tasksetSdkVersion:o().trim().min(1).max(100),sourceCommit:o().trim().min(1).max(256).nullable(),repairHistory:v(Vk).max(1e3),createdAt:Pc}),Tc=d({schemaVersion:x("openpond.taskset.v1"),id:hs,revision:m().int().positive().default(1),profileId:hs,profileRelease:W$.nullable().optional(),createImproveRunId:TN.default(null),name:o().trim().min(1).max(500),objective:o().trim().max(2e4),purpose:_k.default("general"),benchmark:Ck.nullable().default(null),preferenceComparison:Rk.nullable().default(null),status:EN,sourceRefs:v(Tk).min(1).max(1e5),datasetArtifact:zh.nullable().optional(),policy:qh,environment:Dk,capabilities:Bh,metrics:Vc.optional(),tasks:v(lu).max(1e6),graders:v(uu).max(1e3),graderFixtures:v(Lk).max(1e5),learningSignals:Nk,authoringProvenance:ON,readiness:Fk.nullable(),contentHash:Rd,createdAt:Pc,updatedAt:Pc,metadata:zk}).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 Kk(e){return e.schemaVersion==="openpond.trainingSource.v1"}function $N(e,t={}){const n=Tc.safeParse(e);if(!n.success)return{valid:!1,taskset:null,computedHash:null,issues:n.error.issues.map(i=>({code:"schema_invalid",severity:"error",message:i.message,path:i.path.join(".")}))};const a=n.data,s=[];zN(a,s),DN(a,s),HN(a,s),qN(a,s),BN(a,s),t.purpose!=="publication"&&(a.graders.length||s.push({code:"graders_required",severity:"error",message:"Scored execution requires at least one grader.",path:"graders"}),NN(a,s,t)),FN(a,s),VN(a.capabilities,s,a),UN(a,s);const r=Wk(a);return a.contentHash!==r&&s.push({code:"content_hash_mismatch",severity:"error",message:`Taskset contentHash is ${a.contentHash}, expected ${r}.`,path:"contentHash"}),{valid:!s.some(i=>i.severity==="error"),taskset:a,computedHash:r,issues:s}}function NN(e,t,n){const a=e.graders.length>0&&e.graders.every(i=>i.kind==="human");!a&&!e.graderFixtures.length&&!(n.allowUnscoredOnlineRewardBatch&&e.metadata.trainingMethod==="grpo"&&e.metadata.learning)&&t.push({code:"grader_fixtures_required",severity:"error",message:"Taskset admission requires authored grader fixtures.",path:"graderFixtures"});const s=new Set(e.tasks.map(i=>i.id)),r=new Set(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]);for(const i of e.graderFixtures)!e.datasetArtifact&&!s.has(i.taskId)&&t.push({code:"grader_fixture_task_missing",severity:"warning",message:`Fixture ${i.id} references a task outside this Taskset revision (${i.taskId}).`,path:`graderFixtures.${i.id}.taskId`}),r.delete(i.label),i.label==="infrastructure_failure"&&!i.infrastructureError&&t.push({code:"infrastructure_fixture_error_missing",severity:"error",message:`Infrastructure fixture ${i.id} must declare an infrastructure error.`,path:`graderFixtures.${i.id}.infrastructureError`});for(const i of a?[]:r)t.push({code:"grader_fixture_missing",severity:"warning",message:`Taskset does not include the optional ${i} grader calibration fixture.`,path:"graderFixtures"})}function DN(e,t){const n=e.datasetArtifact;if(!n)return;(n.tasksetId!==e.id||n.tasksetRevision!==e.revision)&&t.push({code:"dataset_artifact_taskset_mismatch",severity:"error",message:"Dataset artifact identity does not match its Taskset revision.",path:"datasetArtifact"});const a=Object.values(n.splitCounts).reduce((l,u)=>l+u,0),s=n.shards.reduce((l,u)=>l+u.rowCount,0);(a!==n.rowCount||s!==n.rowCount)&&t.push({code:"dataset_artifact_row_count_mismatch",severity:"error",message:"Dataset artifact row, split, and shard counts do not agree.",path:"datasetArtifact.rowCount"});const r=new Map;for(const l of n.shards)r.set(l.split,(r.get(l.split)??0)+l.rowCount);for(const[l,u]of Object.entries(n.splitCounts))(r.get(l)??0)!==u&&t.push({code:"dataset_artifact_split_count_mismatch",severity:"error",message:`Dataset artifact ${l} shard counts do not match its manifest.`,path:`datasetArtifact.splitCounts.${l}`});const{contentHash:i,...c}=n;Ht(c)!==n.contentHash&&t.push({code:"dataset_artifact_hash_mismatch",severity:"error",message:"Dataset artifact manifest content hash is invalid.",path:"datasetArtifact.contentHash"})}function LN(e){return Wk(e)}function Wk(e){const{contentHash:t,status:n,readiness:a,updatedAt:s,...r}=e;return Ht(r)}function zN(e,t){for(const[n,a]of e.sourceRefs.entries())Kk(a)&&a.consent.status!=="granted"&&t.push({code:"source_consent_missing",severity:"error",message:`Source ${a.id} is not consented.`,path:`sourceRefs.${n}.consent.status`}),a.secretScanStatus!=="passed"&&t.push({code:"source_secret_scan",severity:"error",message:`Source ${a.id} did not pass secret scanning.`,path:`sourceRefs.${n}.secretScanStatus`}),a.piiScanStatus!=="passed"&&t.push({code:"source_pii_scan",severity:"error",message:`Source ${a.id} has unresolved PII policy.`,path:`sourceRefs.${n}.piiScanStatus`}),a.licensingStatus!=="approved"&&t.push({code:"source_license",severity:"error",message:`Source ${a.id} has unresolved licensing policy.`,path:`sourceRefs.${n}.licensingStatus`})}function HN(e,t){const n=new Map;for(const s of e.tasks){const r=n.get(s.clusterKey)??new Set;r.add(s.split),n.set(s.clusterKey,r)}for(const[s,r]of n)r.size>1&&t.push({code:"split_cluster_contamination",severity:"error",message:`Source cluster ${s} appears in multiple splits: ${[...r].join(", ")}.`,path:"tasks"});(e.datasetArtifact?e.datasetArtifact.splitCounts.frozen_eval??0:e.tasks.filter(s=>s.split==="frozen_eval").length)===0&&t.push({code:"frozen_eval_missing",severity:"warning",message:"Add an independent test example before training.",path:"tasks"})}function UN(e,t){if(e.environment.kind!=="work")return;e.environment.entrypoint!=="openpond-work-v1"&&t.push({code:"work_entrypoint_invalid",severity:"error",message:"Work Tasksets must use the openpond-work-v1 entrypoint.",path:"environment.entrypoint"}),(!e.environment.lifecycle.includes("reset")||!e.environment.lifecycle.includes("cleanup"))&&t.push({code:"work_reset_lifecycle_missing",severity:"error",message:"Work attempts require reset and cleanup; filesystem state belongs to one attempt.",path:"environment.lifecycle"});const n=new Set(AN),a=e.environment.toolNames.filter(r=>!n.has(r));a.length&&t.push({code:"work_tool_unknown",severity:"error",message:`Work Taskset declares unknown tools: ${a.join(", ")}.`,path:"environment.toolNames"}),e.environment.toolNames.includes("work_save_output")||t.push({code:"work_output_tool_missing",severity:"error",message:"Work Tasksets must declare work_save_output.",path:"environment.toolNames"});for(const r of["create","reset","step","grade","cleanup"])e.environment.lifecycle.includes(r)||t.push({code:"work_lifecycle_incomplete",severity:"error",message:`Work Tasksets require the ${r} lifecycle stage.`,path:"environment.lifecycle"});const s=new Map(e.sourceRefs.map(r=>[r.id,r]));for(const[r,i]of e.tasks.entries()){const c=new Set,l=new Set;for(const[p,f]of(i.assets??[]).entries()){const S=`tasks.${r}.assets.${p}`;c.has(f.id)&&t.push({code:"work_asset_duplicate_id",severity:"error",message:`Task ${i.id} repeats asset id ${f.id}.`,path:`${S}.id`}),l.has(f.fileName)&&t.push({code:"work_asset_duplicate_name",severity:"error",message:`Task ${i.id} repeats staged file name ${f.fileName}.`,path:`${S}.fileName`}),c.add(f.id),l.add(f.fileName),i.sourceRefs.includes(f.sourceRefId)||t.push({code:"work_asset_task_source_missing",severity:"error",message:`Asset ${f.id} references source ${f.sourceRefId} outside task ${i.id}.`,path:`${S}.sourceRefId`});const b=s.get(f.sourceRefId);b?"sourceFileHashes"in b&&!b.sourceFileHashes.includes(f.sha256)&&t.push({code:"work_asset_hash_unregistered",severity:"error",message:`Asset ${f.id} hash is not registered by source ${f.sourceRefId}.`,path:`${S}.sha256`}):t.push({code:"work_asset_source_missing",severity:"error",message:`Asset ${f.id} references missing source ${f.sourceRefId}.`,path:`${S}.sourceRefId`}),b&&"kind"in b&&b.kind==="uploaded_file"&&!b.originalFileNames.includes(f.fileName)&&t.push({code:"work_asset_name_unregistered",severity:"error",message:`Asset ${f.id} file name is not registered by source ${f.sourceRefId}.`,path:`${S}.fileName`}),b&&"kind"in b&&b.kind==="uploaded_file"&&!b.mediaTypes.includes(f.mediaType)&&t.push({code:"work_asset_media_type_unregistered",severity:"error",message:`Asset ${f.id} media type is not registered by source ${f.sourceRefId}.`,path:`${S}.mediaType`}),f.split!==i.split&&t.push({code:"work_asset_split_mismatch",severity:"error",message:`Asset ${f.id} is assigned to ${f.split}, not task split ${i.split}.`,path:`${S}.split`})}const u=new Set;for(const[p,f]of(i.requiredOutputs??[]).entries()){const S=f.path.replaceAll("\\","/"),b=`tasks.${r}.requiredOutputs.${p}.path`;u.has(S)&&t.push({code:"work_output_duplicate_path",severity:"error",message:`Task ${i.id} repeats required output path ${S}.`,path:b}),u.add(S)}(i.requiredOutputs??[]).length===0&&t.push({code:"work_output_missing",severity:"error",message:`Work task ${i.id} must declare at least one required output.`,path:`tasks.${r}.requiredOutputs`})}}function qN(e,t){const n=new Set(e.policy.policyVisibleFields);for(const a of e.policy.privilegedFields)n.has(a)&&t.push({code:"privileged_field_visible",severity:"error",message:`Field ${a} is both policy-visible and privileged.`,path:"policy"});for(const a of e.tasks)a.privilegedContextRef&&Object.keys(a.policyVisibleContext).includes(a.privilegedContextRef)&&t.push({code:"privileged_context_leak",severity:"error",message:`Task ${a.id} exposes its privileged context reference.`,path:`tasks.${a.id}.policyVisibleContext`})}function BN(e,t){const n=new Set;for(const a of e.graders)n.has(a.id)&&t.push({code:"grader_duplicate",severity:"error",message:`Duplicate grader id ${a.id}.`,path:"graders"}),n.add(a.id),a.kind==="model_judge"&&a.rewardEligible&&a.calibrationStatus!=="passed"&&t.push({code:"judge_calibration_pending",severity:"warning",message:`Model judge ${a.id} is selected for reward without a passing advisory calibration report.`,path:`graders.${a.id}`}),a.kind==="model_judge"&&a.calibrationStatus==="passed"&&typeof a.metadata.calibrationEvidenceHash!="string"&&t.push({code:"judge_calibration_evidence_missing",severity:"warning",message:`Model judge ${a.id} declares calibration without an OpenPond fixture evidence hash.`,path:`graders.${a.id}.metadata.calibrationEvidenceHash`}),a.kind==="human"&&a.rewardEligible&&t.push({code:"human_online_reward",severity:"error",message:`Human grader ${a.id} cannot be an online optimizer reward.`,path:`graders.${a.id}`})}function FN(e,t){const n=new Set(e.tasks.map(s=>s.id)),a=new Set(e.sourceRefs.map(s=>s.id));for(const s of[...e.learningSignals.demonstrations,...e.learningSignals.preferences,...e.learningSignals.corrections,...e.learningSignals.feedback,...e.learningSignals.rewards,...e.learningSignals.labels])s.taskId&&!e.datasetArtifact&&!n.has(s.taskId)&&t.push({code:"learning_signal_task_missing",severity:"error",message:`Signal ${s.id} references missing task ${s.taskId}.`,path:`learningSignals.${s.kind}.${s.id}.taskId`}),s.sourceRefs.some(r=>!a.has(r))&&t.push({code:"learning_signal_source_missing",severity:"error",message:`Signal ${s.id} references a source outside the Dataset.`,path:`learningSignals.${s.kind}.${s.id}.sourceRefs`});for(const s of e.learningSignals.preferences)s.chosen.trim()===s.rejected.trim()&&t.push({code:"preference_pair_identical",severity:"error",message:`Preference ${s.id} has identical chosen and rejected responses.`,path:`learningSignals.preferences.${s.id}`});for(const s of e.learningSignals.rewards)s.executable||t.push({code:"reward_not_executable",severity:"warning",message:`Reward ${s.id} is a reviewed specification but has no executable verifier yet.`,path:`learningSignals.rewards.${s.id}.executable`})}function VN(e,t,n){!e.exportable&&e.portabilityBlockers.length===0&&t.push({code:"portability_reason_missing",severity:"error",message:"Non-exportable Tasksets must declare a portability blocker.",path:"capabilities.portabilityBlockers"}),e.compatibleMethods.includes("grpo")&&!e.rewardKinds.some(a=>a==="exact"||a==="deterministic"||a==="model_judge")&&t.push({code:"grpo_reward_missing",severity:"error",message:"GRPO compatibility requires a scalar reward kind.",path:"capabilities.rewardKinds"}),n?.capabilities.compatibleMethods.includes("sft")&&n.learningSignals.demonstrations.length===0&&t.push({code:"sft_demonstrations_missing",severity:"error",message:"SFT compatibility requires approved demonstrations.",path:"learningSignals.demonstrations"}),n?.capabilities.compatibleMethods.includes("dpo")&&n.learningSignals.preferences.length===0&&t.push({code:"dpo_preferences_missing",severity:"error",message:"DPO compatibility requires chosen and rejected response pairs.",path:"learningSignals.preferences"}),n&&(n.capabilities.compatibleMethods.includes("grpo")||n.capabilities.compatibleMethods.includes("ppo"))&&!n.learningSignals.rewards.some(a=>a.executable)&&!n.graders.some(a=>a.rewardEligible&&a.weight>0&&a.kind!=="human")&&t.push({code:"online_reward_not_executable",severity:"error",message:"GRPO/PPO compatibility requires an executable scalar reward.",path:"learningSignals.rewards"})}var Fo=o().trim().min(1).max(240),sb=o().trim().min(1),KN=o().trim().min(8).max(256),WN=o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),GN=ve(o(),ke()).default({});function rb(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}var Gk=lu.extend({sourceRefs:v(Fo).max(100).default([])}),Zk=k(["draft","validating","needs_review","published"]),ZN=d({enabled:j(),candidateCount:m().int().min(2).max(4),minimumSamples:m().int().min(1).max(1e4).default(100),allowTies:j(),allowRejectAll:j(),rubric:o().trim().max(5e4),criteria:v(d({id:Fo,label:o().trim().min(1).max(500),description:o().trim().max(1e4),weight:m().nonnegative().max(1e3)})).max(100)}),JN=d({mode:k(["text","structured_json","artifacts"]),jsonSchema:ve(o(),ke()).nullable(),renderer:d({module:o().trim().min(1).max(1e3).refine(rb,"Renderer modules must use a safe relative path."),exportName:WN,configRef:o().trim().min(1).max(1e3).refine(rb,"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"]})}),Ka=d({schemaVersion:x("openpond.tasksetDraft.v1"),id:Fo,revision:m().int().positive(),profileId:Fo,modelScope:d({modelId:Fo,expectedModelRevision:m().int().positive(),source:H$.optional()}).strict().nullable().default(null),name:o().trim().max(500),objective:o().trim().max(2e4),purpose:_k.default("general"),benchmark:Ck.nullable().default(null),preferenceComparison:Rk.nullable().default(null),status:Zk,sourceRefs:v(Tk).max(1e5).default([]),datasetArtifact:zh.nullable().optional(),policy:qh,environment:Dk,output:JN.default({mode:"text",jsonSchema:null,renderer:null}),capabilities:Bh,metrics:Vc,review:ZN,tasks:v(Gk).max(1e6).default([]),graders:v(uu).max(1e3).default([]),graderFixtures:v(Lk).max(1e5).default([]),learningSignals:Nk,publishedTasksetRef:d({id:Fo,revision:m().int().positive(),contentHash:KN}).nullable(),createdAt:sb,updatedAt:sb,metadata:GN}).superRefine((e,t)=>{e.purpose==="benchmark"&&!e.benchmark&&t.addIssue({code:"custom",message:"Benchmark drafts require an immutable benchmark binding.",path:["benchmark"]}),e.purpose!=="benchmark"&&e.benchmark&&t.addIssue({code:"custom",message:"Only benchmark drafts may carry a benchmark binding.",path:["benchmark"]}),e.datasetArtifact&&e.tasks.length>0&&t.addIssue({code:"custom",message:"Artifact-backed drafts may not duplicate canonical rows inline.",path:["tasks"]}),e.status==="published"&&!e.publishedTasksetRef&&t.addIssue({code:"custom",message:"Published drafts require an immutable Taskset reference.",path:["publishedTasksetRef"]})}),QN=6e6,YN=new Set(["taskset.json","capabilities.json","data/tasks.jsonl","tasks/tasks.jsonl","graders/graders.json","fixtures/grader-fixtures.json","metrics/policy.json","assets/manifest.json","environment/contract.json","environment/taskset.ts","rubrics/preference-review.md","comparisons/policy.json"]);function XN(e){const t=ou.parse(e);return!YN.has(t)&&!t.startsWith("source-artifacts/")}function ob(e,t){const n=XN(e);if(t.byteLength>QN)throw new Error("Taskset draft file content is invalid or exceeds 6 MB.");let a;try{const s=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t);a=/[\u0000-\u0008\u000e-\u001f]/.test(s)?ib(t):{encoding:"utf8",data:s}}catch{a=ib(t)}return{path:e,writable:n,content:a,sizeBytes:t.byteLength,contentHash:ik(t)}}function ib(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 cb=64*1024*1024,Jk=o().regex(/^[a-f0-9]{64}$/),eD=d({path:ou,contentHash:Jk,sizeBytes:m().int().nonnegative().max(cb),base64:o().max(cb)}).strict(),tD=d({schemaVersion:x("openpond.tasksetDraftWorkspace.v1"),draft:Ka,files:v(eD).max(1e4)}).strict(),$8=tD.extend({contentHash:Jk}).strict(),lb=class extends Error{issues;constructor(e){super(e.map(t=>t.message).join(`
109
109
  `)),this.name="TasksetDraftPublishError",this.issues=e}};function nD(e){const t=[];e.name.trim()||t.push({code:"name_missing",message:"Name is required.",path:"name"}),e.objective.trim()||t.push({code:"objective_missing",message:"Objective is required.",path:"objective"}),!e.datasetArtifact&&e.tasks.length===0&&t.push({code:"tasks_missing",message:"Add at least one task or Dataset artifact.",path:"tasks"});const n=new Set(e.sourceRefs.map(a=>a.id));for(const a of e.tasks)for(const s of a.sourceRefs)n.has(s)||t.push({code:"task_source_missing",message:`Task ${a.id} references missing source ${s}.`,path:`tasks.${a.id}.sourceRefs`});return t}function N8(e){const t=Ka.parse(e.draft),n=e.now??new Date().toISOString(),a=nD(t);if(a.length)throw new lb(a);const s=t.modelScope?.source;if(s&&e.tasksetId&&e.tasksetId!==s.tasksetId)throw new Error("Taskset draft publication differs from its prepared identity.");const r=s?.tasksetId||e.tasksetId?.trim()||t.publishedTasksetRef?.id||t.id.replace(/-draft$/,""),i=s?.tasksetRevision??(t.publishedTasksetRef?.id===r?t.publishedTasksetRef.revision+1:1),c=t.sourceRefs.length?t.sourceRefs:[aD(t,r,n)],l=c[0].id,u=t.tasks.map(E=>lu.parse({...E,sourceRefs:E.sourceRefs.length?E.sourceRefs:[l],metadata:{exampleOrigin:"expert_authored",...E.metadata}})),p=t.capabilities.compatibleMethods.find(E=>E!=="none"&&E!=="retrieval")??null,f=sD(t),S=t.graders.filter(E=>E.rewardEligible&&E.weight>0&&E.kind!=="human"),b=p===null&&f==="verifiable_reward"&&S.length>0,w=p??(b?"grpo":null),C=Tc.parse({schemaVersion:"openpond.taskset.v1",id:r,revision:i,profileId:t.profileId,profileRelease:null,createImproveRunId:null,name:t.name,objective:t.objective,purpose:t.purpose,benchmark:t.benchmark,preferenceComparison:t.preferenceComparison,status:"needs_review",sourceRefs:c,datasetArtifact:t.datasetArtifact??null,policy:t.policy,environment:t.environment,capabilities:b?{...t.capabilities,compatibleMethods:["grpo"],rewardKinds:[...new Set(S.map(E=>E.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:Ht("openpond-taskset-draft-authoring-v1"),promptTemplateVersion:"taskset-draft-v1",buildIntent:f,buildSpecification:null,evidenceHashes:c.map(E=>E.sourceHash),tasksetSdkVersion:"draft-v1",sourceCommit:null,repairHistory:[],createdAt:n},readiness:null,contentHash:"00000000",createdAt:i===1?t.createdAt:n,updatedAt:n,metadata:{...t.metadata,...s?{modelTasksetAuthoring:s.lineage}:{},tasksetReviewPolicy:t.review,tasksetOutputContract:t.output,...e.sourcePackageHash?{sourcePackageHash:e.sourcePackageHash}:{},...w?{trainingMethod:w}:{},diagnosis:{schemaVersion:"openpond.capabilityDiagnosis.v1",summary:t.objective,stableBehavior:[t.objective],changingKnowledge:[],requiredContext:[],requiredTools:t.environment.toolNames,intervention:w==="dpo"?"preference":w==="grpo"||w==="ppo"?"grpo_rft":w==="sft"?"sft":"no_training",trainingEligible:w!==null,rationale:w?[`The author selected ${w.toUpperCase()} compatibility.`]:["The Taskset is currently configured for evaluation only."],confidence:1}}}),P=Tc.parse({...C,contentHash:LN(C)}),M=$N(P,{purpose:"publication"}).issues.filter(E=>E.severity==="error");if(M.length)throw new lb(M.map(E=>({code:E.code,message:E.message,path:E.path})));return P}function aD(e,t,n){const a=Ht({draftId:e.id,draftRevision:e.revision,tasks:e.tasks});return{schemaVersion:"openpond.generatedDatasetSource.v1",kind:"generated",id:`source-${t}`,profileId:e.profileId,title:`${e.name} manual authoring`,sourceHash:a,occurredAt:n,licensingStatus:"approved",secretScanStatus:"passed",piiScanStatus:"passed",generatorId:"openpond-taskset-draft",generatorVersion:"1",seed:0,generatorHash:a,metadata:{draftId:e.id,draftRevision:e.revision}}}function sD(e){return e.metadata.buildIntent==="discovery"||!e.graders.length&&!e.learningSignals.preferences.length&&!e.learningSignals.rewards.length&&!e.learningSignals.labels.length?"discovery":e.learningSignals.preferences.length?"preferences":e.learningSignals.rewards.length?"verifiable_reward":e.learningSignals.labels.length?"rubric":!e.capabilities.compatibleMethods.some(t=>t!=="none"&&t!=="retrieval")&&e.graders.some(t=>t.rewardEligible&&t.weight>0&&t.kind!=="human")?"verifiable_reward":"demonstrations"}var ni=o().regex(/^[a-f0-9]{64}$/),Qk=d({providerId:x("claude-code"),configurationHash:ni,executableHash:ni,version:o().regex(/^2\.\d+\.\d+$/),capabilityHash:ni,maximumRequestCostUsd:m().finite().positive().max(1e4),requestTimeoutMs:m().int().min(1e3).max(3e5),maximumTurns:m().int().min(1).max(100),holdOpen:j()}).strict();d({id:o().min(1).max(200),receiptId:o().min(1).max(200),sessionId:oS(),operationId:o().min(1).max(200),action:k(["message","seal"]),text:o().max(262144).optional()}).strict().superRefine((e,t)=>{e.action==="message"&&!e.text?.trim()&&t.addIssue({code:"custom",message:"A human intervention requires a message."}),e.action==="seal"&&e.text!==void 0&&t.addIssue({code:"custom",message:"Sealing does not add a prompt."})});var D8=d({provider:x("claude-code"),sessionId:oS(),requestId:o().min(1).max(200),modelId:o().min(1).max(500),runtime:Qk,sourceHash:ni,outputHash:ni,traceHash:ni,runtimeEventRefs:v(o().min(1).max(200)).min(1).max(2e4),eventCount:m().int().positive().max(2e4),startedAt:na(),completedAt:na(),cleanupComplete:x(!0)}).strict().superRefine((e,t)=>{(e.runtimeEventRefs.length!==e.eventCount||new Set(e.runtimeEventRefs).size!==e.eventCount)&&t.addIssue({code:"custom",message:"Process event references must match the exact retained trace population."})}),mu=d({id:o().trim().min(1).max(240),revision:m().int().positive(),contentHash:o().regex(/^[a-f0-9]{64}$/),targetId:o().trim().min(1).max(240).nullable()}).strict(),rD=v(d({role:k(["system","user","assistant"]),content:o().max(1e5)}).strict()).max(100).superRefine((e,t)=>{e.reduce((n,a)=>n+a.content.length,0)>1e5&&t.addIssue({code:"custom",message:"Evaluation prompt exceeds 100,000 characters."})}),oD=d({schemaVersion:x("openpond.experimentAttemptGrade.v1"),selectionHash:o().regex(/^[a-f0-9]{64}$/),grades:v($x).min(1).max(100),score:m().min(0).max(1).nullable(),passed:j(),rewardEligible:j(),gradingStatus:k(["scored","pending","unscorable","not_configured"]),failureClass:G$.nullable(),contentHash:o().regex(/^[a-f0-9]{64}$/)}).strict().superRefine((e,t)=>{const{contentHash:n,...a}=e;Ht(a)!==n&&t.addIssue({code:"custom",message:"Experiment grading integrity failed."});const s=e.grades.flatMap(r=>r.components);(s.length!==e.grades.length||new Set(s.map(r=>r.graderId)).size!==s.length)&&t.addIssue({code:"custom",message:"Each selected criterion requires exactly one distinct grader result."});for(const r of e.grades){const{contentHash:i,...c}=r;Ht(c)!==i&&t.addIssue({code:"custom",message:"A retained criterion changed."});for(const l of r.components){const{contentHash:u,...p}=l;Ht(p)!==u&&t.addIssue({code:"custom",message:"A retained grader result changed."})}}}),Xt=o().trim().min(1).max(200),Ur=o().regex(/^[a-f0-9]{64}$/),Yk=rt("kind",[d({kind:x("hosted_chat"),modelId:Xt,localRuntime:dt([d({providerId:x("custom-openai-compatible"),configurationHash:Ur,maximumRequestCostUsd:m().finite().positive().max(1e4),requestTimeoutMs:m().int().min(1e3).max(3e5)}).strict(),Qk]).optional(),candidate:d({artifactId:Xt,contentHash:Ur,preparationId:Xt,dispatchId:Xt,baseProfileId:Xt,workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/)}).strict().optional(),harness:Th.optional(),messages:rD.optional(),maxOutputTokens:m().int().min(1).max(1e6).default(1e5),temperature:m().min(0).max(2).default(0),topP:m().gt(0).max(1).default(1)}).strict(),d({kind:x("fixture"),fixtureId:Xt}).strict()]),iD=d({schemaVersion:x("openpond.modelStarterAttemptRequest.v1"),operationId:Xt,teamId:Xt,modelProjectId:Xt.nullable(),project:mu.optional(),taskset:Fa,taskId:Xt,environmentSeed:m().int().min(0).max(2147483647).default(0),policy:Yk}).strict();d({modelProjectId:Xt.nullable(),taskset:Fa,afterTaskId:Xt.optional(),limit:m().int().min(1).max(100).default(25)}).strict();d({modelProjectId:Xt.nullable(),taskset:Fa,available:j(),unavailableReason:o().max(1e3).nullable(),models:v(d({id:Xt,name:o().max(500),maximumOutputTokens:m().int().min(1).max(1e6).optional()}).strict()).max(200),tasks:v(d({id:Xt,split:Ga,inputPreview:o().max(500),fixtures:v(d({id:Xt,label:o().max(200)}).strict()).max(1e3)}).strict()).max(100),nextCursor:Xt.nullable()}).strict();var Vh=d({schemaVersion:x("openpond.modelStarterAttemptSummary.v1"),id:Xt,revision:m().int().positive(),request:iD,status:k(["queued","running","cancelling","completed","failed","cancelled"]),policySnapshot:d({modelId:Xt,provider:Xt,upstreamModelId:o().min(1).max(500),configurationHash:Ur}).strict().nullable(),createdAt:na(),startedAt:na().nullable(),completedAt:na().nullable(),cleanupComplete:j(),resultAvailable:j(),score:m().min(0).max(1).nullable(),gradingStatus:k(["not_started","pending","scored","unscorable","not_configured"]).default("not_started"),passed:j().nullable(),outputPreview:o().max(500).nullable(),error:d({code:Xt,message:o().max(2e3)}).strict().nullable()}).strict().superRefine((e,t)=>{e.request.policy.kind==="fixture"!=(e.policySnapshot===null)&&t.addIssue({code:"custom",path:["policySnapshot"],message:"Fixture execution must not claim a model identity."}),e.status==="completed"&&(!e.cleanupComplete||!e.resultAvailable||!e.completedAt)&&t.addIssue({code:"custom",message:"Completed attempts require retained results and confirmed cleanup."})});d({modelProjectId:Xt,afterId:Xt.optional(),limit:m().int().min(1).max(100).default(25)}).strict();d({items:v(Vh).max(100),nextCursor:Xt.nullable()}).strict();d({schemaVersion:x("openpond.modelStarterAttemptResult.v1"),attempt:Vh,output:o().max(1048576).nullable(),messages:v(ve(o(),ke())).max(4002),composition:Ic.nullable(),grade:$x.nullable().optional(),experimentGrade:oD.nullable().optional(),environment:d({status:k(["completed","budget_exhausted","cancelled","timed_out","policy_failure","environment_failure"]),collected:j(),definition:Fa,initialStateHash:Ur.nullable(),finalStateHash:Ur.nullable(),attemptHash:Ur}).strict(),native:Lx.optional(),providerRequestIds:v(Xt).max(1001),contentHash:Ur}).strict().superRefine((e,t)=>{const n=e.attempt.request.policy.kind==="hosted_chat"?e.attempt.request.policy.harness:void 0;!!n!=!!e.native&&t.addIssue({code:"custom",path:["native"],message:"Standalone Harness results require their exact native evidence."}),e.native&&(!n||Ht(n)!==Ht(e.native.source)||e.native.modelConfigurationHash!==e.attempt.policySnapshot?.configurationHash||e.environment.initialStateHash!==null||e.environment.finalStateHash!==null||e.environment.status==="completed"&&(!e.environment.collected||e.output===null||e.native.partialOutputAvailable||e.native.outputHash!==Ht(e.output)))&&t.addIssue({code:"custom",path:["native"],message:"Native evidence differs from the admitted source, model or output."}),e.experimentGrade&&((e.grade||e.composition)&&t.addIssue({code:"custom",message:"Selected Experiment grading cannot claim another grade population."}),(!["completed","failed"].includes(e.attempt.status)||!e.attempt.resultAvailable||e.attempt.score!==e.experimentGrade.score||e.attempt.gradingStatus!==e.experimentGrade.gradingStatus||e.attempt.passed!==(e.experimentGrade.score===null?null:e.experimentGrade.passed))&&t.addIssue({code:"custom",message:"Experiment grading differs from its retained attempt summary."})),e.grade&&(e.composition&&t.addIssue({code:"custom",path:["grade"],message:"An ordinary grade cannot also claim a Reward composition."}),(!["completed","failed"].includes(e.attempt.status)||!e.attempt.resultAvailable||e.attempt.score!==e.grade.score||e.attempt.gradingStatus!==e.grade.gradingStatus||e.attempt.passed!==(e.grade.score===null?null:e.grade.passed))&&t.addIssue({code:"custom",path:["grade"],message:"Ordinary grade differs from its terminal attempt summary."}))});var Eo=o().trim().min(1).max(240),Xm=o().regex(/^[a-f0-9]{64}$/),Xk=d({kind:x("hosted_harness"),modelId:Eo,candidate:d({artifactId:Eo,contentHash:Xm,preparationId:Eo,dispatchId:Eo,baseProfileId:Eo,workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/)}).strict().optional(),sourceCandidate:Id.shape.sourceCandidate,reasoningEffort:k(["off","low","medium","high","xhigh","max"]).optional(),profileRepositoryId:Eo,source:Id,modelConfigurationHash:Xm,packageHash:Xm,externalDatasetBinding:ur.optional()}).strict().superRefine((e,t)=>{JSON.stringify(e.externalDatasetBinding??null)!==JSON.stringify(e.source.externalDatasetBinding??null)&&t.addIssue({code:"custom",message:"The policy and source must bind the same external Dataset recipe."}),JSON.stringify(e.sourceCandidate??null)!==JSON.stringify(e.source.sourceCandidate??null)&&t.addIssue({code:"custom",message:"The policy and prepared source must bind the same actual source candidate."})}),qa=o().trim().min(1).max(200),ew=o().regex(/^[a-f0-9]{64}$/),cD=rt("kind",[Yk.options[0],d({kind:x("fixture")}).strict(),Xk]),pu=d({schemaVersion:x("openpond.modelTasksetRunRequest.v1"),operationId:qa,teamId:qa,modelProjectId:qa.nullable(),name:o().trim().min(1).max(200).optional(),project:mu.optional(),taskset:Fa,policy:cD,population:v(xk).min(1).max(1e4)}).strict().superRefine((e,t)=>{new Set(e.population.map(n=>n.receiptId)).size!==e.population.length&&t.addIssue({code:"custom",path:["population"],message:"Run receipt identities must be unique."}),e.population.some(n=>n.fixtureId!==null!=(e.policy.kind==="fixture"))&&t.addIssue({code:"custom",path:["population"],message:"Only fixture runs require a fixture identity for every member."}),e.population.some(n=>!/^(0|[1-9][0-9]*)$/.test(n.seed)||Number(n.seed)>2147483647)&&t.addIssue({code:"custom",path:["population"],message:"Hosted environment seeds must be integers from 0 to 2147483647."}),e.policy.kind==="hosted_harness"&&e.modelProjectId!==null&&t.addIssue({code:"custom",path:["modelProjectId"],message:"A Harness target retains its released Profile binding separately from Model artifacts."}),e.policy.kind==="hosted_harness"&&new Set(e.population.map(n=>$h([n.taskId,n.seed]))).size!==e.population.length&&t.addIssue({code:"custom",path:["population"],message:"Harness case identities must be unique for each task and seed."})}),tw=d({schemaVersion:x("openpond.modelTasksetRunSummary.v1"),id:qa,revision:m().int().positive(),teamId:qa,modelProjectId:qa.nullable(),name:o().trim().min(1).max(200).optional(),project:mu.optional(),operationId:qa,taskset:Fa,policyKind:k(["hosted_chat","fixture","hosted_harness"]),manifestHash:ew,status:k(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:m().int().min(1).max(1e4),counts:d({pending:m().int().nonnegative(),running:m().int().nonnegative(),completed:m().int().nonnegative(),failed:m().int().nonnegative(),cancelled:m().int().nonnegative()}).strict(),createdAt:na(),startedAt:na().nullable(),completedAt:na().nullable(),cleanupComplete:j(),resultAvailable:j(),score:m().min(0).max(1).nullable(),metricName:o().min(1).max(240),error:d({code:qa,message:o().max(2e3)}).strict().nullable()}).strict().superRefine((e,t)=>{Object.values(e.counts).reduce((n,a)=>n+a,0)!==e.totalCount&&t.addIssue({code:"custom",path:["counts"],message:"Run counts must account for the complete population."}),e.status!=="completed"&&e.score!==null&&t.addIssue({code:"custom",path:["score"],message:"Only completed evaluations publish a metric value."}),["completed","failed","cancelled"].includes(e.status)&&(!e.completedAt||e.counts.pending||e.counts.running)&&t.addIssue({code:"custom",message:"Terminal runs require complete population accounting."}),e.status==="cancelled"&&!e.cleanupComplete&&t.addIssue({code:"custom",message:"Cancelled runs require confirmed cleanup."}),e.resultAvailable&&!["completed","failed","cancelled"].includes(e.status)&&t.addIssue({code:"custom",message:"Run results require terminal population accounting."}),e.status==="completed"&&(!e.cleanupComplete||!e.resultAvailable)&&t.addIssue({code:"custom",message:"Completed evaluations require retained results and confirmed cleanup."})}),lD=d({summary:tw,request:pu,manifest:kk,policySnapshot:Vh.shape.policySnapshot}).strict();d({modelProjectId:qa.optional(),projectId:mu.shape.id.optional(),afterId:qa.optional(),limit:m().int().min(1).max(100).default(25)}).strict();d({items:v(tw).max(100),nextCursor:qa.nullable()}).strict();d({schemaVersion:x("openpond.modelTasksetRunResult.v1"),run:lD,receipts:v(C2).min(1).max(1e4),metric:gx.nullable(),contentHash:ew}).strict();var nw=o().min(1).max(200).refine(e=>!["__proto__","prototype","constructor"].includes(e),"Use an ordinary field name."),dD=v(nw).min(1).max(20),db=k(["input","output","expectedOutput","evaluatorContext"]),uD=d({destination:db,path:dD,source:db,sourcePath:v(nw).max(20)}).strict(),Kh=v(uD).max(100).superRefine((e,t)=>{for(const[n,a]of e.entries())e.slice(0,n).some(s=>s.destination===a.destination&&(ub(s.path,a.path)||ub(a.path,s.path)))&&t.addIssue({code:"custom",path:[n,"path"],message:"Mapped destination paths must not overlap."})});function ub(e,t){return e.length<=t.length&&e.every((n,a)=>n===t[a])}var Wn=o().trim().min(1).max(200),Zr=o().regex(/^[a-f0-9]{64}$/),Wh=d({id:Wn,revision:m().int().positive(),contentHash:Zr}).strict(),fu=d({id:Wn,version:o().min(1).max(200),contentHash:Zr,name:o().trim().min(1).max(500).optional(),feedbackKey:Wc,release:Wh.nullable(),mappings:Kh.optional()}).strict(),mD=d({id:Wn,version:o().min(1).max(200),contentHash:Zr,mappings:Kh}).strict(),L8=d({operationId:Wn,id:Wn.optional(),expectedRevision:m().int().nonnegative(),request:pu,maximumCostUsd:m().finite().positive().max(1e4),graders:v(mD).min(1).max(100).optional()}).strict().superRefine((e,t)=>{e.request.name||t.addIssue({code:"custom",path:["request","name"],message:"Name this Experiment before saving it."}),!!e.id!=e.expectedRevision>0&&t.addIssue({code:"custom",path:["expectedRevision"],message:"An update requires its saved definition revision."}),Math.round(e.maximumCostUsd*1e6)<1&&t.addIssue({code:"custom",path:["maximumCostUsd"],message:"The budget must be at least $0.000001."}),e.graders&&new Set(e.graders.map(n=>n.id)).size!==e.graders.length&&t.addIssue({code:"custom",path:["graders"],message:"Select each grader once."})}),pD=d({schemaVersion:x("openpond.experimentDefinition.v1"),id:Wn,teamId:Wn,revision:m().int().positive(),request:pu,maximumCostUsd:m().finite().positive().max(1e4),graders:v(fu).min(1).max(100),createdAt:na(),updatedAt:na()}).strict();pD.extend({contentHash:Zr});d({operationId:Wn,definition:Wh}).strict();d({projectId:Wn.optional(),datasetHash:Zr.optional(),search:o().trim().max(200).optional(),status:k(["queued","running","cancelling","completed","failed","cancelled"]).optional(),afterId:Wn.optional(),limit:m().int().min(1).max(100).default(30)}).strict();d({definition:Wh.nullable(),configurationHash:Zr.optional(),admissionRequestHash:Zr.optional(),sourceExperimentId:Wn.optional(),maximumCostUsd:m().finite().positive().max(1e4),graders:v(fu).min(1).max(100)}).strict().superRefine((e,t)=>{e.definition===null&&(!e.configurationHash||!e.admissionRequestHash)&&t.addIssue({code:"custom",path:["configurationHash"],message:"A flat Experiment requires its sealed configuration hash."})});d({operationId:Wn,profileRepositoryId:Wn,definitionId:Wn,modelId:Wn,reasoningEffort:k(["off","low","medium","high","xhigh","max"]).optional(),maximumCostUsd:m().finite().positive().max(1e4),externalDatasetBinding:ur.optional(),sourceCandidate:Xk.shape.sourceCandidate}).strict();d({request:pu,manifest:kk,maximumCostUsd:m().finite().positive().max(1e4),graders:v(fu).min(1).max(100)}).strict();var ys=Ka.shape.id,Wa=m().int().positive(),Jr=o().regex(/^[a-f0-9]{64}$/),eo={teamId:ys,modelId:ys};d({schemaVersion:x("openpond.tasksetDraftCreate.v1"),operationId:ys,modelId:ys,expectedModelRevision:Wa,name:Ka.shape.name}).strict();d({schemaVersion:x("openpond.tasksetDraftSourceDescriptor.v1"),...eo,expectedModelRevision:Wa,sourcePackageHash:Jr}).strict();d({schemaVersion:x("openpond.tasksetDraftReadback.v1"),...eo,draft:Ka,workspaceHash:Jr,projectEtag:Jr}).strict().refine(e=>e.draft.profileId===e.teamId&&e.draft.modelScope?.modelId===e.modelId,"The hosted draft must belong to its declared workspace and Model.");var fD=d({id:ys,revision:Wa,name:Ka.shape.name,status:Zk,updatedAt:Ka.shape.updatedAt,sourceTasksetRef:Ye.nullable()}).strict();d({schemaVersion:x("openpond.tasksetDraftList.v1"),...eo,drafts:v(fD).max(100),nextCursor:o().min(1).max(2e3).nullable()}).strict();d({expectedDraftRevision:Wa,draft:Ka}).strict();d({expectedDraftRevision:Wa,expectedModelRevision:Wa}).strict();var hD=d({expectedDraftRevision:Wa,expectedWorkspaceHash:Jr}).strict();d({schemaVersion:x("openpond.tasksetDraftValidation.v1"),...eo,draftId:ys,draftRevision:Wa,workspaceHash:Jr,valid:j(),issues:v(d({code:o().min(1),severity:k(["warning","error"]),message:o(),path:o().nullable()}).strict()),packageHash:Jr.nullable(),tasksetRef:Ye.nullable()}).strict().refine(e=>e.valid?e.packageHash!==null&&e.tasksetRef!==null&&e.issues.every(t=>t.severity!=="error"):e.packageHash===null&&e.tasksetRef===null&&e.issues.some(t=>t.severity==="error"),"Validation must retain either a compiled package or publication errors.");hD.extend({operationId:ys,expectedPackageHash:Jr,expectedTasksetRef:Ye}).strict();d({schemaVersion:x("openpond.tasksetDraftFileList.v1"),...eo,draftId:ys,draftRevision:Wa,files:v(ak).max(10020)}).strict();d({schemaVersion:x("openpond.tasksetDraftFileReadback.v1"),...eo,draftId:ys,draftRevision:Wa,file:U$}).strict();d({schemaVersion:x("openpond.tasksetDraftDeletion.v1"),...eo,draftId:ys,revision:Wa,deleted:x(!0)}).strict();Ka.shape.id;m().int().positive();var zs=o().trim().min(1).max(500),gD=d({projectId:zs.optional(),tasksetId:zs.optional(),draftId:zs.optional(),taskId:zs.optional(),query:o().trim().max(1e3).default(""),split:k(["train","validation","test","frozen_eval"]).optional(),after:o().min(1).max(2e3).optional(),limit:m().int().min(1).max(100).default(30)}).strict(),vD=d({id:zs,method:k(["code","judge","human"]),required:j()}),aw=d({tasksetId:zs,tasksetName:o(),tasksetRevision:m().int().positive(),tasksetHash:o(),taskId:zs,ordinal:m().int().nonnegative(),title:o(),description:o(),split:o(),scoring:v(vD),configuration:k(["configured","needs_reward","needs_checks"]),draftId:zs.nullable().default(null),modelId:zs.nullable().default(null)}),bD=d({items:v(aw).max(100),nextCursor:o().nullable()});function z8(e,t){if(D$({format:e.format,files:t}).contentHash!==e.contentHash)throw new Error("The source files differ from the import preview.");const n=`private/intake/${e.contentHash}`,a=t.map((r,i)=>({file:r,path:`${n}/${String(i).padStart(4,"0")}.txt`})),s={schemaVersion:"openpond.taskIntakeSources.v1",format:e.format,previewHash:e.contentHash,files:a.map(({file:r,path:i})=>({originalPath:r.path,retainedPath:i}))};return[...a.map(({file:r,path:i})=>ob(i,new TextEncoder().encode(r.text))),ob(`${n}/manifest.json`,new TextEncoder().encode(JSON.stringify(s)))]}function H8(e,t,n){const a=Qx.parse(t);if(!n.length||new Set(n).size!==n.length)throw new Error("Select unique task records to import.");const s=[...e.tasks];for(const i of n){const c=a.records.find(p=>p.id===i);if(!c||c.kind!=="task"||c.needsContext)throw new Error("Recorded attempts and incomplete histories must be imported into Labeling for review.");const l=Gk.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=s.find(p=>p.id===l.id);if(u&&Ht(u)!==Ht(l))throw new Error(`Task ${l.id} already exists with different content. Import will not replace saved edits.`);u||s.push(l)}const r=new Map;for(const i of s)for(const c of[`family:${i.clusterKey}`,`input:${Ht(i.input)}`]){if(r.has(c)&&r.get(c)!==i.split)throw new Error("The imported task family or request already occurs in another split.");r.set(c,i.split)}return Ka.parse({...e,tasks:s})}const ta=o().trim().min(1).max(240),sr=o().trim().min(1),sw=ve(o(),ke()).default({}),rw=k(["nominated","needs_review","approved_for_creation","creating","needs_task_review","baselining","ready_for_export","rejected","dismissed","retired","blocked"]),ow=k(["no_training","prompting","retrieval","sft","preference","grpo_rft","sdft_opsd","sdpo","agentic_rl"]),yD=d({id:ta,kind:k(["repeated_success","accepted_correction","agent_action_recurrence","outcome_linked_change","frontier_cost","expert_label","runtime_feedback"]),sourceRefIds:v(ta).min(1).max(1e4),occurredAt:sr,signature:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(5e3),confidence:m().min(0).max(1),consented:j(),metadata:sw}),SD=d({frequency:m().min(0).max(1),businessValue:m().min(0).max(1),frontierCost:m().min(0).max(1),signalQuality:m().min(0).max(1),verifiability:m().min(0).max(1),repeatability:m().min(0).max(1),privacyRisk:m().min(0).max(1),overall:m().min(0).max(1)}),xD=d({tactic:ow,eligible:j(),reasons:v(o().trim().min(1).max(5e3)).min(1).max(100),blockers:v(o().trim().min(1).max(5e3)).max(100).default([]),requiredSignals:v(o().trim().min(1).max(500)).max(100).default([]),generatedBy:k(["decision_table","baseline_reassessment"])}),iw=d({schemaVersion:x("openpond.taskCandidate.v1"),id:ta,profileId:ta,status:rw,fingerprint:o().trim().min(1).max(512),title:o().trim().min(1).max(500),summary:o().trim().min(1).max(1e4),workflowSignature:o().trim().min(1).max(2e3),evidence:v(yD).min(1).max(1e5),scorecard:SD,recommendation:xD,mergedIntoId:ta.nullable(),createdAt:sr,updatedAt:sr,metadata:sw}),hu=d({schemaVersion:x("openpond.taskMinerConfig.v1"),enabled:j().default(!1),localOnly:j().default(!0),observationWindowDays:m().int().min(1).max(365).default(30),minimumRecurrence:m().int().min(2).max(100).default(3),clustering:x("hybrid_deterministic_first").default("hybrid_deterministic_first"),consentRequired:j().default(!0)});d({items:v(iw),generatedAt:sr,config:hu});d({status:rw.optional(),mergeIntoId:ta.nullable().optional()});d({profileId:ta,sourceIds:v(ta).max(1e5).default([]),sessionIds:v(ta).max(1e5).default([]),config:hu.optional()});const kD=d({schemaVersion:x("openpond.taskMinerRun.v1"),id:ta,profileId:ta,status:k(["queued","running","cancelling","cancelled","succeeded","failed"]),config:hu,sourceIds:v(ta).max(1e5),sessionIds:v(ta).max(1e5).default([]),progress:d({stage:k(["queued","ingesting","preparing","clustering","persisting","complete"]),processedSources:m().int().nonnegative(),totalSources:m().int().nonnegative(),candidatesFound:m().int().nonnegative(),skippedSources:m().int().nonnegative().default(0)}),candidateIds:v(ta).max(1e5),cancelRequested:j(),error:o().trim().min(1).max(2e4).nullable(),createdAt:sr,startedAt:sr.nullable(),completedAt:sr.nullable(),updatedAt:sr});var wD=d({id:Cn,purpose:o().trim().min(1).max(500),audience:k(["orchestrator","environment","privileged_scorer","trainer","infrastructure"]),required:j(),ttlSeconds:m().int().positive().max(86400),scopes:v(o().trim().min(1).max(500)).max(100).default([])}).strict(),ID=d({declarationId:Cn,leaseRef:o().trim().min(8).max(1e3),audience:wD.shape.audience,expiresAt:Qp}).strict(),_D=d({adapterId:Cn,placement:k(["local","remote","colocated","provider_native"]),capabilityReceipt:hn,runtimeVersion:o().trim().min(1).max(200),dataPlane:d({provider:Cn,dataPlaneId:Cn,cellId:Cn,runnerPoolId:Cn,runtimeImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/),capabilityReceipt:hn}).strict().nullable()}).strict(),CD=d({adapterId:Cn,kind:k(["local","ssh","managed","custom"]),deviceOrPool:o().trim().min(1).max(1e3),capabilityReceipt:hn,provider:Cn.nullable()}).strict(),RD=d({adapterId:Cn,workerVersion:o().trim().min(1).max(200),workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/).nullable(),upstreamRevision:o().trim().min(1).max(500),capabilityReceipt:hn}).strict(),PD=d({schemaVersion:x("openpond.harnessRunManifest.v1"),id:Cn,harnessRelease:bt,datasetRelease:bt,evidenceSets:v(bt).max(1e4),model:d({source:o().trim().min(1).max(200),revision:o().trim().min(1).max(500),artifactHash:hn.nullable(),tokenizerRevision:o().trim().min(1).max(500),chatTemplateHash:hn}).strict(),recipe:d({method:o().trim().min(1).max(100),version:o().trim().min(1).max(200),configHash:hn}).strict(),runtimeTarget:_D,computeTarget:CD,engine:RD,resolvedBundleHash:hn,secretLeaseRefs:v(ID).max(1e3),approval:d({approvalHash:hn,approvedAt:Qp,maximumSpendUsd:m().nonnegative().nullable()}).strict(),createdAt:Qp}).strict();PD.extend({contentHash:hn}).strict();var TD=d({schemaVersion:x("openpond.resolvedTrainingBundle.v1"),projection:x("trainer"),harnessRelease:bt,datasetRelease:bt,evidenceSetRelease:bt.nullable(),files:v(d({path:o().trim().min(1).max(2e3),sha256:hn,sizeBytes:m().int().nonnegative()}).strict()).max(1e5)}).strict();TD.extend({contentHash:hn}).strict();var cw=d({name:x("adamw").default("adamw"),weightDecay:m().nonnegative().max(1).default(0),beta1:m().positive().lt(1).default(.9),beta2:m().positive().lt(1).default(.999),epsilon:m().positive().max(.01).default(1e-8)}).strict().default({name:"adamw",weightDecay:0,beta1:.9,beta2:.999,epsilon:1e-8});const nt=o().trim().min(1).max(240),sa=o().trim().min(1),mi=o().trim().min(8).max(256),Gh=ve(o(),ke()).default({}),gs=nt.nullable(),AD=k(["slash_train","session_menu","bulk_selection","training_page","task_candidate"]),ED=k(["defaults","customize"]),jD=k(["automated","manual"]);d({schemaVersion:x("openpond.trainingSourceEstimate.v1"),sessionId:nt,messageCount:m().int().nonnegative(),estimatedTokens:m().int().nonnegative(),textBytes:m().int().nonnegative()});d({query:o().max(500).default(""),offset:m().int().nonnegative().default(0),limit:m().int().min(1).max(100).default(20),candidates:v(d({sessionId:nt,title:o().trim().min(1).max(500),updatedAt:sa})).max(500).default([])});const MD=d({sessionId:nt,title:o().trim().min(1).max(500),updatedAt:sa,snippet:o().max(2e3).nullable()});d({schemaVersion:x("openpond.trainingChatSearchResult.v1"),query:o(),offset:m().int().nonnegative(),limit:m().int().positive(),total:m().int().nonnegative(),hasMore:j(),indexedChats:m().int().nonnegative(),totalChats:m().int().nonnegative(),indexing:j(),entries:v(MD)});const Zh=k(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]),OD=d({graderId:nt.nullable(),path:o().trim().min(1).max(1e3),language:k(["javascript","typescript","python","json","text"]),content:o().max(2e6),sha256:mi,declaredSha256:mi.nullable(),integrity:k(["verified","unverified","mismatch"])}),$D=d({protocolVersion:o().trim().min(1).max(200),module:o().trim().min(1).max(1e3),moduleSha256:mi,command:v(o().max(2e3)).max(100),cwd:o().trim().min(1).max(4e3),maxTurns:m().int().positive().max(100)});d({schemaVersion:x("openpond.tasksetGraderDetails.v1"),taskset:Kt,sourceTasksetId:nt,graders:v(uu).max(1e3),runtime:$D.nullable(),sources:v(OD).max(1e3),unavailableReason:o().max(2e3).nullable()});const ND=d({id:nt,taskIndex:m().int().nonnegative(),label:Fh,output:ve(o(),ke()),infrastructureError:o().trim().min(1).max(1e4).nullable(),expectedPassed:j(),expectedRewardEligible:j(),metadata:Gh}),DD=d({schemaVersion:x("openpond.taskAttempt.v1"),id:nt,tasksetId:nt,taskId:nt,split:ui,attempt:m().int().nonnegative(),seed:m().int(),modelRef:ln.nullable(),startedAt:sa,completedAt:sa,output:ve(o(),ke()),runtimeEventRefs:v(nt).max(1e4).default([]),artifactRefs:v(nt).max(1e4).default([]),privilegedOutcomeRef:gs,infrastructureError:o().trim().min(1).max(1e4).nullable(),costUsd:m().nonnegative().nullable(),latencyMs:m().int().nonnegative(),userInterventions:m().int().nonnegative().default(0),metadata:Gh}),LD=d({schemaVersion:x("openpond.taskAttemptArtifact.v1"),id:nt,tasksetId:nt,taskId:nt,attemptId:nt,kind:k(["raw_model_response","runtime_trace","environment_state","grader_evidence","output_artifact"]),path:o().trim().min(1).max(4e3),mediaType:o().trim().min(1).max(200).nullable().optional(),sha256:mi,sizeBytes:m().int().nonnegative(),createdAt:sa,metadata:Gh}),zD=d({graderId:nt,graderVersion:o().trim().min(1).max(100),score:m().min(0).max(1).nullable(),passed:j(),hardGate:j(),rewardEligible:j(),feedback:o().trim().max(2e4).nullable(),evidenceRefs:v(nt).max(1e4).default([]),judge:ln.nullable().optional().default(null),calibrationStatus:k(["not_applicable","pending","passed","failed"])}),HD=d({schemaVersion:x("openpond.gradeResult.v1"),id:nt,attemptId:nt,graderSetHash:mi,score:m().min(0).max(1).nullable(),passed:j(),components:v(zD).min(1).max(1e3),failureClass:Zh.nullable(),feedback:v(o().trim().min(1).max(2e4)).max(1e3).default([]),rewardEligible:j(),rewardComposition:Ic.optional(),createdAt:sa});k(["stable_hash_top_n","rft_easy_curriculum_v1"]);const UD=d({schemaVersion:x("openpond.graderAuditReport.v1"),id:nt,tasksetId:nt,tasksetHash:mi,fixtureRefs:v(nt).min(1).max(1e5),gradeRefs:v(nt).min(1).max(1e5),passed:j(),hackingChecksPassed:j(),leakageChecksPassed:j(),infrastructureSafetyPassed:j(),failures:v(d({fixtureId:nt,label:Fh,gradeId:nt,reason:o().trim().min(1).max(5e3)})).max(1e5),createdAt:sa}),qD=d({schemaVersion:x("openpond.capabilityDiagnosis.v1"),summary:o().trim().min(1).max(1e4),stableBehavior:v(o().trim().min(1).max(5e3)).max(100).default([]),changingKnowledge:v(o().trim().min(1).max(5e3)).max(100).default([]),requiredContext:v(o().trim().min(1).max(5e3)).max(100).default([]),requiredTools:v(nt).max(100).default([]),intervention:ow,trainingEligible:j(),rationale:v(o().trim().min(1).max(5e3)).min(1).max(100),confidence:m().min(0).max(1)}),BD=d({id:nt,sourceId:nt,sourceTurnId:gs,split:ui,origin:k(["extracted","corrected","synthetic","expert_authored"]),inputPrompt:o().trim().min(1).max(1e5),expectedOutputText:o().trim().min(1).max(2e5).nullable(),rationale:o().trim().min(1).max(5e3)}),FD=d({schemaVersion:x("openpond.taskDesignProposal.v1"),id:nt,name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),diagnosis:qD.default({schemaVersion:"openpond.capabilityDiagnosis.v1",summary:"Reproduce the selected approved behavior.",stableBehavior:[],changingKnowledge:[],requiredContext:[],requiredTools:[],intervention:"sft",trainingEligible:!0,rationale:["The selected examples were supplied as demonstrations."],confidence:.5}),taskKind:Bh.shape.taskKind,sourceIds:v(nt).min(1).max(1e5),assumptions:v(o().trim().min(1).max(5e3)).max(1e3),successCriteria:v(o().trim().min(1).max(5e3)).min(1).max(1e3),proposedGraders:v(uu).max(1e3).default([]),graderFixtures:v(ND).max(1e5).default([]),generatedFiles:v(jN).max(1e3).default([]),proposedExamples:v(BD).max(1e5).default([]),proposedMethod:Fk.shape.recommendedMethod,trainingPath:qk.nullable().default(null),policy:qh,warnings:v(o().trim().min(1).max(5e3)).default([]),createdAt:sa}),VD=5;function U8(e,t="New model"){const n=e?.trim().split(/\s+/).filter(Boolean)??[];return n.length===0?t:n.slice(0,VD).join(" ")}const Jc=d({schemaVersion:x("openpond.baseModelPreference.v1"),modelId:nt,revision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:o().trim().min(8).max(256).nullable(),modelAssetId:gs,source:k(["managed","local","builtin"])}),KD=d({schemaVersion:x("openpond.taskCreationRequest.v1"),id:nt,profileId:nt,surface:AD,mode:ED,entryMode:jD.default("manual"),resourceIntent:k(["workproduct","dataset"]).default("workproduct"),buildIntent:Hk.default("demonstrations"),buildSpecification:Uk.nullable().default(null),objective:o().trim().min(1).max(2e4).nullable(),methodHint:k(["sft","dpo","grpo","ppo"]).nullable().default(null),preferredBaseModelId:nt.nullable().default(null),preferredBaseModel:Jc.nullable().default(null),sourceIds:v(nt).max(1e5),candidateId:gs,analysisModel:ln.nullable(),analysisReasoningEffort:Yd.nullable().default(null),createImproveRunId:gs.default(null),targetIntent:d({kind:k(["agent","skill","extension","model","configuration"]).nullable(),id:gs,displayName:o().trim().min(1).max(500).nullable(),operation:k(["create","improve"])}).default({kind:"model",id:null,displayName:null,operation:"create"}),disclosure:d({status:k(["not_required","pending","approved","declined"]),content:x("raw_excerpts"),sourceIds:v(nt).max(1e5),providerModel:ln.nullable(),approvalId:gs,approvedAt:sa.nullable()}).default({status:"not_required",content:"raw_excerpts",sourceIds:[],providerModel:null,approvalId:null,approvedAt:null}),createdAt:sa}),lw=d({schemaVersion:x("openpond.taskCreationSnapshot.v1"),id:nt,request:KD,state:k(["planning","awaiting_disclosure_approval","awaiting_questions","recommendation_ready","awaiting_materialization_approval","materializing","validating","ready","blocked","failed","cancelled"]),proposal:FD.nullable(),materializedTasksetId:gs,disclosureApprovalId:gs,materializationApprovalId:gs,blockingQuestions:v(d({id:nt,kind:k(["objective","consent","success_signal","privacy_licensing","interpretation"]),prompt:o().trim().min(1).max(5e3),answer:o().trim().min(1).max(2e4).nullable()})).default([]),transcript:v(d({id:nt,role:k(["user","assistant","system","tool"]),text:o().max(1e5),createdAt:sa})).max(1e4).default([]),repairHistory:v(Vk).max(1e3).default([]),blockedReason:o().trim().min(1).max(1e4).nullable(),createdAt:sa,updatedAt:sa});d({schemaVersion:x("openpond.taskCreationTranscript.v1"),creationId:nt,profileId:nt,messages:lw.shape.transcript,updatedAt:sa});d({sessionId:o().min(1).max(200),creationHash:o().regex(/^[a-f0-9]{64}$/),sessionRevision:o().regex(/^[a-f0-9]{64}$/),executionRevision:o().regex(/^[a-f0-9]{64}$/)}).strict();const it=o().trim().min(1).max(200),Vs=o().regex(/^[a-f0-9]{64}$/),gu=d({installationId:o().uuid(),profileId:it,ownerUserId:it,teamId:it,bindingId:it,bindingRevision:m().int().positive()}).strict();d({version:x(1),scope:gu,epoch:o().uuid().nullable(),runtimeId:o().uuid(),audience:o().url(),nonce:o().uuid(),issuedAt:o().datetime(),payloadHash:Vs,signature:o().regex(/^[A-Za-z0-9+/]{86}==$/)}).strict();const Jh=d({id:it,kind:k(["session","starter"]),title:o().trim().min(1).max(300),providerId:it,modelId:o().trim().min(1).max(300).nullable(),experience:k(["chat","work"]),workspaceId:it,workspaceLabel:o().trim().min(1).max(300),profileSelectionId:it.nullable(),revision:Vs,available:j(),unavailableReason:o().max(500).nullable(),canMessage:j(),canSteer:j(),canStop:j(),activeTurnId:it.nullable()}).strict(),dw=2e4;d({revision:Vs,capturedAt:o().datetime(),targets:v(Jh).max(dw)}).strict();const td=100,uw=d({revision:Vs,capturedAt:o().datetime(),targetCount:m().int().min(0).max(dw),pageCount:m().int().min(0).max(200)}).strict().refine(e=>e.pageCount===Math.ceil(e.targetCount/td),{message:"ponder_desktop_catalog_page_count_invalid"});d({catalog:uw,index:m().int().min(0).max(199),targets:Jh.array().min(1).max(td)}).strict().refine(e=>e.index<e.catalog.pageCount&&e.targets.length===Math.min(td,e.catalog.targetCount-e.index*td),{message:"ponder_desktop_catalog_page_size_invalid"});const q8=d({revision:Vs,pageIndex:m().int().min(0).max(199)}).strict();d({scope:gu,publicKey:o().min(1).max(512),runtimeId:o().uuid(),epoch:o().uuid(),authorizationRevision:m().int().positive(),reauthorizationGeneration:m().int().nonnegative().default(0),state:k(["attached","revoked"]),leaseExpiresAt:o().datetime(),catalog:uw.nullable()}).strict();const jo={targetId:it,targetRevision:Vs},ep=o().trim().min(1).max(32e3),WD=rt("action",[d({...jo,action:x("create"),prompt:ep,title:o().trim().min(1).max(300)}).strict(),d({...jo,action:x("message"),prompt:ep}).strict(),d({...jo,action:x("steer"),prompt:ep,expectedTurnId:it}).strict(),d({...jo,action:x("stop"),expectedTurnId:it}).strict(),d({...jo,action:x("observe"),expectedTurnId:it}).strict(),d({...jo,action:x("inspect"),expectedTurnId:it}).strict()]),GD=d({scope:gu,epoch:o().uuid(),originChatTurnId:it,originToolCallId:it,humanControlId:it.optional(),authorizationRevision:m().int().positive()}).strict();d({scope:gu,epoch:o().uuid(),runtimeId:o().uuid(),authorizationRevision:m().int().positive()}).strict();const ZD=d({id:it,origin:GD,payloadHash:Vs,intent:WD,target:Jh,state:k(["ready","dispatching","admitted","completed","failed","cancelled","expired","attention"]),claimId:o().uuid().nullable(),claimedEpoch:o().uuid().nullable(),expiresAt:o().datetime(),admittedAt:o().datetime().nullable(),createdAt:o().datetime(),updatedAt:o().datetime(),receipt:d({sessionId:it,sessionTitle:o().min(1).max(300),inputId:it.nullable(),turnId:it.nullable(),state:it}).strict().nullable(),error:o().max(1e3).nullable()}).strict(),JD=d({operationId:it,payloadHash:Vs,sessionId:it,sessionTitle:o().min(1).max(300),inputId:it.nullable(),turnId:it,completedAt:o().datetime(),outcome:k(["completed","failed","cancelled"]),body:o().max(128e3),bodyTruncated:j(),assistantEventIds:v(it).max(2e3),providerId:it,modelId:it.nullable(),workspaceId:it,outputs:v(d({id:it,title:o().min(1).max(300),contentType:it,sizeBytes:m().int().nonnegative(),sha256:Vs}).strict()).max(100),error:o().max(2e3).nullable()}).strict(),B8=d({version:x(1),direction:k(["sent","received"]),operationId:it,installationId:o().uuid(),profileId:it,ownerUserId:it,teamId:it,sessionId:it,title:o().min(1).max(300),turnId:it.nullable(),receiptId:it,status:it,body:o(),outputs:JD.shape.outputs}).strict(),Vo=o().trim().min(1).max(240),nd=o().trim().min(1),af=o().trim().min(8).max(256),mw=ve(o(),ke()).default({}),QD=k(["created","inspecting","awaiting_source_review","awaiting_mapping","awaiting_materialization_approval","materializing","validating","ready","cancelling","cancelled","failed"]),pw=d({schemaVersion:x("openpond.huggingFaceDatasetLocator.v1"),repositoryId:o().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:o().url().max(2e3),requestedRevision:o().trim().min(1).max(256).nullable()}),YD=d({path:o().trim().min(1).max(1e3),logicalType:o().trim().min(1).max(500),nullable:j(),sampleValues:v(ke()).max(5)}),XD=d({configuration:o().trim().min(1).max(500),split:o().trim().min(1).max(500),rowCount:m().int().nonnegative().nullable(),sizeBytes:m().int().nonnegative().nullable()}),eL=d({schemaVersion:x("openpond.huggingFaceDatasetInspection.v1"),id:Vo,locator:pw,resolvedRevision:o().trim().min(7).max(256),title:o().trim().min(1).max(500),description:o().max(2e4).nullable(),declaredLicense:o().trim().min(1).max(500).nullable(),gated:j(),private:j(),configurations:v(o().trim().min(1).max(500)).min(1).max(1e3),splits:v(XD).min(1).max(1e4),columns:v(YD).min(1).max(1e4),previewRows:v(ve(o(),ke())).max(25),sourceFiles:v(d({path:o().trim().min(1).max(2e3),configuration:o().trim().min(1).max(500),split:o().trim().min(1).max(500),revision:o().trim().min(7).max(256),sizeBytes:m().int().nonnegative().nullable(),contentHash:af.nullable()})).max(1e5),inspectedAt:nd,metadata:mw}),tL=k(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),nL=d({sourcePath:o().trim().min(1).max(1e3),target:tL,transform:k(["identity","string","json","messages","numeric","math_final_answer"]),policy:k(["visible","privileged","metadata"]),required:j()}),fw=d({schemaVersion:x("openpond.datasetImportMapping.v1"),sourceSchemaHash:af,configuration:o().trim().min(1).max(500),upstreamSplits:v(o().trim().min(1).max(500)).min(1).max(1e3),preset:k(["prompt_only","prompt_completion","messages","preference","prompt_expected_answer","prompt_privileged_solution","prompt_feedback"]),bindings:v(nL).min(1).max(1e4),nullPolicy:k(["reject","drop","preserve"]),invalidRowPolicy:k(["reject_import","drop_with_receipt"]),splitPolicy:d({seed:m().int(),assignments:ve(o(),br),validationPercent:m().min(0).max(100),frozenEvalPercent:m().min(0).max(100)}),importerVersion:o().trim().min(1).max(200),mappingHash:af}),aL=d({phase:k(["idle","metadata","download","mapping","parquet_write","verification","publish"]),completedBytes:m().int().nonnegative(),totalBytes:m().int().nonnegative().nullable(),completedRows:m().int().nonnegative(),totalRows:m().int().nonnegative().nullable(),message:o().trim().min(1).max(2e3).nullable()}),sL=d({schemaVersion:x("openpond.datasetImportJob.v1"),id:Vo,profileId:Vo,sourceKind:k(["huggingface","uploaded_file"]),status:QD,locator:pw.nullable(),inspection:eL.nullable(),mapping:fw.nullable(),progress:aL,targetStorageRoot:o().trim().min(1).max(4e3).nullable(),tasksetId:Vo.nullable(),tasksetRevision:m().int().positive().nullable(),artifactId:Vo.nullable(),error:o().trim().min(1).max(2e4).nullable(),cancellationRequested:j(),createdAt:nd,updatedAt:nd,completedAt:nd.nullable(),metadata:mw});d({profileId:Vo,url:o().trim().min(1).max(2e3)});d({name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),mapping:fw,targetStorageRoot:o().trim().min(1).max(4e3).nullable(),licenseApproved:j().default(!1)});function ht(e){let t;return new Yf({type:"object",get shape(){return t??=e()}})}var pc=o().trim().min(1).max(200),sf=d({operationId:pc,execution:bt,executionKind:x("recorded_evidence").optional(),graders:v(vr).min(1).max(100),maximumCostUsd:m().finite().min(1e-6).max(1e4),mappings:v(d({graderId:pc,fields:Kh}).strict()).max(100).optional()}).strict().superRefine((e,t)=>{new Set(e.graders.map(n=>n.id)).size!==e.graders.length&&t.addIssue({code:"custom",path:["graders"],message:"Select each grader once."}),e.mappings&&(new Set(e.mappings.map(n=>n.graderId)).size!==e.mappings.length||e.mappings.some(n=>!e.graders.some(a=>a.id===n.graderId)))&&t.addIssue({code:"custom",path:["mappings"],message:"Map each selected grader at most once."})}),rL=d({schemaVersion:x("openpond.experimentScoringPass.v1"),id:pc,teamId:pc,revision:m().int().positive(),request:sf,graders:v(fu).min(1).max(100),status:k(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:m().int().min(1).max(1e4),counts:d({pending:m().int().nonnegative(),running:m().int().nonnegative(),scored:m().int().nonnegative(),unavailable:m().int().nonnegative(),failed:m().int().nonnegative(),cancelled:m().int().nonnegative()}).strict(),resultAvailable:j(),createdAt:na(),startedAt:na().nullable(),completedAt:na().nullable(),error:d({code:pc,message:o().max(2e3)}).strict().nullable()}).strict();rL.extend({contentHash:o().regex(/^[a-f0-9]{64}$/)});var hw=d({sourcePass:bt,graders:sf.shape.graders,mappings:sf.shape.mappings,maximumCostUsd:m().finite().positive().max(1e4)}).strict(),gw=d({externalDatasetBinding:ur,scoring:hw.optional(),modelId:o().min(1).max(300),maximumCostUsd:m().finite().positive().max(1e4)}).strict(),Qh=d({source:k(["local","github","openpond_git"]),repositoryId:o().trim().min(1),profileId:o().trim().min(1)}).strict(),Pt=o().min(1).max(240),Jn=o().regex(/^[a-f0-9]{64}$/),fc=d({schemaVersion:x("openpond.experimentImprovement.v1"),id:Pt,operationId:Pt,requestHash:Jn,actorId:Pt,teamId:Pt,projectId:Pt.nullable(),ownerWorkspaceId:Pt,ownerRevision:m().int().nonnegative(),ownerSourceRevision:o().min(1).max(500),baseRelease:bt,profileRef:Qh,baseProfileSourceRevision:o().min(1).max(500),evidence:d({manifest:or,result:ir}).strict(),component:d({kind:k(["skill","workflow","agent","instruction"]),path:o().min(1).max(2e3),workflowId:Pt.optional()}).strict(),mode:k(["manual","llm_assisted"]),status:k(["draft","authoring_queued","authoring","frozen","testing","ready_for_review","adopting","accepted","rolled_back","declined","failed","cancelled"]),revision:m().int().positive(),limits:d({maximumCostUsd:m().finite().positive(),maximumAuthoringSteps:m().int().min(1).max(500),maximumDurationMs:m().int().min(1e3).max(864e5)}).strict(),authoringSteps:m().int().nonnegative().max(500),work:d({sessionId:Pt,turnId:Pt,revision:m().int().positive(),startedAt:o().datetime()}).strict().nullable(),frozen:d({release:bt,sourceRevision:o().min(1).max(500),profileSourceRevision:o().min(1).max(500),authoringHash:Jn,partitionHash:Jn,executableSourceHash:Jn,protectedClosureHash:Jn,candidateRevision:m().int().positive(),diff:v(d({path:o(),before:Jn.nullable(),after:Jn.nullable()}).strict()).max(1e4)}).strict().nullable(),test:d({recipe:gw,recipeHash:o().regex(/^[a-f0-9]{64}$/),baselineOperationId:o(),candidateOperationId:o(),cancelRequestedAt:o().datetime().nullable(),dispatching:d({kind:k(["baseline","candidate"]),token:Pt,pid:m().int().positive(),processStart:o().nullable(),startedAt:o().datetime()}).strict().nullable()}).strict().nullable(),comparison:d({baseline:d({manifest:or,result:ir}).strict(),candidate:d({manifest:or,result:ir}).strict(),frozenHash:Jn,humanProjection:nf.optional()}).strict().nullable(),adoptionIntent:d({operationId:Pt,expectedOwnerRevision:m().int().nonnegative(),frozenHash:Jn,humanProjection:nf.optional()}).strict().nullable(),acceptance:bt.nullable(),rollback:bt.nullable(),error:o().max(2e3).nullable(),createdAt:o().datetime(),updatedAt:o().datetime(),contentHash:Jn}).strict();function F8(e){const t=fc.parse(e),{contentHash:n,...a}=t;if(Ht(a)!==n)throw new Error("Improvement state integrity failed.");if(ei(t.evidence),t.evidence.manifest.teamId!==t.teamId||t.evidence.result.status!=="completed"||!t.evidence.result.cases.some(s=>s.status==="completed"))throw new Error("Improvement requires usable completed owner evidence.");if(t.test&&(Ht(t.test.recipe)!==t.test.recipeHash||Jp(t.test.recipe.externalDatasetBinding).profileId!==t.profileRef.profileId))throw new Error("The test recipe changed its exact selected Profile.");if(t.comparison?.humanProjection){const s=w2(t.comparison.humanProjection);if(s.teamId!==t.teamId||s.projectId!==t.projectId||Ht(s.baseline)!==Ht(t.comparison.baseline)||Ht(s.candidate)!==Ht(t.comparison.candidate))throw new Error("Human comparison projection differs from its exact owner evidence.")}if(t.comparison&&(ei(t.comparison.baseline),ei(t.comparison.candidate),!t.frozen||t.comparison.frozenHash!==Ht(t.frozen)||!t$(t.comparison.baseline,t.comparison.candidate).comparable))throw new Error("Improvement comparison is not bound to a comparable frozen candidate.");if(t.status==="ready_for_review"&&(!t.frozen||!t.comparison))throw new Error("Improvement is missing qualification.");if(t.status==="adopting"&&(!t.adoptionIntent||!t.frozen||t.adoptionIntent.frozenHash!==Ht(t.frozen)))throw new Error("Improvement adoption intent is not bound to its tested revision.");if(t.status==="accepted"&&(!t.acceptance||!t.comparison||!t.frozen))throw new Error("Improvement acceptance is missing its exact qualification receipt.");if(t.status==="rolled_back"&&(!t.acceptance||!t.rollback))throw new Error("Profile rollback is missing its durable owner receipt.");return t}var V8=d({states:v(fc).max(50),nextCursor:Pt.nullable()}).strict(),oL=d({operationId:Pt,ownerWorkspaceId:Pt,expectedOwnerRevision:m().int().nonnegative(),baseRelease:bt,profileRef:Qh,profileSourceRevision:o().min(1).max(500),projectId:Pt.nullable(),evidence:bt,component:fc.shape.component,mode:fc.shape.mode,limits:fc.shape.limits}).strict(),K8=rt("operation",[d({operation:x("list"),limit:m().int().min(1).max(50).default(30),cursor:Pt.optional()}).strict(),d({operation:x("options"),evidence:bt}).strict(),d({operation:x("start"),request:oL}).strict(),d({operation:k(["read","humanComparisonOptions"]),id:Pt}).strict(),d({operation:x("instructions"),id:Pt}).strict(),d({operation:x("edit"),id:Pt,revision:m().int().positive(),expectedFileHash:Jn,text:o().max(25e4)}).strict(),d({operation:x("mode"),id:Pt,revision:m().int().positive(),mode:k(["manual","llm_assisted"])}).strict(),d({operation:x("author"),id:Pt,revision:m().int().positive(),modelId:Pt,prompt:o().min(1).max(2e4)}).strict(),d({operation:k(["freeze","finishAuthoring","useCandidate","discard","cancel","rollback"]),id:Pt,revision:m().int().positive()}).strict(),d({operation:x("test"),id:Pt,revision:m().int().positive(),recipe:gw}).strict(),d({operation:x("compare"),id:Pt,revision:m().int().positive(),baseline:bt,candidate:bt,humanSelections:hk.optional()}).strict()]),vw=d({teamId:Pt,evidence:bt,scoring:hw.optional(),profiles:v(d({id:Jn,name:o(),profileRef:Qh,ownerWorkspaceId:Pt,ownerRevision:m().int().nonnegative(),baseRelease:bt,profileSourceRevision:o(),components:v(d({kind:k(["skill","instruction","agent","workflow"]),path:o(),agentId:o().optional(),workflowId:o().optional(),label:o(),binding:ur}).strict()).max(500)}).strict()).max(100)}).strict(),iL=d({candidateId:Pt,actorId:Pt,teamId:Pt,projectId:Pt.nullable(),candidateRevision:m().int().positive(),recipeHash:Jn,baseline:d({manifest:or,result:ir}).strict(),candidate:d({manifest:or,result:ir}).strict(),contentHash:Jn}).strict();function W8(e){const t=iL.parse(e),{contentHash:n,...a}=t;if(Ht(a)!==n)throw new Error("Accepted Human discovery integrity failed.");for(const s of[t.baseline,t.candidate])if(ei(s),s.manifest.teamId!==t.teamId||s.manifest.lineage?.humanProjection)throw new Error("Discovery must retain original owner evidence.");return t}var Yt=o().trim().min(1).max(240),vs=o().regex(/^[a-f0-9]{64}$/),Yh=d({schemaVersion:x("openpond.advancedRefinerEvaluation.v1"),operationId:Yt,actorId:Yt,teamId:Yt,projectId:Yt.nullable(),mode:k(["review_quality","downstream_adaptation"]),profileRef:d({source:k(["local","github","openpond_git"]),repositoryId:Yt,profileId:Yt}).strict(),sourceRevision:o().min(1).max(500),baselineRelease:bt,refinerRelease:bt,evidence:bt,externalDatasetBinding:ur,adaptationDatasetBinding:ur,privateClosureHash:vs,adaptationTaskIds:v(Yt).min(1).max(1e4),holdoutTaskIds:v(Yt).min(1).max(1e4),adaptationSplit:k(["train","validation","test","frozen_eval"]),holdoutSplit:k(["train","validation","test","frozen_eval"]),environmentPolicy:rt("kind",[d({kind:x("resettable"),environmentHash:vs}).strict(),d({kind:x("frozen_observations"),environmentHash:vs}).strict()]),maximumCostUsd:m().finite().positive().max(1e4),maximumDurationMs:m().int().min(1e3).max(864e5),maximumModelSteps:m().int().min(1).max(1e3),contentHash:vs}).strict();function G8(e){const t=Yh.parse(e),{contentHash:n,...a}=t;if(Ht(a)!==n)throw new Error("Advanced Refiner evaluation admission changed.");const s=Jp(t.externalDatasetBinding);if(s.profileId!==t.profileRef.profileId||s.protectedProfileClosureHash!==t.privateClosureHash)throw new Error("Advanced evaluation changed its Profile or protected evaluator closure.");if(t.adaptationSplit===t.holdoutSplit||new Set([...t.adaptationTaskIds,...t.holdoutTaskIds]).size!==t.adaptationTaskIds.length+t.holdoutTaskIds.length)throw new Error("Adaptation and private holdout must be disjoint ordered cases.");const r=Jp(t.adaptationDatasetBinding);if(r.profileId!==s.profileId||r.packageHash!==s.packageHash||Ht(r.dataset)!==Ht(s.dataset)||Ht(r.target)!==Ht(s.target)||r.protectedProfileClosureHash!==s.protectedProfileClosureHash)throw new Error("This native advanced adapter needs separate adaptation and holdout recipes from the same exact released package and target.");if(r.split!==t.adaptationSplit||s.split!==t.holdoutSplit)throw new Error("Advanced split policies differ from their exact admitted recipes.");const i=new Set(s.population.map(l=>l.taskId)),c=new Set(r.population.map(l=>l.taskId));if(t.holdoutTaskIds.some(l=>!i.has(l))||t.adaptationTaskIds.some(l=>!c.has(l)))throw new Error("Advanced evaluation selected cases outside its exact Dataset recipe.");return t}var cL=d({pin:Yh,modelId:Yt,profileId:Yt,model:Oh,seed:m().int(),reasoningEffort:k(["none","off","low","medium","high","xhigh","max"]).nullable()}).strict(),lL=rt("operation",[d({operation:x("start"),request:cL}).strict(),d({operation:k(["read","cancel","resume"]),id:Yt}).strict(),d({operation:x("list")}).strict()]),dL=d({taskId:Yt,sourceCaseHash:vs,reviewSessionId:Yt,reviewTurnId:Yt,inputHarness:bt,trigger:bt,decision:k(["no_action","route_deterministically","queue_refiner"]),outcome:bt.nullable(),proposal:bt.nullable(),validations:v(bt).max(100),grade:d({id:Yt,contentHash:vs,score:m().min(0).max(1).nullable(),passed:j(),failureClass:o().nullable()}).strict(),resetComplete:j()}).strict(),uL=d({schemaVersion:x("openpond.advancedRefinerReviewReceipt.v1"),id:Yt,runId:Yt,pinHash:vs,ownerActorId:Yt,teamId:Yt,privateClosureHash:vs,refinerRelease:bt,cases:v(dL).min(1).max(1e4),reviewScore:m().min(0).max(1).nullable(),completedCases:m().int().nonnegative(),noActionCases:m().int().nonnegative(),routedCases:m().int().nonnegative(),proposalCases:m().int().nonnegative(),costUsd:m().finite().nonnegative().nullable(),cleanupComplete:j(),createdAt:o().datetime(),contentHash:vs}).strict(),mb=vw.shape.profiles.element,Z8=vw.extend({profiles:v(mb.extend({components:v(mb.shape.components.element.extend({adaptationSplits:v(d({split:k(["train","validation","test","frozen_eval"]),taskIds:v(Yt)})),environmentHash:vs,resettable:j(),reviewQuality:j()}))})),refinerReleases:v(bt),activeRefiner:bt.nullable(),models:v(d({id:Yt,profileId:Yt,name:o(),location:k(["local","hosted"])}))}),mL=d({operation:x("prepare"),evidence:bt,profileOptionId:Yt,componentLabel:Yt,mode:k(["review_quality","downstream_adaptation"]),adaptationSplit:k(["train","validation","test","frozen_eval"]),operationId:Yt,refinerRelease:bt,maximumCostUsd:m().positive(),maximumDurationMs:m().int().positive(),maximumModelSteps:m().int().positive()}).strict();dt([lL,mL,d({operation:x("options"),evidence:bt}).strict()]);var pL=d({modelRequests:m().int().nonnegative(),knownSpendUsd:m().nonnegative(),totalSpendUsd:m().nonnegative().nullable(),heldUsd:m().nonnegative(),uncertainRequests:m().int().nonnegative()}).strict();const Ys=A.nullable(),Os=m().int().nonnegative(),fL=o().regex(/^[a-f0-9]{40}$/),hL=d({name:o().trim().min(1).max(160),startedAt:Ce,completedAt:Ce,durationMs:m().nonnegative(),clock:k(["monotonic","provider","wall"]),outcome:k(["succeeded","failed","cancelled"])}).strict(),gL=d({schemaVersion:x("openpond.correlatedTelemetryReceipt.v1"),stage:k(["training","evaluation","deployment","inference"]),correlation:d({modelRunId:Ys,modelVersionId:Ys,policyVersion:Os.nullable(),taskId:Ys,rolloutGroupId:Ys,providerResourceId:Ys,deploymentId:Ys,inferenceRequestId:Ys}).strict(),spans:v(hL).max(1e4),usage:d({promptTokens:Os.nullable(),generatedTokens:Os.nullable(),gpuSeconds:m().nonnegative().nullable(),workerActiveSeconds:m().nonnegative().nullable(),optimizerSteps:Os.nullable(),rolloutGroups:Os.nullable(),successfulTrajectories:Os.nullable(),failedTrajectories:Os.nullable(),peakGpuMemoryBytes:Os.nullable(),peakGpuUtilizationPercent:m().min(0).max(100).nullable()}).strict(),resource:d({provider:A,resourceIds:v(A).max(1e3),gpuType:o().trim().min(1).max(300).nullable(),gpuCount:Os.nullable(),baseProfileId:Ys,baseRepository:o().trim().min(1).max(512).nullable(),baseRevision:fL.nullable(),adapterContentHash:W.nullable()}).strict(),cost:d({currency:x("USD"),providerReportedUsd:m().nonnegative().nullable(),quotedHourlyUsd:m().nonnegative().nullable(),estimatedUsd:m().nonnegative().nullable(),methodologyVersion:o().trim().min(1).max(160),pricingInputs:ve(o().trim().min(1).max(160),m().finite()),unitEstimates:ve(o().trim().min(1).max(160),m().nonnegative())}).strict(),recordedAt:Ce,contentHash:W}).strict(),vn=o().trim().min(1).max(240),Us=o().regex(/^[a-f0-9]{64}$/),nr=o().datetime({offset:!0}),_n=d({id:vn,contentHash:Us}).strict(),vL=_n.extend({revision:m().int().positive()}).strict(),bw=d({providerId:vn,modelId:o().trim().min(1).max(300)}).strict(),vu=k(["correction","sibling_verification","cumulative_known","development","retained","frozen_final","training_eligible"]),bL=d({taskId:vn,taskContentHash:Us,panelRole:vu,passLabel:vn.nullable(),optimizerEligible:j(),criticalInvariantIds:v(vn).max(100).default([])}).strict().superRefine((e,t)=>{e.optimizerEligible!==(e.panelRole==="correction")&&t.addIssue({code:"custom",path:["optimizerEligible"],message:"Only correction cases may be optimizer eligible."})}),yL=d({schemaVersion:x("openpond.continualBenchIssuePacket.v1"),id:vn,revision:m().int().positive(),contentHash:Us,familyId:vn,familyLabel:o().trim().min(1).max(500),severity:k(["low","medium","high","critical"]),cases:v(bL).min(2).max(1e4),duplicateEvidence:_n,leakageEvidence:_n,priorExposureEvidence:_n,observedAt:nr,reviewedAt:nr,queuedAt:nr.nullable(),runAt:nr.nullable(),createdBy:vn,createdAt:nr}).strict().superRefine((e,t)=>{e.cases.some(n=>n.panelRole==="correction")||t.addIssue({code:"custom",path:["cases"],message:"An issue packet requires a correction case."}),e.cases.some(n=>n.panelRole==="sibling_verification")||t.addIssue({code:"custom",path:["cases"],message:"An issue packet requires a sibling-verification case."}),new Set(e.cases.map(n=>n.taskId)).size!==e.cases.length&&t.addIssue({code:"custom",path:["cases"],message:"Issue-packet task ids must be unique."})}),SL=d({id:vn,role:vu,passLabel:vn.nullable(),taskset:vL,familyIds:v(vn).min(1).max(1e5),taskCount:m().int().positive().max(1e6),sealedAt:nr}).strict().superRefine((e,t)=>{const n=e.role==="correction"||e.role==="sibling_verification"||e.role==="cumulative_known";n!==(e.passLabel!==null)&&t.addIssue({code:"custom",path:["passLabel"],message:n?"This panel role requires a pass label.":"This panel role is series-wide and cannot carry a pass label."})}),tp=rt("kind",[d({kind:x("base_model"),id:vn,revision:o().trim().min(1).max(500),contentHash:Us}).strict(),d({kind:x("model_version"),id:vn,contentHash:Us}).strict(),d({kind:x("external_reference"),id:vn,model:bw,providerRevision:o().trim().min(1).max(500),contentHash:Us}).strict()]),xL=d({scheduleEntryId:vn,ordinal:m().int().nonnegative(),label:vn,role:k(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),parentRule:k(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),trainableRank:m().int().positive().max(1024),correctionPanelIds:v(vn).min(1).max(1e3),optimizerGroupsPerTask:m().int().positive().max(1e3),trajectoriesPerGroup:m().int().min(4).max(1e3)}).strict(),kL=d({revision:m().int().positive(),requireAllAttemptsTerminal:x(!0),criticalCorrectionPassRate:m().min(0).max(1),siblingPassRate:m().min(0).max(1),behavioralRetentionRate:m().min(0).max(1),maximumRetainedRegressionPoints:m().min(0).max(100),blockCriticalPriorRegression:j(),authorizedClaims:v(k(["systems_complete","correction_absorbed","issue_generalized","continually_current","frontier_pareto_result"])).min(1).max(5)}).strict(),wL=d({schemaVersion:x("openpond.continualBenchmarkProtocol.v1"),id:vn,revision:m().int().positive(),contentHash:Us,ownerId:vn,createdAt:nr,sealedAt:nr,creationReceipt:_n,predecessorSeries:d({id:vn,revision:m().int().positive(),contentHash:Us}).strict().nullable(),scenarioPack:_n,issueFamilyLedger:_n,issuePacketRelease:_n,panels:v(SL).min(6).max(1e4),grader:_n,judge:d({release:_n,rubricRelease:_n,calibrationRelease:_n,model:bw}).strict().nullable(),policies:d({base:tp,master:tp.nullable(),externalReferences:v(tp).min(1).max(20)}).strict(),invariants:d({systemPromptHash:Us,toolSchema:_n,application:_n,harness:_n,runtime:_n,workerImage:_n,autoRefiner:d({enabled:j(),release:_n.nullable()}).strict()}).strict(),schedule:v(xL).min(1).max(1e3),evaluation:d({seeds:v(m().int()).min(3).max(100),repetitions:m().int().min(3).max(20),powerRule:_n,pairedBootstrapSamples:m().int().min(1e3).max(1e6),confidenceLevel:x(.95)}).strict(),resources:d({maximumTrainingGpuSeconds:m().int().positive(),maximumEvaluationGpuSeconds:m().int().positive(),maximumProviderSpendUsd:m().positive(),maximumTotalSpendUsd:m().positive(),maximumConcurrentGroups:m().int().positive().max(1e3)}).strict(),currencyThresholds:kL}).strict().superRefine((e,t)=>{const n=e.panels.map(r=>r.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["panels"],message:"Protocol panel ids must be unique."});for(const r of["development","retained","frozen_final","training_eligible"])e.panels.filter(i=>i.role===r).length!==1&&t.addIssue({code:"custom",path:["panels"],message:`A protocol requires exactly one ${r} panel.`});[...e.schedule].sort((r,i)=>r.ordinal-i.ordinal).some((r,i)=>r.ordinal!==i)&&t.addIssue({code:"custom",path:["schedule"],message:"Protocol schedule ordinals must be contiguous from zero."});const s=new Set(n);e.schedule.some(r=>r.correctionPanelIds.some(i=>!s.has(i)))&&t.addIssue({code:"custom",path:["schedule"],message:"Every scheduled correction panel must belong to the protocol."})}),IL=k(["draft","active","completed","archived"]),_L=k(["draft","ready","queued","running","candidate","accepted","rejected","no_signal","failed","cancelled"]),yw=k(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),CL=k(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),RL=k(["seed_taskset","nightly_selection","daily_cohort_union","eligible_task_pool"]),PL=k(["live_client","evaluation_attempt","replay_evidence","manual"]),TL=d({id:A,ordinal:m().int().nonnegative(),label:o().trim().min(1).max(100),role:yw,parentRule:CL,taskSource:RL,trainableRank:m().int().positive().max(1024),minimumTasks:m().int().nonnegative().max(1e5),maximumTasks:m().int().positive().max(1e5)}).strict().superRefine((e,t)=>{e.minimumTasks>e.maximumTasks&&t.addIssue({code:"custom",path:["minimumTasks"],message:"The minimum task count cannot exceed the maximum task count."});const n={seed:{parentRules:["base_model"],taskSource:"seed_taskset"},daily_residual:{parentRules:["previous_release","accepted_daily_head"],taskSource:"nightly_selection"},rank_candidate:{parentRules:["seed_release"],taskSource:"eligible_task_pool"},weekly_rollup:{parentRules:["seed_release","accepted_seed"],taskSource:"daily_cohort_union"},full_refresh:{parentRules:["base_model"],taskSource:"eligible_task_pool"}},{parentRules:a,taskSource:s}=n[e.role];a.includes(e.parentRule)||t.addIssue({code:"custom",path:["parentRule"],message:`${e.role} requires parent rule ${a.join(" or ")}.`}),e.taskSource!==s&&t.addIssue({code:"custom",path:["taskSource"],message:`${e.role} requires task source ${s}.`}),e.ordinal===0&&e.role!=="seed"&&t.addIssue({code:"custom",path:["role"],message:"The first series entry must be the seed."})}),AL=d({id:A,version:m().int().positive(),requireCheckpoint:j(),requireAppliedOptimizerUpdate:j(),minimumCurrentCohortMeanImprovement:m().finite(),maximumRetainedMeanRegression:m().finite().nonnegative(),blockCriticalInvariantRegression:j(),automaticDailyAdvancement:j()}).strict(),EL=d({schemaVersion:x("openpond.modelComparisonSeries.v1"),id:A,profileId:A,modelProjectId:A,name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),status:IL,revision:m().int().positive(),productionBinding:d({role:x("chat_manual"),roleTargetId:A}).strict(),baseModel:d({id:A,revision:o().trim().min(1).max(256)}).strict(),seedTaskset:Kt,eligibleTaskPool:Kt,evaluationTasksets:d({development:Kt,retained:Kt,frozenFinal:Kt}).strict(),grader:re,benchmarkProtocol:wL.nullable().default(null),automaticEvaluation:d({enabled:j()}).strict().default({enabled:!1}),residualProfile:d({profileId:A,serializedEnvelopeRank:m().int().positive().max(1024),maximumEnabledRank:m().int().positive().max(1024),topology:x("uniform_block_masked")}).strict(),schedule:v(TL).min(1).max(1e3),scheduleSealedAt:Ce.nullable(),advancementPolicy:AL,executionPolicy:d({startWhenReady:x(!1)}).strict(),acceptedSeedEntryId:A.nullable(),acceptedDailyHeadEntryId:A.nullable(),promotedBindingId:A.nullable(),createdBy:A,createdAt:Ce,updatedAt:Ce}).strict().superRefine((e,t)=>{[...e.schedule].sort((l,u)=>l.ordinal-u.ordinal).some((l,u)=>l.ordinal!==u)&&t.addIssue({code:"custom",path:["schedule"],message:"Schedule ordinals must be unique and contiguous from zero."}),(new Set(e.schedule.map(l=>l.id)).size!==e.schedule.length||new Set(e.schedule.map(l=>l.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(l=>`${l.id}:${l.revision}:${l.contentHash}`)).size!==a.length&&t.addIssue({code:"custom",path:["evaluationTasksets"],message:"Development, retained, and frozen-final cohorts require distinct immutable Taskset releases."});const s=e.schedule.find(l=>l.role==="seed");if(!s||e.schedule.filter(l=>l.role==="seed").length!==1){t.addIssue({code:"custom",path:["schedule"],message:"A series requires exactly one seed entry."});return}const r=e.schedule.filter(l=>l.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(l=>l.trainableRank)).size!==r.length&&t.addIssue({code:"custom",path:["schedule"],message:"Causal rank candidates must use distinct trainable ranks."}),[s.trainableRank+e.schedule.filter(l=>l.role==="daily_residual").reduce((l,u)=>l+u.trainableRank,0),...e.schedule.filter(l=>l.role==="weekly_rollup").map(l=>s.trainableRank+l.trainableRank),...e.schedule.filter(l=>l.role==="rank_candidate").map(l=>s.trainableRank+l.trainableRank),...e.schedule.filter(l=>l.role==="full_refresh").map(l=>l.trainableRank)].some(l=>l>e.residualProfile.maximumEnabledRank)&&t.addIssue({code:"custom",path:["schedule"],message:"A declared branch exceeds the maximum enabled rank."})}),Sw=d({source:PL,taskIds:v(A).min(1).max(1e5),observedFrom:Ce,observedTo:Ce,reviewedAt:Ce,reviewedBy:A,sourceTaskset:Kt}).strict(),jL=Sw.extend({derivedFamilyKeys:v(A).min(1).max(1e5),familyDerivation:d({algorithm:A,sourceTasksetHash:W}).strict(),selectionHash:W}).strict(),xw=rt("kind",[d({kind:x("base_model"),id:A,revision:o().trim().min(1).max(256)}).strict(),d({kind:x("model_version"),id:A,contentHash:W}).strict()]),ML=d({id:A,branchOrdinal:m().int().nonnegative(),rank:m().int().positive().max(1024),offsetStart:m().int().nonnegative(),offsetEnd:m().int().positive(),optimizationRole:k(["frozen","trainable"]),artifactLineageId:A.nullable()}).strict().superRefine((e,t)=>{e.offsetEnd-e.offsetStart!==e.rank&&t.addIssue({code:"custom",path:["offsetEnd"],message:"Block offsets must span exactly the declared rank."})}),OL=d({disposition:k(["advance","hold","no_signal"]),policy:d({id:A,version:m().int().positive()}).strict(),reasonCodes:v(A).min(1).max(100),summary:o().trim().min(1).max(5e3),decidedBy:A,decidedAt:Ce}).strict(),$L=d({evaluationRunId:A,modelVersionId:A,taskset:Kt,grader:re,cohortRole:k(["current","correction","sibling_verification","cumulative_known","development","retained","prior_disclosed","frozen_final"]),panelId:A.nullable().default(null),protocol:d({id:A,revision:m().int().positive(),contentHash:W}).strict().nullable().default(null)}).strict(),NL=d({attemptOrdinal:m().int().positive(),trainingPlanId:A.nullable(),modelRunId:A.nullable(),terminalStatus:k(["failed","cancelled"]),queuedAt:Ce.nullable(),startedAt:Ce.nullable(),completedAt:Ce}).strict(),pi=d({seriesId:A,entryId:A,scheduleEntryId:A,ordinal:m().int().nonnegative(),releaseHash:W}).strict(),DL=d({schemaVersion:x("openpond.modelComparisonSeriesEntry.v1"),id:A,seriesId:A,profileId:A,modelProjectId:A,scheduleEntryId:A,releaseHash:W,ordinal:m().int().nonnegative(),label:o().trim().min(1).max(100),role:yw,branch:k(["daily","rank_candidate","weekly_rollup","full_refresh"]),status:_L,parent:xw,taskset:Kt,sourceTasksets:v(Kt).min(1).max(1e3),taskSelection:jL.nullable(),trainableRank:m().int().positive().max(1024),serializedEnvelopeRank:m().int().positive().max(1024),enabledCumulativeRank:m().int().positive().max(1024),trainableBlockId:A,residualBlocks:v(ML).min(1).max(1024),attemptOrdinal:m().int().positive().default(1),priorRunAttempts:v(NL).max(100).default([]),trainingPlanId:A.nullable(),modelRunId:A.nullable(),modelVersionId:A.nullable(),evaluations:v($L).max(1e5),decision:OL.nullable(),promotionBindingId:A.nullable(),queuedAt:Ce.nullable(),startedAt:Ce.nullable(),completedAt:Ce.nullable(),createdAt:Ce,updatedAt:Ce}).strict().superRefine((e,t)=>{const n=[...e.residualBlocks].sort((i,c)=>i.offsetStart-c.offsetStart);n.some((i,c)=>i.offsetStart!==(c===0?0:n[c-1].offsetEnd))&&t.addIssue({code:"custom",path:["residualBlocks"],message:"Residual block offsets must be contiguous from zero."});const a=n.at(-1)?.offsetEnd??0;(a!==e.enabledCumulativeRank||a>e.serializedEnvelopeRank)&&t.addIssue({code:"custom",path:["enabledCumulativeRank"],message:"Enabled rank must match the block inventory and fit the envelope."});const s=e.residualBlocks.filter(i=>i.optimizationRole==="trainable");(s.length!==1||s[0]?.id!==e.trainableBlockId||s[0]?.rank!==e.trainableRank)&&t.addIssue({code:"custom",path:["trainableBlockId"],message:"Exactly one block must be trainable during the Run and match trainableRank."});const r=e.priorRunAttempts.map(i=>i.attemptOrdinal);(e.priorRunAttempts.length!==e.attemptOrdinal-1||r.some((i,c)=>i!==c+1))&&t.addIssue({code:"custom",path:["priorRunAttempts"],message:"Prior Run attempts must be a contiguous history before the active attempt."})});d({seriesId:A,scheduleEntryId:A,taskSelection:Sw.nullable(),expectedSeriesRevision:m().int().positive()}).strict();const LL=k(["base_reference","lora_adapter"]),kw=d({baseModel:d({source:x("huggingface"),repoId:A,revision:o().regex(/^[a-f0-9]{40}$/),configHash:W,tokenizerHash:W,licenseId:A,gated:j()}).strict(),processor:d({repository:A,revision:o().regex(/^[a-f0-9]{40}$/),configHash:W}).strict()}).strict().superRefine((e,t)=>{(e.baseModel.repoId!==e.processor.repository||e.baseModel.revision!==e.processor.revision)&&t.addIssue({code:"custom",path:["processor"],message:"Reward Model processor must match the pinned scorer base model."})}),zL=d({schemaVersion:x("openpond.modelVersion.v1"),id:A,modelId:A,profileId:A,version:m().int().nonnegative(),kind:LL,status:k(["available","failed"]),baseModel:Jc,taskset:Kt,comparisonSeriesEntry:pi.nullable().optional(),evaluationTasksetRef:Kt.nullable().optional(),releaseGraph:d({resolvedBundleHash:W,profileRelease:Kt,harnessRelease:re,agentRelease:re.nullable(),grader:d({id:A,contentHash:W}).strict()}).strict(),artifactLineageId:A.nullable(),adapterStatus:k(["not_trained","trained"]),createdAt:Ce,contentHash:W}).strict().superRefine((e,t)=>{e.kind==="base_reference"&&(e.version!==0||e.adapterStatus!=="not_trained"||e.artifactLineageId!==null)&&t.addIssue({code:"custom",message:"A base-reference Model Version must be version 0 without adapter lineage."}),e.kind==="lora_adapter"&&(e.version===0||e.adapterStatus!=="trained"||!e.artifactLineageId)&&t.addIssue({code:"custom",message:"A LoRA Model Version must be version 1+ with adapter lineage."})}),HL=d({schemaVersion:x("openpond.rewardModelVersion.v1"),id:A,modelId:A,profileId:A,version:m().int().positive(),role:x("reward"),status:k(["available","failed"]),scope:k(["synthetic_smoke","human_preference"]),baseModel:Jc,runtime:kw.nullable().default(null),taskset:Kt,preferenceDatasetRelease:re,releaseGraph:d({resolvedBundleHash:W,profileRelease:Kt,harnessRelease:re,grader:d({id:A,contentHash:W}).strict()}).strict(),artifacts:d({checkpoint:re.extend({objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:v(d({path:o().trim().min(1).max(512),sizeBytes:m().int().positive(),sha256:W}).strict()).min(4).max(128)}).strict(),adapter:re,scalarHead:re,bucketHead:re.nullable(),processorRelease:re}).strict(),qualificationReport:re.nullable(),createdAt:Ce,contentHash:W}).strict(),UL=d({schemaVersion:x("openpond.rewardModelRunReceipt.v1"),provider:A,providerRunId:A,resolvedBundleHash:W,finalCheckpoint:re.extend({objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/)}).strict(),adapter:re,scalarHead:re,bucketHead:re.nullable(),processorRelease:re,optimizerEvidence:re,managedExecutionReceipt:re.nullable().default(null),parameterDeltaHash:W,cleanup:d({computeReleased:j(),providerTerminalObserved:j()}).strict(),contentHash:W}).strict(),qL=oE(e=>{if(!e||typeof e!="object"||Array.isArray(e))return e;const t=e;if(t.tasksetRelease!==void 0)return e;const n=t.taskset;if(!n||typeof n!="object"||Array.isArray(n))return e;const a=n;return typeof a.id!="string"||typeof a.contentHash!="string"?e:{...t,tasksetRelease:{id:a.id,contentHash:a.contentHash}}},d({schemaVersion:x("openpond.rewardModelRun.v1"),id:A,rewardModelId:A,rewardModelVersionId:A.nullable(),profileId:A,role:x("reward"),scope:k(["synthetic_smoke","human_preference"]),status:k(["prepared","running","succeeded","failed","cancelled"]),taskset:Kt,tasksetRelease:re,preferenceDatasetRelease:re,recipeRelease:re,destinationId:A,quote:d({maximumSpendUsd:m().positive(),hourlyCostUsd:m().nonnegative().nullable()}).strict(),managedRunId:A.nullable(),progress:d({completedSteps:m().int().nonnegative(),totalSteps:m().int().positive(),latestLoss:m().finite().nullable()}).strict(),receipt:UL.nullable(),qualificationReport:re.nullable(),accruedSpendUsd:m().nonnegative().nullable(),failureOwner:k(["authoring","admission","provider","runner","artifact","qualification","cleanup"]).nullable(),failure:o().trim().min(1).max(5e3).nullable(),startedAt:Ce,completedAt:Ce.nullable(),updatedAt:Ce}).strict()).superRefine((e,t)=>{e.status==="succeeded"&&!e.receipt&&t.addIssue({code:"custom",message:"A successful Reward Model Run requires a canonical receipt."}),e.status!=="succeeded"&&e.rewardModelVersionId!==null&&t.addIssue({code:"custom",message:"Only a successful Reward Model Run can publish a Reward Model Version."})}),BL=d({schemaVersion:x("openpond.modelRunReceipt.v1"),provider:A,providerRunId:A,assignmentHash:W,resultHash:W,transcriptHash:W,traceHash:W.nullable(),resolvedBundleHash:W,artifactPath:o().trim().min(1).max(2e3),cleanup:d({computeReleased:j(),tunnelClosed:j()}).strict(),telemetry:gL.nullable().default(null),contentHash:W}).strict(),er=d({inputTokens:m().int().nonnegative(),outputTokens:m().int().nonnegative(),totalTokens:m().int().nonnegative(),costUsd:m().nonnegative().nullable()}).strict(),pb=o().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),Xh=d({phase:k(["baseline","adaptation","candidate_adaptation","candidate"]),taskId:A,attemptId:A,sessionId:A.nullable(),turnId:A.nullable(),passed:j(),score:m().min(0).max(1).nullable(),failureClass:Zh.nullable(),inputTokens:m().int().nonnegative(),outputTokens:m().int().nonnegative(),totalTokens:m().int().nonnegative(),latencyMs:m().int().nonnegative(),costUsd:m().nonnegative().nullable(),startedAt:Ce}).strict(),fb=d({targetTaskCount:m().int().nonnegative(),comparedTaskCount:m().int().nonnegative(),passedTaskCount:m().int().nonnegative(),failedTaskCount:m().int().nonnegative(),lowerTaskCount:m().int().nonnegative(),higherTaskCount:m().int().nonnegative(),unchangedTaskCount:m().int().nonnegative()}).strict(),ww=d({target:x("all_tasks_lower"),targetTaskCount:m().int().nonnegative(),comparedTaskCount:m().int().nonnegative(),passedTaskCount:m().int().nonnegative(),failedTaskCount:m().int().nonnegative(),lowerTaskCount:m().int().nonnegative(),higherTaskCount:m().int().nonnegative(),unchangedTaskCount:m().int().nonnegative(),baselineTokens:m().int().nonnegative(),refinedTokens:m().int().nonnegative(),tokenDelta:m().int(),tokenDeltaPercent:m().finite().nullable(),complete:j(),passed:j(),cohorts:d({adaptation:fb,heldOut:fb}).strict()}).strict(),eg=d({baseline:er,adaptation:er,candidateAdaptation:er,candidate:er,refiner:er,grader:er}).strict(),FL=d({usage:eg,observedSpendUsd:m().nonnegative(),attempts:v(Xh).max(1e4)}).strict(),VL=d({id:A,contentHash:W,artifactPath:o().trim().min(1).max(2e3)}).strict(),KL=d({schemaVersion:x("openpond.modelEvaluationReceipt.v1"),benchmarkId:A,resultManifest:d({id:A,contentHash:W,artifactPath:o().trim().min(1).max(2e3)}).strict(),stages:d({baseline:re,adaptation:re,refiner:re,candidateAdaptation:re,candidate:re,comparison:re}).strict(),usage:eg,quality:d({baselinePassRate:m().min(0).max(1),candidatePassRate:m().min(0).max(1),adaptationBaselinePassRate:m().min(0).max(1),adaptationCandidatePassRate:m().min(0).max(1),adaptationCandidatePassed:j(),heldOutCandidatePassed:j(),passed:j()}).strict(),foregroundTokenDelta:m().int(),foregroundTokenDeltaPercent:m().finite().nullable(),taskEfficiency:ww.optional(),efficiency:d({grossForegroundTokenSavings:m().int(),overheadTokens:m().int().nonnegative(),firstPassNetTokenSavings:m().int(),breakEvenReuseCount:m().int().nonnegative().nullable(),amortizedTokenSavings:m().int(),amortizedReuseCount:m().int().positive()}).strict(),budget:d({maximumSpendUsd:m().nonnegative(),observedSpendUsd:m().nonnegative(),enforced:j()}).strict(),evidenceSnapshot:re,lineage:d({adaptationEvidenceHash:W,refinerInputHash:W,refinerOutcomeHash:W,validationHash:W,applyReceiptHash:W,candidateRelease:re,valid:j()}).strict(),invalidReasons:v(o().trim().min(1).max(2e3)).max(100),attempts:v(Xh).max(1e4).default([]),terminalClassification:k(["improved","no_improvement","regressed","inconclusive","cancelled","infrastructure_failure"]),profileGit:d({ref:o().trim().min(1).max(2e3),commit:pb,baseCommit:pb}).strict().nullable(),contentHash:W}).strict(),WL=d({schemaVersion:x("openpond.modelEvaluationStopReceipt.v1"),benchmarkId:A,terminalClassification:x("inconclusive"),stopReason:k(["candidate_harness_unchanged","candidate_lineage_invalid"]),reason:o().trim().min(1).max(5e3),stoppedAfter:x("refiner"),baselineHarness:re,candidateHarness:re,refiner:d({id:A,contentHash:W,outcomeCount:m().int().nonnegative()}).strict(),usage:eg,budget:d({maximumSpendUsd:m().nonnegative(),observedSpendUsd:m().nonnegative(),enforced:j()}).strict(),evidenceSnapshot:re,attempts:v(Xh).max(1e4),contentHash:W}).strict(),hb=d({level:x(.95),lower:m().finite(),upper:m().finite()}).strict().superRefine((e,t)=>{e.lower>e.upper&&t.addIssue({code:"custom",message:"A confidence interval's lower bound cannot exceed its upper bound."})}),GL=d({schemaVersion:x("openpond.modelComparisonBenchmarkReceipt.v1"),benchmarkId:x("model-comparison"),target:d({kind:k(["base_model","model_version","external_reference"]),label:o().trim().min(1).max(300),modelVersionId:A.nullable(),model:ln.nullable()}).strict(),taskset:Kt,grader:re,sampling:d({seeds:v(m().int()).min(1).max(100),repetitions:m().int().positive().max(20)}).strict(),deterministic:d({attemptedTaskCount:m().int().nonnegative(),completedTaskCount:m().int().nonnegative(),passedTaskCount:m().int().nonnegative(),failedTaskCount:m().int().nonnegative(),meanScore:m().finite().nullable(),passRate:m().min(0).max(1).nullable(),passRateCi95:hb.nullable()}).strict(),judge:d({judgeModel:ln,judgeRelease:re,rubricRelease:re,calibrationRelease:re,score:m().min(0).max(100),scoreCi95:hb,comparisonCount:m().int().positive(),wins:m().int().nonnegative(),ties:m().int().nonnegative(),losses:m().int().nonnegative(),referenceLabel:o().trim().min(1).max(300)}).strict().superRefine((e,t)=>{e.wins+e.ties+e.losses!==e.comparisonCount&&t.addIssue({code:"custom",message:"Judge win, tie, and loss counts must equal comparisonCount."})}).nullable(),attempts:v(d({attemptId:A.nullable().default(null),taskId:A,seed:m().int(),repetition:m().int().nonnegative(),status:k(["succeeded","failed"]),deterministicScore:m().finite().nullable(),passed:j().nullable(),judgeScore:m().min(0).max(100).nullable(),judgePreference:k(["win","tie","loss"]).nullable(),transcriptHash:W.nullable(),traceHash:W.nullable(),transcriptArtifact:d({artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3)}).strict().nullable().default(null),traceArtifact:d({artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3)}).strict().nullable().default(null),latencyMs:m().int().nonnegative().nullable().default(null),failureClass:Zh.nullable()}).strict()).max(1e5),usage:d({policy:er.nullable(),judge:er.nullable(),observedSpendUsd:m().nonnegative().nullable(),evaluationGpuSeconds:m().nonnegative().nullable().default(null)}).strict(),managedServing:d({jobId:A,terminalState:k(["completed","cancelled","failed","budget_exhausted"]),sourcePolicyVersion:m().int().nonnegative(),sourceAdapterSha256:W.nullable(),servedPolicyVersion:m().int().nonnegative().nullable(),servedAdapterSha256:W.nullable(),accruedSpendUsd:m().nonnegative(),cleanupAttestationHash:W,resourceCount:m().int().nonnegative(),activeResourceCount:x(0)}).strict().nullable().default(null),evidenceSnapshot:d({id:A,contentHash:W,artifactPath:o().trim().min(1).max(2e3)}).strict(),completedAt:Ce,contentHash:W}).strict().superRefine((e,t)=>{const n=e.deterministic;n.completedTaskCount>n.attemptedTaskCount&&t.addIssue({code:"custom",message:"Completed task count cannot exceed attempted task count."}),n.passedTaskCount+n.failedTaskCount!==n.completedTaskCount&&t.addIssue({code:"custom",message:"Passed and failed task counts must equal completed task count."}),n.completedTaskCount===0!=(n.meanScore===null)&&t.addIssue({code:"custom",message:"Deterministic mean score is available exactly when tasks completed."}),n.completedTaskCount===0!=(n.passRate===null)&&t.addIssue({code:"custom",message:"Deterministic pass rate is available exactly when tasks completed."})}),ZL=d({advancedEvaluation:Yh.optional(),benchmarkId:x("harness-refiner"),model:ln,upstreamModel:d({providerId:A,modelId:o().trim().min(1).max(300),revision:o().trim().min(1).max(300),pricing:d({version:o().trim().min(1).max(300),source:o().trim().min(1).max(300),effectiveAt:Ce,inputUsdPerMillionTokens:m().nonnegative(),cachedInputUsdPerMillionTokens:m().nonnegative(),outputUsdPerMillionTokens:m().nonnegative()}).strict().optional()}).strict(),reasoningEffort:o().trim().min(1).max(100).nullable(),seeds:v(m().int()).min(1).max(100),repetitions:m().int().positive().max(20),maximumSpendUsd:m().nonnegative(),attemptPlan:v(d({stage:k(["baseline","adaptation","candidate_adaptation","candidate"]),split:o().trim().min(1).max(100),taskIds:v(A).min(1).max(1e5),attemptCount:m().int().positive()}).strict()).length(4)}).strict(),JL=d({benchmarkId:x("model-comparison"),target:d({kind:k(["base_model","model_version","external_reference"]),label:o().trim().min(1).max(300),modelVersionId:A.nullable(),model:ln.nullable()}).strict(),grader:re,judge:d({model:ln,release:re,rubricRelease:re,calibrationRelease:re,referenceLabel:o().trim().min(1).max(300)}).strict().nullable(),seeds:v(m().int()).min(1).max(100),repetitions:m().int().positive().max(20),maximumSpendUsd:m().nonnegative(),series:d({id:A,protocol:d({id:A,revision:m().int().positive(),contentHash:W}).strict()}).strict().nullable().default(null),panel:d({id:A,role:k(["correction","sibling_verification","cumulative_known","development","retained","frozen_final"]),passLabel:A.nullable()}).strict().nullable().default(null),comparisonPair:d({entryId:A,parent:xw,candidateModelVersionId:A}).strict().nullable().default(null),attemptPlan:v(d({stage:x("comparison"),split:o().trim().min(1).max(100),taskIds:v(A).min(1).max(1e5),attemptCount:m().int().positive()}).strict()).length(1)}).strict(),QL=dt([ZL,JL]),YL=d({schemaVersion:x("openpond.modelRun.v1"),id:A,modelId:A,modelVersionId:A.nullable(),profileId:A,kind:k(["rollout_smoke","training","evaluation"]),status:k(["prepared","running","succeeded","failed","cancelled"]),method:k(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]).nullable(),destinationId:A.nullable(),taskset:Kt,comparisonSeriesEntry:pi.nullable().optional(),evaluationTasksetRef:Kt.nullable().optional(),harnessRelease:re.nullable().optional(),quote:d({maximumSpendUsd:m().nonnegative(),hourlyCostUsd:m().nonnegative().nullable()}).strict().nullable(),evaluation:QL.nullable().default(null),evaluationProgress:d({stage:k(["baseline","adaptation","refiner","candidate_adaptation","candidate","comparison"]),completedAttempts:m().int().nonnegative(),totalAttempts:m().int().positive(),accounting:FL.nullable().default(null),advancedAccounting:pL.optional(),evidenceSnapshot:VL.nullable().default(null)}).strict().nullable().default(null),reward:d({raw:m(),components:ve(o(),m())}).strict().nullable(),receipt:dt([BL,KL,WL,GL,uL]).nullable(),adapterArtifactLineageId:A.nullable(),failure:o().trim().min(1).max(5e3).nullable(),startedAt:Ce,completedAt:Ce.nullable(),updatedAt:Ce}).strict().superRefine((e,t)=>{e.status==="succeeded"&&!e.receipt&&t.addIssue({code:"custom",message:"A successful Model Run requires a canonical receipt."}),e.kind==="evaluation"&&(e.method!==null||e.destinationId!==null||!e.evaluation||e.adapterArtifactLineageId!==null)&&t.addIssue({code:"custom",message:"An evaluation Model Run requires evaluation configuration and cannot claim training method, destination, or adapter lineage."}),e.kind==="evaluation"&&e.receipt&&e.receipt.schemaVersion!=="openpond.modelEvaluationReceipt.v1"&&e.receipt.schemaVersion!=="openpond.modelEvaluationStopReceipt.v1"&&e.receipt.schemaVersion!=="openpond.modelComparisonBenchmarkReceipt.v1"&&e.receipt.schemaVersion!=="openpond.advancedRefinerReviewReceipt.v1"&&t.addIssue({code:"custom",message:"An evaluation Model Run requires an evaluation receipt."}),e.kind!=="evaluation"&&(e.method===null||e.destinationId===null||e.quote===null)&&t.addIssue({code:"custom",message:"A training or rollout Model Run requires method, destination, and quote."}),e.kind==="rollout_smoke"&&e.adapterArtifactLineageId!==null&&t.addIssue({code:"custom",message:"A rollout smoke cannot claim adapter artifacts."})});function J8(e){const t=new Map;for(const w of e.attempts){const C=`${w.phase}\0${w.taskId}`,P=t.get(C);(!P||w.startedAt>P.startedAt||w.startedAt===P.startedAt&&w.attemptId>P.attemptId)&&t.set(C,w)}const n=[...t.values()],a=[["adaptation","adaptation","candidate_adaptation"],["held_out","baseline","candidate"]].flatMap(([w,C,P])=>{const _=new Map(n.filter(M=>M.phase===P).map(M=>[M.taskId,M]));return n.filter(M=>M.phase===C).flatMap(M=>{const E=_.get(M.taskId);return E?[{cohort:w,taskId:M.taskId,baseline:M,refined:E,tokenDelta:E.totalTokens-M.totalTokens}]:[]})}),s=new Set(n.filter(w=>w.phase==="baseline"||w.phase==="adaptation").map(w=>w.taskId)).size,r=e.targetTaskCount??s;if(!Number.isInteger(r)||r<0)throw new Error("Benchmark task-efficiency target must be a non-negative integer.");const i={adaptation:new Set(n.filter(w=>w.phase==="adaptation").map(w=>w.taskId)).size,held_out:new Set(n.filter(w=>w.phase==="baseline").map(w=>w.taskId)).size},c=(w,C)=>({targetTaskCount:C,comparedTaskCount:w.length,passedTaskCount:w.filter(P=>P.tokenDelta<0).length,failedTaskCount:w.filter(P=>P.tokenDelta>=0).length,lowerTaskCount:w.filter(P=>P.tokenDelta<0).length,higherTaskCount:w.filter(P=>P.tokenDelta>0).length,unchangedTaskCount:w.filter(P=>P.tokenDelta===0).length}),l=c(a,r),u=a.reduce((w,C)=>w+C.baseline.totalTokens,0),p=a.reduce((w,C)=>w+C.refined.totalTokens,0),f=p-u,S=a.length===r;return{summary:ww.parse({target:"all_tasks_lower",...l,baselineTokens:u,refinedTokens:p,tokenDelta:f,tokenDeltaPercent:u>0?f/u*100:null,complete:S,passed:S&&l.passedTaskCount===r,cohorts:{adaptation:c(a.filter(w=>w.cohort==="adaptation"),i.adaptation),heldOut:c(a.filter(w=>w.cohort==="held_out"),i.held_out)}}),pairs:a}}const XL=k(["measuring","up_to_date","needs_attention"]),ez=k(["fixed","retained","regressed","unresolved","unavailable"]),gb=d({evaluationRunId:A,attemptKey:A,artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3),transcriptHash:W.nullable(),traceHash:W.nullable()}).strict(),rf=d({level:x(.95),lower:m().finite(),upper:m().finite()}).strict(),tz=d({panelId:A,panelRole:vu,passLabel:A.nullable(),taskset:Kt,attempted:m().int().nonnegative(),available:m().int().nonnegative(),passed:m().int().nonnegative(),strictSuccess:m().min(0).max(1).nullable(),strictSuccessCi95:rf.nullable(),judgeScore:m().min(0).max(100).nullable(),judgeScoreCi95:rf.nullable()}).strict(),nz=d({schemaVersion:x("openpond.modelCurrencySnapshot.v1"),id:A,contentHash:W,seriesId:A,protocol:d({id:A,revision:m().int().positive(),contentHash:W}).strict(),entryId:A,passLabel:A,parent:rt("kind",[d({kind:x("base_model"),id:A,revision:o().trim().min(1).max(500)}).strict(),d({kind:x("model_version"),id:A,contentHash:W}).strict()]),candidate:d({kind:x("model_version"),id:A,contentHash:W}).strict(),sources:d({evaluationRunIds:v(A).max(1e5),attemptIds:v(A).max(1e6),tasksets:v(Kt).max(1e4),grader:re,judge:re.nullable(),calibration:re.nullable()}).strict(),matches:v(d({key:A,panelId:A,panelRole:vu,taskId:A,issueFamilyId:A,seed:m().int(),repetition:m().int().nonnegative(),classification:ez,parentPassed:j().nullable(),candidatePassed:j().nullable(),parentAttempt:gb.nullable(),candidateAttempt:gb.nullable()}).strict()).max(1e6),taskIds:d({fixed:v(A).max(1e6),retained:v(A).max(1e6),regressed:v(A).max(1e6),unresolved:v(A).max(1e6),unavailable:v(A).max(1e6)}).strict(),panels:v(tz).max(1e4),metrics:d({knownIssueCoverage:m().min(0).max(1).nullable(),issueFamilyGeneralization:m().min(0).max(1).nullable(),behavioralRetention:m().min(0).max(1).nullable(),currentAcquisitionDelta:m().finite().nullable(),retainedDeltaPoints:m().finite().nullable(),frontierStrictDelta:m().finite().nullable(),pairedPValue:m().min(0).max(1).nullable(),wins:m().int().nonnegative(),ties:m().int().nonnegative(),losses:m().int().nonnegative()}).strict(),statistics:d({matchedAttemptCount:m().int().nonnegative(),strictDelta:m().finite().nullable(),strictDeltaCi95:rf.nullable(),exactPairedBinaryPValue:m().min(0).max(1).nullable(),pairedBootstrapSamples:m().int().positive()}).strict(),criteria:d({allRequiredAttemptsTerminal:j(),criticalCorrectionPassRate:m().min(0).max(1).nullable(),siblingPassRate:m().min(0).max(1).nullable(),behavioralRetentionRate:m().min(0).max(1).nullable(),retainedRegressionPoints:m().finite().nullable(),criticalPriorRegressionCount:m().int().nonnegative(),thresholdRelease:re}).strict(),efficiency:d({inputTokens:m().int().nonnegative(),outputTokens:m().int().nonnegative(),totalTokens:m().int().nonnegative(),costUsd:m().nonnegative().nullable(),latencyMs:m().int().nonnegative(),tokensPerSuccess:m().nonnegative().nullable(),throughputPerHour:m().nonnegative().nullable(),gpuSeconds:m().nonnegative().nullable()}).strict(),invariants:d({systemPromptHash:W,toolSchema:re,application:re,harness:re,runtime:re,grader:re,autoRefinerEnabled:j()}).strict(),evidenceState:XL,evidenceReasons:v(A).max(100),projectedAt:Ce}).strict(),ad=rt("kind",[d({kind:x("base_model"),id:A,revision:o().trim().min(1).max(500),label:o().trim().min(1).max(300)}).strict(),d({kind:x("model_version"),id:A,label:o().trim().min(1).max(300)}).strict(),d({kind:x("captured_model"),id:A,label:o().trim().min(1).max(300)}).strict()]),hc=dt([d({source:x("evaluation_run").default("evaluation_run"),evaluationRunId:A,attemptId:A,modelLabel:o().trim().min(1).max(300).nullable().default(null),modelVersionId:A.nullable().default(null),reward:m().finite().nullable(),components:ve(o(),m().finite()).default({})}).strict(),d({source:x("imported_response"),modelLabel:o().trim().min(1).max(300),modelVersionId:A.nullable().default(null),response:ke().refine(e=>e!==void 0,"An imported model response is required."),reward:m().finite().nullable().default(null),components:ve(o(),m().finite()).default({})}).strict()]),az=dt([d({taskId:A,target:ad,attempt:hc}).strict(),d({taskId:A,target:k(["base","current"]).default("current"),attempt:hc}).strict(),d({taskId:A,target:k(["base","current"]).default("current"),evaluationRunId:A,attemptId:A,reward:m().finite().nullable(),components:ve(o(),m().finite()).default({})}).strict().transform(({taskId:e,target:t,...n})=>({taskId:e,target:t,attempt:{source:"evaluation_run",modelLabel:null,modelVersionId:null,...n}}))]);d({schemaVersion:x("openpond.continualLearningDailyBatchManifest.v1"),id:A,seriesId:A,scheduleEntryId:A,dayOrdinal:m().int().positive().max(1e4),sourceTaskset:Kt,taskIds:v(A).min(1).max(1e3),observedAttempts:v(az).max(1e3).default([]),sourceFileName:o().trim().min(1).max(500).nullable().default(null),availableAt:Ce}).strict().superRefine((e,t)=>{new Set(e.taskIds).size!==e.taskIds.length&&t.addIssue({code:"custom",path:["taskIds"],message:"A daily batch cannot repeat a task."}),new Set(e.observedAttempts.map(a=>`${a.taskId}:${oz(a.target)}`)).size!==e.observedAttempts.length&&t.addIssue({code:"custom",path:["observedAttempts"],message:"An intake batch cannot repeat a task and Policy target pair."});const n=new Set(e.taskIds);e.observedAttempts.some(a=>!n.has(a.taskId))&&t.addIssue({code:"custom",path:["observedAttempts"],message:"Observed attempts must belong to tasks in the daily batch."})});const sz=d({schemaVersion:x("openpond.continualLearningDailyBatch.v1"),id:A,seriesId:A,scheduleEntryId:A,dayOrdinal:m().int().positive().max(1e4),label:o().trim().min(1).max(100),runMode:k(["automatic","manual"]).optional(),source:k(["json_upload","sealed_fixture"]),sourceFileName:o().trim().min(1).max(500).nullable(),sourceTaskset:Kt,tasks:v(d({taskId:A,taskContentHash:W,familyKey:A,disposition:k(["include","defer","exclude"]).nullable(),oracleReview:k(["pending","confirmed","needs_correction"]),note:o().trim().max(2e3),observedAttempt:hc.nullable(),baselineAttempt:hc.nullable().default(null),responses:v(d({target:ad,attempt:hc}).strict()).max(100).default([]),stagedAt:Ce.nullable().default(null),queuedEntry:pi.nullable().default(null)}).strict()).min(1).max(1e3),intakeEvaluation:d({status:k(["awaiting","running","ready","failed"]),requestedTargets:v(k(["base","current"])).max(2).default(["base","current"]),requestedPolicies:v(ad).max(100).default([]),runs:v(d({target:ad,runId:A}).strict()).max(100).default([]),baselineRunId:A.nullable(),currentRunId:A.nullable(),currentPolicy:rt("kind",[d({kind:x("base_model"),id:A}).strict(),d({kind:x("model_version"),id:A}).strict()]).nullable(),failure:o().trim().min(1).max(2e3).nullable()}).strict().default({status:"awaiting",requestedTargets:["base","current"],requestedPolicies:[],runs:[],baselineRunId:null,currentRunId:null,currentPolicy:null,failure:null}),status:k(["pending","reviewed","queued"]),queuedEntry:pi.nullable(),reviewedBy:A.nullable(),reviewedAt:Ce.nullable(),availableAt:Ce,revision:m().int().positive(),createdAt:Ce,updatedAt:Ce}).strict().superRefine((e,t)=>{new Set(e.tasks.map(a=>a.taskId)).size!==e.tasks.length&&t.addIssue({code:"custom",path:["tasks"],message:"A daily batch cannot repeat a task."});for(const[a,s]of e.tasks.entries()){const r=s.responses.map(i=>Iw(i.target));new Set(r).size!==r.length&&t.addIssue({code:"custom",path:["tasks",a,"responses"],message:"A task cannot repeat a model response target."})}const n=e.tasks.every(a=>a.disposition!==null&&a.oracleReview!=="pending"&&(a.oracleReview!=="needs_correction"||a.note.length>0));e.status!=="pending"&&!n&&t.addIssue({code:"custom",path:["tasks"],message:"Every task requires a decision and oracle review before the day completes."}),e.status==="queued"!=(e.queuedEntry!==null)&&t.addIssue({code:"custom",path:["queuedEntry"],message:"Only a queued day carries an exact series-entry reference."}),e.status==="pending"&&(e.reviewedAt!==null||e.reviewedBy!==null)&&t.addIssue({code:"custom",path:["reviewedAt"],message:"A pending day cannot carry reviewer completion identity."}),e.status!=="pending"&&(e.reviewedAt===null||e.reviewedBy===null)&&t.addIssue({code:"custom",path:["reviewedAt"],message:"Reviewed identity is required after a day review completes."})}),rz=d({schemaVersion:x("openpond.continualBenchIssueReview.v1"),id:A,seriesId:A,scheduleEntryId:A,passLabel:A,packet:yL,splitManifest:d({id:A,contentHash:W}).strict(),decisions:v(d({taskId:A,disposition:k(["include","defer","exclude"]).nullable(),note:o().trim().max(2e3)}).strict()).min(2).max(1e4),status:k(["pending","reviewed","queued"]),queuedEntry:pi.nullable(),reviewedBy:A.nullable(),reviewedAt:Ce.nullable(),revision:m().int().positive(),createdAt:Ce,updatedAt:Ce}).strict().superRefine((e,t)=>{const n=[...e.packet.cases.map(r=>r.taskId)].sort(),a=[...e.decisions.map(r=>r.taskId)].sort();JSON.stringify(n)!==JSON.stringify(a)&&t.addIssue({code:"custom",path:["decisions"],message:"Review decisions must cover the exact issue-packet cases."});const s=e.decisions.every(r=>r.disposition!==null&&r.note.length>0);e.status!=="pending"&&!s&&t.addIssue({code:"custom",path:["decisions"],message:"Every case requires a disposition and note before review completes."}),e.status==="queued"!=(e.queuedEntry!==null)&&t.addIssue({code:"custom",path:["queuedEntry"],message:"Only a queued review carries an exact series-entry reference."})}).readonly();function Iw(e){return`${e.kind}:${e.id}`}function oz(e){return typeof e=="string"?e:Iw(e)}const La=o().trim().min(1).max(240),ya=o().trim().min(8).max(256),_w=k(["grpo","dapo","gspo-token"]),Ac=d({id:La,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:ya}),iz=d({maxRollouts:m().int().positive().max(1e6),maxEnvironmentExecutions:m().int().positive().max(1e6),maxInputTokens:m().int().positive(),maxOutputTokens:m().int().positive(),maxOptimizerSteps:m().int().positive().max(1e6),wallTimeMs:m().int().positive(),maximumCostUsd:m().nonnegative().nullable()}),cz=d({method:x("grpo"),groupSize:m().int().min(2).max(128),normalization:x("group_standardized"),advantageEpsilon:m().positive().max(.01).default(1e-8),loss:_w,clipRange:m().positive().max(1).default(.2),iterations:m().int().min(2).max(16).default(2),microbatchSize:m().int().positive().max(128).default(1),gradientAccumulationSteps:m().int().positive().max(128).default(1),adamw:cw}),Cw=d({method:x("ppo"),valueModel:Ac,gamma:m().min(0).max(1),gaeLambda:m().min(0).max(1),policyClip:m().positive().max(1),valueClip:m().positive().max(10),valueLossCoefficient:m().nonnegative().max(10),ppoEpochs:m().int().positive().max(100),minibatchSize:m().int().positive().max(1e5)}),lz=rt("method",[cz,Cw]),Rw=d({rewardModelVersion:d({id:La,contentHash:ya}).strict(),qualificationReport:d({id:La,contentHash:ya}).strict().nullable().default(null),evaluationReferences:v(d({id:La,contentHash:ya}).strict()).max(1e3).default([]),checkpoint:d({id:La,contentHash:ya,objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:v(d({path:o().trim().min(1).max(512),sizeBytes:m().int().positive(),sha256:ya}).strict()).min(4).max(128)}).strict(),runtime:kw,processorRelease:d({id:La,contentHash:ya}).strict(),rewardComposerRelease:d({id:La,contentHash:ya}).strict(),executionReceipt:d({id:La,contentHash:ya}).strict()}).strict(),Pw=d({schemaVersion:x("openpond.policyOptimization.v1"),policyModel:Ac,referenceModel:Ac,dataset:d({tasksetId:La,tasksetHash:ya,split:x("train"),selectionStrategy:k(["stable_hash_top_n","rft_easy_curriculum_v1"]),selectionSeed:m().int(),maxExamples:m().int().positive().max(1e5)}),sampler:d({temperature:m().min(0).max(2),topP:m().min(0).max(1),maxOutputTokens:m().int().positive().max(32768),maxTurns:m().int().positive().max(1e3),concurrency:m().int().positive().max(1e3)}),environment:d({id:La,version:o().trim().min(1).max(256),toolContractHash:ya}),reward:d({graderId:La,graderHash:ya,learnedPreference:Rw.nullable().default(null)}),kl:d({coefficient:m().nonnegative().nullable(),referenceConstraint:x("fixed_reference")}),budgets:iz,checkpointEverySteps:m().int().positive(),seed:m().int(),evaluationSplit:x("frozen_eval"),optimizer:lz}),ge=o().trim().min(1).max(240),It=o().trim().min(1),tt=o().trim().min(8).max(256),Qc=ve(o(),ke()).default({}),Tw=d({schemaVersion:x("openpond.localModelChatConfiguration.v1").default("openpond.localModelChatConfiguration.v1"),profile:k(["efficient","full_harness","custom"]).default("efficient"),systemPromptMode:k(["lean","full_harness","custom"]).default("lean"),customSystemPrompt:o().max(2e4).nullable().default(null),contextWindowTokens:m().int().min(128).max(32768).default(1024),maxOutputTokens:m().int().min(1).max(512).default(64),temperature:m().min(0).max(2).default(0),repetitionPenalty:m().min(.5).max(2).default(1.1),noRepeatNgramSize:m().int().min(0).max(10).default(3),compaction:k(["off","when_needed"]).default("when_needed"),keepWarmSeconds:m().int().min(0).max(3600).default(300),updatedAt:It.nullable().default(null)}),dz=Tw.parse({}),uz=d({schemaVersion:x("openpond.managedAdapterServingProjection.v1"),teamId:ge.nullable().default(null),source:x("sandbox_managed_rl"),sourceRef:ge,canonicalArtifactId:ge.nullable(),canonicalArtifactState:k(["imported_unvalidated","evaluating","promotable","rejected","deleted"]).nullable(),canonicalDeploymentId:ge.nullable(),canonicalDeploymentState:k(["requested","deploying","ready","degraded","deleting","deleted","failed"]).nullable(),state:k(["pending","imported","ready","failed"]),customerBindingAllowed:j().default(!1),artifactContentHash:tt.nullable().default(null),baseProfileId:ge.nullable().default(null),publishedAt:It.nullable(),lastSyncedAt:It,lastError:o().trim().min(1).max(5e3).nullable()});function Q8(e){const t=e.managedServing;return!!(t?.source==="sandbox_managed_rl"&&t.canonicalArtifactState==="promotable"&&t.customerBindingAllowed)}function Aw(e){return e.state==="ready"&&e.canonicalArtifactState==="promotable"&&e.canonicalDeploymentState==="ready"&&e.customerBindingAllowed&&!!e.teamId&&!!e.canonicalArtifactId&&!!e.canonicalDeploymentId}function Y8(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"&&Aw(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_customer_binding",evaluationArtifactId:null,canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null}function X8(e){const t=e.managedServing;return t?Aw(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_serving",canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null:{kind:"source_artifact",canonicalArtifactId:null,canonicalDeploymentId:null}}const tg="openpond.crossSystemOperations.v1",eG="1.0.0",Ew="openpond.crossSystemTools.v1",mz=["search_crm","query_billing","search_support","run_python"],pz=k(["train","validation","frozen_eval"]),fz=k(["easy","medium","hard"]),hz=k(["renewal_risk_v2"]);k(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]);d({seed:m().int().nonnegative(),split:pz,difficulty:fz,scenarioProfile:hz.optional()});const np={anyOf:[{type:"string",minLength:1,maxLength:256},{type:"null"}],default:null},ap={type:"integer",minimum:1,maximum:50,default:25},jw=[{name:"search_crm",description:"Search synthetic CRM accounts and contacts. Results are scoped, projected, paginated, and budgeted.",parameters:{type:"object",additionalProperties:!1,required:["query","fields","cursor","limit"],properties:{query:{type:"string",minLength:1,maxLength:500},fields:{type:"array",minItems:1,maxItems:12,uniqueItems:!0,items:{type:"string",enum:["account_id","name","aliases","contact_ids","contract_value_usd_cents","renewal_date","tier","active_contract_id","contract_term_months"]}},cursor:np,limit:ap}}},{name:"query_billing",description:"Query synthetic invoices and payments for explicit account IDs and a bounded date range.",parameters:{type:"object",additionalProperties:!1,required:["account_ids","date_range","status","cursor","limit"],properties:{account_ids:{type:"array",minItems:1,maxItems:50,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:100}},date_range:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",format:"date"},to:{type:"string",format:"date"}}},status:{type:"array",minItems:1,maxItems:6,uniqueItems:!0,items:{type:"string",enum:["open","overdue","paid","disputed","scheduled","void"]}},cursor:np,limit:ap}}},{name:"search_support",description:"Search synthetic support cases for explicit account IDs, severity, and state filters.",parameters:{type:"object",additionalProperties:!1,required:["account_ids","severity","state","cursor","limit"],properties:{account_ids:{type:"array",minItems:1,maxItems:50,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:100}},severity:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{type:"string",enum:["P1","P2","P3","P4"]}},state:{type:"array",minItems:1,maxItems:5,uniqueItems:!0,items:{type:"string",enum:["new","investigating","waiting_customer","resolved","closed"]}},cursor:np,limit:ap}}},{name:"run_python",description:"Run standard-library-only Python in the persistent synthetic attempt sandbox with strict limits and no network.",parameters:{type:"object",additionalProperties:!1,required:["code"],properties:{code:{type:"string",minLength:1,maxLength:1e4}}}}],Yc=Cz({schemaVersion:Ew,tools:jw}),gz=[`Use only the four registered synthetic Cross-System Operations tools. Contract ${Yc}.`,"Treat every filter as exact. An overdue-only query_billing call returns invoice rows; payment rows are included only when paid is requested.","For cross-system joins, retrieve the bounded projected rows and use run_python for date filtering, set intersection, and arithmetic before answering.","Finish with ANSWER: JSON."].join(" "),vz=15;function bz(e="auto"){return[gz,"LOCAL TOOL PROTOCOL (strict):","Use only the registered functions below. Never invent, rename, or call any other tool.","For one tool call, output exactly one JSON object and no prose:",'{"type":"tool_call","name":"registered_name","arguments":{}}',"Tool results arrive as exactly one JSON object:",'{"type":"tool_result","name":"registered_name","ok":true,"result":{},"error":null}','After one tool result, either call one registered tool again or answer normally. A JSON final may use {"type":"final","content":"..."}.',`Tool choice: ${JSON.stringify(e)}. Maximum tool turns: ${vz}.`,`Registered tool signatures: ${jw.map(yz).join("; ")}`].join(`
110
- `)}bz();function yz(e){const t=Pd(e.parameters),n=Pd(t.properties),a=Mw(t.required),s=Object.fromEntries(a.map(r=>[r,sd(n[r])]));return`${e.name}(${JSON.stringify(s)})`}function sd(e){const t=Pd(e),n=of(t.anyOf);if(n.length)return n.map(sd).join("|");const a=of(t.enum);if(a.length)return a.join("|");if(t.type==="array")return[sd(t.items)];if(t.type==="object"){const s=Pd(t.properties),r=Mw(t.required);return Object.fromEntries(r.map(i=>[i,sd(s[i])]))}return typeof t.type=="string"?t.type:"unknown"}function Pd(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function of(e){return Array.isArray(e)?e:[]}function Mw(e){return of(e).filter(t=>typeof t=="string")}const Td=k(mz),Sz=rt("kind",[d({kind:x("model"),turn:m().int().nonnegative(),content:o().max(1e5)}),d({kind:x("tool_call"),turn:m().int().nonnegative(),callId:o().trim().min(1).max(240),name:Td,arguments:ve(o(),ke())}),d({kind:x("tool_result"),turn:m().int().nonnegative(),callId:o().trim().min(1).max(240),name:Td,ok:j(),result:ke(),rows:m().int().nonnegative(),bytes:m().int().nonnegative(),durationMs:m().int().nonnegative(),error:o().trim().min(1).max(2e4).nullable()}),d({kind:x("final"),turn:m().int().nonnegative(),content:o().max(1e5)})]),xz=d({schemaVersion:x(tg),id:o().trim().min(1).max(240),worldId:o().trim().min(1).max(240),taskId:o().trim().min(1).max(240),toolContractHash:x(Yc),modelRef:d({providerId:o().trim().min(1),modelId:o().trim().min(1)}).nullable(),status:k(["completed","budget_exhausted","cancelled","infrastructure_failure"]),steps:v(Sz).max(1e3),startedAt:o().trim().min(1),completedAt:o().trim().min(1),infrastructureError:o().trim().min(1).max(2e4).nullable(),metadata:ve(o(),ke()).default({})}),kz=d({schemaVersion:x(tg),trajectoryId:o().trim().min(1).max(240),outcome:k(["correct","incorrect","parse_failure","budget_exhausted","tool_schema_violation","infrastructure_failure","cancelled"]),reward:m().min(0).max(1.15).nullable(),rewardEligible:j(),exactAnswer:j(),components:d({exactAnswer:m().min(0).max(1),efficiency:m().min(0).max(.1),conciseOutput:m().min(0).max(.05)}),metrics:d({toolCalls:m().int().nonnegative(),rowsRead:m().int().nonnegative(),bytesRead:m().int().nonnegative(),consecutiveRetrievalCalls:m().int().nonnegative(),wallTimeMs:m().int().nonnegative(),parseFailures:m().int().nonnegative(),budgetExhausted:j()}),parsedAnswer:ke().nullable(),feedback:v(o().trim().min(1).max(5e3)).max(100)}),wz=d({id:o().trim().min(1).max(240),type:x("function"),function:d({name:Td,arguments:o().max(2e4)})}),Ow=d({role:k(["system","user","assistant","tool"]),content:o().max(2e5).nullable(),tool_call_id:o().trim().min(1).max(240).optional(),tool_calls:v(wz).max(4).optional()});d({schemaVersion:x(tg),id:o().trim().min(1).max(240),taskId:o().trim().min(1).max(240),worldId:o().trim().min(1).max(240),trajectoryId:o().trim().min(1).max(240),toolContractHash:x(Yc),approval:d({status:x("approved"),approvedBy:o().trim().min(1).max(240),approvedAt:o().trim().min(1)}),messages:v(Ow).min(3).max(1e3)});const Iz=d({tasksetTaskId:o().trim().min(1).max(240),environmentTaskId:o().trim().min(1).max(240),family:k(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]),prompt:o().trim().min(1).max(1e5),finalAnswer:o().trim().min(1).max(2e5),trajectoryId:o().trim().min(1).max(240),trajectoryHash:o().trim().min(8).max(256),toolNames:v(Td).min(1).max(100),toolCallCount:m().int().positive(),messageCount:m().int().min(3),reward:m().min(0).max(1.15),messages:v(Ow).min(3).max(1e3)}),_z=d({status:x("approved"),approvedBy:o().trim().min(1).max(240),approvedAt:o().trim().min(1),previewHash:o().trim().min(8).max(256),trajectoryCount:m().int().positive()});d({schemaVersion:x("openpond.crossSystemExpertBootstrapPreview.v1"),tasksetId:o().trim().min(1).max(240),tasksetHash:o().trim().min(8).max(256),tasksetRevision:m().int().positive(),previewHash:o().trim().min(8).max(256),toolContractHash:x(Yc),status:k(["ready_for_review","approved"]),approval:_z.nullable(),tasks:v(Iz).min(1).max(100)});function Cz(e){const t=cf(e);let n=2166136261,a=2654435769;for(let s=0;s<t.length;s+=1){const r=t.charCodeAt(s);n=Math.imul(n^r,16777619),a=Math.imul(a^r,2246822507)}return`${Ew}:${vb(n)}${vb(a)}`}function cf(e){return Array.isArray(e)?`[${e.map(cf).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${cf(n)}`).join(",")}}`:JSON.stringify(e)}function vb(e){return(e>>>0).toString(16).padStart(8,"0")}const Rz=d({schemaVersion:x("openpond.singleTurnPolicyTrajectory.v1"),id:ge,taskId:ge,status:k(["completed","infrastructure_failure"]),promptHash:tt,responseText:o().max(2e6),infrastructureError:o().trim().min(1).max(1e4).nullable(),startedAt:It,completedAt:It,metadata:Qc}),Pz=d({schemaVersion:x("openpond.ppoTrajectory.v1"),id:ge,taskId:ge,policyModelId:ge,referenceModelId:ge,valueModelId:ge,steps:v(d({index:m().int().nonnegative(),observationHash:tt,actionTokenIds:v(m().int().nonnegative()).min(1),terminated:j(),truncated:j(),reward:m(),policyLogProbability:m(),referenceLogProbability:m(),valuePrediction:m(),return:m(),advantage:m(),mask:m().min(0).max(1)})).min(1).max(1e5),createdAt:It}),Tz=d({schemaVersion:x("openpond.exactAnswerVerifierResult.v1"),outcome:k(["correct","incorrect","parse_failure","infrastructure_failure"]),graderSetHash:tt,score:m().min(0).max(1).nullable(),passed:j(),rewardEligible:j(),expectedAnswerHash:tt,extractedAnswer:o().max(2e4).nullable(),feedback:v(o().trim().min(1).max(2e4)).max(1e3)}),Az=d({schemaVersion:x("openpond.rolloutTrajectoryReceipt.v1"),id:ge,jobId:ge,planId:ge,tasksetId:ge,tasksetHash:tt,taskId:ge,split:x("train"),correlationId:ge,provider:ge,providerTrace:d({invocationId:ge,experimentId:ge,rolloutId:ge,runId:ge,rowId:ge}),optimizerMethod:k(["grpo","ppo"]).default("grpo"),evidenceLevels:d({requested:k(["trajectory","aggregate","provider_reported"]),observed:k(["trajectory","aggregate","provider_reported"]),providerReported:k(["trajectory","aggregate","provider_reported"])}).default({requested:"trajectory",observed:"trajectory",providerReported:"provider_reported"}),budgetUsage:d({rollouts:m().int().nonnegative(),environmentExecutions:m().int().nonnegative(),inputTokens:m().int().nonnegative(),outputTokens:m().int().nonnegative(),optimizerSteps:m().int().nonnegative(),costUsd:m().nonnegative()}).default({rollouts:0,environmentExecutions:0,inputTokens:0,outputTokens:0,optimizerSteps:0,costUsd:0}),environment:d({id:ge,version:o().trim().min(1).max(256),worldId:ge,worldHash:tt,toolContractHash:tt}),policy:d({modelId:ge,checkpointId:ge.nullable(),completionParametersHash:tt}),status:k(["received","running","succeeded","failed"]),failureClass:k(["policy_failure","parse_failure","tool_schema_violation","budget_exhausted","cancelled","environment_failure","infrastructure_failure"]).nullable(),reward:d({eligible:j(),raw:m().min(0).max(1.15).nullable(),normalized:m().min(0).max(1).nullable(),components:ve(o(),m())}),trajectory:dt([xz,Rz,Pz]).nullable(),verifier:dt([kz,Tz]).nullable(),providerStatus:ve(o(),ke()).default({}),receivedAt:It,startedAt:It.nullable(),completedAt:It.nullable(),updatedAt:It}),tG="dataset-exact-answer",nG="dataset-exact-answer-v1",aG="no-tools-v1",yr=k(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),bu=k(["lora","full"]),to=k(["openpond_managed"]),Ez=ht(()=>({schemaVersion:x("openpond.sftRecipe.v1"),method:x("sft"),parameterization:x("lora"),baseModel:d({id:ge,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:tt}),dataset:d({trainSplit:x("train"),validationSplit:k(["validation","frozen_eval"]),completionOnly:j(),maxSequenceLength:m().int().positive().max(32768),maxExamples:m().int().positive().max(1e5).default(1e3),selectionStrategy:x("stable_hash_top_n").default("stable_hash_top_n"),selectionSeed:m().int().default(17)}),lora:d({rank:m().int().positive().max(256),alpha:m().positive().max(1024),dropout:m().min(0).max(1),targetModules:v(ge).min(1).max(100)}),optimizer:d({learningRate:m().positive(),epochs:m().positive().max(100),maxSteps:m().int().positive().max(1e6),batchSize:m().int().positive().max(1e4),gradientAccumulationSteps:m().int().positive().max(1e4),seed:m().int()}),resourceLimits:d({cpuThreads:m().int().positive().max(256),memoryBytes:m().int().positive(),wallTimeMs:m().int().positive()})}));ht(()=>({id:ge,input:ve(o(),ke()),expectedOutput:ve(o(),ke()),tags:v(ge).max(100).default([])}));ht(()=>({id:ge,prompt:o().min(1).max(5e5),chosen:o().min(1).max(5e5),rejected:o().min(1).max(5e5),sourceRefs:v(ge).min(1).max(1e4)}));ht(()=>({id:ge,input:ve(o(),ke()),tags:v(ge).max(100).default([])}));ht(()=>({schemaVersion:x("openpond.rewardModelRecipe.v1"),method:x("reward_model"),parameterization:x("lora_with_scalar_head"),runScope:k(["synthetic_smoke","human_preference"]),baseModel:d({id:ge,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),processorRevision:o().trim().min(1).max(256),chatTemplateHash:tt}).strict(),tasksetRelease:re,preferenceDatasetRelease:re,processorRelease:re,input:d({kind:x("structured_text"),serialization:k(["scenario_input_and_candidate_json_v1","visible_agent_trajectory_v1"]),maxCharacters:m().int().positive().max(5e5)}).strict().default({kind:"structured_text",serialization:"scenario_input_and_candidate_json_v1",maxCharacters:32e3}),lora:d({rank:m().int().positive().max(256),alpha:m().positive().max(1024),dropout:m().min(0).max(1),targetModules:v(ge).min(1).max(100)}).strict(),heads:d({scalar:x("pooled_hidden_state_linear"),bucket:k(["none","three_class"]).default("three_class")}).strict(),loss:d({ranking:x("bradley_terry"),rankingWeight:m().positive(),bucketWeight:m().nonnegative(),tieWeight:m().nonnegative()}).strict(),optimizer:d({learningRate:m().positive(),maxSteps:m().int().positive().max(1e5),batchSize:m().int().positive().max(1e4),gradientAccumulationSteps:m().int().positive().max(1e4),seed:m().int(),checkpointEverySteps:m().int().positive().max(1e5)}).strict(),resourceLimits:d({wallTimeMs:m().int().positive().max(1440*60*1e3),maxExamples:m().int().positive().max(1e5),maxInputCharacters:m().int().positive().max(5e5).default(32e3),maxImagePixels:m().int().positive().max(1e8).optional(),maximumSpendUsd:m().nonnegative().max(1e5)}).strict()})).superRefine((e,t)=>{e.runScope==="synthetic_smoke"&&(e.optimizer.maxSteps>100||e.resourceLimits.maximumSpendUsd>10)&&t.addIssue({code:"custom",path:["resourceLimits"],message:"Synthetic-smoke Reward Model runs are limited to 100 steps and USD 10."})});const jz=ht(()=>({schemaVersion:x("openpond.rftRecipe.v1"),method:x("grpo"),parameterization:x("lora"),baseModel:d({id:ge,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:tt}),dataset:d({trainSplit:x("train"),validationSplit:k(["validation","frozen_eval"]),maxPromptTokens:m().int().positive().max(32768),maxExamples:m().int().positive().max(1e5).default(1e3),selectionStrategy:k(["stable_hash_top_n","rft_easy_curriculum_v1"]).default("stable_hash_top_n")}),lora:d({rank:m().int().positive().max(256)}),rollout:d({groupSize:m().int().min(2).max(64),concurrency:m().int().positive().max(32),maxTurns:m().int().positive().max(100),maxOutputTokens:m().int().positive().max(8192),temperature:m().min(0).max(2),topP:m().positive().max(1),seed:m().int()}),optimizer:d({learningRate:m().positive(),maxSteps:m().int().positive().max(1e5),clipRange:m().positive().max(1).default(.2),iterations:m().int().min(2).max(16).default(2),microbatchSize:m().int().positive().max(64).default(1),gradientAccumulationSteps:m().int().positive().max(64).default(1),advantageEpsilon:m().positive().max(.01).default(1e-8),adamw:cw}),loss:d({method:_w.default("grpo"),klBeta:m().min(0).nullable().default(null)}).default({method:"grpo",klBeta:null}),reward:d({graderId:ge,graderHash:tt,environmentId:ge,environmentVersion:o().trim().min(1).max(256),toolContractHash:tt,learnedPreference:Rw.nullable().optional()}),resourceLimits:d({wallTimeMs:m().int().positive().max(1440*60*1e3),maxGpuSeconds:m().int().positive().max(10800).optional(),maxRollouts:m().int().positive().max(1e5),maxPayloadBytes:m().int().positive().max(10*1024*1024)}),policyOptimization:Pw.nullable().default(null),continuation:d({schemaVersion:x("openpond.crossJobContinuationRequest.v1"),parentArtifact:re,sourceArtifact:d({jobId:ge,artifactId:ge,checkpointId:ge,contentHash:tt}).strict(),optimizerMode:k(["continue","reset"])}).strict().optional()})),Mz=ht(()=>({schemaVersion:x("openpond.dpoRecipe.v1"),method:x("dpo"),parameterization:x("lora"),policyModel:Ac,referenceModel:Ac,dataset:d({trainSplit:x("train"),validationSplit:k(["validation","frozen_eval"]),maxPairs:m().int().positive().max(1e5),maxPromptTokens:m().int().positive().max(32768),maxCompletionTokens:m().int().positive().max(32768),selectionStrategy:x("stable_hash_top_n"),selectionSeed:m().int()}),lora:d({rank:m().int().positive().max(256),alpha:m().positive().max(1024),dropout:m().min(0).max(1),targetModules:v(ge).min(1).max(100)}),loss:d({variant:x("sigmoid"),beta:m().positive().max(10),labelSmoothing:m().min(0).max(.5).default(0)}),optimizer:d({learningRate:m().positive(),epochs:m().positive().max(100),maxSteps:m().int().positive().max(1e6),batchSize:m().int().positive().max(1e4),gradientAccumulationSteps:m().int().positive().max(1e4),seed:m().int()}),referenceLogprobs:d({cacheSchemaVersion:x("openpond.dpoReferenceLogprobs.v1"),cacheKey:tt,invalidationHash:tt}),resourceLimits:d({cpuThreads:m().int().positive().max(256),memoryBytes:m().int().positive(),wallTimeMs:m().int().positive()})})),Oz=ht(()=>({schemaVersion:x("openpond.ppoRecipe.v1"),method:x("ppo"),parameterization:x("lora"),policyOptimization:Pw.extend({optimizer:Cw}),lora:d({rank:m().int().positive().max(256),alpha:m().positive().max(1024),dropout:m().min(0).max(1),targetModules:v(ge).min(1).max(100)}),valueHead:d({initialization:x("policy_hidden_state_linear"),optimizerLearningRate:m().positive(),artifactName:x("value_head.safetensors")}),policyLearningRate:m().positive(),resume:d({checkpointId:ge.nullable(),policyHash:tt,referenceHash:tt,valueModelHash:tt,optimizerStateHash:tt.nullable()}),resourceLimits:d({cpuThreads:m().int().positive().max(256),memoryBytes:m().int().positive(),wallTimeMs:m().int().positive()})})),$z=ht(()=>({schemaVersion:x("openpond.unsupportedRecipe.v1"),method:yr.exclude(["sft","dpo","grpo","ppo"]),parameterization:bu,unsupportedReason:o().trim().min(1).max(5e3)})),Nz=dt([Ez,Mz,jz,Oz,$z]),Dz=ht(()=>({schemaVersion:x("openpond.trainingDestinationCapabilities.v1"),destinationId:to,available:j(),methods:v(yr),parameterizations:v(bu),modelAllowlist:v(ge).default([]),maxDatasetBytes:m().int().nonnegative().nullable(),environmentPlacements:v(k(["none","local","remote","colocated","provider_native"])),nonProduction:j(),unavailableReason:o().trim().min(1).max(5e3).nullable(),checkedAt:It})),Lz=ht(()=>({destinationId:to,available:j(),methods:v(yr),parameterizations:v(bu),nonProduction:j(),unavailableReason:o().trim().min(1).max(5e3).nullable()})),zz=ht(()=>({schemaVersion:x("openpond.baseModelCandidate.v1"),selectionKey:ge,label:o().trim().min(1).max(500),sourceLabel:o().trim().min(1).max(500),preference:Jc,available:j(),nonProduction:j(),unavailableReason:o().trim().min(1).max(5e3).nullable(),methods:v(yr),executionOptions:v(Lz).min(1)})),Hz=ht(()=>({code:ge,severity:k(["warning","error"]),path:o().trim().max(2e3).nullable(),message:o().trim().min(1).max(5e3)})),Uz=ht(()=>({schemaVersion:x("openpond.trainingCompatibility.v1"),compatible:j(),destinationId:to,tasksetId:ge,recipeMethod:yr,issues:v(Hz),checkedAt:It})),qz=dt([Bk,k(["destination_unavailable","destination_method_unsupported","destination_model_unsupported","destination_parameterization_unsupported","experimental_destination"])]);ht(()=>({method:yr,state:k(["recommended","compatible","needs_dataset_work","destination_unavailable","experimental_destination"]),reasonCodes:v(qz).default([]),reasons:v(o().trim().min(1).max(5e3)).default([]),destinationId:to.nullable().default(null)}));k(["small","standard","custom","small_experiment"]);const Bz=uk,$w=ht(()=>({schemaVersion:x("openpond.trainingPlan.v1"),id:ge,modelId:ge,tasksetId:ge,tasksetHash:tt,comparisonSeriesEntry:pi.nullable().optional(),evaluationTasksetRef:Kt.nullable().optional(),harnessRelease:re.nullable().optional(),modelImprovementQualification:re.nullable().optional(),destinationId:to,recipe:Nz,environmentPlacement:k(["none","local","remote","colocated","provider_native"]),compatibility:Uz,dataPolicy:d({exportApproved:j(),approvedSourceIds:v(ge),retentionDays:m().int().nonnegative().nullable(),region:o().trim().min(1).max(200).nullable()}),estimatedCostUsd:m().nonnegative().nullable(),createdAt:It,contentHash:tt})),Fz=ht(()=>({path:o().trim().min(1).max(2e3),sha256:tt,sizeBytes:m().int().nonnegative(),role:k(["manifest","task_data","grader","environment","recipe","policy","provenance"])})),ng=ht(()=>({schemaVersion:x("openpond.trainingBundle.v1"),id:ge,planId:ge,tasksetId:ge,tasksetHash:tt,recipeHash:tt,files:v(Fz).min(1).max(1e6),totalSizeBytes:m().int().nonnegative(),sourceIds:v(ge),excludedSourceIds:v(ge),containsRawChats:x(!1),containsSecrets:x(!1),containsHiddenGraderAssets:x(!1),createdAt:It,contentHash:tt}));ht(()=>({schemaVersion:x("openpond.trainingBundleExport.v1"),manifest:ng,files:v(d({path:o().trim().min(1).max(2e3),sha256:tt,sizeBytes:m().int().nonnegative(),encoding:x("base64"),content:o()})).min(1),contentHash:tt}));ht(()=>({schemaVersion:x("openpond.trainingPreparedStart.v1"),plan:$w,bundle:ng,approvalActor:ge.nullable(),preparedAt:It}));ht(()=>({schemaVersion:x("openpond.trainingApproval.v1"),evaluationTasksetRef:Kt.nullable().optional(),id:ge,planId:ge,bundleHash:tt,harnessRelease:re.nullable().optional(),modelImprovementQualification:re.nullable().optional(),destinationId:to,modelId:ge,method:yr,parameterization:bu,maximumCostUsd:m().nonnegative().nullable(),approvedBy:ge,approvedAt:It}));ht(()=>({schemaVersion:x("openpond.trainingJobSourceSnapshot.v1"),evaluationTasksetRef:Kt.nullable().optional(),modelProjectId:ge,sourceProjectRevision:m().int().positive(),profileId:ge,taskset:d({id:ge,revision:m().int().positive(),contentHash:tt}).strict(),tasksetRelease:re,harnessRelease:re,baseModel:Jc,method:yr})).strict();const Vz=k(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),Nw=ht(()=>({schemaVersion:x("openpond.trainingJob.v1"),id:ge,planId:ge,bundleHash:tt,approvalId:ge,destinationId:to,status:Vz,nonProduction:j(),workerPid:m().int().positive().nullable(),startedAt:It.nullable(),completedAt:It.nullable(),error:o().trim().min(1).max(2e4).nullable(),createdAt:It,updatedAt:It,metadata:Qc})),Kz=ht(()=>({schemaVersion:x("openpond.trainingJobEvent.v1"),id:ge,jobId:ge,sequence:m().int().nonnegative(),type:k(["queued","start","progress","metric","checkpoint","cancel","complete","failure","reconcile"]),timestamp:It,payload:Qc})),Wz=ht(()=>({schemaVersion:x("openpond.sftStepMetric.v1"),step:m().int().nonnegative(),maxSteps:m().int().positive(),timestamp:It,epoch:m().nonnegative().nullable(),loss:m().nullable(),learningRate:m().nonnegative().nullable(),gradientNorm:m().nonnegative().nullable(),entropy:m().nonnegative().nullable(),meanTokenAccuracy:m().min(0).max(1).nullable(),preferenceAccuracy:m().min(0).max(1).nullable().default(null),preferenceMargin:m().nullable().default(null),chosenReward:m().nullable().default(null),rejectedReward:m().nullable().default(null),chosenLogProbability:m().nullable().default(null),rejectedLogProbability:m().nullable().default(null),reward:m().nullable().default(null),policyLoss:m().nullable().default(null),advantageLoss:m().nullable().default(null),inputTokensSeen:m().int().nonnegative().nullable(),memoryBytes:m().int().nonnegative().nullable(),elapsedSeconds:m().nonnegative().nullable()})),Gz=ht(()=>({schemaVersion:x("openpond.policyOptimizationMetric.v1"),method:k(["grpo","ppo"]),step:m().int().nonnegative(),timestamp:It,learningRate:m().nonnegative().nullable().default(null),policyLoss:m().nullable(),valueLoss:m().nullable(),gradientNorm:m().nonnegative().nullable().default(null),meanReward:m().nullable(),meanReturn:m().nullable(),kl:m().nullable(),behaviorPolicyKlPreUpdate:m().nonnegative().nullable().default(null),entropy:m().nullable(),policyClipFraction:m().min(0).max(1).nullable(),behaviorPolicyClipFractionPreUpdate:m().min(0).max(1).nullable().default(null),valueClipFraction:m().min(0).max(1).nullable(),explainedVariance:m().nullable(),rolloutLearnerLag:m().int().nonnegative().nullable(),inputTokens:m().int().nonnegative(),outputTokens:m().int().nonnegative(),environmentExecutions:m().int().nonnegative(),trajectoryCount:m().int().nonnegative().nullable().default(null),costUsd:m().nonnegative().nullable()})),Zz=ht(()=>({schemaVersion:x("openpond.managedTrainingRunEvidence.v2"),provider:ge,providerRunId:ge,state:ge,progress:d({targetOptimizerSteps:m().int().nonnegative(),committedOptimizerSteps:m().int().nonnegative(),skippedOptimizerSteps:m().int().nonnegative()}),reward:d({finalMean:m().nullable(),variance:m().nonnegative().nullable(),minimum:m().nullable(),maximum:m().nullable(),distinctValueCount:m().int().nonnegative(),noSignalGroupCount:m().int().nonnegative(),trajectoryCount:m().int().nonnegative(),eligibleTrajectoryCount:m().int().nonnegative()}),usage:d({inputTokens:m().int().nonnegative(),outputTokens:m().int().nonnegative(),environmentExecutions:m().int().nonnegative()}),resource:d({provider:ge,gpuType:o().trim().min(1).max(300).nullable(),gpuCount:m().int().nonnegative().nullable(),hourlyCostUsd:m().nonnegative().nullable(),durationSeconds:m().nonnegative().nullable(),gpuSeconds:m().nonnegative().nullable()}),cost:d({totalUsd:m().nonnegative().nullable()}),checkpoint:d({id:ge,policyVersion:m().int().nonnegative(),sha256:tt.nullable(),sizeBytes:m().int().nonnegative().nullable()}).nullable(),movement:d({adapterDeltaNorm:m().nonnegative().nullable()}),evaluations:v(d({reference:d({id:ge,contentHash:tt}).nullable().optional(),kind:k(["baseline","candidate"]),policyVersion:m().int().nonnegative(),taskCount:m().int().nonnegative().nullable().optional(),targetTaskCount:m().int().nonnegative().nullable().optional(),score:m().nullable(),threshold:m().nullable(),passed:j().nullable()})),canonicalPublication:d({state:ge.nullable(),artifactId:ge.nullable()}),syncedAt:It})),bb=ht(()=>({count:m().int().nonnegative(),scoredCount:m().int().nonnegative(),meanScore:m().min(0).max(1).nullable(),passedCount:m().int().nonnegative(),passRate:m().min(0).max(1).nullable()})),yb=ht(()=>({status:k(["scored","unavailable"]),score:m().min(0).max(1).nullable(),passed:j(),rewardEligible:j(),failureClass:k(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:v(o().trim().min(1).max(2e4)).max(1e3),components:v(d({graderId:ge,score:m().min(0).max(1).nullable(),passed:j(),feedback:o().trim().max(2e4).nullable()})).max(1e3)})),Jz=ht(()=>({taskId:ge,input:ve(o(),ke()),baseOutput:ve(o(),ke()).nullable(),trainedOutput:ve(o(),ke()).nullable(),baseGrade:yb.nullable(),trainedGrade:yb.nullable()})),Qz=ht(()=>({schemaVersion:x("openpond.trainingEvaluationSummary.v1"),jobId:ge,tasksetId:ge,base:bb,trained:bb,meanScoreDelta:m().min(-1).max(1).nullable(),examples:v(Jz).max(1e6)}));ht(()=>({schemaVersion:x("openpond.trainingRunDetail.v1"),job:Nw,events:v(Kz),stepMetrics:v(Wz),policyMetrics:v(Gz).default([]),managedEvidence:Zz.nullable().default(null),evaluation:Qz.nullable(),generatedAt:It}));const Yz=ht(()=>({schemaVersion:x("openpond.trainingArtifact.v1"),id:ge,jobId:ge,kind:k(["adapter","checkpoint","metrics","log","manifest","evaluation"]),path:o().trim().min(1).max(4e3),sha256:tt,sizeBytes:m().int().nonnegative(),baseModelId:ge.nullable(),baseModelRevision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:tt.nullable(),nonProduction:j(),createdAt:It,metadata:Qc})),Xz=ht(()=>({schemaVersion:x("openpond.modelArtifactLineage.v1"),id:ge,modelId:ge,artifactId:ge,jobId:ge,tasksetId:ge,tasksetHash:tt,graderHash:tt,planHash:tt,bundleHash:tt,recipeHash:tt,workerVersion:o().trim().min(1).max(256),trainerVersion:o().trim().min(1).max(256),importedAt:It,frozenEvaluationArtifactId:ge.nullable(),promotable:j(),pinned:j().default(!1),status:k(["imported","rejected"]).default("imported"),rejectedAt:It.nullable().default(null),rejectionReason:o().trim().min(1).max(5e3).nullable().default(null),chatConfiguration:Tw.default(dz),managedServing:uz.nullable().default(null)})),eH=k(["chat_manual","agent","extension","authoring_optimizer"]),tH=ht(()=>({schemaVersion:x("openpond.modelBinding.v1"),id:ge,profileId:ge,role:eH,roleTargetId:ge,modelArtifactLineageId:ge,tasksetId:ge,evaluationArtifactId:ge.nullable(),status:k(["active","rolled_back"]),priorBindingId:ge.nullable(),rollbackTargetBindingId:ge.nullable(),promotedBy:ge,promotedAt:It,rolledBackAt:It.nullable(),metadata:Qc}));ht(()=>({schemaVersion:x("openpond.trainingActivity.v1"),profileId:ge,active:j(),activeCounts:d({jobs:m().int().nonnegative(),creations:m().int().nonnegative(),minerRuns:m().int().nonnegative(),datasetImports:m().int().nonnegative()}),revision:tt,generatedAt:It}));ht(()=>({schemaVersion:x("openpond.tasksetOperationalState.v1"),tasksetId:ge,attempts:v(DD),artifacts:v(LD),grades:v(HD),evaluationResults:v(P2).default([]),generatedAt:It}));const nH=ht(()=>({schemaVersion:x("openpond.trainingState.v1"),profileId:ge,sources:v(Pk),creations:v(lw),tasksetDrafts:v(Ka).default([]),tasksets:v(Tc),benchmarkRuns:v(Fm()).default([]),benchmarkComparisons:v(Fm()).default([]),datasetImports:v(sL).default([]),datasetArtifacts:v(Z2).default([]),graderAuditReports:v(UD),evaluationResults:v(Fm()).default([]),candidates:v(iw),minerConfig:hu,minerRuns:v(kD).default([]),modelProjects:v(Bz).default([]),modelVersions:v(zL).default([]),modelRuns:v(YL).default([]),comparisonSeries:v(EL).default([]),comparisonSeriesEntries:v(DL).default([]),modelCurrencySnapshots:v(nz).default([]),continualBenchIssueReviews:v(rz).default([]),continualLearningDailyBatches:v(sz).default([]),rewardModelVersions:v(HL).default([]),rewardModelRuns:v(qL).default([]),modelTasksets:v(Tc).default([]),plans:v($w),bundles:v(ng),jobs:v(Nw),artifacts:v(Yz),models:v(Xz),rolloutReceipts:v(Az).default([]),modelBindings:v(tH).default([]),destinations:v(Dz),baseModelCandidates:v(zz).default([]),activityRevision:tt.optional(),generatedAt:It})),ag=32e3,aH=k(["steer","message","followup","queued","result"]),sH=k(["pending","included","resolved","cancelled","rejected"]),sg=d({id:o().min(1),sequence:m().int().nonnegative(),sessionId:o().min(1),senderSessionId:o().min(1).nullable(),senderKind:k(["user","task","runtime","ponder"]),kind:aH,body:o().trim().min(1).max(ag),payload:ve(o(),ke()).default({}),idempotencyKey:o().min(1).max(200),replyTo:o().min(1).nullable(),expectedTurnId:o().min(1).nullable(),turnId:o().min(1).nullable(),requestIds:v(o()),state:sH,revision:m().int().positive(),createdAt:o(),updatedAt:o(),error:o().nullable()}).strict();d({expectedTurnId:o().trim().min(1),idempotencyKey:o().trim().min(1).max(200),prompt:o().trim().min(1).max(ag)}).strict();rt("action",[d({action:x("resume"),expectedRevision:m().int().positive()}).strict(),d({action:x("cancel"),expectedRevision:m().int().positive()}).strict(),d({action:x("edit"),expectedRevision:m().int().positive(),body:o().trim().min(1).max(ag)}).strict(),d({action:x("steer"),expectedRevision:m().int().positive(),expectedTurnId:o().trim().min(1)}).strict()]);const rH=d({id:o().min(1),sessionId:o().min(1),turnId:o().min(1),targetSessionId:o().min(1).nullable(),targetTurnId:o().min(1).nullable(),targetInputId:o().min(1).nullable().default(null),afterSequence:m().int().nonnegative(),deadline:o(),state:k(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:o(),updatedAt:o()}).strict();d({sessionId:o(),activeTurnId:o().nullable(),acceptingInput:j(),paused:j(),inputs:v(sg),waits:v(rH)});var Ad=Ye.shape.id,oH=d({schemaVersion:x("openpond.modelBatchReviewInspection.v1"),packageHash:o().regex(/^[a-f0-9]{64}$/),definition:au,binding:Ph,evidence:v(su).min(1).max(1e4),decisions:v(jh).min(1).max(1e4)}).strict(),sG=d({schemaVersion:x("openpond.modelBatchReviewRequest.v1"),operationId:Ad,modelId:Ad,expectedModelRevision:m().int().positive(),tasksetRef:Ye,rewardBindingRef:Ye.nullable(),definition:d({name:o().trim().min(1).max(500).optional(),instructions:o().trim().min(1).max(2e4).optional(),inputSchema:Tt.optional(),outputSchema:Tt.optional(),requiredOutputs:au.shape.requiredOutputs}).strict(),examples:v(d({evidence:Ye,input:Tt.optional(),expected:Tt.nullable().optional(),evaluatorContext:Tt.nullable().optional(),proposedTarget:Tt.nullable().optional()}).strict()).max(1e4)}).strict(),iH=d({schemaVersion:x("openpond.modelBatchReviewReceipt.v1"),operationId:Ad,modelId:Ad,source:Eh,evidence:v(su).min(1).max(1e4),proposals:v(Vx).max(1e4)}).strict();const cH={teamInvitations:e=>L(e,"/v1/team-invitations"),decideTeamInvitation:(e,t,n)=>L(e,`/v1/team-invitations/${t}`,{method:"POST",body:JSON.stringify({token:n})}),organizations:e=>L(e,"/v1/organizations"),createOrganization:(e,t)=>L(e,"/v1/organizations",{method:"POST",body:JSON.stringify(t)}),updateOrganization:(e,t,n)=>L(e,`/v1/organizations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),organizationMembers:(e,t)=>L(e,`/v1/organizations/${encodeURIComponent(t)}/members`),upsertOrganizationMember:(e,t,n)=>L(e,`/v1/organizations/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify(n)}),organizationMcpServer:(e,t)=>L(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`),generateOrganizationMcpServer:(e,t,n)=>L(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`,{method:"POST",body:JSON.stringify(n)}),setOrganizationMcpServerStatus:(e,t,n)=>L(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server/${n}`,{method:"POST"})},lH={taskInbox:(e,t)=>L(e,`/v1/sessions/${encodeURIComponent(t)}/inbox`),steerTurn:(e,t,n)=>L(e,`/v1/sessions/${encodeURIComponent(t)}/turns/steer`,{method:"POST",body:JSON.stringify(n)}),queueTaskInput:(e,t,n,a)=>L(e,`/v1/sessions/${encodeURIComponent(t)}/inbox`,{method:"POST",body:JSON.stringify({input:n,idempotencyKey:a})}),updateTaskInput:(e,t,n,a)=>L(e,`/v1/sessions/${encodeURIComponent(t)}/inbox/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)}),sendTurn:(e,t,n)=>L(e,`/v1/sessions/${t}/turns`,{method:"POST",body:JSON.stringify(n)}),runSessionCommand:(e,t,n)=>L(e,`/v1/sessions/${encodeURIComponent(t)}/commands`,{method:"POST",body:JSON.stringify(n)}),recordPreflightTurnFailure:(e,t,n)=>L(e,`/v1/sessions/${t}/preflight-turns/failure`,{method:"POST",body:JSON.stringify(n)}),listCreateImproveRuns:(e,t={})=>L(e,`/v1/create-improve-runs?${dH(t).toString()}`),getCreateImproveRun:(e,t)=>L(e,`/v1/create-improve-runs/${encodeURIComponent(t)}`),getCreateImproveCandidateDiff:(e,t,n)=>L(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/candidates/${encodeURIComponent(n)}/diff`),applyCreateImproveAction:(e,t,n)=>L(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/actions`,{method:"POST",body:JSON.stringify(n)}),interruptTurn:(e,t,n)=>L(e,`/v1/sessions/${t}/turns/interrupt`,{method:"POST",body:JSON.stringify({reason:n})}),compactSession:(e,t,n={reason:"manual"})=>L(e,`/v1/sessions/${t}/compact`,{method:"POST",body:JSON.stringify(n)}),workspaceTool:(e,t,n)=>L(e,`/v1/sessions/${t}/workspace-tools`,{method:"POST",body:JSON.stringify(n)}),ensureCloudWorkspaceReady:(e,t,n)=>L(e,`/v1/sessions/${encodeURIComponent(t)}/workspace/ensure-ready`,{method:"POST",body:JSON.stringify(n)})};function dH(e){const t=new URLSearchParams;return e.profileId&&t.set("profileId",e.profileId),e.conversationId&&t.set("conversationId",e.conversationId),e.targetKind&&t.set("targetKind",e.targetKind),e.targetId&&t.set("targetId",e.targetId),e.limit&&t.set("limit",String(e.limit)),t}const uH={sandboxFiles:(e,t,n={})=>{const a=new URLSearchParams({list:"1"});return n.path&&a.set("path",n.path),n.recursive!==void 0&&a.set("recursive",String(n.recursive)),n.maxEntries!==void 0&&a.set("maxEntries",String(n.maxEntries)),L(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${a.toString()}`)},sandboxUploadFile:(e,t,n)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/files`,{method:"POST",body:JSON.stringify(n)}),preserveSandboxSource:(e,t,n={})=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/preserve-source`,{method:"POST",body:JSON.stringify(n)}),sandboxDownloadFile:async(e,t,n,a={})=>{const s=new URLSearchParams({path:n});a.offsetBytes!==void 0&&s.set("offsetBytes",String(a.offsetBytes)),a.maxBytes!==void 0&&s.set("maxBytes",String(a.maxBytes));const r=await L(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${s.toString()}`);return{...r,contents:r.file.isBinary?"":fC(r.file.contentsBase64)}}},mH={sandboxGitStatus:(e,t)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/status`),sandboxGitDiff:(e,t,n)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/diff`,{method:"POST",body:JSON.stringify(n)})},pH={connectedAppStatus:(e,t={})=>{const n=ov(t);return n.set("status",t.status??"all"),L(e,`/v1/connected-apps/status${n.size>0?`?${n.toString()}`:""}`)},integrationConnections:(e,t={})=>{const n=ov(t);return t.status&&n.set("status",t.status),L(e,`/v1/integrations/connections${n.size>0?`?${n.toString()}`:""}`)},sandboxIntegrationLeases:(e,t)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`),attachSandboxIntegrationConnection:(e,t,n)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"POST",body:JSON.stringify(n)}),removeSandboxIntegrationLease:(e,t,n)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"DELETE",body:JSON.stringify({leaseId:n})})},fH={listSandboxProjects:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return L(e,`/v1/sandbox-projects?${n.toString()}`)},getSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return L(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`)},getSandboxProjectWorkspace:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return L(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/workspace?${a.toString()}`)},upsertSandboxProject:(e,t)=>L(e,"/v1/sandbox-projects",{method:"POST",body:JSON.stringify(t)}),syncSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return L(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/sync?${a.toString()}`,{method:"POST"})},uploadSandboxProjectSource:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId}),{teamId:s,...r}=n;return L(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/source?${a.toString()}`,{method:"POST",body:JSON.stringify(r)})},archiveSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return L(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`,{method:"DELETE"})},listSandboxAgents:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return L(e,`/v1/sandbox-agents?${n.toString()}`)},upsertSandboxAgent:(e,t)=>L(e,"/v1/sandbox-agents",{method:"POST",body:JSON.stringify(t)}),runSandboxAgent:(e,t,n)=>L(e,`/v1/sandbox-agents/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n)}),runProfileAction:(e,t)=>L(e,"/v1/profile/run",{method:"POST",body:JSON.stringify(t)})},hH={sandbox:(e,t)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},gH={...pH,...fH,...hH,...mH,...uH},vH={communities:(e,t)=>{const n=new URLSearchParams;return t&&n.set("cursor",t),L(e,`/v1/communities${n.size?`?${n}`:""}`)},communityPreview:(e,t)=>L(e,`/v1/communities/${encodeURIComponent(t)}/preview`),communityRules:(e,t)=>L(e,`/v1/communities/${encodeURIComponent(t)}/rules/current`),joinCommunity:(e,t,n)=>L(e,`/v1/communities/${encodeURIComponent(t)}/join`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),acceptCommunityRules:(e,t,n)=>L(e,`/v1/communities/${encodeURIComponent(t)}/rules/accept`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),leaveCommunity:(e,t)=>L(e,`/v1/communities/${encodeURIComponent(t)}/leave`,{method:"POST",body:"{}"}),communityChannels:(e,t)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels`),communityMessages:(e,t,n,a={})=>{const s=new URLSearchParams;return a.beforeSequence!=null&&s.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&s.set("limit",String(a.limit)),L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages${s.size?`?${s}`:""}`)},sendCommunityMessage:(e,t,n,a)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages`,{method:"POST",body:JSON.stringify(a)}),editCommunityMessage:(e,t,n,a,s)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify({body:s})}),deleteCommunityMessage:(e,t,n,a)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"DELETE",body:"{}"}),markCommunityRead:(e,t,n,a)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/read`,{method:"POST",body:JSON.stringify({sequence:a})}),setCommunityChannelMuted:(e,t,n,a)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/mute`,{method:"POST",body:JSON.stringify({muted:a})}),searchCommunityMembers:(e,t,n={})=>{const a=new URLSearchParams;return n.query&&a.set("query",n.query),n.cursor&&a.set("cursor",n.cursor),n.limit!=null&&a.set("limit",String(n.limit)),L(e,`/v1/communities/${encodeURIComponent(t)}/members/search${a.size?`?${a}`:""}`)},updateCommunityNotifications:(e,t,n)=>L(e,`/v1/communities/${encodeURIComponent(t)}/notifications`,{method:"POST",body:JSON.stringify({mode:n})}),communityEvents:(e,t,n={})=>{const a=new URLSearchParams;return n.after!=null&&a.set("after",String(n.after)),n.limit!=null&&a.set("limit",String(n.limit)),L(e,`/v1/communities/${encodeURIComponent(t)}/events${a.size?`?${a}`:""}`)},communityRealtimeSession:(e,t)=>L(e,`/v1/communities/${encodeURIComponent(t)}/realtime-session`),uploadCommunityAttachment:(e,t,n,a)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/upload`,{method:"POST",body:JSON.stringify({attachment:a})}),communityAttachmentDownload:(e,t,n,a)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/${encodeURIComponent(a)}/download`)},rg="openpond-app-server-url",Ec="openpond-app-token",bH=750;function Dw(){return window.location.protocol!=="http:"&&window.location.protocol!=="https:"?null:window.location.origin&&window.location.origin!=="null"?window.location.origin:null}function lf(e){const t=e.getItem(rg)?.trim(),n=e.getItem(Ec)?.trim();return t&&n?{serverUrl:t,token:n}:null}function Ed(e){if(!e)return null;try{const t="__openpond_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function Mo(e,t){e.setItem(rg,t.serverUrl),e.setItem(Ec,t.token)}function Sb(e,t){const n=lf(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(rg),e.removeItem(Ec))}function yH(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function SH(){const e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;const t=new URLSearchParams(e),n=t.get("openpondToken")?.trim(),a=t.get("openpondServerUrl")?.trim()||Dw();return!a||!n?null:{serverUrl:a,token:n}}function xH(){window.location.hash&&window.history.replaceState(null,"",`${window.location.pathname}${window.location.search}`)}function Nl(e,t){t&&(e.some(n=>n.serverUrl===t.serverUrl&&n.token===t.token)||e.push(t))}function kH(){const e=[],t=Ed(window.sessionStorage),n=Ed(window.localStorage),a=Dw(),s=t?.getItem(Ec)??n?.getItem(Ec);return Nl(e,null),Nl(e,a&&s?{serverUrl:a,token:s.trim()}:null),Nl(e,t?lf(t):null),Nl(e,n?lf(n):null),e}async function sp(e){const t=new AbortController,n=window.setTimeout(()=>t.abort(),bH);try{const a=await fetch(`${e}/health`,{signal:t.signal}),s=await a.json().catch(()=>null);return a.ok&&s?.server==="openpond-app-server"}catch{return!1}finally{window.clearTimeout(n)}}async function wH(){if(window.openpond)return window.openpond.getConnection();const e=Ed(window.sessionStorage),t=Ed(window.localStorage),n=SH();if(n&&await sp(n.serverUrl))return t&&Mo(t,n),e&&Mo(e,n),xH(),{...n,platform:navigator.platform};const a=yH();if(a&&await sp(a.serverUrl))return t&&Mo(t,a),e&&Mo(e,a),{...a,platform:navigator.platform};const s=kH();for(const r of s){if(await sp(r.serverUrl))return t&&Mo(t,r),e&&Mo(e,r),{...r,platform:navigator.platform};e&&Sb(e,r),t&&Sb(t,r)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const Z={...vH,bootstrap:e=>L(e,"/v1/bootstrap?refreshCodex=1"),accountScopeSnapshot:e=>L(e,"/v1/bootstrap?ensureProfile=0"),localProjectActions:(e,t)=>L(e,`/v1/projects/${encodeURIComponent(t)}/actions`),extensionCatalog:e=>L(e,"/v1/extensions"),extensionPreview:(e,t)=>L(e,"/v1/extensions/preview",{method:"POST",body:JSON.stringify(t)}),extensionAdd:(e,t)=>L(e,"/v1/extensions",{method:"POST",body:JSON.stringify(t)}),extensionUpdate:(e,t,n={})=>L(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}/update`,{method:"POST",body:JSON.stringify(n)}),extensionUpdateAll:e=>L(e,"/v1/extensions/update-all",{method:"POST"}),extensionRemove:(e,t)=>L(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}`,{method:"DELETE"}),skillSourceFile:(e,t,n,a)=>L(e,`/v1/skills/${t}/${encodeURIComponent(n)}/source?path=${encodeURIComponent(a)}`),teamChatMembers:(e,t)=>L(e,`/v1/team-chat/members?teamId=${encodeURIComponent(t)}`),teamChatAgents:(e,t)=>L(e,`/v1/team-chat/agents?teamId=${encodeURIComponent(t)}`),teamChatThreads:(e,t)=>L(e,`/v1/team-chat/threads?teamId=${encodeURIComponent(t)}`),teamChatRealtimeSession:(e,t)=>L(e,`/v1/team-chat/realtime-session?teamId=${encodeURIComponent(t)}`),teamChatEvents:(e,t,n={})=>{const a=new URLSearchParams({teamId:t});return n.after!=null&&a.set("after",String(n.after)),n.limit!=null&&a.set("limit",String(n.limit)),L(e,`/v1/team-chat/events?${a.toString()}`)},teamChatGeneral:(e,t)=>L(e,"/v1/team-chat/threads/general",{method:"POST",body:JSON.stringify({teamId:t})}),teamChatDm:(e,t,n)=>L(e,"/v1/team-chat/threads/dm",{method:"POST",body:JSON.stringify({teamId:t,otherUserId:n})}),teamChatThread:(e,t,n,a={})=>{const s=new URLSearchParams({teamId:t});return a.beforeSequence!=null&&s.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&s.set("limit",String(a.limit)),L(e,`/v1/team-chat/threads/${encodeURIComponent(n)}?${s.toString()}`)},uploadTeamChatAttachment:(e,t,n)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/attachments/upload`,{method:"POST",body:JSON.stringify(n)}),teamChatAttachmentDownload:(e,t,n)=>L(e,`/v1/team-chat/attachments/${encodeURIComponent(n)}/download?teamId=${encodeURIComponent(t)}`),sendTeamChatMessage:(e,t,n)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages`,{method:"POST",body:JSON.stringify(n)}),createTeamChatAgentRun:(e,t,n)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/agent-runs`,{method:"POST",body:JSON.stringify(n)}),teamChatAgentConversation:(e,t,n)=>L(e,`/v1/team-chat/agent-runs/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),editTeamChatMessage:(e,t,n,a)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)}),deleteTeamChatMessage:(e,t,n,a)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"DELETE",body:JSON.stringify({teamId:a})}),markTeamChatRead:(e,t,n,a)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/read`,{method:"POST",body:JSON.stringify({teamId:n,sequence:a})}),setTeamChatThreadMuted:(e,t,n,a)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/mute`,{method:"POST",body:JSON.stringify({teamId:n,muted:a})}),createTeamChatAiThread:(e,t,n)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/ai-threads`,{method:"POST",body:JSON.stringify(n)}),teamChatAiThread:(e,t,n)=>L(e,`/v1/team-chat/ai-threads/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),sendTeamChatAiTurn:(e,t,n)=>L(e,`/v1/team-chat/ai-threads/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),executeTeamChatAiTurn:(e,t,n)=>L(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute`,{method:"POST",body:JSON.stringify({teamId:n})}),cancelTeamChatAiTurnExecution:(e,t,n)=>L(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute/cancel`,{method:"POST",body:JSON.stringify({teamId:n})}),usage:(e,t={})=>{const n=xb(t),a=n.size?`?${n.toString()}`:"";return L(e,`/v1/usage${a}`)},usageRecords:(e,t={})=>{const n=xb(t);t.sessionId&&n.set("sessionId",t.sessionId),t.turnId&&n.set("turnId",t.turnId),t.limit!==void 0&&n.set("limit",String(t.limit));const a=n.size?`?${n.toString()}`:"";return L(e,`/v1/usage/records${a}`)},usageTurnCache:(e,t)=>L(e,`/v1/usage/turn-cache?sessionId=${encodeURIComponent(t)}`),runtimeEventsPage:(e,t={})=>{const n=new URLSearchParams;t.sessionId&&n.set("sessionId",t.sessionId),t.afterSequence!==void 0&&n.set("afterSequence",String(t.afterSequence)),t.beforeSequence!==void 0&&t.beforeSequence!==null&&n.set("beforeSequence",String(t.beforeSequence)),t.limit!==void 0&&n.set("limit",String(t.limit));const a=n.size?`?${n.toString()}`:"";return L(e,`/v1/events/page${a}`)},workOutputs:e=>L(e,"/v1/work/outputs"),harnessHistory:e=>L(e,"/v1/harness"),refinerHistory:e=>L(e,"/v1/refiner"),updateRefinerProfile:(e,t)=>L(e,"/v1/refiner/update",{method:"POST",body:JSON.stringify(t)}),activateRefinerRelease:(e,t)=>L(e,"/v1/refiner/activate",{method:"POST",body:JSON.stringify(t)}),rollbackRefinerRelease:(e,t)=>L(e,"/v1/refiner/rollback",{method:"POST",body:JSON.stringify(t)}),updateHarnessBackgroundReview:(e,t)=>L(e,"/v1/harness/background-review",{method:"POST",body:JSON.stringify(t)}),reviewHarnessEvaluation:(e,t)=>L(e,"/v1/harness/evaluation-review",{method:"POST",body:JSON.stringify(t)}),updateHarnessEvaluationReviewSchedule:(e,t)=>L(e,"/v1/harness/evaluation-review/settings",{method:"POST",body:JSON.stringify(t)}),harnessReleaseDiff:(e,t)=>L(e,"/v1/harness/diff",{method:"POST",body:JSON.stringify(t)}),rollbackHarness:(e,t)=>L(e,"/v1/harness/rollback",{method:"POST",body:JSON.stringify(t)}),reviewHarnessProposal:(e,t)=>L(e,"/v1/harness/review",{method:"POST",body:JSON.stringify(t)}),runSubagentLifecycleAction:(e,t,n)=>L(e,`/v1/subagents/${encodeURIComponent(t)}/lifecycle`,{method:"POST",body:JSON.stringify(n)}),trainingState:(e,t)=>L(e,`/v1/training?profileId=${encodeURIComponent(t)}`),trainingActivity:(e,t)=>L(e,`/v1/training/activity?profileId=${encodeURIComponent(t)}`),portableTrainingCatalog:(e,t="",n)=>{const a=new URLSearchParams;return t.trim()&&a.set("query",t.trim()),n&&a.set("method",n),L(e,`/v1/training/catalog${a.size?`?${a.toString()}`:""}`)},datasetCatalog:(e,t)=>L(e,`/v1/training/datasets?profileId=${encodeURIComponent(t)}`),trainingRunDetail:(e,t,n={})=>L(e,`/v1/training/jobs/${encodeURIComponent(t)}/detail?evaluation=${n.includeEvaluation===!1?"false":"true"}`),candidateReview:(e,t,n=!1,a="models")=>L(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision?refresh=${n}`),recordCandidateReview:(e,t,n,a="models")=>L(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision`,{method:"POST",body:JSON.stringify(n)}),candidateReviewHistory:(e,t,n,a="models")=>L(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision-history?decisionId=${encodeURIComponent(n.id)}&decisionHash=${n.contentHash}`),trainingEvaluationTasks:async(e,t,n,a)=>{const s=new URLSearchParams({limit:"25"});return a&&s.set("cursor",a),L(e,`/v1/training/jobs/${encodeURIComponent(t)}/evaluations/${encodeURIComponent(n.id)}/tasks?${s}`)},trainingRequest:(e,t,n,a="POST")=>L(e,`/v1/training${t}`,{method:a,body:a==="GET"||a==="DELETE"?void 0:JSON.stringify(n)}),datasetStorageState:e=>L(e,"/v1/settings/dataset-storage"),updateDatasetStorage:(e,t)=>L(e,"/v1/settings/dataset-storage",{method:"PATCH",body:JSON.stringify({datasetStorePath:t})}),hostedSavedWork:e=>L(e,"/v1/saved-work"),createHostedSavedWork:(e,t)=>L(e,"/v1/saved-work",{method:"POST",body:JSON.stringify(t)}),updateHostedSavedWork:(e,t,n)=>L(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteHostedSavedWork:(e,t)=>L(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"DELETE"}),runHostedSavedWork:(e,t,n)=>L(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({clientRequestId:n})}),chatWorkflows:(e,t)=>{const n=t?`?sessionId=${encodeURIComponent(t)}`:"";return L(e,`/v1/chat-workflows${n}`)},createChatWorkflow:(e,t)=>L(e,"/v1/chat-workflows",{method:"POST",body:JSON.stringify(t)}),updateChatWorkflow:(e,t,n)=>L(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteChatWorkflow:(e,t)=>L(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"DELETE"}),runChatWorkflow:(e,t)=>L(e,`/v1/chat-workflows/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({})}),localAgentSchedules:(e,t={})=>{const n=new URLSearchParams;t.localProjectId&&n.set("localProjectId",t.localProjectId);const a=n.size?`?${n.toString()}`:"";return L(e,`/v1/local-agent-schedules${a}`)},syncLocalAgentSchedules:e=>L(e,"/v1/local-agent-schedules/sync",{method:"POST",body:JSON.stringify({})}),patchLocalAgentSchedule:(e,t,n)=>L(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),runLocalAgentSchedule:(e,t,n={})=>L(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n)}),localAgentScheduleRuns:(e,t,n={})=>{const a=new URLSearchParams;n.limit!==void 0&&a.set("limit",String(n.limit));const s=a.size?`?${a.toString()}`:"";return L(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/runs${s}`)},refreshOpenPondAccounts:e=>L(e,"/v1/openpond/accounts/refresh",{method:"POST",body:JSON.stringify({})}),refreshOpenPondAccount:e=>L(e,"/v1/openpond/account?refresh=1"),loadMoreOpenPondApps:(e,t)=>L(e,`/v1/openpond/apps/more?offset=${encodeURIComponent(String(t.offset))}&limit=${encodeURIComponent(String(t.limit))}`),switchOpenPondAccount:(e,t)=>L(e,"/v1/openpond/accounts/switch",{method:"POST",body:JSON.stringify(t)}),removeOpenPondAccount:(e,t)=>L(e,"/v1/openpond/accounts",{method:"DELETE",body:JSON.stringify(t)}),signOutOpenPondAccount:e=>L(e,"/v1/openpond/accounts/logout",{method:"POST",body:JSON.stringify({})}),saveOpenPondAccount:(e,t)=>L(e,"/v1/openpond/accounts/login",{method:"POST",body:JSON.stringify(t)}),updateOpenPondAccountConfig:(e,t)=>L(e,"/v1/openpond/accounts/config",{method:"PATCH",body:JSON.stringify(t)}),savePreferences:(e,t)=>L(e,"/v1/preferences",{method:"PATCH",body:JSON.stringify(t)}),saveProviderSettings:(e,t)=>L(e,"/v1/providers",{method:"PATCH",body:JSON.stringify(t)}),providerSettings:e=>L(e,"/v1/providers"),loadProviderModels:(e,t,n={})=>{const a=new URLSearchParams;n.query?.trim()&&a.set("query",n.query.trim()),n.limit&&a.set("limit",String(n.limit));const s=a.size?`?${a.toString()}`:"";return L(e,`/v1/providers/${encodeURIComponent(t)}/models${s}`)},refreshProviderModels:(e,t,n)=>L(e,`/v1/providers/${encodeURIComponent(t)}/models`,{method:"POST",body:JSON.stringify(n)}),saveProviderCredential:(e,t,n)=>L(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"PUT",body:JSON.stringify(n)}),deleteProviderCredential:(e,t,n)=>L(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"DELETE",body:JSON.stringify(n)}),startOpenAiSubscriptionAuth:(e,t)=>L(e,"/v1/providers/openai/subscription-auth",{method:"POST",body:JSON.stringify(t)}),validateProviderCredential:(e,t,n)=>L(e,`/v1/providers/${encodeURIComponent(t)}/validate`,{method:"POST",body:JSON.stringify(n)}),savePersonalization:(e,t)=>L(e,"/v1/personalization",{method:"PATCH",body:JSON.stringify(t)}),recordClientDiagnostic:(e,t)=>L(e,"/v1/diagnostics/client",{method:"POST",body:JSON.stringify(t)}),profileCurrent:e=>L(e,"/v1/profile"),profileCatalog:e=>L(e,"/v1/profile/catalog"),profileWorkflows:e=>L(e,"/v1/profile/workflows"),profileEvaluations:e=>L(e,"/v1/profile/evaluations"),profileEvaluationDiscovery:(e,t,n)=>L(e,"/v1/profile/evaluations/discover",{method:"POST",body:JSON.stringify({profileRef:t}),signal:n}),profileEvaluationPrepare:(e,t)=>L(e,"/v1/profile/evaluations/prepare",{method:"POST",body:JSON.stringify(t)}),profileEvaluationRun:(e,t)=>L(e,"/v1/profile/evaluations/run",{method:"POST",body:JSON.stringify(t)}),profileEvaluationRunSuite:(e,t)=>L(e,"/v1/profile/evaluations/run-suite",{method:"POST",body:JSON.stringify(t)}),profileEvaluationCompare:(e,t)=>L(e,"/v1/profile/evaluations/compare",{method:"POST",body:JSON.stringify({id:`comparison-${crypto.randomUUID()}`,runIds:t})}),profileEvaluationSaveReport:(e,t,n)=>L(e,"/v1/profile/evaluations/reports",{method:"POST",body:JSON.stringify({id:`report-${crypto.randomUUID()}`,evidenceKind:t,evidenceId:n})}),profileSelect:(e,t)=>L(e,"/v1/profile/select",{method:"POST",body:JSON.stringify({ref:t})}),profileRemove:(e,t)=>L(e,"/v1/profile/remove",{method:"POST",body:JSON.stringify({ref:t})}),profilePublicationPreview:(e,t)=>L(e,"/v1/profile/publication/preview",{method:"POST",body:JSON.stringify(t)}),profilePublicationPublish:(e,t)=>L(e,"/v1/profile/publication/publish",{method:"POST",body:JSON.stringify(t)}),profileInstall:(e,t)=>L(e,"/v1/profile/install",{method:"POST",body:JSON.stringify(t)}),profileUpdate:(e,t)=>L(e,"/v1/profile/update",{method:"POST",body:JSON.stringify({ref:t})}),profileInit:(e,t)=>L(e,"/v1/profile/init",{method:"POST",body:JSON.stringify(t)}),profileLoad:(e,t)=>L(e,"/v1/profile/load",{method:"POST",body:JSON.stringify(t)}),profileCheck:(e,t)=>L(e,"/v1/profile/check",{method:"POST",body:JSON.stringify(t)}),profileAgentRename:(e,t,n)=>L(e,`/v1/profile/agents/${encodeURIComponent(t)}/name`,{method:"PATCH",body:JSON.stringify(n)}),profileCommit:(e,t)=>L(e,"/v1/profile/commit",{method:"POST",body:JSON.stringify(t)}),profilePush:(e,t)=>L(e,"/v1/profile/push",{method:"POST",body:JSON.stringify(t)}),workspaceLspSettingsStatus:e=>L(e,"/v1/lsp/settings-status"),workspaceLspRuntimeStatus:e=>L(e,"/v1/lsp/status"),restartWorkspaceLsp:e=>L(e,"/v1/lsp/restart",{method:"POST"}),remoteAccess:e=>L(e,"/v1/remote-access"),enableRemoteAccess:e=>L(e,"/v1/remote-access/enable",{method:"POST"}),disableRemoteAccess:e=>L(e,"/v1/remote-access/disable",{method:"POST"}),voiceTranscriptionStatus:(e,t={})=>L(e,"/v1/audio/transcriptions/status",{signal:t.signal}),transcribeVoice:(e,t,n={})=>L(e,"/v1/audio/transcriptions",{method:"POST",body:JSON.stringify(t),signal:n.signal}),createSession:(e,t)=>L(e,"/v1/sessions",{method:"POST",body:JSON.stringify(t)}),patchSession:(e,t,n)=>L(e,`/v1/sessions/${t}`,{method:"PATCH",body:JSON.stringify(n)}),codexHistoryThread:(e,t,n={})=>{const a=new URLSearchParams;n.limit!==void 0&&a.set("limit",String(n.limit)),n.tail&&a.set("tail","1");const s=a.size?`?${a.toString()}`:"";return L(e,`/v1/codex-history/${encodeURIComponent(t)}${s}`)},codexHistoryThreadIncremental:(e,t,n={})=>{const a=new URLSearchParams({incremental:"1"});return n.afterEventId&&a.set("afterEventId",n.afterEventId),n.limit!==void 0&&a.set("limit",String(n.limit)),n.revision&&a.set("revision",n.revision),n.tail&&a.set("tail","1"),L(e,`/v1/codex-history/${encodeURIComponent(t)}?${a.toString()}`)},sendCodexHistoryTurn:(e,t,n)=>L(e,`/v1/codex-history/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),interruptCodexHistoryTurn:(e,t)=>L(e,`/v1/codex-history/${encodeURIComponent(t)}/turns/interrupt`,{method:"POST"}),patchSidebarAppPreference:(e,t,n)=>L(e,`/v1/sidebar/apps/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),reorderSidebarApps:(e,t)=>L(e,"/v1/sidebar/apps/reorder",{method:"POST",body:JSON.stringify(t)}),sidebarFiles:e=>L(e,"/v1/sidebar/files"),patchSidebarFile:(e,t)=>L(e,"/v1/sidebar/files",{method:"PATCH",body:JSON.stringify(t)}),workspaceStatus:(e,t,n=!1,a={})=>L(e,`/v1/workspaces/${encodeURIComponent(t)}${n?"?ensure=1":""}`,{signal:a.signal}),createWorkspaceBranch:(e,t,n)=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/branches`,{method:"POST",body:JSON.stringify(n)}),checkoutWorkspaceBranch:(e,t,n)=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/branch`,{method:"PATCH",body:JSON.stringify(n)}),workspaceDiff:(e,t,n={})=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/diff`,{signal:n.signal}),resolveWorkspaceFile:(e,t,n)=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/resolve-file?path=${encodeURIComponent(n)}`),workspaceFile:(e,t,n)=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`),saveWorkspaceFile:(e,t,n)=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/file`,{method:"PATCH",body:JSON.stringify(n)}),signWorkspaceImageUrl:(e,t)=>L(e,"/v1/assets/workspace-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalImageUrl:(e,t)=>L(e,"/v1/assets/local-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalVideoUrl:(e,t)=>L(e,"/v1/assets/local-video-url",{method:"POST",body:JSON.stringify(t)}),signChatAttachmentImageUrl:(e,t)=>L(e,"/v1/assets/chat-attachment-image-url",{method:"POST",body:JSON.stringify(t)}),chatAttachmentFile:(e,t)=>L(e,"/v1/assets/chat-attachment-file",{method:"POST",body:JSON.stringify(t)}),workspaceLspTouch:(e,t,n,a={})=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/touch`,{method:"POST",body:JSON.stringify(n),signal:a.signal}),workspaceLspAction:(e,t,n)=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/action`,{method:"POST",body:JSON.stringify(n)}),workspaceTemplateConfig:(e,t)=>L(e,`/v1/openpond/apps/${encodeURIComponent(t)}/template-config`),...cH,...gH,createLocalProject:(e,t)=>L(e,"/v1/projects",{method:"POST",body:JSON.stringify(t)}),updateLocalProjectAgentSetup:(e,t,n)=>L(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),uploadLocalProjectCloudSource:(e,t,n)=>L(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source`,{method:"POST",body:JSON.stringify(n)}),previewLocalProjectCloudSource:(e,t,n={})=>{const a=new URLSearchParams;n.branch?.trim()&&a.set("branch",n.branch.trim());const s=a.toString()?`?${a.toString()}`:"";return L(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source/preview${s}`)},deleteLocalProject:(e,t)=>L(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"DELETE"}),gitAvailability:e=>L(e,"/v1/system/git"),installMacOSCommandLineTools:e=>L(e,"/v1/system/git/install-command-line-tools",{method:"POST",body:JSON.stringify({})}),...lH,resolveApproval:(e,t,n)=>L(e,`/v1/approvals/${t}`,{method:"POST",body:JSON.stringify(n)})};function xb(e){const t=new URLSearchParams;return e.range&&t.set("range",e.range),e.visibility&&t.set("visibility",e.visibility),e.status&&t.set("status",e.status),e.provider&&t.set("provider",e.provider),e.model&&t.set("model",e.model),t}const IH=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),_H=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),kb=e=>{const t=_H(e);return t.charAt(0).toUpperCase()+t.slice(1)},Lw=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),CH=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var RH={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const PH=h.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:s="",children:r,iconNode:i,...c},l)=>h.createElement("svg",{ref:l,...RH,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:Lw("lucide",s),...!r&&!CH(c)&&{"aria-hidden":"true"},...c},[...i.map(([u,p])=>h.createElement(u,p)),...Array.isArray(r)?r:[r]]));const We=(e,t)=>{const n=h.forwardRef(({className:a,...s},r)=>h.createElement(PH,{ref:r,iconNode:t,className:Lw(`lucide-${IH(kb(e))}`,`lucide-${e}`,a),...s}));return n.displayName=kb(e),n};const TH=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],AH=We("activity",TH);const EH=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]],jH=We("archive-restore",EH);const MH=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],OH=We("arrow-left",MH);const $H=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],zw=We("bookmark",$H);const NH=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2Z",key:"169p4p"}],["path",{d:"m14.5 7.5-5 5",key:"3lb6iw"}],["path",{d:"m9.5 7.5 5 5",key:"ko136h"}]],Hw=We("bookmark-x",NH);const DH=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M16 12h2",key:"7q9ll5"}],["path",{d:"M16 8h2",key:"msurwy"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}],["path",{d:"M6 12h2",key:"32wvfc"}],["path",{d:"M6 8h2",key:"30oboj"}]],wb=We("book-open-text",DH);const LH=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],Ib=We("bot",LH);const zH=[["path",{d:"M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z",key:"lc1i9w"}],["path",{d:"m7 16.5-4.74-2.85",key:"1o9zyk"}],["path",{d:"m7 16.5 5-3",key:"va8pkn"}],["path",{d:"M7 16.5v5.17",key:"jnp8gn"}],["path",{d:"M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z",key:"8zsnat"}],["path",{d:"m17 16.5-5-3",key:"8arw3v"}],["path",{d:"m17 16.5 4.74-2.85",key:"8rfmw"}],["path",{d:"M17 16.5v5.17",key:"k6z78m"}],["path",{d:"M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z",key:"1xygjf"}],["path",{d:"M12 8 7.26 5.15",key:"1vbdud"}],["path",{d:"m12 8 4.74-2.85",key:"3rx089"}],["path",{d:"M12 13.5V8",key:"1io7kd"}]],Dl=We("boxes",zH);const HH=[["path",{d:"M16 14v2.2l1.6 1",key:"fo4ql5"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]],Uw=We("calendar-clock",HH);const UH=[["path",{d:"M11 13H7",key:"t0o9gq"}],["path",{d:"M19 9h-4",key:"rera1j"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"15",y:"5",width:"4",height:"12",rx:"1",key:"q8uenq"}],["rect",{x:"7",y:"8",width:"4",height:"9",rx:"1",key:"sr5ea"}]],qw=We("chart-column-stacked",UH);const qH=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],ds=We("check",qH);const BH=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],rd=We("circle-check",BH);const FH=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],mr=We("chevron-down",FH);const VH=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],pr=We("chevron-right",VH);const KH=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],jd=We("circle-alert",KH);const WH=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],yu=We("cloud",WH);const GH=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],ZH=We("credit-card",GH);const JH=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],QH=We("download",JH);const YH=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],rp=We("external-link",YH);const XH=[["path",{d:"M4.226 20.925A2 2 0 0 0 6 22h12a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v3.127",key:"wfxp4w"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"m5 11-3 3",key:"1dgrs4"}],["path",{d:"m5 17-3-3h10",key:"1mvvaf"}]],Bw=We("file-output",XH);const eU=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],og=We("file-text",eU);const tU=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],Fw=We("folder",tU);const nU=[["path",{d:"M18 19a5 5 0 0 1-5-5v8",key:"sz5oeg"}],["path",{d:"M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v5",key:"1w6njk"}],["circle",{cx:"13",cy:"12",r:"2",key:"1j92g6"}],["circle",{cx:"20",cy:"19",r:"2",key:"1obnsp"}]],ig=We("folder-git-2",nU);const aU=[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]],sU=We("git-branch",aU);const rU=[["path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4",key:"tonef"}],["path",{d:"M9 18c-4.51 2-5-2-7-2",key:"9comsn"}]],oU=We("github",rU);const iU=[["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17",key:"1tzkfa"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"14pb5j"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Vw=We("earth",iU);const cU=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],lU=We("circle-question-mark",cU);const dU=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],uU=We("list-filter",dU);const mU=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Su=We("loader-circle",mU);const pU=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],fU=We("maximize-2",pU);const hU=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],xu=We("message-square",hU);const gU=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],Xc=We("ellipsis",gU);const vU=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],Kw=We("panel-left",vU);const bU=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],df=We("panel-right",bU);const yU=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z",key:"1nkz8b"}]],cg=We("pin",yU);const SU=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89",key:"znwnzq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11",key:"c9qhm2"}]],lg=We("pin-off",SU);const xU=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],kU=We("plus",xU);const wU=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],IU=We("power",wU);const _U=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],dg=We("refresh-cw",_U);const CU=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],RU=We("rotate-ccw",CU);const PU=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],TU=We("search",PU);const AU=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Ww=We("settings",AU);const EU=[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]],ug=We("shapes",EU);const jU=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],_b=We("shield",jU);const MU=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],ku=We("square-pen",MU);const OU=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],Gw=We("square-terminal",OU);const $U=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],Cb=We("user-round",$U);const NU=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],el=We("x",NU);const DU=[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]],mg=We("inbox",DU);const LU=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],zU=We("list",LU);const HU=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],UU=We("terminal",HU);function qU(){const[e,t]=h.useState(null);return h.useEffect(()=>{const n=window.openpond?.updates;if(!n)return;let a=!0;const s=i=>{a&&t(c=>!c||i.revision>c.revision?i:c)},r=n.onState(s);return n.getState().then(s).catch(()=>{}),()=>{a=!1,r()}},[]),e}const pg="openpond.desktop-update-drafts.v1";function BU(e,t=window.localStorage){t.setItem(pg,JSON.stringify(e))}function FU(e){try{const n=(e??window.localStorage).getItem(pg);if(!n)return{};const a=JSON.parse(n);if(!a||typeof a!="object"||Array.isArray(a))return{};const s={};for(const[r,i]of Object.entries(a))typeof i=="string"&&/^(?:new-chat|(?:session|project|app):.+)$/.test(r)&&(s[r]=i);return s}catch{return{}}}function Zw(e=window.localStorage){e.removeItem(pg)}function VU({hasRunningWork:e}){const t=qU(),[n,a]=h.useState(!1),[s,r]=h.useState(null),i=window.openpond?.updates;if(!t?.version||t.status==="unsupported"||!i)return null;const c=t.status==="ready"||t.status==="restarting"||t.retry==="restart",l=n||t.status==="downloading"||t.status==="restarting"||t.status==="checking",u=s??t.error,p=c?"Restart to update":"Update",f=u??(l?c?"Restarting OpenPond…":`Downloading OpenPond ${t.version}${t.progress===null?"":` (${t.progress}%)`}…`:c?`OpenPond ${t.version} is ready. It will be applied when you restart.`:`Download OpenPond ${t.version}`);async function S(){if(!(l||!i)){a(!0),r(null);try{if(c){if(!window.dispatchEvent(new Event("openpond:before-update",{cancelable:!0})))throw new Error("Could not save your drafts. Save them before restarting to update.");(await i.restartAndInstall({hasRunningWork:e})).status!=="restarting"&&Zw()}else t?.retry==="check"?await i.check():await i.download()}catch(b){r(b instanceof Error?b.message:"The update could not start. Try again.")}finally{a(!1)}}}return g.jsxs("div",{className:"sidebar-update-control",children:[g.jsxs("button",{type:"button",className:"sidebar-update-pill",title:f,"aria-label":l?f:`${p}${t.version?` (${t.version})`:""}`,"aria-busy":l,disabled:l,onClick:()=>{S()},children:[g.jsx("span",{className:`sidebar-update-icon${l?" sidebar-update-spinner":""}`,"aria-hidden":"true",children:l?g.jsx(Su,{size:14}):c?g.jsx(dg,{size:14}):g.jsx(QH,{size:14})}),g.jsx("span",{children:p})]}),g.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:t.status==="ready"?`OpenPond ${t.version} is ready to install. Restart to update.`:""}),u?g.jsx("div",{className:"sidebar-update-error",role:"alert",children:u}):null]})}const KU=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],Jw=We("house",KU);const WU=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M9 21V9",key:"1oto5p"}]],GU=We("panels-top-left",WU);function ZU({value:e,options:t,disabled:n,compact:a,className:s,icon:r,placement:i="bottom",label:c,tooltip:l,searchable:u=!1,floating:p=!1,onChange:f}){const[S,b]=h.useState(!1),[w,C]=h.useState(""),P=h.useRef(null),[_,M]=h.useState();h.useLayoutEffect(()=>{if(!S||!p)return;function I(){const R=P.current?.getBoundingClientRect();if(!R)return;const O=window.innerHeight-R.bottom-12,z=R.top-12,$=O<180&&z>O;M({position:"fixed",left:Math.max(12,R.left),width:Math.min(R.width,window.innerWidth-24),minWidth:0,maxWidth:"calc(100vw - 24px)",right:"auto",top:$?"auto":R.bottom+5,bottom:$?window.innerHeight-R.top+5:"auto",maxHeight:Math.max(80,Math.min(320,$?z-5:O-5)),overflowY:"auto",zIndex:1e3})}return I(),window.addEventListener("resize",I),window.addEventListener("scroll",I,!0),()=>{window.removeEventListener("resize",I),window.removeEventListener("scroll",I,!0)}},[S,p]);const E=t.find(I=>I.value===e)??t[0],T=w.trim().toLowerCase(),y=T?t.filter(I=>[I.label,I.shortLabel,I.description].some(R=>R?.toLowerCase().includes(T))):t;return h.useEffect(()=>{if(!S){C("");return}function I(O){P.current?.contains(O.target)||b(!1)}function R(O){O.key==="Escape"&&b(!1)}return document.addEventListener("pointerdown",I),document.addEventListener("keydown",R),()=>{document.removeEventListener("pointerdown",I),document.removeEventListener("keydown",R)}},[S]),g.jsxs("div",{className:`dropdown-select ${s??""} ${a?"compact":""} ${i==="top"?"open-up":""}`,"data-tooltip":l,ref:P,children:[g.jsxs("button",{type:"button",className:`dropdown-trigger ${S?"active":""}`,disabled:n,"aria-label":c,"aria-haspopup":"menu","aria-expanded":S,onClick:()=>b(I=>!I),children:[r,g.jsx("span",{children:E?.shortLabel??E?.label??e}),g.jsx(mr,{size:14})]}),S&&g.jsxs("div",{className:"dropdown-menu",role:"menu",style:p?_:void 0,children:[u?g.jsxs("label",{className:"dropdown-search",onClick:I=>I.stopPropagation(),children:[g.jsxs("span",{className:"sr-only",children:["Search ",c]}),g.jsx("input",{autoFocus:!0,placeholder:`Search ${c.toLowerCase()}`,value:w,onChange:I=>C(I.target.value)})]}):null,y.map(I=>g.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":I.value===e,disabled:I.disabled,className:[I.value===e?"selected":"",I.separatorBefore?"separator-before":"",I.icon?"with-icon":""].filter(Boolean).join(" "),onClick:()=>{I.disabled||(f(I.value),C(""),b(!1))},children:[g.jsxs("span",{children:[I.icon==="plus"?g.jsx(kU,{size:13}):null,g.jsx("span",{children:I.label})]}),I.description&&g.jsx("small",{children:I.description})]},I.value)),y.length?null:g.jsx("div",{className:"dropdown-empty",children:"No matches"})]})]})}const rG=[{value:"chat",label:"Chat"},{value:"work",label:"Work"}];function Qw(e){return e==="chat"?"New chat":"New task"}const uf=["get-started","home","inbox","models","datasets","graders","experiments","tasks","tasksets","labeling","rewards","evaluations","runs","versions","serving"],JU={"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"},QU={tasks:["drafts"],tasksets:["drafts","formats","batches"],rewards:["scorers","combined"],evaluations:["results","review","comparisons"],runs:["series","new"]},YU={datasets:["tasks","experiments","graders","versions"],graders:["overview","checks","usage","versions"],experiments:["overview","cases","compare","configuration"],tasksets:["overview","tasks","reward","attempts","releases"],rewards:["definition","usage","evidence"],evaluations:["overview","comparison","activity"],runs:["details","metrics","evaluation","rollouts","activity","artifacts"],versions:["overview","metrics","evaluation","rollouts","activity","artifacts"]};function wa(e="models",t=null,n={}){return e==="evaluations"&&n.collection==="review"?wa("labeling",t,{...n,collection:"default"}):{page:e,modelId:["get-started","home","inbox","datasets","graders","experiments"].includes(e)?null:t,collection:e==="evaluations"?"results":"default",resourceId:null,detailTab:null,query:"",after:null,...n}}function fg(e){const t=e.pathname.split("/").filter(Boolean);if(t[0]!=="models"&&t[0]!=="console")return null;let n;try{n=t.slice(1).map(decodeURIComponent)}catch{return null}if(n.some(Y=>!Y.trim()||Y.length>2e3||Y.includes("\0")))return null;const a=n[0]&&!uf.includes(n[0])?n.shift():null;if(a&&(a.length>500||["projects","scorers"].includes(a)))return null;n[0]==="runs"&&n[1]==="evaluations"&&n.splice(0,2,"evaluations","results"),n[0]==="runs"&&n[1]==="comparisons"&&n.splice(0,2,"evaluations","comparisons");const s=n.shift(),r=s??"models";if(!uf.includes(r)||s==="models"||a&&r==="get-started")return null;let i=r==="evaluations"?"results":"default";if(QU[r]?.includes(n[0]))i=n.shift();else if(r==="evaluations"&&n.length)return null;if(r==="experiments"&&n[0]==="history")return null;const c=n.shift()??null,l=n.shift()??null;if(n.length||l&&!c||(r==="models"||r==="get-started"||r==="home")&&c)return null;if(i==="drafts"||i==="new"){if(!c||l)return null}else if(i!=="series"){if(["review","formats","batches","comparisons","scorers","combined"].includes(i)){if(l)return null}else if(l&&!YU[r]?.includes(l))return null}if(r==="serving"&&l)return null;const u=new URLSearchParams(e.search??"");if([...u.keys()].some(Y=>!["model","q","after","source","project","pass","dataset","revision","hash","sort","location","kind","review_source","review_snapshot","review_boundary","review_revision"].includes(Y))||[...u.keys()].some(Y=>u.getAll(Y).length!==1))return null;const p=["review_source","review_snapshot","review_boundary","review_revision"],f=p.some(Y=>u.has(Y));if(f&&(r!=="datasets"||c||u.get("location")==="local"||p.some(Y=>!u.get(Y))||[u.get("review_source"),u.get("review_boundary")].some(Y=>!Y.trim()||Y.length>500||Y.includes("\0"))||[u.get("review_snapshot"),u.get("review_revision")].some(Y=>!/^[a-f0-9]{64}$/.test(Y))))return null;const S=f?{id:u.get("review_source"),snapshotHash:u.get("review_snapshot"),boundaryId:u.get("review_boundary"),boundaryRevisionHash:u.get("review_revision")}:void 0,b=u.get("sort");if(b!==null&&(r!=="datasets"||!["id","name","updated"].includes(b)))return null;const w=u.has("revision")?Number(u.get("revision")):void 0,C=u.get("hash")??void 0,P=["datasets","graders"].includes(r);if((w!==void 0||C!==void 0)&&(!c||!P||!Number.isSafeInteger(w)||w<=0||!/^[a-f0-9]{64}$/.test(C??"")))return null;const _=u.get("source");if(_!==null&&(r!=="labeling"&&(r!=="evaluations"||i!=="review")||!_.trim()||_.length>500)||u.has("dataset")&&(r!=="datasets"||!c||u.get("dataset")!=="release"))return null;const M=["home","inbox","datasets","graders","experiments"].includes(r),E=r==="runs"&&!!(c?.startsWith("hosted-run:")||c?.startsWith("hosted-policy:")),T=u.get("location");if(T!==null&&(!M||!["local","hosted"].includes(T)))return null;const y=u.get("kind");if(y!==null&&(r!=="experiments"||!c||T==="local"||y!=="recorded_evidence")||t[0]==="console"&&!M)return null;const I=u.get("project")==="all"?null:u.get("project"),R=u.get("pass");if([I,R].some(Y=>Y!==null&&(!Y.trim()||Y.length>240))||!M&&!E&&(I||R)||r!=="experiments"&&R||(M||E)&&a||R&&!c)return null;const O=u.get("model");if(M&&O!==null||a&&O&&a!==O)return null;const z=a??O;if(r==="get-started"&&u.size!==0)return null;const $=u.get("q")??"",V=u.get("after");return z!==null&&(!z.trim()||z.length>500)||$.length>1e3||V!==null&&(!V.trim()||V.length>2e3)?null:wa(r,z,{...S?{reviewSource:S}:{},collection:i,resourceId:c,detailTab:l,query:$,after:V,...y?{executionKind:"recorded_evidence"}:{},...T?{executionLocation:T}:{},...b?{sort:b}:{},...w!==void 0?{revision:w,contentHash:C}:{},...u.get("dataset")==="release"?{datasetKind:"release"}:{},...t[0]==="console"?{area:"console"}:{},...M||E?{...u.has("project")?{projectId:I}:{},...u.has("pass")?{passId:R}:{}}:{},..._!==null?{sourceId:_}:{}})}function wu(e){const t=[e.area==="console"?"/console":"/models"];if(e.modelId&&t.push(encodeURIComponent(e.modelId)),e.page==="evaluations"&&e.collection==="review")return wu(wa("labeling",e.modelId,{collection:"default",resourceId:e.resourceId,sourceId:e.sourceId,query:e.query,after:e.after}));e.page==="evaluations"?t.push("runs",e.collection==="comparisons"?"comparisons":"evaluations"):(e.page!=="models"&&t.push(e.page),e.collection!=="default"&&t.push(e.collection)),e.resourceId&&t.push(encodeURIComponent(e.resourceId)),e.resourceId&&e.detailTab&&t.push(encodeURIComponent(e.detailTab));const n=new URLSearchParams;return e.page==="datasets"&&!e.resourceId&&e.reviewSource&&(n.set("review_source",e.reviewSource.id),n.set("review_snapshot",e.reviewSource.snapshotHash),n.set("review_boundary",e.reviewSource.boundaryId),n.set("review_revision",e.reviewSource.boundaryRevisionHash)),e.executionLocation&&n.set("location",e.executionLocation),e.projectId?n.set("project",e.projectId):e.projectId===null&&["home","inbox","datasets","graders","experiments"].includes(e.page)&&n.set("project","all"),e.page==="datasets"&&e.resourceId&&e.datasetKind==="release"&&n.set("dataset","release"),e.page==="datasets"&&e.sort&&n.set("sort",e.sort),e.revision!==void 0&&e.contentHash&&e.resourceId&&["datasets","graders"].includes(e.page)&&(n.set("revision",String(e.revision)),n.set("hash",e.contentHash)),e.passId&&n.set("pass",e.passId),e.page==="experiments"&&e.resourceId&&e.executionKind&&n.set("kind",e.executionKind),e.query&&n.set("q",e.query),e.after&&n.set("after",e.after),(e.page==="labeling"||e.page==="evaluations"&&e.collection==="review")&&e.sourceId&&n.set("source",e.sourceId),`${t.join("/")}${n.size?`?${n}`:""}`}function XU(e,t){return wa(e.page,t,{...e.area?{area:e.area}:{},...["home","inbox","datasets","graders","experiments"].includes(e.page)&&e.projectId!==void 0?{projectId:e.projectId}:{},collection:e.collection==="new"||e.collection==="drafts"?"default":e.collection})}function oG(e,t,n=null){return{...e,resourceId:t,detailTab:n,after:null,...t!==e.resourceId?{revision:void 0,contentHash:void 0}:{}}}const Md=new Set,mf=new Set,eq=new Set(["account","notifications","harness","harness-refiner","harness-continuous-review","harness-contents","harness-releases","profile","skills","configuration","context","training","subagents","editor","providers","conversation-imports","dataset-storage","remote","usage","personalization","diagnostics"]),pf={apps:"/apps",outputs:"/outputs",projects:"/projects",scheduled:"/workflows","get-started":"/get-started",team:"/team",community:"/community"};let ff=!1,hf="",od=null,Yw=null,jc="",za=0,Qi=null,gc=!1,op=null,id=!1;function hg(e){const t=fg(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&&eq.has(n[1])){const s=gg(new URLSearchParams(e.search??"").get("returnTo"));return{kind:"settings",section:n[1],...s?{returnTo:s}:{}}}if(n[0]==="chat"&&n.length<=2)try{return{kind:"chat",sessionId:n[1]&&n[1]!=="new"?decodeURIComponent(n[1]):null}}catch{return null}const a=Object.keys(pf).find(s=>pf[s]===e.pathname);return a?{kind:"view",view:a}:null}function Xw(e){if(e.kind==="models")return wu(e.route);if(e.kind==="models_unavailable")return`${e.pathname}${e.search}`;if(e.kind==="settings"){const t=gg(e.returnTo??null);return`/settings/${e.section}${t?`?${new URLSearchParams({returnTo:t})}`:""}`}return e.kind==="chat"?e.sessionId?`/chat/${encodeURIComponent(e.sessionId)}`:"/chat/new":pf[e.view]}function tq(e){const t=e?.kind==="settings"?gg(e.returnTo??null):null;if(t){const n=new URL(t,"https://local.openpond.invalid"),a=fg(n);if(a)return{kind:"models",route:a}}return{kind:"chat",sessionId:null}}function gg(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=fg(t);return n?wu(n):null}function tl(){return`${window.location.pathname}${window.location.search}`}function vg(){if(typeof window>"u")return;const e=ff?jc:tl();e!==hf&&(hf=e,od=hg(new URL(e,window.location.origin)),Yw=od?.kind==="models"?od.route:null)}function eI(){hf="",vg();for(const e of mf)e()}async function bg(e){if(id)return!1;id=!0;try{for(const t of[...Md].reverse())if(!await t(e))return!1;return!0}finally{id=!1}}function yg(e){return{...window.history.state,openpondNavigationIndex:e}}async function nq(){const e=tl(),t=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:za-1;if(Qi&&t===za){const a=Qi;Qi=null,a();return}if(op===t||Md.size===0){op=null,jc=e,za=t,window.history.replaceState(yg(za),"",e),eI();return}if(t===za)return;if(gc||id){Qi??=()=>{},window.history.go(za-t);return}gc=!0;const n=t-za;try{await new Promise(a=>{Qi=a,window.history.go(-n)}),await bg(e)&&(op=t,window.history.go(n))}finally{gc=!1}}function Sg(){if(ff||typeof window>"u")return;const e=hg(window.location);jc=e?Xw(e):tl(),za=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:0,window.history.replaceState(yg(za),"",jc),window.addEventListener("popstate",nq),ff=!0}function tI(e){return mf.add(e),Sg(),()=>{mf.delete(e)}}function iG(e){return Md.add(e),Sg(),()=>{Md.delete(e)}}async function cG(e){!gc&&await bg(tl())&&e()}function aq(){return h.useSyncExternalStore(tI,()=>(vg(),Yw),()=>null)}function sq(){return h.useSyncExternalStore(tI,()=>(vg(),od),()=>null)}async function Lt(e,t="push"){if(typeof window>"u"||(Sg(),gc))return!1;if(e.kind==="settings"&&!e.returnTo){const a=hg(window.location),s=a?.kind==="models"?wu(a.route):a?.kind==="settings"?a.returnTo:void 0;s&&(e={...e,returnTo:s})}const n=Xw(e);return tl()===n?!0:await bg(n)?(t==="push"&&za++,window.history[t==="replace"?"replaceState":"pushState"](yg(za),"",n),jc=n,eI(),!0):!1}function Fr(e,t="push"){return Lt({kind:"models",route:e},t)}function rq({experience:e="work",beginNewChat:t}){return g.jsx("div",{className:"sidebar-new-task",children:g.jsxs("button",{className:"sidebar-row sidebar-task-row sidebar-new-task-entry",type:"button",onClick:async()=>{await Lt({kind:"chat",sessionId:null})&&t(null)},children:[g.jsx("span",{className:"conversation-source-icon","aria-hidden":"true",children:g.jsx(ku,{size:18})}),g.jsx("span",{children:Qw(e)})]})})}function oq({productArea:e="chat",setSectionMenuOpen:t,setSelectedAppId:n,setSelectedProjectId:a,setSelectedSessionId:s,setView:r,view:i,modelProjects:c=[],modelTrainingActivityByProjectId:l={}}){const u=aq(),p=u?.modelId??null,f=u?.page??"models";function S(){n(null),a(null),s(null),t(null)}async function b(_){await Fr(wa(_,["home","inbox","datasets","graders","experiments"].includes(_)?null:p,{...e==="console"?{area:"console"}:{},...u?.projectId!==void 0?{projectId:u.projectId}:{}}))&&(S(),r("labs"))}async function w(_){await Fr(XU(u??wa(),_||null))&&(S(),r("labs"))}async function C(_){await Lt({kind:"view",view:_})&&(S(),r(_))}const P=p?l[p]??null:null;return g.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[e!=="chat"?g.jsxs(g.Fragment,{children:[["home","inbox","datasets","graders","experiments"].includes(f)?null:g.jsxs("div",{className:"sidebar-model-project-picker",children:[g.jsx("span",{className:"sidebar-nav-group-label",children:"Model"}),g.jsx(ZU,{label:"Model",searchable:c.length>8,value:p??"",options:[{value:"",label:"All models"},...p&&!c.some(_=>_.id===p)?[{value:p,label:"Unavailable model",disabled:!0}]:[],...c.map(_=>({value:_.id,label:_.name}))],onChange:_=>{w(_)}})]}),uf.filter(_=>e==="console"?["home","inbox","datasets","graders","experiments"].includes(_):_!=="home"&&_!=="tasksets"&&_!=="evaluations").map(_=>{const M={"get-started":Dl,home:Jw,inbox:mg,models:AH,datasets:Dl,graders:_b,experiments:rd,tasks:Dl,tasksets:Dl,labeling:rd,rewards:_b,evaluations:rd,runs:qw,versions:sU,serving:yu}[_];return g.jsxs("button",{className:`nav-command ${i==="labs"&&(f===_||_==="runs"&&f==="evaluations")?"active":""}`,"aria-current":i==="labs"&&(f===_||_==="runs"&&f==="evaluations")?"page":void 0,type:"button",onClick:()=>{b(_)},children:[g.jsx(M,{size:16}),g.jsx("span",{children:JU[_]}),_==="runs"&&P?g.jsx("span",{className:"sidebar-running-dot","aria-label":P.label}):null]},_)})]}):null,e==="chat"?g.jsxs(g.Fragment,{children:[g.jsxs("button",{className:`nav-command nav-command-prominent ${i==="scheduled"?"active":""}`,"aria-label":"Workflows",type:"button",onClick:()=>{C("scheduled")},children:[g.jsx(Uw,{size:18}),g.jsx("span",{children:"Workflows"})]}),g.jsxs("button",{className:`nav-command nav-command-prominent ${i==="outputs"?"active":""}`,"aria-label":"Outputs",type:"button",onClick:()=>{C("outputs")},children:[g.jsx(Bw,{size:18}),g.jsx("span",{children:"Outputs"})]}),g.jsxs("button",{className:`nav-command nav-command-prominent ${i==="apps"?"active":""}`,"aria-label":"Apps",type:"button",onClick:()=>{C("apps")},children:[g.jsx(ug,{size:18}),g.jsx("span",{children:"Apps"})]}),g.jsxs("button",{className:`nav-command nav-command-prominent ${i==="projects"?"active":""}`,"aria-label":"Projects",type:"button",onClick:()=>{C("projects")},children:[g.jsx(ig,{size:18}),g.jsx("span",{children:"Projects"})]})]}):null]})}const nI=Bm({chatMode:k(["chat","work"]).optional(),sidebarPresentation:k(["grouped","inbox"]).optional(),notificationMode:k(["all","direct_mentions","none"]).optional(),learningNoticeDismissed:j().optional(),sidebarVisibility:Bm({showCodexChats:j(),onlyRunningTasks:j()}).optional(),scheduledWorkView:k(["calendar","list"]).optional(),editorControlsVisible:j().optional(),voiceNoticeAcknowledged:j().optional(),lessonProgress:ve(o().min(1).max(200),Bm({completed:j(),currentTime:m().finite().nonnegative(),duration:m().finite().positive(),updatedAt:m().finite().nonnegative()})).refine(e=>Object.keys(e).length<=200,"Too many lessons").optional()}),gf={"openpond:last-chat-task-mode":"chatMode","openpond.sidebar.presentation.v1":"sidebarPresentation","openpond.team-chat.notification-mode":"notificationMode","openpond.sidebar.continuous-learning.dismissed.v1":"learningNoticeDismissed","openpond.sidebar-task-visibility.v1":"sidebarVisibility","openpond.scheduled-work.view.v1":"scheduledWorkView","openpond.workspace.editorControlsVisible":"editorControlsVisible","openpond.voice.setupNoticeAcknowledged":"voiceNoticeAcknowledged","openpond.post-training-progress.v1":"lessonProgress"},vf=new Set;let vc=null,qs=null,Ua={},Mc={},ip=!1,cd=0,ai=null,Rb=0;const iq="openpond-client-choices-changed";function xg(){vf.forEach(e=>e()),typeof window<"u"&&window.dispatchEvent(new Event(iq))}function cq(){return ai}function lq(e){return vf.add(e),()=>{vf.delete(e)}}function fi(e){const t=h.useRef(e);t.current=e,h.useEffect(()=>lq(()=>t.current()),[])}async function Pb(e){const t=++Rb,n=await L(e,"/v1/configuration");if(n.clientState?.revision===null){const s=dq();if(Object.keys(s.patch).length){n.clientState=await L(e,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n.clientState.owner,patch:s.patch,importOnly:!0})});for(const r of s.keys)try{window.localStorage.removeItem(r)}catch{}}}if(t!==Rb)return;const a=vc?.serverUrl!==e.serverUrl||vc?.token!==e.token||qs?.owner!==n.clientState?.owner;a&&(cd++,Ua={},Mc={},ai=null),vc=e,(a||(n.clientState?.revision??0)>=(qs?.revision??0))&&(qs=n.clientState),xg()}async function kg(){if(ip||!vc||!qs||!Object.keys(Ua).length)return;ip=!0;const e=Ua,t=vc,n=qs.owner,a=cd;Ua={},Mc=e;try{const s=await L(t,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n,patch:e})});a===cd&&(qs=s,ai=null)}catch(s){a===cd&&(Ua={...e,...Ua},ai=`Preference changes have not been saved. ${s instanceof Error?s.message:String(s)}`)}finally{Mc={},ip=!1,xg(),!ai&&Object.keys(Ua).length&&kg()}}function lG(){ai=null,kg()}const no={getItem(e){const t=gf[e];if(!t)return null;const n={...qs?.value,...Mc,...Ua}[t];return n===void 0?null:typeof n=="string"?n:JSON.stringify(n)},setItem(e,t){if(!qs)return;const n=gf[e];if(!n)throw new Error("Unregistered client preference.");let a;try{a=JSON.parse(t)}catch{a=t}const s=nI.parse({[n]:a});JSON.stringify({...qs.value,...Mc,...Ua}[n])!==JSON.stringify(s[n])&&(Ua={...Ua,...s},xg(),kg())}};function dq(){const e={},t=[];if(typeof window>"u")return{patch:e,keys:t};for(const[n,a]of Object.entries(gf))try{const s=window.localStorage.getItem(n);if(s===null)continue;let r;try{r=JSON.parse(s)}catch{r=s}const i=nI.safeParse({[a]:r});i.success&&(Object.assign(e,i.data),t.push(n))}catch{}return{patch:e,keys:t}}function aI(e){return e.replace(/\s+\(default\)$/i,"").replace(/^(?:openai|anthropic|google|xai|deepseek|qwen|meta-llama)\//i,"").replace(/^gpt-/i,"GPT-")}const ld=5,Nn=15,bf=10,Rt={defaultChatProvider:Kr,subagents:TE(),codexPermissionMode:oh,codexReasoningEffort:ih,openPondCommandAccessMode:Qd,defaultBranchPrefix:"feat/",defaultNewProjectDirectory:"",advancedWorkspaceControls:!1,steerActiveResponses:!0,contextCompaction:{autoEnabled:!0,triggerPercent:85,summaryModel:"same_model"},training:{defaultModelRef:null,creationMode:"customize",autoApproveEvidence:!1},sidebarWidth:332,diffPanelWidth:560,sidebarSectionsCollapsed:{pinned:!1,projects:!1,cloudProjects:!1,chats:!1,savedForLater:!0},editor:{languageServers:"auto",diagnosticsWhileEditing:!0,checkOnSave:!0,languages:{typescript:{mode:"auto",customCommand:""},python:{mode:"auto",customCommand:""},rust:{mode:"auto",customCommand:""}}}},dG={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},sI=[{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"}],cp=[{value:"openpond",label:"OpenPond Chat"},{value:"codex",label:"OpenAI Codex",description:"Codex login"}],uq=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],mq=["openpond","codex","claude-code","grok-build","opencode",...uq],pq=new Set(mq),rI=[{value:rh,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"}],uG=[{value:"default",label:"Default permissions",shortLabel:"Default",description:"Workspace sandbox; asks before crossing boundaries."},{value:"auto-review",label:"Auto-review",description:"Workspace sandbox; reviewer handles eligible approvals."},{value:"full-access",label:"Full access",description:"No sandbox or approval prompts."}],yf=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],fq=[{value:"off",label:"Off"},...yf,{value:"max",label:"Max"}],mG=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],pG=[{value:"auto",label:"Auto",description:"Use installed language servers when available."},{value:"off",label:"Off",description:"Disable editor language servers."}],fG=[{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 wg(e){return e.kind==="local"}function hq(e){return e.kind==="cloud"}function ct(e,t){return`${e}:${t}`}function oI(e){const t=e?.trim();if(!t)return null;const n=t.indexOf(":");if(n<=0)return{kind:"local",id:t};const a=t.slice(0,n),s=t.slice(n+1);return(a==="local"||a==="cloud")&&s?{kind:a,id:s}:{kind:"local",id:t}}function qr(e){return`${e.type}:${e.id}`}function Od(e){const t=e.currentTarget.getBoundingClientRect();return e.clientY<t.top+t.height/2?"before":"after"}function $d(e,t,n,a="before"){if(t===n)return e;const s=e.filter(i=>i!==t),r=s.indexOf(n);return r===-1?e:(s.splice(a==="after"?r+1:r,0,t),s)}function Tb(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function gq(e,t){if(!t)return e;const n=new Map(e.map(r=>[r.key,r])),a=t.map(r=>n.get(r)).filter(r=>!!r),s=new Set(a.map(r=>r.key));return[...a,...e.filter(r=>!s.has(r.key))]}function Ig(e,t){return e?.statuses?.[t]??null}function iI(e,t){return e?.providers?.[t]??null}function _g(e,t){return e?.modelCaches?.[t]??null}function vq(e){const t=[e.contextWindow?`${Math.round(e.contextWindow/1e3)}K context`:"",e.capabilities.reasoning?"reasoning":"",e.source].filter(Boolean);return{value:e.id,label:aI(e.displayName||e.id),description:t.join(" · ")||void 0}}function bq(e){return e==="openpond"?sI:e==="codex"||e==="openai"?rI:[]}function yq(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 Sq(e){return xc(e)||pq.has(e)}function Sf(e,t={}){if(!e)return t.localOnly,cp;const n=t.includeUnavailable??!1,a=t.enabledOnly??!1,s=[];for(const r of Object.keys(e.statuses)){if(!xc(r)&&!["openpond","codex","openai","claude-code","grok-build","opencode","custom-openai-compatible"].includes(r)||!Sq(r)||t.localOnly&&r==="openpond")continue;const i=Ig(e,r);i&&(!n&&(r==="codex"&&!i.available&&!i.credential.connected||r!=="openpond"&&r!=="codex"&&!i.enabled)||a&&r!=="openpond"&&!i.enabled||a&&r==="codex"&&!i.available&&!i.credential.connected||s.push({value:r,label:r==="openpond"?"OpenPond Chat":i.displayName,description:r==="openpond"?void 0:i.available?"Connected":i.credential.connected?"Configured":i.routing.localByok?"Set up key":i.enabled?"Enabled":void 0}))}return s.length>0?s:cp}function Oc(e,t){const a=(_g(t,e)?.models??[]).filter(c=>e!=="openpond"||c.id!==ii).map(vq),s=iI(t,e),r=[...s?.modelOverrides??[],s?.defaultModel].filter(c=>!!c?.trim()&&(e!=="openpond"||c!==ii)).map(c=>({value:c,label:aI(c)})),i=e==="openpond"&&a.length>0?[]:bq(e);return yq([...a,...r,...i])}function cI(e,t,n){if(e!=="openpond")return yf;const a=_g(n,e)?.models.find(r=>r.id===t)?.capabilities;if(!a?.reasoningEfforts.length)return yf;const s=new Set(a.reasoningEfforts);return fq.filter(r=>s.has(r.value))}function xq(e,t,n){const a=cI(e,t,n),s=e==="openpond"&&(t==="gpt-6-luna"||t==="gpt-6-sol"||t==="claude-opus-5-5")?"medium":"high";return a.some(r=>r.value===s)?s:a[0]?.value??"high"}function kq(e,t,n,a){return cI(e,t,a).some(s=>s.value===n)?n:xq(e,t,a)}function wq(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const s=_g(n,e)?.models.find(r=>r.id===a);return s?!!s.capabilities.reasoning:Oc(e,n).some(r=>r.value===a&&/\breasoning\b/i.test(r.description??""))}function Nd(e,t){const n=iI(t,e)?.defaultModel?.trim();if(n)return n;const a=Ig(t,e)?.defaultModel?.trim();if(a)return a;const s=Oc(e,t)[0]?.value?.trim();return s||(e==="codex"?rh:e==="openpond"?ii:"")}function Sr(e,t,n){const a=t?.trim();if(xc(e))return a??"";if(a&&["opencode","grok-build","claude-code"].includes(e))return a;if(e==="codex"&&(a==="codex-default"||a==="gpt-5.5"))return rh;const s=Oc(e,n);return a&&s.some(r=>r.value===a)||a&&e!=="codex"&&s.length===0&&!n?a:Nd(e,n)}function lI(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:Sr(n,e.modelRef?.modelId,t)}}function Cg(e,t,n){return Sr(e,t,n)||void 0}function Da(e,t,n){const a=Cg(e,t,n);return a?{providerId:e,modelId:a}:void 0}function Ab(e){return e==="full-access"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function Sa(e){const t=e?.defaultChatProvider??Rt.defaultChatProvider;return{defaultChatProvider:t,defaultChatModel:Sr(t,e?.defaultChatModel),subagents:kc.parse(e?.subagents??Rt.subagents),codexPermissionMode:e?.codexPermissionMode??Rt.codexPermissionMode,codexReasoningEffort:e?.codexReasoningEffort??Rt.codexReasoningEffort,openPondCommandAccessMode:e?.openPondCommandAccessMode??Rt.openPondCommandAccessMode,defaultBranchPrefix:dI(e?.defaultBranchPrefix),defaultNewProjectDirectory:e?.defaultNewProjectDirectory??Rt.defaultNewProjectDirectory,defaultTeamId:e?.defaultTeamId?.trim()||null,advancedWorkspaceControls:e?.advancedWorkspaceControls??Rt.advancedWorkspaceControls,steerActiveResponses:e?.steerActiveResponses??Rt.steerActiveResponses,contextCompaction:{autoEnabled:e?.contextCompaction?.autoEnabled??Rt.contextCompaction.autoEnabled,triggerPercent:e?.contextCompaction?.triggerPercent??Rt.contextCompaction.triggerPercent,summaryModel:e?.contextCompaction?.summaryModel??Rt.contextCompaction.summaryModel},training:{defaultModelRef:e?.training?.defaultModelRef??Rt.training.defaultModelRef,creationMode:e?.training?.creationMode??Rt.training.creationMode,autoApproveEvidence:e?.training?.autoApproveEvidence??Rt.training.autoApproveEvidence},sidebarWidth:e?.sidebarWidth??Rt.sidebarWidth,diffPanelWidth:e?.diffPanelWidth??Rt.diffPanelWidth,sidebarSectionsCollapsed:{pinned:e?.sidebarSectionsCollapsed?.pinned??Rt.sidebarSectionsCollapsed.pinned,projects:e?.sidebarSectionsCollapsed?.projects??Rt.sidebarSectionsCollapsed.projects,cloudProjects:e?.sidebarSectionsCollapsed?.cloudProjects??Rt.sidebarSectionsCollapsed.cloudProjects,chats:e?.sidebarSectionsCollapsed?.chats??Rt.sidebarSectionsCollapsed.chats,savedForLater:e?.sidebarSectionsCollapsed?.savedForLater??Rt.sidebarSectionsCollapsed.savedForLater},editor:{languageServers:e?.editor?.languageServers??Rt.editor.languageServers,diagnosticsWhileEditing:e?.editor?.diagnosticsWhileEditing??Rt.editor.diagnosticsWhileEditing,checkOnSave:e?.editor?.checkOnSave??Rt.editor.checkOnSave,languages:{typescript:{mode:e?.editor?.languages?.typescript?.mode??Rt.editor.languages.typescript.mode,customCommand:e?.editor?.languages?.typescript?.customCommand??Rt.editor.languages.typescript.customCommand},python:{mode:e?.editor?.languages?.python?.mode??Rt.editor.languages.python.mode,customCommand:e?.editor?.languages?.python?.customCommand??Rt.editor.languages.python.customCommand},rust:{mode:e?.editor?.languages?.rust?.mode??Rt.editor.languages.rust.mode,customCommand:e?.editor?.languages?.rust?.customCommand??Rt.editor.languages.rust.customCommand}}}}}function dI(e){const t=e?.trim()??Rt.defaultBranchPrefix;if(!t)return"";const a=t.toLowerCase().replace(/[^a-z0-9._/-]+/g,"-").replace(/\/{2,}/g,"/").replace(/^-+/,"").slice(0,48).split("/").map(s=>s.replace(/^-+|-+$/g,"")).filter(Boolean).join("/");return a?`${a}/`:""}function hG(e,t){return e==="openpond"?"OpenPond Chat":Ig(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function gG(e,t,n){if(n){const a=Oc(n,t).find(s=>s.value===e);if(a)return a.label}if(t)for(const a of Object.keys(t.statuses)){const s=Oc(a,t).find(r=>r.value===e);if(s)return s.label}return[...sI,...rI].find(a=>a.value===e)?.label??e}function Iq(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function _q(e){return e.experience==="chat"?"Chat":"Work"}const Rg="taskDraft";function uI(e){if(e?.experience!=="work")return null;const t=e.metadata?.[Rg];if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t.prompt;return typeof n=="string"&&n.trim()?n:null}function $c(e){return uI(e)!==null}function Cq(e){return(e.split(/\r?\n/u).map(n=>n.trim()).find(Boolean)||"Task draft").slice(0,64)}function lp(e,t,n=new Date().toISOString()){const a={version:1,prompt:t,savedAt:n};return{...e??{},[Rg]:a}}function Rq(e){const t={...e??{}};return delete t[Rg],t}function Ko(e){const t=Ll(e.metadata?.trainingTasksetId)??Ll(e.metadata?.tasksetId);return t?{id:t,name:Ll(e.metadata?.trainingTasksetName)??Ll(e.metadata?.tasksetName)??Pq(t)}:null}function Pq(e){const n=e.replace(/[-_][a-f0-9]{8,}$/i,"").replace(/^(?:benchmark[-_])?taskset[-_]/i,"").replace(/^benchmark[-_]/i,"").split(/[-_]+/).filter(Boolean);return n.length===0?"Taskset":n.map(a=>/^[A-Z0-9]{2,}$/.test(a)?a:`${a.charAt(0).toUpperCase()}${a.slice(1)}`).join(" ")}function Ll(e){return typeof e=="string"&&e.trim()?e.trim():null}const Tq="codex_history_";function Gt(e){return!!e?.startsWith(Tq)}function mI(e){const t=[],n=new Set;for(const a of e)for(const s of[a.workspacePath,a.path]){const r=Iu(s);if(!r)continue;const i=`${a.id}:${r}`;n.has(i)||(n.add(i),t.push({projectId:a.id,path:r}))}return t.sort((a,s)=>s.path.length-a.path.length)}function Aq(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=pI(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"||!fI(e))return null;const s=Iu(e.cwd);if(!s)return null;for(const r of n)if(Pg(s,r.path))return r.projectId;return null}function Eb(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return ct("local",e.localProjectId);if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return ct("local",e.workspaceId);if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const r=pI(e.cwd,n);if(r)return ct("local",r)}if(e.cloudProjectId&&a.has(e.cloudProjectId))return ct("cloud",e.cloudProjectId);if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!fI(e))return null;const s=Iu(e.cwd);if(!s)return null;for(const r of n)if(Pg(s,r.path))return ct("local",r.projectId);return null}function pI(e,t){const n=Iu(e);if(!n)return null;for(const a of t)if(Pg(n,a.path))return a.projectId;return null}function fI(e){return e.workspaceKind==="local_project"||e.provider==="codex"||Gt(e.id)}function Iu(e){const t=e?.trim();if(!t)return null;let n=t.replace(/^file:\/\/+/i,"/").replace(/\\/g,"/").replace(/\/+/g,"/");return/^[a-z]:/i.test(n)&&(n=n[0].toUpperCase()+n.slice(1)),n=n.replace(/\/+$/g,""),n||"/"}function Pg(e,t){const n=jb(e),a=jb(t);return n===a||n.startsWith(`${a}/`)}function jb(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}const Mb=[{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"}],Eq=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function dp(e){const t=[];if(e.filter==="done")t.push(...e.doneSessions.filter(s=>!Ko(s)));else if(e.filter==="all")t.push(...e.activeSessions.filter(s=>!Ko(s)),...e.doneSessions.filter(s=>!Ko(s)));else if(e.filter==="tasksets")t.push(...e.activeSessions.filter(s=>Ob(s,e.selectedTasksetId)),...e.doneSessions.filter(s=>Ob(s,e.selectedTasksetId)));else for(const s of e.activeSessions)Ko(s)||(e.filter==="active"?s.savedForLater||t.push(s):e.filter==="in_progress"?!s.savedForLater&&e.inProgressSessionIds.has(s.id)&&t.push(s):e.filter==="pinned"?s.pinned&&!s.savedForLater&&t.push(s):e.filter==="saved_for_later"&&s.savedForLater&&t.push(s));const n=t.filter(s=>dd(s,{inProgressSessionIds:e.inProgressSessionIds,onlyRunningTasks:e.onlyRunningTasks,showCodexChats:e.showCodexChats})),a=e.previewSessionIds?new Map(e.previewSessionIds.map((s,r)=>[s,r])):null;return e.sort==="recent"?n.sort((s,r)=>Db(s,r,a)):n.sort((s,r)=>{const i=a?.get(s.id),c=a?.get(r.id);if(i!==void 0||c!==void 0){if(i===void 0)return 1;if(c===void 0)return-1;if(i!==c)return i-c}return s.order!==r.order?s.order-r.order:Db(s,r)})}function dd(e,t){return t.showCodexChats===!1&&(e.provider==="codex"||Gt(e.id))?!1:!t.onlyRunningTasks||t.inProgressSessionIds.has(e.id)}function Ob(e,t){const n=Ko(e);return!!(n&&(!t||n.id===t))}function $b(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 Nb(e,t,n){const a=new Set(t);let s=0;return e.map(r=>{if(!a.has(r))return r;const i=n[s];return s+=1,i??r})}function Db(e,t,n=null){const a=Wo(e),s=Wo(t);if(a!==s)return a?-1:1;if(a&&s){const i=n?.get(e.id),c=n?.get(t.id);if(i!==void 0||c!==void 0){if(i===void 0)return 1;if(c===void 0)return-1;if(i!==c)return i-c}if(e.order!==t.order)return e.order-t.order}const r=Date.parse(t.updatedAt)-Date.parse(e.updatedAt);return r!==0?r:e.title.localeCompare(t.title)}function Wo(e){return e.pinned&&!e.savedForLater&&!e.archived}const zl={showCodexChats:!0,onlyRunningTasks:!1},hI="openpond.sidebar-task-visibility.v1";function Lb(e=gI()){try{const t=e?.getItem(hI);if(!t)return zl;const n=JSON.parse(t);return{showCodexChats:typeof n.showCodexChats=="boolean"?n.showCodexChats:zl.showCodexChats,onlyRunningTasks:typeof n.onlyRunningTasks=="boolean"?n.onlyRunningTasks:zl.onlyRunningTasks}}catch{return zl}}function zb(e,t=gI()){try{t?.setItem(hI,JSON.stringify(e))}catch{}}function gI(){return typeof window>"u"?null:no}function vI(e){return`${e.kind}:${e.id}`}function Nc(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function jq(e){return{kind:"session",id:e}}function Mq(e){return{kind:"project",id:e}}function Oq(e){return{kind:"draft",id:e}}function $q(e){return e.selectedSessionId?jq(e.selectedSessionId):e.selectedProjectId?Mq(e.selectedProjectId):Oq(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function Nq(e){if(!e.previousScope||e.previousScope.kind!=="draft"||e.activeScope.kind!=="session")return[...e.tabs];if(Nc(e.previousScope,e.activeScope))return[...e.tabs];const t=e.now??Date.now();return e.tabs.map(n=>Nc(n.scope,e.previousScope)?{...n,scope:e.activeScope,updatedAt:t}:n)}function vG(e,t){return e.filter(n=>Nc(n.scope,t))}function bG(e,t){return!!(e&&Nc(e.scope,t))}function Dq(e){const t={};for(const n of e){const a=vI(n.scope),s=t[a]??{scope:n.scope,tabCount:0,runningCount:0,failedCount:0,lastExitCode:null,status:"none"};s.tabCount+=1,n.commandStatus==="running"&&(s.runningCount+=1),(n.commandStatus==="failed"||n.status==="error")&&(s.failedCount+=1),n.lastExitCode!==null&&(s.lastExitCode=n.lastExitCode),s.status=zq(s.status,n.status,n.commandStatus),t[a]=s}return t}function Lq(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 zq(e,t,n){return n==="running"?"running":e==="running"?e:n==="failed"||t==="error"?"failed":e==="failed"?e:n==="success"?e==="none"||e==="unknown"||e==="idle"?"success":e:n==="idle"?e==="none"||e==="unknown"?"idle":e:e==="none"?"unknown":e}function bI(e,t){if(!e)return t?.path??"Use files on this machine";if(e.error)return"status unavailable";if(!e.initialized)return"not checked out";const a=[e.currentBranch??t?.branch??e.defaultBranch??"no branch"],s=Uq(e),r=t?.linkedCloudSourceKnown===!1&&!!e.headCommit;return s?a.push(s):r?a.push("upload required"):e.diverged?(e.ahead>0&&a.push(rr("ahead",e.ahead)),e.behind>0&&a.push(rr("behind",e.behind)),a.push("diverged")):(e.ahead>0&&a.push(rr("ahead",e.ahead)),e.behind>0&&a.push(rr("behind",e.behind))),e.changedFilesCount>0?a.push(`${e.changedFilesCount} changed`):e.dirty&&a.push("dirty"),e.untrackedFilesCount>0&&a.push(`${e.untrackedFilesCount} untracked`),a.length===1&&a.push("synced"),a.join(" / ")}function yI(e,t,n,a={}){const s=e?.linkedSandboxProject??null;if(!s?.projectId&&!t)return"upload required";if(s?.projectId&&a.cloudLinkTrusted===!1)return"uploaded to a different account";const r=s?.defaultBranch??t?.defaultBranch??"main",i=s?.manifestHash??null,c=e?.sandboxTemplate?.manifestHash??null,l=s?.syncedAt??t?.syncedAt??null,u=!!(i&&c&&i!==c),p=!!(s?.projectId&&n?.headCommit&&!s.lastUploadedCommit),f=qq(n);return f?`${r} / ${f}`:p?`${r} / upload required`:`${r} / ${u||!l?"needs sync":"setup ready"}`}function Hq(e,t,n={}){if(!e)return"select a local project";if(e.linkedSandboxProject?.projectId&&n.cloudLinkTrusted===!1)return"sync to this account";if(!t)return e.linkedSandboxProject?"sync source to cloud":"push local source to cloud";if(t.error)return"repo status unavailable";if(!t.initialized)return"local repo unavailable";const a=[],s=t.aheadOfLinkedSource>0?t.aheadOfLinkedSource:t.ahead;return e.linkedSandboxProject?.projectId||a.push("upload required"),e.linkedSandboxProject?.projectId&&t.headCommit&&!e.linkedSandboxProject.lastUploadedCommit&&a.push("upload required"),s>0&&a.push(SI(s)),t.linkedSourceHeadCommit&&t.headCommit&&t.linkedSourceHeadCommit!==t.headCommit&&t.linkedSourceComparisonError&&s===0&&a.push("source changed"),t.changedFilesCount>0&&a.push(`${t.changedFilesCount} changed file${t.changedFilesCount===1?"":"s"}`),t.untrackedFilesCount>0&&a.push(`${t.untrackedFilesCount} untracked skipped`),a.length>0?a.join(" / "):"nothing to upload"}function Uq(e){return e.linkedSourceHeadCommit?e.divergedFromLinkedSource?"diverged":e.aheadOfLinkedSource>0?rr("local ahead",e.aheadOfLinkedSource):e.behindLinkedSource>0?rr("cloud ahead",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"sync unknown":null:null}function qq(e){return e?.linkedSourceHeadCommit?e.dirty?"local dirty files not in cloud":e.divergedFromLinkedSource?"diverged from local":e.aheadOfLinkedSource>0?rr("cloud behind local",e.aheadOfLinkedSource):e.behindLinkedSource>0?rr("cloud ahead local",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"source check unavailable":"synced":null}function rr(e,t){return`${e} by ${SI(t)}`}function SI(e){return`${e} commit${e===1?"":"s"}`}function Bq({size:e=14,className:t}){return g.jsxs("svg",{className:["lucide lucide-cloud-upload",t??""].filter(Boolean).join(" "),xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[g.jsx("path",{d:"M12 13v8"}),g.jsx("path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"}),g.jsx("path",{d:"m8 17 4-4 4 4"})]})}function xI({kind:e,linkedCloud:t=!1,open:n=!1,className:a,baseSize:s=15}){const r=e==="cloud"?"cloud":n?"folder-open":"folder";return g.jsx("span",{className:["project-kind-icon",e,t?"linked-cloud":"",a??""].filter(Boolean).join(" "),"aria-hidden":"true",children:g.jsxs("svg",{className:`lucide lucide-${r} project-kind-icon-svg`,xmlns:"http://www.w3.org/2000/svg",width:s,height:s,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e==="cloud"?g.jsx(Kq,{}):n?g.jsx(Vq,{}):g.jsx(Fq,{}),t&&e==="local"?g.jsx(Wq,{}):null]})})}function Fq(){return g.jsx("path",{className:"project-kind-icon-base",d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}function Vq(){return g.jsx("path",{className:"project-kind-icon-base",d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"})}function Kq(){return g.jsx("path",{className:"project-kind-icon-base",d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"})}function Wq(){return g.jsxs("g",{className:"project-kind-icon-cloud-badge",children:[g.jsx("circle",{cx:"18",cy:"17",r:"5"}),g.jsx("path",{d:"M20.4 18.6h-4.2a2.2 2.2 0 1 1 2.08-2.9h.88a1.45 1.45 0 1 1 1.24 2.9Z"})]})}var Dd=g_();function Gq({title:e,pinned:t,savedForLater:n,archived:a,onRename:s,onTogglePin:r,onToggleSaveForLater:i,onDockRight:c,onArchive:l}){const u=h.useRef(null),p=h.useRef(null),[f,S]=h.useState(null),b=[...s?[{label:"Rename",Icon:ku,action:s}]:[],{label:t?"Unpin":"Pin",Icon:t?lg:cg,action:r},...i?[{label:n?"Return to active":"Save for later",Icon:n?Hw:zw,action:i}]:[],...c?[{label:"Open in right panel",Icon:df,action:c}]:[],{label:a?"Reopen":"Mark done",Icon:a?jH:ds,action:l}];function w(C=!1){S(null),C&&u.current?.focus()}return h.useEffect(()=>{if(!f)return;p.current?.querySelector("button")?.focus();const C=_=>{!p.current?.contains(_.target)&&!u.current?.contains(_.target)&&S(null)},P=()=>S(null);return document.addEventListener("pointerdown",C),window.addEventListener("resize",P),()=>{document.removeEventListener("pointerdown",C),window.removeEventListener("resize",P)}},[f]),g.jsxs(g.Fragment,{children:[g.jsx("div",{className:`sidebar-row-actions sidebar-task-menu-trigger${f?" is-open":""}`,children:g.jsx("button",{ref:u,type:"button",className:"sidebar-row-action","aria-label":`More actions for task ${e}`,"aria-haspopup":"menu","aria-expanded":!!f,draggable:!1,onDoubleClick:C=>C.stopPropagation(),onClick:C=>{if(C.stopPropagation(),f){w(!0);return}const P=C.currentTarget.getBoundingClientRect();S({left:Math.max(8,Math.min(P.right-192,window.innerWidth-200)),top:Math.max(8,Math.min(P.bottom+4,window.innerHeight-(b.length*32+17)))})},children:g.jsx(Xc,{size:16})})}),f&&Dd.createPortal(g.jsx("div",{ref:p,role:"menu","aria-label":`Actions for ${e}`,className:"sidebar-task-menu",style:f,onClick:C=>C.stopPropagation(),onDoubleClick:C=>C.stopPropagation(),onBlur:C=>{C.currentTarget.contains(C.relatedTarget)||w()},onKeyDown:C=>{C.stopPropagation();const P=Array.from(C.currentTarget.querySelectorAll("button")),_=P.indexOf(document.activeElement);if(C.key==="Escape"&&(C.preventDefault(),w(!0)),["ArrowDown","ArrowUp","Home","End"].includes(C.key)){C.preventDefault();const M=C.key==="Home"?0:C.key==="End"?P.length-1:(_+(C.key==="ArrowDown"?1:-1)+P.length)%P.length;P[M]?.focus()}},children:b.map(({label:C,Icon:P,action:_},M)=>g.jsxs("button",{type:"button",role:"menuitem",className:M===b.length-1?"task-menu-done":void 0,onClick:()=>{w(!0),_()},children:[g.jsx(P,{size:15}),C]},C))}),document.body)]})}function Zq({session:e,onSave:t,onClose:n}){const[a,s]=h.useState(e.title),r=h.useRef(null);h.useEffect(()=>{const l=r.current;l&&(l.focus(),l.select())},[]),h.useEffect(()=>{function l(u){u.key==="Escape"&&n()}return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[n]);function i(){const l=a.trim();l&&(t(l),n())}function c(l){l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),i())}return g.jsx("div",{className:"git-dialog-backdrop rename-chat-backdrop",role:"presentation",onMouseDown:n,children:g.jsxs("section",{className:"git-dialog rename-chat-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"rename-chat-title",onMouseDown:l=>l.stopPropagation(),children:[g.jsx("h2",{id:"rename-chat-title",children:"Rename chat"}),g.jsx("textarea",{ref:r,className:"rename-chat-input",value:a,rows:1,maxLength:200,onChange:l=>s(l.target.value),onKeyDown:c,"aria-label":"Chat title"}),g.jsxs("div",{className:"git-dialog-footer",children:[g.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:n,children:"Cancel"}),g.jsx("button",{type:"button",className:"git-dialog-primary",autoFocus:!0,onClick:i,disabled:!a.trim(),children:"Save"})]})]})})}const Jq=24;function Qq({title:e}){const t=h.useRef(e),[n,a]=h.useState(e);return h.useEffect(()=>{const s=t.current;if(t.current=e,!e){a("");return}if(s||window.matchMedia("(prefers-reduced-motion: reduce)").matches){a(e);return}const r=Array.from(e);let i=0;a("");const c=window.setInterval(()=>{i+=1,a(r.slice(0,i).join("")),i>=r.length&&window.clearInterval(c)},Jq);return()=>window.clearInterval(c)},[e]),g.jsx("span",{className:"sidebar-task-title-text","aria-label":e||"New task",children:n||"New task"})}const Yq="/";function ea(e){return`${Yq}${e.replace(/^\.?\//,"")}`}const Tg=ea("openpond-icon.png"),Xq=ea("openpond-wordlogo-white.png"),yG=ea("tutorials/what-is-an-openpond-agent-poster.png"),SG=ea("tutorials/what-is-an-openpond-agent.vtt"),xG=ea("tutorials/how-to-make-an-agent-poster.png"),kG=ea("tutorials/how-to-make-an-agent.vtt");function wG(e){return ea(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function IG(e){return ea(`tutorials/how-to-make-an-agent-${e}.vtt`)}const Hb={github:ea("connected-apps/github.svg"),google:ea("connected-apps/google.svg"),microsoft_teams:ea("connected-apps/microsoft.svg"),mcp:ea("connected-apps/openpond-mcp.svg"),slack:ea("connected-apps/slack.svg"),x:ea("connected-apps/x.svg")};function _G(e){return Hb[e]??Hb.mcp}const eB={codex:"Codex","claude-code":"Claude Code",opencode:"OpenCode","grok-build":"Grok Build"};function tB({session:e}){const t=eB[e.provider],n=t??(xc(e.provider)?typeof e.metadata?.acpAgentName=="string"?e.metadata.acpAgentName:"ACP agent":e.provider==="openpond"?"OpenPond":e.provider);return g.jsx("span",{className:"conversation-source-icon",role:"img","aria-label":n,title:n,children:t?g.jsx("img",{src:`/agent-sources/${e.provider}.svg`,alt:""}):e.provider==="openpond"?g.jsx("img",{src:Tg,alt:""}):xc(e.provider)?g.jsx(Ib,{size:15,"aria-hidden":"true"}):e.metadata?.nativeSource?g.jsx(UU,{size:15,"aria-hidden":"true"}):e.provider==="openai"?g.jsx(Ib,{size:15,"aria-hidden":"true"}):g.jsx(xu,{size:15,"aria-hidden":"true"})})}var ud={exports:{}},nB=ud.exports,Ub;function aB(){return Ub||(Ub=1,(function(e,t){(function(n,a){e.exports=a()})(nB,(function(){var n=1e3,a=6e4,s=36e5,r="millisecond",i="second",c="minute",l="hour",u="day",p="week",f="month",S="quarter",b="year",w="date",C="Invalid Date",P=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,_=/\[([^\]]+)]|YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(ee){var H=["th","st","nd","rd"],F=ee%100;return"["+ee+(H[(F-20)%10]||H[F]||H[0])+"]"}},E=function(ee,H,F){var J=String(ee);return!J||J.length>=H?ee:""+Array(H+1-J.length).join(F)+ee},T={s:E,z:function(ee){var H=-ee.utcOffset(),F=Math.abs(H),J=Math.floor(F/60),K=F%60;return(H<=0?"+":"-")+E(J,2,"0")+":"+E(K,2,"0")},m:function ee(H,F){if(H.date()<F.date())return-ee(F,H);var J=12*(F.year()-H.year())+(F.month()-H.month()),K=H.clone().add(J,f),B=F-K<0,ne=H.clone().add(J+(B?-1:1),f);return+(-(J+(F-K)/(B?K-ne:ne-K))||0)},a:function(ee){return ee<0?Math.ceil(ee)||0:Math.floor(ee)},p:function(ee){return{M:f,y:b,w:p,d:u,D:w,h:l,m:c,s:i,ms:r,Q:S}[ee]||String(ee||"").toLowerCase().replace(/s$/,"")},u:function(ee){return ee===void 0}},y="en",I={};I[y]=M;var R="$isDayjsObject",O=function(ee){return ee instanceof Y||!(!ee||!ee[R])},z=function ee(H,F,J){var K;if(!H)return y;if(typeof H=="string"){var B=H.toLowerCase();I[B]&&(K=B),F&&(I[B]=F,K=B);var ne=H.split("-");if(!K&&ne.length>1)return ee(ne[0])}else{var G=H.name;I[G]=H,K=G}return!J&&K&&(y=K),K||!J&&y},$=function(ee,H){if(O(ee))return ee.clone();var F=typeof H=="object"?H:{};return F.date=ee,F.args=arguments,new Y(F)},V=T;V.l=z,V.i=O,V.w=function(ee,H){return $(ee,{locale:H.$L,utc:H.$u,x:H.$x,$offset:H.$offset})};var Y=(function(){function ee(F){this.$L=z(F.locale,null,!0),this.parse(F),this.$x=this.$x||F.x||{},this[R]=!0}var H=ee.prototype;return H.parse=function(F){this.$d=(function(J){var K=J.date,B=J.utc;if(K===null)return new Date(NaN);if(V.u(K))return new Date;if(K instanceof Date)return new Date(K);if(typeof K=="string"&&!/Z$/i.test(K)){var ne=K.match(P);if(ne){var G=ne[2]-1||0,te=(ne[7]||"0").substring(0,3);return B?new Date(Date.UTC(ne[1],G,ne[3]||1,ne[4]||0,ne[5]||0,ne[6]||0,te)):new Date(ne[1],G,ne[3]||1,ne[4]||0,ne[5]||0,ne[6]||0,te)}}return new Date(K)})(F),this.init()},H.init=function(){var F=this.$d;this.$y=F.getFullYear(),this.$M=F.getMonth(),this.$D=F.getDate(),this.$W=F.getDay(),this.$H=F.getHours(),this.$m=F.getMinutes(),this.$s=F.getSeconds(),this.$ms=F.getMilliseconds()},H.$utils=function(){return V},H.isValid=function(){return this.$d.toString()!==C},H.isSame=function(F,J){var K=$(F);return this.startOf(J)<=K&&K<=this.endOf(J)},H.isAfter=function(F,J){return $(F)<this.startOf(J)},H.isBefore=function(F,J){return this.endOf(J)<$(F)},H.$g=function(F,J,K){return V.u(F)?this[J]:this.set(K,F)},H.unix=function(){return Math.floor(this.valueOf()/1e3)},H.valueOf=function(){return this.$d.getTime()},H.startOf=function(F,J){var K=this,B=!!V.u(J)||J,ne=V.p(F),G=function(je,De){var He=V.w(K.$u?Date.UTC(K.$y,De,je):new Date(K.$y,De,je),K);return B?He:He.endOf(u)},te=function(je,De){return V.w(K.toDate()[je].apply(K.toDate("s"),(B?[0,0,0,0]:[23,59,59,999]).slice(De)),K)},oe=this.$W,be=this.$M,me=this.$D,Re="set"+(this.$u?"UTC":"");switch(ne){case b:return B?G(1,0):G(31,11);case f:return B?G(1,be):G(0,be+1);case p:var Q=this.$locale().weekStart||0,xe=(oe<Q?oe+7:oe)-Q;return G(B?me-xe:me+(6-xe),be);case u:case w:return te(Re+"Hours",0);case l:return te(Re+"Minutes",1);case c:return te(Re+"Seconds",2);case i:return te(Re+"Milliseconds",3);default:return this.clone()}},H.endOf=function(F){return this.startOf(F,!1)},H.$set=function(F,J){var K,B=V.p(F),ne="set"+(this.$u?"UTC":""),G=(K={},K[u]=ne+"Date",K[w]=ne+"Date",K[f]=ne+"Month",K[b]=ne+"FullYear",K[l]=ne+"Hours",K[c]=ne+"Minutes",K[i]=ne+"Seconds",K[r]=ne+"Milliseconds",K)[B],te=B===u?this.$D+(J-this.$W):J;if(B===f||B===b){var oe=this.clone().set(w,1);oe.$d[G](te),oe.init(),this.$d=oe.set(w,Math.min(this.$D,oe.daysInMonth())).$d}else G&&this.$d[G](te);return this.init(),this},H.set=function(F,J){return this.clone().$set(F,J)},H.get=function(F){return this[V.p(F)]()},H.add=function(F,J){var K,B=this;F=Number(F);var ne=V.p(J),G=function(be){var me=$(B);return V.w(me.date(me.date()+Math.round(be*F)),B)};if(ne===f)return this.set(f,this.$M+F);if(ne===b)return this.set(b,this.$y+F);if(ne===u)return G(1);if(ne===p)return G(7);var te=(K={},K[c]=a,K[l]=s,K[i]=n,K)[ne]||1,oe=this.$d.getTime()+F*te;return V.w(oe,this)},H.subtract=function(F,J){return this.add(-1*F,J)},H.format=function(F){var J=this,K=this.$locale();if(!this.isValid())return K.invalidDate||C;var B=F||"YYYY-MM-DDTHH:mm:ssZ",ne=V.z(this),G=this.$H,te=this.$m,oe=this.$M,be=K.weekdays,me=K.months,Re=K.meridiem,Q=function(De,He,Ie,Me){return De&&(De[He]||De(J,B))||Ie[He].slice(0,Me)},xe=function(De){return V.s(G%12||12,De,"0")},je=Re||function(De,He,Ie){var Me=De<12?"AM":"PM";return Ie?Me.toLowerCase():Me};return B.replace(_,(function(De,He){return He||(function(Ie){switch(Ie){case"YY":return String(J.$y).slice(-2);case"YYYY":return V.s(J.$y,4,"0");case"M":return oe+1;case"MM":return V.s(oe+1,2,"0");case"MMM":return Q(K.monthsShort,oe,me,3);case"MMMM":return Q(me,oe);case"D":return J.$D;case"DD":return V.s(J.$D,2,"0");case"d":return String(J.$W);case"dd":return Q(K.weekdaysMin,J.$W,be,2);case"ddd":return Q(K.weekdaysShort,J.$W,be,3);case"dddd":return be[J.$W];case"H":return String(G);case"HH":return V.s(G,2,"0");case"h":return xe(1);case"hh":return xe(2);case"a":return je(G,te,!0);case"A":return je(G,te,!1);case"m":return String(te);case"mm":return V.s(te,2,"0");case"s":return String(J.$s);case"ss":return V.s(J.$s,2,"0");case"SSS":return V.s(J.$ms,3,"0");case"Z":return ne}return null})(De)||ne.replace(":","")}))},H.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},H.diff=function(F,J,K){var B,ne=this,G=V.p(J),te=$(F),oe=(te.utcOffset()-this.utcOffset())*a,be=this-te,me=function(){return V.m(ne,te)};switch(G){case b:B=me()/12;break;case f:B=me();break;case S:B=me()/3;break;case p:B=(be-oe)/6048e5;break;case u:B=(be-oe)/864e5;break;case l:B=be/s;break;case c:B=be/a;break;case i:B=be/n;break;default:B=be}return K?B:V.a(B)},H.daysInMonth=function(){return this.endOf(f).$D},H.$locale=function(){return I[this.$L]},H.locale=function(F,J){if(!F)return this.$L;var K=this.clone(),B=z(F,J,!0);return B&&(K.$L=B),K},H.clone=function(){return V.w(this.$d,this)},H.toDate=function(){return new Date(this.valueOf())},H.toJSON=function(){return this.isValid()?this.toISOString():null},H.toISOString=function(){return this.$d.toISOString()},H.toString=function(){return this.$d.toUTCString()},ee})(),se=Y.prototype;return $.prototype=se,[["$ms",r],["$s",i],["$m",c],["$H",l],["$W",u],["$M",f],["$y",b],["$D",w]].forEach((function(ee){se[ee[1]]=function(H){return this.$g(H,ee[0],ee[1])}})),$.extend=function(ee,H){return ee.$i||(ee(H,Y,$),ee.$i=!0),$},$.locale=z,$.isDayjs=O,$.unix=function(ee){return $(1e3*ee)},$.en=I[y],$.Ls=I,$.p={},$}))})(ud)),ud.exports}var sB=aB();const kI=f0(sB);var md={exports:{}},rB=md.exports,qb;function oB(){return qb||(qb=1,(function(e,t){(function(n,a){e.exports=a()})(rB,(function(){return function(n,a,s){n=n||{};var r=a.prototype,i={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function c(u,p,f,S){return r.fromToBase(u,p,f,S)}s.en.relativeTime=i,r.fromToBase=function(u,p,f,S,b){for(var w,C,P,_=f.$locale().relativeTime||i,M=n.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],E=M.length,T=0;T<E;T+=1){var y=M[T];y.d&&(w=S?s(u).diff(f,y.d,!0):f.diff(u,y.d,!0));var I=(n.rounding||Math.round)(Math.abs(w));if(P=w>0,I<=y.r||!y.r){I<=1&&T>0&&(y=M[T-1]);var R=_[y.l];b&&(I=b(""+I)),C=typeof R=="string"?R.replace("%d",I):R(I,p,y.l,P);break}}if(p)return C;var O=P?_.future:_.past;return typeof O=="function"?O(C):O.replace("%s",C)},r.to=function(u,p){return c(u,p,this,!0)},r.from=function(u,p){return c(u,p,this)};var l=function(u){return u.$u?s.utc():s()};r.toNow=function(u){return this.to(l(this),u)},r.fromNow=function(u){return this.from(l(this),u)}}}))})(md)),md.exports}var iB=oB();const cB=f0(iB);kI.extend(cB);let xf=Date.now(),Hl;const Ul=new Set,Bb=()=>xf;function lB(e){return Ul.add(e),Hl||(xf=Date.now(),Hl=setInterval(()=>{xf=Date.now();for(const t of Ul)t()},3e4)),()=>{Ul.delete(e),Ul.size===0&&(clearInterval(Hl),Hl=void 0)}}function wI({value:e,className:t}){const n=h.useSyncExternalStore(lB,Bb,Bb),a=e==null?null:kI(e);return a?.isValid()?g.jsx("time",{className:t,dateTime:a.toISOString(),title:`Last activity ${a.format("MMM D, YYYY h:mm A")}`,children:a.from(n)}):null}const dB=2650,uB=304,mB=260;function pB(){return{animationDelay:`${-(Date.now()%dB)}ms`}}function fB(e){const t=e.currentTarget,n=t.firstElementChild;if(!(n instanceof HTMLElement))return;const a=Math.max(0,n.scrollWidth-t.clientWidth),s=a>2;t.dataset.overflowing=String(s),t.style.setProperty("--sidebar-title-ticker-distance",`${-a}px`),t.style.setProperty("--sidebar-title-ticker-duration",`${Math.min(6.5,Math.max(2.8,a/42+2.4))}s`)}function up({label:e,actions:t,actionsVisible:n=!1,className:a,titleAccessory:s,children:r,collapsed:i=!1,titleActive:c=!1,onTitleClick:l,onToggleCollapsed:u}){return g.jsxs("section",{className:["sidebar-section",a,n?"actions-visible":""].filter(Boolean).join(" "),children:[g.jsxs("div",{className:"section-header",children:[g.jsxs("div",{className:"section-title-row",children:[l?g.jsxs("div",{className:"section-title-combo",children:[g.jsx("button",{type:"button",className:`section-title-link${c?" active":""}`,onClick:l,children:g.jsx("span",{children:e})}),u&&g.jsx("button",{type:"button",className:"section-chevron-button","aria-label":`${i?"Expand":"Collapse"} ${e}`,"aria-expanded":!i,onClick:u,children:i?g.jsx(pr,{size:13}):g.jsx(mr,{size:13})})]}):u?g.jsxs("button",{type:"button",className:"section-title-button","aria-label":`${i?"Expand":"Collapse"} ${e}`,"aria-expanded":!i,onClick:u,children:[g.jsx("span",{children:e}),i?g.jsx(pr,{size:13}):g.jsx(mr,{size:13})]}):g.jsx("span",{children:e}),s]}),t&&g.jsx("div",{className:"section-actions",children:t})]}),!i&&g.jsx("div",{className:"sidebar-section-body",children:r})]})}function Fb({children:e,expanded:t=!1,onClick:n}){return g.jsx("button",{type:"button",className:"sidebar-show-more",onClick:n,children:e??(t?"Show less":"Show more")})}function Vb({session:e,selected:t,icon:n,archived:a=!1,nested:s=!1,dragging:r,placeholder:i,running:c,goalRuntime:l,subagentRuntime:u,terminalIndicator:p,projectLabel:f,inbox:S=!1,activityAt:b,ariaDescribedBy:w,childSessionCount:C=0,childSessionsExpanded:P=!1,onSelect:_,onToggleChildSessions:M,onTogglePin:E,onToggleSaveForLater:T,onDockRight:y,onArchive:I,onDragStart:R,onDragEnd:O,onDragOver:z,onDrop:$,onRename:V}){const[Y,se]=h.useState(!1),ee=l?.status==="queued",H=l?.tone==="active"&&!ee,F=(u?.activeCount??0)>0,J=C>0&&!!M,K=F||H||!ee&&(c??e.status==="active"),B=F&&u?u.label:H&&l?gB(l):"Running",ne=["sidebar-task-row",$c(e)?"is-draft":"",K?"has-running-dot":"",S?"sidebar-inbox-row":""].filter(Boolean).join(" "),G=h.useMemo(pB,[]),te=g.jsx(Gq,{title:e.title,pinned:!!e.pinned,savedForLater:!!e.savedForLater,archived:a,onRename:V?()=>se(!0):void 0,onTogglePin:E,onToggleSaveForLater:T,onDockRight:y,onArchive:I}),oe=g.jsxs(Ag,{selected:t,dataSessionId:e.id,dragging:r,nested:s,placeholder:i,className:ne||void 0,ariaExpanded:J?P:void 0,ariaDescribedBy:w,onSelect:_,onDragStart:R,onDragEnd:O,onDragOver:z,onDrop:$,onDoubleClick:V?()=>se(!0):void 0,children:[g.jsx("span",{className:"sidebar-source-slot",children:n??g.jsx(tB,{session:e})}),g.jsxs("span",{className:"sidebar-title-slot",children:[J?g.jsx("button",{type:"button",className:"sidebar-child-toggle","data-tooltip":P?"Hide subagent conversations":"Show subagent conversations","aria-label":`${P?"Hide":"Show"} ${C} subagent ${C===1?"conversation":"conversations"}`,"aria-expanded":P,onClick:me=>{me.stopPropagation(),M?.()},children:P?g.jsx(mr,{size:13}):g.jsx(pr,{size:13})}):null,g.jsxs("span",{className:"row-label-shell",title:e.title,children:[g.jsx("span",{className:"sidebar-session-title-line",children:g.jsx("span",{className:"row-label sidebar-task-title","data-overflowing":"false",onPointerEnter:fB,children:g.jsx(Qq,{title:e.title})})}),S?g.jsxs("span",{className:"sidebar-inbox-project",children:[f?g.jsxs(g.Fragment,{children:[g.jsx("span",{className:"sidebar-inbox-project-name",children:f}),g.jsx("span",{"aria-hidden":"true",children:"|"})]}):null,g.jsx(wI,{value:b??e.createdAt})]}):null]})]}),g.jsxs("div",{className:"row-meta",children:[g.jsxs("span",{className:"row-meta-status",children:[p?g.jsx(II,{indicator:p}):null,K?g.jsx("span",{className:`sidebar-running-dot${F?" subagent":H?" goal":""}`,style:G,"aria-label":B}):null]}),te,S?g.jsx("button",{type:"button",className:"sidebar-inbox-done","aria-label":`${a?"Reopen":"Mark done"}: ${e.title}`,title:a?"Reopen":"Mark done (does not stop running work)",onClick:me=>{me.stopPropagation(),I()},children:a?g.jsx(RU,{size:19}):g.jsx(ds,{size:21})}):null]})]}),be=Y&&V?g.jsx(Zq,{session:e,onSave:me=>V(e,me),onClose:()=>se(!1)}):null;return g.jsxs(g.Fragment,{children:[oe,be]})}function hB({file:e,selected:t=!1,placeholder:n,onSelect:a,onTogglePin:s,onToggleSaveForLater:r,onDragStart:i,onDragEnd:c,onDragOver:l,onDrop:u}){const p=e.path.split("/").at(-1)??e.path,f=`${e.workspaceName} · ${e.path}`;return g.jsxs(Ag,{selected:t,placeholder:n,className:`sidebar-file-row actions-2${e.available?"":" unavailable"}`,onSelect:a,onDragStart:i,onDragEnd:c,onDragOver:l,onDrop:u,children:[e.available?g.jsx(og,{size:15}):g.jsx(jd,{size:15}),g.jsx("span",{className:"row-label-shell",title:f,children:g.jsx("span",{className:"row-label",children:p})}),g.jsx("div",{className:"row-meta",children:g.jsxs("div",{className:"sidebar-row-actions",children:[g.jsx(Ld,{label:e.status==="pinned"?"Unpin file":"Pin file",onClick:s,children:e.status==="pinned"?g.jsx(lg,{size:13}):g.jsx(cg,{size:13})}),g.jsx(Ld,{label:e.status==="saved_for_later"?"Remove from Save for later":"Save file for later",onClick:r,children:e.status==="saved_for_later"?g.jsx(Hw,{size:13}):g.jsx(zw,{size:13})})]})})]})}function gB(e){return e.actionLabel}function vB({kind:e="local",project:t,pinned:n=!1,selected:a,expanded:s=!1,disclosure:r=!0,workspaceState:i,cloudLinkTrusted:c=!0,cloudLinkWarning:l=null,placeholder:u,terminalIndicator:p,onSelect:f,onNewChat:S,onMoveToCloud:b,onWorkspaceTargetSelect:w,onTogglePin:C,onRemove:P,onDragStart:_,onDragEnd:M,onDragOver:E,onDrop:T}){const[y,I]=h.useState(!1),R=h.useRef(null),[O,z]=h.useState({}),$=!!b||!!P,V=e==="local"&&c!==!1&&!!t.linkedSandboxProject?.projectId,Y=h.useCallback(()=>{if(typeof window>"u")return;const H=R.current?.getBoundingClientRect();if(!H)return;const F=Math.max(12,window.innerWidth-uB-12),J=Math.max(12,window.innerHeight-mB),K=Math.max(12,Math.min(H.right+10,F)),B=Math.max(12,Math.min(H.top-4,J)),ne={"--sidebar-project-locations-left":`${Math.round(K)}px`,"--sidebar-project-locations-top":`${Math.round(B)}px`};z(G=>G["--sidebar-project-locations-left"]===ne["--sidebar-project-locations-left"]&&G["--sidebar-project-locations-top"]===ne["--sidebar-project-locations-top"]?G:ne)},[]),se=h.useCallback(()=>{Y(),f()},[f,Y]);function ee(){I(!1)}return g.jsxs("div",{ref:R,className:["sidebar-project-row-shell",y?"project-menu-open":""].filter(Boolean).join(" "),onFocusCapture:Y,onPointerEnter:Y,children:[g.jsxs(Ag,{selected:a,placeholder:u,className:["sidebar-project-row",y?"project-menu-open":""].filter(Boolean).join(" "),ariaExpanded:r?s:void 0,onSelect:se,onDragStart:_,onDragEnd:M,onDragOver:E,onDrop:T,children:[g.jsx(xI,{kind:e,linkedCloud:V,open:e==="local"&&s,className:"sidebar-row-icon",baseSize:15}),g.jsx("span",{className:"row-label-shell",children:g.jsxs("span",{className:"sidebar-project-title-line",children:[g.jsx("span",{className:"row-label",children:t.name}),g.jsxs("span",{className:"sidebar-row-updated-at",children:[g.jsx("span",{"aria-hidden":"true",children:"| "}),g.jsx(wI,{value:t.updatedAt})]}),r?g.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:s?g.jsx(mr,{size:13}):g.jsx(pr,{size:13})}):null]})}),g.jsxs("div",{className:"row-meta",children:[g.jsx("span",{className:"row-meta-status",children:p?g.jsx(II,{indicator:p}):null}),g.jsxs("div",{className:"sidebar-row-actions",children:[g.jsx(Ld,{label:n?"Unpin project":"Pin project",onClick:C,children:n?g.jsx(lg,{size:13}):g.jsx(cg,{size:13})}),$&&g.jsx(AB,{open:y,onToggleOpen:()=>I(H=>!H)}),g.jsx(Ld,{label:"New task",onClick:S,children:g.jsx(ku,{size:13})})]})]})]}),g.jsx(bB,{kind:e,project:t,workspaceState:i,cloudLinkTrusted:c,cloudLinkWarning:l,onWorkspaceTargetSelect:w,style:O}),y&&g.jsx(EB,{onClose:ee,onMoveToCloud:b?()=>{ee(),b()}:void 0,onRemove:()=>{ee(),P()}})]})}function II({indicator:e}){return g.jsx("span",{className:`sidebar-terminal-indicator ${e.status}`,"data-tooltip":e.label,"aria-label":e.label,title:e.label,children:g.jsx(Gw,{size:13})})}function bB({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:s,onWorkspaceTargetSelect:r,style:i}){const c=xB(e,t,n,a,s);return g.jsxs("aside",{className:"sidebar-project-locations-popover","aria-label":`${t.name} status`,style:i,children:[g.jsx("div",{className:"sidebar-project-locations-title",children:t.name}),g.jsx("div",{className:"sidebar-project-location-list",children:c.map(l=>{const u=["sidebar-project-location-row",l.tone??"",l.actionTarget?"clickable":""].filter(Boolean).join(" "),p=g.jsxs(g.Fragment,{children:[g.jsx("span",{className:["sidebar-project-location-icon",l.key].filter(Boolean).join(" "),"aria-hidden":"true",children:l.icon}),g.jsx("span",{className:"sidebar-project-location-copy",children:g.jsx(yB,{value:l.value})})]});return l.actionTarget?g.jsx("button",{type:"button",className:u,"data-workspace-target":l.actionTarget,disabled:l.disabled||!r,title:l.disabledReason??void 0,onClick:f=>{f.stopPropagation(),!l.disabled&&r?.(l.actionTarget)},children:p},l.key):g.jsx("div",{className:u,children:p},l.key)})})]})}function yB({value:e}){const t=SB(e);return g.jsxs("span",{className:"sidebar-project-location-value","aria-label":e,children:[t.branch?g.jsxs(g.Fragment,{children:[g.jsx("span",{className:"sidebar-project-location-branch",children:t.branch}),g.jsx("span",{className:"sidebar-project-location-separator","aria-hidden":"true",children:"/"})]}):null,g.jsx("span",{className:"sidebar-project-location-status",children:t.status})]})}function SB(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function xB(e,t,n,a=!0,s=null){return e==="cloud"?wB(t):kB(t,n,a,s)}function kB(e,t,n=!0,a=null){const s=IB(e,t,n),r=_B(t),i=RB(e,n),c=n===!1&&a;return[{key:"local",value:s,tone:r?"attention":"local",icon:e.source==="git"?g.jsx(ig,{size:13}):g.jsx(Fw,{size:13}),actionTarget:"local"},{key:"cloud",value:c||(i?PB(e,t,n):"not in cloud"),tone:c?"attention":"cloud",icon:g.jsx(yu,{size:13}),actionTarget:i?"cloud":"upload_cloud"}]}function wB(e){return[{key:"cloud",value:TB(e),tone:e.syncedAt?"cloud":"attention",icon:g.jsx(yu,{size:13}),actionTarget:"cloud"}]}function IB(e,t,n){const a=CB(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?bI(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function _B(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function CB(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function RB(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function PB(e,t,n){return yI(e,null,t,{cloudLinkTrusted:n})}function TB(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function AB({open:e,onToggleOpen:t}){return g.jsx("button",{type:"button",className:`sidebar-row-action ${e?"active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-haspopup":"menu","aria-expanded":e,onClick:n=>{n.stopPropagation(),t()},children:g.jsx(Xc,{size:13})})}function EB({onClose:e,onMoveToCloud:t,onRemove:n}){return g.jsxs(g.Fragment,{children:[g.jsx("button",{type:"button",className:"sidebar-project-menu-backdrop","aria-label":"Close project actions",onClick:a=>{a.stopPropagation(),e()}}),g.jsxs("div",{className:"section-menu-popover sidebar-project-row-popover",role:"menu",children:[t&&g.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),t()},children:[g.jsx(Bq,{size:13}),g.jsx("span",{children:"Move to Cloud"})]}),g.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),n()},children:[g.jsx(el,{size:13}),g.jsx("span",{children:"Remove from Projects"})]})]})]})}function Ag({children:e,className:t,dataSessionId:n,dragging:a,iconless:s=!1,nested:r=!1,placeholder:i=!1,selected:c,ariaExpanded:l,ariaDescribedBy:u,onSelect:p,onDragStart:f,onDragEnd:S,onDragOver:b,onDrop:w,onDoubleClick:C}){const P=!!f;return g.jsx("div",{className:["sidebar-row",t??"",c?"selected":"",a?"dragging":"",s?"iconless":"",r?"nested":"",i?"placeholder":""].filter(Boolean).join(" "),draggable:P,"data-session-id":n,role:"button",tabIndex:0,"aria-expanded":l,"aria-describedby":u,onClick:p,onDoubleClick:C,onKeyDown:_=>{_.target===_.currentTarget&&(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),p())},onDragStart:f,onDragEnd:S,onDragEnter:_=>{b&&(_.preventDefault(),_.dataTransfer.dropEffect="move",b(_))},onDragOver:_=>{b&&(_.preventDefault(),_.dataTransfer.dropEffect="move",b(_))},onDrop:_=>{w&&(_.preventDefault(),w(_))},children:e})}function Ld({children:e,label:t,onClick:n}){return g.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":t,"aria-label":t,onClick:a=>{a.stopPropagation(),n()},children:e})}function jB({filter:e,activityOrder:t=!1,groupByProject:n,noun:a,onFilterChange:s,onGroupByProjectChange:r,onOnlyRunningTasksChange:i,onShowCodexChatsChange:c,onTasksetChange:l,onSortChange:u,onlyRunningTasks:p,openMenu:f,setOpenMenu:S,showCodexChats:b,sort:w,selectedTasksetId:C,tasksets:P}){const _=h.useRef(null),[M,E]=h.useState(!1),y=P.find(O=>O.id===C)?.name??Mb.find(O=>O.value===e)?.label??"Active",I=f==="tasks-filter",R=f==="chats";return h.useEffect(()=>{if(!I&&!R)return;function O(z){_.current?.contains(z.target)||S(null)}return document.addEventListener("pointerdown",O),()=>document.removeEventListener("pointerdown",O)},[I,S,R]),g.jsxs("div",{className:"sidebar-task-list-controls",ref:_,children:[g.jsxs("div",{className:"section-menu",children:[g.jsx("button",{type:"button",className:`section-icon ${R?"active":""}`,"aria-label":`${a==="tasks"?"Task":"Chat"} list options`,"aria-haspopup":"menu","aria-expanded":R,onClick:()=>S(O=>O==="chats"?null:"chats"),children:g.jsx(Xc,{size:14})}),R?g.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":`${a==="tasks"?"Task":"Chat"} list options`,children:[g.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":b,onClick:()=>c(!b),children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:b?g.jsx(ds,{size:13}):null}),g.jsx("span",{children:"Show Codex chats, including pinned"})]}),g.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":p,onClick:()=>i(!p),children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:p?g.jsx(ds,{size:13}):null}),g.jsxs("span",{children:["Only running ",a,", including pinned"]})]}),a==="tasks"&&!t?g.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":n,onClick:()=>r(!n),children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:n?g.jsx(ds,{size:13}):null}),g.jsx("span",{children:"Group by project"})]}):null,t?g.jsx("p",{className:"empty-row",children:"Latest activity first"}):Eq.map(O=>g.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w===O.value,onClick:()=>{u(O.value),S(null)},children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:w===O.value?g.jsx(ds,{size:13}):null}),g.jsx("span",{children:O.label})]},O.value))]}):null]}),g.jsxs("div",{className:"section-menu",children:[g.jsx("button",{type:"button",className:`section-icon ${I?"active":""}`,"aria-label":`Filter ${a}: ${y}`,"aria-haspopup":"menu","aria-expanded":I,onClick:()=>S(O=>O==="tasks-filter"?null:"tasks-filter"),children:g.jsx(uU,{size:14})}),I?g.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${a}`,children:Mb.map(O=>g.jsxs(h.Fragment,{children:[O.value==="tasksets"?g.jsxs("button",{type:"button",role:"menuitem","aria-expanded":M,onClick:()=>E(z=>!z),children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:M?g.jsx(mr,{size:13}):g.jsx(pr,{size:13})}),g.jsx("span",{children:O.label})]}):g.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e===O.value,onClick:()=>{s(O.value),S(null)},children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e===O.value?g.jsx(ds,{size:13}):null}),g.jsx("span",{children:O.label})]}),O.value==="tasksets"&&M?g.jsxs(g.Fragment,{children:[g.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&!C,onClick:()=>{l(null),S(null)},children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&!C?g.jsx(ds,{size:13}):null}),g.jsx("span",{children:"All Tasksets"})]}),P.map(z=>g.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&C===z.id,onClick:()=>{l(z.id),S(null)},children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&C===z.id?g.jsx(ds,{size:13}):null}),g.jsx("span",{children:z.name}),g.jsx("span",{className:"section-menu-option-count","aria-hidden":"true",children:z.chatCount})]},z.id))]}):null]},O.value))}):null]})]})}function MB({onAddProject:e,onViewProjects:t}){const[n,a]=h.useState(!1),s=h.useRef(null),r=h.useRef(null);return h.useEffect(()=>{if(!n)return;s.current?.querySelector('[role="menuitem"]')?.focus();const i=c=>{s.current?.contains(c.target)||a(!1)};return document.addEventListener("pointerdown",i),()=>document.removeEventListener("pointerdown",i)},[n]),g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"section-menu",ref:s,onKeyDown:i=>{i.key==="Escape"&&(i.stopPropagation(),a(!1),r.current?.focus())},children:[g.jsx("button",{ref:r,type:"button",className:`section-icon${n?" active":""}`,"aria-label":"Project options","aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(i=>!i),children:g.jsx(Xc,{size:14})}),n?g.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":"Project options",children:[g.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),t()},children:"View all projects"}),g.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),e()},children:"Add project"})]}):null]}),g.jsx("button",{type:"button",className:"section-icon",onClick:e,"aria-label":"Add project",title:"Add project",children:"+"})]})}const OB=240,$B=36;function NB(e,t,n=!1){const a=Math.max(12,t.width-OB-12),s=Math.max(12,t.height-$B-(n?22:0)-12);return{"--sidebar-task-detail-left":`${Math.round(Math.max(12,Math.min(e.right+10,a)))}px`,"--sidebar-task-detail-top":`${Math.round(Math.max(12,Math.min(e.top-4,s)))}px`}}function DB({detail:e,onClose:t}){if(h.useEffect(()=>{if(!e||typeof window>"u")return;const s=c=>{c.key==="Escape"&&t()};let r=!1;const i=window.requestAnimationFrame(()=>{window.addEventListener("scroll",t,!0),r=!0});return window.addEventListener("keydown",s),()=>{window.cancelAnimationFrame(i),window.removeEventListener("keydown",s),r&&window.removeEventListener("scroll",t,!0)}},[e,t]),!e)return null;const n=new Date(e.updatedAt),a=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(n);return g.jsxs("aside",{id:e.descriptionId,className:"sidebar-task-detail-popover",style:e.style,role:"tooltip","aria-label":`Last updated for ${e.title}`,children:[g.jsx("time",{dateTime:e.updatedAt,children:a}),e.folderName?g.jsxs("div",{className:"sidebar-task-detail-folder",children:[g.jsx(Fw,{size:13,"aria-hidden":"true"}),g.jsx("span",{children:e.folderName})]}):null]})}function LB({children:e,expanded:t,groupKey:n,kind:a,label:s,onToggle:r,onNewTask:i,onOpenProject:c,onRemoveProject:l,project:u}){const p=`sidebar-task-group-${n.replace(/[^a-zA-Z0-9_-]/g,"-")}`,f=a==="draft"?og:xu,[S,b]=h.useState(!1),w=!!(i||c||l);return g.jsxs("section",{className:"sidebar-task-project-group",children:[g.jsxs("div",{className:`sidebar-task-project-group-header-shell${S?" menu-open":""}`,children:[g.jsxs("button",{type:"button",className:"sidebar-task-project-group-header","aria-controls":p,"aria-expanded":t,onClick:()=>{b(!1),r()},children:[u?g.jsx(xI,{kind:u.kind,linkedCloud:!!(u.kind==="local"&&u.project.linkedSandboxProject?.projectId),open:u.kind==="local"&&t,className:"sidebar-task-project-group-icon",baseSize:14}):g.jsx(f,{className:"sidebar-task-project-group-icon",size:14,"aria-hidden":"true"}),g.jsx("span",{className:"sidebar-task-project-group-name",children:s}),g.jsx("span",{className:"sidebar-task-project-group-caret","aria-hidden":"true",children:t?g.jsx(mr,{size:13}):g.jsx(pr,{size:13})})]}),u&&w?g.jsxs("div",{className:"sidebar-task-project-group-actions",children:[c||l?g.jsx("button",{type:"button",className:`sidebar-row-action${S?" active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-expanded":S,"aria-haspopup":"menu",onClick:()=>b(C=>!C),children:g.jsx(Xc,{size:13})}):null,i?g.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":"New task","aria-label":"New task",onClick:i,children:g.jsx(ku,{size:13})}):null]}):null,S?g.jsxs(g.Fragment,{children:[g.jsx("button",{type:"button",className:"sidebar-task-project-group-menu-backdrop","aria-label":"Close project actions",onClick:()=>b(!1)}),g.jsxs("div",{className:"section-menu-popover sidebar-task-project-group-menu",role:"menu",children:[c?g.jsx("button",{type:"button",role:"menuitem",onClick:()=>{b(!1),c()},children:g.jsx("span",{children:"Open project"})}):null,l?g.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{b(!1),l()},children:[g.jsx(el,{size:13}),g.jsx("span",{children:"Remove from Projects"})]}):null]})]}):null]}),t?g.jsx("div",{id:p,className:"sidebar-task-project-group-content",children:e}):null]})}function zB({platform:e}){return!Eg()||_I(e)?null:g.jsxs("div",{className:"window-controls","aria-label":"Window controls",children:[g.jsx("button",{type:"button",className:"window-control minimize",title:"Minimize",onClick:()=>{mp("minimize")},children:g.jsx(mr,{size:14})}),g.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{mp("toggleMaximize")},children:g.jsx(fU,{size:12})}),g.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{mp("close")},children:g.jsx(el,{size:13})})]})}function _I(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")}function Eg(){if(typeof window>"u")return!1;const e=window.openpond;return!!(e?.minimizeWindow||e?.toggleMaximizeWindow||e?.closeWindow)}async function mp(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 HB={},UB=new Map,qB=new Map;function Kb(){const e=no.getItem("openpond.sidebar.presentation.v1");return e==="inbox"||e==="grouped"?e:Eg()?"inbox":"grouped"}function BB(e,t){return Math.min(Math.max(e,Nn)+bf,t)}function FB(e,t){const n=Math.max(Nn,Math.min(e,t));if(n<=Nn)return Nn;const a=Math.ceil((n-Nn)/bf);return Math.max(Nn,Nn+(a-1)*bf)}function VB(e,t){const n=new Map;for(const a of e){const s=t(a),r=n.get(s.key);r?r.sessions.push(a):n.set(s.key,{...s,sessions:[a]})}return[...n.values()]}function KB({activeSessions:e,activityTimes:t={},onSelectSession:n,archiveSession:a,archivedSessions:s,chatRowsVisibleCount:r,childSessionRowsByParentId:i={},cloudProjectRows:c,beginProjectChat:l,onAddProject:u,commitTaskDrop:p,commitTaskPreviewDrop:f,dockSessionRight:S,experience:b="work",goalRuntimeBySessionId:w=UB,localProjectRows:C,openSidebarFile:P,pinnedCollapsed:_,pinnedRows:M,previewTaskDrop:E,previewPinnedDrop:T,projectRows:y,renameSession:I,restoreSession:R,runningSessionIds:O,sectionMenuOpen:z,selectedProjectId:$,selectedSessionId:V,setChatRowsVisibleCount:Y,setSectionMenuOpen:se,setSelectedAppId:ee,setSelectedProjectId:H,setSelectedSessionId:F,setView:J,sidebarProjectIdBySessionId:K,startTaskDrag:B,startPinnedDrag:ne,subagentRuntimeBySessionId:G=qB,taskDragSessionId:te,taskPreviewSessionIds:oe,terminalSummaries:be=HB,toggleSessionPinned:me,toggleSessionSavedForLater:Re,view:Q,clearTaskDrag:xe,removeProject:je,toggleProjectPinned:De,onTogglePinnedCollapsed:He,setSidebarFileStatus:Ie,commitPinnedDrop:Me,commitPinnedPreviewDrop:Te,clearSidebarDrag:N,dragItem:q}){const[X,U]=h.useState(Kb);fi(()=>U(Kb()));const ae=X==="inbox",[de,ye]=h.useState("active"),[Oe,$e]=h.useState("recent"),[Ge,yt]=h.useState(!0);h.useEffect(()=>{b!=="chat"&&yt(!0)},[b]);const[Se,Le]=h.useState({work:!1,chat:!0}),[Ae,qe]=h.useState({work:!1,chat:!1}),Ue=b==="chat"?"chat":"work",bn=Se[Ue],[Mt,pe]=h.useState(Lb);fi(()=>pe(Lb()));const{onlyRunningTasks:fe,showCodexChats:Fe}=Mt,[Pe,Ne]=h.useState(null),[ot,ut]=h.useState(()=>new Set),[At,mt]=h.useState(()=>new Map),[at,Ct]=h.useState(null);h.useEffect(()=>{$&&Le(D=>D[Ue]?{...D,[Ue]:!1}:D)},[Ue,$]);const Be=b==="chat"?"chats":"tasks",Et=y??[...C,...c],dn=h.useMemo(()=>new Map(Et.map(D=>[D.id,D.project.name])),[Et]),jn=h.useMemo(()=>new Map(Et.map(D=>[D.id,D])),[Et]),kt=h.useMemo(()=>{const D=new Set(O);for(const we of[...e,...Object.values(i).flat()]){const le=w.get(we.id),Je=G.get(we.id);(le?.tone==="active"&&le.status!=="queued"||(Je?.activeCount??0)>0||_t(we.id)?.status==="running")&&D.add(we.id)}return D},[e,i,w,O,G,be]),ks=h.useMemo(()=>dp({activeSessions:e,doneSessions:s,filter:"all",inProgressSessionIds:kt,sort:"manual"}),[e,s,kt]),un=h.useMemo(()=>dp({activeSessions:e,doneSessions:s,filter:de,inProgressSessionIds:kt,onlyRunningTasks:fe,selectedTasksetId:Pe,previewSessionIds:oe,showCodexChats:Fe,sort:Oe}),[e,s,kt,fe,Pe,Fe,de,oe,Oe]),yn=h.useMemo(()=>{const D=new Map;for(const we of[...e,...s]){if(!dd(we,{inProgressSessionIds:kt,onlyRunningTasks:fe,showCodexChats:Fe}))continue;const le=Ko(we);if(!le)continue;const Je=D.get(le.id);Je?Je.chatCount+=1:D.set(le.id,{...le,chatCount:1})}return[...D.values()].sort((we,le)=>we.name.localeCompare(le.name))},[e,s,kt,fe,Fe]),Ut=h.useMemo(()=>M.filter(D=>D.type!=="session"||dd(D.session,{inProgressSessionIds:kt,onlyRunningTasks:fe,showCodexChats:Fe})),[kt,fe,M,Fe]),Rn=h.useMemo(()=>un.filter(D=>!Wo(D)),[un]),Sn=h.useMemo(()=>Rn.slice(0,Math.max(Nn,r)),[r,Rn]),Pn=h.useMemo(()=>{const D=VB(Sn,we=>{if($c(we))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const le=K[we.id],Je=Ot(we)??"Work";return{key:le?`project:${le}`:`projectless:${Je}`,label:Je,projectId:le??null,project:le?jn.get(le)??null:null,kind:le?"project":"projectless"}});for(const we of Et)D.some(le=>le.projectId===we.id)||D.push({key:`project:${we.id}`,label:we.project.name,projectId:we.id,project:we,kind:"project",sessions:[]});return D},[Et,dn,jn,K,Sn]),Mn=Sn.length<Rn.length,qt=Sn.length>Nn,gt=h.useMemo(()=>new Set(Pn.filter(D=>D.sessions.some(we=>we.id===V||kt.has(we.id))).map(D=>D.key)),[Pn,kt,V]),qn=ks.filter(D=>!Wo(D)).map(D=>D.id),mn=Sn.map(D=>D.id),pt=JSON.stringify(Object.entries(i).filter(([D,we])=>we.some(le=>!le.archived)&&(G.get(D)?.activeCount??0)>0).flatMap(([D,we])=>we.filter(le=>!le.archived).map(le=>[D,le.id])).sort(([D,we],[le,Je])=>D.localeCompare(le)||we.localeCompare(Je)));h.useEffect(()=>{const D=JSON.parse(pt);if(D.length===0)return;const we=new Set(D.map(([le])=>le));ut(le=>[...we].every(Je=>le.has(Je))?le:new Set([...le,...we]))},[pt]);function _t(D){return Lq(be[vI({kind:"session",id:D})])}function Ot(D){if($c(D))return"Draft";const we=K[D.id];return we?dn.get(we)??D.workspaceName??"Project":_q(D)}function pn(D){if(n){n(D);return}Lt({kind:"chat",sessionId:D.id}),F(D.id);const we=K[D.id]??null;ee(we?null:D.appId),H(we),J("chat")}function oa(D){return(i[D.id]??[]).filter(we=>!we.archived&&dd(we,{inProgressSessionIds:kt,onlyRunningTasks:fe,showCodexChats:Fe}))}function Ze(D,we){return ot.has(D.id)||we.some(le=>le.id===V)}function Tn(D){ut(we=>{const le=new Set(we);return le.has(D)?le.delete(D):le.add(D),le})}function Ja(D){const we=oa(D);return we.length===0||!Ze(D,we)?null:g.jsx("div",{className:"sidebar-child-session-group",children:we.map(le=>g.jsx(Vb,{session:le,selected:Q==="chat"&&V===le.id,nested:!0,running:kt.has(le.id),goalRuntime:w.get(le.id)??null,subagentRuntime:G.get(le.id)??null,terminalIndicator:_t(le.id),projectLabel:Ot(D),onSelect:()=>pn(le),onTogglePin:()=>me(le),onToggleSaveForLater:()=>Re(le),onDockRight:()=>S(le),onArchive:()=>le.archived?R(le):a(le),onRename:I},le.id))})}function Ea(D,we){if(typeof window>"u")return;const le=Wo(D)?Ot(D):null;Ct({descriptionId:`sidebar-task-detail-${D.id}`,sessionId:D.id,title:D.title,updatedAt:D.updatedAt,folderName:le,style:NB(we.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight},!!le)})}function Ln(D,we={}){const le=D.archived,Je=we.pinnedRow?.placeholder??te===D.id,ga=oa(D),Bn="sidebar-session-group",Ma=we.pinnedRow?.dragProps??(!ae&&Oe==="manual"?{onDragStart:kn=>B(kn,{allSessionIds:qn,visibleSessionIds:mn,sessionId:D.id}),onDragEnd:xe,onDragOver:kn=>{Je||E(kn,D.id)},onDrop:kn=>{Je?f():p(kn,D.id)}}:{});return g.jsxs("div",{className:Bn,onPointerEnter:kn=>Ea(D,kn.currentTarget),onPointerLeave:()=>Ct(null),onFocusCapture:kn=>Ea(D,kn.currentTarget),onBlurCapture:kn=>{kn.currentTarget.contains(kn.relatedTarget)||Ct(null)},children:[g.jsx(Vb,{session:D,selected:!le&&Q==="chat"&&V===D.id,archived:le,inbox:ae,activityAt:bd(D,t),placeholder:Je,running:kt.has(D.id),goalRuntime:w.get(D.id)??null,subagentRuntime:G.get(D.id)??null,terminalIndicator:_t(D.id),projectLabel:we.projectLabel===void 0?Ot(D):we.projectLabel,metadataPresentation:we.metadataPresentation,ariaDescribedBy:at?.sessionId===D.id?at.descriptionId:void 0,childSessionCount:ga.length,childSessionsExpanded:Ze(D,ga),onToggleChildSessions:()=>Tn(D.id),onSelect:()=>{Ct(null),le&&R(D),pn(D)},onTogglePin:()=>me(D),onToggleSaveForLater:()=>Re(D),onDockRight:()=>S(D),onArchive:()=>le?R(D):a(D),onRename:I,...Ma}),!ae&&!Je?Ja(D):null]},we.pinnedRow?.key??D.id)}function An(D){D!=="tasksets"&&Ne(null),ye(D),Y(Nn)}function Qa(D){Ne(D),ye("tasksets"),Y(Nn)}function ws(D){$e(D),Y(Nn)}function ja(){Y(D=>BB(D,Rn.length))}function lt(){Y(D=>FB(D,Rn.length))}function sn(D){const we={id:D.id,type:D.type};return{onDragStart:le=>ne(le,we),onDragEnd:N,onDragOver:le=>T(le,we),onDrop:le=>{q?.id===D.id&&q.type===D.type?Te():Me(le,we)}}}function Ke(D){const we=sn(D),le=q?.id===D.id&&q.type===D.type;if(D.type==="project"){const Je=D.item;return g.jsx(vB,{kind:Je.kind,project:Je.project,pinned:!0,selected:Q==="chat"&&$===Je.id,expanded:!1,disclosure:!1,placeholder:le,onSelect:()=>{ee(null),H(Je.id),F(null),J("chat")},onNewChat:()=>l(Je.id),onTogglePin:()=>De(Je),onRemove:()=>je(Je),...we},D.key)}return D.type==="file"?g.jsx(hB,{file:D.file,placeholder:le,onSelect:()=>P(D.file),onTogglePin:()=>Ie(D.file,"none"),onToggleSaveForLater:()=>Ie(D.file,"saved_for_later"),...we},D.key):Ln(D.session,{projectLabel:ae&&!K[D.session.id]?null:Ot(D.session),pinnedRow:{key:D.key,dragProps:we,placeholder:le}})}function St(D){const we=gt.has(D.key)||At.get(D.key)!==!1;return g.jsx(LB,{expanded:we,groupKey:D.key,kind:D.kind,label:D.label,onToggle:()=>{mt(le=>{const Je=new Map(le);return Je.set(D.key,!we),Je})},onNewTask:D.project?()=>l(D.project.id):void 0,onOpenProject:D.project?()=>{ee(null),H(D.project.id),F(null),J("chat")}:void 0,onRemoveProject:D.project?()=>je(D.project):void 0,project:D.project,children:D.sessions.map(le=>Ln(le,{metadataPresentation:"flyout",projectLabel:D.label}))},D.key)}const en=g.jsx(jB,{activityOrder:ae,filter:de,groupByProject:Ge,noun:Be,onFilterChange:An,onGroupByProjectChange:yt,onOnlyRunningTasksChange:D=>{pe(we=>{const le={...we,onlyRunningTasks:D};return zb(le),le}),Y(Nn)},onShowCodexChatsChange:D=>{pe(we=>{const le={...we,showCodexChats:D};return zb(le),le}),Y(Nn)},onTasksetChange:Qa,onSortChange:ws,onlyRunningTasks:fe,openMenu:z,setOpenMenu:se,showCodexChats:Fe,sort:Oe,selectedTasksetId:Pe,tasksets:yn}),zn=dp({activeSessions:Object.values(i).flat().filter(D=>!D.archived),doneSessions:Object.values(i).flat().filter(D=>D.archived),filter:de,inProgressSessionIds:kt,onlyRunningTasks:fe,selectedTasksetId:Pe,showCodexChats:Fe,sort:"recent"}),xn=aC([...un,...zn].filter(D=>!Wo(D)),t,kt);return g.jsxs("div",{className:"sidebar-sections",children:[g.jsxs("div",{className:"sidebar-threads-header",children:[g.jsx("span",{children:"Threads"}),g.jsxs("div",{className:"sidebar-threads-header-actions",children:[ae?en:null,g.jsx("button",{type:"button",className:`sidebar-icon${ae?" active":""}`,"aria-label":ae?"Show grouped threads":"Show thread inbox",title:ae?"Grouped threads":"Thread inbox","aria-pressed":ae,onClick:()=>{const D=ae?"grouped":"inbox";U(D),no.setItem("openpond.sidebar.presentation.v1",D)},children:ae?g.jsx(zU,{size:16}):g.jsx(mg,{size:16})})]})]}),Ut.length>0?g.jsx(up,{label:"Pinned",className:"sidebar-pinned-section",collapsed:_,onToggleCollapsed:He,children:Ut.map(Ke)}):null,ae?g.jsxs("section",{className:"sidebar-thread-inbox","aria-label":"Thread inbox",children:[sC(xn,t,kt).map(D=>g.jsxs("div",{children:[D.label?g.jsx("h3",{className:"sidebar-inbox-date",children:D.label}):null,D.sessions.map(we=>Ln(we,{projectLabel:K[we.id]?Ot(we):null}))]},D.key)),xn.length===0&&Ut.length===0?g.jsx("div",{className:"empty-row",children:$b(de,Be)}):null]}):g.jsxs(g.Fragment,{children:[g.jsx(up,{label:"Projects",className:`sidebar-projects-section${b!=="chat"?" development":""}`,collapsed:bn,onToggleCollapsed:()=>Le(D=>({...D,[Ue]:!D[Ue]})),actions:g.jsx(MB,{onAddProject:u,onViewProjects:()=>{(async()=>await Lt({kind:"view",view:"projects"})&&(ee(null),H(null),F(null),J("projects")))()}}),children:Pn.filter(D=>D.kind==="project").map(D=>St(b==="chat"||!Ge?{...D,sessions:[]}:D))}),g.jsxs(up,{label:b==="chat"?"Chat":"Work",className:"sidebar-task-section sidebar-ordinary-section",collapsed:Ae[Ue],onToggleCollapsed:()=>qe(D=>({...D,[Ue]:!D[Ue]})),actionsVisible:z==="chats"||z==="tasks-filter"||de!=="active"||fe||!Fe,actions:en,children:[(b==="chat"||!Ge?Sn:Sn.filter(D=>!K[D.id])).map(D=>Ln(D)),Rn.length===0&&Ut.length===0?g.jsx("div",{className:"empty-row",children:$b(de,Be)}):null,Rn.length>Nn&&(Mn||qt)?g.jsxs("div",{className:"sidebar-pagination-controls","aria-label":`Showing ${Sn.length} of ${Rn.length} ${Be}`,children:[Mn?g.jsx(Fb,{onClick:ja,children:"Show more"}):null,qt?g.jsx(Fb,{onClick:lt,children:"Show less"}):null]}):null]})]}),g.jsx(DB,{detail:at,onClose:()=>Ct(null)})]})}const WB=h.lazy(()=>fr(()=>import("./TerminalOverlay-B4F6Q36s.js"),__vite__mapDeps([0,1,2,3])).then(e=>({default:e.TerminalOverlay})));function GB({connection:e,command:t,onClose:n,onComplete:a}){const[s,r]=h.useState([]),[i]=h.useState(()=>({kind:"draft",id:`native-setup-${crypto.randomUUID()}`})),c=h.useRef(!1),[l]=h.useState(()=>({id:Date.now(),scope:i,command:t}));return h.useEffect(()=>{!c.current&&s.some(u=>u.lastExitCode!==null&&(u.commandStatus==="success"||u.commandStatus==="failed"))&&(c.current=!0,a?.())},[s,a]),Dd.createPortal(g.jsx("div",{className:"native-setup-terminal",children:g.jsx(h.Suspense,{fallback:g.jsx("p",{role:"status",children:"Opening setup terminal…"}),children:g.jsx(WB,{open:!0,disposeOnUnmount:!0,connection:e,scope:i,tabs:s,onTabsChange:r,cwd:null,appId:null,workspaceName:"Agent setup",queuedCommand:l,onClose:n})})}),document.body)}const ql={codex:"Codex",claude_code:"Claude Code",opencode:"OpenCode",grok_build:"Grok Build",hermes:"Hermes",pi:"Pi",oh_my_pi:"Oh My Pi",openclaw:"OpenClaw"};function ZB({status:e,busy:t,onControl:n,onConnectionControl:a,onReconnect:s}){const r=e.desiredState==="stopped",i=r?"Importer stopped":e.running?"Importer running":"Importer offline";return g.jsxs("div",{className:"sidebar-section native-importer-status",children:[g.jsx("strong",{children:i}),e.connections.map(c=>{const l=c.backfill,u=l.stage==="complete",p=l.admitted+l.skipped;return g.jsxs("div",{className:"native-importer-connection",children:[g.jsxs("span",{children:[c.error?g.jsx(jd,{size:12}):u?g.jsx(ds,{size:12}):g.jsx(Su,{size:12}),ql[c.source]??c.source]}),g.jsx("small",{children:c.state==="paused"?"Paused":c.state==="disconnected"?"Disconnected":u?e.running&&!r?"Watching for new conversations":`${l.admitted} conversations imported`:l.stage==="discovering"?"Finding conversations":`${p} of ${l.total} conversations processed`}),g.jsxs("small",{children:[c.admitted," tasks admitted",l.skipped>0?`, ${l.skipped} conversations skipped`:"",l.failed>0?`, ${l.failed} failed`:""]}),!u&&l.total>0?g.jsx("progress",{"aria-label":`${ql[c.source]??c.source} import progress`,value:p,max:l.total}):null,c.queued>0?g.jsxs("small",{children:[c.queued," updates waiting to upload (",new Intl.NumberFormat(void 0,{notation:"compact"}).format(c.pendingBytes)," bytes)"]}):null,c.lastAdmissionAt?g.jsxs("small",{children:["Last synced ",g.jsx("time",{dateTime:c.lastAdmissionAt,children:new Date(c.lastAdmissionAt).toLocaleString()})]}):g.jsx("small",{children:"No uploads acknowledged yet"}),c.destinationLinks?.tasks?g.jsx("a",{href:c.destinationLinks.tasks,target:"_blank",rel:"noopener noreferrer",children:"View tasks"}):null,c.destinationLinks?.conversations?g.jsx("a",{href:c.destinationLinks.conversations,target:"_blank",rel:"noopener noreferrer",children:"View conversations"}):null,c.error?g.jsx("small",{role:"status",children:c.error}):null,c.state==="disconnected"?g.jsx("button",{type:"button",disabled:t,onClick:()=>s(c.id),children:"Reconnect source"}):g.jsxs("div",{children:[g.jsxs("button",{type:"button",disabled:t,onClick:()=>a(c.state==="paused"?"resume":"pause",c.id),children:[c.state==="paused"?"Resume":"Pause"," ",ql[c.source]??c.source]}),g.jsxs("button",{type:"button",disabled:t,onClick:()=>a("disconnect",c.id),children:["Disconnect ",ql[c.source]??c.source]})]})]},c.id)}),g.jsx("button",{type:"button",disabled:t||r,onClick:()=>n("sync"),children:"Sync now"}),g.jsxs("button",{type:"button",disabled:t,onClick:()=>n(r||!e.running?"start":"stop"),children:[r?"Start":e.running?"Stop":"Restart"," importer"]}),!e.running&&!r?g.jsx("button",{type:"button",disabled:t,onClick:()=>n("stop"),children:"Stop importer"}):null,!e.running&&!r?g.jsx("button",{type:"button",disabled:t,onClick:()=>n("install"),children:"Reinstall background service"}):null]})}function JB({title:e,inspection:t,busy:n,onSelect:a,onRefresh:s,onClose:r}){return g.jsxs("section",{className:"native-branch-picker","aria-label":"Choose Claude conversation branch",children:[g.jsx("strong",{children:e||"Claude conversation"}),g.jsx("p",{children:"This conversation has multiple branches. Choose the history to view. Each branch opens as a read-only snapshot."}),t.branches.map(i=>g.jsxs("button",{type:"button",disabled:n,onClick:()=>a({leafId:i.leafId,revision:t.revision}),children:[g.jsx("span",{children:i.title||"Branch without a text message"}),g.jsxs("small",{children:[i.messages," messages · ",i.updatedAt?new Date(i.updatedAt).toLocaleString():"Date unavailable"]}),g.jsx("code",{children:i.leafId})]},i.leafId)),g.jsxs("div",{children:[g.jsx("button",{type:"button",disabled:n,onClick:s,children:"Refresh branches"}),g.jsx("button",{type:"button",disabled:n,onClick:r,children:"Cancel"})]})]})}function QB({connection:e,selectedSessionId:t,selectedSession:n,active:a=!0,onOpen:s}){const r=h.useRef({selectedSessionId:t,active:a});r.current={selectedSessionId:t,active:a};const i=h.useRef(null),c=h.useRef(0),l=h.useRef(null);h.useEffect(()=>(c.current++,i.current=null,M(null),w(null),P(null),S(null),I(null),p(null),()=>{c.current++}),[e]);const[u,p]=h.useState(null),[f,S]=h.useState(null),[b,w]=h.useState(null),[C,P]=h.useState(null),[_,M]=h.useState(null),[E,T]=h.useState(!1),[y,I]=h.useState(null),R=h.useCallback(async()=>{if(!e||l.current===c.current)return;const ee=c.current;l.current=ee,M("refresh");try{const H=await L(e,"/v1/native-history/list",{method:"POST",body:JSON.stringify({retain:!0})});ee===c.current&&(w(H),P(null))}catch(H){ee===c.current&&P(H instanceof Error?H.message:"Local history is unavailable.")}finally{l.current===ee&&(l.current=null),ee===c.current&&M(null)}},[e]);h.useEffect(()=>{R()},[R]),h.useEffect(()=>{const ee=window.setInterval(()=>{document.hidden||R()},3e4);return()=>window.clearInterval(ee)},[R]),h.useEffect(()=>{if(!a||!e||!u||u.sessionId!==t)return;const ee=c.current,H=window.setInterval(()=>{document.hidden||L(e,"/v1/native-history/open",{method:"POST",body:JSON.stringify({id:u.id})}).catch(F=>{ee===c.current&&P(F.message)})},1e4);return()=>window.clearInterval(H)},[a,e,u,t]);async function O(){const ee=c.current;if(!(!e||!b)){M("more");try{const H=await L(e,"/v1/native-history/list",{method:"POST",body:JSON.stringify({cursors:b.nextCursors,retain:!0})});if(ee!==c.current)return;w(F=>({...H,items:[...new Map([...F?.items??[],...H.items].map(J=>[J.id,J])).values()]}))}catch(H){ee===c.current&&P(H instanceof Error?H.message:"Could not load more conversations.")}finally{ee===c.current&&M(null)}}}async function z(ee,H,F=r.current.selectedSessionId){const J=c.current;if(e&&_===null){M(ee);try{if(!H){const B=await L(e,"/v1/native-history/branches",{method:"POST",body:JSON.stringify({id:ee})});if(J!==c.current)return;if(B.branches.length>1){r.current.active&&r.current.selectedSessionId===F&&I({id:ee,inspection:B,originSessionId:F}),P(null);return}}const K=await L(e,"/v1/native-history/open",{method:"POST",body:JSON.stringify({id:ee,branch:H})});if(J!==c.current)return;p(H?null:{id:ee,sessionId:K.id}),I(null),P(K.metadata?.nativeHistoryProjection&&!K.nativeAgent?typeof K.metadata.nativeReadOnlyReason=="string"?K.metadata.nativeReadOnlyReason:"Read-only history: the native source does not report its original working directory.":null),r.current.active&&r.current.selectedSessionId===F&&await s(K)}catch(K){J===c.current&&P(K instanceof Error?K.message:"Could not read this conversation.")}finally{J===c.current&&M(null)}}}h.useEffect(()=>{if(!a||!e||_!==null||!n||n.metadata?.nativeHistoryLoaded!==!1||n.metadata.nativeBranch)return;const ee=n.metadata.nativeHistoryId;if(typeof ee!="string")return;const H=`${c.current}:${n.id}`;i.current!==H&&(i.current=H,z(ee,void 0,n.id))},[e,n,_,a]);async function $(ee){const H=c.current;if(e){M(ee);try{await L(e,"/v1/native-history/collector",{method:"POST",body:JSON.stringify({command:ee})}),H===c.current&&await R()}catch(F){H===c.current&&P(F instanceof Error?F.message:"Collector action failed.")}finally{H===c.current&&M(null)}}}async function V(ee,H){const F=c.current;if(e){M(ee);try{const J=await L(e,"/v1/native-history/collector",{method:"POST",body:JSON.stringify({command:ee,connectionId:H})});if(F!==c.current)return;S(J.command),P(null)}catch(J){F===c.current&&P(J instanceof Error?J.message:"Could not change Importer connection.")}finally{F===c.current&&M(null)}}}async function Y(ee){const H=c.current;if(e){M("connect");try{const F=await L(e,"/v1/native-history/collector",{method:"POST",body:JSON.stringify({command:ee?"reconnect":"connect",connectionId:ee})});if(H!==c.current)return;S(F.command),P(null)}catch(F){H===c.current&&P(F instanceof Error?F.message:"Could not open Importer setup.")}finally{H===c.current&&M(null)}}}async function se(ee){const H=ee.metadata?.nativeHistoryId;await s(ee)&&ee.metadata?.nativeHistoryProjection&&!ee.metadata.nativeBranch&&typeof H=="string"&&z(H,void 0,ee.id)}return{connection:e,history:b,error:C,busy:_,command:f,expanded:E,branchSelection:y,setCommand:S,setExpanded:T,setBranchSelection:I,refresh:R,more:O,open:z,control:$,connectionControl:V,connect:Y,select:se}}function YB({history:e}){const{connection:t,history:n,error:a,busy:s,command:r,expanded:i,branchSelection:c,setCommand:l,setExpanded:u,setBranchSelection:p,refresh:f,more:S,open:b,control:w,connectionControl:C,connect:P}=e;return t?g.jsxs("section",{className:"sidebar-section native-conversations","aria-label":"Conversation import controls",children:[g.jsxs("div",{className:"sidebar-section-heading",children:[g.jsx("button",{type:"button",onClick:()=>u(_=>!_),"aria-expanded":i,children:"Import conversations"}),g.jsx("button",{type:"button",className:"sidebar-icon","aria-label":"Refresh saved conversation history",disabled:s!==null,onClick:()=>{f()},children:s==="refresh"?g.jsx(Su,{size:14}):g.jsx(dg,{size:14})})]}),r?g.jsx(GB,{connection:t,command:r,onClose:()=>{l(null),f()}}):null,c?g.jsx(JB,{title:n?.items.find(_=>_.id===c.id)?.title??"",inspection:c.inspection,busy:s!==null,onSelect:_=>{b(c.id,_,c.originSessionId??null)},onRefresh:()=>{b(c.id,void 0,c.originSessionId??null)},onClose:()=>p(null)}):null,i?g.jsxs(g.Fragment,{children:[g.jsx("button",{type:"button",disabled:s!==null,onClick:()=>{P()},children:"Connect an import source"}),n&&Object.keys(n.nextCursors).length?g.jsx("button",{type:"button",disabled:s!==null,onClick:()=>{S()},children:"Load more saved conversations"}):null,n&&n.items.length===0?g.jsx("p",{children:"No saved conversations found in configured source locations."}):null,n?.warnings.map(_=>g.jsxs("p",{children:[g.jsx(jd,{size:12,"aria-hidden":"true"})," ",_]},_)),n?.collector.connections.length?g.jsx(ZB,{status:n.collector,busy:s!==null,onControl:_=>{w(_)},onConnectionControl:(_,M)=>{C(_,M)},onReconnect:_=>{P(_)}}):g.jsx("p",{children:"Connect an import source to upload conversations. Local history remains available without cloud sync."})]}):null,a?g.jsxs("p",{role:"status",children:[g.jsx(jd,{size:12,"aria-hidden":"true"})," ",a]}):null]}):null}const CI="openpond.sidebar.continuous-learning.dismissed.v1";function Wb(e=RI()){if(!e)return!1;try{return e.getItem(CI)==="true"}catch{return!1}}function XB(e=RI()){if(e)try{e.setItem(CI,"true")}catch{}}function RI(){return typeof window>"u"?null:no}function e4({connection:e,onOpenSettings:t}){const[n,a]=h.useState(null),[s,r]=h.useState(Wb);fi(()=>r(Wb()));const i=h.useCallback(async()=>{if(!e){a(null);return}try{a(await Z.harnessHistory(e))}catch{a(null)}},[e]);if(h.useEffect(()=>{i()},[i]),s||!e||!n?.workspace)return null;const c=n.evaluationReviewSchedule,l=c.activityEnabled?`${c.activityBatchSize} outcomes${c.enabled?` + ${c.cadence}`:""}`:c.enabled?c.cadence:"Manual";return g.jsxs("section",{className:"sidebar-learning-notice","aria-label":"Continuous learning",children:[g.jsxs("header",{children:[g.jsx("strong",{children:"Continuous learning"}),g.jsxs("div",{className:"sidebar-learning-notice-actions",children:[g.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Open Continuous learning settings",onClick:t,type:"button",children:g.jsx(Ww,{size:14})}),g.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{r(!0),XB()},type:"button",children:g.jsx(el,{size:14})})]})]}),g.jsxs("div",{className:"sidebar-learning-status",children:[g.jsx("strong",{children:"Refiner"}),g.jsx("span",{children:n.backgroundReview.enabled?"On":"Off"})]}),g.jsxs("div",{className:"sidebar-learning-status",children:[g.jsx("strong",{children:"Continuous Review"}),g.jsx("span",{children:l})]})]})}function t4(e){const{productArea:t,setSectionMenuOpen:n,setSelectedAppId:a,setSelectedProjectId:s,setSelectedSessionId:r,setSidebarOpen:i,setView:c,view:l,modelProjects:u,modelTrainingActivityByProjectId:p}=e,f=h.useCallback(w=>{n(w)},[n]),S=h.useCallback(async w=>{if(!await Lt({kind:"chat",sessionId:w.id}))return!1;r(w.id);const C=e.sidebarProjectIdBySessionId[w.id]??null;return s(C),a(C?null:w.appId),c("chat"),!0},[r,s,a,c,e.sidebarProjectIdBySessionId]),b=QB({connection:t==="chat"?e.connection:null,active:l==="chat",selectedSessionId:e.selectedSessionId,selectedSession:[...e.activeSessions,...e.archivedSessions,...Object.values(e.childSessionRowsByParentId??{}).flat()].find(w=>w.id===e.selectedSessionId)??null,onOpen:S});return g.jsxs("aside",{className:"sidebar",inert:e.open===!1,children:[g.jsxs("div",{className:"sidebar-toolbar",children:[g.jsx("button",{className:"sidebar-icon","aria-label":"Hide sidebar",onClick:()=>i(!1),children:g.jsx(Kw,{size:16})}),g.jsx("div",{className:"sidebar-brand",children:g.jsx("img",{className:"sidebar-wordmark",src:Xq,alt:"OpenPond"})}),g.jsx(VU,{hasRunningWork:e.runningSessionIds.size>0||Object.values(e.terminalSummaries).some(w=>w.tabCount>0)})]}),t==="chat"?g.jsxs("div",{className:"sidebar-fixed-actions",children:[g.jsx(rq,{experience:e.experience,beginNewChat:e.beginNewChat}),t==="chat"&&l==="chat"&&e.account?.activeProfile&&e.onOpenPonder?g.jsx("div",{className:"sidebar-ponder-fixed",children:g.jsxs("button",{type:"button",className:"sidebar-row sidebar-task-row sidebar-ponder-entry",onClick:e.onOpenPonder,children:[g.jsx("span",{className:"conversation-source-icon","aria-hidden":"true",children:g.jsx("img",{src:Tg,alt:""})}),g.jsx("span",{children:"Ponder Pal"})]})}):null]}):null,g.jsxs("div",{className:"sidebar-scroll",children:[t!=="chat"?g.jsx(oq,{productArea:t,setSectionMenuOpen:f,setSelectedAppId:a,setSelectedProjectId:s,setSelectedSessionId:r,setView:c,view:l,modelProjects:u,modelTrainingActivityByProjectId:p}):null,t!=="chat"||l!=="chat"?null:g.jsx(KB,{...e,onSelectSession:b.select,setSectionMenuOpen:f}),t==="chat"&&l==="chat"?g.jsx(YB,{history:b}):null]}),g.jsx("div",{className:"sidebar-bottom-stack",children:t!=="chat"?null:g.jsx(e4,{connection:e.connection,onOpenSettings:()=>{n(null),Lt({kind:"settings",section:"harness"})}})})]})}const n4=[{destination:"walkthroughs",icon:wb,label:"Walkthroughs"},{destination:"external",icon:wb,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:og,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:ZH,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:Vw,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:oU,label:"GitHub",url:"https://github.com/openpond/openpond"},{destination:"external",icon:xu,label:"Submit issue",url:"https://github.com/openpond/openpond/issues/new/choose"}];function a4({onOpenWalkthroughs:e,onCloseAccount:t,walkthroughsActive:n}){const[a,s]=h.useState(!1),r=h.useRef(null),i=h.useRef(null);h.useLayoutEffect(()=>{a&&i.current?.querySelector('[role="menuitem"]')?.focus()},[a]);function c(){s(!0)}function l(){s(!1),r.current?.focus()}return g.jsxs("div",{className:"user-auth-help",onKeyDown:u=>{a&&(u.key==="Escape"||u.key==="ArrowLeft")&&(u.preventDefault(),u.stopPropagation(),l())},children:[g.jsxs("button",{ref:r,type:"button",className:"user-auth-menu-link",role:"menuitem","aria-haspopup":"menu","aria-expanded":a,onClick:()=>a?l():c(),onKeyDown:u=>{u.key==="ArrowRight"&&(u.preventDefault(),c())},children:[g.jsx(lU,{size:15}),g.jsx("span",{children:"Help"}),g.jsx(pr,{className:"user-auth-help-chevron",size:14})]}),a?g.jsx("div",{ref:i,className:"user-auth-help-submenu",role:"menu","aria-label":"Help",onKeyDown:u=>{if(!["ArrowDown","ArrowUp","Home","End"].includes(u.key))return;u.preventDefault();const p=Array.from(i.current?.querySelectorAll('[role="menuitem"]')??[]),f=p.indexOf(document.activeElement),S=u.key==="Home"?0:u.key==="End"?p.length-1:(f+(u.key==="ArrowDown"?1:-1)+p.length)%p.length;p[S]?.focus()},children:n4.map(u=>{const p=u.icon,f=g.jsxs(g.Fragment,{children:[g.jsx(p,{size:15}),g.jsx("span",{children:u.label})]});return u.destination==="walkthroughs"?g.jsx("button",{type:"button",role:"menuitem",className:"user-auth-menu-link","aria-current":n?"page":void 0,onClick:()=>{t(),e()},children:f},u.label):g.jsx("a",{className:"user-auth-menu-link",role:"menuitem",href:u.url,target:"_blank",rel:"noreferrer",onClick:S=>{S.preventDefault(),t(),s4(u.url)},children:f},u.label)})}):null]})}async function s4(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const Gb=new WeakMap,kf=new WeakMap;function PI(e){if(!e)return"disconnected";let t=Gb.get(e);return(!t||t.serverUrl!==e.serverUrl||t.token!==e.token)&&(t={serverUrl:e.serverUrl,token:e.token,id:crypto.randomUUID()},Gb.set(e,t)),t.id}function CG(e,t){return kf.set(e,t),e}function RG(e){if(!e)return["learning","disconnected"];let t=kf.get(e);return t||(t=["learning",crypto.randomUUID()],kf.set(e,t)),t}function r4(e,t){return P0({queryKey:["provider-plan-usage",PI(e),t],enabled:!!e,queryFn:({signal:n})=>L(e,`/v1/providers/${t}/plan-usage`,{signal:AbortSignal.any([n,AbortSignal.timeout(25e3)])}),staleTime:3e4,refetchInterval:6e4,refetchOnWindowFocus:"always",retry:!1,gcTime:3e5})}function pp(e){return`${Math.floor(e)}%`}function Zb(e){return e.resetsAt?`Resets ${new Date(e.resetsAt).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}`:"Reset time unavailable"}function o4(e,t){return t?"Loading…":e?.status==="signed_out"?"Sign in":e?.status==="unsupported"?"Not available":"Unavailable"}function i4({connection:e,provider:t,compact:n=!1,onOpen:a}){const s=r4(e,t),r=s.data,i=r?.windows.filter(b=>b.shared)??[],c=!!r?.windows.some(b=>b.resetsAt&&Date.parse(b.resetsAt)<=Date.now()),l=s.isError||c||!!(r&&Date.parse(r.refreshAfter)+6e4<Date.now()),u=t==="claude-code"?"Claude":"Codex",p=r?.status==="ready",f=o4(r,s.isPending&&!!e),S=r?.windows.map(b=>`${b.label}: ${pp(b.remainingPercent)} remaining. ${Zb(b)}.`).join(`
111
- `);return n?g.jsxs("button",{type:"button",role:"menuitem",className:"plan-usage-compact",onClick:a,title:l?`Usage needs refreshing. ${S??""}`:S||r?.message||"View plan usage in Providers",children:[g.jsx("span",{children:u}),g.jsx("span",{className:"plan-usage-compact-values",children:!l&&p&&i.length?i.map(b=>g.jsxs("span",{className:"plan-usage-compact-value",children:[g.jsx("small",{children:b.label}),g.jsx("strong",{children:pp(b.remainingPercent)})]},b.id)):g.jsx("strong",{children:l?"Unavailable":f})})]}):g.jsxs("section",{className:"provider-plan-usage","aria-label":`${u} plan usage`,children:[g.jsx("div",{className:"plan-usage-heading",children:g.jsx("button",{type:"button",className:"plan-usage-refresh","aria-label":`Refresh ${u} plan usage`,title:`Check usage (cached for up to ${t==="claude-code"?"5 minutes":"1 minute"})`,disabled:!e||s.isFetching,onClick:()=>{s.refetch()},children:g.jsx(dg,{size:13,className:s.isFetching?"settings-spin":void 0})})}),p?g.jsxs(g.Fragment,{children:[r.windows.map(b=>g.jsxs("div",{className:"plan-usage-window",children:[g.jsxs("div",{children:[g.jsx("span",{children:b.label}),g.jsxs("strong",{children:[pp(b.remainingPercent),l?" · last known":""]})]}),g.jsx("meter",{min:0,max:100,low:10,high:25,optimum:100,value:b.remainingPercent,"aria-label":`${u} ${b.label} remaining`}),g.jsx("small",{children:Zb(b)})]},b.id)),l?g.jsxs("small",{role:"status",children:["Usage needs refreshing. Last checked ",new Date(r.fetchedAt).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),"."]}):g.jsx("small",{className:"plan-usage-note",children:"Shared across your account. Updates automatically."})]}):g.jsx("p",{role:"status",children:s.isError?"Could not load usage. Try refreshing.":r?.message??(e?"Loading plan usage…":"Connect to load plan usage.")})]})}function c4(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function l4(e){const t=e?.accounts.find(i=>i.isActive)??null,n=e?.profile??null,a=e?.activeProfile?.handle??null;return{label:(e?.state==="signed_in"?c4(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 d4({connection:e,onOpenProviders:t,account:n,open:a,organizations:s,selectedTeamId:r,onOpenActivity:i,onOpenChange:c,onOpenSettings:l,onOpenWalkthroughs:u,walkthroughsActive:p,onSelectTeam:f,onLogOut:S,railTooltip:b}){const[w,C]=h.useState(null),[P,_]=h.useState(!1),M=h.useRef(null),E=h.useMemo(()=>l4(n),[n]),T=E.label.trim().slice(0,1).toUpperCase();return h.useEffect(()=>{if(!a)return;function y(R){M.current?.contains(R.target)||c(!1)}function I(R){R.key==="Escape"&&c(!1)}return document.addEventListener("pointerdown",y),document.addEventListener("keydown",I),()=>{document.removeEventListener("pointerdown",y),document.removeEventListener("keydown",I)}},[c,a]),g.jsxs("div",{className:"user-auth-footer",ref:M,children:[g.jsxs("button",{type:"button",className:`user-auth-trigger ${a?"active":""}`,"aria-haspopup":"menu","aria-expanded":a,"aria-label":`${E.label} account menu`,"data-rail-tooltip":b,onClick:()=>c(!a),children:[g.jsx("span",{className:"user-auth-avatar","aria-hidden":"true",children:E.image?g.jsx("img",{src:E.image,alt:""}):T?g.jsx("span",{children:T}):g.jsx(Cb,{size:16})}),g.jsx("span",{className:"user-auth-name",children:E.label})]}),a?g.jsxs("div",{className:"user-auth-menu",role:"menu","aria-label":"Account",children:[g.jsxs("div",{className:"user-auth-menu-header",children:[g.jsx("span",{className:"user-auth-menu-avatar","aria-hidden":"true",children:E.image?g.jsx("img",{src:E.image,alt:""}):T?g.jsx("span",{children:T}):g.jsx(Cb,{size:17})}),g.jsxs("span",{className:"user-auth-menu-identity",children:[g.jsx("strong",{children:E.label}),n?.state==="signed_in"&&n.environment?g.jsx("small",{title:n.baseUrl??void 0,children:n.environment==="production"?"Production":n.environment==="staging"?"Staging":n.environment}):null]})]}),s.length>0&&f?g.jsxs("div",{children:[g.jsxs("label",{className:"user-auth-team-picker",children:[g.jsx(ug,{size:15,"aria-hidden":"true"}),g.jsx("span",{className:"user-auth-team-picker-label",children:"Team"}),g.jsxs("select",{"aria-label":"Active team","aria-describedby":"account-task-ownership-hint",disabled:w!==null,value:r??"",onChange:async y=>{const I=y.currentTarget.value;C(I);try{await f(I||null)}catch{}finally{C(null)}},children:[g.jsx("option",{value:"",children:"Personal account"}),r&&!s.some(y=>y.teamId===r)?g.jsx("option",{value:r,disabled:!0,children:"Selected workspace unavailable"}):null,s.map(y=>g.jsx("option",{value:y.teamId,children:y.displayName},y.teamId))]})]}),g.jsx("p",{className:"user-auth-task-ownership-hint",id:"account-task-ownership-hint",children:"New tasks use this selection. Existing tasks keep their owner."})]}):null,g.jsx("div",{className:"user-auth-plan-usage",children:["claude-code","codex"].map(y=>g.jsx(i4,{connection:e,provider:y,compact:!0,onOpen:()=>{c(!1),t()}},y))}),g.jsx("div",{className:"user-auth-menu-divider"}),i?g.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{c(!1),i()},children:[g.jsx(qw,{size:15}),g.jsx("span",{children:"Activity"})]}):null,g.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{c(!1),l()},children:[g.jsx(Ww,{size:15}),g.jsx("span",{children:"Settings"})]}),g.jsx(a4,{onOpenWalkthroughs:u,walkthroughsActive:p,onCloseAccount:()=>c(!1)}),n?.state==="signed_in"&&S?g.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",disabled:P,onClick:async()=>{_(!0);try{await S(),c(!1)}catch{}finally{_(!1)}},children:[g.jsx(IU,{size:15}),g.jsx("span",{children:P?"Logging out…":"Log out"})]}):null]}):null]})}function u4({sidebar:e,open:t}){const[n,a]=h.useState(!1),s=[{view:"chat",label:"Home",Icon:Jw},{view:"scheduled",label:"Workflows",Icon:Uw},{view:"outputs",label:"Outputs",Icon:Bw},{view:"apps",label:"Apps",Icon:ug},{view:"projects",label:"Projects",Icon:ig}];async function r(c){if(a(!1),e.productArea==="chat"&&e.view===c){c==="chat"&&e.setSidebarOpen(!t);return}const l=c==="chat"?{kind:"chat",sessionId:e.selectedSessionId}:{kind:"view",view:c};await Lt(l)&&(e.setSectionMenuOpen(null),e.setView(c),c==="chat"&&e.setSidebarOpen(!0))}async function i(){await Lt({kind:"view",view:"get-started"})&&(e.setSelectedAppId(null),e.setSelectedProjectId(null),e.setSelectedSessionId(null),e.setSectionMenuOpen(null),e.setView("get-started"))}return g.jsxs("nav",{className:"desktop-navigation-rail","aria-label":"Desktop destinations",children:[g.jsxs("div",{className:"desktop-rail-destinations",children:[g.jsx("button",{type:"button","data-rail-tooltip":"Training","aria-label":"Training",className:`desktop-rail-button desktop-training-entry${e.productArea==="console"?" active":""}`,"aria-expanded":e.productArea==="console"&&t,onClick:()=>{e.productArea==="console"?e.setSidebarOpen(!t):(e.onProductAreaChange("console"),e.setSidebarOpen(!0))},children:g.jsx(GU,{size:19})}),s.map(({view:c,label:l,Icon:u})=>{const p=e.productArea==="chat"&&e.view===c;return g.jsx("button",{type:"button","data-rail-tooltip":l,"aria-label":l,"aria-current":p?"page":void 0,"aria-expanded":c==="chat"?p&&t:void 0,className:`desktop-rail-button${p?" active":""}`,onClick:()=>{r(c)},children:g.jsx(u,{size:19})},c)}),[{view:"team",label:"Team chat",Icon:xu,onOpen:e.onOpenTeamChat},{view:"community",label:"Discover communities",Icon:Vw,onOpen:e.discoverCommunities}].map(({view:c,label:l,Icon:u,onOpen:p})=>g.jsx("button",{type:"button","data-rail-tooltip":l,"aria-label":l,className:`desktop-rail-button${e.productArea==="chat"&&e.view===c?" active":""}`,"aria-current":e.productArea==="chat"&&e.view===c?"page":void 0,onClick:()=>{a(!1),(e.productArea!=="chat"||e.view!==c)&&p()},children:g.jsx(u,{size:19})},c))]}),g.jsx("div",{className:"desktop-rail-account",children:g.jsx(d4,{account:e.account,open:n,onOpenChange:a,connection:e.connection,onOpenProviders:()=>{Lt({kind:"settings",section:"providers"})},railTooltip:n?void 0:"Account",organizations:e.organizations,selectedTeamId:e.selectedTeamId,onSelectTeam:e.onSelectTeam,onLogOut:e.onLogOut,walkthroughsActive:e.view==="get-started",onOpenWalkthroughs:()=>{i()},onOpenActivity:()=>{Lt({kind:"settings",section:"usage"})},onOpenSettings:()=>{Lt({kind:"settings",section:"account"})}})})]})}const m4=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function TI(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?AI(a)?"Couldn’t connect to OpenPond.":a:t}function AI(e){const t=e.trim();return m4.some(n=>n.test(t))}const EI=h.createContext(null);function Jb({children:e,showToast:t}){return g.jsx(EI.Provider,{value:t,children:e})}function p4(){return h.useContext(EI)}function Qb(e,t={}){const n=p4(),a=h.useRef(null),s=t.enabled??!0,r=t.fallback??"Something went wrong.",i=t.prefix?.trim()??"",c=e==null||e===""?null:`${i}${i?": ":""}${TI(e,r)}`;h.useEffect(()=>{if(!s||!c){a.current=null;return}a.current!==c&&(a.current=c,n?.(c,"error"))},[s,c,n])}function f4({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(Qb(e?.previewError,{prefix:"Upload preview"}),Qb(e?.error,{prefix:"Cloud setup"}),!e)return null;const s=e.status==="uploading",r=e.status==="ready",i=e.status==="error",c=e.projectKind==="cloud",l=e.preview??null;return g.jsx("div",{className:"git-dialog-backdrop",role:"presentation",children:g.jsxs("section",{className:"git-dialog cloud-setup-dialog",role:"dialog","aria-modal":"true","aria-label":"Set up Cloud coding",children:[g.jsx("button",{className:"git-dialog-close",disabled:s,type:"button",onClick:t,"aria-label":"Close Cloud setup",title:"Close",children:g.jsx(el,{size:14})}),g.jsx("div",{className:"git-dialog-icon",children:r?g.jsx(rd,{size:18}):g.jsx(yu,{size:18})}),g.jsx("h2",{children:r?"Cloud repo ready":"Set up Cloud coding"}),g.jsx("p",{children:r?"Your source is ready in OpenPond Git. Finish by creating the Cloud sandbox environment.":c?"This Cloud Project is ready for a sandbox environment.":"OpenPond will upload tracked and unignored files into OpenPond Git, then send you to the Cloud sandbox setup page."}),g.jsxs("div",{className:"cloud-setup-summary",children:[g.jsxs("div",{className:"git-dialog-row",children:[g.jsx("span",{children:"Project"}),g.jsx("strong",{children:e.projectName})]}),g.jsxs("div",{className:"git-dialog-row",children:[g.jsx("span",{children:"Source"}),g.jsx("strong",{children:c?"OpenPond Git":"Local project upload"})]}),g.jsxs("div",{className:"git-dialog-row",children:[g.jsx("span",{children:"Branch"}),g.jsx("strong",{children:l?.branch??e.branch??"main"})]}),!c&&g.jsxs("div",{className:"git-dialog-row",children:[g.jsx("span",{children:"Cloud project"}),g.jsx("strong",{children:l?.targetProjectId??e.cloudProjectId??"New on upload"})]})]}),!r&&!c&&g.jsx("div",{className:"cloud-setup-upload-preview",role:"status","aria-live":"polite",children:e.previewLoading?g.jsxs(g.Fragment,{children:[g.jsx("strong",{children:"Calculating upload preview"}),g.jsx("span",{children:"Checking tracked and unignored files before anything is pushed."})]}):e.previewError?g.jsxs(g.Fragment,{children:[g.jsx("strong",{children:"Preview unavailable"}),g.jsx("span",{children:"Close and reopen setup to try the preview again."})]}):l?g.jsxs(g.Fragment,{children:[g.jsx("strong",{children:l.initializedEmptyProject?"Will initialize an empty project":`Will upload ${l.fileCount} files`}),g.jsx("span",{children:Yb({byteCount:l.byteCount,skippedCount:l.skippedCount,headCommit:l.headCommit,targetProjectName:l.targetProjectName})})]}):g.jsxs(g.Fragment,{children:[g.jsx("strong",{children:"Upload preview pending"}),g.jsx("span",{children:"File count, byte count, and skipped files will appear here before upload."})]})}),s&&g.jsxs("div",{className:"cloud-setup-progress",role:"status","aria-live":"polite",children:[g.jsx(Su,{className:"cloud-setup-spinner",size:16}),g.jsx("span",{children:"Uploading source to OpenPond Git..."})]}),r&&e.upload&&g.jsxs("div",{className:"cloud-setup-upload-result",children:[g.jsx("strong",{children:e.upload.initializedEmptyProject?"Initialized empty project":`Uploaded ${e.upload.fileCount} files`}),g.jsx("span",{children:Yb({byteCount:e.upload.byteCount,skippedCount:e.upload.skippedCount,headCommit:e.upload.headCommit,targetProjectName:e.upload.branch})})]}),r&&e.setupUrl&&g.jsxs("div",{className:"cloud-setup-next",children:[e.projectUrl?g.jsxs("span",{children:["Your repo is ready here:"," ",g.jsxs("a",{href:e.projectUrl,target:"_blank",rel:"noreferrer",onClick:u=>fp(u,e.projectUrl,n,{newTab:!0}),children:["Project page",g.jsx(rp,{size:13})]})]}):g.jsx("span",{children:"Your repo is ready. Next step:"}),g.jsxs("a",{href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:u=>fp(u,e.setupUrl,n),children:["Setup the Cloud sandbox",g.jsx(rp,{size:13})]})]}),g.jsxs("div",{className:"git-dialog-footer",children:[g.jsx("button",{className:"git-dialog-secondary",disabled:s,type:"button",onClick:t,children:r?"Done":"Cancel"}),r?e.setupUrl?g.jsxs("a",{className:"git-dialog-primary cloud-setup-primary-link",href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:u=>fp(u,e.setupUrl,n),children:["Open setup",g.jsx(rp,{size:13})]}):null:g.jsx("button",{className:"git-dialog-primary",disabled:s,type:"button",onClick:a,children:s?"Uploading":i?"Try again":c?"Show setup link":"Upload source"})]})]})})}function fp(e,t,n,a={}){!t||!n||(e.preventDefault(),n(t,a))}function h4(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 Yb({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const s=[h4(e),`${t} skipped`],r=g4(n);return r&&s.push(`local ${r}`),s.push(a),s.join(" · ")}function g4(e){const t=e?.trim();return t?t.slice(0,7):null}const v4=h.lazy(()=>fr(()=>import("./CommandMenu-GfQIMe6W.js"),__vite__mapDeps([4,1,2,5])).then(e=>({default:e.CommandMenu}))),b4=h.lazy(()=>fr(()=>import("./SettingsView-DtldfnV-.js"),__vite__mapDeps([6,1,2,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25])).then(e=>({default:e.SettingsView}))),y4=h.lazy(()=>fr(()=>import("./NewProjectDialog-B6XZkJrU.js"),__vite__mapDeps([26,1,2,12,18,27])).then(e=>({default:e.NewProjectDialog}))),S4=h.lazy(()=>fr(()=>import("./WorkspaceGitDialogs-CZSmjnrc.js"),__vite__mapDeps([28,1,2,15,16,29,25])).then(e=>({default:e.CommitDialog}))),x4=h.lazy(()=>fr(()=>import("./WorkspaceGitDialogs-CZSmjnrc.js"),__vite__mapDeps([28,1,2,15,16,29,25])).then(e=>({default:e.BranchDialog})));function k4({payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:s,onError:r,onToast:i,onBack:c,onOpenSourceSession:l,onStartRefinerAuthoring:u,onAcceptEvaluationReview:p,onOpenSkill:f,onOpenExtension:S,teamChatCurrentUserId:b,teamChatEnabled:w,teamChatNotificationMode:C,teamChatThreads:P,onTeamChatNotificationModeChange:_,onTeamChatThreadMuteChange:M,diffPanelWidth:E,diffPanelResizing:T,diffPanelExpanded:y,onDiffPanelResizeStart:I,onDiffPanelExpandedChange:R}){return g.jsx(h.Suspense,{fallback:null,children:g.jsx(b4,{payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:s,onError:r,onToast:i,onBack:c,onOpenSourceSession:l,onStartRefinerAuthoring:u,onAcceptEvaluationReview:p,onOpenSkill:f,onOpenExtension:S,teamChatCurrentUserId:b,teamChatEnabled:w,teamChatNotificationMode:C,teamChatThreads:P,onTeamChatNotificationModeChange:_,onTeamChatThreadMuteChange:M,diffPanelWidth:E,diffPanelResizing:T,diffPanelExpanded:y,onDiffPanelResizeStart:I,onDiffPanelExpandedChange:R})})}function w4({activeSessions:e,branchDialogName:t,branchDialogOpen:n,commitDialogOpen:a,commitDraft:s,commitIncludeUnstaged:r,commitMessage:i,commitNextStep:c,canPublishOpenPondProject:l,expandProject:u,newProjectBusy:p,newProjectDialogOpen:f,newProjectDirectory:S,newProjectMode:b,newProjectName:w,newProjectPath:C,projectRows:P,query:_,searchOpen:M,visibleWorkspaceDiff:E,visibleWorkspaceState:T,workspaceBusy:y,appDispatch:I,beginNewChat:R,openDefaultsSettingsFromBranchDialog:O,setBranchDialogName:z,setBranchDialogOpen:$,setCommitDialogOpen:V,setCommitDraft:Y,setCommitIncludeUnstaged:se,setCommitMessage:ee,setCommitNextStep:H,setNewProjectDialogOpen:F,setNewProjectName:J,setNewProjectPath:K,setQuery:B,setSearchOpen:ne,submitCommitDialog:G,submitCreateWorkspaceBranch:te,submitNewProjectDialog:oe}){return g.jsxs(g.Fragment,{children:[M&&g.jsx(h.Suspense,{fallback:null,children:g.jsx(v4,{open:M,query:_,projects:P,sessions:e,onQueryChange:B,onClose:()=>{ne(!1),B("")},onNewChat:()=>{ne(!1),B(""),R()},onOpenProject:be=>{I({type:"selectProject",projectId:be.id}),I({type:"patch",patch:{searchOpen:!1,query:""}}),u(be.id)},onOpenSession:be=>{I({type:"selectSession",sessionId:be.id,appId:be.appId,projectId:be.workspaceKind==="local_project"&&be.workspaceId?ct("local",be.workspaceId):null}),I({type:"patch",patch:{searchOpen:!1,query:""}})}})}),f&&g.jsx(h.Suspense,{fallback:null,children:g.jsx(y4,{open:f,mode:b,name:w,path:C,directory:S,busy:p,onNameChange:J,onPathChange:K,onClose:()=>{p||F(!1)},onSubmit:oe})}),a&&g.jsx(h.Suspense,{fallback:null,children:g.jsx(S4,{open:a,branch:T?.currentBranch??null,filesChanged:E?.filesChanged??T?.changedFilesCount??0,additions:E?.additions??0,deletions:E?.deletions??0,message:i,includeUnstaged:r,nextStep:c,draft:s,busy:y,canPush:!!T?.remoteUrl,canPublish:l,onMessageChange:ee,onIncludeUnstagedChange:se,onNextStepChange:H,onDraftChange:Y,onClose:()=>{y||V(!1)},onSubmit:G})}),n&&g.jsx(h.Suspense,{fallback:null,children:g.jsx(x4,{open:n,branchName:t,busy:y,onBranchNameChange:z,onSetPrefix:O,onClose:()=>{y||$(!1)},onSubmit:te})})]})}function jI({toast:e,onDismiss:t}){if(!e)return null;const n=!!(e.actionLabel&&e.onAction);return g.jsxs("div",{className:`app-toast ${e.tone} ${e.placement??"bottom-right"}`,role:e.tone==="error"?"alert":"status","aria-live":"polite",children:[g.jsx("span",{className:"app-toast-message",children:e.message}),n&&g.jsx("div",{className:"app-toast-actions",children:g.jsx("button",{type:"button","aria-label":e.actionLabel,onClick:()=>{t(),e.onAction?.()},children:e.actionLabel})})]})}async function Bl(e,t,n){if(t.scope!==e.scope)throw new Error("Review workspace changed. Reload the assignment.");return L(e.connection,`/v1/human-review?location=${e.location}`,{method:"POST",body:JSON.stringify(_O.parse(t)),signal:n})}function Xb(e,t,n){const a=wx.parse(e);if(a.scope!==t.scope||a.id!==n)throw new Error("Review response identity differs from the requested assignment.");return a}const I4={inbox:async(e,t,n)=>_4(await Bl(e,{...t,endpoint:"inbox",scope:e.scope},n),e),get:async(e,t,n)=>Xb(await Bl(e,{endpoint:"get",scope:e.scope,id:t},n),e,t),inspect:async(e,t,n,a,s)=>C4(await Bl(e,{endpoint:"inspect",scope:e.scope,id:t,...n===void 0?{}:{slot:n},...a?{afterId:a}:{}},s),t),command:async(e,t)=>Xb(await Bl(e,{endpoint:"command",scope:e.scope,command:t}),e,t.id)};function _4(e,t){const n=mO.parse(e);if(n.items.some(a=>a.scope!==t.scope))throw new Error("Inbox response belongs to another workspace.");return n}function C4(e,t){const n=CO.parse(e);if(n.some(a=>a.reviewId!==t))throw new Error("Evidence response belongs to another assignment.");return n}function R4({context:e,onOpen:t}){const[n,a]=h.useState(null);return h.useEffect(()=>{const s=new AbortController;let r=0;async function i(){const l=++r;try{const u=await I4.inbox(e,{view:"mine",status:"active",limit:1},s.signal);!s.signal.aborted&&l===r&&a(u.actionCount)}catch{!s.signal.aborted&&l===r&&a(null)}}a(null),i();const c=window.setInterval(()=>{document.visibilityState==="visible"&&i()},15e3);return window.addEventListener("human-review-changed",i),()=>{s.abort(),window.clearInterval(c),window.removeEventListener("human-review-changed",i)}},[e.scope,e.actorId,e.location,e.connection]),g.jsxs("button",{type:"button",className:"titlebar-icon human-review-inbox-control",title:n?`Inbox · ${n} actions`:"Inbox","aria-label":n?`Inbox, ${n} actions`:"Inbox",onClick:t,children:[g.jsx(mg,{size:17,"aria-hidden":"true"}),n?g.jsx("span",{className:"human-review-inbox-count","aria-hidden":"true",children:n>99?"99+":n}):null]})}function P4({connection:e,teamId:t,actorId:n,projectId:a}){if(!e||!t||!n)return null;const s=()=>{Fr(wa("inbox",null,{area:"console",projectId:a}))};return g.jsx(R4,{context:{connection:e,scope:t,actorId:n,location:"hosted"},onOpen:s})}const nl=h.createContext(null);function T4({children:e}){const[t,n]=h.useState(null),[a,s]=h.useState(null),[r,i]=h.useState(null),c=h.useMemo(()=>({title:t,actions:a,activity:r,setTitle:n,setActions:s,setActivity:i}),[t,a,r]);return g.jsx(nl.Provider,{value:c,children:e})}function PG({children:e}){return g.jsx(nl.Provider,{value:null,children:e})}function A4({children:e,className:t=""}){const n=h.useContext(nl);return g.jsx("div",{ref:n?.setTitle,className:`page-chrome-title-target ${t}`,children:e?g.jsx("div",{className:"page-chrome-fallback",children:e}):null})}function E4({className:e=""}){const t=h.useContext(nl);return g.jsx("div",{ref:t?.setActions,className:e})}function TG({title:e,actions:t,fallback:n,children:a}){const s=h.useContext(nl);return s?g.jsxs(g.Fragment,{children:[s.title?Dd.createPortal(g.jsx("div",{className:"page-chrome-title",children:e}),s.title):null,s.actions&&t?Dd.createPortal(t,s.actions):null,a]}):n??g.jsxs("header",{children:[e,t]})}const j4=h.lazy(()=>fr(()=>import("./WorkspaceEnvironmentMenu-zdzSDofs.js"),__vite__mapDeps([30,1,2,21,27,13,16,31,29,32])).then(e=>({default:e.WorkspaceEnvironmentMenu})));function M4({sidebarOpen:e,sidebarAvailable:t=!0,title:n,breadcrumbs:a,backAction:s,workspaceName:r,workspaceId:i,busy:c,workspaceState:l,workspaceKind:u,selectedApp:p,selectedProject:f,workspaceDiff:S,managedWorkspace:b,workspaceBusy:w,defaultTeamId:C,activityActorId:P,activityProjectId:_,showDiffControls:M,diffPanelOpen:E,terminalOpen:T,rightSidebarAvailable:y=!1,rightSidebarOpen:I=!1,onToggleDiffPanel:R,onToggleRightSidebar:O,onOpenSearch:z,onToggleTerminal:$,onRunTerminalCommand:V,onWorkspaceToolAction:Y,onOpenCommitDialog:se,onWorkspaceBranchChange:ee,onWorkspaceBranchCreate:H,connection:F,onBootstrap:J,onOpenSandboxWorkspace:K,onShowSidebar:B,platform:ne,showWorkspaceControls:G=!0}){const te=S?.filesChanged??0;return g.jsxs("header",{className:"app-titlebar",children:[g.jsxs("div",{className:"titlebar-left",children:[t&&!e&&g.jsx("button",{className:"titlebar-icon",title:"Show sidebar",onClick:B,children:g.jsx(Kw,{size:16})}),s?g.jsx("button",{className:"titlebar-icon",type:"button","aria-label":s.label,title:s.label,onClick:s.onSelect,children:g.jsx(OH,{size:16})}):null,g.jsx(A4,{children:a?.length?g.jsx("nav",{className:"titlebar-breadcrumbs","aria-label":"Breadcrumb",children:a.map((oe,be)=>{const me=be===a.length-1;return g.jsxs("div",{className:"titlebar-breadcrumb-item",children:[oe.onSelect&&!me?g.jsx("button",{type:"button",onClick:oe.onSelect,children:oe.label}):g.jsx("strong",{children:oe.label}),!me&&g.jsx(pr,{size:14})]},`${oe.label}-${be}`)})}):g.jsxs("div",{className:"titlebar-title",children:[g.jsx("strong",{children:n}),r&&g.jsx("span",{children:r})]})})]}),g.jsxs("div",{className:"titlebar-right",children:[g.jsx(E4,{className:"page-chrome-actions"}),g.jsx(P4,{connection:F,teamId:C??null,actorId:P??null,projectId:_??null}),G&&g.jsxs("div",{className:"titlebar-actions",children:[g.jsx(h.Suspense,{fallback:null,children:g.jsx(j4,{mode:"topbar",busy:c,workspaceState:l,workspaceId:i,workspaceKind:u,selectedApp:p,selectedProject:f,workspaceBusy:w,defaultTeamId:C,workspaceDiff:S,managedWorkspace:b,showDiffControls:M,diffPanelOpen:E,onToggleDiffPanel:R,onRunTerminalCommand:V,onWorkspaceToolAction:Y,onOpenCommitDialog:se,onWorkspaceBranchChange:ee,onWorkspaceBranchCreate:H,connection:F,onBootstrap:J,onOpenSandboxWorkspace:K})}),g.jsx("button",{type:"button",className:"titlebar-icon",title:"Search chats and projects","aria-label":"Search chats and projects",onClick:z,children:g.jsx(TU,{size:16})}),g.jsx("button",{type:"button",className:`titlebar-icon ${T?"active":""}`,title:`${T?"Hide":"Show"} terminal`,"aria-label":`${T?"Hide":"Show"} terminal`,"aria-pressed":T,onClick:$,children:g.jsx(Gw,{size:16})}),M&&g.jsx("button",{type:"button",className:`topbar-diff-button ${I?"active":""}`,title:`${I?"Hide":"Show"} sidebar${te?`, ${te} changed files`:""}`,"aria-label":`${I?"Hide":"Show"} sidebar`,"aria-pressed":I,onClick:R,children:g.jsx(df,{size:16})})]}),y&&O&&!M?g.jsx("div",{className:"titlebar-actions",children:g.jsx("button",{type:"button",className:`topbar-diff-button ${I?"active":""}`,title:`${I?"Hide":"Show"} sidebar`,"aria-label":`${I?"Hide":"Show"} sidebar`,"aria-pressed":I,onClick:O,children:g.jsx(df,{size:16})})}):null,g.jsx(zB,{platform:ne})]})]})}function O4(){const[e,t]=h.useState(null),n=h.useRef(null),a=h.useCallback(r=>new Promise(i=>{n.current?.resolve(!1);const c={...r,cancelLabel:r.cancelLabel??"Cancel",tone:r.tone??"default",resolve:i};n.current=c,t(c)}),[]),s=h.useCallback(r=>{const i=n.current;n.current=null,t(null),i?.resolve(r)},[]);return{confirmAction:a,confirmDialog:e,resolveConfirmDialog:s}}function $4({state:e,onResolve:t}){const n=h.useId(),a=h.useId();if(h.useEffect(()=>{if(!e)return;function r(i){i.key==="Escape"&&t(!1)}return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[t,e]),!e)return null;const s=e.tone==="danger"?"git-dialog-primary danger":"git-dialog-primary";return g.jsx("div",{className:"git-dialog-backdrop",role:"presentation",onMouseDown:()=>t(!1),children:g.jsxs("section",{className:"git-dialog project-confirm-dialog",role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":a,onMouseDown:r=>r.stopPropagation(),children:[g.jsx("h2",{id:n,children:e.title}),g.jsx("p",{id:a,children:e.body}),g.jsxs("div",{className:"git-dialog-footer",children:[g.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:()=>t(!1),children:e.cancelLabel}),g.jsx("button",{type:"button",className:s,autoFocus:!0,onClick:()=>t(!0),children:e.confirmLabel})]})]})})}function N4(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=O4();return{confirmProjectAction:h.useCallback(s=>e({tone:"danger",...s}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function D4({state:e,onResolve:t}){return g.jsx($4,{state:e,onResolve:t})}const zd=new Map,L4=(e,t,n)=>{const a=zd.get(e)??{commits:0,maxActualDurationMs:0,totalActualDurationMs:0};a.commits+=1,a.maxActualDurationMs=Math.max(a.maxActualDurationMs,n),a.totalActualDurationMs+=n,zd.set(e,a)};function z4({children:e,id:t}){return g.jsx(h.Profiler,{id:t,onRender:L4,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...zd.entries()].map(([e,t])=>[e,{...t}])),reset:()=>zd.clear()});const H4=h.lazy(()=>fr(()=>import("./MainPane-C86le7UF.js").then(e=>e.o),__vite__mapDeps([33,1,2,10,34,15,31,12,13,35])).then(e=>({default:e.MainPane})));function U4({className:e,style:t,sidebar:n,topBar:a,mainPane:s,cloudSetup:r,projectConfirm:i,lazyPanels:c,toast:l}){return g.jsx(T4,{children:g.jsxs("div",{className:e,style:t,children:[g.jsx(u4,{sidebar:n,open:a.sidebarOpen}),a.sidebarAvailable!==!1?g.jsxs(z4,{id:"sidebar",children:[g.jsx(t4,{...n,open:a.sidebarOpen}),a.sidebarOpen?g.jsx("div",{className:"sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",onPointerDown:n.onSidebarResizeStart}):null]}):null,g.jsxs("div",{className:"content-shell",children:[g.jsx(M4,{...a}),g.jsx(h.Suspense,{fallback:g.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:g.jsx(H4,{...s})})]}),g.jsx(f4,{...r}),g.jsx(D4,{...i}),g.jsx(w4,{...c}),g.jsx(jI,{...l})]})})}function q4({settings:e,toast:t}){return g.jsxs(g.Fragment,{children:[g.jsx(k4,{...e}),g.jsx(jI,{...t})]})}const pd="OpenPond".split("");function B4({visibleLetterCount:e=pd.length}){const t=pd.slice(0,Math.max(0,Math.min(e,pd.length)));return g.jsxs("div",{className:"app-splash-lockup",children:[g.jsx("div",{className:"app-splash-mark",children:g.jsx("img",{alt:"OpenPond",className:"app-splash-logo",decoding:"async",src:Tg})}),g.jsx("span",{"aria-hidden":"true",className:`app-splash-wordmark${t.length>0?" is-visible":""}`,children:t.map((n,a)=>g.jsx("span",{className:"app-splash-letter",children:n},`${n}-${a}`))})]})}const hp=pd.length,F4=520,V4=240;function ey(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function K4({startup:e}){const[t,n]=h.useState(()=>ey()?hp:0);return h.useEffect(()=>{if(ey()){n(hp);return}const a=Array.from({length:hp},(s,r)=>window.setTimeout(()=>n(r+1),F4+V4*r));return()=>{a.forEach(s=>window.clearTimeout(s))}},[]),g.jsxs("main",{className:"app-splash","aria-busy":"true","aria-label":e.label,role:"status",children:[g.jsx(B4,{visibleLetterCount:t}),g.jsx("span",{className:"app-splash-status",children:e.label})]})}const jg=5e3;function si(e,t){if(e.length===0)return t;if(t.length===0)return e;const n=new Set,a=[];for(const s of[...e,...t])n.has(s.id)||(n.add(s.id),a.push(s));return a}function Ds(e,t,n=jg){return fd(si(e,t),n)}function fd(e,t=jg){return e.length<=t?e:e.slice(e.length-t)}function W4(e,t){if(t.length===0)return fd(e);if(e.length===0)return fd(t);const n=new Map;let a=0;for(const s of[...e,...t])n.has(s.id)||n.set(s.id,{event:s,index:a}),a+=1;return fd([...n.values()].sort((s,r)=>Z4(s,r)).map(({event:s})=>s))}function wf(e){let t=null;for(const n of e)typeof n.sequence=="number"&&(t=t===null?n.sequence:Math.max(t,n.sequence));return t}function G4(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function Z4(e,t){const n=e.event.sequence,a=t.event.sequence;if(typeof n=="number"&&typeof a=="number"){const i=n-a;if(i!==0)return i}const s=Date.parse(e.event.timestamp),r=Date.parse(t.event.timestamp);if(Number.isFinite(s)&&Number.isFinite(r)){const i=s-r;if(i!==0)return i}return e.index-t.index}function ty(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 J4(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function Q4(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 ny(e){return e==="codex"||e==="claude-code"}function Y4(e){return e==="openpond"}function MI(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=tj.safeParse(n.data);if(a.success)return a.data}return null}function OI(e){if(e.snapshot&&e.snapshot.provider===e.provider){const n=e.snapshot.usedTokens,a=e.snapshot.maxContextTokens,s=Math.min(100,Math.round(e.snapshot.percentFull)),r=`${s}% full`,i=`${ty(n)} / ${ty(a)} tokens used`,c=ny(e.provider)?`Context and compaction are managed by ${e.provider==="claude-code"?"Claude Code":"Codex app-server"}.`:Q4(e.preferences,s);return{usedTokens:n,maxTokens:a,percent:s,summary:r,tokensLabel:i,detail:c,tooltip:`Context window: ${r} ${i}. ${c}`,tone:J4(s)}}if(ny(e.provider)){const n=e.provider==="claude-code"?"Claude Code":"Codex app-server",a=`Context is managed by ${n}.`;return{usedTokens:0,maxTokens:null,percent:null,summary:"Managed externally",tokensLabel:n,detail:a,tooltip:`Context window: ${a}`,tone:"unknown"}}if(!Y4(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 Mg(e){let t=!1;const n=$I(e);for(let a=e.length-1;a>=0;a-=1){const s=e[a];if(X4(s)){t=!0;continue}const r=hi(s?.data);if(!(s?.name!=="diagnostic"||!r)){if(r.kind==="thread_goal_cleared")return null;if(r.kind==="thread_goal"){const i=Og(hi(r.goal),Qn(r.provider),n);if(i){const c=Dc(i);return t&&c.tone==="active"?null:c}}if(r.kind==="goal_context"){const i=DI(s.output??"",Qn(r.provider)??"codex",n);if(i){const c=Dc(i);return t&&c.tone==="active"?null:c}}}}return null}function Hd(e){const t=$I(e);for(let n=e.length-1;n>=0;n-=1){const a=e[n],s=hi(a?.data);if(!(a?.name!=="diagnostic"||!s)){if(s.kind==="thread_goal_cleared"&&s.synthetic!==!0)return null;if(s.kind==="thread_goal"){const r=Og(hi(s.goal),Qn(s.provider),t);if(!r)continue;const i=Dc(r);return i.tone==="active"?i:null}if(s.kind==="goal_context"){const r=DI(a.output??"",Qn(s.provider)??"codex",t);if(!r)continue;const i=Dc(r);return i.tone==="active"?i:null}}}return null}function gp(e){const t=hi(hi(e)?.codexGoalRuntime),n=Og(t,Qn(t?.provider)??"codex");if(!n)return null;const a=Dc(n);return a.tone==="active"?a:null}function X4(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function Dc(e){const t=LI(e.status),n=UI(e.timeUsedSeconds),a=`Goal ${n}`,s=e.tokensUsed===null?null:e.tokenBudget===null?`${vp(e.tokensUsed)} tokens`:`${vp(e.tokensUsed)} / ${vp(e.tokenBudget)} tokens`,r=s?`${e.statusLabel} · ${s}`:e.statusLabel;return{objective:e.objective,status:e.status,timeUsedSeconds:e.timeUsedSeconds,tokensUsed:e.tokensUsed,tokenBudget:e.tokenBudget,actionLabel:t.actionLabel,timeLabel:n,label:a,detail:r,tooltip:`Goal runtime: ${qI(e.timeUsedSeconds)}. ${r}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function eF(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=NI(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,s=UI(a);return{...e,timeUsedSeconds:a,timeLabel:s,label:`Goal ${s}`,tooltip:`Goal runtime: ${qI(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function Og(e,t=null,n=null){if(!e)return null;const a=Qn(e.objective)??"Active goal",s=Qn(e.status)??"active";if((If(t)??If(Qn(e.provider)))!=="codex")return null;const i=n??Qn(e.updatedAt)??Qn(e.updated_at)??null,c=Oo(e.timeUsedSeconds)??Oo(e.time_used_seconds)??0,l=Qn(e.activeSinceAt)??Qn(e.active_since_at),u=LI(s).tone==="active"?NI(l??Qn(e.createdAt)??Qn(e.created_at),i):0,p=l?c+u:Math.max(c,u),f=Oo(e.tokensUsed)??Oo(e.tokens_used),S=Oo(e.tokenBudget)??Oo(e.token_budget);return{objective:a,status:s,statusLabel:HI(s),timeUsedSeconds:Math.max(0,Math.floor(p)),tokensUsed:f===null?null:Math.max(0,Math.floor(f)),tokenBudget:S===null?null:Math.max(0,Math.floor(S)),observedAt:i}}function $I(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t]?.timestamp;if(n&&Number.isFinite(Date.parse(n)))return n}return null}function NI(e,t){if(!e||!t)return 0;const n=Date.parse(e),a=Date.parse(t);return!Number.isFinite(n)||!Number.isFinite(a)||a<=n?0:Math.floor((a-n)/1e3)}function DI(e,t=null,n=null){if(!e.trim()||If(t)!=="codex")return null;const a=zI(e,"Status")??"active",s=Yi(e,"Tokens used"),r=Yi(e,"Token budget"),i=Yi(e,"Time used seconds")??Yi(e,"Time spent pursuing goal")??Yi(e,"Elapsed seconds")??0;return{objective:ay(e,"objective")??ay(e,"untrusted_objective")??"Active goal",status:a,statusLabel:HI(a),timeUsedSeconds:Math.max(0,Math.floor(i)),tokensUsed:s,tokenBudget:r,observedAt:n}}function LI(e){switch(tF(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 tF(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function zI(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^\\s*-?\\s*${n}:\\s*(.+?)\\s*$`,"im").exec(e)?.[1]?.trim()||null}function Yi(e,t){const n=zI(e,t);if(!n)return null;const a=n.replace(/,/g,""),s=/-?\d+(?:\.\d+)?/.exec(a);if(!s)return null;const r=Number(s[0]);return Number.isFinite(r)?r:null}function ay(e,t){return new RegExp(`<${t}>\\s*([\\s\\S]*?)\\s*<\\/${t}>`,"i").exec(e)?.[1]?.trim()||null}function HI(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function UI(e){if(e<60)return`${e}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const n=Math.floor(t/60),a=t%60;return a>0?`${n}h ${a}m`:`${n}h`}function qI(e){if(e<60)return`${e} ${e===1?"second":"seconds"}`;const t=Math.floor(e/60);if(t<60)return`${t} ${t===1?"minute":"minutes"}`;const n=Math.floor(t/60),a=t%60;return a===0?`${n} ${n===1?"hour":"hours"}`:`${n}h ${a}m`}function vp(e){if(e<1e3)return String(e);if(e>=1e6){const n=e/1e6;return n<10?`${sy(n,2)}M`:n<100?`${sy(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 sy(e,t){return e.toFixed(t).replace(/\.?0+$/,"")}function hi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Qn(e){return typeof e=="string"&&e.trim()?e.trim():null}function If(e){return e?.trim().toLowerCase()||null}function Oo(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const nF=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),aF=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function _f(e){const t=BI(e);return t?iF(t):null}function BI(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=oF(mF(n.data));if(a)return a}return null}function sF(e){if(e.events)return BI(e.events);const t=e.messages??[];for(let n=t.length-1;n>=0;n-=1){const a=t[n]?.createImproveRun??null;if(a)return a}return null}function rF(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 oF(e){const t=qc.safeParse(e?.createImproveRun);return t.success?t.data:null}function iF(e){const t=cF(e);if(!t)return null;const n=lF(e.createdAt,e.updatedAt),a=e.blockedReason??dF(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:uF(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function cF(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return nF.has(t)?{tone:"active",actionLabel:`${n} running`}:aF.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 lF(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 dF(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function uF(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 mF(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function FI(e,t){if(!t)return null;const n=new Map,a=[];for(const T of e){if(!T.name.startsWith("subagent."))continue;const y=hF(T);y&&a.push(y);const I=fF(T);I?.parentSessionId===t&&n.set(I.id,I)}if(n.size===0)return null;const s=[...n.values()].sort((T,y)=>No(y).localeCompare(No(T))),r=s.filter(T=>T.status==="queued"||T.status==="running"),i=s.filter(T=>T.status==="completed"),c=s.filter(T=>T.status==="failed"),l=s.filter(T=>T.status==="cancelled"),u=s.filter(T=>T.status==="needs_resume"),p=[...i,...c,...l].sort((T,y)=>No(y).localeCompare(No(T))),f=s.reduce((T,y)=>{const I=gi(y.metadata?.usage);return T.totalTokens+=Vl(I?.totalTokens),T.promptTokens+=Vl(I?.promptTokens),T.completionTokens+=Vl(I?.completionTokens),T.requestCount+=Vl(I?.requestCount),T},{totalTokens:0,promptTokens:0,completionTokens:0,requestCount:0}),S=s.flatMap(T=>VI([...T.report?.blockers??[],T.error,T.progress.currentBlocker]).map(y=>({runId:T.id,roleId:T.roleId,status:T.status,message:y}))),b=s.flatMap(T=>KI([...T.report?.artifacts??[],T.report?.patchRef,T.report?.diffRef,...T.progress.patchRefs]).map(y=>({...y,runId:T.id,roleId:T.roleId}))),w=p.map(T=>pF(T,a)),C=s[0]??null,P=C?{runId:C.id,roleId:C.roleId,status:C.status,message:C.progress.latestMeaningfulActivity||C.report?.summary||C.objective,updatedAt:No(C)}:null,_=r.length>0?`${r.length} ${r.length===1?"child":"children"} running`:`${p.length} ${p.length===1?"child":"children"} finished`,M=[r.length?`${r.length} active`:null,i.length?`${i.length} completed`:null,c.length?`${c.length} failed`:null,l.length?`${l.length} cancelled`:null,u.length?`${u.length} paused`:null].filter(Boolean).join(" · "),E=P?`${bF(P.roleId)}: ${P.message}`:"";return{sessionId:t,runs:s,activeRuns:r,completedRuns:i,failedRuns:c,cancelledRuns:l,needsResumeRuns:u,terminalRuns:p,latestRun:C,latestMeaningfulUpdate:P,activeCount:r.length,completedCount:i.length,failedCount:c.length,cancelledCount:l.length,needsResumeCount:u.length,terminalCount:p.length,usage:f,blockers:S,evidenceRefs:b,finalResults:w,testsRunCount:s.reduce((T,y)=>T+y.progress.validationAttempts.length,0),label:_,tooltip:[M,E].filter(Boolean).join(". ")}}function pF(e,t){return{runId:e.id,roleId:e.roleId,status:e.status,objective:e.objective,summary:e.report?.summary||e.error||"Child conversation finished.",findings:e.report?.findings??[],changedFiles:e.progress.changedFiles,refs:KI([...e.report?.artifacts??[],e.report?.patchRef,e.report?.diffRef]),testsRun:e.report?.testsRun??[],validationAttempts:e.progress.validationAttempts.map(n=>n.command),blockers:VI([...e.report?.blockers??[],e.error]),confidence:e.report?.confidence??null,importantMessages:t.filter(n=>n.fromRunId===e.id).map(n=>({id:n.id,runId:e.id,fromRunId:n.fromRunId,kind:n.kind,body:n.body,createdAt:n.createdAt})),workspaceRetention:gF(e),updatedAt:No(e)}}function fF(e){const t=gi(e.data),n=[t?.run,gi(t?.message)?.run];for(const a of n){const s=wS.safeParse(a);if(s.success)return s.data}return null}function hF(e){const t=PE.safeParse(gi(e.data)?.message);return t.success?t.data:null}function gF(e){const t=gi(gi(e.metadata?.workspaceHandoff)?.workspaceRetention);return t?.status!=="retained"?null:{status:"retained",reason:Fl(t.reason),retainedAt:Fl(t.retainedAt),expiresAt:Fl(t.expiresAt),retentionDays:vF(t.retentionDays),trigger:Fl(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function No(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function VI(e){return[...new Set(e.map(t=>t?.trim()).filter(t=>!!t))]}function KI(e){const t=new Map;for(const n of e)n&&t.set(`${n.kind}:${n.id}`,n);return[...t.values()]}function gi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Fl(e){return typeof e=="string"&&e.trim()?e.trim():null}function Vl(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function vF(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function bF(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const Cf=[];function Rf(e,t){return WI(e,t,null)}function WI(e,t,n){const a=n&&wF(n.events,e)?SF(n.indexes,n.events.length,e):yF(e),s=kF(t);return{...a,...s}}function yF(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 xF(t)}function SF(e,t,n){const a=new Map(e.eventsBySessionId),s=new Map(e.latestContextUsageBySessionId),r=new Map(e.latestGoalRuntimeBySessionId),i=new Map(e.latestSubagentRuntimeBySessionId),c=new Set(e.activeGoalSessionIds),l=new Set(e.activeSubagentSessionIds),u=new Set;for(let p=t;p<n.length;p+=1){const f=n[p];if(!f.sessionId)continue;if(u.has(f.sessionId)){a.get(f.sessionId).push(f);continue}const S=a.get(f.sessionId);a.set(f.sessionId,S?[...S,f]:[f]),u.add(f.sessionId)}for(const p of u){const f=a.get(p)??Cf,S=MI(f);S?s.set(p,S):s.delete(p);const b=ZI(f);b?(r.set(p,b),b.tone==="active"?c.add(p):c.delete(p)):(r.delete(p),c.delete(p));const w=FI(f,p);w?(i.set(p,w),GI({sessionEvents:f,sessionId:p,latestGoalRuntimeBySessionId:r,activeGoalSessionIds:c}),w.activeCount>0?l.add(p):l.delete(p)):(i.delete(p),l.delete(p))}return{eventsBySessionId:a,latestContextUsageBySessionId:s,latestGoalRuntimeBySessionId:r,latestSubagentRuntimeBySessionId:i,activeGoalSessionIds:c,activeSubagentSessionIds:l}}function xF(e){const t=new Map,n=new Map,a=new Map,s=new Set,r=new Set;for(const[i,c]of e){const l=MI(c);l&&t.set(i,l);const u=ZI(c);u&&(n.set(i,u),u.tone==="active"&&s.add(i))}for(const[i,c]of e){const l=FI(c,i);l&&(a.set(i,l),GI({sessionEvents:c,sessionId:i,latestGoalRuntimeBySessionId:n,activeGoalSessionIds:s}),l.activeCount>0&&r.add(i))}return{eventsBySessionId:e,latestContextUsageBySessionId:t,latestGoalRuntimeBySessionId:n,latestSubagentRuntimeBySessionId:a,activeGoalSessionIds:s,activeSubagentSessionIds:r}}function GI(e){if(e.latestGoalRuntimeBySessionId.has(e.sessionId))return;const t=Hd(e.sessionEvents);t&&(e.latestGoalRuntimeBySessionId.set(e.sessionId,t),t.tone==="active"&&e.activeGoalSessionIds.add(e.sessionId))}function ZI(e){return _f(e)??Mg(e)??Hd(e)}function kF(e){const t=new Map,n=new Map,a=new Map,s=new Map;for(const r of e){t.set(r.id,r);const i=n.get(r.status);if(i?i.push(r):n.set(r.status,[r]),r.status!=="pending")continue;const c=a.get(r.sessionId);c?c.push(r):a.set(r.sessionId,[r]);const l=s.get(r.sessionId);(!l||ry(r.createdAt)>ry(l.createdAt))&&s.set(r.sessionId,r)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:s}}function wF(e,t){return e===t?!0:e.length>t.length||e.length===t.length?!1:e.length===0?!0:e[0]===t[0]&&e[e.length-1]===t[e.length-1]}function al(e,t){return t?e.eventsBySessionId.get(t)??Cf:Cf}function JI(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function QI(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function IF(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function _F(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function ry(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function CF(e,t){return e?.conversationId===t}function RF(e,t){return e?.id===t?null:e}function PF(e){const t=new Set;if(e.readmePath){const n=e.readmePath.replaceAll("\\","/").split("/").at(-1);n&&t.add(n)}for(const n of e.skills){t.add(n.relativePath);const a=n.relativePath.lastIndexOf("/"),s=a>=0?n.relativePath.slice(0,a):"";for(const r of n.resourceFiles)t.add(s?`${s}/${r}`:r)}return{name:`${e.owner}/${e.repo}`,description:`${e.skills.length} installed skill${e.skills.length===1?"":"s"} from GitHub.`,scope:"extension",packagePath:e.sourcePath,files:[...t]}}function TF(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function AG(e,t){return e.profiles.find(n=>TF(n.ref)===t)?.ref??null}function AF(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function EG(e,t){return e.profiles.find(n=>AF(n.ref,t))?.state??null}function EF(e,t){const n=new Map(Kj.map(a=>[a.name,{...a,validationMessages:[...a.validationMessages],resourceFiles:[...a.resourceFiles]}]));for(const a of e?.skills??[])n.has(a.name)||n.set(a.name,a);for(const a of t?.extensions??[])if(a.validationStatus==="valid")for(const s of a.skills)s.validationStatus!=="valid"||n.has(s.name)||n.set(s.name,{name:s.name,description:s.description,path:s.relativePath,scope:"profile",enabled:!0,sourcePath:a.sourcePath,charCount:s.charCount,sourceHash:s.sourceHash,validationStatus:"valid",validationMessages:[],resourceFiles:s.resourceFiles});return[...n.values()].sort((a,s)=>a.name.localeCompare(s.name))}function jF(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 jG(e,t){const n=`Continue from the attached Work output "${e.title}" (revision ${e.revision}).`;return t==="work"?`${n} Choose a Project or repository before making source changes; do not mutate a checkout until I choose it.`:n}const YI="openpond:last-chat-task-mode";function MF(e,t){return e==="labs"?"models":"chat"}function OF(e){try{return e.getItem(YI)==="work"?"work":"chat"}catch{return"chat"}}function $g(){if(typeof window>"u")return"chat";try{return OF(no)}catch{return"chat"}}function $F(e,t){try{e.setItem(YI,t==="chat"?"chat":"work")}catch{}}function NF(e){if(!(typeof window>"u"))try{$F(no,e)}catch{}}const DF="uploaded to a different account";function XI(e,t){const n=e?.linkedSandboxProject??null;if(!n?.projectId||!n.teamId)return{state:"none",linked:null,cloudProject:null};const a=t?.find(s=>s.id===n.projectId&&s.teamId===n.teamId)??null;return a?{state:"confirmed",linked:n,cloudProject:a}:{state:"different_account",linked:n,cloudProject:null}}function Ra(e,t){const n=XI(e,t);return n.state==="confirmed"?n.cloudProject:null}function LF(e,t){return XI(e,t).state==="different_account"?DF:null}function Ss(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function e1(e={}){return{...e,workspaceTarget:"hybrid"}}function zF(e={}){return{...e,workspaceTarget:"local"}}function xs(e){return e?.metadata?.workspaceTarget==="hybrid"}function HF(e){return!!(e&&e.provider==="openpond"&&e.workspaceKind==="local_project"&&e.cloudProjectId&&e.title.trim().endsWith(" Cloud"))}function t1({cloudProjects:e,selectedCloudProject:t,selectedProject:n}){const a=n?.linkedSandboxProject??null,s=e?Ra(n,e):null,r=t?.id??s?.id??(e?null:a?.projectId??null),i=t?.teamId??s?.teamId??(e?null:a?.teamId??null);return!r||!i?{kind:"missing_cloud_project",message:"Upload/sync this Project to Cloud before using Hybrid."}:{kind:"ready",cloudProjectId:r,cloudTeamId:i,cwd:n?.workspacePath??null,localProjectId:n?.id??null,workspaceName:t?.name??s?.name??a?.projectName??n?.name??"Hybrid workspace"}}function n1({modelRef:e,provider:t,target:n,title:a}){return{provider:t,...e?{modelRef:e}:{},appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:n.workspaceName,localProjectId:n.localProjectId,cloudProjectId:n.cloudProjectId,cloudTeamId:n.cloudTeamId,metadata:e1(),cwd:n.cwd,title:a}}function UF(e){return h.useEffect(()=>{const t=uI(e.selectedSession);!t||e.composerDraftStore.getSnapshot()||e.composerDraftStore.set(t)},[e.composerDraftStore,e.selectedSession?.id]),h.useCallback(async t=>{const n=t.trim();if(!e.connection||!n||e.activeExperience==="chat")return!1;const a=Cq(n);try{let s;const r=e.selectedSession;if(r&&$c(r))s=await Z.patchSession(e.connection,r.id,{title:a,metadata:lp(r.metadata,n)}),e.setSessions(i=>i.map(c=>c.id===s.id?s:c));else{const i=r?.metadata?.workspaceTarget==="hybrid"?"hybrid":r?.metadata?.workspaceTarget==="local"?"local":null,c=r?.provider??(e.selectedCloudProject?"openpond":e.activeProvider),l=r?.modelRef??(c==="openpond"?{providerId:"openpond",modelId:ii}:{providerId:c,modelId:e.activeModel}),u=i?{workspaceTarget:i}:!r&&e.workspaceTarget==="local"?{workspaceTarget:"local"}:{};let p;if(!r&&e.workspaceTarget==="hybrid"){const f=t1({cloudProjects:e.cloudProjects,selectedCloudProject:e.selectedCloudProject,selectedProject:e.selectedProject});if(f.kind!=="ready")throw new Error(f.message);const S=n1({modelRef:l,provider:c,target:f,title:a});p={...S,experience:"work",metadata:lp(S.metadata,n)}}else p={experience:"work",provider:c,modelRef:l,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:lp(u,n),title:a};s=await Z.createSession(e.connection,p),e.setSessions(f=>[s,...f])}return e.composerDraftStore.set(""),e.setMentionedAppId(null),e.setSelectedSessionId(null),e.setView("chat"),e.requestComposerFocus(),e.showToast("Task draft saved.","success"),!0}catch(s){return e.showToast(s instanceof Error?s.message:"Could not save task draft.","error"),!1}},[e.activeExperience,e.activeModel,e.activeOpenPondCommandAccessMode,e.activeProvider,e.cloudProjects,e.composerDraftStore,e.connection,e.requestComposerFocus,e.selectedCloudProject,e.selectedProject,e.selectedSession,e.setMentionedAppId,e.setSelectedSessionId,e.setSessions,e.setView,e.showToast,e.workspaceTarget])}const qF=[];function BF({primary:e,secondary:t}){const[n,a]=h.useState(null),s=h.useRef(new Set),[r,i]=h.useState(!1),[c,l]=h.useState(null),u=sq(),p=u?.kind==="models"&&["home","inbox","datasets","graders","experiments"].includes(u.route.page),{composerDraftStore:f,appDispatch:S,pendingTerminalCommand:b,setPendingTerminalCommand:w,terminalTabs:C,setTerminalTabs:P,trainingDetailTasksetId:_,setTrainingDetailTasksetId:M,mentionedAppId:E,setMentionedAppId:T,cloudSetupDialog:y,setCloudSetupDialog:I,rightPanelTabRequest:R,workspaceDiffPanelViewState:O,mainComposerFocusRequestId:z,requestMainComposerFocus:$,projectConfirmDialog:V,resolveProjectConfirmDialog:Y,query:se,searchOpen:ee,archivedChatsOpen:H,sectionMenuOpen:F,cloudProjectsExpanded:J,sidebarOpen:K,view:B,selectedAppId:ne,selectedProjectId:G,selectedSessionId:te,codexPermissionMode:oe,codexReasoningEffort:be,busy:me,diffPanelOpen:Re,diffPanelExpanded:Q,rightPanelMode:xe,activeExperience:je,changeNewExperience:De,terminalOpen:He,settingsSection:Ie,newProjectDialogOpen:Me,newProjectMode:Te,newProjectName:N,newProjectPath:q,newProjectBusy:X,commitDialogOpen:U,commitMessage:ae,commitIncludeUnstaged:de,commitNextStep:ye,commitDraft:Oe,branchDialogOpen:$e,branchDialogName:Ge,toast:yt,labDetailNavigation:Se,setQuery:Le,setSearchOpen:Ae,setArchivedChatsOpen:qe,setSectionMenuOpen:Ue,setCloudProjectsExpanded:bn,setChatRowsVisibleCount:Mt,setSidebarOpen:pe,setView:fe,setSelectedAppId:Fe,setSelectedProjectId:Pe,setSelectedSessionId:Ne,setPrompt:ot,setDraftProvider:ut,setDraftModel:At,setDraftExperience:mt,setDiffPanelOpen:at,setDiffPanelExpanded:Ct,setRightPanelMode:Be,setTerminalOpen:Et,setSettingsSection:dn,setNewProjectDialogOpen:jn,setNewProjectName:kt,setNewProjectPath:ks,setCommitDialogOpen:un,setCommitMessage:yn,setCommitIncludeUnstaged:Ut,setCommitNextStep:Rn,setCommitDraft:Sn,setBranchDialogOpen:Pn,setBranchDialogName:Mn,setError:qt,showToast:gt,applyBootstrapPayload:qn,applyPreferencesPayload:mn,bootstrap:pt,connection:_t,startup:Ot,training:pn,pinnedCollapsed:oa,cloudProjectsCollapsed:Ze,chatsCollapsed:Tn,savedForLaterCollapsed:Ja,sidebarWidth:Ea,sidebarResizing:Ln,diffPanelWidth:An,diffPanelResizing:Qa,togglePinnedCollapsed:ws,toggleCloudProjectsCollapsed:ja,toggleChatsCollapsed:lt,toggleSavedForLaterCollapsed:sn,startSidebarResize:Ke,startDiffPanelResize:St,selectedApp:en,selectedCloudProject:zn,selectedProject:xn,selectedProjectLinkedApp:D,selectedSession:we,sidebarSessions:le,runtimeIndexes:Je,runtimeEventStore:ga,chatMentionApps:Bn,connectedAppMentions:Ma,pendingApproval:kn,pendingChatUserMessages:ao,account:Is,activeModel:On,activeProvider:ia,appDefaults:ca,startMessage:_s,organizations:kr,teamChatOrganization:wr,teamChatTeamId:Ir,teamChat:ft,publishTeamProfileAgent:_i,communitySidebar:_r,communityView:Ci,teamAiThreadId:so,toggleTeamAiSidebar:Ri,activeOpenPondCommandAccessMode:Cs,viewWorkspaceAppId:Pi,viewWorkspaceId:ro,viewWorkspaceKind:oo,viewWorkspaceName:io,selectedActionCatalog:Ti,expandedProjectIds:Ai,expandProject:Ya,toggleProjectExpanded:Ei,changeCodexPermissionMode:co,changeCodexReasoningEffort:Cr,changeOpenPondCommandAccessMode:Rr,resolveApproval:lo,beginNewChat:la,beginNewChatWithTrainingModel:ji,dismissTrainingChatHandoff:Pr,trainingChatHandoff:Rs,selectTrainingChatTaskForComposer:Gn,chatHistoryLoadStates:Mi,loadMoreSelectedChatHistory:Oi,selectedPagedSessionEvents:wn,activeSessions:Ks,archivedSessions:Zn,pinnedSessions:Ps,savedForLaterSessions:Tr,savedForLaterFiles:Ws,sidebarFileBookmarks:$i,setSidebarFileStatus:uo,setSessions:Ar,projectRows:Ts,localProjectRows:As,cloudProjectRows:Er,projectSessionRowsByProjectId:mo,childSessionRowsByParentId:Gs,sidebarProjectIdBySessionId:Xa,chatRows:va,visibleChatRows:po,chatRowsVisibleCount:Zs,sessionEvents:es,goalRuntime:fo,subagentRuntime:Oa,visibleChatMessages:ho,activeTerminalScope:Ni,terminalSummaries:go,runningSessionIds:Di,selectedSessionRunning:vo,sidebarGoalRuntimeBySessionId:bo,sidebarSubagentRuntimeBySessionId:yo,taskDragSessionId:jr,taskPreviewSessionIds:So,startTaskDrag:Mr,clearTaskDrag:ts,previewTaskDrop:Li,commitTaskDrop:zi,commitTaskPreviewDrop:Hi,dragItem:Ui,startPinnedDrag:ns,clearSidebarDrag:xo,previewPinnedDrop:qi,commitPinnedDrop:Bi,commitPinnedPreviewDrop:Fi,commandProjectRows:da,contextWindowStatus:ko,pinnedRows:et,workspaceBusy:Ft,diffBusy:as,visibleWorkspaceState:rn,visibleWorkspaceDiff:Hn,refreshVisibleWorkspaceDiff:$n,managedWorkspace:ju,canSyncActiveWorkspace:Mu,canPublishOpenPondProject:Ou,projectTarget:$u,workspaceTarget:rl}=e,{title:Nu,browserConversationId:Or,handleWorkspaceDiffPanelViewStateChange:ol,openSessionInChat:wo,changeProjectTarget:Du,submitNewProjectDialog:Lu,changeWorkspaceBranch:zu,openCommitDialog:Hu,openCreateWorkspaceBranchDialog:Uu,openDefaultsSettingsFromBranchDialog:qu,runWorkspaceTool:Bu,submitCommitDialog:Fu,submitCreateWorkspaceBranch:Vu,syncWorkspaceLocally:Ku,answerCreateImproveQuestion:il,applyCreateImproveCandidate:Wu,approveCreateImproveRun:Gu,cancelCreateImproveRun:Zu,changeDraftProvider:Vi,openCreateImprovePullRequest:cl,reconcileCreateImprovePullRequest:Ju,rejectCreateImproveCandidate:Qu,pauseCreateImproveRun:ll,resumeCreateImproveRun:dl,reviseCreateImproveRun:Yu,stopTurn:Io,archiveSession:Xu,restoreSession:ul,renameSession:em,toggleSessionPinned:Ki,toggleProjectPinned:ml,toggleSessionSavedForLater:pl,moveProjectToCloud:tm,startCloudSetupUpload:fl,changeWorkspaceTarget:nm,sendPromptFromMainComposer:am,openSandboxWorkspace:hl,openCloudProjectDialog:sm,openExistingProjectPathDialog:gl,openUrlInBrowserPanel:rm,showBrowserPanel:om,showChangesPanel:im,showGoalSidebarTab:Js,rightChatTrainingLaunchRequest:vl,setRightChatTrainingLaunchRequest:cm,closeRightChatPanel:lm,openRightChatPanel:Wi,rightChatPanelViews:dm,showRightChatPanel:um,showRightPanelDiffTab:mm,submitRightChatPrompt:pm,activateRightChatPanel:fm,updateRightChatModel:hm,updateRightChatPrompt:gm,updateRightChatProvider:vm,updateRightChatScrollState:bm,openProfileSettings:ym,diagnosticEvents:Sm,toggleRightSidebar:bl,removeProject:xm}=t;hC(_t,pt?.account.activeProfile&&pt.preferences.defaultTeamId?JSON.stringify([pt.account.baseUrl,pt.account.activeProfile,pt.account.profile?.id,pt.account.state,pt.preferences.defaultTeamId]):null,()=>{Lt({kind:"chat",sessionId:null}).then(he=>{he&&(Ne(null),fe("chat"),a("activity"))})});const $a=pt?.account.activeProfile&&pt?.preferences.defaultTeamId?`${pt.account.activeProfile.handle}:${pt.preferences.defaultTeamId}`:null;h.useEffect(()=>{if(!(!$a||B!=="chat"||u?.kind!=="chat"||u.sessionId||te||s.current.has($a))){s.current.add($a);try{const he=localStorage.getItem(`openpond:ponder-mode:v1:${$a}`);(he==="clean"||he==="activity")&&a(he)}catch{}}},[$a,u,B,te]),h.useEffect(()=>{if(!(!$a||!s.current.has($a)))try{localStorage.setItem(`openpond:ponder-mode:v1:${$a}`,n??"off")}catch{}},[$a,n]);const _o=h.useCallback(he=>{Fe(null),Pe(he),Ne(null),fe("chat"),Ya(he),$()},[Ya,$,Fe,Pe,Ne,fe]),km=h.useCallback((he=null)=>{a(null);const Xe=te?Xa[te]??null:null;if(!he&&Xe){_o(Xe);return}la(he)},[la,_o,te,Xa]),wm=h.useCallback(async he=>{if(!(!_t||!pt))try{const Xe=await Z.savePreferences(_t,{defaultTeamId:he});mn(Xe)}catch(Xe){const $t=Xe instanceof Error?Xe.message:String(Xe);throw qt($t),gt("Could not switch teams","error"),Xe}},[mn,pt,_t,qt,gt]),Im=h.useCallback(async()=>{if(_t)try{const he=await Z.signOutOpenPondAccount(_t);qn(he),gt("Logged out","success")}catch(he){const Xe=he instanceof Error?he.message:String(he);throw qt(Xe),gt("Could not log out","error"),he}},[qn,_t,qt,gt]),Gi=ca.defaultTeamId??null,_m=h.useMemo(()=>Ts.filter(he=>he.kind==="local"||Gi!==null&&he.project.teamId===Gi),[Ts,Gi]),Cm=h.useMemo(()=>{const he={};for(const Xe of Ks){const $t=Xa[Xe.id];$t&&(he[$t]=(he[$t]??0)+1)}for(const Xe of As){if(Xe.kind!=="local")continue;const $t=Xe.project.linkedSandboxProject?.projectId;if(!$t||!Xe.cloudLinkTrusted)continue;const ba=ct("cloud",$t);he[Xe.id]=(he[Xe.id]??0)+(he[ba]??0)}return he},[Ks,As,Xa]),[yl,Es]=h.useState(null),[Co,Ro]=h.useState(null),Rm=EF(pt?.profile,pt?.extensionCatalog),[$r,Zi]=h.useState(null),[Po,Ji]=h.useState(null),[ss,Sl]=h.useState(null),Pm=h.useCallback(async()=>{await Lt({kind:"view",view:"team"})&&(Fe(null),Pe(null),Ne(null),Ue(null),fe("team"))},[Ue,Fe,Pe,Ne,fe]),Tm=h.useCallback(async()=>{await Lt({kind:"view",view:"community"})&&(Fe(null),Pe(null),Ne(null),Ue(null),_r.discoverCommunities())},[_r.discoverCommunities,Ue,Fe,Pe,Ne]),Am=UF({activeExperience:je,activeModel:On,activeOpenPondCommandAccessMode:Cs,activeProvider:ia,cloudProjects:pt?.cloudProjects??qF,composerDraftStore:f,connection:_t,requestComposerFocus:$,selectedCloudProject:zn,selectedProject:xn,selectedSession:we,setMentionedAppId:T,setSelectedSessionId:Ne,setSessions:Ar,setView:fe,showToast:gt,workspaceTarget:rl.value}),Em=h.useCallback(async he=>{if(!_t)throw new Error("OpenPond is not connected.");let Xe=ia,$t=On;Xe==="codex"&&(Xe=Sf(pt?.providers,{enabledOnly:!0}).find(In=>In.value!=="codex")?.value??Kr,$t=Nd(Xe,pt?.providers)??wc);const ba=le.find(In=>In.id===he.sourceSessionId),js=await Z.createSession(_t,{experience:he.target,provider:Xe,modelRef:{providerId:Xe,modelId:$t},openPondCommandAccessMode:Cs,appId:null,appName:null,workspaceId:null,workspaceName:null,localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,title:`Continue ${ba?.title??"task"}`.slice(0,120),metadata:{experienceHandoff:jF({sourceTaskId:he.sourceSessionId,sourceExperience:ba?.experience??null,targetExperience:he.target,sourceMessageIds:he.sourceMessageIds??[],sourceContext:he.sourceContext,output:he.output})}});return Ar(In=>[js,...In]),mt(he.target),ut(Xe),At($t),f.set(he.prompt),Lt({kind:"chat",sessionId:js.id}),S({type:"selectSession",sessionId:js.id,appId:null,projectId:null}),Fe(null),Pe(null),Et(!1),fe("chat"),Be("home"),at(he.target==="work"),Ct(!1),js},[On,Cs,ia,S,pt?.providers,f,_t,Ct,at,mt,At,ut,Be,Fe,Pe,Ar,Et,fe,le]),jm=h.useCallback(he=>{Zi(he),Ji(null),la(null),pe(!0)},[la,pe]),Mm=h.useCallback(he=>{la(null),mt("work"),f.set(`$openpond-refiner-authoring ${he}`),fe("chat"),pe(!0)},[la,f,mt,pe,fe]),xl=h.useCallback(he=>{Ji(PF(he)),Zi(null),la(null),pe(!0)},[la,pe]);h.useEffect(()=>{!$r&&!Po||B!=="chat"||te||G||ne||(Es($r),Ro(Po),Zi(null),Ji(null),Be("home"),Ct(!1),at(!0))},[$r,Po,ne,G,te,Ct,at,Be,B]),h.useEffect(()=>{!yl&&!Co||B==="chat"&&Re&&xe==="home"||(Es(null),Ro(null))},[Re,Co,yl,xe,B]);const kl=h.useCallback(()=>{Es(null),Ro(null),Ct(!1),at(!1)},[Ct,at]),Om=h.useCallback(he=>{let Xe;if(he.workspaceKind==="local"){const $t=ct("local",he.workspaceId);Xe=`draft:${$t}`,Fe(null),Pe($t),Ne(null),Ya($t),fe("chat")}else{const $t=le.find(ba=>ba.id===he.sourceSessionId||ba.workspaceId===he.workspaceId);if(!$t){gt("This saved file's cloud chat is no longer available.","error");return}Xe=$t.id,wo($t.id)}Be("changes"),at(!0),Sl({id:Date.now(),conversationId:Xe,file:he}),he.available||gt(`File unavailable: ${he.path}`,"error")},[Ya,wo,at,Be,Fe,Pe,Ne,fe,gt,le]);h.useEffect(()=>{if(!CF(ss,Or))return;const he=window.setTimeout(()=>{Be("changes"),at(!0),Sl(Xe=>RF(Xe,ss.id))},0);return()=>window.clearTimeout(he)},[Or,at,Be,ss]);const wl=u?.kind==="models"&&u.route.area==="console"?"console":MF(B);h.useEffect(()=>{if(u){if(u.kind==="models"||u.kind==="models_unavailable"){B!=="labs"&&fe("labs");return}if(u.kind==="settings"){Fe(null),Pe(null),Ne(null),dn(u.section),B!=="settings"&&fe("settings");return}if(u.kind==="view"){Fe(null),Pe(null),Ne(null),B!==u.view&&fe(u.view);return}u.sessionId!==null&&(a(null),Fe(null),Pe(null)),Ne(u.sessionId),B!=="chat"&&fe("chat")}},[u,Fe,Pe,Ne,dn,fe,B]);const $m=h.useCallback(he=>{if(Ue(null),Fe(null),Pe(null),Ne(null),he==="models"||he==="console"){Fr(he==="console"?wa("datasets",null,{area:"console"}):wa()),fe("labs");return}he==="chat"&&Lt({kind:"chat",sessionId:null}),De($g())},[De,Lt,Ue,Fe,Pe,Ne,fe]),Nm=h.useCallback(async(he,Xe)=>{const $t=await pn.actions.acceptHarnessReview(he,Xe,{providerId:ia,modelId:On},be);return $t?(M($t.materializedTasksetId??null),Fr(wa()),fe("labs"),!0):(gt("Taskset review could not be opened.","error"),!1)},[On,ia,be,Fr,wa,M,fe,gt,pn.actions]),Ve=h.useMemo(()=>nC([...Je.eventsBySessionId.values()].flat()),[Je.eventsBySessionId]);if(!Ot.ready)return g.jsx(K4,{startup:Ot});if(B==="settings")return g.jsx(Jb,{showToast:gt,children:g.jsx(q4,{settings:{payload:pt,connection:_t,diagnostics:Sm,initialSection:Ie,onPayload:qn,onError:qt,onToast:gt,onOpenSourceSession:wo,onStartRefinerAuthoring:Mm,onAcceptEvaluationReview:Nm,onOpenSkill:jm,onOpenExtension:xl,teamChatCurrentUserId:ft.currentUserId,teamChatEnabled:Ir!==null,teamChatNotificationMode:ft.notificationMode,teamChatThreads:ft.threads,onTeamChatNotificationModeChange:ft.setNotificationMode,onTeamChatThreadMuteChange:ft.setThreadMuted,diffPanelWidth:An,diffPanelResizing:Qa,diffPanelExpanded:Q,onDiffPanelResizeStart:St,onDiffPanelExpandedChange:Ct,onBack:()=>{const he=tq(u);Lt(he),fe(he.kind==="models"?"labs":"chat"),pe(!0)}},toast:{toast:yt,onDismiss:()=>S({type:"field",key:"toast",value:null})}})});const tn=Eg(),Bt=wl==="console"||B==="chat",Vt=Bt&&K,ua=_t?.platform??navigator.platform,Dm=tn&&_I(ua),Zg=Ni,i_=rn?.initialized?rn.repoPath:we?.cwd??null,c_={"--sidebar-width":`${Ea}px`,"--diff-panel-width":`${An}px`},l_=B==="chat"&&je!=="chat"||B==="labs"||B==="scheduled"&&r||B==="team"&&!!so,d_=["app-shell",Dm?"platform-macos":"",Vt?"sidebar-open":"sidebar-closed",Ln?"sidebar-resizing":"",Qa?"diff-panel-resizing":""].filter(Boolean).join(" "),Lm=te?Mi[te]:null,u_=te?Lm?.cursorSequence??G4(Ds(wn,al(Je,te))):null,m_=!!te&&!!_t&&(Gt(te)?!0:!!pt?.eventWindow?.hasMoreBefore&&!!u_)&&(Lm?.hasMore??!0),p_=!!Lm?.loading,f_=(()=>{const he=pn.payload;if(!he)return{};const Xe=new Map(he.plans.map(In=>[In.id,In])),$t=new Set(["queued","starting","running","cancelling","reconciling"]),ba={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},js={};for(const In of[...he.modelRuns].sort((Na,To)=>To.updatedAt.localeCompare(Na.updatedAt))){if(In.kind==="evaluation"||!["prepared","running"].includes(In.status))continue;const Na=he.jobs.filter(zm=>zm.metadata.modelRunId===In.id).sort((zm,h_)=>h_.updatedAt.localeCompare(zm.updatedAt))[0];if(Na&&!$t.has(Na.status))continue;const To=Na?.status??(In.status==="prepared"?"starting":"running");js[In.modelId]={label:ba[To]??"Running",status:To}}for(const In of[...he.jobs].sort((Na,To)=>To.updatedAt.localeCompare(Na.updatedAt))){if(!$t.has(In.status))continue;const Na=Xe.get(In.planId)?.modelId;!Na||js[Na]||(js[Na]={label:ba[In.status]??"Active",status:In.status})}return js})();return g.jsx(Jb,{showToast:gt,children:g.jsx(U4,{className:d_,style:c_,sidebar:{activityTimes:Ve,onOpenPonder:()=>{Lt({kind:"chat",sessionId:null}),Ne(null),fe("chat"),a("activity")},productArea:wl,modelProjects:(pn.payload?.modelProjects??[]).filter(he=>he.hosted===null||he.hosted.teamId===(ca.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:f_,onProductAreaChange:$m,experience:je,view:B,selectedAppId:ne,selectedProjectId:G,selectedSessionId:te,selectedTeamThreadId:ft.selectedThreadId,teamChatEnabled:Ir!==null,organizations:kr,selectedTeamId:ca.defaultTeamId??null,teamChatOrganization:wr,teamChatLoading:ft.loading,currentUserId:ft.currentUserId,teamMembers:ft.members,teamThreads:ft.threads,..._r,onOpenTeamChat:Pm,discoverCommunities:Tm,account:Is,connection:_t,profile:pt?.profile,pinnedCollapsed:oa,cloudProjectsCollapsed:Ze,chatsCollapsed:Tn,savedForLaterCollapsed:Ja,archivedChatsOpen:H,cloudProjectsExpanded:J,sectionMenuOpen:F,dragItem:Ui,taskDragSessionId:jr,taskPreviewSessionIds:So,activeSessions:Ks,archivedSessions:Zn,pinnedRows:et,pinnedSessions:Ps,savedForLaterSessions:Tr,savedForLaterFiles:Ws,projectRows:Ts,localProjectRows:As,cloudProjectRows:Er,projectSessionRowsByProjectId:mo,childSessionRowsByParentId:Gs,sidebarProjectIdBySessionId:Xa,terminalSummaries:go,runningSessionIds:Di,goalRuntimeBySessionId:bo,subagentRuntimeBySessionId:yo,visibleChatRows:po,chatRows:va,chatRowsVisibleCount:Zs,expandedProjectIds:Ai,currentVersion:pt?.server.version??null,platform:ua,arch:_t?.arch??null,onSidebarResizeStart:Ke,setSidebarOpen:pe,setView:fe,setSelectedAppId:Fe,setSelectedProjectId:Pe,setSelectedSessionId:Ne,setSearchOpen:Ae,setSectionMenuOpen:Ue,setSettingsSection:dn,onSelectTeam:wm,onLogOut:Im,onTogglePinnedCollapsed:ws,onToggleCloudProjectsCollapsed:ja,onToggleChatsCollapsed:lt,onToggleSavedForLaterCollapsed:sn,setArchivedChatsOpen:qe,setCloudProjectsExpanded:bn,setChatRowsVisibleCount:Mt,beginNewChat:km,beginProjectChat:_o,onAddProject:gl,dockSessionRight:Wi,selectTeamThread:he=>{fe("team"),ft.selectThread(he)},openTeamDm:he=>{fe("team"),ft.openDm(he)},toggleSessionPinned:Ki,toggleProjectPinned:ml,toggleSessionSavedForLater:pl,openSidebarFile:Om,setSidebarFileStatus:(he,Xe)=>{uo(he,Xe)},archiveSession:Xu,restoreSession:ul,renameSession:em,removeProject:xm,expandProject:Ya,toggleProjectExpanded:Ei,startPinnedDrag:ns,clearSidebarDrag:xo,previewPinnedDrop:qi,commitPinnedDrop:Bi,commitPinnedPreviewDrop:Fi,startTaskDrag:Mr,clearTaskDrag:ts,previewTaskDrop:Li,commitTaskDrop:zi,commitTaskPreviewDrop:Hi},topBar:{sidebarOpen:Vt,sidebarAvailable:Bt,title:B==="chat"&&n?"Ponder Pal":Nu,backAction:Se.backAction,breadcrumbs:Se.breadcrumbs,workspaceName:io,workspaceId:ro,busy:me,workspaceState:rn,workspaceKind:oo,selectedApp:D??en,selectedProject:xn,workspaceDiff:Hn,managedWorkspace:ju,workspaceBusy:Ft,defaultTeamId:ca.defaultTeamId,activityActorId:pt?.account.profile?.id??null,activityProjectId:u?.kind==="models"?u.route.projectId??null:null,showDiffControls:B==="chat"&&je==="development",diffPanelOpen:Re,terminalOpen:He,rightSidebarAvailable:l_,rightSidebarOpen:B==="labs"&&p?c?.open??!1:B==="scheduled"?r:Re,onToggleDiffPanel:bl,onToggleRightSidebar:B==="labs"&&p?c?.toggle:B==="scheduled"?()=>i(he=>!he):B==="team"&&so?Ri:bl,onOpenSearch:()=>{Ue(null),Ae(!0)},onToggleTerminal:()=>Et(he=>!he),onRunTerminalCommand:he=>{w({id:Date.now(),scope:Zg,command:he}),Et(!0)},onWorkspaceToolAction:Bu,onOpenCommitDialog:Hu,onWorkspaceBranchChange:zu,onWorkspaceBranchCreate:Uu,connection:_t,onBootstrap:qn,onOpenSandboxWorkspace:hl,onShowSidebar:()=>pe(!0),platform:ua,showWorkspaceControls:B!=="team"&&B!=="community"&&B!=="labs"&&B!=="scheduled"&&B!=="outputs"&&B!=="projects"&&(je==="development"||je==="work"&&!!(xn||we?.localProjectId||we?.cloudProjectId||we?.workspaceKind==="local_project"))},mainPane:{ponderMode:n,onPonderModeChange:a,experience:je,onNewExperienceChange:De,view:B,teamChat:{currentUserId:ft.currentUserId,members:ft.members,agents:ft.agents,profile:pt?.profile??null,teamId:Ir,teamName:wr?.displayName??null,detail:ft.detail,aiThread:ft.aiThread,agentConversation:ft.agentConversation,loading:ft.loading,busy:ft.busy,error:ft.error,connection:_t,providerSettings:pt?.providers??null,provider:ia,model:On,codexPermissionMode:oe,codexReasoningEffort:be,openPondCommandAccessMode:Cs,contextWindowStatus:ko,showToast:gt,onProviderChange:Vi,onModelChange:At,onCodexPermissionModeChange:co,onCodexReasoningEffortChange:Cr,onOpenPondCommandAccessModeChange:Rr,onOpenProviderSettings:()=>{Lt({kind:"view",view:"apps"})},onSendMessage:ft.sendMessage,onPublishProfileAgent:_i,onOpenAiThread:async he=>{await ft.openAiThread(he),Be("chat"),at(!0)},onOpenAgentConversation:async he=>{await ft.openAgentConversation(he),Be("chat"),at(!0)},onCloseAiThread:()=>at(!1),onCloseAgentConversation:()=>{ft.closeAgentConversation(),at(!1)},onSendAgentTurn:ft.sendAgentTurn,onSendAiTurn:ft.sendAiTurn,onStopAiTurn:ft.stopAiTurn,onEditMessage:ft.editMessage,onDeleteMessage:ft.deleteMessage,onRetryMessage:ft.retryMessage,onDismissFailedMessage:ft.dismissFailedMessage,onLoadMoreMessages:ft.loadMoreMessages,onRetryLoad:ft.refresh},community:Ci,bootstrap:pt,runtimeEvents:es,chatMessages:ho,pendingUserMessage:te?ao[te]??null:null,contextWindowStatus:ko,goalRuntime:fo,subagentRuntime:Oa,selectedSessionId:te,composerDraftStore:f,mainComposerFocusRequestId:z,labCloseDetailRequestId:Se.closeDetailRequestId,labCloseDetailKind:Se.closeDetailKind,sideChatTrainingLaunchRequest:vl,onSideChatTrainingLaunchHandled:he=>cm(Xe=>Xe?.id===he?null:Xe),mentionApps:Bn,connectedAppMentions:Ma,profileSkills:Rm,selectedMentionAppId:E,busy:me,turnRunning:vo,activeProvider:ia,activeModel:On,codexPermissionMode:oe,codexReasoningEffort:be,openPondCommandAccessMode:Cs,pendingApproval:kn,activeWorkspaceAppId:Pi,activeWorkspaceId:ro,activeWorkspaceKind:oo,projectTarget:$u,actionCatalog:Ti,workspaceTarget:rl,connection:_t,workspaceName:io,workspaceState:rn,workspaceDiff:Hn,workspaceBusy:Ft,diffBusy:as,forceChatThread:!!te,diffPanelOpen:Re,diffPanelExpanded:Q,rightPanelMode:xe,rightPanelTabRequest:R,rightChatPanels:dm,runtimeEventStore:ga,nativeSkillSidebar:yl,extensionSkillSidebar:Co,workspaceDiffPanelViewState:O,sidebarFileOpenRequest:ss,sidebarFileBookmarks:$i,onSetSidebarFileStatus:(he,Xe)=>{uo(he,Xe)},browserConversationId:Or,terminalScope:Zg,terminalTabs:C,terminalCwd:i_,pendingTerminalCommand:b,terminalOpen:He,onToggleTerminal:()=>Et(he=>!he),onWorkspaceDiffPanelViewStateChange:ol,training:pn,trainingSessions:le,trainingChatHandoff:Rs,trainingDetailTasksetId:_,onTrainingDetailTasksetIdChange:M,onTrainingChatTaskSelect:Gn,onTrainingChatHandoffDismiss:Pr,onOpenSession:wo,onExperienceHandoff:Em,cloudProjects:pt?.cloudProjects??[],projects:_m,projectsAccountBaseUrl:Is?.baseUrl??Is?.activeProfile?.baseUrl??null,projectsTeamName:wr?.displayName??null,projectTaskCounts:Cm,onNewCloudProject:sm,onNewLocalProject:gl,onNewProjectTask:he=>_o(he.id),onToggleProjectPinned:ml,onUploadLocalProject:tm,chatHistoryHasMore:m_,chatHistoryLoading:p_,onDiffPanelResizeStart:St,onToggleDiffPanelExpanded:()=>Ct(he=>!he),onShowDiffPanel:im,onShowBrowserPanel:om,onShowFilesPanel:()=>mm("files"),onShowGoalSidebarTab:Js,onShowTrainingDraftPanel:()=>{Be("training"),at(!0)},onShowRightChatPanel:um,onAddRightChat:()=>Wi(null),onOpenRightChatForSession:(he,Xe)=>{const $t=Xe??le.find(ba=>ba.id===he)??null;$t&&Wi($t,{preserveView:!0})},onLabDetailOpenChange:Se.onDetailOpenChange,evaluationSidebarActive:B==="labs"&&p,onEvaluationSidebarControl:l,scheduledDetailOpen:r,onScheduledDetailOpenChange:i,onTerminalTabsChange:P,onCloseRightChatPanel:lm,onCloseNativeSkillSidebar:kl,onActivateRightChatPanel:fm,onRightChatModelChange:hm,onRightChatPromptChange:gm,onRightChatScrollStateChange:bm,onRightChatProviderChange:vm,onSubmitRightChat:pm,onStopRightChat:he=>Io(he),onCloseTerminal:()=>Et(!1),onLoadMoreChatHistory:Oi,canSyncWorkspace:Mu,startMessage:_s,onPayload:qn,onError:qt,setView:fe,onOpenProfileSettings:ym,onOpenProviderSettings:()=>{Lt({kind:"view",view:"apps"})},onOpenTrainingSettings:()=>{Lt({kind:"settings",section:"training"})},onOpenDatasetStorageSettings:()=>{Lt({kind:"settings",section:"dataset-storage"})},changeDraftProvider:Vi,changeProjectTarget:Du,changeWorkspaceTarget:nm,setDraftProvider:ut,setDraftModel:At,onBeginNewChatWithModel:ji,changeCodexPermissionMode:co,changeCodexReasoningEffort:Cr,changeOpenPondCommandAccessMode:Rr,resolveApproval:lo,answerCreateImproveQuestion:il,applyCreateImproveCandidate:Wu,approveCreateImproveRun:Gu,cancelCreateImproveRun:Zu,openCreateImprovePullRequest:cl,reconcileCreateImprovePullRequest:Ju,rejectCreateImproveCandidate:Qu,pauseCreateImproveRun:ll,resumeCreateImproveRun:dl,reviseCreateImproveRun:Yu,setMentionedAppId:T,showToast:gt,onSaveTaskDraft:Am,sendPrompt:am,stopTurn:he=>Io(void 0,he),syncWorkspaceLocally:Ku,refreshWorkspaceDiff:$n},cloudSetup:{state:y,onClose:()=>I(null),onOpenBrowserUrl:rm,onStart:()=>{fl()}},projectConfirm:{state:V,onResolve:Y},lazyPanels:{activeSessions:Ks,branchDialogName:Ge,branchDialogOpen:$e,commitDialogOpen:U,commitDraft:Oe,commitIncludeUnstaged:de,commitMessage:ae,commitNextStep:ye,canPublishOpenPondProject:Ou,connection:_t,expandProject:Ya,newProjectBusy:X,newProjectDialogOpen:Me,newProjectDirectory:ca.defaultNewProjectDirectory,newProjectMode:Te,newProjectName:N,newProjectPath:q,projectRows:da,query:se,searchOpen:ee,visibleWorkspaceDiff:Hn,visibleWorkspaceState:rn,workspaceBusy:Ft,appDispatch:S,beginNewChat:()=>la(null),openDefaultsSettingsFromBranchDialog:qu,setBranchDialogName:Mn,setBranchDialogOpen:Pn,setCommitDialogOpen:un,setCommitDraft:Sn,setCommitIncludeUnstaged:Ut,setCommitMessage:yn,setCommitNextStep:Rn,setNewProjectDialogOpen:jn,setNewProjectName:kt,setNewProjectPath:ks,setPrompt:ot,setQuery:Le,setSearchOpen:Ae,submitCommitDialog:Fu,submitCreateWorkspaceBranch:Vu,submitNewProjectDialog:Lu},toast:{toast:yt,onDismiss:()=>S({type:"field",key:"toast",value:null})}})})}const Go=new Map,hd=new Map;function Pf(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(s=>s.isActive)??null,n=e.activeProfile?.handle?.trim()||t?.handle?.trim()||e.label.trim()||"signed_in",a=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"";return[n,a,e.apiBaseUrl??"",e.chatApiBaseUrl??""].join("|")}function FF(e){const t=e?.trim();if(!t)return null;const n=Go.get(t);return n?.updatedAt?n.organizations:null}function VF(e,t){const n=e?.trim();if(n){Go.set(n,{organizations:t,promise:null,updatedAt:Date.now()});for(const a of hd.get(n)??[])a()}}function KF(e,t){const n=e?.trim();if(!n)return()=>{};const a=hd.get(n)??new Set;return a.add(t),hd.set(n,a),()=>{a.delete(t),a.size===0&&hd.delete(n)}}function oy(e){const t=e.accountKey?.trim();if(!t)return Promise.resolve([]);const n=Go.get(t);if(!e.force){if(n?.updatedAt)return Promise.resolve(n.organizations);if(n?.promise)return n.promise}const a=e.fetchOrganizations().then(s=>(VF(t,s),s)).catch(s=>{const r=Go.get(t);throw r?.promise===a&&Go.set(t,{organizations:r.organizations,promise:null,updatedAt:r.updatedAt}),s});return Go.set(t,{organizations:n?.organizations??[],promise:a,updatedAt:n?.updatedAt??0}),a}const MG="openpond.config.json";function OG(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function a1(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function bp(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function $G(e,t=null){const n=GF(e.openFilePaths.map(s=>cy(s,t)).filter(Boolean)),a=e.selectedPath&&cy(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function iy(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 cy(e,t=null){let n=WF(e);const a=t?.trim().replace(/\\/g,"/").replace(/\/+$/,"");if(!a)return n;if(n===a)return"";n.startsWith(`${a}/`)&&(n=n.slice(a.length+1));const s=a.split("/").filter(Boolean).at(-1);return s&&n.startsWith(`${s}/`)&&(n=n.slice(s.length+1)),n}function NG(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function DG(e){return{path:e,status:"unchanged",additions:0,deletions:0,patch:"",content:null}}function LG(e,t){const n=ly(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const s=ly(a);return!!(s&&s.startsWith(`${n}/`))})}function zG(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function HG(e){return/\.(?:doc|docx|pdf)$/i.test(e)}function WF(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 GF(e){return Array.from(new Set(e))}function ly(e){const n=e.replace(/\\/g,"/").replace(/^\.\/+/,"").split("/").filter(Boolean);return n.length===0?null:n.join("/")}function ZF(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(c=>c.isActive)??null,n=e.profile?.id?.trim()??"",a=e.activeProfile?.handle?.trim()||t?.handle?.trim()||e.label.trim()||"signed_in",s=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"",r=e.apiBaseUrl??t?.apiBaseUrl??"",i=e.chatApiBaseUrl??t?.chatApiBaseUrl??"";return[n?`profile:${n}`:"profile:unknown",a,s,r,i].join("|")}function s1(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function JF(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n)}function _u(e){const t=e,n=t.teamId||t.id||"";if(!n)return null;const a=t.displayName||t.name||n,s=t.workspaceKind==="personal"||t.isPersonalDefault===!0||t.kind==="personal_default"||t.name?.trim().toLowerCase()==="personal";return{teamId:n,slug:t.slug||s1(a),name:t.name||a,displayName:a,role:t.role==="owner"||t.role==="admin"||t.role==="member"?t.role:"member",workspaceKind:t.workspaceKind==="personal"||t.workspaceKind==="shared"?t.workspaceKind:s?"personal":"shared",status:t.status==="disabled"||t.status==="archived"?t.status:"active",kind:t.kind==="personal_default"||t.kind==="managed_client"||t.kind==="team"?t.kind:void 0,isPersonalDefault:s,isManagedClient:t.isManagedClient===!0||t.kind==="managed_client",primaryContactEmail:t.primaryContactEmail??null,customDomain:t.customDomain??null,planKey:typeof t.planKey=="string"?t.planKey:null,effectiveAccessState:t.effectiveAccessState==="checkout_pending"||t.effectiveAccessState==="active"||t.effectiveAccessState==="grace"||t.effectiveAccessState==="suspended"||t.effectiveAccessState==="cancelling"||t.effectiveAccessState==="cancelled"?t.effectiveAccessState:null,canManageBilling:t.canManageBilling===!0||t.role==="owner",createdAt:t.createdAt??"",updatedAt:t.updatedAt??""}}function QF(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 YF(e,t){const n=e.filter(s=>s.status==="active"&&s.workspaceKind==="shared"),a=t?.trim()??"";if(a){const s=n.find(r=>r.teamId===a);if(s)return s}return n.find(s=>s.role==="owner")??n.find(s=>s.role==="admin")??n[0]??null}function XF(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function e5({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const t5=[{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 n5(...e){return XF(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function a5(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return n5(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function s5({bootstrap:e,draftModel:t,draftProvider:n,selectedApp:a,selectedAppId:s,selectedCloudProject:r,selectedProject:i,selectedSession:c,selectedSessionId:l,selectedSessionLinkedProject:u}){const p=c?.workspaceKind==="local_project"?c.workspaceId??null:u?.id??null,f=Gt(l)&&!c,S=c?Ss(c.workspaceKind):!1,b=xs(c),w=c?HF(c):!1,C=c?.cwd&&(!S||b)?AS(c.cwd):null,P=e?.providers??null,_=Ra(i,e?.cloudProjects??[]),M=e5({draftProvider:n,hasSelectedCloudProject:!!r,selectedSessionHybridWorkspace:b}),E=Sr(M,t,P),T=Sa(e?.preferences),y=f?null:c?S?c.workspaceKind??"sandbox":w?"sandbox":p?"local_project":c.workspaceKind??(c.appId?"sandbox_app":C?"local_project":null):r?"sandbox":i?"local_project":s?"sandbox_app":null,I=f?null:c?S&&!b||w?null:p||(c.workspaceId??c.appId??C):r?null:i?.id??s,R=f?null:c?S?c.workspaceId??null:w?null:p??c.workspaceId??c.appId??C:r?null:i?.id??s,O=e?.account??null,z=!e||O?.state==="loading"||O?.state==="switching",$=!z&&O?.state==="signed_out",V=z?null:$?"Sign in":O?.label??O?.activeProfile?.handle??"Account",Y=a5(O),se=Y?`Welcome, ${Y}`:"Welcome",ee=c?.workspaceName??c?.appName??r?.name??i?.name??a?.name??null,H=Ss(y)?"cloud":"local",F=i?.name??u?.name??(c?.workspaceKind==="local_project"?c.workspaceName:null)??"Local workspace",J=(H==="cloud"?ee:null)??r?.name??_?.name??i?.name??"Cloud workspace",K=!!(r?.id||_?.id||c?.cloudProjectId||H==="cloud");return{account:O,accountLabel:V,accountPending:z,accountSignedOut:$,activeModel:E,activeProvider:M,activeWorkspaceAppId:I,activeWorkspaceId:R,activeWorkspaceKind:y,activeWorkspaceLocation:H,appDefaults:T,cloudLinked:K,cloudTargetName:J,localTargetName:F,selectedCodexHistoryPending:f,selectedSessionCloudWorkspace:S,selectedSessionLocalPathWorkspaceId:C,selectedSessionPendingCloudStart:w,selectedSessionProjectId:p,startMessage:se,workspaceName:ee}}function r5({accountPending:e,accountSignedOut:t,activeWorkspaceLocation:n,bootstrap:a,busy:s,cloudLinked:r,selectedCloudProject:i,selectedProject:c,selectedSession:l,pendingWorkspaceTarget:u,workspaceStates:p,workspaceBusy:f}){const S=Ra(c,a?.cloudProjects??[]),w=!!!c?.linkedSandboxProject?.projectId||!!S,C=h.useMemo(()=>{const R=(a?.localProjects??[]).map(V=>({value:`local:${V.id}`,label:V.name,detail:V.workspacePath,kind:"local"})),O=(a?.cloudProjects??[]).map(V=>({value:`cloud:${V.id}`,label:V.name,detail:V.organizationName??V.sourceLabel??"OpenPond Cloud",kind:"cloud"})),z=c?`local:${c.id}`:i?`cloud:${i.id}`:"none",$=[...R,...O].find(V=>V.value===z)??null;return{value:z,label:$?.label??"Select Project",detail:$?.detail??"Choose a project for local or cloud work",busy:f||s,options:[...R,...O,...t5,{value:"none",label:"Don't work in a project",detail:"General chat without project files",kind:"none"}]}},[a?.cloudProjects,a?.localProjects,s,i,c,f]),P=!!(r||c),_=!!(i?.id||S?.id||l?.cloudProjectId||xs(l)),M=c?p[c.id]??null:null,E=bI(M,{branch:c?.linkedSandboxProject?.defaultBranch??null,path:c?.workspacePath??l?.cwd??null,linkedCloudSourceKnown:c?.linkedSandboxProject?.projectId&&w?!!c.linkedSandboxProject.lastUploadedCommit||!M?.headCommit:!0}),T=yI(c,i??S,M,{cloudLinkTrusted:w}),y=Hq(c,M,{cloudLinkTrusted:w}),I=h.useMemo(()=>{const R={value:"local",label:c?"Local checkout":"Local",detail:c?"Use the selected checkout on this machine.":"Use an app-managed task workspace on this machine.",stateNote:c?E:"App-managed local task workspace",disabled:!1,disabledReason:null},O={value:"hybrid",label:"Hybrid",detail:"Use your selected model with hosted sandbox edits.",stateNote:_?T:"upload required",disabled:e||t||!_,disabledReason:t?"Add an OpenPond account before using Hybrid.":"Upload/sync this Project to Cloud before using Hybrid."},z={value:"cloud",label:"Hosted",detail:"Run with hosted compute, with or without a Project.",stateNote:c||i?T:"Projectless hosted task",disabled:e||t,disabledReason:t?"Add an OpenPond account before using Cloud.":e?"Checking OpenPond account.":null},$={value:"upload_cloud",label:"Upload/sync to cloud",detail:"Push local source to OpenPond Git before cloud work.",stateNote:y,disabled:e||t||!c,disabledReason:t?"Add an OpenPond account before uploading source.":"Select a local Project before uploading source."},V=n==="cloud"?"local":"cloud",Y=V==="local"?R:z;let se=n==="cloud"?z:R;return u==="cloud"?se=z:u==="local"?se=R:(xs(l)||u==="hybrid")&&(se=O),{value:se.value,label:se.label,detail:se.stateNote||se.detail,busy:f,action:{...Y,label:V==="cloud"?"Hosted":c?"Local checkout":"Check out locally"},uploadAction:c?$:null,options:[R,O,z]}},[n,e,t,r,P,T,_,E,u,c,l,y,f]);return{projectTarget:C,workspaceTarget:I}}function Un(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}function r1(e){return Un(e.name||e.gitRepo||e.id)}function UG(e){return`@${r1(e)}`}function o1(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Un(t[1]??"")).filter(Boolean)}function o5(e,t){const n=o1(e);if(n.length===0)return!1;const a=new Set([Un(t.id),r1(t),t.gitRepo?Un(t.gitRepo):""].filter(Boolean));return n.some(s=>a.has(s))}function i1(e){return e.filter(t=>t.sandbox)}function i5(e,t){const n=o1(e);if(n.length===0)return null;const a=new Map;for(const s of n){const r=t.find(i=>{const c=Un(i.id),l=Un(i.name),u=i.gitRepo?Un(i.gitRepo):"";return s===c||s===l||s===u});r&&a.set(r.id,r)}return a.size===1?Array.from(a.values())[0]??null:null}function qG(e,t){const n=e.slice(0,t),a=n.match(/(?:^|\s)@([A-Za-z0-9_-]*)$/);if(!a||typeof a.index!="number")return null;const s=n.slice(a.index).indexOf("@");return s<0?null:{query:Un(a[1]??""),start:a.index+s}}function c5(e){return new Set(e.map(t=>t.id))}function dy(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function l5({bootstrap:e,codexHistorySessions:t,selectedProjectId:n,selectedSessionId:a,selectedAppId:s,sessions:r}){const i=h.useMemo(()=>e?.apps.find($=>$.id===s)??null,[e?.apps,s]),c=h.useMemo(()=>new Map((e?.localProjects??[]).map($=>[$.id,$])),[e?.localProjects]),l=h.useMemo(()=>new Map((e?.cloudProjects??[]).map($=>[$.id,$])),[e?.cloudProjects]),u=h.useMemo(()=>oI(n),[n]),p=h.useMemo(()=>u?.kind==="local"?c.get(u.id)??null:null,[c,u]),f=h.useMemo(()=>u?.kind==="cloud"?l.get(u.id)??null:null,[l,u]),S=h.useMemo(()=>c5(e?.apps??[]),[e?.apps]),b=h.useMemo(()=>i1(e?.apps??[]),[e?.apps]),w=h.useMemo(()=>{const $=[];for(const V of e?.localProjects??[]){const Y=dy(V,S);Y&&$.push([Y.appId,V.id])}return new Map($)},[e?.localProjects,S]),C=h.useMemo(()=>new Set((e?.localProjects??[]).map($=>$.id)),[e?.localProjects]),P=h.useMemo(()=>mI(e?.localProjects??[]),[e?.localProjects]),_=h.useRef([]),M=h.useMemo(()=>d5(r,t,_.current),[t,r]),E=h.useMemo(()=>M.find($=>$.id===a)??null,[M,a]),T=h.useMemo(()=>{if(!E)return null;if(E.localProjectId)return c.get(E.localProjectId)??null;if(E.workspaceKind==="local_project")return E.workspaceId?c.get(E.workspaceId)??null:null;const $=Aq(E,C,P);if($)return c.get($)??null;if(!E.appId)return null;const V=w.get(E.appId);return V?c.get(V)??null:null},[w,c,C,P,E]),y=h.useMemo(()=>E?.cloudProjectId?l.get(E.cloudProjectId)??null:null,[l,E]),I=p??T,R=f??y,O=h.useMemo(()=>dy(I,S),[S,I]),z=h.useMemo(()=>O?e?.apps.find($=>$.id===O.appId)??null:null,[e?.apps,O]);return{cloudProjectById:l,currentAppIds:S,linkedProjectByAppId:w,localProjectById:c,mentionableSandboxApps:b,selectedApp:i,selectedCloudProject:R,selectedProject:I,selectedProjectLinkedApp:z,selectedProjectLinkedOpenPondApp:O,selectedSession:E,selectedSessionLinkedProject:T,sidebarSessions:M}}function d5(e,t,n){const a=new Map;for(const u of e){const p=uy(u);a.set(p,u)}for(const u of t){const p=uy(u),f=a.get(p);a.set(p,f?u5(f,u):u)}const s=Array.from(a.entries());if(!n)return s.sort((u,p)=>my(u[1],p[1])).map(u=>u[1]);const r=[],i=new Set;for(const u of n){const p=a.get(u);p&&(r.push([u,p]),i.add(u))}const l=[...s.filter(([u])=>!i.has(u)).sort((u,p)=>my(u[1],p[1])),...r];return n.splice(0,n.length,...l.map(([u])=>u)),l.map(u=>u[1])}function u5(e,t){return{...e,metadata:m5(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:p5(e.updatedAt,t.updatedAt)}}function uy(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function my(e,t){const n=py(t)-py(e);return n!==0?n:e.title.localeCompare(t.title)}function m5(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function p5(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 py(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 f5(e){return!!(e&&Ss(e.workspaceKind)&&!xs(e)&&e.provider!=="openpond")}function h5(e,t){const n=lI(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function g5({activeWorkspaceId:e,activeWorkspaceKind:t,appDispatch:n,connection:a,expandProject:s,linkedProjectByAppId:r,providerSettings:i,selectedAppId:c,selectedSession:l,selectedSessionId:u,selectedSessionProjectId:p,setDiffPanelExpanded:f,setDraftModel:S,setDraftProvider:b,setError:w,setSelectedAppId:C,setSelectedProjectId:P,setSessions:_,setTerminalOpen:M,toast:E}){const T=h.useRef(null);h.useEffect(()=>{if(!c)return;const y=p??(u?null:r.get(c)??null);if(!y)return;const I=ct("local",y);C(null),P(I),s(I)},[s,r,c,u,p,C,P]),h.useEffect(()=>{if(!E||E.persistent)return;const y=window.setTimeout(()=>{n({type:"clearToast",toastId:E.id})},E.durationMs??(E.tone==="error"?7e3:3500));return()=>window.clearTimeout(y)},[n,E]),h.useEffect(()=>{function y(I){(I.metaKey||I.ctrlKey)&&I.key==="`"&&(I.preventDefault(),M(R=>!R))}return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[M]),h.useEffect(()=>{f(!1)},[e,t,f]),h.useEffect(()=>{if(!u){T.current=null;return}if(!l||l.id!==u)return;const y=h5(l,i);if(T.current===y)return;T.current=y;const I=lI(l,i);b(I.provider),S(I.model)},[i,l,u,S,b]),h.useEffect(()=>{!a||!l||!f5(l)||Z.patchSession(a,l.id,{provider:"openpond"}).then(y=>{_(I=>I.map(R=>R.id===y.id?y:R)),b("openpond"),S(I=>Sr("openpond",I))}).catch(y=>{w(y instanceof Error?y.message:String(y))})},[a,l,S,b,w,_])}function v5({connection:e,setError:t}){return h.useCallback(async(n,a,s)=>{if(!e){const r=new Error("OpenPond App server is not connected.");throw t(r.message),r}t(null);try{await Z.resolveApproval(e,n,{decision:a,answers:s})}catch(r){const i=r instanceof Error?r.message:String(r);throw t(i),r}},[e,t])}function b5({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:s,pinnedProjects:r,projectRows:i,visibleProjectRows:c}){const l=h.useMemo(()=>gq(a,s),[a,s]),u=h.useMemo(()=>OI({provider:e,snapshot:n,preferences:t}),[e,t,n]),p=h.useMemo(()=>Array.from(new Set([...r,...c].filter(wg).map(S=>S.project.id))),[r,c]);return{commandProjectRows:h.useMemo(()=>i,[i]),contextWindowStatus:u,pinnedRows:l,sidebarWorkspaceAppIds:p}}function y5({appDispatch:e,expandProject:t,linkedProjectByAppId:n,requestComposerFocus:a,onBeginNewChat:s,setMentionedAppId:r}){return h.useCallback((i=null)=>{s?.();const c=i?.id?n.get(i.id)??null:null;if(c){const l=ct("local",c);r(null),e({type:"selectProject",projectId:l}),t(l),a();return}r(null),e({type:"beginNewChat",appId:i?.id??null}),a()},[e,t,n,s,a,r])}const c1={slack:["slack"],microsoft_teams:["teams","microsoft-teams","microsoft_teams"],github:["github","gh"],google:["google","drive","google-drive","docs"],turnkey:["turnkey","agent-wallet","agent_wallet","wallet"],x:["x","twitter"],mcp:["mcp","openpond-mcp"]};function BG(e){return`@${e.token}`}function S5(e){return`@${_5(e)}`}function x5(e){const t=new Map;for(const n of e){if(!n.connected||n.statusSource!=="integration_connection")continue;const a=t.get(n.providerFamily)??[];a.push(n),t.set(n.providerFamily,a)}return Array.from(t.entries()).map(([n,a])=>{const s=a[0],r=Do(a.flatMap(f=>f.capabilities.map(S=>S.id))),i=Do(a.flatMap(f=>f.capabilityLabels)),c=Do(a.flatMap(f=>f.connections.map(S=>S.id).filter(R5))),l=Do(a.map(f=>f.id)),u=Do(a.map(f=>f.setupSurface)),p=I5(n);return{provider:n,label:s.providerLabel,detail:i.length>0?i.slice(0,4).join(", "):s.description,token:p,tokens:w5(a),ref:{kind:"integration",provider:n,appIds:l,setupSurfaces:u,...c.length>0?{connectionIds:c}:{},...r.length>0?{capabilities:r}:{}}}})}function FG(e,t){const n=Un(t);return e.filter(a=>n?a.tokens.some(s=>s.includes(n)):!0).slice(0,8)}function k5(e,t){const n=C5(e);if(n.length===0)return[];const a=new Map;for(const s of n){const r=t.find(i=>i.tokens.includes(s));r&&a.set(r.provider,r)}return Array.from(a.values())}function VG(e,t){if(t.length===0)return[];const n=[];for(const a of e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)){const s=a[1]??"",r=Un(s);if(!r)continue;const i=t.find(f=>f.tokens.includes(r));if(!i)continue;const l=(a[0]??"").indexOf("@");if(l<0||typeof a.index!="number")continue;const u=a.index+l,p=`@${s}`;n.push({detail:i.detail,displayText:S5(i),end:u+p.length,label:i.label,provider:i.provider,start:u,text:p})}return n}function w5(e){return Do(e.flatMap(t=>[...c1[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map(Un).filter(Boolean))}function I5(e){return Un(c1[e][0]??e)}function _5(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function C5(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Un(t[1]??"")).filter(Boolean)}function Do(e){return Array.from(new Set(e))}function R5(e){return typeof e=="string"&&e.length>0}function P5({bootstrap:e,connectedAppRows:t,mentionableSandboxApps:n,runtimeIndexes:a,selectedApp:s,selectedCloudProject:r,selectedProject:i,selectedSession:c,selectedSessionId:l}){const u=h.useMemo(()=>{const w=new Map;for(const C of e?.cloudProjects??[]){const P=w.get(C.teamId)??[];P.push(C.id),w.set(C.teamId,P)}return w},[e?.cloudProjects]),f=!!(c||s||i||r)?[]:n,S=h.useMemo(()=>x5(t),[t]),b=h.useMemo(()=>_F(a,l),[a,l]);return{chatMentionApps:f,cloudProjectIdsByTeam:u,connectedAppMentions:S,pendingApproval:b}}function T5({connection:e,setBootstrap:t,setCodexPermissionMode:n,setCodexReasoningEffort:a,setError:s}){const r=h.useCallback(c=>{if(!e){s("Connect to OpenPond before saving preferences.");return}Z.savePreferences(e,{codexPermissionMode:c}).then(l=>{n(l.preferences.codexPermissionMode),a(l.preferences.codexReasoningEffort),t(u=>u&&{...u,preferences:l.preferences})}).catch(l=>{s(l instanceof Error?l.message:String(l))})},[e,t,n,a,s]),i=h.useCallback(c=>{if(!e){s("Connect to OpenPond before saving preferences.");return}Z.savePreferences(e,{codexReasoningEffort:c}).then(l=>{n(l.preferences.codexPermissionMode),a(l.preferences.codexReasoningEffort),t(u=>u&&{...u,preferences:l.preferences})}).catch(l=>{s(l instanceof Error?l.message:String(l))})},[e,t,n,a,s]);return{changeCodexPermissionMode:r,changeCodexReasoningEffort:i}}const A5=6e4;function Ng(e,t){if(!e)return t;const n=j5(e.updatedAt,t.updatedAt)?{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,status:e.status,updatedAt:e.updatedAt}:t;return d1(e,n)?e:n}function E5(e,t){const n=Ng(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&d1(e,a)?e:a}function cc(e,t){let n=!1,a=!1;const s=e.map(r=>{if(r.id!==t.id)return r;n=!0;const i=Ng(r,t);return i!==r&&(a=!0),i});return n?a?s:e:[t,...e]}function Cu(e,t){let n=!1,a=!1;const s=e.map(r=>{if(r.id!==t.id)return r;n=!0;const i=E5(r,t);return i!==r&&(a=!0),i});return n?a?s:e:[t,...e]}function Tf(e,t,n,a=Date.now()){const s=new Map(e.map(r=>[r.id,r]));return t.map(r=>{const i=s.get(r.id);if(i&&n){const c=O5(i,r,n,a);if(c)return c}return Ng(i,r)})}function fy(e,t,n,a=Date.now()){const s=new Map(e.map(u=>[u.id,u])),r=new Map(Tf(e,t,n,a).map(u=>[u.id,u])),i=new Set(s.keys()),c=t.filter(u=>!i.has(u.id)).map(u=>r.get(u.id)??u),l=e.map(u=>{const p=r.get(u.id);return p||(l1(u,t)?u:null)}).filter(u=>!!u);return[...c,...l]}function l1(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=M5(t);return a===null||n>=a}function hy(e,t,n,a=Date.now()){const s=new Map(t.map(r=>[r.id,r]));for(const r of n){const i=s.get(r.id);i&&(u1(i,r)||(e[r.id]=a))}}function j5(e,t){const n=Date.parse(e),a=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(a)&&n>a}function d1(e,t){return JSON.stringify(e)===JSON.stringify(t)}function M5(e){let t=null;for(const n of e){const a=Date.parse(n.updatedAt);Number.isFinite(a)&&(t=t===null?a:Math.max(t,a))}return t}function O5(e,t,n,a){const s=n[t.id];return s===void 0?null:a-s>A5||u1(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function u1(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const m1=800,$5=5e3,gy=5e4,N5=16,D5=3e4,Xn=new Map;function L5(e,t){return Xn.get(f1(e,t))?.payload??null}async function p1(e,t,n={}){const a=f1(e,t),s=Xn.get(a),r=n.limit??m1,i=n.tail??!0;if(s?.promise)return s.promise;if(!n.force&&i&&s?.payload&&Date.now()-s.fetchedAt<=D5)return vy(a,s),s.payload;const c=!!(n.force&&i&&s?.payload),l=c?s?.payload?.events.at(-1)?.id:void 0,u=Z.codexHistoryThreadIncremental(e,t,{afterEventId:l,limit:r,revision:c?s?.revision:void 0,tail:i}).then(p=>{const f=Xn.get(a)?.payload??s?.payload;if(p.unchanged){if(!f)throw new Error("Codex history revision matched without a cached thread.");return Xn.set(a,{fetchedAt:Date.now(),payload:f,revision:p.revision}),vy(a,Xn.get(a)),f}const S={session:p.session,events:p.events},b=i&&f&&!p.reset?{...S,events:z5(f.events,S.events)}:S;return Xn.set(a,{fetchedAt:Date.now(),payload:b,revision:p.revision}),by(),b}).catch(p=>{throw Xn.get(a)?.promise===u&&Xn.delete(a),p});return Xn.set(a,{fetchedAt:s?.fetchedAt??0,payload:s?.payload,promise:u,revision:s?.revision}),by(),u}function f1(e,t){return`${e.serverUrl}
110
+ `)}bz();function yz(e){const t=Pd(e.parameters),n=Pd(t.properties),a=Mw(t.required),s=Object.fromEntries(a.map(r=>[r,sd(n[r])]));return`${e.name}(${JSON.stringify(s)})`}function sd(e){const t=Pd(e),n=of(t.anyOf);if(n.length)return n.map(sd).join("|");const a=of(t.enum);if(a.length)return a.join("|");if(t.type==="array")return[sd(t.items)];if(t.type==="object"){const s=Pd(t.properties),r=Mw(t.required);return Object.fromEntries(r.map(i=>[i,sd(s[i])]))}return typeof t.type=="string"?t.type:"unknown"}function Pd(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function of(e){return Array.isArray(e)?e:[]}function Mw(e){return of(e).filter(t=>typeof t=="string")}const Td=k(mz),Sz=rt("kind",[d({kind:x("model"),turn:m().int().nonnegative(),content:o().max(1e5)}),d({kind:x("tool_call"),turn:m().int().nonnegative(),callId:o().trim().min(1).max(240),name:Td,arguments:ve(o(),ke())}),d({kind:x("tool_result"),turn:m().int().nonnegative(),callId:o().trim().min(1).max(240),name:Td,ok:j(),result:ke(),rows:m().int().nonnegative(),bytes:m().int().nonnegative(),durationMs:m().int().nonnegative(),error:o().trim().min(1).max(2e4).nullable()}),d({kind:x("final"),turn:m().int().nonnegative(),content:o().max(1e5)})]),xz=d({schemaVersion:x(tg),id:o().trim().min(1).max(240),worldId:o().trim().min(1).max(240),taskId:o().trim().min(1).max(240),toolContractHash:x(Yc),modelRef:d({providerId:o().trim().min(1),modelId:o().trim().min(1)}).nullable(),status:k(["completed","budget_exhausted","cancelled","infrastructure_failure"]),steps:v(Sz).max(1e3),startedAt:o().trim().min(1),completedAt:o().trim().min(1),infrastructureError:o().trim().min(1).max(2e4).nullable(),metadata:ve(o(),ke()).default({})}),kz=d({schemaVersion:x(tg),trajectoryId:o().trim().min(1).max(240),outcome:k(["correct","incorrect","parse_failure","budget_exhausted","tool_schema_violation","infrastructure_failure","cancelled"]),reward:m().min(0).max(1.15).nullable(),rewardEligible:j(),exactAnswer:j(),components:d({exactAnswer:m().min(0).max(1),efficiency:m().min(0).max(.1),conciseOutput:m().min(0).max(.05)}),metrics:d({toolCalls:m().int().nonnegative(),rowsRead:m().int().nonnegative(),bytesRead:m().int().nonnegative(),consecutiveRetrievalCalls:m().int().nonnegative(),wallTimeMs:m().int().nonnegative(),parseFailures:m().int().nonnegative(),budgetExhausted:j()}),parsedAnswer:ke().nullable(),feedback:v(o().trim().min(1).max(5e3)).max(100)}),wz=d({id:o().trim().min(1).max(240),type:x("function"),function:d({name:Td,arguments:o().max(2e4)})}),Ow=d({role:k(["system","user","assistant","tool"]),content:o().max(2e5).nullable(),tool_call_id:o().trim().min(1).max(240).optional(),tool_calls:v(wz).max(4).optional()});d({schemaVersion:x(tg),id:o().trim().min(1).max(240),taskId:o().trim().min(1).max(240),worldId:o().trim().min(1).max(240),trajectoryId:o().trim().min(1).max(240),toolContractHash:x(Yc),approval:d({status:x("approved"),approvedBy:o().trim().min(1).max(240),approvedAt:o().trim().min(1)}),messages:v(Ow).min(3).max(1e3)});const Iz=d({tasksetTaskId:o().trim().min(1).max(240),environmentTaskId:o().trim().min(1).max(240),family:k(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]),prompt:o().trim().min(1).max(1e5),finalAnswer:o().trim().min(1).max(2e5),trajectoryId:o().trim().min(1).max(240),trajectoryHash:o().trim().min(8).max(256),toolNames:v(Td).min(1).max(100),toolCallCount:m().int().positive(),messageCount:m().int().min(3),reward:m().min(0).max(1.15),messages:v(Ow).min(3).max(1e3)}),_z=d({status:x("approved"),approvedBy:o().trim().min(1).max(240),approvedAt:o().trim().min(1),previewHash:o().trim().min(8).max(256),trajectoryCount:m().int().positive()});d({schemaVersion:x("openpond.crossSystemExpertBootstrapPreview.v1"),tasksetId:o().trim().min(1).max(240),tasksetHash:o().trim().min(8).max(256),tasksetRevision:m().int().positive(),previewHash:o().trim().min(8).max(256),toolContractHash:x(Yc),status:k(["ready_for_review","approved"]),approval:_z.nullable(),tasks:v(Iz).min(1).max(100)});function Cz(e){const t=cf(e);let n=2166136261,a=2654435769;for(let s=0;s<t.length;s+=1){const r=t.charCodeAt(s);n=Math.imul(n^r,16777619),a=Math.imul(a^r,2246822507)}return`${Ew}:${vb(n)}${vb(a)}`}function cf(e){return Array.isArray(e)?`[${e.map(cf).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${cf(n)}`).join(",")}}`:JSON.stringify(e)}function vb(e){return(e>>>0).toString(16).padStart(8,"0")}const Rz=d({schemaVersion:x("openpond.singleTurnPolicyTrajectory.v1"),id:ge,taskId:ge,status:k(["completed","infrastructure_failure"]),promptHash:tt,responseText:o().max(2e6),infrastructureError:o().trim().min(1).max(1e4).nullable(),startedAt:It,completedAt:It,metadata:Qc}),Pz=d({schemaVersion:x("openpond.ppoTrajectory.v1"),id:ge,taskId:ge,policyModelId:ge,referenceModelId:ge,valueModelId:ge,steps:v(d({index:m().int().nonnegative(),observationHash:tt,actionTokenIds:v(m().int().nonnegative()).min(1),terminated:j(),truncated:j(),reward:m(),policyLogProbability:m(),referenceLogProbability:m(),valuePrediction:m(),return:m(),advantage:m(),mask:m().min(0).max(1)})).min(1).max(1e5),createdAt:It}),Tz=d({schemaVersion:x("openpond.exactAnswerVerifierResult.v1"),outcome:k(["correct","incorrect","parse_failure","infrastructure_failure"]),graderSetHash:tt,score:m().min(0).max(1).nullable(),passed:j(),rewardEligible:j(),expectedAnswerHash:tt,extractedAnswer:o().max(2e4).nullable(),feedback:v(o().trim().min(1).max(2e4)).max(1e3)}),Az=d({schemaVersion:x("openpond.rolloutTrajectoryReceipt.v1"),id:ge,jobId:ge,planId:ge,tasksetId:ge,tasksetHash:tt,taskId:ge,split:x("train"),correlationId:ge,provider:ge,providerTrace:d({invocationId:ge,experimentId:ge,rolloutId:ge,runId:ge,rowId:ge}),optimizerMethod:k(["grpo","ppo"]).default("grpo"),evidenceLevels:d({requested:k(["trajectory","aggregate","provider_reported"]),observed:k(["trajectory","aggregate","provider_reported"]),providerReported:k(["trajectory","aggregate","provider_reported"])}).default({requested:"trajectory",observed:"trajectory",providerReported:"provider_reported"}),budgetUsage:d({rollouts:m().int().nonnegative(),environmentExecutions:m().int().nonnegative(),inputTokens:m().int().nonnegative(),outputTokens:m().int().nonnegative(),optimizerSteps:m().int().nonnegative(),costUsd:m().nonnegative()}).default({rollouts:0,environmentExecutions:0,inputTokens:0,outputTokens:0,optimizerSteps:0,costUsd:0}),environment:d({id:ge,version:o().trim().min(1).max(256),worldId:ge,worldHash:tt,toolContractHash:tt}),policy:d({modelId:ge,checkpointId:ge.nullable(),completionParametersHash:tt}),status:k(["received","running","succeeded","failed"]),failureClass:k(["policy_failure","parse_failure","tool_schema_violation","budget_exhausted","cancelled","environment_failure","infrastructure_failure"]).nullable(),reward:d({eligible:j(),raw:m().min(0).max(1.15).nullable(),normalized:m().min(0).max(1).nullable(),components:ve(o(),m())}),trajectory:dt([xz,Rz,Pz]).nullable(),verifier:dt([kz,Tz]).nullable(),providerStatus:ve(o(),ke()).default({}),receivedAt:It,startedAt:It.nullable(),completedAt:It.nullable(),updatedAt:It}),tG="dataset-exact-answer",nG="dataset-exact-answer-v1",aG="no-tools-v1",yr=k(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),bu=k(["lora","full"]),to=k(["openpond_managed"]),Ez=ht(()=>({schemaVersion:x("openpond.sftRecipe.v1"),method:x("sft"),parameterization:x("lora"),baseModel:d({id:ge,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:tt}),dataset:d({trainSplit:x("train"),validationSplit:k(["validation","frozen_eval"]),completionOnly:j(),maxSequenceLength:m().int().positive().max(32768),maxExamples:m().int().positive().max(1e5).default(1e3),selectionStrategy:x("stable_hash_top_n").default("stable_hash_top_n"),selectionSeed:m().int().default(17)}),lora:d({rank:m().int().positive().max(256),alpha:m().positive().max(1024),dropout:m().min(0).max(1),targetModules:v(ge).min(1).max(100)}),optimizer:d({learningRate:m().positive(),epochs:m().positive().max(100),maxSteps:m().int().positive().max(1e6),batchSize:m().int().positive().max(1e4),gradientAccumulationSteps:m().int().positive().max(1e4),seed:m().int()}),resourceLimits:d({cpuThreads:m().int().positive().max(256),memoryBytes:m().int().positive(),wallTimeMs:m().int().positive()})}));ht(()=>({id:ge,input:ve(o(),ke()),expectedOutput:ve(o(),ke()),tags:v(ge).max(100).default([])}));ht(()=>({id:ge,prompt:o().min(1).max(5e5),chosen:o().min(1).max(5e5),rejected:o().min(1).max(5e5),sourceRefs:v(ge).min(1).max(1e4)}));ht(()=>({id:ge,input:ve(o(),ke()),tags:v(ge).max(100).default([])}));ht(()=>({schemaVersion:x("openpond.rewardModelRecipe.v1"),method:x("reward_model"),parameterization:x("lora_with_scalar_head"),runScope:k(["synthetic_smoke","human_preference"]),baseModel:d({id:ge,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),processorRevision:o().trim().min(1).max(256),chatTemplateHash:tt}).strict(),tasksetRelease:re,preferenceDatasetRelease:re,processorRelease:re,input:d({kind:x("structured_text"),serialization:k(["scenario_input_and_candidate_json_v1","visible_agent_trajectory_v1"]),maxCharacters:m().int().positive().max(5e5)}).strict().default({kind:"structured_text",serialization:"scenario_input_and_candidate_json_v1",maxCharacters:32e3}),lora:d({rank:m().int().positive().max(256),alpha:m().positive().max(1024),dropout:m().min(0).max(1),targetModules:v(ge).min(1).max(100)}).strict(),heads:d({scalar:x("pooled_hidden_state_linear"),bucket:k(["none","three_class"]).default("three_class")}).strict(),loss:d({ranking:x("bradley_terry"),rankingWeight:m().positive(),bucketWeight:m().nonnegative(),tieWeight:m().nonnegative()}).strict(),optimizer:d({learningRate:m().positive(),maxSteps:m().int().positive().max(1e5),batchSize:m().int().positive().max(1e4),gradientAccumulationSteps:m().int().positive().max(1e4),seed:m().int(),checkpointEverySteps:m().int().positive().max(1e5)}).strict(),resourceLimits:d({wallTimeMs:m().int().positive().max(1440*60*1e3),maxExamples:m().int().positive().max(1e5),maxInputCharacters:m().int().positive().max(5e5).default(32e3),maxImagePixels:m().int().positive().max(1e8).optional(),maximumSpendUsd:m().nonnegative().max(1e5)}).strict()})).superRefine((e,t)=>{e.runScope==="synthetic_smoke"&&(e.optimizer.maxSteps>100||e.resourceLimits.maximumSpendUsd>10)&&t.addIssue({code:"custom",path:["resourceLimits"],message:"Synthetic-smoke Reward Model runs are limited to 100 steps and USD 10."})});const jz=ht(()=>({schemaVersion:x("openpond.rftRecipe.v1"),method:x("grpo"),parameterization:x("lora"),baseModel:d({id:ge,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:tt}),dataset:d({trainSplit:x("train"),validationSplit:k(["validation","frozen_eval"]),maxPromptTokens:m().int().positive().max(32768),maxExamples:m().int().positive().max(1e5).default(1e3),selectionStrategy:k(["stable_hash_top_n","rft_easy_curriculum_v1"]).default("stable_hash_top_n")}),lora:d({rank:m().int().positive().max(256)}),rollout:d({groupSize:m().int().min(2).max(64),concurrency:m().int().positive().max(32),maxTurns:m().int().positive().max(100),maxOutputTokens:m().int().positive().max(8192),temperature:m().min(0).max(2),topP:m().positive().max(1),seed:m().int()}),optimizer:d({learningRate:m().positive(),maxSteps:m().int().positive().max(1e5),clipRange:m().positive().max(1).default(.2),iterations:m().int().min(2).max(16).default(2),microbatchSize:m().int().positive().max(64).default(1),gradientAccumulationSteps:m().int().positive().max(64).default(1),advantageEpsilon:m().positive().max(.01).default(1e-8),adamw:cw}),loss:d({method:_w.default("grpo"),klBeta:m().min(0).nullable().default(null)}).default({method:"grpo",klBeta:null}),reward:d({graderId:ge,graderHash:tt,environmentId:ge,environmentVersion:o().trim().min(1).max(256),toolContractHash:tt,learnedPreference:Rw.nullable().optional()}),resourceLimits:d({wallTimeMs:m().int().positive().max(1440*60*1e3),maxGpuSeconds:m().int().positive().max(10800).optional(),maxRollouts:m().int().positive().max(1e5),maxPayloadBytes:m().int().positive().max(10*1024*1024)}),policyOptimization:Pw.nullable().default(null),continuation:d({schemaVersion:x("openpond.crossJobContinuationRequest.v1"),parentArtifact:re,sourceArtifact:d({jobId:ge,artifactId:ge,checkpointId:ge,contentHash:tt}).strict(),optimizerMode:k(["continue","reset"])}).strict().optional()})),Mz=ht(()=>({schemaVersion:x("openpond.dpoRecipe.v1"),method:x("dpo"),parameterization:x("lora"),policyModel:Ac,referenceModel:Ac,dataset:d({trainSplit:x("train"),validationSplit:k(["validation","frozen_eval"]),maxPairs:m().int().positive().max(1e5),maxPromptTokens:m().int().positive().max(32768),maxCompletionTokens:m().int().positive().max(32768),selectionStrategy:x("stable_hash_top_n"),selectionSeed:m().int()}),lora:d({rank:m().int().positive().max(256),alpha:m().positive().max(1024),dropout:m().min(0).max(1),targetModules:v(ge).min(1).max(100)}),loss:d({variant:x("sigmoid"),beta:m().positive().max(10),labelSmoothing:m().min(0).max(.5).default(0)}),optimizer:d({learningRate:m().positive(),epochs:m().positive().max(100),maxSteps:m().int().positive().max(1e6),batchSize:m().int().positive().max(1e4),gradientAccumulationSteps:m().int().positive().max(1e4),seed:m().int()}),referenceLogprobs:d({cacheSchemaVersion:x("openpond.dpoReferenceLogprobs.v1"),cacheKey:tt,invalidationHash:tt}),resourceLimits:d({cpuThreads:m().int().positive().max(256),memoryBytes:m().int().positive(),wallTimeMs:m().int().positive()})})),Oz=ht(()=>({schemaVersion:x("openpond.ppoRecipe.v1"),method:x("ppo"),parameterization:x("lora"),policyOptimization:Pw.extend({optimizer:Cw}),lora:d({rank:m().int().positive().max(256),alpha:m().positive().max(1024),dropout:m().min(0).max(1),targetModules:v(ge).min(1).max(100)}),valueHead:d({initialization:x("policy_hidden_state_linear"),optimizerLearningRate:m().positive(),artifactName:x("value_head.safetensors")}),policyLearningRate:m().positive(),resume:d({checkpointId:ge.nullable(),policyHash:tt,referenceHash:tt,valueModelHash:tt,optimizerStateHash:tt.nullable()}),resourceLimits:d({cpuThreads:m().int().positive().max(256),memoryBytes:m().int().positive(),wallTimeMs:m().int().positive()})})),$z=ht(()=>({schemaVersion:x("openpond.unsupportedRecipe.v1"),method:yr.exclude(["sft","dpo","grpo","ppo"]),parameterization:bu,unsupportedReason:o().trim().min(1).max(5e3)})),Nz=dt([Ez,Mz,jz,Oz,$z]),Dz=ht(()=>({schemaVersion:x("openpond.trainingDestinationCapabilities.v1"),destinationId:to,available:j(),methods:v(yr),parameterizations:v(bu),modelAllowlist:v(ge).default([]),maxDatasetBytes:m().int().nonnegative().nullable(),environmentPlacements:v(k(["none","local","remote","colocated","provider_native"])),nonProduction:j(),unavailableReason:o().trim().min(1).max(5e3).nullable(),checkedAt:It})),Lz=ht(()=>({destinationId:to,available:j(),methods:v(yr),parameterizations:v(bu),nonProduction:j(),unavailableReason:o().trim().min(1).max(5e3).nullable()})),zz=ht(()=>({schemaVersion:x("openpond.baseModelCandidate.v1"),selectionKey:ge,label:o().trim().min(1).max(500),sourceLabel:o().trim().min(1).max(500),preference:Jc,available:j(),nonProduction:j(),unavailableReason:o().trim().min(1).max(5e3).nullable(),methods:v(yr),executionOptions:v(Lz).min(1)})),Hz=ht(()=>({code:ge,severity:k(["warning","error"]),path:o().trim().max(2e3).nullable(),message:o().trim().min(1).max(5e3)})),Uz=ht(()=>({schemaVersion:x("openpond.trainingCompatibility.v1"),compatible:j(),destinationId:to,tasksetId:ge,recipeMethod:yr,issues:v(Hz),checkedAt:It})),qz=dt([Bk,k(["destination_unavailable","destination_method_unsupported","destination_model_unsupported","destination_parameterization_unsupported","experimental_destination"])]);ht(()=>({method:yr,state:k(["recommended","compatible","needs_dataset_work","destination_unavailable","experimental_destination"]),reasonCodes:v(qz).default([]),reasons:v(o().trim().min(1).max(5e3)).default([]),destinationId:to.nullable().default(null)}));k(["small","standard","custom","small_experiment"]);const Bz=uk,$w=ht(()=>({schemaVersion:x("openpond.trainingPlan.v1"),id:ge,modelId:ge,tasksetId:ge,tasksetHash:tt,comparisonSeriesEntry:pi.nullable().optional(),evaluationTasksetRef:Kt.nullable().optional(),harnessRelease:re.nullable().optional(),modelImprovementQualification:re.nullable().optional(),destinationId:to,recipe:Nz,environmentPlacement:k(["none","local","remote","colocated","provider_native"]),compatibility:Uz,dataPolicy:d({exportApproved:j(),approvedSourceIds:v(ge),retentionDays:m().int().nonnegative().nullable(),region:o().trim().min(1).max(200).nullable()}),estimatedCostUsd:m().nonnegative().nullable(),createdAt:It,contentHash:tt})),Fz=ht(()=>({path:o().trim().min(1).max(2e3),sha256:tt,sizeBytes:m().int().nonnegative(),role:k(["manifest","task_data","grader","environment","recipe","policy","provenance"])})),ng=ht(()=>({schemaVersion:x("openpond.trainingBundle.v1"),id:ge,planId:ge,tasksetId:ge,tasksetHash:tt,recipeHash:tt,files:v(Fz).min(1).max(1e6),totalSizeBytes:m().int().nonnegative(),sourceIds:v(ge),excludedSourceIds:v(ge),containsRawChats:x(!1),containsSecrets:x(!1),containsHiddenGraderAssets:x(!1),createdAt:It,contentHash:tt}));ht(()=>({schemaVersion:x("openpond.trainingBundleExport.v1"),manifest:ng,files:v(d({path:o().trim().min(1).max(2e3),sha256:tt,sizeBytes:m().int().nonnegative(),encoding:x("base64"),content:o()})).min(1),contentHash:tt}));ht(()=>({schemaVersion:x("openpond.trainingPreparedStart.v1"),plan:$w,bundle:ng,approvalActor:ge.nullable(),preparedAt:It}));ht(()=>({schemaVersion:x("openpond.trainingApproval.v1"),evaluationTasksetRef:Kt.nullable().optional(),id:ge,planId:ge,bundleHash:tt,harnessRelease:re.nullable().optional(),modelImprovementQualification:re.nullable().optional(),destinationId:to,modelId:ge,method:yr,parameterization:bu,maximumCostUsd:m().nonnegative().nullable(),approvedBy:ge,approvedAt:It}));ht(()=>({schemaVersion:x("openpond.trainingJobSourceSnapshot.v1"),evaluationTasksetRef:Kt.nullable().optional(),modelProjectId:ge,sourceProjectRevision:m().int().positive(),profileId:ge,taskset:d({id:ge,revision:m().int().positive(),contentHash:tt}).strict(),tasksetRelease:re,harnessRelease:re,baseModel:Jc,method:yr})).strict();const Vz=k(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),Nw=ht(()=>({schemaVersion:x("openpond.trainingJob.v1"),id:ge,planId:ge,bundleHash:tt,approvalId:ge,destinationId:to,status:Vz,nonProduction:j(),workerPid:m().int().positive().nullable(),startedAt:It.nullable(),completedAt:It.nullable(),error:o().trim().min(1).max(2e4).nullable(),createdAt:It,updatedAt:It,metadata:Qc})),Kz=ht(()=>({schemaVersion:x("openpond.trainingJobEvent.v1"),id:ge,jobId:ge,sequence:m().int().nonnegative(),type:k(["queued","start","progress","metric","checkpoint","cancel","complete","failure","reconcile"]),timestamp:It,payload:Qc})),Wz=ht(()=>({schemaVersion:x("openpond.sftStepMetric.v1"),step:m().int().nonnegative(),maxSteps:m().int().positive(),timestamp:It,epoch:m().nonnegative().nullable(),loss:m().nullable(),learningRate:m().nonnegative().nullable(),gradientNorm:m().nonnegative().nullable(),entropy:m().nonnegative().nullable(),meanTokenAccuracy:m().min(0).max(1).nullable(),preferenceAccuracy:m().min(0).max(1).nullable().default(null),preferenceMargin:m().nullable().default(null),chosenReward:m().nullable().default(null),rejectedReward:m().nullable().default(null),chosenLogProbability:m().nullable().default(null),rejectedLogProbability:m().nullable().default(null),reward:m().nullable().default(null),policyLoss:m().nullable().default(null),advantageLoss:m().nullable().default(null),inputTokensSeen:m().int().nonnegative().nullable(),memoryBytes:m().int().nonnegative().nullable(),elapsedSeconds:m().nonnegative().nullable()})),Gz=ht(()=>({schemaVersion:x("openpond.policyOptimizationMetric.v1"),method:k(["grpo","ppo"]),step:m().int().nonnegative(),timestamp:It,learningRate:m().nonnegative().nullable().default(null),policyLoss:m().nullable(),valueLoss:m().nullable(),gradientNorm:m().nonnegative().nullable().default(null),meanReward:m().nullable(),meanReturn:m().nullable(),kl:m().nullable(),behaviorPolicyKlPreUpdate:m().nonnegative().nullable().default(null),entropy:m().nullable(),policyClipFraction:m().min(0).max(1).nullable(),behaviorPolicyClipFractionPreUpdate:m().min(0).max(1).nullable().default(null),valueClipFraction:m().min(0).max(1).nullable(),explainedVariance:m().nullable(),rolloutLearnerLag:m().int().nonnegative().nullable(),inputTokens:m().int().nonnegative(),outputTokens:m().int().nonnegative(),environmentExecutions:m().int().nonnegative(),trajectoryCount:m().int().nonnegative().nullable().default(null),costUsd:m().nonnegative().nullable()})),Zz=ht(()=>({schemaVersion:x("openpond.managedTrainingRunEvidence.v2"),provider:ge,providerRunId:ge,state:ge,progress:d({targetOptimizerSteps:m().int().nonnegative(),committedOptimizerSteps:m().int().nonnegative(),skippedOptimizerSteps:m().int().nonnegative()}),reward:d({finalMean:m().nullable(),variance:m().nonnegative().nullable(),minimum:m().nullable(),maximum:m().nullable(),distinctValueCount:m().int().nonnegative(),noSignalGroupCount:m().int().nonnegative(),trajectoryCount:m().int().nonnegative(),eligibleTrajectoryCount:m().int().nonnegative()}),usage:d({inputTokens:m().int().nonnegative(),outputTokens:m().int().nonnegative(),environmentExecutions:m().int().nonnegative()}),resource:d({provider:ge,gpuType:o().trim().min(1).max(300).nullable(),gpuCount:m().int().nonnegative().nullable(),hourlyCostUsd:m().nonnegative().nullable(),durationSeconds:m().nonnegative().nullable(),gpuSeconds:m().nonnegative().nullable()}),cost:d({totalUsd:m().nonnegative().nullable()}),checkpoint:d({id:ge,policyVersion:m().int().nonnegative(),sha256:tt.nullable(),sizeBytes:m().int().nonnegative().nullable()}).nullable(),movement:d({adapterDeltaNorm:m().nonnegative().nullable()}),evaluations:v(d({reference:d({id:ge,contentHash:tt}).nullable().optional(),kind:k(["baseline","candidate"]),policyVersion:m().int().nonnegative(),taskCount:m().int().nonnegative().nullable().optional(),targetTaskCount:m().int().nonnegative().nullable().optional(),score:m().nullable(),threshold:m().nullable(),passed:j().nullable()})),canonicalPublication:d({state:ge.nullable(),artifactId:ge.nullable()}),syncedAt:It})),bb=ht(()=>({count:m().int().nonnegative(),scoredCount:m().int().nonnegative(),meanScore:m().min(0).max(1).nullable(),passedCount:m().int().nonnegative(),passRate:m().min(0).max(1).nullable()})),yb=ht(()=>({status:k(["scored","unavailable"]),score:m().min(0).max(1).nullable(),passed:j(),rewardEligible:j(),failureClass:k(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:v(o().trim().min(1).max(2e4)).max(1e3),components:v(d({graderId:ge,score:m().min(0).max(1).nullable(),passed:j(),feedback:o().trim().max(2e4).nullable()})).max(1e3)})),Jz=ht(()=>({taskId:ge,input:ve(o(),ke()),baseOutput:ve(o(),ke()).nullable(),trainedOutput:ve(o(),ke()).nullable(),baseGrade:yb.nullable(),trainedGrade:yb.nullable()})),Qz=ht(()=>({schemaVersion:x("openpond.trainingEvaluationSummary.v1"),jobId:ge,tasksetId:ge,base:bb,trained:bb,meanScoreDelta:m().min(-1).max(1).nullable(),examples:v(Jz).max(1e6)}));ht(()=>({schemaVersion:x("openpond.trainingRunDetail.v1"),job:Nw,events:v(Kz),stepMetrics:v(Wz),policyMetrics:v(Gz).default([]),managedEvidence:Zz.nullable().default(null),evaluation:Qz.nullable(),generatedAt:It}));const Yz=ht(()=>({schemaVersion:x("openpond.trainingArtifact.v1"),id:ge,jobId:ge,kind:k(["adapter","checkpoint","metrics","log","manifest","evaluation"]),path:o().trim().min(1).max(4e3),sha256:tt,sizeBytes:m().int().nonnegative(),baseModelId:ge.nullable(),baseModelRevision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:tt.nullable(),nonProduction:j(),createdAt:It,metadata:Qc})),Xz=ht(()=>({schemaVersion:x("openpond.modelArtifactLineage.v1"),id:ge,modelId:ge,artifactId:ge,jobId:ge,tasksetId:ge,tasksetHash:tt,graderHash:tt,planHash:tt,bundleHash:tt,recipeHash:tt,workerVersion:o().trim().min(1).max(256),trainerVersion:o().trim().min(1).max(256),importedAt:It,frozenEvaluationArtifactId:ge.nullable(),promotable:j(),pinned:j().default(!1),status:k(["imported","rejected"]).default("imported"),rejectedAt:It.nullable().default(null),rejectionReason:o().trim().min(1).max(5e3).nullable().default(null),chatConfiguration:Tw.default(dz),managedServing:uz.nullable().default(null)})),eH=k(["chat_manual","agent","extension","authoring_optimizer"]),tH=ht(()=>({schemaVersion:x("openpond.modelBinding.v1"),id:ge,profileId:ge,role:eH,roleTargetId:ge,modelArtifactLineageId:ge,tasksetId:ge,evaluationArtifactId:ge.nullable(),status:k(["active","rolled_back"]),priorBindingId:ge.nullable(),rollbackTargetBindingId:ge.nullable(),promotedBy:ge,promotedAt:It,rolledBackAt:It.nullable(),metadata:Qc}));ht(()=>({schemaVersion:x("openpond.trainingActivity.v1"),profileId:ge,active:j(),activeCounts:d({jobs:m().int().nonnegative(),creations:m().int().nonnegative(),minerRuns:m().int().nonnegative(),datasetImports:m().int().nonnegative()}),revision:tt,generatedAt:It}));ht(()=>({schemaVersion:x("openpond.tasksetOperationalState.v1"),tasksetId:ge,attempts:v(DD),artifacts:v(LD),grades:v(HD),evaluationResults:v(P2).default([]),generatedAt:It}));const nH=ht(()=>({schemaVersion:x("openpond.trainingState.v1"),profileId:ge,sources:v(Pk),creations:v(lw),tasksetDrafts:v(Ka).default([]),tasksets:v(Tc),benchmarkRuns:v(Fm()).default([]),benchmarkComparisons:v(Fm()).default([]),datasetImports:v(sL).default([]),datasetArtifacts:v(Z2).default([]),graderAuditReports:v(UD),evaluationResults:v(Fm()).default([]),candidates:v(iw),minerConfig:hu,minerRuns:v(kD).default([]),modelProjects:v(Bz).default([]),modelVersions:v(zL).default([]),modelRuns:v(YL).default([]),comparisonSeries:v(EL).default([]),comparisonSeriesEntries:v(DL).default([]),modelCurrencySnapshots:v(nz).default([]),continualBenchIssueReviews:v(rz).default([]),continualLearningDailyBatches:v(sz).default([]),rewardModelVersions:v(HL).default([]),rewardModelRuns:v(qL).default([]),modelTasksets:v(Tc).default([]),plans:v($w),bundles:v(ng),jobs:v(Nw),artifacts:v(Yz),models:v(Xz),rolloutReceipts:v(Az).default([]),modelBindings:v(tH).default([]),destinations:v(Dz),baseModelCandidates:v(zz).default([]),activityRevision:tt.optional(),generatedAt:It})),ag=32e3,aH=k(["steer","message","followup","queued","result"]),sH=k(["pending","included","resolved","cancelled","rejected"]),sg=d({id:o().min(1),sequence:m().int().nonnegative(),sessionId:o().min(1),senderSessionId:o().min(1).nullable(),senderKind:k(["user","task","runtime","ponder"]),kind:aH,body:o().trim().min(1).max(ag),payload:ve(o(),ke()).default({}),idempotencyKey:o().min(1).max(200),replyTo:o().min(1).nullable(),expectedTurnId:o().min(1).nullable(),turnId:o().min(1).nullable(),requestIds:v(o()),state:sH,revision:m().int().positive(),createdAt:o(),updatedAt:o(),error:o().nullable()}).strict();d({expectedTurnId:o().trim().min(1),idempotencyKey:o().trim().min(1).max(200),prompt:o().trim().min(1).max(ag)}).strict();rt("action",[d({action:x("resume"),expectedRevision:m().int().positive()}).strict(),d({action:x("cancel"),expectedRevision:m().int().positive()}).strict(),d({action:x("edit"),expectedRevision:m().int().positive(),body:o().trim().min(1).max(ag)}).strict(),d({action:x("steer"),expectedRevision:m().int().positive(),expectedTurnId:o().trim().min(1)}).strict()]);const rH=d({id:o().min(1),sessionId:o().min(1),turnId:o().min(1),targetSessionId:o().min(1).nullable(),targetTurnId:o().min(1).nullable(),targetInputId:o().min(1).nullable().default(null),afterSequence:m().int().nonnegative(),deadline:o(),state:k(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:o(),updatedAt:o()}).strict();d({sessionId:o(),activeTurnId:o().nullable(),acceptingInput:j(),paused:j(),inputs:v(sg),waits:v(rH)});var Ad=Ye.shape.id,oH=d({schemaVersion:x("openpond.modelBatchReviewInspection.v1"),packageHash:o().regex(/^[a-f0-9]{64}$/),definition:au,binding:Ph,evidence:v(su).min(1).max(1e4),decisions:v(jh).min(1).max(1e4)}).strict(),sG=d({schemaVersion:x("openpond.modelBatchReviewRequest.v1"),operationId:Ad,modelId:Ad,expectedModelRevision:m().int().positive(),tasksetRef:Ye,rewardBindingRef:Ye.nullable(),definition:d({name:o().trim().min(1).max(500).optional(),instructions:o().trim().min(1).max(2e4).optional(),inputSchema:Tt.optional(),outputSchema:Tt.optional(),requiredOutputs:au.shape.requiredOutputs}).strict(),examples:v(d({evidence:Ye,input:Tt.optional(),expected:Tt.nullable().optional(),evaluatorContext:Tt.nullable().optional(),proposedTarget:Tt.nullable().optional()}).strict()).max(1e4)}).strict(),iH=d({schemaVersion:x("openpond.modelBatchReviewReceipt.v1"),operationId:Ad,modelId:Ad,source:Eh,evidence:v(su).min(1).max(1e4),proposals:v(Vx).max(1e4)}).strict();const cH={teamInvitations:e=>L(e,"/v1/team-invitations"),decideTeamInvitation:(e,t,n)=>L(e,`/v1/team-invitations/${t}`,{method:"POST",body:JSON.stringify({token:n})}),organizations:e=>L(e,"/v1/organizations"),createOrganization:(e,t)=>L(e,"/v1/organizations",{method:"POST",body:JSON.stringify(t)}),updateOrganization:(e,t,n)=>L(e,`/v1/organizations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),organizationMembers:(e,t)=>L(e,`/v1/organizations/${encodeURIComponent(t)}/members`),upsertOrganizationMember:(e,t,n)=>L(e,`/v1/organizations/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify(n)}),organizationMcpServer:(e,t)=>L(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`),generateOrganizationMcpServer:(e,t,n)=>L(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`,{method:"POST",body:JSON.stringify(n)}),setOrganizationMcpServerStatus:(e,t,n)=>L(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server/${n}`,{method:"POST"})},lH={taskInbox:(e,t)=>L(e,`/v1/sessions/${encodeURIComponent(t)}/inbox`),steerTurn:(e,t,n)=>L(e,`/v1/sessions/${encodeURIComponent(t)}/turns/steer`,{method:"POST",body:JSON.stringify(n)}),queueTaskInput:(e,t,n,a)=>L(e,`/v1/sessions/${encodeURIComponent(t)}/inbox`,{method:"POST",body:JSON.stringify({input:n,idempotencyKey:a})}),updateTaskInput:(e,t,n,a)=>L(e,`/v1/sessions/${encodeURIComponent(t)}/inbox/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)}),sendTurn:(e,t,n)=>L(e,`/v1/sessions/${t}/turns`,{method:"POST",body:JSON.stringify(n)}),runSessionCommand:(e,t,n)=>L(e,`/v1/sessions/${encodeURIComponent(t)}/commands`,{method:"POST",body:JSON.stringify(n)}),recordPreflightTurnFailure:(e,t,n)=>L(e,`/v1/sessions/${t}/preflight-turns/failure`,{method:"POST",body:JSON.stringify(n)}),listCreateImproveRuns:(e,t={})=>L(e,`/v1/create-improve-runs?${dH(t).toString()}`),getCreateImproveRun:(e,t)=>L(e,`/v1/create-improve-runs/${encodeURIComponent(t)}`),getCreateImproveCandidateDiff:(e,t,n)=>L(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/candidates/${encodeURIComponent(n)}/diff`),applyCreateImproveAction:(e,t,n)=>L(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/actions`,{method:"POST",body:JSON.stringify(n)}),interruptTurn:(e,t,n)=>L(e,`/v1/sessions/${t}/turns/interrupt`,{method:"POST",body:JSON.stringify({reason:n})}),compactSession:(e,t,n={reason:"manual"})=>L(e,`/v1/sessions/${t}/compact`,{method:"POST",body:JSON.stringify(n)}),workspaceTool:(e,t,n)=>L(e,`/v1/sessions/${t}/workspace-tools`,{method:"POST",body:JSON.stringify(n)}),ensureCloudWorkspaceReady:(e,t,n)=>L(e,`/v1/sessions/${encodeURIComponent(t)}/workspace/ensure-ready`,{method:"POST",body:JSON.stringify(n)})};function dH(e){const t=new URLSearchParams;return e.profileId&&t.set("profileId",e.profileId),e.conversationId&&t.set("conversationId",e.conversationId),e.targetKind&&t.set("targetKind",e.targetKind),e.targetId&&t.set("targetId",e.targetId),e.limit&&t.set("limit",String(e.limit)),t}const uH={sandboxFiles:(e,t,n={})=>{const a=new URLSearchParams({list:"1"});return n.path&&a.set("path",n.path),n.recursive!==void 0&&a.set("recursive",String(n.recursive)),n.maxEntries!==void 0&&a.set("maxEntries",String(n.maxEntries)),L(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${a.toString()}`)},sandboxUploadFile:(e,t,n)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/files`,{method:"POST",body:JSON.stringify(n)}),preserveSandboxSource:(e,t,n={})=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/preserve-source`,{method:"POST",body:JSON.stringify(n)}),sandboxDownloadFile:async(e,t,n,a={})=>{const s=new URLSearchParams({path:n});a.offsetBytes!==void 0&&s.set("offsetBytes",String(a.offsetBytes)),a.maxBytes!==void 0&&s.set("maxBytes",String(a.maxBytes));const r=await L(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${s.toString()}`);return{...r,contents:r.file.isBinary?"":fC(r.file.contentsBase64)}}},mH={sandboxGitStatus:(e,t)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/status`),sandboxGitDiff:(e,t,n)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/diff`,{method:"POST",body:JSON.stringify(n)})},pH={connectedAppStatus:(e,t={})=>{const n=ov(t);return n.set("status",t.status??"all"),L(e,`/v1/connected-apps/status${n.size>0?`?${n.toString()}`:""}`)},integrationConnections:(e,t={})=>{const n=ov(t);return t.status&&n.set("status",t.status),L(e,`/v1/integrations/connections${n.size>0?`?${n.toString()}`:""}`)},sandboxIntegrationLeases:(e,t)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`),attachSandboxIntegrationConnection:(e,t,n)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"POST",body:JSON.stringify(n)}),removeSandboxIntegrationLease:(e,t,n)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"DELETE",body:JSON.stringify({leaseId:n})})},fH={listSandboxProjects:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return L(e,`/v1/sandbox-projects?${n.toString()}`)},getSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return L(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`)},getSandboxProjectWorkspace:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return L(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/workspace?${a.toString()}`)},upsertSandboxProject:(e,t)=>L(e,"/v1/sandbox-projects",{method:"POST",body:JSON.stringify(t)}),syncSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return L(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/sync?${a.toString()}`,{method:"POST"})},uploadSandboxProjectSource:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId}),{teamId:s,...r}=n;return L(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/source?${a.toString()}`,{method:"POST",body:JSON.stringify(r)})},archiveSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return L(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`,{method:"DELETE"})},listSandboxAgents:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return L(e,`/v1/sandbox-agents?${n.toString()}`)},upsertSandboxAgent:(e,t)=>L(e,"/v1/sandbox-agents",{method:"POST",body:JSON.stringify(t)}),runSandboxAgent:(e,t,n)=>L(e,`/v1/sandbox-agents/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n)}),runProfileAction:(e,t)=>L(e,"/v1/profile/run",{method:"POST",body:JSON.stringify(t)})},hH={sandbox:(e,t)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},gH={...pH,...fH,...hH,...mH,...uH},vH={communities:(e,t)=>{const n=new URLSearchParams;return t&&n.set("cursor",t),L(e,`/v1/communities${n.size?`?${n}`:""}`)},communityPreview:(e,t)=>L(e,`/v1/communities/${encodeURIComponent(t)}/preview`),communityRules:(e,t)=>L(e,`/v1/communities/${encodeURIComponent(t)}/rules/current`),joinCommunity:(e,t,n)=>L(e,`/v1/communities/${encodeURIComponent(t)}/join`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),acceptCommunityRules:(e,t,n)=>L(e,`/v1/communities/${encodeURIComponent(t)}/rules/accept`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),leaveCommunity:(e,t)=>L(e,`/v1/communities/${encodeURIComponent(t)}/leave`,{method:"POST",body:"{}"}),communityChannels:(e,t)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels`),communityMessages:(e,t,n,a={})=>{const s=new URLSearchParams;return a.beforeSequence!=null&&s.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&s.set("limit",String(a.limit)),L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages${s.size?`?${s}`:""}`)},sendCommunityMessage:(e,t,n,a)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages`,{method:"POST",body:JSON.stringify(a)}),editCommunityMessage:(e,t,n,a,s)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify({body:s})}),deleteCommunityMessage:(e,t,n,a)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"DELETE",body:"{}"}),markCommunityRead:(e,t,n,a)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/read`,{method:"POST",body:JSON.stringify({sequence:a})}),setCommunityChannelMuted:(e,t,n,a)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/mute`,{method:"POST",body:JSON.stringify({muted:a})}),searchCommunityMembers:(e,t,n={})=>{const a=new URLSearchParams;return n.query&&a.set("query",n.query),n.cursor&&a.set("cursor",n.cursor),n.limit!=null&&a.set("limit",String(n.limit)),L(e,`/v1/communities/${encodeURIComponent(t)}/members/search${a.size?`?${a}`:""}`)},updateCommunityNotifications:(e,t,n)=>L(e,`/v1/communities/${encodeURIComponent(t)}/notifications`,{method:"POST",body:JSON.stringify({mode:n})}),communityEvents:(e,t,n={})=>{const a=new URLSearchParams;return n.after!=null&&a.set("after",String(n.after)),n.limit!=null&&a.set("limit",String(n.limit)),L(e,`/v1/communities/${encodeURIComponent(t)}/events${a.size?`?${a}`:""}`)},communityRealtimeSession:(e,t)=>L(e,`/v1/communities/${encodeURIComponent(t)}/realtime-session`),uploadCommunityAttachment:(e,t,n,a)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/upload`,{method:"POST",body:JSON.stringify({attachment:a})}),communityAttachmentDownload:(e,t,n,a)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/${encodeURIComponent(a)}/download`)},rg="openpond-app-server-url",Ec="openpond-app-token",bH=750;function Dw(){return window.location.protocol!=="http:"&&window.location.protocol!=="https:"?null:window.location.origin&&window.location.origin!=="null"?window.location.origin:null}function lf(e){const t=e.getItem(rg)?.trim(),n=e.getItem(Ec)?.trim();return t&&n?{serverUrl:t,token:n}:null}function Ed(e){if(!e)return null;try{const t="__openpond_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function Mo(e,t){e.setItem(rg,t.serverUrl),e.setItem(Ec,t.token)}function Sb(e,t){const n=lf(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(rg),e.removeItem(Ec))}function yH(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function SH(){const e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;const t=new URLSearchParams(e),n=t.get("openpondToken")?.trim(),a=t.get("openpondServerUrl")?.trim()||Dw();return!a||!n?null:{serverUrl:a,token:n}}function xH(){window.location.hash&&window.history.replaceState(null,"",`${window.location.pathname}${window.location.search}`)}function Nl(e,t){t&&(e.some(n=>n.serverUrl===t.serverUrl&&n.token===t.token)||e.push(t))}function kH(){const e=[],t=Ed(window.sessionStorage),n=Ed(window.localStorage),a=Dw(),s=t?.getItem(Ec)??n?.getItem(Ec);return Nl(e,null),Nl(e,a&&s?{serverUrl:a,token:s.trim()}:null),Nl(e,t?lf(t):null),Nl(e,n?lf(n):null),e}async function sp(e){const t=new AbortController,n=window.setTimeout(()=>t.abort(),bH);try{const a=await fetch(`${e}/health`,{signal:t.signal}),s=await a.json().catch(()=>null);return a.ok&&s?.server==="openpond-app-server"}catch{return!1}finally{window.clearTimeout(n)}}async function wH(){if(window.openpond)return window.openpond.getConnection();const e=Ed(window.sessionStorage),t=Ed(window.localStorage),n=SH();if(n&&await sp(n.serverUrl))return t&&Mo(t,n),e&&Mo(e,n),xH(),{...n,platform:navigator.platform};const a=yH();if(a&&await sp(a.serverUrl))return t&&Mo(t,a),e&&Mo(e,a),{...a,platform:navigator.platform};const s=kH();for(const r of s){if(await sp(r.serverUrl))return t&&Mo(t,r),e&&Mo(e,r),{...r,platform:navigator.platform};e&&Sb(e,r),t&&Sb(t,r)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const Z={...vH,bootstrap:e=>L(e,"/v1/bootstrap?refreshCodex=1"),accountScopeSnapshot:e=>L(e,"/v1/bootstrap?ensureProfile=0"),localProjectActions:(e,t)=>L(e,`/v1/projects/${encodeURIComponent(t)}/actions`),extensionCatalog:e=>L(e,"/v1/extensions"),extensionPreview:(e,t)=>L(e,"/v1/extensions/preview",{method:"POST",body:JSON.stringify(t)}),extensionAdd:(e,t)=>L(e,"/v1/extensions",{method:"POST",body:JSON.stringify(t)}),extensionUpdate:(e,t,n={})=>L(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}/update`,{method:"POST",body:JSON.stringify(n)}),extensionUpdateAll:e=>L(e,"/v1/extensions/update-all",{method:"POST"}),extensionRemove:(e,t)=>L(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}`,{method:"DELETE"}),skillSourceFile:(e,t,n,a)=>L(e,`/v1/skills/${t}/${encodeURIComponent(n)}/source?path=${encodeURIComponent(a)}`),teamChatMembers:(e,t)=>L(e,`/v1/team-chat/members?teamId=${encodeURIComponent(t)}`),teamChatAgents:(e,t)=>L(e,`/v1/team-chat/agents?teamId=${encodeURIComponent(t)}`),teamChatThreads:(e,t)=>L(e,`/v1/team-chat/threads?teamId=${encodeURIComponent(t)}`),teamChatRealtimeSession:(e,t)=>L(e,`/v1/team-chat/realtime-session?teamId=${encodeURIComponent(t)}`),teamChatEvents:(e,t,n={})=>{const a=new URLSearchParams({teamId:t});return n.after!=null&&a.set("after",String(n.after)),n.limit!=null&&a.set("limit",String(n.limit)),L(e,`/v1/team-chat/events?${a.toString()}`)},teamChatGeneral:(e,t)=>L(e,"/v1/team-chat/threads/general",{method:"POST",body:JSON.stringify({teamId:t})}),teamChatDm:(e,t,n)=>L(e,"/v1/team-chat/threads/dm",{method:"POST",body:JSON.stringify({teamId:t,otherUserId:n})}),teamChatThread:(e,t,n,a={})=>{const s=new URLSearchParams({teamId:t});return a.beforeSequence!=null&&s.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&s.set("limit",String(a.limit)),L(e,`/v1/team-chat/threads/${encodeURIComponent(n)}?${s.toString()}`)},uploadTeamChatAttachment:(e,t,n)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/attachments/upload`,{method:"POST",body:JSON.stringify(n)}),teamChatAttachmentDownload:(e,t,n)=>L(e,`/v1/team-chat/attachments/${encodeURIComponent(n)}/download?teamId=${encodeURIComponent(t)}`),sendTeamChatMessage:(e,t,n)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages`,{method:"POST",body:JSON.stringify(n)}),createTeamChatAgentRun:(e,t,n)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/agent-runs`,{method:"POST",body:JSON.stringify(n)}),teamChatAgentConversation:(e,t,n)=>L(e,`/v1/team-chat/agent-runs/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),editTeamChatMessage:(e,t,n,a)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)}),deleteTeamChatMessage:(e,t,n,a)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"DELETE",body:JSON.stringify({teamId:a})}),markTeamChatRead:(e,t,n,a)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/read`,{method:"POST",body:JSON.stringify({teamId:n,sequence:a})}),setTeamChatThreadMuted:(e,t,n,a)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/mute`,{method:"POST",body:JSON.stringify({teamId:n,muted:a})}),createTeamChatAiThread:(e,t,n)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/ai-threads`,{method:"POST",body:JSON.stringify(n)}),teamChatAiThread:(e,t,n)=>L(e,`/v1/team-chat/ai-threads/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),sendTeamChatAiTurn:(e,t,n)=>L(e,`/v1/team-chat/ai-threads/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),executeTeamChatAiTurn:(e,t,n)=>L(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute`,{method:"POST",body:JSON.stringify({teamId:n})}),cancelTeamChatAiTurnExecution:(e,t,n)=>L(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute/cancel`,{method:"POST",body:JSON.stringify({teamId:n})}),usage:(e,t={})=>{const n=xb(t),a=n.size?`?${n.toString()}`:"";return L(e,`/v1/usage${a}`)},usageRecords:(e,t={})=>{const n=xb(t);t.sessionId&&n.set("sessionId",t.sessionId),t.turnId&&n.set("turnId",t.turnId),t.limit!==void 0&&n.set("limit",String(t.limit));const a=n.size?`?${n.toString()}`:"";return L(e,`/v1/usage/records${a}`)},usageTurnCache:(e,t)=>L(e,`/v1/usage/turn-cache?sessionId=${encodeURIComponent(t)}`),runtimeEventsPage:(e,t={})=>{const n=new URLSearchParams;t.sessionId&&n.set("sessionId",t.sessionId),t.afterSequence!==void 0&&n.set("afterSequence",String(t.afterSequence)),t.beforeSequence!==void 0&&t.beforeSequence!==null&&n.set("beforeSequence",String(t.beforeSequence)),t.limit!==void 0&&n.set("limit",String(t.limit));const a=n.size?`?${n.toString()}`:"";return L(e,`/v1/events/page${a}`)},workOutputs:e=>L(e,"/v1/work/outputs"),harnessHistory:e=>L(e,"/v1/harness"),refinerHistory:e=>L(e,"/v1/refiner"),updateRefinerProfile:(e,t)=>L(e,"/v1/refiner/update",{method:"POST",body:JSON.stringify(t)}),activateRefinerRelease:(e,t)=>L(e,"/v1/refiner/activate",{method:"POST",body:JSON.stringify(t)}),rollbackRefinerRelease:(e,t)=>L(e,"/v1/refiner/rollback",{method:"POST",body:JSON.stringify(t)}),updateHarnessBackgroundReview:(e,t)=>L(e,"/v1/harness/background-review",{method:"POST",body:JSON.stringify(t)}),reviewHarnessEvaluation:(e,t)=>L(e,"/v1/harness/evaluation-review",{method:"POST",body:JSON.stringify(t)}),updateHarnessEvaluationReviewSchedule:(e,t)=>L(e,"/v1/harness/evaluation-review/settings",{method:"POST",body:JSON.stringify(t)}),harnessReleaseDiff:(e,t)=>L(e,"/v1/harness/diff",{method:"POST",body:JSON.stringify(t)}),rollbackHarness:(e,t)=>L(e,"/v1/harness/rollback",{method:"POST",body:JSON.stringify(t)}),reviewHarnessProposal:(e,t)=>L(e,"/v1/harness/review",{method:"POST",body:JSON.stringify(t)}),runSubagentLifecycleAction:(e,t,n)=>L(e,`/v1/subagents/${encodeURIComponent(t)}/lifecycle`,{method:"POST",body:JSON.stringify(n)}),trainingState:(e,t)=>L(e,`/v1/training?profileId=${encodeURIComponent(t)}`),trainingActivity:(e,t)=>L(e,`/v1/training/activity?profileId=${encodeURIComponent(t)}`),portableTrainingCatalog:(e,t="",n)=>{const a=new URLSearchParams;return t.trim()&&a.set("query",t.trim()),n&&a.set("method",n),L(e,`/v1/training/catalog${a.size?`?${a.toString()}`:""}`)},datasetCatalog:(e,t)=>L(e,`/v1/training/datasets?profileId=${encodeURIComponent(t)}`),trainingRunDetail:(e,t,n={})=>L(e,`/v1/training/jobs/${encodeURIComponent(t)}/detail?evaluation=${n.includeEvaluation===!1?"false":"true"}`),candidateReview:(e,t,n=!1,a="models")=>L(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision?refresh=${n}`),recordCandidateReview:(e,t,n,a="models")=>L(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision`,{method:"POST",body:JSON.stringify(n)}),candidateReviewHistory:(e,t,n,a="models")=>L(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision-history?decisionId=${encodeURIComponent(n.id)}&decisionHash=${n.contentHash}`),trainingEvaluationTasks:async(e,t,n,a)=>{const s=new URLSearchParams({limit:"25"});return a&&s.set("cursor",a),L(e,`/v1/training/jobs/${encodeURIComponent(t)}/evaluations/${encodeURIComponent(n.id)}/tasks?${s}`)},trainingRequest:(e,t,n,a="POST")=>L(e,`/v1/training${t}`,{method:a,body:a==="GET"||a==="DELETE"?void 0:JSON.stringify(n)}),datasetStorageState:e=>L(e,"/v1/settings/dataset-storage"),updateDatasetStorage:(e,t)=>L(e,"/v1/settings/dataset-storage",{method:"PATCH",body:JSON.stringify({datasetStorePath:t})}),hostedSavedWork:e=>L(e,"/v1/saved-work"),createHostedSavedWork:(e,t)=>L(e,"/v1/saved-work",{method:"POST",body:JSON.stringify(t)}),updateHostedSavedWork:(e,t,n)=>L(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteHostedSavedWork:(e,t)=>L(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"DELETE"}),runHostedSavedWork:(e,t,n)=>L(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({clientRequestId:n})}),chatWorkflows:(e,t)=>{const n=t?`?sessionId=${encodeURIComponent(t)}`:"";return L(e,`/v1/chat-workflows${n}`)},createChatWorkflow:(e,t)=>L(e,"/v1/chat-workflows",{method:"POST",body:JSON.stringify(t)}),updateChatWorkflow:(e,t,n)=>L(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteChatWorkflow:(e,t)=>L(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"DELETE"}),runChatWorkflow:(e,t)=>L(e,`/v1/chat-workflows/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({})}),localAgentSchedules:(e,t={})=>{const n=new URLSearchParams;t.localProjectId&&n.set("localProjectId",t.localProjectId);const a=n.size?`?${n.toString()}`:"";return L(e,`/v1/local-agent-schedules${a}`)},syncLocalAgentSchedules:e=>L(e,"/v1/local-agent-schedules/sync",{method:"POST",body:JSON.stringify({})}),patchLocalAgentSchedule:(e,t,n)=>L(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),runLocalAgentSchedule:(e,t,n={})=>L(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n)}),localAgentScheduleRuns:(e,t,n={})=>{const a=new URLSearchParams;n.limit!==void 0&&a.set("limit",String(n.limit));const s=a.size?`?${a.toString()}`:"";return L(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/runs${s}`)},refreshOpenPondAccounts:e=>L(e,"/v1/openpond/accounts/refresh",{method:"POST",body:JSON.stringify({})}),refreshOpenPondAccount:e=>L(e,"/v1/openpond/account?refresh=1"),loadMoreOpenPondApps:(e,t)=>L(e,`/v1/openpond/apps/more?offset=${encodeURIComponent(String(t.offset))}&limit=${encodeURIComponent(String(t.limit))}`),switchOpenPondAccount:(e,t)=>L(e,"/v1/openpond/accounts/switch",{method:"POST",body:JSON.stringify(t)}),removeOpenPondAccount:(e,t)=>L(e,"/v1/openpond/accounts",{method:"DELETE",body:JSON.stringify(t)}),signOutOpenPondAccount:e=>L(e,"/v1/openpond/accounts/logout",{method:"POST",body:JSON.stringify({})}),saveOpenPondAccount:(e,t)=>L(e,"/v1/openpond/accounts/login",{method:"POST",body:JSON.stringify(t)}),updateOpenPondAccountConfig:(e,t)=>L(e,"/v1/openpond/accounts/config",{method:"PATCH",body:JSON.stringify(t)}),savePreferences:(e,t)=>L(e,"/v1/preferences",{method:"PATCH",body:JSON.stringify(t)}),saveProviderSettings:(e,t)=>L(e,"/v1/providers",{method:"PATCH",body:JSON.stringify(t)}),providerSettings:e=>L(e,"/v1/providers"),loadProviderModels:(e,t,n={})=>{const a=new URLSearchParams;n.query?.trim()&&a.set("query",n.query.trim()),n.limit&&a.set("limit",String(n.limit));const s=a.size?`?${a.toString()}`:"";return L(e,`/v1/providers/${encodeURIComponent(t)}/models${s}`)},refreshProviderModels:(e,t,n)=>L(e,`/v1/providers/${encodeURIComponent(t)}/models`,{method:"POST",body:JSON.stringify(n)}),saveProviderCredential:(e,t,n)=>L(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"PUT",body:JSON.stringify(n)}),deleteProviderCredential:(e,t,n)=>L(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"DELETE",body:JSON.stringify(n)}),startOpenAiSubscriptionAuth:(e,t)=>L(e,"/v1/providers/openai/subscription-auth",{method:"POST",body:JSON.stringify(t)}),validateProviderCredential:(e,t,n)=>L(e,`/v1/providers/${encodeURIComponent(t)}/validate`,{method:"POST",body:JSON.stringify(n)}),savePersonalization:(e,t)=>L(e,"/v1/personalization",{method:"PATCH",body:JSON.stringify(t)}),recordClientDiagnostic:(e,t)=>L(e,"/v1/diagnostics/client",{method:"POST",body:JSON.stringify(t)}),profileCurrent:e=>L(e,"/v1/profile"),profileCatalog:e=>L(e,"/v1/profile/catalog"),profileWorkflows:e=>L(e,"/v1/profile/workflows"),profileEvaluations:e=>L(e,"/v1/profile/evaluations"),profileEvaluationDiscovery:(e,t,n)=>L(e,"/v1/profile/evaluations/discover",{method:"POST",body:JSON.stringify({profileRef:t}),signal:n}),profileEvaluationPrepare:(e,t)=>L(e,"/v1/profile/evaluations/prepare",{method:"POST",body:JSON.stringify(t)}),profileEvaluationRun:(e,t)=>L(e,"/v1/profile/evaluations/run",{method:"POST",body:JSON.stringify(t)}),profileEvaluationRunSuite:(e,t)=>L(e,"/v1/profile/evaluations/run-suite",{method:"POST",body:JSON.stringify(t)}),profileEvaluationCompare:(e,t)=>L(e,"/v1/profile/evaluations/compare",{method:"POST",body:JSON.stringify({id:`comparison-${crypto.randomUUID()}`,runIds:t})}),profileEvaluationSaveReport:(e,t,n)=>L(e,"/v1/profile/evaluations/reports",{method:"POST",body:JSON.stringify({id:`report-${crypto.randomUUID()}`,evidenceKind:t,evidenceId:n})}),profileSelect:(e,t)=>L(e,"/v1/profile/select",{method:"POST",body:JSON.stringify({ref:t})}),profileRemove:(e,t)=>L(e,"/v1/profile/remove",{method:"POST",body:JSON.stringify({ref:t})}),profilePublicationPreview:(e,t)=>L(e,"/v1/profile/publication/preview",{method:"POST",body:JSON.stringify(t)}),profilePublicationPublish:(e,t)=>L(e,"/v1/profile/publication/publish",{method:"POST",body:JSON.stringify(t)}),profileInstall:(e,t)=>L(e,"/v1/profile/install",{method:"POST",body:JSON.stringify(t)}),profileUpdate:(e,t)=>L(e,"/v1/profile/update",{method:"POST",body:JSON.stringify({ref:t})}),profileInit:(e,t)=>L(e,"/v1/profile/init",{method:"POST",body:JSON.stringify(t)}),profileLoad:(e,t)=>L(e,"/v1/profile/load",{method:"POST",body:JSON.stringify(t)}),profileCheck:(e,t)=>L(e,"/v1/profile/check",{method:"POST",body:JSON.stringify(t)}),profileAgentRename:(e,t,n)=>L(e,`/v1/profile/agents/${encodeURIComponent(t)}/name`,{method:"PATCH",body:JSON.stringify(n)}),profileCommit:(e,t)=>L(e,"/v1/profile/commit",{method:"POST",body:JSON.stringify(t)}),profilePush:(e,t)=>L(e,"/v1/profile/push",{method:"POST",body:JSON.stringify(t)}),workspaceLspSettingsStatus:e=>L(e,"/v1/lsp/settings-status"),workspaceLspRuntimeStatus:e=>L(e,"/v1/lsp/status"),restartWorkspaceLsp:e=>L(e,"/v1/lsp/restart",{method:"POST"}),remoteAccess:e=>L(e,"/v1/remote-access"),enableRemoteAccess:e=>L(e,"/v1/remote-access/enable",{method:"POST"}),disableRemoteAccess:e=>L(e,"/v1/remote-access/disable",{method:"POST"}),voiceTranscriptionStatus:(e,t={})=>L(e,"/v1/audio/transcriptions/status",{signal:t.signal}),transcribeVoice:(e,t,n={})=>L(e,"/v1/audio/transcriptions",{method:"POST",body:JSON.stringify(t),signal:n.signal}),createSession:(e,t)=>L(e,"/v1/sessions",{method:"POST",body:JSON.stringify(t)}),patchSession:(e,t,n)=>L(e,`/v1/sessions/${t}`,{method:"PATCH",body:JSON.stringify(n)}),codexHistoryThread:(e,t,n={})=>{const a=new URLSearchParams;n.limit!==void 0&&a.set("limit",String(n.limit)),n.tail&&a.set("tail","1");const s=a.size?`?${a.toString()}`:"";return L(e,`/v1/codex-history/${encodeURIComponent(t)}${s}`)},codexHistoryThreadIncremental:(e,t,n={})=>{const a=new URLSearchParams({incremental:"1"});return n.afterEventId&&a.set("afterEventId",n.afterEventId),n.limit!==void 0&&a.set("limit",String(n.limit)),n.revision&&a.set("revision",n.revision),n.tail&&a.set("tail","1"),L(e,`/v1/codex-history/${encodeURIComponent(t)}?${a.toString()}`)},sendCodexHistoryTurn:(e,t,n)=>L(e,`/v1/codex-history/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),interruptCodexHistoryTurn:(e,t)=>L(e,`/v1/codex-history/${encodeURIComponent(t)}/turns/interrupt`,{method:"POST"}),patchSidebarAppPreference:(e,t,n)=>L(e,`/v1/sidebar/apps/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),reorderSidebarApps:(e,t)=>L(e,"/v1/sidebar/apps/reorder",{method:"POST",body:JSON.stringify(t)}),sidebarFiles:e=>L(e,"/v1/sidebar/files"),patchSidebarFile:(e,t)=>L(e,"/v1/sidebar/files",{method:"PATCH",body:JSON.stringify(t)}),workspaceStatus:(e,t,n=!1,a={})=>L(e,`/v1/workspaces/${encodeURIComponent(t)}${n?"?ensure=1":""}`,{signal:a.signal}),createWorkspaceBranch:(e,t,n)=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/branches`,{method:"POST",body:JSON.stringify(n)}),checkoutWorkspaceBranch:(e,t,n)=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/branch`,{method:"PATCH",body:JSON.stringify(n)}),workspaceDiff:(e,t,n={})=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/diff`,{signal:n.signal}),resolveWorkspaceFile:(e,t,n)=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/resolve-file?path=${encodeURIComponent(n)}`),workspaceFile:(e,t,n)=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`),saveWorkspaceFile:(e,t,n)=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/file`,{method:"PATCH",body:JSON.stringify(n)}),signWorkspaceImageUrl:(e,t)=>L(e,"/v1/assets/workspace-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalImageUrl:(e,t)=>L(e,"/v1/assets/local-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalVideoUrl:(e,t)=>L(e,"/v1/assets/local-video-url",{method:"POST",body:JSON.stringify(t)}),signChatAttachmentImageUrl:(e,t)=>L(e,"/v1/assets/chat-attachment-image-url",{method:"POST",body:JSON.stringify(t)}),chatAttachmentFile:(e,t)=>L(e,"/v1/assets/chat-attachment-file",{method:"POST",body:JSON.stringify(t)}),workspaceLspTouch:(e,t,n,a={})=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/touch`,{method:"POST",body:JSON.stringify(n),signal:a.signal}),workspaceLspAction:(e,t,n)=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/action`,{method:"POST",body:JSON.stringify(n)}),workspaceTemplateConfig:(e,t)=>L(e,`/v1/openpond/apps/${encodeURIComponent(t)}/template-config`),...cH,...gH,createLocalProject:(e,t)=>L(e,"/v1/projects",{method:"POST",body:JSON.stringify(t)}),updateLocalProjectAgentSetup:(e,t,n)=>L(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),uploadLocalProjectCloudSource:(e,t,n)=>L(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source`,{method:"POST",body:JSON.stringify(n)}),previewLocalProjectCloudSource:(e,t,n={})=>{const a=new URLSearchParams;n.branch?.trim()&&a.set("branch",n.branch.trim());const s=a.toString()?`?${a.toString()}`:"";return L(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source/preview${s}`)},deleteLocalProject:(e,t)=>L(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"DELETE"}),gitAvailability:e=>L(e,"/v1/system/git"),installMacOSCommandLineTools:e=>L(e,"/v1/system/git/install-command-line-tools",{method:"POST",body:JSON.stringify({})}),...lH,resolveApproval:(e,t,n)=>L(e,`/v1/approvals/${t}`,{method:"POST",body:JSON.stringify(n)})};function xb(e){const t=new URLSearchParams;return e.range&&t.set("range",e.range),e.visibility&&t.set("visibility",e.visibility),e.status&&t.set("status",e.status),e.provider&&t.set("provider",e.provider),e.model&&t.set("model",e.model),t}const IH=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),_H=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),kb=e=>{const t=_H(e);return t.charAt(0).toUpperCase()+t.slice(1)},Lw=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),CH=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var RH={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const PH=h.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:s="",children:r,iconNode:i,...c},l)=>h.createElement("svg",{ref:l,...RH,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:Lw("lucide",s),...!r&&!CH(c)&&{"aria-hidden":"true"},...c},[...i.map(([u,p])=>h.createElement(u,p)),...Array.isArray(r)?r:[r]]));const We=(e,t)=>{const n=h.forwardRef(({className:a,...s},r)=>h.createElement(PH,{ref:r,iconNode:t,className:Lw(`lucide-${IH(kb(e))}`,`lucide-${e}`,a),...s}));return n.displayName=kb(e),n};const TH=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],AH=We("activity",TH);const EH=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]],jH=We("archive-restore",EH);const MH=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],OH=We("arrow-left",MH);const $H=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],zw=We("bookmark",$H);const NH=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2Z",key:"169p4p"}],["path",{d:"m14.5 7.5-5 5",key:"3lb6iw"}],["path",{d:"m9.5 7.5 5 5",key:"ko136h"}]],Hw=We("bookmark-x",NH);const DH=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M16 12h2",key:"7q9ll5"}],["path",{d:"M16 8h2",key:"msurwy"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}],["path",{d:"M6 12h2",key:"32wvfc"}],["path",{d:"M6 8h2",key:"30oboj"}]],wb=We("book-open-text",DH);const LH=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],Ib=We("bot",LH);const zH=[["path",{d:"M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z",key:"lc1i9w"}],["path",{d:"m7 16.5-4.74-2.85",key:"1o9zyk"}],["path",{d:"m7 16.5 5-3",key:"va8pkn"}],["path",{d:"M7 16.5v5.17",key:"jnp8gn"}],["path",{d:"M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z",key:"8zsnat"}],["path",{d:"m17 16.5-5-3",key:"8arw3v"}],["path",{d:"m17 16.5 4.74-2.85",key:"8rfmw"}],["path",{d:"M17 16.5v5.17",key:"k6z78m"}],["path",{d:"M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z",key:"1xygjf"}],["path",{d:"M12 8 7.26 5.15",key:"1vbdud"}],["path",{d:"m12 8 4.74-2.85",key:"3rx089"}],["path",{d:"M12 13.5V8",key:"1io7kd"}]],Dl=We("boxes",zH);const HH=[["path",{d:"M16 14v2.2l1.6 1",key:"fo4ql5"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]],Uw=We("calendar-clock",HH);const UH=[["path",{d:"M11 13H7",key:"t0o9gq"}],["path",{d:"M19 9h-4",key:"rera1j"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"15",y:"5",width:"4",height:"12",rx:"1",key:"q8uenq"}],["rect",{x:"7",y:"8",width:"4",height:"9",rx:"1",key:"sr5ea"}]],qw=We("chart-column-stacked",UH);const qH=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],ds=We("check",qH);const BH=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],rd=We("circle-check",BH);const FH=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],mr=We("chevron-down",FH);const VH=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],pr=We("chevron-right",VH);const KH=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],jd=We("circle-alert",KH);const WH=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],yu=We("cloud",WH);const GH=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],ZH=We("credit-card",GH);const JH=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],QH=We("download",JH);const YH=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],rp=We("external-link",YH);const XH=[["path",{d:"M4.226 20.925A2 2 0 0 0 6 22h12a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v3.127",key:"wfxp4w"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"m5 11-3 3",key:"1dgrs4"}],["path",{d:"m5 17-3-3h10",key:"1mvvaf"}]],Bw=We("file-output",XH);const eU=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],og=We("file-text",eU);const tU=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],Fw=We("folder",tU);const nU=[["path",{d:"M18 19a5 5 0 0 1-5-5v8",key:"sz5oeg"}],["path",{d:"M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v5",key:"1w6njk"}],["circle",{cx:"13",cy:"12",r:"2",key:"1j92g6"}],["circle",{cx:"20",cy:"19",r:"2",key:"1obnsp"}]],ig=We("folder-git-2",nU);const aU=[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]],sU=We("git-branch",aU);const rU=[["path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4",key:"tonef"}],["path",{d:"M9 18c-4.51 2-5-2-7-2",key:"9comsn"}]],oU=We("github",rU);const iU=[["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17",key:"1tzkfa"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"14pb5j"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Vw=We("earth",iU);const cU=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],lU=We("circle-question-mark",cU);const dU=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],uU=We("list-filter",dU);const mU=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Su=We("loader-circle",mU);const pU=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],fU=We("maximize-2",pU);const hU=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],xu=We("message-square",hU);const gU=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],Xc=We("ellipsis",gU);const vU=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],Kw=We("panel-left",vU);const bU=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],df=We("panel-right",bU);const yU=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z",key:"1nkz8b"}]],cg=We("pin",yU);const SU=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89",key:"znwnzq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11",key:"c9qhm2"}]],lg=We("pin-off",SU);const xU=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],kU=We("plus",xU);const wU=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],IU=We("power",wU);const _U=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],dg=We("refresh-cw",_U);const CU=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],RU=We("rotate-ccw",CU);const PU=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],TU=We("search",PU);const AU=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Ww=We("settings",AU);const EU=[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]],ug=We("shapes",EU);const jU=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],_b=We("shield",jU);const MU=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],ku=We("square-pen",MU);const OU=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],Gw=We("square-terminal",OU);const $U=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],Cb=We("user-round",$U);const NU=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],el=We("x",NU);const DU=[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]],mg=We("inbox",DU);const LU=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],zU=We("list",LU);const HU=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],UU=We("terminal",HU);function qU(){const[e,t]=h.useState(null);return h.useEffect(()=>{const n=window.openpond?.updates;if(!n)return;let a=!0;const s=i=>{a&&t(c=>!c||i.revision>c.revision?i:c)},r=n.onState(s);return n.getState().then(s).catch(()=>{}),()=>{a=!1,r()}},[]),e}const pg="openpond.desktop-update-drafts.v1";function BU(e,t=window.localStorage){t.setItem(pg,JSON.stringify(e))}function FU(e){try{const n=(e??window.localStorage).getItem(pg);if(!n)return{};const a=JSON.parse(n);if(!a||typeof a!="object"||Array.isArray(a))return{};const s={};for(const[r,i]of Object.entries(a))typeof i=="string"&&/^(?:new-chat|(?:session|project|app):.+)$/.test(r)&&(s[r]=i);return s}catch{return{}}}function Zw(e=window.localStorage){e.removeItem(pg)}function VU({hasRunningWork:e}){const t=qU(),[n,a]=h.useState(!1),[s,r]=h.useState(null),i=window.openpond?.updates;if(!t?.version||t.status==="unsupported"||!i)return null;const c=t.status==="ready"||t.status==="restarting"||t.retry==="restart",l=n||t.status==="downloading"||t.status==="restarting"||t.status==="checking",u=s??t.error,p=c?"Restart to update":"Update",f=u??(l?c?"Restarting OpenPond…":`Downloading OpenPond ${t.version}${t.progress===null?"":` (${t.progress}%)`}…`:c?`OpenPond ${t.version} is ready. It will be applied when you restart.`:`Download OpenPond ${t.version}`);async function S(){if(!(l||!i)){a(!0),r(null);try{if(c){if(!window.dispatchEvent(new Event("openpond:before-update",{cancelable:!0})))throw new Error("Could not save your drafts. Save them before restarting to update.");(await i.restartAndInstall({hasRunningWork:e})).status!=="restarting"&&Zw()}else t?.retry==="check"?await i.check():await i.download()}catch(b){r(b instanceof Error?b.message:"The update could not start. Try again.")}finally{a(!1)}}}return g.jsxs("div",{className:"sidebar-update-control",children:[g.jsxs("button",{type:"button",className:"sidebar-update-pill",title:f,"aria-label":l?f:`${p}${t.version?` (${t.version})`:""}`,"aria-busy":l,disabled:l,onClick:()=>{S()},children:[g.jsx("span",{className:`sidebar-update-icon${l?" sidebar-update-spinner":""}`,"aria-hidden":"true",children:l?g.jsx(Su,{size:14}):c?g.jsx(dg,{size:14}):g.jsx(QH,{size:14})}),g.jsx("span",{children:p})]}),g.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:t.status==="ready"?`OpenPond ${t.version} is ready to install. Restart to update.`:""}),u?g.jsx("div",{className:"sidebar-update-error",role:"alert",children:u}):null]})}const KU=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],Jw=We("house",KU);const WU=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M9 21V9",key:"1oto5p"}]],GU=We("panels-top-left",WU);function ZU({value:e,options:t,disabled:n,compact:a,className:s,icon:r,placement:i="bottom",label:c,tooltip:l,searchable:u=!1,floating:p=!1,onChange:f}){const[S,b]=h.useState(!1),[w,C]=h.useState(""),P=h.useRef(null),[_,M]=h.useState();h.useLayoutEffect(()=>{if(!S||!p)return;function I(){const R=P.current?.getBoundingClientRect();if(!R)return;const O=window.innerHeight-R.bottom-12,z=R.top-12,$=O<180&&z>O;M({position:"fixed",left:Math.max(12,R.left),width:Math.min(R.width,window.innerWidth-24),minWidth:0,maxWidth:"calc(100vw - 24px)",right:"auto",top:$?"auto":R.bottom+5,bottom:$?window.innerHeight-R.top+5:"auto",maxHeight:Math.max(80,Math.min(320,$?z-5:O-5)),overflowY:"auto",zIndex:1e3})}return I(),window.addEventListener("resize",I),window.addEventListener("scroll",I,!0),()=>{window.removeEventListener("resize",I),window.removeEventListener("scroll",I,!0)}},[S,p]);const E=t.find(I=>I.value===e)??t[0],T=w.trim().toLowerCase(),y=T?t.filter(I=>[I.label,I.shortLabel,I.description].some(R=>R?.toLowerCase().includes(T))):t;return h.useEffect(()=>{if(!S){C("");return}function I(O){P.current?.contains(O.target)||b(!1)}function R(O){O.key==="Escape"&&b(!1)}return document.addEventListener("pointerdown",I),document.addEventListener("keydown",R),()=>{document.removeEventListener("pointerdown",I),document.removeEventListener("keydown",R)}},[S]),g.jsxs("div",{className:`dropdown-select ${s??""} ${a?"compact":""} ${i==="top"?"open-up":""}`,"data-tooltip":l,ref:P,children:[g.jsxs("button",{type:"button",className:`dropdown-trigger ${S?"active":""}`,disabled:n,"aria-label":c,"aria-haspopup":"menu","aria-expanded":S,onClick:()=>b(I=>!I),children:[r,g.jsx("span",{children:E?.shortLabel??E?.label??e}),g.jsx(mr,{size:14})]}),S&&g.jsxs("div",{className:"dropdown-menu",role:"menu",style:p?_:void 0,children:[u?g.jsxs("label",{className:"dropdown-search",onClick:I=>I.stopPropagation(),children:[g.jsxs("span",{className:"sr-only",children:["Search ",c]}),g.jsx("input",{autoFocus:!0,placeholder:`Search ${c.toLowerCase()}`,value:w,onChange:I=>C(I.target.value)})]}):null,y.map(I=>g.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":I.value===e,disabled:I.disabled,className:[I.value===e?"selected":"",I.separatorBefore?"separator-before":"",I.icon?"with-icon":""].filter(Boolean).join(" "),onClick:()=>{I.disabled||(f(I.value),C(""),b(!1))},children:[g.jsxs("span",{children:[I.icon==="plus"?g.jsx(kU,{size:13}):null,g.jsx("span",{children:I.label})]}),I.description&&g.jsx("small",{children:I.description})]},I.value)),y.length?null:g.jsx("div",{className:"dropdown-empty",children:"No matches"})]})]})}const rG=[{value:"chat",label:"Chat"},{value:"work",label:"Work"}];function Qw(e){return e==="chat"?"New chat":"New task"}const uf=["get-started","home","inbox","models","datasets","graders","experiments","tasks","tasksets","labeling","rewards","evaluations","runs","versions","serving"],JU={"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"},QU={tasks:["drafts"],tasksets:["drafts","formats","batches"],rewards:["scorers","combined"],evaluations:["results","review","comparisons"],runs:["series","new"]},YU={datasets:["tasks","experiments","graders","versions"],graders:["overview","checks","usage","versions"],experiments:["overview","cases","compare","configuration"],tasksets:["overview","tasks","reward","attempts","releases"],rewards:["definition","usage","evidence"],evaluations:["overview","comparison","activity"],runs:["details","metrics","evaluation","rollouts","activity","artifacts"],versions:["overview","metrics","evaluation","rollouts","activity","artifacts"]};function wa(e="models",t=null,n={}){return e==="evaluations"&&n.collection==="review"?wa("labeling",t,{...n,collection:"default"}):{page:e,modelId:["get-started","home","inbox","datasets","graders","experiments"].includes(e)?null:t,collection:e==="evaluations"?"results":"default",resourceId:null,detailTab:null,query:"",after:null,...n}}function fg(e){const t=e.pathname.split("/").filter(Boolean);if(t[0]!=="models"&&t[0]!=="console")return null;let n;try{n=t.slice(1).map(decodeURIComponent)}catch{return null}if(n.some(Y=>!Y.trim()||Y.length>2e3||Y.includes("\0")))return null;const a=n[0]&&!uf.includes(n[0])?n.shift():null;if(a&&(a.length>500||["projects","scorers"].includes(a)))return null;n[0]==="runs"&&n[1]==="evaluations"&&n.splice(0,2,"evaluations","results"),n[0]==="runs"&&n[1]==="comparisons"&&n.splice(0,2,"evaluations","comparisons");const s=n.shift(),r=s??"models";if(!uf.includes(r)||s==="models"||a&&r==="get-started")return null;let i=r==="evaluations"?"results":"default";if(QU[r]?.includes(n[0]))i=n.shift();else if(r==="evaluations"&&n.length)return null;if(r==="experiments"&&n[0]==="history")return null;const c=n.shift()??null,l=n.shift()??null;if(n.length||l&&!c||(r==="models"||r==="get-started"||r==="home")&&c)return null;if(i==="drafts"||i==="new"){if(!c||l)return null}else if(i!=="series"){if(["review","formats","batches","comparisons","scorers","combined"].includes(i)){if(l)return null}else if(l&&!YU[r]?.includes(l))return null}if(r==="serving"&&l)return null;const u=new URLSearchParams(e.search??"");if([...u.keys()].some(Y=>!["model","q","after","source","project","pass","dataset","revision","hash","sort","location","kind","review_source","review_snapshot","review_boundary","review_revision"].includes(Y))||[...u.keys()].some(Y=>u.getAll(Y).length!==1))return null;const p=["review_source","review_snapshot","review_boundary","review_revision"],f=p.some(Y=>u.has(Y));if(f&&(r!=="datasets"||c||u.get("location")==="local"||p.some(Y=>!u.get(Y))||[u.get("review_source"),u.get("review_boundary")].some(Y=>!Y.trim()||Y.length>500||Y.includes("\0"))||[u.get("review_snapshot"),u.get("review_revision")].some(Y=>!/^[a-f0-9]{64}$/.test(Y))))return null;const S=f?{id:u.get("review_source"),snapshotHash:u.get("review_snapshot"),boundaryId:u.get("review_boundary"),boundaryRevisionHash:u.get("review_revision")}:void 0,b=u.get("sort");if(b!==null&&(r!=="datasets"||!["id","name","updated"].includes(b)))return null;const w=u.has("revision")?Number(u.get("revision")):void 0,C=u.get("hash")??void 0,P=["datasets","graders"].includes(r);if((w!==void 0||C!==void 0)&&(!c||!P||!Number.isSafeInteger(w)||w<=0||!/^[a-f0-9]{64}$/.test(C??"")))return null;const _=u.get("source");if(_!==null&&(r!=="labeling"&&(r!=="evaluations"||i!=="review")||!_.trim()||_.length>500)||u.has("dataset")&&(r!=="datasets"||!c||u.get("dataset")!=="release"))return null;const M=["home","inbox","datasets","graders","experiments"].includes(r),E=r==="runs"&&!!(c?.startsWith("hosted-run:")||c?.startsWith("hosted-policy:")),T=u.get("location");if(T!==null&&(!M||!["local","hosted"].includes(T)))return null;const y=u.get("kind");if(y!==null&&(r!=="experiments"||!c||T==="local"||y!=="recorded_evidence")||t[0]==="console"&&!M)return null;const I=u.get("project")==="all"?null:u.get("project"),R=u.get("pass");if([I,R].some(Y=>Y!==null&&(!Y.trim()||Y.length>240))||!M&&!E&&(I||R)||r!=="experiments"&&R||(M||E)&&a||R&&!c)return null;const O=u.get("model");if(M&&O!==null||a&&O&&a!==O)return null;const z=a??O;if(r==="get-started"&&u.size!==0)return null;const $=u.get("q")??"",V=u.get("after");return z!==null&&(!z.trim()||z.length>500)||$.length>1e3||V!==null&&(!V.trim()||V.length>2e3)?null:wa(r,z,{...S?{reviewSource:S}:{},collection:i,resourceId:c,detailTab:l,query:$,after:V,...y?{executionKind:"recorded_evidence"}:{},...T?{executionLocation:T}:{},...b?{sort:b}:{},...w!==void 0?{revision:w,contentHash:C}:{},...u.get("dataset")==="release"?{datasetKind:"release"}:{},...t[0]==="console"?{area:"console"}:{},...M||E?{...u.has("project")?{projectId:I}:{},...u.has("pass")?{passId:R}:{}}:{},..._!==null?{sourceId:_}:{}})}function wu(e){const t=[e.area==="console"?"/console":"/models"];if(e.modelId&&t.push(encodeURIComponent(e.modelId)),e.page==="evaluations"&&e.collection==="review")return wu(wa("labeling",e.modelId,{collection:"default",resourceId:e.resourceId,sourceId:e.sourceId,query:e.query,after:e.after}));e.page==="evaluations"?t.push("runs",e.collection==="comparisons"?"comparisons":"evaluations"):(e.page!=="models"&&t.push(e.page),e.collection!=="default"&&t.push(e.collection)),e.resourceId&&t.push(encodeURIComponent(e.resourceId)),e.resourceId&&e.detailTab&&t.push(encodeURIComponent(e.detailTab));const n=new URLSearchParams;return e.page==="datasets"&&!e.resourceId&&e.reviewSource&&(n.set("review_source",e.reviewSource.id),n.set("review_snapshot",e.reviewSource.snapshotHash),n.set("review_boundary",e.reviewSource.boundaryId),n.set("review_revision",e.reviewSource.boundaryRevisionHash)),e.executionLocation&&n.set("location",e.executionLocation),e.projectId?n.set("project",e.projectId):e.projectId===null&&["home","inbox","datasets","graders","experiments"].includes(e.page)&&n.set("project","all"),e.page==="datasets"&&e.resourceId&&e.datasetKind==="release"&&n.set("dataset","release"),e.page==="datasets"&&e.sort&&n.set("sort",e.sort),e.revision!==void 0&&e.contentHash&&e.resourceId&&["datasets","graders"].includes(e.page)&&(n.set("revision",String(e.revision)),n.set("hash",e.contentHash)),e.passId&&n.set("pass",e.passId),e.page==="experiments"&&e.resourceId&&e.executionKind&&n.set("kind",e.executionKind),e.query&&n.set("q",e.query),e.after&&n.set("after",e.after),(e.page==="labeling"||e.page==="evaluations"&&e.collection==="review")&&e.sourceId&&n.set("source",e.sourceId),`${t.join("/")}${n.size?`?${n}`:""}`}function XU(e,t){return wa(e.page,t,{...e.area?{area:e.area}:{},...["home","inbox","datasets","graders","experiments"].includes(e.page)&&e.projectId!==void 0?{projectId:e.projectId}:{},collection:e.collection==="new"||e.collection==="drafts"?"default":e.collection})}function oG(e,t,n=null){return{...e,resourceId:t,detailTab:n,after:null,...t!==e.resourceId?{revision:void 0,contentHash:void 0}:{}}}const Md=new Set,mf=new Set,eq=new Set(["account","notifications","harness","harness-refiner","harness-continuous-review","harness-contents","harness-releases","profile","skills","configuration","context","training","subagents","editor","providers","conversation-imports","dataset-storage","remote","usage","personalization","diagnostics"]),pf={apps:"/apps",outputs:"/outputs",projects:"/projects",scheduled:"/workflows","get-started":"/get-started",team:"/team",community:"/community"};let ff=!1,hf="",od=null,Yw=null,jc="",za=0,Qi=null,gc=!1,op=null,id=!1;function hg(e){const t=fg(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&&eq.has(n[1])){const s=gg(new URLSearchParams(e.search??"").get("returnTo"));return{kind:"settings",section:n[1],...s?{returnTo:s}:{}}}if(n[0]==="chat"&&n.length<=2)try{return{kind:"chat",sessionId:n[1]&&n[1]!=="new"?decodeURIComponent(n[1]):null}}catch{return null}const a=Object.keys(pf).find(s=>pf[s]===e.pathname);return a?{kind:"view",view:a}:null}function Xw(e){if(e.kind==="models")return wu(e.route);if(e.kind==="models_unavailable")return`${e.pathname}${e.search}`;if(e.kind==="settings"){const t=gg(e.returnTo??null);return`/settings/${e.section}${t?`?${new URLSearchParams({returnTo:t})}`:""}`}return e.kind==="chat"?e.sessionId?`/chat/${encodeURIComponent(e.sessionId)}`:"/chat/new":pf[e.view]}function tq(e){const t=e?.kind==="settings"?gg(e.returnTo??null):null;if(t){const n=new URL(t,"https://local.openpond.invalid"),a=fg(n);if(a)return{kind:"models",route:a}}return{kind:"chat",sessionId:null}}function gg(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=fg(t);return n?wu(n):null}function tl(){return`${window.location.pathname}${window.location.search}`}function vg(){if(typeof window>"u")return;const e=ff?jc:tl();e!==hf&&(hf=e,od=hg(new URL(e,window.location.origin)),Yw=od?.kind==="models"?od.route:null)}function eI(){hf="",vg();for(const e of mf)e()}async function bg(e){if(id)return!1;id=!0;try{for(const t of[...Md].reverse())if(!await t(e))return!1;return!0}finally{id=!1}}function yg(e){return{...window.history.state,openpondNavigationIndex:e}}async function nq(){const e=tl(),t=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:za-1;if(Qi&&t===za){const a=Qi;Qi=null,a();return}if(op===t||Md.size===0){op=null,jc=e,za=t,window.history.replaceState(yg(za),"",e),eI();return}if(t===za)return;if(gc||id){Qi??=()=>{},window.history.go(za-t);return}gc=!0;const n=t-za;try{await new Promise(a=>{Qi=a,window.history.go(-n)}),await bg(e)&&(op=t,window.history.go(n))}finally{gc=!1}}function Sg(){if(ff||typeof window>"u")return;const e=hg(window.location);jc=e?Xw(e):tl(),za=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:0,window.history.replaceState(yg(za),"",jc),window.addEventListener("popstate",nq),ff=!0}function tI(e){return mf.add(e),Sg(),()=>{mf.delete(e)}}function iG(e){return Md.add(e),Sg(),()=>{Md.delete(e)}}async function cG(e){!gc&&await bg(tl())&&e()}function aq(){return h.useSyncExternalStore(tI,()=>(vg(),Yw),()=>null)}function sq(){return h.useSyncExternalStore(tI,()=>(vg(),od),()=>null)}async function Lt(e,t="push"){if(typeof window>"u"||(Sg(),gc))return!1;if(e.kind==="settings"&&!e.returnTo){const a=hg(window.location),s=a?.kind==="models"?wu(a.route):a?.kind==="settings"?a.returnTo:void 0;s&&(e={...e,returnTo:s})}const n=Xw(e);return tl()===n?!0:await bg(n)?(t==="push"&&za++,window.history[t==="replace"?"replaceState":"pushState"](yg(za),"",n),jc=n,eI(),!0):!1}function Fr(e,t="push"){return Lt({kind:"models",route:e},t)}function rq({experience:e="work",beginNewChat:t}){return g.jsx("div",{className:"sidebar-new-task",children:g.jsxs("button",{className:"sidebar-row sidebar-task-row sidebar-new-task-entry",type:"button",onClick:async()=>{await Lt({kind:"chat",sessionId:null})&&t(null)},children:[g.jsx("span",{className:"conversation-source-icon","aria-hidden":"true",children:g.jsx(ku,{size:18})}),g.jsx("span",{children:Qw(e)})]})})}function oq({productArea:e="chat",setSectionMenuOpen:t,setSelectedAppId:n,setSelectedProjectId:a,setSelectedSessionId:s,setView:r,view:i,modelProjects:c=[],modelTrainingActivityByProjectId:l={}}){const u=aq(),p=u?.modelId??null,f=u?.page??"models";function S(){n(null),a(null),s(null),t(null)}async function b(_){await Fr(wa(_,["home","inbox","datasets","graders","experiments"].includes(_)?null:p,{...e==="console"?{area:"console"}:{},...u?.projectId!==void 0?{projectId:u.projectId}:{}}))&&(S(),r("labs"))}async function w(_){await Fr(XU(u??wa(),_||null))&&(S(),r("labs"))}async function C(_){await Lt({kind:"view",view:_})&&(S(),r(_))}const P=p?l[p]??null:null;return g.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[e!=="chat"?g.jsxs(g.Fragment,{children:[["home","inbox","datasets","graders","experiments"].includes(f)?null:g.jsxs("div",{className:"sidebar-model-project-picker",children:[g.jsx("span",{className:"sidebar-nav-group-label",children:"Model"}),g.jsx(ZU,{label:"Model",searchable:c.length>8,value:p??"",options:[{value:"",label:"All models"},...p&&!c.some(_=>_.id===p)?[{value:p,label:"Unavailable model",disabled:!0}]:[],...c.map(_=>({value:_.id,label:_.name}))],onChange:_=>{w(_)}})]}),uf.filter(_=>e==="console"?["home","inbox","datasets","graders","experiments"].includes(_):_!=="home"&&_!=="tasksets"&&_!=="evaluations").map(_=>{const M={"get-started":Dl,home:Jw,inbox:mg,models:AH,datasets:Dl,graders:_b,experiments:rd,tasks:Dl,tasksets:Dl,labeling:rd,rewards:_b,evaluations:rd,runs:qw,versions:sU,serving:yu}[_];return g.jsxs("button",{className:`nav-command ${i==="labs"&&(f===_||_==="runs"&&f==="evaluations")?"active":""}`,"aria-current":i==="labs"&&(f===_||_==="runs"&&f==="evaluations")?"page":void 0,type:"button",onClick:()=>{b(_)},children:[g.jsx(M,{size:16}),g.jsx("span",{children:JU[_]}),_==="runs"&&P?g.jsx("span",{className:"sidebar-running-dot","aria-label":P.label}):null]},_)})]}):null,e==="chat"?g.jsxs(g.Fragment,{children:[g.jsxs("button",{className:`nav-command nav-command-prominent ${i==="scheduled"?"active":""}`,"aria-label":"Workflows",type:"button",onClick:()=>{C("scheduled")},children:[g.jsx(Uw,{size:18}),g.jsx("span",{children:"Workflows"})]}),g.jsxs("button",{className:`nav-command nav-command-prominent ${i==="outputs"?"active":""}`,"aria-label":"Outputs",type:"button",onClick:()=>{C("outputs")},children:[g.jsx(Bw,{size:18}),g.jsx("span",{children:"Outputs"})]}),g.jsxs("button",{className:`nav-command nav-command-prominent ${i==="apps"?"active":""}`,"aria-label":"Apps",type:"button",onClick:()=>{C("apps")},children:[g.jsx(ug,{size:18}),g.jsx("span",{children:"Apps"})]}),g.jsxs("button",{className:`nav-command nav-command-prominent ${i==="projects"?"active":""}`,"aria-label":"Projects",type:"button",onClick:()=>{C("projects")},children:[g.jsx(ig,{size:18}),g.jsx("span",{children:"Projects"})]})]}):null]})}const nI=Bm({chatMode:k(["chat","work"]).optional(),sidebarPresentation:k(["grouped","inbox"]).optional(),notificationMode:k(["all","direct_mentions","none"]).optional(),learningNoticeDismissed:j().optional(),sidebarVisibility:Bm({showCodexChats:j(),onlyRunningTasks:j()}).optional(),scheduledWorkView:k(["calendar","list"]).optional(),editorControlsVisible:j().optional(),voiceNoticeAcknowledged:j().optional(),lessonProgress:ve(o().min(1).max(200),Bm({completed:j(),currentTime:m().finite().nonnegative(),duration:m().finite().positive(),updatedAt:m().finite().nonnegative()})).refine(e=>Object.keys(e).length<=200,"Too many lessons").optional()}),gf={"openpond:last-chat-task-mode":"chatMode","openpond.sidebar.presentation.v1":"sidebarPresentation","openpond.team-chat.notification-mode":"notificationMode","openpond.sidebar.continuous-learning.dismissed.v1":"learningNoticeDismissed","openpond.sidebar-task-visibility.v1":"sidebarVisibility","openpond.scheduled-work.view.v1":"scheduledWorkView","openpond.workspace.editorControlsVisible":"editorControlsVisible","openpond.voice.setupNoticeAcknowledged":"voiceNoticeAcknowledged","openpond.post-training-progress.v1":"lessonProgress"},vf=new Set;let vc=null,qs=null,Ua={},Mc={},ip=!1,cd=0,ai=null,Rb=0;const iq="openpond-client-choices-changed";function xg(){vf.forEach(e=>e()),typeof window<"u"&&window.dispatchEvent(new Event(iq))}function cq(){return ai}function lq(e){return vf.add(e),()=>{vf.delete(e)}}function fi(e){const t=h.useRef(e);t.current=e,h.useEffect(()=>lq(()=>t.current()),[])}async function Pb(e){const t=++Rb,n=await L(e,"/v1/configuration");if(n.clientState?.revision===null){const s=dq();if(Object.keys(s.patch).length){n.clientState=await L(e,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n.clientState.owner,patch:s.patch,importOnly:!0})});for(const r of s.keys)try{window.localStorage.removeItem(r)}catch{}}}if(t!==Rb)return;const a=vc?.serverUrl!==e.serverUrl||vc?.token!==e.token||qs?.owner!==n.clientState?.owner;a&&(cd++,Ua={},Mc={},ai=null),vc=e,(a||(n.clientState?.revision??0)>=(qs?.revision??0))&&(qs=n.clientState),xg()}async function kg(){if(ip||!vc||!qs||!Object.keys(Ua).length)return;ip=!0;const e=Ua,t=vc,n=qs.owner,a=cd;Ua={},Mc=e;try{const s=await L(t,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n,patch:e})});a===cd&&(qs=s,ai=null)}catch(s){a===cd&&(Ua={...e,...Ua},ai=`Preference changes have not been saved. ${s instanceof Error?s.message:String(s)}`)}finally{Mc={},ip=!1,xg(),!ai&&Object.keys(Ua).length&&kg()}}function lG(){ai=null,kg()}const no={getItem(e){const t=gf[e];if(!t)return null;const n={...qs?.value,...Mc,...Ua}[t];return n===void 0?null:typeof n=="string"?n:JSON.stringify(n)},setItem(e,t){if(!qs)return;const n=gf[e];if(!n)throw new Error("Unregistered client preference.");let a;try{a=JSON.parse(t)}catch{a=t}const s=nI.parse({[n]:a});JSON.stringify({...qs.value,...Mc,...Ua}[n])!==JSON.stringify(s[n])&&(Ua={...Ua,...s},xg(),kg())}};function dq(){const e={},t=[];if(typeof window>"u")return{patch:e,keys:t};for(const[n,a]of Object.entries(gf))try{const s=window.localStorage.getItem(n);if(s===null)continue;let r;try{r=JSON.parse(s)}catch{r=s}const i=nI.safeParse({[a]:r});i.success&&(Object.assign(e,i.data),t.push(n))}catch{}return{patch:e,keys:t}}function aI(e){return e.replace(/\s+\(default\)$/i,"").replace(/^(?:openai|anthropic|google|xai|deepseek|qwen|meta-llama)\//i,"").replace(/^gpt-/i,"GPT-")}const ld=5,Nn=15,bf=10,Rt={defaultChatProvider:Kr,subagents:TE(),codexPermissionMode:oh,codexReasoningEffort:ih,openPondCommandAccessMode:Qd,defaultBranchPrefix:"feat/",defaultNewProjectDirectory:"",advancedWorkspaceControls:!1,steerActiveResponses:!0,contextCompaction:{autoEnabled:!0,triggerPercent:85,summaryModel:"same_model"},training:{defaultModelRef:null,creationMode:"customize",autoApproveEvidence:!1},sidebarWidth:332,diffPanelWidth:560,sidebarSectionsCollapsed:{pinned:!1,projects:!1,cloudProjects:!1,chats:!1,savedForLater:!0},editor:{languageServers:"auto",diagnosticsWhileEditing:!0,checkOnSave:!0,languages:{typescript:{mode:"auto",customCommand:""},python:{mode:"auto",customCommand:""},rust:{mode:"auto",customCommand:""}}}},dG={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},sI=[{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"}],cp=[{value:"openpond",label:"OpenPond Chat"},{value:"codex",label:"OpenAI Codex",description:"Codex login"}],uq=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],mq=["openpond","codex","claude-code","grok-build","opencode",...uq],pq=new Set(mq),rI=[{value:rh,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"}],uG=[{value:"default",label:"Default permissions",shortLabel:"Default",description:"Workspace sandbox; asks before crossing boundaries."},{value:"auto-review",label:"Auto-review",description:"Workspace sandbox; reviewer handles eligible approvals."},{value:"full-access",label:"Full access",description:"No sandbox or approval prompts."}],yf=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],fq=[{value:"off",label:"Off"},...yf,{value:"max",label:"Max"}],mG=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],pG=[{value:"auto",label:"Auto",description:"Use installed language servers when available."},{value:"off",label:"Off",description:"Disable editor language servers."}],fG=[{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 wg(e){return e.kind==="local"}function hq(e){return e.kind==="cloud"}function ct(e,t){return`${e}:${t}`}function oI(e){const t=e?.trim();if(!t)return null;const n=t.indexOf(":");if(n<=0)return{kind:"local",id:t};const a=t.slice(0,n),s=t.slice(n+1);return(a==="local"||a==="cloud")&&s?{kind:a,id:s}:{kind:"local",id:t}}function qr(e){return`${e.type}:${e.id}`}function Od(e){const t=e.currentTarget.getBoundingClientRect();return e.clientY<t.top+t.height/2?"before":"after"}function $d(e,t,n,a="before"){if(t===n)return e;const s=e.filter(i=>i!==t),r=s.indexOf(n);return r===-1?e:(s.splice(a==="after"?r+1:r,0,t),s)}function Tb(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function gq(e,t){if(!t)return e;const n=new Map(e.map(r=>[r.key,r])),a=t.map(r=>n.get(r)).filter(r=>!!r),s=new Set(a.map(r=>r.key));return[...a,...e.filter(r=>!s.has(r.key))]}function Ig(e,t){return e?.statuses?.[t]??null}function iI(e,t){return e?.providers?.[t]??null}function _g(e,t){return e?.modelCaches?.[t]??null}function vq(e){const t=[e.contextWindow?`${Math.round(e.contextWindow/1e3)}K context`:"",e.capabilities.reasoning?"reasoning":"",e.source].filter(Boolean);return{value:e.id,label:aI(e.displayName||e.id),description:t.join(" · ")||void 0}}function bq(e){return e==="openpond"?sI:e==="codex"||e==="openai"?rI:[]}function yq(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 Sq(e){return xc(e)||pq.has(e)}function Sf(e,t={}){if(!e)return t.localOnly,cp;const n=t.includeUnavailable??!1,a=t.enabledOnly??!1,s=[];for(const r of Object.keys(e.statuses)){if(!xc(r)&&!["openpond","codex","openai","claude-code","grok-build","opencode","custom-openai-compatible"].includes(r)||!Sq(r)||t.localOnly&&r==="openpond")continue;const i=Ig(e,r);i&&(!n&&(r==="codex"&&!i.available&&!i.credential.connected||r!=="openpond"&&r!=="codex"&&!i.enabled)||a&&r!=="openpond"&&!i.enabled||a&&r==="codex"&&!i.available&&!i.credential.connected||s.push({value:r,label:r==="openpond"?"OpenPond Chat":i.displayName,description:r==="openpond"?void 0:i.available?"Connected":i.credential.connected?"Configured":i.routing.localByok?"Set up key":i.enabled?"Enabled":void 0}))}return s.length>0?s:cp}function Oc(e,t){const a=(_g(t,e)?.models??[]).filter(c=>e!=="openpond"||c.id!==ii).map(vq),s=iI(t,e),r=[...s?.modelOverrides??[],s?.defaultModel].filter(c=>!!c?.trim()&&(e!=="openpond"||c!==ii)).map(c=>({value:c,label:aI(c)})),i=e==="openpond"&&a.length>0?[]:bq(e);return yq([...a,...r,...i])}function cI(e,t,n){if(e!=="openpond")return yf;const a=_g(n,e)?.models.find(r=>r.id===t)?.capabilities;if(!a?.reasoningEfforts.length)return yf;const s=new Set(a.reasoningEfforts);return fq.filter(r=>s.has(r.value))}function xq(e,t,n){const a=cI(e,t,n),s=e==="openpond"&&(t==="gpt-6-luna"||t==="gpt-6-sol"||t==="claude-opus-5-5")?"medium":"high";return a.some(r=>r.value===s)?s:a[0]?.value??"high"}function kq(e,t,n,a){return cI(e,t,a).some(s=>s.value===n)?n:xq(e,t,a)}function wq(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const s=_g(n,e)?.models.find(r=>r.id===a);return s?!!s.capabilities.reasoning:Oc(e,n).some(r=>r.value===a&&/\breasoning\b/i.test(r.description??""))}function Nd(e,t){const n=iI(t,e)?.defaultModel?.trim();if(n)return n;const a=Ig(t,e)?.defaultModel?.trim();if(a)return a;const s=Oc(e,t)[0]?.value?.trim();return s||(e==="codex"?rh:e==="openpond"?ii:"")}function Sr(e,t,n){const a=t?.trim();if(xc(e))return a??"";if(a&&["opencode","grok-build","claude-code"].includes(e))return a;if(e==="codex"&&(a==="codex-default"||a==="gpt-5.5"))return rh;const s=Oc(e,n);return a&&s.some(r=>r.value===a)||a&&e!=="codex"&&s.length===0&&!n?a:Nd(e,n)}function lI(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:Sr(n,e.modelRef?.modelId,t)}}function Cg(e,t,n){return Sr(e,t,n)||void 0}function Da(e,t,n){const a=Cg(e,t,n);return a?{providerId:e,modelId:a}:void 0}function Ab(e){return e==="full-access"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function Sa(e){const t=e?.defaultChatProvider??Rt.defaultChatProvider;return{defaultChatProvider:t,defaultChatModel:Sr(t,e?.defaultChatModel),subagents:kc.parse(e?.subagents??Rt.subagents),codexPermissionMode:e?.codexPermissionMode??Rt.codexPermissionMode,codexReasoningEffort:e?.codexReasoningEffort??Rt.codexReasoningEffort,openPondCommandAccessMode:e?.openPondCommandAccessMode??Rt.openPondCommandAccessMode,defaultBranchPrefix:dI(e?.defaultBranchPrefix),defaultNewProjectDirectory:e?.defaultNewProjectDirectory??Rt.defaultNewProjectDirectory,defaultTeamId:e?.defaultTeamId?.trim()||null,advancedWorkspaceControls:e?.advancedWorkspaceControls??Rt.advancedWorkspaceControls,steerActiveResponses:e?.steerActiveResponses??Rt.steerActiveResponses,contextCompaction:{autoEnabled:e?.contextCompaction?.autoEnabled??Rt.contextCompaction.autoEnabled,triggerPercent:e?.contextCompaction?.triggerPercent??Rt.contextCompaction.triggerPercent,summaryModel:e?.contextCompaction?.summaryModel??Rt.contextCompaction.summaryModel},training:{defaultModelRef:e?.training?.defaultModelRef??Rt.training.defaultModelRef,creationMode:e?.training?.creationMode??Rt.training.creationMode,autoApproveEvidence:e?.training?.autoApproveEvidence??Rt.training.autoApproveEvidence},sidebarWidth:e?.sidebarWidth??Rt.sidebarWidth,diffPanelWidth:e?.diffPanelWidth??Rt.diffPanelWidth,sidebarSectionsCollapsed:{pinned:e?.sidebarSectionsCollapsed?.pinned??Rt.sidebarSectionsCollapsed.pinned,projects:e?.sidebarSectionsCollapsed?.projects??Rt.sidebarSectionsCollapsed.projects,cloudProjects:e?.sidebarSectionsCollapsed?.cloudProjects??Rt.sidebarSectionsCollapsed.cloudProjects,chats:e?.sidebarSectionsCollapsed?.chats??Rt.sidebarSectionsCollapsed.chats,savedForLater:e?.sidebarSectionsCollapsed?.savedForLater??Rt.sidebarSectionsCollapsed.savedForLater},editor:{languageServers:e?.editor?.languageServers??Rt.editor.languageServers,diagnosticsWhileEditing:e?.editor?.diagnosticsWhileEditing??Rt.editor.diagnosticsWhileEditing,checkOnSave:e?.editor?.checkOnSave??Rt.editor.checkOnSave,languages:{typescript:{mode:e?.editor?.languages?.typescript?.mode??Rt.editor.languages.typescript.mode,customCommand:e?.editor?.languages?.typescript?.customCommand??Rt.editor.languages.typescript.customCommand},python:{mode:e?.editor?.languages?.python?.mode??Rt.editor.languages.python.mode,customCommand:e?.editor?.languages?.python?.customCommand??Rt.editor.languages.python.customCommand},rust:{mode:e?.editor?.languages?.rust?.mode??Rt.editor.languages.rust.mode,customCommand:e?.editor?.languages?.rust?.customCommand??Rt.editor.languages.rust.customCommand}}}}}function dI(e){const t=e?.trim()??Rt.defaultBranchPrefix;if(!t)return"";const a=t.toLowerCase().replace(/[^a-z0-9._/-]+/g,"-").replace(/\/{2,}/g,"/").replace(/^-+/,"").slice(0,48).split("/").map(s=>s.replace(/^-+|-+$/g,"")).filter(Boolean).join("/");return a?`${a}/`:""}function hG(e,t){return e==="openpond"?"OpenPond Chat":Ig(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function gG(e,t,n){if(n){const a=Oc(n,t).find(s=>s.value===e);if(a)return a.label}if(t)for(const a of Object.keys(t.statuses)){const s=Oc(a,t).find(r=>r.value===e);if(s)return s.label}return[...sI,...rI].find(a=>a.value===e)?.label??e}function Iq(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function _q(e){return e.experience==="chat"?"Chat":"Work"}const Rg="taskDraft";function uI(e){if(e?.experience!=="work")return null;const t=e.metadata?.[Rg];if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t.prompt;return typeof n=="string"&&n.trim()?n:null}function $c(e){return uI(e)!==null}function Cq(e){return(e.split(/\r?\n/u).map(n=>n.trim()).find(Boolean)||"Task draft").slice(0,64)}function lp(e,t,n=new Date().toISOString()){const a={version:1,prompt:t,savedAt:n};return{...e??{},[Rg]:a}}function Rq(e){const t={...e??{}};return delete t[Rg],t}function Ko(e){const t=Ll(e.metadata?.trainingTasksetId)??Ll(e.metadata?.tasksetId);return t?{id:t,name:Ll(e.metadata?.trainingTasksetName)??Ll(e.metadata?.tasksetName)??Pq(t)}:null}function Pq(e){const n=e.replace(/[-_][a-f0-9]{8,}$/i,"").replace(/^(?:benchmark[-_])?taskset[-_]/i,"").replace(/^benchmark[-_]/i,"").split(/[-_]+/).filter(Boolean);return n.length===0?"Taskset":n.map(a=>/^[A-Z0-9]{2,}$/.test(a)?a:`${a.charAt(0).toUpperCase()}${a.slice(1)}`).join(" ")}function Ll(e){return typeof e=="string"&&e.trim()?e.trim():null}const Tq="codex_history_";function Gt(e){return!!e?.startsWith(Tq)}function mI(e){const t=[],n=new Set;for(const a of e)for(const s of[a.workspacePath,a.path]){const r=Iu(s);if(!r)continue;const i=`${a.id}:${r}`;n.has(i)||(n.add(i),t.push({projectId:a.id,path:r}))}return t.sort((a,s)=>s.path.length-a.path.length)}function Aq(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=pI(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"||!fI(e))return null;const s=Iu(e.cwd);if(!s)return null;for(const r of n)if(Pg(s,r.path))return r.projectId;return null}function Eb(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return ct("local",e.localProjectId);if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return ct("local",e.workspaceId);if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const r=pI(e.cwd,n);if(r)return ct("local",r)}if(e.cloudProjectId&&a.has(e.cloudProjectId))return ct("cloud",e.cloudProjectId);if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!fI(e))return null;const s=Iu(e.cwd);if(!s)return null;for(const r of n)if(Pg(s,r.path))return ct("local",r.projectId);return null}function pI(e,t){const n=Iu(e);if(!n)return null;for(const a of t)if(Pg(n,a.path))return a.projectId;return null}function fI(e){return e.workspaceKind==="local_project"||e.provider==="codex"||Gt(e.id)}function Iu(e){const t=e?.trim();if(!t)return null;let n=t.replace(/^file:\/\/+/i,"/").replace(/\\/g,"/").replace(/\/+/g,"/");return/^[a-z]:/i.test(n)&&(n=n[0].toUpperCase()+n.slice(1)),n=n.replace(/\/+$/g,""),n||"/"}function Pg(e,t){const n=jb(e),a=jb(t);return n===a||n.startsWith(`${a}/`)}function jb(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}const Mb=[{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"}],Eq=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function dp(e){const t=[];if(e.filter==="done")t.push(...e.doneSessions.filter(s=>!Ko(s)));else if(e.filter==="all")t.push(...e.activeSessions.filter(s=>!Ko(s)),...e.doneSessions.filter(s=>!Ko(s)));else if(e.filter==="tasksets")t.push(...e.activeSessions.filter(s=>Ob(s,e.selectedTasksetId)),...e.doneSessions.filter(s=>Ob(s,e.selectedTasksetId)));else for(const s of e.activeSessions)Ko(s)||(e.filter==="active"?s.savedForLater||t.push(s):e.filter==="in_progress"?!s.savedForLater&&e.inProgressSessionIds.has(s.id)&&t.push(s):e.filter==="pinned"?s.pinned&&!s.savedForLater&&t.push(s):e.filter==="saved_for_later"&&s.savedForLater&&t.push(s));const n=t.filter(s=>dd(s,{inProgressSessionIds:e.inProgressSessionIds,onlyRunningTasks:e.onlyRunningTasks,showCodexChats:e.showCodexChats})),a=e.previewSessionIds?new Map(e.previewSessionIds.map((s,r)=>[s,r])):null;return e.sort==="recent"?n.sort((s,r)=>Db(s,r,a)):n.sort((s,r)=>{const i=a?.get(s.id),c=a?.get(r.id);if(i!==void 0||c!==void 0){if(i===void 0)return 1;if(c===void 0)return-1;if(i!==c)return i-c}return s.order!==r.order?s.order-r.order:Db(s,r)})}function dd(e,t){return t.showCodexChats===!1&&(e.provider==="codex"||Gt(e.id))?!1:!t.onlyRunningTasks||t.inProgressSessionIds.has(e.id)}function Ob(e,t){const n=Ko(e);return!!(n&&(!t||n.id===t))}function $b(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 Nb(e,t,n){const a=new Set(t);let s=0;return e.map(r=>{if(!a.has(r))return r;const i=n[s];return s+=1,i??r})}function Db(e,t,n=null){const a=Wo(e),s=Wo(t);if(a!==s)return a?-1:1;if(a&&s){const i=n?.get(e.id),c=n?.get(t.id);if(i!==void 0||c!==void 0){if(i===void 0)return 1;if(c===void 0)return-1;if(i!==c)return i-c}if(e.order!==t.order)return e.order-t.order}const r=Date.parse(t.updatedAt)-Date.parse(e.updatedAt);return r!==0?r:e.title.localeCompare(t.title)}function Wo(e){return e.pinned&&!e.savedForLater&&!e.archived}const zl={showCodexChats:!0,onlyRunningTasks:!1},hI="openpond.sidebar-task-visibility.v1";function Lb(e=gI()){try{const t=e?.getItem(hI);if(!t)return zl;const n=JSON.parse(t);return{showCodexChats:typeof n.showCodexChats=="boolean"?n.showCodexChats:zl.showCodexChats,onlyRunningTasks:typeof n.onlyRunningTasks=="boolean"?n.onlyRunningTasks:zl.onlyRunningTasks}}catch{return zl}}function zb(e,t=gI()){try{t?.setItem(hI,JSON.stringify(e))}catch{}}function gI(){return typeof window>"u"?null:no}function vI(e){return`${e.kind}:${e.id}`}function Nc(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function jq(e){return{kind:"session",id:e}}function Mq(e){return{kind:"project",id:e}}function Oq(e){return{kind:"draft",id:e}}function $q(e){return e.selectedSessionId?jq(e.selectedSessionId):e.selectedProjectId?Mq(e.selectedProjectId):Oq(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function Nq(e){if(!e.previousScope||e.previousScope.kind!=="draft"||e.activeScope.kind!=="session")return[...e.tabs];if(Nc(e.previousScope,e.activeScope))return[...e.tabs];const t=e.now??Date.now();return e.tabs.map(n=>Nc(n.scope,e.previousScope)?{...n,scope:e.activeScope,updatedAt:t}:n)}function vG(e,t){return e.filter(n=>Nc(n.scope,t))}function bG(e,t){return!!(e&&Nc(e.scope,t))}function Dq(e){const t={};for(const n of e){const a=vI(n.scope),s=t[a]??{scope:n.scope,tabCount:0,runningCount:0,failedCount:0,lastExitCode:null,status:"none"};s.tabCount+=1,n.commandStatus==="running"&&(s.runningCount+=1),(n.commandStatus==="failed"||n.status==="error")&&(s.failedCount+=1),n.lastExitCode!==null&&(s.lastExitCode=n.lastExitCode),s.status=zq(s.status,n.status,n.commandStatus),t[a]=s}return t}function Lq(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 zq(e,t,n){return n==="running"?"running":e==="running"?e:n==="failed"||t==="error"?"failed":e==="failed"?e:n==="success"?e==="none"||e==="unknown"||e==="idle"?"success":e:n==="idle"?e==="none"||e==="unknown"?"idle":e:e==="none"?"unknown":e}function bI(e,t){if(!e)return t?.path??"Use files on this machine";if(e.error)return"status unavailable";if(!e.initialized)return"not checked out";const a=[e.currentBranch??t?.branch??e.defaultBranch??"no branch"],s=Uq(e),r=t?.linkedCloudSourceKnown===!1&&!!e.headCommit;return s?a.push(s):r?a.push("upload required"):e.diverged?(e.ahead>0&&a.push(rr("ahead",e.ahead)),e.behind>0&&a.push(rr("behind",e.behind)),a.push("diverged")):(e.ahead>0&&a.push(rr("ahead",e.ahead)),e.behind>0&&a.push(rr("behind",e.behind))),e.changedFilesCount>0?a.push(`${e.changedFilesCount} changed`):e.dirty&&a.push("dirty"),e.untrackedFilesCount>0&&a.push(`${e.untrackedFilesCount} untracked`),a.length===1&&a.push("synced"),a.join(" / ")}function yI(e,t,n,a={}){const s=e?.linkedSandboxProject??null;if(!s?.projectId&&!t)return"upload required";if(s?.projectId&&a.cloudLinkTrusted===!1)return"uploaded to a different account";const r=s?.defaultBranch??t?.defaultBranch??"main",i=s?.manifestHash??null,c=e?.sandboxTemplate?.manifestHash??null,l=s?.syncedAt??t?.syncedAt??null,u=!!(i&&c&&i!==c),p=!!(s?.projectId&&n?.headCommit&&!s.lastUploadedCommit),f=qq(n);return f?`${r} / ${f}`:p?`${r} / upload required`:`${r} / ${u||!l?"needs sync":"setup ready"}`}function Hq(e,t,n={}){if(!e)return"select a local project";if(e.linkedSandboxProject?.projectId&&n.cloudLinkTrusted===!1)return"sync to this account";if(!t)return e.linkedSandboxProject?"sync source to cloud":"push local source to cloud";if(t.error)return"repo status unavailable";if(!t.initialized)return"local repo unavailable";const a=[],s=t.aheadOfLinkedSource>0?t.aheadOfLinkedSource:t.ahead;return e.linkedSandboxProject?.projectId||a.push("upload required"),e.linkedSandboxProject?.projectId&&t.headCommit&&!e.linkedSandboxProject.lastUploadedCommit&&a.push("upload required"),s>0&&a.push(SI(s)),t.linkedSourceHeadCommit&&t.headCommit&&t.linkedSourceHeadCommit!==t.headCommit&&t.linkedSourceComparisonError&&s===0&&a.push("source changed"),t.changedFilesCount>0&&a.push(`${t.changedFilesCount} changed file${t.changedFilesCount===1?"":"s"}`),t.untrackedFilesCount>0&&a.push(`${t.untrackedFilesCount} untracked skipped`),a.length>0?a.join(" / "):"nothing to upload"}function Uq(e){return e.linkedSourceHeadCommit?e.divergedFromLinkedSource?"diverged":e.aheadOfLinkedSource>0?rr("local ahead",e.aheadOfLinkedSource):e.behindLinkedSource>0?rr("cloud ahead",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"sync unknown":null:null}function qq(e){return e?.linkedSourceHeadCommit?e.dirty?"local dirty files not in cloud":e.divergedFromLinkedSource?"diverged from local":e.aheadOfLinkedSource>0?rr("cloud behind local",e.aheadOfLinkedSource):e.behindLinkedSource>0?rr("cloud ahead local",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"source check unavailable":"synced":null}function rr(e,t){return`${e} by ${SI(t)}`}function SI(e){return`${e} commit${e===1?"":"s"}`}function Bq({size:e=14,className:t}){return g.jsxs("svg",{className:["lucide lucide-cloud-upload",t??""].filter(Boolean).join(" "),xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[g.jsx("path",{d:"M12 13v8"}),g.jsx("path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"}),g.jsx("path",{d:"m8 17 4-4 4 4"})]})}function xI({kind:e,linkedCloud:t=!1,open:n=!1,className:a,baseSize:s=15}){const r=e==="cloud"?"cloud":n?"folder-open":"folder";return g.jsx("span",{className:["project-kind-icon",e,t?"linked-cloud":"",a??""].filter(Boolean).join(" "),"aria-hidden":"true",children:g.jsxs("svg",{className:`lucide lucide-${r} project-kind-icon-svg`,xmlns:"http://www.w3.org/2000/svg",width:s,height:s,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e==="cloud"?g.jsx(Kq,{}):n?g.jsx(Vq,{}):g.jsx(Fq,{}),t&&e==="local"?g.jsx(Wq,{}):null]})})}function Fq(){return g.jsx("path",{className:"project-kind-icon-base",d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}function Vq(){return g.jsx("path",{className:"project-kind-icon-base",d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"})}function Kq(){return g.jsx("path",{className:"project-kind-icon-base",d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"})}function Wq(){return g.jsxs("g",{className:"project-kind-icon-cloud-badge",children:[g.jsx("circle",{cx:"18",cy:"17",r:"5"}),g.jsx("path",{d:"M20.4 18.6h-4.2a2.2 2.2 0 1 1 2.08-2.9h.88a1.45 1.45 0 1 1 1.24 2.9Z"})]})}var Dd=g_();function Gq({title:e,pinned:t,savedForLater:n,archived:a,onRename:s,onTogglePin:r,onToggleSaveForLater:i,onDockRight:c,onArchive:l}){const u=h.useRef(null),p=h.useRef(null),[f,S]=h.useState(null),b=[...s?[{label:"Rename",Icon:ku,action:s}]:[],{label:t?"Unpin":"Pin",Icon:t?lg:cg,action:r},...i?[{label:n?"Return to active":"Save for later",Icon:n?Hw:zw,action:i}]:[],...c?[{label:"Open in right panel",Icon:df,action:c}]:[],{label:a?"Reopen":"Mark done",Icon:a?jH:ds,action:l}];function w(C=!1){S(null),C&&u.current?.focus()}return h.useEffect(()=>{if(!f)return;p.current?.querySelector("button")?.focus();const C=_=>{!p.current?.contains(_.target)&&!u.current?.contains(_.target)&&S(null)},P=()=>S(null);return document.addEventListener("pointerdown",C),window.addEventListener("resize",P),()=>{document.removeEventListener("pointerdown",C),window.removeEventListener("resize",P)}},[f]),g.jsxs(g.Fragment,{children:[g.jsx("div",{className:`sidebar-row-actions sidebar-task-menu-trigger${f?" is-open":""}`,children:g.jsx("button",{ref:u,type:"button",className:"sidebar-row-action","aria-label":`More actions for task ${e}`,"aria-haspopup":"menu","aria-expanded":!!f,draggable:!1,onDoubleClick:C=>C.stopPropagation(),onClick:C=>{if(C.stopPropagation(),f){w(!0);return}const P=C.currentTarget.getBoundingClientRect();S({left:Math.max(8,Math.min(P.right-192,window.innerWidth-200)),top:Math.max(8,Math.min(P.bottom+4,window.innerHeight-(b.length*32+17)))})},children:g.jsx(Xc,{size:16})})}),f&&Dd.createPortal(g.jsx("div",{ref:p,role:"menu","aria-label":`Actions for ${e}`,className:"sidebar-task-menu",style:f,onClick:C=>C.stopPropagation(),onDoubleClick:C=>C.stopPropagation(),onBlur:C=>{C.currentTarget.contains(C.relatedTarget)||w()},onKeyDown:C=>{C.stopPropagation();const P=Array.from(C.currentTarget.querySelectorAll("button")),_=P.indexOf(document.activeElement);if(C.key==="Escape"&&(C.preventDefault(),w(!0)),["ArrowDown","ArrowUp","Home","End"].includes(C.key)){C.preventDefault();const M=C.key==="Home"?0:C.key==="End"?P.length-1:(_+(C.key==="ArrowDown"?1:-1)+P.length)%P.length;P[M]?.focus()}},children:b.map(({label:C,Icon:P,action:_},M)=>g.jsxs("button",{type:"button",role:"menuitem",className:M===b.length-1?"task-menu-done":void 0,onClick:()=>{w(!0),_()},children:[g.jsx(P,{size:15}),C]},C))}),document.body)]})}function Zq({session:e,onSave:t,onClose:n}){const[a,s]=h.useState(e.title),r=h.useRef(null);h.useEffect(()=>{const l=r.current;l&&(l.focus(),l.select())},[]),h.useEffect(()=>{function l(u){u.key==="Escape"&&n()}return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[n]);function i(){const l=a.trim();l&&(t(l),n())}function c(l){l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),i())}return g.jsx("div",{className:"git-dialog-backdrop rename-chat-backdrop",role:"presentation",onMouseDown:n,children:g.jsxs("section",{className:"git-dialog rename-chat-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"rename-chat-title",onMouseDown:l=>l.stopPropagation(),children:[g.jsx("h2",{id:"rename-chat-title",children:"Rename chat"}),g.jsx("textarea",{ref:r,className:"rename-chat-input",value:a,rows:1,maxLength:200,onChange:l=>s(l.target.value),onKeyDown:c,"aria-label":"Chat title"}),g.jsxs("div",{className:"git-dialog-footer",children:[g.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:n,children:"Cancel"}),g.jsx("button",{type:"button",className:"git-dialog-primary",autoFocus:!0,onClick:i,disabled:!a.trim(),children:"Save"})]})]})})}const Jq=24;function Qq({title:e}){const t=h.useRef(e),[n,a]=h.useState(e);return h.useEffect(()=>{const s=t.current;if(t.current=e,!e){a("");return}if(s||window.matchMedia("(prefers-reduced-motion: reduce)").matches){a(e);return}const r=Array.from(e);let i=0;a("");const c=window.setInterval(()=>{i+=1,a(r.slice(0,i).join("")),i>=r.length&&window.clearInterval(c)},Jq);return()=>window.clearInterval(c)},[e]),g.jsx("span",{className:"sidebar-task-title-text","aria-label":e||"New task",children:n||"New task"})}const Yq="/";function ea(e){return`${Yq}${e.replace(/^\.?\//,"")}`}const Tg=ea("openpond-icon.png"),Xq=ea("openpond-wordlogo-white.png"),yG=ea("tutorials/what-is-an-openpond-agent-poster.png"),SG=ea("tutorials/what-is-an-openpond-agent.vtt"),xG=ea("tutorials/how-to-make-an-agent-poster.png"),kG=ea("tutorials/how-to-make-an-agent.vtt");function wG(e){return ea(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function IG(e){return ea(`tutorials/how-to-make-an-agent-${e}.vtt`)}const Hb={github:ea("connected-apps/github.svg"),google:ea("connected-apps/google.svg"),microsoft_teams:ea("connected-apps/microsoft.svg"),mcp:ea("connected-apps/openpond-mcp.svg"),slack:ea("connected-apps/slack.svg"),x:ea("connected-apps/x.svg")};function _G(e){return Hb[e]??Hb.mcp}const eB={codex:"Codex","claude-code":"Claude Code",opencode:"OpenCode","grok-build":"Grok Build"};function tB({session:e}){const t=eB[e.provider],n=t??(xc(e.provider)?typeof e.metadata?.acpAgentName=="string"?e.metadata.acpAgentName:"ACP agent":e.provider==="openpond"?"OpenPond":e.provider);return g.jsx("span",{className:"conversation-source-icon",role:"img","aria-label":n,title:n,children:t?g.jsx("img",{src:`/agent-sources/${e.provider}.svg`,alt:""}):e.provider==="openpond"?g.jsx("img",{src:Tg,alt:""}):xc(e.provider)?g.jsx(Ib,{size:15,"aria-hidden":"true"}):e.metadata?.nativeSource?g.jsx(UU,{size:15,"aria-hidden":"true"}):e.provider==="openai"?g.jsx(Ib,{size:15,"aria-hidden":"true"}):g.jsx(xu,{size:15,"aria-hidden":"true"})})}var ud={exports:{}},nB=ud.exports,Ub;function aB(){return Ub||(Ub=1,(function(e,t){(function(n,a){e.exports=a()})(nB,(function(){var n=1e3,a=6e4,s=36e5,r="millisecond",i="second",c="minute",l="hour",u="day",p="week",f="month",S="quarter",b="year",w="date",C="Invalid Date",P=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,_=/\[([^\]]+)]|YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(ee){var H=["th","st","nd","rd"],F=ee%100;return"["+ee+(H[(F-20)%10]||H[F]||H[0])+"]"}},E=function(ee,H,F){var J=String(ee);return!J||J.length>=H?ee:""+Array(H+1-J.length).join(F)+ee},T={s:E,z:function(ee){var H=-ee.utcOffset(),F=Math.abs(H),J=Math.floor(F/60),K=F%60;return(H<=0?"+":"-")+E(J,2,"0")+":"+E(K,2,"0")},m:function ee(H,F){if(H.date()<F.date())return-ee(F,H);var J=12*(F.year()-H.year())+(F.month()-H.month()),K=H.clone().add(J,f),B=F-K<0,ne=H.clone().add(J+(B?-1:1),f);return+(-(J+(F-K)/(B?K-ne:ne-K))||0)},a:function(ee){return ee<0?Math.ceil(ee)||0:Math.floor(ee)},p:function(ee){return{M:f,y:b,w:p,d:u,D:w,h:l,m:c,s:i,ms:r,Q:S}[ee]||String(ee||"").toLowerCase().replace(/s$/,"")},u:function(ee){return ee===void 0}},y="en",I={};I[y]=M;var R="$isDayjsObject",O=function(ee){return ee instanceof Y||!(!ee||!ee[R])},z=function ee(H,F,J){var K;if(!H)return y;if(typeof H=="string"){var B=H.toLowerCase();I[B]&&(K=B),F&&(I[B]=F,K=B);var ne=H.split("-");if(!K&&ne.length>1)return ee(ne[0])}else{var G=H.name;I[G]=H,K=G}return!J&&K&&(y=K),K||!J&&y},$=function(ee,H){if(O(ee))return ee.clone();var F=typeof H=="object"?H:{};return F.date=ee,F.args=arguments,new Y(F)},V=T;V.l=z,V.i=O,V.w=function(ee,H){return $(ee,{locale:H.$L,utc:H.$u,x:H.$x,$offset:H.$offset})};var Y=(function(){function ee(F){this.$L=z(F.locale,null,!0),this.parse(F),this.$x=this.$x||F.x||{},this[R]=!0}var H=ee.prototype;return H.parse=function(F){this.$d=(function(J){var K=J.date,B=J.utc;if(K===null)return new Date(NaN);if(V.u(K))return new Date;if(K instanceof Date)return new Date(K);if(typeof K=="string"&&!/Z$/i.test(K)){var ne=K.match(P);if(ne){var G=ne[2]-1||0,te=(ne[7]||"0").substring(0,3);return B?new Date(Date.UTC(ne[1],G,ne[3]||1,ne[4]||0,ne[5]||0,ne[6]||0,te)):new Date(ne[1],G,ne[3]||1,ne[4]||0,ne[5]||0,ne[6]||0,te)}}return new Date(K)})(F),this.init()},H.init=function(){var F=this.$d;this.$y=F.getFullYear(),this.$M=F.getMonth(),this.$D=F.getDate(),this.$W=F.getDay(),this.$H=F.getHours(),this.$m=F.getMinutes(),this.$s=F.getSeconds(),this.$ms=F.getMilliseconds()},H.$utils=function(){return V},H.isValid=function(){return this.$d.toString()!==C},H.isSame=function(F,J){var K=$(F);return this.startOf(J)<=K&&K<=this.endOf(J)},H.isAfter=function(F,J){return $(F)<this.startOf(J)},H.isBefore=function(F,J){return this.endOf(J)<$(F)},H.$g=function(F,J,K){return V.u(F)?this[J]:this.set(K,F)},H.unix=function(){return Math.floor(this.valueOf()/1e3)},H.valueOf=function(){return this.$d.getTime()},H.startOf=function(F,J){var K=this,B=!!V.u(J)||J,ne=V.p(F),G=function(je,De){var He=V.w(K.$u?Date.UTC(K.$y,De,je):new Date(K.$y,De,je),K);return B?He:He.endOf(u)},te=function(je,De){return V.w(K.toDate()[je].apply(K.toDate("s"),(B?[0,0,0,0]:[23,59,59,999]).slice(De)),K)},oe=this.$W,be=this.$M,me=this.$D,Re="set"+(this.$u?"UTC":"");switch(ne){case b:return B?G(1,0):G(31,11);case f:return B?G(1,be):G(0,be+1);case p:var Q=this.$locale().weekStart||0,xe=(oe<Q?oe+7:oe)-Q;return G(B?me-xe:me+(6-xe),be);case u:case w:return te(Re+"Hours",0);case l:return te(Re+"Minutes",1);case c:return te(Re+"Seconds",2);case i:return te(Re+"Milliseconds",3);default:return this.clone()}},H.endOf=function(F){return this.startOf(F,!1)},H.$set=function(F,J){var K,B=V.p(F),ne="set"+(this.$u?"UTC":""),G=(K={},K[u]=ne+"Date",K[w]=ne+"Date",K[f]=ne+"Month",K[b]=ne+"FullYear",K[l]=ne+"Hours",K[c]=ne+"Minutes",K[i]=ne+"Seconds",K[r]=ne+"Milliseconds",K)[B],te=B===u?this.$D+(J-this.$W):J;if(B===f||B===b){var oe=this.clone().set(w,1);oe.$d[G](te),oe.init(),this.$d=oe.set(w,Math.min(this.$D,oe.daysInMonth())).$d}else G&&this.$d[G](te);return this.init(),this},H.set=function(F,J){return this.clone().$set(F,J)},H.get=function(F){return this[V.p(F)]()},H.add=function(F,J){var K,B=this;F=Number(F);var ne=V.p(J),G=function(be){var me=$(B);return V.w(me.date(me.date()+Math.round(be*F)),B)};if(ne===f)return this.set(f,this.$M+F);if(ne===b)return this.set(b,this.$y+F);if(ne===u)return G(1);if(ne===p)return G(7);var te=(K={},K[c]=a,K[l]=s,K[i]=n,K)[ne]||1,oe=this.$d.getTime()+F*te;return V.w(oe,this)},H.subtract=function(F,J){return this.add(-1*F,J)},H.format=function(F){var J=this,K=this.$locale();if(!this.isValid())return K.invalidDate||C;var B=F||"YYYY-MM-DDTHH:mm:ssZ",ne=V.z(this),G=this.$H,te=this.$m,oe=this.$M,be=K.weekdays,me=K.months,Re=K.meridiem,Q=function(De,He,Ie,Me){return De&&(De[He]||De(J,B))||Ie[He].slice(0,Me)},xe=function(De){return V.s(G%12||12,De,"0")},je=Re||function(De,He,Ie){var Me=De<12?"AM":"PM";return Ie?Me.toLowerCase():Me};return B.replace(_,(function(De,He){return He||(function(Ie){switch(Ie){case"YY":return String(J.$y).slice(-2);case"YYYY":return V.s(J.$y,4,"0");case"M":return oe+1;case"MM":return V.s(oe+1,2,"0");case"MMM":return Q(K.monthsShort,oe,me,3);case"MMMM":return Q(me,oe);case"D":return J.$D;case"DD":return V.s(J.$D,2,"0");case"d":return String(J.$W);case"dd":return Q(K.weekdaysMin,J.$W,be,2);case"ddd":return Q(K.weekdaysShort,J.$W,be,3);case"dddd":return be[J.$W];case"H":return String(G);case"HH":return V.s(G,2,"0");case"h":return xe(1);case"hh":return xe(2);case"a":return je(G,te,!0);case"A":return je(G,te,!1);case"m":return String(te);case"mm":return V.s(te,2,"0");case"s":return String(J.$s);case"ss":return V.s(J.$s,2,"0");case"SSS":return V.s(J.$ms,3,"0");case"Z":return ne}return null})(De)||ne.replace(":","")}))},H.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},H.diff=function(F,J,K){var B,ne=this,G=V.p(J),te=$(F),oe=(te.utcOffset()-this.utcOffset())*a,be=this-te,me=function(){return V.m(ne,te)};switch(G){case b:B=me()/12;break;case f:B=me();break;case S:B=me()/3;break;case p:B=(be-oe)/6048e5;break;case u:B=(be-oe)/864e5;break;case l:B=be/s;break;case c:B=be/a;break;case i:B=be/n;break;default:B=be}return K?B:V.a(B)},H.daysInMonth=function(){return this.endOf(f).$D},H.$locale=function(){return I[this.$L]},H.locale=function(F,J){if(!F)return this.$L;var K=this.clone(),B=z(F,J,!0);return B&&(K.$L=B),K},H.clone=function(){return V.w(this.$d,this)},H.toDate=function(){return new Date(this.valueOf())},H.toJSON=function(){return this.isValid()?this.toISOString():null},H.toISOString=function(){return this.$d.toISOString()},H.toString=function(){return this.$d.toUTCString()},ee})(),se=Y.prototype;return $.prototype=se,[["$ms",r],["$s",i],["$m",c],["$H",l],["$W",u],["$M",f],["$y",b],["$D",w]].forEach((function(ee){se[ee[1]]=function(H){return this.$g(H,ee[0],ee[1])}})),$.extend=function(ee,H){return ee.$i||(ee(H,Y,$),ee.$i=!0),$},$.locale=z,$.isDayjs=O,$.unix=function(ee){return $(1e3*ee)},$.en=I[y],$.Ls=I,$.p={},$}))})(ud)),ud.exports}var sB=aB();const kI=f0(sB);var md={exports:{}},rB=md.exports,qb;function oB(){return qb||(qb=1,(function(e,t){(function(n,a){e.exports=a()})(rB,(function(){return function(n,a,s){n=n||{};var r=a.prototype,i={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function c(u,p,f,S){return r.fromToBase(u,p,f,S)}s.en.relativeTime=i,r.fromToBase=function(u,p,f,S,b){for(var w,C,P,_=f.$locale().relativeTime||i,M=n.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],E=M.length,T=0;T<E;T+=1){var y=M[T];y.d&&(w=S?s(u).diff(f,y.d,!0):f.diff(u,y.d,!0));var I=(n.rounding||Math.round)(Math.abs(w));if(P=w>0,I<=y.r||!y.r){I<=1&&T>0&&(y=M[T-1]);var R=_[y.l];b&&(I=b(""+I)),C=typeof R=="string"?R.replace("%d",I):R(I,p,y.l,P);break}}if(p)return C;var O=P?_.future:_.past;return typeof O=="function"?O(C):O.replace("%s",C)},r.to=function(u,p){return c(u,p,this,!0)},r.from=function(u,p){return c(u,p,this)};var l=function(u){return u.$u?s.utc():s()};r.toNow=function(u){return this.to(l(this),u)},r.fromNow=function(u){return this.from(l(this),u)}}}))})(md)),md.exports}var iB=oB();const cB=f0(iB);kI.extend(cB);let xf=Date.now(),Hl;const Ul=new Set,Bb=()=>xf;function lB(e){return Ul.add(e),Hl||(xf=Date.now(),Hl=setInterval(()=>{xf=Date.now();for(const t of Ul)t()},3e4)),()=>{Ul.delete(e),Ul.size===0&&(clearInterval(Hl),Hl=void 0)}}function wI({value:e,className:t}){const n=h.useSyncExternalStore(lB,Bb,Bb),a=e==null?null:kI(e);return a?.isValid()?g.jsx("time",{className:t,dateTime:a.toISOString(),title:`Last activity ${a.format("MMM D, YYYY h:mm A")}`,children:a.from(n)}):null}const dB=2650,uB=304,mB=260;function pB(){return{animationDelay:`${-(Date.now()%dB)}ms`}}function fB(e){const t=e.currentTarget,n=t.firstElementChild;if(!(n instanceof HTMLElement))return;const a=Math.max(0,n.scrollWidth-t.clientWidth),s=a>2;t.dataset.overflowing=String(s),t.style.setProperty("--sidebar-title-ticker-distance",`${-a}px`),t.style.setProperty("--sidebar-title-ticker-duration",`${Math.min(6.5,Math.max(2.8,a/42+2.4))}s`)}function up({label:e,actions:t,actionsVisible:n=!1,className:a,titleAccessory:s,children:r,collapsed:i=!1,titleActive:c=!1,onTitleClick:l,onToggleCollapsed:u}){return g.jsxs("section",{className:["sidebar-section",a,n?"actions-visible":""].filter(Boolean).join(" "),children:[g.jsxs("div",{className:"section-header",children:[g.jsxs("div",{className:"section-title-row",children:[l?g.jsxs("div",{className:"section-title-combo",children:[g.jsx("button",{type:"button",className:`section-title-link${c?" active":""}`,onClick:l,children:g.jsx("span",{children:e})}),u&&g.jsx("button",{type:"button",className:"section-chevron-button","aria-label":`${i?"Expand":"Collapse"} ${e}`,"aria-expanded":!i,onClick:u,children:i?g.jsx(pr,{size:13}):g.jsx(mr,{size:13})})]}):u?g.jsxs("button",{type:"button",className:"section-title-button","aria-label":`${i?"Expand":"Collapse"} ${e}`,"aria-expanded":!i,onClick:u,children:[g.jsx("span",{children:e}),i?g.jsx(pr,{size:13}):g.jsx(mr,{size:13})]}):g.jsx("span",{children:e}),s]}),t&&g.jsx("div",{className:"section-actions",children:t})]}),!i&&g.jsx("div",{className:"sidebar-section-body",children:r})]})}function Fb({children:e,expanded:t=!1,onClick:n}){return g.jsx("button",{type:"button",className:"sidebar-show-more",onClick:n,children:e??(t?"Show less":"Show more")})}function Vb({session:e,selected:t,icon:n,archived:a=!1,nested:s=!1,dragging:r,placeholder:i,running:c,goalRuntime:l,subagentRuntime:u,terminalIndicator:p,projectLabel:f,inbox:S=!1,activityAt:b,ariaDescribedBy:w,childSessionCount:C=0,childSessionsExpanded:P=!1,onSelect:_,onToggleChildSessions:M,onTogglePin:E,onToggleSaveForLater:T,onDockRight:y,onArchive:I,onDragStart:R,onDragEnd:O,onDragOver:z,onDrop:$,onRename:V}){const[Y,se]=h.useState(!1),ee=l?.status==="queued",H=l?.tone==="active"&&!ee,F=(u?.activeCount??0)>0,J=C>0&&!!M,K=F||H||!ee&&(c??e.status==="active"),B=F&&u?u.label:H&&l?gB(l):"Running",ne=["sidebar-task-row",$c(e)?"is-draft":"",K?"has-running-dot":"",S?"sidebar-inbox-row":""].filter(Boolean).join(" "),G=h.useMemo(pB,[]),te=g.jsx(Gq,{title:e.title,pinned:!!e.pinned,savedForLater:!!e.savedForLater,archived:a,onRename:V?()=>se(!0):void 0,onTogglePin:E,onToggleSaveForLater:T,onDockRight:y,onArchive:I}),oe=g.jsxs(Ag,{selected:t,dataSessionId:e.id,dragging:r,nested:s,placeholder:i,className:ne||void 0,ariaExpanded:J?P:void 0,ariaDescribedBy:w,onSelect:_,onDragStart:R,onDragEnd:O,onDragOver:z,onDrop:$,onDoubleClick:V?()=>se(!0):void 0,children:[g.jsx("span",{className:"sidebar-source-slot",children:n??g.jsx(tB,{session:e})}),g.jsxs("span",{className:"sidebar-title-slot",children:[J?g.jsx("button",{type:"button",className:"sidebar-child-toggle","data-tooltip":P?"Hide subagent conversations":"Show subagent conversations","aria-label":`${P?"Hide":"Show"} ${C} subagent ${C===1?"conversation":"conversations"}`,"aria-expanded":P,onClick:me=>{me.stopPropagation(),M?.()},children:P?g.jsx(mr,{size:13}):g.jsx(pr,{size:13})}):null,g.jsxs("span",{className:"row-label-shell",title:e.title,children:[g.jsx("span",{className:"sidebar-session-title-line",children:g.jsx("span",{className:"row-label sidebar-task-title","data-overflowing":"false",onPointerEnter:fB,children:g.jsx(Qq,{title:e.title})})}),S?g.jsxs("span",{className:"sidebar-inbox-project",children:[f?g.jsxs(g.Fragment,{children:[g.jsx("span",{className:"sidebar-inbox-project-name",children:f}),g.jsx("span",{"aria-hidden":"true",children:"|"})]}):null,g.jsx(wI,{value:b??e.createdAt})]}):null]})]}),g.jsxs("div",{className:"row-meta",children:[g.jsxs("span",{className:"row-meta-status",children:[p?g.jsx(II,{indicator:p}):null,K?g.jsx("span",{className:`sidebar-running-dot${F?" subagent":H?" goal":""}`,style:G,"aria-label":B}):null]}),te,S?g.jsx("button",{type:"button",className:"sidebar-inbox-done","aria-label":`${a?"Reopen":"Mark done"}: ${e.title}`,title:a?"Reopen":"Mark done (does not stop running work)",onClick:me=>{me.stopPropagation(),I()},children:a?g.jsx(RU,{size:19}):g.jsx(ds,{size:21})}):null]})]}),be=Y&&V?g.jsx(Zq,{session:e,onSave:me=>V(e,me),onClose:()=>se(!1)}):null;return g.jsxs(g.Fragment,{children:[oe,be]})}function hB({file:e,selected:t=!1,placeholder:n,onSelect:a,onTogglePin:s,onToggleSaveForLater:r,onDragStart:i,onDragEnd:c,onDragOver:l,onDrop:u}){const p=e.path.split("/").at(-1)??e.path,f=`${e.workspaceName} · ${e.path}`;return g.jsxs(Ag,{selected:t,placeholder:n,className:`sidebar-file-row actions-2${e.available?"":" unavailable"}`,onSelect:a,onDragStart:i,onDragEnd:c,onDragOver:l,onDrop:u,children:[e.available?g.jsx(og,{size:15}):g.jsx(jd,{size:15}),g.jsx("span",{className:"row-label-shell",title:f,children:g.jsx("span",{className:"row-label",children:p})}),g.jsx("div",{className:"row-meta",children:g.jsxs("div",{className:"sidebar-row-actions",children:[g.jsx(Ld,{label:e.status==="pinned"?"Unpin file":"Pin file",onClick:s,children:e.status==="pinned"?g.jsx(lg,{size:13}):g.jsx(cg,{size:13})}),g.jsx(Ld,{label:e.status==="saved_for_later"?"Remove from Save for later":"Save file for later",onClick:r,children:e.status==="saved_for_later"?g.jsx(Hw,{size:13}):g.jsx(zw,{size:13})})]})})]})}function gB(e){return e.actionLabel}function vB({kind:e="local",project:t,pinned:n=!1,selected:a,expanded:s=!1,disclosure:r=!0,workspaceState:i,cloudLinkTrusted:c=!0,cloudLinkWarning:l=null,placeholder:u,terminalIndicator:p,onSelect:f,onNewChat:S,onMoveToCloud:b,onWorkspaceTargetSelect:w,onTogglePin:C,onRemove:P,onDragStart:_,onDragEnd:M,onDragOver:E,onDrop:T}){const[y,I]=h.useState(!1),R=h.useRef(null),[O,z]=h.useState({}),$=!!b||!!P,V=e==="local"&&c!==!1&&!!t.linkedSandboxProject?.projectId,Y=h.useCallback(()=>{if(typeof window>"u")return;const H=R.current?.getBoundingClientRect();if(!H)return;const F=Math.max(12,window.innerWidth-uB-12),J=Math.max(12,window.innerHeight-mB),K=Math.max(12,Math.min(H.right+10,F)),B=Math.max(12,Math.min(H.top-4,J)),ne={"--sidebar-project-locations-left":`${Math.round(K)}px`,"--sidebar-project-locations-top":`${Math.round(B)}px`};z(G=>G["--sidebar-project-locations-left"]===ne["--sidebar-project-locations-left"]&&G["--sidebar-project-locations-top"]===ne["--sidebar-project-locations-top"]?G:ne)},[]),se=h.useCallback(()=>{Y(),f()},[f,Y]);function ee(){I(!1)}return g.jsxs("div",{ref:R,className:["sidebar-project-row-shell",y?"project-menu-open":""].filter(Boolean).join(" "),onFocusCapture:Y,onPointerEnter:Y,children:[g.jsxs(Ag,{selected:a,placeholder:u,className:["sidebar-project-row",y?"project-menu-open":""].filter(Boolean).join(" "),ariaExpanded:r?s:void 0,onSelect:se,onDragStart:_,onDragEnd:M,onDragOver:E,onDrop:T,children:[g.jsx(xI,{kind:e,linkedCloud:V,open:e==="local"&&s,className:"sidebar-row-icon",baseSize:15}),g.jsx("span",{className:"row-label-shell",children:g.jsxs("span",{className:"sidebar-project-title-line",children:[g.jsx("span",{className:"row-label",children:t.name}),g.jsxs("span",{className:"sidebar-row-updated-at",children:[g.jsx("span",{"aria-hidden":"true",children:"| "}),g.jsx(wI,{value:t.updatedAt})]}),r?g.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:s?g.jsx(mr,{size:13}):g.jsx(pr,{size:13})}):null]})}),g.jsxs("div",{className:"row-meta",children:[g.jsx("span",{className:"row-meta-status",children:p?g.jsx(II,{indicator:p}):null}),g.jsxs("div",{className:"sidebar-row-actions",children:[g.jsx(Ld,{label:n?"Unpin project":"Pin project",onClick:C,children:n?g.jsx(lg,{size:13}):g.jsx(cg,{size:13})}),$&&g.jsx(AB,{open:y,onToggleOpen:()=>I(H=>!H)}),g.jsx(Ld,{label:"New task",onClick:S,children:g.jsx(ku,{size:13})})]})]})]}),g.jsx(bB,{kind:e,project:t,workspaceState:i,cloudLinkTrusted:c,cloudLinkWarning:l,onWorkspaceTargetSelect:w,style:O}),y&&g.jsx(EB,{onClose:ee,onMoveToCloud:b?()=>{ee(),b()}:void 0,onRemove:()=>{ee(),P()}})]})}function II({indicator:e}){return g.jsx("span",{className:`sidebar-terminal-indicator ${e.status}`,"data-tooltip":e.label,"aria-label":e.label,title:e.label,children:g.jsx(Gw,{size:13})})}function bB({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:s,onWorkspaceTargetSelect:r,style:i}){const c=xB(e,t,n,a,s);return g.jsxs("aside",{className:"sidebar-project-locations-popover","aria-label":`${t.name} status`,style:i,children:[g.jsx("div",{className:"sidebar-project-locations-title",children:t.name}),g.jsx("div",{className:"sidebar-project-location-list",children:c.map(l=>{const u=["sidebar-project-location-row",l.tone??"",l.actionTarget?"clickable":""].filter(Boolean).join(" "),p=g.jsxs(g.Fragment,{children:[g.jsx("span",{className:["sidebar-project-location-icon",l.key].filter(Boolean).join(" "),"aria-hidden":"true",children:l.icon}),g.jsx("span",{className:"sidebar-project-location-copy",children:g.jsx(yB,{value:l.value})})]});return l.actionTarget?g.jsx("button",{type:"button",className:u,"data-workspace-target":l.actionTarget,disabled:l.disabled||!r,title:l.disabledReason??void 0,onClick:f=>{f.stopPropagation(),!l.disabled&&r?.(l.actionTarget)},children:p},l.key):g.jsx("div",{className:u,children:p},l.key)})})]})}function yB({value:e}){const t=SB(e);return g.jsxs("span",{className:"sidebar-project-location-value","aria-label":e,children:[t.branch?g.jsxs(g.Fragment,{children:[g.jsx("span",{className:"sidebar-project-location-branch",children:t.branch}),g.jsx("span",{className:"sidebar-project-location-separator","aria-hidden":"true",children:"/"})]}):null,g.jsx("span",{className:"sidebar-project-location-status",children:t.status})]})}function SB(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function xB(e,t,n,a=!0,s=null){return e==="cloud"?wB(t):kB(t,n,a,s)}function kB(e,t,n=!0,a=null){const s=IB(e,t,n),r=_B(t),i=RB(e,n),c=n===!1&&a;return[{key:"local",value:s,tone:r?"attention":"local",icon:e.source==="git"?g.jsx(ig,{size:13}):g.jsx(Fw,{size:13}),actionTarget:"local"},{key:"cloud",value:c||(i?PB(e,t,n):"not in cloud"),tone:c?"attention":"cloud",icon:g.jsx(yu,{size:13}),actionTarget:i?"cloud":"upload_cloud"}]}function wB(e){return[{key:"cloud",value:TB(e),tone:e.syncedAt?"cloud":"attention",icon:g.jsx(yu,{size:13}),actionTarget:"cloud"}]}function IB(e,t,n){const a=CB(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?bI(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function _B(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function CB(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function RB(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function PB(e,t,n){return yI(e,null,t,{cloudLinkTrusted:n})}function TB(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function AB({open:e,onToggleOpen:t}){return g.jsx("button",{type:"button",className:`sidebar-row-action ${e?"active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-haspopup":"menu","aria-expanded":e,onClick:n=>{n.stopPropagation(),t()},children:g.jsx(Xc,{size:13})})}function EB({onClose:e,onMoveToCloud:t,onRemove:n}){return g.jsxs(g.Fragment,{children:[g.jsx("button",{type:"button",className:"sidebar-project-menu-backdrop","aria-label":"Close project actions",onClick:a=>{a.stopPropagation(),e()}}),g.jsxs("div",{className:"section-menu-popover sidebar-project-row-popover",role:"menu",children:[t&&g.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),t()},children:[g.jsx(Bq,{size:13}),g.jsx("span",{children:"Move to Cloud"})]}),g.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),n()},children:[g.jsx(el,{size:13}),g.jsx("span",{children:"Remove from Projects"})]})]})]})}function Ag({children:e,className:t,dataSessionId:n,dragging:a,iconless:s=!1,nested:r=!1,placeholder:i=!1,selected:c,ariaExpanded:l,ariaDescribedBy:u,onSelect:p,onDragStart:f,onDragEnd:S,onDragOver:b,onDrop:w,onDoubleClick:C}){const P=!!f;return g.jsx("div",{className:["sidebar-row",t??"",c?"selected":"",a?"dragging":"",s?"iconless":"",r?"nested":"",i?"placeholder":""].filter(Boolean).join(" "),draggable:P,"data-session-id":n,role:"button",tabIndex:0,"aria-expanded":l,"aria-describedby":u,onClick:p,onDoubleClick:C,onKeyDown:_=>{_.target===_.currentTarget&&(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),p())},onDragStart:f,onDragEnd:S,onDragEnter:_=>{b&&(_.preventDefault(),_.dataTransfer.dropEffect="move",b(_))},onDragOver:_=>{b&&(_.preventDefault(),_.dataTransfer.dropEffect="move",b(_))},onDrop:_=>{w&&(_.preventDefault(),w(_))},children:e})}function Ld({children:e,label:t,onClick:n}){return g.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":t,"aria-label":t,onClick:a=>{a.stopPropagation(),n()},children:e})}function jB({filter:e,activityOrder:t=!1,groupByProject:n,noun:a,onFilterChange:s,onGroupByProjectChange:r,onOnlyRunningTasksChange:i,onShowCodexChatsChange:c,onTasksetChange:l,onSortChange:u,onlyRunningTasks:p,openMenu:f,setOpenMenu:S,showCodexChats:b,sort:w,selectedTasksetId:C,tasksets:P}){const _=h.useRef(null),[M,E]=h.useState(!1),y=P.find(O=>O.id===C)?.name??Mb.find(O=>O.value===e)?.label??"Active",I=f==="tasks-filter",R=f==="chats";return h.useEffect(()=>{if(!I&&!R)return;function O(z){_.current?.contains(z.target)||S(null)}return document.addEventListener("pointerdown",O),()=>document.removeEventListener("pointerdown",O)},[I,S,R]),g.jsxs("div",{className:"sidebar-task-list-controls",ref:_,children:[g.jsxs("div",{className:"section-menu",children:[g.jsx("button",{type:"button",className:`section-icon ${R?"active":""}`,"aria-label":`${a==="tasks"?"Task":"Chat"} list options`,"aria-haspopup":"menu","aria-expanded":R,onClick:()=>S(O=>O==="chats"?null:"chats"),children:g.jsx(Xc,{size:14})}),R?g.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":`${a==="tasks"?"Task":"Chat"} list options`,children:[g.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":b,onClick:()=>c(!b),children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:b?g.jsx(ds,{size:13}):null}),g.jsx("span",{children:"Show Codex chats, including pinned"})]}),g.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":p,onClick:()=>i(!p),children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:p?g.jsx(ds,{size:13}):null}),g.jsxs("span",{children:["Only running ",a,", including pinned"]})]}),a==="tasks"&&!t?g.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":n,onClick:()=>r(!n),children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:n?g.jsx(ds,{size:13}):null}),g.jsx("span",{children:"Group by project"})]}):null,t?g.jsx("p",{className:"empty-row",children:"Latest activity first"}):Eq.map(O=>g.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w===O.value,onClick:()=>{u(O.value),S(null)},children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:w===O.value?g.jsx(ds,{size:13}):null}),g.jsx("span",{children:O.label})]},O.value))]}):null]}),g.jsxs("div",{className:"section-menu",children:[g.jsx("button",{type:"button",className:`section-icon ${I?"active":""}`,"aria-label":`Filter ${a}: ${y}`,"aria-haspopup":"menu","aria-expanded":I,onClick:()=>S(O=>O==="tasks-filter"?null:"tasks-filter"),children:g.jsx(uU,{size:14})}),I?g.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${a}`,children:Mb.map(O=>g.jsxs(h.Fragment,{children:[O.value==="tasksets"?g.jsxs("button",{type:"button",role:"menuitem","aria-expanded":M,onClick:()=>E(z=>!z),children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:M?g.jsx(mr,{size:13}):g.jsx(pr,{size:13})}),g.jsx("span",{children:O.label})]}):g.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e===O.value,onClick:()=>{s(O.value),S(null)},children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e===O.value?g.jsx(ds,{size:13}):null}),g.jsx("span",{children:O.label})]}),O.value==="tasksets"&&M?g.jsxs(g.Fragment,{children:[g.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&!C,onClick:()=>{l(null),S(null)},children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&!C?g.jsx(ds,{size:13}):null}),g.jsx("span",{children:"All Tasksets"})]}),P.map(z=>g.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&C===z.id,onClick:()=>{l(z.id),S(null)},children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&C===z.id?g.jsx(ds,{size:13}):null}),g.jsx("span",{children:z.name}),g.jsx("span",{className:"section-menu-option-count","aria-hidden":"true",children:z.chatCount})]},z.id))]}):null]},O.value))}):null]})]})}function MB({onAddProject:e,onViewProjects:t}){const[n,a]=h.useState(!1),s=h.useRef(null),r=h.useRef(null);return h.useEffect(()=>{if(!n)return;s.current?.querySelector('[role="menuitem"]')?.focus();const i=c=>{s.current?.contains(c.target)||a(!1)};return document.addEventListener("pointerdown",i),()=>document.removeEventListener("pointerdown",i)},[n]),g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"section-menu",ref:s,onKeyDown:i=>{i.key==="Escape"&&(i.stopPropagation(),a(!1),r.current?.focus())},children:[g.jsx("button",{ref:r,type:"button",className:`section-icon${n?" active":""}`,"aria-label":"Project options","aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(i=>!i),children:g.jsx(Xc,{size:14})}),n?g.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":"Project options",children:[g.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),t()},children:"View all projects"}),g.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),e()},children:"Add project"})]}):null]}),g.jsx("button",{type:"button",className:"section-icon",onClick:e,"aria-label":"Add project",title:"Add project",children:"+"})]})}const OB=240,$B=36;function NB(e,t,n=!1){const a=Math.max(12,t.width-OB-12),s=Math.max(12,t.height-$B-(n?22:0)-12);return{"--sidebar-task-detail-left":`${Math.round(Math.max(12,Math.min(e.right+10,a)))}px`,"--sidebar-task-detail-top":`${Math.round(Math.max(12,Math.min(e.top-4,s)))}px`}}function DB({detail:e,onClose:t}){if(h.useEffect(()=>{if(!e||typeof window>"u")return;const s=c=>{c.key==="Escape"&&t()};let r=!1;const i=window.requestAnimationFrame(()=>{window.addEventListener("scroll",t,!0),r=!0});return window.addEventListener("keydown",s),()=>{window.cancelAnimationFrame(i),window.removeEventListener("keydown",s),r&&window.removeEventListener("scroll",t,!0)}},[e,t]),!e)return null;const n=new Date(e.updatedAt),a=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(n);return g.jsxs("aside",{id:e.descriptionId,className:"sidebar-task-detail-popover",style:e.style,role:"tooltip","aria-label":`Last updated for ${e.title}`,children:[g.jsx("time",{dateTime:e.updatedAt,children:a}),e.folderName?g.jsxs("div",{className:"sidebar-task-detail-folder",children:[g.jsx(Fw,{size:13,"aria-hidden":"true"}),g.jsx("span",{children:e.folderName})]}):null]})}function LB({children:e,expanded:t,groupKey:n,kind:a,label:s,onToggle:r,onNewTask:i,onOpenProject:c,onRemoveProject:l,project:u}){const p=`sidebar-task-group-${n.replace(/[^a-zA-Z0-9_-]/g,"-")}`,f=a==="draft"?og:xu,[S,b]=h.useState(!1),w=!!(i||c||l);return g.jsxs("section",{className:"sidebar-task-project-group",children:[g.jsxs("div",{className:`sidebar-task-project-group-header-shell${S?" menu-open":""}`,children:[g.jsxs("button",{type:"button",className:"sidebar-task-project-group-header","aria-controls":p,"aria-expanded":t,onClick:()=>{b(!1),r()},children:[u?g.jsx(xI,{kind:u.kind,linkedCloud:!!(u.kind==="local"&&u.project.linkedSandboxProject?.projectId),open:u.kind==="local"&&t,className:"sidebar-task-project-group-icon",baseSize:14}):g.jsx(f,{className:"sidebar-task-project-group-icon",size:14,"aria-hidden":"true"}),g.jsx("span",{className:"sidebar-task-project-group-name",children:s}),g.jsx("span",{className:"sidebar-task-project-group-caret","aria-hidden":"true",children:t?g.jsx(mr,{size:13}):g.jsx(pr,{size:13})})]}),u&&w?g.jsxs("div",{className:"sidebar-task-project-group-actions",children:[c||l?g.jsx("button",{type:"button",className:`sidebar-row-action${S?" active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-expanded":S,"aria-haspopup":"menu",onClick:()=>b(C=>!C),children:g.jsx(Xc,{size:13})}):null,i?g.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":"New task","aria-label":"New task",onClick:i,children:g.jsx(ku,{size:13})}):null]}):null,S?g.jsxs(g.Fragment,{children:[g.jsx("button",{type:"button",className:"sidebar-task-project-group-menu-backdrop","aria-label":"Close project actions",onClick:()=>b(!1)}),g.jsxs("div",{className:"section-menu-popover sidebar-task-project-group-menu",role:"menu",children:[c?g.jsx("button",{type:"button",role:"menuitem",onClick:()=>{b(!1),c()},children:g.jsx("span",{children:"Open project"})}):null,l?g.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{b(!1),l()},children:[g.jsx(el,{size:13}),g.jsx("span",{children:"Remove from Projects"})]}):null]})]}):null]}),t?g.jsx("div",{id:p,className:"sidebar-task-project-group-content",children:e}):null]})}function zB({platform:e}){return!Eg()||_I(e)?null:g.jsxs("div",{className:"window-controls","aria-label":"Window controls",children:[g.jsx("button",{type:"button",className:"window-control minimize",title:"Minimize",onClick:()=>{mp("minimize")},children:g.jsx(mr,{size:14})}),g.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{mp("toggleMaximize")},children:g.jsx(fU,{size:12})}),g.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{mp("close")},children:g.jsx(el,{size:13})})]})}function _I(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")}function Eg(){if(typeof window>"u")return!1;const e=window.openpond;return!!(e?.minimizeWindow||e?.toggleMaximizeWindow||e?.closeWindow)}async function mp(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 HB={},UB=new Map,qB=new Map;function Kb(){const e=no.getItem("openpond.sidebar.presentation.v1");return e==="inbox"||e==="grouped"?e:Eg()?"inbox":"grouped"}function BB(e,t){return Math.min(Math.max(e,Nn)+bf,t)}function FB(e,t){const n=Math.max(Nn,Math.min(e,t));if(n<=Nn)return Nn;const a=Math.ceil((n-Nn)/bf);return Math.max(Nn,Nn+(a-1)*bf)}function VB(e,t){const n=new Map;for(const a of e){const s=t(a),r=n.get(s.key);r?r.sessions.push(a):n.set(s.key,{...s,sessions:[a]})}return[...n.values()]}function KB({activeSessions:e,activityTimes:t={},onSelectSession:n,archiveSession:a,archivedSessions:s,chatRowsVisibleCount:r,childSessionRowsByParentId:i={},cloudProjectRows:c,beginProjectChat:l,onAddProject:u,commitTaskDrop:p,commitTaskPreviewDrop:f,dockSessionRight:S,experience:b="work",goalRuntimeBySessionId:w=UB,localProjectRows:C,openSidebarFile:P,pinnedCollapsed:_,pinnedRows:M,previewTaskDrop:E,previewPinnedDrop:T,projectRows:y,renameSession:I,restoreSession:R,runningSessionIds:O,sectionMenuOpen:z,selectedProjectId:$,selectedSessionId:V,setChatRowsVisibleCount:Y,setSectionMenuOpen:se,setSelectedAppId:ee,setSelectedProjectId:H,setSelectedSessionId:F,setView:J,sidebarProjectIdBySessionId:K,startTaskDrag:B,startPinnedDrag:ne,subagentRuntimeBySessionId:G=qB,taskDragSessionId:te,taskPreviewSessionIds:oe,terminalSummaries:be=HB,toggleSessionPinned:me,toggleSessionSavedForLater:Re,view:Q,clearTaskDrag:xe,removeProject:je,toggleProjectPinned:De,onTogglePinnedCollapsed:He,setSidebarFileStatus:Ie,commitPinnedDrop:Me,commitPinnedPreviewDrop:Te,clearSidebarDrag:N,dragItem:q}){const[X,U]=h.useState(Kb);fi(()=>U(Kb()));const ae=X==="inbox",[de,ye]=h.useState("active"),[Oe,$e]=h.useState("recent"),[Ge,yt]=h.useState(!0);h.useEffect(()=>{b!=="chat"&&yt(!0)},[b]);const[Se,Le]=h.useState({work:!1,chat:!0}),[Ae,qe]=h.useState({work:!1,chat:!1}),Ue=b==="chat"?"chat":"work",bn=Se[Ue],[Mt,pe]=h.useState(Lb);fi(()=>pe(Lb()));const{onlyRunningTasks:fe,showCodexChats:Fe}=Mt,[Pe,Ne]=h.useState(null),[ot,ut]=h.useState(()=>new Set),[At,mt]=h.useState(()=>new Map),[at,Ct]=h.useState(null);h.useEffect(()=>{$&&Le(D=>D[Ue]?{...D,[Ue]:!1}:D)},[Ue,$]);const Be=b==="chat"?"chats":"tasks",Et=y??[...C,...c],dn=h.useMemo(()=>new Map(Et.map(D=>[D.id,D.project.name])),[Et]),jn=h.useMemo(()=>new Map(Et.map(D=>[D.id,D])),[Et]),kt=h.useMemo(()=>{const D=new Set(O);for(const we of[...e,...Object.values(i).flat()]){const le=w.get(we.id),Je=G.get(we.id);(le?.tone==="active"&&le.status!=="queued"||(Je?.activeCount??0)>0||_t(we.id)?.status==="running")&&D.add(we.id)}return D},[e,i,w,O,G,be]),ks=h.useMemo(()=>dp({activeSessions:e,doneSessions:s,filter:"all",inProgressSessionIds:kt,sort:"manual"}),[e,s,kt]),un=h.useMemo(()=>dp({activeSessions:e,doneSessions:s,filter:de,inProgressSessionIds:kt,onlyRunningTasks:fe,selectedTasksetId:Pe,previewSessionIds:oe,showCodexChats:Fe,sort:Oe}),[e,s,kt,fe,Pe,Fe,de,oe,Oe]),yn=h.useMemo(()=>{const D=new Map;for(const we of[...e,...s]){if(!dd(we,{inProgressSessionIds:kt,onlyRunningTasks:fe,showCodexChats:Fe}))continue;const le=Ko(we);if(!le)continue;const Je=D.get(le.id);Je?Je.chatCount+=1:D.set(le.id,{...le,chatCount:1})}return[...D.values()].sort((we,le)=>we.name.localeCompare(le.name))},[e,s,kt,fe,Fe]),Ut=h.useMemo(()=>M.filter(D=>D.type!=="session"||dd(D.session,{inProgressSessionIds:kt,onlyRunningTasks:fe,showCodexChats:Fe})),[kt,fe,M,Fe]),Rn=h.useMemo(()=>un.filter(D=>!Wo(D)),[un]),Sn=h.useMemo(()=>Rn.slice(0,Math.max(Nn,r)),[r,Rn]),Pn=h.useMemo(()=>{const D=VB(Sn,we=>{if($c(we))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const le=K[we.id],Je=Ot(we)??"Work";return{key:le?`project:${le}`:`projectless:${Je}`,label:Je,projectId:le??null,project:le?jn.get(le)??null:null,kind:le?"project":"projectless"}});for(const we of Et)D.some(le=>le.projectId===we.id)||D.push({key:`project:${we.id}`,label:we.project.name,projectId:we.id,project:we,kind:"project",sessions:[]});return D},[Et,dn,jn,K,Sn]),Mn=Sn.length<Rn.length,qt=Sn.length>Nn,gt=h.useMemo(()=>new Set(Pn.filter(D=>D.sessions.some(we=>we.id===V||kt.has(we.id))).map(D=>D.key)),[Pn,kt,V]),qn=ks.filter(D=>!Wo(D)).map(D=>D.id),mn=Sn.map(D=>D.id),pt=JSON.stringify(Object.entries(i).filter(([D,we])=>we.some(le=>!le.archived)&&(G.get(D)?.activeCount??0)>0).flatMap(([D,we])=>we.filter(le=>!le.archived).map(le=>[D,le.id])).sort(([D,we],[le,Je])=>D.localeCompare(le)||we.localeCompare(Je)));h.useEffect(()=>{const D=JSON.parse(pt);if(D.length===0)return;const we=new Set(D.map(([le])=>le));ut(le=>[...we].every(Je=>le.has(Je))?le:new Set([...le,...we]))},[pt]);function _t(D){return Lq(be[vI({kind:"session",id:D})])}function Ot(D){if($c(D))return"Draft";const we=K[D.id];return we?dn.get(we)??D.workspaceName??"Project":_q(D)}function pn(D){if(n){n(D);return}Lt({kind:"chat",sessionId:D.id}),F(D.id);const we=K[D.id]??null;ee(we?null:D.appId),H(we),J("chat")}function oa(D){return(i[D.id]??[]).filter(we=>!we.archived&&dd(we,{inProgressSessionIds:kt,onlyRunningTasks:fe,showCodexChats:Fe}))}function Ze(D,we){return ot.has(D.id)||we.some(le=>le.id===V)}function Tn(D){ut(we=>{const le=new Set(we);return le.has(D)?le.delete(D):le.add(D),le})}function Ja(D){const we=oa(D);return we.length===0||!Ze(D,we)?null:g.jsx("div",{className:"sidebar-child-session-group",children:we.map(le=>g.jsx(Vb,{session:le,selected:Q==="chat"&&V===le.id,nested:!0,running:kt.has(le.id),goalRuntime:w.get(le.id)??null,subagentRuntime:G.get(le.id)??null,terminalIndicator:_t(le.id),projectLabel:Ot(D),onSelect:()=>pn(le),onTogglePin:()=>me(le),onToggleSaveForLater:()=>Re(le),onDockRight:()=>S(le),onArchive:()=>le.archived?R(le):a(le),onRename:I},le.id))})}function Ea(D,we){if(typeof window>"u")return;const le=Wo(D)?Ot(D):null;Ct({descriptionId:`sidebar-task-detail-${D.id}`,sessionId:D.id,title:D.title,updatedAt:D.updatedAt,folderName:le,style:NB(we.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight},!!le)})}function Ln(D,we={}){const le=D.archived,Je=we.pinnedRow?.placeholder??te===D.id,ga=oa(D),Bn="sidebar-session-group",Ma=we.pinnedRow?.dragProps??(!ae&&Oe==="manual"?{onDragStart:kn=>B(kn,{allSessionIds:qn,visibleSessionIds:mn,sessionId:D.id}),onDragEnd:xe,onDragOver:kn=>{Je||E(kn,D.id)},onDrop:kn=>{Je?f():p(kn,D.id)}}:{});return g.jsxs("div",{className:Bn,onPointerEnter:kn=>Ea(D,kn.currentTarget),onPointerLeave:()=>Ct(null),onFocusCapture:kn=>Ea(D,kn.currentTarget),onBlurCapture:kn=>{kn.currentTarget.contains(kn.relatedTarget)||Ct(null)},children:[g.jsx(Vb,{session:D,selected:!le&&Q==="chat"&&V===D.id,archived:le,inbox:ae,activityAt:bd(D,t),placeholder:Je,running:kt.has(D.id),goalRuntime:w.get(D.id)??null,subagentRuntime:G.get(D.id)??null,terminalIndicator:_t(D.id),projectLabel:we.projectLabel===void 0?Ot(D):we.projectLabel,metadataPresentation:we.metadataPresentation,ariaDescribedBy:at?.sessionId===D.id?at.descriptionId:void 0,childSessionCount:ga.length,childSessionsExpanded:Ze(D,ga),onToggleChildSessions:()=>Tn(D.id),onSelect:()=>{Ct(null),le&&R(D),pn(D)},onTogglePin:()=>me(D),onToggleSaveForLater:()=>Re(D),onDockRight:()=>S(D),onArchive:()=>le?R(D):a(D),onRename:I,...Ma}),!ae&&!Je?Ja(D):null]},we.pinnedRow?.key??D.id)}function An(D){D!=="tasksets"&&Ne(null),ye(D),Y(Nn)}function Qa(D){Ne(D),ye("tasksets"),Y(Nn)}function ws(D){$e(D),Y(Nn)}function ja(){Y(D=>BB(D,Rn.length))}function lt(){Y(D=>FB(D,Rn.length))}function sn(D){const we={id:D.id,type:D.type};return{onDragStart:le=>ne(le,we),onDragEnd:N,onDragOver:le=>T(le,we),onDrop:le=>{q?.id===D.id&&q.type===D.type?Te():Me(le,we)}}}function Ke(D){const we=sn(D),le=q?.id===D.id&&q.type===D.type;if(D.type==="project"){const Je=D.item;return g.jsx(vB,{kind:Je.kind,project:Je.project,pinned:!0,selected:Q==="chat"&&$===Je.id,expanded:!1,disclosure:!1,placeholder:le,onSelect:()=>{ee(null),H(Je.id),F(null),J("chat")},onNewChat:()=>l(Je.id),onTogglePin:()=>De(Je),onRemove:()=>je(Je),...we},D.key)}return D.type==="file"?g.jsx(hB,{file:D.file,placeholder:le,onSelect:()=>P(D.file),onTogglePin:()=>Ie(D.file,"none"),onToggleSaveForLater:()=>Ie(D.file,"saved_for_later"),...we},D.key):Ln(D.session,{projectLabel:ae&&!K[D.session.id]?null:Ot(D.session),pinnedRow:{key:D.key,dragProps:we,placeholder:le}})}function St(D){const we=gt.has(D.key)||At.get(D.key)!==!1;return g.jsx(LB,{expanded:we,groupKey:D.key,kind:D.kind,label:D.label,onToggle:()=>{mt(le=>{const Je=new Map(le);return Je.set(D.key,!we),Je})},onNewTask:D.project?()=>l(D.project.id):void 0,onOpenProject:D.project?()=>{ee(null),H(D.project.id),F(null),J("chat")}:void 0,onRemoveProject:D.project?()=>je(D.project):void 0,project:D.project,children:D.sessions.map(le=>Ln(le,{metadataPresentation:"flyout",projectLabel:D.label}))},D.key)}const en=g.jsx(jB,{activityOrder:ae,filter:de,groupByProject:Ge,noun:Be,onFilterChange:An,onGroupByProjectChange:yt,onOnlyRunningTasksChange:D=>{pe(we=>{const le={...we,onlyRunningTasks:D};return zb(le),le}),Y(Nn)},onShowCodexChatsChange:D=>{pe(we=>{const le={...we,showCodexChats:D};return zb(le),le}),Y(Nn)},onTasksetChange:Qa,onSortChange:ws,onlyRunningTasks:fe,openMenu:z,setOpenMenu:se,showCodexChats:Fe,sort:Oe,selectedTasksetId:Pe,tasksets:yn}),zn=dp({activeSessions:Object.values(i).flat().filter(D=>!D.archived),doneSessions:Object.values(i).flat().filter(D=>D.archived),filter:de,inProgressSessionIds:kt,onlyRunningTasks:fe,selectedTasksetId:Pe,showCodexChats:Fe,sort:"recent"}),xn=aC([...un,...zn].filter(D=>!Wo(D)),t,kt);return g.jsxs("div",{className:"sidebar-sections",children:[g.jsxs("div",{className:"sidebar-threads-header",children:[g.jsx("span",{children:"Threads"}),g.jsxs("div",{className:"sidebar-threads-header-actions",children:[ae?en:null,g.jsx("button",{type:"button",className:`sidebar-icon${ae?" active":""}`,"aria-label":ae?"Show grouped threads":"Show thread inbox",title:ae?"Grouped threads":"Thread inbox","aria-pressed":ae,onClick:()=>{const D=ae?"grouped":"inbox";U(D),no.setItem("openpond.sidebar.presentation.v1",D)},children:ae?g.jsx(zU,{size:16}):g.jsx(mg,{size:16})})]})]}),Ut.length>0?g.jsx(up,{label:"Pinned",className:"sidebar-pinned-section",collapsed:_,onToggleCollapsed:He,children:Ut.map(Ke)}):null,ae?g.jsxs("section",{className:"sidebar-thread-inbox","aria-label":"Thread inbox",children:[sC(xn,t,kt).map(D=>g.jsxs("div",{children:[D.label?g.jsx("h3",{className:"sidebar-inbox-date",children:D.label}):null,D.sessions.map(we=>Ln(we,{projectLabel:K[we.id]?Ot(we):null}))]},D.key)),xn.length===0&&Ut.length===0?g.jsx("div",{className:"empty-row",children:$b(de,Be)}):null]}):g.jsxs(g.Fragment,{children:[g.jsx(up,{label:"Projects",className:`sidebar-projects-section${b!=="chat"?" development":""}`,collapsed:bn,onToggleCollapsed:()=>Le(D=>({...D,[Ue]:!D[Ue]})),actions:g.jsx(MB,{onAddProject:u,onViewProjects:()=>{(async()=>await Lt({kind:"view",view:"projects"})&&(ee(null),H(null),F(null),J("projects")))()}}),children:Pn.filter(D=>D.kind==="project").map(D=>St(b==="chat"||!Ge?{...D,sessions:[]}:D))}),g.jsxs(up,{label:b==="chat"?"Chat":"Work",className:"sidebar-task-section sidebar-ordinary-section",collapsed:Ae[Ue],onToggleCollapsed:()=>qe(D=>({...D,[Ue]:!D[Ue]})),actionsVisible:z==="chats"||z==="tasks-filter"||de!=="active"||fe||!Fe,actions:en,children:[(b==="chat"||!Ge?Sn:Sn.filter(D=>!K[D.id])).map(D=>Ln(D)),Rn.length===0&&Ut.length===0?g.jsx("div",{className:"empty-row",children:$b(de,Be)}):null,Rn.length>Nn&&(Mn||qt)?g.jsxs("div",{className:"sidebar-pagination-controls","aria-label":`Showing ${Sn.length} of ${Rn.length} ${Be}`,children:[Mn?g.jsx(Fb,{onClick:ja,children:"Show more"}):null,qt?g.jsx(Fb,{onClick:lt,children:"Show less"}):null]}):null]})]}),g.jsx(DB,{detail:at,onClose:()=>Ct(null)})]})}const WB=h.lazy(()=>fr(()=>import("./TerminalOverlay-DGrZRZ_3.js"),__vite__mapDeps([0,1,2,3])).then(e=>({default:e.TerminalOverlay})));function GB({connection:e,command:t,onClose:n,onComplete:a}){const[s,r]=h.useState([]),[i]=h.useState(()=>({kind:"draft",id:`native-setup-${crypto.randomUUID()}`})),c=h.useRef(!1),[l]=h.useState(()=>({id:Date.now(),scope:i,command:t}));return h.useEffect(()=>{!c.current&&s.some(u=>u.lastCommand===t&&u.lastExitCode===0&&u.commandStatus==="success")&&(c.current=!0,a?.())},[s,t,a]),Dd.createPortal(g.jsx("div",{className:"native-setup-terminal",children:g.jsx(h.Suspense,{fallback:g.jsx("p",{role:"status",children:"Opening setup terminal…"}),children:g.jsx(WB,{open:!0,disposeOnUnmount:!0,connection:e,scope:i,tabs:s,onTabsChange:r,cwd:null,appId:null,workspaceName:"Agent setup",queuedCommand:l,onClose:n})})}),document.body)}const ql={codex:"Codex",claude_code:"Claude Code",opencode:"OpenCode",grok_build:"Grok Build",hermes:"Hermes",pi:"Pi",oh_my_pi:"Oh My Pi",openclaw:"OpenClaw"};function ZB({status:e,busy:t,onControl:n,onConnectionControl:a,onReconnect:s}){const r=e.desiredState==="stopped",i=r?"Importer stopped":e.running?"Importer running":"Importer offline";return g.jsxs("div",{className:"sidebar-section native-importer-status",children:[g.jsx("strong",{children:i}),e.connections.map(c=>{const l=c.backfill,u=l.stage==="complete",p=l.admitted+l.skipped;return g.jsxs("div",{className:"native-importer-connection",children:[g.jsxs("span",{children:[c.error?g.jsx(jd,{size:12}):u?g.jsx(ds,{size:12}):g.jsx(Su,{size:12}),ql[c.source]??c.source]}),g.jsx("small",{children:c.state==="paused"?"Paused":c.state==="disconnected"?"Disconnected":u?e.running&&!r?"Watching for new conversations":`${l.admitted} conversations imported`:l.stage==="discovering"?"Finding conversations":`${p} of ${l.total} conversations processed`}),g.jsxs("small",{children:[c.admitted," tasks admitted",l.skipped>0?`, ${l.skipped} conversations skipped`:"",l.failed>0?`, ${l.failed} failed`:""]}),!u&&l.total>0?g.jsx("progress",{"aria-label":`${ql[c.source]??c.source} import progress`,value:p,max:l.total}):null,c.queued>0?g.jsxs("small",{children:[c.queued," updates waiting to upload (",new Intl.NumberFormat(void 0,{notation:"compact"}).format(c.pendingBytes)," bytes)"]}):null,c.lastAdmissionAt?g.jsxs("small",{children:["Last synced ",g.jsx("time",{dateTime:c.lastAdmissionAt,children:new Date(c.lastAdmissionAt).toLocaleString()})]}):g.jsx("small",{children:"No uploads acknowledged yet"}),c.destinationLinks?.tasks?g.jsx("a",{href:c.destinationLinks.tasks,target:"_blank",rel:"noopener noreferrer",children:"View tasks"}):null,c.destinationLinks?.conversations?g.jsx("a",{href:c.destinationLinks.conversations,target:"_blank",rel:"noopener noreferrer",children:"View conversations"}):null,c.error?g.jsx("small",{role:"status",children:c.error}):null,c.state==="disconnected"?g.jsx("button",{type:"button",disabled:t,onClick:()=>s(c.id),children:"Reconnect source"}):g.jsxs("div",{children:[g.jsxs("button",{type:"button",disabled:t,onClick:()=>a(c.state==="paused"?"resume":"pause",c.id),children:[c.state==="paused"?"Resume":"Pause"," ",ql[c.source]??c.source]}),g.jsxs("button",{type:"button",disabled:t,onClick:()=>a("disconnect",c.id),children:["Disconnect ",ql[c.source]??c.source]})]})]},c.id)}),g.jsx("button",{type:"button",disabled:t||r,onClick:()=>n("sync"),children:"Sync now"}),g.jsxs("button",{type:"button",disabled:t,onClick:()=>n(r||!e.running?"start":"stop"),children:[r?"Start":e.running?"Stop":"Restart"," importer"]}),!e.running&&!r?g.jsx("button",{type:"button",disabled:t,onClick:()=>n("stop"),children:"Stop importer"}):null,!e.running&&!r?g.jsx("button",{type:"button",disabled:t,onClick:()=>n("install"),children:"Reinstall background service"}):null]})}function JB({title:e,inspection:t,busy:n,onSelect:a,onRefresh:s,onClose:r}){return g.jsxs("section",{className:"native-branch-picker","aria-label":"Choose Claude conversation branch",children:[g.jsx("strong",{children:e||"Claude conversation"}),g.jsx("p",{children:"This conversation has multiple branches. Choose the history to view. Each branch opens as a read-only snapshot."}),t.branches.map(i=>g.jsxs("button",{type:"button",disabled:n,onClick:()=>a({leafId:i.leafId,revision:t.revision}),children:[g.jsx("span",{children:i.title||"Branch without a text message"}),g.jsxs("small",{children:[i.messages," messages · ",i.updatedAt?new Date(i.updatedAt).toLocaleString():"Date unavailable"]}),g.jsx("code",{children:i.leafId})]},i.leafId)),g.jsxs("div",{children:[g.jsx("button",{type:"button",disabled:n,onClick:s,children:"Refresh branches"}),g.jsx("button",{type:"button",disabled:n,onClick:r,children:"Cancel"})]})]})}function QB({connection:e,selectedSessionId:t,selectedSession:n,active:a=!0,onOpen:s}){const r=h.useRef({selectedSessionId:t,active:a});r.current={selectedSessionId:t,active:a};const i=h.useRef(null),c=h.useRef(0),l=h.useRef(null);h.useEffect(()=>(c.current++,i.current=null,M(null),w(null),P(null),S(null),I(null),p(null),()=>{c.current++}),[e]);const[u,p]=h.useState(null),[f,S]=h.useState(null),[b,w]=h.useState(null),[C,P]=h.useState(null),[_,M]=h.useState(null),[E,T]=h.useState(!1),[y,I]=h.useState(null),R=h.useCallback(async()=>{if(!e||l.current===c.current)return;const ee=c.current;l.current=ee,M("refresh");try{const H=await L(e,"/v1/native-history/list",{method:"POST",body:JSON.stringify({retain:!0})});ee===c.current&&(w(H),P(null))}catch(H){ee===c.current&&P(H instanceof Error?H.message:"Local history is unavailable.")}finally{l.current===ee&&(l.current=null),ee===c.current&&M(null)}},[e]);h.useEffect(()=>{R()},[R]),h.useEffect(()=>{const ee=window.setInterval(()=>{document.hidden||R()},3e4);return()=>window.clearInterval(ee)},[R]),h.useEffect(()=>{if(!a||!e||!u||u.sessionId!==t)return;const ee=c.current,H=window.setInterval(()=>{document.hidden||L(e,"/v1/native-history/open",{method:"POST",body:JSON.stringify({id:u.id})}).catch(F=>{ee===c.current&&P(F.message)})},1e4);return()=>window.clearInterval(H)},[a,e,u,t]);async function O(){const ee=c.current;if(!(!e||!b)){M("more");try{const H=await L(e,"/v1/native-history/list",{method:"POST",body:JSON.stringify({cursors:b.nextCursors,retain:!0})});if(ee!==c.current)return;w(F=>({...H,items:[...new Map([...F?.items??[],...H.items].map(J=>[J.id,J])).values()]}))}catch(H){ee===c.current&&P(H instanceof Error?H.message:"Could not load more conversations.")}finally{ee===c.current&&M(null)}}}async function z(ee,H,F=r.current.selectedSessionId){const J=c.current;if(e&&_===null){M(ee);try{if(!H){const B=await L(e,"/v1/native-history/branches",{method:"POST",body:JSON.stringify({id:ee})});if(J!==c.current)return;if(B.branches.length>1){r.current.active&&r.current.selectedSessionId===F&&I({id:ee,inspection:B,originSessionId:F}),P(null);return}}const K=await L(e,"/v1/native-history/open",{method:"POST",body:JSON.stringify({id:ee,branch:H})});if(J!==c.current)return;p(H?null:{id:ee,sessionId:K.id}),I(null),P(K.metadata?.nativeHistoryProjection&&!K.nativeAgent?typeof K.metadata.nativeReadOnlyReason=="string"?K.metadata.nativeReadOnlyReason:"Read-only history: the native source does not report its original working directory.":null),r.current.active&&r.current.selectedSessionId===F&&await s(K)}catch(K){J===c.current&&P(K instanceof Error?K.message:"Could not read this conversation.")}finally{J===c.current&&M(null)}}}h.useEffect(()=>{if(!a||!e||_!==null||!n||n.metadata?.nativeHistoryLoaded!==!1||n.metadata.nativeBranch)return;const ee=n.metadata.nativeHistoryId;if(typeof ee!="string")return;const H=`${c.current}:${n.id}`;i.current!==H&&(i.current=H,z(ee,void 0,n.id))},[e,n,_,a]);async function $(ee){const H=c.current;if(e){M(ee);try{await L(e,"/v1/native-history/collector",{method:"POST",body:JSON.stringify({command:ee})}),H===c.current&&await R()}catch(F){H===c.current&&P(F instanceof Error?F.message:"Collector action failed.")}finally{H===c.current&&M(null)}}}async function V(ee,H){const F=c.current;if(e){M(ee);try{const J=await L(e,"/v1/native-history/collector",{method:"POST",body:JSON.stringify({command:ee,connectionId:H})});if(F!==c.current)return;S(J.command),P(null)}catch(J){F===c.current&&P(J instanceof Error?J.message:"Could not change Importer connection.")}finally{F===c.current&&M(null)}}}async function Y(ee){const H=c.current;if(e){M("connect");try{const F=await L(e,"/v1/native-history/collector",{method:"POST",body:JSON.stringify({command:ee?"reconnect":"connect",connectionId:ee})});if(H!==c.current)return;S(F.command),P(null)}catch(F){H===c.current&&P(F instanceof Error?F.message:"Could not open Importer setup.")}finally{H===c.current&&M(null)}}}async function se(ee){const H=ee.metadata?.nativeHistoryId;await s(ee)&&ee.metadata?.nativeHistoryProjection&&!ee.metadata.nativeBranch&&typeof H=="string"&&z(H,void 0,ee.id)}return{connection:e,history:b,error:C,busy:_,command:f,expanded:E,branchSelection:y,setCommand:S,setExpanded:T,setBranchSelection:I,refresh:R,more:O,open:z,control:$,connectionControl:V,connect:Y,select:se}}function YB({history:e}){const{connection:t,history:n,error:a,busy:s,command:r,expanded:i,branchSelection:c,setCommand:l,setExpanded:u,setBranchSelection:p,refresh:f,more:S,open:b,control:w,connectionControl:C,connect:P}=e;return t?g.jsxs("section",{className:"sidebar-section native-conversations","aria-label":"Conversation import controls",children:[g.jsxs("div",{className:"sidebar-section-heading",children:[g.jsx("button",{type:"button",onClick:()=>u(_=>!_),"aria-expanded":i,children:"Import conversations"}),g.jsx("button",{type:"button",className:"sidebar-icon","aria-label":"Refresh saved conversation history",disabled:s!==null,onClick:()=>{f()},children:s==="refresh"?g.jsx(Su,{size:14}):g.jsx(dg,{size:14})})]}),r?g.jsx(GB,{connection:t,command:r,onClose:()=>{l(null),f()}}):null,c?g.jsx(JB,{title:n?.items.find(_=>_.id===c.id)?.title??"",inspection:c.inspection,busy:s!==null,onSelect:_=>{b(c.id,_,c.originSessionId??null)},onRefresh:()=>{b(c.id,void 0,c.originSessionId??null)},onClose:()=>p(null)}):null,i?g.jsxs(g.Fragment,{children:[g.jsx("button",{type:"button",disabled:s!==null,onClick:()=>{P()},children:"Connect an import source"}),n&&Object.keys(n.nextCursors).length?g.jsx("button",{type:"button",disabled:s!==null,onClick:()=>{S()},children:"Load more saved conversations"}):null,n&&n.items.length===0?g.jsx("p",{children:"No saved conversations found in configured source locations."}):null,n?.warnings.map(_=>g.jsxs("p",{children:[g.jsx(jd,{size:12,"aria-hidden":"true"})," ",_]},_)),n?.collector.connections.length?g.jsx(ZB,{status:n.collector,busy:s!==null,onControl:_=>{w(_)},onConnectionControl:(_,M)=>{C(_,M)},onReconnect:_=>{P(_)}}):g.jsx("p",{children:"Connect an import source to upload conversations. Local history remains available without cloud sync."})]}):null,a?g.jsxs("p",{role:"status",children:[g.jsx(jd,{size:12,"aria-hidden":"true"})," ",a]}):null]}):null}const CI="openpond.sidebar.continuous-learning.dismissed.v1";function Wb(e=RI()){if(!e)return!1;try{return e.getItem(CI)==="true"}catch{return!1}}function XB(e=RI()){if(e)try{e.setItem(CI,"true")}catch{}}function RI(){return typeof window>"u"?null:no}function e4({connection:e,onOpenSettings:t}){const[n,a]=h.useState(null),[s,r]=h.useState(Wb);fi(()=>r(Wb()));const i=h.useCallback(async()=>{if(!e){a(null);return}try{a(await Z.harnessHistory(e))}catch{a(null)}},[e]);if(h.useEffect(()=>{i()},[i]),s||!e||!n?.workspace)return null;const c=n.evaluationReviewSchedule,l=c.activityEnabled?`${c.activityBatchSize} outcomes${c.enabled?` + ${c.cadence}`:""}`:c.enabled?c.cadence:"Manual";return g.jsxs("section",{className:"sidebar-learning-notice","aria-label":"Continuous learning",children:[g.jsxs("header",{children:[g.jsx("strong",{children:"Continuous learning"}),g.jsxs("div",{className:"sidebar-learning-notice-actions",children:[g.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Open Continuous learning settings",onClick:t,type:"button",children:g.jsx(Ww,{size:14})}),g.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{r(!0),XB()},type:"button",children:g.jsx(el,{size:14})})]})]}),g.jsxs("div",{className:"sidebar-learning-status",children:[g.jsx("strong",{children:"Refiner"}),g.jsx("span",{children:n.backgroundReview.enabled?"On":"Off"})]}),g.jsxs("div",{className:"sidebar-learning-status",children:[g.jsx("strong",{children:"Continuous Review"}),g.jsx("span",{children:l})]})]})}function t4(e){const{productArea:t,setSectionMenuOpen:n,setSelectedAppId:a,setSelectedProjectId:s,setSelectedSessionId:r,setSidebarOpen:i,setView:c,view:l,modelProjects:u,modelTrainingActivityByProjectId:p}=e,f=h.useCallback(w=>{n(w)},[n]),S=h.useCallback(async w=>{if(!await Lt({kind:"chat",sessionId:w.id}))return!1;r(w.id);const C=e.sidebarProjectIdBySessionId[w.id]??null;return s(C),a(C?null:w.appId),c("chat"),!0},[r,s,a,c,e.sidebarProjectIdBySessionId]),b=QB({connection:t==="chat"?e.connection:null,active:l==="chat",selectedSessionId:e.selectedSessionId,selectedSession:[...e.activeSessions,...e.archivedSessions,...Object.values(e.childSessionRowsByParentId??{}).flat()].find(w=>w.id===e.selectedSessionId)??null,onOpen:S});return g.jsxs("aside",{className:"sidebar",inert:e.open===!1,children:[g.jsxs("div",{className:"sidebar-toolbar",children:[g.jsx("button",{className:"sidebar-icon","aria-label":"Hide sidebar",onClick:()=>i(!1),children:g.jsx(Kw,{size:16})}),g.jsx("div",{className:"sidebar-brand",children:g.jsx("img",{className:"sidebar-wordmark",src:Xq,alt:"OpenPond"})}),g.jsx(VU,{hasRunningWork:e.runningSessionIds.size>0||Object.values(e.terminalSummaries).some(w=>w.tabCount>0)})]}),t==="chat"?g.jsxs("div",{className:"sidebar-fixed-actions",children:[g.jsx(rq,{experience:e.experience,beginNewChat:e.beginNewChat}),t==="chat"&&l==="chat"&&e.account?.activeProfile&&e.onOpenPonder?g.jsx("div",{className:"sidebar-ponder-fixed",children:g.jsxs("button",{type:"button",className:"sidebar-row sidebar-task-row sidebar-ponder-entry",onClick:e.onOpenPonder,children:[g.jsx("span",{className:"conversation-source-icon","aria-hidden":"true",children:g.jsx("img",{src:Tg,alt:""})}),g.jsx("span",{children:"Ponder Pal"})]})}):null]}):null,g.jsxs("div",{className:"sidebar-scroll",children:[t!=="chat"?g.jsx(oq,{productArea:t,setSectionMenuOpen:f,setSelectedAppId:a,setSelectedProjectId:s,setSelectedSessionId:r,setView:c,view:l,modelProjects:u,modelTrainingActivityByProjectId:p}):null,t!=="chat"||l!=="chat"?null:g.jsx(KB,{...e,onSelectSession:b.select,setSectionMenuOpen:f}),t==="chat"&&l==="chat"?g.jsx(YB,{history:b}):null]}),g.jsx("div",{className:"sidebar-bottom-stack",children:t!=="chat"?null:g.jsx(e4,{connection:e.connection,onOpenSettings:()=>{n(null),Lt({kind:"settings",section:"harness"})}})})]})}const n4=[{destination:"walkthroughs",icon:wb,label:"Walkthroughs"},{destination:"external",icon:wb,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:og,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:ZH,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:Vw,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:oU,label:"GitHub",url:"https://github.com/openpond/openpond"},{destination:"external",icon:xu,label:"Submit issue",url:"https://github.com/openpond/openpond/issues/new/choose"}];function a4({onOpenWalkthroughs:e,onCloseAccount:t,walkthroughsActive:n}){const[a,s]=h.useState(!1),r=h.useRef(null),i=h.useRef(null);h.useLayoutEffect(()=>{a&&i.current?.querySelector('[role="menuitem"]')?.focus()},[a]);function c(){s(!0)}function l(){s(!1),r.current?.focus()}return g.jsxs("div",{className:"user-auth-help",onKeyDown:u=>{a&&(u.key==="Escape"||u.key==="ArrowLeft")&&(u.preventDefault(),u.stopPropagation(),l())},children:[g.jsxs("button",{ref:r,type:"button",className:"user-auth-menu-link",role:"menuitem","aria-haspopup":"menu","aria-expanded":a,onClick:()=>a?l():c(),onKeyDown:u=>{u.key==="ArrowRight"&&(u.preventDefault(),c())},children:[g.jsx(lU,{size:15}),g.jsx("span",{children:"Help"}),g.jsx(pr,{className:"user-auth-help-chevron",size:14})]}),a?g.jsx("div",{ref:i,className:"user-auth-help-submenu",role:"menu","aria-label":"Help",onKeyDown:u=>{if(!["ArrowDown","ArrowUp","Home","End"].includes(u.key))return;u.preventDefault();const p=Array.from(i.current?.querySelectorAll('[role="menuitem"]')??[]),f=p.indexOf(document.activeElement),S=u.key==="Home"?0:u.key==="End"?p.length-1:(f+(u.key==="ArrowDown"?1:-1)+p.length)%p.length;p[S]?.focus()},children:n4.map(u=>{const p=u.icon,f=g.jsxs(g.Fragment,{children:[g.jsx(p,{size:15}),g.jsx("span",{children:u.label})]});return u.destination==="walkthroughs"?g.jsx("button",{type:"button",role:"menuitem",className:"user-auth-menu-link","aria-current":n?"page":void 0,onClick:()=>{t(),e()},children:f},u.label):g.jsx("a",{className:"user-auth-menu-link",role:"menuitem",href:u.url,target:"_blank",rel:"noreferrer",onClick:S=>{S.preventDefault(),t(),s4(u.url)},children:f},u.label)})}):null]})}async function s4(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const Gb=new WeakMap,kf=new WeakMap;function PI(e){if(!e)return"disconnected";let t=Gb.get(e);return(!t||t.serverUrl!==e.serverUrl||t.token!==e.token)&&(t={serverUrl:e.serverUrl,token:e.token,id:crypto.randomUUID()},Gb.set(e,t)),t.id}function CG(e,t){return kf.set(e,t),e}function RG(e){if(!e)return["learning","disconnected"];let t=kf.get(e);return t||(t=["learning",crypto.randomUUID()],kf.set(e,t)),t}function r4(e,t){return P0({queryKey:["provider-plan-usage",PI(e),t],enabled:!!e,queryFn:({signal:n})=>L(e,`/v1/providers/${t}/plan-usage`,{signal:AbortSignal.any([n,AbortSignal.timeout(25e3)])}),staleTime:3e4,refetchInterval:6e4,refetchOnWindowFocus:"always",retry:!1,gcTime:3e5})}function pp(e){return`${Math.floor(e)}%`}function Zb(e){return e.resetsAt?`Resets ${new Date(e.resetsAt).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}`:"Reset time unavailable"}function o4(e,t){return t?"Loading…":e?.status==="signed_out"?"Sign in":e?.status==="unsupported"?"Not available":"Unavailable"}function i4({connection:e,provider:t,compact:n=!1,onOpen:a}){const s=r4(e,t),r=s.data,i=r?.windows.filter(b=>b.shared)??[],c=!!r?.windows.some(b=>b.resetsAt&&Date.parse(b.resetsAt)<=Date.now()),l=s.isError||c||!!(r&&Date.parse(r.refreshAfter)+6e4<Date.now()),u=t==="claude-code"?"Claude":"Codex",p=r?.status==="ready",f=o4(r,s.isPending&&!!e),S=r?.windows.map(b=>`${b.label}: ${pp(b.remainingPercent)} remaining. ${Zb(b)}.`).join(`
111
+ `);return n?g.jsxs("button",{type:"button",role:"menuitem",className:"plan-usage-compact",onClick:a,title:l?`Usage needs refreshing. ${S??""}`:S||r?.message||"View plan usage in Providers",children:[g.jsx("span",{children:u}),g.jsx("span",{className:"plan-usage-compact-values",children:!l&&p&&i.length?i.map(b=>g.jsxs("span",{className:"plan-usage-compact-value",children:[g.jsx("small",{children:b.label}),g.jsx("strong",{children:pp(b.remainingPercent)})]},b.id)):g.jsx("strong",{children:l?"Unavailable":f})})]}):g.jsxs("section",{className:"provider-plan-usage","aria-label":`${u} plan usage`,children:[g.jsx("div",{className:"plan-usage-heading",children:g.jsx("button",{type:"button",className:"plan-usage-refresh","aria-label":`Refresh ${u} plan usage`,title:`Check usage (cached for up to ${t==="claude-code"?"5 minutes":"1 minute"})`,disabled:!e||s.isFetching,onClick:()=>{s.refetch()},children:g.jsx(dg,{size:13,className:s.isFetching?"settings-spin":void 0})})}),p?g.jsxs(g.Fragment,{children:[r.windows.map(b=>g.jsxs("div",{className:"plan-usage-window",children:[g.jsxs("div",{children:[g.jsx("span",{children:b.label}),g.jsxs("strong",{children:[pp(b.remainingPercent),l?" · last known":""]})]}),g.jsx("meter",{min:0,max:100,low:10,high:25,optimum:100,value:b.remainingPercent,"aria-label":`${u} ${b.label} remaining`}),g.jsx("small",{children:Zb(b)})]},b.id)),l?g.jsxs("small",{role:"status",children:["Usage needs refreshing. Last checked ",new Date(r.fetchedAt).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),"."]}):g.jsx("small",{className:"plan-usage-note",children:"Shared across your account. Updates automatically."})]}):g.jsx("p",{role:"status",children:s.isError?"Could not load usage. Try refreshing.":r?.message??(e?"Loading plan usage…":"Connect to load plan usage.")})]})}function c4(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function l4(e){const t=e?.accounts.find(i=>i.isActive)??null,n=e?.profile??null,a=e?.activeProfile?.handle??null;return{label:(e?.state==="signed_in"?c4(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 d4({connection:e,onOpenProviders:t,account:n,open:a,organizations:s,selectedTeamId:r,onOpenActivity:i,onOpenChange:c,onOpenSettings:l,onOpenWalkthroughs:u,walkthroughsActive:p,onSelectTeam:f,onLogOut:S,railTooltip:b}){const[w,C]=h.useState(null),[P,_]=h.useState(!1),M=h.useRef(null),E=h.useMemo(()=>l4(n),[n]),T=E.label.trim().slice(0,1).toUpperCase();return h.useEffect(()=>{if(!a)return;function y(R){M.current?.contains(R.target)||c(!1)}function I(R){R.key==="Escape"&&c(!1)}return document.addEventListener("pointerdown",y),document.addEventListener("keydown",I),()=>{document.removeEventListener("pointerdown",y),document.removeEventListener("keydown",I)}},[c,a]),g.jsxs("div",{className:"user-auth-footer",ref:M,children:[g.jsxs("button",{type:"button",className:`user-auth-trigger ${a?"active":""}`,"aria-haspopup":"menu","aria-expanded":a,"aria-label":`${E.label} account menu`,"data-rail-tooltip":b,onClick:()=>c(!a),children:[g.jsx("span",{className:"user-auth-avatar","aria-hidden":"true",children:E.image?g.jsx("img",{src:E.image,alt:""}):T?g.jsx("span",{children:T}):g.jsx(Cb,{size:16})}),g.jsx("span",{className:"user-auth-name",children:E.label})]}),a?g.jsxs("div",{className:"user-auth-menu",role:"menu","aria-label":"Account",children:[g.jsxs("div",{className:"user-auth-menu-header",children:[g.jsx("span",{className:"user-auth-menu-avatar","aria-hidden":"true",children:E.image?g.jsx("img",{src:E.image,alt:""}):T?g.jsx("span",{children:T}):g.jsx(Cb,{size:17})}),g.jsxs("span",{className:"user-auth-menu-identity",children:[g.jsx("strong",{children:E.label}),n?.state==="signed_in"&&n.environment?g.jsx("small",{title:n.baseUrl??void 0,children:n.environment==="production"?"Production":n.environment==="staging"?"Staging":n.environment}):null]})]}),s.length>0&&f?g.jsxs("div",{children:[g.jsxs("label",{className:"user-auth-team-picker",children:[g.jsx(ug,{size:15,"aria-hidden":"true"}),g.jsx("span",{className:"user-auth-team-picker-label",children:"Team"}),g.jsxs("select",{"aria-label":"Active team","aria-describedby":"account-task-ownership-hint",disabled:w!==null,value:r??"",onChange:async y=>{const I=y.currentTarget.value;C(I);try{await f(I||null)}catch{}finally{C(null)}},children:[g.jsx("option",{value:"",children:"Personal account"}),r&&!s.some(y=>y.teamId===r)?g.jsx("option",{value:r,disabled:!0,children:"Selected workspace unavailable"}):null,s.map(y=>g.jsx("option",{value:y.teamId,children:y.displayName},y.teamId))]})]}),g.jsx("p",{className:"user-auth-task-ownership-hint",id:"account-task-ownership-hint",children:"New tasks use this selection. Existing tasks keep their owner."})]}):null,g.jsx("div",{className:"user-auth-plan-usage",children:["claude-code","codex"].map(y=>g.jsx(i4,{connection:e,provider:y,compact:!0,onOpen:()=>{c(!1),t()}},y))}),g.jsx("div",{className:"user-auth-menu-divider"}),i?g.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{c(!1),i()},children:[g.jsx(qw,{size:15}),g.jsx("span",{children:"Activity"})]}):null,g.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{c(!1),l()},children:[g.jsx(Ww,{size:15}),g.jsx("span",{children:"Settings"})]}),g.jsx(a4,{onOpenWalkthroughs:u,walkthroughsActive:p,onCloseAccount:()=>c(!1)}),n?.state==="signed_in"&&S?g.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",disabled:P,onClick:async()=>{_(!0);try{await S(),c(!1)}catch{}finally{_(!1)}},children:[g.jsx(IU,{size:15}),g.jsx("span",{children:P?"Logging out…":"Log out"})]}):null]}):null]})}function u4({sidebar:e,open:t}){const[n,a]=h.useState(!1),s=[{view:"chat",label:"Home",Icon:Jw},{view:"scheduled",label:"Workflows",Icon:Uw},{view:"outputs",label:"Outputs",Icon:Bw},{view:"apps",label:"Apps",Icon:ug},{view:"projects",label:"Projects",Icon:ig}];async function r(c){if(a(!1),e.productArea==="chat"&&e.view===c){c==="chat"&&e.setSidebarOpen(!t);return}const l=c==="chat"?{kind:"chat",sessionId:e.selectedSessionId}:{kind:"view",view:c};await Lt(l)&&(e.setSectionMenuOpen(null),e.setView(c),c==="chat"&&e.setSidebarOpen(!0))}async function i(){await Lt({kind:"view",view:"get-started"})&&(e.setSelectedAppId(null),e.setSelectedProjectId(null),e.setSelectedSessionId(null),e.setSectionMenuOpen(null),e.setView("get-started"))}return g.jsxs("nav",{className:"desktop-navigation-rail","aria-label":"Desktop destinations",children:[g.jsxs("div",{className:"desktop-rail-destinations",children:[g.jsx("button",{type:"button","data-rail-tooltip":"Training","aria-label":"Training",className:`desktop-rail-button desktop-training-entry${e.productArea==="console"?" active":""}`,"aria-expanded":e.productArea==="console"&&t,onClick:()=>{e.productArea==="console"?e.setSidebarOpen(!t):(e.onProductAreaChange("console"),e.setSidebarOpen(!0))},children:g.jsx(GU,{size:19})}),s.map(({view:c,label:l,Icon:u})=>{const p=e.productArea==="chat"&&e.view===c;return g.jsx("button",{type:"button","data-rail-tooltip":l,"aria-label":l,"aria-current":p?"page":void 0,"aria-expanded":c==="chat"?p&&t:void 0,className:`desktop-rail-button${p?" active":""}`,onClick:()=>{r(c)},children:g.jsx(u,{size:19})},c)}),[{view:"team",label:"Team chat",Icon:xu,onOpen:e.onOpenTeamChat},{view:"community",label:"Discover communities",Icon:Vw,onOpen:e.discoverCommunities}].map(({view:c,label:l,Icon:u,onOpen:p})=>g.jsx("button",{type:"button","data-rail-tooltip":l,"aria-label":l,className:`desktop-rail-button${e.productArea==="chat"&&e.view===c?" active":""}`,"aria-current":e.productArea==="chat"&&e.view===c?"page":void 0,onClick:()=>{a(!1),(e.productArea!=="chat"||e.view!==c)&&p()},children:g.jsx(u,{size:19})},c))]}),g.jsx("div",{className:"desktop-rail-account",children:g.jsx(d4,{account:e.account,open:n,onOpenChange:a,connection:e.connection,onOpenProviders:()=>{Lt({kind:"settings",section:"providers"})},railTooltip:n?void 0:"Account",organizations:e.organizations,selectedTeamId:e.selectedTeamId,onSelectTeam:e.onSelectTeam,onLogOut:e.onLogOut,walkthroughsActive:e.view==="get-started",onOpenWalkthroughs:()=>{i()},onOpenActivity:()=>{Lt({kind:"settings",section:"usage"})},onOpenSettings:()=>{Lt({kind:"settings",section:"account"})}})})]})}const m4=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function TI(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?AI(a)?"Couldn’t connect to OpenPond.":a:t}function AI(e){const t=e.trim();return m4.some(n=>n.test(t))}const EI=h.createContext(null);function Jb({children:e,showToast:t}){return g.jsx(EI.Provider,{value:t,children:e})}function p4(){return h.useContext(EI)}function Qb(e,t={}){const n=p4(),a=h.useRef(null),s=t.enabled??!0,r=t.fallback??"Something went wrong.",i=t.prefix?.trim()??"",c=e==null||e===""?null:`${i}${i?": ":""}${TI(e,r)}`;h.useEffect(()=>{if(!s||!c){a.current=null;return}a.current!==c&&(a.current=c,n?.(c,"error"))},[s,c,n])}function f4({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(Qb(e?.previewError,{prefix:"Upload preview"}),Qb(e?.error,{prefix:"Cloud setup"}),!e)return null;const s=e.status==="uploading",r=e.status==="ready",i=e.status==="error",c=e.projectKind==="cloud",l=e.preview??null;return g.jsx("div",{className:"git-dialog-backdrop",role:"presentation",children:g.jsxs("section",{className:"git-dialog cloud-setup-dialog",role:"dialog","aria-modal":"true","aria-label":"Set up Cloud coding",children:[g.jsx("button",{className:"git-dialog-close",disabled:s,type:"button",onClick:t,"aria-label":"Close Cloud setup",title:"Close",children:g.jsx(el,{size:14})}),g.jsx("div",{className:"git-dialog-icon",children:r?g.jsx(rd,{size:18}):g.jsx(yu,{size:18})}),g.jsx("h2",{children:r?"Cloud repo ready":"Set up Cloud coding"}),g.jsx("p",{children:r?"Your source is ready in OpenPond Git. Finish by creating the Cloud sandbox environment.":c?"This Cloud Project is ready for a sandbox environment.":"OpenPond will upload tracked and unignored files into OpenPond Git, then send you to the Cloud sandbox setup page."}),g.jsxs("div",{className:"cloud-setup-summary",children:[g.jsxs("div",{className:"git-dialog-row",children:[g.jsx("span",{children:"Project"}),g.jsx("strong",{children:e.projectName})]}),g.jsxs("div",{className:"git-dialog-row",children:[g.jsx("span",{children:"Source"}),g.jsx("strong",{children:c?"OpenPond Git":"Local project upload"})]}),g.jsxs("div",{className:"git-dialog-row",children:[g.jsx("span",{children:"Branch"}),g.jsx("strong",{children:l?.branch??e.branch??"main"})]}),!c&&g.jsxs("div",{className:"git-dialog-row",children:[g.jsx("span",{children:"Cloud project"}),g.jsx("strong",{children:l?.targetProjectId??e.cloudProjectId??"New on upload"})]})]}),!r&&!c&&g.jsx("div",{className:"cloud-setup-upload-preview",role:"status","aria-live":"polite",children:e.previewLoading?g.jsxs(g.Fragment,{children:[g.jsx("strong",{children:"Calculating upload preview"}),g.jsx("span",{children:"Checking tracked and unignored files before anything is pushed."})]}):e.previewError?g.jsxs(g.Fragment,{children:[g.jsx("strong",{children:"Preview unavailable"}),g.jsx("span",{children:"Close and reopen setup to try the preview again."})]}):l?g.jsxs(g.Fragment,{children:[g.jsx("strong",{children:l.initializedEmptyProject?"Will initialize an empty project":`Will upload ${l.fileCount} files`}),g.jsx("span",{children:Yb({byteCount:l.byteCount,skippedCount:l.skippedCount,headCommit:l.headCommit,targetProjectName:l.targetProjectName})})]}):g.jsxs(g.Fragment,{children:[g.jsx("strong",{children:"Upload preview pending"}),g.jsx("span",{children:"File count, byte count, and skipped files will appear here before upload."})]})}),s&&g.jsxs("div",{className:"cloud-setup-progress",role:"status","aria-live":"polite",children:[g.jsx(Su,{className:"cloud-setup-spinner",size:16}),g.jsx("span",{children:"Uploading source to OpenPond Git..."})]}),r&&e.upload&&g.jsxs("div",{className:"cloud-setup-upload-result",children:[g.jsx("strong",{children:e.upload.initializedEmptyProject?"Initialized empty project":`Uploaded ${e.upload.fileCount} files`}),g.jsx("span",{children:Yb({byteCount:e.upload.byteCount,skippedCount:e.upload.skippedCount,headCommit:e.upload.headCommit,targetProjectName:e.upload.branch})})]}),r&&e.setupUrl&&g.jsxs("div",{className:"cloud-setup-next",children:[e.projectUrl?g.jsxs("span",{children:["Your repo is ready here:"," ",g.jsxs("a",{href:e.projectUrl,target:"_blank",rel:"noreferrer",onClick:u=>fp(u,e.projectUrl,n,{newTab:!0}),children:["Project page",g.jsx(rp,{size:13})]})]}):g.jsx("span",{children:"Your repo is ready. Next step:"}),g.jsxs("a",{href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:u=>fp(u,e.setupUrl,n),children:["Setup the Cloud sandbox",g.jsx(rp,{size:13})]})]}),g.jsxs("div",{className:"git-dialog-footer",children:[g.jsx("button",{className:"git-dialog-secondary",disabled:s,type:"button",onClick:t,children:r?"Done":"Cancel"}),r?e.setupUrl?g.jsxs("a",{className:"git-dialog-primary cloud-setup-primary-link",href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:u=>fp(u,e.setupUrl,n),children:["Open setup",g.jsx(rp,{size:13})]}):null:g.jsx("button",{className:"git-dialog-primary",disabled:s,type:"button",onClick:a,children:s?"Uploading":i?"Try again":c?"Show setup link":"Upload source"})]})]})})}function fp(e,t,n,a={}){!t||!n||(e.preventDefault(),n(t,a))}function h4(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 Yb({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const s=[h4(e),`${t} skipped`],r=g4(n);return r&&s.push(`local ${r}`),s.push(a),s.join(" · ")}function g4(e){const t=e?.trim();return t?t.slice(0,7):null}const v4=h.lazy(()=>fr(()=>import("./CommandMenu-CFW3WJ11.js"),__vite__mapDeps([4,1,2,5])).then(e=>({default:e.CommandMenu}))),b4=h.lazy(()=>fr(()=>import("./SettingsView-BhcP72KH.js"),__vite__mapDeps([6,1,2,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25])).then(e=>({default:e.SettingsView}))),y4=h.lazy(()=>fr(()=>import("./NewProjectDialog-DIyjAxJG.js"),__vite__mapDeps([26,1,2,12,18,27])).then(e=>({default:e.NewProjectDialog}))),S4=h.lazy(()=>fr(()=>import("./WorkspaceGitDialogs-CBViLL3S.js"),__vite__mapDeps([28,1,2,15,16,29,25])).then(e=>({default:e.CommitDialog}))),x4=h.lazy(()=>fr(()=>import("./WorkspaceGitDialogs-CBViLL3S.js"),__vite__mapDeps([28,1,2,15,16,29,25])).then(e=>({default:e.BranchDialog})));function k4({payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:s,onError:r,onToast:i,onBack:c,onOpenSourceSession:l,onStartRefinerAuthoring:u,onAcceptEvaluationReview:p,onOpenSkill:f,onOpenExtension:S,teamChatCurrentUserId:b,teamChatEnabled:w,teamChatNotificationMode:C,teamChatThreads:P,onTeamChatNotificationModeChange:_,onTeamChatThreadMuteChange:M,diffPanelWidth:E,diffPanelResizing:T,diffPanelExpanded:y,onDiffPanelResizeStart:I,onDiffPanelExpandedChange:R}){return g.jsx(h.Suspense,{fallback:null,children:g.jsx(b4,{payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:s,onError:r,onToast:i,onBack:c,onOpenSourceSession:l,onStartRefinerAuthoring:u,onAcceptEvaluationReview:p,onOpenSkill:f,onOpenExtension:S,teamChatCurrentUserId:b,teamChatEnabled:w,teamChatNotificationMode:C,teamChatThreads:P,onTeamChatNotificationModeChange:_,onTeamChatThreadMuteChange:M,diffPanelWidth:E,diffPanelResizing:T,diffPanelExpanded:y,onDiffPanelResizeStart:I,onDiffPanelExpandedChange:R})})}function w4({activeSessions:e,branchDialogName:t,branchDialogOpen:n,commitDialogOpen:a,commitDraft:s,commitIncludeUnstaged:r,commitMessage:i,commitNextStep:c,canPublishOpenPondProject:l,expandProject:u,newProjectBusy:p,newProjectDialogOpen:f,newProjectDirectory:S,newProjectMode:b,newProjectName:w,newProjectPath:C,projectRows:P,query:_,searchOpen:M,visibleWorkspaceDiff:E,visibleWorkspaceState:T,workspaceBusy:y,appDispatch:I,beginNewChat:R,openDefaultsSettingsFromBranchDialog:O,setBranchDialogName:z,setBranchDialogOpen:$,setCommitDialogOpen:V,setCommitDraft:Y,setCommitIncludeUnstaged:se,setCommitMessage:ee,setCommitNextStep:H,setNewProjectDialogOpen:F,setNewProjectName:J,setNewProjectPath:K,setQuery:B,setSearchOpen:ne,submitCommitDialog:G,submitCreateWorkspaceBranch:te,submitNewProjectDialog:oe}){return g.jsxs(g.Fragment,{children:[M&&g.jsx(h.Suspense,{fallback:null,children:g.jsx(v4,{open:M,query:_,projects:P,sessions:e,onQueryChange:B,onClose:()=>{ne(!1),B("")},onNewChat:()=>{ne(!1),B(""),R()},onOpenProject:be=>{I({type:"selectProject",projectId:be.id}),I({type:"patch",patch:{searchOpen:!1,query:""}}),u(be.id)},onOpenSession:be=>{I({type:"selectSession",sessionId:be.id,appId:be.appId,projectId:be.workspaceKind==="local_project"&&be.workspaceId?ct("local",be.workspaceId):null}),I({type:"patch",patch:{searchOpen:!1,query:""}})}})}),f&&g.jsx(h.Suspense,{fallback:null,children:g.jsx(y4,{open:f,mode:b,name:w,path:C,directory:S,busy:p,onNameChange:J,onPathChange:K,onClose:()=>{p||F(!1)},onSubmit:oe})}),a&&g.jsx(h.Suspense,{fallback:null,children:g.jsx(S4,{open:a,branch:T?.currentBranch??null,filesChanged:E?.filesChanged??T?.changedFilesCount??0,additions:E?.additions??0,deletions:E?.deletions??0,message:i,includeUnstaged:r,nextStep:c,draft:s,busy:y,canPush:!!T?.remoteUrl,canPublish:l,onMessageChange:ee,onIncludeUnstagedChange:se,onNextStepChange:H,onDraftChange:Y,onClose:()=>{y||V(!1)},onSubmit:G})}),n&&g.jsx(h.Suspense,{fallback:null,children:g.jsx(x4,{open:n,branchName:t,busy:y,onBranchNameChange:z,onSetPrefix:O,onClose:()=>{y||$(!1)},onSubmit:te})})]})}function jI({toast:e,onDismiss:t}){if(!e)return null;const n=!!(e.actionLabel&&e.onAction);return g.jsxs("div",{className:`app-toast ${e.tone} ${e.placement??"bottom-right"}`,role:e.tone==="error"?"alert":"status","aria-live":"polite",children:[g.jsx("span",{className:"app-toast-message",children:e.message}),n&&g.jsx("div",{className:"app-toast-actions",children:g.jsx("button",{type:"button","aria-label":e.actionLabel,onClick:()=>{t(),e.onAction?.()},children:e.actionLabel})})]})}async function Bl(e,t,n){if(t.scope!==e.scope)throw new Error("Review workspace changed. Reload the assignment.");return L(e.connection,`/v1/human-review?location=${e.location}`,{method:"POST",body:JSON.stringify(_O.parse(t)),signal:n})}function Xb(e,t,n){const a=wx.parse(e);if(a.scope!==t.scope||a.id!==n)throw new Error("Review response identity differs from the requested assignment.");return a}const I4={inbox:async(e,t,n)=>_4(await Bl(e,{...t,endpoint:"inbox",scope:e.scope},n),e),get:async(e,t,n)=>Xb(await Bl(e,{endpoint:"get",scope:e.scope,id:t},n),e,t),inspect:async(e,t,n,a,s)=>C4(await Bl(e,{endpoint:"inspect",scope:e.scope,id:t,...n===void 0?{}:{slot:n},...a?{afterId:a}:{}},s),t),command:async(e,t)=>Xb(await Bl(e,{endpoint:"command",scope:e.scope,command:t}),e,t.id)};function _4(e,t){const n=mO.parse(e);if(n.items.some(a=>a.scope!==t.scope))throw new Error("Inbox response belongs to another workspace.");return n}function C4(e,t){const n=CO.parse(e);if(n.some(a=>a.reviewId!==t))throw new Error("Evidence response belongs to another assignment.");return n}function R4({context:e,onOpen:t}){const[n,a]=h.useState(null);return h.useEffect(()=>{const s=new AbortController;let r=0;async function i(){const l=++r;try{const u=await I4.inbox(e,{view:"mine",status:"active",limit:1},s.signal);!s.signal.aborted&&l===r&&a(u.actionCount)}catch{!s.signal.aborted&&l===r&&a(null)}}a(null),i();const c=window.setInterval(()=>{document.visibilityState==="visible"&&i()},15e3);return window.addEventListener("human-review-changed",i),()=>{s.abort(),window.clearInterval(c),window.removeEventListener("human-review-changed",i)}},[e.scope,e.actorId,e.location,e.connection]),g.jsxs("button",{type:"button",className:"titlebar-icon human-review-inbox-control",title:n?`Inbox · ${n} actions`:"Inbox","aria-label":n?`Inbox, ${n} actions`:"Inbox",onClick:t,children:[g.jsx(mg,{size:17,"aria-hidden":"true"}),n?g.jsx("span",{className:"human-review-inbox-count","aria-hidden":"true",children:n>99?"99+":n}):null]})}function P4({connection:e,teamId:t,actorId:n,projectId:a}){if(!e||!t||!n)return null;const s=()=>{Fr(wa("inbox",null,{area:"console",projectId:a}))};return g.jsx(R4,{context:{connection:e,scope:t,actorId:n,location:"hosted"},onOpen:s})}const nl=h.createContext(null);function T4({children:e}){const[t,n]=h.useState(null),[a,s]=h.useState(null),[r,i]=h.useState(null),c=h.useMemo(()=>({title:t,actions:a,activity:r,setTitle:n,setActions:s,setActivity:i}),[t,a,r]);return g.jsx(nl.Provider,{value:c,children:e})}function PG({children:e}){return g.jsx(nl.Provider,{value:null,children:e})}function A4({children:e,className:t=""}){const n=h.useContext(nl);return g.jsx("div",{ref:n?.setTitle,className:`page-chrome-title-target ${t}`,children:e?g.jsx("div",{className:"page-chrome-fallback",children:e}):null})}function E4({className:e=""}){const t=h.useContext(nl);return g.jsx("div",{ref:t?.setActions,className:e})}function TG({title:e,actions:t,fallback:n,children:a}){const s=h.useContext(nl);return s?g.jsxs(g.Fragment,{children:[s.title?Dd.createPortal(g.jsx("div",{className:"page-chrome-title",children:e}),s.title):null,s.actions&&t?Dd.createPortal(t,s.actions):null,a]}):n??g.jsxs("header",{children:[e,t]})}const j4=h.lazy(()=>fr(()=>import("./WorkspaceEnvironmentMenu-xUYg-iGn.js"),__vite__mapDeps([30,1,2,21,27,13,16,31,29,32])).then(e=>({default:e.WorkspaceEnvironmentMenu})));function M4({sidebarOpen:e,sidebarAvailable:t=!0,title:n,breadcrumbs:a,backAction:s,workspaceName:r,workspaceId:i,busy:c,workspaceState:l,workspaceKind:u,selectedApp:p,selectedProject:f,workspaceDiff:S,managedWorkspace:b,workspaceBusy:w,defaultTeamId:C,activityActorId:P,activityProjectId:_,showDiffControls:M,diffPanelOpen:E,terminalOpen:T,rightSidebarAvailable:y=!1,rightSidebarOpen:I=!1,onToggleDiffPanel:R,onToggleRightSidebar:O,onOpenSearch:z,onToggleTerminal:$,onRunTerminalCommand:V,onWorkspaceToolAction:Y,onOpenCommitDialog:se,onWorkspaceBranchChange:ee,onWorkspaceBranchCreate:H,connection:F,onBootstrap:J,onOpenSandboxWorkspace:K,onShowSidebar:B,platform:ne,showWorkspaceControls:G=!0}){const te=S?.filesChanged??0;return g.jsxs("header",{className:"app-titlebar",children:[g.jsxs("div",{className:"titlebar-left",children:[t&&!e&&g.jsx("button",{className:"titlebar-icon",title:"Show sidebar",onClick:B,children:g.jsx(Kw,{size:16})}),s?g.jsx("button",{className:"titlebar-icon",type:"button","aria-label":s.label,title:s.label,onClick:s.onSelect,children:g.jsx(OH,{size:16})}):null,g.jsx(A4,{children:a?.length?g.jsx("nav",{className:"titlebar-breadcrumbs","aria-label":"Breadcrumb",children:a.map((oe,be)=>{const me=be===a.length-1;return g.jsxs("div",{className:"titlebar-breadcrumb-item",children:[oe.onSelect&&!me?g.jsx("button",{type:"button",onClick:oe.onSelect,children:oe.label}):g.jsx("strong",{children:oe.label}),!me&&g.jsx(pr,{size:14})]},`${oe.label}-${be}`)})}):g.jsxs("div",{className:"titlebar-title",children:[g.jsx("strong",{children:n}),r&&g.jsx("span",{children:r})]})})]}),g.jsxs("div",{className:"titlebar-right",children:[g.jsx(E4,{className:"page-chrome-actions"}),g.jsx(P4,{connection:F,teamId:C??null,actorId:P??null,projectId:_??null}),G&&g.jsxs("div",{className:"titlebar-actions",children:[g.jsx(h.Suspense,{fallback:null,children:g.jsx(j4,{mode:"topbar",busy:c,workspaceState:l,workspaceId:i,workspaceKind:u,selectedApp:p,selectedProject:f,workspaceBusy:w,defaultTeamId:C,workspaceDiff:S,managedWorkspace:b,showDiffControls:M,diffPanelOpen:E,onToggleDiffPanel:R,onRunTerminalCommand:V,onWorkspaceToolAction:Y,onOpenCommitDialog:se,onWorkspaceBranchChange:ee,onWorkspaceBranchCreate:H,connection:F,onBootstrap:J,onOpenSandboxWorkspace:K})}),g.jsx("button",{type:"button",className:"titlebar-icon",title:"Search chats and projects","aria-label":"Search chats and projects",onClick:z,children:g.jsx(TU,{size:16})}),g.jsx("button",{type:"button",className:`titlebar-icon ${T?"active":""}`,title:`${T?"Hide":"Show"} terminal`,"aria-label":`${T?"Hide":"Show"} terminal`,"aria-pressed":T,onClick:$,children:g.jsx(Gw,{size:16})}),M&&g.jsx("button",{type:"button",className:`topbar-diff-button ${I?"active":""}`,title:`${I?"Hide":"Show"} sidebar${te?`, ${te} changed files`:""}`,"aria-label":`${I?"Hide":"Show"} sidebar`,"aria-pressed":I,onClick:R,children:g.jsx(df,{size:16})})]}),y&&O&&!M?g.jsx("div",{className:"titlebar-actions",children:g.jsx("button",{type:"button",className:`topbar-diff-button ${I?"active":""}`,title:`${I?"Hide":"Show"} sidebar`,"aria-label":`${I?"Hide":"Show"} sidebar`,"aria-pressed":I,onClick:O,children:g.jsx(df,{size:16})})}):null,g.jsx(zB,{platform:ne})]})]})}function O4(){const[e,t]=h.useState(null),n=h.useRef(null),a=h.useCallback(r=>new Promise(i=>{n.current?.resolve(!1);const c={...r,cancelLabel:r.cancelLabel??"Cancel",tone:r.tone??"default",resolve:i};n.current=c,t(c)}),[]),s=h.useCallback(r=>{const i=n.current;n.current=null,t(null),i?.resolve(r)},[]);return{confirmAction:a,confirmDialog:e,resolveConfirmDialog:s}}function $4({state:e,onResolve:t}){const n=h.useId(),a=h.useId();if(h.useEffect(()=>{if(!e)return;function r(i){i.key==="Escape"&&t(!1)}return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[t,e]),!e)return null;const s=e.tone==="danger"?"git-dialog-primary danger":"git-dialog-primary";return g.jsx("div",{className:"git-dialog-backdrop",role:"presentation",onMouseDown:()=>t(!1),children:g.jsxs("section",{className:"git-dialog project-confirm-dialog",role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":a,onMouseDown:r=>r.stopPropagation(),children:[g.jsx("h2",{id:n,children:e.title}),g.jsx("p",{id:a,children:e.body}),g.jsxs("div",{className:"git-dialog-footer",children:[g.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:()=>t(!1),children:e.cancelLabel}),g.jsx("button",{type:"button",className:s,autoFocus:!0,onClick:()=>t(!0),children:e.confirmLabel})]})]})})}function N4(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=O4();return{confirmProjectAction:h.useCallback(s=>e({tone:"danger",...s}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function D4({state:e,onResolve:t}){return g.jsx($4,{state:e,onResolve:t})}const zd=new Map,L4=(e,t,n)=>{const a=zd.get(e)??{commits:0,maxActualDurationMs:0,totalActualDurationMs:0};a.commits+=1,a.maxActualDurationMs=Math.max(a.maxActualDurationMs,n),a.totalActualDurationMs+=n,zd.set(e,a)};function z4({children:e,id:t}){return g.jsx(h.Profiler,{id:t,onRender:L4,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...zd.entries()].map(([e,t])=>[e,{...t}])),reset:()=>zd.clear()});const H4=h.lazy(()=>fr(()=>import("./MainPane-DCz38-qy.js").then(e=>e.o),__vite__mapDeps([33,1,2,10,34,15,31,12,13,35])).then(e=>({default:e.MainPane})));function U4({className:e,style:t,sidebar:n,topBar:a,mainPane:s,cloudSetup:r,projectConfirm:i,lazyPanels:c,toast:l}){return g.jsx(T4,{children:g.jsxs("div",{className:e,style:t,children:[g.jsx(u4,{sidebar:n,open:a.sidebarOpen}),a.sidebarAvailable!==!1?g.jsxs(z4,{id:"sidebar",children:[g.jsx(t4,{...n,open:a.sidebarOpen}),a.sidebarOpen?g.jsx("div",{className:"sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",onPointerDown:n.onSidebarResizeStart}):null]}):null,g.jsxs("div",{className:"content-shell",children:[g.jsx(M4,{...a}),g.jsx(h.Suspense,{fallback:g.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:g.jsx(H4,{...s})})]}),g.jsx(f4,{...r}),g.jsx(D4,{...i}),g.jsx(w4,{...c}),g.jsx(jI,{...l})]})})}function q4({settings:e,toast:t}){return g.jsxs(g.Fragment,{children:[g.jsx(k4,{...e}),g.jsx(jI,{...t})]})}const pd="OpenPond".split("");function B4({visibleLetterCount:e=pd.length}){const t=pd.slice(0,Math.max(0,Math.min(e,pd.length)));return g.jsxs("div",{className:"app-splash-lockup",children:[g.jsx("div",{className:"app-splash-mark",children:g.jsx("img",{alt:"OpenPond",className:"app-splash-logo",decoding:"async",src:Tg})}),g.jsx("span",{"aria-hidden":"true",className:`app-splash-wordmark${t.length>0?" is-visible":""}`,children:t.map((n,a)=>g.jsx("span",{className:"app-splash-letter",children:n},`${n}-${a}`))})]})}const hp=pd.length,F4=520,V4=240;function ey(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function K4({startup:e}){const[t,n]=h.useState(()=>ey()?hp:0);return h.useEffect(()=>{if(ey()){n(hp);return}const a=Array.from({length:hp},(s,r)=>window.setTimeout(()=>n(r+1),F4+V4*r));return()=>{a.forEach(s=>window.clearTimeout(s))}},[]),g.jsxs("main",{className:"app-splash","aria-busy":"true","aria-label":e.label,role:"status",children:[g.jsx(B4,{visibleLetterCount:t}),g.jsx("span",{className:"app-splash-status",children:e.label})]})}const jg=5e3;function si(e,t){if(e.length===0)return t;if(t.length===0)return e;const n=new Set,a=[];for(const s of[...e,...t])n.has(s.id)||(n.add(s.id),a.push(s));return a}function Ds(e,t,n=jg){return fd(si(e,t),n)}function fd(e,t=jg){return e.length<=t?e:e.slice(e.length-t)}function W4(e,t){if(t.length===0)return fd(e);if(e.length===0)return fd(t);const n=new Map;let a=0;for(const s of[...e,...t])n.has(s.id)||n.set(s.id,{event:s,index:a}),a+=1;return fd([...n.values()].sort((s,r)=>Z4(s,r)).map(({event:s})=>s))}function wf(e){let t=null;for(const n of e)typeof n.sequence=="number"&&(t=t===null?n.sequence:Math.max(t,n.sequence));return t}function G4(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function Z4(e,t){const n=e.event.sequence,a=t.event.sequence;if(typeof n=="number"&&typeof a=="number"){const i=n-a;if(i!==0)return i}const s=Date.parse(e.event.timestamp),r=Date.parse(t.event.timestamp);if(Number.isFinite(s)&&Number.isFinite(r)){const i=s-r;if(i!==0)return i}return e.index-t.index}function ty(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 J4(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function Q4(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 ny(e){return e==="codex"||e==="claude-code"}function Y4(e){return e==="openpond"}function MI(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=tj.safeParse(n.data);if(a.success)return a.data}return null}function OI(e){if(e.snapshot&&e.snapshot.provider===e.provider){const n=e.snapshot.usedTokens,a=e.snapshot.maxContextTokens,s=Math.min(100,Math.round(e.snapshot.percentFull)),r=`${s}% full`,i=`${ty(n)} / ${ty(a)} tokens used`,c=ny(e.provider)?`Context and compaction are managed by ${e.provider==="claude-code"?"Claude Code":"Codex app-server"}.`:Q4(e.preferences,s);return{usedTokens:n,maxTokens:a,percent:s,summary:r,tokensLabel:i,detail:c,tooltip:`Context window: ${r} ${i}. ${c}`,tone:J4(s)}}if(ny(e.provider)){const n=e.provider==="claude-code"?"Claude Code":"Codex app-server",a=`Context is managed by ${n}.`;return{usedTokens:0,maxTokens:null,percent:null,summary:"Managed externally",tokensLabel:n,detail:a,tooltip:`Context window: ${a}`,tone:"unknown"}}if(!Y4(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 Mg(e){let t=!1;const n=$I(e);for(let a=e.length-1;a>=0;a-=1){const s=e[a];if(X4(s)){t=!0;continue}const r=hi(s?.data);if(!(s?.name!=="diagnostic"||!r)){if(r.kind==="thread_goal_cleared")return null;if(r.kind==="thread_goal"){const i=Og(hi(r.goal),Qn(r.provider),n);if(i){const c=Dc(i);return t&&c.tone==="active"?null:c}}if(r.kind==="goal_context"){const i=DI(s.output??"",Qn(r.provider)??"codex",n);if(i){const c=Dc(i);return t&&c.tone==="active"?null:c}}}}return null}function Hd(e){const t=$I(e);for(let n=e.length-1;n>=0;n-=1){const a=e[n],s=hi(a?.data);if(!(a?.name!=="diagnostic"||!s)){if(s.kind==="thread_goal_cleared"&&s.synthetic!==!0)return null;if(s.kind==="thread_goal"){const r=Og(hi(s.goal),Qn(s.provider),t);if(!r)continue;const i=Dc(r);return i.tone==="active"?i:null}if(s.kind==="goal_context"){const r=DI(a.output??"",Qn(s.provider)??"codex",t);if(!r)continue;const i=Dc(r);return i.tone==="active"?i:null}}}return null}function gp(e){const t=hi(hi(e)?.codexGoalRuntime),n=Og(t,Qn(t?.provider)??"codex");if(!n)return null;const a=Dc(n);return a.tone==="active"?a:null}function X4(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function Dc(e){const t=LI(e.status),n=UI(e.timeUsedSeconds),a=`Goal ${n}`,s=e.tokensUsed===null?null:e.tokenBudget===null?`${vp(e.tokensUsed)} tokens`:`${vp(e.tokensUsed)} / ${vp(e.tokenBudget)} tokens`,r=s?`${e.statusLabel} · ${s}`:e.statusLabel;return{objective:e.objective,status:e.status,timeUsedSeconds:e.timeUsedSeconds,tokensUsed:e.tokensUsed,tokenBudget:e.tokenBudget,actionLabel:t.actionLabel,timeLabel:n,label:a,detail:r,tooltip:`Goal runtime: ${qI(e.timeUsedSeconds)}. ${r}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function eF(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=NI(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,s=UI(a);return{...e,timeUsedSeconds:a,timeLabel:s,label:`Goal ${s}`,tooltip:`Goal runtime: ${qI(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function Og(e,t=null,n=null){if(!e)return null;const a=Qn(e.objective)??"Active goal",s=Qn(e.status)??"active";if((If(t)??If(Qn(e.provider)))!=="codex")return null;const i=n??Qn(e.updatedAt)??Qn(e.updated_at)??null,c=Oo(e.timeUsedSeconds)??Oo(e.time_used_seconds)??0,l=Qn(e.activeSinceAt)??Qn(e.active_since_at),u=LI(s).tone==="active"?NI(l??Qn(e.createdAt)??Qn(e.created_at),i):0,p=l?c+u:Math.max(c,u),f=Oo(e.tokensUsed)??Oo(e.tokens_used),S=Oo(e.tokenBudget)??Oo(e.token_budget);return{objective:a,status:s,statusLabel:HI(s),timeUsedSeconds:Math.max(0,Math.floor(p)),tokensUsed:f===null?null:Math.max(0,Math.floor(f)),tokenBudget:S===null?null:Math.max(0,Math.floor(S)),observedAt:i}}function $I(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t]?.timestamp;if(n&&Number.isFinite(Date.parse(n)))return n}return null}function NI(e,t){if(!e||!t)return 0;const n=Date.parse(e),a=Date.parse(t);return!Number.isFinite(n)||!Number.isFinite(a)||a<=n?0:Math.floor((a-n)/1e3)}function DI(e,t=null,n=null){if(!e.trim()||If(t)!=="codex")return null;const a=zI(e,"Status")??"active",s=Yi(e,"Tokens used"),r=Yi(e,"Token budget"),i=Yi(e,"Time used seconds")??Yi(e,"Time spent pursuing goal")??Yi(e,"Elapsed seconds")??0;return{objective:ay(e,"objective")??ay(e,"untrusted_objective")??"Active goal",status:a,statusLabel:HI(a),timeUsedSeconds:Math.max(0,Math.floor(i)),tokensUsed:s,tokenBudget:r,observedAt:n}}function LI(e){switch(tF(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 tF(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function zI(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^\\s*-?\\s*${n}:\\s*(.+?)\\s*$`,"im").exec(e)?.[1]?.trim()||null}function Yi(e,t){const n=zI(e,t);if(!n)return null;const a=n.replace(/,/g,""),s=/-?\d+(?:\.\d+)?/.exec(a);if(!s)return null;const r=Number(s[0]);return Number.isFinite(r)?r:null}function ay(e,t){return new RegExp(`<${t}>\\s*([\\s\\S]*?)\\s*<\\/${t}>`,"i").exec(e)?.[1]?.trim()||null}function HI(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function UI(e){if(e<60)return`${e}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const n=Math.floor(t/60),a=t%60;return a>0?`${n}h ${a}m`:`${n}h`}function qI(e){if(e<60)return`${e} ${e===1?"second":"seconds"}`;const t=Math.floor(e/60);if(t<60)return`${t} ${t===1?"minute":"minutes"}`;const n=Math.floor(t/60),a=t%60;return a===0?`${n} ${n===1?"hour":"hours"}`:`${n}h ${a}m`}function vp(e){if(e<1e3)return String(e);if(e>=1e6){const n=e/1e6;return n<10?`${sy(n,2)}M`:n<100?`${sy(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 sy(e,t){return e.toFixed(t).replace(/\.?0+$/,"")}function hi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Qn(e){return typeof e=="string"&&e.trim()?e.trim():null}function If(e){return e?.trim().toLowerCase()||null}function Oo(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const nF=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),aF=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function _f(e){const t=BI(e);return t?iF(t):null}function BI(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=oF(mF(n.data));if(a)return a}return null}function sF(e){if(e.events)return BI(e.events);const t=e.messages??[];for(let n=t.length-1;n>=0;n-=1){const a=t[n]?.createImproveRun??null;if(a)return a}return null}function rF(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 oF(e){const t=qc.safeParse(e?.createImproveRun);return t.success?t.data:null}function iF(e){const t=cF(e);if(!t)return null;const n=lF(e.createdAt,e.updatedAt),a=e.blockedReason??dF(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:uF(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function cF(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return nF.has(t)?{tone:"active",actionLabel:`${n} running`}:aF.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 lF(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 dF(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function uF(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 mF(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function FI(e,t){if(!t)return null;const n=new Map,a=[];for(const T of e){if(!T.name.startsWith("subagent."))continue;const y=hF(T);y&&a.push(y);const I=fF(T);I?.parentSessionId===t&&n.set(I.id,I)}if(n.size===0)return null;const s=[...n.values()].sort((T,y)=>No(y).localeCompare(No(T))),r=s.filter(T=>T.status==="queued"||T.status==="running"),i=s.filter(T=>T.status==="completed"),c=s.filter(T=>T.status==="failed"),l=s.filter(T=>T.status==="cancelled"),u=s.filter(T=>T.status==="needs_resume"),p=[...i,...c,...l].sort((T,y)=>No(y).localeCompare(No(T))),f=s.reduce((T,y)=>{const I=gi(y.metadata?.usage);return T.totalTokens+=Vl(I?.totalTokens),T.promptTokens+=Vl(I?.promptTokens),T.completionTokens+=Vl(I?.completionTokens),T.requestCount+=Vl(I?.requestCount),T},{totalTokens:0,promptTokens:0,completionTokens:0,requestCount:0}),S=s.flatMap(T=>VI([...T.report?.blockers??[],T.error,T.progress.currentBlocker]).map(y=>({runId:T.id,roleId:T.roleId,status:T.status,message:y}))),b=s.flatMap(T=>KI([...T.report?.artifacts??[],T.report?.patchRef,T.report?.diffRef,...T.progress.patchRefs]).map(y=>({...y,runId:T.id,roleId:T.roleId}))),w=p.map(T=>pF(T,a)),C=s[0]??null,P=C?{runId:C.id,roleId:C.roleId,status:C.status,message:C.progress.latestMeaningfulActivity||C.report?.summary||C.objective,updatedAt:No(C)}:null,_=r.length>0?`${r.length} ${r.length===1?"child":"children"} running`:`${p.length} ${p.length===1?"child":"children"} finished`,M=[r.length?`${r.length} active`:null,i.length?`${i.length} completed`:null,c.length?`${c.length} failed`:null,l.length?`${l.length} cancelled`:null,u.length?`${u.length} paused`:null].filter(Boolean).join(" · "),E=P?`${bF(P.roleId)}: ${P.message}`:"";return{sessionId:t,runs:s,activeRuns:r,completedRuns:i,failedRuns:c,cancelledRuns:l,needsResumeRuns:u,terminalRuns:p,latestRun:C,latestMeaningfulUpdate:P,activeCount:r.length,completedCount:i.length,failedCount:c.length,cancelledCount:l.length,needsResumeCount:u.length,terminalCount:p.length,usage:f,blockers:S,evidenceRefs:b,finalResults:w,testsRunCount:s.reduce((T,y)=>T+y.progress.validationAttempts.length,0),label:_,tooltip:[M,E].filter(Boolean).join(". ")}}function pF(e,t){return{runId:e.id,roleId:e.roleId,status:e.status,objective:e.objective,summary:e.report?.summary||e.error||"Child conversation finished.",findings:e.report?.findings??[],changedFiles:e.progress.changedFiles,refs:KI([...e.report?.artifacts??[],e.report?.patchRef,e.report?.diffRef]),testsRun:e.report?.testsRun??[],validationAttempts:e.progress.validationAttempts.map(n=>n.command),blockers:VI([...e.report?.blockers??[],e.error]),confidence:e.report?.confidence??null,importantMessages:t.filter(n=>n.fromRunId===e.id).map(n=>({id:n.id,runId:e.id,fromRunId:n.fromRunId,kind:n.kind,body:n.body,createdAt:n.createdAt})),workspaceRetention:gF(e),updatedAt:No(e)}}function fF(e){const t=gi(e.data),n=[t?.run,gi(t?.message)?.run];for(const a of n){const s=wS.safeParse(a);if(s.success)return s.data}return null}function hF(e){const t=PE.safeParse(gi(e.data)?.message);return t.success?t.data:null}function gF(e){const t=gi(gi(e.metadata?.workspaceHandoff)?.workspaceRetention);return t?.status!=="retained"?null:{status:"retained",reason:Fl(t.reason),retainedAt:Fl(t.retainedAt),expiresAt:Fl(t.expiresAt),retentionDays:vF(t.retentionDays),trigger:Fl(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function No(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function VI(e){return[...new Set(e.map(t=>t?.trim()).filter(t=>!!t))]}function KI(e){const t=new Map;for(const n of e)n&&t.set(`${n.kind}:${n.id}`,n);return[...t.values()]}function gi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Fl(e){return typeof e=="string"&&e.trim()?e.trim():null}function Vl(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function vF(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function bF(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const Cf=[];function Rf(e,t){return WI(e,t,null)}function WI(e,t,n){const a=n&&wF(n.events,e)?SF(n.indexes,n.events.length,e):yF(e),s=kF(t);return{...a,...s}}function yF(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 xF(t)}function SF(e,t,n){const a=new Map(e.eventsBySessionId),s=new Map(e.latestContextUsageBySessionId),r=new Map(e.latestGoalRuntimeBySessionId),i=new Map(e.latestSubagentRuntimeBySessionId),c=new Set(e.activeGoalSessionIds),l=new Set(e.activeSubagentSessionIds),u=new Set;for(let p=t;p<n.length;p+=1){const f=n[p];if(!f.sessionId)continue;if(u.has(f.sessionId)){a.get(f.sessionId).push(f);continue}const S=a.get(f.sessionId);a.set(f.sessionId,S?[...S,f]:[f]),u.add(f.sessionId)}for(const p of u){const f=a.get(p)??Cf,S=MI(f);S?s.set(p,S):s.delete(p);const b=ZI(f);b?(r.set(p,b),b.tone==="active"?c.add(p):c.delete(p)):(r.delete(p),c.delete(p));const w=FI(f,p);w?(i.set(p,w),GI({sessionEvents:f,sessionId:p,latestGoalRuntimeBySessionId:r,activeGoalSessionIds:c}),w.activeCount>0?l.add(p):l.delete(p)):(i.delete(p),l.delete(p))}return{eventsBySessionId:a,latestContextUsageBySessionId:s,latestGoalRuntimeBySessionId:r,latestSubagentRuntimeBySessionId:i,activeGoalSessionIds:c,activeSubagentSessionIds:l}}function xF(e){const t=new Map,n=new Map,a=new Map,s=new Set,r=new Set;for(const[i,c]of e){const l=MI(c);l&&t.set(i,l);const u=ZI(c);u&&(n.set(i,u),u.tone==="active"&&s.add(i))}for(const[i,c]of e){const l=FI(c,i);l&&(a.set(i,l),GI({sessionEvents:c,sessionId:i,latestGoalRuntimeBySessionId:n,activeGoalSessionIds:s}),l.activeCount>0&&r.add(i))}return{eventsBySessionId:e,latestContextUsageBySessionId:t,latestGoalRuntimeBySessionId:n,latestSubagentRuntimeBySessionId:a,activeGoalSessionIds:s,activeSubagentSessionIds:r}}function GI(e){if(e.latestGoalRuntimeBySessionId.has(e.sessionId))return;const t=Hd(e.sessionEvents);t&&(e.latestGoalRuntimeBySessionId.set(e.sessionId,t),t.tone==="active"&&e.activeGoalSessionIds.add(e.sessionId))}function ZI(e){return _f(e)??Mg(e)??Hd(e)}function kF(e){const t=new Map,n=new Map,a=new Map,s=new Map;for(const r of e){t.set(r.id,r);const i=n.get(r.status);if(i?i.push(r):n.set(r.status,[r]),r.status!=="pending")continue;const c=a.get(r.sessionId);c?c.push(r):a.set(r.sessionId,[r]);const l=s.get(r.sessionId);(!l||ry(r.createdAt)>ry(l.createdAt))&&s.set(r.sessionId,r)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:s}}function wF(e,t){return e===t?!0:e.length>t.length||e.length===t.length?!1:e.length===0?!0:e[0]===t[0]&&e[e.length-1]===t[e.length-1]}function al(e,t){return t?e.eventsBySessionId.get(t)??Cf:Cf}function JI(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function QI(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function IF(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function _F(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function ry(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function CF(e,t){return e?.conversationId===t}function RF(e,t){return e?.id===t?null:e}function PF(e){const t=new Set;if(e.readmePath){const n=e.readmePath.replaceAll("\\","/").split("/").at(-1);n&&t.add(n)}for(const n of e.skills){t.add(n.relativePath);const a=n.relativePath.lastIndexOf("/"),s=a>=0?n.relativePath.slice(0,a):"";for(const r of n.resourceFiles)t.add(s?`${s}/${r}`:r)}return{name:`${e.owner}/${e.repo}`,description:`${e.skills.length} installed skill${e.skills.length===1?"":"s"} from GitHub.`,scope:"extension",packagePath:e.sourcePath,files:[...t]}}function TF(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function AG(e,t){return e.profiles.find(n=>TF(n.ref)===t)?.ref??null}function AF(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function EG(e,t){return e.profiles.find(n=>AF(n.ref,t))?.state??null}function EF(e,t){const n=new Map(Kj.map(a=>[a.name,{...a,validationMessages:[...a.validationMessages],resourceFiles:[...a.resourceFiles]}]));for(const a of e?.skills??[])n.has(a.name)||n.set(a.name,a);for(const a of t?.extensions??[])if(a.validationStatus==="valid")for(const s of a.skills)s.validationStatus!=="valid"||n.has(s.name)||n.set(s.name,{name:s.name,description:s.description,path:s.relativePath,scope:"profile",enabled:!0,sourcePath:a.sourcePath,charCount:s.charCount,sourceHash:s.sourceHash,validationStatus:"valid",validationMessages:[],resourceFiles:s.resourceFiles});return[...n.values()].sort((a,s)=>a.name.localeCompare(s.name))}function jF(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 jG(e,t){const n=`Continue from the attached Work output "${e.title}" (revision ${e.revision}).`;return t==="work"?`${n} Choose a Project or repository before making source changes; do not mutate a checkout until I choose it.`:n}const YI="openpond:last-chat-task-mode";function MF(e,t){return e==="labs"?"models":"chat"}function OF(e){try{return e.getItem(YI)==="work"?"work":"chat"}catch{return"chat"}}function $g(){if(typeof window>"u")return"chat";try{return OF(no)}catch{return"chat"}}function $F(e,t){try{e.setItem(YI,t==="chat"?"chat":"work")}catch{}}function NF(e){if(!(typeof window>"u"))try{$F(no,e)}catch{}}const DF="uploaded to a different account";function XI(e,t){const n=e?.linkedSandboxProject??null;if(!n?.projectId||!n.teamId)return{state:"none",linked:null,cloudProject:null};const a=t?.find(s=>s.id===n.projectId&&s.teamId===n.teamId)??null;return a?{state:"confirmed",linked:n,cloudProject:a}:{state:"different_account",linked:n,cloudProject:null}}function Ra(e,t){const n=XI(e,t);return n.state==="confirmed"?n.cloudProject:null}function LF(e,t){return XI(e,t).state==="different_account"?DF:null}function Ss(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function e1(e={}){return{...e,workspaceTarget:"hybrid"}}function zF(e={}){return{...e,workspaceTarget:"local"}}function xs(e){return e?.metadata?.workspaceTarget==="hybrid"}function HF(e){return!!(e&&e.provider==="openpond"&&e.workspaceKind==="local_project"&&e.cloudProjectId&&e.title.trim().endsWith(" Cloud"))}function t1({cloudProjects:e,selectedCloudProject:t,selectedProject:n}){const a=n?.linkedSandboxProject??null,s=e?Ra(n,e):null,r=t?.id??s?.id??(e?null:a?.projectId??null),i=t?.teamId??s?.teamId??(e?null:a?.teamId??null);return!r||!i?{kind:"missing_cloud_project",message:"Upload/sync this Project to Cloud before using Hybrid."}:{kind:"ready",cloudProjectId:r,cloudTeamId:i,cwd:n?.workspacePath??null,localProjectId:n?.id??null,workspaceName:t?.name??s?.name??a?.projectName??n?.name??"Hybrid workspace"}}function n1({modelRef:e,provider:t,target:n,title:a}){return{provider:t,...e?{modelRef:e}:{},appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:n.workspaceName,localProjectId:n.localProjectId,cloudProjectId:n.cloudProjectId,cloudTeamId:n.cloudTeamId,metadata:e1(),cwd:n.cwd,title:a}}function UF(e){return h.useEffect(()=>{const t=uI(e.selectedSession);!t||e.composerDraftStore.getSnapshot()||e.composerDraftStore.set(t)},[e.composerDraftStore,e.selectedSession?.id]),h.useCallback(async t=>{const n=t.trim();if(!e.connection||!n||e.activeExperience==="chat")return!1;const a=Cq(n);try{let s;const r=e.selectedSession;if(r&&$c(r))s=await Z.patchSession(e.connection,r.id,{title:a,metadata:lp(r.metadata,n)}),e.setSessions(i=>i.map(c=>c.id===s.id?s:c));else{const i=r?.metadata?.workspaceTarget==="hybrid"?"hybrid":r?.metadata?.workspaceTarget==="local"?"local":null,c=r?.provider??(e.selectedCloudProject?"openpond":e.activeProvider),l=r?.modelRef??(c==="openpond"?{providerId:"openpond",modelId:ii}:{providerId:c,modelId:e.activeModel}),u=i?{workspaceTarget:i}:!r&&e.workspaceTarget==="local"?{workspaceTarget:"local"}:{};let p;if(!r&&e.workspaceTarget==="hybrid"){const f=t1({cloudProjects:e.cloudProjects,selectedCloudProject:e.selectedCloudProject,selectedProject:e.selectedProject});if(f.kind!=="ready")throw new Error(f.message);const S=n1({modelRef:l,provider:c,target:f,title:a});p={...S,experience:"work",metadata:lp(S.metadata,n)}}else p={experience:"work",provider:c,modelRef:l,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:lp(u,n),title:a};s=await Z.createSession(e.connection,p),e.setSessions(f=>[s,...f])}return e.composerDraftStore.set(""),e.setMentionedAppId(null),e.setSelectedSessionId(null),e.setView("chat"),e.requestComposerFocus(),e.showToast("Task draft saved.","success"),!0}catch(s){return e.showToast(s instanceof Error?s.message:"Could not save task draft.","error"),!1}},[e.activeExperience,e.activeModel,e.activeOpenPondCommandAccessMode,e.activeProvider,e.cloudProjects,e.composerDraftStore,e.connection,e.requestComposerFocus,e.selectedCloudProject,e.selectedProject,e.selectedSession,e.setMentionedAppId,e.setSelectedSessionId,e.setSessions,e.setView,e.showToast,e.workspaceTarget])}const qF=[];function BF({primary:e,secondary:t}){const[n,a]=h.useState(null),s=h.useRef(new Set),[r,i]=h.useState(!1),[c,l]=h.useState(null),u=sq(),p=u?.kind==="models"&&["home","inbox","datasets","graders","experiments"].includes(u.route.page),{composerDraftStore:f,appDispatch:S,pendingTerminalCommand:b,setPendingTerminalCommand:w,terminalTabs:C,setTerminalTabs:P,trainingDetailTasksetId:_,setTrainingDetailTasksetId:M,mentionedAppId:E,setMentionedAppId:T,cloudSetupDialog:y,setCloudSetupDialog:I,rightPanelTabRequest:R,workspaceDiffPanelViewState:O,mainComposerFocusRequestId:z,requestMainComposerFocus:$,projectConfirmDialog:V,resolveProjectConfirmDialog:Y,query:se,searchOpen:ee,archivedChatsOpen:H,sectionMenuOpen:F,cloudProjectsExpanded:J,sidebarOpen:K,view:B,selectedAppId:ne,selectedProjectId:G,selectedSessionId:te,codexPermissionMode:oe,codexReasoningEffort:be,busy:me,diffPanelOpen:Re,diffPanelExpanded:Q,rightPanelMode:xe,activeExperience:je,changeNewExperience:De,terminalOpen:He,settingsSection:Ie,newProjectDialogOpen:Me,newProjectMode:Te,newProjectName:N,newProjectPath:q,newProjectBusy:X,commitDialogOpen:U,commitMessage:ae,commitIncludeUnstaged:de,commitNextStep:ye,commitDraft:Oe,branchDialogOpen:$e,branchDialogName:Ge,toast:yt,labDetailNavigation:Se,setQuery:Le,setSearchOpen:Ae,setArchivedChatsOpen:qe,setSectionMenuOpen:Ue,setCloudProjectsExpanded:bn,setChatRowsVisibleCount:Mt,setSidebarOpen:pe,setView:fe,setSelectedAppId:Fe,setSelectedProjectId:Pe,setSelectedSessionId:Ne,setPrompt:ot,setDraftProvider:ut,setDraftModel:At,setDraftExperience:mt,setDiffPanelOpen:at,setDiffPanelExpanded:Ct,setRightPanelMode:Be,setTerminalOpen:Et,setSettingsSection:dn,setNewProjectDialogOpen:jn,setNewProjectName:kt,setNewProjectPath:ks,setCommitDialogOpen:un,setCommitMessage:yn,setCommitIncludeUnstaged:Ut,setCommitNextStep:Rn,setCommitDraft:Sn,setBranchDialogOpen:Pn,setBranchDialogName:Mn,setError:qt,showToast:gt,applyBootstrapPayload:qn,applyPreferencesPayload:mn,bootstrap:pt,connection:_t,startup:Ot,training:pn,pinnedCollapsed:oa,cloudProjectsCollapsed:Ze,chatsCollapsed:Tn,savedForLaterCollapsed:Ja,sidebarWidth:Ea,sidebarResizing:Ln,diffPanelWidth:An,diffPanelResizing:Qa,togglePinnedCollapsed:ws,toggleCloudProjectsCollapsed:ja,toggleChatsCollapsed:lt,toggleSavedForLaterCollapsed:sn,startSidebarResize:Ke,startDiffPanelResize:St,selectedApp:en,selectedCloudProject:zn,selectedProject:xn,selectedProjectLinkedApp:D,selectedSession:we,sidebarSessions:le,runtimeIndexes:Je,runtimeEventStore:ga,chatMentionApps:Bn,connectedAppMentions:Ma,pendingApproval:kn,pendingChatUserMessages:ao,account:Is,activeModel:On,activeProvider:ia,appDefaults:ca,startMessage:_s,organizations:kr,teamChatOrganization:wr,teamChatTeamId:Ir,teamChat:ft,publishTeamProfileAgent:_i,communitySidebar:_r,communityView:Ci,teamAiThreadId:so,toggleTeamAiSidebar:Ri,activeOpenPondCommandAccessMode:Cs,viewWorkspaceAppId:Pi,viewWorkspaceId:ro,viewWorkspaceKind:oo,viewWorkspaceName:io,selectedActionCatalog:Ti,expandedProjectIds:Ai,expandProject:Ya,toggleProjectExpanded:Ei,changeCodexPermissionMode:co,changeCodexReasoningEffort:Cr,changeOpenPondCommandAccessMode:Rr,resolveApproval:lo,beginNewChat:la,beginNewChatWithTrainingModel:ji,dismissTrainingChatHandoff:Pr,trainingChatHandoff:Rs,selectTrainingChatTaskForComposer:Gn,chatHistoryLoadStates:Mi,loadMoreSelectedChatHistory:Oi,selectedPagedSessionEvents:wn,activeSessions:Ks,archivedSessions:Zn,pinnedSessions:Ps,savedForLaterSessions:Tr,savedForLaterFiles:Ws,sidebarFileBookmarks:$i,setSidebarFileStatus:uo,setSessions:Ar,projectRows:Ts,localProjectRows:As,cloudProjectRows:Er,projectSessionRowsByProjectId:mo,childSessionRowsByParentId:Gs,sidebarProjectIdBySessionId:Xa,chatRows:va,visibleChatRows:po,chatRowsVisibleCount:Zs,sessionEvents:es,goalRuntime:fo,subagentRuntime:Oa,visibleChatMessages:ho,activeTerminalScope:Ni,terminalSummaries:go,runningSessionIds:Di,selectedSessionRunning:vo,sidebarGoalRuntimeBySessionId:bo,sidebarSubagentRuntimeBySessionId:yo,taskDragSessionId:jr,taskPreviewSessionIds:So,startTaskDrag:Mr,clearTaskDrag:ts,previewTaskDrop:Li,commitTaskDrop:zi,commitTaskPreviewDrop:Hi,dragItem:Ui,startPinnedDrag:ns,clearSidebarDrag:xo,previewPinnedDrop:qi,commitPinnedDrop:Bi,commitPinnedPreviewDrop:Fi,commandProjectRows:da,contextWindowStatus:ko,pinnedRows:et,workspaceBusy:Ft,diffBusy:as,visibleWorkspaceState:rn,visibleWorkspaceDiff:Hn,refreshVisibleWorkspaceDiff:$n,managedWorkspace:ju,canSyncActiveWorkspace:Mu,canPublishOpenPondProject:Ou,projectTarget:$u,workspaceTarget:rl}=e,{title:Nu,browserConversationId:Or,handleWorkspaceDiffPanelViewStateChange:ol,openSessionInChat:wo,changeProjectTarget:Du,submitNewProjectDialog:Lu,changeWorkspaceBranch:zu,openCommitDialog:Hu,openCreateWorkspaceBranchDialog:Uu,openDefaultsSettingsFromBranchDialog:qu,runWorkspaceTool:Bu,submitCommitDialog:Fu,submitCreateWorkspaceBranch:Vu,syncWorkspaceLocally:Ku,answerCreateImproveQuestion:il,applyCreateImproveCandidate:Wu,approveCreateImproveRun:Gu,cancelCreateImproveRun:Zu,changeDraftProvider:Vi,openCreateImprovePullRequest:cl,reconcileCreateImprovePullRequest:Ju,rejectCreateImproveCandidate:Qu,pauseCreateImproveRun:ll,resumeCreateImproveRun:dl,reviseCreateImproveRun:Yu,stopTurn:Io,archiveSession:Xu,restoreSession:ul,renameSession:em,toggleSessionPinned:Ki,toggleProjectPinned:ml,toggleSessionSavedForLater:pl,moveProjectToCloud:tm,startCloudSetupUpload:fl,changeWorkspaceTarget:nm,sendPromptFromMainComposer:am,openSandboxWorkspace:hl,openCloudProjectDialog:sm,openExistingProjectPathDialog:gl,openUrlInBrowserPanel:rm,showBrowserPanel:om,showChangesPanel:im,showGoalSidebarTab:Js,rightChatTrainingLaunchRequest:vl,setRightChatTrainingLaunchRequest:cm,closeRightChatPanel:lm,openRightChatPanel:Wi,rightChatPanelViews:dm,showRightChatPanel:um,showRightPanelDiffTab:mm,submitRightChatPrompt:pm,activateRightChatPanel:fm,updateRightChatModel:hm,updateRightChatPrompt:gm,updateRightChatProvider:vm,updateRightChatScrollState:bm,openProfileSettings:ym,diagnosticEvents:Sm,toggleRightSidebar:bl,removeProject:xm}=t;hC(_t,pt?.account.activeProfile&&pt.preferences.defaultTeamId?JSON.stringify([pt.account.baseUrl,pt.account.activeProfile,pt.account.profile?.id,pt.account.state,pt.preferences.defaultTeamId]):null,()=>{Lt({kind:"chat",sessionId:null}).then(he=>{he&&(Ne(null),fe("chat"),a("activity"))})});const $a=pt?.account.activeProfile&&pt?.preferences.defaultTeamId?`${pt.account.activeProfile.handle}:${pt.preferences.defaultTeamId}`:null;h.useEffect(()=>{if(!(!$a||B!=="chat"||u?.kind!=="chat"||u.sessionId||te||s.current.has($a))){s.current.add($a);try{const he=localStorage.getItem(`openpond:ponder-mode:v1:${$a}`);(he==="clean"||he==="activity")&&a(he)}catch{}}},[$a,u,B,te]),h.useEffect(()=>{if(!(!$a||!s.current.has($a)))try{localStorage.setItem(`openpond:ponder-mode:v1:${$a}`,n??"off")}catch{}},[$a,n]);const _o=h.useCallback(he=>{Fe(null),Pe(he),Ne(null),fe("chat"),Ya(he),$()},[Ya,$,Fe,Pe,Ne,fe]),km=h.useCallback((he=null)=>{a(null);const Xe=te?Xa[te]??null:null;if(!he&&Xe){_o(Xe);return}la(he)},[la,_o,te,Xa]),wm=h.useCallback(async he=>{if(!(!_t||!pt))try{const Xe=await Z.savePreferences(_t,{defaultTeamId:he});mn(Xe)}catch(Xe){const $t=Xe instanceof Error?Xe.message:String(Xe);throw qt($t),gt("Could not switch teams","error"),Xe}},[mn,pt,_t,qt,gt]),Im=h.useCallback(async()=>{if(_t)try{const he=await Z.signOutOpenPondAccount(_t);qn(he),gt("Logged out","success")}catch(he){const Xe=he instanceof Error?he.message:String(he);throw qt(Xe),gt("Could not log out","error"),he}},[qn,_t,qt,gt]),Gi=ca.defaultTeamId??null,_m=h.useMemo(()=>Ts.filter(he=>he.kind==="local"||Gi!==null&&he.project.teamId===Gi),[Ts,Gi]),Cm=h.useMemo(()=>{const he={};for(const Xe of Ks){const $t=Xa[Xe.id];$t&&(he[$t]=(he[$t]??0)+1)}for(const Xe of As){if(Xe.kind!=="local")continue;const $t=Xe.project.linkedSandboxProject?.projectId;if(!$t||!Xe.cloudLinkTrusted)continue;const ba=ct("cloud",$t);he[Xe.id]=(he[Xe.id]??0)+(he[ba]??0)}return he},[Ks,As,Xa]),[yl,Es]=h.useState(null),[Co,Ro]=h.useState(null),Rm=EF(pt?.profile,pt?.extensionCatalog),[$r,Zi]=h.useState(null),[Po,Ji]=h.useState(null),[ss,Sl]=h.useState(null),Pm=h.useCallback(async()=>{await Lt({kind:"view",view:"team"})&&(Fe(null),Pe(null),Ne(null),Ue(null),fe("team"))},[Ue,Fe,Pe,Ne,fe]),Tm=h.useCallback(async()=>{await Lt({kind:"view",view:"community"})&&(Fe(null),Pe(null),Ne(null),Ue(null),_r.discoverCommunities())},[_r.discoverCommunities,Ue,Fe,Pe,Ne]),Am=UF({activeExperience:je,activeModel:On,activeOpenPondCommandAccessMode:Cs,activeProvider:ia,cloudProjects:pt?.cloudProjects??qF,composerDraftStore:f,connection:_t,requestComposerFocus:$,selectedCloudProject:zn,selectedProject:xn,selectedSession:we,setMentionedAppId:T,setSelectedSessionId:Ne,setSessions:Ar,setView:fe,showToast:gt,workspaceTarget:rl.value}),Em=h.useCallback(async he=>{if(!_t)throw new Error("OpenPond is not connected.");let Xe=ia,$t=On;Xe==="codex"&&(Xe=Sf(pt?.providers,{enabledOnly:!0}).find(In=>In.value!=="codex")?.value??Kr,$t=Nd(Xe,pt?.providers)??wc);const ba=le.find(In=>In.id===he.sourceSessionId),js=await Z.createSession(_t,{experience:he.target,provider:Xe,modelRef:{providerId:Xe,modelId:$t},openPondCommandAccessMode:Cs,appId:null,appName:null,workspaceId:null,workspaceName:null,localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,title:`Continue ${ba?.title??"task"}`.slice(0,120),metadata:{experienceHandoff:jF({sourceTaskId:he.sourceSessionId,sourceExperience:ba?.experience??null,targetExperience:he.target,sourceMessageIds:he.sourceMessageIds??[],sourceContext:he.sourceContext,output:he.output})}});return Ar(In=>[js,...In]),mt(he.target),ut(Xe),At($t),f.set(he.prompt),Lt({kind:"chat",sessionId:js.id}),S({type:"selectSession",sessionId:js.id,appId:null,projectId:null}),Fe(null),Pe(null),Et(!1),fe("chat"),Be("home"),at(he.target==="work"),Ct(!1),js},[On,Cs,ia,S,pt?.providers,f,_t,Ct,at,mt,At,ut,Be,Fe,Pe,Ar,Et,fe,le]),jm=h.useCallback(he=>{Zi(he),Ji(null),la(null),pe(!0)},[la,pe]),Mm=h.useCallback(he=>{la(null),mt("work"),f.set(`$openpond-refiner-authoring ${he}`),fe("chat"),pe(!0)},[la,f,mt,pe,fe]),xl=h.useCallback(he=>{Ji(PF(he)),Zi(null),la(null),pe(!0)},[la,pe]);h.useEffect(()=>{!$r&&!Po||B!=="chat"||te||G||ne||(Es($r),Ro(Po),Zi(null),Ji(null),Be("home"),Ct(!1),at(!0))},[$r,Po,ne,G,te,Ct,at,Be,B]),h.useEffect(()=>{!yl&&!Co||B==="chat"&&Re&&xe==="home"||(Es(null),Ro(null))},[Re,Co,yl,xe,B]);const kl=h.useCallback(()=>{Es(null),Ro(null),Ct(!1),at(!1)},[Ct,at]),Om=h.useCallback(he=>{let Xe;if(he.workspaceKind==="local"){const $t=ct("local",he.workspaceId);Xe=`draft:${$t}`,Fe(null),Pe($t),Ne(null),Ya($t),fe("chat")}else{const $t=le.find(ba=>ba.id===he.sourceSessionId||ba.workspaceId===he.workspaceId);if(!$t){gt("This saved file's cloud chat is no longer available.","error");return}Xe=$t.id,wo($t.id)}Be("changes"),at(!0),Sl({id:Date.now(),conversationId:Xe,file:he}),he.available||gt(`File unavailable: ${he.path}`,"error")},[Ya,wo,at,Be,Fe,Pe,Ne,fe,gt,le]);h.useEffect(()=>{if(!CF(ss,Or))return;const he=window.setTimeout(()=>{Be("changes"),at(!0),Sl(Xe=>RF(Xe,ss.id))},0);return()=>window.clearTimeout(he)},[Or,at,Be,ss]);const wl=u?.kind==="models"&&u.route.area==="console"?"console":MF(B);h.useEffect(()=>{if(u){if(u.kind==="models"||u.kind==="models_unavailable"){B!=="labs"&&fe("labs");return}if(u.kind==="settings"){Fe(null),Pe(null),Ne(null),dn(u.section),B!=="settings"&&fe("settings");return}if(u.kind==="view"){Fe(null),Pe(null),Ne(null),B!==u.view&&fe(u.view);return}u.sessionId!==null&&(a(null),Fe(null),Pe(null)),Ne(u.sessionId),B!=="chat"&&fe("chat")}},[u,Fe,Pe,Ne,dn,fe,B]);const $m=h.useCallback(he=>{if(Ue(null),Fe(null),Pe(null),Ne(null),he==="models"||he==="console"){Fr(he==="console"?wa("datasets",null,{area:"console"}):wa()),fe("labs");return}he==="chat"&&Lt({kind:"chat",sessionId:null}),De($g())},[De,Lt,Ue,Fe,Pe,Ne,fe]),Nm=h.useCallback(async(he,Xe)=>{const $t=await pn.actions.acceptHarnessReview(he,Xe,{providerId:ia,modelId:On},be);return $t?(M($t.materializedTasksetId??null),Fr(wa()),fe("labs"),!0):(gt("Taskset review could not be opened.","error"),!1)},[On,ia,be,Fr,wa,M,fe,gt,pn.actions]),Ve=h.useMemo(()=>nC([...Je.eventsBySessionId.values()].flat()),[Je.eventsBySessionId]);if(!Ot.ready)return g.jsx(K4,{startup:Ot});if(B==="settings")return g.jsx(Jb,{showToast:gt,children:g.jsx(q4,{settings:{payload:pt,connection:_t,diagnostics:Sm,initialSection:Ie,onPayload:qn,onError:qt,onToast:gt,onOpenSourceSession:wo,onStartRefinerAuthoring:Mm,onAcceptEvaluationReview:Nm,onOpenSkill:jm,onOpenExtension:xl,teamChatCurrentUserId:ft.currentUserId,teamChatEnabled:Ir!==null,teamChatNotificationMode:ft.notificationMode,teamChatThreads:ft.threads,onTeamChatNotificationModeChange:ft.setNotificationMode,onTeamChatThreadMuteChange:ft.setThreadMuted,diffPanelWidth:An,diffPanelResizing:Qa,diffPanelExpanded:Q,onDiffPanelResizeStart:St,onDiffPanelExpandedChange:Ct,onBack:()=>{const he=tq(u);Lt(he),fe(he.kind==="models"?"labs":"chat"),pe(!0)}},toast:{toast:yt,onDismiss:()=>S({type:"field",key:"toast",value:null})}})});const tn=Eg(),Bt=wl==="console"||B==="chat",Vt=Bt&&K,ua=_t?.platform??navigator.platform,Dm=tn&&_I(ua),Zg=Ni,i_=rn?.initialized?rn.repoPath:we?.cwd??null,c_={"--sidebar-width":`${Ea}px`,"--diff-panel-width":`${An}px`},l_=B==="chat"&&je!=="chat"||B==="labs"||B==="scheduled"&&r||B==="team"&&!!so,d_=["app-shell",Dm?"platform-macos":"",Vt?"sidebar-open":"sidebar-closed",Ln?"sidebar-resizing":"",Qa?"diff-panel-resizing":""].filter(Boolean).join(" "),Lm=te?Mi[te]:null,u_=te?Lm?.cursorSequence??G4(Ds(wn,al(Je,te))):null,m_=!!te&&!!_t&&(Gt(te)?!0:!!pt?.eventWindow?.hasMoreBefore&&!!u_)&&(Lm?.hasMore??!0),p_=!!Lm?.loading,f_=(()=>{const he=pn.payload;if(!he)return{};const Xe=new Map(he.plans.map(In=>[In.id,In])),$t=new Set(["queued","starting","running","cancelling","reconciling"]),ba={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},js={};for(const In of[...he.modelRuns].sort((Na,To)=>To.updatedAt.localeCompare(Na.updatedAt))){if(In.kind==="evaluation"||!["prepared","running"].includes(In.status))continue;const Na=he.jobs.filter(zm=>zm.metadata.modelRunId===In.id).sort((zm,h_)=>h_.updatedAt.localeCompare(zm.updatedAt))[0];if(Na&&!$t.has(Na.status))continue;const To=Na?.status??(In.status==="prepared"?"starting":"running");js[In.modelId]={label:ba[To]??"Running",status:To}}for(const In of[...he.jobs].sort((Na,To)=>To.updatedAt.localeCompare(Na.updatedAt))){if(!$t.has(In.status))continue;const Na=Xe.get(In.planId)?.modelId;!Na||js[Na]||(js[Na]={label:ba[In.status]??"Active",status:In.status})}return js})();return g.jsx(Jb,{showToast:gt,children:g.jsx(U4,{className:d_,style:c_,sidebar:{activityTimes:Ve,onOpenPonder:()=>{Lt({kind:"chat",sessionId:null}),Ne(null),fe("chat"),a("activity")},productArea:wl,modelProjects:(pn.payload?.modelProjects??[]).filter(he=>he.hosted===null||he.hosted.teamId===(ca.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:f_,onProductAreaChange:$m,experience:je,view:B,selectedAppId:ne,selectedProjectId:G,selectedSessionId:te,selectedTeamThreadId:ft.selectedThreadId,teamChatEnabled:Ir!==null,organizations:kr,selectedTeamId:ca.defaultTeamId??null,teamChatOrganization:wr,teamChatLoading:ft.loading,currentUserId:ft.currentUserId,teamMembers:ft.members,teamThreads:ft.threads,..._r,onOpenTeamChat:Pm,discoverCommunities:Tm,account:Is,connection:_t,profile:pt?.profile,pinnedCollapsed:oa,cloudProjectsCollapsed:Ze,chatsCollapsed:Tn,savedForLaterCollapsed:Ja,archivedChatsOpen:H,cloudProjectsExpanded:J,sectionMenuOpen:F,dragItem:Ui,taskDragSessionId:jr,taskPreviewSessionIds:So,activeSessions:Ks,archivedSessions:Zn,pinnedRows:et,pinnedSessions:Ps,savedForLaterSessions:Tr,savedForLaterFiles:Ws,projectRows:Ts,localProjectRows:As,cloudProjectRows:Er,projectSessionRowsByProjectId:mo,childSessionRowsByParentId:Gs,sidebarProjectIdBySessionId:Xa,terminalSummaries:go,runningSessionIds:Di,goalRuntimeBySessionId:bo,subagentRuntimeBySessionId:yo,visibleChatRows:po,chatRows:va,chatRowsVisibleCount:Zs,expandedProjectIds:Ai,currentVersion:pt?.server.version??null,platform:ua,arch:_t?.arch??null,onSidebarResizeStart:Ke,setSidebarOpen:pe,setView:fe,setSelectedAppId:Fe,setSelectedProjectId:Pe,setSelectedSessionId:Ne,setSearchOpen:Ae,setSectionMenuOpen:Ue,setSettingsSection:dn,onSelectTeam:wm,onLogOut:Im,onTogglePinnedCollapsed:ws,onToggleCloudProjectsCollapsed:ja,onToggleChatsCollapsed:lt,onToggleSavedForLaterCollapsed:sn,setArchivedChatsOpen:qe,setCloudProjectsExpanded:bn,setChatRowsVisibleCount:Mt,beginNewChat:km,beginProjectChat:_o,onAddProject:gl,dockSessionRight:Wi,selectTeamThread:he=>{fe("team"),ft.selectThread(he)},openTeamDm:he=>{fe("team"),ft.openDm(he)},toggleSessionPinned:Ki,toggleProjectPinned:ml,toggleSessionSavedForLater:pl,openSidebarFile:Om,setSidebarFileStatus:(he,Xe)=>{uo(he,Xe)},archiveSession:Xu,restoreSession:ul,renameSession:em,removeProject:xm,expandProject:Ya,toggleProjectExpanded:Ei,startPinnedDrag:ns,clearSidebarDrag:xo,previewPinnedDrop:qi,commitPinnedDrop:Bi,commitPinnedPreviewDrop:Fi,startTaskDrag:Mr,clearTaskDrag:ts,previewTaskDrop:Li,commitTaskDrop:zi,commitTaskPreviewDrop:Hi},topBar:{sidebarOpen:Vt,sidebarAvailable:Bt,title:B==="chat"&&n?"Ponder Pal":Nu,backAction:Se.backAction,breadcrumbs:Se.breadcrumbs,workspaceName:io,workspaceId:ro,busy:me,workspaceState:rn,workspaceKind:oo,selectedApp:D??en,selectedProject:xn,workspaceDiff:Hn,managedWorkspace:ju,workspaceBusy:Ft,defaultTeamId:ca.defaultTeamId,activityActorId:pt?.account.profile?.id??null,activityProjectId:u?.kind==="models"?u.route.projectId??null:null,showDiffControls:B==="chat"&&je==="development",diffPanelOpen:Re,terminalOpen:He,rightSidebarAvailable:l_,rightSidebarOpen:B==="labs"&&p?c?.open??!1:B==="scheduled"?r:Re,onToggleDiffPanel:bl,onToggleRightSidebar:B==="labs"&&p?c?.toggle:B==="scheduled"?()=>i(he=>!he):B==="team"&&so?Ri:bl,onOpenSearch:()=>{Ue(null),Ae(!0)},onToggleTerminal:()=>Et(he=>!he),onRunTerminalCommand:he=>{w({id:Date.now(),scope:Zg,command:he}),Et(!0)},onWorkspaceToolAction:Bu,onOpenCommitDialog:Hu,onWorkspaceBranchChange:zu,onWorkspaceBranchCreate:Uu,connection:_t,onBootstrap:qn,onOpenSandboxWorkspace:hl,onShowSidebar:()=>pe(!0),platform:ua,showWorkspaceControls:B!=="team"&&B!=="community"&&B!=="labs"&&B!=="scheduled"&&B!=="outputs"&&B!=="projects"&&(je==="development"||je==="work"&&!!(xn||we?.localProjectId||we?.cloudProjectId||we?.workspaceKind==="local_project"))},mainPane:{ponderMode:n,onPonderModeChange:a,experience:je,onNewExperienceChange:De,view:B,teamChat:{currentUserId:ft.currentUserId,members:ft.members,agents:ft.agents,profile:pt?.profile??null,teamId:Ir,teamName:wr?.displayName??null,detail:ft.detail,aiThread:ft.aiThread,agentConversation:ft.agentConversation,loading:ft.loading,busy:ft.busy,error:ft.error,connection:_t,providerSettings:pt?.providers??null,provider:ia,model:On,codexPermissionMode:oe,codexReasoningEffort:be,openPondCommandAccessMode:Cs,contextWindowStatus:ko,showToast:gt,onProviderChange:Vi,onModelChange:At,onCodexPermissionModeChange:co,onCodexReasoningEffortChange:Cr,onOpenPondCommandAccessModeChange:Rr,onOpenProviderSettings:()=>{Lt({kind:"view",view:"apps"})},onSendMessage:ft.sendMessage,onPublishProfileAgent:_i,onOpenAiThread:async he=>{await ft.openAiThread(he),Be("chat"),at(!0)},onOpenAgentConversation:async he=>{await ft.openAgentConversation(he),Be("chat"),at(!0)},onCloseAiThread:()=>at(!1),onCloseAgentConversation:()=>{ft.closeAgentConversation(),at(!1)},onSendAgentTurn:ft.sendAgentTurn,onSendAiTurn:ft.sendAiTurn,onStopAiTurn:ft.stopAiTurn,onEditMessage:ft.editMessage,onDeleteMessage:ft.deleteMessage,onRetryMessage:ft.retryMessage,onDismissFailedMessage:ft.dismissFailedMessage,onLoadMoreMessages:ft.loadMoreMessages,onRetryLoad:ft.refresh},community:Ci,bootstrap:pt,runtimeEvents:es,chatMessages:ho,pendingUserMessage:te?ao[te]??null:null,contextWindowStatus:ko,goalRuntime:fo,subagentRuntime:Oa,selectedSessionId:te,composerDraftStore:f,mainComposerFocusRequestId:z,labCloseDetailRequestId:Se.closeDetailRequestId,labCloseDetailKind:Se.closeDetailKind,sideChatTrainingLaunchRequest:vl,onSideChatTrainingLaunchHandled:he=>cm(Xe=>Xe?.id===he?null:Xe),mentionApps:Bn,connectedAppMentions:Ma,profileSkills:Rm,selectedMentionAppId:E,busy:me,turnRunning:vo,activeProvider:ia,activeModel:On,codexPermissionMode:oe,codexReasoningEffort:be,openPondCommandAccessMode:Cs,pendingApproval:kn,activeWorkspaceAppId:Pi,activeWorkspaceId:ro,activeWorkspaceKind:oo,projectTarget:$u,actionCatalog:Ti,workspaceTarget:rl,connection:_t,workspaceName:io,workspaceState:rn,workspaceDiff:Hn,workspaceBusy:Ft,diffBusy:as,forceChatThread:!!te,diffPanelOpen:Re,diffPanelExpanded:Q,rightPanelMode:xe,rightPanelTabRequest:R,rightChatPanels:dm,runtimeEventStore:ga,nativeSkillSidebar:yl,extensionSkillSidebar:Co,workspaceDiffPanelViewState:O,sidebarFileOpenRequest:ss,sidebarFileBookmarks:$i,onSetSidebarFileStatus:(he,Xe)=>{uo(he,Xe)},browserConversationId:Or,terminalScope:Zg,terminalTabs:C,terminalCwd:i_,pendingTerminalCommand:b,terminalOpen:He,onToggleTerminal:()=>Et(he=>!he),onWorkspaceDiffPanelViewStateChange:ol,training:pn,trainingSessions:le,trainingChatHandoff:Rs,trainingDetailTasksetId:_,onTrainingDetailTasksetIdChange:M,onTrainingChatTaskSelect:Gn,onTrainingChatHandoffDismiss:Pr,onOpenSession:wo,onExperienceHandoff:Em,cloudProjects:pt?.cloudProjects??[],projects:_m,projectsAccountBaseUrl:Is?.baseUrl??Is?.activeProfile?.baseUrl??null,projectsTeamName:wr?.displayName??null,projectTaskCounts:Cm,onNewCloudProject:sm,onNewLocalProject:gl,onNewProjectTask:he=>_o(he.id),onToggleProjectPinned:ml,onUploadLocalProject:tm,chatHistoryHasMore:m_,chatHistoryLoading:p_,onDiffPanelResizeStart:St,onToggleDiffPanelExpanded:()=>Ct(he=>!he),onShowDiffPanel:im,onShowBrowserPanel:om,onShowFilesPanel:()=>mm("files"),onShowGoalSidebarTab:Js,onShowTrainingDraftPanel:()=>{Be("training"),at(!0)},onShowRightChatPanel:um,onAddRightChat:()=>Wi(null),onOpenRightChatForSession:(he,Xe)=>{const $t=Xe??le.find(ba=>ba.id===he)??null;$t&&Wi($t,{preserveView:!0})},onLabDetailOpenChange:Se.onDetailOpenChange,evaluationSidebarActive:B==="labs"&&p,onEvaluationSidebarControl:l,scheduledDetailOpen:r,onScheduledDetailOpenChange:i,onTerminalTabsChange:P,onCloseRightChatPanel:lm,onCloseNativeSkillSidebar:kl,onActivateRightChatPanel:fm,onRightChatModelChange:hm,onRightChatPromptChange:gm,onRightChatScrollStateChange:bm,onRightChatProviderChange:vm,onSubmitRightChat:pm,onStopRightChat:he=>Io(he),onCloseTerminal:()=>Et(!1),onLoadMoreChatHistory:Oi,canSyncWorkspace:Mu,startMessage:_s,onPayload:qn,onError:qt,setView:fe,onOpenProfileSettings:ym,onOpenProviderSettings:()=>{Lt({kind:"view",view:"apps"})},onOpenTrainingSettings:()=>{Lt({kind:"settings",section:"training"})},onOpenDatasetStorageSettings:()=>{Lt({kind:"settings",section:"dataset-storage"})},changeDraftProvider:Vi,changeProjectTarget:Du,changeWorkspaceTarget:nm,setDraftProvider:ut,setDraftModel:At,onBeginNewChatWithModel:ji,changeCodexPermissionMode:co,changeCodexReasoningEffort:Cr,changeOpenPondCommandAccessMode:Rr,resolveApproval:lo,answerCreateImproveQuestion:il,applyCreateImproveCandidate:Wu,approveCreateImproveRun:Gu,cancelCreateImproveRun:Zu,openCreateImprovePullRequest:cl,reconcileCreateImprovePullRequest:Ju,rejectCreateImproveCandidate:Qu,pauseCreateImproveRun:ll,resumeCreateImproveRun:dl,reviseCreateImproveRun:Yu,setMentionedAppId:T,showToast:gt,onSaveTaskDraft:Am,sendPrompt:am,stopTurn:he=>Io(void 0,he),syncWorkspaceLocally:Ku,refreshWorkspaceDiff:$n},cloudSetup:{state:y,onClose:()=>I(null),onOpenBrowserUrl:rm,onStart:()=>{fl()}},projectConfirm:{state:V,onResolve:Y},lazyPanels:{activeSessions:Ks,branchDialogName:Ge,branchDialogOpen:$e,commitDialogOpen:U,commitDraft:Oe,commitIncludeUnstaged:de,commitMessage:ae,commitNextStep:ye,canPublishOpenPondProject:Ou,connection:_t,expandProject:Ya,newProjectBusy:X,newProjectDialogOpen:Me,newProjectDirectory:ca.defaultNewProjectDirectory,newProjectMode:Te,newProjectName:N,newProjectPath:q,projectRows:da,query:se,searchOpen:ee,visibleWorkspaceDiff:Hn,visibleWorkspaceState:rn,workspaceBusy:Ft,appDispatch:S,beginNewChat:()=>la(null),openDefaultsSettingsFromBranchDialog:qu,setBranchDialogName:Mn,setBranchDialogOpen:Pn,setCommitDialogOpen:un,setCommitDraft:Sn,setCommitIncludeUnstaged:Ut,setCommitMessage:yn,setCommitNextStep:Rn,setNewProjectDialogOpen:jn,setNewProjectName:kt,setNewProjectPath:ks,setPrompt:ot,setQuery:Le,setSearchOpen:Ae,submitCommitDialog:Fu,submitCreateWorkspaceBranch:Vu,submitNewProjectDialog:Lu},toast:{toast:yt,onDismiss:()=>S({type:"field",key:"toast",value:null})}})})}const Go=new Map,hd=new Map;function Pf(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(s=>s.isActive)??null,n=e.activeProfile?.handle?.trim()||t?.handle?.trim()||e.label.trim()||"signed_in",a=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"";return[n,a,e.apiBaseUrl??"",e.chatApiBaseUrl??""].join("|")}function FF(e){const t=e?.trim();if(!t)return null;const n=Go.get(t);return n?.updatedAt?n.organizations:null}function VF(e,t){const n=e?.trim();if(n){Go.set(n,{organizations:t,promise:null,updatedAt:Date.now()});for(const a of hd.get(n)??[])a()}}function KF(e,t){const n=e?.trim();if(!n)return()=>{};const a=hd.get(n)??new Set;return a.add(t),hd.set(n,a),()=>{a.delete(t),a.size===0&&hd.delete(n)}}function oy(e){const t=e.accountKey?.trim();if(!t)return Promise.resolve([]);const n=Go.get(t);if(!e.force){if(n?.updatedAt)return Promise.resolve(n.organizations);if(n?.promise)return n.promise}const a=e.fetchOrganizations().then(s=>(VF(t,s),s)).catch(s=>{const r=Go.get(t);throw r?.promise===a&&Go.set(t,{organizations:r.organizations,promise:null,updatedAt:r.updatedAt}),s});return Go.set(t,{organizations:n?.organizations??[],promise:a,updatedAt:n?.updatedAt??0}),a}const MG="openpond.config.json";function OG(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function a1(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function bp(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function $G(e,t=null){const n=GF(e.openFilePaths.map(s=>cy(s,t)).filter(Boolean)),a=e.selectedPath&&cy(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function iy(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 cy(e,t=null){let n=WF(e);const a=t?.trim().replace(/\\/g,"/").replace(/\/+$/,"");if(!a)return n;if(n===a)return"";n.startsWith(`${a}/`)&&(n=n.slice(a.length+1));const s=a.split("/").filter(Boolean).at(-1);return s&&n.startsWith(`${s}/`)&&(n=n.slice(s.length+1)),n}function NG(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function DG(e){return{path:e,status:"unchanged",additions:0,deletions:0,patch:"",content:null}}function LG(e,t){const n=ly(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const s=ly(a);return!!(s&&s.startsWith(`${n}/`))})}function zG(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function HG(e){return/\.(?:doc|docx|pdf)$/i.test(e)}function WF(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 GF(e){return Array.from(new Set(e))}function ly(e){const n=e.replace(/\\/g,"/").replace(/^\.\/+/,"").split("/").filter(Boolean);return n.length===0?null:n.join("/")}function ZF(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(c=>c.isActive)??null,n=e.profile?.id?.trim()??"",a=e.activeProfile?.handle?.trim()||t?.handle?.trim()||e.label.trim()||"signed_in",s=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"",r=e.apiBaseUrl??t?.apiBaseUrl??"",i=e.chatApiBaseUrl??t?.chatApiBaseUrl??"";return[n?`profile:${n}`:"profile:unknown",a,s,r,i].join("|")}function s1(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function JF(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n)}function _u(e){const t=e,n=t.teamId||t.id||"";if(!n)return null;const a=t.displayName||t.name||n,s=t.workspaceKind==="personal"||t.isPersonalDefault===!0||t.kind==="personal_default"||t.name?.trim().toLowerCase()==="personal";return{teamId:n,slug:t.slug||s1(a),name:t.name||a,displayName:a,role:t.role==="owner"||t.role==="admin"||t.role==="member"?t.role:"member",workspaceKind:t.workspaceKind==="personal"||t.workspaceKind==="shared"?t.workspaceKind:s?"personal":"shared",status:t.status==="disabled"||t.status==="archived"?t.status:"active",kind:t.kind==="personal_default"||t.kind==="managed_client"||t.kind==="team"?t.kind:void 0,isPersonalDefault:s,isManagedClient:t.isManagedClient===!0||t.kind==="managed_client",primaryContactEmail:t.primaryContactEmail??null,customDomain:t.customDomain??null,planKey:typeof t.planKey=="string"?t.planKey:null,effectiveAccessState:t.effectiveAccessState==="checkout_pending"||t.effectiveAccessState==="active"||t.effectiveAccessState==="grace"||t.effectiveAccessState==="suspended"||t.effectiveAccessState==="cancelling"||t.effectiveAccessState==="cancelled"?t.effectiveAccessState:null,canManageBilling:t.canManageBilling===!0||t.role==="owner",createdAt:t.createdAt??"",updatedAt:t.updatedAt??""}}function QF(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 YF(e,t){const n=e.filter(s=>s.status==="active"&&s.workspaceKind==="shared"),a=t?.trim()??"";if(a){const s=n.find(r=>r.teamId===a);if(s)return s}return n.find(s=>s.role==="owner")??n.find(s=>s.role==="admin")??n[0]??null}function XF(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function e5({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const t5=[{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 n5(...e){return XF(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function a5(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return n5(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function s5({bootstrap:e,draftModel:t,draftProvider:n,selectedApp:a,selectedAppId:s,selectedCloudProject:r,selectedProject:i,selectedSession:c,selectedSessionId:l,selectedSessionLinkedProject:u}){const p=c?.workspaceKind==="local_project"?c.workspaceId??null:u?.id??null,f=Gt(l)&&!c,S=c?Ss(c.workspaceKind):!1,b=xs(c),w=c?HF(c):!1,C=c?.cwd&&(!S||b)?AS(c.cwd):null,P=e?.providers??null,_=Ra(i,e?.cloudProjects??[]),M=e5({draftProvider:n,hasSelectedCloudProject:!!r,selectedSessionHybridWorkspace:b}),E=Sr(M,t,P),T=Sa(e?.preferences),y=f?null:c?S?c.workspaceKind??"sandbox":w?"sandbox":p?"local_project":c.workspaceKind??(c.appId?"sandbox_app":C?"local_project":null):r?"sandbox":i?"local_project":s?"sandbox_app":null,I=f?null:c?S&&!b||w?null:p||(c.workspaceId??c.appId??C):r?null:i?.id??s,R=f?null:c?S?c.workspaceId??null:w?null:p??c.workspaceId??c.appId??C:r?null:i?.id??s,O=e?.account??null,z=!e||O?.state==="loading"||O?.state==="switching",$=!z&&O?.state==="signed_out",V=z?null:$?"Sign in":O?.label??O?.activeProfile?.handle??"Account",Y=a5(O),se=Y?`Welcome, ${Y}`:"Welcome",ee=c?.workspaceName??c?.appName??r?.name??i?.name??a?.name??null,H=Ss(y)?"cloud":"local",F=i?.name??u?.name??(c?.workspaceKind==="local_project"?c.workspaceName:null)??"Local workspace",J=(H==="cloud"?ee:null)??r?.name??_?.name??i?.name??"Cloud workspace",K=!!(r?.id||_?.id||c?.cloudProjectId||H==="cloud");return{account:O,accountLabel:V,accountPending:z,accountSignedOut:$,activeModel:E,activeProvider:M,activeWorkspaceAppId:I,activeWorkspaceId:R,activeWorkspaceKind:y,activeWorkspaceLocation:H,appDefaults:T,cloudLinked:K,cloudTargetName:J,localTargetName:F,selectedCodexHistoryPending:f,selectedSessionCloudWorkspace:S,selectedSessionLocalPathWorkspaceId:C,selectedSessionPendingCloudStart:w,selectedSessionProjectId:p,startMessage:se,workspaceName:ee}}function r5({accountPending:e,accountSignedOut:t,activeWorkspaceLocation:n,bootstrap:a,busy:s,cloudLinked:r,selectedCloudProject:i,selectedProject:c,selectedSession:l,pendingWorkspaceTarget:u,workspaceStates:p,workspaceBusy:f}){const S=Ra(c,a?.cloudProjects??[]),w=!!!c?.linkedSandboxProject?.projectId||!!S,C=h.useMemo(()=>{const R=(a?.localProjects??[]).map(V=>({value:`local:${V.id}`,label:V.name,detail:V.workspacePath,kind:"local"})),O=(a?.cloudProjects??[]).map(V=>({value:`cloud:${V.id}`,label:V.name,detail:V.organizationName??V.sourceLabel??"OpenPond Cloud",kind:"cloud"})),z=c?`local:${c.id}`:i?`cloud:${i.id}`:"none",$=[...R,...O].find(V=>V.value===z)??null;return{value:z,label:$?.label??"Select Project",detail:$?.detail??"Choose a project for local or cloud work",busy:f||s,options:[...R,...O,...t5,{value:"none",label:"Don't work in a project",detail:"General chat without project files",kind:"none"}]}},[a?.cloudProjects,a?.localProjects,s,i,c,f]),P=!!(r||c),_=!!(i?.id||S?.id||l?.cloudProjectId||xs(l)),M=c?p[c.id]??null:null,E=bI(M,{branch:c?.linkedSandboxProject?.defaultBranch??null,path:c?.workspacePath??l?.cwd??null,linkedCloudSourceKnown:c?.linkedSandboxProject?.projectId&&w?!!c.linkedSandboxProject.lastUploadedCommit||!M?.headCommit:!0}),T=yI(c,i??S,M,{cloudLinkTrusted:w}),y=Hq(c,M,{cloudLinkTrusted:w}),I=h.useMemo(()=>{const R={value:"local",label:c?"Local checkout":"Local",detail:c?"Use the selected checkout on this machine.":"Use an app-managed task workspace on this machine.",stateNote:c?E:"App-managed local task workspace",disabled:!1,disabledReason:null},O={value:"hybrid",label:"Hybrid",detail:"Use your selected model with hosted sandbox edits.",stateNote:_?T:"upload required",disabled:e||t||!_,disabledReason:t?"Add an OpenPond account before using Hybrid.":"Upload/sync this Project to Cloud before using Hybrid."},z={value:"cloud",label:"Hosted",detail:"Run with hosted compute, with or without a Project.",stateNote:c||i?T:"Projectless hosted task",disabled:e||t,disabledReason:t?"Add an OpenPond account before using Cloud.":e?"Checking OpenPond account.":null},$={value:"upload_cloud",label:"Upload/sync to cloud",detail:"Push local source to OpenPond Git before cloud work.",stateNote:y,disabled:e||t||!c,disabledReason:t?"Add an OpenPond account before uploading source.":"Select a local Project before uploading source."},V=n==="cloud"?"local":"cloud",Y=V==="local"?R:z;let se=n==="cloud"?z:R;return u==="cloud"?se=z:u==="local"?se=R:(xs(l)||u==="hybrid")&&(se=O),{value:se.value,label:se.label,detail:se.stateNote||se.detail,busy:f,action:{...Y,label:V==="cloud"?"Hosted":c?"Local checkout":"Check out locally"},uploadAction:c?$:null,options:[R,O,z]}},[n,e,t,r,P,T,_,E,u,c,l,y,f]);return{projectTarget:C,workspaceTarget:I}}function Un(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}function r1(e){return Un(e.name||e.gitRepo||e.id)}function UG(e){return`@${r1(e)}`}function o1(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Un(t[1]??"")).filter(Boolean)}function o5(e,t){const n=o1(e);if(n.length===0)return!1;const a=new Set([Un(t.id),r1(t),t.gitRepo?Un(t.gitRepo):""].filter(Boolean));return n.some(s=>a.has(s))}function i1(e){return e.filter(t=>t.sandbox)}function i5(e,t){const n=o1(e);if(n.length===0)return null;const a=new Map;for(const s of n){const r=t.find(i=>{const c=Un(i.id),l=Un(i.name),u=i.gitRepo?Un(i.gitRepo):"";return s===c||s===l||s===u});r&&a.set(r.id,r)}return a.size===1?Array.from(a.values())[0]??null:null}function qG(e,t){const n=e.slice(0,t),a=n.match(/(?:^|\s)@([A-Za-z0-9_-]*)$/);if(!a||typeof a.index!="number")return null;const s=n.slice(a.index).indexOf("@");return s<0?null:{query:Un(a[1]??""),start:a.index+s}}function c5(e){return new Set(e.map(t=>t.id))}function dy(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function l5({bootstrap:e,codexHistorySessions:t,selectedProjectId:n,selectedSessionId:a,selectedAppId:s,sessions:r}){const i=h.useMemo(()=>e?.apps.find($=>$.id===s)??null,[e?.apps,s]),c=h.useMemo(()=>new Map((e?.localProjects??[]).map($=>[$.id,$])),[e?.localProjects]),l=h.useMemo(()=>new Map((e?.cloudProjects??[]).map($=>[$.id,$])),[e?.cloudProjects]),u=h.useMemo(()=>oI(n),[n]),p=h.useMemo(()=>u?.kind==="local"?c.get(u.id)??null:null,[c,u]),f=h.useMemo(()=>u?.kind==="cloud"?l.get(u.id)??null:null,[l,u]),S=h.useMemo(()=>c5(e?.apps??[]),[e?.apps]),b=h.useMemo(()=>i1(e?.apps??[]),[e?.apps]),w=h.useMemo(()=>{const $=[];for(const V of e?.localProjects??[]){const Y=dy(V,S);Y&&$.push([Y.appId,V.id])}return new Map($)},[e?.localProjects,S]),C=h.useMemo(()=>new Set((e?.localProjects??[]).map($=>$.id)),[e?.localProjects]),P=h.useMemo(()=>mI(e?.localProjects??[]),[e?.localProjects]),_=h.useRef([]),M=h.useMemo(()=>d5(r,t,_.current),[t,r]),E=h.useMemo(()=>M.find($=>$.id===a)??null,[M,a]),T=h.useMemo(()=>{if(!E)return null;if(E.localProjectId)return c.get(E.localProjectId)??null;if(E.workspaceKind==="local_project")return E.workspaceId?c.get(E.workspaceId)??null:null;const $=Aq(E,C,P);if($)return c.get($)??null;if(!E.appId)return null;const V=w.get(E.appId);return V?c.get(V)??null:null},[w,c,C,P,E]),y=h.useMemo(()=>E?.cloudProjectId?l.get(E.cloudProjectId)??null:null,[l,E]),I=p??T,R=f??y,O=h.useMemo(()=>dy(I,S),[S,I]),z=h.useMemo(()=>O?e?.apps.find($=>$.id===O.appId)??null:null,[e?.apps,O]);return{cloudProjectById:l,currentAppIds:S,linkedProjectByAppId:w,localProjectById:c,mentionableSandboxApps:b,selectedApp:i,selectedCloudProject:R,selectedProject:I,selectedProjectLinkedApp:z,selectedProjectLinkedOpenPondApp:O,selectedSession:E,selectedSessionLinkedProject:T,sidebarSessions:M}}function d5(e,t,n){const a=new Map;for(const u of e){const p=uy(u);a.set(p,u)}for(const u of t){const p=uy(u),f=a.get(p);a.set(p,f?u5(f,u):u)}const s=Array.from(a.entries());if(!n)return s.sort((u,p)=>my(u[1],p[1])).map(u=>u[1]);const r=[],i=new Set;for(const u of n){const p=a.get(u);p&&(r.push([u,p]),i.add(u))}const l=[...s.filter(([u])=>!i.has(u)).sort((u,p)=>my(u[1],p[1])),...r];return n.splice(0,n.length,...l.map(([u])=>u)),l.map(u=>u[1])}function u5(e,t){return{...e,metadata:m5(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:p5(e.updatedAt,t.updatedAt)}}function uy(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function my(e,t){const n=py(t)-py(e);return n!==0?n:e.title.localeCompare(t.title)}function m5(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function p5(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 py(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 f5(e){return!!(e&&Ss(e.workspaceKind)&&!xs(e)&&e.provider!=="openpond")}function h5(e,t){const n=lI(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function g5({activeWorkspaceId:e,activeWorkspaceKind:t,appDispatch:n,connection:a,expandProject:s,linkedProjectByAppId:r,providerSettings:i,selectedAppId:c,selectedSession:l,selectedSessionId:u,selectedSessionProjectId:p,setDiffPanelExpanded:f,setDraftModel:S,setDraftProvider:b,setError:w,setSelectedAppId:C,setSelectedProjectId:P,setSessions:_,setTerminalOpen:M,toast:E}){const T=h.useRef(null);h.useEffect(()=>{if(!c)return;const y=p??(u?null:r.get(c)??null);if(!y)return;const I=ct("local",y);C(null),P(I),s(I)},[s,r,c,u,p,C,P]),h.useEffect(()=>{if(!E||E.persistent)return;const y=window.setTimeout(()=>{n({type:"clearToast",toastId:E.id})},E.durationMs??(E.tone==="error"?7e3:3500));return()=>window.clearTimeout(y)},[n,E]),h.useEffect(()=>{function y(I){(I.metaKey||I.ctrlKey)&&I.key==="`"&&(I.preventDefault(),M(R=>!R))}return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[M]),h.useEffect(()=>{f(!1)},[e,t,f]),h.useEffect(()=>{if(!u){T.current=null;return}if(!l||l.id!==u)return;const y=h5(l,i);if(T.current===y)return;T.current=y;const I=lI(l,i);b(I.provider),S(I.model)},[i,l,u,S,b]),h.useEffect(()=>{!a||!l||!f5(l)||Z.patchSession(a,l.id,{provider:"openpond"}).then(y=>{_(I=>I.map(R=>R.id===y.id?y:R)),b("openpond"),S(I=>Sr("openpond",I))}).catch(y=>{w(y instanceof Error?y.message:String(y))})},[a,l,S,b,w,_])}function v5({connection:e,setError:t}){return h.useCallback(async(n,a,s)=>{if(!e){const r=new Error("OpenPond App server is not connected.");throw t(r.message),r}t(null);try{await Z.resolveApproval(e,n,{decision:a,answers:s})}catch(r){const i=r instanceof Error?r.message:String(r);throw t(i),r}},[e,t])}function b5({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:s,pinnedProjects:r,projectRows:i,visibleProjectRows:c}){const l=h.useMemo(()=>gq(a,s),[a,s]),u=h.useMemo(()=>OI({provider:e,snapshot:n,preferences:t}),[e,t,n]),p=h.useMemo(()=>Array.from(new Set([...r,...c].filter(wg).map(S=>S.project.id))),[r,c]);return{commandProjectRows:h.useMemo(()=>i,[i]),contextWindowStatus:u,pinnedRows:l,sidebarWorkspaceAppIds:p}}function y5({appDispatch:e,expandProject:t,linkedProjectByAppId:n,requestComposerFocus:a,onBeginNewChat:s,setMentionedAppId:r}){return h.useCallback((i=null)=>{s?.();const c=i?.id?n.get(i.id)??null:null;if(c){const l=ct("local",c);r(null),e({type:"selectProject",projectId:l}),t(l),a();return}r(null),e({type:"beginNewChat",appId:i?.id??null}),a()},[e,t,n,s,a,r])}const c1={slack:["slack"],microsoft_teams:["teams","microsoft-teams","microsoft_teams"],github:["github","gh"],google:["google","drive","google-drive","docs"],turnkey:["turnkey","agent-wallet","agent_wallet","wallet"],x:["x","twitter"],mcp:["mcp","openpond-mcp"]};function BG(e){return`@${e.token}`}function S5(e){return`@${_5(e)}`}function x5(e){const t=new Map;for(const n of e){if(!n.connected||n.statusSource!=="integration_connection")continue;const a=t.get(n.providerFamily)??[];a.push(n),t.set(n.providerFamily,a)}return Array.from(t.entries()).map(([n,a])=>{const s=a[0],r=Do(a.flatMap(f=>f.capabilities.map(S=>S.id))),i=Do(a.flatMap(f=>f.capabilityLabels)),c=Do(a.flatMap(f=>f.connections.map(S=>S.id).filter(R5))),l=Do(a.map(f=>f.id)),u=Do(a.map(f=>f.setupSurface)),p=I5(n);return{provider:n,label:s.providerLabel,detail:i.length>0?i.slice(0,4).join(", "):s.description,token:p,tokens:w5(a),ref:{kind:"integration",provider:n,appIds:l,setupSurfaces:u,...c.length>0?{connectionIds:c}:{},...r.length>0?{capabilities:r}:{}}}})}function FG(e,t){const n=Un(t);return e.filter(a=>n?a.tokens.some(s=>s.includes(n)):!0).slice(0,8)}function k5(e,t){const n=C5(e);if(n.length===0)return[];const a=new Map;for(const s of n){const r=t.find(i=>i.tokens.includes(s));r&&a.set(r.provider,r)}return Array.from(a.values())}function VG(e,t){if(t.length===0)return[];const n=[];for(const a of e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)){const s=a[1]??"",r=Un(s);if(!r)continue;const i=t.find(f=>f.tokens.includes(r));if(!i)continue;const l=(a[0]??"").indexOf("@");if(l<0||typeof a.index!="number")continue;const u=a.index+l,p=`@${s}`;n.push({detail:i.detail,displayText:S5(i),end:u+p.length,label:i.label,provider:i.provider,start:u,text:p})}return n}function w5(e){return Do(e.flatMap(t=>[...c1[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map(Un).filter(Boolean))}function I5(e){return Un(c1[e][0]??e)}function _5(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function C5(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Un(t[1]??"")).filter(Boolean)}function Do(e){return Array.from(new Set(e))}function R5(e){return typeof e=="string"&&e.length>0}function P5({bootstrap:e,connectedAppRows:t,mentionableSandboxApps:n,runtimeIndexes:a,selectedApp:s,selectedCloudProject:r,selectedProject:i,selectedSession:c,selectedSessionId:l}){const u=h.useMemo(()=>{const w=new Map;for(const C of e?.cloudProjects??[]){const P=w.get(C.teamId)??[];P.push(C.id),w.set(C.teamId,P)}return w},[e?.cloudProjects]),f=!!(c||s||i||r)?[]:n,S=h.useMemo(()=>x5(t),[t]),b=h.useMemo(()=>_F(a,l),[a,l]);return{chatMentionApps:f,cloudProjectIdsByTeam:u,connectedAppMentions:S,pendingApproval:b}}function T5({connection:e,setBootstrap:t,setCodexPermissionMode:n,setCodexReasoningEffort:a,setError:s}){const r=h.useCallback(c=>{if(!e){s("Connect to OpenPond before saving preferences.");return}Z.savePreferences(e,{codexPermissionMode:c}).then(l=>{n(l.preferences.codexPermissionMode),a(l.preferences.codexReasoningEffort),t(u=>u&&{...u,preferences:l.preferences})}).catch(l=>{s(l instanceof Error?l.message:String(l))})},[e,t,n,a,s]),i=h.useCallback(c=>{if(!e){s("Connect to OpenPond before saving preferences.");return}Z.savePreferences(e,{codexReasoningEffort:c}).then(l=>{n(l.preferences.codexPermissionMode),a(l.preferences.codexReasoningEffort),t(u=>u&&{...u,preferences:l.preferences})}).catch(l=>{s(l instanceof Error?l.message:String(l))})},[e,t,n,a,s]);return{changeCodexPermissionMode:r,changeCodexReasoningEffort:i}}const A5=6e4;function Ng(e,t){if(!e)return t;const n=j5(e.updatedAt,t.updatedAt)?{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,status:e.status,updatedAt:e.updatedAt}:t;return d1(e,n)?e:n}function E5(e,t){const n=Ng(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&d1(e,a)?e:a}function cc(e,t){let n=!1,a=!1;const s=e.map(r=>{if(r.id!==t.id)return r;n=!0;const i=Ng(r,t);return i!==r&&(a=!0),i});return n?a?s:e:[t,...e]}function Cu(e,t){let n=!1,a=!1;const s=e.map(r=>{if(r.id!==t.id)return r;n=!0;const i=E5(r,t);return i!==r&&(a=!0),i});return n?a?s:e:[t,...e]}function Tf(e,t,n,a=Date.now()){const s=new Map(e.map(r=>[r.id,r]));return t.map(r=>{const i=s.get(r.id);if(i&&n){const c=O5(i,r,n,a);if(c)return c}return Ng(i,r)})}function fy(e,t,n,a=Date.now()){const s=new Map(e.map(u=>[u.id,u])),r=new Map(Tf(e,t,n,a).map(u=>[u.id,u])),i=new Set(s.keys()),c=t.filter(u=>!i.has(u.id)).map(u=>r.get(u.id)??u),l=e.map(u=>{const p=r.get(u.id);return p||(l1(u,t)?u:null)}).filter(u=>!!u);return[...c,...l]}function l1(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=M5(t);return a===null||n>=a}function hy(e,t,n,a=Date.now()){const s=new Map(t.map(r=>[r.id,r]));for(const r of n){const i=s.get(r.id);i&&(u1(i,r)||(e[r.id]=a))}}function j5(e,t){const n=Date.parse(e),a=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(a)&&n>a}function d1(e,t){return JSON.stringify(e)===JSON.stringify(t)}function M5(e){let t=null;for(const n of e){const a=Date.parse(n.updatedAt);Number.isFinite(a)&&(t=t===null?a:Math.max(t,a))}return t}function O5(e,t,n,a){const s=n[t.id];return s===void 0?null:a-s>A5||u1(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function u1(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const m1=800,$5=5e3,gy=5e4,N5=16,D5=3e4,Xn=new Map;function L5(e,t){return Xn.get(f1(e,t))?.payload??null}async function p1(e,t,n={}){const a=f1(e,t),s=Xn.get(a),r=n.limit??m1,i=n.tail??!0;if(s?.promise)return s.promise;if(!n.force&&i&&s?.payload&&Date.now()-s.fetchedAt<=D5)return vy(a,s),s.payload;const c=!!(n.force&&i&&s?.payload),l=c?s?.payload?.events.at(-1)?.id:void 0,u=Z.codexHistoryThreadIncremental(e,t,{afterEventId:l,limit:r,revision:c?s?.revision:void 0,tail:i}).then(p=>{const f=Xn.get(a)?.payload??s?.payload;if(p.unchanged){if(!f)throw new Error("Codex history revision matched without a cached thread.");return Xn.set(a,{fetchedAt:Date.now(),payload:f,revision:p.revision}),vy(a,Xn.get(a)),f}const S={session:p.session,events:p.events},b=i&&f&&!p.reset?{...S,events:z5(f.events,S.events)}:S;return Xn.set(a,{fetchedAt:Date.now(),payload:b,revision:p.revision}),by(),b}).catch(p=>{throw Xn.get(a)?.promise===u&&Xn.delete(a),p});return Xn.set(a,{fetchedAt:s?.fetchedAt??0,payload:s?.payload,promise:u,revision:s?.revision}),by(),u}function f1(e,t){return`${e.serverUrl}
112
112
  ${e.token}
113
113
  ${t}`}function vy(e,t){Xn.delete(e),Xn.set(e,t)}function by(){for(;Xn.size>N5;){const e=Xn.keys().next().value;if(!e)return;Xn.delete(e)}}function z5(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 H5=500,U5=2500,q5=15e3;function B5(e){return e.active?H5:e.surface==="thread"?U5:q5}function Dg(e,t){return!t||e.session.status==="active"?e:{...e,session:{...e.session,status:"active"}}}function F5(e={}){const t={cachedPayload:e.cachedPayload??L5,clearTimer:e.clearTimer??(u=>globalThis.clearTimeout(u)),loadPayload:e.loadPayload??p1,now:e.now??Date.now,setTimer:e.setTimer??((u,p)=>globalThis.setTimeout(u,p))},n=new Map;let a=1;function s(u){const p=K5(u.connection,u.sessionId);let f=n.get(p);f||(f={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(p,f));const S=a++;return f.subscribers.set(S,u),f.latestPayload&&u.onPayload(f.latestPayload),r(f,0),()=>{const b=n.get(p);if(b){if(b.subscribers.delete(S),b.subscribers.size>0){r(b,c(b));return}b.disposed=!0,l(b),n.delete(p)}}}function r(u,p){if(u.disposed||u.subscribers.size===0||u.inFlight)return;const f=t.now()+Math.max(0,p);u.timer&&u.nextRefreshAt!==null&&u.nextRefreshAt<=f||(l(u),u.nextRefreshAt=f,u.timer=t.setTimer(()=>{u.timer=null,u.nextRefreshAt=null,i(u)},Math.max(0,p)))}async function i(u){if(u.disposed||u.subscribers.size===0||u.inFlight)return;const p=t.loadPayload(u.connection,u.sessionId,{force:!!u.latestPayload});u.inFlight=p;try{const f=await p;if(u.disposed||f===u.latestPayload)return;u.latestPayload=f;for(const S of u.subscribers.values())S.onPayload(f)}catch(f){if(u.disposed)return;for(const S of u.subscribers.values())S.onError?.(f)}finally{u.inFlight===p&&(u.inFlight=null),u.disposed||r(u,c(u))}}function c(u){const p=[...u.subscribers.values()],f=p.some(b=>b.locallyActive||b.reportedActive)||u.latestPayload?.session.status==="active"||Mg(u.latestPayload?.events??[])?.tone==="active",S=p.some(b=>b.surface==="thread")?"thread":"sidebar";return B5({active:f,surface:S})}function l(u){u.timer&&t.clearTimer(u.timer),u.timer=null,u.nextRefreshAt=null}return{subscribe:s}}const V5=F5();function Lg(e){return V5.subscribe(e)}function K5(e,t){return`${e.serverUrl}
114
114
  ${e.token}