openpond 0.2.69 → 0.2.71

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 (397) hide show
  1. package/dist/api/client-context.d.ts +4 -0
  2. package/dist/app-server.js +1 -1
  3. package/dist/chunks/{account-context-V3KLSNKS.js → account-context-LEZDNYMR.js} +1 -1
  4. package/dist/chunks/{acp-ER6CUXG2.js → acp-VWPJ2EL4.js} +1 -1
  5. package/dist/chunks/{acp-agent-AYJ5RPVF.js → acp-agent-OZHZMQ6R.js} +1 -1
  6. package/dist/chunks/{actions-command-BBUS3HDK.js → actions-command-AXGXBU75.js} +1 -1
  7. package/dist/chunks/{app-layer-JCEWGUDH.js → app-layer-OHPIYEOJ.js} +1 -1
  8. package/dist/chunks/{app-server-connected-apps-ILXBFD3S.js → app-server-connected-apps-NH4667QJ.js} +1 -1
  9. package/dist/chunks/{app-server-evaluations-RRLYWLPK.js → app-server-evaluations-Y5UEF2Y7.js} +1 -1
  10. package/dist/chunks/{app-server-harness-services-XXM336NU.js → app-server-harness-services-GUHAIIPS.js} +1 -1
  11. package/dist/chunks/app-server-runtime-CH5STRJP.js +2 -0
  12. package/dist/chunks/apps-DNLT6P4J.js +2 -0
  13. package/dist/chunks/{chunk-MOXIGLN2.js → chunk-23YW5PAQ.js} +1 -1
  14. package/dist/chunks/{chunk-ZDEIVUUI.js → chunk-27OJ2OLP.js} +1 -1
  15. package/dist/chunks/{chunk-RY46UPBO.js → chunk-2ACX7IW5.js} +1 -1
  16. package/dist/chunks/{chunk-NSSZ2ZIU.js → chunk-2EAZB2MW.js} +1 -1
  17. package/dist/chunks/{chunk-DRLP7GIU.js → chunk-2GEZ3ZY7.js} +1 -1
  18. package/dist/chunks/{chunk-PAYFJHPO.js → chunk-2PVW2XFF.js} +1 -1
  19. package/dist/chunks/{chunk-Y2WNZWT2.js → chunk-2Q6FTL4C.js} +1 -1
  20. package/dist/chunks/{chunk-KP2MYTP5.js → chunk-2QHB5P2K.js} +1 -1
  21. package/dist/chunks/{chunk-FNGZ4UDZ.js → chunk-33UVQ7DU.js} +1 -1
  22. package/dist/chunks/{chunk-M4ZHFDRJ.js → chunk-3JVZ7OCQ.js} +1 -1
  23. package/dist/chunks/{chunk-4BUM6JEC.js → chunk-3JYPUOK4.js} +1 -1
  24. package/dist/chunks/{chunk-DXJC3QW7.js → chunk-3VT2PPKW.js} +1 -1
  25. package/dist/chunks/{chunk-Z33RVGP6.js → chunk-5LKEVB2P.js} +1 -1
  26. package/dist/chunks/{chunk-P4QM63L3.js → chunk-5ZBDHIIE.js} +1 -1
  27. package/dist/chunks/{chunk-WD4KAKEX.js → chunk-64EDQ7UV.js} +1 -1
  28. package/dist/chunks/{chunk-UMAVVMXL.js → chunk-6BTX66SV.js} +1 -1
  29. package/dist/chunks/{chunk-KU4TPDPH.js → chunk-6LAGMWJE.js} +1 -1
  30. package/dist/chunks/{chunk-65FJWWXG.js → chunk-6YR5IYHH.js} +1 -1
  31. package/dist/chunks/{chunk-AUO5DCEU.js → chunk-73COPJ32.js} +1 -1
  32. package/dist/chunks/{chunk-KDER7R45.js → chunk-7PDF2UX2.js} +1 -1
  33. package/dist/chunks/{chunk-SO4GMSNP.js → chunk-7SOHV5BH.js} +1 -1
  34. package/dist/chunks/{chunk-XOPHFUUY.js → chunk-ASMQTMQB.js} +1 -1
  35. package/dist/chunks/{chunk-ESYPMD7Q.js → chunk-AT3ZYNX4.js} +1 -1
  36. package/dist/chunks/{chunk-NMMHXYDJ.js → chunk-AVEHWUML.js} +1 -1
  37. package/dist/chunks/{chunk-M4A7G4S5.js → chunk-B7SCVTE6.js} +1 -1
  38. package/dist/chunks/{chunk-7EQLW2KM.js → chunk-BLNEHU62.js} +1 -1
  39. package/dist/chunks/{chunk-DKOVZ6R2.js → chunk-BQNU4HZW.js} +1 -1
  40. package/dist/chunks/{chunk-UANH7U3Y.js → chunk-BTEBZYK3.js} +1 -1
  41. package/dist/chunks/{chunk-BU6MW65V.js → chunk-BYVE4TMU.js} +1 -1
  42. package/dist/chunks/{chunk-PNPV2LDE.js → chunk-BZS2PA4O.js} +1 -1
  43. package/dist/chunks/{chunk-AFYYIJ6K.js → chunk-C7NQPICU.js} +1 -1
  44. package/dist/chunks/{chunk-K7KBFM2T.js → chunk-CBD554GZ.js} +1 -1
  45. package/dist/chunks/{chunk-GYYJ47GX.js → chunk-CWE2N3JI.js} +1 -1
  46. package/dist/chunks/{chunk-ZYLLPRPU.js → chunk-CX4T7I47.js} +1 -1
  47. package/dist/chunks/{chunk-AQUZCWM3.js → chunk-D2V2Y3FB.js} +1 -1
  48. package/dist/chunks/chunk-DFZTRMTL.js +2 -0
  49. package/dist/chunks/{chunk-2PXKSAG6.js → chunk-DLOJG7LP.js} +1 -1
  50. package/dist/chunks/{chunk-5G7BQAUA.js → chunk-DNNWMOMG.js} +1 -1
  51. package/dist/chunks/{chunk-M5X7XKXY.js → chunk-DNRC6TPJ.js} +7 -7
  52. package/dist/chunks/{chunk-HKVFU3B3.js → chunk-DUR32LJG.js} +1 -1
  53. package/dist/chunks/{chunk-XT4CSKHM.js → chunk-E57PUTV2.js} +1 -1
  54. package/dist/chunks/{chunk-4N4EH3RJ.js → chunk-EJOV6Z6F.js} +1 -1
  55. package/dist/chunks/{chunk-OUJ63LMU.js → chunk-ER2VONWQ.js} +1 -1
  56. package/dist/chunks/{chunk-PSY6IRJE.js → chunk-ESOIZG2G.js} +4 -4
  57. package/dist/chunks/{chunk-WNXUSELC.js → chunk-EXAJ2B4I.js} +1 -1
  58. package/dist/chunks/{chunk-CCZ276IA.js → chunk-F2EUZG2W.js} +1 -1
  59. package/dist/chunks/{chunk-VJR2GNRY.js → chunk-FVMTQSVW.js} +1 -1
  60. package/dist/chunks/{chunk-YI6ME6PU.js → chunk-GG6PM7TB.js} +1 -1
  61. package/dist/chunks/{chunk-DDOIPTOM.js → chunk-GMA365GI.js} +1 -1
  62. package/dist/chunks/{chunk-JVMSN7LH.js → chunk-GR4MJJCE.js} +1 -1
  63. package/dist/chunks/{chunk-TB5P3FWM.js → chunk-GUWNSMGH.js} +1 -1
  64. package/dist/chunks/{chunk-AYOMVI7J.js → chunk-HIMG7S5E.js} +1 -1
  65. package/dist/chunks/{chunk-2LJCJOJ7.js → chunk-HLJJAOI2.js} +1 -1
  66. package/dist/chunks/{chunk-AFH462DO.js → chunk-HT6ILPD6.js} +1 -1
  67. package/dist/chunks/{chunk-3Z4VM2LF.js → chunk-HUMNLSCV.js} +1 -1
  68. package/dist/chunks/{chunk-NZDLL6JN.js → chunk-HYUTDZ3N.js} +1 -1
  69. package/dist/chunks/{chunk-XYZV3FKD.js → chunk-I6KTJ3GH.js} +1 -1
  70. package/dist/chunks/{chunk-WZ35ICTE.js → chunk-IFMWAOBR.js} +1 -1
  71. package/dist/chunks/{chunk-R2FYCJL6.js → chunk-IJJ7FYZE.js} +1 -1
  72. package/dist/chunks/{chunk-XHACK2KR.js → chunk-IUYGQO2K.js} +1 -1
  73. package/dist/chunks/{chunk-55YD4UTW.js → chunk-IV2HEX3I.js} +1 -1
  74. package/dist/chunks/chunk-J7X72QUY.js +2 -0
  75. package/dist/chunks/{chunk-U7X5ZLAL.js → chunk-JCHLDNCX.js} +1 -1
  76. package/dist/chunks/chunk-JF7WWLNW.js +2 -0
  77. package/dist/chunks/{chunk-7PKDJHT6.js → chunk-JH4RACOB.js} +1 -1
  78. package/dist/chunks/{chunk-65WRWLUD.js → chunk-JVEIK4RH.js} +1 -1
  79. package/dist/chunks/{chunk-Z5CQXPIS.js → chunk-K3WM4NEC.js} +1 -1
  80. package/dist/chunks/{chunk-EGP6DF34.js → chunk-KASHK2U5.js} +2 -2
  81. package/dist/chunks/{chunk-JEMECEQH.js → chunk-KHDCMVEJ.js} +1 -1
  82. package/dist/chunks/{chunk-BDZDWHBJ.js → chunk-KURL76NW.js} +1 -1
  83. package/dist/chunks/{chunk-7OFD6TFD.js → chunk-LMLGEOKV.js} +1 -1
  84. package/dist/chunks/{chunk-QUNQM2E3.js → chunk-MPEK4ZNY.js} +1 -1
  85. package/dist/chunks/chunk-MZKCW6CB.js +2 -0
  86. package/dist/chunks/{chunk-SDHG6CKU.js → chunk-NDNSLCPE.js} +1 -1
  87. package/dist/chunks/chunk-NK2L5HA2.js +2 -0
  88. package/dist/chunks/{chunk-WCNPGKST.js → chunk-O4YHISU2.js} +1 -1
  89. package/dist/chunks/{chunk-RCQYEHHD.js → chunk-O5ZOW474.js} +1 -1
  90. package/dist/chunks/{chunk-IIT66347.js → chunk-OEAKX5TS.js} +1 -1
  91. package/dist/chunks/{chunk-LSKMALD6.js → chunk-OFV26C2U.js} +2 -2
  92. package/dist/chunks/{chunk-IO5DZUKL.js → chunk-OI4DAZ4U.js} +1 -1
  93. package/dist/chunks/{chunk-Q73RKX7I.js → chunk-OIIE5GUK.js} +1 -1
  94. package/dist/chunks/{chunk-R6I623SZ.js → chunk-OKPV6MBX.js} +6 -6
  95. package/dist/chunks/{chunk-N5EAVX4G.js → chunk-OOKHHOIU.js} +1 -1
  96. package/dist/chunks/{chunk-MIFVX5PK.js → chunk-OQ4RWCYI.js} +1 -1
  97. package/dist/chunks/{chunk-RCRZXHAI.js → chunk-OTG77H7U.js} +1 -1
  98. package/dist/chunks/{chunk-7OKZCJHS.js → chunk-OXRN2257.js} +1 -1
  99. package/dist/chunks/{chunk-4KNPCJR4.js → chunk-PJJSQ4ZI.js} +1 -1
  100. package/dist/chunks/{chunk-7RSQOC5M.js → chunk-PXQZOVSV.js} +2 -2
  101. package/dist/chunks/chunk-QKGNAYSC.js +2 -0
  102. package/dist/chunks/{chunk-R4EEGWXB.js → chunk-QN4CFJQC.js} +1 -1
  103. package/dist/chunks/{chunk-V24VHT76.js → chunk-REGKOCDO.js} +1 -1
  104. package/dist/chunks/chunk-RJY4EI46.js +2 -0
  105. package/dist/chunks/{chunk-E2JB5OCO.js → chunk-RP4DPUN2.js} +1 -1
  106. package/dist/chunks/{chunk-QLGP2OAQ.js → chunk-SNBFWBJI.js} +1 -1
  107. package/dist/chunks/{chunk-G4FRBT7G.js → chunk-SRJTQS2D.js} +3 -3
  108. package/dist/chunks/{chunk-XY7HFXLH.js → chunk-SVLVIYH2.js} +1 -1
  109. package/dist/chunks/{chunk-NW6WGGSL.js → chunk-TCTBCAI6.js} +1 -1
  110. package/dist/chunks/{chunk-7NCM6GBN.js → chunk-TOWY6Y23.js} +1 -1
  111. package/dist/chunks/{chunk-VWWKWYSQ.js → chunk-TWLPZHH7.js} +1 -1
  112. package/dist/chunks/{chunk-Y4I6CFZJ.js → chunk-UGDBMRCT.js} +1 -1
  113. package/dist/chunks/{chunk-JQOVC35K.js → chunk-UKTPX2EE.js} +1 -1
  114. package/dist/chunks/{chunk-CO23RRN7.js → chunk-UMRQKE3W.js} +1 -1
  115. package/dist/chunks/{chunk-B66QCXH2.js → chunk-USKCFST5.js} +1 -1
  116. package/dist/chunks/{chunk-3A2Y7UK3.js → chunk-USTDWGR4.js} +1 -1
  117. package/dist/chunks/{chunk-EWDDDHJN.js → chunk-UZNRH6I3.js} +1 -1
  118. package/dist/chunks/{chunk-CIZI6Z7D.js → chunk-VMW23TIZ.js} +1 -1
  119. package/dist/chunks/{chunk-22RLEU3Q.js → chunk-VND53FAU.js} +1 -1
  120. package/dist/chunks/{chunk-4G3GTEVS.js → chunk-VSQPWLAG.js} +1 -1
  121. package/dist/chunks/{chunk-KCLMA2IH.js → chunk-VV4K5YPD.js} +1 -1
  122. package/dist/chunks/{chunk-7RJOCGQ6.js → chunk-WAUFXZ5B.js} +1 -1
  123. package/dist/chunks/{chunk-HG2YFMVU.js → chunk-WXG3G2O6.js} +1 -1
  124. package/dist/chunks/{chunk-PACLKDTN.js → chunk-XBAB3HMA.js} +1 -1
  125. package/dist/chunks/chunk-XJU47QS2.js +2 -0
  126. package/dist/chunks/{chunk-WGQ3FMRF.js → chunk-XKDOPNQ5.js} +1 -1
  127. package/dist/chunks/{chunk-EYTTZ5H4.js → chunk-XLZMSD5K.js} +1 -1
  128. package/dist/chunks/{chunk-Q7FBVLLB.js → chunk-XNPTLJ5Z.js} +1 -1
  129. package/dist/chunks/{chunk-ZIQJDTQB.js → chunk-XTT3K3TR.js} +1 -1
  130. package/dist/chunks/{chunk-Q7P34B2O.js → chunk-YFHQRDNQ.js} +1 -1
  131. package/dist/chunks/{chunk-UGFSAG4U.js → chunk-YG3HITOU.js} +1 -1
  132. package/dist/chunks/{chunk-DWF3FCY4.js → chunk-Z5R4OSGC.js} +1 -1
  133. package/dist/chunks/{chunk-JT5YQ52I.js → chunk-Z6HWSTEP.js} +1 -1
  134. package/dist/chunks/{chunk-4PUOWSDE.js → chunk-ZEOYNUHL.js} +1 -1
  135. package/dist/chunks/{chunk-2TGHZXJE.js → chunk-ZG3DBXQG.js} +1 -1
  136. package/dist/chunks/{chunk-4KTGYHCE.js → chunk-ZMRP2A7K.js} +1 -1
  137. package/dist/chunks/cli-5JARGJOD.js +2 -0
  138. package/dist/chunks/{command-LNOVZQSK.js → command-AI3SMEAH.js} +11 -11
  139. package/dist/chunks/{configuration-command-C3QBDFND.js → configuration-command-NPA46ZOT.js} +1 -1
  140. package/dist/chunks/connected-app-executor-DLC23O43.js +2 -0
  141. package/dist/chunks/connected-evidence-TVORI55Q.js +2 -0
  142. package/dist/chunks/{connected-starting-assets-5LAJ7CZY.js → connected-starting-assets-WGGBWH4K.js} +1 -1
  143. package/dist/chunks/{continual-FVOLGGOE.js → continual-UHQI2EQD.js} +1 -1
  144. package/dist/chunks/core-commands-QNZUBKOC.js +2 -0
  145. package/dist/chunks/{dataset-preparation-authoring-UUYFWWCT.js → dataset-preparation-authoring-OBMJLGA4.js} +1 -1
  146. package/dist/chunks/datasets-USJLJOEQ.js +2 -0
  147. package/dist/chunks/desktop-test-IYHAOR47.js +3 -0
  148. package/dist/chunks/{dist-2MKJC6HN.js → dist-C5XFRP53.js} +1 -1
  149. package/dist/chunks/evaluation-coordination-UJENK4WQ.js +2 -0
  150. package/dist/chunks/experiment-improvements-6GJMKIER.js +2 -0
  151. package/dist/chunks/experiments-FZHILSC6.js +2 -0
  152. package/dist/chunks/experiments-signal-E32CWBS4.js +2 -0
  153. package/dist/chunks/{help-PLQJOP4P.js → help-32DLAPJR.js} +1 -1
  154. package/dist/chunks/host-profile-evaluation-tools-QAV2UGSB.js +2 -0
  155. package/dist/chunks/{host-profile-external-dataset-KSEPXY2S.js → host-profile-external-dataset-C6ZPMTX6.js} +1 -1
  156. package/dist/chunks/{hosted-app-server-composition-GZES7QXJ.js → hosted-app-server-composition-5DVBKNV3.js} +1 -1
  157. package/dist/chunks/{hosted-experiment-improvement-VG2WE7XZ.js → hosted-experiment-improvement-YQ24C54D.js} +1 -1
  158. package/dist/chunks/hosted-harness-runtime-KLIORGWV.js +2 -0
  159. package/dist/chunks/{hosted-profile-candidate-PTGQLPZO.js → hosted-profile-candidate-RCWFLOVJ.js} +1 -1
  160. package/dist/chunks/{hosted-profile-compiler-FS5R6CHJ.js → hosted-profile-compiler-UDG4BCEW.js} +1 -1
  161. package/dist/chunks/{hosted-profile-evaluation-control-UUEZEMXU.js → hosted-profile-evaluation-control-4R3L4FTK.js} +1 -1
  162. package/dist/chunks/{hosted-profile-evaluation-inspection-4F7OEF4T.js → hosted-profile-evaluation-inspection-NA4SSY7N.js} +1 -1
  163. package/dist/chunks/{hosted-profile-evaluation-preparation-LIJJZDHQ.js → hosted-profile-evaluation-preparation-B4BW6JTB.js} +1 -1
  164. package/dist/chunks/{hosted-tasksets-V24IBVJX.js → hosted-tasksets-IUK3VWSL.js} +1 -1
  165. package/dist/chunks/human-review-D6QCZLYN.js +2 -0
  166. package/dist/chunks/{import-SI24Z7EF.js → import-UCG75PN5.js} +1 -1
  167. package/dist/chunks/{learning-Y3UKNUGE.js → learning-3XDYMYBE.js} +1 -1
  168. package/dist/chunks/learning-OR4CYV4B.js +2 -0
  169. package/dist/chunks/local-harness-improvement-runtime-GZBMBZB2.js +2 -0
  170. package/dist/chunks/local-harness-taskset-review-YVP2ZQJG.js +2 -0
  171. package/dist/chunks/{model-projects-6YWVD2TS.js → model-projects-POZRHXTF.js} +1 -1
  172. package/dist/chunks/opchat-APJUUTT7.js +3 -0
  173. package/dist/chunks/opchat-bounded-chat-PBUSUAY2.js +2 -0
  174. package/dist/chunks/organizations-WK6EZ6L3.js +2 -0
  175. package/dist/chunks/{profile-TD5U3INY.js → profile-BQMS7ALQ.js} +1 -1
  176. package/dist/chunks/project-action-payload-CGV77JSA.js +2 -0
  177. package/dist/chunks/project-agent-XVFYTEUQ.js +2 -0
  178. package/dist/chunks/{published-experiment-source-SDXUVPE7.js → published-experiment-source-2CYFIRBL.js} +1 -1
  179. package/dist/chunks/{refiner-profile-service-56VYLZQJ.js → refiner-profile-service-OLJHA4DI.js} +1 -1
  180. package/dist/chunks/{runtime-Q7JUJO4D.js → runtime-32KYSVZR.js} +1 -1
  181. package/dist/chunks/sandbox-command-OY3VZXGG.js +2 -0
  182. package/dist/chunks/{sandbox-template-GOY7QQUY.js → sandbox-template-YOOSJ4FK.js} +1 -1
  183. package/dist/chunks/saved-work-L4KNWLZB.js +2 -0
  184. package/dist/chunks/setup-EU6CMRXQ.js +2 -0
  185. package/dist/chunks/{src-C3ZUESMK.js → src-3DJR7OAH.js} +1 -1
  186. package/dist/chunks/{src-MT4B43TD.js → src-HYOTHMRX.js} +111 -113
  187. package/dist/chunks/{standalone-experiment-turn-owner-TW5MTWIO.js → standalone-experiment-turn-owner-UYPA6XHW.js} +1 -1
  188. package/dist/chunks/{store-chat-resources-IRHBW2EC.js → store-chat-resources-HISLEZZM.js} +1 -1
  189. package/dist/chunks/{store-continual-support-reviews-3KK42L4I.js → store-continual-support-reviews-ORWHS57V.js} +1 -1
  190. package/dist/chunks/{store-conversation-serving-IVURK52V.js → store-conversation-serving-5UGYKEGJ.js} +1 -1
  191. package/dist/chunks/{store-create-improve-UTCLBXF2.js → store-create-improve-APLPTVYQ.js} +1 -1
  192. package/dist/chunks/{store-datasets-4AQOVAQY.js → store-datasets-HDW6IYBL.js} +1 -1
  193. package/dist/chunks/{store-evaluation-results-PK2P3IMH.js → store-evaluation-results-KB2UDCF3.js} +1 -1
  194. package/dist/chunks/{store-harness-workspaces-YEXB4IRV.js → store-harness-workspaces-TKX5PZWP.js} +1 -1
  195. package/dist/chunks/{store-human-review-O4BVHP25.js → store-human-review-IURNTX3C.js} +1 -1
  196. package/dist/chunks/{store-learned-preference-migration-validation-44SVX6YB.js → store-learned-preference-migration-validation-TH2LKQWV.js} +1 -1
  197. package/dist/chunks/{store-learning-SIUQIY5C.js → store-learning-WLUW2PWE.js} +1 -1
  198. package/dist/chunks/{store-learning-credentials-BUHR7SN6.js → store-learning-credentials-FDKCEDHK.js} +1 -1
  199. package/dist/chunks/{store-local-experiments-BHVTKPPE.js → store-local-experiments-M4V5RLHJ.js} +1 -1
  200. package/dist/chunks/{store-model-batch-review-RVAYUVK2.js → store-model-batch-review-DDZLWVTG.js} +1 -1
  201. package/dist/chunks/{store-model-configuration-6L3OYXF4.js → store-model-configuration-ATOFA5OH.js} +1 -1
  202. package/dist/chunks/{store-model-project-preparation-AAEKCF6V.js → store-model-project-preparation-ZRSCQEQR.js} +1 -1
  203. package/dist/chunks/{store-modification-recordings-LCPK6K2T.js → store-modification-recordings-YJIDUPVJ.js} +1 -1
  204. package/dist/chunks/{store-preference-comparison-5YVIQNVB.js → store-preference-comparison-JKURBESE.js} +1 -1
  205. package/dist/chunks/{store-task-inbox-L6IQTY26.js → store-task-inbox-L53OT6ZC.js} +1 -1
  206. package/dist/chunks/{store-task-inventory-QWS2C656.js → store-task-inventory-R2JJGAHW.js} +1 -1
  207. package/dist/chunks/{store-taskset-drafts-FRFL6ITK.js → store-taskset-drafts-FPNJPFPO.js} +1 -1
  208. package/dist/chunks/{store-training-FYXZU2FE.js → store-training-DIBW7OMP.js} +1 -1
  209. package/dist/chunks/{store-training-jobs-3N3VKPIY.js → store-training-jobs-K7I4SXWW.js} +1 -1
  210. package/dist/chunks/{store-training-models-VOFVGPZR.js → store-training-models-LCSB37YY.js} +1 -1
  211. package/dist/chunks/{taskset-UDDLFYKV.js → taskset-XI5SJBJL.js} +1 -1
  212. package/dist/chunks/{taskset-packages-WMG5DUBN.js → taskset-packages-FUQWNTSB.js} +1 -1
  213. package/dist/chunks/{taskset-packages-T6B6HYKZ.js → taskset-packages-GM6IUOTY.js} +1 -1
  214. package/dist/chunks/{teams-bot-YCUTDDDC.js → teams-bot-CYC5TR64.js} +1 -1
  215. package/dist/chunks/{tool-learning-ZQ6NSJ5K.js → tool-learning-52QZIJIR.js} +1 -1
  216. package/dist/chunks/{training-5UMT45UL.js → training-GDLLLXSV.js} +1 -1
  217. package/dist/chunks/training-RL7UUBER.js +2 -0
  218. package/dist/chunks/training-UJ62NOJJ.js +2 -0
  219. package/dist/chunks/training-hardware-MR4FUC4U.js +3 -0
  220. package/dist/chunks/training-hosted-V5CHG3M3.js +2 -0
  221. package/dist/chunks/{training-hosted-alphaedit-HSMRDJTD.js → training-hosted-alphaedit-R5PVATV4.js} +1 -1
  222. package/dist/chunks/{training-hosted-decision-7JALOU6O.js → training-hosted-decision-WNK5DE3M.js} +1 -1
  223. package/dist/chunks/{training-hosted-engram-SXO75MFG.js → training-hosted-engram-ZQDOKXAV.js} +1 -1
  224. package/dist/chunks/{training-hosted-learning-E2N32YU5.js → training-hosted-learning-UEBGSSNC.js} +1 -1
  225. package/dist/chunks/{training-hosted-modification-comparison-TXFDJFTG.js → training-hosted-modification-comparison-KKI5CKOH.js} +1 -1
  226. package/dist/chunks/{training-hosted-neuron-training-J42WK4EH.js → training-hosted-neuron-training-CFWEDRSR.js} +1 -1
  227. package/dist/chunks/{training-hosted-serving-report-BAEABGJH.js → training-hosted-serving-report-N4NF5AVW.js} +1 -1
  228. package/dist/chunks/{training-hosted-steering-T556BUBG.js → training-hosted-steering-4MDUQ2YV.js} +1 -1
  229. package/dist/chunks/{training-model-start-P3PXDWNT.js → training-model-start-NOA6TYQK.js} +1 -1
  230. package/dist/chunks/{web-search-ZEKJHZW4.js → web-search-FTVNZ7PH.js} +1 -1
  231. package/dist/cli.js +2 -2
  232. package/dist/index.js +1 -1
  233. package/dist/skills/manifest.json +3 -3
  234. package/dist/skills/openpond-cli/references/experiments-and-training.md +19 -0
  235. package/dist/web/assets/App-L7RV4D0A.js +54 -0
  236. package/dist/web/assets/{AppDialog-CxjDHVk9.js → AppDialog-B2V84J7f.js} +1 -1
  237. package/dist/web/assets/{AppTerminalPanel-CKJIVpKa.js → AppTerminalPanel-DfYpUDKT.js} +2 -2
  238. package/dist/web/assets/{AppToastContext-EpiT1dHs.js → AppToastContext-DuiPouLz.js} +1 -1
  239. package/dist/web/assets/{AppsView-BsMyPX_3.js → AppsView-B20RHDCy.js} +1 -1
  240. package/dist/web/assets/{AttachmentTypeIcon-BXvZy5gB.js → AttachmentTypeIcon-l-GRNxaz.js} +1 -1
  241. package/dist/web/assets/{BrowserSidebar-BIIV4aq4.js → BrowserSidebar-Ce0ToS2O.js} +1 -1
  242. package/dist/web/assets/{CartesianChart-brqLBqnF.js → CartesianChart-CtfMRAfp.js} +1 -1
  243. package/dist/web/assets/{ChatTimelineEntry-CwZbn16X.js → ChatTimelineEntry-DzcucW20.js} +1 -1
  244. package/dist/web/assets/{CollaborationTabs-BU4uc4tZ.js → CollaborationTabs-BpmKjNAC.js} +1 -1
  245. package/dist/web/assets/{CommandMenu-DkWpXR55.js → CommandMenu-JXsoxijv.js} +1 -1
  246. package/dist/web/assets/{CommunityView-CsSxJZGn.js → CommunityView-ggdn8pcH.js} +1 -1
  247. package/dist/web/assets/{ComposerAttachments-BdJGCYzI.js → ComposerAttachments-BMmALUs_.js} +1 -1
  248. package/dist/web/assets/{ComposerCreateImproveStrip-CWy0j1vv.js → ComposerCreateImproveStrip-DcM1bkfu.js} +1 -1
  249. package/dist/web/assets/{ConversationImportsSettings-DCmiakbZ.js → ConversationImportsSettings-BKNeARHI.js} +1 -1
  250. package/dist/web/assets/{DatasetReviewImport-DEnF_pGu.js → DatasetReviewImport-DyFOE0Q0.js} +1 -1
  251. package/dist/web/assets/{ExperimentTrainingDataWorkspace-WhwQ0QBi.js → ExperimentTrainingDataWorkspace-CfOyoMrq.js} +2 -2
  252. package/dist/web/assets/{FilePagePreview-BRhhz99q.js → FilePagePreview-B7bWObJN.js} +2 -2
  253. package/dist/web/assets/{GetStartedView-CLVD-qEi.js → GetStartedView-BYbFl93M.js} +1 -1
  254. package/dist/web/assets/{GettingStartedDialog-CMxaAMg-.js → GettingStartedDialog-UgreDozV.js} +1 -1
  255. package/dist/web/assets/{HostedModelLearningReview-Cn-j-rDo.js → HostedModelLearningReview-C_kng2U_.js} +1 -1
  256. package/dist/web/assets/HostedModelLearningSettings-aesD_ifF.js +1 -0
  257. package/dist/web/assets/{HtmlVisual-D5y2WG9L.js → HtmlVisual-nvl1x-jh.js} +1 -1
  258. package/dist/web/assets/{LabModelVersionDetailPage-BxRmYD6h.js → LabModelVersionDetailPage-DrdoNvI-.js} +1 -1
  259. package/dist/web/assets/{LabModelWorkspace-u2Ulm_z4.js → LabModelWorkspace-CHlhzG3q.js} +1 -1
  260. package/dist/web/assets/{LabSkillSidebar-C7IceJTJ.js → LabSkillSidebar-CqHeZzoj.js} +1 -1
  261. package/dist/web/assets/{LabsRoute-CbztQaEf.js → LabsRoute-DzEbPpMK.js} +4 -4
  262. package/dist/web/assets/{LearningBatchesPage-CJqgZNvM.js → LearningBatchesPage-A2dFQW2j.js} +1 -1
  263. package/dist/web/assets/{MainChatThread-DNMfrrRq.js → MainChatThread-BSvKu4e5.js} +2 -2
  264. package/dist/web/assets/{MainPane-CQQxSDPS.js → MainPane-DiWIAxMj.js} +6 -6
  265. package/dist/web/assets/{ModelProjectPageHeader-Dge19aE1.js → ModelProjectPageHeader-lu6iRXHK.js} +1 -1
  266. package/dist/web/assets/{NativeSetupTerminal-D4JnbpyD.js → NativeSetupTerminal-kZ-nFPE8.js} +2 -2
  267. package/dist/web/assets/{NativeSkillSidebar-Jzx1BeKV.js → NativeSkillSidebar-DkkD1uH2.js} +1 -1
  268. package/dist/web/assets/{NewProjectDialog-DcnGzEd9.js → NewProjectDialog-Dg8dMEpc.js} +1 -1
  269. package/dist/web/assets/{OutputsPage-Cmk15Vt_.js → OutputsPage-Dz190U9t.js} +1 -1
  270. package/dist/web/assets/{PageChrome-Cz_fCqtn.js → PageChrome-Bncv-ps0.js} +1 -1
  271. package/dist/web/assets/{ProjectsPage-BZ3Eo3Mz.js → ProjectsPage-DVkYvLtd.js} +1 -1
  272. package/dist/web/assets/{RightChatPanelStack-C6H2vU9N.js → RightChatPanelStack-CP4leenI.js} +1 -1
  273. package/dist/web/assets/RightSidebarHomePanel-C0etQXpt.js +1 -0
  274. package/dist/web/assets/{ScheduledWorkPage-CAkSwM0T.js → ScheduledWorkPage-DI0mgt82.js} +1 -1
  275. package/dist/web/assets/{SettingsView-DvQXGw3_.js → SettingsView-cCtkr089.js} +3 -3
  276. package/dist/web/assets/{TasksetDraftEditorPrimitives-JuU1k8vr.js → TasksetDraftEditorPrimitives-DCQTuswJ.js} +1 -1
  277. package/dist/web/assets/{TeamChatView-DmHjr8W9.js → TeamChatView-BBEomfQ7.js} +1 -1
  278. package/dist/web/assets/{TerminalOverlay-DlaM9d8F.js → TerminalOverlay-Dj5NUDMp.js} +1 -1
  279. package/dist/web/assets/{TrainingCreationPanel-ClpylNsr.js → TrainingCreationPanel-Ds4PLfsd.js} +1 -1
  280. package/dist/web/assets/{TrainingDraftPanel-6tH2xSDj.js → TrainingDraftPanel-BAuh_BF3.js} +1 -1
  281. package/dist/web/assets/{UsageSettingsSection-CzDqxOYM.js → UsageSettingsSection-DbzeatcW.js} +1 -1
  282. package/dist/web/assets/WorkSidebarPanel-BaNuXoZc.js +1 -0
  283. package/dist/web/assets/{WorkspaceDiffPanel-B4e0lyF7.js → WorkspaceDiffPanel-xk-ve1MO.js} +3 -3
  284. package/dist/web/assets/{WorkspaceEnvironmentMenu-D01ZkZZF.js → WorkspaceEnvironmentMenu-D8GSuoYz.js} +1 -1
  285. package/dist/web/assets/{WorkspaceFileLocation-C5s_njZb.js → WorkspaceFileLocation-Dl8M2ZKN.js} +1 -1
  286. package/dist/web/assets/{WorkspaceGitDialogs-DjPZ6KIh.js → WorkspaceGitDialogs-9BhLjYx4.js} +1 -1
  287. package/dist/web/assets/{WorkspaceMonacoEditor-CC4sfOiU.js → WorkspaceMonacoEditor-DYPuC7pj.js} +3 -3
  288. package/dist/web/assets/{WorkspacePdfPreview-vszQqFa4.js → WorkspacePdfPreview-B7BI9tLR.js} +2 -2
  289. package/dist/web/assets/{WorkspacePresentationPreview-DQTvhaRD.js → WorkspacePresentationPreview-sP7JUT7m.js} +1 -1
  290. package/dist/web/assets/{bot-Doyx3T4j.js → bot-D7M8ZtE6.js} +1 -1
  291. package/dist/web/assets/{chat-resources-Beh5lB36.js → chat-resources-DhKAnljP.js} +1 -1
  292. package/dist/web/assets/chevron-down-BAEcJitl.js +1 -0
  293. package/dist/web/assets/chevron-right-3G9s2cQ9.js +1 -0
  294. package/dist/web/assets/chevron-up-DTYF52H1.js +1 -0
  295. package/dist/web/assets/{chunk-C3TS766N-ppRhs95p.js → chunk-C3TS766N-DENE60SE.js} +1 -1
  296. package/dist/web/assets/{client-choice-storage-DitqKiIT.js → client-choice-storage-DYZsrVr9.js} +1 -1
  297. package/dist/web/assets/{client-DwZ92xtu.js → client-gy7zrd7a.js} +1 -1
  298. package/dist/web/assets/{cloud-upload-HdzNTgr2.js → cloud-upload-De-XSMUr.js} +1 -1
  299. package/dist/web/assets/{copy-DTQhoBNg.js → copy-DEK20zbZ.js} +1 -1
  300. package/dist/web/assets/{cssMode-BRTtfXxU.js → cssMode-Dau-Fhqf.js} +1 -1
  301. package/dist/web/assets/{external-link-H1629UU6.js → external-link-DwDry0Fb.js} +1 -1
  302. package/dist/web/assets/{folder-open-CAGdWOrr.js → folder-open-DOb4AjV6.js} +1 -1
  303. package/dist/web/assets/{folder-plus-C14cs2mE.js → folder-plus-BAouDaXv.js} +1 -1
  304. package/dist/web/assets/{git-commit-horizontal-DFUfuVvF.js → git-commit-horizontal-DZbHXcai.js} +1 -1
  305. package/dist/web/assets/{htmlMode-BVaCcL76.js → htmlMode-DlNEe6hu.js} +1 -1
  306. package/dist/web/assets/{icons-Bk2b68aC.js → icons-OQhKVrDc.js} +1 -1
  307. package/dist/web/assets/{image-0DPVY6Ev.js → image-BkYJDChH.js} +1 -1
  308. package/dist/web/assets/{index-B6XX_0h3.js → index-M_h2Ok4V.js} +2 -2
  309. package/dist/web/assets/{info-C8b_tafZ.js → info-Mj5lp4Ic.js} +1 -1
  310. package/dist/web/assets/{jsonMode-BCKKQmmV.js → jsonMode-CyOEyonV.js} +1 -1
  311. package/dist/web/assets/loader-circle-DXVtGvuV.js +1 -0
  312. package/dist/web/assets/{lspLanguageFeatures-DozmNUOx.js → lspLanguageFeatures-DAYPzatg.js} +1 -1
  313. package/dist/web/assets/{maximize-2-CByk9-zN.js → maximize-2-BwFXSX6b.js} +1 -1
  314. package/dist/web/assets/{message-square-C889vRqm.js → message-square-C2nqfNLn.js} +1 -1
  315. package/dist/web/assets/{monaco.contribution-BITdsRbn.js → monaco.contribution-BZcNCJER.js} +2 -2
  316. package/dist/web/assets/{monaco.contribution-DxAV1oS5.js → monaco.contribution-BZkfRhss.js} +2 -2
  317. package/dist/web/assets/{monaco.contribution-BqA-XZ44.js → monaco.contribution-D7_X8TXe.js} +2 -2
  318. package/dist/web/assets/{monaco.contribution-B9q6qbbo.js → monaco.contribution-KyLdVay7.js} +2 -2
  319. package/dist/web/assets/{monitor-BtxlcLuI.js → monitor-B0Qj5Wea.js} +1 -1
  320. package/dist/web/assets/{paperclip-BeIdaspf.js → paperclip-CmrRruxi.js} +1 -1
  321. package/dist/web/assets/{pdf-perlzwEB.js → pdf-BM-9_48p.js} +1 -1
  322. package/dist/web/assets/play-CkACZ6Zo.js +1 -0
  323. package/dist/web/assets/plus-CB258e62.js +1 -0
  324. package/dist/web/assets/{presentation-0bzvu6_u.js → presentation-BYxhoSIo.js} +1 -1
  325. package/dist/web/assets/{python-B9hOnkOI.js → python-B3Mj03I5.js} +1 -1
  326. package/dist/web/assets/{refresh-cw-D61-Ozk3.js → refresh-cw-CwEmO71D.js} +1 -1
  327. package/dist/web/assets/{save-iEMNZoPe.js → save-S--FOuce.js} +1 -1
  328. package/dist/web/assets/{settings-lists-C84qxFmP.js → settings-lists-ChqDppMP.js} +1 -1
  329. package/dist/web/assets/square-BmPfHjGU.js +1 -0
  330. package/dist/web/assets/{square-terminal-Djpzo2Qs.js → square-terminal-CawpQtCi.js} +1 -1
  331. package/dist/web/assets/{submit-issue-command-HfKzyxg5.js → submit-issue-command-CFitxxmO.js} +1 -1
  332. package/dist/web/assets/{toggleHighContrast-ClsXu39R.js → toggleHighContrast-D-cMCvXx.js} +1 -1
  333. package/dist/web/assets/training-CzbWtx75.js +1 -0
  334. package/dist/web/assets/{training-model-data-CIysl8wH.js → training-model-data-G-D64935.js} +1 -1
  335. package/dist/web/assets/{tsMode-nbmaMc-D.js → tsMode-9kzS1ijG.js} +1 -1
  336. package/dist/web/assets/{upload-C6ug8RD-.js → upload-CtYsSYrM.js} +1 -1
  337. package/dist/web/assets/{useAccountSettings-Dr9h4Qz_.js → useAccountSettings-DYYa6puz.js} +1 -1
  338. package/dist/web/assets/{useAgentInventory-ByCk2JAv.js → useAgentInventory-c5B_Tszj.js} +1 -1
  339. package/dist/web/assets/{useChatContextSelection-C0eMm2g6.js → useChatContextSelection-DOISZpTz.js} +1 -1
  340. package/dist/web/assets/{useLocalAgentSchedules-Do0y_leJ.js → useLocalAgentSchedules-QJ8RsMKm.js} +1 -1
  341. package/dist/web/assets/{useQuery-D2MQ7e5U.js → useQuery-DuTGOe2b.js} +1 -1
  342. package/dist/web/assets/{wifi-off-Dr-CapyW.js → wifi-off-BOfP4Vmg.js} +1 -1
  343. package/dist/web/assets/{workers-DKvM2NdM.js → workers-BwGpyrdj.js} +1 -1
  344. package/dist/web/assets/x-5_iy6IDd.js +1 -0
  345. package/dist/web/assets/{yaml-C02vq4ar.js → yaml-BU4IWV_7.js} +1 -1
  346. package/dist/web/index.html +1 -1
  347. package/docs/command-reference.md +1 -0
  348. package/package.json +1 -1
  349. package/dist/chunks/app-server-runtime-43MCH5SY.js +0 -2
  350. package/dist/chunks/apps-VNFGMQFG.js +0 -2
  351. package/dist/chunks/chunk-6D3FI2XT.js +0 -2
  352. package/dist/chunks/chunk-APKXXAUF.js +0 -2
  353. package/dist/chunks/chunk-JCLTFDVW.js +0 -2
  354. package/dist/chunks/chunk-KTIBXRWQ.js +0 -2
  355. package/dist/chunks/chunk-VEBW7NKD.js +0 -2
  356. package/dist/chunks/chunk-YDZBX4XQ.js +0 -2
  357. package/dist/chunks/cli-R7TAP6Z2.js +0 -2
  358. package/dist/chunks/connected-app-executor-LAEAQUJS.js +0 -2
  359. package/dist/chunks/connected-evidence-VKY6O2JW.js +0 -2
  360. package/dist/chunks/core-commands-5TNBVR72.js +0 -2
  361. package/dist/chunks/datasets-BIDZJYDC.js +0 -2
  362. package/dist/chunks/desktop-test-BY2MS3UL.js +0 -3
  363. package/dist/chunks/evaluation-coordination-FXB4DXZA.js +0 -2
  364. package/dist/chunks/experiment-improvements-JPDLKZXD.js +0 -2
  365. package/dist/chunks/experiments-IEN7RXLX.js +0 -2
  366. package/dist/chunks/experiments-signal-L32D36NH.js +0 -2
  367. package/dist/chunks/host-profile-evaluation-tools-UF4ATIUF.js +0 -2
  368. package/dist/chunks/hosted-harness-runtime-MMTLCL23.js +0 -2
  369. package/dist/chunks/human-review-6V6EMNVN.js +0 -2
  370. package/dist/chunks/learning-LAXMGWSQ.js +0 -2
  371. package/dist/chunks/local-harness-improvement-runtime-3YJQRYXC.js +0 -2
  372. package/dist/chunks/local-harness-taskset-review-XQHQ6JCR.js +0 -2
  373. package/dist/chunks/opchat-SV67HVMX.js +0 -3
  374. package/dist/chunks/opchat-bounded-chat-KLMIYSZZ.js +0 -2
  375. package/dist/chunks/organizations-OZZFX7RG.js +0 -2
  376. package/dist/chunks/project-action-payload-TK6G4VMC.js +0 -2
  377. package/dist/chunks/project-agent-FFXPNXCO.js +0 -2
  378. package/dist/chunks/sandbox-command-4BCUDAED.js +0 -2
  379. package/dist/chunks/saved-work-M6PUHKCC.js +0 -2
  380. package/dist/chunks/setup-RMZ2BHLM.js +0 -2
  381. package/dist/chunks/training-5NT2YB2L.js +0 -2
  382. package/dist/chunks/training-UY6KRG4M.js +0 -2
  383. package/dist/chunks/training-hardware-UWQCRDMV.js +0 -3
  384. package/dist/chunks/training-hosted-CKSDRVL6.js +0 -2
  385. package/dist/web/assets/App-CCuh99JW.js +0 -54
  386. package/dist/web/assets/HostedModelLearningSettings-VNBvf38S.js +0 -1
  387. package/dist/web/assets/RightSidebarHomePanel-BfMMVkM1.js +0 -1
  388. package/dist/web/assets/WorkSidebarPanel-CY-AHZ4-.js +0 -1
  389. package/dist/web/assets/chevron-down-DX1hzujj.js +0 -1
  390. package/dist/web/assets/chevron-right-DHN0y3KC.js +0 -1
  391. package/dist/web/assets/chevron-up-_QrW88NF.js +0 -1
  392. package/dist/web/assets/loader-circle-y-SSPwpk.js +0 -1
  393. package/dist/web/assets/play-CHXXdkuO.js +0 -1
  394. package/dist/web/assets/plus-DFFWjhPw.js +0 -1
  395. package/dist/web/assets/square-BE_4JMR3.js +0 -1
  396. package/dist/web/assets/training-DWfghwfZ.js +0 -1
  397. package/dist/web/assets/x-Jx2jlP9u.js +0 -1
@@ -1,13 +1,13 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MainChatThread-DNMfrrRq.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/index-B6XX_0h3.js","assets/index-g7UqJhnX.css","assets/useQuery-D2MQ7e5U.js","assets/schemas-Brv9Vmnk.js","assets/common-BWVSBnpX.js","assets/chunk-AG6UJ3DI-D9KZjTYP.js","assets/chunk-GCUWJUUM-Dy6oUNJ6.js","assets/chunk-H3JZ3P5T-DolwEJXo.js","assets/reward-checks-DJJZYgf8.js","assets/chunk-Q4RGCEOI-Cr-dg4Nk.js","assets/chunk-3BYFS4RO-ztZjcMmt.js","assets/api-client-DJRVOFzS.js","assets/ChatTimelineEntry-CwZbn16X.js","assets/create-pipeline-DsZzNkt9.js","assets/icons-Bk2b68aC.js","assets/training-model-data-CIysl8wH.js","assets/copy-DTQhoBNg.js","assets/x-Jx2jlP9u.js","assets/App-CCuh99JW.js","assets/settings-BC-bzgk6.js","assets/client-choice-storage-DitqKiIT.js","assets/requests-DmeUYik4.js","assets/profile-ref-D8lxL7dW.js","assets/work-outputs-D_8TovAK.js","assets/chunk-GS5HEE4M-C0RLeIsy.js","assets/intake-contracts-B8JZKYwb.js","assets/training-DWfghwfZ.js","assets/ponder-desktop-Ca-9KggQ.js","assets/chat-resources-Beh5lB36.js","assets/app-models-BUdzQbXo.js","assets/model-display-zPvC4L2B.js","assets/submit-issue-command-HfKzyxg5.js","assets/connected-app-mentions-D3wRZLwI.js","assets/profile-agent-labels-Duh96b8x.js","assets/browser-sidebar-links-PVPCrsDJ.js","assets/browser-url-LACq2Ngu.js","assets/query-scope-BRpcgljO.js","assets/bot-Doyx3T4j.js","assets/chevron-down-DX1hzujj.js","assets/chevron-right-DHN0y3KC.js","assets/external-link-H1629UU6.js","assets/loader-circle-y-SSPwpk.js","assets/maximize-2-CByk9-zN.js","assets/message-square-C889vRqm.js","assets/plus-DFFWjhPw.js","assets/refresh-cw-D61-Ozk3.js","assets/square-terminal-Djpzo2Qs.js","assets/AppToastContext-EpiT1dHs.js","assets/NativeSetupTerminal-D4JnbpyD.js","assets/AppDialog-CxjDHVk9.js","assets/PageChrome-Cz_fCqtn.js","assets/NativeSetupTerminal-3eR9D_R3.css","assets/organization-types-PP-yuR2J.js","assets/ui-theme.generated-D-mc26qt.js","assets/App-DpFKLxuA.css","assets/CartesianChart-brqLBqnF.js","assets/chevron-up-_QrW88NF.js","assets/folder-open-CAGdWOrr.js","assets/image-0DPVY6Ev.js","assets/play-CHXXdkuO.js","assets/HtmlVisual-D5y2WG9L.js","assets/HtmlVisual-C7GlEVfH.css","assets/TasksetDraftEditorPrimitives-JuU1k8vr.js","assets/AttachmentTypeIcon-BXvZy5gB.js","assets/presentation-0bzvu6_u.js","assets/ChatTimelineEntry-vs8RaEGD.css","assets/ComposerCreateImproveStrip-CWy0j1vv.js","assets/WorkspacePresentationPreview-DQTvhaRD.js","assets/WorkspaceFileLocation-C5s_njZb.js","assets/aiden0z-pptx-renderer.es-Bo43EjzT.js","assets/jszip.min-BWcKrrYP.js","assets/FilePagePreview-BRhhz99q.js","assets/pdf.worker.min-BrEVksTu.js","assets/docx-preview-Blk_WGfs.js","assets/ExperimentTrainingDataWorkspace-WhwQ0QBi.js","assets/LearningBatchesPage-CJqgZNvM.js","assets/chunk-C3TS766N-ppRhs95p.js","assets/ModelProjectPageHeader-Dge19aE1.js","assets/LearningBatchesPage-B1NZTBSv.css","assets/WorkspaceDiffPanel-B4e0lyF7.js","assets/info-C8b_tafZ.js","assets/save-iEMNZoPe.js","assets/AppTerminalPanel-CKJIVpKa.js","assets/CollaborationTabs-BU4uc4tZ.js","assets/CollaborationTabs-CU-9Shwu.css","assets/AppsView-BsMyPX_3.js","assets/settings-lists-C84qxFmP.js","assets/settings-lists-CBaz4cGG.css","assets/client-DwZ92xtu.js","assets/useAgentInventory-ByCk2JAv.js","assets/AppsView-D3vVesNd.css","assets/settings-forms-DLe1dTYN.css","assets/GetStartedView-CLVD-qEi.js","assets/GetStartedView-idp5pnnE.css","assets/LabsRoute-CbztQaEf.js","assets/useChatContextSelection-C0eMm2g6.js","assets/LabModelWorkspace-u2Ulm_z4.js","assets/LabModelWorkspace-DOrgCk9Z.css","assets/cloud-upload-HdzNTgr2.js","assets/dataset-workspaces-BTPi71mz.js","assets/LabsRoute-C9Y0GU34.css","assets/ScheduledWorkPage-CAkSwM0T.js","assets/ComposerAttachments-BdJGCYzI.js","assets/useLocalAgentSchedules-Do0y_leJ.js","assets/OutputsPage-Cmk15Vt_.js","assets/ProjectsPage-BZ3Eo3Mz.js","assets/ProjectsPage-BPoAzc-Z.css","assets/LabSkillSidebar-C7IceJTJ.js","assets/LabSkillSidebar-Uy4vA6fy.css","assets/BrowserSidebar-BIIV4aq4.js","assets/RightChatPanelStack-C6H2vU9N.js","assets/NativeSkillSidebar-Jzx1BeKV.js","assets/NativeSkillSidebar-D4DVkqqR.css","assets/TeamChatView-DmHjr8W9.js","assets/TeamChatView-BMZ8S7Sj.css","assets/CommunityView-CsSxJZGn.js","assets/wifi-off-Dr-CapyW.js","assets/paperclip-BeIdaspf.js","assets/CommunityView-C5uLqiF2.css","assets/TrainingDraftPanel-6tH2xSDj.js","assets/TrainingCreationPanel-ClpylNsr.js"])))=>i.map(i=>d[i]);
2
- import{i as e}from"./rolldown-runtime-Dd_uD5pT.js";import{g as t,h as n,l as r,m as i,s as a,t as o}from"./index-B6XX_0h3.js";import{A as s,E as c,O as l,P as u,S as d,a as f,b as p,c as m,d as h,i as g,j as _,l as v,o as y,r as b,s as x,t as S,u as C,v as w}from"./useQuery-D2MQ7e5U.js";import{a as T,i as E,n as D,o as O,r as k,s as A,t as j}from"./useChatContextSelection-C0eMm2g6.js";import{C as M,E as N,S as P,a as F,c as I,d as L,f as ee,g as R,m as z,o as B,p as V,r as H,v as U,w as te,x as ne}from"./schemas-Brv9Vmnk.js";import{a as re,c as W,d as ie,i as G,n as ae,o as K,s as q}from"./common-BWVSBnpX.js";import{A as oe,O as se,k as ce,y as le}from"./settings-BC-bzgk6.js";import{n as ue,o as de}from"./client-choice-storage-DitqKiIT.js";import{t as fe}from"./model-display-zPvC4L2B.js";import{a as pe,i as me,n as he,t as ge}from"./requests-DmeUYik4.js";import{t as _e}from"./profile-ref-D8lxL7dW.js";import{F as ve,H as ye,L as be,M as xe,N as Se,Ot as Ce,Q as we,R as Te,S as Ee,U as De,_ as Oe,at as ke,b as Ae,d as je,ft as Me,i as Ne,it as Pe,j as Fe,m as Ie,pt as Le,q as Re,rt as ze,u as Be,w as Ve,z as He}from"./chunk-H3JZ3P5T-DolwEJXo.js";import{a as Ue,i as We,n as Ge,o as Ke,r as qe,t as Je}from"./ComposerAttachments-BdJGCYzI.js";import{n as Ye}from"./work-outputs-D_8TovAK.js";import{_ as Xe,a as Ze,c as Qe,h as $e,i as et,l as tt,o as nt,p as rt,r as it,t as at,u as ot,y as st}from"./chunk-GS5HEE4M-C0RLeIsy.js";import{u as ct}from"./reward-checks-DJJZYgf8.js";import{a as lt,i as ut,l as dt,r as ft,t as pt}from"./chunk-C3TS766N-ppRhs95p.js";import{$ as mt,$t as ht,A as gt,B as _t,Bn as vt,Bt as yt,Cn as bt,D as xt,Dn as St,Dt as Ct,E as wt,En as Tt,Et,F as Dt,Ft as Ot,G as kt,Gt as At,Ht as jt,I as Mt,It as Nt,J as Pt,Jt as Ft,K as It,Kt as Lt,L as Rt,Ln as zt,Lt as Bt,M as Vt,Mt as Ht,Nt as Ut,On as Wt,Ot as Gt,P as Kt,Pt as qt,Qt as Jt,Rn as Yt,Rt as Xt,S as Zt,Sn as Qt,St as $t,T as en,Tn as tn,Tt as nn,U as rn,Ut as an,Vn as on,Vt as sn,W as cn,Wt as ln,X as un,Xt as dn,Y as fn,Yt as pn,Zt as mn,_ as hn,_n as gn,_t as _n,a as vn,an as yn,at as bn,b as xn,bn as Sn,bt as Cn,c as wn,cn as Tn,d as En,dn as Dn,dt as On,en as kn,et as An,f as jn,fn as Mn,g as Nn,gt as Pn,ht as Fn,i as In,in as Ln,it as Rn,j as zn,jt as Bn,k as Vn,kt as Hn,l as Un,ln as Wn,lt as Gn,m as Kn,mn as qn,mt as Jn,n as Yn,nn as Xn,nt as Zn,o as Qn,on as $n,ot as er,pn as tr,q as nr,qt as rr,r as ir,rn as ar,rt as or,s as sr,sn as cr,st as lr,t as ur,tn as dr,u as fr,un as pr,ut as mr,vn as hr,vt as gr,w as _r,wn as vr,wt as yr,x as br,xn as xr,xt as Sr,y as Cr,yn as wr,yt as Tr,z as Er,zn as Dr,zt as Or}from"./training-DWfghwfZ.js";import{A as kr,E as Ar,G as jr,H as Mr,J as Nr,K as Pr,L as Fr,M as Ir,W as Lr,Z as Rr,it as zr,j as Br,nt as J,ot as Vr,x as Hr,z as Ur}from"./chunk-GCUWJUUM-Dy6oUNJ6.js";import{r as Wr}from"./ponder-desktop-Ca-9KggQ.js";import{i as Gr,n as Kr,o as qr,s as Jr,t as Yr}from"./chat-resources-Beh5lB36.js";import{C as Xr,D as Zr,E as Qr,O as $r,S as ei,T as ti,_ as ni,b as ri,d as ii,l as ai,m as oi,r as si,v as ci,w as li,x as ui}from"./LabModelWorkspace-u2Ulm_z4.js";import{C as di,D as fi,O as pi,S as mi,c as hi,d as gi,f as _i,k as vi,l as yi,o as bi,t as xi,u as Si,v as Ci,y as wi}from"./app-models-BUdzQbXo.js";import{n as Y,t as Ti}from"./api-client-DJRVOFzS.js";import{A as Ei,D as Di,I as Oi,L as ki,N as Ai,O as ji,S as Mi,_ as Ni,a as Pi,c as Fi,d as Ii,f as Li,g as Ri,i as zi,l as Bi,m as Vi,n as Hi,o as Ui,p as Wi,r as Gi,s as Ki,t as qi,w as Ji,x as Yi}from"./submit-issue-command-HfKzyxg5.js";import{a as Xi,l as Zi,n as Qi,o as $i,t as ea}from"./browser-sidebar-links-PVPCrsDJ.js";import{n as ta,r as na,t as ra}from"./query-scope-BRpcgljO.js";import{t as ia}from"./icons-Bk2b68aC.js";import{A as aa,B as oa,C as sa,E as ca,F as la,I as ua,L as da,M as fa,N as pa,O as ma,P as ha,S as ga,V as _a,b as va,j as ya,k as ba,m as xa,n as Sa,o as Ca,x as wa,z as Ta}from"./training-model-data-CIysl8wH.js";import{Ut as Ea}from"./CartesianChart-brqLBqnF.js";import{t as Da}from"./bot-Doyx3T4j.js";import{t as Oa}from"./chevron-down-DX1hzujj.js";import{t as ka}from"./chevron-right-DHN0y3KC.js";import{t as Aa}from"./cloud-upload-HdzNTgr2.js";import{t as ja}from"./copy-DTQhoBNg.js";import{t as Ma}from"./external-link-H1629UU6.js";import{t as Na}from"./folder-open-CAGdWOrr.js";import{t as Pa}from"./loader-circle-y-SSPwpk.js";import{t as Fa}from"./maximize-2-CByk9-zN.js";import{t as Ia}from"./message-square-C889vRqm.js";import{t as La}from"./paperclip-BeIdaspf.js";import{t as Ra}from"./play-CHXXdkuO.js";import{t as za}from"./plus-DFFWjhPw.js";import{t as Ba}from"./refresh-cw-D61-Ozk3.js";import{t as Va}from"./square-BE_4JMR3.js";import{t as Ha}from"./square-terminal-Djpzo2Qs.js";import{t as Ua}from"./x-Jx2jlP9u.js";import{a as Wa,n as Ga,r as Ka}from"./AppToastContext-EpiT1dHs.js";import{t as qa}from"./AppDialog-CxjDHVk9.js";import{c as Ja,i as Ya,l as Xa,o as Za,r as Qa,s as $a,t as eo,u as to}from"./connected-app-mentions-D3wRZLwI.js";import{t as no}from"./browser-url-LACq2Ngu.js";import{$ as ro,A as io,Bt as ao,C as oo,Cn as so,En as co,Fn as lo,Ft as uo,Gn as fo,Gt as X,Ht as po,In as mo,It as ho,Jt as go,Kn as _o,Ln as vo,Mt as yo,O as bo,On as xo,Ot as So,P as Co,Pt as wo,Q as To,Tn as Eo,U as Do,Un as Oo,Ut as Z,Wt as ko,_n as Ao,_r as jo,an as Mo,ar as No,bn as Po,bt as Fo,ct as Io,et as Lo,gn as Ro,hn as zo,ir as Bo,it as Vo,jt as Ho,kn as Uo,ln as Wo,lt as Go,nn as Ko,nr as qo,on as Jo,pn as Yo,q as Xo,qn as Zo,rr as Qo,rt as $o,tn as es,un as ts,v as ns,wn as rs,y as is,zt as as}from"./App-CCuh99JW.js";import{t as os}from"./AttachmentTypeIcon-BXvZy5gB.js";var ss=class extends p{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),s(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&d(t.mutationKey)!==d(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??jo();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){w.batch(()=>{if(this.#r&&this.hasListeners()){let t=this.#t.variables,n=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{this.#r.onSuccess?.(e.data,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(e.data,null,t,n,r)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{this.#r.onError?.(e.error,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(void 0,e.error,t,n,r)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}};function cs(e,t){let n=new Set(t);return e.filter(e=>!n.has(e))}var ls=class extends p{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=[];constructor(e,t,n){super(),this.#e=e,this.#r=n,this.#n=[],this.#i=[],this.#t=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#i.forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#i.forEach(e=>{e.destroy()})}setQueries(e,t){this.#n=e,this.#r=t,w.batch(()=>{let e=this.#i,t=this.#p(this.#n);t.forEach(e=>e.observer.setOptions(e.defaultedQueryOptions));let n=t.map(e=>e.observer),r=n.map(e=>e.getCurrentResult()),i=e.length!==n.length,a=n.some((t,n)=>t!==e[n]),o=i||a,c=o?!0:r.some((e,t)=>{let n=this.#t[t];return!n||!s(e,n)});(o||c)&&(o&&(this.#l=t,this.#i=n),this.#t=r,this.hasListeners()&&(o&&(cs(e,n).forEach(e=>{e.destroy()}),cs(n,e).forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})),this.#h()))})}getCurrentResult(){return this.#t}getQueries(){return this.#i.map(e=>e.getCurrentQuery())}getObservers(){return this.#i}getOptimisticResult(e,t){let n=this.#p(e),r=n.map(e=>e.observer.getOptimisticResult(e.defaultedQueryOptions)),i=n.map(e=>e.defaultedQueryOptions.queryHash);return[r,e=>this.#d(e??r,t,i),()=>this.#u(r,n)]}#u(e,t){let n=new Set;return t.map((r,i)=>{let a=e[i];return r.defaultedQueryOptions.notifyOnChangeProps?a:r.observer.trackResult(a,e=>{n.has(e)||(n.add(e),t.forEach(t=>{t.observer.trackProp(e)}))})})}#d(e,t,n){if(t){let r=this.#c,i=n!==void 0&&r!==void 0&&(r.length!==n.length||n.some((e,t)=>e!==r[t]));return(this.#t!==this.#s||i||t!==this.#o)&&(this.#o=t,this.#s=this.#t,n!==void 0&&(this.#c=n),this.#a=l(this.#a,t(e))),this.#a}return e}#f(){return!this.#r?.combine||this.#i.some((e,t)=>e.options.suspense&&this.#t[t]?.data===void 0)}#p(e){let t=new Map;this.#i.forEach(e=>{let n=e.options.queryHash;if(!n)return;let r=t.get(n);r?r.push(e):t.set(n,[e])});let n=[];return e.forEach(e=>{let r=this.#e.defaultQueryOptions(e),i=t.get(r.queryHash)?.shift()??new h(this.#e,r);n.push({defaultedQueryOptions:r,observer:i})}),n}#m(e,t){let n=this.#i.indexOf(e);n!==-1&&(this.#t=this.#t.slice(),this.#t[n]=t,this.#h())}#h(){if(this.hasListeners()){let e=this.#f(),t=this.#a,n=e?t:this.#d(this.#u(this.#t,this.#l),this.#r?.combine);(e||t!==n)&&w.batch(()=>{this.listeners.forEach(e=>{e(this.#t)})})}}},Q=e(t(),1);function us({queries:e,...t},n){let r=u(n),i=C(),a=v(),o=t.subscribed!==!1,s=Q.useMemo(()=>e.map(e=>{let t=r.defaultQueryOptions(e);return t._optimisticResults=i?`isRestoring`:o?`optimistic`:void 0,t}),[e,r,i,o]);s.forEach(e=>{b(e);let t=r.getQueryCache().get(e.queryHash);y(e,a,t)}),m(a);let[l]=Q.useState(()=>new ls(r,s,t)),[d,p,_]=l.getOptimisticResult(s,t.combine),S=!i&&o;Q.useSyncExternalStore(Q.useCallback(e=>S?l.subscribe(w.batchCalls(e)):c,[l,S]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),Q.useEffect(()=>{l.setQueries(s,t)},[s,t,l]);let T=d.some((e,t)=>f(s[t],e))?d.flatMap((e,t)=>{let n=s[t];if(n&&f(n,e)){let e=new h(r,n);return g(n,e,a)}return[]}):[];if(T.length>0)throw Promise.all(T);let E=d.find((e,t)=>{let n=s[t];return n&&x({result:e,errorResetBoundary:a,throwOnError:n.throwOnError,query:r.getQueryCache().get(n.queryHash),suspense:n.suspense})});if(E)throw E.error;return p(_())}function ds(e,t){let n=u(t),[r]=Q.useState(()=>new ss(n,e));Q.useEffect(()=>{r.setOptions(e)},[r,e]);let i=Q.useSyncExternalStore(Q.useCallback(e=>r.subscribe(w.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=Q.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(c)},[r]);if(i.error&&_(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}var fs=H([`visual.published`,`file.preview_requested`,`task.inbox`,`task.input`,`task.wait`,`session.started`,`session.updated`,`session.title.updated`,`turn.started`,`assistant.delta`,`assistant.reasoning.delta`,`tool.started`,`tool.completed`,`skill.selected`,`skill.loaded`,`skill.load_failed`,`user_question.asked`,`user_question.answered`,`user_question.dismissed`,`approval.requested`,`approval.resolved`,`command.output`,`workspace_action`,`workspace_action_result`,`workspace.diff`,`create_improve.updated`,`session.context.updated`,`session.compaction.started`,`session.compaction.completed`,`session.compaction.failed`,`goal.continuation.started`,`goal.continuation.skipped`,`goal.continuation.failed`,`harness.refiner.queued`,`harness.refiner.started`,`harness.refiner.completed`,`harness.refiner.failed`,`turn.completed`,`turn.failed`,`turn.interrupted`,`session.closed`,...le,`diagnostic`]);z({id:U(),sequence:V().int().positive().optional(),sessionId:U().optional(),turnId:U().optional(),name:fs,timestamp:U(),source:H([`ui_button`,`chat_action`,`terminal_command`,`hook`,`provider`,`server`]).optional(),action:U().optional(),appId:U().nullable().optional(),args:R(U(),P()).optional(),status:H([`started`,`completed`,`failed`,`pending`]).optional(),output:U().optional(),error:U().optional(),relatedDeploymentId:U().optional(),data:P().optional()});var ps=I(`target`,[z({target:L(`local`),path:U().min(1),source:B()}).strict(),z({target:L(`sandbox`),path:U().min(1),sandboxId:U().min(1),source:B()}).strict()]),ms=z({schemaVersion:L(`openpond.profileEvaluationComparison.v1`),id:q,tasksetRelease:G,populationHash:K,environmentHash:K,metricPolicyHash:K,limitsHash:K,members:F(z({runManifest:G,metricResultHash:K,source:Pe,policy:Xe.shape.policy,score:V().min(0).max(1).nullable()}).strict()).min(2).max(100),createdAt:W}).strict().extend({contentHash:K}).strict(),hs=z({profileId:q,sourceRevision:U().trim().min(1).max(240),harnessRelease:G}).strict(),gs=z({kind:H([`run`,`suite`,`comparison`]),id:q,contentHash:K}).strict(),_s=z({schemaVersion:L(`openpond.profileEvaluationReport.v1`),id:q,createdAt:W,testedSources:F(hs).min(1).max(100),tasksetReleases:F(G).min(1).max(100),metricPolicyHashes:F(K).min(1).max(100),modelConfigurationHashes:F(K).min(1).max(100),evidence:F(gs).min(1).max(100),summary:z({totalChecks:V().int().nonnegative(),passedChecks:V().int().nonnegative(),failedChecks:V().int().nonnegative(),unscoredChecks:V().int().nonnegative(),meanScore:V().min(0).max(1).nullable()}).strict()}).strict().superRefine((e,t)=>{let{summary:n}=e;n.passedChecks+n.failedChecks+n.unscoredChecks!==n.totalChecks&&t.addIssue({code:`custom`,path:[`summary`],message:`Report check counts must add up.`}),new Set(e.evidence.map(({kind:e,id:t})=>`${e}:${t}`)).size!==e.evidence.length&&t.addIssue({code:`custom`,path:[`evidence`],message:`Report evidence must be unique.`})}).safeExtend({contentHash:K}),vs=z({schemaVersion:L(`openpond.profileEvaluationSuiteRun.v1`),id:q,suiteId:q,suiteHash:K,catalogHash:K,profileId:q,sourceRevision:U().trim().min(1).max(240),harnessRelease:G,members:F(z({definitionId:q,runManifest:G,runHash:K,passed:B(),score:V().min(0).max(1).nullable()}).strict()).min(1).max(1e3),passed:B(),createdAt:W,completedAt:W}).strict().extend({contentHash:K}).strict(),ys=z({schemaVersion:L(`openpond.optimizerTrainingSample.v1`),tokenIds:F(V().int().nonnegative()).min(2).max(32768),mask:F(B()).min(2).max(32768),logprobs:F(V().finite()).min(2).max(32768),temperatures:F(V().positive().finite()).min(2).max(32768),envName:U().trim().min(1).max(200),modelRequestId:U().trim().min(1).max(1e3),promptTokenCount:V().int().positive(),completionTokenCount:V().int().positive(),servedPolicyVersion:V().int().nonnegative()}).strict().superRefine((e,t)=>{let n=e.tokenIds.length;for(let[r,i]of[[`mask`,e.mask],[`logprobs`,e.logprobs],[`temperatures`,e.temperatures]])i.length!==n&&t.addIssue({code:`custom`,path:[r],message:`${r} must align with tokenIds`});e.promptTokenCount+e.completionTokenCount!==n&&t.addIssue({code:`custom`,path:[`completionTokenCount`],message:`prompt and completion token counts must span tokenIds`}),e.mask.filter(e=>!e).length!==e.promptTokenCount&&t.addIssue({code:`custom`,path:[`mask`],message:`promptTokenCount must equal the non-trainable mask count`}),e.mask.filter(Boolean).length!==e.completionTokenCount&&t.addIssue({code:`custom`,path:[`mask`],message:`completionTokenCount must equal the trainable mask count`})}),bs=z({id:q,environmentRelease:G,status:H([`completed`,`failed`,`timed_out`,`cancelled`]),startedAt:W,completedAt:W,traceRefs:F(ae).max(1e4),metadata:re}).strict(),xs=z({receiptRef:G,status:Ir,value:V().min(0).max(1).nullable(),learningEligible:B(),passed:B(),outcomeClass:kr,failureOwner:Br.nullable(),components:R(q,V().min(0).max(1).nullable())}).strict(),Ss=z({schemaVersion:L(`openpond.canonicalRolloutRecord.v1`),id:q,attemptRef:G,artifactManifestRef:G,tasksetRelease:G,environmentRelease:G,verifierSetRelease:G,harnessRelease:G,taskId:q,split:Me,model:se,seed:U().trim().min(1).max(500),reward:xs,traceRef:ae,optimizerSample:ys.nullable(),environmentExecutions:F(bs).min(1).max(1e5),startedAt:W,completedAt:W,metadata:re}).strict();function Cs(e,t){e.reward.status===`scored`&&(e.reward.value===null||!e.reward.learningEligible)&&t.addIssue({code:`custom`,path:[`reward`,`status`],message:`A scored rollout requires a numeric, learning-eligible reward.`}),e.reward.status===`unscorable`&&(e.reward.value!==null||e.reward.learningEligible)&&t.addIssue({code:`custom`,path:[`reward`,`status`],message:`An unscorable rollout has no reward and cannot be learning-eligible.`})}Ss.superRefine(Cs),z({...Ss.shape,contentHash:K}).strict().superRefine(Cs);var ws=U().trim().min(1).max(200),Ts=z({operationId:ws,request:tt,maximumCostUsd:V().finite().positive().max(1e4),graders:F(Ze).min(1).max(100).optional(),sourceExperimentId:ws.optional()}).strict().superRefine((e,t)=>{e.request.name||t.addIssue({code:`custom`,path:[`request`,`name`],message:`Name this Experiment before starting it.`}),e.operationId!==e.request.operationId&&t.addIssue({code:`custom`,path:[`request`,`operationId`],message:`Use one operation identity for this Experiment.`}),Math.round(e.maximumCostUsd*1e6)<1&&t.addIssue({code:`custom`,path:[`maximumCostUsd`],message:`The spending cap must be at least $0.000001.`}),e.graders&&new Set(e.graders.map(e=>e.id)).size!==e.graders.length&&t.addIssue({code:`custom`,path:[`graders`],message:`Select each grader once.`})}),Es=U().trim().min(1).max(200),Ds=U().regex(/^[a-f0-9]{64}$/),Os=z({id:Es,contentHash:Ds}).strict(),ks=z({available:B(),reason:U().max(1e3).nullable(),origin:be.nullable()}).strict(),As=z({schemaVersion:L(`openpond.postTrainingAttachment.v1`),binding:z({kind:H([`preparation`,`policy`]),id:Es,revision:V().int().positive(),contentHash:Ds}).strict(),projectId:Es.nullable(),automatic:B(),maximumSpendUsd:V().finite().positive().max(1e4),experiments:F(z({id:Es,configuration:Ts}).strict()).min(1).max(20),acceptancePlan:on.nullable()}).strict().superRefine((e,t)=>{if(new Set(e.experiments.map(e=>e.id)).size!==e.experiments.length&&t.addIssue({code:`custom`,message:`Attach each evaluation once.`}),e.experiments.reduce((e,t)=>e+t.configuration.maximumCostUsd,0)>e.maximumSpendUsd+1e-9&&t.addIssue({code:`custom`,message:`Attached evaluation budgets exceed the total approved budget.`}),e.experiments.some(t=>(t.configuration.request.project?.id??null)!==e.projectId)&&t.addIssue({code:`custom`,message:`Attached experiments must use the training Project.`}),e.acceptancePlan){let n=new Set(e.acceptancePlan.checks.map(e=>e.id));e.acceptancePlan.checks.some(t=>!e.experiments.some(e=>e.id===t.id))&&t.addIssue({code:`custom`,message:`Select the frozen Experiment for each acceptance check.`}),e.acceptancePlan.maximumSpendUsd+e.experiments.filter(e=>!n.has(e.id)).reduce((e,t)=>e+t.configuration.maximumCostUsd,0)>e.maximumSpendUsd+1e-9&&t.addIssue({code:`custom`,message:`Paired acceptance and diagnostic ceilings exceed the approved evaluation budget.`})}});function js(e){let{modelId:t,candidate:n,...r}=e.request.policy.kind===`fixture`?{modelId:null,candidate:null,...e.request.policy}:e.request.policy;return`modelConfigurationHash`in r&&delete r.modelConfigurationHash,{dataset:{id:e.request.taskset.id,contentHash:e.request.taskset.contentHash},populationHash:je(e.request.population.map(e=>({caseId:e.taskId,seed:e.seed,fixtureId:e.fixtureId}))),executionHash:je({settings:r,graders:e.graders??null})}}var Ms=z({baseline:Os,checks:F(z({id:Es,sourceRunId:Es,sourceManifestHash:Ds,targetConfigurationHash:Ds,executionHash:Ds,populationHash:Ds,evaluator:Os,feedbackKey:Es,output:H([`boolean`,`score`]),unit:U().min(1).max(80)}).strict()).min(1).max(100)}).strict(),Ns=H([`waiting_for_training`,`ready`,`preparing`,`queued`,`running`,`cleaning`,`completed`,`failed`,`blocked`,`cancelled`,`budget_exhausted`]),Ps=z({schemaVersion:L(`openpond.postTrainingSummary.v1`),id:Es,teamId:Es,jobId:Es,revision:V().int().positive(),planHash:Ds,automatic:B(),candidate:Os.nullable(),state:Ns,total:V().int().positive(),completed:V().int().nonnegative(),failed:V().int().nonnegative(),requiredOutcome:H([`none`,`pending`,`passed`,`failed`,`blocked`]),reason:U().max(500).nullable(),groupId:Es.nullable(),experimentIds:F(Es).max(20),updatedAt:N()}).strict().superRefine((e,t)=>{e.completed+e.failed>e.total&&t.addIssue({code:`custom`,message:`Evaluation totals are inconsistent.`}),[`preparing`,`queued`,`running`,`cleaning`,`completed`].includes(e.state)&&!e.candidate&&t.addIssue({code:`custom`,message:`Evaluation execution requires the exact trained candidate.`})}),Fs=z({operationId:Es,expectedRevision:V().int().positive(),planHash:Ds}).strict();z({operationId:Es,attachment:As}).strict(),z({id:Es,teamId:Es,ownerUserId:Es,attachment:As,qualification:Ms.nullable(),contentHash:Ds,createdAt:N()}).strict();function Is(e){return!!(e&&[`preparing`,`queued`,`running`,`cleaning`].includes(e.state))}var Ls=z({teamId:Es,actorId:Es,projectId:Es.nullable(),configuration:Fr,batches:F(Ee).max(1e4),sources:F(Ae).max(1e4),definitions:F(Ve).max(1e4),experiments:F(z({id:Es,name:U().max(500),configuration:Ts,graders:F(z({feedbackKey:Es,name:U().max(500),ref:Os}).strict()).max(100)}).strict()).max(1e4)}).strict();H([`hardware-catalog`,`gpu-catalog`,`modification-capabilities`,`estimate`,`funding`,`funding-handoff`,`list-drafts`,`get-draft`,`save-draft`,`archive-draft`,`prepare`,`prepare-draft`,`review-dataset`,`start`,`cancel`,`publish`,`attach`]);var Rs=z({teamId:Es,actorId:Es,configuration:Fr,policy:Oe,inspection:dt,iterations:F(z({iteration:Ie,evals:Ps.nullable()}).strict()).max(100),nextCursor:Es.nullable()}).strict(),zs=z({id:Es,expectedRevision:V().int().positive(),policyHash:Ds,operationId:Es,action:H([`pause`,`resume`,`reserve`,`cancel-iteration`,`retry-iteration`]),iterationId:Es.optional(),iterationRevision:V().int().positive().optional()}).strict(),Bs=H([`trajectory`,`reward`,`demonstration`,`preference`,`correction`,`critique`,`targeted_feedback`,`grader_evidence`,`infrastructure_failure`]),Vs=z({datasetRelease:G,harnessRelease:G,evidenceSetRelease:G.nullable(),profileRelease:G.nullable(),model:z({source:U().trim().min(1).max(200),revision:U().trim().min(1).max(500),artifactHash:K.nullable()}).strict(),environmentHash:K,graderHash:K,toolContractHash:K,verificationReceiptHash:K.nullable()}).strict(),Hs=z({schemaVersion:L(`openpond.learningSignal.v1`),id:q,taskId:q.nullable(),episodeId:q.nullable(),policyVersion:V().int().nonnegative().nullable(),lineage:Vs,approved:B(),verifier:H([`deterministic`,`model_judge`,`human`,`none`]),createdAt:W,contentHash:K,metadata:R(U(),P()).default({})}).strict(),Us=Hs.extend({kind:L(`trajectory`),payload:z({traceRef:U().trim().min(1).max(2e3),traceHash:K,terminal:B(),failureClass:H([`policy_failure`,`grader_failure`,`environment_failure`,`infrastructure_failure`,`timeout`,`cancelled`]).nullable(),optimizerSample:ys.nullable().optional()}).strict()}).strict(),Ws=Hs.extend({kind:L(`reward`),payload:z({reward:V().finite(),components:R(U(),V().finite()),eligible:B(),graderEvidenceRefs:F(q).max(1e3)}).strict()}).strict(),Gs=Hs.extend({kind:L(`demonstration`),payload:z({prompt:U().max(5e5),response:U().max(1e6)}).strict()}).strict(),Ks=Hs.extend({kind:L(`preference`),payload:z({prompt:U().max(5e5),chosen:U().max(1e6),rejected:U().max(1e6),rationale:U().max(5e5).nullable()}).strict()}).strict(),qs=Hs.extend({kind:L(`correction`),payload:z({original:U().max(1e6),corrected:U().max(1e6),rationale:U().max(5e5).nullable()}).strict()}).strict(),Js=Hs.extend({kind:L(`critique`),payload:z({response:U().max(1e6),critique:U().max(5e5),severity:H([`note`,`warning`,`error`])}).strict()}).strict(),Ys=Hs.extend({kind:L(`targeted_feedback`),payload:z({turnIndex:V().int().nonnegative(),target:H([`reasoning`,`tool`,`answer`,`policy`]),feedback:U().max(5e5)}).strict()}).strict(),Xs=Hs.extend({kind:L(`grader_evidence`),payload:z({graderId:q,score:V().finite().nullable(),passed:B(),privilegedArtifactRefs:F(U().trim().min(1).max(2e3))}).strict()}).strict(),Zs=Hs.extend({kind:L(`infrastructure_failure`),approved:L(!1),verifier:L(`none`),payload:z({code:q,phase:q,retryable:B(),rewardEligible:L(!1)}).strict()}).strict(),Qs=I(`kind`,[Us,Ws,Gs,Ks,qs,Js,Ys,Xs,Zs]);z({schemaVersion:L(`openpond.learningSignalBatch.v1`),manifestId:q,manifestHash:K,sequence:V().int().nonnegative(),signals:F(Qs).min(1).max(1e5),contentHash:K}).strict();var $s=z({schemaVersion:L(`openpond.trainingEngineCapabilities.v1`),adapterId:q,available:B(),methods:F(U().trim().min(1).max(100)),signalKinds:F(Bs),modelFamilies:F(U().trim().min(1).max(200)),precisions:F(H([`fp32`,`fp16`,`bf16`,`tf32`,`int8`,`int4`])),topologies:F(U().trim().min(1).max(200)),workerProtocolVersion:U().trim().min(1).max(200),upstreamRevision:U().trim().min(1).max(500),workerImageDigest:U().regex(/^sha256:[a-f0-9]{64}$/).nullable().default(null),capabilityReceipt:K,checkedAt:W,unavailableReason:U().trim().min(1).max(5e3).nullable()}).strict(),ec=z({schemaVersion:L(`openpond.computeTargetCapabilities.v1`),adapterId:q,kind:H([`local`,`ssh`,`managed`,`custom`]),provider:q.nullable(),available:B(),devices:F(z({id:q,kind:H([`cpu`,`gpu`,`accelerator`]),vendor:U().trim().min(1).max(200),name:U().trim().min(1).max(500),memoryBytes:V().int().nonnegative().nullable(),runtime:U().trim().min(1).max(200)}).strict()),supportsWorkerImages:B(),supportsArtifactTransfer:B(),supportsCancellation:B(),capabilityReceipt:K,checkedAt:W,unavailableReason:U().trim().min(1).max(5e3).nullable()}).strict(),tc=z({schemaVersion:L(`openpond.harnessRuntimeCapabilities.v1`),adapterId:q,available:B(),placements:F(H([`local`,`remote`,`colocated`,`provider_native`])),lifecycle:F(H([`create`,`reset`,`step`,`grade`,`collect`,`destroy`])),deterministicReplay:B(),privilegedIsolation:B(),capabilityReceipt:K,checkedAt:W,unavailableReason:U().trim().min(1).max(5e3).nullable()}).strict();z({schemaVersion:L(`openpond.resolvedTrainingPlan.v1`),manifest:Qo,recipe:mo,runtime:Bo,compute:qo,engine:No,execution:z({trainingPlanId:q,approvalId:q}).strict().nullable(),maximumSpendUsd:V().nonnegative().nullable(),approvalHash:K,contentHash:K}).strict().superRefine((e,t)=>{let n=[[`runtime`,e.runtime,e.manifest.runtimeTarget],[`compute`,e.compute,e.manifest.computeTarget],[`engine`,e.engine,e.manifest.engine]];for(let[e,r,i]of n)JSON.stringify(r)!==JSON.stringify(i)&&t.addIssue({code:`custom`,path:[e],message:`${e} must exactly match the Harness Run Manifest`});e.recipe.method!==e.manifest.recipe.method&&t.addIssue({code:`custom`,path:[`recipe`,`method`],message:`Recipe method must match the Harness Run Manifest`}),e.approvalHash!==e.manifest.approval.approvalHash&&t.addIssue({code:`custom`,path:[`approvalHash`],message:`Approval hash must match the Harness Run Manifest`}),e.maximumSpendUsd!==e.manifest.approval.maximumSpendUsd&&t.addIssue({code:`custom`,path:[`maximumSpendUsd`],message:`Maximum spend must match the Harness Run Manifest`})}),z({schemaVersion:L(`openpond.adapterValidationReceipt.v1`),adapterId:q,valid:B(),issues:F(z({code:q,path:U().trim().max(2e3).nullable(),message:U().trim().min(1).max(5e3)}).strict()),capabilityReceipt:K,planHash:K,createdAt:W,contentHash:K}).strict(),z({runId:q,adapterId:q,protocolVersion:H([`openpond.training.v2`,`adapter.native.v1`]).default(`adapter.native.v1`),routeFamily:H([`training_v2`,`adapter_native`]).default(`adapter_native`),routeId:q.optional(),providerJobId:U().trim().min(1).max(1e3).nullable(),tenantId:q.optional(),leaseId:q.nullable(),manifestHash:K.optional(),inputBundleHash:K.optional(),createdAt:W}).strict(),z({runId:q,state:H([`queued`,`preparing`,`running`,`cancelling`,`cancelled`,`succeeded`,`failed`]),phase:U().trim().min(1).max(200),progress:V().min(0).max(1).nullable(),rolloutProgress:z({groupsCompleted:V().int().nonnegative(),groupsTarget:V().int().nonnegative(),optimizerUpdatesApplied:V().int().nonnegative(),optimizerUpdatesSkipped:V().int().nonnegative()}).strict().optional(),updatedAt:W,errorCode:q.nullable()}).strict(),z({runId:q,manifestHash:K,artifacts:F(z({kind:H([`checkpoint`,`adapter`,`metrics`,`trace`,`evaluation`,`receipt`]),objectRef:U().trim().min(1).max(2e3),sha256:K,sizeBytes:V().int().nonnegative(),metadata:R(U(),P()).optional()}).strict()),contentHash:K}).strict();var nc=H([`ready`,`model_download_required`,`compute_setup_required`,`provider_managed`,`unsupported`]),rc=z({id:q,label:U().trim().min(1).max(500),description:U().trim().min(1).max(2e3),destinationId:q,computeAdapterId:q,runtimeAdapterId:q,engineAdapterId:q,methods:F(U().trim().min(1).max(100)),capabilityPills:F(U().trim().min(1).max(100)),executionMode:H([`local_worker`,`provider_native`]),approvalPolicy:z({providerId:ce,providerLabel:U().trim().min(1).max(200),settingsActionLabel:U().trim().min(1).max(500).nullable(),exportApprovalRequired:B(),exportDescription:U().trim().min(1).max(2e3).nullable(),preparationRequired:B(),minimumSpendUsd:V().nonnegative(),maximumSpendUsd:V().positive(),defaultMaximumSpendUsd:V().positive(),minimumRetentionDays:V().int().positive(),maximumRetentionDays:V().int().positive(),defaultRetentionDays:V().int().positive(),methodRequirement:U().trim().min(1).max(2e3).nullable()}).strict().nullable(),limits:z({maximumSequenceLength:V().int().positive(),maximumOutputTokens:V().int().positive(),maximumTrainingExamples:V().int().positive().nullable()}).strict(),defaults:z({loraRank:V().int().positive(),maxSteps:V().int().positive(),rolloutGroupSize:V().int().min(2).max(32),rolloutConcurrency:V().int().positive().max(32),rolloutOutputTokens:V().int().positive()}).strict(),available:B(),unavailableReason:U().trim().min(1).max(5e3).nullable()}).strict(),ic=z({selectionKey:q,label:U().trim().min(1).max(500),source:H([`local`,`builtin`,`huggingface`,`managed`,`search`]),modelId:U().trim().min(1).max(1e3),revision:U().trim().min(1).max(500).nullable(),tokenizerRevision:U().trim().min(1).max(500).nullable(),chatTemplateHash:K.nullable(),modelAssetId:q.nullable(),expectedBytes:V().int().nonnegative().nullable(),cached:B(),known:B(),searchResolved:B(),computeAdapterIds:F(q),engineAdapterIds:F(q),preparationState:nc,reason:U().trim().min(1).max(5e3).nullable(),compatibilities:F(z({targetId:q,methods:F(U().trim().min(1).max(100)),state:nc,reason:U().trim().min(1).max(5e3).nullable()}).strict())}).strict(),ac=z({schemaVersion:L(`openpond.trainingCatalog.v1`),models:F(ic).max(1e5),engines:F($s),compute:F(ec),runtimes:F(tc),targets:F(rc),generatedAt:W,contentHash:K}).strict();z({schemaVersion:L(`openpond.trainingPreparationPlan.v1`),modelRunId:q,state:nc,reason:U().trim().min(1).max(5e3).nullable(),runtime:Bo.nullable(),compute:qo.nullable(),engine:No.nullable(),downloads:F(z({kind:L(`model`),label:U().trim().min(1).max(500),expectedBytes:V().int().nonnegative(),digest:U().trim().min(8).max(500),cached:B(),state:H([`ready`,`required`,`downloading`,`cancelled`,`failed`]),progress:V().min(0).max(1).nullable(),cancellable:B(),diskImpactBytes:V().int().nonnegative()}).strict()),dataMovement:F(z({direction:H([`upload`,`download`,`none`]),label:U().trim().min(1).max(500),bytes:V().int().nonnegative().nullable()}).strict()),quoteUsd:V().nonnegative().nullable(),maximumSpendUsd:V().nonnegative().nullable(),retentionDays:V().int().nonnegative().nullable(),sideEffectsStarted:L(!1),contentHash:K}).strict();var oc=U().regex(/^[a-f0-9]{64}$/),sc=z({request:tt,maximumCostUsd:V().finite().positive().max(1e4),graders:F(et).min(1).max(100),admissionRequestHash:oc.optional(),sourceExperimentId:U().trim().min(1).max(200).optional()}).strict().extend({configurationHash:oc}).strict();Qe.extend({configuration:sc}).strict();var cc=z({teamId:U().trim().min(1).max(240),items:F(z({name:U().trim().min(1).max(500),source:De,ready:B(),reason:U().min(1).max(2e3).nullable()}).strict()).max(8),nextCursor:U().min(1).max(8192).nullable()}).strict(),lc=U().min(1).max(500),uc=U().regex(/^[a-f0-9]{64}$/),dc=N(),fc=V().finite().nonnegative().nullable(),pc=V().int().nonnegative().nullable(),mc=z({id:lc,sequence:V().int().nonnegative(),at:dc.nullable(),type:U().max(160),action:U().max(160).nullable(),correlationId:lc.nullable(),attempt:pc,taskId:lc.nullable(),status:U().max(100).nullable(),errorCode:U().max(200).nullable(),cleanupComplete:B().nullable()}).strict(),hc=z({id:lc,kind:U().max(100),status:U().max(100),receiptId:lc.nullable(),maximumUsd:fc,settledUsd:fc,model:U().max(200).nullable(),durationMs:pc,inputTokens:pc,outputTokens:pc,totalTokens:pc}).strict(),gc=z({schemaVersion:L(`openpond.runDiagnostics.v1`),teamId:lc,runId:lc,location:H([`local`,`hosted`]),manifestHash:uc,observedAt:dc,status:U().max(100),startedAt:dc.nullable(),completedAt:dc.nullable(),error:U().max(8192).nullable(),resultAvailable:B(),parent:z({id:lc,status:U().max(100),attempt:pc,heartbeatAt:dc.nullable(),leaseExpiresAt:dc.nullable(),releasedAt:dc.nullable(),errorCode:U().max(200).nullable()}).strict().nullable(),accounting:z({maximumUsd:fc,settledUsd:fc,outstandingUsd:fc,outstandingCount:pc,final:B(),receiptCount:pc}).strict(),events:F(mc).max(100),nextEventCursor:V().int().nonnegative().nullable(),eventCount:V().int().nonnegative(),calls:F(hc).max(100),nextCallCursor:lc.nullable(),callCount:V().int().nonnegative(),limitations:F(U().max(1e3)).max(30)}).strict(),_c=gc.extend({contentHash:uc}).strict();z({afterSequence:V().int().nonnegative().optional(),afterCallId:lc.optional()}).strict();function vc(e){let t=gc.parse(e);return{...t,contentHash:je(t)}}function yc(e,t){let n=_c.parse(e),{contentHash:r,...i}=n;if(r!==je(i)||n.teamId!==t.teamId||n.runId!==t.runId||t.manifestHash&&n.manifestHash!==t.manifestHash)throw Error(`Diagnostics differ from the selected workspace, run or retained evidence.`);if(n.events.length>n.eventCount||n.calls.length>n.callCount||new Set(n.events.map(e=>e.id)).size!==n.events.length||n.events.some((e,r)=>e.sequence<=(r?n.events[r-1].sequence:t.afterSequence??-1))||n.calls.some((e,r)=>e.id<=(r?n.calls[r-1].id:t.afterCallId??``))||n.nextEventCursor!==null&&n.nextEventCursor!==n.events.at(-1)?.sequence||n.nextCallCursor!==null&&n.nextCallCursor!==n.calls.at(-1)?.id||n.accounting.final&&(n.accounting.outstandingCount!==0||n.accounting.settledUsd===null||!n.accounting.receiptCount))throw Error(`Diagnostic evidence pagination or final accounting is inconsistent.`);return n}function bc(e){let t=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:{},n=t(e.payload),r=t(n.data),i=(e,t)=>typeof e==`string`&&/^[a-zA-Z0-9_.:/-]+$/.test(e)?e.slice(0,t):null;return mc.parse({id:e.id,sequence:e.sequence,at:e.at,type:e.type.slice(0,160),action:i(n.action,160),correlationId:i(r.callId??r.toolCallId,500),attempt:typeof n.attempt==`number`&&Number.isInteger(n.attempt)&&n.attempt>=0?n.attempt:null,taskId:i(n.taskId??r.taskId,500),status:i(n.status,100),errorCode:i(n.errorCode??n.code,200),cleanupComplete:typeof n.complete==`boolean`&&e.type===`experiment.harness.cleanup`?n.complete:null})}function xc(e){let t=[],n=new Map;for(let r of[...e].sort((e,t)=>e.sequence-t.sequence)){if(r.type.startsWith(`training.`)){t.push({id:r.id,label:r.action??r.type,taskId:r.taskId,startedAt:r.at,completedAt:null,durationMs:null,status:`observed`,evidenceIds:[r.id]});continue}if(![`tool.started`,`tool.completed`,`tool.failed`].includes(r.type))continue;let e=JSON.stringify([r.correlationId??r.action,r.taskId,r.attempt]);if(r.type===`tool.started`){let i={id:r.id,label:r.action??`Operation`,taskId:r.taskId,startedAt:r.at,completedAt:null,durationMs:null,status:`running`,evidenceIds:[r.id]};n.set(e,i),t.push(i)}else{let i=n.get(e);i?(i.completedAt=r.at,i.status=r.type===`tool.failed`?`failed`:`completed`,i.durationMs=i.startedAt&&r.at?Math.max(0,Date.parse(r.at)-Date.parse(i.startedAt)):null,i.evidenceIds.push(r.id),n.delete(e)):t.push({id:r.id,label:r.action??`Operation`,taskId:r.taskId,startedAt:null,completedAt:r.at,durationMs:null,status:r.type===`tool.failed`?`failed`:`completed`,evidenceIds:[r.id]})}}return t}function Sc(e,t=e.events,n=e.calls){let{contentHash:r,...i}=e;return`Investigate this OpenPond run using the retained metadata below. Start read-only. Separate observed facts, hypotheses, missing evidence and recommended investigations. Cite event/call IDs. Do not infer zero costs or successful grading from missing evidence; gateway duration is not pure inference. Do not replay, regrade, edit source, change configuration, restart or deploy without a separate user instruction. Never request credentials or private grader content. This snapshot may be partial.
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MainChatThread-BSvKu4e5.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/index-M_h2Ok4V.js","assets/index-g7UqJhnX.css","assets/useQuery-DuTGOe2b.js","assets/schemas-Brv9Vmnk.js","assets/common-BWVSBnpX.js","assets/chunk-AG6UJ3DI-D9KZjTYP.js","assets/chunk-GCUWJUUM-Dy6oUNJ6.js","assets/chunk-H3JZ3P5T-DolwEJXo.js","assets/reward-checks-DJJZYgf8.js","assets/chunk-Q4RGCEOI-Cr-dg4Nk.js","assets/chunk-3BYFS4RO-ztZjcMmt.js","assets/api-client-DJRVOFzS.js","assets/ChatTimelineEntry-DzcucW20.js","assets/create-pipeline-DsZzNkt9.js","assets/icons-OQhKVrDc.js","assets/training-model-data-G-D64935.js","assets/copy-DEK20zbZ.js","assets/x-5_iy6IDd.js","assets/App-L7RV4D0A.js","assets/settings-BC-bzgk6.js","assets/client-choice-storage-DYZsrVr9.js","assets/requests-DmeUYik4.js","assets/profile-ref-D8lxL7dW.js","assets/work-outputs-D_8TovAK.js","assets/chunk-GS5HEE4M-C0RLeIsy.js","assets/intake-contracts-B8JZKYwb.js","assets/training-CzbWtx75.js","assets/ponder-desktop-Ca-9KggQ.js","assets/chat-resources-DhKAnljP.js","assets/app-models-BUdzQbXo.js","assets/model-display-zPvC4L2B.js","assets/submit-issue-command-CFitxxmO.js","assets/connected-app-mentions-D3wRZLwI.js","assets/profile-agent-labels-Duh96b8x.js","assets/browser-sidebar-links-PVPCrsDJ.js","assets/browser-url-LACq2Ngu.js","assets/query-scope-BRpcgljO.js","assets/bot-D7M8ZtE6.js","assets/chevron-down-BAEcJitl.js","assets/chevron-right-3G9s2cQ9.js","assets/external-link-DwDry0Fb.js","assets/loader-circle-DXVtGvuV.js","assets/maximize-2-BwFXSX6b.js","assets/message-square-C2nqfNLn.js","assets/plus-CB258e62.js","assets/refresh-cw-CwEmO71D.js","assets/square-terminal-CawpQtCi.js","assets/AppToastContext-DuiPouLz.js","assets/NativeSetupTerminal-kZ-nFPE8.js","assets/AppDialog-B2V84J7f.js","assets/PageChrome-Bncv-ps0.js","assets/NativeSetupTerminal-3eR9D_R3.css","assets/organization-types-PP-yuR2J.js","assets/ui-theme.generated-D-mc26qt.js","assets/App-DpFKLxuA.css","assets/CartesianChart-CtfMRAfp.js","assets/chevron-up-DTYF52H1.js","assets/folder-open-DOb4AjV6.js","assets/image-BkYJDChH.js","assets/play-CkACZ6Zo.js","assets/HtmlVisual-nvl1x-jh.js","assets/HtmlVisual-C7GlEVfH.css","assets/TasksetDraftEditorPrimitives-DCQTuswJ.js","assets/AttachmentTypeIcon-l-GRNxaz.js","assets/presentation-BYxhoSIo.js","assets/ChatTimelineEntry-vs8RaEGD.css","assets/ComposerCreateImproveStrip-DcM1bkfu.js","assets/WorkspacePresentationPreview-sP7JUT7m.js","assets/WorkspaceFileLocation-Dl8M2ZKN.js","assets/aiden0z-pptx-renderer.es-Bo43EjzT.js","assets/jszip.min-BWcKrrYP.js","assets/FilePagePreview-B7bWObJN.js","assets/pdf.worker.min-BrEVksTu.js","assets/docx-preview-Blk_WGfs.js","assets/ExperimentTrainingDataWorkspace-CfOyoMrq.js","assets/LearningBatchesPage-A2dFQW2j.js","assets/chunk-C3TS766N-DENE60SE.js","assets/ModelProjectPageHeader-lu6iRXHK.js","assets/LearningBatchesPage-B1NZTBSv.css","assets/WorkspaceDiffPanel-xk-ve1MO.js","assets/info-Mj5lp4Ic.js","assets/save-S--FOuce.js","assets/AppTerminalPanel-DfYpUDKT.js","assets/CollaborationTabs-BpmKjNAC.js","assets/CollaborationTabs-CU-9Shwu.css","assets/AppsView-B20RHDCy.js","assets/settings-lists-ChqDppMP.js","assets/settings-lists-CBaz4cGG.css","assets/client-gy7zrd7a.js","assets/useAgentInventory-c5B_Tszj.js","assets/AppsView-D3vVesNd.css","assets/settings-forms-DLe1dTYN.css","assets/GetStartedView-BYbFl93M.js","assets/GetStartedView-idp5pnnE.css","assets/LabsRoute-DzEbPpMK.js","assets/useChatContextSelection-DOISZpTz.js","assets/LabModelWorkspace-CHlhzG3q.js","assets/LabModelWorkspace-DOrgCk9Z.css","assets/cloud-upload-De-XSMUr.js","assets/dataset-workspaces-BTPi71mz.js","assets/LabsRoute-C9Y0GU34.css","assets/ScheduledWorkPage-DI0mgt82.js","assets/ComposerAttachments-BMmALUs_.js","assets/useLocalAgentSchedules-QJ8RsMKm.js","assets/OutputsPage-Dz190U9t.js","assets/ProjectsPage-DVkYvLtd.js","assets/ProjectsPage-BPoAzc-Z.css","assets/LabSkillSidebar-CqHeZzoj.js","assets/LabSkillSidebar-Uy4vA6fy.css","assets/BrowserSidebar-Ce0ToS2O.js","assets/RightChatPanelStack-CP4leenI.js","assets/NativeSkillSidebar-DkkD1uH2.js","assets/NativeSkillSidebar-D4DVkqqR.css","assets/TeamChatView-BBEomfQ7.js","assets/TeamChatView-BMZ8S7Sj.css","assets/CommunityView-ggdn8pcH.js","assets/wifi-off-BOfP4Vmg.js","assets/paperclip-CmrRruxi.js","assets/CommunityView-C5uLqiF2.css","assets/TrainingDraftPanel-BAuh_BF3.js","assets/TrainingCreationPanel-Ds4PLfsd.js"])))=>i.map(i=>d[i]);
2
+ import{i as e}from"./rolldown-runtime-Dd_uD5pT.js";import{g as t,h as n,l as r,m as i,s as a,t as o}from"./index-M_h2Ok4V.js";import{A as s,E as c,O as l,P as u,S as d,a as f,b as p,c as m,d as h,i as g,j as _,l as v,o as y,r as b,s as x,t as S,u as C,v as w}from"./useQuery-DuTGOe2b.js";import{a as T,i as E,n as D,o as O,r as k,s as A,t as j}from"./useChatContextSelection-DOISZpTz.js";import{C as M,E as N,S as P,a as F,c as I,d as L,f as ee,g as R,m as z,o as B,p as V,r as H,v as U,w as te,x as ne}from"./schemas-Brv9Vmnk.js";import{a as re,c as W,d as ie,i as G,n as ae,o as K,s as q}from"./common-BWVSBnpX.js";import{A as oe,O as se,k as ce,y as le}from"./settings-BC-bzgk6.js";import{n as ue,o as de}from"./client-choice-storage-DYZsrVr9.js";import{t as fe}from"./model-display-zPvC4L2B.js";import{a as pe,i as me,n as he,t as ge}from"./requests-DmeUYik4.js";import{t as _e}from"./profile-ref-D8lxL7dW.js";import{F as ve,H as ye,L as be,M as xe,N as Se,Ot as Ce,Q as we,R as Te,S as Ee,U as De,_ as Oe,at as ke,b as Ae,d as je,ft as Me,i as Ne,it as Pe,j as Fe,m as Ie,pt as Le,q as Re,rt as ze,u as Be,w as Ve,z as He}from"./chunk-H3JZ3P5T-DolwEJXo.js";import{a as Ue,i as We,n as Ge,o as Ke,r as qe,t as Je}from"./ComposerAttachments-BMmALUs_.js";import{n as Ye}from"./work-outputs-D_8TovAK.js";import{_ as Xe,a as Ze,c as Qe,h as $e,i as et,l as tt,o as nt,p as rt,r as it,t as at,u as ot,y as st}from"./chunk-GS5HEE4M-C0RLeIsy.js";import{u as ct}from"./reward-checks-DJJZYgf8.js";import{a as lt,i as ut,l as dt,r as ft,t as pt}from"./chunk-C3TS766N-DENE60SE.js";import{$ as mt,$t as ht,A as gt,B as _t,Bn as vt,Bt as yt,Cn as bt,D as xt,Dn as St,Dt as Ct,E as wt,En as Tt,Et,F as Dt,Ft as Ot,G as kt,Gt as At,Ht as jt,I as Mt,It as Nt,J as Pt,Jt as Ft,K as It,Kt as Lt,L as Rt,Ln as zt,Lt as Bt,M as Vt,Mt as Ht,Nt as Ut,On as Wt,Ot as Gt,P as Kt,Pt as qt,Qt as Jt,Rn as Yt,Rt as Xt,S as Zt,Sn as Qt,St as $t,T as en,Tn as tn,Tt as nn,U as rn,Ut as an,Vn as on,Vt as sn,W as cn,Wt as ln,X as un,Xt as dn,Y as fn,Yt as pn,Zt as mn,_ as hn,_n as gn,_t as _n,a as vn,an as yn,at as bn,b as xn,bn as Sn,bt as Cn,c as wn,cn as Tn,d as En,dn as Dn,dt as On,en as kn,et as An,f as jn,fn as Mn,g as Nn,gt as Pn,ht as Fn,i as In,in as Ln,it as Rn,j as zn,jt as Bn,k as Vn,kt as Hn,l as Un,ln as Wn,lt as Gn,m as Kn,mn as qn,mt as Jn,n as Yn,nn as Xn,nt as Zn,o as Qn,on as $n,ot as er,pn as tr,q as nr,qt as rr,r as ir,rn as ar,rt as or,s as sr,sn as cr,st as lr,t as ur,tn as dr,u as fr,un as pr,ut as mr,vn as hr,vt as gr,w as _r,wn as vr,wt as yr,x as br,xn as xr,xt as Sr,y as Cr,yn as wr,yt as Tr,z as Er,zn as Dr,zt as Or}from"./training-CzbWtx75.js";import{A as kr,E as Ar,G as jr,H as Mr,J as Nr,K as Pr,L as Fr,M as Ir,W as Lr,Z as Rr,it as zr,j as Br,nt as J,ot as Vr,x as Hr,z as Ur}from"./chunk-GCUWJUUM-Dy6oUNJ6.js";import{r as Wr}from"./ponder-desktop-Ca-9KggQ.js";import{i as Gr,n as Kr,o as qr,s as Jr,t as Yr}from"./chat-resources-DhKAnljP.js";import{C as Xr,D as Zr,E as Qr,O as $r,S as ei,T as ti,_ as ni,b as ri,d as ii,l as ai,m as oi,r as si,v as ci,w as li,x as ui}from"./LabModelWorkspace-CHlhzG3q.js";import{C as di,D as fi,O as pi,S as mi,c as hi,d as gi,f as _i,k as vi,l as yi,o as bi,t as xi,u as Si,v as Ci,y as wi}from"./app-models-BUdzQbXo.js";import{n as Y,t as Ti}from"./api-client-DJRVOFzS.js";import{A as Ei,D as Di,I as Oi,L as ki,N as Ai,O as ji,S as Mi,_ as Ni,a as Pi,c as Fi,d as Ii,f as Li,g as Ri,i as zi,l as Bi,m as Vi,n as Hi,o as Ui,p as Wi,r as Gi,s as Ki,t as qi,w as Ji,x as Yi}from"./submit-issue-command-CFitxxmO.js";import{a as Xi,l as Zi,n as Qi,o as $i,t as ea}from"./browser-sidebar-links-PVPCrsDJ.js";import{n as ta,r as na,t as ra}from"./query-scope-BRpcgljO.js";import{t as ia}from"./icons-OQhKVrDc.js";import{A as aa,B as oa,C as sa,E as ca,F as la,I as ua,L as da,M as fa,N as pa,O as ma,P as ha,S as ga,V as _a,b as va,j as ya,k as ba,m as xa,n as Sa,o as Ca,x as wa,z as Ta}from"./training-model-data-G-D64935.js";import{Ut as Ea}from"./CartesianChart-CtfMRAfp.js";import{t as Da}from"./bot-D7M8ZtE6.js";import{t as Oa}from"./chevron-down-BAEcJitl.js";import{t as ka}from"./chevron-right-3G9s2cQ9.js";import{t as Aa}from"./cloud-upload-De-XSMUr.js";import{t as ja}from"./copy-DEK20zbZ.js";import{t as Ma}from"./external-link-DwDry0Fb.js";import{t as Na}from"./folder-open-DOb4AjV6.js";import{t as Pa}from"./loader-circle-DXVtGvuV.js";import{t as Fa}from"./maximize-2-BwFXSX6b.js";import{t as Ia}from"./message-square-C2nqfNLn.js";import{t as La}from"./paperclip-CmrRruxi.js";import{t as Ra}from"./play-CkACZ6Zo.js";import{t as za}from"./plus-CB258e62.js";import{t as Ba}from"./refresh-cw-CwEmO71D.js";import{t as Va}from"./square-BmPfHjGU.js";import{t as Ha}from"./square-terminal-CawpQtCi.js";import{t as Ua}from"./x-5_iy6IDd.js";import{a as Wa,n as Ga,r as Ka}from"./AppToastContext-DuiPouLz.js";import{t as qa}from"./AppDialog-B2V84J7f.js";import{c as Ja,i as Ya,l as Xa,o as Za,r as Qa,s as $a,t as eo,u as to}from"./connected-app-mentions-D3wRZLwI.js";import{t as no}from"./browser-url-LACq2Ngu.js";import{$ as ro,A as io,Bt as ao,C as oo,Cn as so,En as co,Fn as lo,Ft as uo,Gn as fo,Gt as X,Ht as po,In as mo,It as ho,Jt as go,Kn as _o,Ln as vo,Mt as yo,O as bo,On as xo,Ot as So,P as Co,Pt as wo,Q as To,Tn as Eo,U as Do,Un as Oo,Ut as Z,Wt as ko,_n as Ao,_r as jo,an as Mo,ar as No,bn as Po,bt as Fo,ct as Io,et as Lo,gn as Ro,hn as zo,ir as Bo,it as Vo,jt as Ho,kn as Uo,ln as Wo,lt as Go,nn as Ko,nr as qo,on as Jo,pn as Yo,q as Xo,qn as Zo,rr as Qo,rt as $o,tn as es,un as ts,v as ns,wn as rs,y as is,zt as as}from"./App-L7RV4D0A.js";import{t as os}from"./AttachmentTypeIcon-l-GRNxaz.js";var ss=class extends p{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),s(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&d(t.mutationKey)!==d(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??jo();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){w.batch(()=>{if(this.#r&&this.hasListeners()){let t=this.#t.variables,n=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{this.#r.onSuccess?.(e.data,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(e.data,null,t,n,r)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{this.#r.onError?.(e.error,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(void 0,e.error,t,n,r)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}};function cs(e,t){let n=new Set(t);return e.filter(e=>!n.has(e))}var ls=class extends p{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=[];constructor(e,t,n){super(),this.#e=e,this.#r=n,this.#n=[],this.#i=[],this.#t=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#i.forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#i.forEach(e=>{e.destroy()})}setQueries(e,t){this.#n=e,this.#r=t,w.batch(()=>{let e=this.#i,t=this.#p(this.#n);t.forEach(e=>e.observer.setOptions(e.defaultedQueryOptions));let n=t.map(e=>e.observer),r=n.map(e=>e.getCurrentResult()),i=e.length!==n.length,a=n.some((t,n)=>t!==e[n]),o=i||a,c=o?!0:r.some((e,t)=>{let n=this.#t[t];return!n||!s(e,n)});(o||c)&&(o&&(this.#l=t,this.#i=n),this.#t=r,this.hasListeners()&&(o&&(cs(e,n).forEach(e=>{e.destroy()}),cs(n,e).forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})),this.#h()))})}getCurrentResult(){return this.#t}getQueries(){return this.#i.map(e=>e.getCurrentQuery())}getObservers(){return this.#i}getOptimisticResult(e,t){let n=this.#p(e),r=n.map(e=>e.observer.getOptimisticResult(e.defaultedQueryOptions)),i=n.map(e=>e.defaultedQueryOptions.queryHash);return[r,e=>this.#d(e??r,t,i),()=>this.#u(r,n)]}#u(e,t){let n=new Set;return t.map((r,i)=>{let a=e[i];return r.defaultedQueryOptions.notifyOnChangeProps?a:r.observer.trackResult(a,e=>{n.has(e)||(n.add(e),t.forEach(t=>{t.observer.trackProp(e)}))})})}#d(e,t,n){if(t){let r=this.#c,i=n!==void 0&&r!==void 0&&(r.length!==n.length||n.some((e,t)=>e!==r[t]));return(this.#t!==this.#s||i||t!==this.#o)&&(this.#o=t,this.#s=this.#t,n!==void 0&&(this.#c=n),this.#a=l(this.#a,t(e))),this.#a}return e}#f(){return!this.#r?.combine||this.#i.some((e,t)=>e.options.suspense&&this.#t[t]?.data===void 0)}#p(e){let t=new Map;this.#i.forEach(e=>{let n=e.options.queryHash;if(!n)return;let r=t.get(n);r?r.push(e):t.set(n,[e])});let n=[];return e.forEach(e=>{let r=this.#e.defaultQueryOptions(e),i=t.get(r.queryHash)?.shift()??new h(this.#e,r);n.push({defaultedQueryOptions:r,observer:i})}),n}#m(e,t){let n=this.#i.indexOf(e);n!==-1&&(this.#t=this.#t.slice(),this.#t[n]=t,this.#h())}#h(){if(this.hasListeners()){let e=this.#f(),t=this.#a,n=e?t:this.#d(this.#u(this.#t,this.#l),this.#r?.combine);(e||t!==n)&&w.batch(()=>{this.listeners.forEach(e=>{e(this.#t)})})}}},Q=e(t(),1);function us({queries:e,...t},n){let r=u(n),i=C(),a=v(),o=t.subscribed!==!1,s=Q.useMemo(()=>e.map(e=>{let t=r.defaultQueryOptions(e);return t._optimisticResults=i?`isRestoring`:o?`optimistic`:void 0,t}),[e,r,i,o]);s.forEach(e=>{b(e);let t=r.getQueryCache().get(e.queryHash);y(e,a,t)}),m(a);let[l]=Q.useState(()=>new ls(r,s,t)),[d,p,_]=l.getOptimisticResult(s,t.combine),S=!i&&o;Q.useSyncExternalStore(Q.useCallback(e=>S?l.subscribe(w.batchCalls(e)):c,[l,S]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),Q.useEffect(()=>{l.setQueries(s,t)},[s,t,l]);let T=d.some((e,t)=>f(s[t],e))?d.flatMap((e,t)=>{let n=s[t];if(n&&f(n,e)){let e=new h(r,n);return g(n,e,a)}return[]}):[];if(T.length>0)throw Promise.all(T);let E=d.find((e,t)=>{let n=s[t];return n&&x({result:e,errorResetBoundary:a,throwOnError:n.throwOnError,query:r.getQueryCache().get(n.queryHash),suspense:n.suspense})});if(E)throw E.error;return p(_())}function ds(e,t){let n=u(t),[r]=Q.useState(()=>new ss(n,e));Q.useEffect(()=>{r.setOptions(e)},[r,e]);let i=Q.useSyncExternalStore(Q.useCallback(e=>r.subscribe(w.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=Q.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(c)},[r]);if(i.error&&_(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}var fs=H([`visual.published`,`file.preview_requested`,`task.inbox`,`task.input`,`task.wait`,`session.started`,`session.updated`,`session.title.updated`,`turn.started`,`assistant.delta`,`assistant.reasoning.delta`,`tool.started`,`tool.completed`,`skill.selected`,`skill.loaded`,`skill.load_failed`,`user_question.asked`,`user_question.answered`,`user_question.dismissed`,`approval.requested`,`approval.resolved`,`command.output`,`workspace_action`,`workspace_action_result`,`workspace.diff`,`create_improve.updated`,`session.context.updated`,`session.compaction.started`,`session.compaction.completed`,`session.compaction.failed`,`goal.continuation.started`,`goal.continuation.skipped`,`goal.continuation.failed`,`harness.refiner.queued`,`harness.refiner.started`,`harness.refiner.completed`,`harness.refiner.failed`,`turn.completed`,`turn.failed`,`turn.interrupted`,`session.closed`,...le,`diagnostic`]);z({id:U(),sequence:V().int().positive().optional(),sessionId:U().optional(),turnId:U().optional(),name:fs,timestamp:U(),source:H([`ui_button`,`chat_action`,`terminal_command`,`hook`,`provider`,`server`]).optional(),action:U().optional(),appId:U().nullable().optional(),args:R(U(),P()).optional(),status:H([`started`,`completed`,`failed`,`pending`]).optional(),output:U().optional(),error:U().optional(),relatedDeploymentId:U().optional(),data:P().optional()});var ps=I(`target`,[z({target:L(`local`),path:U().min(1),source:B()}).strict(),z({target:L(`sandbox`),path:U().min(1),sandboxId:U().min(1),source:B()}).strict()]),ms=z({schemaVersion:L(`openpond.profileEvaluationComparison.v1`),id:q,tasksetRelease:G,populationHash:K,environmentHash:K,metricPolicyHash:K,limitsHash:K,members:F(z({runManifest:G,metricResultHash:K,source:Pe,policy:Xe.shape.policy,score:V().min(0).max(1).nullable()}).strict()).min(2).max(100),createdAt:W}).strict().extend({contentHash:K}).strict(),hs=z({profileId:q,sourceRevision:U().trim().min(1).max(240),harnessRelease:G}).strict(),gs=z({kind:H([`run`,`suite`,`comparison`]),id:q,contentHash:K}).strict(),_s=z({schemaVersion:L(`openpond.profileEvaluationReport.v1`),id:q,createdAt:W,testedSources:F(hs).min(1).max(100),tasksetReleases:F(G).min(1).max(100),metricPolicyHashes:F(K).min(1).max(100),modelConfigurationHashes:F(K).min(1).max(100),evidence:F(gs).min(1).max(100),summary:z({totalChecks:V().int().nonnegative(),passedChecks:V().int().nonnegative(),failedChecks:V().int().nonnegative(),unscoredChecks:V().int().nonnegative(),meanScore:V().min(0).max(1).nullable()}).strict()}).strict().superRefine((e,t)=>{let{summary:n}=e;n.passedChecks+n.failedChecks+n.unscoredChecks!==n.totalChecks&&t.addIssue({code:`custom`,path:[`summary`],message:`Report check counts must add up.`}),new Set(e.evidence.map(({kind:e,id:t})=>`${e}:${t}`)).size!==e.evidence.length&&t.addIssue({code:`custom`,path:[`evidence`],message:`Report evidence must be unique.`})}).safeExtend({contentHash:K}),vs=z({schemaVersion:L(`openpond.profileEvaluationSuiteRun.v1`),id:q,suiteId:q,suiteHash:K,catalogHash:K,profileId:q,sourceRevision:U().trim().min(1).max(240),harnessRelease:G,members:F(z({definitionId:q,runManifest:G,runHash:K,passed:B(),score:V().min(0).max(1).nullable()}).strict()).min(1).max(1e3),passed:B(),createdAt:W,completedAt:W}).strict().extend({contentHash:K}).strict(),ys=z({schemaVersion:L(`openpond.optimizerTrainingSample.v1`),tokenIds:F(V().int().nonnegative()).min(2).max(32768),mask:F(B()).min(2).max(32768),logprobs:F(V().finite()).min(2).max(32768),temperatures:F(V().positive().finite()).min(2).max(32768),envName:U().trim().min(1).max(200),modelRequestId:U().trim().min(1).max(1e3),promptTokenCount:V().int().positive(),completionTokenCount:V().int().positive(),servedPolicyVersion:V().int().nonnegative()}).strict().superRefine((e,t)=>{let n=e.tokenIds.length;for(let[r,i]of[[`mask`,e.mask],[`logprobs`,e.logprobs],[`temperatures`,e.temperatures]])i.length!==n&&t.addIssue({code:`custom`,path:[r],message:`${r} must align with tokenIds`});e.promptTokenCount+e.completionTokenCount!==n&&t.addIssue({code:`custom`,path:[`completionTokenCount`],message:`prompt and completion token counts must span tokenIds`}),e.mask.filter(e=>!e).length!==e.promptTokenCount&&t.addIssue({code:`custom`,path:[`mask`],message:`promptTokenCount must equal the non-trainable mask count`}),e.mask.filter(Boolean).length!==e.completionTokenCount&&t.addIssue({code:`custom`,path:[`mask`],message:`completionTokenCount must equal the trainable mask count`})}),bs=z({id:q,environmentRelease:G,status:H([`completed`,`failed`,`timed_out`,`cancelled`]),startedAt:W,completedAt:W,traceRefs:F(ae).max(1e4),metadata:re}).strict(),xs=z({receiptRef:G,status:Ir,value:V().min(0).max(1).nullable(),learningEligible:B(),passed:B(),outcomeClass:kr,failureOwner:Br.nullable(),components:R(q,V().min(0).max(1).nullable())}).strict(),Ss=z({schemaVersion:L(`openpond.canonicalRolloutRecord.v1`),id:q,attemptRef:G,artifactManifestRef:G,tasksetRelease:G,environmentRelease:G,verifierSetRelease:G,harnessRelease:G,taskId:q,split:Me,model:se,seed:U().trim().min(1).max(500),reward:xs,traceRef:ae,optimizerSample:ys.nullable(),environmentExecutions:F(bs).min(1).max(1e5),startedAt:W,completedAt:W,metadata:re}).strict();function Cs(e,t){e.reward.status===`scored`&&(e.reward.value===null||!e.reward.learningEligible)&&t.addIssue({code:`custom`,path:[`reward`,`status`],message:`A scored rollout requires a numeric, learning-eligible reward.`}),e.reward.status===`unscorable`&&(e.reward.value!==null||e.reward.learningEligible)&&t.addIssue({code:`custom`,path:[`reward`,`status`],message:`An unscorable rollout has no reward and cannot be learning-eligible.`})}Ss.superRefine(Cs),z({...Ss.shape,contentHash:K}).strict().superRefine(Cs);var ws=U().trim().min(1).max(200),Ts=z({operationId:ws,request:tt,maximumCostUsd:V().finite().positive().max(1e4),graders:F(Ze).min(1).max(100).optional(),sourceExperimentId:ws.optional()}).strict().superRefine((e,t)=>{e.request.name||t.addIssue({code:`custom`,path:[`request`,`name`],message:`Name this Experiment before starting it.`}),e.operationId!==e.request.operationId&&t.addIssue({code:`custom`,path:[`request`,`operationId`],message:`Use one operation identity for this Experiment.`}),Math.round(e.maximumCostUsd*1e6)<1&&t.addIssue({code:`custom`,path:[`maximumCostUsd`],message:`The spending cap must be at least $0.000001.`}),e.graders&&new Set(e.graders.map(e=>e.id)).size!==e.graders.length&&t.addIssue({code:`custom`,path:[`graders`],message:`Select each grader once.`})}),Es=U().trim().min(1).max(200),Ds=U().regex(/^[a-f0-9]{64}$/),Os=z({id:Es,contentHash:Ds}).strict(),ks=z({available:B(),reason:U().max(1e3).nullable(),origin:be.nullable()}).strict(),As=z({schemaVersion:L(`openpond.postTrainingAttachment.v1`),binding:z({kind:H([`preparation`,`policy`]),id:Es,revision:V().int().positive(),contentHash:Ds}).strict(),projectId:Es.nullable(),automatic:B(),maximumSpendUsd:V().finite().positive().max(1e4),experiments:F(z({id:Es,configuration:Ts}).strict()).min(1).max(20),acceptancePlan:on.nullable()}).strict().superRefine((e,t)=>{if(new Set(e.experiments.map(e=>e.id)).size!==e.experiments.length&&t.addIssue({code:`custom`,message:`Attach each evaluation once.`}),e.experiments.reduce((e,t)=>e+t.configuration.maximumCostUsd,0)>e.maximumSpendUsd+1e-9&&t.addIssue({code:`custom`,message:`Attached evaluation budgets exceed the total approved budget.`}),e.experiments.some(t=>(t.configuration.request.project?.id??null)!==e.projectId)&&t.addIssue({code:`custom`,message:`Attached experiments must use the training Project.`}),e.acceptancePlan){let n=new Set(e.acceptancePlan.checks.map(e=>e.id));e.acceptancePlan.checks.some(t=>!e.experiments.some(e=>e.id===t.id))&&t.addIssue({code:`custom`,message:`Select the frozen Experiment for each acceptance check.`}),e.acceptancePlan.maximumSpendUsd+e.experiments.filter(e=>!n.has(e.id)).reduce((e,t)=>e+t.configuration.maximumCostUsd,0)>e.maximumSpendUsd+1e-9&&t.addIssue({code:`custom`,message:`Paired acceptance and diagnostic ceilings exceed the approved evaluation budget.`})}});function js(e){let{modelId:t,candidate:n,...r}=e.request.policy.kind===`fixture`?{modelId:null,candidate:null,...e.request.policy}:e.request.policy;return`modelConfigurationHash`in r&&delete r.modelConfigurationHash,{dataset:{id:e.request.taskset.id,contentHash:e.request.taskset.contentHash},populationHash:je(e.request.population.map(e=>({caseId:e.taskId,seed:e.seed,fixtureId:e.fixtureId}))),executionHash:je({settings:r,graders:e.graders??null})}}var Ms=z({baseline:Os,checks:F(z({id:Es,sourceRunId:Es,sourceManifestHash:Ds,targetConfigurationHash:Ds,executionHash:Ds,populationHash:Ds,evaluator:Os,feedbackKey:Es,output:H([`boolean`,`score`]),unit:U().min(1).max(80)}).strict()).min(1).max(100)}).strict(),Ns=H([`waiting_for_training`,`ready`,`preparing`,`queued`,`running`,`cleaning`,`completed`,`failed`,`blocked`,`cancelled`,`budget_exhausted`]),Ps=z({schemaVersion:L(`openpond.postTrainingSummary.v1`),id:Es,teamId:Es,jobId:Es,revision:V().int().positive(),planHash:Ds,automatic:B(),candidate:Os.nullable(),state:Ns,total:V().int().positive(),completed:V().int().nonnegative(),failed:V().int().nonnegative(),requiredOutcome:H([`none`,`pending`,`passed`,`failed`,`blocked`]),reason:U().max(500).nullable(),groupId:Es.nullable(),experimentIds:F(Es).max(20),updatedAt:N()}).strict().superRefine((e,t)=>{e.completed+e.failed>e.total&&t.addIssue({code:`custom`,message:`Evaluation totals are inconsistent.`}),[`preparing`,`queued`,`running`,`cleaning`,`completed`].includes(e.state)&&!e.candidate&&t.addIssue({code:`custom`,message:`Evaluation execution requires the exact trained candidate.`})}),Fs=z({operationId:Es,expectedRevision:V().int().positive(),planHash:Ds}).strict();z({operationId:Es,attachment:As}).strict(),z({id:Es,teamId:Es,ownerUserId:Es,attachment:As,qualification:Ms.nullable(),contentHash:Ds,createdAt:N()}).strict();function Is(e){return!!(e&&[`preparing`,`queued`,`running`,`cleaning`].includes(e.state))}var Ls=z({teamId:Es,actorId:Es,projectId:Es.nullable(),configuration:Fr,batches:F(Ee).max(1e4),sources:F(Ae).max(1e4),definitions:F(Ve).max(1e4),experiments:F(z({id:Es,name:U().max(500),configuration:Ts,graders:F(z({feedbackKey:Es,name:U().max(500),ref:Os}).strict()).max(100)}).strict()).max(1e4)}).strict();H([`hardware-catalog`,`gpu-catalog`,`modification-capabilities`,`estimate`,`funding`,`funding-handoff`,`list-drafts`,`get-draft`,`save-draft`,`archive-draft`,`prepare`,`prepare-draft`,`save-experiment-learning`,`review-dataset`,`start`,`cancel`,`publish`,`attach`]);var Rs=z({teamId:Es,actorId:Es,configuration:Fr,policy:Oe,inspection:dt,iterations:F(z({iteration:Ie,evals:Ps.nullable()}).strict()).max(100),nextCursor:Es.nullable()}).strict(),zs=z({id:Es,expectedRevision:V().int().positive(),policyHash:Ds,operationId:Es,action:H([`pause`,`resume`,`reserve`,`cancel-iteration`,`retry-iteration`]),iterationId:Es.optional(),iterationRevision:V().int().positive().optional()}).strict(),Bs=H([`trajectory`,`reward`,`demonstration`,`preference`,`correction`,`critique`,`targeted_feedback`,`grader_evidence`,`infrastructure_failure`]),Vs=z({datasetRelease:G,harnessRelease:G,evidenceSetRelease:G.nullable(),profileRelease:G.nullable(),model:z({source:U().trim().min(1).max(200),revision:U().trim().min(1).max(500),artifactHash:K.nullable()}).strict(),environmentHash:K,graderHash:K,toolContractHash:K,verificationReceiptHash:K.nullable()}).strict(),Hs=z({schemaVersion:L(`openpond.learningSignal.v1`),id:q,taskId:q.nullable(),episodeId:q.nullable(),policyVersion:V().int().nonnegative().nullable(),lineage:Vs,approved:B(),verifier:H([`deterministic`,`model_judge`,`human`,`none`]),createdAt:W,contentHash:K,metadata:R(U(),P()).default({})}).strict(),Us=Hs.extend({kind:L(`trajectory`),payload:z({traceRef:U().trim().min(1).max(2e3),traceHash:K,terminal:B(),failureClass:H([`policy_failure`,`grader_failure`,`environment_failure`,`infrastructure_failure`,`timeout`,`cancelled`]).nullable(),optimizerSample:ys.nullable().optional()}).strict()}).strict(),Ws=Hs.extend({kind:L(`reward`),payload:z({reward:V().finite(),components:R(U(),V().finite()),eligible:B(),graderEvidenceRefs:F(q).max(1e3)}).strict()}).strict(),Gs=Hs.extend({kind:L(`demonstration`),payload:z({prompt:U().max(5e5),response:U().max(1e6)}).strict()}).strict(),Ks=Hs.extend({kind:L(`preference`),payload:z({prompt:U().max(5e5),chosen:U().max(1e6),rejected:U().max(1e6),rationale:U().max(5e5).nullable()}).strict()}).strict(),qs=Hs.extend({kind:L(`correction`),payload:z({original:U().max(1e6),corrected:U().max(1e6),rationale:U().max(5e5).nullable()}).strict()}).strict(),Js=Hs.extend({kind:L(`critique`),payload:z({response:U().max(1e6),critique:U().max(5e5),severity:H([`note`,`warning`,`error`])}).strict()}).strict(),Ys=Hs.extend({kind:L(`targeted_feedback`),payload:z({turnIndex:V().int().nonnegative(),target:H([`reasoning`,`tool`,`answer`,`policy`]),feedback:U().max(5e5)}).strict()}).strict(),Xs=Hs.extend({kind:L(`grader_evidence`),payload:z({graderId:q,score:V().finite().nullable(),passed:B(),privilegedArtifactRefs:F(U().trim().min(1).max(2e3))}).strict()}).strict(),Zs=Hs.extend({kind:L(`infrastructure_failure`),approved:L(!1),verifier:L(`none`),payload:z({code:q,phase:q,retryable:B(),rewardEligible:L(!1)}).strict()}).strict(),Qs=I(`kind`,[Us,Ws,Gs,Ks,qs,Js,Ys,Xs,Zs]);z({schemaVersion:L(`openpond.learningSignalBatch.v1`),manifestId:q,manifestHash:K,sequence:V().int().nonnegative(),signals:F(Qs).min(1).max(1e5),contentHash:K}).strict();var $s=z({schemaVersion:L(`openpond.trainingEngineCapabilities.v1`),adapterId:q,available:B(),methods:F(U().trim().min(1).max(100)),signalKinds:F(Bs),modelFamilies:F(U().trim().min(1).max(200)),precisions:F(H([`fp32`,`fp16`,`bf16`,`tf32`,`int8`,`int4`])),topologies:F(U().trim().min(1).max(200)),workerProtocolVersion:U().trim().min(1).max(200),upstreamRevision:U().trim().min(1).max(500),workerImageDigest:U().regex(/^sha256:[a-f0-9]{64}$/).nullable().default(null),capabilityReceipt:K,checkedAt:W,unavailableReason:U().trim().min(1).max(5e3).nullable()}).strict(),ec=z({schemaVersion:L(`openpond.computeTargetCapabilities.v1`),adapterId:q,kind:H([`local`,`ssh`,`managed`,`custom`]),provider:q.nullable(),available:B(),devices:F(z({id:q,kind:H([`cpu`,`gpu`,`accelerator`]),vendor:U().trim().min(1).max(200),name:U().trim().min(1).max(500),memoryBytes:V().int().nonnegative().nullable(),runtime:U().trim().min(1).max(200)}).strict()),supportsWorkerImages:B(),supportsArtifactTransfer:B(),supportsCancellation:B(),capabilityReceipt:K,checkedAt:W,unavailableReason:U().trim().min(1).max(5e3).nullable()}).strict(),tc=z({schemaVersion:L(`openpond.harnessRuntimeCapabilities.v1`),adapterId:q,available:B(),placements:F(H([`local`,`remote`,`colocated`,`provider_native`])),lifecycle:F(H([`create`,`reset`,`step`,`grade`,`collect`,`destroy`])),deterministicReplay:B(),privilegedIsolation:B(),capabilityReceipt:K,checkedAt:W,unavailableReason:U().trim().min(1).max(5e3).nullable()}).strict();z({schemaVersion:L(`openpond.resolvedTrainingPlan.v1`),manifest:Qo,recipe:mo,runtime:Bo,compute:qo,engine:No,execution:z({trainingPlanId:q,approvalId:q}).strict().nullable(),maximumSpendUsd:V().nonnegative().nullable(),approvalHash:K,contentHash:K}).strict().superRefine((e,t)=>{let n=[[`runtime`,e.runtime,e.manifest.runtimeTarget],[`compute`,e.compute,e.manifest.computeTarget],[`engine`,e.engine,e.manifest.engine]];for(let[e,r,i]of n)JSON.stringify(r)!==JSON.stringify(i)&&t.addIssue({code:`custom`,path:[e],message:`${e} must exactly match the Harness Run Manifest`});e.recipe.method!==e.manifest.recipe.method&&t.addIssue({code:`custom`,path:[`recipe`,`method`],message:`Recipe method must match the Harness Run Manifest`}),e.approvalHash!==e.manifest.approval.approvalHash&&t.addIssue({code:`custom`,path:[`approvalHash`],message:`Approval hash must match the Harness Run Manifest`}),e.maximumSpendUsd!==e.manifest.approval.maximumSpendUsd&&t.addIssue({code:`custom`,path:[`maximumSpendUsd`],message:`Maximum spend must match the Harness Run Manifest`})}),z({schemaVersion:L(`openpond.adapterValidationReceipt.v1`),adapterId:q,valid:B(),issues:F(z({code:q,path:U().trim().max(2e3).nullable(),message:U().trim().min(1).max(5e3)}).strict()),capabilityReceipt:K,planHash:K,createdAt:W,contentHash:K}).strict(),z({runId:q,adapterId:q,protocolVersion:H([`openpond.training.v2`,`adapter.native.v1`]).default(`adapter.native.v1`),routeFamily:H([`training_v2`,`adapter_native`]).default(`adapter_native`),routeId:q.optional(),providerJobId:U().trim().min(1).max(1e3).nullable(),tenantId:q.optional(),leaseId:q.nullable(),manifestHash:K.optional(),inputBundleHash:K.optional(),createdAt:W}).strict(),z({runId:q,state:H([`queued`,`preparing`,`running`,`cancelling`,`cancelled`,`succeeded`,`failed`]),phase:U().trim().min(1).max(200),progress:V().min(0).max(1).nullable(),rolloutProgress:z({groupsCompleted:V().int().nonnegative(),groupsTarget:V().int().nonnegative(),optimizerUpdatesApplied:V().int().nonnegative(),optimizerUpdatesSkipped:V().int().nonnegative()}).strict().optional(),updatedAt:W,errorCode:q.nullable()}).strict(),z({runId:q,manifestHash:K,artifacts:F(z({kind:H([`checkpoint`,`adapter`,`metrics`,`trace`,`evaluation`,`receipt`]),objectRef:U().trim().min(1).max(2e3),sha256:K,sizeBytes:V().int().nonnegative(),metadata:R(U(),P()).optional()}).strict()),contentHash:K}).strict();var nc=H([`ready`,`model_download_required`,`compute_setup_required`,`provider_managed`,`unsupported`]),rc=z({id:q,label:U().trim().min(1).max(500),description:U().trim().min(1).max(2e3),destinationId:q,computeAdapterId:q,runtimeAdapterId:q,engineAdapterId:q,methods:F(U().trim().min(1).max(100)),capabilityPills:F(U().trim().min(1).max(100)),executionMode:H([`local_worker`,`provider_native`]),approvalPolicy:z({providerId:ce,providerLabel:U().trim().min(1).max(200),settingsActionLabel:U().trim().min(1).max(500).nullable(),exportApprovalRequired:B(),exportDescription:U().trim().min(1).max(2e3).nullable(),preparationRequired:B(),minimumSpendUsd:V().nonnegative(),maximumSpendUsd:V().positive(),defaultMaximumSpendUsd:V().positive(),minimumRetentionDays:V().int().positive(),maximumRetentionDays:V().int().positive(),defaultRetentionDays:V().int().positive(),methodRequirement:U().trim().min(1).max(2e3).nullable()}).strict().nullable(),limits:z({maximumSequenceLength:V().int().positive(),maximumOutputTokens:V().int().positive(),maximumTrainingExamples:V().int().positive().nullable()}).strict(),defaults:z({loraRank:V().int().positive(),maxSteps:V().int().positive(),rolloutGroupSize:V().int().min(2).max(32),rolloutConcurrency:V().int().positive().max(32),rolloutOutputTokens:V().int().positive()}).strict(),available:B(),unavailableReason:U().trim().min(1).max(5e3).nullable()}).strict(),ic=z({selectionKey:q,label:U().trim().min(1).max(500),source:H([`local`,`builtin`,`huggingface`,`managed`,`search`]),modelId:U().trim().min(1).max(1e3),revision:U().trim().min(1).max(500).nullable(),tokenizerRevision:U().trim().min(1).max(500).nullable(),chatTemplateHash:K.nullable(),modelAssetId:q.nullable(),expectedBytes:V().int().nonnegative().nullable(),cached:B(),known:B(),searchResolved:B(),computeAdapterIds:F(q),engineAdapterIds:F(q),preparationState:nc,reason:U().trim().min(1).max(5e3).nullable(),compatibilities:F(z({targetId:q,methods:F(U().trim().min(1).max(100)),state:nc,reason:U().trim().min(1).max(5e3).nullable()}).strict())}).strict(),ac=z({schemaVersion:L(`openpond.trainingCatalog.v1`),models:F(ic).max(1e5),engines:F($s),compute:F(ec),runtimes:F(tc),targets:F(rc),generatedAt:W,contentHash:K}).strict();z({schemaVersion:L(`openpond.trainingPreparationPlan.v1`),modelRunId:q,state:nc,reason:U().trim().min(1).max(5e3).nullable(),runtime:Bo.nullable(),compute:qo.nullable(),engine:No.nullable(),downloads:F(z({kind:L(`model`),label:U().trim().min(1).max(500),expectedBytes:V().int().nonnegative(),digest:U().trim().min(8).max(500),cached:B(),state:H([`ready`,`required`,`downloading`,`cancelled`,`failed`]),progress:V().min(0).max(1).nullable(),cancellable:B(),diskImpactBytes:V().int().nonnegative()}).strict()),dataMovement:F(z({direction:H([`upload`,`download`,`none`]),label:U().trim().min(1).max(500),bytes:V().int().nonnegative().nullable()}).strict()),quoteUsd:V().nonnegative().nullable(),maximumSpendUsd:V().nonnegative().nullable(),retentionDays:V().int().nonnegative().nullable(),sideEffectsStarted:L(!1),contentHash:K}).strict();var oc=U().regex(/^[a-f0-9]{64}$/),sc=z({request:tt,maximumCostUsd:V().finite().positive().max(1e4),graders:F(et).min(1).max(100),admissionRequestHash:oc.optional(),sourceExperimentId:U().trim().min(1).max(200).optional()}).strict().extend({configurationHash:oc}).strict();Qe.extend({configuration:sc}).strict();var cc=z({teamId:U().trim().min(1).max(240),items:F(z({name:U().trim().min(1).max(500),source:De,ready:B(),reason:U().min(1).max(2e3).nullable()}).strict()).max(8),nextCursor:U().min(1).max(8192).nullable()}).strict(),lc=U().min(1).max(500),uc=U().regex(/^[a-f0-9]{64}$/),dc=N(),fc=V().finite().nonnegative().nullable(),pc=V().int().nonnegative().nullable(),mc=z({id:lc,sequence:V().int().nonnegative(),at:dc.nullable(),type:U().max(160),action:U().max(160).nullable(),correlationId:lc.nullable(),attempt:pc,taskId:lc.nullable(),status:U().max(100).nullable(),errorCode:U().max(200).nullable(),cleanupComplete:B().nullable()}).strict(),hc=z({id:lc,kind:U().max(100),status:U().max(100),receiptId:lc.nullable(),maximumUsd:fc,settledUsd:fc,model:U().max(200).nullable(),durationMs:pc,inputTokens:pc,outputTokens:pc,totalTokens:pc}).strict(),gc=z({schemaVersion:L(`openpond.runDiagnostics.v1`),teamId:lc,runId:lc,location:H([`local`,`hosted`]),manifestHash:uc,observedAt:dc,status:U().max(100),startedAt:dc.nullable(),completedAt:dc.nullable(),error:U().max(8192).nullable(),resultAvailable:B(),parent:z({id:lc,status:U().max(100),attempt:pc,heartbeatAt:dc.nullable(),leaseExpiresAt:dc.nullable(),releasedAt:dc.nullable(),errorCode:U().max(200).nullable()}).strict().nullable(),accounting:z({maximumUsd:fc,settledUsd:fc,outstandingUsd:fc,outstandingCount:pc,final:B(),receiptCount:pc}).strict(),events:F(mc).max(100),nextEventCursor:V().int().nonnegative().nullable(),eventCount:V().int().nonnegative(),calls:F(hc).max(100),nextCallCursor:lc.nullable(),callCount:V().int().nonnegative(),limitations:F(U().max(1e3)).max(30)}).strict(),_c=gc.extend({contentHash:uc}).strict();z({afterSequence:V().int().nonnegative().optional(),afterCallId:lc.optional()}).strict();function vc(e){let t=gc.parse(e);return{...t,contentHash:je(t)}}function yc(e,t){let n=_c.parse(e),{contentHash:r,...i}=n;if(r!==je(i)||n.teamId!==t.teamId||n.runId!==t.runId||t.manifestHash&&n.manifestHash!==t.manifestHash)throw Error(`Diagnostics differ from the selected workspace, run or retained evidence.`);if(n.events.length>n.eventCount||n.calls.length>n.callCount||new Set(n.events.map(e=>e.id)).size!==n.events.length||n.events.some((e,r)=>e.sequence<=(r?n.events[r-1].sequence:t.afterSequence??-1))||n.calls.some((e,r)=>e.id<=(r?n.calls[r-1].id:t.afterCallId??``))||n.nextEventCursor!==null&&n.nextEventCursor!==n.events.at(-1)?.sequence||n.nextCallCursor!==null&&n.nextCallCursor!==n.calls.at(-1)?.id||n.accounting.final&&(n.accounting.outstandingCount!==0||n.accounting.settledUsd===null||!n.accounting.receiptCount))throw Error(`Diagnostic evidence pagination or final accounting is inconsistent.`);return n}function bc(e){let t=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:{},n=t(e.payload),r=t(n.data),i=(e,t)=>typeof e==`string`&&/^[a-zA-Z0-9_.:/-]+$/.test(e)?e.slice(0,t):null;return mc.parse({id:e.id,sequence:e.sequence,at:e.at,type:e.type.slice(0,160),action:i(n.action,160),correlationId:i(r.callId??r.toolCallId,500),attempt:typeof n.attempt==`number`&&Number.isInteger(n.attempt)&&n.attempt>=0?n.attempt:null,taskId:i(n.taskId??r.taskId,500),status:i(n.status,100),errorCode:i(n.errorCode??n.code,200),cleanupComplete:typeof n.complete==`boolean`&&e.type===`experiment.harness.cleanup`?n.complete:null})}function xc(e){let t=[],n=new Map;for(let r of[...e].sort((e,t)=>e.sequence-t.sequence)){if(r.type.startsWith(`training.`)){t.push({id:r.id,label:r.action??r.type,taskId:r.taskId,startedAt:r.at,completedAt:null,durationMs:null,status:`observed`,evidenceIds:[r.id]});continue}if(![`tool.started`,`tool.completed`,`tool.failed`].includes(r.type))continue;let e=JSON.stringify([r.correlationId??r.action,r.taskId,r.attempt]);if(r.type===`tool.started`){let i={id:r.id,label:r.action??`Operation`,taskId:r.taskId,startedAt:r.at,completedAt:null,durationMs:null,status:`running`,evidenceIds:[r.id]};n.set(e,i),t.push(i)}else{let i=n.get(e);i?(i.completedAt=r.at,i.status=r.type===`tool.failed`?`failed`:`completed`,i.durationMs=i.startedAt&&r.at?Math.max(0,Date.parse(r.at)-Date.parse(i.startedAt)):null,i.evidenceIds.push(r.id),n.delete(e)):t.push({id:r.id,label:r.action??`Operation`,taskId:r.taskId,startedAt:null,completedAt:r.at,durationMs:null,status:r.type===`tool.failed`?`failed`:`completed`,evidenceIds:[r.id]})}}return t}function Sc(e,t=e.events,n=e.calls){let{contentHash:r,...i}=e;return`Investigate this OpenPond run using the retained metadata below. Start read-only. Separate observed facts, hypotheses, missing evidence and recommended investigations. Cite event/call IDs. Do not infer zero costs or successful grading from missing evidence; gateway duration is not pure inference. Do not replay, regrade, edit source, change configuration, restart or deploy without a separate user instruction. Never request credentials or private grader content. This snapshot may be partial.
3
3
 
4
4
  ${JSON.stringify({...i,sourcePageHash:r,error:Cc(e.error),events:t.slice(0,100),calls:n.slice(0,100),analysisCoverage:{eventCount:t.length,callCount:n.length,maximumIncluded:100}},null,2)}`}function Cc(e){return e?e.match(/\b[a-z][a-z0-9]+(?:_[a-z0-9]+){1,12}\b/g)?.slice(0,6).join(` / `)||`Failure recorded. Inspect the authorized run for its exact message.`:null}U().trim().min(1).max(200);var wc=U().trim().min(1).max(500),Tc=U().regex(/^[a-f0-9]{64}$/);z({schemaVersion:L(`openpond.experimentCaseInspection.v1`),teamId:wc,executionId:wc,manifestHash:Tc,receiptId:wc,taskId:wc,seed:U().min(1),input:R(U(),P()).nullable(),output:P().nullable(),error:U().nullable(),events:F(R(U(),P())).max(25),nextEventCursor:wc.nullable(),eventCount:V().int().nonnegative()}).strict().extend({contentHash:Tc}).strict();function Ec(e){return JSON.stringify(e.release?[`reward`,e.release.id,e.release.revision,e.release.contentHash,e.feedbackKey]:[`dataset`,e.id,e.version,e.contentHash,e.feedbackKey])}function Dc(e){let t=new Map;for(let n of e){let e=Ec(n),r=t.get(e);r?r.aliases.push(n):t.set(e,{key:e,grader:n,aliases:[n]})}return[...t.values()]}function Oc(e){let t=Dc(e),n=new Map;for(let e of t){let t=n.get(e.grader.feedbackKey);if(t&&t!==e.key)throw Error(`Different selected grader releases use feedback key "${e.grader.feedbackKey}". Select one, or publish graders with distinct feedback keys.`);n.set(e.grader.feedbackKey,e.key);let r=JSON.stringify(e.grader.mappings??[]);if(e.aliases.some(e=>JSON.stringify(e.mappings??[])!==r))throw Error(`Aliases of grader "${e.grader.feedbackKey}" have different field mappings. Select one alias and review its mappings.`)}return t.map(e=>e.grader)}var kc=U().trim().min(1).max(240),Ac=z({profileRef:z({source:H([`local`,`github`,`openpond_git`]),repositoryId:kc,profileId:kc}).strict(),sourceRevision:U().min(1).max(500),harnessRelease:Ne,catalogHash:U().regex(/^[a-f0-9]{64}$/).nullable(),definitions:F(ze).max(1e3),suites:F(ke).max(100),runs:F(z({profileRef:z({source:H([`local`,`github`,`openpond_git`]),repositoryId:kc,profileId:kc}).strict(),manifest:Xe,metric:Ce,gradeRefs:F(Ne),receiptRefs:F(Ne),passRate:V().min(0).max(1),passed:B(),completedAt:N(),contentHash:U().regex(/^[a-f0-9]{64}$/)}).strict()).max(1e3),comparisons:F(ms).max(1e3),suiteRuns:F(vs).max(1e3),reports:F(_s).max(1e3)}).strict();z({teamId:kc,profileRepositoryId:kc,trainingProjectId:kc.optional()}).strict();var jc=U().trim().min(1).max(200),Mc=U().regex(/^[a-f0-9]{64}$/),Nc=H([`queued`,`running`,`cancelling`,`completed`,`failed`,`cancelled`,`interrupted`]),Pc=z({providerId:H([`openpond`,`custom-openai-compatible`,`claude-code`,`codex`]),modelId:U().trim().min(1).max(500),configurationHash:Mc,maxOutputTokens:V().int().positive().max(262144),temperature:V().min(0).max(2).optional(),topP:V().positive().max(1).optional(),messages:F(z({role:H([`system`,`user`,`assistant`]),content:U().max(262144)}).strict()).max(200)}).strict();z({configuration:nt,package:Ar}).strict(),z({configuration:nt,expectedPackageHash:Mc.optional()}).strict(),z({schemaVersion:L(`openpond.localExperimentDefinition.v1`),location:L(`local`),id:jc,teamId:jc,ownerActorId:jc,revision:V().int().positive(),configuration:nt,model:Pc,packageHash:Mc,graders:F(et).min(1).max(100),availableGraders:F(et).min(1).max(1e3),createdAt:N(),updatedAt:N(),contentHash:Mc}).strict(),z({operationId:jc,definition:at}).strict(),z({teamId:jc,id:jc}).strict(),z({teamId:jc,projectId:jc.optional(),status:Nc.optional(),datasetHash:Mc.optional(),search:U().max(100).optional(),afterId:jc.optional(),limit:V().int().min(1).max(100).default(30)}).strict();var Fc=z({schemaVersion:L(`openpond.localExperimentExecution.v1`),location:L(`local`),id:jc,teamId:jc,ownerActorId:jc,operationId:jc,definition:at,kind:H([`target`,`scoring`]),executionHash:Mc,sourceExecution:z({id:jc,executionHash:Mc}).strict().nullable(),packageHash:Mc,maximumCostUsd:V().finite().positive(),status:Nc,createdAt:N(),completedAt:N().nullable(),counts:z({pending:V().int().nonnegative(),running:V().int().nonnegative(),completed:V().int().nonnegative(),failed:V().int().nonnegative(),cancelled:V().int().nonnegative(),unknown:V().int().nonnegative()}).strict(),usage:z({knownCostUsd:V().finite().nonnegative(),costUsd:V().finite().nonnegative().nullable(),heldUsd:V().finite().nonnegative(),uncertainRequests:V().int().nonnegative()}).strict(),cleanupComplete:B(),error:U().max(2e3).nullable()}).strict(),Ic=Fc.omit({definition:!0});function Lc(e,t){e.kind===`scoring`!=(e.sourceExecution!==null)&&t.addIssue({code:`custom`,message:`Only retained scoring passes name an original execution.`}),[`completed`,`failed`,`cancelled`,`interrupted`].includes(e.status)&&(!e.completedAt||e.counts.pending||e.counts.running)&&t.addIssue({code:`custom`,message:`Terminal local execution requires complete population accounting.`}),[`completed`,`cancelled`].includes(e.status)&&!e.cleanupComplete&&t.addIssue({code:`custom`,message:`Successful completion or cancellation requires confirmed local transport cleanup.`}),e.usage.uncertainRequests>0&&e.usage.costUsd!==null&&t.addIssue({code:`custom`,message:`Uncertain provider charges cannot claim a measured total.`})}Fc.superRefine(Lc);var Rc=Ic.superRefine(Lc);z({configuration:Ts,package:Ar}).strict();var zc=z({configuration:Ts,expectedPackageHash:U().regex(/^[a-f0-9]{64}$/).optional()}).strict(),Bc=z({configuration:Ts,model:Pc,packageHash:U().regex(/^[a-f0-9]{64}$/),graders:F(et).min(1).max(100),availableGraders:F(et).min(1).max(1e3),retainedConfigurationHash:U().regex(/^[a-f0-9]{64}$/).optional(),configurationHash:U().regex(/^[a-f0-9]{64}$/)}).strict().superRefine((e,t)=>{let{configurationHash:n,...r}=e;ie(r)!==n&&t.addIssue({code:`custom`,message:`Local configuration snapshot bytes changed.`})}),{definition:Vc,...Hc}=Fc.shape,Uc=z({...Hc,kind:L(`target`),...Bc.shape}).strict().superRefine((e,t)=>{let n={configuration:e.configuration,model:e.model,packageHash:e.packageHash,graders:e.graders,availableGraders:e.availableGraders,...e.retainedConfigurationHash?{retainedConfigurationHash:e.retainedConfigurationHash}:{},configurationHash:e.configurationHash};Lc(e,t),Bc.safeParse(n).success||t.addIssue({code:`custom`,message:`Local Experiment configuration changed.`}),(e.operationId!==e.configuration.operationId||e.teamId!==e.configuration.request.teamId||e.maximumCostUsd!==e.configuration.maximumCostUsd)&&t.addIssue({code:`custom`,message:`Local Experiment differs from its sealed admission.`})}),Wc=z({items:F(Uc).max(100),nextCursor:U().nullable()}).strict();z({teamId:U().min(1).max(200),id:U().min(1).max(200),configurationHash:U().regex(/^[a-f0-9]{64}$/).optional()}).strict();var Gc=z({operationId:jc,execution:z({id:jc,executionHash:Mc}).strict(),graderPackage:Ar,graders:F(Ze).min(1).max(100),maximumCostUsd:V().finite().positive().max(1e4)}).strict().omit({graderPackage:!0}),Kc=st,qc=z({sessionId:jc,turnId:jc,source:Pe,profileRef:_e,admissionHash:Mc,modelConfigurationHash:Mc,traceHash:Mc,runtimeEventRefs:F(jc).max(1e4),startedAt:N(),completedAt:N(),outputHash:Mc,partialOutputAvailable:B()}).strict(),Jc=z({receiptId:jc,taskId:jc,seed:U(),status:H([`pending`,`running`,`completed`,`failed`,`cancelled`,`unknown`]),input:R(U(),P()),policyVisibleContext:R(U(),P()),output:U().nullable(),messages:F(P()).max(4002),grade:rt.nullable(),error:U().nullable(),native:Kc.optional(),profileNative:qc.optional(),externalProcess:ot.optional()}).strict(),Yc=z({execution:ne([Uc,Rc]),cases:F(Jc).max(1e4),contentHash:Mc}).strict(),Xc=z({items:F(z({sequence:V().int().positive(),type:U().min(1),payload:P()}).strict()).max(500),nextCursor:V().int().positive().nullable()}).strict(),Zc=z({location:L(`local`),execution:ne([Uc,Rc]),case:Jc,trace:Xc}).strict(),Qc=z({items:F(Rc).max(100),nextCursor:jc.nullable()}).strict(),$c=z({execution:Rc,graders:F(et).min(1).max(100),graderPackageHash:Mc}).strict(),el=z({execution:Rc,manifest:Te,result:He}).strict().superRefine((e,t)=>{try{if(ye(e),e.manifest.id!==e.execution.id||e.manifest.teamId!==e.execution.teamId||e.manifest.lineage?.execution.id!==(e.execution.sourceExecution?.id??e.execution.id)||e.manifest.lineage.execution.contentHash!==(e.execution.sourceExecution?.executionHash??e.execution.executionHash)||e.manifest.lineage.scoringPassId!==(e.execution.kind===`scoring`?e.execution.id:null)||e.manifest.maximumCostUsd!==e.execution.maximumCostUsd)throw Error(`Portable evidence differs from its retained local execution.`)}catch(e){t.addIssue({code:`custom`,message:e instanceof Error?e.message:`Local portable evidence verification failed.`})}}),tl=z({location:L(`local`),baseline:el,candidate:el}).strict(),nl=U().trim().min(1).max(240),rl=U().regex(/^[a-f0-9]{64}$/),il=z({location:L(`local`),harnesses:F(z({id:nl,name:U().max(500),source:De}).strict()).max(100),profiles:F(z({id:nl,name:U().max(500),profileRef:_e,sourceRevision:U().min(1).max(500),harnessRelease:z({id:nl,contentHash:rl}).strict(),definitionId:nl,definitionHash:rl,taskset:z({id:nl,revision:V().int().positive(),contentHash:rl}).strict(),taskCount:V().int().nonnegative(),taskIds:F(nl).max(1e4),seeds:F(U()).max(1e4)}).strict()).max(100)}).strict(),al=H(`advanced-refiner-start.experiment-evaluation-schedule.training-result-save.training-steering-result-save.training-engram-result-save.training-model-serving-control.training:prepare-draft.training:control-preparation.training:prepare-modification.training:start-modification.training:cancel-modification.training:prepare-engram.training:start-engram.training:cancel-engram.training:prepare-decision.training:start-decision.training:cancel-decision.training-decision-result-save.training-decision-score.training:prepare-alphaedit.training:start-alphaedit.training:cancel-alphaedit.training-alphaedit-result-save.training:prepare-neuron-training.training:start-neuron-training.training:cancel-neuron-training.training-neuron-training-result-save`.split(`.`)),ol=z({id:te(),action:al,intentHash:U().regex(/^[a-f0-9]{64}$/),createdAt:N(),reviewedIntent:P().nullable(),command:P().nullable(),phase:H([`reviewed`,`dispatching`]).nullable(),recoveryReady:B()}).strict().superRefine((e,t)=>{e.recoveryReady!==(e.reviewedIntent!==null&&e.command!==null&&e.phase!==null)&&t.addIssue({code:`custom`,message:`Only the actual retained intent and command admit automatic recovery.`})}),sl=z({items:F(ol).max(100),nextCursor:te().nullable()}).strict(),cl=U().trim().min(1).max(240),ll=z({draftId:cl,form:Zn,request:z(Rn.shape).omit({operationId:!0}).strict()}).strict().superRefine(({form:e,request:t},n)=>{let r=!t.usageFunding&&e.billingMode!==`actual_usage`&&(e.customerCapUsd===void 0||e.billingMode===`prepaid_only`);if(t.usageFunding)try{r=e.billingMode!==`prepaid_only`&&vt(e.customerCapUsd)===t.usageFunding.customerCapUsd}catch{r=!1}Rn.safeParse({...t,operationId:`reviewed-intent`}).success||n.addIssue({code:`custom`,message:`Retain a complete valid training preparation before journaling its review.`});let i={...e.recipe,dataset:{...e.recipe.dataset&&typeof e.recipe.dataset==`object`?e.recipe.dataset:{},validationSplit:e.validationSplit}};(J(e.baseModel)!==J(t.baseModel)||J(e.parent??null)!==J(t.parent??null)||J(e.batch)!==J(t.batch)||J(e.evaluation)!==J(t.settings.evaluationTasksetRef??null)||J(i)!==J(t.settings.recipe)||J(e.gpuSelection??null)!==J(t.gpuSelection??null)||e.recipe.method!==t.settings.method||e.name.trim()!==t.name||!r||Number(e.budget)!==t.maximumSpendUsd)&&n.addIssue({code:`custom`,message:`The retained form must match its exact reviewed training request.`})}),ul=z({action:H([`start`,`cancel`]),id:U().trim().min(1).max(191),control:lr}).strict(),dl=z({draftId:cl,method:H([`sft`,`grpo`]),preparationOperationId:te(),receipt:Gn,command:ul}).strict().superRefine(({receipt:e,command:t,preparationOperationId:n},r)=>{(e.state!==`prepared`||e.plan.request.operationId!==n||t.id!==e.plan.id||t.control.teamId!==e.plan.request.teamId||t.control.planHash!==e.plan.contentHash||t.control.expectedRevision!==e.revision||t.action===`start`&&t.control.usageQuoteHash!==e.plan.usageQuote?.contentHash||t.action===`start`&&!t.control.estimateReview||t.action===`cancel`&&t.control.estimateReview!==void 0)&&r.addIssue({code:`custom`,message:`Retain the exact prepared revision and reviewed training control.`})}),fl=H([`prepare_evaluation`,`check_graders`,`inspect_results`,`diagnose`,`compare`]),pl=z({id:U(),sessionId:U(),sourceTurnId:U(),action:fl,label:U(),draft:U(),contexts:Uo,focus:T}).strict(),ml=z({teamId:U().trim().min(1).max(240),actorId:U().trim().min(1).max(240),apiOrigin:M().refine(e=>{try{return new URL(e).origin===e&&/^https?:/.test(e)}catch{return!1}})}).strict(),hl=z({account:ml,draftId:U().trim().min(1).max(240),request:Kt.omit({operationId:!0})}).strict().superRefine((e,t)=>{(e.account.teamId!==e.request.teamId||e.request.query.teamId!==e.request.teamId)&&t.addIssue({code:`custom`,message:`Retain the original account and compiled preparation workspace.`})}),gl=z({account:ml,draftId:U().trim().min(1).max(240).nullable(),preparationOperationId:U().trim().min(1).max(240).nullable(),execution:Vt,request:I(`action`,[Dt.omit({operationId:!0}),zn.omit({operationId:!0})])}).strict().superRefine(({account:e,draftId:t,preparationOperationId:n,execution:r,request:i},a)=>{(n===null&&t!==null||e.teamId!==r.teamId||e.actorId!==r.ownerUserId||i.teamId!==e.teamId||i.id!==r.id||i.expectedRevision!==r.revision||i.planHash!==r.plan.contentHash||i.action===`start`&&(r.phase!==`prepared`||i.approvedMaximumSpendUsd!==r.plan.maximumSpendUsd))&&a.addIssue({code:`custom`,message:`Retain the exact creator, execution revision, plan and approved spending cap.`})}),{operationId:_l,...vl}=Pt.shape,yl=z(vl).strict().refine(e=>e.modelProjectId?e.expectedModelRevision>0:e.expectedModelRevision===0,{message:`Retain the exact destination Model revision, or create a new Model.`}),bl=z({account:ml,execution:Vt,request:yl}).strict().superRefine(({account:e,execution:t,request:n},r)=>{(e.actorId!==t.ownerUserId||e.teamId!==t.teamId||n.teamId!==e.teamId||t.method!==`neuron_steering`||t.phase!==`completed`||n.executionId!==t.id)&&r.addIssue({code:`custom`,message:`Retain the exact completed steering result, creator and workspace.`})}),xl=z({account:ml,projectId:U().min(1).max(240).nullable(),executionId:U().min(1).max(240),models:F(Fr).max(1e3)}).strict(),Sl=z({account:ml,draftId:U().trim().min(1).max(240),request:Vn.omit({operationId:!0})}).strict().superRefine((e,t)=>{(e.account.teamId!==e.request.teamId||e.request.query.teamId!==e.request.teamId)&&t.addIssue({code:`custom`,message:`Retain the original account and compiled preparation workspace.`})}),Cl=z({account:ml,draftId:U().trim().min(1).max(240).nullable(),preparationOperationId:U().trim().min(1).max(240).nullable(),execution:xt,request:I(`action`,[gt.omit({operationId:!0}),wt.omit({operationId:!0})])}).strict().superRefine(({account:e,draftId:t,preparationOperationId:n,execution:r,request:i},a)=>{(n===null&&t!==null||e.teamId!==r.teamId||e.actorId!==r.ownerUserId||i.teamId!==e.teamId||i.id!==r.id||i.expectedRevision!==r.revision||i.planHash!==r.plan.contentHash||i.action===`start`&&(r.phase!==`prepared`||i.approvedMaximumSpendUsd!==r.plan.maximumSpendUsd))&&a.addIssue({code:`custom`,message:`Retain the exact creator, execution revision, plan and approved spending cap.`})}),{operationId:wl,...Tl}=jn.shape,El=z(Tl).strict().refine(e=>e.modelProjectId?e.expectedModelRevision>0:e.expectedModelRevision===0,{message:`Retain the exact destination Model revision, or create a new Model.`}),Dl=z({account:ml,execution:xt,request:El}).strict().superRefine(({account:e,execution:t,request:n},r)=>{(e.actorId!==t.ownerUserId||e.teamId!==t.teamId||n.teamId!==e.teamId||t.method!==`engram_adapter`||t.phase!==`completed`||n.executionId!==t.id)&&r.addIssue({code:`custom`,message:`Retain the exact completed Engram result, creator and workspace.`})}),Ol=z({account:ml,projectId:U().min(1).max(240).nullable(),executionId:U().min(1).max(240),models:F(Fr).max(1e3)}).strict(),kl=z({account:ml,draftId:U().trim().min(1).max(240),request:_r.omit({operationId:!0})}).strict().superRefine((e,t)=>{(e.account.teamId!==e.request.teamId||e.request.query.teamId!==e.request.teamId)&&t.addIssue({code:`custom`,message:`Retain the original account and compiled preparation workspace.`})}),Al=z({account:ml,draftId:U().trim().min(1).max(240).nullable(),preparationOperationId:U().trim().min(1).max(240).nullable(),execution:Zt,request:I(`action`,[en.omit({operationId:!0}),br.omit({operationId:!0})])}).strict().superRefine(({account:e,draftId:t,preparationOperationId:n,execution:r,request:i},a)=>{(n===null&&t!==null||e.teamId!==r.teamId||e.actorId!==r.ownerUserId||i.teamId!==e.teamId||i.id!==r.id||i.expectedRevision!==r.revision||i.planHash!==r.plan.contentHash||i.action===`start`&&(r.phase!==`prepared`||i.approvedMaximumSpendUsd!==r.plan.maximumSpendUsd))&&a.addIssue({code:`custom`,message:`Retain the exact creator, execution revision, plan and approved spending cap.`})}),{operationId:jl,...Ml}=sr.shape,Nl=z(Ml).strict().refine(e=>e.modelProjectId?e.expectedModelRevision>0:e.expectedModelRevision===0,{message:`Retain the exact destination Model revision, or create a new Model.`}),Pl=z({account:ml,execution:Zt,request:Nl}).strict().superRefine(({account:e,execution:t,request:n},r)=>{(e.actorId!==t.ownerUserId||e.teamId!==t.teamId||n.teamId!==e.teamId||t.method!==`decision_model`||t.phase!==`completed`||t.mode!==`train`||n.executionId!==t.id)&&r.addIssue({code:`custom`,message:`Retain the exact completed Decision result, creator and workspace.`})}),Fl=z({account:ml,projectId:U().min(1).max(240).nullable(),executionId:U().min(1).max(240),models:F(Fr).max(1e3)}).strict(),Il=z({account:ml,modelProjectId:U().trim().min(1).max(240),request:In.omit({requestId:!0})}).strict().superRefine((e,t)=>{e.account.teamId!==e.request.teamId&&t.addIssue({code:`custom`,message:`Retain the original scoring account and workspace.`})});z({modelProjectId:U().trim().min(1).max(240),request:In}).strict();var Ll=z({account:ml,draftId:U().trim().min(1).max(240),request:Cr.omit({operationId:!0})}).strict().superRefine((e,t)=>{(e.account.teamId!==e.request.teamId||e.request.query.teamId!==e.request.teamId)&&t.addIssue({code:`custom`,message:`Retain the original account and compiled preparation workspace.`})}),Rl=z({account:ml,draftId:U().trim().min(1).max(240).nullable(),preparationOperationId:U().trim().min(1).max(240).nullable(),execution:hn,request:I(`action`,[xn.omit({operationId:!0}),Nn.omit({operationId:!0})])}).strict().superRefine(({account:e,draftId:t,preparationOperationId:n,execution:r,request:i},a)=>{(n===null&&t!==null||e.teamId!==r.teamId||e.actorId!==r.ownerUserId||i.teamId!==e.teamId||i.id!==r.id||i.expectedRevision!==r.revision||i.planHash!==r.plan.contentHash||i.action===`start`&&(r.phase!==`prepared`||i.approvedMaximumSpendUsd!==r.plan.maximumSpendUsd))&&a.addIssue({code:`custom`,message:`Retain the exact creator, execution revision, plan and approved spending cap.`})}),{operationId:zl,...Bl}=ir.shape,Vl=z(Bl).strict().refine(e=>e.modelProjectId?e.expectedModelRevision>0:e.expectedModelRevision===0,{message:`Retain the exact destination Model revision, or create a new Model.`}),Hl=z({account:ml,execution:hn,request:Vl}).strict().superRefine(({account:e,execution:t,request:n},r)=>{(e.actorId!==t.ownerUserId||e.teamId!==t.teamId||n.teamId!==e.teamId||t.method!==`alphaedit`||t.phase!==`completed`||n.executionId!==t.id)&&r.addIssue({code:`custom`,message:`Retain the exact completed AlphaEdit result, creator and workspace.`})}),Ul=z({account:ml,projectId:U().min(1).max(240).nullable(),executionId:U().min(1).max(240),models:F(Fr).max(1e3)}).strict(),Wl=z({account:ml,draftId:U().trim().min(1).max(240),request:Er.omit({operationId:!0})}).strict().superRefine((e,t)=>{(e.account.teamId!==e.request.teamId||e.request.query.teamId!==e.request.teamId)&&t.addIssue({code:`custom`,message:`Retain the original account and compiled preparation workspace.`})}),Gl=z({account:ml,draftId:U().trim().min(1).max(240).nullable(),preparationOperationId:U().trim().min(1).max(240).nullable(),execution:Rt,request:I(`action`,[_t.omit({operationId:!0}),Mt.omit({operationId:!0})])}).strict().superRefine(({account:e,draftId:t,preparationOperationId:n,execution:r,request:i},a)=>{(n===null&&t!==null||e.teamId!==r.teamId||e.actorId!==r.ownerUserId||i.teamId!==e.teamId||i.id!==r.id||i.expectedRevision!==r.revision||i.planHash!==r.plan.contentHash||i.action===`start`&&(r.phase!==`prepared`||i.approvedMaximumSpendUsd!==r.plan.maximumSpendUsd))&&a.addIssue({code:`custom`,message:`Retain the exact creator, execution revision, plan and approved spending cap.`})}),{operationId:Kl,...ql}=kt.shape,Jl=z(ql).strict().refine(e=>e.modelProjectId?e.expectedModelRevision>0:e.expectedModelRevision===0,{message:`Retain the exact destination Model revision, or create a new Model.`}),Yl=z({account:ml,execution:Rt,request:Jl}).strict().superRefine(({account:e,execution:t,request:n},r)=>{(e.actorId!==t.ownerUserId||e.teamId!==t.teamId||n.teamId!==e.teamId||t.method!==`selective_neuron_training`||t.phase!==`completed`||n.executionId!==t.id)&&r.addIssue({code:`custom`,message:`Retain the exact completed NeuronTraining result, creator and workspace.`})}),Xl=z({account:ml,projectId:U().min(1).max(240).nullable(),executionId:U().min(1).max(240),models:F(Fr).max(1e3)}).strict(),Zl=ia(`arrow-down`,[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]),Ql=ia(`arrow-up`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),$l=ia(`at-sign`,[[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}],[`path`,{d:`M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8`,key:`7n84p3`}]]),eu=ia(`badge-check`,[[`path`,{d:`M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z`,key:`3c2336`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),tu=ia(`ban`,[[`path`,{d:`M4.929 4.929 19.07 19.071`,key:`196cmz`}],[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]),nu=ia(`circle-dashed`,[[`path`,{d:`M10.1 2.182a10 10 0 0 1 3.8 0`,key:`5ilxe3`}],[`path`,{d:`M13.9 21.818a10 10 0 0 1-3.8 0`,key:`11zvb9`}],[`path`,{d:`M17.609 3.721a10 10 0 0 1 2.69 2.7`,key:`1iw5b2`}],[`path`,{d:`M2.182 13.9a10 10 0 0 1 0-3.8`,key:`c0bmvh`}],[`path`,{d:`M20.279 17.609a10 10 0 0 1-2.7 2.69`,key:`1ruxm7`}],[`path`,{d:`M21.818 10.1a10 10 0 0 1 0 3.8`,key:`qkgqxc`}],[`path`,{d:`M3.721 6.391a10 10 0 0 1 2.7-2.69`,key:`1mcia2`}],[`path`,{d:`M6.391 20.279a10 10 0 0 1-2.69-2.7`,key:`1fvljs`}]]),ru=ia(`cloud-download`,[[`path`,{d:`M12 13v8l-4-4`,key:`1f5nwf`}],[`path`,{d:`m12 21 4-4`,key:`1lfcce`}],[`path`,{d:`M4.393 15.269A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.436 8.284`,key:`ui1hmy`}]]),iu=ia(`mic`,[[`path`,{d:`M12 19v3`,key:`npa21l`}],[`path`,{d:`M19 10v2a7 7 0 0 1-14 0v-2`,key:`1vc78b`}],[`rect`,{x:`9`,y:`2`,width:`6`,height:`13`,rx:`3`,key:`s6n7sd`}]]),au=ia(`reply`,[[`path`,{d:`M20 18v-2a4 4 0 0 0-4-4H4`,key:`5vmcpk`}],[`path`,{d:`m9 17-5-5 5-5`,key:`nvlc11`}]]),ou=ia(`pencil`,[[`path`,{d:`M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z`,key:`1a8usu`}],[`path`,{d:`m15 5 4 4`,key:`1mk7zo`}]]),su=ia(`target`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`circle`,{cx:`12`,cy:`12`,r:`6`,key:`1vlfrh`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}]]),$=i();function cu(e,t){return{toolCount:e.reduce((e,t)=>e+ +!lu(t),0),toolsExpanded:t,visibleActivities:t?e.filter(e=>!lu(e)):[]}}function lu(e){return e.kind===`reasoning`}function uu(e,t){if(!e||!t)return null;let n=Date.parse(t)-Date.parse(e);if(!Number.isFinite(n)||n<1e3)return null;let r=Math.round(n/1e3);if(r<60)return`${r}s`;let i=Math.floor(r/60),a=r%60;if(i<60)return a>0?`${i}m ${a}s`:`${i}m`;let o=Math.floor(i/60),s=i%60;return s>0?`${o}h ${s}m`:`${o}h`}function du(e){return{id:`message:${e.id}`,type:`message`,message:e,showFooter:e.role===`assistant`&&e.finalAnswer===!0}}function fu(e){return e.flatMap(e=>e.type===`message`?[e.message]:e.type===`work`?e.messages.map(e=>e.message):[])}function pu(e,t={}){let n=[],r=[],i=[],a=[],o=()=>{n.push(...i,...a),i=[],a=[]},s,c,l=e=>{if(r.length===0)return;let t=[],i=()=>{t.length&&(e?n.push({id:`work:${t[0].message.id}`,type:`work`,label:typeof e==`function`?e(t.length):e,messages:t}):n.push(...t),t=[])};for(let e of r)e.message.role===`task_message`?(i(),n.push(e)):t.push(e);i(),r=[]};for(let t of e)if(t.role===`user`)l(t.interactionKind===`steer`?e=>`${e} previous ${e===1?`message`:`messages`}`:void 0),o(),n.push(du(t)),s=t.timestamp,c=t.turnId;else if(c&&t.turnId&&t.turnId!==c&&(l(),o(),s=void 0),c=t.turnId??c,t.role===`visual`)a.push(du(t));else if(t.role===`resources`)i.push(du(t));else if(t.role===`error`||t.userQuestion?.status===`pending`)l(),n.push(du(t));else if(t.role===`assistant`&&t.finalAnswer){t.reasoningContent&&r.push(du({id:`${t.id}:reasoning`,role:`assistant`,timestamp:t.timestamp,turnId:t.turnId,reasoningContent:t.reasoningContent}));let e=uu(t.turnStartedAt??s??r[0]?.message.traceStartedAt??r[0]?.message.timestamp,t.turnCompletedAt??t.timestamp);l(e?`Worked for ${e}`:`Worked`),n.push(du(t.reasoningContent?{...t,reasoningContent:void 0}:t)),s=void 0}else r.push(du(t));return l(),o(),t.showThinkingIndicator&&n.push({id:`thinking`,type:`thinking`}),n}function mu(e){let t=e[e.length-1];if(!t)return!0;if(t.role===`assistant`||t.role===`error`||t.role===`status_divider`&&t.statusState===`running`)return!1;if(t.role===`activity_group`){if(t.traceState===`running`)return!1;let e=t.activities?.[t.activities.length-1]??null;return e?.state!==`running`&&e?.state!==`pending`}return!0}function hu({children:e,className:t=``,controls:n,danger:r=!1,expanded:i=!1,icon:a,onToggle:o,running:s=!1}){let c=[`activity-summary`,o?``:`static`,r?`danger`:``,s?`working`:``,t].filter(Boolean).join(` `),l=(0,$.jsxs)($.Fragment,{children:[a,(0,$.jsx)(`span`,{className:`activity-summary-text`,children:(0,$.jsx)(`span`,{children:e})}),o?(0,$.jsx)(Oa,{"aria-hidden":!0,className:`activity-summary-toggle ${i?`expanded`:``}`,size:14}):null]});return o?(0,$.jsx)(`button`,{type:`button`,"aria-controls":n,"aria-expanded":i,className:c,onClick:o,children:l}):(0,$.jsx)(`div`,{className:c,role:s?`status`:void 0,children:l})}var gu=(0,Q.createContext)(null),_u=(0,Q.createContext)(null),vu=n();async function yu(e,t){let{ownerScope:n}=await Y(e,`/v1/ponder/desktop`);if(!n||[`installationId`,`profileId`,`ownerUserId`,`teamId`].some(e=>n[e]!==t[e]))throw Error(`Open this task on its original desktop, account and workspace.`)}function bu(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.plan!==void 0)return e[t].plan}function xu(e){let t=0;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role===`user`&&r.interactionKind!==`steer`){t=n;break}}let n,r=new Set;for(let i=t;i<e.length;i++){let t=e[i],a=bu(t.activities??[]);a!==void 0&&(n=a,r.add(t.id))}return n?.length?{scopeKey:e[t].id,entries:n,messageIds:r}:null}function Su({entries:e,initiallyExpanded:t=!1}){let[n,r]=(0,Q.useState)(t),i=(0,Q.useId)(),a=e.filter(e=>e.status===`completed`).length,o=e.find(e=>e.status===`in_progress`),s=o??e.find(e=>e.status===`pending`),c=s?(s===o?s.activeForm:null)??s.content:`All tasks completed`;return(0,$.jsxs)(`section`,{className:`activity-plan-card`,"aria-label":`Task progress`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`activity-plan-heading`,"aria-expanded":n,"aria-controls":n?i:void 0,onClick:()=>r(e=>!e),children:[(0,$.jsxs)(`strong`,{className:`activity-plan-title`,title:c,children:[o?(0,$.jsx)(Pa,{"aria-hidden":!0,size:13,className:`activity-plan-spinner`}):s?(0,$.jsx)(nu,{"aria-hidden":!0,size:13}):(0,$.jsx)(Ro,{"aria-hidden":!0,size:13}),(0,$.jsx)(`span`,{children:c})]}),(0,$.jsxs)(`span`,{children:[a,` of `,e.length,` completed`,(0,$.jsx)(Oa,{"aria-hidden":!0,size:13,className:`activity-plan-chevron ${n?`expanded`:``}`})]})]}),n?(0,$.jsx)(`ol`,{id:i,children:e.map((e,t)=>(0,$.jsxs)(`li`,{"data-state":e.status,children:[e.status===`completed`?(0,$.jsx)(Ro,{"aria-hidden":!0,size:13}):e.status===`in_progress`?(0,$.jsx)(Pa,{"aria-hidden":!0,size:13,className:`activity-plan-spinner`}):(0,$.jsx)(nu,{"aria-hidden":!0,size:13}),(0,$.jsxs)(`span`,{children:[(0,$.jsxs)(`span`,{className:`sr-only`,children:[e.status.replace(`_`,` `),`: `]}),e.status===`in_progress`&&e.activeForm?e.activeForm:e.content]})]},e.id??t))}):null]})}var Cu=(0,Q.createContext)(null);function wu({messages:e,enabled:t,conversationKey:n,children:r}){let i=(0,Q.useMemo)(()=>{let r=t?xu(e):null;return r?{...r,scopeKey:`${n}:${r.scopeKey}`}:null},[e,t,n]);return(0,$.jsx)(Cu.Provider,{value:i,children:r})}function Tu(){return(0,Q.useContext)(Cu)}function Eu(){let e=Tu();return e?(0,$.jsx)(`div`,{className:`composer-task-progress`,children:(0,$.jsx)(Su,{entries:e.entries},e.scopeKey)}):null}function Du({artifact:e,onOpenFileInSidebar:t,preview:n}){let[r,i]=(0,Q.useState)(null),a=(0,Q.useCallback)(()=>i(null),[]);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`activity-artifact`,title:e.path,onClick:t?n=>{n.target.closest(`button`)||t(e.path)}:void 0,onContextMenu:t=>{t.preventDefault(),i({path:e.path,title:e.title,...ku(t.clientX,t.clientY)})},children:[t?(0,$.jsxs)(`button`,{"aria-label":`Open ${e.title} in right sidebar`,className:`activity-artifact-name`,type:`button`,onClick:()=>t(e.path),children:[n?(0,$.jsx)(`span`,{className:`activity-artifact-preview`,"aria-hidden":!0,children:n}):(0,$.jsx)(ts,{"aria-hidden":!0,size:14}),(0,$.jsx)(`strong`,{children:e.title})]}):(0,$.jsxs)(`span`,{className:`activity-artifact-name`,children:[(0,$.jsx)(ts,{"aria-hidden":!0,size:14}),(0,$.jsx)(`strong`,{children:e.title})]}),(0,$.jsx)(`span`,{className:`activity-artifact-actions`,children:(0,$.jsx)(`button`,{"aria-label":`Show ${e.title} in file browser`,"data-tooltip":`Open in file browser`,type:`button`,onClick:()=>void ga(e.path),children:(0,$.jsx)(Na,{"aria-hidden":!0,size:14})})})]}),(0,$.jsx)(Ou,{menu:r,onClose:a})]})}function Ou({menu:e,onClose:t}){let n=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{if(!e)return;n.current?.focus();let r=()=>t(),i=e=>{e.key===`Escape`&&r()};return window.addEventListener(`pointerdown`,r),window.addEventListener(`blur`,r),window.addEventListener(`keydown`,i),window.addEventListener(`scroll`,r,!0),()=>{window.removeEventListener(`pointerdown`,r),window.removeEventListener(`blur`,r),window.removeEventListener(`keydown`,i),window.removeEventListener(`scroll`,r,!0)}},[e,t]),!e||typeof document>`u`?null:(0,vu.createPortal)((0,$.jsx)(`div`,{"aria-label":`${e.title} file actions`,className:`activity-artifact-context-menu`,role:`menu`,style:{left:e.x,top:e.y},onPointerDown:e=>e.stopPropagation(),children:(0,$.jsxs)(`button`,{ref:n,role:`menuitem`,type:`button`,onClick:()=>{pa(e.path),t()},children:[(0,$.jsx)(ja,{"aria-hidden":!0,size:14}),(0,$.jsx)(`span`,{children:`Copy path`})]})}),document.body)}function ku(e,t){return{x:Math.max(8,Math.min(e,window.innerWidth-164-8)),y:Math.max(8,Math.min(t,window.innerHeight-42-8))}}function Au(e,t,n){let r=(0,Q.useRef)({sessionId:t,openFile:n});r.current={sessionId:t,openFile:n},(0,Q.useEffect)(()=>e.subscribeLive(e=>{for(let t of e){if(!r.current.sessionId||t.sessionId!==r.current.sessionId||t.name!==`file.preview_requested`||t.source!==`server`)continue;let e=ps.safeParse(t.data);if(!e.success)continue;let n=e.data;r.current.openFile(n.path,n.target===`local`?{source:n.source,local:!0}:{source:n.source,sandboxId:n.sandboxId})}}),[e])}function ju(e){let t=e instanceof Error?e.message:String(e);return{local_ponder_model_unavailable:`Choose a configured model that supports Pal’s coordination tools.`,local_ponder_model_change_requires_idle:`Wait for Pal to finish before changing its model.`,local_ponder_setup_pending:`Finish setup with the previously selected model to recover this conversation.`,local_ponder_configuration_changed:`Pal settings changed. Reopen settings and try again.`,local_ponder_control_changed:`This agent’s control changed. Review its current state and try again.`,local_ponder_agent_not_found:`This agent is no longer available. Refresh Pal’s agents.`}[t]??t}function Mu({busy:e,handoff:t,onDismiss:n,onSelectTask:r}){let i=ns(t),a=t.selectedTaskIndex+1;return(0,$.jsxs)(`section`,{className:`training-chat-handoff`,"aria-label":`Model chat`,children:[(0,$.jsxs)(`div`,{className:`training-chat-handoff-copy`,children:[(0,$.jsx)(`strong`,{children:i?`Generated Taskset question`:`Model chat`}),(0,$.jsx)(`span`,{children:t.tasksetName}),(0,$.jsx)(`small`,{children:i?`${Nu(i.split)} · ${a} of ${t.tasks.length} · New chat per question`:`Ask the imported model directly`})]}),(0,$.jsxs)(`div`,{className:`training-chat-handoff-actions`,children:[i?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,"aria-label":`Previous generated question`,title:`Previous question`,disabled:e||t.selectedTaskIndex===0,onClick:()=>r(t.selectedTaskIndex-1),children:(0,$.jsx)(so,{size:14})}),(0,$.jsx)(`button`,{type:`button`,className:`training-chat-handoff-load`,disabled:e,onClick:()=>r(t.selectedTaskIndex),children:`Load question`}),(0,$.jsx)(`button`,{type:`button`,"aria-label":`Next generated question`,title:`Next question`,disabled:e||t.selectedTaskIndex>=t.tasks.length-1,onClick:()=>r(t.selectedTaskIndex+1),children:(0,$.jsx)(_a,{size:14})})]}):null,(0,$.jsx)(`button`,{type:`button`,"aria-label":`Close generated question handoff`,title:`Close`,disabled:e,onClick:n,children:(0,$.jsx)(Ua,{size:14})})]})]})}function Nu(e){return e===`frozen_eval`?`Frozen evaluation`:e===`validation`?`Validation`:`Training`}function Pu({activeModel:e,activeProvider:t,busy:n,handoff:r,onDismiss:i,onSelectTask:a}){return!r||r.model.providerId!==t||r.model.modelId!==e?null:(0,$.jsx)(Mu,{busy:n,handoff:r,onDismiss:i,onSelectTask:a})}function Fu({canGoNext:e,canGoPrevious:t,onJumpToLatest:n,onNext:r,onPrevious:i}){return(0,$.jsxs)(`div`,{className:`chat-scroll-controls`,"aria-label":`Message navigation`,children:[(0,$.jsx)(`button`,{type:`button`,className:`chat-scroll-control-button`,"data-tooltip":`Go to previous message`,"aria-label":`Go to previous message`,"aria-disabled":!t,onClick:i,children:(0,$.jsx)(so,{size:17})}),(0,$.jsx)(`button`,{type:`button`,className:`chat-scroll-control-button primary`,"data-tooltip":`Jump to latest`,"aria-label":`Jump to latest`,onClick:n,children:(0,$.jsx)(Zl,{size:18})}),(0,$.jsx)(`button`,{type:`button`,className:`chat-scroll-control-button`,"data-tooltip":`Go to next message`,"aria-label":`Go to next message`,"aria-disabled":!e,onClick:r,children:(0,$.jsx)(_a,{size:17})})]})}function Iu({busy:e,onSync:t}){return(0,$.jsxs)(`button`,{type:`button`,className:`sync-local-button`,disabled:e,onClick:t,children:[(0,$.jsx)(ru,{size:15}),(0,$.jsx)(`span`,{children:e?`Syncing locally`:`Sync locally to work on this`})]})}function Lu(e){return e.supportedView&&e.open&&!e.hasContentPanel}function Ru(e,t){return e===`team`?`team-active`:e===`community`?`community-active`:e===`apps`||e===`get-started`||e===`labs`||e===`outputs`||e===`projects`||e===`scheduled`?`page-active`:t?`chat-active`:`chat-start`}var zu=72,Bu=280,Vu=460;function Hu(e){return e.scrollHeight-e.scrollTop-e.clientHeight<=zu}var Uu={canGoPrevious:!1,canGoNext:!1};function Wu(e){return Array.from(e.children).filter(e=>e instanceof HTMLElement&&(e.matches(`.message-row.user`)||e.dataset.chatUserMessage===`true`))}function Gu({activeWorkspaceId:e,cloudProjects:t}){let n=t.find(t=>t.id===e),r=t.find(e=>e.organizationSlug||e.teamId),i=n??r??null;return{organizationSlug:i?.organizationSlug??null,teamId:i?.teamId??null}}function Ku(e,t){return t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop}function qu(e,t){return Ku(e,t)+t.getBoundingClientRect().height}function Ju(e){return e.scrollTop+24}function Yu(e){return e.scrollTop+8}function Xu(e){let t=Ju(e),n=Yu(e),r=!1,i=!1;for(let a of Wu(e)){let o=Ku(e,a);if(qu(e,a)<n&&(r=!0),o>t+8&&(i=!0),r&&i)break}return{canGoPrevious:r,canGoNext:i}}function Zu(e,t){let n=Wu(e),r=Ju(e);if(t===`previous`){let t=Yu(e);for(let r=n.length-1;r>=0;--r){let i=n[r];if(qu(e,i)<t)return i}return null}for(let t of n)if(Ku(e,t)>r+8)return t;return null}function Qu(e){return Math.min(Vu,Math.max(Bu,Math.abs(e)/5))}function $u(e){return e<.5?4*e*e*e:1-(-2*e+2)**3/2}function ed(e){let t=Zi({messages:e});return t?{run:t}:null}function td(e){return e.command===`workflow`?[`Create a scheduled workflow attached to this chat.`,`Use the schedule_work tool after resolving the exact cadence, local date/time, and timezone from my request. Ask a concise clarification only if a required scheduling detail is genuinely missing.`,`Workflow request: ${e.args}`].join(`
5
5
 
6
- `):e.command===`agent`?e.args?`/agent ${e.args}`:`/agent`:e.command===`skill`?e.args?`/skill ${e.args}`:`/skill`:e.args?`/${e.command} ${e.args}`:`/${e.command}`}function nd(e,t){return{surface:`chat`,workflowKind:`slash_command`,commandName:`/${e.command}`,commandSource:t}}function rd(e){return e.command===`goal`||e.command===`agent`||e.command===`skill`||e.command===`workflow`||e.command===`sync-cloud`}function id(e){let t=e?.trim()??``;return/^[a-z0-9]{24}$/.test(t)?t:null}function ad(e,t){if(!t.row.isConnected||t.row.parentElement!==e)return null;let n=Number.parseFloat(e.style.getPropertyValue(`--chat-sent-message-space`))||0,r=Number.parseFloat(getComputedStyle(e).paddingBottom)-n,i=e.lastElementChild,a=i?i.getBoundingClientRect().bottom-t.row.getBoundingClientRect().top+r:r,o=Math.max(0,e.clientHeight-96-a);return Math.abs(o-n)>.5&&e.style.setProperty(`--chat-sent-message-space`,`${o}px`),Math.max(0,Ku(e,t.row)-96)}function od(e,t,n){let r=e=>{e.deltaY<0?t():e.deltaY>0&&n?.()},i=null,a=e=>{i=e.touches[0]?.clientY??null},o=e=>{let r=e.touches[0]?.clientY??null;r!==null&&i!==null&&r>i?t():r!==null&&i!==null&&r<i&&n?.(),i=r},s=e=>{e.target?.closest?.(`input, textarea, select, [contenteditable='true']`)||([`ArrowUp`,`PageUp`,`Home`].includes(e.key)||e.key===` `&&e.shiftKey?t():([`ArrowDown`,`PageDown`,`End`].includes(e.key)||e.key===` `&&!e.shiftKey)&&n?.())},c=n=>{if(n.target!==e)return;let r=e.getBoundingClientRect().left+e.clientLeft+e.clientWidth;n.clientX>=r&&t()};return e.addEventListener(`openpond-visual-interaction`,t),e.addEventListener(`wheel`,r,{passive:!0}),e.addEventListener(`touchstart`,a,{passive:!0}),e.addEventListener(`touchmove`,o,{passive:!0}),e.addEventListener(`keydown`,s),e.addEventListener(`pointerdown`,c),()=>{e.removeEventListener(`openpond-visual-interaction`,t),e.removeEventListener(`wheel`,r),e.removeEventListener(`touchstart`,a),e.removeEventListener(`touchmove`,o),e.removeEventListener(`keydown`,s),e.removeEventListener(`pointerdown`,c)}}function sd(e){let t=e.getBoundingClientRect().top;for(let n of Array.from(e.children)){let e=n.getBoundingClientRect();if(!(e.bottom<=t))return{row:n,offset:e.top-t}}return null}function cd(e,t){if(t.row.parentElement!==e)return;let n=t.row.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=n-t.offset}function ld(e){let{contentKey:t,threadElement:n=null,enabled:r=!0,onContentChange:i,threadRef:a}=e,o=(0,Q.useRef)(i),s=(0,Q.useRef)(null);o.current=i,(0,Q.useLayoutEffect)(()=>{let e=n??a.current;if(!r||!e||typeof window>`u`)return;let t=null,i=0,c=e.scrollHeight,l=(n=!0)=>{n&&(i=Math.max(i,4)),t===null&&(t=window.requestAnimationFrame(()=>{t=null,a.current===e&&o.current(e);let n=Math.abs(e.scrollHeight-c)>1;c=e.scrollHeight,--i,(i>0||n)&&l(!1)}))};s.current=()=>l();let u=typeof MutationObserver>`u`?null:new MutationObserver(()=>{p(),l()}),d=typeof ResizeObserver>`u`?null:new ResizeObserver(()=>l()),f=new Set,p=()=>{if(!d)return;let t=new Set(Array.from(e.children).filter(e=>e instanceof HTMLElement));for(let e of f)t.has(e)||(d.unobserve(e),f.delete(e));for(let e of t)f.has(e)||(d.observe(e),f.add(e))};u?.observe(e,{childList:!0,characterData:!0,subtree:!0}),p();let m=()=>l();return e.addEventListener(`load`,m,!0),()=>{s.current=null,u?.disconnect(),d?.disconnect(),e.removeEventListener(`load`,m,!0),t!==null&&window.cancelAnimationFrame(t)}},[r,n,a]),(0,Q.useLayoutEffect)(()=>{r&&s.current?.()},[t,r])}function ud({navigationVersion:e=0,browserConversationId:t,chatSubmissionVersion:n,chatHistoryHasMore:r,chatHistoryLoading:i,chatMessages:a,onLoadMoreChatHistory:o,pendingApproval:s,showChatThread:c,showThinkingIndicator:l,turnRunning:u,view:d}){let f=(0,Q.useRef)(null),[p,m]=(0,Q.useState)(null),h=(0,Q.useCallback)(e=>{f.current=e,m(t=>t===e?t:e)},[]),g=(0,Q.useRef)(null),_=(0,Q.useRef)(!0),v=(0,Q.useRef)(null),y=(0,Q.useRef)(!1),b=(0,Q.useRef)(0),x=(0,Q.useRef)(null),S=(0,Q.useRef)(0),C=(0,Q.useRef)(0),w=(0,Q.useRef)(0),T=(0,Q.useRef)(null),E=(0,Q.useRef)(null),D=(0,Q.useRef)(null),O=(0,Q.useRef)(!1),[k,A]=(0,Q.useState)(0),j=(0,Q.useRef)(!1),M=(0,Q.useRef)(!1),N=(0,Q.useRef)(null),P=(0,Q.useRef)(null),F=(0,Q.useRef)(null),[I,L]=(0,Q.useState)(0),[ee,R]=(0,Q.useState)(null),[z,B]=(0,Q.useState)(!1),[V,H]=(0,Q.useState)(132),[U,te]=(0,Q.useState)(Uu),ne=(0,Q.useMemo)(()=>pu(a,{showThinkingIndicator:l}),[a,l]),re=(0,Q.useMemo)(()=>({"--chat-composer-reserve":`${V}px`}),[V]),W=a.at(-1),ie=[ne.length,W?.id??``,W?.content?.length??0,W?.timestamp??``,JSON.stringify(W?.resources??[]),l?`thinking`:``].join(`:`),G=r,ae=t,K=d===`chat`&&c&&!!ae&&ee!==ae,q=(0,Q.useCallback)(e=>{B(t=>t===e?t:e)},[]),oe=(0,Q.useCallback)(e=>{te(t=>t.canGoPrevious===e.canGoPrevious&&t.canGoNext===e.canGoNext?t:e)},[]),se=(0,Q.useCallback)((e,t={})=>{let n=t.nearBottom??Hu(e);q(!n),oe(Xu(e))},[q,oe]),ce=(0,Q.useCallback)(e=>{let t=j.current;j.current=!1,R(e),q(!1),oe(Uu),t&&L(e=>e+1)},[q,oe]),le=(0,Q.useCallback)(()=>{F.current!==null&&typeof window<`u`&&(window.cancelAnimationFrame(F.current),F.current=null)},[]),ue=(0,Q.useCallback)((e,t,n)=>{le();let r=Math.max(0,e.scrollHeight-e.clientHeight),i=()=>{let n=typeof t==`function`?t():t;return Math.max(0,Math.min(n,Math.max(0,e.scrollHeight-e.clientHeight)))},a=Math.max(0,Math.min(i(),r)),o=e.scrollTop,s=a-o;if(typeof window>`u`||window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches===!0||Math.abs(s)<1){e.scrollTop=a,n?.();return}let c=Qu(s),l=window.performance.now(),u=t=>{if(f.current!==e){F.current=null;return}let r=Math.min(1,(t-l)/c),a=i();e.scrollTop=o+(a-o)*$u(r),r<1?F.current=window.requestAnimationFrame(u):(e.scrollTop=i(),F.current=null,n?.())};F.current=window.requestAnimationFrame(u)},[le]),de=(0,Q.useCallback)(()=>{M.current=!1,N.current!==null&&typeof window<`u`&&(window.cancelAnimationFrame(N.current),N.current=null)},[]),fe=(0,Q.useCallback)(()=>{P.current!==null&&typeof window<`u`&&(window.cancelAnimationFrame(P.current),P.current=null)},[]),pe=(0,Q.useCallback)(e=>{if(typeof window>`u`){e.scrollTop=e.scrollHeight;return}if(P.current!==null)return;let t=window.performance.now(),n=r=>{if(f.current!==e||!_.current){P.current=null;return}let i=Math.max(0,e.scrollHeight-e.clientHeight),a=i-e.scrollTop;if(Math.abs(a)<=1)e.scrollTop=i,P.current=null;else{if(a<0||a>240)e.scrollTop=i;else{let n=Math.max(.5,Math.min(3,(r-t)/(1e3/60))),i=1-.78**n;e.scrollTop+=Math.min(a,Math.max(1,Math.min(36*n,a*i)))}t=r,P.current=window.requestAnimationFrame(n)}};P.current=window.requestAnimationFrame(n)},[]),me=(0,Q.useCallback)((e,t={})=>{if(fe(),e.scrollTop=e.scrollHeight,typeof window>`u`){t.finishInitial&&ce(t.conversationKey??null);return}de(),M.current=!0;let n=0,r=0,i=e.scrollHeight,a=t.settle?12:2,o=()=>{let e=f.current;if(!e){N.current=null,M.current=!1,t.finishInitial&&ce(t.conversationKey??null);return}e.scrollTop=e.scrollHeight;let s=e.scrollHeight-e.scrollTop-e.clientHeight,c=Math.abs(e.scrollHeight-i)<=1;i=e.scrollHeight,r=s<=1&&c?r+1:0,n+=1,n<a&&r<2?N.current=window.requestAnimationFrame(o):(N.current=null,M.current=!1,_.current=!0,q(!1),oe(Xu(e)),t.finishInitial&&ce(t.conversationKey??null))};N.current=window.requestAnimationFrame(o)},[de,fe,ce,q,oe]),he=(0,Q.useCallback)(()=>{v.current=null,f.current?.style.removeProperty(`--chat-sent-message-space`);let e=f.current;e&&(de(),fe(),_.current=!0,q(!1),ue(e,()=>e.scrollHeight-e.clientHeight,()=>{f.current===e&&(e.scrollTop=e.scrollHeight,_.current=!0,q(!1),oe(Xu(e)))}))},[de,fe,q,oe,ue]),ge=(0,Q.useCallback)(e=>{v.current=null,e.style.removeProperty(`--chat-sent-message-space`),le(),_.current=!0,me(e,{settle:!0}),se(e,{nearBottom:!0})},[le,me,se]),_e=(0,Q.useCallback)(e=>{let t=f.current;if(!t)return;let n=Zu(t,e);n&&(de(),fe(),v.current&&(v.current.following=!1),ue(t,()=>n.isConnected?Math.max(0,Ku(t,n)-24):t.scrollTop,()=>{if(f.current!==t)return;let e=Hu(t);_.current=e,se(t,{nearBottom:e})}))},[de,fe,ue,se]),ve=(0,Q.useCallback)(async()=>{if(!G||!o||i||D.current)return;let e=f.current;if(!e)return;let t={anchor:sd(e),firstRowId:ne[0]?.id,settled:!1};E.current=t,_.current=!1,de(),fe(),le(),D.current=t,O.current=!1;try{let e=await o();D.current===t&&(O.current=!e),!e&&E.current===t&&(E.current=null)}catch{D.current===t&&(O.current=!0,E.current=null)}finally{t.settled=!0,D.current===t&&(D.current=null,A(e=>e+1))}},[G,i,o,ne,de,fe,le]),ye=(0,Q.useCallback)(e=>{let t=E.current;t&&(t.anchor=sd(e));let n=Hu(e),r=Math.abs(e.scrollHeight-C.current)>1||Math.abs(e.clientHeight-w.current)>1,a=e.scrollTop<S.current-1,o=e.scrollTop>S.current+1,s=n&&o&&(!r||e.scrollHeight-e.scrollTop-e.clientHeight<=1);if(S.current=e.scrollTop,C.current=e.scrollHeight,w.current=e.clientHeight,v.current)!v.current.following&&s?ge(e):(_.current=!1,se(e));else if(M.current){if(a&&!r)de(),ce(T.current),_.current=!1,se(e,{nearBottom:!1});else{_.current=!0,q(!1),oe(Uu);return}}else n&&(_.current||s)?(_.current=!0,se(e,{nearBottom:!0})):a&&!r?(_.current=!1,fe(),se(e,{nearBottom:!1})):_.current?(q(!1),oe(Xu(e))):se(e,{nearBottom:n});!j.current&&e.scrollTop<=120&&G&&!i&&ve()},[G,de,fe,ce,i,ve,ge,q,oe,se]),be=(0,Q.useCallback)(e=>{let t=v.current;if(t){let n=ad(e,t);if(n!==null&&t.following&&F.current===null){if(e.scrollHeight-e.clientHeight>n+1){ge(e);return}e.scrollTop=n}se(e)}else _.current&&F.current===null&&!M.current&&pe(e)},[pe,ge,se]);return(0,Q.useEffect)(()=>{let e=p;if(!e)return;let t=null,n=()=>{t!==null&&window.cancelAnimationFrame(t),t=null},r=()=>{n(),v.current&&(v.current.following=!1),_.current=!1,S.current=e.scrollTop,C.current=e.scrollHeight,w.current=e.clientHeight,de(),fe(),le(),j.current&&ce(T.current)},i=()=>{v.current&&r()},a=e=>{[`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `].includes(e.key)&&i()},o=()=>{n();let r=Hu(e),i=T.current;t=window.requestAnimationFrame(()=>{t=null,f.current===e&&T.current===i&&(r||Hu(e))&&(!_.current||v.current)&&ge(e)})};e.addEventListener(`wheel`,i,{passive:!0}),e.addEventListener(`touchmove`,i,{passive:!0}),e.addEventListener(`pointerdown`,i),e.addEventListener(`keydown`,a);let s=od(e,r,o);return()=>{n(),s(),e.removeEventListener(`wheel`,i),e.removeEventListener(`touchmove`,i),e.removeEventListener(`pointerdown`,i),e.removeEventListener(`keydown`,a)}},[p,de,fe,le,ce,ge]),(0,Q.useEffect)(()=>{if(!p||typeof ResizeObserver>`u`)return;let e=new ResizeObserver(()=>{v.current&&be(p)});return e.observe(p),()=>e.disconnect()},[p,be]),ld({contentKey:ie,enabled:d===`chat`&&c,onContentChange:be,threadElement:p,threadRef:f}),(0,Q.useLayoutEffect)(()=>{if(d!==`chat`||!c||typeof window>`u`)return;let e=g.current;if(!e)return;let t=null,n=()=>{t=null;let n=Math.max(0,Math.ceil(e.getBoundingClientRect().height));H(e=>e===n?e:n)},r=()=>{t===null&&(t=window.requestAnimationFrame(n))};n();let i=window.ResizeObserver===void 0?null:new window.ResizeObserver(r);return i?.observe(e),window.addEventListener(`resize`,r),()=>{t!==null&&window.cancelAnimationFrame(t),i?.disconnect(),window.removeEventListener(`resize`,r)}},[c,d]),(0,Q.useLayoutEffect)(()=>{let e=f.current;d===`chat`&&c&&e&&!j.current&&(v.current?be(e):_.current&&me(e,{settle:!0}))},[V,be,me,c,d]),(0,Q.useLayoutEffect)(()=>{v.current=null,y.current=!1,f.current?.style.removeProperty(`--chat-sent-message-space`),E.current=null,D.current=null,O.current=!1,j.current=!0,_.current=!0,S.current=0,C.current=0,w.current=0,fe(),le(),de(),R(null),q(!1),oe(Uu)},[de,le,fe,ae,e,q,oe]),(0,Q.useLayoutEffect)(()=>{if(n===0||n===b.current||d!==`chat`||!c)return;let e=f.current,t=e?Wu(e).at(-1):void 0;if(!e||!t||t===x.current)return;b.current=n,de(),fe();let r={row:t,following:!0};v.current=r,_.current=!1,ad(e,r),ue(e,()=>ad(e,r)??e.scrollTop,()=>be(e)),ce(ae)},[n,ne,p,ae,d,c,de,fe,ue,ce,be]),(0,Q.useLayoutEffect)(()=>{let e=f.current;x.current=e?Wu(e).at(-1)??null:null}),(0,Q.useLayoutEffect)(()=>{if(u){y.current=!0;return}let e=a.length-1;for(;e>=0&&a[e]?.role!==`user`;)e--;let t=a.slice(e+1).some(e=>e.role===`assistant`&&e.finalAnswer);if(!y.current&&!t)return;y.current=!1;let n=f.current,r=v.current;n&&r&&(v.current=null,n.style.removeProperty(`--chat-sent-message-space`),le(),_.current=r.following,r.following&&me(n,{settle:!0}),se(n))},[a,u,le,me,se]),(0,Q.useEffect)(()=>{let e=f.current;d!==`chat`||!e||j.current||!G||i||O.current||e.scrollTop<=120&&ve()},[G,i,I,k,ne.length,ve,d]),(0,Q.useLayoutEffect)(()=>{let e=E.current,t=f.current;e&&t&&!j.current&&(ne[0]?.id===e.firstRowId?e.settled&&!i&&(E.current=null):(E.current=null,e.anchor&&cd(t,e.anchor),se(t)))},[ne,i,se]),(0,Q.useLayoutEffect)(()=>{let e=f.current;if(d!==`chat`||!ae){T.current=ae,_.current=!0,ce(ae);return}if(!e)return;let t=T.current!==ae;if(i&&(t||j.current))return;if(T.current=ae,v.current){ce(ae);return}if(t||j.current){_.current=!0,me(e,{conversationKey:ae,finishInitial:!0,settle:!0});return}let n=Hu(e);_.current?(_.current=!0,q(!1),oe(Xu(e)),me(e,{settle:!0})):se(e,{nearBottom:n})},[ae,e,i,p,ce,s?.id,me,q,oe,se,d]),(0,Q.useEffect)(()=>()=>{de(),le(),fe()},[de,le,fe]),{chatColumnStyle:re,chatThreadPreparingInitialScroll:K,chatThreadRef:h,composerStackRef:g,goToUserMessage:_e,handleChatScroll:ye,jumpToLatestChatMessage:he,showScrollToBottomButton:z,userMessageNavigation:U,chatTimelineRows:ne}}var dd=(0,Q.lazy)(()=>o(()=>import(`./MainChatThread-DNMfrrRq.js`).then(e=>({default:e.MainChatThread})),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67])));function fd({scroll:e,thread:t,composer:n,composerPrefix:r,hasApproval:i=!1,className:a=``}){let o=ud(e);return(0,$.jsx)(wu,{conversationKey:e.browserConversationId??`draft`,messages:e.chatMessages,enabled:!!n&&e.turnRunning,children:(0,$.jsxs)(`div`,{className:`chat-column ${i?`has-approval`:``} ${a}`,style:o.chatColumnStyle,children:[(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(dd,{...t,rows:o.chatTimelineRows,threadRef:o.chatThreadRef,onScroll:e=>o.handleChatScroll(e.currentTarget),sessionId:e.browserConversationId,conversationKey:e.browserConversationId??`draft`,turnRunning:e.turnRunning})}),(0,$.jsxs)(`div`,{className:`composer-stack dock ${i?`has-approval`:``}`,ref:o.composerStackRef,children:[r,o.showScrollToBottomButton&&!o.chatThreadPreparingInitialScroll?(0,$.jsx)(Fu,{canGoNext:o.userMessageNavigation.canGoNext,canGoPrevious:o.userMessageNavigation.canGoPrevious,onJumpToLatest:o.jumpToLatestChatMessage,onNext:()=>{o.userMessageNavigation.canGoNext&&o.goToUserMessage(`next`)},onPrevious:()=>{o.userMessageNavigation.canGoPrevious&&o.goToUserMessage(`previous`)}}):null,n]})]})})}function pd({connection:e,conversationId:t,messages:n,loading:r,running:i,hasMore:a=!1,loadOlder:o,children:s,usageSessionId:c=t}){return(0,$.jsx)(fd,{className:`ponder-agent-conversation`,scroll:{browserConversationId:t,chatSubmissionVersion:0,chatMessages:n,chatHistoryHasMore:a,chatHistoryLoading:r,onLoadMoreChatHistory:o,pendingApproval:null,showChatThread:!0,showThinkingIndicator:i,turnRunning:i,view:`chat`},thread:{connection:e,usageSessionId:c,label:`Agent conversation`,loading:r,afterMessages:s}})}var md=Object.freeze({events:[],messages:[]}),hd=class{projection=md;project(e){if(e===this.projection.events)return this.projection.messages;if(!vd(this.projection.events,e))return this.replace(e);let t=e.slice(this.projection.events.length);if(t.length===0)return this.projection={events:e,messages:this.projection.messages},this.projection.messages;let n=gd(this.projection.messages,t);if(n)return this.projection={events:e,messages:n},n;let r=_d(e,this.projection.events.length);if(!r)return this.replace(e);let i=e.slice(r.eventIndex),a=new Set(i.flatMap(e=>e.turnId?[e.turnId]:[])),o=this.projection.messages.filter(e=>!e.turnId||!a.has(e.turnId)),s=oo(i),c=new Set(o.map(e=>e.id));if(s.some(e=>c.has(e.id)))return this.replace(e);let l=[...o,...s];return this.projection={events:e,messages:l},l}reset(){this.projection=md}snapshot(){return this.projection}replace(e){let t=oo(e);return this.projection={events:e,messages:t},t}};function gd(e,t){if(t.length===0||e.length===0)return null;let n=e[e.length-1];if(n?.role!==`assistant`||n.createImproveRun||t.some(e=>e.name!==`assistant.delta`&&e.name!==`assistant.reasoning.delta`||typeof io(e.data)?.nativeMessageId==`string`||e.turnId!==n.turnId||!e.output))return null;let r=n.content,i=n.reasoningContent,a=n.timestamp,o=!1,s=!1;for(let e of t)e.name===`assistant.delta`?(r=`${r??``}${e.output}`,o=!0):(i=`${i??``}${e.output}`,s=!0),a=e.timestamp;let c={...n,...o?{content:r}:{},...s?{reasoningContent:i}:{},timestamp:a};return[...e.slice(0,-1),c]}function _d(e,t){let n=e[t];if(!n?.turnId)return null;let r=e.findIndex(e=>e.turnId===n.turnId);return r<0?null:{eventIndex:r}}function vd(e,t){return e.length===0?!0:e.length>=t.length?!1:e[0]===t[0]&&e[e.length-1]===t[e.length-1]}function yd(e,t){let n=new Map(e.events.map(e=>[e.id,e]));for(let e of t)n.set(e.id,e);let r=[...n.values()].sort((e,t)=>(e.sequence??0)-(t.sequence??0));return{...e,events:r,cursor:Math.max(e.cursor,...t.map(e=>e.sequence??0))}}function bd(e){return{events:e.events.map(e=>({...e.event,sequence:e.sequence})),cursor:e.nextSequence,before:e.previousSequence,hasMore:e.hasMore}}var xd=[];function Sd(e,t){let n=u(),r=ra(e),i=(0,Q.useMemo)(()=>[`ponder-history`,r,t],[r,t]),a=(0,Q.useRef)(new hd),o=S({queryKey:i,enabled:!!t,staleTime:1/0,gcTime:6e5,queryFn:async()=>bd(await Eo.runtimeEventsPage(e,{sessionId:t,beforeSequence:2**53-1,limit:200}))}),[s,c]=(0,Q.useState)(null),l=!!o.data;(0,Q.useEffect)(()=>{if(!t||!l)return;let r=n.getQueryData(i);if(!r)return;let a=xo(e,e=>{e.sessionId===t&&n.setQueryData(i,t=>t&&yd(t,[e]))},()=>{},void 0,{afterSequence:r.cursor,fetchImpl:(e,n)=>{let r=new URL(String(e));return r.searchParams.set(`sessionId`,t),fetch(r,n)}});return()=>a.close()},[e,t,l,i,n]);async function d(){let r=n.getQueryData(i);if(!t||!r?.hasMore||s?.key===i&&s.loading)return!1;c({key:i,loading:!0,error:null});try{let a=bd(await Eo.runtimeEventsPage(e,{sessionId:t,beforeSequence:r.before,limit:200}));return n.setQueryData(i,e=>e&&{...yd(e,a.events),before:a.before,hasMore:a.hasMore}),c({key:i,loading:!1,error:null}),a.events.length>0}catch(e){return c({key:i,loading:!1,error:e instanceof Error?e.message:String(e)}),!1}}let f=o.data?.events??xd,p=(0,Q.useMemo)(()=>a.current.project(f),[f]),m=[...f].reverse().find(e=>[`turn.started`,`turn.completed`,`turn.failed`,`turn.interrupted`].includes(e.name));return{events:f,messages:p,error:s?.key===i&&s.error?s.error:o.error?.message??null,loading:!!t&&o.isPending||s?.key===i&&s.loading===!0,hasMore:o.data?.hasMore??!1,loadOlder:d,running:m?.name===`turn.started`}}var Cd=[];function wd(e,t){let n=t?.id.startsWith(`codex_history_`)===!0,r=t?.metadata?.nativeHistoryId,i=n||typeof r==`string`,a=Sd(e,i?null:t?.id??null),[o,s]=(0,Q.useState)({sessionId:t?.id,limit:500}),c=o.sessionId===t?.id?o.limit:500,l=(0,Q.useRef)(new hd),u=S({queryKey:[`native-agent-transcript`,ra(e),t?.id,c],enabled:!!(t&&i),staleTime:2e3,gcTime:6e5,refetchInterval:3e3,queryFn:async()=>{if(n){let n=await Eo.codexHistoryThread(e,t.id,{limit:c,tail:!0});return{events:n.events,hasMore:n.events.length>=c}}await Y(e,`/v1/native-history/open`,{method:`POST`,body:JSON.stringify({id:r})});let i=[],a=2**53-1,o=!1;do{let n=await Eo.runtimeEventsPage(e,{sessionId:t.id,beforeSequence:a,limit:Math.min(200,c-i.length)});if(i.unshift(...n.events.map(e=>e.event)),o=n.hasMore,!o||n.previousSequence===a)break;a=n.previousSequence}while(i.length<c);return{events:i,hasMore:o}}}),d=u.data?.events??Cd,f=(0,Q.useMemo)(()=>l.current.project(d),[d]),p=[...d].reverse().find(e=>[`turn.started`,`turn.completed`,`turn.failed`,`turn.interrupted`].includes(e.name));return i?{events:d,messages:f,error:u.error?.message??null,loading:u.isPending,hasMore:u.data?.hasMore??!1,loadOlder:async()=>{s({sessionId:t?.id,limit:c+500})},running:p?.name===`turn.started`}:a}function Td(e,t){let n={turnId:e.remoteTurnId??e.id,timestamp:``,source:`provider`},r=[{...n,id:`${e.id}:prompt`,name:`turn.started`,timestamp:e.createdAt,args:{prompt:e.assignment}}];for(let e of t)if(e.type===`assistant.delta`||e.type===`assistant.reasoning.delta`)e.text&&r.push({...n,id:e.id,name:e.type,output:e.text});else if([`tool.started`,`tool.completed`,`tool.failed`].includes(e.type)){let t=/^([A-Za-z][A-Za-z0-9_.:-]{0,95}): (?:started|completed|failed|updated)$/.exec(e.text??``)?.[1];r.push({...n,id:e.id,name:e.type===`tool.started`?`tool.started`:`tool.completed`,action:t??`tool`,status:e.type===`tool.started`?`started`:e.type===`tool.failed`?`failed`:`completed`})}let i=[`completed`,`failed`,`cancelled`].includes(e.state),a=e.resultText?.trim();if(i&&a){let t=-1,i=-1;for(let e=0;e<r.length;e++)r[e].name===`assistant.delta`&&(t=e),(r[e].name===`tool.started`||r[e].name===`tool.completed`)&&(i=e);let o=t;for(;o>0&&r[o-1]?.name===`assistant.delta`;)o--;let s=t<0?``:r.slice(o,t+1).map(e=>e.output??``).join(``);t>=0&&(t>i||s.trim()===a)?r.splice(o,t-o+1,{...n,id:r[o].id,name:`assistant.delta`,output:a,timestamp:``}):r.push({...n,id:`${e.id}:result`,name:`assistant.delta`,output:a,timestamp:``})}return i&&r.push({...n,id:`${e.id}:terminal`,name:e.state===`failed`?`turn.failed`:e.state===`cancelled`?`turn.interrupted`:`turn.completed`,timestamp:``,...e.error?{error:e.error}:{}}),oo(r)}function Ed({connection:e,accountScopeKey:t,assignmentId:n,output:r}){let i=u(),a=JSON.stringify([ra(e),t,n]),o=(0,Q.useRef)(a);o.current=a;let[s,c]=(0,Q.useState)(!1),[l,d]=(0,Q.useState)(null);(0,Q.useEffect)(()=>(o.current=a,c(!1),d(null),()=>{o.current=null}),[a]),Ka(l);async function f(l){if(s)return;let u=a,f=window.open(`about:blank`,`_blank`);f&&(f.opener=null),c(!0),d(null);try{let a=await i.fetchQuery({queryKey:[`ponder-hosted-output`,ra(e),t,n,r.id],staleTime:0,gcTime:6e4,queryFn:({signal:t})=>Y(e,`/v1/ponder/local/hosted-agents/${encodeURIComponent(n)}/outputs/${encodeURIComponent(r.id)}`,{signal:t})});if(o.current!==u){f?.close();return}let s=l===`preview`?a.previewURL:a.downloadURL,c=s?no(s):null;if(!c)throw Error(l===`preview`?`This output is not available for preview.`:`This output is not available for download.`);f?f.location.replace(c):window.location.assign(c)}catch(e){f?.close(),o.current===u&&d(e instanceof Error?e.message:String(e))}finally{o.current===u&&c(!1)}}return(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`strong`,{children:r.name}),r.previewURL?(0,$.jsx)(`button`,{type:`button`,disabled:s,onClick:()=>void f(`preview`),children:`Preview`}):null,(0,$.jsx)(`button`,{type:`button`,disabled:s,"aria-label":`Download ${r.name}`,onClick:()=>void f(`download`),children:s?`Preparing…`:`Download`})]})}var Dd={preparing:`Preparing`,submitting:`Submitting`,running:`Working`,completed:`Completed`,needs_attention:`Needs attention`,failed:`Failed`,cancelled:`Cancelled`,unknown:`Status unknown`};function Od(e){try{return`Hosted sandbox · ${new URL(e.account.apiBaseUrl).host}`}catch{return`Hosted sandbox`}}function kd(e){if(typeof e==`string`)return e;if(e&&typeof e==`object`&&!Array.isArray(e)){let t=e;for(let e of[`label`,`title`,`text`,`name`,`value`])if(typeof t[e]==`string`)return t[e]}return JSON.stringify(e)??String(e)}function Ad({connection:e,accountScopeKey:t,assignment:n}){let r=u(),i=ra(e),a=[`ponder-hosted-agent`,i,t,n.id],o=`/v1/ponder/local/hosted-agents/${encodeURIComponent(n.id)}`,s=S({queryKey:a,staleTime:2e3,gcTime:6e5,refetchInterval:e=>[`completed`,`failed`,`cancelled`].includes(e.state.data?.assignment.state??``)?3e4:3e3,queryFn:({signal:t})=>Y(e,o,{signal:t})}),c=ds({mutationFn:()=>Y(e,`${o}/cancel`,{method:`POST`,body:`{}`}),onSuccess:e=>{r.setQueryData(a,e),r.invalidateQueries({queryKey:[`ponder-hosted-agents`,i]})},onError:()=>{s.refetch()}});Ka(s.error),Ka(c.error);let l=s.data?.assignment??n,d=(0,Q.useMemo)(()=>Td(l,s.data?.events??[]),[l,s.data?.events]),f=[`preparing`,`submitting`,`running`].includes(l.state);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`ponder-agent-assignment`,children:[(0,$.jsxs)(`span`,{children:[Od(l),` · `,Dd[l.state]]}),l.wait?(0,$.jsxs)(`div`,{className:`ponder-hosted-wait`,children:[(0,$.jsx)(`strong`,{children:l.wait.title}),(0,$.jsx)(`span`,{children:`This hosted assignment is waiting in its Work environment.`}),l.wait.options.length?(0,$.jsxs)(`dl`,{children:[(0,$.jsx)(`dt`,{children:`Recorded response options`}),l.wait.options.map((e,t)=>(0,$.jsx)(`dd`,{children:kd(e)},t))]}):null]}):null,l.canCancel?(0,$.jsx)(`button`,{type:`button`,disabled:c.isPending,onClick:()=>c.mutate(),children:`Cancel assignment`}):null]}),(0,$.jsxs)(pd,{connection:e,usageSessionId:null,conversationId:`hosted:${l.id}`,messages:d,loading:s.isPending,running:f,children:[!s.data&&!s.isPending?(0,$.jsx)(`button`,{type:`button`,onClick:()=>void s.refetch(),children:`Retry loading conversation`}):null,s.data?.outputs.length?(0,$.jsxs)(`section`,{className:`ponder-hosted-outputs`,"aria-label":`Assignment outputs`,children:[(0,$.jsx)(`h3`,{children:`Outputs`}),s.data.outputs.map(n=>(0,$.jsx)(Ed,{connection:e,accountScopeKey:t,assignmentId:l.id,output:n},`${t}:${l.id}:${n.id}`))]}):null]})]})}function jd({connection:e,accountScopeKey:t,agents:n,hostedAgents:r=[],onControl:i,onOpenChat:a,selectionRequest:o}){let[s,c]=(0,Q.useState)(null);(0,Q.useLayoutEffect)(()=>{o&&c({kind:`local`,id:o.sessionId})},[o]);let l=(0,Q.useRef)(null),u=(0,Q.useRef)(new Map),d=(0,Q.useRef)(null),f=(0,Q.useRef)(s);(0,Q.useLayoutEffect)(()=>{s?l.current?.focus():f.current&&u.current.get(`${f.current.kind}:${f.current.id}`)?.focus(),f.current=s},[s]),(0,Q.useLayoutEffect)(()=>{let e=d.current;d.current=null,!s&&e&&document.activeElement===document.body&&u.current.get(e)?.focus()});function p(e,t){t?u.current.set(e,t):(u.current.get(e)===document.activeElement&&(d.current=e),u.current.delete(e))}let m=s?.kind===`local`?n.find(e=>e.session.id===s.id):void 0,h=s?.kind===`hosted`?r.find(e=>e.id===s.id):void 0,g=wd(e,m?.session);Ka(g.error);let[_,v]=(0,Q.useState)(!1),[y,b]=(0,Q.useState)(null);Ka(y);async function x(e,t){v(!0);try{await i(e,t),b(null)}catch(e){b(ju(e))}finally{v(!1)}}async function S(e){v(!0);try{await a(e.session.id),b(null)}catch(e){b(ju(e))}finally{v(!1)}}function C(e){return[`working`,`queued`,`preparing`,`submitting`,`running`].includes(e)?`Active`:[`failed`,`waiting_approval`,`waiting`,`paused`,`interrupted`,`unknown`,`needs_attention`].includes(e)?`Needs attention`:`Done`}return(0,$.jsxs)(`section`,{className:`ponder-agents-view`,"aria-label":`Pal agents`,children:[(0,$.jsxs)(`header`,{children:[m||h?(0,$.jsx)(`button`,{ref:l,type:`button`,"aria-label":`Back to agents`,onClick:()=>c(null),children:(0,$.jsx)(so,{size:16})}):null,(0,$.jsx)(`h2`,{children:h?.title??m?.session.title??`Agents`})]}),h?(0,$.jsx)(Ad,{connection:e,accountScopeKey:t,assignment:h}):m?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`ponder-agent-assignment`,children:[m.session.metadata?.nativeWorkerCanResume===!1?(0,$.jsx)(`span`,{children:`Controlled by its parent conversation · Read-only transcript`}):null,m.owner?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{children:m.owner===`user`?`You are directing this agent`:`Pal is directing this agent`}),(0,$.jsx)(`button`,{type:`button`,disabled:_,onClick:()=>void x(m,m.owner===`ponder`?`user`:`ponder`),children:m.owner===`ponder`?`Take control`:`Return to Pal`})]}):(0,$.jsx)(`button`,{type:`button`,disabled:_,onClick:()=>void S(m),children:m.session.metadata?.nativeWorkerCanResume===!1?`Open transcript`:`Open chat`})]}),(0,$.jsx)(pd,{connection:e,conversationId:m.session.id,messages:g.messages,loading:g.loading,running:g.running,hasMore:g.hasMore,loadOlder:async()=>await g.loadOlder()!==!1})]}):(0,$.jsx)(`div`,{className:`ponder-agent-list`,children:n.length||r.length?[`Active`,`Needs attention`,`Done`].map(e=>{let t=n.filter(t=>C(t.status)===e),i=r.filter(t=>C(t.state)===e);return t.length||i.length?(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h3`,{children:e}),t.map(e=>(0,$.jsxs)(`div`,{className:`ponder-agent-row`,children:[(0,$.jsxs)(`button`,{ref:t=>p(`local:${e.session.id}`,t),type:`button`,onClick:()=>c({kind:`local`,id:e.session.id}),children:[(0,$.jsx)(Ho,{session:e.session}),(0,$.jsxs)(`span`,{children:[e.session.title,e.latestActivity||e.assignment!==e.session.title?(0,$.jsx)(`small`,{children:e.latestActivity??e.assignment}):null]})]}),e.owner?(0,$.jsx)(`button`,{type:`button`,disabled:_,onClick:()=>void x(e,e.owner===`ponder`?`user`:`ponder`),children:e.owner===`ponder`?`Take control`:`Return`}):(0,$.jsx)(`button`,{type:`button`,disabled:_,onClick:()=>void S(e),children:e.session.metadata?.nativeWorkerCanResume===!1?`Open transcript`:`Open chat`})]},e.session.id)),i.map(e=>(0,$.jsxs)(`div`,{className:`ponder-agent-row`,children:[(0,$.jsxs)(`button`,{ref:t=>p(`hosted:${e.id}`,t),type:`button`,onClick:()=>c({kind:`hosted`,id:e.id}),children:[(0,$.jsx)(Yo,{size:16}),(0,$.jsxs)(`span`,{children:[e.title,(0,$.jsxs)(`small`,{children:[Od(e),` · `,Dd[e.state]]})]})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>c({kind:`hosted`,id:e.id}),children:`Open conversation`})]},`hosted:${e.id}`))]},e):null}):null})]})}function Md({connection:e,ponder:t,accountScopeKey:n,parentSessionId:r,sessions:i,onOpenChat:a,selectionRequest:o}){let[s,c]=(0,Q.useState)([]),[l,u]=(0,Q.useState)(null);Ka(l),(0,Q.useEffect)(()=>{if(c([]),u(null),!t)return;let n=!0,r=!1;async function i(){if(!r){r=!0;try{let t=await Y(e,`/v1/ponder/local/agents`);n&&(c(t.items),u(null))}catch(e){n&&u(ju(e))}finally{r=!1}}}i();let a=window.setInterval(()=>void i(),3e3);return()=>{n=!1,window.clearInterval(a)}},[e,t,n]);let d=S({queryKey:[`ponder-hosted-agents`,ra(e),n],enabled:t,staleTime:2e3,refetchInterval:t?5e3:!1,queryFn:({signal:t})=>Y(e,`/v1/ponder/local/hosted-agents`,{signal:t})});Ka(d.error);let f=A({queryKey:[`native-agent-children`,ra(e),n,r],enabled:!(t||!r),staleTime:2e3,refetchInterval:3e3,initialPageParam:{},queryFn:({pageParam:t})=>Y(e,`/v1/native-history/children`,{method:`POST`,body:JSON.stringify({parentSessionId:r,...t})}),getNextPageParam:e=>e.beforeOffset===null?e.cursors&&Object.keys(e.cursors).length?{cursors:e.cursors}:void 0:{beforeOffset:e.beforeOffset}});Ka(f.error);let p=new Map(i.map(e=>[e.id,e]));for(let e of f.data?.pages??[])for(let t of e.items)p.set(t.id,t);let m=t?s:[...p.values()].filter(e=>r&&e.parentSessionId===r).map(e=>({session:e,status:e.status===`active`?`working`:e.status===`failed`?`failed`:`idle`,assignment:e.title,latestActivity:null}));async function h(t,n){let r=s.find(e=>e.session.id===t.session.id);if(!r)throw Error(`This agent has no Pal control relationship.`);let i=await Y(e,`/v1/ponder/local/agents/${encodeURIComponent(t.session.id)}/control`,{method:`POST`,body:JSON.stringify({owner:n,revision:r.revision})});c(e=>e.map(e=>e.session.id===i.session.id?i:e)),n===`user`&&await a(t.session.id)}async function g(t){let n=m.find(e=>e.session.id===t)?.session;if(n?.metadata?.nativeWorker&&n.hiddenFromDefaultSidebar){let n=`/v1/sessions/${encodeURIComponent(t)}`;await Y(e,n,{method:`PATCH`,body:JSON.stringify({hiddenFromDefaultSidebar:!1})})}await a(t)}return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(jd,{selectionRequest:o,connection:e,accountScopeKey:n,agents:m,hostedAgents:t?d.data?.items??[]:[],onControl:h,onOpenChat:g},t?`ponder:${n}`:r),!t&&f.hasNextPage?(0,$.jsx)(`button`,{type:`button`,disabled:f.isFetchingNextPage,onClick:()=>void f.fetchNextPage(),children:`Load earlier agents`}):null]})}function Nd({connection:e,sessionId:t,accountScope:n,active:r,onOpen:i}){let a=k(r?e:null,t,n);return(0,Q.useEffect)(()=>{let e=e=>{let n=e.detail;r&&n?.sessionId===t&&n.scope===a.scope&&i()};return window.addEventListener(j,e),()=>window.removeEventListener(j,e)},[r,t,a.scope,i]),a.selection?.target.kind===`dataset`?`Experiment draft`:a.selection?.model?.name??a.selection?.label??`Ponder`}function Pd(e){let[t,n]=(0,Q.useState)({tabs:[],activeId:null});(0,Q.useEffect)(()=>{n({tabs:[],activeId:null})},[e]),(0,Q.useEffect)(()=>window.openpond?.browser?.onRevealRequest?.(t=>{t.conversationId===e&&n(e=>({...e,activeId:null}))}),[e]);let r=(0,Q.useCallback)(e=>{n(t=>({tabs:t.tabs.some(t=>t.publicationId===e.publicationId)?t.tabs:[...t.tabs,e],activeId:e.publicationId}))},[]),i=(0,Q.useCallback)(e=>{n(t=>{let n=t.tabs.findIndex(t=>t.publicationId===e),r=t.tabs.filter(t=>t.publicationId!==e);return{tabs:r,activeId:t.activeId===e?r[Math.min(n,r.length-1)]?.publicationId??null:t.activeId}})},[]),a=(0,Q.useCallback)(e=>n(t=>({...t,activeId:e})),[]),o=(0,Q.useCallback)(()=>a(null),[a]);return{...t,open:r,close:i,select:a,showBrowser:o}}function Fd(e,t){let n=(0,Q.useCallback)(n=>t?e.subscribeSession(t,n):()=>void 0,[t,e]),r=(0,Q.useCallback)(()=>e.getSessionSnapshot(t),[t,e]),i=(0,Q.useSyncExternalStore)(n,r,r);return(0,Q.useEffect)(()=>{if(t)return e.retainSession(t,!0),()=>e.retainSession(t,!1)},[t,e]),i}var Id=new Set([`ArrowDown`,`ArrowUp`,`Home`,`End`,`Enter`,`Escape`]);function Ld(e,t){return!t||!Id.has(e.key)?!1:(e.preventDefault(),!0)}function Rd(e,{open:t,matches:n,index:r,setIndex:i,select:a,dismiss:o}){if(!t)return!1;if(n.length>0){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let t=e.key===`ArrowDown`?1:-1;return i(e=>(e+t+n.length)%n.length),!0}if(e.key===`Enter`||e.key===`Tab`)return e.preventDefault(),a(n[r]??n[0]),!0}return e.key===`Escape`&&(e.preventDefault(),o(),!0)}var zd=`openpond-composer-resource-request`;function Bd(e){window.dispatchEvent(new CustomEvent(zd,{detail:{...e,contexts:Uo.parse(e.contexts)}}))}function Vd({connection:e,sessionId:t,events:n,blocked:r,prompt:i,selectionKey:a,inputRef:o}){let[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(null),d=(0,Q.useId)(),f=(0,Q.useRef)(!1),[p,m]=(0,Q.useState)(!1),h=(0,Q.useRef)(!1),g=(0,Q.useRef)(0),_=(0,Q.useRef)(new Set),v=[...n].reverse().find(e=>e.sessionId===t&&[`turn.started`,`turn.completed`,`turn.failed`,`turn.interrupted`,`workspace_action_result`].includes(e.name))?.id,y=`${ra(e)}:${t}:${a}:${v??``}`,b=(0,Q.useRef)({key:y,blocked:r,prompt:i,value:s,error:l});b.current={key:y,blocked:r,prompt:i,value:s,error:l},(0,Q.useEffect)(()=>{let n=++g.current;if(b.current.error!==null&&u(null),!e||!t||r||p||i)return;let a=new AbortController,o;async function s(){try{let r=await ko(e,`dataset`,{action:`next_step`,payload:{sessionId:t,operation:`read`}},a.signal);if(n!==g.current||a.signal.aborted)return;let i=r.suggestion?pl.parse(r.suggestion):null;i?.sessionId!==t||!i||_.current.has(i.id)?b.current.value!==null&&c(null):(b.current.value?.key!==y||b.current.value.suggestion.id!==i.id)&&c({key:y,suggestion:i})}catch{}finally{a.signal.aborted||(o=setTimeout(s,1e4))}}return s(),()=>{a.abort(),clearTimeout(o)}},[e,t,y,r,p,!!i,v]);let x=!p&&!r&&!i&&s?.key===y&&!_.current.has(s.suggestion.id)?s.suggestion:null;async function S(){if(!e||!t||!x||f.current||h.current||b.current.blocked||o.current?.getPrompt())return;let n=x,r=y,i=g.current;h.current=!0,u(null);try{let a=await ko(e,`dataset`,{action:`next_step`,payload:{sessionId:t,operation:`accept`,id:n.id}});if(_.current.add(n.id),c(null),!a.suggestion||g.current!==i||b.current.key!==r||b.current.blocked||f.current||o.current?.getPrompt())return;let s=pl.parse(a.suggestion);if(s.id!==n.id||s.sessionId!==t)return;Bd({sessionId:t,text:s.draft,contexts:s.contexts})}catch(e){u(e instanceof Error?e.message:`Could not prepare this suggestion.`)}finally{h.current=!1}}function C(){x&&e&&t&&!_.current.has(x.id)&&(_.current.add(x.id),c(null),ko(e,`dataset`,{action:`next_step`,payload:{sessionId:t,operation:`dismiss`,id:x.id}}).catch(e=>u(e instanceof Error?e.message:`Could not dismiss this suggestion.`)))}function w(){f.current||(f.current=!0,g.current++,m(!0))}function T(e){return f.current||e.nativeEvent.isComposing||e.keyCode===229?(w(),!0):(e.key===`Enter`||e.key===`Tab`)&&(h.current||e.repeat)?(e.preventDefault(),!0):x?e.key===`Escape`?(e.preventDefault(),C(),!0):(e.key===`Enter`||e.key===`Tab`)&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&(e.preventDefault(),e.stopPropagation(),S(),!0):!1}return{suggestion:x,descriptionId:d,accept:S,dismiss:C,onKeyDown:T,error:l,onCompositionStart:w,onCompositionEnd:()=>{f.current=!1,m(!1)}}}function Hd({next:e}){return(0,$.jsxs)($.Fragment,{children:[e.suggestion?(0,$.jsxs)(`div`,{className:`composer-next-step`,id:e.descriptionId,children:[(0,$.jsx)(`span`,{children:e.suggestion.label}),(0,$.jsx)(`small`,{"aria-hidden":`true`,children:`Enter to draft`}),(0,$.jsx)(`span`,{className:`sr-only`,children:`Press Enter or Tab to insert an editable draft. This does not send.`})]}):null,(0,$.jsx)(X,{error:e.error})]})}function Ud(e,t){if(!e.scope||!e.focus.scopeContext)return[];let n=e.scope.runs.at(-1),r=e.focus.experiment??(n?e.experiments.find(e=>e.id===n.id)??n:null),i=[e.focus.dataset,r,...e.graders].filter(e=>!!e).map(({kind:e,id:t,revision:n,datasetId:r,datasetRevision:i,owner:a,profileRef:o})=>({kind:e,id:t,revision:n,datasetId:r,datasetRevision:i,owner:a,profileRef:o})),a=t??e.scope.training?.find(t=>qr(t)===e.scope.selectedTrainingKey);return Uo.parse([{scopeId:e.scope.id,selectionVersion:e.focus.scopeContext.selectionVersion,...e.scope.evaluationModel?{evaluationModel:e.scope.evaluationModel}:{},executionLocation:e.scope.executionLocation??`local`,resources:i,...a?{training:[Jr(a)]}:{}}])}function Wd(e,t){let n=new Map([...e,...t].map(e=>[JSON.stringify(e),e]));return Uo.parse([...n.values()])}function Gd(e){return e.length?{chatResourceContexts:e,...e.length===1?{chatExperimentScopeId:e[0].scopeId,chatExperimentSelectionVersion:e[0].selectionVersion}:{}}:{}}function Kd(e,t,n){return e?.length?{contexts:e,focus:null}:{contexts:n?.model||n?.training?[]:t,focus:n}}function qd(e,t,n,r){let i=(0,Q.useRef)(new Map),a=r?.resourceContexts,o={current:a?{get:e=>a.get(`session:${e}`),set:(e,t)=>a.set(`session:${e}`,t),delete:e=>a.delete(`session:${e}`)}:i.current},s=(0,Q.useCallback)(n=>{n.trim()||o.current.delete(e),t(n)},[t,e,a]);function c(){return o.current.get(e)??Ud(n)}return{resourceDrafts:o,onPromptChange:s,currentResourceContexts:c}}function Jd(e){async function t(t,n){let r=(n??e.getPrompt()).trim()||(e.attachmentCount?`Please review the attached files.`:``);if(!e.running||!r)return!1;let i=e.getResourceContexts?.()??[];if(e.hasActions)return e.showToast(`Send the selected action as a separate message before steering this turn.`,`info`),!1;if(!e.begin(e.scope))return!1;e.setError(null);let a,o=!1;try{a=await e.prepareAttachments?.();let n=a?.attachments??[];if(t===`queued`&&!e.inbox.enabled)return e.stageLocal(r,i,n),e.clear(),o=!0,!0;let s=e.inbox.enabled?t===`steer`?await e.inbox.steer(r,i,n.length?n:void 0):await e.inbox.queue({prompt:r,attachments:n,metadata:Gd(i),modelRef:{providerId:e.provider,modelId:e.model},...e.provider===`codex`?yi(e.codexPermissionMode):{approvalPolicy:`on-request`,sandbox:`workspace-write`},codexPermissionMode:e.codexPermissionMode,codexReasoningEffort:e.codexReasoningEffort}):await e.onSubmit(n,null,null,{preservePrompt:!0,promptOverride:r,turnMetadata:{...Gd(i),interactionKind:`steer`}});return s&&(!e.getCurrentSubmissionScopeKey||e.getCurrentSubmissionScopeKey()===e.scope)&&e.clear(),o=s,s}catch(t){return e.setError(t instanceof Error?t.message:String(t)),!1}finally{a?.settle(o),e.finish(e.scope)}}return{stageCurrentSteerDraft:e=>t(`queued`,e),submitImmediateSteer:e=>t(`steer`,e)}}var Yd=()=>({dataset:null,experiment:null});function Xd(e,t){let[n,r]=(0,Q.useState)(Yd),[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)([]),[c,l]=(0,Q.useState)([]),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(null),[g,_]=(0,Q.useState)(0),[v,y]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(!1),S=(0,Q.useRef)(0),C=(0,Q.useRef)(null),w=(0,Q.useRef)(n);w.current=n;let T=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{if(S.current++,C.current?.abort(),C.current=null,a([]),s([]),l([]),x(!1),r(Yd()),y(null),!e||!t)return;let n=new AbortController,i,o=!1,c=!1,u=async()=>{if(o){c=!0;return}o=!0,clearTimeout(i);let d=S.current;try{let i=await ko(e,`dataset`,{action:`context`,payload:{sessionId:t}},n.signal);!n.signal.aborted&&d===S.current&&(r(i.focus),a(i.datasets),s(i.experiments),l(i.graders),y(null))}catch(e){!n.signal.aborted&&d===S.current&&y(e instanceof Error?e.message:`Resource context unavailable.`)}o=!1,n.signal.aborted||(c?(c=!1,u()):i=setTimeout(()=>void u(),1e4))};T.current=()=>void u();let d=e=>{e.detail?.sessionId===t&&u()};return window.addEventListener(`openpond-resource-focus-changed`,d),u(),()=>{window.removeEventListener(`openpond-resource-focus-changed`,d),T.current=null,S.current++,C.current?.abort(),n.abort(),clearTimeout(i)}},[e,t]),(0,Q.useEffect)(()=>{if(d([]),h(null),!e||!t||!n.scopeContext?.activeScopeId)return;let r=new AbortController;return p(!0),ko(e,`experiment`,{action:`models`},r.signal).then(e=>{r.signal.aborted||d(e.models)}).catch(e=>{r.signal.aborted||h(e instanceof Error?e.message:`Model choices unavailable.`)}).finally(()=>{r.signal.aborted||p(!1)}),()=>r.abort()},[e,t,!!n.scopeContext?.activeScopeId,g]);async function E(n,i){if(!e||!t||C.current)return!1;let a=++S.current,o=new AbortController;C.current=o,x(!0);try{let s=await ko(e,`dataset`,{action:n,payload:{sessionId:t,...i,...w.current.scopeContext?{expectedSelectionVersion:w.current.scopeContext.selectionVersion}:{}}},o.signal);return a===S.current&&!o.signal.aborted&&(r(s),w.current=s,n!==`set_model`&&n!==`set_destination`&&l((s.scopeContext?Gr(s.scopeContext).find(e=>e.id===s.scopeContext?.activeScopeId):null)?.graders??[]),y(null)),o.signal.aborted||window.dispatchEvent(new CustomEvent(`openpond-resource-focus-changed`,{detail:{sessionId:t}})),!o.signal.aborted}catch(e){return a===S.current&&!o.signal.aborted&&y(e instanceof Error?e.message:`Resource selection failed.`),!1}finally{C.current===o&&(C.current=null,x(!1),T.current?.())}}let D=n.dataset?.id,O=n.dataset?.revision,k=(0,Q.useCallback)(t=>!e||!D||!O?Promise.reject(Error(`Select a dataset to inspect its rows.`)):ko(e,`dataset`,{action:`read`,id:D,expectedRevision:O},t),[e,D,O]);return{focus:n,scope:(n.scopeContext?Gr(n.scopeContext).find(e=>e.id===n.scopeContext?.activeScopeId):null)??null,datasets:i,experiments:o,graders:c,selecting:b,error:v,readDataset:k,models:u,modelsLoading:f,modelsError:m,refreshModels:()=>_(e=>e+1),selectDestination:e=>E(`set_destination`,{executionLocation:e}),selectModel:e=>E(`set_model`,{evaluationModel:e}),select:(e,t,n)=>E(`set_focus`,{kind:e,id:t||null,...n?{revision:n}:{}}),selectScope:e=>E(`select_scope`,{scopeId:e}),createScope:e=>E(`create_scope`,{operationId:`scope-${crypto.randomUUID()}`,...e===void 0?{}:{graderId:e}}),renameScope:(e,t)=>E(`rename_scope`,{scopeId:e,name:t})}}var Zd={experiment:`Experiment`,model:`Model`};function Qd({context:e,disabled:t=!1,placement:n=`bottom`}){let[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(null),l=(0,Q.useRef)(null),u=(0,Q.useRef)(null),d=e.selection,f=d?.target.kind===`training`?`model`:d?.target.kind===`dataset`||d?.target.kind===`training_result`||d?.target.kind===`managed_modification_result`||d?.target.kind===`engram_result`||d?.target.kind===`decision_result`||d?.target.kind===`alphaedit_result`||d?.target.kind===`neuron_training_result`?`experiment`:d?.target.kind,p=a??f??`experiment`,m=(e.catalog.data?.options??[]).filter(e=>e.target.kind===p||p===`experiment`&&(!!e.target.result||e.target.kind===`decision_result`||e.target.kind===`alphaedit_result`||e.target.kind===`neuron_training_result`)),h=d?.training?d.training.location===`cloud`?d.training.job.modelProjectId:d.training.modelId:null,g=d?.target.kind===p||p===`experiment`&&(d?.target.kind===`dataset`||d?.target.result||d?.target.kind===`decision_result`||d?.target.kind===`alphaedit_result`||d?.target.kind===`neuron_training_result`)?d:p===`model`&&h?m.find(e=>e.target.id===h&&e.target.location===d?.training?.location):null,_=g?JSON.stringify(g.target):``;g&&!m.some(e=>JSON.stringify(e.target)===_)&&m.unshift(g);let v=t||e.selecting,y=s??e.selectionError?.message??e.catalog.error?.message??e.catalog.data?.warning;(0,Q.useEffect)(()=>{if(!r)return;function e(e){l.current?.contains(e.target)||i(!1)}function t(e){e.key===`Escape`&&(i(!1),u.current?.focus())}return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[r]);async function b(t){c(null);try{if(t===`saved-model-experiment`){if(!g||g.target.kind!==`model`||g.target.location!==`cloud`)throw Error(`Select the hosted saved Model first.`);await e.select(g.target,{newExperiment:!0})&&i(!1);return}if(t===`new-experiment`){let t=`draft-${crypto.randomUUID()}`;await e.select({kind:`experiment`,id:t,location:`local`,draft:{schemaVersion:`openpond.experimentDraft.v1`,id:t,operationType:`evaluate`,name:`Evaluation`}},{newExperiment:!0})&&i(!1);return}if(!await e.select(t?O.parse(JSON.parse(t)):null))return;i(!1),u.current?.focus()}catch(e){c(e instanceof Error?e.message:`Training selection failed.`)}}return(0,$.jsxs)(`div`,{ref:l,className:`chat-context-picker codex-model-reasoning${n===`top`?` open-up`:``}`,children:[(0,$.jsxs)(`button`,{ref:u,type:`button`,className:`composer-project-trigger chat-training-trigger${r?` active`:``}`,"aria-label":`Ponder`,"aria-haspopup":`dialog`,"aria-expanded":r,disabled:v,title:d?`${d.label}: ${d.detail}`:`Ponder`,onClick:()=>{o(null),i(e=>!e)},children:[(0,$.jsx)(`span`,{children:d?.target.kind===`dataset`?`Experiment draft · ${d.label}`:d?.model?.name??d?.label??`Ponder`}),(0,$.jsx)(Oa,{size:14})]}),r?(0,$.jsxs)(`div`,{className:`codex-model-menu chat-training-menu`,role:`dialog`,"aria-label":`Training context`,children:[(0,$.jsx)(Z,{compact:!0,floating:!0,label:`Training type`,value:p,floatingMenuWidth:180,options:Object.entries(Zd).map(([e,t])=>({value:e,label:t})),triggerContent:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{children:`Type`}),(0,$.jsx)(`span`,{className:`chat-training-menu-value`,children:Zd[p]}),(0,$.jsx)(ka,{size:14})]}),disabled:v,onChange:e=>o(e)}),(0,$.jsx)(Z,{compact:!0,floating:!0,label:`${Zd[p]} name`,value:_,floatingMenuWidth:340,floatingMenuMaxHeight:360,triggerContent:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{children:Zd[p]}),(0,$.jsx)(`span`,{className:`chat-training-menu-value`,children:(g?.target.kind===`dataset`?`Draft · ${g.label}`:g?.label)??(e.catalog.isPending?`Loading…`:`None`)}),(0,$.jsx)(ka,{size:14})]}),options:[{value:``,label:`None`},...p===`model`&&g?.target.kind===`model`&&g.target.location===`cloud`?[{value:`saved-model-experiment`,label:`New experiment from saved Model…`,separatorBefore:!0}]:[],...p===`experiment`?[{value:`new-experiment`,label:`New experiment…`,separatorBefore:!0}]:[],...m.map(e=>({value:JSON.stringify(e.target),label:e.label,description:`${e.target.location===`cloud`?`OpenPond Managed`:`Local`} · ${e.detail}${m.filter(t=>t.label===e.label&&t.target.location===e.target.location).length>1?` · ${e.target.id.slice(-8)}`:``}`}))],disabled:v,onChange:e=>void b(e)}),p===`experiment`&&e.catalog.hasNextPage?(0,$.jsx)(`button`,{type:`button`,disabled:e.catalog.isFetchingNextPage,onClick:()=>void e.catalog.fetchNextPage(),children:`More saved experiments`}):null,y?(0,$.jsx)(X,{error:y,children:e.catalog.error?(0,$.jsx)(`button`,{type:`button`,onClick:()=>void e.catalog.refetch(),children:`Retry`}):null}):null]}):y?(0,$.jsx)(X,{error:y}):null]})}var $d=[{value:`model_judge`,label:`LLM judge`,request:`Create an LLM judge (model_judge) with an explicit rubric and passing and failing calibration examples. Ask for the judge model and a fixture-check spending limit if they are not already agreed.`},{value:`human`,label:`Human assessment`,request:`Create a human assessment (human) with a structured review form, explicit criteria, scale anchors and reviewer guidance. Keep human decisions separate from automatic evaluation scores; do not invent reviews or use pending reviews as training rewards.`},{value:`custom_verifier`,label:`Code grader`,request:`Create a code grader (custom_verifier) using an isolated JavaScript verifier. Include known-good, known-bad and boundary fixtures, and check them before reporting the grader as validated.`},{value:`python_correctness`,label:`Python correctness`,request:`Create a Python correctness grader using the supported Python correctness starter and private tests. Verify that the dataset contains admitted Python code and that a qualified isolated runtime is available. Missing code, tests or runtime evidence must remain unscorable.`}];function ef({dataset:e,busy:t,onDraft:n}){function r(r){e&&!t&&n(`${r.request}\n\nDataset: ${e.name}, ID ${e.id}, revision ${e.revision}. Inspect its tasks and existing graders to determine the appropriate checks.\n\nPreserve the existing graders and retained experiment inputs. Save changes as a new dataset revision. Do not start an experiment or training run.`)}return(0,$.jsxs)(`div`,{className:`chat-grader-request`,children:[(0,$.jsx)(`div`,{className:`evaluation-dataset-choices chat-grader-type-choices`,role:`group`,"aria-label":`Grader type`,children:$d.map(n=>(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:t||!e,onClick:()=>r(n),children:n.label},n.value))}),(0,$.jsx)(`div`,{className:`training-dialog-actions`,children:(0,$.jsx)(`a`,{className:`training-text-button`,href:ao(as(`graders`,null,{area:`console`})),children:`Manage graders`})})]})}function tf({kind:e,resources:t,busy:n,onDraft:r}){let[i,a]=(0,Q.useState)(``);if(e===`rows`)return(0,$.jsx)(nf,{resources:t});let o=t.focus.dataset;if(e===`grader`)return(0,$.jsx)(ef,{dataset:o,busy:n||t.selecting,onDraft:r});let s={title:`New dataset`,placeholder:`What examples should it contain?`,button:`Chat`};function c(){r(`Create a new dataset: ${i.trim()}`)}let l=n||t.selecting||!i.trim();return(0,$.jsxs)(`div`,{className:`composer-resource-request`,onKeyDown:e=>{!e.nativeEvent.isComposing&&e.key===`Enter`&&e.target instanceof HTMLInputElement&&(e.preventDefault(),e.stopPropagation(),l||c())},children:[(0,$.jsx)(`div`,{className:`composer-experiment-setup-heading`,children:(0,$.jsx)(`strong`,{children:s.title})}),(0,$.jsx)(`input`,{autoFocus:!0,"aria-label":s.placeholder,placeholder:s.placeholder,value:i,onChange:e=>a(e.target.value),disabled:n}),(0,$.jsxs)(`button`,{type:`button`,"aria-label":`Add to chat`,title:`Add to chat`,className:`composer-experiment-create`,onClick:c,disabled:l,children:[(0,$.jsx)(za,{size:13,"aria-hidden":!0}),` `,s.button]})]})}function nf({resources:e}){let[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(0);(0,Q.useEffect)(()=>{let t=new AbortController;return n(null),i(null),o(0),e.readDataset(t.signal).then(e=>{t.signal.aborted||n(e)}).catch(e=>{t.signal.aborted||i(e instanceof Error?e.message:`Could not load dataset rows.`)}),()=>t.abort()},[e.readDataset]);let s=t?.record.workspace.draft.tasks??[],c=Math.max(1,Math.ceil(s.length/5));return(0,$.jsxs)(`section`,{className:`composer-dataset-rows`,"aria-label":`Dataset rows`,children:[(0,$.jsxs)(`div`,{className:`composer-experiment-setup-heading`,children:[(0,$.jsx)(`strong`,{children:`Dataset rows`}),(0,$.jsx)(`span`,{children:t?`${s.length} examples · V${t.summary.revision}`:``}),c>1?(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`button`,{type:`button`,disabled:a===0,onClick:()=>o(e=>e-1),"aria-label":`Previous rows`,children:`‹`}),(0,$.jsxs)(`span`,{children:[a+1,`/`,c]}),(0,$.jsx)(`button`,{type:`button`,disabled:a+1>=c,onClick:()=>o(e=>e+1),"aria-label":`Next rows`,children:`›`})]}):null]}),r?(0,$.jsx)(X,{error:r}):t?(0,$.jsx)(`div`,{className:`composer-dataset-rows-scroll`,children:(0,$.jsxs)(`table`,{children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Example`}),(0,$.jsx)(`th`,{children:`Input`})]})}),(0,$.jsxs)(`tbody`,{children:[s.slice(a*5,a*5+5).map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.id}),(0,$.jsx)(`td`,{children:typeof e.input.prompt==`string`?e.input.prompt:typeof e.input.request==`string`?e.input.request:JSON.stringify(e.input)})]},e.id)),s.length?null:(0,$.jsx)(`tr`,{children:(0,$.jsx)(`td`,{colSpan:2,children:`No saved rows yet.`})})]})]})}):(0,$.jsx)(`p`,{role:`status`,children:`Loading rows…`})]})}function rf({resources:e,busy:t,onClose:n,onAddGrader:r,onRows:i,createNew:a,setupOnly:o=!1}){let s=(0,Q.useRef)(null),c=e.focus.dataset,l=t||e.selecting,u=e.scope?.evaluationModel,d=e.scope?.executionLocation??`local`,f=e.models.filter(e=>d===`local`||e.providerId===`openpond`),p=f.some(e=>`${e.providerId}/${e.id}`===u);return(0,Q.useEffect)(()=>{s.current?.querySelector(`.dropdown-trigger:not(:disabled)`)?.focus()},[]),(0,$.jsxs)(`div`,{ref:s,className:`composer-experiment-setup`,role:`region`,"aria-label":a?`New experiment`:`Experiment configuration`,children:[(0,$.jsxs)(`div`,{className:`composer-experiment-setup-heading`,children:[(0,$.jsx)(`strong`,{children:a?`New experiment`:`Configuration`}),(0,$.jsx)(`span`,{children:c?`Uses ${e.graders.length} dataset grader${e.graders.length===1?``:`s`}`:`Choose a dataset above`})]}),(0,$.jsx)(Z,{compact:!0,floating:!0,placement:`top`,label:`Run on`,value:d,options:[{value:`local`,label:`Local`},{value:`cloud`,label:`Hosted`,disabled:!!(c?.owner||c?.profileRef)}],onChange:t=>void e.selectDestination(t),disabled:l}),(0,$.jsx)(Z,{compact:!0,floating:!0,placement:`top`,searchable:!0,label:`Evaluation model`,value:u??``,options:[{value:``,label:e.modelsLoading?`Loading models…`:`Choose evaluation model`,disabled:!0},...u&&!p?[{value:u,label:`${u} (unavailable)`,disabled:!0}]:[],...f.map(e=>({value:`${e.providerId}/${e.id}`,label:e.name??e.id,description:e.providerId})),{value:`refresh`,label:`Refresh models`,separatorBefore:!0}],onChange:t=>{t===`refresh`?e.refreshModels():e.selectModel(t)},disabled:l||e.modelsLoading}),i&&c&&!c.owner&&!c.profileRef?(0,$.jsx)(`button`,{type:`button`,className:`composer-resource-secondary`,onClick:i,disabled:l,children:`Rows`}):null,o?null:e.graders.length?a?(0,$.jsx)(`button`,{type:`button`,className:`composer-experiment-create`,disabled:l||!c||!p,onClick:()=>{e.createScope(null).then(e=>{e&&n()})},children:`Create experiment`}):null:(0,$.jsx)(`button`,{type:`button`,className:`composer-resource-secondary`,onClick:r,disabled:l||!c,children:`Create grader`}),e.modelsError?(0,$.jsx)(X,{error:e.modelsError}):null]})}function af(e){let{dataset:t,run:n,model:r}=e;if(!e.isExperiment)return`New experiment`;if(n&&/^(running|queued|pending|starting)$/i.test(n.state))return`View progress`;if(!t||t.taskCount===0||!e.graders||!r||!e.modelAvailable)return`Set up`;if(!n)return`Run`;let i=t.owner?.teamId===n.owner?.teamId&&t.owner?.actorId===n.owner?.actorId&&JSON.stringify(t.profileRef)===JSON.stringify(n.profileRef);return(e.executionLocation??`local`)===(n.location??`local`)&&i&&t.id===n.datasetId&&r===n.model&&(t.evaluationHash&&n.evaluationHash?t.evaluationHash===n.evaluationHash:t.revision===n.datasetRevision)?/^(completed|complete|succeeded)$/i.test(n.state)?`Improve`:`Retry`:`Run updated`}function of({resources:e,busy:t,onDraft:n}){let[r,i]=(0,Q.useState)(`experiment`),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(`Run`),d=(0,Q.useRef)(null),f=(0,Q.useId)(),{scope:p,focus:m}=e;if((0,Q.useEffect)(()=>{c(!1),o(!1)},[p?.id]),(0,Q.useEffect)(()=>{s&&r===`action`&&d.current?.focus()},[s,r,l]),!p)return null;let h=m.dataset,g=p.ordinal!==null,_=t||e.selecting,v=h?[h,...e.datasets.filter(e=>e.id!==h.id||e.revision!==h.revision)]:e.datasets,y=p.runs.at(-1),b=m.experiment??(y?e.experiments.find(e=>e.id===y.id)??y:null),x=p.evaluationModel,S=p.executionLocation??`local`,C=S===`cloud`?`on OpenPond hosted execution`:`locally`,w=e.models.some(e=>`${e.providerId}/${e.id}`===x&&(S===`local`||e.providerId===`openpond`))&&(S!==`cloud`||!h?.owner&&!h?.profileRef),T=e.graders.find(e=>e.id===p.selectedGraderId)??(e.graders.length===1?e.graders[0]:void 0),E=!!(h&&e.graders.length&&w),D=![`Run`,`Run updated`,`Repeat run`,`Retry`].includes(l)||E&&!b?.state.match(/^(running|queued|pending|starting)$/i),O=af({isExperiment:g,dataset:h,graders:e.graders.length,model:x,modelAvailable:w,executionLocation:S,run:b});function k(e){i(e),o(!0),c(!0)}function A(e){u(e),k(`action`)}let j=e.models.find(e=>`${e.providerId}/${e.id}`===x),M=j?`${j.name??j.id} (${j.providerId})`:x??`the selected evaluation model`,N=`${e.graders.length} dataset grader${e.graders.length===1?``:`s`}`,P=h?`${h.name} V${h.revision}`:`this dataset`,F={"New experiment":`Create a new experiment draft for ${P}, keeping its current revision and graders. Do not run an evaluation, upload data, or start training.`,"Training readiness":`Is ${P} ready to train? Inspect its examples, splits, graders, source permissions, and supported training options. Explain what is missing without changing data or starting training.`,"Prepare training":`Prepare a hosted training plan on OpenPond for ${P}. Show me the model options, data requirements, plan, and cost first. Do not upload data or start training.`,Run:`Run ${P} ${C} against ${M}, using ${N}.`,"Run updated":`Run the updated configuration for ${P} ${C} against ${M}, using ${N}. Keep previous results for comparison.`,Retry:`Inspect why the previous run stopped, then retry ${P} ${C} against ${M} with its dataset graders if appropriate. Reconcile any uncertain submission first.`,"Repeat run":`Repeat ${P} ${C} against ${M} with its dataset graders as a new run. Preserve the previous results.`,Improve:`Improve experiment ${p.ordinal}: inspect its results, make a targeted change, validate it, and run a comparison ${C} against ${M} within the agreed budget.`,"View progress":`Check the progress of experiment ${p.ordinal}${b?` (run ${b.id})`:``}.`,Compare:`Compare experiment ${p.ordinal}${b?` (run ${b.id})`:``} with its earlier results.`,Diagnose:`Diagnose ${g?`experiment ${p.ordinal}`:P}: inspect the evidence and explain the cause and next step without changing it.`,"Improve dataset":`Improve ${P}: inspect its examples and results, fix relevant data or coverage issues, and evaluate the changes ${C} within the agreed budget.`,"Improve grader":`Improve ${T?.name??`the selected grader`} for ${P}: inspect its rules and failures, repair it, test good and bad answers without weakening the criteria, then run an experiment ${C} to check real outputs within the agreed budget.`,"Test grader":`Test ${T?.name??`the dataset graders`} on ${P} against known-good and known-bad examples.`},I=[{value:`New experiment`,label:`New experiment`,disabled:!h},{value:`Diagnose`,label:`Diagnose`,disabled:!h},...b?[{value:`Improve`,label:`Improve experiment`}]:[],{value:`Improve dataset`,label:`Improve dataset`,disabled:!h},{value:`Improve grader`,label:`Improve grader`,disabled:!T},{value:`Test grader`,label:T?`Test grader`:`Test graders`,disabled:!h||!e.graders.length},...!h?.owner&&!h?.profileRef?[{value:`Training readiness`,label:`Ready to train?`,disabled:!h,separatorBefore:!0},{value:`Prepare training`,label:`Prepare training`,disabled:!h}]:[],...b?[{value:`Compare`,label:`Compare results`,separatorBefore:!0},...O===`Improve`?[{value:`Repeat run`,label:`Repeat run`}]:[]]:[]];return(0,$.jsxs)(`div`,{className:`composer-resource-area ${s?`is-expanded`:``}`,children:[(0,$.jsxs)(`div`,{className:`composer-resource-bar`,"aria-label":g?`Current experiment`:`Current dataset`,children:[g?(0,$.jsx)(Z,{compact:!0,floating:!0,placement:`top`,floatingMenuWidth:280,label:`Experiment scope`,value:p.id,className:`composer-resource-number`,triggerContent:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{children:p.ordinal}),(0,$.jsx)(Oa,{size:12})]}),tooltip:`${p.ordinal}: ${p.name}`,options:[...(m.scopeContext?.scopes??[]).map(e=>({value:e.id,label:`${e.ordinal} ${e.name}`})),{value:`new`,label:`New experiment`,icon:`plus`}],onChange:t=>{t===`new`?A(`New experiment`):e.selectScope(t)},disabled:_}):null,(0,$.jsx)(Z,{compact:!0,floating:!0,searchable:!0,floatingMenuWidth:320,placement:`top`,label:`Dataset focus`,className:`composer-resource-dataset`,value:h?`${h.id}@${h.revision}`:``,tooltip:P,triggerContent:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`composer-resource-dataset-name`,children:h?.name??`Dataset`}),h?(0,$.jsxs)(`span`,{className:`composer-resource-version`,children:[`V`,h.revision]}):null,(0,$.jsx)(Oa,{size:12})]}),options:[{value:``,label:`Choose dataset`},...v.map(e=>({value:`${e.id}@${e.revision}`,label:`${e.name} V${e.revision}`})),{value:`create`,label:`New dataset…`,icon:`plus`}],onChange:t=>{if(t===`create`)return k(`dataset`);let n=t.lastIndexOf(`@`);e.select(`dataset`,n<0?t:t.slice(0,n),n<0?void 0:Number(t.slice(n+1)))},disabled:_}),(0,$.jsx)(Z,{compact:!0,floating:!0,placement:`top`,floatingMenuWidth:280,label:`Grader focus`,className:`composer-resource-graders`,value:p.selectedGraderId??``,options:[{value:``,label:`All graders`,shortLabel:`Graders ${e.graders.length}`},...e.graders.map(e=>({value:e.id,label:e.name})),{value:`add`,label:`Create grader`,icon:`plus`,separatorBefore:!0}],onChange:t=>{t===`add`?k(`grader`):e.select(`grader`,t)},disabled:_||!h}),O!==`New experiment`&&O!==`Improve`?(0,$.jsx)(`button`,{type:`button`,className:`composer-resource-primary`,disabled:_,onClick:()=>O===`Set up`?k(`experiment`):A(O),children:O}):null,(0,$.jsx)(Z,{compact:!0,floating:!0,searchable:!0,placement:`top`,floatingMenuWidth:280,floatingMenuMaxHeight:440,label:`Chat actions`,tooltip:`Add a request to chat`,value:``,className:`composer-resource-chat-actions`,triggerContent:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(za,{size:13}),(0,$.jsx)(Ia,{size:15})]}),options:[...I,...(p.training??[]).map((e,t)=>({value:`training:${qr(e)}`,label:`Check training ${t+1}`}))],onChange:e=>{if(!_){if(e.startsWith(`training:`)){let t=p.training?.find(t=>`training:${qr(t)}`===e);t&&n(`Check this training job and show its results and any model it produced.`,t)}else{let t=I.find(t=>t.value===e);if(!t||`disabled`in t&&t.disabled||!F[e])return;n(F[e])}c(!1)}},disabled:_}),(0,$.jsx)(`button`,{type:`button`,className:`composer-resource-expand`,"aria-label":s?`Collapse resource controls`:`Expand resource controls`,"aria-expanded":s,"aria-controls":f,onClick:()=>{o(!0),s||i(`experiment`),c(e=>!e)},children:(0,$.jsx)(Oa,{size:15})})]}),(0,$.jsx)(`div`,{id:f,className:`composer-resource-expansion`,inert:!s,"aria-hidden":!s,children:(0,$.jsx)(`div`,{className:`composer-resource-expansion-inner`,children:a?r===`experiment`?(0,$.jsx)(rf,{resources:e,busy:t,createNew:!g,onClose:()=>c(!1),onAddGrader:()=>k(`grader`),setupOnly:!0}):r===`action`?(0,$.jsxs)(`div`,{className:`composer-resource-request`,role:`region`,"aria-label":`${l} request preview`,children:[(0,$.jsxs)(`div`,{className:`composer-experiment-setup-heading`,children:[(0,$.jsx)(`strong`,{children:l}),(0,$.jsx)(`span`,{children:`Edit in chat before sending`})]}),(0,$.jsx)(`p`,{children:F[l]}),(0,$.jsxs)(`button`,{ref:d,type:`button`,"aria-label":`Add to chat`,title:`Add to chat`,className:`composer-experiment-create`,disabled:_||!D,onClick:()=>{n(F[l]),c(!1)},children:[(0,$.jsx)(za,{size:13,"aria-hidden":!0}),(0,$.jsx)(Ia,{size:13,"aria-hidden":!0}),` Add to chat`]})]}):(0,$.jsx)(tf,{kind:r,resources:e,busy:t,onDraft:e=>{n(e),c(!1)}},`${r}:${h?.id}:${h?.revision}`):null})}),e.error?(0,$.jsx)(X,{error:e.error}):null]})}function sf({context:e,sessionId:t,busy:n}){let[r,i]=(0,Q.useState)(null),a=e.selection;if(!a)return null;let o=a.training,s=a.model,c=n||e.selecting,l=o?JSON.stringify(a.target):``,u=(e.runs.data?.runs??[]).map(e=>({value:JSON.stringify(e.target),label:e.label,description:e.detail}));o&&!u.some(e=>e.value===l)&&u.unshift({value:l,label:a.label,description:a.detail});let d=(e.catalog.data?.options??[]).filter(e=>e.target.kind===`model`),f=d.find(e=>e.target.id===s?.id&&e.target.location===a.target.location)?.target??(s?{...a.target,kind:`model`,id:s.id}:null),p=f?JSON.stringify(f):``,m=d.map(e=>({value:JSON.stringify(e.target),label:e.label,description:e.detail}));f&&!m.some(e=>e.value===p)&&m.unshift({value:p,label:s?.name??a.label,description:a.detail});async function h(t){try{i(null),await e.select(O.parse(JSON.parse(t)))}catch(e){i(e instanceof Error?e.message:`Training selection failed.`)}}return(0,$.jsxs)(`div`,{className:`composer-resource-area`,children:[(0,$.jsxs)(`div`,{className:`composer-resource-bar`,"aria-label":`Current training`,children:[(0,$.jsx)(Z,{compact:!0,floating:!0,searchable:!0,placement:`top`,floatingMenuWidth:320,label:`Model focus`,className:`composer-resource-dataset`,value:p,triggerContent:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`composer-resource-dataset-name`,children:s?.name??a.label}),(0,$.jsx)(Oa,{size:12})]}),options:m,onChange:e=>void h(e),disabled:c}),(0,$.jsx)(Z,{compact:!0,floating:!0,placement:`top`,floatingMenuWidth:320,label:`Training run`,className:`composer-resource-graders`,value:l,options:[...o?[]:[{value:``,label:e.runs.isPending?`Loading runs…`:u.length?`Choose training run`:`No runs`,disabled:!0}],...u],onChange:e=>void h(e),disabled:c||e.runs.isPending}),(0,$.jsx)(`button`,{type:`button`,className:`composer-resource-primary`,onClick:()=>window.dispatchEvent(new CustomEvent(j,{detail:{sessionId:t,scope:e.scope,targetKey:JSON.stringify(a.target)}})),children:`View progress`})]}),(0,$.jsx)(X,{error:r??e.runs.error})]})}var cf=e=>JSON.stringify([e.kind,e.id,e.owner??null,e.profileRef??null]),lf=(e,t)=>e.datasetId===t.id&&JSON.stringify(e.owner??null)===JSON.stringify(t.owner??null)&&JSON.stringify(e.profileRef??null)===JSON.stringify(t.profileRef??null),uf=e=>/^(queued|running|pending|starting|cancelling)$/i.test(e);function df(e){return Kr.array().parse(e)}function ff(e,t,n){let{scope:r,focus:i}=e;if(!r||!i.scopeContext||!i.dataset)return[];let a=i.dataset;if(t&&!lf(t,a))throw Error(`This run belongs to a different Dataset.`);let o=t?.datasetRevision??a.revision,s=[{kind:`dataset`,id:a.id,revision:o,owner:a.owner,profileRef:a.profileRef},...t?[{kind:t.kind,id:t.id,revision:t.revision,datasetId:t.datasetId,datasetRevision:o,owner:t.owner,profileRef:t.profileRef}]:[],...!t||o===a.revision?e.graders.map(e=>({kind:e.kind,id:e.id,revision:e.revision,datasetId:e.datasetId,datasetRevision:e.datasetRevision,owner:e.owner,profileRef:e.profileRef})):[]];return Uo.parse([{scopeId:r.id,selectionVersion:i.scopeContext.selectionVersion,evaluationModel:t?.model??r.evaluationModel,executionLocation:t?.location??r.executionLocation??`local`,resources:s,...n?{training:[Jr(n)]}:{}}])}function pf({context:e,resources:t,sessionId:n,busy:r}){let[i,a]=(0,Q.useState)(null),o=e.selection;if(!o)return null;if(o.model||o.training)return(0,$.jsx)(sf,{context:e,sessionId:n,busy:r});if(o.draft&&o.draft.operationType!==`evaluate`)return(0,$.jsx)(`div`,{className:`composer-resource-area`,children:(0,$.jsxs)(`div`,{className:`composer-resource-bar`,"aria-label":`Current experiment draft`,children:[(0,$.jsx)(`span`,{className:`composer-resource-dataset-name`,children:o.label}),(0,$.jsx)(`span`,{children:Tr(o.draft.operationType)}),(0,$.jsx)(`button`,{type:`button`,className:`composer-resource-primary`,disabled:r||e.selecting,onClick:()=>window.dispatchEvent(new CustomEvent(j,{detail:{sessionId:n,scope:e.scope,targetKey:JSON.stringify(o.target)}})),children:`View draft`})]})});let s=o.dataset??(o.resource?.kind===`dataset`?o.resource:null),c=o.resource?.kind===`experiment`?o.resource:null,l=t.scope;if(!(l&&(o.draft&&o.target.scopeId===l.id||s&&l.dataset&&cf(s)===cf(l.dataset)&&s.revision===l.dataset.revision&&(o.target.scopeId===l.id||o.target.kind===`dataset`||c&&l.runs.some(e=>cf(e)===cf(c))))))return null;async function u(t){a(null);try{return await e.select(t),!0}catch(e){return a(e instanceof Error?e.message:`Resource selection failed.`),!1}}let d={...t,focus:{...t.focus,dataset:s,experiment:c},graders:o.graders??t.graders,selecting:t.selecting||e.selecting,selectScope:e=>u({kind:`experiment`,id:e,scopeId:e,sessionId:n,location:`local`}),select:(n,r,i)=>{if(n===`grader`)return t.select(n,r,i);if(!r)return u(null);let o=e.catalog.data?.options.find(e=>e.target.kind===n&&e.target.id===r&&(i===void 0||e.target.revision===i))?.target,s=[...t.datasets,...t.experiments].find(e=>e.kind===n&&e.id===r&&(i===void 0||e.revision===i));return!o&&!s?(a(`This resource is no longer available. Choose it again from Ponder.`),Promise.resolve(!1)):u(o??{kind:n,id:r,revision:i,location:s.location??`local`})}};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(of,{resources:d,busy:r,onDraft:(e,t)=>{Bd({sessionId:n,text:e,contexts:ff(d,c??void 0,t)})}}),(0,$.jsx)(X,{error:i})]})}function mf({surface:e,voiceInputChannelKey:t=``,taskSessionId:n,submissionScopeKey:r=`default`,prompt:i,onPromptChange:a,showToast:o,resourceDrafts:s,inputRef:c,composerDraftStore:l}){(0,Q.useEffect)(()=>{if(e!==`chat`||!t.startsWith(`main-composer:`))return;let l=e=>{let t=e.detail;if(t?.sessionId!==(n??null)||!t.text.trim())return;try{s.current.set(r,Wd(s.current.get(r)??[],t.contexts))}catch{o(`Send or clear the current resource actions before adding more.`,`info`);return}let l=c.current?.getPrompt()??i,u=l.trim()?`${l}\n\n${t.text}`:t.text;a(u),requestAnimationFrame(()=>c.current?.focusAtPromptIndex(u.length))};return window.addEventListener(zd,l),()=>window.removeEventListener(zd,l)},[e,t,n,r,i,a,o,l])}function hf(e,t){let n=e.slice(0,Math.max(0,Math.min(t,e.length))),r=/(?:^|\s)\$([a-zA-Z][a-zA-Z0-9_-]*)?$/.exec(n);if(!r||typeof r.index!=`number`)return null;let i=r[0].lastIndexOf(`$`);return i<0?null:{end:n.length,query:(r[1]??``).toLowerCase(),start:r.index+i}}function gf(e){return`$${e.name}`}function _f(e,t,n){let r=Math.max(0,Math.min(t.start,e.length)),i=Math.max(r,Math.min(t.end,e.length)),a=e.slice(0,r),o=e.slice(i),s=a&&!/\s$/.test(a)?` `:``,c=o&&/^\s/.test(o)?``:` `,l=`${s}${gf(n)}${c}`;return{cursor:a.length+l.length-(o?c.length:0),value:`${a}${l}${o}`}}function vf(e,t,n){let r=t.trim().toLowerCase(),i=e.filter(e=>e.enabled&&e.validationStatus===`valid`).filter(e=>!r||[e.name,e.description,e.path].join(` `).toLowerCase().includes(r)).sort((e,t)=>e.name.localeCompare(t.name));return typeof n==`number`&&Number.isFinite(n)?i.slice(0,Math.max(0,n)):i}function yf(e,t,n){let r=t.trim().replace(/\s+/g,` `),i=bf(n,e.length);if(!r)return{value:e,cursorIndex:i};let a=e.slice(0,i),o=e.slice(i),s=a&&!/\s$/.test(a)?` `:``,c=o&&!/^\s/.test(o)?` `:``;return{value:`${a}${`${s}${r}${c}`}${o}`,cursorIndex:a.length+s.length+r.length+c.length}}function bf(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,Math.round(e))):t}async function xf({appendToEnd:e=!1,currentScopeKey:t,cursorIndex:n,originScopeKey:r,prompt:i,setOriginDraft:a,submit:o=!1,submitFromOrigin:s,transcript:c}){let l=yf(i,c,e?i.length:n);return a(l.value),t===r&&!o?`drafted`:await s(l.value)?(a(``),`submitted`):`retained`}var Sf=new Map,Cf=new Map,wf=new Map;function Tf(e){for(let t of Cf.get(e)??[])t()}function Ef(e){return Sf.has(e)}function Df(e){return Sf.get(e)?.submitRequested??!1}function Of(e,t){let n=Cf.get(e)??new Set;return n.add(t),Cf.set(e,n),()=>{n.delete(t),n.size===0&&Cf.delete(e)}}function kf(e){Sf.get(e)?.controller.abort()}function Af(e,t){let n=wf.get(e)??new Set;return n.add(t),wf.set(e,n),()=>{n.delete(t),n.size===0&&wf.delete(e)}}function jf(e){let t=Sf.get(e);if(t)return t.submitRequested||(t.submitRequested=!0,Tf(e)),!0;for(let t of wf.get(e)??[])if(t())return!0;return!1}function Mf(e,t,n={}){kf(e);let r=new AbortController,i={controller:r,promise:Promise.resolve(),submitRequested:n.submit??!1};return i.promise=Promise.resolve().then(()=>{if(!r.signal.aborted)return t(r.signal,()=>i.submitRequested)}).catch(e=>{if(!r.signal.aborted)throw e}).finally(()=>{Sf.get(e)===i&&(Sf.delete(e),Tf(e))}),Sf.set(e,i),Tf(e),i.promise}function Nf(e,t){return t?e.find(e=>e.idempotencyKey===t.key&&e.senderKind===`user`&&e.kind===t.kind&&e.body===t.body&&[`pending`,`included`,`resolved`].includes(e.state))??null:null}function Pf(e,t,n){let r=e??{sessionId:t,activeTurnId:null,acceptingInput:!1,paused:!1,inputs:[],waits:[]},i=r.inputs.find(e=>e.id===n.id);return i&&(i.revision>n.revision||i.revision===n.revision&&i.updatedAt>n.updatedAt)?r:{...r,inputs:[...r.inputs.filter(e=>e.id!==n.id),n].sort((e,t)=>e.sequence-t.sequence)}}var Ff=new Set([`task.inbox`,`task.input`,`task.wait`,`turn.started`,`turn.completed`,`turn.failed`,`turn.interrupted`,`approval.requested`,`approval.resolved`]);function If(e){try{let t=JSON.parse(sessionStorage.getItem(e)??`null`);return t&&typeof t.body==`string`&&typeof t.key==`string`&&(t.kind===`steer`||t.kind===`queued`)?t:null}catch{return null}}function Lf(e,t,n){let r=u(),i=ra(e),a=(0,Q.useMemo)(()=>[`task-inbox`,i,t],[i,t]),o=!!(e&&t),s=S({queryKey:a,enabled:o,staleTime:0,refetchOnWindowFocus:!0,refetchOnReconnect:!0,queryFn:()=>co.taskInbox(e,t),refetchInterval:e=>e.state.data?.inputs.some(e=>e.state===`pending`)?2e3:e.state.data?.paused?1e4:!1}),[c,l]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)({}),h=`${i}:${t}`,g=p[h],_;for(let e=n.length-1;e>=0;e--){let r=n[e];if(r.sessionId===t&&Ff.has(r.name)){_=r.id;break}}let v=(0,Q.useCallback)(async()=>{o&&await r.invalidateQueries({queryKey:a,exact:!0})},[o,r,a]);(0,Q.useEffect)(()=>{v()},[v,_]),(0,Q.useEffect)(()=>{let e=()=>{v()};return window.addEventListener(`openpond-runtime-connected`,e),()=>window.removeEventListener(`openpond-runtime-connected`,e)},[v]);async function y(e,n){if(!o)return!1;l({scope:h,id:e}),f(null);try{let e=await n();return await r.cancelQueries({queryKey:a,exact:!0}),r.setQueryData(a,n=>Pf(n,t,e)),v(),!0}catch(t){let n=r.getQueryData(a)?.inputs.find(t=>t.idempotencyKey===e);return n&&[`pending`,`included`,`resolved`].includes(n.state)?!0:(f({scope:h,message:t instanceof Error?t.message:String(t)}),v(),!1)}finally{l(t=>t?.scope===h&&t.id===e?null:t)}}async function b(n,r,i,a,o){if(!e||!t)return!1;let c=`openpond:task-input:${e.serverUrl}:${t}`,l=If(c),u=l?.body===r&&l.kind===n&&JSON.stringify(l.request)===JSON.stringify(i)&&JSON.stringify(l.resourceContexts)===JSON.stringify(a)&&JSON.stringify(l.attachments)===JSON.stringify(o),d=u?l:{body:r,kind:n,request:i,resourceContexts:a,attachments:o,key:crypto.randomUUID(),turnId:n===`steer`?s.data?.activeTurnId??null:null};if(n===`steer`&&(!d.turnId||!u&&!s.data?.acceptingInput))return f({scope:h,message:`This turn is no longer accepting steering. Your text is still in the composer; send it as a follow-up or queue it.`}),v(),!1;try{sessionStorage.setItem(c,JSON.stringify(d))}catch{}n===`queued`&&m(e=>({...e,[h]:d}));let p=await y(d.key,async()=>{let i;try{i=await(n===`steer`?co.steerTurn(e,t,{prompt:r,expectedTurnId:d.turnId,idempotencyKey:d.key,resourceContexts:d.resourceContexts,attachments:d.attachments}):co.queueTaskInput(e,t,d.request,d.key))}catch(e){if(e instanceof Ti&&e.status>=400&&e.status<500)try{sessionStorage.removeItem(c)}catch{}throw e}if(i.state===`rejected`||i.state===`cancelled`){try{sessionStorage.removeItem(c)}catch{}throw Error(i.error??`This input was cancelled. Review your text before sending again.`)}return i});if(n===`queued`&&m(e=>{if(e[h]?.key!==d.key)return e;let t={...e};return delete t[h],t}),p)try{If(c)?.key===d.key&&sessionStorage.removeItem(c)}catch{}return p}let x=e&&t?`openpond:task-input:${e.serverUrl}:${t}`:null,C=x?If(x):null,w=Nf(s.data?.inputs??[],C);return{pendingQueue:g&&!s.data?.inputs.some(e=>e.idempotencyKey===g.key)?{id:g.key,body:g.body,attachments:g.request?.attachments??[]}:null,acknowledgedInput:w,acknowledgeRetainedInput:()=>{if(x&&w&&If(x)?.key===w.idempotencyKey){try{sessionStorage.removeItem(x)}catch{}l(e=>e?.scope===h&&e.id===w.idempotencyKey?null:e)}},enabled:o,snapshot:s.data??null,busyId:c?.scope===h?c.id:null,error:d?.scope===h?d.message:s.error?.message??null,steer:(e,t,n)=>b(`steer`,e,void 0,t,n),queue:e=>b(`queued`,e.prompt,e),mutate:(n,r)=>y(n.id,()=>co.updateTaskInput(e,t,n.id,r)),refresh:v}}function Rf(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`steer-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,9)}`}function zf(e,t=120){let n=e.trim().replace(/\s+/g,` `);return n.length<=t?n:`${n.slice(0,Math.max(0,t-1)).trimEnd()}...`}function Bf(e,t={}){let n=t.now??new Date().toISOString();return{...t.resourceContexts?{resourceContexts:structuredClone(t.resourceContexts)}:{},...t.attachments?.length?{attachments:structuredClone(t.attachments)}:{},createdAt:n,id:t.id??Rf(),prompt:e,updatedAt:n}}function Vf(e,t){return e.filter(e=>e.id!==t)}function Hf(e,t,n){return n?Vf(e,t):e}function Uf(e,t,n=[]){return e[t]??n}function Wf(e,t,n,r=[]){let i=Uf(e,t,r),a=n(i);return Object.is(i,a)?e:{...e,[t]:a}}function Gf({prompt:e,attachments:t=[],sending:n=!1,disabled:r=!1,actionLabel:i=`Steer`,actionDisabledReason:a,onSend:o,onDelete:s,onEdit:c}){let l=t.find(e=>e.kind===`image`&&e.contentsBase64)??t[0],u=t.map(e=>e.name).join(`, `);return(0,$.jsxs)(`div`,{className:`composer-steer-row ${n?`sending`:``}`,children:[(0,$.jsx)(`span`,{className:`composer-steer-row-icon`,"aria-hidden":!l||void 0,role:l?`img`:void 0,"aria-label":l?`Attachments: ${u}`:void 0,title:l?u:void 0,children:l?(0,$.jsx)(Kf,{attachment:l}):(0,$.jsx)(au,{size:13})}),(0,$.jsx)(`span`,{className:`composer-steer-row-text`,title:[e,...t.map(e=>e.name)].join(`
6
+ `):e.command===`agent`?e.args?`/agent ${e.args}`:`/agent`:e.command===`skill`?e.args?`/skill ${e.args}`:`/skill`:e.args?`/${e.command} ${e.args}`:`/${e.command}`}function nd(e,t){return{surface:`chat`,workflowKind:`slash_command`,commandName:`/${e.command}`,commandSource:t}}function rd(e){return e.command===`goal`||e.command===`agent`||e.command===`skill`||e.command===`workflow`||e.command===`sync-cloud`}function id(e){let t=e?.trim()??``;return/^[a-z0-9]{24}$/.test(t)?t:null}function ad(e,t){if(!t.row.isConnected||t.row.parentElement!==e)return null;let n=Number.parseFloat(e.style.getPropertyValue(`--chat-sent-message-space`))||0,r=Number.parseFloat(getComputedStyle(e).paddingBottom)-n,i=e.lastElementChild,a=i?i.getBoundingClientRect().bottom-t.row.getBoundingClientRect().top+r:r,o=Math.max(0,e.clientHeight-96-a);return Math.abs(o-n)>.5&&e.style.setProperty(`--chat-sent-message-space`,`${o}px`),Math.max(0,Ku(e,t.row)-96)}function od(e,t,n){let r=e=>{e.deltaY<0?t():e.deltaY>0&&n?.()},i=null,a=e=>{i=e.touches[0]?.clientY??null},o=e=>{let r=e.touches[0]?.clientY??null;r!==null&&i!==null&&r>i?t():r!==null&&i!==null&&r<i&&n?.(),i=r},s=e=>{e.target?.closest?.(`input, textarea, select, [contenteditable='true']`)||([`ArrowUp`,`PageUp`,`Home`].includes(e.key)||e.key===` `&&e.shiftKey?t():([`ArrowDown`,`PageDown`,`End`].includes(e.key)||e.key===` `&&!e.shiftKey)&&n?.())},c=n=>{if(n.target!==e)return;let r=e.getBoundingClientRect().left+e.clientLeft+e.clientWidth;n.clientX>=r&&t()};return e.addEventListener(`openpond-visual-interaction`,t),e.addEventListener(`wheel`,r,{passive:!0}),e.addEventListener(`touchstart`,a,{passive:!0}),e.addEventListener(`touchmove`,o,{passive:!0}),e.addEventListener(`keydown`,s),e.addEventListener(`pointerdown`,c),()=>{e.removeEventListener(`openpond-visual-interaction`,t),e.removeEventListener(`wheel`,r),e.removeEventListener(`touchstart`,a),e.removeEventListener(`touchmove`,o),e.removeEventListener(`keydown`,s),e.removeEventListener(`pointerdown`,c)}}function sd(e){let t=e.getBoundingClientRect().top;for(let n of Array.from(e.children)){let e=n.getBoundingClientRect();if(!(e.bottom<=t))return{row:n,offset:e.top-t}}return null}function cd(e,t){if(t.row.parentElement!==e)return;let n=t.row.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=n-t.offset}function ld(e){let{contentKey:t,threadElement:n=null,enabled:r=!0,onContentChange:i,threadRef:a}=e,o=(0,Q.useRef)(i),s=(0,Q.useRef)(null);o.current=i,(0,Q.useLayoutEffect)(()=>{let e=n??a.current;if(!r||!e||typeof window>`u`)return;let t=null,i=0,c=e.scrollHeight,l=(n=!0)=>{n&&(i=Math.max(i,4)),t===null&&(t=window.requestAnimationFrame(()=>{t=null,a.current===e&&o.current(e);let n=Math.abs(e.scrollHeight-c)>1;c=e.scrollHeight,--i,(i>0||n)&&l(!1)}))};s.current=()=>l();let u=typeof MutationObserver>`u`?null:new MutationObserver(()=>{p(),l()}),d=typeof ResizeObserver>`u`?null:new ResizeObserver(()=>l()),f=new Set,p=()=>{if(!d)return;let t=new Set(Array.from(e.children).filter(e=>e instanceof HTMLElement));for(let e of f)t.has(e)||(d.unobserve(e),f.delete(e));for(let e of t)f.has(e)||(d.observe(e),f.add(e))};u?.observe(e,{childList:!0,characterData:!0,subtree:!0}),p();let m=()=>l();return e.addEventListener(`load`,m,!0),()=>{s.current=null,u?.disconnect(),d?.disconnect(),e.removeEventListener(`load`,m,!0),t!==null&&window.cancelAnimationFrame(t)}},[r,n,a]),(0,Q.useLayoutEffect)(()=>{r&&s.current?.()},[t,r])}function ud({navigationVersion:e=0,browserConversationId:t,chatSubmissionVersion:n,chatHistoryHasMore:r,chatHistoryLoading:i,chatMessages:a,onLoadMoreChatHistory:o,pendingApproval:s,showChatThread:c,showThinkingIndicator:l,turnRunning:u,view:d}){let f=(0,Q.useRef)(null),[p,m]=(0,Q.useState)(null),h=(0,Q.useCallback)(e=>{f.current=e,m(t=>t===e?t:e)},[]),g=(0,Q.useRef)(null),_=(0,Q.useRef)(!0),v=(0,Q.useRef)(null),y=(0,Q.useRef)(!1),b=(0,Q.useRef)(0),x=(0,Q.useRef)(null),S=(0,Q.useRef)(0),C=(0,Q.useRef)(0),w=(0,Q.useRef)(0),T=(0,Q.useRef)(null),E=(0,Q.useRef)(null),D=(0,Q.useRef)(null),O=(0,Q.useRef)(!1),[k,A]=(0,Q.useState)(0),j=(0,Q.useRef)(!1),M=(0,Q.useRef)(!1),N=(0,Q.useRef)(null),P=(0,Q.useRef)(null),F=(0,Q.useRef)(null),[I,L]=(0,Q.useState)(0),[ee,R]=(0,Q.useState)(null),[z,B]=(0,Q.useState)(!1),[V,H]=(0,Q.useState)(132),[U,te]=(0,Q.useState)(Uu),ne=(0,Q.useMemo)(()=>pu(a,{showThinkingIndicator:l}),[a,l]),re=(0,Q.useMemo)(()=>({"--chat-composer-reserve":`${V}px`}),[V]),W=a.at(-1),ie=[ne.length,W?.id??``,W?.content?.length??0,W?.timestamp??``,JSON.stringify(W?.resources??[]),l?`thinking`:``].join(`:`),G=r,ae=t,K=d===`chat`&&c&&!!ae&&ee!==ae,q=(0,Q.useCallback)(e=>{B(t=>t===e?t:e)},[]),oe=(0,Q.useCallback)(e=>{te(t=>t.canGoPrevious===e.canGoPrevious&&t.canGoNext===e.canGoNext?t:e)},[]),se=(0,Q.useCallback)((e,t={})=>{let n=t.nearBottom??Hu(e);q(!n),oe(Xu(e))},[q,oe]),ce=(0,Q.useCallback)(e=>{let t=j.current;j.current=!1,R(e),q(!1),oe(Uu),t&&L(e=>e+1)},[q,oe]),le=(0,Q.useCallback)(()=>{F.current!==null&&typeof window<`u`&&(window.cancelAnimationFrame(F.current),F.current=null)},[]),ue=(0,Q.useCallback)((e,t,n)=>{le();let r=Math.max(0,e.scrollHeight-e.clientHeight),i=()=>{let n=typeof t==`function`?t():t;return Math.max(0,Math.min(n,Math.max(0,e.scrollHeight-e.clientHeight)))},a=Math.max(0,Math.min(i(),r)),o=e.scrollTop,s=a-o;if(typeof window>`u`||window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches===!0||Math.abs(s)<1){e.scrollTop=a,n?.();return}let c=Qu(s),l=window.performance.now(),u=t=>{if(f.current!==e){F.current=null;return}let r=Math.min(1,(t-l)/c),a=i();e.scrollTop=o+(a-o)*$u(r),r<1?F.current=window.requestAnimationFrame(u):(e.scrollTop=i(),F.current=null,n?.())};F.current=window.requestAnimationFrame(u)},[le]),de=(0,Q.useCallback)(()=>{M.current=!1,N.current!==null&&typeof window<`u`&&(window.cancelAnimationFrame(N.current),N.current=null)},[]),fe=(0,Q.useCallback)(()=>{P.current!==null&&typeof window<`u`&&(window.cancelAnimationFrame(P.current),P.current=null)},[]),pe=(0,Q.useCallback)(e=>{if(typeof window>`u`){e.scrollTop=e.scrollHeight;return}if(P.current!==null)return;let t=window.performance.now(),n=r=>{if(f.current!==e||!_.current){P.current=null;return}let i=Math.max(0,e.scrollHeight-e.clientHeight),a=i-e.scrollTop;if(Math.abs(a)<=1)e.scrollTop=i,P.current=null;else{if(a<0||a>240)e.scrollTop=i;else{let n=Math.max(.5,Math.min(3,(r-t)/(1e3/60))),i=1-.78**n;e.scrollTop+=Math.min(a,Math.max(1,Math.min(36*n,a*i)))}t=r,P.current=window.requestAnimationFrame(n)}};P.current=window.requestAnimationFrame(n)},[]),me=(0,Q.useCallback)((e,t={})=>{if(fe(),e.scrollTop=e.scrollHeight,typeof window>`u`){t.finishInitial&&ce(t.conversationKey??null);return}de(),M.current=!0;let n=0,r=0,i=e.scrollHeight,a=t.settle?12:2,o=()=>{let e=f.current;if(!e){N.current=null,M.current=!1,t.finishInitial&&ce(t.conversationKey??null);return}e.scrollTop=e.scrollHeight;let s=e.scrollHeight-e.scrollTop-e.clientHeight,c=Math.abs(e.scrollHeight-i)<=1;i=e.scrollHeight,r=s<=1&&c?r+1:0,n+=1,n<a&&r<2?N.current=window.requestAnimationFrame(o):(N.current=null,M.current=!1,_.current=!0,q(!1),oe(Xu(e)),t.finishInitial&&ce(t.conversationKey??null))};N.current=window.requestAnimationFrame(o)},[de,fe,ce,q,oe]),he=(0,Q.useCallback)(()=>{v.current=null,f.current?.style.removeProperty(`--chat-sent-message-space`);let e=f.current;e&&(de(),fe(),_.current=!0,q(!1),ue(e,()=>e.scrollHeight-e.clientHeight,()=>{f.current===e&&(e.scrollTop=e.scrollHeight,_.current=!0,q(!1),oe(Xu(e)))}))},[de,fe,q,oe,ue]),ge=(0,Q.useCallback)(e=>{v.current=null,e.style.removeProperty(`--chat-sent-message-space`),le(),_.current=!0,me(e,{settle:!0}),se(e,{nearBottom:!0})},[le,me,se]),_e=(0,Q.useCallback)(e=>{let t=f.current;if(!t)return;let n=Zu(t,e);n&&(de(),fe(),v.current&&(v.current.following=!1),ue(t,()=>n.isConnected?Math.max(0,Ku(t,n)-24):t.scrollTop,()=>{if(f.current!==t)return;let e=Hu(t);_.current=e,se(t,{nearBottom:e})}))},[de,fe,ue,se]),ve=(0,Q.useCallback)(async()=>{if(!G||!o||i||D.current)return;let e=f.current;if(!e)return;let t={anchor:sd(e),firstRowId:ne[0]?.id,settled:!1};E.current=t,_.current=!1,de(),fe(),le(),D.current=t,O.current=!1;try{let e=await o();D.current===t&&(O.current=!e),!e&&E.current===t&&(E.current=null)}catch{D.current===t&&(O.current=!0,E.current=null)}finally{t.settled=!0,D.current===t&&(D.current=null,A(e=>e+1))}},[G,i,o,ne,de,fe,le]),ye=(0,Q.useCallback)(e=>{let t=E.current;t&&(t.anchor=sd(e));let n=Hu(e),r=Math.abs(e.scrollHeight-C.current)>1||Math.abs(e.clientHeight-w.current)>1,a=e.scrollTop<S.current-1,o=e.scrollTop>S.current+1,s=n&&o&&(!r||e.scrollHeight-e.scrollTop-e.clientHeight<=1);if(S.current=e.scrollTop,C.current=e.scrollHeight,w.current=e.clientHeight,v.current)!v.current.following&&s?ge(e):(_.current=!1,se(e));else if(M.current){if(a&&!r)de(),ce(T.current),_.current=!1,se(e,{nearBottom:!1});else{_.current=!0,q(!1),oe(Uu);return}}else n&&(_.current||s)?(_.current=!0,se(e,{nearBottom:!0})):a&&!r?(_.current=!1,fe(),se(e,{nearBottom:!1})):_.current?(q(!1),oe(Xu(e))):se(e,{nearBottom:n});!j.current&&e.scrollTop<=120&&G&&!i&&ve()},[G,de,fe,ce,i,ve,ge,q,oe,se]),be=(0,Q.useCallback)(e=>{let t=v.current;if(t){let n=ad(e,t);if(n!==null&&t.following&&F.current===null){if(e.scrollHeight-e.clientHeight>n+1){ge(e);return}e.scrollTop=n}se(e)}else _.current&&F.current===null&&!M.current&&pe(e)},[pe,ge,se]);return(0,Q.useEffect)(()=>{let e=p;if(!e)return;let t=null,n=()=>{t!==null&&window.cancelAnimationFrame(t),t=null},r=()=>{n(),v.current&&(v.current.following=!1),_.current=!1,S.current=e.scrollTop,C.current=e.scrollHeight,w.current=e.clientHeight,de(),fe(),le(),j.current&&ce(T.current)},i=()=>{v.current&&r()},a=e=>{[`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `].includes(e.key)&&i()},o=()=>{n();let r=Hu(e),i=T.current;t=window.requestAnimationFrame(()=>{t=null,f.current===e&&T.current===i&&(r||Hu(e))&&(!_.current||v.current)&&ge(e)})};e.addEventListener(`wheel`,i,{passive:!0}),e.addEventListener(`touchmove`,i,{passive:!0}),e.addEventListener(`pointerdown`,i),e.addEventListener(`keydown`,a);let s=od(e,r,o);return()=>{n(),s(),e.removeEventListener(`wheel`,i),e.removeEventListener(`touchmove`,i),e.removeEventListener(`pointerdown`,i),e.removeEventListener(`keydown`,a)}},[p,de,fe,le,ce,ge]),(0,Q.useEffect)(()=>{if(!p||typeof ResizeObserver>`u`)return;let e=new ResizeObserver(()=>{v.current&&be(p)});return e.observe(p),()=>e.disconnect()},[p,be]),ld({contentKey:ie,enabled:d===`chat`&&c,onContentChange:be,threadElement:p,threadRef:f}),(0,Q.useLayoutEffect)(()=>{if(d!==`chat`||!c||typeof window>`u`)return;let e=g.current;if(!e)return;let t=null,n=()=>{t=null;let n=Math.max(0,Math.ceil(e.getBoundingClientRect().height));H(e=>e===n?e:n)},r=()=>{t===null&&(t=window.requestAnimationFrame(n))};n();let i=window.ResizeObserver===void 0?null:new window.ResizeObserver(r);return i?.observe(e),window.addEventListener(`resize`,r),()=>{t!==null&&window.cancelAnimationFrame(t),i?.disconnect(),window.removeEventListener(`resize`,r)}},[c,d]),(0,Q.useLayoutEffect)(()=>{let e=f.current;d===`chat`&&c&&e&&!j.current&&(v.current?be(e):_.current&&me(e,{settle:!0}))},[V,be,me,c,d]),(0,Q.useLayoutEffect)(()=>{v.current=null,y.current=!1,f.current?.style.removeProperty(`--chat-sent-message-space`),E.current=null,D.current=null,O.current=!1,j.current=!0,_.current=!0,S.current=0,C.current=0,w.current=0,fe(),le(),de(),R(null),q(!1),oe(Uu)},[de,le,fe,ae,e,q,oe]),(0,Q.useLayoutEffect)(()=>{if(n===0||n===b.current||d!==`chat`||!c)return;let e=f.current,t=e?Wu(e).at(-1):void 0;if(!e||!t||t===x.current)return;b.current=n,de(),fe();let r={row:t,following:!0};v.current=r,_.current=!1,ad(e,r),ue(e,()=>ad(e,r)??e.scrollTop,()=>be(e)),ce(ae)},[n,ne,p,ae,d,c,de,fe,ue,ce,be]),(0,Q.useLayoutEffect)(()=>{let e=f.current;x.current=e?Wu(e).at(-1)??null:null}),(0,Q.useLayoutEffect)(()=>{if(u){y.current=!0;return}let e=a.length-1;for(;e>=0&&a[e]?.role!==`user`;)e--;let t=a.slice(e+1).some(e=>e.role===`assistant`&&e.finalAnswer);if(!y.current&&!t)return;y.current=!1;let n=f.current,r=v.current;n&&r&&(v.current=null,n.style.removeProperty(`--chat-sent-message-space`),le(),_.current=r.following,r.following&&me(n,{settle:!0}),se(n))},[a,u,le,me,se]),(0,Q.useEffect)(()=>{let e=f.current;d!==`chat`||!e||j.current||!G||i||O.current||e.scrollTop<=120&&ve()},[G,i,I,k,ne.length,ve,d]),(0,Q.useLayoutEffect)(()=>{let e=E.current,t=f.current;e&&t&&!j.current&&(ne[0]?.id===e.firstRowId?e.settled&&!i&&(E.current=null):(E.current=null,e.anchor&&cd(t,e.anchor),se(t)))},[ne,i,se]),(0,Q.useLayoutEffect)(()=>{let e=f.current;if(d!==`chat`||!ae){T.current=ae,_.current=!0,ce(ae);return}if(!e)return;let t=T.current!==ae;if(i&&(t||j.current))return;if(T.current=ae,v.current){ce(ae);return}if(t||j.current){_.current=!0,me(e,{conversationKey:ae,finishInitial:!0,settle:!0});return}let n=Hu(e);_.current?(_.current=!0,q(!1),oe(Xu(e)),me(e,{settle:!0})):se(e,{nearBottom:n})},[ae,e,i,p,ce,s?.id,me,q,oe,se,d]),(0,Q.useEffect)(()=>()=>{de(),le(),fe()},[de,le,fe]),{chatColumnStyle:re,chatThreadPreparingInitialScroll:K,chatThreadRef:h,composerStackRef:g,goToUserMessage:_e,handleChatScroll:ye,jumpToLatestChatMessage:he,showScrollToBottomButton:z,userMessageNavigation:U,chatTimelineRows:ne}}var dd=(0,Q.lazy)(()=>o(()=>import(`./MainChatThread-BSvKu4e5.js`).then(e=>({default:e.MainChatThread})),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67])));function fd({scroll:e,thread:t,composer:n,composerPrefix:r,hasApproval:i=!1,className:a=``}){let o=ud(e);return(0,$.jsx)(wu,{conversationKey:e.browserConversationId??`draft`,messages:e.chatMessages,enabled:!!n&&e.turnRunning,children:(0,$.jsxs)(`div`,{className:`chat-column ${i?`has-approval`:``} ${a}`,style:o.chatColumnStyle,children:[(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(dd,{...t,rows:o.chatTimelineRows,threadRef:o.chatThreadRef,onScroll:e=>o.handleChatScroll(e.currentTarget),sessionId:e.browserConversationId,conversationKey:e.browserConversationId??`draft`,turnRunning:e.turnRunning})}),(0,$.jsxs)(`div`,{className:`composer-stack dock ${i?`has-approval`:``}`,ref:o.composerStackRef,children:[r,o.showScrollToBottomButton&&!o.chatThreadPreparingInitialScroll?(0,$.jsx)(Fu,{canGoNext:o.userMessageNavigation.canGoNext,canGoPrevious:o.userMessageNavigation.canGoPrevious,onJumpToLatest:o.jumpToLatestChatMessage,onNext:()=>{o.userMessageNavigation.canGoNext&&o.goToUserMessage(`next`)},onPrevious:()=>{o.userMessageNavigation.canGoPrevious&&o.goToUserMessage(`previous`)}}):null,n]})]})})}function pd({connection:e,conversationId:t,messages:n,loading:r,running:i,hasMore:a=!1,loadOlder:o,children:s,usageSessionId:c=t}){return(0,$.jsx)(fd,{className:`ponder-agent-conversation`,scroll:{browserConversationId:t,chatSubmissionVersion:0,chatMessages:n,chatHistoryHasMore:a,chatHistoryLoading:r,onLoadMoreChatHistory:o,pendingApproval:null,showChatThread:!0,showThinkingIndicator:i,turnRunning:i,view:`chat`},thread:{connection:e,usageSessionId:c,label:`Agent conversation`,loading:r,afterMessages:s}})}var md=Object.freeze({events:[],messages:[]}),hd=class{projection=md;project(e){if(e===this.projection.events)return this.projection.messages;if(!vd(this.projection.events,e))return this.replace(e);let t=e.slice(this.projection.events.length);if(t.length===0)return this.projection={events:e,messages:this.projection.messages},this.projection.messages;let n=gd(this.projection.messages,t);if(n)return this.projection={events:e,messages:n},n;let r=_d(e,this.projection.events.length);if(!r)return this.replace(e);let i=e.slice(r.eventIndex),a=new Set(i.flatMap(e=>e.turnId?[e.turnId]:[])),o=this.projection.messages.filter(e=>!e.turnId||!a.has(e.turnId)),s=oo(i),c=new Set(o.map(e=>e.id));if(s.some(e=>c.has(e.id)))return this.replace(e);let l=[...o,...s];return this.projection={events:e,messages:l},l}reset(){this.projection=md}snapshot(){return this.projection}replace(e){let t=oo(e);return this.projection={events:e,messages:t},t}};function gd(e,t){if(t.length===0||e.length===0)return null;let n=e[e.length-1];if(n?.role!==`assistant`||n.createImproveRun||t.some(e=>e.name!==`assistant.delta`&&e.name!==`assistant.reasoning.delta`||typeof io(e.data)?.nativeMessageId==`string`||e.turnId!==n.turnId||!e.output))return null;let r=n.content,i=n.reasoningContent,a=n.timestamp,o=!1,s=!1;for(let e of t)e.name===`assistant.delta`?(r=`${r??``}${e.output}`,o=!0):(i=`${i??``}${e.output}`,s=!0),a=e.timestamp;let c={...n,...o?{content:r}:{},...s?{reasoningContent:i}:{},timestamp:a};return[...e.slice(0,-1),c]}function _d(e,t){let n=e[t];if(!n?.turnId)return null;let r=e.findIndex(e=>e.turnId===n.turnId);return r<0?null:{eventIndex:r}}function vd(e,t){return e.length===0?!0:e.length>=t.length?!1:e[0]===t[0]&&e[e.length-1]===t[e.length-1]}function yd(e,t){let n=new Map(e.events.map(e=>[e.id,e]));for(let e of t)n.set(e.id,e);let r=[...n.values()].sort((e,t)=>(e.sequence??0)-(t.sequence??0));return{...e,events:r,cursor:Math.max(e.cursor,...t.map(e=>e.sequence??0))}}function bd(e){return{events:e.events.map(e=>({...e.event,sequence:e.sequence})),cursor:e.nextSequence,before:e.previousSequence,hasMore:e.hasMore}}var xd=[];function Sd(e,t){let n=u(),r=ra(e),i=(0,Q.useMemo)(()=>[`ponder-history`,r,t],[r,t]),a=(0,Q.useRef)(new hd),o=S({queryKey:i,enabled:!!t,staleTime:1/0,gcTime:6e5,queryFn:async()=>bd(await Eo.runtimeEventsPage(e,{sessionId:t,beforeSequence:2**53-1,limit:200}))}),[s,c]=(0,Q.useState)(null),l=!!o.data;(0,Q.useEffect)(()=>{if(!t||!l)return;let r=n.getQueryData(i);if(!r)return;let a=xo(e,e=>{e.sessionId===t&&n.setQueryData(i,t=>t&&yd(t,[e]))},()=>{},void 0,{afterSequence:r.cursor,fetchImpl:(e,n)=>{let r=new URL(String(e));return r.searchParams.set(`sessionId`,t),fetch(r,n)}});return()=>a.close()},[e,t,l,i,n]);async function d(){let r=n.getQueryData(i);if(!t||!r?.hasMore||s?.key===i&&s.loading)return!1;c({key:i,loading:!0,error:null});try{let a=bd(await Eo.runtimeEventsPage(e,{sessionId:t,beforeSequence:r.before,limit:200}));return n.setQueryData(i,e=>e&&{...yd(e,a.events),before:a.before,hasMore:a.hasMore}),c({key:i,loading:!1,error:null}),a.events.length>0}catch(e){return c({key:i,loading:!1,error:e instanceof Error?e.message:String(e)}),!1}}let f=o.data?.events??xd,p=(0,Q.useMemo)(()=>a.current.project(f),[f]),m=[...f].reverse().find(e=>[`turn.started`,`turn.completed`,`turn.failed`,`turn.interrupted`].includes(e.name));return{events:f,messages:p,error:s?.key===i&&s.error?s.error:o.error?.message??null,loading:!!t&&o.isPending||s?.key===i&&s.loading===!0,hasMore:o.data?.hasMore??!1,loadOlder:d,running:m?.name===`turn.started`}}var Cd=[];function wd(e,t){let n=t?.id.startsWith(`codex_history_`)===!0,r=t?.metadata?.nativeHistoryId,i=n||typeof r==`string`,a=Sd(e,i?null:t?.id??null),[o,s]=(0,Q.useState)({sessionId:t?.id,limit:500}),c=o.sessionId===t?.id?o.limit:500,l=(0,Q.useRef)(new hd),u=S({queryKey:[`native-agent-transcript`,ra(e),t?.id,c],enabled:!!(t&&i),staleTime:2e3,gcTime:6e5,refetchInterval:3e3,queryFn:async()=>{if(n){let n=await Eo.codexHistoryThread(e,t.id,{limit:c,tail:!0});return{events:n.events,hasMore:n.events.length>=c}}await Y(e,`/v1/native-history/open`,{method:`POST`,body:JSON.stringify({id:r})});let i=[],a=2**53-1,o=!1;do{let n=await Eo.runtimeEventsPage(e,{sessionId:t.id,beforeSequence:a,limit:Math.min(200,c-i.length)});if(i.unshift(...n.events.map(e=>e.event)),o=n.hasMore,!o||n.previousSequence===a)break;a=n.previousSequence}while(i.length<c);return{events:i,hasMore:o}}}),d=u.data?.events??Cd,f=(0,Q.useMemo)(()=>l.current.project(d),[d]),p=[...d].reverse().find(e=>[`turn.started`,`turn.completed`,`turn.failed`,`turn.interrupted`].includes(e.name));return i?{events:d,messages:f,error:u.error?.message??null,loading:u.isPending,hasMore:u.data?.hasMore??!1,loadOlder:async()=>{s({sessionId:t?.id,limit:c+500})},running:p?.name===`turn.started`}:a}function Td(e,t){let n={turnId:e.remoteTurnId??e.id,timestamp:``,source:`provider`},r=[{...n,id:`${e.id}:prompt`,name:`turn.started`,timestamp:e.createdAt,args:{prompt:e.assignment}}];for(let e of t)if(e.type===`assistant.delta`||e.type===`assistant.reasoning.delta`)e.text&&r.push({...n,id:e.id,name:e.type,output:e.text});else if([`tool.started`,`tool.completed`,`tool.failed`].includes(e.type)){let t=/^([A-Za-z][A-Za-z0-9_.:-]{0,95}): (?:started|completed|failed|updated)$/.exec(e.text??``)?.[1];r.push({...n,id:e.id,name:e.type===`tool.started`?`tool.started`:`tool.completed`,action:t??`tool`,status:e.type===`tool.started`?`started`:e.type===`tool.failed`?`failed`:`completed`})}let i=[`completed`,`failed`,`cancelled`].includes(e.state),a=e.resultText?.trim();if(i&&a){let t=-1,i=-1;for(let e=0;e<r.length;e++)r[e].name===`assistant.delta`&&(t=e),(r[e].name===`tool.started`||r[e].name===`tool.completed`)&&(i=e);let o=t;for(;o>0&&r[o-1]?.name===`assistant.delta`;)o--;let s=t<0?``:r.slice(o,t+1).map(e=>e.output??``).join(``);t>=0&&(t>i||s.trim()===a)?r.splice(o,t-o+1,{...n,id:r[o].id,name:`assistant.delta`,output:a,timestamp:``}):r.push({...n,id:`${e.id}:result`,name:`assistant.delta`,output:a,timestamp:``})}return i&&r.push({...n,id:`${e.id}:terminal`,name:e.state===`failed`?`turn.failed`:e.state===`cancelled`?`turn.interrupted`:`turn.completed`,timestamp:``,...e.error?{error:e.error}:{}}),oo(r)}function Ed({connection:e,accountScopeKey:t,assignmentId:n,output:r}){let i=u(),a=JSON.stringify([ra(e),t,n]),o=(0,Q.useRef)(a);o.current=a;let[s,c]=(0,Q.useState)(!1),[l,d]=(0,Q.useState)(null);(0,Q.useEffect)(()=>(o.current=a,c(!1),d(null),()=>{o.current=null}),[a]),Ka(l);async function f(l){if(s)return;let u=a,f=window.open(`about:blank`,`_blank`);f&&(f.opener=null),c(!0),d(null);try{let a=await i.fetchQuery({queryKey:[`ponder-hosted-output`,ra(e),t,n,r.id],staleTime:0,gcTime:6e4,queryFn:({signal:t})=>Y(e,`/v1/ponder/local/hosted-agents/${encodeURIComponent(n)}/outputs/${encodeURIComponent(r.id)}`,{signal:t})});if(o.current!==u){f?.close();return}let s=l===`preview`?a.previewURL:a.downloadURL,c=s?no(s):null;if(!c)throw Error(l===`preview`?`This output is not available for preview.`:`This output is not available for download.`);f?f.location.replace(c):window.location.assign(c)}catch(e){f?.close(),o.current===u&&d(e instanceof Error?e.message:String(e))}finally{o.current===u&&c(!1)}}return(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`strong`,{children:r.name}),r.previewURL?(0,$.jsx)(`button`,{type:`button`,disabled:s,onClick:()=>void f(`preview`),children:`Preview`}):null,(0,$.jsx)(`button`,{type:`button`,disabled:s,"aria-label":`Download ${r.name}`,onClick:()=>void f(`download`),children:s?`Preparing…`:`Download`})]})}var Dd={preparing:`Preparing`,submitting:`Submitting`,running:`Working`,completed:`Completed`,needs_attention:`Needs attention`,failed:`Failed`,cancelled:`Cancelled`,unknown:`Status unknown`};function Od(e){try{return`Hosted sandbox · ${new URL(e.account.apiBaseUrl).host}`}catch{return`Hosted sandbox`}}function kd(e){if(typeof e==`string`)return e;if(e&&typeof e==`object`&&!Array.isArray(e)){let t=e;for(let e of[`label`,`title`,`text`,`name`,`value`])if(typeof t[e]==`string`)return t[e]}return JSON.stringify(e)??String(e)}function Ad({connection:e,accountScopeKey:t,assignment:n}){let r=u(),i=ra(e),a=[`ponder-hosted-agent`,i,t,n.id],o=`/v1/ponder/local/hosted-agents/${encodeURIComponent(n.id)}`,s=S({queryKey:a,staleTime:2e3,gcTime:6e5,refetchInterval:e=>[`completed`,`failed`,`cancelled`].includes(e.state.data?.assignment.state??``)?3e4:3e3,queryFn:({signal:t})=>Y(e,o,{signal:t})}),c=ds({mutationFn:()=>Y(e,`${o}/cancel`,{method:`POST`,body:`{}`}),onSuccess:e=>{r.setQueryData(a,e),r.invalidateQueries({queryKey:[`ponder-hosted-agents`,i]})},onError:()=>{s.refetch()}});Ka(s.error),Ka(c.error);let l=s.data?.assignment??n,d=(0,Q.useMemo)(()=>Td(l,s.data?.events??[]),[l,s.data?.events]),f=[`preparing`,`submitting`,`running`].includes(l.state);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`ponder-agent-assignment`,children:[(0,$.jsxs)(`span`,{children:[Od(l),` · `,Dd[l.state]]}),l.wait?(0,$.jsxs)(`div`,{className:`ponder-hosted-wait`,children:[(0,$.jsx)(`strong`,{children:l.wait.title}),(0,$.jsx)(`span`,{children:`This hosted assignment is waiting in its Work environment.`}),l.wait.options.length?(0,$.jsxs)(`dl`,{children:[(0,$.jsx)(`dt`,{children:`Recorded response options`}),l.wait.options.map((e,t)=>(0,$.jsx)(`dd`,{children:kd(e)},t))]}):null]}):null,l.canCancel?(0,$.jsx)(`button`,{type:`button`,disabled:c.isPending,onClick:()=>c.mutate(),children:`Cancel assignment`}):null]}),(0,$.jsxs)(pd,{connection:e,usageSessionId:null,conversationId:`hosted:${l.id}`,messages:d,loading:s.isPending,running:f,children:[!s.data&&!s.isPending?(0,$.jsx)(`button`,{type:`button`,onClick:()=>void s.refetch(),children:`Retry loading conversation`}):null,s.data?.outputs.length?(0,$.jsxs)(`section`,{className:`ponder-hosted-outputs`,"aria-label":`Assignment outputs`,children:[(0,$.jsx)(`h3`,{children:`Outputs`}),s.data.outputs.map(n=>(0,$.jsx)(Ed,{connection:e,accountScopeKey:t,assignmentId:l.id,output:n},`${t}:${l.id}:${n.id}`))]}):null]})]})}function jd({connection:e,accountScopeKey:t,agents:n,hostedAgents:r=[],onControl:i,onOpenChat:a,selectionRequest:o}){let[s,c]=(0,Q.useState)(null);(0,Q.useLayoutEffect)(()=>{o&&c({kind:`local`,id:o.sessionId})},[o]);let l=(0,Q.useRef)(null),u=(0,Q.useRef)(new Map),d=(0,Q.useRef)(null),f=(0,Q.useRef)(s);(0,Q.useLayoutEffect)(()=>{s?l.current?.focus():f.current&&u.current.get(`${f.current.kind}:${f.current.id}`)?.focus(),f.current=s},[s]),(0,Q.useLayoutEffect)(()=>{let e=d.current;d.current=null,!s&&e&&document.activeElement===document.body&&u.current.get(e)?.focus()});function p(e,t){t?u.current.set(e,t):(u.current.get(e)===document.activeElement&&(d.current=e),u.current.delete(e))}let m=s?.kind===`local`?n.find(e=>e.session.id===s.id):void 0,h=s?.kind===`hosted`?r.find(e=>e.id===s.id):void 0,g=wd(e,m?.session);Ka(g.error);let[_,v]=(0,Q.useState)(!1),[y,b]=(0,Q.useState)(null);Ka(y);async function x(e,t){v(!0);try{await i(e,t),b(null)}catch(e){b(ju(e))}finally{v(!1)}}async function S(e){v(!0);try{await a(e.session.id),b(null)}catch(e){b(ju(e))}finally{v(!1)}}function C(e){return[`working`,`queued`,`preparing`,`submitting`,`running`].includes(e)?`Active`:[`failed`,`waiting_approval`,`waiting`,`paused`,`interrupted`,`unknown`,`needs_attention`].includes(e)?`Needs attention`:`Done`}return(0,$.jsxs)(`section`,{className:`ponder-agents-view`,"aria-label":`Pal agents`,children:[(0,$.jsxs)(`header`,{children:[m||h?(0,$.jsx)(`button`,{ref:l,type:`button`,"aria-label":`Back to agents`,onClick:()=>c(null),children:(0,$.jsx)(so,{size:16})}):null,(0,$.jsx)(`h2`,{children:h?.title??m?.session.title??`Agents`})]}),h?(0,$.jsx)(Ad,{connection:e,accountScopeKey:t,assignment:h}):m?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`ponder-agent-assignment`,children:[m.session.metadata?.nativeWorkerCanResume===!1?(0,$.jsx)(`span`,{children:`Controlled by its parent conversation · Read-only transcript`}):null,m.owner?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{children:m.owner===`user`?`You are directing this agent`:`Pal is directing this agent`}),(0,$.jsx)(`button`,{type:`button`,disabled:_,onClick:()=>void x(m,m.owner===`ponder`?`user`:`ponder`),children:m.owner===`ponder`?`Take control`:`Return to Pal`})]}):(0,$.jsx)(`button`,{type:`button`,disabled:_,onClick:()=>void S(m),children:m.session.metadata?.nativeWorkerCanResume===!1?`Open transcript`:`Open chat`})]}),(0,$.jsx)(pd,{connection:e,conversationId:m.session.id,messages:g.messages,loading:g.loading,running:g.running,hasMore:g.hasMore,loadOlder:async()=>await g.loadOlder()!==!1})]}):(0,$.jsx)(`div`,{className:`ponder-agent-list`,children:n.length||r.length?[`Active`,`Needs attention`,`Done`].map(e=>{let t=n.filter(t=>C(t.status)===e),i=r.filter(t=>C(t.state)===e);return t.length||i.length?(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h3`,{children:e}),t.map(e=>(0,$.jsxs)(`div`,{className:`ponder-agent-row`,children:[(0,$.jsxs)(`button`,{ref:t=>p(`local:${e.session.id}`,t),type:`button`,onClick:()=>c({kind:`local`,id:e.session.id}),children:[(0,$.jsx)(Ho,{session:e.session}),(0,$.jsxs)(`span`,{children:[e.session.title,e.latestActivity||e.assignment!==e.session.title?(0,$.jsx)(`small`,{children:e.latestActivity??e.assignment}):null]})]}),e.owner?(0,$.jsx)(`button`,{type:`button`,disabled:_,onClick:()=>void x(e,e.owner===`ponder`?`user`:`ponder`),children:e.owner===`ponder`?`Take control`:`Return`}):(0,$.jsx)(`button`,{type:`button`,disabled:_,onClick:()=>void S(e),children:e.session.metadata?.nativeWorkerCanResume===!1?`Open transcript`:`Open chat`})]},e.session.id)),i.map(e=>(0,$.jsxs)(`div`,{className:`ponder-agent-row`,children:[(0,$.jsxs)(`button`,{ref:t=>p(`hosted:${e.id}`,t),type:`button`,onClick:()=>c({kind:`hosted`,id:e.id}),children:[(0,$.jsx)(Yo,{size:16}),(0,$.jsxs)(`span`,{children:[e.title,(0,$.jsxs)(`small`,{children:[Od(e),` · `,Dd[e.state]]})]})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>c({kind:`hosted`,id:e.id}),children:`Open conversation`})]},`hosted:${e.id}`))]},e):null}):null})]})}function Md({connection:e,ponder:t,accountScopeKey:n,parentSessionId:r,sessions:i,onOpenChat:a,selectionRequest:o}){let[s,c]=(0,Q.useState)([]),[l,u]=(0,Q.useState)(null);Ka(l),(0,Q.useEffect)(()=>{if(c([]),u(null),!t)return;let n=!0,r=!1;async function i(){if(!r){r=!0;try{let t=await Y(e,`/v1/ponder/local/agents`);n&&(c(t.items),u(null))}catch(e){n&&u(ju(e))}finally{r=!1}}}i();let a=window.setInterval(()=>void i(),3e3);return()=>{n=!1,window.clearInterval(a)}},[e,t,n]);let d=S({queryKey:[`ponder-hosted-agents`,ra(e),n],enabled:t,staleTime:2e3,refetchInterval:t?5e3:!1,queryFn:({signal:t})=>Y(e,`/v1/ponder/local/hosted-agents`,{signal:t})});Ka(d.error);let f=A({queryKey:[`native-agent-children`,ra(e),n,r],enabled:!(t||!r),staleTime:2e3,refetchInterval:3e3,initialPageParam:{},queryFn:({pageParam:t})=>Y(e,`/v1/native-history/children`,{method:`POST`,body:JSON.stringify({parentSessionId:r,...t})}),getNextPageParam:e=>e.beforeOffset===null?e.cursors&&Object.keys(e.cursors).length?{cursors:e.cursors}:void 0:{beforeOffset:e.beforeOffset}});Ka(f.error);let p=new Map(i.map(e=>[e.id,e]));for(let e of f.data?.pages??[])for(let t of e.items)p.set(t.id,t);let m=t?s:[...p.values()].filter(e=>r&&e.parentSessionId===r).map(e=>({session:e,status:e.status===`active`?`working`:e.status===`failed`?`failed`:`idle`,assignment:e.title,latestActivity:null}));async function h(t,n){let r=s.find(e=>e.session.id===t.session.id);if(!r)throw Error(`This agent has no Pal control relationship.`);let i=await Y(e,`/v1/ponder/local/agents/${encodeURIComponent(t.session.id)}/control`,{method:`POST`,body:JSON.stringify({owner:n,revision:r.revision})});c(e=>e.map(e=>e.session.id===i.session.id?i:e)),n===`user`&&await a(t.session.id)}async function g(t){let n=m.find(e=>e.session.id===t)?.session;if(n?.metadata?.nativeWorker&&n.hiddenFromDefaultSidebar){let n=`/v1/sessions/${encodeURIComponent(t)}`;await Y(e,n,{method:`PATCH`,body:JSON.stringify({hiddenFromDefaultSidebar:!1})})}await a(t)}return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(jd,{selectionRequest:o,connection:e,accountScopeKey:n,agents:m,hostedAgents:t?d.data?.items??[]:[],onControl:h,onOpenChat:g},t?`ponder:${n}`:r),!t&&f.hasNextPage?(0,$.jsx)(`button`,{type:`button`,disabled:f.isFetchingNextPage,onClick:()=>void f.fetchNextPage(),children:`Load earlier agents`}):null]})}function Nd({connection:e,sessionId:t,accountScope:n,active:r,onOpen:i}){let a=k(r?e:null,t,n);return(0,Q.useEffect)(()=>{let e=e=>{let n=e.detail;r&&n?.sessionId===t&&n.scope===a.scope&&i()};return window.addEventListener(j,e),()=>window.removeEventListener(j,e)},[r,t,a.scope,i]),a.selection?.target.kind===`dataset`?`Experiment draft`:a.selection?.model?.name??a.selection?.label??`Ponder`}function Pd(e){let[t,n]=(0,Q.useState)({tabs:[],activeId:null});(0,Q.useEffect)(()=>{n({tabs:[],activeId:null})},[e]),(0,Q.useEffect)(()=>window.openpond?.browser?.onRevealRequest?.(t=>{t.conversationId===e&&n(e=>({...e,activeId:null}))}),[e]);let r=(0,Q.useCallback)(e=>{n(t=>({tabs:t.tabs.some(t=>t.publicationId===e.publicationId)?t.tabs:[...t.tabs,e],activeId:e.publicationId}))},[]),i=(0,Q.useCallback)(e=>{n(t=>{let n=t.tabs.findIndex(t=>t.publicationId===e),r=t.tabs.filter(t=>t.publicationId!==e);return{tabs:r,activeId:t.activeId===e?r[Math.min(n,r.length-1)]?.publicationId??null:t.activeId}})},[]),a=(0,Q.useCallback)(e=>n(t=>({...t,activeId:e})),[]),o=(0,Q.useCallback)(()=>a(null),[a]);return{...t,open:r,close:i,select:a,showBrowser:o}}function Fd(e,t){let n=(0,Q.useCallback)(n=>t?e.subscribeSession(t,n):()=>void 0,[t,e]),r=(0,Q.useCallback)(()=>e.getSessionSnapshot(t),[t,e]),i=(0,Q.useSyncExternalStore)(n,r,r);return(0,Q.useEffect)(()=>{if(t)return e.retainSession(t,!0),()=>e.retainSession(t,!1)},[t,e]),i}var Id=new Set([`ArrowDown`,`ArrowUp`,`Home`,`End`,`Enter`,`Escape`]);function Ld(e,t){return!t||!Id.has(e.key)?!1:(e.preventDefault(),!0)}function Rd(e,{open:t,matches:n,index:r,setIndex:i,select:a,dismiss:o}){if(!t)return!1;if(n.length>0){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let t=e.key===`ArrowDown`?1:-1;return i(e=>(e+t+n.length)%n.length),!0}if(e.key===`Enter`||e.key===`Tab`)return e.preventDefault(),a(n[r]??n[0]),!0}return e.key===`Escape`&&(e.preventDefault(),o(),!0)}var zd=`openpond-composer-resource-request`;function Bd(e){window.dispatchEvent(new CustomEvent(zd,{detail:{...e,contexts:Uo.parse(e.contexts)}}))}function Vd({connection:e,sessionId:t,events:n,blocked:r,prompt:i,selectionKey:a,inputRef:o}){let[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(null),d=(0,Q.useId)(),f=(0,Q.useRef)(!1),[p,m]=(0,Q.useState)(!1),h=(0,Q.useRef)(!1),g=(0,Q.useRef)(0),_=(0,Q.useRef)(new Set),v=[...n].reverse().find(e=>e.sessionId===t&&[`turn.started`,`turn.completed`,`turn.failed`,`turn.interrupted`,`workspace_action_result`].includes(e.name))?.id,y=`${ra(e)}:${t}:${a}:${v??``}`,b=(0,Q.useRef)({key:y,blocked:r,prompt:i,value:s,error:l});b.current={key:y,blocked:r,prompt:i,value:s,error:l},(0,Q.useEffect)(()=>{let n=++g.current;if(b.current.error!==null&&u(null),!e||!t||r||p||i)return;let a=new AbortController,o;async function s(){try{let r=await ko(e,`dataset`,{action:`next_step`,payload:{sessionId:t,operation:`read`}},a.signal);if(n!==g.current||a.signal.aborted)return;let i=r.suggestion?pl.parse(r.suggestion):null;i?.sessionId!==t||!i||_.current.has(i.id)?b.current.value!==null&&c(null):(b.current.value?.key!==y||b.current.value.suggestion.id!==i.id)&&c({key:y,suggestion:i})}catch{}finally{a.signal.aborted||(o=setTimeout(s,1e4))}}return s(),()=>{a.abort(),clearTimeout(o)}},[e,t,y,r,p,!!i,v]);let x=!p&&!r&&!i&&s?.key===y&&!_.current.has(s.suggestion.id)?s.suggestion:null;async function S(){if(!e||!t||!x||f.current||h.current||b.current.blocked||o.current?.getPrompt())return;let n=x,r=y,i=g.current;h.current=!0,u(null);try{let a=await ko(e,`dataset`,{action:`next_step`,payload:{sessionId:t,operation:`accept`,id:n.id}});if(_.current.add(n.id),c(null),!a.suggestion||g.current!==i||b.current.key!==r||b.current.blocked||f.current||o.current?.getPrompt())return;let s=pl.parse(a.suggestion);if(s.id!==n.id||s.sessionId!==t)return;Bd({sessionId:t,text:s.draft,contexts:s.contexts})}catch(e){u(e instanceof Error?e.message:`Could not prepare this suggestion.`)}finally{h.current=!1}}function C(){x&&e&&t&&!_.current.has(x.id)&&(_.current.add(x.id),c(null),ko(e,`dataset`,{action:`next_step`,payload:{sessionId:t,operation:`dismiss`,id:x.id}}).catch(e=>u(e instanceof Error?e.message:`Could not dismiss this suggestion.`)))}function w(){f.current||(f.current=!0,g.current++,m(!0))}function T(e){return f.current||e.nativeEvent.isComposing||e.keyCode===229?(w(),!0):(e.key===`Enter`||e.key===`Tab`)&&(h.current||e.repeat)?(e.preventDefault(),!0):x?e.key===`Escape`?(e.preventDefault(),C(),!0):(e.key===`Enter`||e.key===`Tab`)&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&(e.preventDefault(),e.stopPropagation(),S(),!0):!1}return{suggestion:x,descriptionId:d,accept:S,dismiss:C,onKeyDown:T,error:l,onCompositionStart:w,onCompositionEnd:()=>{f.current=!1,m(!1)}}}function Hd({next:e}){return(0,$.jsxs)($.Fragment,{children:[e.suggestion?(0,$.jsxs)(`div`,{className:`composer-next-step`,id:e.descriptionId,children:[(0,$.jsx)(`span`,{children:e.suggestion.label}),(0,$.jsx)(`small`,{"aria-hidden":`true`,children:`Enter to draft`}),(0,$.jsx)(`span`,{className:`sr-only`,children:`Press Enter or Tab to insert an editable draft. This does not send.`})]}):null,(0,$.jsx)(X,{error:e.error})]})}function Ud(e,t){if(!e.scope||!e.focus.scopeContext)return[];let n=e.scope.runs.at(-1),r=e.focus.experiment??(n?e.experiments.find(e=>e.id===n.id)??n:null),i=[e.focus.dataset,r,...e.graders].filter(e=>!!e).map(({kind:e,id:t,revision:n,datasetId:r,datasetRevision:i,owner:a,profileRef:o})=>({kind:e,id:t,revision:n,datasetId:r,datasetRevision:i,owner:a,profileRef:o})),a=t??e.scope.training?.find(t=>qr(t)===e.scope.selectedTrainingKey);return Uo.parse([{scopeId:e.scope.id,selectionVersion:e.focus.scopeContext.selectionVersion,...e.scope.evaluationModel?{evaluationModel:e.scope.evaluationModel}:{},executionLocation:e.scope.executionLocation??`local`,resources:i,...a?{training:[Jr(a)]}:{}}])}function Wd(e,t){let n=new Map([...e,...t].map(e=>[JSON.stringify(e),e]));return Uo.parse([...n.values()])}function Gd(e){return e.length?{chatResourceContexts:e,...e.length===1?{chatExperimentScopeId:e[0].scopeId,chatExperimentSelectionVersion:e[0].selectionVersion}:{}}:{}}function Kd(e,t,n){return e?.length?{contexts:e,focus:null}:{contexts:n?.model||n?.training?[]:t,focus:n}}function qd(e,t,n,r){let i=(0,Q.useRef)(new Map),a=r?.resourceContexts,o={current:a?{get:e=>a.get(`session:${e}`),set:(e,t)=>a.set(`session:${e}`,t),delete:e=>a.delete(`session:${e}`)}:i.current},s=(0,Q.useCallback)(n=>{n.trim()||o.current.delete(e),t(n)},[t,e,a]);function c(){return o.current.get(e)??Ud(n)}return{resourceDrafts:o,onPromptChange:s,currentResourceContexts:c}}function Jd(e){async function t(t,n){let r=(n??e.getPrompt()).trim()||(e.attachmentCount?`Please review the attached files.`:``);if(!e.running||!r)return!1;let i=e.getResourceContexts?.()??[];if(e.hasActions)return e.showToast(`Send the selected action as a separate message before steering this turn.`,`info`),!1;if(!e.begin(e.scope))return!1;e.setError(null);let a,o=!1;try{a=await e.prepareAttachments?.();let n=a?.attachments??[];if(t===`queued`&&!e.inbox.enabled)return e.stageLocal(r,i,n),e.clear(),o=!0,!0;let s=e.inbox.enabled?t===`steer`?await e.inbox.steer(r,i,n.length?n:void 0):await e.inbox.queue({prompt:r,attachments:n,metadata:Gd(i),modelRef:{providerId:e.provider,modelId:e.model},...e.provider===`codex`?yi(e.codexPermissionMode):{approvalPolicy:`on-request`,sandbox:`workspace-write`},codexPermissionMode:e.codexPermissionMode,codexReasoningEffort:e.codexReasoningEffort}):await e.onSubmit(n,null,null,{preservePrompt:!0,promptOverride:r,turnMetadata:{...Gd(i),interactionKind:`steer`}});return s&&(!e.getCurrentSubmissionScopeKey||e.getCurrentSubmissionScopeKey()===e.scope)&&e.clear(),o=s,s}catch(t){return e.setError(t instanceof Error?t.message:String(t)),!1}finally{a?.settle(o),e.finish(e.scope)}}return{stageCurrentSteerDraft:e=>t(`queued`,e),submitImmediateSteer:e=>t(`steer`,e)}}var Yd=()=>({dataset:null,experiment:null});function Xd(e,t){let[n,r]=(0,Q.useState)(Yd),[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)([]),[c,l]=(0,Q.useState)([]),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(null),[g,_]=(0,Q.useState)(0),[v,y]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(!1),S=(0,Q.useRef)(0),C=(0,Q.useRef)(null),w=(0,Q.useRef)(n);w.current=n;let T=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{if(S.current++,C.current?.abort(),C.current=null,a([]),s([]),l([]),x(!1),r(Yd()),y(null),!e||!t)return;let n=new AbortController,i,o=!1,c=!1,u=async()=>{if(o){c=!0;return}o=!0,clearTimeout(i);let d=S.current;try{let i=await ko(e,`dataset`,{action:`context`,payload:{sessionId:t}},n.signal);!n.signal.aborted&&d===S.current&&(r(i.focus),a(i.datasets),s(i.experiments),l(i.graders),y(null))}catch(e){!n.signal.aborted&&d===S.current&&y(e instanceof Error?e.message:`Resource context unavailable.`)}o=!1,n.signal.aborted||(c?(c=!1,u()):i=setTimeout(()=>void u(),1e4))};T.current=()=>void u();let d=e=>{e.detail?.sessionId===t&&u()};return window.addEventListener(`openpond-resource-focus-changed`,d),u(),()=>{window.removeEventListener(`openpond-resource-focus-changed`,d),T.current=null,S.current++,C.current?.abort(),n.abort(),clearTimeout(i)}},[e,t]),(0,Q.useEffect)(()=>{if(d([]),h(null),!e||!t||!n.scopeContext?.activeScopeId)return;let r=new AbortController;return p(!0),ko(e,`experiment`,{action:`models`},r.signal).then(e=>{r.signal.aborted||d(e.models)}).catch(e=>{r.signal.aborted||h(e instanceof Error?e.message:`Model choices unavailable.`)}).finally(()=>{r.signal.aborted||p(!1)}),()=>r.abort()},[e,t,!!n.scopeContext?.activeScopeId,g]);async function E(n,i){if(!e||!t||C.current)return!1;let a=++S.current,o=new AbortController;C.current=o,x(!0);try{let s=await ko(e,`dataset`,{action:n,payload:{sessionId:t,...i,...w.current.scopeContext?{expectedSelectionVersion:w.current.scopeContext.selectionVersion}:{}}},o.signal);return a===S.current&&!o.signal.aborted&&(r(s),w.current=s,n!==`set_model`&&n!==`set_destination`&&l((s.scopeContext?Gr(s.scopeContext).find(e=>e.id===s.scopeContext?.activeScopeId):null)?.graders??[]),y(null)),o.signal.aborted||window.dispatchEvent(new CustomEvent(`openpond-resource-focus-changed`,{detail:{sessionId:t}})),!o.signal.aborted}catch(e){return a===S.current&&!o.signal.aborted&&y(e instanceof Error?e.message:`Resource selection failed.`),!1}finally{C.current===o&&(C.current=null,x(!1),T.current?.())}}let D=n.dataset?.id,O=n.dataset?.revision,k=(0,Q.useCallback)(t=>!e||!D||!O?Promise.reject(Error(`Select a dataset to inspect its rows.`)):ko(e,`dataset`,{action:`read`,id:D,expectedRevision:O},t),[e,D,O]);return{focus:n,scope:(n.scopeContext?Gr(n.scopeContext).find(e=>e.id===n.scopeContext?.activeScopeId):null)??null,datasets:i,experiments:o,graders:c,selecting:b,error:v,readDataset:k,models:u,modelsLoading:f,modelsError:m,refreshModels:()=>_(e=>e+1),selectDestination:e=>E(`set_destination`,{executionLocation:e}),selectModel:e=>E(`set_model`,{evaluationModel:e}),select:(e,t,n)=>E(`set_focus`,{kind:e,id:t||null,...n?{revision:n}:{}}),selectScope:e=>E(`select_scope`,{scopeId:e}),createScope:e=>E(`create_scope`,{operationId:`scope-${crypto.randomUUID()}`,...e===void 0?{}:{graderId:e}}),renameScope:(e,t)=>E(`rename_scope`,{scopeId:e,name:t})}}var Zd={experiment:`Experiment`,model:`Model`};function Qd({context:e,disabled:t=!1,placement:n=`bottom`}){let[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(null),l=(0,Q.useRef)(null),u=(0,Q.useRef)(null),d=e.selection,f=d?.target.kind===`training`?`model`:d?.target.kind===`dataset`||d?.target.kind===`training_result`||d?.target.kind===`managed_modification_result`||d?.target.kind===`engram_result`||d?.target.kind===`decision_result`||d?.target.kind===`alphaedit_result`||d?.target.kind===`neuron_training_result`?`experiment`:d?.target.kind,p=a??f??`experiment`,m=(e.catalog.data?.options??[]).filter(e=>e.target.kind===p||p===`experiment`&&(!!e.target.result||e.target.kind===`decision_result`||e.target.kind===`alphaedit_result`||e.target.kind===`neuron_training_result`)),h=d?.training?d.training.location===`cloud`?d.training.job.modelProjectId:d.training.modelId:null,g=d?.target.kind===p||p===`experiment`&&(d?.target.kind===`dataset`||d?.target.result||d?.target.kind===`decision_result`||d?.target.kind===`alphaedit_result`||d?.target.kind===`neuron_training_result`)?d:p===`model`&&h?m.find(e=>e.target.id===h&&e.target.location===d?.training?.location):null,_=g?JSON.stringify(g.target):``;g&&!m.some(e=>JSON.stringify(e.target)===_)&&m.unshift(g);let v=t||e.selecting,y=s??e.selectionError?.message??e.catalog.error?.message??e.catalog.data?.warning;(0,Q.useEffect)(()=>{if(!r)return;function e(e){l.current?.contains(e.target)||i(!1)}function t(e){e.key===`Escape`&&(i(!1),u.current?.focus())}return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[r]);async function b(t){c(null);try{if(t===`saved-model-experiment`){if(!g||g.target.kind!==`model`||g.target.location!==`cloud`)throw Error(`Select the hosted saved Model first.`);await e.select(g.target,{newExperiment:!0})&&i(!1);return}if(t===`new-experiment`){let t=`draft-${crypto.randomUUID()}`;await e.select({kind:`experiment`,id:t,location:`local`,draft:{schemaVersion:`openpond.experimentDraft.v1`,id:t,operationType:`evaluate`,name:`Evaluation`}},{newExperiment:!0})&&i(!1);return}if(!await e.select(t?O.parse(JSON.parse(t)):null))return;i(!1),u.current?.focus()}catch(e){c(e instanceof Error?e.message:`Training selection failed.`)}}return(0,$.jsxs)(`div`,{ref:l,className:`chat-context-picker codex-model-reasoning${n===`top`?` open-up`:``}`,children:[(0,$.jsxs)(`button`,{ref:u,type:`button`,className:`composer-project-trigger chat-training-trigger${r?` active`:``}`,"aria-label":`Ponder`,"aria-haspopup":`dialog`,"aria-expanded":r,disabled:v,title:d?`${d.label}: ${d.detail}`:`Ponder`,onClick:()=>{o(null),i(e=>!e)},children:[(0,$.jsx)(`span`,{children:d?.target.kind===`dataset`?`Experiment draft · ${d.label}`:d?.model?.name??d?.label??`Ponder`}),(0,$.jsx)(Oa,{size:14})]}),r?(0,$.jsxs)(`div`,{className:`codex-model-menu chat-training-menu`,role:`dialog`,"aria-label":`Training context`,children:[(0,$.jsx)(Z,{compact:!0,floating:!0,label:`Training type`,value:p,floatingMenuWidth:180,options:Object.entries(Zd).map(([e,t])=>({value:e,label:t})),triggerContent:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{children:`Type`}),(0,$.jsx)(`span`,{className:`chat-training-menu-value`,children:Zd[p]}),(0,$.jsx)(ka,{size:14})]}),disabled:v,onChange:e=>o(e)}),(0,$.jsx)(Z,{compact:!0,floating:!0,label:`${Zd[p]} name`,value:_,floatingMenuWidth:340,floatingMenuMaxHeight:360,triggerContent:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{children:Zd[p]}),(0,$.jsx)(`span`,{className:`chat-training-menu-value`,children:(g?.target.kind===`dataset`?`Draft · ${g.label}`:g?.label)??(e.catalog.isPending?`Loading…`:`None`)}),(0,$.jsx)(ka,{size:14})]}),options:[{value:``,label:`None`},...p===`model`&&g?.target.kind===`model`&&g.target.location===`cloud`?[{value:`saved-model-experiment`,label:`New experiment from saved Model…`,separatorBefore:!0}]:[],...p===`experiment`?[{value:`new-experiment`,label:`New experiment…`,separatorBefore:!0}]:[],...m.map(e=>({value:JSON.stringify(e.target),label:e.label,description:`${e.target.location===`cloud`?`OpenPond Managed`:`Local`} · ${e.detail}${m.filter(t=>t.label===e.label&&t.target.location===e.target.location).length>1?` · ${e.target.id.slice(-8)}`:``}`}))],disabled:v,onChange:e=>void b(e)}),p===`experiment`&&e.catalog.hasNextPage?(0,$.jsx)(`button`,{type:`button`,disabled:e.catalog.isFetchingNextPage,onClick:()=>void e.catalog.fetchNextPage(),children:`More saved experiments`}):null,y?(0,$.jsx)(X,{error:y,children:e.catalog.error?(0,$.jsx)(`button`,{type:`button`,onClick:()=>void e.catalog.refetch(),children:`Retry`}):null}):null]}):y?(0,$.jsx)(X,{error:y}):null]})}var $d=[{value:`model_judge`,label:`LLM judge`,request:`Create an LLM judge (model_judge) with an explicit rubric and passing and failing calibration examples. Ask for the judge model and a fixture-check spending limit if they are not already agreed.`},{value:`human`,label:`Human assessment`,request:`Create a human assessment (human) with a structured review form, explicit criteria, scale anchors and reviewer guidance. Keep human decisions separate from automatic evaluation scores; do not invent reviews or use pending reviews as training rewards.`},{value:`custom_verifier`,label:`Code grader`,request:`Create a code grader (custom_verifier) using an isolated JavaScript verifier. Include known-good, known-bad and boundary fixtures, and check them before reporting the grader as validated.`},{value:`python_correctness`,label:`Python correctness`,request:`Create a Python correctness grader using the supported Python correctness starter and private tests. Verify that the dataset contains admitted Python code and that a qualified isolated runtime is available. Missing code, tests or runtime evidence must remain unscorable.`}];function ef({dataset:e,busy:t,onDraft:n}){function r(r){e&&!t&&n(`${r.request}\n\nDataset: ${e.name}, ID ${e.id}, revision ${e.revision}. Inspect its tasks and existing graders to determine the appropriate checks.\n\nPreserve the existing graders and retained experiment inputs. Save changes as a new dataset revision. Do not start an experiment or training run.`)}return(0,$.jsxs)(`div`,{className:`chat-grader-request`,children:[(0,$.jsx)(`div`,{className:`evaluation-dataset-choices chat-grader-type-choices`,role:`group`,"aria-label":`Grader type`,children:$d.map(n=>(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:t||!e,onClick:()=>r(n),children:n.label},n.value))}),(0,$.jsx)(`div`,{className:`training-dialog-actions`,children:(0,$.jsx)(`a`,{className:`training-text-button`,href:ao(as(`graders`,null,{area:`console`})),children:`Manage graders`})})]})}function tf({kind:e,resources:t,busy:n,onDraft:r}){let[i,a]=(0,Q.useState)(``);if(e===`rows`)return(0,$.jsx)(nf,{resources:t});let o=t.focus.dataset;if(e===`grader`)return(0,$.jsx)(ef,{dataset:o,busy:n||t.selecting,onDraft:r});let s={title:`New dataset`,placeholder:`What examples should it contain?`,button:`Chat`};function c(){r(`Create a new dataset: ${i.trim()}`)}let l=n||t.selecting||!i.trim();return(0,$.jsxs)(`div`,{className:`composer-resource-request`,onKeyDown:e=>{!e.nativeEvent.isComposing&&e.key===`Enter`&&e.target instanceof HTMLInputElement&&(e.preventDefault(),e.stopPropagation(),l||c())},children:[(0,$.jsx)(`div`,{className:`composer-experiment-setup-heading`,children:(0,$.jsx)(`strong`,{children:s.title})}),(0,$.jsx)(`input`,{autoFocus:!0,"aria-label":s.placeholder,placeholder:s.placeholder,value:i,onChange:e=>a(e.target.value),disabled:n}),(0,$.jsxs)(`button`,{type:`button`,"aria-label":`Add to chat`,title:`Add to chat`,className:`composer-experiment-create`,onClick:c,disabled:l,children:[(0,$.jsx)(za,{size:13,"aria-hidden":!0}),` `,s.button]})]})}function nf({resources:e}){let[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(0);(0,Q.useEffect)(()=>{let t=new AbortController;return n(null),i(null),o(0),e.readDataset(t.signal).then(e=>{t.signal.aborted||n(e)}).catch(e=>{t.signal.aborted||i(e instanceof Error?e.message:`Could not load dataset rows.`)}),()=>t.abort()},[e.readDataset]);let s=t?.record.workspace.draft.tasks??[],c=Math.max(1,Math.ceil(s.length/5));return(0,$.jsxs)(`section`,{className:`composer-dataset-rows`,"aria-label":`Dataset rows`,children:[(0,$.jsxs)(`div`,{className:`composer-experiment-setup-heading`,children:[(0,$.jsx)(`strong`,{children:`Dataset rows`}),(0,$.jsx)(`span`,{children:t?`${s.length} examples · V${t.summary.revision}`:``}),c>1?(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`button`,{type:`button`,disabled:a===0,onClick:()=>o(e=>e-1),"aria-label":`Previous rows`,children:`‹`}),(0,$.jsxs)(`span`,{children:[a+1,`/`,c]}),(0,$.jsx)(`button`,{type:`button`,disabled:a+1>=c,onClick:()=>o(e=>e+1),"aria-label":`Next rows`,children:`›`})]}):null]}),r?(0,$.jsx)(X,{error:r}):t?(0,$.jsx)(`div`,{className:`composer-dataset-rows-scroll`,children:(0,$.jsxs)(`table`,{children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Example`}),(0,$.jsx)(`th`,{children:`Input`})]})}),(0,$.jsxs)(`tbody`,{children:[s.slice(a*5,a*5+5).map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.id}),(0,$.jsx)(`td`,{children:typeof e.input.prompt==`string`?e.input.prompt:typeof e.input.request==`string`?e.input.request:JSON.stringify(e.input)})]},e.id)),s.length?null:(0,$.jsx)(`tr`,{children:(0,$.jsx)(`td`,{colSpan:2,children:`No saved rows yet.`})})]})]})}):(0,$.jsx)(`p`,{role:`status`,children:`Loading rows…`})]})}function rf({resources:e,busy:t,onClose:n,onAddGrader:r,onRows:i,createNew:a,setupOnly:o=!1}){let s=(0,Q.useRef)(null),c=e.focus.dataset,l=t||e.selecting,u=e.scope?.evaluationModel,d=e.scope?.executionLocation??`local`,f=e.models.filter(e=>d===`local`||e.providerId===`openpond`),p=f.some(e=>`${e.providerId}/${e.id}`===u);return(0,Q.useEffect)(()=>{s.current?.querySelector(`.dropdown-trigger:not(:disabled)`)?.focus()},[]),(0,$.jsxs)(`div`,{ref:s,className:`composer-experiment-setup`,role:`region`,"aria-label":a?`New experiment`:`Experiment configuration`,children:[(0,$.jsxs)(`div`,{className:`composer-experiment-setup-heading`,children:[(0,$.jsx)(`strong`,{children:a?`New experiment`:`Configuration`}),(0,$.jsx)(`span`,{children:c?`Uses ${e.graders.length} dataset grader${e.graders.length===1?``:`s`}`:`Choose a dataset above`})]}),(0,$.jsx)(Z,{compact:!0,floating:!0,placement:`top`,label:`Run on`,value:d,options:[{value:`local`,label:`Local`},{value:`cloud`,label:`Hosted`,disabled:!!(c?.owner||c?.profileRef)}],onChange:t=>void e.selectDestination(t),disabled:l}),(0,$.jsx)(Z,{compact:!0,floating:!0,placement:`top`,searchable:!0,label:`Evaluation model`,value:u??``,options:[{value:``,label:e.modelsLoading?`Loading models…`:`Choose evaluation model`,disabled:!0},...u&&!p?[{value:u,label:`${u} (unavailable)`,disabled:!0}]:[],...f.map(e=>({value:`${e.providerId}/${e.id}`,label:e.name??e.id,description:e.providerId})),{value:`refresh`,label:`Refresh models`,separatorBefore:!0}],onChange:t=>{t===`refresh`?e.refreshModels():e.selectModel(t)},disabled:l||e.modelsLoading}),i&&c&&!c.owner&&!c.profileRef?(0,$.jsx)(`button`,{type:`button`,className:`composer-resource-secondary`,onClick:i,disabled:l,children:`Rows`}):null,o?null:e.graders.length?a?(0,$.jsx)(`button`,{type:`button`,className:`composer-experiment-create`,disabled:l||!c||!p,onClick:()=>{e.createScope(null).then(e=>{e&&n()})},children:`Create experiment`}):null:(0,$.jsx)(`button`,{type:`button`,className:`composer-resource-secondary`,onClick:r,disabled:l||!c,children:`Create grader`}),e.modelsError?(0,$.jsx)(X,{error:e.modelsError}):null]})}function af(e){let{dataset:t,run:n,model:r}=e;if(!e.isExperiment)return`New experiment`;if(n&&/^(running|queued|pending|starting)$/i.test(n.state))return`View progress`;if(!t||t.taskCount===0||!e.graders||!r||!e.modelAvailable)return`Set up`;if(!n)return`Run`;let i=t.owner?.teamId===n.owner?.teamId&&t.owner?.actorId===n.owner?.actorId&&JSON.stringify(t.profileRef)===JSON.stringify(n.profileRef);return(e.executionLocation??`local`)===(n.location??`local`)&&i&&t.id===n.datasetId&&r===n.model&&(t.evaluationHash&&n.evaluationHash?t.evaluationHash===n.evaluationHash:t.revision===n.datasetRevision)?/^(completed|complete|succeeded)$/i.test(n.state)?`Improve`:`Retry`:`Run updated`}function of({resources:e,busy:t,onDraft:n}){let[r,i]=(0,Q.useState)(`experiment`),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(`Run`),d=(0,Q.useRef)(null),f=(0,Q.useId)(),{scope:p,focus:m}=e;if((0,Q.useEffect)(()=>{c(!1),o(!1)},[p?.id]),(0,Q.useEffect)(()=>{s&&r===`action`&&d.current?.focus()},[s,r,l]),!p)return null;let h=m.dataset,g=p.ordinal!==null,_=t||e.selecting,v=h?[h,...e.datasets.filter(e=>e.id!==h.id||e.revision!==h.revision)]:e.datasets,y=p.runs.at(-1),b=m.experiment??(y?e.experiments.find(e=>e.id===y.id)??y:null),x=p.evaluationModel,S=p.executionLocation??`local`,C=S===`cloud`?`on OpenPond hosted execution`:`locally`,w=e.models.some(e=>`${e.providerId}/${e.id}`===x&&(S===`local`||e.providerId===`openpond`))&&(S!==`cloud`||!h?.owner&&!h?.profileRef),T=e.graders.find(e=>e.id===p.selectedGraderId)??(e.graders.length===1?e.graders[0]:void 0),E=!!(h&&e.graders.length&&w),D=![`Run`,`Run updated`,`Repeat run`,`Retry`].includes(l)||E&&!b?.state.match(/^(running|queued|pending|starting)$/i),O=af({isExperiment:g,dataset:h,graders:e.graders.length,model:x,modelAvailable:w,executionLocation:S,run:b});function k(e){i(e),o(!0),c(!0)}function A(e){u(e),k(`action`)}let j=e.models.find(e=>`${e.providerId}/${e.id}`===x),M=j?`${j.name??j.id} (${j.providerId})`:x??`the selected evaluation model`,N=`${e.graders.length} dataset grader${e.graders.length===1?``:`s`}`,P=h?`${h.name} V${h.revision}`:`this dataset`,F={"New experiment":`Create a new experiment draft for ${P}, keeping its current revision and graders. Do not run an evaluation, upload data, or start training.`,"Training readiness":`Is ${P} ready to train? Inspect its examples, splits, graders, source permissions, and supported training options. Explain what is missing without changing data or starting training.`,"Prepare training":`Prepare a hosted training plan on OpenPond for ${P}. Show me the model options, data requirements, plan, and cost first. Do not upload data or start training.`,Run:`Run ${P} ${C} against ${M}, using ${N}.`,"Run updated":`Run the updated configuration for ${P} ${C} against ${M}, using ${N}. Keep previous results for comparison.`,Retry:`Inspect why the previous run stopped, then retry ${P} ${C} against ${M} with its dataset graders if appropriate. Reconcile any uncertain submission first.`,"Repeat run":`Repeat ${P} ${C} against ${M} with its dataset graders as a new run. Preserve the previous results.`,Improve:`Improve experiment ${p.ordinal}: inspect its results, make a targeted change, validate it, and run a comparison ${C} against ${M} within the agreed budget.`,"View progress":`Check the progress of experiment ${p.ordinal}${b?` (run ${b.id})`:``}.`,Compare:`Compare experiment ${p.ordinal}${b?` (run ${b.id})`:``} with its earlier results.`,Diagnose:`Diagnose ${g?`experiment ${p.ordinal}`:P}: inspect the evidence and explain the cause and next step without changing it.`,"Improve dataset":`Improve ${P}: inspect its examples and results, fix relevant data or coverage issues, and evaluate the changes ${C} within the agreed budget.`,"Improve grader":`Improve ${T?.name??`the selected grader`} for ${P}: inspect its rules and failures, repair it, test good and bad answers without weakening the criteria, then run an experiment ${C} to check real outputs within the agreed budget.`,"Test grader":`Test ${T?.name??`the dataset graders`} on ${P} against known-good and known-bad examples.`},I=[{value:`New experiment`,label:`New experiment`,disabled:!h},{value:`Diagnose`,label:`Diagnose`,disabled:!h},...b?[{value:`Improve`,label:`Improve experiment`}]:[],{value:`Improve dataset`,label:`Improve dataset`,disabled:!h},{value:`Improve grader`,label:`Improve grader`,disabled:!T},{value:`Test grader`,label:T?`Test grader`:`Test graders`,disabled:!h||!e.graders.length},...!h?.owner&&!h?.profileRef?[{value:`Training readiness`,label:`Ready to train?`,disabled:!h,separatorBefore:!0},{value:`Prepare training`,label:`Prepare training`,disabled:!h}]:[],...b?[{value:`Compare`,label:`Compare results`,separatorBefore:!0},...O===`Improve`?[{value:`Repeat run`,label:`Repeat run`}]:[]]:[]];return(0,$.jsxs)(`div`,{className:`composer-resource-area ${s?`is-expanded`:``}`,children:[(0,$.jsxs)(`div`,{className:`composer-resource-bar`,"aria-label":g?`Current experiment`:`Current dataset`,children:[g?(0,$.jsx)(Z,{compact:!0,floating:!0,placement:`top`,floatingMenuWidth:280,label:`Experiment scope`,value:p.id,className:`composer-resource-number`,triggerContent:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{children:p.ordinal}),(0,$.jsx)(Oa,{size:12})]}),tooltip:`${p.ordinal}: ${p.name}`,options:[...(m.scopeContext?.scopes??[]).map(e=>({value:e.id,label:`${e.ordinal} ${e.name}`})),{value:`new`,label:`New experiment`,icon:`plus`}],onChange:t=>{t===`new`?A(`New experiment`):e.selectScope(t)},disabled:_}):null,(0,$.jsx)(Z,{compact:!0,floating:!0,searchable:!0,floatingMenuWidth:320,placement:`top`,label:`Dataset focus`,className:`composer-resource-dataset`,value:h?`${h.id}@${h.revision}`:``,tooltip:P,triggerContent:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`composer-resource-dataset-name`,children:h?.name??`Dataset`}),h?(0,$.jsxs)(`span`,{className:`composer-resource-version`,children:[`V`,h.revision]}):null,(0,$.jsx)(Oa,{size:12})]}),options:[{value:``,label:`Choose dataset`},...v.map(e=>({value:`${e.id}@${e.revision}`,label:`${e.name} V${e.revision}`})),{value:`create`,label:`New dataset…`,icon:`plus`}],onChange:t=>{if(t===`create`)return k(`dataset`);let n=t.lastIndexOf(`@`);e.select(`dataset`,n<0?t:t.slice(0,n),n<0?void 0:Number(t.slice(n+1)))},disabled:_}),(0,$.jsx)(Z,{compact:!0,floating:!0,placement:`top`,floatingMenuWidth:280,label:`Grader focus`,className:`composer-resource-graders`,value:p.selectedGraderId??``,options:[{value:``,label:`All graders`,shortLabel:`Graders ${e.graders.length}`},...e.graders.map(e=>({value:e.id,label:e.name})),{value:`add`,label:`Create grader`,icon:`plus`,separatorBefore:!0}],onChange:t=>{t===`add`?k(`grader`):e.select(`grader`,t)},disabled:_||!h}),O!==`New experiment`&&O!==`Improve`?(0,$.jsx)(`button`,{type:`button`,className:`composer-resource-primary`,disabled:_,onClick:()=>O===`Set up`?k(`experiment`):A(O),children:O}):null,(0,$.jsx)(Z,{compact:!0,floating:!0,searchable:!0,placement:`top`,floatingMenuWidth:280,floatingMenuMaxHeight:440,label:`Chat actions`,tooltip:`Add a request to chat`,value:``,className:`composer-resource-chat-actions`,triggerContent:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(za,{size:13}),(0,$.jsx)(Ia,{size:15})]}),options:[...I,...(p.training??[]).map((e,t)=>({value:`training:${qr(e)}`,label:`Check training ${t+1}`}))],onChange:e=>{if(!_){if(e.startsWith(`training:`)){let t=p.training?.find(t=>`training:${qr(t)}`===e);t&&n(`Check this training job and show its results and any model it produced.`,t)}else{let t=I.find(t=>t.value===e);if(!t||`disabled`in t&&t.disabled||!F[e])return;n(F[e])}c(!1)}},disabled:_}),(0,$.jsx)(`button`,{type:`button`,className:`composer-resource-expand`,"aria-label":s?`Collapse resource controls`:`Expand resource controls`,"aria-expanded":s,"aria-controls":f,onClick:()=>{o(!0),s||i(`experiment`),c(e=>!e)},children:(0,$.jsx)(Oa,{size:15})})]}),(0,$.jsx)(`div`,{id:f,className:`composer-resource-expansion`,inert:!s,"aria-hidden":!s,children:(0,$.jsx)(`div`,{className:`composer-resource-expansion-inner`,children:a?r===`experiment`?(0,$.jsx)(rf,{resources:e,busy:t,createNew:!g,onClose:()=>c(!1),onAddGrader:()=>k(`grader`),setupOnly:!0}):r===`action`?(0,$.jsxs)(`div`,{className:`composer-resource-request`,role:`region`,"aria-label":`${l} request preview`,children:[(0,$.jsxs)(`div`,{className:`composer-experiment-setup-heading`,children:[(0,$.jsx)(`strong`,{children:l}),(0,$.jsx)(`span`,{children:`Edit in chat before sending`})]}),(0,$.jsx)(`p`,{children:F[l]}),(0,$.jsxs)(`button`,{ref:d,type:`button`,"aria-label":`Add to chat`,title:`Add to chat`,className:`composer-experiment-create`,disabled:_||!D,onClick:()=>{n(F[l]),c(!1)},children:[(0,$.jsx)(za,{size:13,"aria-hidden":!0}),(0,$.jsx)(Ia,{size:13,"aria-hidden":!0}),` Add to chat`]})]}):(0,$.jsx)(tf,{kind:r,resources:e,busy:t,onDraft:e=>{n(e),c(!1)}},`${r}:${h?.id}:${h?.revision}`):null})}),e.error?(0,$.jsx)(X,{error:e.error}):null]})}function sf({context:e,sessionId:t,busy:n}){let[r,i]=(0,Q.useState)(null),a=e.selection;if(!a)return null;let o=a.training,s=a.model,c=n||e.selecting,l=o?JSON.stringify(a.target):``,u=(e.runs.data?.runs??[]).map(e=>({value:JSON.stringify(e.target),label:e.label,description:e.detail}));o&&!u.some(e=>e.value===l)&&u.unshift({value:l,label:a.label,description:a.detail});let d=(e.catalog.data?.options??[]).filter(e=>e.target.kind===`model`),f=d.find(e=>e.target.id===s?.id&&e.target.location===a.target.location)?.target??(s?{...a.target,kind:`model`,id:s.id}:null),p=f?JSON.stringify(f):``,m=d.map(e=>({value:JSON.stringify(e.target),label:e.label,description:e.detail}));f&&!m.some(e=>e.value===p)&&m.unshift({value:p,label:s?.name??a.label,description:a.detail});async function h(t){try{i(null),await e.select(O.parse(JSON.parse(t)))}catch(e){i(e instanceof Error?e.message:`Training selection failed.`)}}return(0,$.jsxs)(`div`,{className:`composer-resource-area`,children:[(0,$.jsxs)(`div`,{className:`composer-resource-bar`,"aria-label":`Current training`,children:[(0,$.jsx)(Z,{compact:!0,floating:!0,searchable:!0,placement:`top`,floatingMenuWidth:320,label:`Model focus`,className:`composer-resource-dataset`,value:p,triggerContent:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`composer-resource-dataset-name`,children:s?.name??a.label}),(0,$.jsx)(Oa,{size:12})]}),options:m,onChange:e=>void h(e),disabled:c}),(0,$.jsx)(Z,{compact:!0,floating:!0,placement:`top`,floatingMenuWidth:320,label:`Training run`,className:`composer-resource-graders`,value:l,options:[...o?[]:[{value:``,label:e.runs.isPending?`Loading runs…`:u.length?`Choose training run`:`No runs`,disabled:!0}],...u],onChange:e=>void h(e),disabled:c||e.runs.isPending}),(0,$.jsx)(`button`,{type:`button`,className:`composer-resource-primary`,onClick:()=>window.dispatchEvent(new CustomEvent(j,{detail:{sessionId:t,scope:e.scope,targetKey:JSON.stringify(a.target)}})),children:`View progress`})]}),(0,$.jsx)(X,{error:r??e.runs.error})]})}var cf=e=>JSON.stringify([e.kind,e.id,e.owner??null,e.profileRef??null]),lf=(e,t)=>e.datasetId===t.id&&JSON.stringify(e.owner??null)===JSON.stringify(t.owner??null)&&JSON.stringify(e.profileRef??null)===JSON.stringify(t.profileRef??null),uf=e=>/^(queued|running|pending|starting|cancelling)$/i.test(e);function df(e){return Kr.array().parse(e)}function ff(e,t,n){let{scope:r,focus:i}=e;if(!r||!i.scopeContext||!i.dataset)return[];let a=i.dataset;if(t&&!lf(t,a))throw Error(`This run belongs to a different Dataset.`);let o=t?.datasetRevision??a.revision,s=[{kind:`dataset`,id:a.id,revision:o,owner:a.owner,profileRef:a.profileRef},...t?[{kind:t.kind,id:t.id,revision:t.revision,datasetId:t.datasetId,datasetRevision:o,owner:t.owner,profileRef:t.profileRef}]:[],...!t||o===a.revision?e.graders.map(e=>({kind:e.kind,id:e.id,revision:e.revision,datasetId:e.datasetId,datasetRevision:e.datasetRevision,owner:e.owner,profileRef:e.profileRef})):[]];return Uo.parse([{scopeId:r.id,selectionVersion:i.scopeContext.selectionVersion,evaluationModel:t?.model??r.evaluationModel,executionLocation:t?.location??r.executionLocation??`local`,resources:s,...n?{training:[Jr(n)]}:{}}])}function pf({context:e,resources:t,sessionId:n,busy:r}){let[i,a]=(0,Q.useState)(null),o=e.selection;if(!o)return null;if(o.model||o.training)return(0,$.jsx)(sf,{context:e,sessionId:n,busy:r});if(o.draft&&o.draft.operationType!==`evaluate`)return(0,$.jsx)(`div`,{className:`composer-resource-area`,children:(0,$.jsxs)(`div`,{className:`composer-resource-bar`,"aria-label":`Current experiment draft`,children:[(0,$.jsx)(`span`,{className:`composer-resource-dataset-name`,children:o.label}),(0,$.jsx)(`span`,{children:Tr(o.draft.operationType)}),(0,$.jsx)(`button`,{type:`button`,className:`composer-resource-primary`,disabled:r||e.selecting,onClick:()=>window.dispatchEvent(new CustomEvent(j,{detail:{sessionId:n,scope:e.scope,targetKey:JSON.stringify(o.target)}})),children:`View draft`})]})});let s=o.dataset??(o.resource?.kind===`dataset`?o.resource:null),c=o.resource?.kind===`experiment`?o.resource:null,l=t.scope;if(!(l&&(o.draft&&o.target.scopeId===l.id||s&&l.dataset&&cf(s)===cf(l.dataset)&&s.revision===l.dataset.revision&&(o.target.scopeId===l.id||o.target.kind===`dataset`||c&&l.runs.some(e=>cf(e)===cf(c))))))return null;async function u(t){a(null);try{return await e.select(t),!0}catch(e){return a(e instanceof Error?e.message:`Resource selection failed.`),!1}}let d={...t,focus:{...t.focus,dataset:s,experiment:c},graders:o.graders??t.graders,selecting:t.selecting||e.selecting,selectScope:e=>u({kind:`experiment`,id:e,scopeId:e,sessionId:n,location:`local`}),select:(n,r,i)=>{if(n===`grader`)return t.select(n,r,i);if(!r)return u(null);let o=e.catalog.data?.options.find(e=>e.target.kind===n&&e.target.id===r&&(i===void 0||e.target.revision===i))?.target,s=[...t.datasets,...t.experiments].find(e=>e.kind===n&&e.id===r&&(i===void 0||e.revision===i));return!o&&!s?(a(`This resource is no longer available. Choose it again from Ponder.`),Promise.resolve(!1)):u(o??{kind:n,id:r,revision:i,location:s.location??`local`})}};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(of,{resources:d,busy:r,onDraft:(e,t)=>{Bd({sessionId:n,text:e,contexts:ff(d,c??void 0,t)})}}),(0,$.jsx)(X,{error:i})]})}function mf({surface:e,voiceInputChannelKey:t=``,taskSessionId:n,submissionScopeKey:r=`default`,prompt:i,onPromptChange:a,showToast:o,resourceDrafts:s,inputRef:c,composerDraftStore:l}){(0,Q.useEffect)(()=>{if(e!==`chat`||!t.startsWith(`main-composer:`))return;let l=e=>{let t=e.detail;if(t?.sessionId!==(n??null)||!t.text.trim())return;try{s.current.set(r,Wd(s.current.get(r)??[],t.contexts))}catch{o(`Send or clear the current resource actions before adding more.`,`info`);return}let l=c.current?.getPrompt()??i,u=l.trim()?`${l}\n\n${t.text}`:t.text;a(u),requestAnimationFrame(()=>c.current?.focusAtPromptIndex(u.length))};return window.addEventListener(zd,l),()=>window.removeEventListener(zd,l)},[e,t,n,r,i,a,o,l])}function hf(e,t){let n=e.slice(0,Math.max(0,Math.min(t,e.length))),r=/(?:^|\s)\$([a-zA-Z][a-zA-Z0-9_-]*)?$/.exec(n);if(!r||typeof r.index!=`number`)return null;let i=r[0].lastIndexOf(`$`);return i<0?null:{end:n.length,query:(r[1]??``).toLowerCase(),start:r.index+i}}function gf(e){return`$${e.name}`}function _f(e,t,n){let r=Math.max(0,Math.min(t.start,e.length)),i=Math.max(r,Math.min(t.end,e.length)),a=e.slice(0,r),o=e.slice(i),s=a&&!/\s$/.test(a)?` `:``,c=o&&/^\s/.test(o)?``:` `,l=`${s}${gf(n)}${c}`;return{cursor:a.length+l.length-(o?c.length:0),value:`${a}${l}${o}`}}function vf(e,t,n){let r=t.trim().toLowerCase(),i=e.filter(e=>e.enabled&&e.validationStatus===`valid`).filter(e=>!r||[e.name,e.description,e.path].join(` `).toLowerCase().includes(r)).sort((e,t)=>e.name.localeCompare(t.name));return typeof n==`number`&&Number.isFinite(n)?i.slice(0,Math.max(0,n)):i}function yf(e,t,n){let r=t.trim().replace(/\s+/g,` `),i=bf(n,e.length);if(!r)return{value:e,cursorIndex:i};let a=e.slice(0,i),o=e.slice(i),s=a&&!/\s$/.test(a)?` `:``,c=o&&!/^\s/.test(o)?` `:``;return{value:`${a}${`${s}${r}${c}`}${o}`,cursorIndex:a.length+s.length+r.length+c.length}}function bf(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,Math.round(e))):t}async function xf({appendToEnd:e=!1,currentScopeKey:t,cursorIndex:n,originScopeKey:r,prompt:i,setOriginDraft:a,submit:o=!1,submitFromOrigin:s,transcript:c}){let l=yf(i,c,e?i.length:n);return a(l.value),t===r&&!o?`drafted`:await s(l.value)?(a(``),`submitted`):`retained`}var Sf=new Map,Cf=new Map,wf=new Map;function Tf(e){for(let t of Cf.get(e)??[])t()}function Ef(e){return Sf.has(e)}function Df(e){return Sf.get(e)?.submitRequested??!1}function Of(e,t){let n=Cf.get(e)??new Set;return n.add(t),Cf.set(e,n),()=>{n.delete(t),n.size===0&&Cf.delete(e)}}function kf(e){Sf.get(e)?.controller.abort()}function Af(e,t){let n=wf.get(e)??new Set;return n.add(t),wf.set(e,n),()=>{n.delete(t),n.size===0&&wf.delete(e)}}function jf(e){let t=Sf.get(e);if(t)return t.submitRequested||(t.submitRequested=!0,Tf(e)),!0;for(let t of wf.get(e)??[])if(t())return!0;return!1}function Mf(e,t,n={}){kf(e);let r=new AbortController,i={controller:r,promise:Promise.resolve(),submitRequested:n.submit??!1};return i.promise=Promise.resolve().then(()=>{if(!r.signal.aborted)return t(r.signal,()=>i.submitRequested)}).catch(e=>{if(!r.signal.aborted)throw e}).finally(()=>{Sf.get(e)===i&&(Sf.delete(e),Tf(e))}),Sf.set(e,i),Tf(e),i.promise}function Nf(e,t){return t?e.find(e=>e.idempotencyKey===t.key&&e.senderKind===`user`&&e.kind===t.kind&&e.body===t.body&&[`pending`,`included`,`resolved`].includes(e.state))??null:null}function Pf(e,t,n){let r=e??{sessionId:t,activeTurnId:null,acceptingInput:!1,paused:!1,inputs:[],waits:[]},i=r.inputs.find(e=>e.id===n.id);return i&&(i.revision>n.revision||i.revision===n.revision&&i.updatedAt>n.updatedAt)?r:{...r,inputs:[...r.inputs.filter(e=>e.id!==n.id),n].sort((e,t)=>e.sequence-t.sequence)}}var Ff=new Set([`task.inbox`,`task.input`,`task.wait`,`turn.started`,`turn.completed`,`turn.failed`,`turn.interrupted`,`approval.requested`,`approval.resolved`]);function If(e){try{let t=JSON.parse(sessionStorage.getItem(e)??`null`);return t&&typeof t.body==`string`&&typeof t.key==`string`&&(t.kind===`steer`||t.kind===`queued`)?t:null}catch{return null}}function Lf(e,t,n){let r=u(),i=ra(e),a=(0,Q.useMemo)(()=>[`task-inbox`,i,t],[i,t]),o=!!(e&&t),s=S({queryKey:a,enabled:o,staleTime:0,refetchOnWindowFocus:!0,refetchOnReconnect:!0,queryFn:()=>co.taskInbox(e,t),refetchInterval:e=>e.state.data?.inputs.some(e=>e.state===`pending`)?2e3:e.state.data?.paused?1e4:!1}),[c,l]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)({}),h=`${i}:${t}`,g=p[h],_;for(let e=n.length-1;e>=0;e--){let r=n[e];if(r.sessionId===t&&Ff.has(r.name)){_=r.id;break}}let v=(0,Q.useCallback)(async()=>{o&&await r.invalidateQueries({queryKey:a,exact:!0})},[o,r,a]);(0,Q.useEffect)(()=>{v()},[v,_]),(0,Q.useEffect)(()=>{let e=()=>{v()};return window.addEventListener(`openpond-runtime-connected`,e),()=>window.removeEventListener(`openpond-runtime-connected`,e)},[v]);async function y(e,n){if(!o)return!1;l({scope:h,id:e}),f(null);try{let e=await n();return await r.cancelQueries({queryKey:a,exact:!0}),r.setQueryData(a,n=>Pf(n,t,e)),v(),!0}catch(t){let n=r.getQueryData(a)?.inputs.find(t=>t.idempotencyKey===e);return n&&[`pending`,`included`,`resolved`].includes(n.state)?!0:(f({scope:h,message:t instanceof Error?t.message:String(t)}),v(),!1)}finally{l(t=>t?.scope===h&&t.id===e?null:t)}}async function b(n,r,i,a,o){if(!e||!t)return!1;let c=`openpond:task-input:${e.serverUrl}:${t}`,l=If(c),u=l?.body===r&&l.kind===n&&JSON.stringify(l.request)===JSON.stringify(i)&&JSON.stringify(l.resourceContexts)===JSON.stringify(a)&&JSON.stringify(l.attachments)===JSON.stringify(o),d=u?l:{body:r,kind:n,request:i,resourceContexts:a,attachments:o,key:crypto.randomUUID(),turnId:n===`steer`?s.data?.activeTurnId??null:null};if(n===`steer`&&(!d.turnId||!u&&!s.data?.acceptingInput))return f({scope:h,message:`This turn is no longer accepting steering. Your text is still in the composer; send it as a follow-up or queue it.`}),v(),!1;try{sessionStorage.setItem(c,JSON.stringify(d))}catch{}n===`queued`&&m(e=>({...e,[h]:d}));let p=await y(d.key,async()=>{let i;try{i=await(n===`steer`?co.steerTurn(e,t,{prompt:r,expectedTurnId:d.turnId,idempotencyKey:d.key,resourceContexts:d.resourceContexts,attachments:d.attachments}):co.queueTaskInput(e,t,d.request,d.key))}catch(e){if(e instanceof Ti&&e.status>=400&&e.status<500)try{sessionStorage.removeItem(c)}catch{}throw e}if(i.state===`rejected`||i.state===`cancelled`){try{sessionStorage.removeItem(c)}catch{}throw Error(i.error??`This input was cancelled. Review your text before sending again.`)}return i});if(n===`queued`&&m(e=>{if(e[h]?.key!==d.key)return e;let t={...e};return delete t[h],t}),p)try{If(c)?.key===d.key&&sessionStorage.removeItem(c)}catch{}return p}let x=e&&t?`openpond:task-input:${e.serverUrl}:${t}`:null,C=x?If(x):null,w=Nf(s.data?.inputs??[],C);return{pendingQueue:g&&!s.data?.inputs.some(e=>e.idempotencyKey===g.key)?{id:g.key,body:g.body,attachments:g.request?.attachments??[]}:null,acknowledgedInput:w,acknowledgeRetainedInput:()=>{if(x&&w&&If(x)?.key===w.idempotencyKey){try{sessionStorage.removeItem(x)}catch{}l(e=>e?.scope===h&&e.id===w.idempotencyKey?null:e)}},enabled:o,snapshot:s.data??null,busyId:c?.scope===h?c.id:null,error:d?.scope===h?d.message:s.error?.message??null,steer:(e,t,n)=>b(`steer`,e,void 0,t,n),queue:e=>b(`queued`,e.prompt,e),mutate:(n,r)=>y(n.id,()=>co.updateTaskInput(e,t,n.id,r)),refresh:v}}function Rf(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`steer-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,9)}`}function zf(e,t=120){let n=e.trim().replace(/\s+/g,` `);return n.length<=t?n:`${n.slice(0,Math.max(0,t-1)).trimEnd()}...`}function Bf(e,t={}){let n=t.now??new Date().toISOString();return{...t.resourceContexts?{resourceContexts:structuredClone(t.resourceContexts)}:{},...t.attachments?.length?{attachments:structuredClone(t.attachments)}:{},createdAt:n,id:t.id??Rf(),prompt:e,updatedAt:n}}function Vf(e,t){return e.filter(e=>e.id!==t)}function Hf(e,t,n){return n?Vf(e,t):e}function Uf(e,t,n=[]){return e[t]??n}function Wf(e,t,n,r=[]){let i=Uf(e,t,r),a=n(i);return Object.is(i,a)?e:{...e,[t]:a}}function Gf({prompt:e,attachments:t=[],sending:n=!1,disabled:r=!1,actionLabel:i=`Steer`,actionDisabledReason:a,onSend:o,onDelete:s,onEdit:c}){let l=t.find(e=>e.kind===`image`&&e.contentsBase64)??t[0],u=t.map(e=>e.name).join(`, `);return(0,$.jsxs)(`div`,{className:`composer-steer-row ${n?`sending`:``}`,children:[(0,$.jsx)(`span`,{className:`composer-steer-row-icon`,"aria-hidden":!l||void 0,role:l?`img`:void 0,"aria-label":l?`Attachments: ${u}`:void 0,title:l?u:void 0,children:l?(0,$.jsx)(Kf,{attachment:l}):(0,$.jsx)(au,{size:13})}),(0,$.jsx)(`span`,{className:`composer-steer-row-text`,title:[e,...t.map(e=>e.name)].join(`
7
7
  `),children:zf(e)}),(0,$.jsxs)(`button`,{type:`button`,className:`composer-steer-row-action primary`,disabled:r||n||!!a,title:a,"aria-label":`${i}: ${zf(e,60)}${a?`. ${a}`:``}`,onClick:o,children:[(0,$.jsx)(Ea,{size:12}),(0,$.jsx)(`span`,{children:n?`Sending`:i})]}),(0,$.jsx)(`button`,{type:`button`,className:`composer-steer-row-icon-button`,disabled:r||n,"data-tooltip":`Delete queued message`,"aria-label":`Delete queued message`,onClick:s,children:(0,$.jsx)(la,{size:13})}),(0,$.jsx)(`button`,{type:`button`,className:`composer-steer-row-action`,disabled:r||n,"aria-label":`Edit: ${zf(e,60)}`,onClick:c,children:(0,$.jsx)(`span`,{children:`Edit`})})]})}function Kf({attachment:e}){let{kind:t,mediaType:n,contentsBase64:r}=e,i=(0,Q.useMemo)(()=>t===`image`&&n.startsWith(`image/`)&&r?`data:${n};base64,${r}`:null,[t,n,r]),[a,o]=(0,Q.useState)(null);return i&&i!==a?(0,$.jsx)(`img`,{className:`composer-steer-attachment-preview`,src:i,alt:``,width:13,height:13,loading:`lazy`,decoding:`async`,onError:()=>o(i)}):(0,$.jsx)(os,{attachment:e,size:13})}function qf({inbox:e,onRestore:t,canRestore:n}){let r=e.snapshot,i=r?.inputs.filter(e=>e.senderKind===`user`&&e.kind===`queued`&&e.state===`pending`)??[];return!i.length&&!e.pendingQueue&&!e.error?null:(0,$.jsxs)($.Fragment,{children:[e.error&&(0,$.jsx)(X,{error:e.error}),(i.length>0||e.pendingQueue)&&(0,$.jsxs)(`div`,{className:`composer-steer-stack`,"aria-label":`Queued messages`,children:[i.map(i=>{let a=r?.activeTurnId,o=!(!i.turnId||r?.paused),s=o?`Starting`:a?`Steer`:r?.paused?`Resume`:`Send`,c=o?`This message is starting its turn.`:a&&!r?.acceptingInput?`This turn is no longer accepting steering. The message stays queued for the next turn.`:void 0;return(0,$.jsx)(Gf,{prompt:i.body,attachments:Yf(i),disabled:!!e.busyId||o,actionLabel:s,actionDisabledReason:c,onSend:()=>void e.mutate(i,a?{action:`steer`,expectedRevision:i.revision,expectedTurnId:a}:{action:`resume`,expectedRevision:i.revision}),onDelete:()=>void e.mutate(i,{action:`cancel`,expectedRevision:i.revision}),onEdit:()=>void Jf(e,i,t,n)},i.id)}),e.pendingQueue&&(0,$.jsx)(Gf,{prompt:e.pendingQueue.body,attachments:e.pendingQueue.attachments,disabled:!0,actionLabel:`Queuing`,onSend:()=>{},onDelete:()=>{},onEdit:()=>{}},e.pendingQueue.id)]})]})}async function Jf(e,t,n,r){let i=t.payload.metadata,a=Uo.safeParse(i?.chatResourceContexts),o=a.success?a.data:[],s=Yf(t);(!r||r(o,s))&&await e.mutate(t,{action:`cancel`,expectedRevision:t.revision})&&n(t.body,o,s)}function Yf(e){return he.array().parse(e.payload.attachments??[])}var Xf=new Set([`claude-code`,`opencode`,`grok-build`]);function Zf({currentModelOptions:e,currentProvider:t,providerOptions:n,providerSettings:r}){return n.flatMap(n=>{if(n.value===`setup-provider`)return[];let i=n.value,a=i===t?e:Ci(i,r);if(i===`openpond`){let e=new Set((r?.modelCaches.openpond?.models??[]).filter(e=>e.raw?.managedServing===!0).map(e=>e.id)),t=a.filter(t=>!e.has(t.value)),o=a.filter(t=>e.has(t.value));return[...t.length?[{key:i,provider:i,label:n.label,defaultModel:Si(i,r),options:t}]:[],{key:`openpond-managed`,provider:i,label:`OpenPond Managed`,managed:!0,defaultModel:o[0]?.value??``,options:o}]}if(i===`custom-openai-compatible`){let e=r?.modelCaches[i]?.models??[],t=new Map;for(let r of a){let i=e.find(e=>e.id===r.value)?.raw?.connectionProvider,a=typeof i==`string`?i:n.label;t.set(a,[...t.get(a)??[],r])}return[...t].map(([e,t])=>({key:`${i}:${e}`,provider:i,label:e,defaultModel:t[0].value,options:t}))}return a.length||oe(i)||Xf.has(i)?[{key:i,provider:i,label:n.label,defaultModel:Si(i,r),options:a}]:[]})}function Qf(e){let t=Oi(),n=t?.modelsByProvider?.[e.provider]??(t?.provider===e.provider?t.model:void 0),r=e.options.find(e=>e.value===n)??e.options.find(t=>t.value===e.defaultModel)??e.options[0];return!r&&!e.managed&&!(oe(e.provider)||Xf.has(e.provider))?null:{provider:e.provider,model:r?.value??(e.managed?``:n??``)}}function $f({busy:e,placement:t,state:n,onChange:r}){let[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.useState)(``),c=(0,Q.useRef)(null),l=(0,Q.useMemo)(()=>{let e=o.trim().toLowerCase();return e?n.options.filter(t=>`${t.label} ${t.detail}`.toLowerCase().includes(e)):n.options},[o,n.options]);return(0,Q.useEffect)(()=>{if(!i){s(``);return}function e(e){c.current?.contains(e.target)||a(!1)}function t(e){e.key===`Escape`&&a(!1)}return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[i]),n.options.length<=1?null:(0,$.jsxs)(`div`,{className:`composer-profile-target ${t===`top`?`open-up`:``}`,ref:c,children:[(0,$.jsxs)(`button`,{type:`button`,className:`composer-profile-trigger ${i?`active`:``}`,disabled:e,"aria-label":`Profile`,"aria-haspopup":`menu`,"aria-expanded":i,onClick:()=>a(e=>!e),children:[(0,$.jsx)(`span`,{children:n.label}),(0,$.jsx)(Oa,{size:14})]}),i?(0,$.jsxs)(`div`,{className:`composer-project-menu`,role:`menu`,"aria-label":`Profile`,children:[(0,$.jsx)(`div`,{className:`composer-menu-search`,children:(0,$.jsx)(`input`,{autoFocus:!0,value:o,placeholder:`Search profiles`,onChange:e=>s(e.currentTarget.value)})}),(0,$.jsx)(`div`,{className:`composer-menu-items`,children:l.map(e=>{let t=e.value===n.value;return(0,$.jsxs)(`button`,{type:`button`,role:`menuitemradio`,"aria-checked":t,className:`composer-project-option ${t?`selected`:``}`,onClick:()=>{r(e.value),a(!1)},children:[(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:e.label}),(0,$.jsx)(`small`,{children:e.detail})]}),t?(0,$.jsx)(Ro,{size:14}):null]},e.value)})})]}):null]})}function ep({busy:e,placement:t,state:n,onChange:r}){let[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(``),u=(0,Q.useRef)(null),d=n.value===`none`?`Project`:n.label,f=n.options.find(e=>e.value===n.value)?.kind??`local`,p=(0,Q.useMemo)(()=>{let e=c.trim().toLowerCase();return e?n.options.filter(t=>[t.label,t.detail].filter(Boolean).some(t=>t.toLowerCase().includes(e))):n.options},[c,n.options]),m=p.filter(e=>e.kind===`local`||e.kind===`cloud`),h=p.filter(e=>e.kind===`action`),g=p.filter(e=>e.kind===`none`);(0,Q.useEffect)(()=>{if(!i){l(``),s(!1);return}function e(e){u.current?.contains(e.target)||a(!1)}function t(e){e.key===`Escape`&&(o?s(!1):a(!1))}return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[o,i]);function _(t){let i=t.value===n.value,o=e||t.disabled,c=t.kind===`action`;return(0,$.jsxs)(`button`,{type:`button`,role:c?`menuitem`:`menuitemradio`,"aria-checked":c?void 0:i,className:`composer-project-option ${i?`selected`:``} ${t.kind}`,disabled:o,onClick:()=>{r(t.value),s(!1),a(!1)},children:[(0,$.jsx)(tp,{kind:t.kind,size:14}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:t.label}),(0,$.jsx)(`small`,{children:t.detail})]}),i&&(0,$.jsx)(Ro,{size:14})]},t.value)}return(0,$.jsxs)(`div`,{className:`composer-project-target ${t===`top`?`open-up`:``}`,ref:u,children:[(0,$.jsxs)(`button`,{type:`button`,className:`composer-project-trigger ${i?`active`:``} ${f}`,disabled:e,"aria-label":`Project`,"aria-haspopup":`menu`,"aria-expanded":i,onClick:()=>{a(e=>!e),s(!1)},children:[(0,$.jsx)(tp,{kind:f,size:14}),(0,$.jsx)(`span`,{children:d}),(0,$.jsx)(Oa,{size:14})]}),i&&(0,$.jsxs)(`div`,{className:`composer-project-menu`,role:`menu`,"aria-label":`Project`,children:[(0,$.jsx)(`div`,{className:`composer-menu-search`,children:(0,$.jsx)(`input`,{autoFocus:!0,value:c,placeholder:`Search projects`,onChange:e=>l(e.target.value)})}),(0,$.jsx)(`div`,{className:`composer-menu-items`,children:p.length===0?(0,$.jsx)(`div`,{className:`composer-menu-empty`,children:`No projects found`}):m.map(_)}),h.length>0||g.length>0?(0,$.jsxs)(`div`,{className:`composer-project-actions`,children:[h.length>0?(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`composer-project-option action composer-project-new-trigger ${o?`selected`:``}`,"aria-haspopup":`menu`,"aria-expanded":o,onClick:()=>s(e=>!e),children:[(0,$.jsx)(za,{size:14}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:`New`}),(0,$.jsx)(`small`,{children:`Create or add a project`})]}),(0,$.jsx)(ka,{size:14})]}):null,g.map(_)]}):null]}),i&&o?(0,$.jsxs)(`div`,{className:`composer-project-new-menu`,role:`menu`,"aria-label":`New project`,children:[(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`composer-project-new-menu-back`,onClick:()=>s(!1),children:[(0,$.jsx)(so,{size:14}),(0,$.jsx)(`span`,{children:`New project`})]}),h.map(_)]}):null]})}function tp({kind:e,size:t}){return e===`cloud`?(0,$.jsx)(Yo,{size:t}):e===`action`?(0,$.jsx)(za,{size:t}):(0,$.jsx)(Wo,{size:t})}function np({busy:e,placement:t,state:n,onChange:r}){let[i,a]=(0,Q.useState)(!1),o=(0,Q.useRef)(null),s=n.value===`cloud`?`cloud`:n.value===`hybrid`?`hybrid`:`local`,c=`${n.label}: ${n.detail}`,l=n.uploadAction??null,u=l?rp(l):null,d=l?l.disabled&&l.disabledReason?l.disabledReason:`${l.label}: ${u??l.detail}`:null,f=!!(l&&(e||n.busy||l.disabled));return(0,Q.useEffect)(()=>{if(!i)return;function e(e){o.current?.contains(e.target)||a(!1)}function t(e){e.key===`Escape`&&a(!1)}return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[i]),(0,$.jsxs)(`div`,{className:`workspace-action-control ${t===`top`?`open-up`:``}`,ref:o,children:[(0,$.jsxs)(`button`,{type:`button`,className:`workspace-action-trigger ${s} ${i?`active`:``}`,disabled:e,"data-tooltip":c,"aria-label":`Working in`,"aria-haspopup":`menu`,"aria-expanded":i,onClick:()=>a(e=>!e),children:[(0,$.jsx)(ip,{value:n.value,size:14}),(0,$.jsx)(`span`,{className:`workspace-target-trigger-label`,children:n.label}),(0,$.jsx)(Oa,{size:14})]}),l?(0,$.jsx)(`button`,{type:`button`,className:`workspace-upload-trigger ${l.value}`,disabled:f,"data-tooltip":d??void 0,"aria-label":l.label,onClick:()=>{r(l.value),a(!1)},children:(0,$.jsx)(ip,{value:l.value,size:14})}):null,i&&(0,$.jsx)(`div`,{className:`workspace-target-menu`,role:`menu`,"aria-label":`Working in`,children:n.options.map(t=>{let i=t.value===n.value,o=e||n.busy||t.disabled,s=rp(t)??t.detail,c=t.disabled&&t.disabledReason?t.disabledReason:`${t.label}: ${s}`;return(0,$.jsxs)(`button`,{type:`button`,role:`menuitemradio`,"aria-checked":i,className:`workspace-target-option ${i?`selected`:``} ${t.value}`,disabled:o,"data-tooltip":c,onClick:()=>{r(t.value),a(!1)},children:[(0,$.jsx)(ip,{value:t.value,size:14}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:t.label}),(0,$.jsx)(`small`,{children:s})]}),i&&(0,$.jsx)(Ro,{size:14})]},t.value)})})]})}function rp(e){return e.disabled&&e.disabledReason?e.disabledReason:e.stateNote??null}function ip({value:e,size:t}){return e===`cloud`?(0,$.jsx)(Yo,{size:t}):e===`hybrid`?(0,$.jsxs)(`span`,{className:`workspace-target-hybrid-icon`,"aria-hidden":`true`,children:[(0,$.jsx)(Wo,{className:`hybrid-folder`,size:t}),(0,$.jsx)(Yo,{className:`hybrid-cloud`,size:Math.max(7,Math.round(t*.62))})]}):e===`upload_cloud`?(0,$.jsx)(Aa,{size:t}):(0,$.jsx)(Wo,{size:t})}function ap({disabled:e,model:t,modelGroups:n,placement:r,provider:i,providerSettings:a,reasoningEffort:o,showReasoning:s,onModelSelectionChange:c,onReasoningEffortChange:l}){let[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(`root`),m=(0,Q.useRef)(null),h=(i===`openpond`&&(!t||t.startsWith(`managed:`))?n.find(e=>e.managed):void 0)??n.find(e=>e.provider===i&&e.options.some(e=>e.value===t))??n.find(e=>e.provider===i),g=h?.options.find(e=>e.value===t),_=vi(i,t,a),v=_i(i,t,o,a),y=_.find(e=>e.value===v)??_[0],b=op(g?.label??t)||h?.label||i,x=s?`${b} ${y.shortLabel??y.label}`:b,S=s?`Model and reasoning`:`Model`;return(0,Q.useEffect)(()=>{if(!u){p(`root`);return}function e(e){m.current?.contains(e.target)||d(!1)}function t(e){e.key===`Escape`&&d(!1)}return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[u]),(0,Q.useEffect)(()=>{!s&&f===`effort`&&p(`root`)},[f,s]),(0,$.jsxs)(`div`,{className:`codex-model-reasoning ${r===`top`?`open-up`:``}`,"data-tooltip":S,ref:m,children:[(0,$.jsxs)(`button`,{type:`button`,className:`codex-model-trigger ${u?`active`:``}`,disabled:e,"aria-label":S,"aria-haspopup":`menu`,"aria-expanded":u,onClick:()=>d(e=>!e),children:[(0,$.jsx)(`span`,{children:x}),(0,$.jsx)(Oa,{size:14})]}),u&&(0,$.jsx)(`div`,{className:`codex-model-menu`,role:`menu`,"aria-label":S,children:f===`root`?(0,$.jsxs)(`div`,{className:`codex-model-menu-root`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`codex-model-menu-row`,role:`menuitem`,onClick:()=>p(`provider`),children:[(0,$.jsx)(`span`,{children:`Provider`}),(0,$.jsx)(`span`,{className:`codex-model-menu-value`,children:h?.label??i}),(0,$.jsx)(ka,{size:14})]}),(0,$.jsxs)(`button`,{type:`button`,className:`codex-model-menu-row`,role:`menuitem`,onClick:()=>p(`model`),children:[(0,$.jsx)(`span`,{children:`Model`}),(0,$.jsx)(`span`,{className:`codex-model-menu-value`,children:fe(g?.label??t)||(h?.managed?`Choose model`:`Agent default`)}),(0,$.jsx)(ka,{size:14})]}),s?(0,$.jsxs)(`button`,{type:`button`,className:`codex-model-menu-row`,role:`menuitem`,onClick:()=>p(`effort`),children:[(0,$.jsx)(`span`,{children:`Effort`}),(0,$.jsx)(`span`,{className:`codex-model-menu-value`,children:y.shortLabel??y.label}),(0,$.jsx)(ka,{size:14})]}):null]}):f===`provider`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,className:`codex-model-submenu-heading`,"aria-label":`Back to model settings — Provider`,onClick:()=>p(`root`),children:[(0,$.jsx)(so,{size:14}),(0,$.jsx)(`span`,{children:`Provider`})]}),(0,$.jsx)(`div`,{className:`codex-model-menu-divider`}),(0,$.jsx)(`div`,{className:`codex-model-menu-options`,children:n.filter(e=>!e.managed).map(e=>{let t=e.key===h?.key;return(0,$.jsxs)(`button`,{type:`button`,role:`menuitemradio`,"aria-checked":t,className:t?`selected`:``,onClick:()=>{let t=Qf(e);t&&(c(t.provider,t.model),p(`root`))},children:[(0,$.jsx)(`span`,{children:e.label}),t?(0,$.jsx)(Ro,{size:14}):null]},e.key)})}),n.filter(e=>e.managed).map(e=>(0,$.jsxs)(`button`,{type:`button`,role:`menuitemradio`,"aria-checked":e.key===h?.key,className:`codex-model-managed-provider`,onClick:()=>{let t=Qf(e);t&&(c(t.provider,t.model),p(`root`))},children:[(0,$.jsx)(`span`,{children:e.label}),e.key===h?.key?(0,$.jsx)(Ro,{size:14}):null]},e.key))]}):f===`model`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,className:`codex-model-submenu-heading`,"aria-label":`Back to model settings — Model`,onClick:()=>p(`root`),children:[(0,$.jsx)(so,{size:14}),(0,$.jsx)(`span`,{children:`Model`})]}),(0,$.jsx)(`div`,{className:`codex-model-menu-divider`}),(0,$.jsxs)(`div`,{className:`codex-model-menu-options`,children:[(h?.options??[]).map(e=>{let n=e.value===t;return(0,$.jsxs)(`button`,{type:`button`,role:`menuitemradio`,"aria-checked":n,className:n?`selected`:``,onClick:()=>{c(i,e.value),p(`root`)},children:[(0,$.jsx)(`span`,{children:fe(e.label)}),n?(0,$.jsx)(Ro,{size:14}):null]},e.value)}),h?.options.length?null:(0,$.jsx)(`div`,{className:`codex-model-menu-empty`,role:`status`,children:h?.managed?`No trained models in this workspace.`:`No models available. Connect or check this provider in Settings.`})]})]}):(0,$.jsxs)(`div`,{className:`codex-model-menu-effort`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`codex-model-submenu-heading`,"aria-label":`Back to model settings — Effort`,onClick:()=>p(`root`),children:[(0,$.jsx)(so,{size:14}),(0,$.jsx)(`span`,{children:`Effort`})]}),(0,$.jsx)(`div`,{className:`codex-model-menu-divider`}),_.map(e=>(0,$.jsxs)(`button`,{type:`button`,role:`menuitemradio`,"aria-checked":e.value===v,className:e.value===v?`selected`:``,onClick:()=>{l(e.value),p(`root`)},children:[(0,$.jsx)(`span`,{children:e.label}),e.value===v?(0,$.jsx)(Ro,{size:14}):null]},e.value))]})})]})}function op(e){return fe(e).replace(/^GPT-/,``).replace(/\s+Codex Spark$/,` Spark`).replace(/\s+Codex$/,` Codex`)}function sp({detailsOpen:e,goalRuntime:t,objectiveId:n,subagentRuntime:r,onToggleDetails:i,connection:a,sessionId:o,running:s,onPause:c,onResume:l}){let[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(null),[g,_]=(0,Q.useState)(null),v=(0,Q.useRef)(!1),y=(0,Q.useRef)(0),b=(0,Q.useRef)(null),x=JSON.stringify([t?.objective,t?.status,t?.tokensUsed,t?.tokenBudget]),S=ji((g?.source===x?g.runtime:t)?.tone===`active`),C=g?.source===x?Ai(g.runtime,S):t,w=C??t,T=!!(a&&o);Ka(m,{prefix:`Goal`}),(0,Q.useEffect)(()=>{if(!a||!o)return;let e=!1,t=y.current;return co.getGoal(a,o).then(n=>{!e&&!v.current&&y.current===t&&_({source:x,runtime:n.goal?Ei(n.goal,n.observedAt):null})}).catch(t=>{e||h(t)}),()=>{e=!0}},[a,o,x,s]);async function E(){if(a&&o&&!v.current){y.current++,v.current=!0,p(`load`),h(null);try{let e=await co.getGoal(a,o),t=e.goal?Ei(e.goal,e.observedAt):null;_({source:x,runtime:t}),t&&d({original:t.objective,draft:t.objective})}catch(e){h(e)}finally{v.current=!1,p(null)}}}function D(){d(null),b.current?.focus()}async function O(e){if(!a||!o||v.current||!w)return;let t=u?.draft.trim();if(e===`save`&&!t)return;let n=++y.current;v.current=!0,p(e),h(null);try{let r=await co.patchGoal(a,o,{expectedObjective:e===`save`?u.original:w.objective,...e===`save`?{objective:t}:{status:e===`pause`?`paused`:`active`}}),i=Ei(r.goal,r.observedAt);i&&_({source:x,runtime:i}),e===`save`&&D(),e===`pause`&&s&&await c(),e===`resume`&&!s&&l().catch(e=>(h(e),!1)).then(async e=>{if(e||y.current!==n)return;let t=await co.patchGoal(a,o,{expectedObjective:w.objective,status:`paused`}),r=Ei(t.goal,t.observedAt);r&&y.current===n&&_({source:x,runtime:r})}).catch(e=>h(e))}catch(e){h(e)}finally{v.current=!1,p(null)}}return!C||!w?null:(0,$.jsxs)(`section`,{className:`composer-goal-strip ${w.tone}`,"aria-label":`Goal`,"aria-busy":!!f,children:[(0,$.jsxs)(`div`,{className:`composer-goal-heading`,children:[(0,$.jsxs)(`button`,{ref:b,type:`button`,className:`composer-goal-toggle`,"aria-label":`${e?`Hide`:`Show`} goal details`,"aria-expanded":e||!!u,"aria-controls":n,onClick:()=>{u||i()},title:w.objective,children:[(0,$.jsx)(su,{size:15,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`composer-goal-status`,children:w.actionLabel}),(0,$.jsx)(`span`,{className:`composer-goal-preview`,children:w.objective})]}),(0,$.jsx)(`span`,{className:`composer-goal-time`,title:w.tooltip,children:w.timeLabel}),T?(0,$.jsxs)(`div`,{className:`composer-goal-actions`,children:[(0,$.jsx)(`button`,{type:`button`,"aria-label":`Edit goal`,title:`Edit goal`,disabled:!!f||!!u,onClick:()=>void E(),children:(0,$.jsx)(ou,{size:15})}),w.tone===`active`||w.tone===`paused`?(0,$.jsx)(`button`,{type:`button`,"aria-label":w.tone===`active`?`Pause goal`:`Resume goal`,title:w.tone===`active`?`Pause goal`:`Resume goal`,disabled:!!f||!!u,onClick:()=>void O(w.tone===`active`?`pause`:`resume`),children:w.tone===`active`?(0,$.jsx)(ua,{size:15}):(0,$.jsx)(Ra,{size:15})}):null]}):null,(0,$.jsx)(`button`,{type:`button`,className:`composer-goal-disclosure`,"aria-label":`Toggle goal details`,"aria-expanded":e||!!u,"aria-controls":n,disabled:!!u,onClick:i,children:(0,$.jsx)(Oa,{size:15})})]}),u||e?(0,$.jsxs)(`div`,{className:`composer-goal-objective`,id:n,children:[u?(0,$.jsxs)(`div`,{className:`composer-goal-editor`,children:[(0,$.jsx)(`label`,{htmlFor:`${n}-input`,children:`Goal objective`}),(0,$.jsx)(`textarea`,{id:`${n}-input`,autoFocus:!0,rows:3,maxLength:32e3,value:u.draft,disabled:!!f,onChange:e=>d({...u,draft:e.target.value}),onKeyDown:e=>{e.stopPropagation(),e.key===`Escape`&&!f&&(e.preventDefault(),D()),e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),O(`save`))}}),(0,$.jsxs)(`div`,{className:`composer-goal-editor-actions`,children:[(0,$.jsx)(`button`,{type:`button`,disabled:!!f,onClick:D,children:`Cancel`}),(0,$.jsx)(`button`,{type:`button`,className:`composer-goal-save`,disabled:!!f||!u.draft.trim()||u.draft.trim()===u.original,onClick:()=>void O(`save`),children:f===`save`?`Saving…`:`Save goal`})]})]}):(0,$.jsx)(`p`,{children:w.objective}),(0,$.jsx)(`small`,{children:w.detail}),r?(0,$.jsx)(`span`,{className:`composer-goal-subagent-summary`,children:r.tooltip}):null]}):null]})}function cp({drafts:e,sendingDraftId:t,onDeleteDraft:n,onEditDraft:r,onSteerDraft:i}){return e.length===0?null:(0,$.jsx)(`div`,{className:`composer-steer-stack`,"aria-label":`Steer drafts`,children:e.map(e=>(0,$.jsx)(Gf,{prompt:e.prompt,attachments:e.attachments,sending:t===e.id,onSend:()=>i(e.id),onDelete:()=>n(e.id),onEdit:()=>r(e)},e.id))})}var lp=/\b(?:https?:\/\/)?(?:github\.com|(?:[a-z0-9-]+\.)*openpond\.ai)\/[^\s<>"'`]+/gi,up=/\b(?:git@)?(?:github\.com|(?:[a-z0-9-]+\.)*openpond\.ai):[^\s<>"'`]+/gi,dp=new Set(`about.apps.collections.codespaces.contact.customer-stories.enterprise.events.explore.features.issues.login.marketplace.mobile.new.notifications.orgs.organizations.pricing.pulls.readme.search.settings.sponsors.team.topics.trending`.split(`.`)),fp=new Set([`account`,`api`,`dashboard`,`docs`,`install.sh`,`login`,`logout`,`opchat`,`sandboxes`,`settings`]);function pp(e){let t=e.toLowerCase().replace(/^www\./,``);return t===`github.com`?`github`:t===`openpond.ai`||t.endsWith(`.openpond.ai`)?`openpond`:null}function mp(e){return e===`github`?dp:fp}function hp(e){let t=e;for(;/[.,;!?]$/.test(t);)t=t.slice(0,-1);for(;gp(t);)t=t.slice(0,-1);return t}function gp(e){let t=e.at(-1);if(!t||!`)]}`.includes(t))return!1;let n=t===`)`?`(`:t===`]`?`[`:`{`,r=0;for(let i of e)i===n&&(r+=1),i===t&&--r;return r<0}function _p(e){return e.replace(/\.git$/i,``)}function vp(e){try{return decodeURIComponent(e)}catch{return e}}function yp(e){return _p(vp(e.trim()))}function bp(e){let t=e.host.toLowerCase().replace(/^www\./,``),n=pp(t);if(!n)return null;let r=vp(e.owner?.trim()??``),i=yp(e.repo??``);return!r||!i||mp(n).has(r.toLowerCase())?null:{end:e.end,host:t,label:`${r}/${i}`,provider:n,repo:i,start:e.start,url:e.url,owner:r}}function xp(e,t){let n=hp(e);if(!n)return null;try{let e=new URL(/^https?:\/\//i.test(n)?n:`https://${n}`),r=e.pathname.split(`/`).filter(Boolean);return bp({end:t+n.length,host:e.hostname,owner:r[0],repo:r[1],start:t,url:n})}catch{return null}}function Sp(e,t){let n=hp(e),r=/^(?:git@)?([^:]+):(.+)$/i.exec(n);if(!r)return null;let i=r[1]?.trim()??``,a=(r[2]??``).split(`/`).filter(Boolean);return bp({end:t+n.length,host:i,owner:a[0],repo:a[1],start:t,url:n})}function Cp(e,t,n){let r=[];t.lastIndex=0;let i;for(;i=t.exec(e);){let e=n(i[0]??``,i.index);e&&r.push(e)}return r}function wp(e){if(!e)return[];let t=[...Cp(e,lp,xp),...Cp(e,up,Sp)].sort((e,t)=>e.start-t.start||t.end-e.end),n=[];for(let e of t)n.some(t=>e.start<t.end&&e.end>t.start)||n.push(e);return n.sort((e,t)=>e.start-t.start)}var Tp=10,Ep=340,Dp=320,Op=160,kp=56;function Ap(e,t=0){let n=Number.parseFloat(e);return Number.isFinite(n)?n:t}function jp(e){if(!e)return;e.style.height=`auto`;let t=window.getComputedStyle(e),n=Ap(t.fontSize,16),r=Ap(t.lineHeight,n*1.45),i=Ap(t.paddingTop)+Ap(t.paddingBottom),a=Ap(t.borderTopWidth)+Ap(t.borderBottomWidth),o=Ap(t.minHeight,66),s=Math.max(o,Math.ceil(r*Tp+i+a)),c=Math.max(o,Math.min(e.scrollHeight,s));e.style.height=`${c}px`,e.style.overflowY=e.scrollHeight>s?`auto`:`hidden`}function Mp(e,t){let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i=window.getComputedStyle(e),a=Ap(i.paddingLeft,14),o=Ap(i.paddingTop,15),s=Math.max(0,r.width-16),c=Math.min(Ep,s),l=n.left-r.left+a-8;return{left:Math.max(8,Math.min(l,r.width-c-8)),top:Math.max(8,n.top-r.top+o+2),width:c}}function Np(e){let t=e.getBoundingClientRect(),n=Math.floor(t.top-kp);return{maxHeight:Math.max(Op,Math.min(Dp,n))}}function Pp(e){let t=``,n=null,r=[e];for(;r.length;){let i=r.pop();if(i instanceof HTMLElement){if(i.matches(`[data-inline-token="true"]`)){n=t.length;continue}if(i.matches(`[data-inline-repo-link="true"]`)){t+=i.dataset.repoUrl??``;continue}if(i.matches(`[data-inline-connected-app-mention="true"]`)){t+=i.dataset.connectedMentionText??``;continue}if(i!==e&&(i.tagName===`DIV`||i.tagName===`P`)){let e=i.previousSibling;for(;e&&(e instanceof HTMLElement&&e.matches(`[data-inline-token="true"]`)||e.nodeType===Node.TEXT_NODE&&e.textContent===``);)e=e.previousSibling;e&&(t+=`
8
8
  `)}if(i.tagName===`BR`){i.parentNode?.childNodes.length!==1&&(t+=`
9
9
  `);continue}}if(i.nodeType===Node.TEXT_NODE)t+=i.textContent??``;else for(let e=i.childNodes.length-1;e>=0;e--)r.push(i.childNodes[e])}return{text:t,tokenPosition:n}}var Fp=`[data-inline-token='true']`,Ip=`[data-inline-repo-link='true']`,Lp=`[data-inline-connected-app-mention='true']`;function Rp(e){return e instanceof HTMLElement&&e.matches(Fp)}function zp(e){return e instanceof HTMLElement&&e.matches(Ip)}function Bp(e){return e instanceof HTMLElement&&e.matches(Lp)}function Vp(e,t){return Math.max(0,Math.min(e,t))}function Hp(e,t){return e?Vp(e.position,t.length):null}function Up(e,t,n,r=!1){let i=Hp(t,n),a=Vp(e,n.length);return i===null?a:a>i||r&&a===i?a+1:a}function Wp(e,t,n){let r=Hp(t,n);return Vp(r===null?e:e>r?e-1:e,n.length)}var Gp=Pp;function Kp(e){let t=Pp(e);return t.text.length+(t.tokenPosition===null?0:1)}function qp(e,t,n){if(!t||t!==e&&!e.contains(t))return null;let r=document.createRange();return r.selectNodeContents(e),r.setEnd(t,n),Kp(r.cloneContents())}function Jp(e){let t=window.getSelection();if(!t||t.rangeCount===0)return null;let n=qp(e,t.anchorNode,t.anchorOffset),r=qp(e,t.focusNode,t.focusOffset);return n===null||r===null?null:{anchor:n,focus:r}}function Yp(e,t){let n=Math.max(0,t);function r(t){let n=t.parentNode;return n?{node:n,offset:Array.prototype.indexOf.call(n.childNodes,t)}:{node:e,offset:0}}function i(e){let t=r(e);return{node:t.node,offset:t.offset+1}}function a(e){if(Rp(e)||zp(e)||Bp(e)){let t=Kp(e);return n<=0?r(e):n<=t?i(e):(n-=t,null)}if(e.nodeType===Node.TEXT_NODE){let t=e.textContent?.length??0;return n<=t?{node:e,offset:n}:(n-=t,null)}if(e instanceof HTMLBRElement)return null;for(let t of e.childNodes){let e=a(t);if(e)return e}return null}return a(e)??{node:e,offset:e.childNodes.length}}function Xp(e,t){let n=window.getSelection();if(!n)return;let r=Yp(e,t.anchor),i=Yp(e,t.focus);if(n.removeAllRanges(),typeof n.setBaseAndExtent==`function`){n.setBaseAndExtent(r.node,r.offset,i.node,i.offset);return}let a=document.createRange(),o=t.anchor<=t.focus,s=o?r:i,c=o?i:r;a.setStart(s.node,s.offset),a.setEnd(c.node,c.offset),n.addRange(a)}function Zp(e,t){Xp(e,{anchor:t,focus:t})}function Qp(e){document.execCommand(`insertText`,!1,e)}function $p(e){return e===`plus`?`<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14"></path><path d="M12 5v14"></path></svg>`:e===`bot`?`<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 8V4H8"></path><rect width="16" height="12" x="4" y="8" rx="2"></rect><path d="M2 14h2"></path><path d="M20 14h2"></path><path d="M15 13v2"></path><path d="M9 13v2"></path></svg>`:e===`skill`?`<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 7v14"></path><path d="M3 18a1 1 0 0 1-1-1V5a2 2 0 0 1 2-2h5a3 3 0 0 1 3 3v15a3 3 0 0 0-3-3Z"></path><path d="M21 18a1 1 0 0 0 1-1V5a2 2 0 0 0-2-2h-5a3 3 0 0 0-3 3v15a3 3 0 0 1 3-3Z"></path></svg>`:`<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="8" height="8" x="3" y="3" rx="2"></rect><path d="M7 11v4a2 2 0 0 0 2 2h4"></path><rect width="8" height="8" x="13" y="13" rx="2"></rect></svg>`}function em(){return`<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="composer-invocation-clear" aria-hidden="true"><path d="M18 6 6 18"></path><path d="m6 6 12 12"></path></svg>`}function tm(e){let t=document.createElement(`span`);t.className=`composer-invocation-pill`,t.contentEditable=`false`,t.dataset.inlineToken=`true`;let n=document.createElement(`button`);n.type=`button`,n.className=`composer-invocation-remove`,n.setAttribute(`aria-label`,`Remove ${e.label}`),n.addEventListener(`mousedown`,e=>e.preventDefault()),n.addEventListener(`click`,t=>{t.preventDefault(),e.onRemove()});let r=document.createElement(`span`);r.className=`composer-invocation-icon`,r.setAttribute(`aria-hidden`,`true`),r.innerHTML=$p(e.icon),n.append(r),n.insertAdjacentHTML(`beforeend`,em());let i=document.createElement(`span`);return i.className=`composer-invocation-label`,i.textContent=e.label,t.append(n,i),t}function nm(e){return e.provider===`github`?r(`github`):a}function rm(e){let t=document.createElement(`span`);t.className=`composer-repo-link ${e.provider}`,t.contentEditable=`false`,t.dataset.inlineRepoLink=`true`,t.dataset.repoUrl=e.url,t.dataset.repoProvider=e.provider,t.setAttribute(`aria-label`,`${e.provider===`github`?`GitHub`:`OpenPond`} repository ${e.label}`),t.title=e.url;let n=document.createElement(`img`);n.className=`composer-repo-link-icon`,n.src=nm(e),n.alt=``,n.draggable=!1;let r=document.createElement(`span`);return r.className=`composer-repo-link-label`,r.textContent=e.label,t.append(n,r),t}function im(e){return r(e)}function am(e){let t=document.createElement(`span`);t.className=`composer-connected-app-mention ${e.provider}`,t.contentEditable=`false`,t.dataset.inlineConnectedAppMention=`true`,t.dataset.connectedMentionText=e.text,t.dataset.connectedMentionProvider=e.provider,t.setAttribute(`aria-label`,`${e.label} connected app mention ${e.displayText}`),t.title=e.detail;let n=document.createElement(`img`);n.className=`composer-connected-app-mention-icon`,n.src=im(e.provider),n.alt=``,n.draggable=!1;let r=document.createElement(`span`);return r.className=`composer-connected-app-mention-label`,r.textContent=e.displayText,t.append(n,r),t}function om(e,t){let n=wp(e);return t===null?n:n.filter(e=>t<=e.start||t>=e.end)}function sm(e,t,n){let r=Ya(e,t);return n===null?r:r.filter(e=>n<=e.start||n>=e.end)}function cm(e,t,n){let r=[...om(e,t).map(e=>({end:e.end,kind:`repo`,link:e,start:e.start})),...sm(e,n,t).map(e=>({end:e.end,kind:`connected-app`,mention:e,start:e.start}))].sort((e,t)=>e.start-t.start||t.end-e.end),i=[],a=0;for(let e of r)e.start<a||(i.push(e),a=e.end);return i}function lm(e,t,n){return cm(e,t,n).map(e=>e.kind===`repo`?`${e.start}:${e.end}:repo:${e.link.provider}:${e.link.label}:${e.link.url}`:`${e.start}:${e.end}:connected-app:${e.mention.provider}:${e.mention.text}:${e.mention.displayText}`).join(`|`)}function um(e,t,n,r){let i=Hp(n,t),a=cm(t,i,r),o=!1;function s(t){t&&e.append(document.createTextNode(t))}function c(r,a){!n||i===null||o||i<r||i>a?s(t.slice(r,a)):(s(t.slice(r,i)),e.append(tm(n)),o=!0,s(t.slice(i,a)))}e.replaceChildren();let l=0;for(let t of a)c(l,t.start),t.kind===`repo`?e.append(rm(t.link)):e.append(am(t.mention)),l=t.end;c(l,t.length),n&&!o&&e.append(tm(n))}var dm=(0,Q.forwardRef)(function({connectedAppMentions:e=[],ariaDescribedBy:t,disabled:n,onCursorChange:r,onKeyDown:i,onPasteFiles:a,onPasteTextAsAttachment:o,onPromptChange:s,onTokenPositionChange:c,placeholder:l,prompt:u,token:d},f){let p=(0,Q.useRef)(null),m=`${d?`${d.key}:${Hp(d,u)??0}`:`none`}|${lm(u,Hp(d,u),e)}`,h=(0,Q.useRef)(null),g=u.length===0&&!d;(0,Q.useImperativeHandle)(f,()=>({get element(){return p.current},getPrompt(){let e=p.current;return e?Gp(e).text:u},focusAtPromptIndex(e,t){let n=p.current;if(!n)return;let r=Up(e,d,u,t?.afterToken);n.focus(),Zp(n,r),jp(n)},resize(){jp(p.current)}}),[u,d]),(0,Q.useLayoutEffect)(()=>{let t=p.current;if(!t)return;let n=h.current!==m;h.current=m;let r=Gp(t);if(n||u===``||r.text!==u||r.tokenPosition!==Hp(d,u)){let n=document.activeElement===t?Jp(t):null;um(t,u,d,e),t.dataset.empty=u.length===0&&!d?`true`:`false`,n&&Xp(t,n)}jp(t)},[e,u,d,m]);function _(){let t=p.current;if(!t)return;let n=Jp(t)?.focus??Kp(t),i=Gp(t);t.querySelector(`div, p, br`)&&(um(t,i.text,d&&i.tokenPosition!==null?{...d,position:i.tokenPosition}:null,e),Zp(t,n));let a=Wp(n,d,i.text);t.dataset.empty=i.text.length===0&&!d?`true`:`false`,c(i.tokenPosition),r(a),s(i.text,a)}function v(){_(),window.requestAnimationFrame(_)}function y(){let e=p.current;e&&r(Wp(Jp(e)?.focus??Kp(e),d,u))}return(0,$.jsx)(`div`,{ref:p,className:`composer-inline-input`,role:`textbox`,"aria-multiline":`true`,"aria-describedby":t,contentEditable:!n,suppressContentEditableWarning:!0,"data-empty":g?`true`:`false`,"data-placeholder":l,onBeforeInput:e=>{e.nativeEvent.inputType===`insertParagraph`&&(e.preventDefault(),Qp(`
10
- `),v())},onInput:e=>{e.nativeEvent.isComposing||_()},onCompositionEnd:_,onKeyDown:e=>{i(e)},onKeyUp:y,onMouseUp:y,onPaste:e=>{e.preventDefault();let t=Array.from(e.clipboardData.files);if(t.length>0&&a){a(t);return}let n=e.clipboardData.getData(`text/plain`);n&&(o?.(n)||(Qp(n),v()))}})});function fm(e){e.saving||(e.prompt.trim()?e.attachmentsCount>0?e.showInfo(`Task drafts currently save instructions only. Remove attachments before saving.`):e.hasSelectedInvocation?e.showInfo(`Finish or remove the selected command before saving this task draft.`):(e.setSaving(!0),e.onSave(e.prompt).then(t=>{t&&e.onSaved()}).finally(()=>e.setSaving(!1))):e.showInfo(`Add task instructions before saving a draft.`))}function pm(e,t,n,r,i,a,o){return e===`Enter`&&(t||n)&&!r&&i===`work`&&a===`chat`&&o}function mm(e){return e.surface===`team`?`Message team`:e.mode===`start`?e.experience===`chat`?`Ask anything`:`What should we work on? Ctrl Enter to save as draft`:`Ask for follow-up changes`}function hm(e){let t=e.implementation?.type;return t===`openpond-agent`||t===`local-profile-agent`||t===`openpond-profile-action`&&(e.sourceActionId===`chat`||e.id===`chat`||e.id.endsWith(`.chat`))}function gm(e){return e.kind===`command`?`command:${e.command.id}`:e.kind===`app-context`?`app-context:${e.app.id}`:e.kind===`skill`?`skill:${e.skill.name}`:`action:${e.action.id}`}function _m(e){return e.kind===`command`?`${e.command.command} ${e.command.label}`:e.kind===`app-context`?e.app.name:e.kind===`skill`?gf(e.skill):Ni(e.action)}function vm(e){return e.kind===`command`?Ki(e.command):e.kind===`app-context`?`Planning context${e.app.description?`: ${e.app.description}`:e.app.gitRepo?`: ${e.app.gitRepo}`:``}`:e.kind===`skill`?e.skill.description||e.skill.path:e.action.description||Ri(e.action)}function ym(e){return e.kind===`app`?`app:${e.app.id}`:e.kind===`connected-app`?`connected-app:${e.app.provider}`:e.kind===`team-member`?`team-member:${e.member.userId}`:e.kind===`skill`?`skill:${e.skill.name}`:`action:${e.action.id}`}function bm(e){return e.kind===`app`?e.app.name:e.kind===`connected-app`?e.app.label:e.kind===`team-member`?e.member.name:e.kind===`skill`?gf(e.skill):Wi(e.action)}function xm(e){if(e.kind===`action`)return Li(e.action);if(e.kind===`connected-app`)return e.app.detail;if(e.kind===`team-member`)return e.member.handle?`@${e.member.handle}`:`Team member`;if(e.kind===`skill`)return e.skill.description||e.skill.path;let t=e.app.sandboxActionRegistry?.actions.map(e=>e.name)??[];return t.length>0?`Actions: ${t.slice(0,4).join(`, `)}${t.length>4?` +${t.length-4}`:``}`:e.app.sandboxManifestError?`Manifest registry unavailable`:e.app.description||e.app.gitRepo||e.app.id}function Sm(e){return e.kind===`files`?`files`:e.kind===`folder`?`folder`:e.kind===`slash`?`slash:${gm(e.item)}`:`mention:${ym(e.item)}`}function Cm(e){return e.kind===`files`?`Files and folders`:e.kind===`folder`?`Local folder`:e.kind===`slash`?_m(e.item):bm(e.item)}function wm(e){return e.kind===`files`?`Attach images, documents, or other files`:e.kind===`folder`?`Share a bounded folder as Work input`:e.kind===`slash`?vm(e.item):xm(e.item)}function Tm(e,t){let n=t.toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return!0;let r=`${Cm(e)} ${wm(e)}`.toLowerCase();return n.every(e=>r.includes(e))}function Em(e,t){let n=t.trimStart(),r=n.startsWith(`/`)?`slash`:n.startsWith(`@`)?`mentions`:null,i=r?n.slice(1).trimStart():n,a=r?e.filter(e=>e.id===r||e.queryScope===r||e.queryScopes?.includes(r)):e;if(!i)return a;let o=a.map(e=>({...e,items:e.items.filter(e=>Tm(e,i))})).filter(e=>e.items.length>0);return o.length>0?o:[{...(r?a[0]:null)??{id:`results`,label:`Results`},emptyLabel:r===`slash`?`No slash commands match`:r===`mentions`?`No mentions match`:`No commands match`,items:[]}]}function Dm(e){if(e.kind===`files`||e.kind===`folder`)return(0,$.jsx)(La,{size:14});if(e.kind===`slash`){let t=e.item;return t.kind===`command`?t.command.id===`agent`?(0,$.jsx)(Da,{size:14}):t.command.id===`skill`?(0,$.jsx)(Po,{size:14}):(0,$.jsx)(ha,{size:14}):t.kind===`app-context`?(0,$.jsx)($l,{size:14}):t.kind===`skill`?(0,$.jsx)(ts,{size:14}):hm(t.action)?(0,$.jsx)(Da,{size:14}):(0,$.jsx)(ha,{size:14})}let t=e.item;return t.kind===`connected-app`?(0,$.jsx)(`img`,{alt:``,className:`composer-provider-mention-icon`,draggable:!1,src:r(t.app.provider)}):t.kind===`action`?hm(t.action)?(0,$.jsx)(Da,{size:14}):(0,$.jsx)(ha,{size:14}):t.kind===`skill`?(0,$.jsx)(ts,{size:14}):(0,$.jsx)($l,{size:14})}function Om(e){if(e.kind===`slash`&&e.item.kind===`app-context`||e.kind===`mention`&&e.item.kind===`app`)return e.item.app.id}function km({ariaLabel:e,className:t=``,id:n,menuIndex:r,menuRef:i,onSelect:a,onSelectIndex:o,sections:s,style:c,variant:l}){let u=(0,Q.useRef)(null),d=s.reduce((e,t)=>e+t.items.length,0);(0,Q.useEffect)(()=>{if(l===`add`&&r===0){let e=u.current?.closest(`.composer-command-menu`);e&&(e.scrollTop=0)}else u.current?.scrollIntoView({block:`nearest`})},[d,r,l]);let f=0;return(0,$.jsx)(`div`,{ref:i,id:n,className:`composer-project-menu composer-slash-menu ${t} composer-command-menu composer-command-menu-${l}`.trim(),role:l===`add`?`menu`:`listbox`,"aria-label":e,style:c,children:s.map(e=>{let t=f;return f+=e.items.length,(0,$.jsxs)(`div`,{className:`composer-command-section ${e.grid?`composer-command-section-grid`:``}`.trim(),role:`group`,"aria-label":e.label,children:[(0,$.jsx)(`div`,{className:`composer-command-section-title`,children:e.label}),e.items.length>0?e.items.map((e,n)=>{let i=t+n,s=i===r;return(0,$.jsxs)(`button`,{type:`button`,role:l===`add`?`menuitem`:`option`,ref:s?u:void 0,"aria-selected":l===`typed`?s:void 0,className:`composer-project-option ${s?`selected`:``} composer-command-option`,"data-app-context-id":Om(e),onFocus:()=>o(i),onMouseEnter:()=>o(i),onMouseDown:e=>{e.preventDefault()},onClick:()=>a(e),children:[Dm(e),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:Cm(e)}),(0,$.jsx)(`small`,{children:wm(e)})]}),l===`typed`&&s?(0,$.jsx)(Ro,{size:14}):(0,$.jsx)(`span`,{"aria-hidden":`true`})]},Sm(e))}):(0,$.jsx)(`div`,{className:`composer-menu-empty`,children:e.emptyLabel??`No items available`})]},e.id)})})}function Am({mentionIndex:e,items:t,onSelect:n,onSelectIndex:r,style:i}){return(0,$.jsx)(km,{ariaLabel:`Mentions`,className:`composer-mention-menu`,menuIndex:e,sections:[{emptyLabel:`No matching mentions`,id:`mentions`,items:t.map(e=>({kind:`mention`,item:e})),label:`@`}],style:i,variant:`typed`,onSelect:e=>{e.kind===`mention`&&n(e.item)},onSelectIndex:r})}function jm({running:e,sendDisabled:t,hasComposerInput:n,sendTooltip:r,stopIcon:i,stopLabel:a,voiceInputActive:o,onSend:s,onStop:c}){let l=e&&!n&&!o,u=l?a:r;return(0,$.jsx)(`button`,{type:`button`,className:`send-button ${l?`stop-button`:``}`.trim(),disabled:!l&&t&&!o,"data-tooltip":u,"aria-label":u,onClick:l?()=>void c():s,children:l?i===`pause`?(0,$.jsx)(ua,{size:15}):(0,$.jsx)(Va,{size:13,fill:`currentColor`}):(0,$.jsx)(Ql,{size:18})})}var Mm=new WeakMap,Nm=new WeakMap,Pm=3e4;function Fm(e,t){return JSON.stringify([e,t?.binaryPath??null,t?.sourceHome??null,t?.enabled??!0,t?.acp??null])}function Im(e,t,n){return Nm.get(e)?.get(Fm(t,n))?.value??null}function Lm(e,t,n,r){let i=Nm.get(e);i||(i=new Map,Nm.set(e,i)),i.set(Fm(t,r),{value:n,refreshedAt:Date.now()})}function Rm(e,t,n){let r=Fm(t,n),i=Nm.get(e)?.get(r);if(i&&Date.now()-i.refreshedAt<Pm)return{promise:Promise.resolve(i.value),release(){}};let a=Mm.get(e);a||(a=new Map,Mm.set(e,a));let o=a.get(r);if(!o){let i=new AbortController;o={controller:i,readers:0,promise:Y(e,`/v1/providers/${t}/native-setup`,{method:`POST`,body:JSON.stringify({action:`capabilities`}),signal:i.signal})},a.set(r,o);let s=o,c=()=>{a.get(r)===s&&a.delete(r)};o.promise.then(o=>{a.get(r)===s&&!i.signal.aborted&&!o.error&&o.session&&Lm(e,t,o,n),c()},c)}o.readers++;let s=o,c=!1;return{promise:s.promise,release(){c||(c=!0,s.readers--,s.readers===0&&a.get(r)===s&&(a.delete(r),s.controller.abort()))}}}function zm({connection:e,provider:t,providerSettings:n,disabled:r,placement:i=`top`,onSettings:a,onSetup:o}){let s=n?.providers[t],[c,l]=(0,Q.useState)(null),u=Fm(t,s),d=e?Im(e,t,s):null,f=c?.connection===e&&c.provider===t&&c.instance===u?c.value:d,[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(!1),{recovery:_}=Fo(e),v=p??f?.error;Ka(v);let y=oe(t)||[`opencode`,`grok-build`,`claude-code`].includes(t);if((0,Q.useEffect)(()=>{if(m(null),!e||!y)return;let n=Rm(e,t,s),r=!0;return n.promise.then(n=>{r&&(n.error?m(n.error):(l({connection:e,provider:t,instance:u,value:n}),a({provider:t,settings:n.settings})))}).catch(e=>{r&&m(e.message)}),()=>{r=!1,n.release()}},[e,t,y,a,u,_]),!y||!e)return null;let b=s?.nativeMode??f?.session?.modes?.currentModeId??``;async function x(n){if(e){g(!0);try{let r=await Y(e,`/v1/providers`,{method:`PATCH`,body:JSON.stringify({providers:{[t]:n}})});if(f){let n={...f,settings:r};Lm(e,t,n,s),l({connection:e,provider:t,instance:u,value:n})}a({provider:t,settings:r}),m(null)}catch(e){m(e instanceof Error?e.message:`Could not save agent settings.`)}finally{g(!1)}}}return(0,$.jsxs)($.Fragment,{children:[s&&!s.enabled?(0,$.jsx)(`button`,{type:`button`,disabled:r||h,onClick:()=>void x({enabled:!0}),children:`Enable agent`}):null,f?.session?.modes?(0,$.jsx)(Z,{compact:!0,className:`permission-select`,icon:(0,$.jsx)(go,{size:14}),placement:i,label:t===`claude-code`?`Claude permissions`:`Agent mode`,disabled:r||h,value:t===`claude-code`&&b==="default"?`manual`:b,options:f.session.modes.availableModes.map(e=>({value:e.id,label:t===`claude-code`&&e.id===`manual`?`Ask`:e.name,...t===`claude-code`?{description:e.id===`plan`?`Inspect and plan before making changes.`:e.id===`bypassPermissions`?`Run tools and commands without permission prompts.`:`Ask before actions that require permission.`}:{}})),onChange:e=>void x({nativeMode:e})}):null,f?.session?.configOptions?.filter(e=>e.type===`select`&&e.category!==`model`&&e.category!==`mode`).map(e=>(0,$.jsxs)(`label`,{className:`composer-native-option`,children:[(0,$.jsx)(`span`,{children:e.name}),(0,$.jsx)(`select`,{title:`Default ${e.name.toLowerCase()} for this agent installation`,disabled:r||h,value:s?.nativeOptions?.[e.id]??e.currentValue,onChange:t=>void x({nativeOptions:{...s?.nativeOptions,[e.id]:t.target.value}}),children:e.options?.flatMap(e=>`options`in e?e.options:[e]).map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.name},e.value))})]},e.id)),v?(0,$.jsxs)(`span`,{role:`status`,title:`Open agent setup`,children:[`Agent needs attention`,o?(0,$.jsx)(`button`,{type:`button`,onClick:o,children:`Open setup`}):null]}):null]})}function Bm(){return!!(navigator.mediaDevices&&typeof AudioContext<`u`)}async function Vm(e={}){if(!Bm())throw Error(`Voice recording is not available in this browser.`);let t=await navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,channelCount:1,echoCancellation:!0,noiseSuppression:!0}}),n=new AudioContext,r=n.createMediaStreamSource(t),i=n.createScriptProcessor(4096,1,1),a=n.createGain();a.gain.value=0;let o={audioContext:n,chunks:[],processor:i,silentGain:a,source:r,stream:t,startedAt:performance.now(),stopped:!1,onAudioLevel:e.onAudioLevel};return i.onaudioprocess=e=>{if(o.stopped)return;let t=e.inputBuffer.getChannelData(0);o.chunks.push(new Float32Array(t)),o.onAudioLevel?.(Hm(t))},r.connect(i),i.connect(a),a.connect(n.destination),{stop:()=>Um(o,!0),cancel:()=>Um(o,!1).then(()=>void 0)}}function Hm(e){if(e.length===0)return 0;let t=0;for(let n of e)t+=n*n;let n=Math.sqrt(t/e.length);return Math.min(1,(n*5)**.6)}async function Um(e,t){if(e.stopped)return{blob:new Blob([],{type:`audio/wav`}),durationMs:0,sampleRate:e.audioContext.sampleRate};e.stopped=!0,e.processor.disconnect(),e.silentGain.disconnect(),e.source.disconnect();for(let t of e.stream.getTracks())t.stop();await e.audioContext.close().catch(()=>void 0);let n=Math.max(0,performance.now()-e.startedAt);if(!t)return{blob:new Blob([],{type:`audio/wav`}),durationMs:n,sampleRate:e.audioContext.sampleRate};let r=Wm(e.chunks);if(r.length===0)throw Error(`No microphone audio was captured.`);return{blob:Gm(r,e.audioContext.sampleRate),durationMs:n,sampleRate:e.audioContext.sampleRate}}function Wm(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Float32Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function Gm(e,t){let n=e.length*2,r=new ArrayBuffer(44+n),i=new DataView(r);Km(i,0,`RIFF`),i.setUint32(4,36+n,!0),Km(i,8,`WAVE`),Km(i,12,`fmt `),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*1*2,!0),i.setUint16(32,2,!0),i.setUint16(34,16,!0),Km(i,36,`data`),i.setUint32(40,n,!0);let a=44;for(let t of e){let e=Math.max(-1,Math.min(1,t));i.setInt16(a,e<0?e*32768:e*32767,!0),a+=2}return new Blob([r],{type:`audio/wav`})}function Km(e,t,n){for(let r=0;r<n.length;r+=1)e.setUint8(t+r,n.charCodeAt(r))}var qm=96,Jm=Array.from({length:qm},()=>0);function Ym(){return[...Jm]}function Xm(e,t){return[...e.slice(-95),Math.max(0,Math.min(1,t))]}function Zm({levels:e}){let t=(0,Q.useMemo)(()=>e.length>=qm?e.slice(-96):[...Jm.slice(e.length),...e],[e]);return(0,$.jsx)(`span`,{className:`voice-recording-waveform`,role:`img`,"aria-label":`Live microphone level`,children:t.map((e,t)=>(0,$.jsx)(`span`,{className:`voice-recording-bar`,style:{"--voice-level":e},"aria-hidden":`true`},t))})}var Qm=12e4,$m=`openpond.voice.setupNoticeAcknowledged`,eh=`Voice dictation runs locally with whisper.cpp. OpenPond uses a local whisper-cli binary and downloads the voice model on first use.`;function th({connection:e,buttonClassName:t,wrapperClassName:n=``,disabled:r=!1,iconSize:i=16,language:a=`en`,onActiveChange:o,showToast:s,onTranscript:c,transcriptionChannelKey:l,submitLabel:u=`Send`}){let d=(0,Q.useRef)(null),f=(0,Q.useRef)(null),p=(0,Q.useRef)(e),m=(0,Q.useRef)(r),h=(0,Q.useRef)(`idle`),g=(0,Q.useRef)(!1),_=(0,Q.useRef)(ih());de(()=>{_.current=ih()}),p.current=e,m.current=r;let[v,y]=(0,Q.useState)(`idle`),b=(0,Q.useRef)(!1),[x,S]=(0,Q.useState)(Ym),C=(0,Q.useCallback)(e=>Of(l,e),[l]),w=(0,Q.useCallback)(()=>Ef(l),[l]),T=(0,Q.useSyncExternalStore)(C,w,w),E=(0,Q.useCallback)(()=>Df(l),[l]),D=(0,Q.useSyncExternalStore)(C,E,E)?`Transcribing · ${u.toLowerCase()} when ready`:`Transcribing`,O=T,k=v===`starting`,A=v===`recording`,j=A||T,M=k||j;h.current=v;let N=(0,Q.useCallback)(()=>{f.current!==null&&(window.clearTimeout(f.current),f.current=null)},[]),P=(0,Q.useCallback)(async()=>{N();let e=d.current;d.current=null,g.current=!1,y(`idle`),S(Ym()),e&&await e.cancel().catch(()=>void 0)},[N]),F=(0,Q.useCallback)(async(e,t,n)=>{let r=p.current;if(!r)throw Error(`Voice input is still connecting.`);let i=await Eo.voiceTranscriptionStatus(r,{signal:t});if(!i.binaryPath)throw Error(i.installHint??`Install whisper.cpp to use dictation.`);let o=await Eo.transcribeVoice(r,{audioBase64:await nh(e.blob),durationMs:Math.round(e.durationMs),language:a,mimeType:`audio/wav`},{signal:t});t.aborted||await c(o.text,{submit:n()})},[a,c]),I=(0,Q.useCallback)(()=>{kf(l),S(Ym())},[l]),L=(0,Q.useCallback)(async(e=!1)=>{N();let t=d.current;d.current=null,t&&(y(`idle`),S(Ym()),Mf(l,async(e,n)=>{let r=await t.stop();e.aborted||await F(r,e,n)},{submit:e}).catch(e=>{e instanceof DOMException&&e.name===`AbortError`||s(rh(e),`error`)}))},[N,s,F,l]),ee=(0,Q.useCallback)(async()=>{if(b.current&&!m.current){if(!p.current)s(`Voice input is still connecting.`,`error`);else if(!Bm())s(`Voice recording is not available in this browser.`,`error`);else{y(`starting`);try{let e=await window.openpond?.requestMicrophoneAccess?.();if(!b.current||m.current){await P();return}if(e===!1)throw Error(`Microphone access is denied.`);let t=await Vm({onAudioLevel:e=>{S(t=>Xm(t,e))}});if(!b.current||m.current){await t.cancel(),await P();return}if(d.current=t,S(Ym()),y(`recording`),g.current){g.current=!1,L(!0);return}f.current=window.setTimeout(()=>{L(!1)},Qm)}catch(e){b.current&&s(rh(e),`error`),await P()}}}},[P,s,L]),R=(0,Q.useCallback)(()=>{_.current?ee():s(eh,`info`,{actionLabel:`Continue`,onAction:()=>{_.current=!0,ah(),ee()}})},[ee,s]);return(0,Q.useEffect)(()=>Af(l,()=>d.current?(L(!0),!0):h.current===`starting`&&(g.current=!0,!0)),[L,l]),(0,Q.useEffect)(()=>{o?.(M)},[M,o]),(0,Q.useEffect)(()=>()=>o?.(!1),[o]),(0,Q.useEffect)(()=>(b.current=!0,()=>{b.current=!1,P()}),[P]),(0,$.jsx)(`span`,{className:`voice-input-control ${n} ${k?`starting`:``} ${A?`recording`:``} ${T?`transcribing`:``}`.trim(),children:j?(0,$.jsxs)(`span`,{className:`voice-recording-strip`,children:[(0,$.jsx)(`span`,{className:`sr-only`,role:`status`,children:T?D:`Recording voice`}),(0,$.jsx)(`button`,{type:`button`,className:`voice-recording-action cancel`,"aria-label":T?`Cancel transcription`:`Cancel dictation`,onClick:()=>{T?I():P()},children:(0,$.jsx)(Ua,{size:15})}),T?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`span`,{className:`voice-transcribing-label`,"aria-hidden":`true`,children:[D,(0,$.jsxs)(`span`,{className:`voice-transcribing-dots`,children:[(0,$.jsx)(`span`,{children:`.`}),(0,$.jsx)(`span`,{children:`.`}),(0,$.jsx)(`span`,{children:`.`})]})]}),(0,$.jsx)(`span`,{className:`voice-recording-action-spacer`,"aria-hidden":`true`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Zm,{levels:x}),(0,$.jsx)(`button`,{type:`button`,className:`voice-recording-action stop`,"aria-label":`Stop and transcribe`,onClick:()=>void L(!1),children:(0,$.jsx)(Va,{size:10,fill:`currentColor`})})]})]}):(0,$.jsx)(`button`,{type:`button`,className:`voice-input-trigger ${t} ${k?`starting`:``}`.trim(),"aria-label":k?`Starting dictation`:`Dictate`,disabled:r||O||k,onClick:R,children:(0,$.jsx)(iu,{size:i})})})}async function nh(e){let t=new Uint8Array(await e.arrayBuffer()),n=``;for(let e=0;e<t.length;e+=32768){let r=t.subarray(e,e+32768);n+=String.fromCharCode(...r)}return window.btoa(n)}function rh(e){let t=e instanceof Error?e.message:String(e);return/NotAllowedError|Permission denied|denied/i.test(t)?`Microphone access is denied.`:/NotFoundError|Requested device not found/i.test(t)?`No microphone was found.`:t||`Voice input failed.`}function ih(){if(typeof window>`u`)return!1;try{return ue.getItem($m)===`true`}catch{return!1}}function ah(){if(typeof window<`u`)try{ue.setItem($m,`true`)}catch{}}var oh=new Set([`codex`,`openai`,`xai`,`openrouter`,`deepseek`,`zai`,`moonshot`,`together`,`groq`,`custom-openai-compatible`,`setup-provider`]);function sh({surface:e=`chat`,teamUseModel:t=!1,teamUseModelLocked:n=!1,onTeamUseModelChange:r,addFiles:i,addMenuId:a,addMenuOpen:o,addMenuRef:s,busy:c,codexPermissionMode:l,codexReasoningEffort:u,connection:d,contextStatusStyle:f,contextStatusTooltipId:p,contextWindowStatus:m,disabled:h,dropdownPlacement:g,fileInputRef:_,modelValue:v,modelOptions:y=[],hideModelControls:b=!1,trainingControl:x,executionControl:S,allowedModelRefs:C,modelSelectionDisabled:w=!1,openPondCommandAccessMode:T,showCommandAccess:E=!0,profileTarget:D,onCodexPermissionModeChange:O,onCodexReasoningEffortChange:k,onOpenPondCommandAccessModeChange:A,onProfileTargetChange:j,onModelChange:M,onOpenFilePicker:N,onProviderChange:P,onProviderSetupOpen:F,onSend:I,onStop:L,onToggleAddMenu:ee,onTranscript:R,voiceInputChannelKey:z,provider:B,providerSettings:V,providerOptions:H,running:U,sendDisabled:te,hasComposerInput:ne,sendTooltip:re,showToast:W,stopIcon:ie=`stop`,stopLabel:G=`Stop response`}){let ae=Fm(B,V?.providers[B]),[K,q]=(0,Q.useState)(null),se=d?Im(d,B,V?.providers[B]):null,ce=K?.connection===d&&K.provider===B&&K.instance===ae?K.settings:se?.settings??null,le=(0,Q.useMemo)(()=>ce?V?{...V,providers:{...V.providers,[B]:ce.providers[B]},statuses:{...V.statuses,[B]:ce.statuses[B]},modelCaches:{...V.modelCaches,[B]:ce.modelCaches[B]}}:ce:V,[V,ce,B]),ue=(0,Q.useCallback)(e=>{d&&q({connection:d,provider:e.provider,instance:ae,settings:e.settings})},[d,ae]),de=oe(B)||[`claude-code`,`opencode`,`grok-build`].includes(B),fe=B===`openpond`?v:v||Si(B,le),[pe,me]=(0,Q.useState)(!1),he=fi(B,fe,le),ge=(0,Q.useMemo)(()=>Zf({currentModelOptions:ce?Ci(B,le):y,currentProvider:B,providerOptions:H,providerSettings:le}).flatMap(e=>{if(!C)return[e];let t=e.options.filter(t=>C.some(n=>n.providerId===e.provider&&n.modelId===t.value));return t.length?[{...e,options:t,defaultModel:t.some(t=>t.value===e.defaultModel)?e.defaultModel:t[0].value}]:[]}),[y,B,H,le,ce,C]),_e=(0,Q.useMemo)(()=>ge.filter(e=>oh.has(e.provider)),[ge]),ve=(e,t)=>{k(gi(e,t,le)),e===B?M(t):P(e,t)};return e===`team`?(0,$.jsxs)(`div`,{className:`composer-primary-controls team-chat-composer-controls ${U?`has-running-turn`:``}`.trim(),children:[(0,$.jsx)(`button`,{type:`button`,className:`composer-icon`,"aria-label":`Add photos and files`,disabled:h,onClick:N,children:(0,$.jsx)(za,{size:18})}),(0,$.jsx)(`input`,{ref:_,className:`composer-file-input`,type:`file`,multiple:!0,tabIndex:-1,onChange:e=>{i(Array.from(e.currentTarget.files??[])),e.currentTarget.value=``}}),(0,$.jsxs)(`label`,{className:`team-chat-model-toggle`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:t,disabled:c||n,onChange:e=>r?.(e.currentTarget.checked)}),(0,$.jsx)(`span`,{children:`Use model`})]}),(0,$.jsx)(`div`,{className:`composer-spacer`}),t?(0,$.jsx)(ap,{disabled:c,model:fe,modelGroups:_e,placement:g,provider:B,providerSettings:le,reasoningEffort:u,showReasoning:he,onModelSelectionChange:ve,onReasoningEffortChange:k}):null,S,(0,$.jsx)(th,{buttonClassName:`composer-icon`,connection:d,disabled:h,iconSize:16,wrapperClassName:`composer-voice-input`,onActiveChange:me,showToast:W,onTranscript:R,transcriptionChannelKey:z,submitLabel:re}),(0,$.jsx)(jm,{running:U,sendDisabled:te||B===`openpond`&&!v,hasComposerInput:ne,sendTooltip:re,stopIcon:ie,stopLabel:G,voiceInputActive:pe,onSend:I,onStop:L})]}):(0,$.jsxs)(`div`,{className:`composer-primary-controls ${U?`has-running-turn`:``}`.trim(),children:[(0,$.jsxs)(`div`,{className:`composer-add-control open-up`,ref:s,children:[(0,$.jsx)(`button`,{type:`button`,className:`composer-icon ${o?`active`:``}`,"aria-label":`Add to message`,"aria-haspopup":`menu`,"aria-expanded":o,"aria-controls":o?a:void 0,disabled:h,onMouseDown:e=>e.preventDefault(),onClick:ee,children:(0,$.jsx)(za,{size:18})}),(0,$.jsx)(`input`,{ref:_,className:`composer-file-input`,type:`file`,multiple:!0,tabIndex:-1,onChange:e=>{i(Array.from(e.currentTarget.files??[])),e.currentTarget.value=``}})]}),!b&&de?(0,$.jsx)(zm,{connection:d,provider:B,providerSettings:le,placement:g,onSettings:ue,onSetup:F,disabled:c||h}):null,E&&B===`codex`?(0,$.jsx)(Z,{compact:!0,className:`permission-select`,icon:(0,$.jsx)(go,{size:14}),placement:g,label:`Codex permissions`,tooltip:xi.find(e=>e.value===l)?.label,value:l,options:xi,disabled:c,onChange:e=>O(e)}):E&&!de?(0,$.jsx)(Z,{compact:!0,className:`permission-select`,icon:(0,$.jsx)(Ha,{size:14}),placement:g,label:`Command access`,tooltip:bi.find(e=>e.value===(T===`disabled`?`ask`:T))?.label,value:T===`disabled`?`ask`:T,options:bi,disabled:c,onChange:e=>A(e)}):null,D&&j?(0,$.jsx)($f,{busy:c,placement:g,state:D,onChange:j}):null,(0,$.jsx)(`div`,{className:`composer-spacer`}),!b&&(0,$.jsxs)(`span`,{className:`context-status-shell ${m.tone}`,style:f,children:[(0,$.jsx)(`span`,{className:`composer-status ${m.tone}`,role:m.maxTokens===null?`img`:`meter`,"aria-label":m.tooltip,"aria-describedby":p,"aria-valuemin":m.maxTokens===null?void 0:0,"aria-valuemax":m.maxTokens??void 0,"aria-valuenow":m.maxTokens===null?void 0:m.usedTokens,tabIndex:0}),(0,$.jsxs)(`span`,{className:`context-status-tooltip`,id:p,role:`tooltip`,children:[(0,$.jsx)(`span`,{className:`context-status-tooltip-title`,children:`Context window`}),(0,$.jsxs)(`span`,{className:`context-status-tooltip-main`,children:[(0,$.jsx)(`span`,{children:m.summary}),(0,$.jsx)(`span`,{children:m.tokensLabel})]}),m.maxTokens!==null&&(0,$.jsx)(`span`,{className:`context-status-tooltip-bar`,"aria-hidden":`true`,children:(0,$.jsx)(`span`,{})}),m.detail?(0,$.jsx)(`span`,{className:`context-status-tooltip-detail`,children:m.detail}):null]})]}),x,!b&&(0,$.jsx)(ap,{disabled:c||w,model:fe,modelGroups:ge,placement:g,provider:B,providerSettings:le,reasoningEffort:u,showReasoning:he,onModelSelectionChange:ve,onReasoningEffortChange:k}),S,(0,$.jsx)(th,{buttonClassName:`composer-icon`,connection:d,disabled:h,iconSize:16,wrapperClassName:`composer-voice-input`,onActiveChange:me,showToast:W,onTranscript:R,transcriptionChannelKey:z,submitLabel:re}),(0,$.jsx)(jm,{running:U,sendDisabled:te||B===`openpond`&&!v,hasComposerInput:ne,sendTooltip:re,stopIcon:ie,stopLabel:G,voiceInputActive:pe,onSend:I,onStop:L})]})}function ch(e){return e.description||e.path}function lh({items:e,onSelect:t,onSelectIndex:n,skillIndex:r,style:i}){let a=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{a.current?.scrollIntoView({block:`nearest`})},[e.length,r]),(0,$.jsx)(`div`,{className:`composer-project-menu composer-slash-menu composer-skill-menu`,role:`listbox`,"aria-label":`Available skills`,style:i,children:e.length>0?e.map((e,i)=>{let o=i===r;return(0,$.jsxs)(`button`,{type:`button`,className:`composer-project-option ${o?`selected`:``}`,ref:o?a:void 0,role:`option`,"aria-selected":o,onMouseEnter:()=>n(i),onMouseDown:n=>{n.preventDefault(),t(e)},children:[(0,$.jsx)(ts,{size:14}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:gf(e)}),(0,$.jsx)(`small`,{children:ch(e)})]}),o?(0,$.jsx)(Ro,{size:14}):(0,$.jsx)(`span`,{"aria-hidden":`true`})]},e.name)}):(0,$.jsx)(`div`,{className:`composer-menu-empty`,role:`option`,"aria-selected":`false`,children:`No matching skills`})})}function uh({actionCatalogCount:e,actionIndex:t,items:n,onSelect:r,onSelectIndex:i,style:a}){return(0,$.jsx)(km,{ariaLabel:`OpenPond agents and actions`,menuIndex:t,sections:[{emptyLabel:e===0?`No matching commands or apps`:`No matching commands, apps, agents, or actions`,id:`slash`,items:n.map(e=>({kind:`slash`,item:e})),label:`/`}],style:a,variant:`typed`,onSelect:e=>{e.kind===`slash`&&r(e.item)},onSelectIndex:i})}function dh({busy:e,initialDescription:t,open:n,onClose:r,onSubmit:i}){let[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(()=>t.trim()),l=a.trim(),u=s.trim(),d=e||!l||!u;if((0,Q.useEffect)(()=>{n&&(o(``),c(t.trim()))},[t,n]),(0,Q.useEffect)(()=>{if(!n||e)return;function t(e){e.key===`Escape`&&r()}return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e,r,n]),!n)return null;async function f(){d||await i({title:l,description:u})&&(o(``),c(``))}return(0,$.jsx)(`div`,{className:`git-dialog-backdrop`,role:`presentation`,onMouseDown:e?void 0:r,children:(0,$.jsxs)(`section`,{className:`git-dialog submit-issue-dialog`,role:`dialog`,"aria-modal":`true`,"aria-label":`Submit GitHub issue`,onMouseDown:e=>e.stopPropagation(),onKeyDown:e=>{e.key===`Enter`&&e.target instanceof HTMLInputElement&&(e.preventDefault(),f())},children:[(0,$.jsx)(`button`,{className:`git-dialog-close`,disabled:e,type:`button`,onClick:r,children:(0,$.jsx)(Ua,{size:16})}),(0,$.jsx)(`div`,{className:`git-dialog-icon`,children:(0,$.jsx)(Jo,{size:18})}),(0,$.jsx)(`h2`,{children:`Submit issue`}),(0,$.jsxs)(`div`,{className:`git-dialog-row submit-issue-repo-row`,children:[(0,$.jsx)(`span`,{children:`Repository`}),(0,$.jsx)(`strong`,{children:qi})]}),(0,$.jsxs)(`label`,{className:`git-dialog-field`,children:[(0,$.jsx)(`span`,{children:`Title`}),(0,$.jsx)(`input`,{autoFocus:!0,disabled:e,placeholder:`Short issue title`,value:a,onChange:e=>o(e.target.value)})]}),(0,$.jsxs)(`label`,{className:`git-dialog-field`,children:[(0,$.jsx)(`span`,{children:`Description`}),(0,$.jsx)(`textarea`,{disabled:e,placeholder:`What happened, what you expected, and any useful context`,value:s,onChange:e=>c(e.target.value)})]}),(0,$.jsxs)(`div`,{className:`git-dialog-footer`,children:[(0,$.jsx)(`button`,{className:`git-dialog-secondary`,disabled:e,type:`button`,onClick:r,children:`Cancel`}),(0,$.jsx)(`button`,{className:`git-dialog-primary`,disabled:d,type:`button`,onClick:()=>void f(),children:`Submit issue`})]})]})})}function fh(){let e=(0,Q.useRef)([]),t=(0,Q.useRef)([]),n=(0,Q.useRef)(!1),[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{e.current=r},[r]),(0,Q.useEffect)(()=>(n.current=!1,()=>{n.current=!0;for(let t of e.current)ph(t);for(let e of t.current)ph(e)}),[]);let s=(0,Q.useCallback)(t=>{if(t.length===0||n.current)return;let r=e.current,a=Math.max(0,ge.maxAttachments-r.length),s=[],c=0,l=0;for(let e of t){if(e.size>ge.maxAttachmentBytes){c+=1;continue}if(s.length>=a){l+=1;continue}let t=`webkitRelativePath`in e&&typeof e.webkitRelativePath==`string`&&e.webkitRelativePath.trim()?e.webkitRelativePath.trim():void 0;s.push({id:qe(),file:e,name:e.name||`Untitled file`,mediaType:e.type||`application/octet-stream`,sizeBytes:e.size,kind:Ge(e),...t?{relativePath:t}:{},...e.type.startsWith(`image/`)?{previewUrl:URL.createObjectURL(e)}:{}})}if(s.length>0){let t=[...r,...s];e.current=t,i(t),o(null)}if(c>0||l>0){let e=[];c>0&&e.push(`${c} file${c===1?``:`s`} exceeded ${Ue(ge.maxAttachmentBytes)}`),l>0&&e.push(`maximum ${ge.maxAttachments} attachments`),o(e.join(`; `))}},[]),c=(0,Q.useCallback)(t=>{let n=e.current,r=n.find(e=>e.id===t);r&&ph(r);let a=n.filter(e=>e.id!==t);e.current=a,i(a),a.length===0&&o(null)},[]),l=(0,Q.useCallback)(()=>{for(let t of e.current)ph(t);e.current=[],i([]),o(null)},[]),u=(0,Q.useCallback)(()=>{let n=e.current;return n.length===0||(e.current=[],t.current=n,i([]),o(null)),n},[]),d=(0,Q.useCallback)((r,a)=>{if(r.length===0)return;let o=new Set(r.map(e=>e.id));if(t.current=t.current.filter(e=>!o.has(e.id)),a===`restore`&&!n.current)i(t=>{let n=new Set(t.map(e=>e.id)),i=[...r.filter(e=>!n.has(e.id)),...t];return e.current=i,i});else for(let e of r)ph(e)},[]);return{attachmentError:a,attachments:r,addFiles:s,clearAttachments:l,removeAttachment:c,settleStagedAttachments:d,setAttachmentError:o,stageAttachmentsForSubmit:u,prepareAttachmentsForSubmit:(0,Q.useCallback)(async()=>{let e=u();try{return{attachments:await Promise.all(e.map(Ke)),settle:t=>d(e,t?`dispose`:`restore`)}}catch(t){throw d(e,`restore`),t}},[u,d]),restoreAttachmentPayloads:(0,Q.useCallback)(e=>{s(e.map(e=>{let t=e.contentsBase64?Uint8Array.from(atob(e.contentsBase64),e=>e.charCodeAt(0)):new TextEncoder().encode(e.text??``),n=new File([t],e.name,{type:e.mediaType});return e.relativePath&&Object.defineProperty(n,"webkitRelativePath",{value:e.relativePath}),n}))},[s])}}function ph(e){e.previewUrl&&URL.revokeObjectURL(e.previewUrl)}function mh(e){let t=e.current?.id===e.sessionId?e.current:null,n=e.observed?.id===e.sessionId?e.observed:null,r=[t,n].find(e=>e?.metadata?.nativeWorker===!0&&e.metadata.nativeWorkerCanResume===!1),i=r??n??t,a=typeof i?.metadata?.nativeReadOnlyReason==`string`?i.metadata.nativeReadOnlyReason:null;return{session:i,reason:r?a??`This native agent is controlled by its parent conversation. Send further instructions through the parent conversation.`:i?a:e.fallbackReason}}function hh({connection:e,sessionId:t,events:n,fallbackReason:r,fallbackSession:i}){let a=(0,Q.useMemo)(()=>{for(let e=n.length-1;e>=0;e--){let r=n[e];if(r.sessionId!==t||![`session.started`,`session.updated`,`session.title.updated`].includes(r.name))continue;let i=r.data,a=pe.safeParse(i&&typeof i==`object`&&`session`in i?i.session:null);if(a.success)return{session:a.data,eventId:r.id}}return null},[n,t]),[o,s]=(0,Q.useState)(null),{session:c,reason:l}=mh({sessionId:t,current:i,observed:o?.connection===e&&o.session.id===t&&o.eventId===a?.eventId?o.session:a?.session??null,fallbackReason:r});return{session:c,reason:l,acceptSession:t=>s({connection:e,eventId:a?.eventId,session:t})}}function gh({connection:e,session:t,reason:n,onRechecked:r,onOpenParent:i}){let[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(null);Ka(s);let l=(0,Q.useRef)(0);(0,Q.useEffect)(()=>(l.current++,o(!1),c(null),()=>{l.current++}),[e,t?.id]);let u=t?.metadata?.nativeWorker===!0&&t.metadata.nativeWorkerCanResume===!1,d=!u&&!t?.metadata?.nativeBranch&&t?.metadata?.nativeHistoryId;return(0,$.jsxs)(`div`,{className:`composer dock native-conversation-unavailable`,children:[(0,$.jsx)(`p`,{role:`status`,children:n}),u&&t?.parentSessionId&&i?(0,$.jsx)(`button`,{type:`button`,disabled:a,onClick:async()=>{o(!0),c(null);try{await i(t.parentSessionId)}catch(e){c(e instanceof Error?e.message:String(e))}finally{o(!1)}},children:`Open parent chat`}):null,e&&typeof d==`string`?(0,$.jsx)(`button`,{type:`button`,disabled:a,onClick:async()=>{let t=l.current;o(!0),c(null);try{let n=await Y(e,`/v1/native-history/open`,{method:`POST`,body:JSON.stringify({id:d,retryWorkspace:!0})});t===l.current&&r(pe.parse(n))}catch(e){t===l.current&&c(e instanceof Error?e.message:`Could not reconnect to this conversation.`)}finally{t===l.current&&o(!1)}},children:a?`Checking…`:`Check again`}):null]})}function _h(e,t){let n=e.slice(0,Math.max(0,Math.min(t,e.length))),r=/(?:^|\s)\/([a-zA-Z0-9_-]*)$/.exec(n);if(!r||typeof r.index!=`number`)return null;let i=r[0].lastIndexOf(`/`);if(i<0)return null;let a=r.index+i;return{end:n.length,query:(r[1]??``).toLowerCase(),start:a}}function vh(e,t,n=Pi){let r=e.slice(0,Math.max(0,Math.min(t,e.length))),i=/(?:^|\s)\/([a-z][a-z0-9_-]*)\s$/.exec(r);if(!i)return null;let a=n.find(e=>e.id===i[1]);if(!a)return null;let o=i[0].lastIndexOf(`/`);return o<0||typeof i.index!=`number`?null:{command:a,end:r.length,start:i.index+o}}function yh(e,t=Pi){return Fi({commands:t,prompt:`/${e}`})}function bh(e,t){return e.length===0?[]:e.filter(e=>!t||[e.id,e.name??``,e.label??``,e.description??``,typeof e.implementation?.type==`string`?e.implementation.type:``].join(` `).toLowerCase().includes(t))}function xh(e,t){return e.length===0?[]:e.filter(e=>!t||[e.id,e.name,e.description??``,e.gitRepo??``,Ja(e)].join(` `).toLowerCase().includes(t)).slice(0,8)}function Sh({actionCatalog:e,connectedAppMentions:t,mentionApps:n,profileSkills:r,query:i,surface:a,teamMentionMembers:o}){let s=i.toLowerCase();if(a===`team`){let t=o.filter(e=>!s||[e.name,e.handle??``].map(Xa).some(e=>e.includes(s))).map(e=>({kind:`team-member`,member:e}));return[...Vi(e,s,e.length).map(e=>({kind:`action`,action:e})),...t]}let c=n.filter(e=>!s||[Xa(e.id),Xa(e.name),e.gitRepo?Xa(e.gitRepo):``,Ja(e)].some(e=>e.includes(s))).map(e=>({kind:`app`,app:e})),l=Vi(e,s,e.length).map(e=>({kind:`action`,action:e})),u=vf(r,s).map(e=>({kind:`skill`,skill:e})),d=eo(t,s).map(e=>({kind:`connected-app`,app:e}));return[...l,...u,...c,...d]}function Ch(e,t,n){let r=t?.trim();if(!r)return e;let i=Math.max(0,Math.min(n??0,e.length)),a=e.slice(0,i),o=e.slice(i);return`${a}${a&&!/\s$/.test(a)?` `:``}${r}${o&&!/^\s/.test(o)?` `:``}${o}`.replace(/\s+/g,` `).trim()}function wh(e){let t=Xa(Ni(e)||e.name||e.id);return t?`@${t}`:null}function Th(e){let t=e.trim();if(!t.startsWith(`{`)||!t.endsWith(`}`))return e;try{let n=JSON.parse(t);if(!n||Array.isArray(n)||typeof n!=`object`)return e;let r=Object.entries(n).filter(([,e])=>e!=null&&e!==``).map(([e,t])=>`${Eh(e)}: ${Dh(e,t)}`);return r.length?r.join(` · `):e}catch{return e}}function Eh(e){let t=e.replace(/Id$/,``).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replaceAll(`_`,` `).trim().toLowerCase();return t?`${t[0].toUpperCase()}${t.slice(1)}`:`Input`}function Dh(e,t){if(Array.isArray(t))return t.map(t=>Dh(e,t)).join(`, `);if(t&&typeof t==`object`)return Object.entries(t).map(([e,t])=>`${Eh(e)}: ${Dh(e,t)}`).join(` · `);let n=String(t);return/Id$/.test(e)&&/^[a-z0-9_-]+$/i.test(n)?n.split(/[-_]+/).filter(Boolean).map(e=>`${e[0].toUpperCase()}${e.slice(1)}`).join(` `):n}function Oh({action:e,prompt:t,selectedActionMentionText:n,selectedInvocationPosition:r}){if(!e)return null;let i=n?.trim(),a=i?.startsWith(`@`)?i:wh(e);return a?Ch(Th(t),a,r):null}function kh({attachmentCount:e,prompt:t,selectedAction:n,selectedCommand:r}){return!!(t.trim()||e>0||n||r)}var Ah=new Set([`openpond-agent-authoring`,`openpond-skill-authoring`,`openpond-taskset-authoring`,`openpond-refiner-authoring`]);function jh({activeMentionKey:e,activeSkillKey:t,activeSlashKey:n,addMenuIndex:r,addMenuItems:i,addMenuOpen:a,addMenuPanelRef:o,addMenuRef:s,attachmentCount:c,composerRef:l,createImproveActive:u,goalRuntimeActive:d,inputRef:f,inputShellRef:p,mentionQuery:m,prompt:h,selectedActionId:g,selectAddMenuItem:_,setActionIndex:v,setActionMenuDismissedPrompt:y,setAddMenuIndex:b,setAddMenuOpen:x,setAddMenuQuery:S,setMentionMenuDismissedPrompt:C,setMentionIndex:w,setSkillIndex:T,setSkillMenuDismissedPrompt:E,skillMatchCount:D,skillQuery:O,slashMatchCount:k,slashQuery:A,showActionMenu:j,showMentionMenu:M,showSkillMenu:N}){let[P,F]=(0,Q.useState)({}),[I,L]=(0,Q.useState)({}),[ee,R]=(0,Q.useState)({}),[z,B]=(0,Q.useState)({});return(0,Q.useEffect)(()=>{w(0)},[m]),(0,Q.useEffect)(()=>{T(0)},[D,O]),(0,Q.useEffect)(()=>{v(0)},[k,A]),(0,Q.useEffect)(()=>{let e=f.current?.element,t=e?.parentElement;if(!e||!t||typeof ResizeObserver>`u`)return;let n=new ResizeObserver(()=>f.current?.resize());return n.observe(t),()=>n.disconnect()},[]),(0,Q.useEffect)(()=>{if(!a)return;function c(r){let i=r.target,a=f.current?.element?.parentElement;!s.current?.contains(i)&&!o.current?.contains(i)&&!a?.contains(i)&&(x(!1),S(``),C(e),y(n),E(t))}function l(a){if(a.key===`Escape`)a.preventDefault(),x(!1),S(``),C(e),y(n),E(t);else if(i.length!==0){if(a.key===`ArrowDown`)a.preventDefault(),b(e=>(e+1)%i.length);else if(a.key===`ArrowUp`)a.preventDefault(),b(e=>(e-1+i.length)%i.length);else if(a.key===`Home`)a.preventDefault(),b(0);else if(a.key===`End`)a.preventDefault(),b(i.length-1);else if(a.key===`Enter`){a.preventDefault();let e=i[r]??i[0];e&&_(e)}}}return document.addEventListener(`pointerdown`,c),document.addEventListener(`keydown`,l),()=>{document.removeEventListener(`pointerdown`,c),document.removeEventListener(`keydown`,l)}},[e,t,n,r,i,a]),(0,Q.useLayoutEffect)(()=>{if(!a)return;let e=p.current;if(!e)return;let t=e;function n(){B(Np(t))}return n(),window.addEventListener(`resize`,n),window.addEventListener(`scroll`,n,!0),()=>{window.removeEventListener(`resize`,n),window.removeEventListener(`scroll`,n,!0)}},[a,c,u,d]),(0,Q.useLayoutEffect)(()=>{if(!j)return;let e=f.current?.element,t=l.current;if(!e||!t)return;let n=e,r=t;function i(){R(Mp(n,r))}return i(),window.addEventListener(`resize`,i),window.addEventListener(`scroll`,i,!0),()=>{window.removeEventListener(`resize`,i),window.removeEventListener(`scroll`,i,!0)}},[c,u,d,h,g,j]),(0,Q.useLayoutEffect)(()=>{if(!N)return;let e=f.current?.element,t=l.current;if(!e||!t)return;let n=e,r=t;function i(){L(Mp(n,r))}return i(),window.addEventListener(`resize`,i),window.addEventListener(`scroll`,i,!0),()=>{window.removeEventListener(`resize`,i),window.removeEventListener(`scroll`,i,!0)}},[c,u,d,h,g,N]),(0,Q.useLayoutEffect)(()=>{if(!M)return;let e=f.current?.element,t=l.current;if(!e||!t)return;let n=e,r=t;function i(){F(Mp(n,r))}return i(),window.addEventListener(`resize`,i),window.addEventListener(`scroll`,i,!0),()=>{window.removeEventListener(`resize`,i),window.removeEventListener(`scroll`,i,!0)}},[c,u,d,h,g,M]),{actionMenuStyle:ee,addMenuStyle:z,mentionMenuStyle:P,skillMenuStyle:I}}var Mh=(0,Q.lazy)(()=>o(()=>import(`./ComposerCreateImproveStrip-CWy0j1vv.js`).then(e=>e.n).then(e=>({default:e.ComposerCreateImproveStrip})),__vite__mapDeps([68,1,2,3,15,5,16,17,13,18,19,20,4,6,21,22,23,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,61]))),Nh=Pi.find(e=>e.id===`submit-issue`),Ph=[],Fh=[];function Ih({experience:e=`development`,mode:t,surface:n=`chat`,placeholder:r,teamUseModel:i=!1,teamUseModelLocked:a=!1,teamMentionMembers:o=[],onTeamUseModelChange:s,prompt:c,composeNotice:l=null,mentionApps:u=[],connectedAppMentions:d=[],profileSkills:f=[],selectedMentionAppId:p=null,contextWindowStatus:m,goalRuntime:h=null,subagentRuntime:g=null,createImproveRuntime:_=null,busy:v,readOnlyReason:y=null,readOnlySession:b=null,onOpenNativeParent:x,running:S=v,taskSessionId:C=null,goalSessionId:w=C,taskEvents:T=Fh,steerActiveResponses:E=!1,submissionScopeKey:D=`default`,composerDraftStore:O,getCurrentSubmissionScopeKey:A,voiceInputChannelKey:j=D,initialSteerDrafts:M=Ph,showProjectFooter:N=!0,hideModelControls:P=!1,modelSelectionDisabled:F=!1,allowedModelRefs:I,executionControl:L,enableResourceContext:ee=!0,autoFocus:R=!1,focusRequestId:z=0,attachmentRequest:B=null,connection:V,providerSettings:H=null,provider:U,model:te,projectTarget:ne,profileTarget:re=null,actionCatalog:W=[],requestedAction:ie=null,workspaceTarget:G,codexPermissionMode:ae,codexReasoningEffort:K,openPondCommandAccessMode:q,onProviderChange:oe,onProviderSetupOpen:se,onProjectTargetChange:ce,onProfileTargetChange:le,onWorkspaceTargetChange:ue,onModelChange:de,onCodexPermissionModeChange:fe,onCodexReasoningEffortChange:pe,onOpenPondCommandAccessModeChange:me,onPromptChange:he,onMentionAppSelect:_e,onSaveTaskDraft:ve,showToast:ye,onSubmit:be,onStop:xe,onPauseGoal:Se}){let Ce=hh({connection:V,sessionId:C??b?.id??null,events:T,fallbackReason:y??null,fallbackSession:b}),we=Ce.reason,Te=(0,Q.useRef)(null),Ee=(0,Q.useRef)(null),De=(0,Q.useRef)(null),Oe=O?.getScopeKey(),ke=E,Ae=Lf(V,C,T),je=k(n===`chat`&&ee?V:null,C??null),Me=Xd(n===`chat`&&ee&&!je.selection?.model&&!je.selection?.training?V:null,C??null),{resourceDrafts:Ne,onPromptChange:Pe,currentResourceContexts:Fe}=qd(D,he,Me,O);mf({surface:n,voiceInputChannelKey:j,taskSessionId:C,submissionScopeKey:D,prompt:c,onPromptChange:Pe,showToast:ye,resourceDrafts:Ne,inputRef:De,composerDraftStore:O});let Ie=(0,Q.useRef)(null),Le=(0,Q.useRef)(null),Re=(0,Q.useRef)(null),ze=(0,Q.useRef)(null),Be=(0,Q.useRef)(0),Ve=ie&&W.some(e=>e.id===ie.actionId)?ie:null,He=(0,Q.useRef)(!1),Ue=(0,Q.useRef)(0),Ge=(0,Q.useRef)(Ve?.requestId??0),qe=(0,Q.useRef)(new Set),Ye=(0,Q.useRef)(new Set),[Xe,Ze]=(0,Q.useState)(c.length),Qe=(0,Q.useRef)(Xe);Qe.current=Xe;let[$e,et]=(0,Q.useState)(0),[tt,nt]=(0,Q.useState)(0),[rt,it]=(0,Q.useState)(0),[at,ot]=(0,Q.useState)(0),[st,ct]=(0,Q.useState)(``),[lt,ut]=(0,Q.useState)(null),[dt,ft]=(0,Q.useState)(null),[pt,mt]=(0,Q.useState)(null),[ht,gt]=(0,Q.useState)(!1),[_t,vt]=(0,Q.useState)(!1),[yt,bt]=(0,Q.useState)(Ve?.actionId??null),[xt,St]=(0,Q.useState)(null),[Ct,wt]=(0,Q.useState)(null),[Tt,Et]=(0,Q.useState)(null),[Dt,Ot]=(0,Q.useState)(null),[kt,At]=(0,Q.useState)(!1),[jt,Mt]=(0,Q.useState)(()=>({[D]:M})),[Nt,Pt]=(0,Q.useState)(null),[Ft,It]=(0,Q.useState)(!1),[Lt,Rt]=(0,Q.useState)(``),[zt,Bt]=(0,Q.useState)(!1),{attachmentError:Vt,attachments:Ht,addFiles:Ut,removeAttachment:Wt,settleStagedAttachments:Gt,setAttachmentError:Kt,stageAttachmentsForSubmit:qt,prepareAttachmentsForSubmit:Jt,restoreAttachmentPayloads:Yt}=fh(),Xt=(0,Q.useRef)(0);(0,Q.useEffect)(()=>{B&&Xt.current!==B.id&&(Xt.current=B.id,Ut([B.file]))},[Ut,B]);let Zt=(0,Q.useCallback)(e=>{let t=We(e,Ht);return!t||Ht.length>=ge.maxAttachments||t.size>ge.maxAttachmentBytes?!1:(Ut([t]),!0)},[Ut,Ht]),Qt=r??mm({experience:e,mode:t,surface:n}),$t=e===`development`||e===`work`&&ne.value!==`none`,en=mi(U,te,H),tn=(0,Q.useId)(),nn=(0,Q.useId)(),rn=(0,Q.useId)(),an={"--context-fill":`${Math.round((m.percent??0)/100*360)}deg`,"--context-bar-fill":`${m.percent??0}%`},on=(0,Q.useMemo)(()=>W.find(e=>e.id===yt)??null,[W,yt]),sn=(0,Q.useMemo)(()=>Bi(U,e),[e,U]),cn=(0,Q.useMemo)(()=>$t?f:f.filter(e=>!Ah.has(e.name)),[e,f]),ln=(0,Q.useMemo)(()=>sn.find(e=>e.id===xt)??null,[sn,xt]),un=Oh({action:on,prompt:c,selectedActionMentionText:Tt,selectedInvocationPosition:Ct}),dn=kh({attachmentCount:Ht.length,prompt:c,selectedAction:on,selectedCommand:ln}),fn=(0,Q.useMemo)(()=>{let e=Math.max(0,Math.min(Ct??0,c.length));return ln?{icon:ln.id===`agent`?`plus`:ln.id===`skill`?`skill`:`workflow`,key:`command:${ln.id}`,label:ln.id===`agent`?`Author Agent`:ln.id,position:e,onRemove:()=>{St(null),wt(null),Et(null)}}:on?{icon:on.implementation?.type===`openpond-agent`?`bot`:`workflow`,key:`action:${on.id}`,label:Ni(on),position:e,onRemove:()=>{bt(null),wt(null),Et(null)}}:null},[c.length,on,ln,Ct]),pn=Dt===D,mn=pn||!dn,hn=pn?`Preparing files`:S?ke?`Steer`:`Queue`:`Send`,gn=pn,_n=pn||je.selecting,vn=Vd({connection:n===`chat`&&ee?V:null,sessionId:C??null,events:T,prompt:c,selectionKey:JSON.stringify(je.selection?.target??null),inputRef:De,blocked:v||S||pn||je.selecting||Ht.length>0||!!(on||ln)||Uf(jt,D,M).length>0||!(!Ae.enabled||Ae.snapshot)||!!(Ae.snapshot?.activeTurnId||Ae.snapshot?.inputs.some(e=>e.state===`pending`))});function yn(e=D){if(we)return!1;let t=qe.current;return!t.has(e)&&(t.add(e),!0)}function bn(e){qe.current.delete(e)}function xn(e){return qe.current.has(e)}function Sn(){return xn(D)}function Cn(e){Ot(t=>t===e?null:t)}let wn=(0,Q.useMemo)(()=>{let e=I?[...new Set(I.map(e=>e.providerId))].map(e=>({value:e,label:hi(e,H),description:void 0})):pi(H,{enabledOnly:!0}).map(e=>({...e,description:void 0})),t=G.value===`cloud`&&$t?e.filter(e=>e.value===`openpond`):e,n=t.some(e=>e.value===U)?t:[{value:U,label:hi(U,H),description:`Current`},...t],r={value:`setup-provider`,label:`New Model/Provider`,icon:`plus`,separatorBefore:!0};return[...n,r]},[U,H,$t,G.value,I]),Tn=(0,Q.useMemo)(()=>Ci(U,H),[U,H]),En=(0,Q.useMemo)(()=>Za(c,Math.min(Xe,c.length)),[Xe,c]),Dn=En?`${c}:${En.start}:${Math.min(Xe,c.length)}`:null,On=(0,Q.useMemo)(()=>En?Sh({actionCatalog:W,connectedAppMentions:d,mentionApps:u,profileSkills:cn,query:En.query,surface:n,teamMentionMembers:o}):[],[W,d,u,En,cn,n,o]),kn=(0,Q.useMemo)(()=>n===`team`?[]:Sh({actionCatalog:W,connectedAppMentions:d,mentionApps:u,profileSkills:cn,query:``,surface:n,teamMentionMembers:o}).filter(e=>e.kind!==`skill`),[W,d,u,cn,n,o]),An=!!(!ht&&!gn&&En&&Dn&&lt!==Dn&&On.length>0),jn=(0,Q.useMemo)(()=>hf(c,Math.min(Xe,c.length)),[Xe,c]),Mn=jn?`${c}:${jn.start}:${jn.end}`:null,Nn=(0,Q.useMemo)(()=>jn?vf(cn,jn.query):[],[jn,cn]),Pn=!(ht||gn||!jn||!Mn||pt===Mn),Fn=(0,Q.useMemo)(()=>_h(c,Math.min(Xe,c.length)),[Xe,c]),In=Fn?`${c}:${Fn.start}:${Fn.end}`:null,Ln=(0,Q.useMemo)(()=>Fn?bh(W,Fn.query):[],[W,Fn]),Rn=(0,Q.useMemo)(()=>Fn&&n!==`team`?xh(u,Fn.query):[],[Fn,u,n]),zn=(0,Q.useMemo)(()=>Fn&&n!==`team`?yh(Fn.query,sn):[],[Fn,sn,n]),Bn=(0,Q.useMemo)(()=>Fn&&n!==`team`?vf(cn,Fn.query):[],[Fn,cn,n]),Vn=(0,Q.useMemo)(()=>[...Ln.map(e=>({kind:`action`,action:e})),...Bn.map(e=>({kind:`skill`,skill:e})),...zn.map(e=>({kind:`command`,command:e})),...Rn.map(e=>({kind:`app-context`,app:e}))],[Ln,Rn,zn,Bn]),Hn=!(ht||gn||!Fn||!In||dt===In),Un=(0,Q.useMemo)(()=>sn.map(e=>({kind:`command`,command:e})),[sn]),Wn=(0,Q.useMemo)(()=>[...bh(W,``).map(e=>({kind:`action`,action:e})),...xh(u,``).map(e=>({kind:`app-context`,app:e}))],[W,u]),Gn=(0,Q.useMemo)(()=>vf(cn,``).map(e=>({kind:`skill`,skill:e})),[cn]),Kn=(0,Q.useMemo)(()=>{let t=[{id:`add`,items:e===`work`?[{kind:`files`},{kind:`folder`}]:[{kind:`files`}],label:`Add`}];return Wn.length>0&&t.push({id:`slash`,items:Wn.map(e=>({kind:`slash`,item:e})),label:`Agents and actions`,queryScope:`slash`}),Gn.length>0&&t.push({id:`skills`,items:Gn.map(e=>({kind:`slash`,item:e})),label:`Skills`,queryScopes:[`slash`,`mentions`]}),t.push({id:`openpond`,items:Un.map(e=>({kind:`slash`,item:e})),label:`OpenPond`,grid:!0,queryScope:`slash`}),t.push({emptyLabel:`No mentions available`,id:`mentions`,items:kn.map(e=>({kind:`mention`,item:e})),label:`@`}),t},[kn,Un,Gn,Wn,e]),qn=(0,Q.useMemo)(()=>Em(Kn,st),[st,Kn]),Jn=(0,Q.useMemo)(()=>qn.flatMap(e=>e.items),[qn]);(0,Q.useEffect)(()=>{ht&&ot(e=>e<Jn.length?e:0)},[Jn.length,ht]);let Yn=!!h,Xn=Yn&&h?.tone===`active`,Zn=Xn?`Pause goal`:`Stop response`,Qn=Xn?`pause`:`stop`,$n=ne.value!==`none`,er=Uf(jt,D,M),tr=Nt?.scopeKey===D?Nt.draftId:null;function nr(e,t){Mt(n=>Wf(n,e,t,e===D?M:[]))}(0,Q.useLayoutEffect)(()=>{De.current?.resize()},[Ht.length,Vt,_,h,c,yt,xt,Ct]),(0,Q.useEffect)(()=>{if(!R){He.current=!1;return}if(He.current||gn)return;let e=window.requestAnimationFrame(()=>{He.current=!0;let e=document.activeElement;e&&e!==document.body&&e!==document.documentElement||De.current?.focusAtPromptIndex(c.length)});return()=>window.cancelAnimationFrame(e)},[R,gn,c.length]),(0,Q.useEffect)(()=>{if(!z||Ue.current===z||gn)return;let e=window.requestAnimationFrame(()=>{De.current?.element?.isConnected&&(De.current.focusAtPromptIndex(c.length),Ue.current=z)});return()=>window.cancelAnimationFrame(e)},[z,gn,c.length]),(0,Q.useEffect)(()=>{h||At(!1)},[h]),(0,Q.useEffect)(()=>{yt&&!W.some(e=>e.id===yt)&&(bt(null),wt(null))},[W,yt]),(0,Q.useEffect)(()=>{if(!ie||ie.requestId<=Ge.current)return;let e=W.find(e=>e.id===ie.actionId);e&&(Ge.current=ie.requestId,bt(e.id),St(null),wt(0),Et(null),Pe(``),Ze(0),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(0,{afterToken:!0})}))},[W,Pe,ie]),(0,Q.useEffect)(()=>{(on||ln)&&wt(e=>e===null?0:Math.max(0,Math.min(e,c.length)))},[c.length,on,ln]),(0,Q.useEffect)(()=>{if(!p||!_e)return;let e=u.find(e=>e.id===p);(!e||!to(c,e))&&_e(null)},[u,_e,c,p]);let{actionMenuStyle:rr,addMenuStyle:ir,mentionMenuStyle:ar,skillMenuStyle:or}=jh({activeMentionKey:Dn,activeSkillKey:Mn,activeSlashKey:In,addMenuIndex:at,addMenuItems:Jn,addMenuOpen:ht,addMenuPanelRef:ze,addMenuRef:Re,attachmentCount:Ht.length,composerRef:Te,createImproveActive:!!_,goalRuntimeActive:!!h,inputRef:De,inputShellRef:Ee,mentionQuery:En?.query,prompt:c,selectedActionId:yt,selectAddMenuItem:jr,setActionIndex:it,setActionMenuDismissedPrompt:ft,setAddMenuIndex:ot,setAddMenuOpen:gt,setAddMenuQuery:ct,setMentionMenuDismissedPrompt:ut,setMentionIndex:et,setSkillIndex:nt,setSkillMenuDismissedPrompt:mt,skillMatchCount:Nn.length,skillQuery:jn?.query,slashMatchCount:Vn.length,slashQuery:Fn?.query,showActionMenu:Hn,showMentionMenu:An,showSkillMenu:Pn});function sr(){bt(null),St(null),wt(null),Et(null)}function cr(){sr(),Pe(``),Ze(0)}function lr(e){Rt(e.trim()),It(!0)}function ur(){zt||(It(!1),sr())}async function dr(){return await(Xn&&Se?Se():xe())}function fr(e,t){let n=Math.max(0,Math.min(Xe,c.length)),r=t?Math.max(0,Math.min(t.start,c.length)):n,i=t?Math.max(r,Math.min(t.end,c.length)):r,a=c.slice(0,r),o=c.slice(i),s=a&&!/\s$/.test(a)?` `:``,l=o&&!/^\s/.test(o)?` `:``,u=`${s}${`${$a(e)} `}${l}`,d=`${a}${u}${o}`,f=a.length+u.length;return Pe(d),_e?.(e.id),Ze(f),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(f)}),f}function pr(e){if(!En)return;let t=Math.max(0,Math.min(Xe,c.length));fr(e,{start:En.start,end:t})}function mr(e,t,n=null){let r=Math.max(0,Math.min(Xe,c.length)),i=t?Math.max(0,Math.min(t.start,c.length)):r,a=t?Math.max(i,Math.min(t.end,c.length)):i,o=`${c.slice(0,i)}${c.slice(a)}`;return bt(e.id),St(null),wt(i),Et(n?.startsWith(`@`)?n:null),ft(null),Pe(o),Ze(i),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(i,{afterToken:!0})}),i}function hr(e){if(!En)return;let t=Math.max(0,Math.min(Xe,c.length)),n=Math.max(0,Math.min(En.start,c.length)),r=Math.max(n,Math.min(t,c.length));mr(e,{start:n,end:r},c.slice(n,r).trim())}function gr(e,t){let n=Math.max(0,Math.min(Xe,c.length)),r=t?Math.max(0,Math.min(t.start,c.length)):n,i=t?Math.max(r,Math.min(t.end,c.length)):r,a=c.slice(0,r),o=c.slice(i),s=a&&!/\s$/.test(a)?` `:``,l=o&&!/^\s/.test(o)?` `:``,u=`${s}${`${Qa(e)} `}${l}`,d=`${a}${u}${o}`,f=a.length+u.length;return Pe(d),Ze(f),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(f)}),f}function _r(e){if(!En)return;let t=Math.max(0,Math.min(Xe,c.length));gr(e,{start:En.start,end:t})}function vr(e,t){let n=Math.max(0,Math.min(Xe,c.length)),r=t?Math.max(0,Math.min(t.start,c.length)):n,i=t?Math.max(r,Math.min(t.end,c.length)):r,a=e.handle||Xa(e.name),o=c.slice(0,r),s=c.slice(i),l=`${o&&!/\s$/.test(o)?` `:``}@${a} ${s&&!/^\s/.test(s)?` `:``}`,u=`${o}${l}${s}`,d=o.length+l.length;return Pe(u),Ze(d),window.requestAnimationFrame(()=>De.current?.focusAtPromptIndex(d)),d}function yr(e){if(e.kind===`team-member`){if(!En)return;let t=Math.max(0,Math.min(Xe,c.length));vr(e.member,{start:En.start,end:t})}else if(e.kind===`app`)pr(e.app);else if(e.kind===`connected-app`)_r(e.app);else if(e.kind===`skill`){if(!En)return;let t=Math.max(0,Math.min(Xe,c.length));Tr(e.skill,{start:En.start,end:t})}else hr(e.action)}function br(e){Fn&&(ft(null),fr(e,{start:Fn.start,end:Fn.end}))}function xr(e){Fn&&mr(e,Fn)}function Sr(e,t){let n=Math.max(0,Math.min(Xe,c.length)),r=t?Math.max(0,Math.min(t.start,c.length)):n,i=t?Math.max(r,Math.min(t.end,c.length)):r,a=`${c.slice(0,r)}${c.slice(i)}`;return St(e.id),bt(null),wt(r),Et(null),ft(null),Pe(a),Ze(r),e.id===`submit-issue`&&lr(a),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(r,{afterToken:!0})}),r}function Cr(e){Fn&&Sr(e,Fn)}function wr(e){if(e.kind===`command`)Cr(e.command);else if(e.kind===`app-context`)br(e.app);else if(e.kind===`skill`){if(!Fn)return;Tr(e.skill,Fn)}else xr(e.action)}function Tr(e,t){let n=_f(c,t,e);return mt(null),ut(null),ft(null),Pe(n.value),Ze(n.cursor),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(n.cursor)}),n.cursor}function Er(e){jn&&Tr(e,jn)}function Dr(){Ie.current?.click()}function Or(){Le.current?.click()}function kr(e){Be.current=e,ct(``),ot(0)}function Ar(){let e=Math.max(0,Math.min(Xe,c.length)),t=Math.max(0,Math.min(Be.current,c.length));return e>=t?{start:t,end:e}:{start:e,end:e}}function jr(e){let t=Ar();if(gt(!1),ct(``),e.kind===`files`||e.kind===`folder`){if(t.start!==t.end){let e=`${c.slice(0,t.start)}${c.slice(t.end)}`;Pe(e),Ze(t.start)}kr(t.start),e.kind===`folder`?Or():Dr()}else if(e.kind===`slash`){if(e.item.kind===`command`){kr(Sr(e.item.command,t));return}if(e.item.kind===`app-context`){kr(fr(e.item.app,t));return}if(e.item.kind===`skill`){kr(Tr(e.item.skill,t));return}kr(mr(e.item.action,t))}else e.item.kind===`team-member`?kr(vr(e.item.member,t)):e.item.kind===`app`?kr(fr(e.item.app,t)):e.item.kind===`connected-app`?kr(gr(e.item.app,t)):e.item.kind===`skill`?kr(Tr(e.item.skill,t)):kr(mr(e.item.action,t))}let{stageCurrentSteerDraft:Mr,submitImmediateSteer:Nr}=Jd({running:S,scope:D,inbox:Ae,getPrompt:()=>De.current?.getPrompt()??c,getResourceContexts:Fe,hasActions:!!(on||ln),attachmentCount:Ht.length,prepareAttachments:async()=>{Ot(Ht.length?D:null);try{return await Jt()}finally{Cn(D)}},provider:U,model:te,codexPermissionMode:ae,codexReasoningEffort:K,openPondCommandAccessMode:q,getCurrentSubmissionScopeKey:A,onSubmit:be,showToast:ye,begin:e=>!Ye.current.has(e)&&(Ye.current.add(e),!0),finish:e=>{Ye.current.delete(e)},clear:cr,setError:Kt,stageLocal:(e,t,n)=>{nr(D,r=>[...r,Bf(e,{resourceContexts:t,attachments:n})]),window.requestAnimationFrame(()=>De.current?.focusAtPromptIndex(0))}});async function Pr(e){let t=D;if(Nt?.scopeKey===t)return!1;let n=Uf(jt,t,M).find(t=>t.id===e);if(!n)return!1;Pt({draftId:e,scopeKey:t}),Kt(null);try{let r=S,i=await be(n.attachments??[],null,null,{preservePrompt:!0,promptOverride:n.prompt,turnMetadata:{...Gd(n.resourceContexts??[]),...r?{interactionKind:`steer`}:{}}});return nr(t,t=>Hf(t,e,i)),i}catch(e){return Kt(e instanceof Error?e.message:String(e)),!1}finally{Pt(n=>n?.scopeKey===t&&n.draftId===e?null:n)}}function Fr(e){tr!==e&&nr(D,t=>Vf(t,e))}function Ir(e){if(tr===e.id)return;if(yt||xt){ye(`Finish the current composer before editing a queued message.`,`info`);return}if(Ht.length+(e.attachments?.length??0)>ge.maxAttachments){ye(`Remove some attachments before editing this message (maximum ${ge.maxAttachments}).`,`info`);return}let t;try{t=Wd(Fe(),e.resourceContexts??[])}catch{ye(`Send or clear the current resource actions before editing this queued message.`,`info`);return}let n=De.current?.getPrompt()??c,r=n.trim()?`${n}\n\n${e.prompt}`:e.prompt;nr(D,t=>Vf(t,e.id)),Ne.current.set(D,t),Yt(e.attachments??[]),Pe(r),Ze(r.length),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(r.length)})}async function Lr(e={}){if(je.selecting)return!1;let t=D;if(!yn(t))return!1;gt(!1),Kt(null);let{contexts:n,focus:r}=Kd(Ne.current.get(t),Fe(),je.selection),i=qt();try{Ot(i.length>0?t:null);let a;try{a=await Promise.all(i.map(Ke))}finally{Cn(t)}let o=on&&un&&!c.trim()?un:void 0,s=e.promptOverride??o,l=await be(a,on,ln,un||s||e.preservePrompt||n.length||je.selection?{...un?{displayPrompt:un}:{},...s===void 0?{}:{promptOverride:s},...e.preservePrompt?{preservePrompt:!0}:{},turnMetadata:{...Gd(n),...r?{chatResourceFocus:r}:{}},...je.selection?{sessionMetadata:{chatContextSelection:je.selection.target}}:{},onSessionCreated:e=>je.moveToSession(e.id)}:void 0);return l&&Ne.current.get(t)===n&&Ne.current.delete(t),Gt(i,l?`dispose`:`restore`),l&&!Di(on)&&sr(),l}catch(e){return Gt(i,`restore`),Kt(e instanceof Error?e.message:String(e)),!1}finally{bn(t),Cn(t)}}async function Rr(){if(jf(j))return;if(S){ke?await Nr():await Mr();return}if(Sn())return;let e=on||ln?null:Ii(c);ln?.id===`submit-issue`||e?.command===`submit-issue`?lr(e?.command===`submit-issue`?e.args:c):mn||await Lr()}async function zr(e){if(Sn()||zt||je.selecting)return!1;let t=D;if(!yn(t))return!1;Bt(!0),gt(!1),Kt(null);try{let t=await be([],null,Nh,{displayPrompt:`/submit-issue ${e.title.trim()}`,promptOverride:Gi(e)});return t&&(It(!1),sr()),t}catch(e){return Kt(e instanceof Error?e.message:String(e)),!1}finally{bn(t),Bt(!1)}}async function Br(e,t){let n=A?.()??D,r=n!==D&&Oe?O?.getDrafts()[Oe]:void 0,i=n===D?De.current?.getPrompt()??c:typeof r==`string`?r:r?.prompt??(O?``:c),a=Math.max(0,Math.min(Qe.current,i.length)),o=yf(i,e,t.submit?i.length:a),s=await xf({appendToEnd:t.submit,currentScopeKey:n,cursorIndex:a,originScopeKey:D,prompt:i,setOriginDraft:e=>Pe(e),submit:t.submit,submitFromOrigin:e=>S?ke?Nr(e):Mr(e):Lr({preservePrompt:!0,promptOverride:e}),transcript:e});s!==`retained`&&(s===`submitted`?n!==D&&ye(S&&!ke?`Voice message queued in the chat where recording started.`:`Voice message sent to the chat where recording started.`,`success`):(Ze(o.cursorIndex),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(o.cursorIndex)})))}return we?(0,$.jsx)(gh,{connection:V,session:Ce.session,reason:we,onRechecked:Ce.acceptSession,onOpenParent:x}):(0,$.jsxs)(`form`,{ref:Te,className:`composer ${t} ${_?`has-create-runtime`:``} ${Yn?`has-goal-runtime`:``} ${Ht.length>0?`has-attachments`:``} ${on||ln?`has-selected-action`:``} ${Vt?`has-attachment-error`:``} ${ht?`has-add-menu`:``}`,onSubmit:e=>{e.preventDefault(),Rr()},children:[Ce.session?.metadata?.nativeWorkspaceRecovered===!0?(0,$.jsx)(`p`,{className:`composer-workspace-notice`,role:`status`,title:Ce.session.cwd??void 0,children:`Using an app workspace because the original folder is unavailable.`}):null,(0,$.jsx)(`input`,{webkitdirectory:``,ref:Le,className:`composer-file-input`,type:`file`,multiple:!0,tabIndex:-1,onChange:e=>{Ut(Array.from(e.currentTarget.files??[])),e.currentTarget.value=``}}),An&&(0,$.jsx)(Am,{items:On,mentionIndex:$e,onSelect:yr,onSelectIndex:et,style:ar}),Pn&&(0,$.jsx)(lh,{items:Nn,onSelect:Er,onSelectIndex:nt,skillIndex:tt,style:or}),Hn&&(0,$.jsx)(uh,{actionCatalogCount:W.length,actionIndex:rt,items:Vn,onSelect:wr,onSelectIndex:it,style:rr}),(0,$.jsx)(dh,{busy:zt,initialDescription:Lt,open:Ft,onClose:ur,onSubmit:zr}),t===`start`&&(N||n===`chat`)&&(0,$.jsxs)(`div`,{className:`composer-footer`,children:[N?(0,$.jsx)(ep,{busy:v||ne.busy,placement:`top`,state:ne,onChange:ce}):null,re&&le?(0,$.jsx)($f,{busy:v,placement:`top`,state:re,onChange:le}):null,$n?(0,$.jsx)(np,{busy:v,placement:`top`,state:G,onChange:ue}):null]}),_?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Mh,{runtime:_})}):null,Ae.enabled?(0,$.jsx)(qf,{inbox:Ae,canRestore:(e,t)=>{if(Ht.length+t.length>ge.maxAttachments)return ye(`Remove some attachments before editing this message (maximum ${ge.maxAttachments}).`,`info`),!1;try{return Wd(Ne.current.get(D)??[],e),!0}catch{return ye(`Send or clear the current resource actions before editing this queued message.`,`info`),!1}},onRestore:(e,t,n)=>{let r=!A||A()===D,i=r?De.current?.getPrompt()??c:c;Ne.current.set(D,Wd(Ne.current.get(D)??[],t)),Pe(i.trim()?`${i}\n\n${e}`:e),Yt(n),r&&De.current?.focusAtPromptIndex(0)}}):(0,$.jsx)(cp,{drafts:er,sendingDraftId:tr,onDeleteDraft:Fr,onEditDraft:Ir,onSteerDraft:e=>{Pr(e)}}),l?.tone===`warning`?(0,$.jsx)(X,{error:l.message}):l?(0,$.jsx)(`div`,{className:`composer-notice info`,role:`status`,children:l.message}):null,n===`chat`&&ee?(0,$.jsx)(pf,{context:je,resources:Me,sessionId:C??null,busy:v},`${C}:${JSON.stringify(je.selection?.target)}`):null,(Yn||t!==`start`&&U===`codex`&&w)&&(0,$.jsx)(sp,{connection:U===`codex`?V:null,sessionId:w??null,running:S,onPause:dr,onResume:()=>be([],null,null,{preservePrompt:!0,promptOverride:`Continue pursuing the current goal.`}),detailsOpen:kt,goalRuntime:h,objectiveId:rn,subagentRuntime:g,onToggleDetails:()=>At(e=>!e)},w??D),(0,$.jsx)(Eu,{}),(0,$.jsxs)(`div`,{className:`composer-input-shell`,ref:Ee,children:[ht&&n!==`team`&&(0,$.jsx)(km,{id:tn,ariaLabel:`Add to message`,className:`composer-add-command-menu`,menuIndex:at,menuRef:ze,sections:qn,style:ir,variant:`add`,onSelect:jr,onSelectIndex:ot}),Ht.length>0&&(0,$.jsx)(`div`,{className:`composer-attachments`,"aria-label":`Selected attachments`,children:Ht.map(e=>(0,$.jsx)(Je,{attachment:e,onRemove:()=>Wt(e.id)},e.id))}),Vt&&(0,$.jsx)(X,{error:Vt}),(0,$.jsxs)(`div`,{className:`composer-textarea-frame`,onCompositionStartCapture:vn.onCompositionStart,onCompositionEndCapture:vn.onCompositionEnd,onClick:e=>{e.target===e.currentTarget&&De.current?.focusAtPromptIndex(Xe)},children:[(0,$.jsx)(Hd,{next:vn}),(0,$.jsx)(dm,{ref:De,connectedAppMentions:d,ariaDescribedBy:vn.suggestion?vn.descriptionId:void 0,disabled:gn,onCursorChange:Ze,onKeyDown:t=>{vn.onKeyDown(t)||Ld(t,ht)||Rd(t,{open:An,matches:On,index:$e,setIndex:et,select:yr,dismiss:()=>ut(Dn)})||Rd(t,{open:Pn,matches:Nn,index:tt,setIndex:nt,select:Er,dismiss:()=>mt(Mn??c)})||Rd(t,{open:Hn,matches:Vn,index:rt,setIndex:it,select:wr,dismiss:()=>ft(In??c)})||((on||ln)&&t.key===`Backspace`&&Xe===(Ct??0)?(t.preventDefault(),sr()):pm(t.key,t.ctrlKey,t.metaKey,t.shiftKey,e,n,!!ve)?(t.preventDefault(),fm({attachmentsCount:Ht.length,hasSelectedInvocation:!!(on||ln),onSave:ve,onSaved:sr,prompt:c,saving:_t,setSaving:vt,showInfo:e=>ye(e,`info`)})):t.key===`Enter`&&!t.shiftKey&&(t.preventDefault(),pn||Rr()))},onPasteFiles:Ut,onPasteTextAsAttachment:Zt,onPromptChange:(e,t)=>{if(ht){let n=Math.max(0,Math.min(Be.current,e.length));t<n?(Be.current=t,ct(``)):ct(e.slice(n,t))}let r=n===`team`?null:vh(e,t,sn);if(r){let n=`${e.slice(0,r.start)}${e.slice(r.end)}`,i=r.start;Pe(e),Ze(t),window.requestAnimationFrame(()=>{St(r.command.id),bt(null),wt(i),ft(null),Pe(n),Ze(i),r.command.id===`submit-issue`&&lr(n),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(i,{afterToken:!0})})})}else Pe(e)},onTokenPositionChange:e=>{(on||ln)&&(e===null?sr():wt(e))},placeholder:vn.suggestion?``:Qt,prompt:c,token:fn})]}),(0,$.jsx)(sh,{trainingControl:n===`chat`&&ee?(0,$.jsx)(Qd,{context:je,disabled:v,placement:`top`}):null,surface:n,teamUseModel:i,teamUseModelLocked:a,onTeamUseModelChange:s,addFiles:Ut,addMenuId:tn,addMenuOpen:ht,addMenuRef:Re,busy:v,codexPermissionMode:ae,codexReasoningEffort:K,connection:V,contextStatusStyle:an,contextStatusTooltipId:nn,contextWindowStatus:m,disabled:_n,dropdownPlacement:`top`,fileInputRef:Ie,modelValue:en,modelOptions:Tn,hideModelControls:P,modelSelectionDisabled:F,allowedModelRefs:I,executionControl:L,openPondCommandAccessMode:q,showCommandAccess:$t,profileTarget:N?null:re,onCodexPermissionModeChange:fe,onCodexReasoningEffortChange:pe,onOpenPondCommandAccessModeChange:me,onProfileTargetChange:le,onModelChange:de,onOpenFilePicker:Dr,onProviderChange:oe,onProviderSetupOpen:se,onSend:()=>void Rr(),onStop:dr,onToggleAddMenu:()=>{let e=Math.max(0,Math.min(Xe,c.length));ht||(Be.current=e,ct(``),ot(0),gt(!0)),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(e)})},onTranscript:Br,voiceInputChannelKey:j,provider:U,providerSettings:H,providerOptions:wn,running:S,sendDisabled:mn,hasComposerInput:dn,sendTooltip:hn,showToast:ye,stopIcon:Qn,stopLabel:Zn})]})]})}var Lh=(0,Q.memo)(function({draftStore:e,...t}){let n=zh(t.onProviderChange),r=zh(t.onProviderSetupOpen),i=zh(t.onProfileTargetChange),a=zh(t.onWorkspaceTargetChange),o=zh(t.onSubmit),s=zh(t.onStop),c=t.contextWindowStatus,l=(0,Q.useMemo)(()=>({...c}),[c.usedTokens,c.maxTokens,c.percent,c.summary,c.tokensLabel,c.detail,c.tooltip,c.tone]);return(0,$.jsx)(Bh,{...t,draftStore:e,mentionApps:t.mentionApps?.length===0?Rh:t.mentionApps,contextWindowStatus:l,onProviderChange:n,onProviderSetupOpen:r,onProfileTargetChange:i,onWorkspaceTargetChange:a,onSubmit:o,onStop:s})}),Rh=[];function zh(e){let t=(0,Q.useRef)(e);(0,Q.useLayoutEffect)(()=>{t.current=e},[e]);let n=(0,Q.useCallback)((...e)=>t.current?.(...e),[]);return e&&n}var Bh=(0,Q.memo)(function({draftStore:e,...t}){let n=is(e),r=e.getScopeKey(),i=(0,Q.useCallback)(t=>{e.setForScope(r,t)},[r,e]);return(0,$.jsx)(Go,{id:`composer`,children:(0,$.jsx)(Ih,{...t,prompt:n,onPromptChange:i})})}),Vh=new Set(`div span p pre code h1 h2 h3 h4 h5 h6 br hr strong em b i ul ol li table thead tbody tfoot tr th td img section article header footer main figure figcaption`.split(` `)),Hh=new Set([`style`,`title`,`aria-label`,`alt`,`width`,`height`,`colspan`,`rowspan`]);function Uh(e){let t=new DOMParser().parseFromString(e,`text/html`);for(let e of t.body.querySelectorAll(`*`))if(!Vh.has(e.localName))e.remove();else for(let t=e.attributes.length-1;t>=0;t--){let n=e.attributes[t],r=e.localName===`img`&&n.name===`src`&&/^data:image\/(png|jpeg|gif|webp|avif);base64,/i.test(n.value);!Hh.has(n.name)&&!r&&e.removeAttribute(n.name)}return`<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'"><style>body{margin:8px;font:13px/1.5 system-ui;color-scheme:light dark;background:Canvas;color:CanvasText}img{max-width:100%;height:auto}</style></head><body>${t.body.innerHTML}</body></html>`}function Wh({preview:e,label:t}){let n=/^\s*<[a-z][\w-]*\b[^>]*>/i.test(e),r=(0,Q.useMemo)(()=>n?Uh(e):``,[n,e]);return n?(0,$.jsx)(`iframe`,{className:`native-question-preview`,title:`${t} preview`,sandbox:``,referrerPolicy:`no-referrer`,srcDoc:r}):(0,$.jsx)(`div`,{className:`native-question-preview`,children:(0,$.jsx)(wa,{content:e})})}function Gh({id:e,value:t,disabled:n,connection:r,showToast:i,onChange:a,activeVoiceChannel:o,onVoiceActiveChange:s}){let c=`question-answer:${(0,Q.useId)()}`,l=(0,Q.useRef)(null),u=(0,Q.useRef)({value:t,disabled:n,onChange:a});u.current={value:t,disabled:n,onChange:a};let d=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>(d.current=!0,()=>{d.current=!1,kf(c)}),[c]),(0,Q.useEffect)(()=>{n&&kf(c)},[c,n]);let f=(0,Q.useCallback)(e=>s(c,e),[c,s]),p=(0,Q.useCallback)((e,{submit:t})=>{if(!d.current||u.current.disabled)return;let n=yf(u.current.value,e,l.current?.selectionStart??u.current.value.length);u.current.onChange(n.value.slice(0,8e3),t)},[]);return(0,$.jsxs)(`div`,{className:`native-question-custom`,children:[(0,$.jsx)(`label`,{className:`sr-only`,htmlFor:e,children:`Your answer`}),(0,$.jsx)(`textarea`,{ref:l,id:e,maxLength:8e3,rows:2,value:t,placeholder:`Write your answer…`,disabled:n,onChange:e=>a(e.target.value)}),(0,$.jsx)(`div`,{className:`native-question-answer-controls`,children:n?null:(0,$.jsx)(th,{connection:r,showToast:i,buttonClassName:`native-question-mic`,disabled:n||!r||!!(o&&o!==c),transcriptionChannelKey:c,onActiveChange:f,onTranscript:p})})]})}function Kh({questions:e,answers:t,onChange:n,onSubmit:r,...i}){let a=(0,Q.useRef)(t);return a.current=t,(0,$.jsx)(`div`,{className:`native-question-fields`,children:e.map(e=>(0,$.jsx)(qh,{question:e,...i,onChange:(t,i=!1)=>{let o={...a.current,[e.question]:t};a.current=o,n(o),i&&r(o)}},e.question))})}function qh({question:e,disabled:t,connection:n,showToast:r,onChange:i,activeVoiceChannel:a,onVoiceActiveChange:o}){let s=(0,Q.useId)(),[c,l]=(0,Q.useState)([]),[u,d]=(0,Q.useState)(e.options.length===0),[f,p]=(0,Q.useState)(``);function m(t){let n=e.multiSelect&&!u?c.includes(t)?c.filter(e=>e!==t):[...c,t]:[t];l(n),d(!1),i(n.map(t=>e.options[t].label).join(`, `))}return(0,$.jsxs)(`fieldset`,{disabled:t,children:[(0,$.jsxs)(`legend`,{children:[e.header?(0,$.jsx)(`small`,{children:e.header}):null,e.question]}),(0,$.jsxs)(`div`,{className:`native-question-options`,children:[e.options.map((e,t)=>(0,$.jsxs)(`button`,{type:`button`,className:`native-question-option`,"aria-pressed":!u&&c.includes(t),onClick:()=>m(t),children:[(0,$.jsx)(`span`,{children:e.label}),e.description?(0,$.jsx)(`small`,{children:e.description}):null]},t)),e.options.length?(0,$.jsx)(`button`,{type:`button`,className:`native-question-option custom`,"aria-pressed":u,onClick:()=>{d(!0),i(f)},children:`Write your own answer`}):null]}),e.multiSelect&&!u?(0,$.jsx)(`small`,{children:`Select one or more.`}):null,u?(0,$.jsx)(Gh,{id:s,value:f,disabled:t,connection:n,showToast:r,activeVoiceChannel:a,onVoiceActiveChange:o,onChange:(e,t)=>{p(e),i(e,t)}},s):c.map(t=>{let n=e.options[t];return n.preview?(0,$.jsx)(Wh,{preview:n.preview,label:n.label},t):null})]})}function Jh({approval:e,questions:t,canAccept:n,canSkip:r,connection:i,showToast:a,onResolve:o}){let[s,c]=(0,Q.useState)({}),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(null),p=(0,Q.useRef)(!1),m=(0,Q.useCallback)((e,t)=>{f(n=>t?e:n===e?null:n)},[]),h=e=>t.every(t=>e[t.question]?.trim());async function g(t,i=s){if(!p.current&&(t!==`accept`||n&&h(i))&&(t!==`decline`||r)){p.current=!0,u(!0);try{await o(e.id,t,t===`accept`?i:void 0)}catch{p.current=!1,u(!1)}}}return(0,$.jsxs)(`section`,{className:`native-question-request`,"data-notification-approval":e.id,"aria-label":`Questions from agent`,"aria-busy":l,children:[(0,$.jsx)(`div`,{className:`native-question-body`,children:(0,$.jsx)(Kh,{questions:t,answers:s,disabled:l,connection:i,showToast:a,onChange:c,onSubmit:e=>void g(`accept`,e),activeVoiceChannel:d,onVoiceActiveChange:m})}),(0,$.jsxs)(`div`,{className:`native-question-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`native-question-skip`,disabled:l||!r,onClick:()=>void g(`decline`),children:`Skip`}),(0,$.jsxs)(`button`,{type:`button`,className:`native-question-send`,disabled:l||!n||!d&&!h(s),onClick:()=>{d&&jf(d)||g(`accept`)},children:[(0,$.jsx)(Ql,{size:14}),(0,$.jsx)(`span`,{children:l?`Sending`:`Send`})]})]})]})}function Yh({approval:e,onResolve:t,connection:n,showToast:r}){let[i,a]=(0,Q.useState)(null);if((0,Q.useEffect)(()=>{a(null)},[e?.id]),!e||e.kind===`create_plan`)return null;let o=Zh(e.detail),s=typeof e.providerRequestId==`string`&&e.providerRequestId.startsWith(`native-agent:`),c=[],l=[],u=null;if(s)try{let t=JSON.parse(e.detail);c=t.options??[],l=t.questions??[],(t.toolCall?.toolName??t.toolCall?.title)===`ExitPlanMode`&&(u=typeof t.toolCall?.rawInput?.plan==`string`?t.toolCall?.rawInput.plan:``)}catch{}if(l.length)return(0,$.jsx)(Jh,{approval:e,questions:l,canAccept:c.some(e=>e.kind===`allow_once`),canSkip:c.some(e=>e.kind===`reject_once`),connection:n,showToast:r,onResolve:t},e.id);let d=s?c.some(e=>e.kind===`allow_always`):e.kind!==`subagent_patch_apply`,f=c.find(e=>e.kind===`allow_always`)?.name;async function p(n){if(e&&!i){a(n);try{await t(e.id,n)}catch{a(null)}}}return(0,$.jsx)(`div`,{"data-notification-approval":e.id,className:`approval-request-shell ${u===null?``:`native-input-shell`}`,role:`status`,"aria-live":`polite`,children:(0,$.jsxs)(`section`,{className:`approval-request-card`,"aria-label":u===null?`${Xh(e.kind)} approval request`:`Plan review`,children:[(0,$.jsxs)(`div`,{className:`approval-request-copy`,children:[(0,$.jsx)(`div`,{className:`approval-request-header`,children:(0,$.jsx)(`span`,{children:u===null?Xh(e.kind):`Plan review`})}),u===null?(0,$.jsx)(`code`,{className:`approval-request-title`,title:e.title,children:e.title}):null,u===null&&o&&o!==e.title&&(0,$.jsxs)(`details`,{className:`approval-request-details`,children:[(0,$.jsx)(`summary`,{children:`Details`}),(0,$.jsx)(`pre`,{children:o})]}),u===null?null:(0,$.jsx)(`div`,{className:`native-plan-review`,children:u?(0,$.jsx)(wa,{content:u}):(0,$.jsx)(`p`,{children:`Claude is ready to leave plan mode. Review the proposed plan in the conversation before continuing.`})})]}),(0,$.jsxs)(`div`,{className:`approval-request-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`approval-action primary`,disabled:!!i||s&&!c.some(e=>e.kind===`allow_once`),onClick:()=>void p(`accept`),children:[(0,$.jsx)(Ro,{size:14}),(0,$.jsx)(`span`,{children:i===`accept`?`Sending`:u===null?`Approve`:`Approve plan`})]}),d?(0,$.jsxs)(`button`,{type:`button`,className:`approval-action`,title:s?f:`Approve for the rest of this session`,disabled:!!i,onClick:()=>void p(`acceptForSession`),children:[(0,$.jsx)(eu,{size:14}),(0,$.jsx)(`span`,{children:i===`acceptForSession`?`Approving`:s?f:`Session`})]}):null,(0,$.jsxs)(`button`,{type:`button`,className:`approval-action muted`,disabled:!!i||s&&!c.some(e=>e.kind===`reject_once`),onClick:()=>void p(`decline`),children:[(0,$.jsx)(tu,{size:14}),(0,$.jsx)(`span`,{children:i===`decline`?`Sending`:u===null?`Deny`:`Keep planning`})]}),(0,$.jsx)(`button`,{type:`button`,className:`approval-action icon-only`,title:s?`Dismiss request`:`Cancel task`,"aria-label":s?`Dismiss request`:`Cancel task`,disabled:!!i,onClick:()=>void p(`cancel`),children:(0,$.jsx)(Ua,{size:15})})]})]})})}function Xh(e){return e===`create_plan`?`Plan review`:e===`subagent_patch_apply`?`Subagent patch`:e===`file_change`||e===`legacy_patch`?`File change`:e===`permissions`?`Permissions`:e===`user_input`?`Input needed`:`Command`}function Zh(e){let t=e.trim();if(!t)return``;try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}}function Qh({resolution:e,onSelect:t,onClose:n}){let r=(0,Q.useRef)(null),i=(0,Q.useId)();return(0,Q.useEffect)(()=>{let e=r.current;return e?.showModal(),()=>e?.close()},[]),(0,$.jsxs)(`dialog`,{ref:r,className:`chat-file-resolution`,"aria-labelledby":i,onCancel:n,children:[(0,$.jsx)(`h2`,{id:i,children:`Choose a file`}),(0,$.jsxs)(`p`,{children:[`Matches for `,(0,$.jsx)(`strong`,{children:e.requestedPath}),` in this project's folders:`]}),e.truncated?(0,$.jsx)(`p`,{children:`The search reached its limit. More matches may exist.`}):null,(0,$.jsx)(`div`,{className:`chat-file-resolution-options`,children:e.candidates.map(e=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>t(e),children:e},e))}),(0,$.jsx)(`button`,{type:`button`,className:`git-dialog-secondary`,onClick:n,children:`Cancel`})]})}var $h=/\.(?:m4v|mov|mp4|webm)$/i;function eg(e){return $h.test(e.trim().split(/[?#]/,1)[0]??``)}function tg(e,t){let n=e.trim();if(!n||!eg(n))return null;if(/^file:\/\//i.test(n))try{n=decodeURIComponent(new URL(n).pathname)}catch{n=n.replace(/^file:\/\//i,``)}if(/^\//.test(n)||/^[A-Za-z]:[\\/]/.test(n))return n;let r=t?.trim().replace(/[\\/]+$/,``);return r?`${r}/${n.replace(/^\.\//,``)}`:null}function ng({conversationKey:e,connection:t,handleOpenBrowserLink:n,activeWorkspaceAppId:r,rightSidebarUsesSandbox:i,rightSidebarSandboxId:a,onShowDiffPanel:s,showToast:c,workspaceRootPath:l,setOpenDiffFileRequest:u}){let[d,f]=(0,Q.useState)(null),p=(0,Q.useRef)(0),m=(0,Q.useRef)(0),h=(0,Q.useRef)(0),g=ra(t);(0,Q.useEffect)(()=>(p.current++,f(null),()=>{p.current++}),[g,r,e,a]),(0,Q.useEffect)(()=>(m.current++,()=>{m.current++}),[g,e]);let _=(0,Q.useCallback)(async(e,d)=>{if(/[\\/]$/.test(e)){let t=/^(?:[~/\\]|[A-Za-z]:)/.test(e)?e:l?`${l}/${e}`:e;ga(t).then(e=>{e||c(`Open this folder in the desktop app on the machine where it was created.`,`error`)});return}let f=d?.local?null:d?.sandboxId??(i?a:null),p=f??(d?.local?va(e):r);if(fa(e)&&!d?.source&&t&&p){ya(t,p,e,f?`sandbox`:`local`).then(e=>n(e)).catch(e=>c(e instanceof Error?e.message:`Could not open HTML preview.`,`error`));return}let g=tg(e,l);if(g&&t){Eo.signLocalVideoUrl(t,{path:g}).then(({url:e})=>n(e)).catch(e=>{c(e instanceof Error?e.message:`Could not open this video.`,`error`)});return}if(/\.pptx$/i.test(e)&&o(()=>import(`./WorkspacePresentationPreview-DQTvhaRD.js`),__vite__mapDeps([69,1,2,3,16,20,4,5,6,21,22,13,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,18,42,43,44,45,46,47,48,19,49,50,51,52,53,54,55,56,70,71,72])).catch(()=>{}),/\.docx$/i.test(e)&&(o(()=>import(`./FilePagePreview-BRhhz99q.js`),__vite__mapDeps([73,1,2,3,16,20,4,5,6,21,22,13,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,18,42,43,44,45,46,47,48,19,49,50,51,52,53,54,55,56,74])).catch(()=>{}),o(()=>import(`./docx-preview-Blk_WGfs.js`),__vite__mapDeps([75,1,72])).catch(()=>{})),d?.sandboxId&&t){let n=m.current,r=++h.current;s(),u({id:++h.current,loadId:r,sandboxId:d.sandboxId,path:e,file:Xo(e),loading:!0});try{let i=await xa(t,d.sandboxId,e);if(n!==m.current)return;let a=bo(i.path)&&i.content?`data:image/${/\.jpe?g$/i.test(e)?`jpeg`:e.split(`.`).pop()};base64,${i.content}`:void 0;u({id:++h.current,loadId:r,sandboxId:d.sandboxId,path:i.path,file:i,imageUrl:a})}catch(t){n===m.current&&u({id:++h.current,loadId:r,sandboxId:d.sandboxId,path:e,file:Xo(e),error:t instanceof Error?t.message:`Could not open this file.`})}return}let _=ma(e,{workspaceRootPath:l}),v=d?.local?e:_?.path??e,y=va(v);if((d?.local||!r&&!i)&&t&&y){let e=m.current,n=++h.current;s(),u({id:++h.current,loadId:n,sandboxId:null,path:v,file:Xo(v),loading:!0});try{let r=bo(v)?await Eo.signLocalImageUrl(t,{path:v}):null,i=r?Xo(v):await Eo.workspaceFile(t,y,v);if(e!==m.current)return;u({id:++h.current,loadId:n,sandboxId:null,path:i.path,file:i,imageUrl:r?.url})}catch(t){e===m.current&&u({id:++h.current,loadId:n,sandboxId:null,path:v,file:Xo(v),error:t instanceof Error?t.message:`Could not open this file.`})}}else s(),u({id:++h.current,path:d?.source&&fa(e)?(_?.path??e).replace(/[?#].*$/,``):_?.path??e,source:d?.source})},[t,n,r,i,a,s,c,l,u]),v=(0,Q.useCallback)((e,a)=>{let o=++p.current;if(f(null),/^https?:\/\//i.test(e)){n(e);return}let s=!a?.sandboxId&&!!va(e)&&(!i||!/^\/workspace(?:\/|$)/.test(e));if(a?.local||a?.sandboxId||s||!t||!r||i){_(e,s?{...a,local:!0}:a);return}let l=ma(e)?.path??e,u=fa(l)?l.match(/[?#].*$/)?.[0]??``:``,d=u?l.slice(0,-u.length):l;Eo.resolveWorkspaceFile(t,r,d).then(t=>{o===p.current&&(t.status===`resolved`?_(t.kind===`directory`?`${t.path}/`:`${t.path}${u}`,a):t.candidates.length?f({requestedPath:e,candidates:t.candidates.map(e=>`${e}${u}`),truncated:t.truncated,source:a?.source}):c(t.truncated?`The project search reached its limit. Open this file using its full path.`:`Could not find ${e} in this project's folders. Try its full path.`,`error`))}).catch(e=>{o===p.current&&c(e instanceof Error?e.message:`Could not locate this file.`,`error`)})},[t,r,i,_,n,c]);return{handleOpenFileInSidebar:v,fileResolution:d,dismissFileResolution:(0,Q.useCallback)(()=>f(null),[]),selectFileResolution:(0,Q.useCallback)(e=>{let t=d?.source;f(null),v(e,{source:t})},[d,v])}}function rg(e){let t=[];if(e.localWorkspaceId&&t.push({value:`local`,label:`Local`}),(e.sandboxSourceAvailable??!!e.sandboxWorkspaceId)&&t.push({value:`sandbox`,label:`Sandbox`}),t.length===0)return{source:null,options:t};let n=new Set(t.map(e=>e.value));if(e.override&&n.has(e.override))return{source:e.override,options:t};let r=e.workspaceTarget===`local`?`local`:`sandbox`;return n.has(r)?{source:r,options:t}:{source:t[0].value,options:t}}var ig=new Set([`create`,`edit`,`help`,`list`]);function ag(e,t,n=null){return og(e)}function og(e){let t=e.trim();if(!t)return`/skill`;let[n=``]=t.split(/\s+/,1);return ig.has(n.toLowerCase())?`/skill ${t}`:`/skill create ${t}`}async function sg(e){let t=e.session?.currentProfile??null,n=e.session?await e.patchSession(e.session.id,e.ref):null;try{return{selected:await e.selectProfile(e.ref),session:n}}catch(r){if(n)try{await e.patchSession(n.id,t)}catch{}throw r}}function cg(e,t){if(!e||!t)return null;let n=new Set(e.sources.filter(e=>e.sessionId===t).map(e=>e.id));return n.size?e.creations.find(e=>e.request.sourceIds.some(e=>n.has(e)))??null:null}function lg(e){let[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(null),d=(0,Q.useRef)(null),f=(0,Q.useRef)(0),p=(0,Q.useCallback)(async(t,n={})=>{if(!e){i(null),c(`OpenPond App server is not connected.`);return}let r=f.current+1;f.current=r,n.silent||o(!0),c(null);try{let n=await Eo.getCreateImproveCandidateDiff(e,t.runId,t.candidateId),a=d.current;if(r!==f.current||a?.runId!==t.runId||a.candidateId!==t.candidateId)return;i(n)}catch(e){if(r!==f.current)return;c(e instanceof Error?e.message:String(e))}finally{r===f.current&&!n.silent&&o(!1)}},[e]),m=(0,Q.useCallback)(e=>{let t=d.current;e&&t?.runId===e.runId&&t.candidateId===e.candidateId||(d.current=e,n(e),u(null),e?(i(t=>t?.appId===ug(e)?t:null),p(e)):(f.current+=1,i(null),c(null),o(!1)))},[p]),h=(0,Q.useCallback)(async(e={})=>{let t=d.current;t&&await p(t,e)},[p]),g=(0,Q.useCallback)(e=>{u({id:Date.now(),path:e})},[]);return(0,Q.useEffect)(()=>{e||m(null)},[m,e]),{selection:t,diff:r,loading:a,error:s,openFileRequest:l,activate:m,refresh:h,openFile:g}}function ug(e){return`candidate:${e.runId}:${e.candidateId}`}function dg(e){let{activeModel:t,activeProvider:n,bootstrap:r,codexPermissionMode:i,codexReasoningEffort:a,connection:o,onOpenRightChatForSession:s,onPayload:c}=e,l=(0,Q.useCallback)(async e=>{if(!o||!r)throw Error(`OpenPond is still connecting.`);let i=r.profile;if(i.mode!==`local`||!i.repoPath)throw Error(`A local Git-backed Profile is required to change an Agent.`);let l=e.authoringModel??wi(n,t,r.providers);if(!l)throw Error(`Choose a model before changing an Agent.`);let u=await Eo.createSession(o,{provider:l.providerId,modelRef:l,systemKind:`openpond.lab`,hiddenFromDefaultSidebar:!0,title:`${e.operation===`create`?`New`:`Improve`} Agent · ${e.objective.slice(0,80)}`,cwd:i.repoPath,metadata:{source:e.operation===`create`?`lab_agent_create`:`lab_agent_improve`,profileId:i.activeProfile??`default`,targetAgentId:e.agentId??null}}),d=e.objective.trim();if(!d)throw Error(e.operation===`create`?`Describe what the Agent should do.`:`Describe what the Agent could do better.`);if(l.providerId===`codex`)throw Error(`Agent authoring uses OpenPond's bundled authoring skill. Choose a hosted model.`);let f=e.operation===`create`?`/agent create ${d}`:`/agent improve ${e.agentId??``} ${d}`,p=await Eo.sendTurn(o,u.id,{prompt:f,model:l.modelId,modelRef:l,approvalPolicy:`never`,sandbox:`workspace-write`,codexPermissionMode:`default`,codexReasoningEffort:a});if(p.status===`failed`)throw Error(p.error??`OpenPond could not complete the Agent authoring turn.`);c(await Eo.bootstrap(o)),s(u.id,u)},[t,n,r,i,a,o,s,c]);return{createAgentFromLab:(0,Q.useCallback)((e,t,n)=>l({objective:e,operation:`create`,authoringRunId:t,authoringModel:n}),[l]),improveAgentFromLab:(0,Q.useCallback)((e,t,n,r,i)=>l({agentId:e,agentName:n,objective:t,operation:`improve`,authoringRunId:r,authoringModel:i}),[l])}}function fg(e,t,n=!0){let r=u(),i=[`ponder-hosted-sandboxes`,ra(e),t],a=S({queryKey:i,enabled:n,staleTime:5e3,refetchInterval:n?3e4:!1,queryFn:({signal:t})=>Y(e,`/v1/ponder/local/hosted-sandboxes`,{signal:t})}),o=ds({mutationFn:async t=>{if(!a.data)throw Error(`Wait for hosted sandbox availability to load.`);return Y(e,`/v1/ponder/local/hosted-sandboxes`,{method:`POST`,body:JSON.stringify({enabled:t,revision:a.data.revision,...t?{teamId:a.data.account?.teamId??null,accountId:a.data.account?.id,apiBaseUrl:a.data.account?.apiBaseUrl}:{}})})},onSuccess:e=>r.setQueryData(i,e),onError:()=>{r.invalidateQueries({queryKey:i})}});return Ka(a.error),Ka(o.error),{state:a.data,loading:a.isPending,saving:o.isPending,setEnabled:e=>o.mutate(e),refetch:a.refetch}}function pg({connection:e,accountScopeKey:t}){let n=fg(e,t),r=!n.state||n.saving||!n.state.available&&!n.state.enabled;return(0,$.jsxs)(`div`,{className:`ponder-setup-card`,children:[(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`strong`,{children:`Hosted sandboxes`}),(0,$.jsx)(`input`,{type:`checkbox`,role:`switch`,"aria-label":`Hosted sandboxes`,checked:n.state?.enabled??!1,disabled:r,onChange:e=>n.setEnabled(e.currentTarget.checked)})]}),(0,$.jsx)(`p`,{children:`Allow Pal to send selected assignments and their required project context to hosted Work environments. Hosted usage may incur charges.`}),(0,$.jsx)(`small`,{children:n.loading?`Checking availability…`:n.state?.enabled?`Enabled for this account. Turning this off prevents new hosted assignments; existing work stays available.`:n.state?.reason??`Off. Turn on to allow hosted assignments.`}),!n.state&&!n.loading?(0,$.jsx)(`button`,{type:`button`,className:`git-dialog-secondary`,onClick:()=>void n.refetch(),children:`Check availability`}):null]})}function mg(e){let t=[],n=new Map,r=new Map;for(let i of e){if(i.source===`ponder-recommendation`)continue;let e=Wr.safeParse(i.metadata.ponderLocalMessage),a=e.success?e.data:null,o=i.metadata.ponderMessage;if(a||o){let e=a??o,s=a?.sessionId??o.conversationId,c=e.status===`resolved`||e.status===`completed`?`resolved`:e.status===`consumed`||e.status===`included`?`included`:e.status===`cancelled`?`cancelled`:e.status===`failed`||e.status===`rejected`?`rejected`:`pending`;if(t.push({id:i.id,role:`task_message`,content:e.body,timestamp:i.createdAt,taskMessagePresentation:{input:{body:e.body,state:c,error:null},direction:e.direction,peer:{sessionId:s,title:e.title,provider:a?`local`:`openpond`}}}),a&&r.set(s,a),a?.outputs.length||o?.outputFileIds.length){let e=`${i.id}:outputs`;t.push({id:e,role:`resources`,timestamp:i.createdAt}),n.set(e,i)}}else(i.role===`user`||i.role===`assistant`&&i.text.trim())&&t.push({id:i.id,role:i.role,content:i.text,timestamp:i.createdAt,finalAnswer:i.role===`assistant`,footerCacheSummary:i.metadata.kvCacheSummary})}return{messages:t,sources:n,localPeers:r}}function hg(e){return e.state===`proposed`&&[`waiting_input`,`waiting_approval`,`cancelled`].includes(e.target.status)}function gg({items:e,busy:t,editingId:n,onEdit:r,onSend:i,onDismiss:a,onOpen:o}){return e.length?(0,$.jsx)(`section`,{className:`ponder-recommendations`,"aria-label":`Pal recommendations`,children:e.map(e=>(0,$.jsxs)(`article`,{className:`ponder-recommendation`,"data-state":e.state,children:[(0,$.jsx)(`button`,{type:`button`,className:`ponder-recommendation-target`,onClick:()=>o(e.target.conversationId),children:e.target.title}),(0,$.jsx)(`p`,{children:e.summary}),e.submittedText||e.proposedText?(0,$.jsx)(`blockquote`,{children:e.submittedText??e.proposedText}):null,(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Why Pal suggested this`}),e.evidence.map(e=>(0,$.jsx)(`p`,{children:e.excerpt},e.id))]}),[`proposed`,`failed`,`stale`,`submitting`].includes(e.state)?(0,$.jsxs)(`div`,{className:`ponder-recommendation-actions`,children:[e.state===`proposed`&&e.proposedText?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,disabled:!!t,onClick:()=>r(e),children:n===e.id?`Editing below`:`Edit`}),(0,$.jsx)(`button`,{type:`button`,disabled:!!t||hg(e),onClick:()=>i(e),children:t===e.id?`Sending…`:n===e.id?`Send edited message`:`Send`})]}):null,(e.state===`failed`||e.state===`submitting`)&&e.submittedText&&e.submissionRevision!==null?(0,$.jsx)(`button`,{type:`button`,disabled:!!t,onClick:()=>i(e),children:t===e.id?`Retrying…`:`Retry reviewed message`}):null,hg(e)?(0,$.jsx)(`small`,{role:`status`,children:`Resolve this task's wait or cancellation before sending a new message.`}):null,e.state===`submitting`?(0,$.jsx)(`small`,{role:`status`,children:`Awaiting task acknowledgment`}):(0,$.jsx)(`button`,{type:`button`,disabled:!!t,onClick:()=>a(e),children:`Dismiss`}),e.state===`stale`?(0,$.jsx)(`small`,{role:`status`,children:`Task changed — review its latest state`}):null]}):(0,$.jsx)(`small`,{role:`status`,children:e.state===`submitted`?`Message submitted to the task`:e.state===`stale`?`Task changed — review the latest task before sending`:e.state.replaceAll(`_`,` `)}),e.error?(0,$.jsx)(`p`,{role:`alert`,children:e.error}):null]},e.id))}):null}function _g(e,t){let[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(null),c=(0,Q.useRef)({connection:e,bindingId:t});c.current={connection:e,bindingId:t};let l=(0,Q.useRef)(!1),u=(0,Q.useRef)(!0),d=(0,Q.useCallback)(async n=>{if(!t)return;let i=await Y(e,`/v1/ponder/recommendations`,{signal:n});u.current&&!n?.aborted&&c.current.connection===e&&c.current.bindingId===t&&i.bindingId===t&&(r(i.items),a(null))},[e,t]);return(0,Q.useEffect)(()=>{if(u.current=!0,r([]),a(null),s(null),!t)return()=>{u.current=!1};let e=new AbortController,n=!1,i=async()=>{if(!n){n=!0;try{await d(e.signal)}catch(t){e.signal.aborted||a(t instanceof Error?t.message:`Unable to read recommendations.`)}finally{n=!1}}};i();let o=window.setInterval(()=>void i(),5e3);return()=>{u.current=!1,e.abort(),window.clearInterval(o)}},[t,d]),{items:n,error:i,busy:o,action:(0,Q.useCallback)(async(n,r,i)=>{if(l.current||!t)return!1;if(r===`send`&&hg(n))return a(`Resolve this task's wait or cancellation before sending a new message.`),!1;let o=r===`send`&&(n.state===`submitting`||n.state===`failed`);if(o&&(!n.submittedText||n.submissionRevision===null))return!1;let f=o?n.submissionRevision:n.revision,p=o?n.submittedText:i;l.current=!0,s(n.id);try{return await Y(e,`/v1/ponder/recommendations/${encodeURIComponent(n.id)}/action`,{method:`POST`,body:JSON.stringify({action:r,expectedRevision:f,...p===void 0?{}:{message:p}})}),!u.current||c.current.connection!==e||c.current.bindingId!==t?!1:(await d(),u.current&&c.current.connection===e&&c.current.bindingId===t)}catch(n){return c.current.connection===e&&c.current.bindingId===t&&a(n instanceof Error?n.message:`Recommendation action failed.`),!1}finally{l.current=!1,c.current.connection===e&&c.current.bindingId===t&&s(null)}},[t,e,d]),refresh:d}}function vg({connection:e,work:t,localWork:n,busy:r,onOpenWork:i,onOpenLocalWork:a,onOpenLocalOutput:o,onOpenOutput:s}){let[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(null),f=(0,Q.useRef)({connection:e,mounted:!0,inFlight:!1});f.current.connection!==e&&(f.current={connection:e,mounted:!0,inFlight:!1}),(0,Q.useEffect)(()=>{let e=f.current;return e.mounted=!0,l(null),d(null),()=>{e.mounted=!1}},[e]);let p=[...t.flatMap(e=>e.deliveries.filter(e=>e.status===`attention`&&e.attentionAt).map(t=>({task:e,delivery:t,kind:`hosted`}))),...n.flatMap(e=>e.deliveries.filter(e=>e.status===`attention`&&e.attentionAt).map(t=>({task:e,delivery:t,kind:`local`})))];async function m(t){let n=f.current;if(!t.attentionAt||n.inFlight)return;let r=()=>n.mounted&&f.current===n;n.inFlight=!0,l(t.inputId),d(null);try{await Y(e,`/v1/ponder/results/retry`,{method:`POST`,body:JSON.stringify({inputId:t.inputId,attentionAt:t.attentionAt,priorTurnId:t.ponderTurnId})})}catch(e){r()&&d(e instanceof Error&&e.message===`hosted_work_model_not_available`?`The selected model is unavailable. Choose an available model, then retry.`:`The discussion could not be started. Refresh and try again.`)}finally{n.inFlight=!1,r()&&l(null)}}return p.length===0?null:(0,$.jsxs)(`section`,{"aria-label":`Saved results needing discussion`,"aria-live":`polite`,children:[p.map(e=>(0,$.jsxs)(`div`,{className:`ponder-desktop-attention`,children:[(0,$.jsxs)(`p`,{children:[`The result from`,` `,(0,$.jsx)(`button`,{type:`button`,onClick:()=>e.kind===`hosted`?i(e.task.conversationId):a(e.task),children:e.task.title}),` `,`is saved.`,e.delivery.attentionReason===`model_unavailable`?` The selected model was unavailable.`:e.delivery.attentionReason===`chat_cancelled`?` The discussion was cancelled.`:` The discussion failed.`]}),e.delivery.outputs.map(t=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>e.kind===`local`?o({...e.task,turnId:e.delivery.localTurnId},t.id):s(t.id),children:[t.title,` · Download`]},t.id)),(0,$.jsx)(`button`,{type:`button`,disabled:r||c!==null,onClick:()=>void m(e.delivery),children:c===e.delivery.inputId?`Starting discussion…`:`Retry discussion`})]},e.delivery.inputId)),u?(0,$.jsx)(X,{error:u}):null]})}function yg({message:e,work:t,onOpenOutput:n,onOpenLocalOutput:r}){let i=Wr.safeParse(e.metadata.ponderLocalMessage),a=i.success?i.data:null;return(0,$.jsxs)(`div`,{className:`ponder-message-destination`,children:[e.metadata.ponderMessage?.outputFileIds.map(e=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>n(e),children:t.flatMap(e=>e.deliveries.flatMap(e=>e.outputs)).find(t=>t.id===e)?.title??`Saved file`},e)),a?.outputs.map(e=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>r(a,e.id),children:[e.title,` · Download`]},e.id))]})}function bg(e){let t=e.deliveries[0]?.outcome;if(t===`completed`)return`Completed`;if(t===`failed`)return`Failed`;if(t===`cancelled`)return`Stopped`;switch(e.status){case`ready`:return`Waiting to start on desktop`;case`dispatching`:return`Starting on desktop`;case`admitted`:return`Waiting for result`;case`completed`:return`Completed`;case`failed`:return`Failed to start`;case`cancelled`:return`Stopped`;case`expired`:return`Couldn’t start before the request expired`;case`attention`:return`Needs attention`;default:return`Checking task status`}}function xg({items:e,workflow:t,sessions:n,onOpenTask:r}){let i=t?new Set([t.prerequisite.sessionId,t.successor.sessionId,t.workflow?.preparationSessionId]):null,a=[...new Map([...e].reverse().filter(e=>e.sessionId&&(!i||i.has(e.sessionId))).map(e=>[e.sessionId,e])).values()].reverse();if(!a.length)return null;let o=new Map(n.map(e=>[e.id,e]));return(0,$.jsxs)(`div`,{className:`assistant-sources ponder-agent-sources`,"aria-label":`Conversations started`,children:[(0,$.jsx)(`h3`,{children:`Conversations started`}),(0,$.jsx)(`div`,{className:`assistant-source-stack`,children:a.map(e=>{let t=o.get(e.sessionId);return(0,$.jsxs)(`button`,{type:`button`,className:`assistant-source-pill`,title:`${e.title} · ${bg(e)}`,"aria-label":`Open ${e.title}`,onClick:()=>r(e),children:[t?(0,$.jsx)(Ho,{session:t}):(0,$.jsx)(Da,{size:14,"aria-hidden":`true`}),(0,$.jsx)(`span`,{children:e.title})]},e.sessionId)})})]})}async function Sg(e,t,n,r){if(!t.turnId)throw Error(`This local result has no completed task turn.`);if(await yu(e,t),!r())return;let i=await Y(e,`/v1/ponder/desktop/outputs`,{method:`POST`,body:JSON.stringify({operationId:t.operationId,turnId:t.turnId,outputId:n})});if(!r())return;let a=Uint8Array.from(atob(i.contentsBase64),e=>e.charCodeAt(0)),o=URL.createObjectURL(new Blob([a],{type:i.contentType})),s=document.createElement(`a`);s.href=o,s.download=i.filename,document.body.append(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(o),3e4)}function Cg(e){if(e instanceof Ti&&(e.message===`public_api_route_not_found`||e.message===`product_route_not_found`))return`Pal is available in this app, but the connected OpenPond service has not been updated yet.`;let t=e instanceof Error?e.message:String(e);return/<(?:!doctype|html|head|body)\b/i.test(t)||/\b50[234]\b/.test(t)?`Pal is temporarily unavailable. Please try again.`:t.length>240?`Pal couldn’t complete this action. Please try again.`:t}function wg({connection:e,accountScopeKey:t,localSessions:n,composer:r,onOpenWork:i,onOpenLocalWork:a,navigationVersion:o=0}){let[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(0),[y,b]=(0,Q.useState)(null);Ka(y?Cg(y):null);let x=yo(e,!!s,t,!1),S=x.data?.items??[],C=x.data?.localItems??[],w=x.data?.localHandoffs??[],T=_g(e,s?.bindingId??null);Ka(T.error?Cg(T.error):null),Ka(l?.activeTurn?.status===`failed`?Cg(l.activeTurn.errorText??`Pal couldn’t complete this request. Please try again.`):null);let[E,D]=(0,Q.useState)(null),O=E?T.items.find(e=>e.id===E.id):null,k=!(!E||O&&O.state===`proposed`&&O.revision===E.revision&&!hg(O)),A=(0,Q.useRef)(``),j=(0,Q.useRef)({connection:e,bindingId:s?.bindingId,destination:E?.id??`chat`,draft:d});j.current={connection:e,bindingId:s?.bindingId,destination:E?.id??`chat`,draft:d};let M=(0,Q.useRef)(!1),N=(0,Q.useRef)(!0);function P(){D(null),f(A.current)}function F(e){E||(A.current=d),D(e),f(e.proposedText??``)}async function I(e,t){let n=j.current,r=E?.id===e.id;await T.action(e,t,t===`send`?r?d:e.proposedText??void 0:void 0)&&r&&j.current.connection===n.connection&&j.current.bindingId===n.bindingId&&j.current.destination===n.destination&&(j.current.draft===n.draft?P():D(null))}(0,Q.useEffect)(()=>{N.current=!0;let t=!0;return c(null),u(null),b(null),f(``),A.current=``,g(!1),m(``),D(null),Y(e,`/v1/ponder`,{method:`POST`,body:`{}`}).then(e=>{t&&(c(e),b(null))}).catch(e=>{t&&b(Cg(e))}),()=>{t=!1,N.current=!1}},[e]),(0,Q.useEffect)(()=>{if(!s)return;let t=!0,n=!1,r=async()=>{if(!n){n=!0;try{let n=await Y(e,`/v1/ponder/conversations/${encodeURIComponent(s.conversationId)}`);t&&u(n)}catch(e){t&&b(Cg(e))}finally{n=!1}}};r();let i=window.setInterval(()=>void r(),3e3);return()=>{t=!1,window.clearInterval(i)}},[e,s]),(0,Q.useEffect)(()=>{x.error&&b(Cg(x.error))},[x.error]);async function L(t){let n=t.contentsBase64?Uint8Array.from(atob(t.contentsBase64),e=>e.charCodeAt(0)):t.text===void 0?null:new TextEncoder().encode(t.text);if(!n)throw Error(`Attachment ${t.name} has no content to upload.`);let r=await crypto.subtle.digest(`SHA-256`,n),i=btoa(String.fromCharCode(...new Uint8Array(r))),a=await Y(e,`/v1/ponder/work-inputs`,{method:`POST`,body:JSON.stringify({name:t.name,contentType:t.mediaType,sizeBytes:n.byteLength,sha256Base64:i})}),o=await fetch(a.upload.url,{method:a.upload.method,headers:a.upload.headers,body:new Blob([n],{type:t.mediaType})});if(!o.ok)throw Error(`Attachment upload failed (${o.status})`);return Y(e,`/v1/ponder/work-inputs/${encodeURIComponent(a.input.id)}/finalize`,{method:`POST`,body:`{}`})}async function ee(t=[],n){let r=(n?.promptOverride??d).trim();if(!s||!r||M.current)return!1;let i=j.current,a=()=>N.current&&j.current.connection===i.connection&&j.current.bindingId===i.bindingId&&j.current.destination===i.destination;M.current=!0,g(!0);try{if(E){if(k)throw Error(`Review the latest task state before sending this proposed message.`);if(t.length)throw Error(`Send task messages as text. Attachments can be sent in the task's own conversation.`);let e=await T.action(E,`send`,r);return a()?(e&&j.current.draft===i.draft&&P(),e):!1}let n=await Promise.all(t.map(L));if(!a())return!1;let o=await Y(e,`/v1/ponder/conversations/${encodeURIComponent(s.conversationId)}/turns`,{method:`POST`,headers:{"idempotency-key":crypto.randomUUID()},body:JSON.stringify({prompt:r,attachments:n})});return a()?(u(e=>e?{...e,activeTurn:o}:{id:s.conversationId,messages:[],activeTurn:o}),v(e=>e+1),j.current.draft===i.draft&&f(``),b(null),!0):!1}catch(e){return a()&&b(Cg(e)),!1}finally{M.current=!1,g(!1)}}async function R(t,n){if(t.wait)try{await Y(e,`/v1/ponder/turns/${encodeURIComponent(t.id)}/waits/${encodeURIComponent(t.wait.id)}/resolve`,{method:`POST`,body:JSON.stringify(n)}),m(``)}catch(e){b(Cg(e))}}async function z(t){try{await Y(e,`/v1/ponder/turns/${encodeURIComponent(t.id)}/cancel`,{method:`POST`,body:`{}`})}catch(e){b(Cg(e))}}async function B(t){let n=window.open(`about:blank`,`_blank`);try{let r=await Y(e,`/v1/ponder/work-outputs/${encodeURIComponent(t)}`);if(!r.downloadURL)throw Error(`This output is not available for download.`);n?n.location.replace(r.downloadURL):window.location.assign(r.downloadURL)}catch(e){n?.close(),b(Cg(e))}}async function V(t){if(!t.sessionId)return;let n=j.current,r=()=>N.current&&j.current.connection===n.connection&&j.current.bindingId===n.bindingId;try{if(await yu(e,t),!r())return;a(t.sessionId)}catch(e){r()&&b(Cg(e))}}async function H(t,n){let r=j.current,i=()=>N.current&&j.current.connection===r.connection&&j.current.bindingId===r.bindingId;try{await Sg(e,t,n,i)}catch(e){i()&&b(Cg(e))}}let U=!!(l?.activeTurn&&[`queued`,`running`,`retry_scheduled`].includes(l.activeTurn.status)),te=!!(l?.activeTurn&&[`queued`,`running`,`retry_scheduled`,`waiting_approval`,`waiting_input`].includes(l.activeTurn.status)),ne=(0,$.jsx)(xg,{items:C,workflow:w[0],sessions:n,onOpenTask:e=>void V(e)}),re=(0,Q.useMemo)(()=>mg(l?.messages??[]),[l?.messages]);return(0,$.jsx)(fd,{scroll:{navigationVersion:o,browserConversationId:l?.id??null,chatSubmissionVersion:_,chatMessages:re.messages,chatHistoryHasMore:!1,chatHistoryLoading:!1,pendingApproval:null,showChatThread:!0,showThinkingIndicator:U,turnRunning:te,view:`chat`},thread:{connection:e,usageSessionId:null,label:`Pal conversation`,loading:!l,onOpenSession:e=>{let t=re.localPeers.get(e);t?V(t):i(e)},renderMessage:e=>{let t=re.sources.get(e.message.id);return t?(0,$.jsx)(yg,{message:t,work:S,onOpenOutput:e=>void B(e),onOpenLocalOutput:(e,t)=>void H(e,t)}):void 0},beforeMessages:(0,$.jsxs)($.Fragment,{children:[!l&&!y&&(0,$.jsx)(`article`,{className:`activity-group thinking-row`,role:`status`,children:(0,$.jsx)(hu,{running:!0,children:`Loading conversation…`})}),(0,$.jsx)(vg,{connection:e,work:S,localWork:C,onOpenWork:i,onOpenLocalWork:e=>void V(e),onOpenLocalOutput:(e,t)=>void H(e,t),onOpenOutput:e=>void B(e),busy:h||te})]}),afterMessages:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(gg,{items:T.items,busy:T.busy,editingId:E?.id??null,onEdit:F,onSend:e=>{I(e,`send`)},onDismiss:e=>{I(e,`dismiss`)},onOpen:i}),ne,l?.activeTurn?.wait&&(0,$.jsxs)(`section`,{className:`ponder-desktop-attention`,children:[(0,$.jsx)(`strong`,{children:l.activeTurn.wait.title}),l.activeTurn.wait.kind===`approval`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>void R(l.activeTurn,{decision:`accepted`}),children:`Approve`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>void R(l.activeTurn,{decision:`declined`}),children:`Decline`})]}):l.activeTurn.wait.options.length>0?l.activeTurn.wait.options.map(e=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>void R(l.activeTurn,{value:e}),children:e},e)):(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),R(l.activeTurn,{value:p})},children:[(0,$.jsx)(`input`,{"aria-label":`Response to Pal`,value:p,onChange:e=>m(e.target.value)}),(0,$.jsx)(`button`,{type:`submit`,disabled:!p.trim(),children:`Send response`})]})]}),l?.activeTurn?.outputs?.map(e=>e.downloadURL?(0,$.jsx)(`a`,{href:e.downloadURL,target:`_blank`,rel:`noreferrer`,children:e.name},e.id):(0,$.jsx)(`button`,{type:`button`,onClick:()=>void B(e.id),children:e.name},e.id))]})},composerPrefix:(0,$.jsx)($.Fragment,{children:E?(0,$.jsxs)(`div`,{className:`ponder-message-destination`,role:`status`,children:[(0,$.jsxs)(`span`,{children:[`Message to `,E.target.title,k?` — review the latest task state before sending`:``]}),(0,$.jsx)(`button`,{type:`button`,onClick:P,children:`Return to Pal chat`})]}):null}),composer:(0,$.jsx)(Ih,{...r,experience:`chat`,mode:`dock`,showProjectFooter:!1,hideModelControls:!0,connection:e,prompt:d,onPromptChange:f,busy:h||k||!!T.busy||!s,running:U&&!E,submissionScopeKey:`ponder:${s?.conversationId??`loading`}:${E?.id??`chat`}`,voiceInputChannelKey:`ponder:${s?.conversationId??`loading`}`,onSubmit:(e,t,n,r)=>ee(e,r?.promptOverride?{promptOverride:r.promptOverride}:void 0),onStop:()=>l?.activeTurn?z(l.activeTurn):void 0})})}function Tg({state:e,connection:t,accountScopeKey:n,onSetup:r}){let i=(0,Q.useId)(),a=(0,Q.useRef)(null),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)({}),u=fg(t,n,o),d=S({queryKey:[`account-remote-access`,ra(t)],enabled:o,staleTime:5e3,refetchInterval:o?1e4:!1,queryFn:({signal:e})=>Y(t,`/v1/account-remote-access`,{signal:AbortSignal.any([e,AbortSignal.timeout(15e3)])})});Ka(d.error?.message??null);let f=d.data?{connected:`Connected`,connecting:`Connecting`,reconnecting:`Reconnecting`,offline:`Offline`,off:`Off`,signed_out:`Sign in required`,update_required:`Update required`}[d.data.state]:d.isPending?`Checking connection…`:`Unknown`;return(0,Q.useEffect)(()=>{if(!o)return;function e(){let e=a.current?.getBoundingClientRect();if(!e)return;let t=Math.min(320,window.innerWidth-24);l({left:Math.max(12,Math.min(e.left,window.innerWidth-t-12)),bottom:window.innerHeight-e.top+8,width:t,maxHeight:Math.max(100,e.top-24)})}return e(),window.addEventListener(`resize`,e),window.addEventListener(`scroll`,e,!0),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`scroll`,e,!0)}},[o]),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{ref:a,type:`button`,className:`ponder-execution-control`,popoverTarget:i,children:`Pal`}),(0,$.jsxs)(`div`,{id:i,popover:`auto`,className:`ponder-connections`,style:c,onToggle:e=>s(e.newState===`open`),role:`dialog`,"aria-label":`Pal connections`,children:[(0,$.jsx)(`h3`,{children:`Connections`}),(0,$.jsxs)(`section`,{className:`ponder-access-section`,"aria-label":`Desktop and remote access`,children:[(0,$.jsxs)(`label`,{children:[(0,$.jsxs)(`span`,{children:[`This desktop`,(0,$.jsx)(`small`,{children:e?.session?`Pal runs here`:`Set up Pal to start`})]}),(0,$.jsx)(`input`,{type:`checkbox`,role:`switch`,"aria-label":`This desktop execution`,checked:!!e?.session,readOnly:!0,disabled:!0})]}),[`Web access`,`iOS access`].map(e=>(0,$.jsxs)(`div`,{className:`ponder-connection-card`,role:`group`,"aria-label":e,children:[(0,$.jsxs)(`span`,{children:[e,(0,$.jsx)(`small`,{children:f})]}),(0,$.jsx)(`span`,{className:`ponder-connection-dot${d.data?.state===`connected`?` connected`:``}`,role:`img`,"aria-label":`${e}: ${f}`,title:`Shared desktop relay connection`})]},e))]}),(0,$.jsxs)(`label`,{className:`ponder-hosted-sandboxes`,children:[(0,$.jsxs)(`span`,{children:[`Hosted sandboxes`,(0,$.jsx)(`small`,{children:u.loading?`Checking availability…`:u.state?.enabled?`Selected assignments may run in hosted Work.`:u.state?.reason??`Allow selected assignments and required project context to run in hosted Work. Usage may incur charges.`})]}),(0,$.jsx)(`input`,{type:`checkbox`,role:`switch`,"aria-label":`Hosted sandboxes enabled`,checked:u.state?.enabled??!1,disabled:!u.state||u.saving||!u.state.available&&!u.state.enabled,onChange:e=>u.setEnabled(e.currentTarget.checked)})]}),(0,$.jsx)(`button`,{type:`button`,onClick:r,children:`Pal settings`})]})]})}function Eg({children:e,onClose:t}){let n=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{let e=document.activeElement;return n.current?.showModal(),()=>{n.current?.close(),e instanceof HTMLElement&&e.isConnected&&e.focus()}},[]),(0,$.jsx)(`dialog`,{ref:n,className:`git-dialog ponder-setup`,"aria-labelledby":`ponder-setup-title`,onCancel:e=>{e.preventDefault(),t()},children:e})}function Dg(e){let{connection:t,composer:n}=e,r=(0,Q.useMemo)(()=>t,[t.serverUrl,t.token,t.platform,t.arch]),i=JSON.stringify([ra(r),e.accountScopeKey]),a=(0,Q.useRef)(i);a.current=i;let o=u(),s=[`ponder-local`,ra(r),e.accountScopeKey],c=[...s,`snapshot`],l=S({queryKey:c,staleTime:3e4,queryFn:()=>Y(r,`/v1/ponder/local?catalog=0`)}),d=S({queryKey:s,staleTime:3e4,queryFn:()=>Y(r,`/v1/ponder/local`)}),f=l.data,p=(0,Q.useMemo)(()=>f&&(!d.data||f.coordinator.revision>d.data.coordinator.revision)?{...f,supportedModelRefs:d.data?.supportedModelRefs??[]}:d.data??null,[f,d.data]);function m(e){o.setQueryData(s,e),o.setQueryData(c,e)}Ka(d.error?.message??null),Ka(l.error?.message??null);let[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(!1),y=(0,Q.useRef)(null),[b,x]=(0,Q.useState)(null);Ka(b);let[C,w]=(0,Q.useState)(!1),[T,E]=(0,Q.useState)(0),[D,O]=(0,Q.useState)(``),[k,A]=(0,Q.useState)(`openai`),[j,M]=(0,Q.useState)(``),N=Sd(r,h?null:p?.session?.id??null),P=Lf(r,h?null:p?.session?.id??null,N.events);Ka(N.error),Ka(P.error);let F=P.snapshot?!(!P.snapshot.activeTurnId||P.snapshot.paused):N.running;(0,Q.useEffect)(()=>{let e=P.acknowledgedInput;if(!e||e.sessionId!==p?.session?.id)return;let t=y.current;t&&typeof t==`object`&&t.scope!==i||(t?.acknowledge?.(!0),y.current=null,w(!1),O(t=>t.trim()===e.body.trim()?``:t),P.acknowledgeRetainedInput())},[P.acknowledgedInput,p?.session?.id,i]),(0,Q.useEffect)(()=>{g(!1),x(null),O(``),w(!1),y.current=null},[i]),(0,Q.useEffect)(()=>{p&&(v(!p.session),p.coordinator.modelRef&&(A(p.coordinator.modelRef.providerId),M(p.coordinator.modelRef.modelId)))},[p]);async function I(e=k,t=j){w(!0);try{let n=await Y(r,`/v1/ponder/local`,{method:`POST`,body:JSON.stringify({modelRef:{providerId:e,modelId:t}})});if(a.current!==i)return;m(n),A(e),M(t),v(!1),x(null)}catch(e){a.current===i&&x(ju(e))}finally{a.current===i&&w(!1)}}async function L(e,t){let r=p?.session,o=(t??D).trim();if(!r||!o||C||y.current)return!1;let s={scope:i,acknowledge:void 0};y.current=s;let c=new Promise(e=>{s.acknowledge=e});w(!0);try{let t={prompt:o,attachments:e,modelRef:p.coordinator.modelRef??void 0,approvalPolicy:`on-request`,sandbox:`workspace-write`,codexPermissionMode:`default`,codexReasoningEffort:n.codexReasoningEffort};return!await Promise.race([P.queue(t),c])||a.current!==i?!1:(E(e=>e+1),O(e=>e===D?``:e),x(null),!0)}catch(e){return a.current===i&&x(ju(e)),!1}finally{y.current===s&&(y.current=null),a.current===i&&w(!1)}}let ee=Object.values(n.providerSettings?.statuses??{}).filter(e=>e.available&&e.enabled&&p?.supportedModelRefs?.some(t=>t.providerId===e.id)).map(e=>({value:e.id,label:e.displayName})),R=Ci(k,n.providerSettings).filter(e=>p?.supportedModelRefs?.some(t=>t.providerId===k&&t.modelId===e.value));(0,Q.useEffect)(()=>{if(p?.session||!p?.supportedModelRefs.length)return;let e=p.supportedModelRefs,t=e.find(e=>e.providerId===`openai`&&e.modelId===`gpt-6.1-sol`)??e.find(e=>e.providerId===`anthropic`&&e.modelId===n.providerSettings?.statuses.anthropic?.defaultModel)??e.find(e=>e.providerId===n.provider&&e.modelId===n.model)??e[0];A(t.providerId),M(t.modelId)},[p,n.providerSettings,n.provider,n.model]);let z=$i(N.events),B=Xi({provider:p?.session?.provider??k,snapshot:z?.model===p?.coordinator.modelRef?.modelId?z:null,preferences:e.contextCompaction});return(0,$.jsxs)(`div`,{className:`ponder-workspace`,children:[(0,$.jsx)(`div`,{className:`ponder-main`,children:h?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`ponder-connection-bar`,children:(0,$.jsx)(`button`,{type:`button`,onClick:()=>g(!1),children:`Return to local Pal`})}),(0,$.jsx)(wg,{...e})]}):(0,$.jsx)(fd,{scroll:{navigationVersion:e.navigationVersion,browserConversationId:p?.session?.id??null,chatSubmissionVersion:T,chatMessages:N.messages,chatHistoryHasMore:N.hasMore,chatHistoryLoading:N.loading,onLoadMoreChatHistory:N.loadOlder,pendingApproval:null,showChatThread:!0,showThinkingIndicator:F,turnRunning:F,view:`chat`},thread:{...e.messageContext,connection:r,label:`Pal conversation`,loading:!p||N.loading,onOpenSession:t=>e.onOpenAgents(t),beforeMessages:(0,$.jsxs)($.Fragment,{children:[!p&&l.isError?(0,$.jsx)(`button`,{type:`button`,onClick:()=>void l.refetch(),children:`Retry opening Pal`}):null,p&&!p.session?(0,$.jsxs)(`div`,{className:`ponder-empty`,children:[(0,$.jsx)(`h2`,{children:`Meet Pal`}),(0,$.jsx)(`p`,{children:`Delegate work and keep your agents coordinated in one conversation.`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>v(!0),children:`Set up local Pal`})]}):null,p?.session&&!N.loading&&N.messages.length===0?(0,$.jsxs)(`div`,{className:`ponder-empty`,children:[(0,$.jsx)(`h2`,{children:`What would you like to work on?`}),(0,$.jsx)(`p`,{children:`Tell Pal what you need. Delegated agents will appear on the right, and you can take control whenever you want.`})]}):null]})},composer:(0,$.jsx)(Ih,{...n,connection:r,experience:`chat`,mode:`dock`,placeholder:`Ask Pal to coordinate work…`,showProjectFooter:!1,provider:p?.session?.provider??k,model:p?.coordinator.modelRef?.modelId??j,contextWindowStatus:B,allowedModelRefs:p?.supportedModelRefs??[],modelSelectionDisabled:F,onProviderChange:(e,t)=>{t&&I(e,t)},onModelChange:e=>{I(p?.session?.provider??k,e)},executionControl:(0,$.jsx)(Tg,{state:p,connection:r,accountScopeKey:e.accountScopeKey,onSetup:()=>v(!0)}),goalSessionId:null,enableResourceContext:!1,taskSessionId:p?.session?.id,taskEvents:N.events,prompt:D,onPromptChange:O,busy:C||!p?.session,running:F,submissionScopeKey:`ponder-local:${p?.session?.id??`setup`}`,onSubmit:(e,t,n,r)=>L(e??[],r?.promptOverride),onStop:async()=>{if(p?.session)try{await co.interruptTurn(r,p.session.id)}catch(e){x(ju(e))}}})})}),_&&p?(0,$.jsxs)(Eg,{onClose:()=>v(!1),children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`h2`,{id:`ponder-setup-title`,children:`Welcome to Pal`}),(0,$.jsx)(`button`,{type:`button`,"aria-label":`Close setup`,onClick:()=>v(!1),children:(0,$.jsx)(Ua,{size:16})})]}),(0,$.jsx)(`p`,{children:`Pal stands for Ponder Assisted Learning. It coordinates your agents. Start on this desktop and keep your conversation here.`}),(0,$.jsxs)(`div`,{className:`ponder-setup-card`,children:[(0,$.jsx)(`h3`,{children:`On this desktop`}),(0,$.jsx)(`p`,{children:`Use your configured model. Your provider’s inference charges may apply.`}),(0,$.jsx)(Z,{label:`Pal provider`,value:k,options:ee,onChange:e=>{A(e),M(Ci(e,n.providerSettings)[0]?.value??``)}}),(0,$.jsx)(Z,{label:`Pal model`,value:j,options:R,onChange:M}),d.isError?(0,$.jsx)(`button`,{type:`button`,className:`git-dialog-secondary`,onClick:()=>void d.refetch(),children:`Retry loading models`}):null,(0,$.jsx)(`button`,{type:`button`,className:`git-dialog-primary`,disabled:C||!j||!ee.some(e=>e.value===k),onClick:()=>void I(k,j),children:p.session?`Save local model`:`Start locally`}),(0,$.jsx)(`button`,{type:`button`,className:`git-dialog-secondary`,onClick:()=>{v(!1),n.onProviderSetupOpen?.()},children:`Configure a provider`})]}),(0,$.jsx)(pg,{connection:r,accountScopeKey:e.accountScopeKey}),[[`remoteAccess`,`Web and iOS access`,`Access local Pal without a subscription while your desktop stays online.`],[`hostedCoordinator`,`Hosted Pal`,`Keep your coordinator available in the cloud. Activation uploads this Pal conversation.`]].map(([e,t,n])=>(0,$.jsxs)(`div`,{className:`ponder-setup-card`,children:[(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`strong`,{children:t}),(0,$.jsx)(`input`,{type:`checkbox`,role:`switch`,checked:!1,disabled:!0,"aria-label":t})]}),(0,$.jsx)(`p`,{children:n}),(0,$.jsx)(`small`,{children:p.capabilities[e].reason??`Setup is not available yet.`})]},e)),(0,$.jsx)(`button`,{type:`button`,className:`git-dialog-secondary`,onClick:()=>{g(!0),v(!1)},children:`Open existing hosted Pal`})]}):null]})}function Og({accountBaseUrl:e,onOpenBrowserLink:t,...n}){function r(r){if(!e)n.composer.showToast(`OpenPond account URL is unavailable for this Work task.`,`error`);else try{t(new URL(`/tasks/${encodeURIComponent(r)}`,e).toString(),{newTab:!0})}catch{n.composer.showToast(`OpenPond account URL is invalid for this Work task.`,`error`)}}return(0,$.jsx)(Dg,{...n,onOpenWork:r})}function kg(e){return JSON.stringify({account:e?.account.activeProfile??null,baseUrl:e?.account.baseUrl??null,owner:e?.account.profile?.id??null,state:e?.account.state??null,teamId:e?.preferences.defaultTeamId??null})}function Ag({expanded:e,terminalOpen:t,sideChatAvailable:n,onOpenFiles:r,onOpenAgents:i,onOpenReview:a,onOpenSideChat:o,onOpenTrainingDraft:s,trainingDraftAvailable:c,onResizeStart:l,onToggleExpanded:u,onToggleTerminal:d}){return(0,$.jsxs)(`aside`,{className:`workspace-diff-panel right-sidebar-home-panel ${e?`expanded`:``}`,"aria-label":`Right sidebar`,children:[e?null:(0,$.jsx)(`div`,{className:`workspace-diff-resize-handle`,role:`separator`,"aria-orientation":`vertical`,"aria-label":`Resize right sidebar`,onPointerDown:l}),(0,$.jsxs)(`div`,{className:`workspace-diff-topbar right-sidebar-home-topbar`,children:[(0,$.jsx)(`div`,{className:`workspace-diff-tabs`,role:`tablist`,"aria-label":`Right sidebar views`,children:(0,$.jsxs)(`button`,{type:`button`,className:`workspace-diff-tab active`,role:`tab`,"aria-selected":!0,children:[(0,$.jsx)(es,{size:14}),(0,$.jsx)(`span`,{children:`Workspace`})]})}),(0,$.jsx)(`div`,{className:`workspace-diff-toolbar-actions`,children:(0,$.jsx)(`button`,{type:`button`,className:`diff-icon-button`,title:e?`Dock sidebar`:`Expand sidebar`,"aria-label":e?`Dock sidebar`:`Expand sidebar`,onClick:u,children:e?(0,$.jsx)(da,{size:14}):(0,$.jsx)(Fa,{size:14})})})]}),(0,$.jsx)(`div`,{className:`right-sidebar-home-body`,children:(0,$.jsx)(jg,{terminalOpen:t,sideChatAvailable:n,onOpenFiles:r,onOpenAgents:i,onOpenReview:a,onOpenSideChat:o,onOpenTrainingDraft:s,trainingDraftAvailable:c,onToggleTerminal:d})})]})}function jg({terminalOpen:e,sideChatAvailable:t,onOpenFiles:n,onOpenFile:r,onOpenReview:i,onOpenExperiments:a,onOpenAgents:o,onOpenSideChat:s,onOpenTrainingDraft:c,trainingDraftAvailable:l,onToggleTerminal:u}){let d=[{id:`review`,label:`Review`,meta:`Diffs`,icon:oa,onSelect:i},{id:`files`,label:`Files`,meta:`Workspace`,icon:Na,onSelect:n},{id:`side-chat`,label:`Side chat`,meta:`Context`,icon:Ia,onSelect:s,disabled:!t},{id:`training-draft`,label:`Task draft`,meta:`Training`,icon:Ao,onSelect:c,disabled:!l},{id:`terminal`,label:e?`Hide terminal`:`Terminal`,meta:`Shell`,icon:Ha,onSelect:u}];return o&&d.push({id:`agents`,label:`Agents`,icon:Ia,onSelect:o}),a&&d.unshift({id:`experiments`,label:`Ponder`,meta:`Experiments and models`,icon:Ao,onSelect:a}),r&&d.splice(a?3:2,0,{id:`open-file`,label:`Open file`,icon:Na,onSelect:r}),(0,$.jsx)(`div`,{className:`right-sidebar-home-actions`,role:`menu`,"aria-label":`Workspace actions`,children:d.map(e=>(0,$.jsxs)(`button`,{type:`button`,className:`right-sidebar-home-row`,role:`menuitem`,disabled:e.disabled,onClick:e.onSelect,children:[(0,$.jsx)(e.icon,{size:15}),(0,$.jsx)(`span`,{children:e.label}),e.meta?(0,$.jsx)(`span`,{className:`right-sidebar-home-chip`,children:e.meta}):null]},e.id))})}var Mg=[];function Ng(e){let t=window.openpond?.browser,[n,r]=(0,Q.useState)(()=>({conversationId:e,activeTabId:null,tabs:Mg}));(0,Q.useEffect)(()=>{if(r({conversationId:e,activeTabId:null,tabs:Mg}),!t)return;let n=!1,i=!1;t.getState({conversationId:e}).then(e=>{!n&&!i&&r(e)});let a=t.onState(t=>{t.conversationId===e&&(i=!0,r(t))});return()=>{n=!0,a()}},[t,e]);let i=(0,Q.useMemo)(()=>n.tabs.find(e=>e.id===n.activeTabId)??null,[n.activeTabId,n.tabs]),a=(0,Q.useCallback)(async(n,r={})=>{if(!t)return!1;let i=no(n,{explicitFile:r.explicitFile});if(!i)return!1;let a=r.newTab?await t.newTab({conversationId:e,url:i,explicitFile:r.explicitFile}):await t.open({conversationId:e,url:i,explicitFile:r.explicitFile});if(!a.ok)throw Error(a.error||`Could not open browser.`);return!0},[t,e]),o=i?{conversationId:e,tabId:i.id}:null;return{activeTab:i,available:!!t,bridge:t,state:n,back:()=>t&&o?t.back(o):Promise.resolve({ok:!1}),clearData:()=>t?t.clearData({conversationId:e}):Promise.resolve({ok:!1}),closeTab:n=>t?t.closeTab({conversationId:e,tabId:n}):Promise.resolve({ok:!1}),forward:()=>t&&o?t.forward(o):Promise.resolve({ok:!1}),newTab:n=>t?t.newTab({conversationId:e,url:n}):Promise.resolve({ok:!1}),open:a,openExternal:()=>t&&o?t.openExternal(o):Promise.resolve({ok:!1}),reload:()=>t&&o?t.reload(o):Promise.resolve({ok:!1}),snapshot:(n={})=>t?t.snapshot({conversationId:e,...n}):Promise.resolve({ok:!1,output:`Desktop browser bridge unavailable.`}),moveCursor:n=>t?t.moveCursor({conversationId:e,...n}):Promise.resolve({ok:!1,output:`Desktop browser bridge unavailable.`}),click:n=>t?t.click({conversationId:e,...n}):Promise.resolve({ok:!1,output:`Desktop browser bridge unavailable.`}),typeText:n=>t?t.typeText({conversationId:e,...n}):Promise.resolve({ok:!1,output:`Desktop browser bridge unavailable.`}),key:n=>t?t.key({conversationId:e,...n}):Promise.resolve({ok:!1,output:`Desktop browser bridge unavailable.`}),scroll:n=>t?t.scroll({conversationId:e,...n}):Promise.resolve({ok:!1,output:`Desktop browser bridge unavailable.`}),selectTab:n=>t?t.selectTab({conversationId:e,tabId:n}):Promise.resolve({ok:!1}),setBounds:n=>t?t.setBounds({conversationId:e,bounds:n}):Promise.resolve({ok:!1}),stop:()=>t&&o?t.stop(o):Promise.resolve({ok:!1})}}function Pg({activeTab:e,documentName:t,snapshotActions:n,available:r,onBack:i,onClearData:a,onForward:o,onNavigate:s,onOpenExternal:c,onReload:l,onStop:u}){let[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{f(t??e?.url??``)},[e?.id,e?.url,t]);function h(e){e.preventDefault(),!t&&s(d)}return(0,$.jsxs)(`div`,{className:`browser-toolbar`,children:[(0,$.jsxs)(`div`,{className:`browser-nav-actions`,children:[(0,$.jsx)(`button`,{type:`button`,title:`Back`,"aria-label":`Back`,disabled:!e?.canGoBack,onClick:i,children:(0,$.jsx)(so,{size:15})}),(0,$.jsx)(`button`,{type:`button`,title:`Forward`,"aria-label":`Forward`,disabled:!e?.canGoForward,onClick:o,children:(0,$.jsx)(_a,{size:15})}),(0,$.jsx)(`button`,{type:`button`,title:e?.loading?`Stop`:`Reload`,"aria-label":e?.loading?`Stop`:`Reload`,disabled:!e,onClick:e?.loading?u:l,children:e?.loading?(0,$.jsx)(Va,{size:13}):(0,$.jsx)(Ba,{size:14})})]}),(0,$.jsx)(`form`,{className:`browser-address-form`,onSubmit:h,children:(0,$.jsx)(`input`,{"aria-label":`Browser address`,disabled:!r&&!t,readOnly:!!t,placeholder:`Search or enter address`,spellCheck:!1,value:d,onChange:e=>f(e.target.value)})}),(0,$.jsxs)(`div`,{className:`browser-panel-actions`,children:[n,(0,$.jsx)(`button`,{type:`button`,title:`Open external`,"aria-label":`Open external`,disabled:!e||!!t,onClick:c,children:(0,$.jsx)(Ma,{size:14})}),(0,$.jsxs)(`div`,{className:`browser-menu-anchor`,children:[(0,$.jsx)(`button`,{type:`button`,title:`Browser actions`,"aria-label":`Browser actions`,onClick:()=>m(e=>!e),children:(0,$.jsx)(Ko,{size:15})}),p&&(0,$.jsx)(`div`,{className:`browser-options-menu`,role:`menu`,children:(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{m(!1),a()},children:`Clear Browser Data...`})})]})]})]})}function Fg({conversationId:e,onOpenBrowser:t}){let n=Ng(e),r=Ga();return(0,$.jsx)(Pg,{activeTab:null,available:n.available,onBack:()=>{},onForward:()=>{},onReload:()=>{},onStop:()=>{},onOpenExternal:()=>{},onClearData:()=>{window.confirm(`Clear shared browser data? Cookies, logins, cache, and site storage will be removed for all chats. This chat's browser tabs will also close.`)&&n.clearData()},onNavigate:e=>{n.open(e,{explicitFile:!0,newTab:!0}).then(e=>{e&&t()}).catch(e=>r?.(e instanceof Error?e.message:`Could not open browser.`,`error`))}})}var Ig=(0,Q.lazy)(()=>o(()=>import(`./FilePagePreview-BRhhz99q.js`),__vite__mapDeps([73,1,2,3,16,20,4,5,6,21,22,13,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,18,42,43,44,45,46,47,48,19,49,50,51,52,53,54,55,56,74])));function Lg({path:e,connection:t,workspaceId:n,sandboxId:r,revision:i}){let a=(0,Q.useRef)(null),[o,s]=(0,Q.useState)(!1),c=bo(e),l=va(e)||n,u=`${ra(t)}:${l}:${r??``}:${e}`,d=ca(t,o&&c&&!r?l:null,e);(0,Q.useEffect)(()=>{let e=a.current;if(!e)return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&(s(!0),t.disconnect())});return t.observe(e),()=>t.disconnect()},[]);let f=S({queryKey:[`file-thumbnail`,u,i],enabled:!(!o||!t||c&&!r||!l&&!r),queryFn:()=>r?xa(t,r,e):Eo.workspaceFile(t,l,e),staleTime:i?1/0:15e3,gcTime:6e4}).data,p=c&&r&&f?.contentEncoding===`base64`&&f.content?`data:image/${/\.jpe?g$/i.test(e)?`jpeg`:e.split(`.`).pop()?.toLowerCase()};base64,${f.content}`:null;return(0,$.jsx)(`span`,{ref:a,className:`workspace-file-thumbnail`,children:d||p?(0,$.jsx)(`img`,{alt:``,src:d||p,loading:`lazy`}):f?.content&&(Do(f)||/\.(?:docx|pdf)$/i.test(f.path))?(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(ts,{size:28}),children:(0,$.jsx)(Ig,{file:f})}):f?.content&&f.contentEncoding!==`base64`?(0,$.jsx)(`pre`,{children:f.content.slice(0,1200)}):(0,$.jsx)(ts,{size:28})})}function Rg({chatMessages:e,connection:t,contextWindowStatus:n,expanded:r,runtimeEvents:i,sessionId:a,showToast:o,onResizeStart:s,onToggleExpanded:c,onUseOutput:l,onHandoffOutput:u,onReviseOutput:d,onAgentPackageInstalled:f}){let[p,m]=(0,Q.useState)(`outputs`),[h,g]=(0,Q.useState)(null),[_,v]=(0,Q.useState)(null),[y,b]=(0,Q.useState)(``),[x,S]=(0,Q.useState)({}),C=(0,Q.useMemo)(()=>Vg(i),[i]),w=(0,Q.useMemo)(()=>Ug(C),[C]),T=(0,Q.useMemo)(()=>zg(e),[e]),E=(0,Q.useMemo)(()=>Bg(e),[e]),D=(0,Q.useMemo)(()=>Gg(e),[e]);(0,Q.useEffect)(()=>()=>{_?.objectUrl&&URL.revokeObjectURL(_.objectUrl)},[_?.objectUrl]);async function O(e){if(!t||!a||e.kind!==`file`)return null;g(Hg(e));try{let n=await Eo.workspaceTool(t,a,{action:`work_output_read`,source:`ui_button`,args:{outputId:e.id,revision:e.revision}});if(!n.ok)throw Error(n.output);let r=Qg(n.data),i=typeof r.contentsBase64==`string`?r.contentsBase64:``;if(!i)throw Error(`The output did not include file data.`);return new File([Yg(i)],e.title,{type:e.contentType})}catch(e){return o(e instanceof Error?e.message:`Could not load the output.`,`error`),null}finally{g(null)}}async function k(e){let t=await O(e);if(!t)return;_?.objectUrl&&URL.revokeObjectURL(_.objectUrl);let n=e.kind===`file`&&(e.contentType.startsWith(`text/`)||e.contentType===`application/json`);b(``),v({output:e,file:t,text:n?await t.text():null,objectUrl:n?null:URL.createObjectURL(t)})}async function A(e){let t=await O(e);t&&(l(t),o(`Added the output to the task as input.`,`success`))}async function j(e,t){let n=t.kind===`file`?await O(t):null;(t.kind!==`file`||n)&&await u(e,t,n)}async function M(e){if(t&&a&&window.confirm(`Delete ${e.title} revision ${e.revision} from this device?`)){g(Hg(e));try{let n=await Eo.workspaceTool(t,a,{action:`work_output_delete`,source:`ui_button`,args:{outputId:e.id,revision:e.revision}});if(!n.ok)throw Error(n.output);_?.output.id===e.id&&v(null),o(`Work output deleted.`,`success`)}catch(e){o(e instanceof Error?e.message:`Could not delete the output.`,`error`)}finally{g(null)}}}async function N(e){if(!t||!a||!window.confirm(`Add ${e.title} version ${e.versionId} to your active Agents profile?`))return;let n=async n=>Eo.workspaceTool(t,a,{action:`work_agent_package_install`,source:`ui_button`,args:{outputId:e.id,revision:e.revision,overwrite:n}});g(Hg(e));try{let t;try{t=await n(!1)}catch(r){if(!(r instanceof Error?r.message:`Agent installation failed.`).includes(`already exists`)||!window.confirm(`${e.agentId} already exists. Replace its active checkout with this immutable version?`))throw r;t=await n(!0)}if(!t.ok)throw Error(t.output);await f?.(),o(`${e.title} was added to Agents. Its package remains available in this Work task.`,`success`)}catch(e){o(e instanceof Error?e.message:`Could not add the Agent package.`,`error`)}finally{g(null)}}return(0,$.jsxs)(`aside`,{className:`workspace-diff-panel work-sidebar-panel ${r?`expanded`:``}`,"aria-label":`Thread details`,children:[r?null:(0,$.jsx)(`div`,{className:`workspace-diff-resize-handle`,role:`separator`,"aria-orientation":`vertical`,"aria-label":`Resize Thread details`,onPointerDown:s}),(0,$.jsxs)(`div`,{className:`workspace-diff-topbar`,children:[(0,$.jsx)(`div`,{className:`workspace-diff-tabs`,role:`tablist`,"aria-label":`Thread details`,children:[[`outputs`,`Outputs`],[`activity`,`Activity`],[`context`,`Context`]].map(([e,t])=>(0,$.jsx)(`button`,{type:`button`,className:`workspace-diff-tab ${p===e?`active`:``}`,role:`tab`,"aria-selected":p===e,onClick:()=>m(e),children:t},e))}),(0,$.jsx)(`div`,{className:`workspace-diff-toolbar-actions`,children:(0,$.jsx)(`button`,{type:`button`,className:`diff-icon-button`,title:r?`Dock sidebar`:`Expand sidebar`,"aria-label":r?`Dock sidebar`:`Expand sidebar`,onClick:c,children:r?(0,$.jsx)(da,{size:14}):(0,$.jsx)(Fa,{size:14})})})]}),(0,$.jsxs)(`div`,{className:`work-sidebar-body`,children:[p===`outputs`?_?(0,$.jsxs)(`div`,{className:`work-output-preview`,children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>{_.objectUrl&&URL.revokeObjectURL(_.objectUrl),v(null)},children:`Outputs`}),(0,$.jsxs)(`strong`,{children:[_.output.title,` · revision `,_.output.revision]})]}),_.text===null?_.output.kind===`file`&&_.output.contentType.startsWith(`image/`)&&_.objectUrl?(0,$.jsx)(`img`,{src:_.objectUrl,alt:_.output.title}):_.output.kind===`file`&&_.output.contentType===`application/pdf`&&_.objectUrl?(0,$.jsx)(`iframe`,{src:_.objectUrl,title:_.output.title}):_.output.kind===`file`&&_.output.contentType.startsWith(`audio/`)&&_.objectUrl?(0,$.jsx)(`audio`,{controls:!0,src:_.objectUrl}):_.output.kind===`file`&&_.output.contentType.startsWith(`video/`)&&_.objectUrl?(0,$.jsx)(`video`,{controls:!0,src:_.objectUrl}):(0,$.jsx)(`p`,{children:`This file type uses its native application for detailed review.`}):(0,$.jsx)(wa,{content:_.text}),(0,$.jsxs)(`section`,{className:`work-output-annotation`,children:[(0,$.jsx)(`label`,{htmlFor:`work-output-revision-note`,children:`Revision note`}),(0,$.jsx)(`textarea`,{id:`work-output-revision-note`,value:y,onChange:e=>b(e.target.value),placeholder:`Describe the exact change to make in the next revision.`}),(0,$.jsx)(`button`,{type:`button`,disabled:!y.trim(),onClick:()=>{d(_.output,_.file,y.trim()),o(`Prepared revision ${_.output.revision+1}.`,`success`)},children:`Revise this version`})]})]}):w.length>0?(0,$.jsx)(`div`,{className:`work-output-list`,children:w.map(e=>{let t=e.revisions.find(t=>t.revision===x[e.id])??e.revisions[0];return(0,$.jsxs)(`article`,{className:`work-output-card`,children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(ts,{size:16}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:t.title}),e.revisions.length>1?(0,$.jsxs)(`label`,{className:`work-output-version`,children:[(0,$.jsx)(`span`,{children:`Version`}),(0,$.jsx)(`select`,{value:t.revision,onChange:t=>S(n=>({...n,[e.id]:Number(t.target.value)})),children:e.revisions.map(e=>(0,$.jsxs)(`option`,{value:e.revision,children:[`Revision `,e.revision]},Hg(e)))})]}):(0,$.jsxs)(`small`,{children:[`Revision `,t.revision]}),(0,$.jsx)(`small`,{children:qg(t)})]})]}),t.validation.length>0?(0,$.jsxs)(`div`,{className:`work-output-validation`,children:[(0,$.jsx)(zo,{size:13}),(0,$.jsxs)(`span`,{children:[t.validation.filter(e=>e.status===`passed`).length,` `,`checks passed`]})]}):null,(0,$.jsxs)(`div`,{className:`work-output-actions`,children:[t.kind===`file`&&t.location.kind===`local`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>void ga(Xg(t)),children:[(0,$.jsx)(Na,{size:13}),`Reveal`]}),(0,$.jsx)(`button`,{type:`button`,onClick:async()=>{let e=await sa(Xg(t),t.title);e.ok?o(`Saved a copy of the Work output.`,`success`):e.canceled||o(`Could not save a copy of the Work output.`,`error`)},children:`Save as`})]}):null,t.kind===`file`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,disabled:h===Hg(t),onClick:()=>void k(t),children:`Preview`}),(0,$.jsxs)(`button`,{type:`button`,disabled:h===Hg(t),onClick:()=>void A(t),children:[(0,$.jsx)(La,{size:13}),`Use as input`]})]}):t.kind===`agent_package`?(0,$.jsx)(`button`,{type:`button`,disabled:h===Hg(t),onClick:()=>void N(t),children:`Add to Agents`}):`url`in t&&t.url?(0,$.jsx)(`button`,{type:`button`,onClick:()=>window.open(t.url,`_blank`,`noopener,noreferrer`),children:`Open`}):null,t.kind===`file`&&t.location.kind===`local`?(0,$.jsxs)(`button`,{type:`button`,className:`danger`,disabled:h===Hg(t),onClick:()=>void M(t),children:[(0,$.jsx)(la,{size:13}),`Delete`]}):null,(0,$.jsx)(`button`,{type:`button`,disabled:h===Hg(t),onClick:()=>void j(`work`,t),children:`Continue in new thread`})]})]},e.id)})}):E.length>0?(0,$.jsx)(`div`,{className:`work-output-list`,children:E.map(e=>(0,$.jsxs)(`article`,{className:`work-output-card`,children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(ts,{size:16}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:e.title}),(0,$.jsx)(`small`,{children:Jg(e.sizeBytes)})]})]}),(0,$.jsx)(`div`,{className:`work-output-actions`,children:(0,$.jsxs)(`button`,{type:`button`,onClick:()=>void ga(e.path),children:[(0,$.jsx)(Na,{size:13}),`Reveal`]})})]},e.path))}):(0,$.jsx)(Kg,{icon:ts,title:`No saved outputs yet`,detail:`Finished files and connected results will appear here.`}):null,p===`activity`?T.length>0?(0,$.jsx)(`div`,{className:`work-activity-list`,children:T.map(e=>(0,$.jsxs)(`details`,{className:`work-activity-row ${e.state??``}`,children:[(0,$.jsxs)(`summary`,{children:[(0,$.jsx)(rs,{size:14}),(0,$.jsx)(`span`,{children:e.label}),(0,$.jsx)(`small`,{children:e.state??`completed`})]}),(0,$.jsx)(`p`,{children:e.content}),e.detail?(0,$.jsx)(`pre`,{children:e.detail}):null]},e.id))}):(0,$.jsx)(Kg,{icon:rs,title:`No activity yet`,detail:`Commands, tool receipts, and checks appear while the thread runs.`}):null,p===`context`?(0,$.jsxs)(`div`,{className:`work-context`,children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h3`,{children:`Model context`}),(0,$.jsx)(`p`,{children:n.summary}),(0,$.jsx)(`small`,{children:n.tokensLabel})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h3`,{children:`Task inputs and sources`}),D.length>0?(0,$.jsx)(`ul`,{children:D.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(La,{size:13}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:e.title}),(0,$.jsx)(`small`,{children:e.detail})]})]},e.key))}):(0,$.jsx)(`p`,{children:`No attached files or cited sources yet.`})]})]}):null]})]})}function zg(e){return e.flatMap(e=>e.activities??[]).filter(e=>e.kind!==`reasoning`).reverse()}function Bg(e){let t=new Map;for(let n of e)for(let e of n.activities??[])for(let n of e.artifacts??[])n.path&&n.sizeBytes!==null&&(t.delete(n.path),t.set(n.path,{path:n.path,title:n.title,sizeBytes:n.sizeBytes}));return[...t.values()].reverse()}function Vg(e){let t=new Map,n=new Set;for(let r of e){let e=Wg(r.data);if(r.action===`work_output_delete`&&r.status===`completed`)for(let r of e){let e=Hg(r);n.add(e),t.delete(e)}else if(r.action!==`work_output_read`)for(let r of e){let e=Hg(r);n.has(e)||t.set(e,r)}}return[...t.values()].sort((e,t)=>t.createdAt.localeCompare(e.createdAt)||t.revision-e.revision)}function Hg(e){return`${e.id}:${e.revision}`}function Ug(e){let t=new Map;for(let n of e){let e=t.get(n.id)??[];e.push(n),t.set(n.id,e)}return[...t.entries()].map(([e,t])=>({id:e,revisions:t.sort((e,t)=>t.revision-e.revision||t.createdAt.localeCompare(e.createdAt))})).sort((e,t)=>t.revisions[0].createdAt.localeCompare(e.revisions[0].createdAt))}function Wg(e,t=[],n=new Set,r=0){if(r>8||e==null)return t;let i=Ye.safeParse(e);if(i.success){let e=`${i.data.id}:${i.data.revision}`;return n.has(e)||(n.add(e),t.push(i.data)),t}if(Array.isArray(e)){for(let i of e)Wg(i,t,n,r+1);return t}if(typeof e==`object`)for(let i of Object.values(e))Wg(i,t,n,r+1);return t}function Gg(e){let t=new Map;for(let n of e){for(let e of n.attachments??[])t.set(`attachment:${e.id}`,{key:`attachment:${e.id}`,title:e.name,detail:`${e.mediaType} · ${Jg(e.sizeBytes)}`});for(let e of n.sources??[])t.set(`source:${e.id}`,{key:`source:${e.id}`,title:e.title,detail:e.sourceName??Zg(e.url)})}return[...t.values()]}function Kg({icon:e,title:t,detail:n}){return(0,$.jsxs)(`div`,{className:`work-sidebar-empty`,children:[(0,$.jsx)(e,{size:22}),(0,$.jsx)(`strong`,{children:t}),(0,$.jsx)(`p`,{children:n})]})}function qg(e){return e.kind===`deployment`?`Deployment`:e.kind===`source_change`?`Source change`:e.kind===`external_resource`?e.provider:e.kind===`agent_package`?`${e.actions.length} action${e.actions.length===1?``:`s`}`:e.location.kind===`local`?Jg(e.sizeBytes):e.location.kind===`managed`?`Managed file`:e.location.provider}function Jg(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1048576).toFixed(1)} MB`}function Yg(e){let t=window.atob(e),n=new ArrayBuffer(t.length),r=new Uint8Array(n);for(let e=0;e<t.length;e+=1)r[e]=t.charCodeAt(e);return n}function Xg(e){return e.kind===`file`&&e.location.kind===`local`?e.location.path:``}function Zg(e){try{return new URL(e).hostname||e}catch{return e}}function Qg(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function $g({messages:e,events:t,actions:n,onOpenFile:r,connection:i,workspaceId:a,sandboxId:o,sessionId:s,conversationId:c,onOpenBrowser:l}){let u=(0,Q.useContext)(gu),d=ra(i),f=t.filter(e=>e.name===`visual.published`||e.name===`workspace_action_result`||e.name===`tool.completed`||e.name===`turn.completed`).at(-1)?.id??``,p=S({queryKey:[`thread-html-visuals`,d,s,f],enabled:!!(i&&s),queryFn:async()=>Co.array().parse((await Y(i,`/v1/sessions/${encodeURIComponent(s)}/visuals`)).visuals),staleTime:15e3,refetchInterval:5e3}),m=(0,Q.useMemo)(()=>{let t=new Map;for(let e of p.data??[])t.set(e.visualId,e);for(let n of e)if(n.visual){let e=t.get(n.visual.visualId);(!e||e.output.revision<n.visual.output.revision)&&t.set(n.visual.visualId,n.visual)}return[...t.values()]},[e,p.data]),h=(0,Q.useMemo)(()=>Vg(t),[t]),g=S({queryKey:[`thread-output-files`,d,s,f],placeholderData:(e,t)=>t?.queryKey[1]===d&&t.queryKey[2]===s?e:void 0,enabled:!!(i&&s),queryFn:async()=>(await Eo.sessionFiles(i,s)).files,staleTime:15e3,refetchOnWindowFocus:!0,refetchInterval:5e3}),_=(0,Q.useMemo)(()=>{if(g.data)return g.data;let t=new Map(Bg(e).map(e=>[`${o??`local`}:${e.path}`,{...e,contentType:`application/octet-stream`,sandboxId:o??null}])),n=new Set;for(let e of h)n.has(e.id)||(n.add(e.id),e.kind===`file`&&e.location.kind===`local`&&t.set(`local:${e.location.path}`,{path:e.location.path,title:e.title,sizeBytes:e.sizeBytes,contentType:e.contentType,sandboxId:null}));return[...t.values()]},[e,h,o,g.data]);return(0,$.jsxs)(`div`,{className:`right-sidebar-new-tab`,children:[(0,$.jsx)(Fg,{conversationId:c,onOpenBrowser:l}),(0,$.jsxs)(`div`,{className:`right-sidebar-overview`,children:[(0,$.jsxs)(`section`,{className:`right-sidebar-overview-files`,"aria-label":`Outputs`,children:[(0,$.jsx)(`h3`,{children:`Outputs`}),_.length||m.length?(0,$.jsxs)($.Fragment,{children:[m.map(e=>(0,$.jsxs)(`div`,{className:`activity-artifact`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`activity-artifact-name`,onClick:()=>u?.(e),"aria-label":`Open ${e.output.title} in browser panel`,children:[(0,$.jsx)(Ta,{size:14,"aria-hidden":!0}),(0,$.jsx)(`strong`,{children:e.output.title})]}),(0,$.jsxs)(`span`,{className:`activity-artifact-actions`,children:[`HTML`,e.output.revision>1?` · Revision ${e.output.revision}`:``]})]},e.publicationId)),_.map(e=>(0,$.jsx)(Du,{artifact:e,onOpenFileInSidebar:t=>r(t,{sandboxId:e.sandboxId,local:!e.sandboxId}),preview:(0,$.jsx)(Lg,{revision:e.revision,path:e.path,connection:i,workspaceId:a,sandboxId:e.sandboxId})},`${e.sandboxId??`local`}:${e.path}`))]}):(0,$.jsx)(`p`,{className:`right-sidebar-output-empty`,children:`Outputs from this chat will appear here.`})]}),(0,$.jsxs)(`section`,{className:`right-sidebar-overview-tools`,"aria-label":`Tools`,children:[(0,$.jsx)(`h3`,{children:`Tools`}),n]})]})]})}function e_({value:e}){let{preservation:t,reload:n}=e;return(0,$.jsxs)(`section`,{"aria-label":`AlphaEdit measured comparisons`,children:[(0,$.jsx)(`h4`,{children:`Measured comparisons`}),(0,$.jsxs)(`p`,{children:[`Measured on reviewed training inputs; held-out quality is unmeasured. Before refers to the`,` `,e.startingState===`parent`?`retained parent patch`:`original base model`,`. Target NLL means are weighted over target tokens across all contexts.`]}),(0,$.jsx)(`div`,{className:`evaluation-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`caption`,{children:`Teacher-forced target NLL on reviewed edits`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:`Edit`}),(0,$.jsx)(`th`,{scope:`col`,children:`Contexts`}),(0,$.jsx)(`th`,{scope:`col`,children:`Target tokens`}),(0,$.jsx)(`th`,{scope:`col`,children:`Before NLL`}),(0,$.jsx)(`th`,{scope:`col`,children:`After NLL`}),(0,$.jsx)(`th`,{scope:`col`,children:`Reloaded NLL`})]})}),(0,$.jsx)(`tbody`,{children:e.edits.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.id}),(0,$.jsx)(`td`,{children:e.contextCount.toLocaleString()}),(0,$.jsx)(`td`,{children:e.targetTokens.toLocaleString()}),(0,$.jsx)(`td`,{children:e.beforeMeanTargetNll}),(0,$.jsx)(`td`,{children:e.afterMeanTargetNll}),(0,$.jsx)(`td`,{children:e.reloadedMeanTargetNll})]},e.id))})]})}),(0,$.jsx)(`div`,{className:`evaluation-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsxs)(`caption`,{children:[`Next-token distribution KL across `,e.vocabularySize.toLocaleString(),` vocabulary entries`]}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:`Comparison`}),(0,$.jsx)(`th`,{scope:`col`,children:`Measured inputs`}),(0,$.jsx)(`th`,{scope:`col`,children:`Mean KL`}),(0,$.jsx)(`th`,{scope:`col`,children:`Maximum KL`})]})}),(0,$.jsxs)(`tbody`,{children:[(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:`Preservation · KL(final edited || starting)`}),(0,$.jsxs)(`td`,{children:[t.examples.toLocaleString(),` reviewed examples ·`,` `,t.comparedPositions.toLocaleString(),` final non-padding positions`]}),(0,$.jsx)(`td`,{children:t.meanNextTokenKl}),(0,$.jsx)(`td`,{children:t.maximumNextTokenKl})]}),(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:`Reload · KL(reloaded patch || final edited)`}),(0,$.jsxs)(`td`,{children:[n.comparedTargetTokens.toLocaleString(),` target tokens ·`,` `,n.comparedPreservationPositions.toLocaleString(),` preservation positions`]}),(0,$.jsx)(`td`,{children:n.meanNextTokenKl}),(0,$.jsx)(`td`,{children:n.maximumNextTokenKl})]})]})]})}),(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Reload reference`}),(0,$.jsx)(`dd`,{children:`Final edited model`}),(0,$.jsx)(`dt`,{children:`Reload equivalence`}),(0,$.jsx)(`dd`,{children:n.equivalent?`Equivalent under recorded checks`:`Not equivalent under recorded checks`}),(0,$.jsx)(`dt`,{children:`Absolute tolerance`}),(0,$.jsx)(`dd`,{children:n.absoluteTolerance}),(0,$.jsx)(`dt`,{children:`Maximum absolute per-token target NLL difference`}),(0,$.jsx)(`dd`,{children:n.maximumAbsoluteTargetNllDifference}),(0,$.jsx)(`dt`,{children:`Maximum absolute log-probability difference`}),(0,$.jsx)(`dd`,{children:n.maximumAbsoluteLogProbabilityDifference})]})]})}function t_({result:e}){let t=e.schemaVersion===`openpond.alphaEditTrainingResult.v1`;return(0,$.jsxs)(ft,{title:t?`AlphaEdit result`:`Neuron training result`,children:[(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Duration`}),(0,$.jsxs)(`dd`,{children:[(e.durationMs/1e3).toLocaleString(),` seconds`]}),(0,$.jsx)(`dt`,{children:`Forward token work`}),(0,$.jsx)(`dd`,{children:e.forwardTokenWork.toLocaleString()}),e.schemaVersion===`openpond.alphaEditTrainingResult.v1`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Edits processed`}),(0,$.jsx)(`dd`,{children:e.editsProcessed}),(0,$.jsx)(`dt`,{children:`Latent optimizer steps`}),(0,$.jsx)(`dd`,{children:e.latentOptimizerSteps}),(0,$.jsx)(`dt`,{children:`Untouched weights before`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.untouchedWeightsHashBefore}),(0,$.jsx)(`dt`,{children:`Untouched weights after`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.untouchedWeightsHashAfter}),(0,$.jsx)(`dt`,{children:`Edited weights before`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.editedWeightsHashBefore}),(0,$.jsx)(`dt`,{children:`Edited weights after`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.editedWeightsHashAfter})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Selection`}),(0,$.jsxs)(`dd`,{children:[e.selection.source,` · `,e.selection.entries.length,` of`,` `,e.selection.eligibleCount.toLocaleString(),` eligible neurons`]}),(0,$.jsx)(`dt`,{children:`Optimizer steps`}),(0,$.jsx)(`dd`,{children:e.optimizerSteps}),(0,$.jsx)(`dt`,{children:`Examples processed`}),(0,$.jsx)(`dd`,{children:e.examplesProcessed}),(0,$.jsx)(`dt`,{children:`Trainable parameters`}),(0,$.jsx)(`dd`,{children:e.trainableParameterCount.toLocaleString()}),(0,$.jsx)(`dt`,{children:`Mean loss`}),(0,$.jsx)(`dd`,{children:e.meanLoss}),(0,$.jsx)(`dt`,{children:`Final loss`}),(0,$.jsx)(`dd`,{children:e.finalLoss}),(0,$.jsx)(`dt`,{children:`Mean preservation KL`}),(0,$.jsx)(`dd`,{children:e.meanPreservationKl??`Preservation disabled`}),(0,$.jsx)(`dt`,{children:`Base weights before`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.baseWeightsHashBefore}),(0,$.jsx)(`dt`,{children:`Base weights after`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.baseWeightsHashAfter})]})]}),e.schemaVersion===`openpond.alphaEditTrainingResult.v1`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(e_,{value:e.comparisons}),(0,$.jsx)(`div`,{className:`evaluation-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`caption`,{children:`Latent target optimization objective`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Edit`}),(0,$.jsx)(`th`,{children:`Initial loss`}),(0,$.jsx)(`th`,{children:`Final loss`}),(0,$.jsx)(`th`,{children:`Optimizer steps`})]})}),(0,$.jsx)(`tbody`,{children:e.targetLosses.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.id}),(0,$.jsx)(`td`,{children:e.initial}),(0,$.jsx)(`td`,{children:e.final}),(0,$.jsx)(`td`,{children:e.optimizerSteps})]},e.id))})]})}),(0,$.jsx)(`div`,{className:`evaluation-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`caption`,{children:`Layer evidence`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Layer`}),(0,$.jsx)(`th`,{children:`Preservation tokens`}),(0,$.jsx)(`th`,{children:`Nullspace rank`}),(0,$.jsx)(`th`,{children:`Update norm`}),(0,$.jsx)(`th`,{children:`Solve residual`}),(0,$.jsx)(`th`,{children:`Sequential keys`})]})}),(0,$.jsx)(`tbody`,{children:e.layerEvidence.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.layer}),(0,$.jsx)(`td`,{children:e.preservationTokens}),(0,$.jsx)(`td`,{children:e.nullspaceRank}),(0,$.jsx)(`td`,{children:e.updateFrobeniusNorm}),(0,$.jsx)(`td`,{children:e.solveRelativeResidual}),(0,$.jsx)(`td`,{children:e.sequentialKeyCount})]},e.layer))})]})})]}):(0,$.jsx)(`div`,{className:`evaluation-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`caption`,{children:`Selected neurons`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Layer`}),(0,$.jsx)(`th`,{children:`Neuron`}),(0,$.jsx)(`th`,{children:`Target activity`}),(0,$.jsx)(`th`,{children:`Background activity`}),(0,$.jsx)(`th`,{children:`Ratio`}),(0,$.jsx)(`th`,{children:`Gradient norm`}),(0,$.jsx)(`th`,{children:`Score`})]})}),(0,$.jsx)(`tbody`,{children:e.selection.entries.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.layer}),(0,$.jsx)(`td`,{children:e.neuron}),(0,$.jsx)(`td`,{children:e.targetMeanAbsolute}),(0,$.jsx)(`td`,{children:e.backgroundMeanAbsolute}),(0,$.jsx)(`td`,{children:e.backgroundTargetRatio}),(0,$.jsx)(`td`,{children:e.gradientNorm}),(0,$.jsx)(`td`,{children:e.score})]},`${e.layer}:${e.neuron}`))})]})}),(0,$.jsx)(`div`,{className:`evaluation-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`caption`,{children:`Committed output files`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`File`}),(0,$.jsx)(`th`,{children:`Bytes`}),(0,$.jsx)(`th`,{children:`SHA-256`})]})}),(0,$.jsx)(`tbody`,{children:e.artifact.files.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.path}),(0,$.jsx)(`td`,{children:e.sizeBytes.toLocaleString()}),(0,$.jsx)(`td`,{className:`saved-model-version-reference`,children:e.sha256})]},e.path))})]})}),(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Artifact`}),(0,$.jsx)(`dd`,{children:e.artifact.id}),(0,$.jsx)(`dt`,{children:`Artifact hash`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.artifact.contentHash}),(0,$.jsx)(`dt`,{children:`Result hash`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.contentHash})]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Complete retained evidence`}),(0,$.jsx)(`pre`,{className:`saved-model-version-reference`,children:JSON.stringify(e,null,2)})]})]})}function n_({input:e,id:t}){let n=typeof e.prompt==`string`?e.prompt:typeof e.request==`string`?e.request:null,r=Object.fromEntries(Object.entries(e).filter(([e])=>e!==`prompt`&&e!==`request`)),i=Object.keys(r).length>0;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{tabIndex:0,"aria-label":`Input for ${t}`,children:i?JSON.stringify(r,null,2):n??JSON.stringify(e,null,2)}),i&&n?(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Full prompt`}),(0,$.jsx)(`pre`,{children:n})]}):null]})}function r_({connection:e,dataset:t}){let[n,r]=(0,Q.useState)(0),i=S({queryKey:[`training-dataset-rows`,ra(e),cf(t),t.revision],staleTime:6e4,queryFn:async({signal:n})=>{let r=await ko(e,`dataset`,{action:`read`,id:t.id,expectedRevision:t.revision},n);if(cf(r.summary)!==cf(t)||r.summary.revision!==t.revision)throw Error(`Dataset rows do not match the selected revision.`);return r}}),a=i.data?.record.workspace.draft.tasks??[],o=Math.max(1,Math.ceil(a.length/5)),s=Math.min(n,o-1);return(0,$.jsxs)(`section`,{className:`dataset-row-preview`,"aria-label":`Examples from ${t.name}, revision ${t.revision}`,children:[(0,$.jsx)(X,{error:i.error?.message,children:i.error?(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void i.refetch(),children:`Retry rows`}):null}),(0,$.jsx)(`div`,{className:`training-table-wrap`,children:(0,$.jsxs)(`table`,{className:`training-data-table evaluation-workspace-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Example`}),(0,$.jsx)(`th`,{children:`Input`}),(0,$.jsx)(`th`,{children:`Split`})]})}),(0,$.jsx)(`tbody`,{children:a.slice(s*5,s*5+5).map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.id}),(0,$.jsxs)(`td`,{children:[(0,$.jsx)(n_,{input:e.input,id:e.id}),e.expectedOutput?(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Expected output`}),(0,$.jsx)(`pre`,{children:JSON.stringify(e.expectedOutput,null,2)})]}):null]}),(0,$.jsx)(`td`,{children:e.split})]},e.id))})]})}),i.isPending?(0,$.jsx)(`p`,{role:`status`,children:`Loading examples…`}):!a.length&&!i.error?(0,$.jsx)(`p`,{children:`No saved examples.`}):null,o>1?(0,$.jsxs)(`div`,{className:`training-rollout-pagination`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:!s,onClick:()=>r(s-1),children:`Previous`}),(0,$.jsxs)(`span`,{children:[s*5+1,`–`,Math.min(a.length,(s+1)*5),` of `,a.length]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:s+1===o,onClick:()=>r(s+1),children:`Next`})]}):null]})}function i_({title:e,children:t,open:n=!1,onOpenChange:r}){return(0,$.jsxs)(`details`,{className:`training-workspace-section`,open:n,onToggle:e=>r?.(e.currentTarget.open),children:[(0,$.jsx)(`summary`,{children:e}),(0,$.jsx)(`div`,{className:`training-workspace-section-content`,children:t})]})}function a_({dataset:e,graders:t,model:n,connection:r}){let[i,a]=(0,Q.useState)(!1),o=n?[{role:`Training`,dataset:n.trainingDataset},{role:`Evaluation`,dataset:n.evaluationDataset}].filter(e=>e.dataset):[];return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(i_,{title:`Dataset`,open:i,onOpenChange:a,children:[(0,$.jsx)(`div`,{className:`training-table-wrap`,children:(0,$.jsxs)(`table`,{className:`training-data-table evaluation-workspace-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[n?(0,$.jsx)(`th`,{children:`Use`}):null,(0,$.jsx)(`th`,{children:`Dataset`}),(0,$.jsx)(`th`,{children:`Revision`}),n?null:(0,$.jsx)(`th`,{children:`Examples`})]})}),(0,$.jsx)(`tbody`,{children:n?o.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.role}),(0,$.jsx)(`td`,{children:e.dataset.name}),(0,$.jsx)(`td`,{children:e.dataset.revision})]},e.role)):e?(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.name}),(0,$.jsx)(`td`,{children:e.revision}),(0,$.jsx)(`td`,{children:e.taskCount??`—`})]}):null})]})}),i&&e&&r&&!n?(0,$.jsx)(r_,{connection:r,dataset:e},`${e.id}:${e.revision}`):null,n?(0,$.jsx)(`p`,{className:`chat-context-note`,children:`Model configuration. Each training run retains its own input snapshot.`}):null,!e&&!o.length?(0,$.jsx)(`p`,{children:`No dataset configured.`}):null]}),(0,$.jsx)(i_,{title:`Graders`,children:t.length?(0,$.jsx)(`div`,{className:`training-table-wrap`,children:(0,$.jsxs)(`table`,{className:`training-data-table evaluation-workspace-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Grader`}),(0,$.jsx)(`th`,{children:`Type`}),(0,$.jsx)(`th`,{children:`Checks`})]})}),(0,$.jsx)(`tbody`,{children:t.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.name}),(0,$.jsx)(`td`,{children:e.graderType??`—`}),(0,$.jsx)(`td`,{children:e.checkState??e.state})]},e.id))})]})}):(0,$.jsx)(`p`,{children:n?`Inspect the model’s training dataset for its grader definitions.`:`No graders configured for this dataset revision.`})})]})}var o_=(0,Q.createContext)(null);function s_({targets:e}){let t=(0,Q.useContext)(o_);return t&&e?.length?(0,$.jsx)(c_,{...t,targets:e}):null}function c_({connection:e,teamId:t,jobId:n,targets:r}){let[i,a]=(0,Q.useState)(()=>JSON.stringify(r[0])),o=r.find(e=>JSON.stringify(e)===i)??r[0],s=S({queryKey:[`retained-run-feedback`,ra(e),t,n,o.kind,o.id,o.taskId??null],queryFn:async({signal:r})=>{let i=new URLSearchParams({teamId:t,kind:o.kind,id:o.id,...o.taskId?{taskId:o.taskId}:{}}),a=Zr.parse(await Y(e,`/v1/training/hosted-jobs/${encodeURIComponent(n)}/feedback?${i}`,{signal:r}));if(a.jobId!==n||a.id!==o.id||a.kind!==o.kind||a.taskId!==o.taskId)throw Error(`Grader feedback belongs to another run or attempt.`);return a},staleTime:1/0,gcTime:3e5,retry:!1});return(0,$.jsxs)(`section`,{className:`retained-run-feedback`,children:[(0,$.jsx)(`h3`,{children:`Retained grader feedback`}),r.length>1?(0,$.jsx)(Z,{label:`Feedback record`,value:JSON.stringify(o),options:r.map(e=>({value:JSON.stringify(e),label:e.kind===`trajectory`?`Trajectory ${e.id.slice(0,6)}…`:`Task ${e.taskId?.slice(0,6)}… · evaluation ${e.id.slice(0,6)}…`})),onChange:a}):null,(0,$.jsx)(X,{error:s.error}),s.isPending?(0,$.jsx)(`p`,{role:`status`,children:`Loading verified grader receipt…`}):null,s.isError?(0,$.jsx)(`button`,{className:`training-button secondary`,type:`button`,onClick:()=>void s.refetch(),children:`Retry grader feedback`}):null,s.data?(0,$.jsx)(u_,{value:s.data}):null]})}var l_=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:{};function u_({value:e}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[`Training reward: `,e.training.status,` · score `,e.training.score??`not retained`]}),(0,$.jsxs)(`p`,{children:[`Evaluation graders: `,e.evaluation.status,` · score `,e.evaluation.score??`not retained`,` · recorded aggregate acceptance `,e.evaluation.passed===null?`not retained`:String(e.evaluation.passed)]}),(0,$.jsxs)(`p`,{className:`training-muted`,children:[`Verified composition `,e.compositionSha256.slice(0,12),`…`]}),e.graders.length?null:(0,$.jsx)(`p`,{className:`training-muted`,children:`No grader records retained in this receipt; quality is not established.`}),e.graders.map(e=>(0,$.jsxs)(`article`,{children:[(0,$.jsxs)(`h4`,{children:[e.graderId,` · `,e.role]}),(0,$.jsxs)(`p`,{children:[e.status,` · raw score `,e.rawScore??`not retained`,` · normalized score `,e.normalizedScore??`not retained`,` · grader verdict `,e.passed===!0?`Passed`:e.passed===!1?`Failed`:`No verdict retained`]}),e.message?(0,$.jsx)(`p`,{children:e.message}):null,e.failureClass?(0,$.jsxs)(`p`,{children:[`Recorded failure: `,e.failureClass]}):null,e.feedback.map((e,t)=>(0,$.jsx)(d_,{text:e},t)),e.feedback.length?null:(0,$.jsx)(`p`,{className:`training-muted`,children:`No feedback text retained by this grader.`})]},`${e.role}:${e.graderId}`))]})}function d_({text:e}){let t={};try{t=l_(JSON.parse(e))}catch{}let n=l_(t.diagnostics).differences;return Array.isArray(n)?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dl`,{children:n.slice(0,80).map((e,t)=>{let n=l_(e);return(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`dt`,{children:[typeof n.kind==`string`?n.kind.replaceAll(`_`,` `):`Retained difference`,` · `,typeof n.path==`string`?n.path:`Path not retained`]}),(0,$.jsx)(`dd`,{children:(0,$.jsxs)(`pre`,{children:[`Expected: `,JSON.stringify(n.expected)??`Not retained`,`
10
+ `),v())},onInput:e=>{e.nativeEvent.isComposing||_()},onCompositionEnd:_,onKeyDown:e=>{i(e)},onKeyUp:y,onMouseUp:y,onPaste:e=>{e.preventDefault();let t=Array.from(e.clipboardData.files);if(t.length>0&&a){a(t);return}let n=e.clipboardData.getData(`text/plain`);n&&(o?.(n)||(Qp(n),v()))}})});function fm(e){e.saving||(e.prompt.trim()?e.attachmentsCount>0?e.showInfo(`Task drafts currently save instructions only. Remove attachments before saving.`):e.hasSelectedInvocation?e.showInfo(`Finish or remove the selected command before saving this task draft.`):(e.setSaving(!0),e.onSave(e.prompt).then(t=>{t&&e.onSaved()}).finally(()=>e.setSaving(!1))):e.showInfo(`Add task instructions before saving a draft.`))}function pm(e,t,n,r,i,a,o){return e===`Enter`&&(t||n)&&!r&&i===`work`&&a===`chat`&&o}function mm(e){return e.surface===`team`?`Message team`:e.mode===`start`?e.experience===`chat`?`Ask anything`:`What should we work on? Ctrl Enter to save as draft`:`Ask for follow-up changes`}function hm(e){let t=e.implementation?.type;return t===`openpond-agent`||t===`local-profile-agent`||t===`openpond-profile-action`&&(e.sourceActionId===`chat`||e.id===`chat`||e.id.endsWith(`.chat`))}function gm(e){return e.kind===`command`?`command:${e.command.id}`:e.kind===`app-context`?`app-context:${e.app.id}`:e.kind===`skill`?`skill:${e.skill.name}`:`action:${e.action.id}`}function _m(e){return e.kind===`command`?`${e.command.command} ${e.command.label}`:e.kind===`app-context`?e.app.name:e.kind===`skill`?gf(e.skill):Ni(e.action)}function vm(e){return e.kind===`command`?Ki(e.command):e.kind===`app-context`?`Planning context${e.app.description?`: ${e.app.description}`:e.app.gitRepo?`: ${e.app.gitRepo}`:``}`:e.kind===`skill`?e.skill.description||e.skill.path:e.action.description||Ri(e.action)}function ym(e){return e.kind===`app`?`app:${e.app.id}`:e.kind===`connected-app`?`connected-app:${e.app.provider}`:e.kind===`team-member`?`team-member:${e.member.userId}`:e.kind===`skill`?`skill:${e.skill.name}`:`action:${e.action.id}`}function bm(e){return e.kind===`app`?e.app.name:e.kind===`connected-app`?e.app.label:e.kind===`team-member`?e.member.name:e.kind===`skill`?gf(e.skill):Wi(e.action)}function xm(e){if(e.kind===`action`)return Li(e.action);if(e.kind===`connected-app`)return e.app.detail;if(e.kind===`team-member`)return e.member.handle?`@${e.member.handle}`:`Team member`;if(e.kind===`skill`)return e.skill.description||e.skill.path;let t=e.app.sandboxActionRegistry?.actions.map(e=>e.name)??[];return t.length>0?`Actions: ${t.slice(0,4).join(`, `)}${t.length>4?` +${t.length-4}`:``}`:e.app.sandboxManifestError?`Manifest registry unavailable`:e.app.description||e.app.gitRepo||e.app.id}function Sm(e){return e.kind===`files`?`files`:e.kind===`folder`?`folder`:e.kind===`slash`?`slash:${gm(e.item)}`:`mention:${ym(e.item)}`}function Cm(e){return e.kind===`files`?`Files and folders`:e.kind===`folder`?`Local folder`:e.kind===`slash`?_m(e.item):bm(e.item)}function wm(e){return e.kind===`files`?`Attach images, documents, or other files`:e.kind===`folder`?`Share a bounded folder as Work input`:e.kind===`slash`?vm(e.item):xm(e.item)}function Tm(e,t){let n=t.toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return!0;let r=`${Cm(e)} ${wm(e)}`.toLowerCase();return n.every(e=>r.includes(e))}function Em(e,t){let n=t.trimStart(),r=n.startsWith(`/`)?`slash`:n.startsWith(`@`)?`mentions`:null,i=r?n.slice(1).trimStart():n,a=r?e.filter(e=>e.id===r||e.queryScope===r||e.queryScopes?.includes(r)):e;if(!i)return a;let o=a.map(e=>({...e,items:e.items.filter(e=>Tm(e,i))})).filter(e=>e.items.length>0);return o.length>0?o:[{...(r?a[0]:null)??{id:`results`,label:`Results`},emptyLabel:r===`slash`?`No slash commands match`:r===`mentions`?`No mentions match`:`No commands match`,items:[]}]}function Dm(e){if(e.kind===`files`||e.kind===`folder`)return(0,$.jsx)(La,{size:14});if(e.kind===`slash`){let t=e.item;return t.kind===`command`?t.command.id===`agent`?(0,$.jsx)(Da,{size:14}):t.command.id===`skill`?(0,$.jsx)(Po,{size:14}):(0,$.jsx)(ha,{size:14}):t.kind===`app-context`?(0,$.jsx)($l,{size:14}):t.kind===`skill`?(0,$.jsx)(ts,{size:14}):hm(t.action)?(0,$.jsx)(Da,{size:14}):(0,$.jsx)(ha,{size:14})}let t=e.item;return t.kind===`connected-app`?(0,$.jsx)(`img`,{alt:``,className:`composer-provider-mention-icon`,draggable:!1,src:r(t.app.provider)}):t.kind===`action`?hm(t.action)?(0,$.jsx)(Da,{size:14}):(0,$.jsx)(ha,{size:14}):t.kind===`skill`?(0,$.jsx)(ts,{size:14}):(0,$.jsx)($l,{size:14})}function Om(e){if(e.kind===`slash`&&e.item.kind===`app-context`||e.kind===`mention`&&e.item.kind===`app`)return e.item.app.id}function km({ariaLabel:e,className:t=``,id:n,menuIndex:r,menuRef:i,onSelect:a,onSelectIndex:o,sections:s,style:c,variant:l}){let u=(0,Q.useRef)(null),d=s.reduce((e,t)=>e+t.items.length,0);(0,Q.useEffect)(()=>{if(l===`add`&&r===0){let e=u.current?.closest(`.composer-command-menu`);e&&(e.scrollTop=0)}else u.current?.scrollIntoView({block:`nearest`})},[d,r,l]);let f=0;return(0,$.jsx)(`div`,{ref:i,id:n,className:`composer-project-menu composer-slash-menu ${t} composer-command-menu composer-command-menu-${l}`.trim(),role:l===`add`?`menu`:`listbox`,"aria-label":e,style:c,children:s.map(e=>{let t=f;return f+=e.items.length,(0,$.jsxs)(`div`,{className:`composer-command-section ${e.grid?`composer-command-section-grid`:``}`.trim(),role:`group`,"aria-label":e.label,children:[(0,$.jsx)(`div`,{className:`composer-command-section-title`,children:e.label}),e.items.length>0?e.items.map((e,n)=>{let i=t+n,s=i===r;return(0,$.jsxs)(`button`,{type:`button`,role:l===`add`?`menuitem`:`option`,ref:s?u:void 0,"aria-selected":l===`typed`?s:void 0,className:`composer-project-option ${s?`selected`:``} composer-command-option`,"data-app-context-id":Om(e),onFocus:()=>o(i),onMouseEnter:()=>o(i),onMouseDown:e=>{e.preventDefault()},onClick:()=>a(e),children:[Dm(e),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:Cm(e)}),(0,$.jsx)(`small`,{children:wm(e)})]}),l===`typed`&&s?(0,$.jsx)(Ro,{size:14}):(0,$.jsx)(`span`,{"aria-hidden":`true`})]},Sm(e))}):(0,$.jsx)(`div`,{className:`composer-menu-empty`,children:e.emptyLabel??`No items available`})]},e.id)})})}function Am({mentionIndex:e,items:t,onSelect:n,onSelectIndex:r,style:i}){return(0,$.jsx)(km,{ariaLabel:`Mentions`,className:`composer-mention-menu`,menuIndex:e,sections:[{emptyLabel:`No matching mentions`,id:`mentions`,items:t.map(e=>({kind:`mention`,item:e})),label:`@`}],style:i,variant:`typed`,onSelect:e=>{e.kind===`mention`&&n(e.item)},onSelectIndex:r})}function jm({running:e,sendDisabled:t,hasComposerInput:n,sendTooltip:r,stopIcon:i,stopLabel:a,voiceInputActive:o,onSend:s,onStop:c}){let l=e&&!n&&!o,u=l?a:r;return(0,$.jsx)(`button`,{type:`button`,className:`send-button ${l?`stop-button`:``}`.trim(),disabled:!l&&t&&!o,"data-tooltip":u,"aria-label":u,onClick:l?()=>void c():s,children:l?i===`pause`?(0,$.jsx)(ua,{size:15}):(0,$.jsx)(Va,{size:13,fill:`currentColor`}):(0,$.jsx)(Ql,{size:18})})}var Mm=new WeakMap,Nm=new WeakMap,Pm=3e4;function Fm(e,t){return JSON.stringify([e,t?.binaryPath??null,t?.sourceHome??null,t?.enabled??!0,t?.acp??null])}function Im(e,t,n){return Nm.get(e)?.get(Fm(t,n))?.value??null}function Lm(e,t,n,r){let i=Nm.get(e);i||(i=new Map,Nm.set(e,i)),i.set(Fm(t,r),{value:n,refreshedAt:Date.now()})}function Rm(e,t,n){let r=Fm(t,n),i=Nm.get(e)?.get(r);if(i&&Date.now()-i.refreshedAt<Pm)return{promise:Promise.resolve(i.value),release(){}};let a=Mm.get(e);a||(a=new Map,Mm.set(e,a));let o=a.get(r);if(!o){let i=new AbortController;o={controller:i,readers:0,promise:Y(e,`/v1/providers/${t}/native-setup`,{method:`POST`,body:JSON.stringify({action:`capabilities`}),signal:i.signal})},a.set(r,o);let s=o,c=()=>{a.get(r)===s&&a.delete(r)};o.promise.then(o=>{a.get(r)===s&&!i.signal.aborted&&!o.error&&o.session&&Lm(e,t,o,n),c()},c)}o.readers++;let s=o,c=!1;return{promise:s.promise,release(){c||(c=!0,s.readers--,s.readers===0&&a.get(r)===s&&(a.delete(r),s.controller.abort()))}}}function zm({connection:e,provider:t,providerSettings:n,disabled:r,placement:i=`top`,onSettings:a,onSetup:o}){let s=n?.providers[t],[c,l]=(0,Q.useState)(null),u=Fm(t,s),d=e?Im(e,t,s):null,f=c?.connection===e&&c.provider===t&&c.instance===u?c.value:d,[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(!1),{recovery:_}=Fo(e),v=p??f?.error;Ka(v);let y=oe(t)||[`opencode`,`grok-build`,`claude-code`].includes(t);if((0,Q.useEffect)(()=>{if(m(null),!e||!y)return;let n=Rm(e,t,s),r=!0;return n.promise.then(n=>{r&&(n.error?m(n.error):(l({connection:e,provider:t,instance:u,value:n}),a({provider:t,settings:n.settings})))}).catch(e=>{r&&m(e.message)}),()=>{r=!1,n.release()}},[e,t,y,a,u,_]),!y||!e)return null;let b=s?.nativeMode??f?.session?.modes?.currentModeId??``;async function x(n){if(e){g(!0);try{let r=await Y(e,`/v1/providers`,{method:`PATCH`,body:JSON.stringify({providers:{[t]:n}})});if(f){let n={...f,settings:r};Lm(e,t,n,s),l({connection:e,provider:t,instance:u,value:n})}a({provider:t,settings:r}),m(null)}catch(e){m(e instanceof Error?e.message:`Could not save agent settings.`)}finally{g(!1)}}}return(0,$.jsxs)($.Fragment,{children:[s&&!s.enabled?(0,$.jsx)(`button`,{type:`button`,disabled:r||h,onClick:()=>void x({enabled:!0}),children:`Enable agent`}):null,f?.session?.modes?(0,$.jsx)(Z,{compact:!0,className:`permission-select`,icon:(0,$.jsx)(go,{size:14}),placement:i,label:t===`claude-code`?`Claude permissions`:`Agent mode`,disabled:r||h,value:t===`claude-code`&&b==="default"?`manual`:b,options:f.session.modes.availableModes.map(e=>({value:e.id,label:t===`claude-code`&&e.id===`manual`?`Ask`:e.name,...t===`claude-code`?{description:e.id===`plan`?`Inspect and plan before making changes.`:e.id===`bypassPermissions`?`Run tools and commands without permission prompts.`:`Ask before actions that require permission.`}:{}})),onChange:e=>void x({nativeMode:e})}):null,f?.session?.configOptions?.filter(e=>e.type===`select`&&e.category!==`model`&&e.category!==`mode`).map(e=>(0,$.jsxs)(`label`,{className:`composer-native-option`,children:[(0,$.jsx)(`span`,{children:e.name}),(0,$.jsx)(`select`,{title:`Default ${e.name.toLowerCase()} for this agent installation`,disabled:r||h,value:s?.nativeOptions?.[e.id]??e.currentValue,onChange:t=>void x({nativeOptions:{...s?.nativeOptions,[e.id]:t.target.value}}),children:e.options?.flatMap(e=>`options`in e?e.options:[e]).map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.name},e.value))})]},e.id)),v?(0,$.jsxs)(`span`,{role:`status`,title:`Open agent setup`,children:[`Agent needs attention`,o?(0,$.jsx)(`button`,{type:`button`,onClick:o,children:`Open setup`}):null]}):null]})}function Bm(){return!!(navigator.mediaDevices&&typeof AudioContext<`u`)}async function Vm(e={}){if(!Bm())throw Error(`Voice recording is not available in this browser.`);let t=await navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,channelCount:1,echoCancellation:!0,noiseSuppression:!0}}),n=new AudioContext,r=n.createMediaStreamSource(t),i=n.createScriptProcessor(4096,1,1),a=n.createGain();a.gain.value=0;let o={audioContext:n,chunks:[],processor:i,silentGain:a,source:r,stream:t,startedAt:performance.now(),stopped:!1,onAudioLevel:e.onAudioLevel};return i.onaudioprocess=e=>{if(o.stopped)return;let t=e.inputBuffer.getChannelData(0);o.chunks.push(new Float32Array(t)),o.onAudioLevel?.(Hm(t))},r.connect(i),i.connect(a),a.connect(n.destination),{stop:()=>Um(o,!0),cancel:()=>Um(o,!1).then(()=>void 0)}}function Hm(e){if(e.length===0)return 0;let t=0;for(let n of e)t+=n*n;let n=Math.sqrt(t/e.length);return Math.min(1,(n*5)**.6)}async function Um(e,t){if(e.stopped)return{blob:new Blob([],{type:`audio/wav`}),durationMs:0,sampleRate:e.audioContext.sampleRate};e.stopped=!0,e.processor.disconnect(),e.silentGain.disconnect(),e.source.disconnect();for(let t of e.stream.getTracks())t.stop();await e.audioContext.close().catch(()=>void 0);let n=Math.max(0,performance.now()-e.startedAt);if(!t)return{blob:new Blob([],{type:`audio/wav`}),durationMs:n,sampleRate:e.audioContext.sampleRate};let r=Wm(e.chunks);if(r.length===0)throw Error(`No microphone audio was captured.`);return{blob:Gm(r,e.audioContext.sampleRate),durationMs:n,sampleRate:e.audioContext.sampleRate}}function Wm(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Float32Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function Gm(e,t){let n=e.length*2,r=new ArrayBuffer(44+n),i=new DataView(r);Km(i,0,`RIFF`),i.setUint32(4,36+n,!0),Km(i,8,`WAVE`),Km(i,12,`fmt `),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*1*2,!0),i.setUint16(32,2,!0),i.setUint16(34,16,!0),Km(i,36,`data`),i.setUint32(40,n,!0);let a=44;for(let t of e){let e=Math.max(-1,Math.min(1,t));i.setInt16(a,e<0?e*32768:e*32767,!0),a+=2}return new Blob([r],{type:`audio/wav`})}function Km(e,t,n){for(let r=0;r<n.length;r+=1)e.setUint8(t+r,n.charCodeAt(r))}var qm=96,Jm=Array.from({length:qm},()=>0);function Ym(){return[...Jm]}function Xm(e,t){return[...e.slice(-95),Math.max(0,Math.min(1,t))]}function Zm({levels:e}){let t=(0,Q.useMemo)(()=>e.length>=qm?e.slice(-96):[...Jm.slice(e.length),...e],[e]);return(0,$.jsx)(`span`,{className:`voice-recording-waveform`,role:`img`,"aria-label":`Live microphone level`,children:t.map((e,t)=>(0,$.jsx)(`span`,{className:`voice-recording-bar`,style:{"--voice-level":e},"aria-hidden":`true`},t))})}var Qm=12e4,$m=`openpond.voice.setupNoticeAcknowledged`,eh=`Voice dictation runs locally with whisper.cpp. OpenPond uses a local whisper-cli binary and downloads the voice model on first use.`;function th({connection:e,buttonClassName:t,wrapperClassName:n=``,disabled:r=!1,iconSize:i=16,language:a=`en`,onActiveChange:o,showToast:s,onTranscript:c,transcriptionChannelKey:l,submitLabel:u=`Send`}){let d=(0,Q.useRef)(null),f=(0,Q.useRef)(null),p=(0,Q.useRef)(e),m=(0,Q.useRef)(r),h=(0,Q.useRef)(`idle`),g=(0,Q.useRef)(!1),_=(0,Q.useRef)(ih());de(()=>{_.current=ih()}),p.current=e,m.current=r;let[v,y]=(0,Q.useState)(`idle`),b=(0,Q.useRef)(!1),[x,S]=(0,Q.useState)(Ym),C=(0,Q.useCallback)(e=>Of(l,e),[l]),w=(0,Q.useCallback)(()=>Ef(l),[l]),T=(0,Q.useSyncExternalStore)(C,w,w),E=(0,Q.useCallback)(()=>Df(l),[l]),D=(0,Q.useSyncExternalStore)(C,E,E)?`Transcribing · ${u.toLowerCase()} when ready`:`Transcribing`,O=T,k=v===`starting`,A=v===`recording`,j=A||T,M=k||j;h.current=v;let N=(0,Q.useCallback)(()=>{f.current!==null&&(window.clearTimeout(f.current),f.current=null)},[]),P=(0,Q.useCallback)(async()=>{N();let e=d.current;d.current=null,g.current=!1,y(`idle`),S(Ym()),e&&await e.cancel().catch(()=>void 0)},[N]),F=(0,Q.useCallback)(async(e,t,n)=>{let r=p.current;if(!r)throw Error(`Voice input is still connecting.`);let i=await Eo.voiceTranscriptionStatus(r,{signal:t});if(!i.binaryPath)throw Error(i.installHint??`Install whisper.cpp to use dictation.`);let o=await Eo.transcribeVoice(r,{audioBase64:await nh(e.blob),durationMs:Math.round(e.durationMs),language:a,mimeType:`audio/wav`},{signal:t});t.aborted||await c(o.text,{submit:n()})},[a,c]),I=(0,Q.useCallback)(()=>{kf(l),S(Ym())},[l]),L=(0,Q.useCallback)(async(e=!1)=>{N();let t=d.current;d.current=null,t&&(y(`idle`),S(Ym()),Mf(l,async(e,n)=>{let r=await t.stop();e.aborted||await F(r,e,n)},{submit:e}).catch(e=>{e instanceof DOMException&&e.name===`AbortError`||s(rh(e),`error`)}))},[N,s,F,l]),ee=(0,Q.useCallback)(async()=>{if(b.current&&!m.current){if(!p.current)s(`Voice input is still connecting.`,`error`);else if(!Bm())s(`Voice recording is not available in this browser.`,`error`);else{y(`starting`);try{let e=await window.openpond?.requestMicrophoneAccess?.();if(!b.current||m.current){await P();return}if(e===!1)throw Error(`Microphone access is denied.`);let t=await Vm({onAudioLevel:e=>{S(t=>Xm(t,e))}});if(!b.current||m.current){await t.cancel(),await P();return}if(d.current=t,S(Ym()),y(`recording`),g.current){g.current=!1,L(!0);return}f.current=window.setTimeout(()=>{L(!1)},Qm)}catch(e){b.current&&s(rh(e),`error`),await P()}}}},[P,s,L]),R=(0,Q.useCallback)(()=>{_.current?ee():s(eh,`info`,{actionLabel:`Continue`,onAction:()=>{_.current=!0,ah(),ee()}})},[ee,s]);return(0,Q.useEffect)(()=>Af(l,()=>d.current?(L(!0),!0):h.current===`starting`&&(g.current=!0,!0)),[L,l]),(0,Q.useEffect)(()=>{o?.(M)},[M,o]),(0,Q.useEffect)(()=>()=>o?.(!1),[o]),(0,Q.useEffect)(()=>(b.current=!0,()=>{b.current=!1,P()}),[P]),(0,$.jsx)(`span`,{className:`voice-input-control ${n} ${k?`starting`:``} ${A?`recording`:``} ${T?`transcribing`:``}`.trim(),children:j?(0,$.jsxs)(`span`,{className:`voice-recording-strip`,children:[(0,$.jsx)(`span`,{className:`sr-only`,role:`status`,children:T?D:`Recording voice`}),(0,$.jsx)(`button`,{type:`button`,className:`voice-recording-action cancel`,"aria-label":T?`Cancel transcription`:`Cancel dictation`,onClick:()=>{T?I():P()},children:(0,$.jsx)(Ua,{size:15})}),T?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`span`,{className:`voice-transcribing-label`,"aria-hidden":`true`,children:[D,(0,$.jsxs)(`span`,{className:`voice-transcribing-dots`,children:[(0,$.jsx)(`span`,{children:`.`}),(0,$.jsx)(`span`,{children:`.`}),(0,$.jsx)(`span`,{children:`.`})]})]}),(0,$.jsx)(`span`,{className:`voice-recording-action-spacer`,"aria-hidden":`true`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Zm,{levels:x}),(0,$.jsx)(`button`,{type:`button`,className:`voice-recording-action stop`,"aria-label":`Stop and transcribe`,onClick:()=>void L(!1),children:(0,$.jsx)(Va,{size:10,fill:`currentColor`})})]})]}):(0,$.jsx)(`button`,{type:`button`,className:`voice-input-trigger ${t} ${k?`starting`:``}`.trim(),"aria-label":k?`Starting dictation`:`Dictate`,disabled:r||O||k,onClick:R,children:(0,$.jsx)(iu,{size:i})})})}async function nh(e){let t=new Uint8Array(await e.arrayBuffer()),n=``;for(let e=0;e<t.length;e+=32768){let r=t.subarray(e,e+32768);n+=String.fromCharCode(...r)}return window.btoa(n)}function rh(e){let t=e instanceof Error?e.message:String(e);return/NotAllowedError|Permission denied|denied/i.test(t)?`Microphone access is denied.`:/NotFoundError|Requested device not found/i.test(t)?`No microphone was found.`:t||`Voice input failed.`}function ih(){if(typeof window>`u`)return!1;try{return ue.getItem($m)===`true`}catch{return!1}}function ah(){if(typeof window<`u`)try{ue.setItem($m,`true`)}catch{}}var oh=new Set([`codex`,`openai`,`xai`,`openrouter`,`deepseek`,`zai`,`moonshot`,`together`,`groq`,`custom-openai-compatible`,`setup-provider`]);function sh({surface:e=`chat`,teamUseModel:t=!1,teamUseModelLocked:n=!1,onTeamUseModelChange:r,addFiles:i,addMenuId:a,addMenuOpen:o,addMenuRef:s,busy:c,codexPermissionMode:l,codexReasoningEffort:u,connection:d,contextStatusStyle:f,contextStatusTooltipId:p,contextWindowStatus:m,disabled:h,dropdownPlacement:g,fileInputRef:_,modelValue:v,modelOptions:y=[],hideModelControls:b=!1,trainingControl:x,executionControl:S,allowedModelRefs:C,modelSelectionDisabled:w=!1,openPondCommandAccessMode:T,showCommandAccess:E=!0,profileTarget:D,onCodexPermissionModeChange:O,onCodexReasoningEffortChange:k,onOpenPondCommandAccessModeChange:A,onProfileTargetChange:j,onModelChange:M,onOpenFilePicker:N,onProviderChange:P,onProviderSetupOpen:F,onSend:I,onStop:L,onToggleAddMenu:ee,onTranscript:R,voiceInputChannelKey:z,provider:B,providerSettings:V,providerOptions:H,running:U,sendDisabled:te,hasComposerInput:ne,sendTooltip:re,showToast:W,stopIcon:ie=`stop`,stopLabel:G=`Stop response`}){let ae=Fm(B,V?.providers[B]),[K,q]=(0,Q.useState)(null),se=d?Im(d,B,V?.providers[B]):null,ce=K?.connection===d&&K.provider===B&&K.instance===ae?K.settings:se?.settings??null,le=(0,Q.useMemo)(()=>ce?V?{...V,providers:{...V.providers,[B]:ce.providers[B]},statuses:{...V.statuses,[B]:ce.statuses[B]},modelCaches:{...V.modelCaches,[B]:ce.modelCaches[B]}}:ce:V,[V,ce,B]),ue=(0,Q.useCallback)(e=>{d&&q({connection:d,provider:e.provider,instance:ae,settings:e.settings})},[d,ae]),de=oe(B)||[`claude-code`,`opencode`,`grok-build`].includes(B),fe=B===`openpond`?v:v||Si(B,le),[pe,me]=(0,Q.useState)(!1),he=fi(B,fe,le),ge=(0,Q.useMemo)(()=>Zf({currentModelOptions:ce?Ci(B,le):y,currentProvider:B,providerOptions:H,providerSettings:le}).flatMap(e=>{if(!C)return[e];let t=e.options.filter(t=>C.some(n=>n.providerId===e.provider&&n.modelId===t.value));return t.length?[{...e,options:t,defaultModel:t.some(t=>t.value===e.defaultModel)?e.defaultModel:t[0].value}]:[]}),[y,B,H,le,ce,C]),_e=(0,Q.useMemo)(()=>ge.filter(e=>oh.has(e.provider)),[ge]),ve=(e,t)=>{k(gi(e,t,le)),e===B?M(t):P(e,t)};return e===`team`?(0,$.jsxs)(`div`,{className:`composer-primary-controls team-chat-composer-controls ${U?`has-running-turn`:``}`.trim(),children:[(0,$.jsx)(`button`,{type:`button`,className:`composer-icon`,"aria-label":`Add photos and files`,disabled:h,onClick:N,children:(0,$.jsx)(za,{size:18})}),(0,$.jsx)(`input`,{ref:_,className:`composer-file-input`,type:`file`,multiple:!0,tabIndex:-1,onChange:e=>{i(Array.from(e.currentTarget.files??[])),e.currentTarget.value=``}}),(0,$.jsxs)(`label`,{className:`team-chat-model-toggle`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:t,disabled:c||n,onChange:e=>r?.(e.currentTarget.checked)}),(0,$.jsx)(`span`,{children:`Use model`})]}),(0,$.jsx)(`div`,{className:`composer-spacer`}),t?(0,$.jsx)(ap,{disabled:c,model:fe,modelGroups:_e,placement:g,provider:B,providerSettings:le,reasoningEffort:u,showReasoning:he,onModelSelectionChange:ve,onReasoningEffortChange:k}):null,S,(0,$.jsx)(th,{buttonClassName:`composer-icon`,connection:d,disabled:h,iconSize:16,wrapperClassName:`composer-voice-input`,onActiveChange:me,showToast:W,onTranscript:R,transcriptionChannelKey:z,submitLabel:re}),(0,$.jsx)(jm,{running:U,sendDisabled:te||B===`openpond`&&!v,hasComposerInput:ne,sendTooltip:re,stopIcon:ie,stopLabel:G,voiceInputActive:pe,onSend:I,onStop:L})]}):(0,$.jsxs)(`div`,{className:`composer-primary-controls ${U?`has-running-turn`:``}`.trim(),children:[(0,$.jsxs)(`div`,{className:`composer-add-control open-up`,ref:s,children:[(0,$.jsx)(`button`,{type:`button`,className:`composer-icon ${o?`active`:``}`,"aria-label":`Add to message`,"aria-haspopup":`menu`,"aria-expanded":o,"aria-controls":o?a:void 0,disabled:h,onMouseDown:e=>e.preventDefault(),onClick:ee,children:(0,$.jsx)(za,{size:18})}),(0,$.jsx)(`input`,{ref:_,className:`composer-file-input`,type:`file`,multiple:!0,tabIndex:-1,onChange:e=>{i(Array.from(e.currentTarget.files??[])),e.currentTarget.value=``}})]}),!b&&de?(0,$.jsx)(zm,{connection:d,provider:B,providerSettings:le,placement:g,onSettings:ue,onSetup:F,disabled:c||h}):null,E&&B===`codex`?(0,$.jsx)(Z,{compact:!0,className:`permission-select`,icon:(0,$.jsx)(go,{size:14}),placement:g,label:`Codex permissions`,tooltip:xi.find(e=>e.value===l)?.label,value:l,options:xi,disabled:c,onChange:e=>O(e)}):E&&!de?(0,$.jsx)(Z,{compact:!0,className:`permission-select`,icon:(0,$.jsx)(Ha,{size:14}),placement:g,label:`Command access`,tooltip:bi.find(e=>e.value===(T===`disabled`?`ask`:T))?.label,value:T===`disabled`?`ask`:T,options:bi,disabled:c,onChange:e=>A(e)}):null,D&&j?(0,$.jsx)($f,{busy:c,placement:g,state:D,onChange:j}):null,(0,$.jsx)(`div`,{className:`composer-spacer`}),!b&&(0,$.jsxs)(`span`,{className:`context-status-shell ${m.tone}`,style:f,children:[(0,$.jsx)(`span`,{className:`composer-status ${m.tone}`,role:m.maxTokens===null?`img`:`meter`,"aria-label":m.tooltip,"aria-describedby":p,"aria-valuemin":m.maxTokens===null?void 0:0,"aria-valuemax":m.maxTokens??void 0,"aria-valuenow":m.maxTokens===null?void 0:m.usedTokens,tabIndex:0}),(0,$.jsxs)(`span`,{className:`context-status-tooltip`,id:p,role:`tooltip`,children:[(0,$.jsx)(`span`,{className:`context-status-tooltip-title`,children:`Context window`}),(0,$.jsxs)(`span`,{className:`context-status-tooltip-main`,children:[(0,$.jsx)(`span`,{children:m.summary}),(0,$.jsx)(`span`,{children:m.tokensLabel})]}),m.maxTokens!==null&&(0,$.jsx)(`span`,{className:`context-status-tooltip-bar`,"aria-hidden":`true`,children:(0,$.jsx)(`span`,{})}),m.detail?(0,$.jsx)(`span`,{className:`context-status-tooltip-detail`,children:m.detail}):null]})]}),x,!b&&(0,$.jsx)(ap,{disabled:c||w,model:fe,modelGroups:ge,placement:g,provider:B,providerSettings:le,reasoningEffort:u,showReasoning:he,onModelSelectionChange:ve,onReasoningEffortChange:k}),S,(0,$.jsx)(th,{buttonClassName:`composer-icon`,connection:d,disabled:h,iconSize:16,wrapperClassName:`composer-voice-input`,onActiveChange:me,showToast:W,onTranscript:R,transcriptionChannelKey:z,submitLabel:re}),(0,$.jsx)(jm,{running:U,sendDisabled:te||B===`openpond`&&!v,hasComposerInput:ne,sendTooltip:re,stopIcon:ie,stopLabel:G,voiceInputActive:pe,onSend:I,onStop:L})]})}function ch(e){return e.description||e.path}function lh({items:e,onSelect:t,onSelectIndex:n,skillIndex:r,style:i}){let a=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{a.current?.scrollIntoView({block:`nearest`})},[e.length,r]),(0,$.jsx)(`div`,{className:`composer-project-menu composer-slash-menu composer-skill-menu`,role:`listbox`,"aria-label":`Available skills`,style:i,children:e.length>0?e.map((e,i)=>{let o=i===r;return(0,$.jsxs)(`button`,{type:`button`,className:`composer-project-option ${o?`selected`:``}`,ref:o?a:void 0,role:`option`,"aria-selected":o,onMouseEnter:()=>n(i),onMouseDown:n=>{n.preventDefault(),t(e)},children:[(0,$.jsx)(ts,{size:14}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:gf(e)}),(0,$.jsx)(`small`,{children:ch(e)})]}),o?(0,$.jsx)(Ro,{size:14}):(0,$.jsx)(`span`,{"aria-hidden":`true`})]},e.name)}):(0,$.jsx)(`div`,{className:`composer-menu-empty`,role:`option`,"aria-selected":`false`,children:`No matching skills`})})}function uh({actionCatalogCount:e,actionIndex:t,items:n,onSelect:r,onSelectIndex:i,style:a}){return(0,$.jsx)(km,{ariaLabel:`OpenPond agents and actions`,menuIndex:t,sections:[{emptyLabel:e===0?`No matching commands or apps`:`No matching commands, apps, agents, or actions`,id:`slash`,items:n.map(e=>({kind:`slash`,item:e})),label:`/`}],style:a,variant:`typed`,onSelect:e=>{e.kind===`slash`&&r(e.item)},onSelectIndex:i})}function dh({busy:e,initialDescription:t,open:n,onClose:r,onSubmit:i}){let[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(()=>t.trim()),l=a.trim(),u=s.trim(),d=e||!l||!u;if((0,Q.useEffect)(()=>{n&&(o(``),c(t.trim()))},[t,n]),(0,Q.useEffect)(()=>{if(!n||e)return;function t(e){e.key===`Escape`&&r()}return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e,r,n]),!n)return null;async function f(){d||await i({title:l,description:u})&&(o(``),c(``))}return(0,$.jsx)(`div`,{className:`git-dialog-backdrop`,role:`presentation`,onMouseDown:e?void 0:r,children:(0,$.jsxs)(`section`,{className:`git-dialog submit-issue-dialog`,role:`dialog`,"aria-modal":`true`,"aria-label":`Submit GitHub issue`,onMouseDown:e=>e.stopPropagation(),onKeyDown:e=>{e.key===`Enter`&&e.target instanceof HTMLInputElement&&(e.preventDefault(),f())},children:[(0,$.jsx)(`button`,{className:`git-dialog-close`,disabled:e,type:`button`,onClick:r,children:(0,$.jsx)(Ua,{size:16})}),(0,$.jsx)(`div`,{className:`git-dialog-icon`,children:(0,$.jsx)(Jo,{size:18})}),(0,$.jsx)(`h2`,{children:`Submit issue`}),(0,$.jsxs)(`div`,{className:`git-dialog-row submit-issue-repo-row`,children:[(0,$.jsx)(`span`,{children:`Repository`}),(0,$.jsx)(`strong`,{children:qi})]}),(0,$.jsxs)(`label`,{className:`git-dialog-field`,children:[(0,$.jsx)(`span`,{children:`Title`}),(0,$.jsx)(`input`,{autoFocus:!0,disabled:e,placeholder:`Short issue title`,value:a,onChange:e=>o(e.target.value)})]}),(0,$.jsxs)(`label`,{className:`git-dialog-field`,children:[(0,$.jsx)(`span`,{children:`Description`}),(0,$.jsx)(`textarea`,{disabled:e,placeholder:`What happened, what you expected, and any useful context`,value:s,onChange:e=>c(e.target.value)})]}),(0,$.jsxs)(`div`,{className:`git-dialog-footer`,children:[(0,$.jsx)(`button`,{className:`git-dialog-secondary`,disabled:e,type:`button`,onClick:r,children:`Cancel`}),(0,$.jsx)(`button`,{className:`git-dialog-primary`,disabled:d,type:`button`,onClick:()=>void f(),children:`Submit issue`})]})]})})}function fh(){let e=(0,Q.useRef)([]),t=(0,Q.useRef)([]),n=(0,Q.useRef)(!1),[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{e.current=r},[r]),(0,Q.useEffect)(()=>(n.current=!1,()=>{n.current=!0;for(let t of e.current)ph(t);for(let e of t.current)ph(e)}),[]);let s=(0,Q.useCallback)(t=>{if(t.length===0||n.current)return;let r=e.current,a=Math.max(0,ge.maxAttachments-r.length),s=[],c=0,l=0;for(let e of t){if(e.size>ge.maxAttachmentBytes){c+=1;continue}if(s.length>=a){l+=1;continue}let t=`webkitRelativePath`in e&&typeof e.webkitRelativePath==`string`&&e.webkitRelativePath.trim()?e.webkitRelativePath.trim():void 0;s.push({id:qe(),file:e,name:e.name||`Untitled file`,mediaType:e.type||`application/octet-stream`,sizeBytes:e.size,kind:Ge(e),...t?{relativePath:t}:{},...e.type.startsWith(`image/`)?{previewUrl:URL.createObjectURL(e)}:{}})}if(s.length>0){let t=[...r,...s];e.current=t,i(t),o(null)}if(c>0||l>0){let e=[];c>0&&e.push(`${c} file${c===1?``:`s`} exceeded ${Ue(ge.maxAttachmentBytes)}`),l>0&&e.push(`maximum ${ge.maxAttachments} attachments`),o(e.join(`; `))}},[]),c=(0,Q.useCallback)(t=>{let n=e.current,r=n.find(e=>e.id===t);r&&ph(r);let a=n.filter(e=>e.id!==t);e.current=a,i(a),a.length===0&&o(null)},[]),l=(0,Q.useCallback)(()=>{for(let t of e.current)ph(t);e.current=[],i([]),o(null)},[]),u=(0,Q.useCallback)(()=>{let n=e.current;return n.length===0||(e.current=[],t.current=n,i([]),o(null)),n},[]),d=(0,Q.useCallback)((r,a)=>{if(r.length===0)return;let o=new Set(r.map(e=>e.id));if(t.current=t.current.filter(e=>!o.has(e.id)),a===`restore`&&!n.current)i(t=>{let n=new Set(t.map(e=>e.id)),i=[...r.filter(e=>!n.has(e.id)),...t];return e.current=i,i});else for(let e of r)ph(e)},[]);return{attachmentError:a,attachments:r,addFiles:s,clearAttachments:l,removeAttachment:c,settleStagedAttachments:d,setAttachmentError:o,stageAttachmentsForSubmit:u,prepareAttachmentsForSubmit:(0,Q.useCallback)(async()=>{let e=u();try{return{attachments:await Promise.all(e.map(Ke)),settle:t=>d(e,t?`dispose`:`restore`)}}catch(t){throw d(e,`restore`),t}},[u,d]),restoreAttachmentPayloads:(0,Q.useCallback)(e=>{s(e.map(e=>{let t=e.contentsBase64?Uint8Array.from(atob(e.contentsBase64),e=>e.charCodeAt(0)):new TextEncoder().encode(e.text??``),n=new File([t],e.name,{type:e.mediaType});return e.relativePath&&Object.defineProperty(n,"webkitRelativePath",{value:e.relativePath}),n}))},[s])}}function ph(e){e.previewUrl&&URL.revokeObjectURL(e.previewUrl)}function mh(e){let t=e.current?.id===e.sessionId?e.current:null,n=e.observed?.id===e.sessionId?e.observed:null,r=[t,n].find(e=>e?.metadata?.nativeWorker===!0&&e.metadata.nativeWorkerCanResume===!1),i=r??n??t,a=typeof i?.metadata?.nativeReadOnlyReason==`string`?i.metadata.nativeReadOnlyReason:null;return{session:i,reason:r?a??`This native agent is controlled by its parent conversation. Send further instructions through the parent conversation.`:i?a:e.fallbackReason}}function hh({connection:e,sessionId:t,events:n,fallbackReason:r,fallbackSession:i}){let a=(0,Q.useMemo)(()=>{for(let e=n.length-1;e>=0;e--){let r=n[e];if(r.sessionId!==t||![`session.started`,`session.updated`,`session.title.updated`].includes(r.name))continue;let i=r.data,a=pe.safeParse(i&&typeof i==`object`&&`session`in i?i.session:null);if(a.success)return{session:a.data,eventId:r.id}}return null},[n,t]),[o,s]=(0,Q.useState)(null),{session:c,reason:l}=mh({sessionId:t,current:i,observed:o?.connection===e&&o.session.id===t&&o.eventId===a?.eventId?o.session:a?.session??null,fallbackReason:r});return{session:c,reason:l,acceptSession:t=>s({connection:e,eventId:a?.eventId,session:t})}}function gh({connection:e,session:t,reason:n,onRechecked:r,onOpenParent:i}){let[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(null);Ka(s);let l=(0,Q.useRef)(0);(0,Q.useEffect)(()=>(l.current++,o(!1),c(null),()=>{l.current++}),[e,t?.id]);let u=t?.metadata?.nativeWorker===!0&&t.metadata.nativeWorkerCanResume===!1,d=!u&&!t?.metadata?.nativeBranch&&t?.metadata?.nativeHistoryId;return(0,$.jsxs)(`div`,{className:`composer dock native-conversation-unavailable`,children:[(0,$.jsx)(`p`,{role:`status`,children:n}),u&&t?.parentSessionId&&i?(0,$.jsx)(`button`,{type:`button`,disabled:a,onClick:async()=>{o(!0),c(null);try{await i(t.parentSessionId)}catch(e){c(e instanceof Error?e.message:String(e))}finally{o(!1)}},children:`Open parent chat`}):null,e&&typeof d==`string`?(0,$.jsx)(`button`,{type:`button`,disabled:a,onClick:async()=>{let t=l.current;o(!0),c(null);try{let n=await Y(e,`/v1/native-history/open`,{method:`POST`,body:JSON.stringify({id:d,retryWorkspace:!0})});t===l.current&&r(pe.parse(n))}catch(e){t===l.current&&c(e instanceof Error?e.message:`Could not reconnect to this conversation.`)}finally{t===l.current&&o(!1)}},children:a?`Checking…`:`Check again`}):null]})}function _h(e,t){let n=e.slice(0,Math.max(0,Math.min(t,e.length))),r=/(?:^|\s)\/([a-zA-Z0-9_-]*)$/.exec(n);if(!r||typeof r.index!=`number`)return null;let i=r[0].lastIndexOf(`/`);if(i<0)return null;let a=r.index+i;return{end:n.length,query:(r[1]??``).toLowerCase(),start:a}}function vh(e,t,n=Pi){let r=e.slice(0,Math.max(0,Math.min(t,e.length))),i=/(?:^|\s)\/([a-z][a-z0-9_-]*)\s$/.exec(r);if(!i)return null;let a=n.find(e=>e.id===i[1]);if(!a)return null;let o=i[0].lastIndexOf(`/`);return o<0||typeof i.index!=`number`?null:{command:a,end:r.length,start:i.index+o}}function yh(e,t=Pi){return Fi({commands:t,prompt:`/${e}`})}function bh(e,t){return e.length===0?[]:e.filter(e=>!t||[e.id,e.name??``,e.label??``,e.description??``,typeof e.implementation?.type==`string`?e.implementation.type:``].join(` `).toLowerCase().includes(t))}function xh(e,t){return e.length===0?[]:e.filter(e=>!t||[e.id,e.name,e.description??``,e.gitRepo??``,Ja(e)].join(` `).toLowerCase().includes(t)).slice(0,8)}function Sh({actionCatalog:e,connectedAppMentions:t,mentionApps:n,profileSkills:r,query:i,surface:a,teamMentionMembers:o}){let s=i.toLowerCase();if(a===`team`){let t=o.filter(e=>!s||[e.name,e.handle??``].map(Xa).some(e=>e.includes(s))).map(e=>({kind:`team-member`,member:e}));return[...Vi(e,s,e.length).map(e=>({kind:`action`,action:e})),...t]}let c=n.filter(e=>!s||[Xa(e.id),Xa(e.name),e.gitRepo?Xa(e.gitRepo):``,Ja(e)].some(e=>e.includes(s))).map(e=>({kind:`app`,app:e})),l=Vi(e,s,e.length).map(e=>({kind:`action`,action:e})),u=vf(r,s).map(e=>({kind:`skill`,skill:e})),d=eo(t,s).map(e=>({kind:`connected-app`,app:e}));return[...l,...u,...c,...d]}function Ch(e,t,n){let r=t?.trim();if(!r)return e;let i=Math.max(0,Math.min(n??0,e.length)),a=e.slice(0,i),o=e.slice(i);return`${a}${a&&!/\s$/.test(a)?` `:``}${r}${o&&!/^\s/.test(o)?` `:``}${o}`.replace(/\s+/g,` `).trim()}function wh(e){let t=Xa(Ni(e)||e.name||e.id);return t?`@${t}`:null}function Th(e){let t=e.trim();if(!t.startsWith(`{`)||!t.endsWith(`}`))return e;try{let n=JSON.parse(t);if(!n||Array.isArray(n)||typeof n!=`object`)return e;let r=Object.entries(n).filter(([,e])=>e!=null&&e!==``).map(([e,t])=>`${Eh(e)}: ${Dh(e,t)}`);return r.length?r.join(` · `):e}catch{return e}}function Eh(e){let t=e.replace(/Id$/,``).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replaceAll(`_`,` `).trim().toLowerCase();return t?`${t[0].toUpperCase()}${t.slice(1)}`:`Input`}function Dh(e,t){if(Array.isArray(t))return t.map(t=>Dh(e,t)).join(`, `);if(t&&typeof t==`object`)return Object.entries(t).map(([e,t])=>`${Eh(e)}: ${Dh(e,t)}`).join(` · `);let n=String(t);return/Id$/.test(e)&&/^[a-z0-9_-]+$/i.test(n)?n.split(/[-_]+/).filter(Boolean).map(e=>`${e[0].toUpperCase()}${e.slice(1)}`).join(` `):n}function Oh({action:e,prompt:t,selectedActionMentionText:n,selectedInvocationPosition:r}){if(!e)return null;let i=n?.trim(),a=i?.startsWith(`@`)?i:wh(e);return a?Ch(Th(t),a,r):null}function kh({attachmentCount:e,prompt:t,selectedAction:n,selectedCommand:r}){return!!(t.trim()||e>0||n||r)}var Ah=new Set([`openpond-agent-authoring`,`openpond-skill-authoring`,`openpond-taskset-authoring`,`openpond-refiner-authoring`]);function jh({activeMentionKey:e,activeSkillKey:t,activeSlashKey:n,addMenuIndex:r,addMenuItems:i,addMenuOpen:a,addMenuPanelRef:o,addMenuRef:s,attachmentCount:c,composerRef:l,createImproveActive:u,goalRuntimeActive:d,inputRef:f,inputShellRef:p,mentionQuery:m,prompt:h,selectedActionId:g,selectAddMenuItem:_,setActionIndex:v,setActionMenuDismissedPrompt:y,setAddMenuIndex:b,setAddMenuOpen:x,setAddMenuQuery:S,setMentionMenuDismissedPrompt:C,setMentionIndex:w,setSkillIndex:T,setSkillMenuDismissedPrompt:E,skillMatchCount:D,skillQuery:O,slashMatchCount:k,slashQuery:A,showActionMenu:j,showMentionMenu:M,showSkillMenu:N}){let[P,F]=(0,Q.useState)({}),[I,L]=(0,Q.useState)({}),[ee,R]=(0,Q.useState)({}),[z,B]=(0,Q.useState)({});return(0,Q.useEffect)(()=>{w(0)},[m]),(0,Q.useEffect)(()=>{T(0)},[D,O]),(0,Q.useEffect)(()=>{v(0)},[k,A]),(0,Q.useEffect)(()=>{let e=f.current?.element,t=e?.parentElement;if(!e||!t||typeof ResizeObserver>`u`)return;let n=new ResizeObserver(()=>f.current?.resize());return n.observe(t),()=>n.disconnect()},[]),(0,Q.useEffect)(()=>{if(!a)return;function c(r){let i=r.target,a=f.current?.element?.parentElement;!s.current?.contains(i)&&!o.current?.contains(i)&&!a?.contains(i)&&(x(!1),S(``),C(e),y(n),E(t))}function l(a){if(a.key===`Escape`)a.preventDefault(),x(!1),S(``),C(e),y(n),E(t);else if(i.length!==0){if(a.key===`ArrowDown`)a.preventDefault(),b(e=>(e+1)%i.length);else if(a.key===`ArrowUp`)a.preventDefault(),b(e=>(e-1+i.length)%i.length);else if(a.key===`Home`)a.preventDefault(),b(0);else if(a.key===`End`)a.preventDefault(),b(i.length-1);else if(a.key===`Enter`){a.preventDefault();let e=i[r]??i[0];e&&_(e)}}}return document.addEventListener(`pointerdown`,c),document.addEventListener(`keydown`,l),()=>{document.removeEventListener(`pointerdown`,c),document.removeEventListener(`keydown`,l)}},[e,t,n,r,i,a]),(0,Q.useLayoutEffect)(()=>{if(!a)return;let e=p.current;if(!e)return;let t=e;function n(){B(Np(t))}return n(),window.addEventListener(`resize`,n),window.addEventListener(`scroll`,n,!0),()=>{window.removeEventListener(`resize`,n),window.removeEventListener(`scroll`,n,!0)}},[a,c,u,d]),(0,Q.useLayoutEffect)(()=>{if(!j)return;let e=f.current?.element,t=l.current;if(!e||!t)return;let n=e,r=t;function i(){R(Mp(n,r))}return i(),window.addEventListener(`resize`,i),window.addEventListener(`scroll`,i,!0),()=>{window.removeEventListener(`resize`,i),window.removeEventListener(`scroll`,i,!0)}},[c,u,d,h,g,j]),(0,Q.useLayoutEffect)(()=>{if(!N)return;let e=f.current?.element,t=l.current;if(!e||!t)return;let n=e,r=t;function i(){L(Mp(n,r))}return i(),window.addEventListener(`resize`,i),window.addEventListener(`scroll`,i,!0),()=>{window.removeEventListener(`resize`,i),window.removeEventListener(`scroll`,i,!0)}},[c,u,d,h,g,N]),(0,Q.useLayoutEffect)(()=>{if(!M)return;let e=f.current?.element,t=l.current;if(!e||!t)return;let n=e,r=t;function i(){F(Mp(n,r))}return i(),window.addEventListener(`resize`,i),window.addEventListener(`scroll`,i,!0),()=>{window.removeEventListener(`resize`,i),window.removeEventListener(`scroll`,i,!0)}},[c,u,d,h,g,M]),{actionMenuStyle:ee,addMenuStyle:z,mentionMenuStyle:P,skillMenuStyle:I}}var Mh=(0,Q.lazy)(()=>o(()=>import(`./ComposerCreateImproveStrip-DcM1bkfu.js`).then(e=>e.n).then(e=>({default:e.ComposerCreateImproveStrip})),__vite__mapDeps([68,1,2,3,15,5,16,17,13,18,19,20,4,6,21,22,23,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,61]))),Nh=Pi.find(e=>e.id===`submit-issue`),Ph=[],Fh=[];function Ih({experience:e=`development`,mode:t,surface:n=`chat`,placeholder:r,teamUseModel:i=!1,teamUseModelLocked:a=!1,teamMentionMembers:o=[],onTeamUseModelChange:s,prompt:c,composeNotice:l=null,mentionApps:u=[],connectedAppMentions:d=[],profileSkills:f=[],selectedMentionAppId:p=null,contextWindowStatus:m,goalRuntime:h=null,subagentRuntime:g=null,createImproveRuntime:_=null,busy:v,readOnlyReason:y=null,readOnlySession:b=null,onOpenNativeParent:x,running:S=v,taskSessionId:C=null,goalSessionId:w=C,taskEvents:T=Fh,steerActiveResponses:E=!1,submissionScopeKey:D=`default`,composerDraftStore:O,getCurrentSubmissionScopeKey:A,voiceInputChannelKey:j=D,initialSteerDrafts:M=Ph,showProjectFooter:N=!0,hideModelControls:P=!1,modelSelectionDisabled:F=!1,allowedModelRefs:I,executionControl:L,enableResourceContext:ee=!0,autoFocus:R=!1,focusRequestId:z=0,attachmentRequest:B=null,connection:V,providerSettings:H=null,provider:U,model:te,projectTarget:ne,profileTarget:re=null,actionCatalog:W=[],requestedAction:ie=null,workspaceTarget:G,codexPermissionMode:ae,codexReasoningEffort:K,openPondCommandAccessMode:q,onProviderChange:oe,onProviderSetupOpen:se,onProjectTargetChange:ce,onProfileTargetChange:le,onWorkspaceTargetChange:ue,onModelChange:de,onCodexPermissionModeChange:fe,onCodexReasoningEffortChange:pe,onOpenPondCommandAccessModeChange:me,onPromptChange:he,onMentionAppSelect:_e,onSaveTaskDraft:ve,showToast:ye,onSubmit:be,onStop:xe,onPauseGoal:Se}){let Ce=hh({connection:V,sessionId:C??b?.id??null,events:T,fallbackReason:y??null,fallbackSession:b}),we=Ce.reason,Te=(0,Q.useRef)(null),Ee=(0,Q.useRef)(null),De=(0,Q.useRef)(null),Oe=O?.getScopeKey(),ke=E,Ae=Lf(V,C,T),je=k(n===`chat`&&ee?V:null,C??null),Me=Xd(n===`chat`&&ee&&!je.selection?.model&&!je.selection?.training?V:null,C??null),{resourceDrafts:Ne,onPromptChange:Pe,currentResourceContexts:Fe}=qd(D,he,Me,O);mf({surface:n,voiceInputChannelKey:j,taskSessionId:C,submissionScopeKey:D,prompt:c,onPromptChange:Pe,showToast:ye,resourceDrafts:Ne,inputRef:De,composerDraftStore:O});let Ie=(0,Q.useRef)(null),Le=(0,Q.useRef)(null),Re=(0,Q.useRef)(null),ze=(0,Q.useRef)(null),Be=(0,Q.useRef)(0),Ve=ie&&W.some(e=>e.id===ie.actionId)?ie:null,He=(0,Q.useRef)(!1),Ue=(0,Q.useRef)(0),Ge=(0,Q.useRef)(Ve?.requestId??0),qe=(0,Q.useRef)(new Set),Ye=(0,Q.useRef)(new Set),[Xe,Ze]=(0,Q.useState)(c.length),Qe=(0,Q.useRef)(Xe);Qe.current=Xe;let[$e,et]=(0,Q.useState)(0),[tt,nt]=(0,Q.useState)(0),[rt,it]=(0,Q.useState)(0),[at,ot]=(0,Q.useState)(0),[st,ct]=(0,Q.useState)(``),[lt,ut]=(0,Q.useState)(null),[dt,ft]=(0,Q.useState)(null),[pt,mt]=(0,Q.useState)(null),[ht,gt]=(0,Q.useState)(!1),[_t,vt]=(0,Q.useState)(!1),[yt,bt]=(0,Q.useState)(Ve?.actionId??null),[xt,St]=(0,Q.useState)(null),[Ct,wt]=(0,Q.useState)(null),[Tt,Et]=(0,Q.useState)(null),[Dt,Ot]=(0,Q.useState)(null),[kt,At]=(0,Q.useState)(!1),[jt,Mt]=(0,Q.useState)(()=>({[D]:M})),[Nt,Pt]=(0,Q.useState)(null),[Ft,It]=(0,Q.useState)(!1),[Lt,Rt]=(0,Q.useState)(``),[zt,Bt]=(0,Q.useState)(!1),{attachmentError:Vt,attachments:Ht,addFiles:Ut,removeAttachment:Wt,settleStagedAttachments:Gt,setAttachmentError:Kt,stageAttachmentsForSubmit:qt,prepareAttachmentsForSubmit:Jt,restoreAttachmentPayloads:Yt}=fh(),Xt=(0,Q.useRef)(0);(0,Q.useEffect)(()=>{B&&Xt.current!==B.id&&(Xt.current=B.id,Ut([B.file]))},[Ut,B]);let Zt=(0,Q.useCallback)(e=>{let t=We(e,Ht);return!t||Ht.length>=ge.maxAttachments||t.size>ge.maxAttachmentBytes?!1:(Ut([t]),!0)},[Ut,Ht]),Qt=r??mm({experience:e,mode:t,surface:n}),$t=e===`development`||e===`work`&&ne.value!==`none`,en=mi(U,te,H),tn=(0,Q.useId)(),nn=(0,Q.useId)(),rn=(0,Q.useId)(),an={"--context-fill":`${Math.round((m.percent??0)/100*360)}deg`,"--context-bar-fill":`${m.percent??0}%`},on=(0,Q.useMemo)(()=>W.find(e=>e.id===yt)??null,[W,yt]),sn=(0,Q.useMemo)(()=>Bi(U,e),[e,U]),cn=(0,Q.useMemo)(()=>$t?f:f.filter(e=>!Ah.has(e.name)),[e,f]),ln=(0,Q.useMemo)(()=>sn.find(e=>e.id===xt)??null,[sn,xt]),un=Oh({action:on,prompt:c,selectedActionMentionText:Tt,selectedInvocationPosition:Ct}),dn=kh({attachmentCount:Ht.length,prompt:c,selectedAction:on,selectedCommand:ln}),fn=(0,Q.useMemo)(()=>{let e=Math.max(0,Math.min(Ct??0,c.length));return ln?{icon:ln.id===`agent`?`plus`:ln.id===`skill`?`skill`:`workflow`,key:`command:${ln.id}`,label:ln.id===`agent`?`Author Agent`:ln.id,position:e,onRemove:()=>{St(null),wt(null),Et(null)}}:on?{icon:on.implementation?.type===`openpond-agent`?`bot`:`workflow`,key:`action:${on.id}`,label:Ni(on),position:e,onRemove:()=>{bt(null),wt(null),Et(null)}}:null},[c.length,on,ln,Ct]),pn=Dt===D,mn=pn||!dn,hn=pn?`Preparing files`:S?ke?`Steer`:`Queue`:`Send`,gn=pn,_n=pn||je.selecting,vn=Vd({connection:n===`chat`&&ee?V:null,sessionId:C??null,events:T,prompt:c,selectionKey:JSON.stringify(je.selection?.target??null),inputRef:De,blocked:v||S||pn||je.selecting||Ht.length>0||!!(on||ln)||Uf(jt,D,M).length>0||!(!Ae.enabled||Ae.snapshot)||!!(Ae.snapshot?.activeTurnId||Ae.snapshot?.inputs.some(e=>e.state===`pending`))});function yn(e=D){if(we)return!1;let t=qe.current;return!t.has(e)&&(t.add(e),!0)}function bn(e){qe.current.delete(e)}function xn(e){return qe.current.has(e)}function Sn(){return xn(D)}function Cn(e){Ot(t=>t===e?null:t)}let wn=(0,Q.useMemo)(()=>{let e=I?[...new Set(I.map(e=>e.providerId))].map(e=>({value:e,label:hi(e,H),description:void 0})):pi(H,{enabledOnly:!0}).map(e=>({...e,description:void 0})),t=G.value===`cloud`&&$t?e.filter(e=>e.value===`openpond`):e,n=t.some(e=>e.value===U)?t:[{value:U,label:hi(U,H),description:`Current`},...t],r={value:`setup-provider`,label:`New Model/Provider`,icon:`plus`,separatorBefore:!0};return[...n,r]},[U,H,$t,G.value,I]),Tn=(0,Q.useMemo)(()=>Ci(U,H),[U,H]),En=(0,Q.useMemo)(()=>Za(c,Math.min(Xe,c.length)),[Xe,c]),Dn=En?`${c}:${En.start}:${Math.min(Xe,c.length)}`:null,On=(0,Q.useMemo)(()=>En?Sh({actionCatalog:W,connectedAppMentions:d,mentionApps:u,profileSkills:cn,query:En.query,surface:n,teamMentionMembers:o}):[],[W,d,u,En,cn,n,o]),kn=(0,Q.useMemo)(()=>n===`team`?[]:Sh({actionCatalog:W,connectedAppMentions:d,mentionApps:u,profileSkills:cn,query:``,surface:n,teamMentionMembers:o}).filter(e=>e.kind!==`skill`),[W,d,u,cn,n,o]),An=!!(!ht&&!gn&&En&&Dn&&lt!==Dn&&On.length>0),jn=(0,Q.useMemo)(()=>hf(c,Math.min(Xe,c.length)),[Xe,c]),Mn=jn?`${c}:${jn.start}:${jn.end}`:null,Nn=(0,Q.useMemo)(()=>jn?vf(cn,jn.query):[],[jn,cn]),Pn=!(ht||gn||!jn||!Mn||pt===Mn),Fn=(0,Q.useMemo)(()=>_h(c,Math.min(Xe,c.length)),[Xe,c]),In=Fn?`${c}:${Fn.start}:${Fn.end}`:null,Ln=(0,Q.useMemo)(()=>Fn?bh(W,Fn.query):[],[W,Fn]),Rn=(0,Q.useMemo)(()=>Fn&&n!==`team`?xh(u,Fn.query):[],[Fn,u,n]),zn=(0,Q.useMemo)(()=>Fn&&n!==`team`?yh(Fn.query,sn):[],[Fn,sn,n]),Bn=(0,Q.useMemo)(()=>Fn&&n!==`team`?vf(cn,Fn.query):[],[Fn,cn,n]),Vn=(0,Q.useMemo)(()=>[...Ln.map(e=>({kind:`action`,action:e})),...Bn.map(e=>({kind:`skill`,skill:e})),...zn.map(e=>({kind:`command`,command:e})),...Rn.map(e=>({kind:`app-context`,app:e}))],[Ln,Rn,zn,Bn]),Hn=!(ht||gn||!Fn||!In||dt===In),Un=(0,Q.useMemo)(()=>sn.map(e=>({kind:`command`,command:e})),[sn]),Wn=(0,Q.useMemo)(()=>[...bh(W,``).map(e=>({kind:`action`,action:e})),...xh(u,``).map(e=>({kind:`app-context`,app:e}))],[W,u]),Gn=(0,Q.useMemo)(()=>vf(cn,``).map(e=>({kind:`skill`,skill:e})),[cn]),Kn=(0,Q.useMemo)(()=>{let t=[{id:`add`,items:e===`work`?[{kind:`files`},{kind:`folder`}]:[{kind:`files`}],label:`Add`}];return Wn.length>0&&t.push({id:`slash`,items:Wn.map(e=>({kind:`slash`,item:e})),label:`Agents and actions`,queryScope:`slash`}),Gn.length>0&&t.push({id:`skills`,items:Gn.map(e=>({kind:`slash`,item:e})),label:`Skills`,queryScopes:[`slash`,`mentions`]}),t.push({id:`openpond`,items:Un.map(e=>({kind:`slash`,item:e})),label:`OpenPond`,grid:!0,queryScope:`slash`}),t.push({emptyLabel:`No mentions available`,id:`mentions`,items:kn.map(e=>({kind:`mention`,item:e})),label:`@`}),t},[kn,Un,Gn,Wn,e]),qn=(0,Q.useMemo)(()=>Em(Kn,st),[st,Kn]),Jn=(0,Q.useMemo)(()=>qn.flatMap(e=>e.items),[qn]);(0,Q.useEffect)(()=>{ht&&ot(e=>e<Jn.length?e:0)},[Jn.length,ht]);let Yn=!!h,Xn=Yn&&h?.tone===`active`,Zn=Xn?`Pause goal`:`Stop response`,Qn=Xn?`pause`:`stop`,$n=ne.value!==`none`,er=Uf(jt,D,M),tr=Nt?.scopeKey===D?Nt.draftId:null;function nr(e,t){Mt(n=>Wf(n,e,t,e===D?M:[]))}(0,Q.useLayoutEffect)(()=>{De.current?.resize()},[Ht.length,Vt,_,h,c,yt,xt,Ct]),(0,Q.useEffect)(()=>{if(!R){He.current=!1;return}if(He.current||gn)return;let e=window.requestAnimationFrame(()=>{He.current=!0;let e=document.activeElement;e&&e!==document.body&&e!==document.documentElement||De.current?.focusAtPromptIndex(c.length)});return()=>window.cancelAnimationFrame(e)},[R,gn,c.length]),(0,Q.useEffect)(()=>{if(!z||Ue.current===z||gn)return;let e=window.requestAnimationFrame(()=>{De.current?.element?.isConnected&&(De.current.focusAtPromptIndex(c.length),Ue.current=z)});return()=>window.cancelAnimationFrame(e)},[z,gn,c.length]),(0,Q.useEffect)(()=>{h||At(!1)},[h]),(0,Q.useEffect)(()=>{yt&&!W.some(e=>e.id===yt)&&(bt(null),wt(null))},[W,yt]),(0,Q.useEffect)(()=>{if(!ie||ie.requestId<=Ge.current)return;let e=W.find(e=>e.id===ie.actionId);e&&(Ge.current=ie.requestId,bt(e.id),St(null),wt(0),Et(null),Pe(``),Ze(0),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(0,{afterToken:!0})}))},[W,Pe,ie]),(0,Q.useEffect)(()=>{(on||ln)&&wt(e=>e===null?0:Math.max(0,Math.min(e,c.length)))},[c.length,on,ln]),(0,Q.useEffect)(()=>{if(!p||!_e)return;let e=u.find(e=>e.id===p);(!e||!to(c,e))&&_e(null)},[u,_e,c,p]);let{actionMenuStyle:rr,addMenuStyle:ir,mentionMenuStyle:ar,skillMenuStyle:or}=jh({activeMentionKey:Dn,activeSkillKey:Mn,activeSlashKey:In,addMenuIndex:at,addMenuItems:Jn,addMenuOpen:ht,addMenuPanelRef:ze,addMenuRef:Re,attachmentCount:Ht.length,composerRef:Te,createImproveActive:!!_,goalRuntimeActive:!!h,inputRef:De,inputShellRef:Ee,mentionQuery:En?.query,prompt:c,selectedActionId:yt,selectAddMenuItem:jr,setActionIndex:it,setActionMenuDismissedPrompt:ft,setAddMenuIndex:ot,setAddMenuOpen:gt,setAddMenuQuery:ct,setMentionMenuDismissedPrompt:ut,setMentionIndex:et,setSkillIndex:nt,setSkillMenuDismissedPrompt:mt,skillMatchCount:Nn.length,skillQuery:jn?.query,slashMatchCount:Vn.length,slashQuery:Fn?.query,showActionMenu:Hn,showMentionMenu:An,showSkillMenu:Pn});function sr(){bt(null),St(null),wt(null),Et(null)}function cr(){sr(),Pe(``),Ze(0)}function lr(e){Rt(e.trim()),It(!0)}function ur(){zt||(It(!1),sr())}async function dr(){return await(Xn&&Se?Se():xe())}function fr(e,t){let n=Math.max(0,Math.min(Xe,c.length)),r=t?Math.max(0,Math.min(t.start,c.length)):n,i=t?Math.max(r,Math.min(t.end,c.length)):r,a=c.slice(0,r),o=c.slice(i),s=a&&!/\s$/.test(a)?` `:``,l=o&&!/^\s/.test(o)?` `:``,u=`${s}${`${$a(e)} `}${l}`,d=`${a}${u}${o}`,f=a.length+u.length;return Pe(d),_e?.(e.id),Ze(f),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(f)}),f}function pr(e){if(!En)return;let t=Math.max(0,Math.min(Xe,c.length));fr(e,{start:En.start,end:t})}function mr(e,t,n=null){let r=Math.max(0,Math.min(Xe,c.length)),i=t?Math.max(0,Math.min(t.start,c.length)):r,a=t?Math.max(i,Math.min(t.end,c.length)):i,o=`${c.slice(0,i)}${c.slice(a)}`;return bt(e.id),St(null),wt(i),Et(n?.startsWith(`@`)?n:null),ft(null),Pe(o),Ze(i),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(i,{afterToken:!0})}),i}function hr(e){if(!En)return;let t=Math.max(0,Math.min(Xe,c.length)),n=Math.max(0,Math.min(En.start,c.length)),r=Math.max(n,Math.min(t,c.length));mr(e,{start:n,end:r},c.slice(n,r).trim())}function gr(e,t){let n=Math.max(0,Math.min(Xe,c.length)),r=t?Math.max(0,Math.min(t.start,c.length)):n,i=t?Math.max(r,Math.min(t.end,c.length)):r,a=c.slice(0,r),o=c.slice(i),s=a&&!/\s$/.test(a)?` `:``,l=o&&!/^\s/.test(o)?` `:``,u=`${s}${`${Qa(e)} `}${l}`,d=`${a}${u}${o}`,f=a.length+u.length;return Pe(d),Ze(f),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(f)}),f}function _r(e){if(!En)return;let t=Math.max(0,Math.min(Xe,c.length));gr(e,{start:En.start,end:t})}function vr(e,t){let n=Math.max(0,Math.min(Xe,c.length)),r=t?Math.max(0,Math.min(t.start,c.length)):n,i=t?Math.max(r,Math.min(t.end,c.length)):r,a=e.handle||Xa(e.name),o=c.slice(0,r),s=c.slice(i),l=`${o&&!/\s$/.test(o)?` `:``}@${a} ${s&&!/^\s/.test(s)?` `:``}`,u=`${o}${l}${s}`,d=o.length+l.length;return Pe(u),Ze(d),window.requestAnimationFrame(()=>De.current?.focusAtPromptIndex(d)),d}function yr(e){if(e.kind===`team-member`){if(!En)return;let t=Math.max(0,Math.min(Xe,c.length));vr(e.member,{start:En.start,end:t})}else if(e.kind===`app`)pr(e.app);else if(e.kind===`connected-app`)_r(e.app);else if(e.kind===`skill`){if(!En)return;let t=Math.max(0,Math.min(Xe,c.length));Tr(e.skill,{start:En.start,end:t})}else hr(e.action)}function br(e){Fn&&(ft(null),fr(e,{start:Fn.start,end:Fn.end}))}function xr(e){Fn&&mr(e,Fn)}function Sr(e,t){let n=Math.max(0,Math.min(Xe,c.length)),r=t?Math.max(0,Math.min(t.start,c.length)):n,i=t?Math.max(r,Math.min(t.end,c.length)):r,a=`${c.slice(0,r)}${c.slice(i)}`;return St(e.id),bt(null),wt(r),Et(null),ft(null),Pe(a),Ze(r),e.id===`submit-issue`&&lr(a),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(r,{afterToken:!0})}),r}function Cr(e){Fn&&Sr(e,Fn)}function wr(e){if(e.kind===`command`)Cr(e.command);else if(e.kind===`app-context`)br(e.app);else if(e.kind===`skill`){if(!Fn)return;Tr(e.skill,Fn)}else xr(e.action)}function Tr(e,t){let n=_f(c,t,e);return mt(null),ut(null),ft(null),Pe(n.value),Ze(n.cursor),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(n.cursor)}),n.cursor}function Er(e){jn&&Tr(e,jn)}function Dr(){Ie.current?.click()}function Or(){Le.current?.click()}function kr(e){Be.current=e,ct(``),ot(0)}function Ar(){let e=Math.max(0,Math.min(Xe,c.length)),t=Math.max(0,Math.min(Be.current,c.length));return e>=t?{start:t,end:e}:{start:e,end:e}}function jr(e){let t=Ar();if(gt(!1),ct(``),e.kind===`files`||e.kind===`folder`){if(t.start!==t.end){let e=`${c.slice(0,t.start)}${c.slice(t.end)}`;Pe(e),Ze(t.start)}kr(t.start),e.kind===`folder`?Or():Dr()}else if(e.kind===`slash`){if(e.item.kind===`command`){kr(Sr(e.item.command,t));return}if(e.item.kind===`app-context`){kr(fr(e.item.app,t));return}if(e.item.kind===`skill`){kr(Tr(e.item.skill,t));return}kr(mr(e.item.action,t))}else e.item.kind===`team-member`?kr(vr(e.item.member,t)):e.item.kind===`app`?kr(fr(e.item.app,t)):e.item.kind===`connected-app`?kr(gr(e.item.app,t)):e.item.kind===`skill`?kr(Tr(e.item.skill,t)):kr(mr(e.item.action,t))}let{stageCurrentSteerDraft:Mr,submitImmediateSteer:Nr}=Jd({running:S,scope:D,inbox:Ae,getPrompt:()=>De.current?.getPrompt()??c,getResourceContexts:Fe,hasActions:!!(on||ln),attachmentCount:Ht.length,prepareAttachments:async()=>{Ot(Ht.length?D:null);try{return await Jt()}finally{Cn(D)}},provider:U,model:te,codexPermissionMode:ae,codexReasoningEffort:K,openPondCommandAccessMode:q,getCurrentSubmissionScopeKey:A,onSubmit:be,showToast:ye,begin:e=>!Ye.current.has(e)&&(Ye.current.add(e),!0),finish:e=>{Ye.current.delete(e)},clear:cr,setError:Kt,stageLocal:(e,t,n)=>{nr(D,r=>[...r,Bf(e,{resourceContexts:t,attachments:n})]),window.requestAnimationFrame(()=>De.current?.focusAtPromptIndex(0))}});async function Pr(e){let t=D;if(Nt?.scopeKey===t)return!1;let n=Uf(jt,t,M).find(t=>t.id===e);if(!n)return!1;Pt({draftId:e,scopeKey:t}),Kt(null);try{let r=S,i=await be(n.attachments??[],null,null,{preservePrompt:!0,promptOverride:n.prompt,turnMetadata:{...Gd(n.resourceContexts??[]),...r?{interactionKind:`steer`}:{}}});return nr(t,t=>Hf(t,e,i)),i}catch(e){return Kt(e instanceof Error?e.message:String(e)),!1}finally{Pt(n=>n?.scopeKey===t&&n.draftId===e?null:n)}}function Fr(e){tr!==e&&nr(D,t=>Vf(t,e))}function Ir(e){if(tr===e.id)return;if(yt||xt){ye(`Finish the current composer before editing a queued message.`,`info`);return}if(Ht.length+(e.attachments?.length??0)>ge.maxAttachments){ye(`Remove some attachments before editing this message (maximum ${ge.maxAttachments}).`,`info`);return}let t;try{t=Wd(Fe(),e.resourceContexts??[])}catch{ye(`Send or clear the current resource actions before editing this queued message.`,`info`);return}let n=De.current?.getPrompt()??c,r=n.trim()?`${n}\n\n${e.prompt}`:e.prompt;nr(D,t=>Vf(t,e.id)),Ne.current.set(D,t),Yt(e.attachments??[]),Pe(r),Ze(r.length),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(r.length)})}async function Lr(e={}){if(je.selecting)return!1;let t=D;if(!yn(t))return!1;gt(!1),Kt(null);let{contexts:n,focus:r}=Kd(Ne.current.get(t),Fe(),je.selection),i=qt();try{Ot(i.length>0?t:null);let a;try{a=await Promise.all(i.map(Ke))}finally{Cn(t)}let o=on&&un&&!c.trim()?un:void 0,s=e.promptOverride??o,l=await be(a,on,ln,un||s||e.preservePrompt||n.length||je.selection?{...un?{displayPrompt:un}:{},...s===void 0?{}:{promptOverride:s},...e.preservePrompt?{preservePrompt:!0}:{},turnMetadata:{...Gd(n),...r?{chatResourceFocus:r}:{}},...je.selection?{sessionMetadata:{chatContextSelection:je.selection.target}}:{},onSessionCreated:e=>je.moveToSession(e.id)}:void 0);return l&&Ne.current.get(t)===n&&Ne.current.delete(t),Gt(i,l?`dispose`:`restore`),l&&!Di(on)&&sr(),l}catch(e){return Gt(i,`restore`),Kt(e instanceof Error?e.message:String(e)),!1}finally{bn(t),Cn(t)}}async function Rr(){if(jf(j))return;if(S){ke?await Nr():await Mr();return}if(Sn())return;let e=on||ln?null:Ii(c);ln?.id===`submit-issue`||e?.command===`submit-issue`?lr(e?.command===`submit-issue`?e.args:c):mn||await Lr()}async function zr(e){if(Sn()||zt||je.selecting)return!1;let t=D;if(!yn(t))return!1;Bt(!0),gt(!1),Kt(null);try{let t=await be([],null,Nh,{displayPrompt:`/submit-issue ${e.title.trim()}`,promptOverride:Gi(e)});return t&&(It(!1),sr()),t}catch(e){return Kt(e instanceof Error?e.message:String(e)),!1}finally{bn(t),Bt(!1)}}async function Br(e,t){let n=A?.()??D,r=n!==D&&Oe?O?.getDrafts()[Oe]:void 0,i=n===D?De.current?.getPrompt()??c:typeof r==`string`?r:r?.prompt??(O?``:c),a=Math.max(0,Math.min(Qe.current,i.length)),o=yf(i,e,t.submit?i.length:a),s=await xf({appendToEnd:t.submit,currentScopeKey:n,cursorIndex:a,originScopeKey:D,prompt:i,setOriginDraft:e=>Pe(e),submit:t.submit,submitFromOrigin:e=>S?ke?Nr(e):Mr(e):Lr({preservePrompt:!0,promptOverride:e}),transcript:e});s!==`retained`&&(s===`submitted`?n!==D&&ye(S&&!ke?`Voice message queued in the chat where recording started.`:`Voice message sent to the chat where recording started.`,`success`):(Ze(o.cursorIndex),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(o.cursorIndex)})))}return we?(0,$.jsx)(gh,{connection:V,session:Ce.session,reason:we,onRechecked:Ce.acceptSession,onOpenParent:x}):(0,$.jsxs)(`form`,{ref:Te,className:`composer ${t} ${_?`has-create-runtime`:``} ${Yn?`has-goal-runtime`:``} ${Ht.length>0?`has-attachments`:``} ${on||ln?`has-selected-action`:``} ${Vt?`has-attachment-error`:``} ${ht?`has-add-menu`:``}`,onSubmit:e=>{e.preventDefault(),Rr()},children:[Ce.session?.metadata?.nativeWorkspaceRecovered===!0?(0,$.jsx)(`p`,{className:`composer-workspace-notice`,role:`status`,title:Ce.session.cwd??void 0,children:`Using an app workspace because the original folder is unavailable.`}):null,(0,$.jsx)(`input`,{webkitdirectory:``,ref:Le,className:`composer-file-input`,type:`file`,multiple:!0,tabIndex:-1,onChange:e=>{Ut(Array.from(e.currentTarget.files??[])),e.currentTarget.value=``}}),An&&(0,$.jsx)(Am,{items:On,mentionIndex:$e,onSelect:yr,onSelectIndex:et,style:ar}),Pn&&(0,$.jsx)(lh,{items:Nn,onSelect:Er,onSelectIndex:nt,skillIndex:tt,style:or}),Hn&&(0,$.jsx)(uh,{actionCatalogCount:W.length,actionIndex:rt,items:Vn,onSelect:wr,onSelectIndex:it,style:rr}),(0,$.jsx)(dh,{busy:zt,initialDescription:Lt,open:Ft,onClose:ur,onSubmit:zr}),t===`start`&&(N||n===`chat`)&&(0,$.jsxs)(`div`,{className:`composer-footer`,children:[N?(0,$.jsx)(ep,{busy:v||ne.busy,placement:`top`,state:ne,onChange:ce}):null,re&&le?(0,$.jsx)($f,{busy:v,placement:`top`,state:re,onChange:le}):null,$n?(0,$.jsx)(np,{busy:v,placement:`top`,state:G,onChange:ue}):null]}),_?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Mh,{runtime:_})}):null,Ae.enabled?(0,$.jsx)(qf,{inbox:Ae,canRestore:(e,t)=>{if(Ht.length+t.length>ge.maxAttachments)return ye(`Remove some attachments before editing this message (maximum ${ge.maxAttachments}).`,`info`),!1;try{return Wd(Ne.current.get(D)??[],e),!0}catch{return ye(`Send or clear the current resource actions before editing this queued message.`,`info`),!1}},onRestore:(e,t,n)=>{let r=!A||A()===D,i=r?De.current?.getPrompt()??c:c;Ne.current.set(D,Wd(Ne.current.get(D)??[],t)),Pe(i.trim()?`${i}\n\n${e}`:e),Yt(n),r&&De.current?.focusAtPromptIndex(0)}}):(0,$.jsx)(cp,{drafts:er,sendingDraftId:tr,onDeleteDraft:Fr,onEditDraft:Ir,onSteerDraft:e=>{Pr(e)}}),l?.tone===`warning`?(0,$.jsx)(X,{error:l.message}):l?(0,$.jsx)(`div`,{className:`composer-notice info`,role:`status`,children:l.message}):null,n===`chat`&&ee?(0,$.jsx)(pf,{context:je,resources:Me,sessionId:C??null,busy:v},`${C}:${JSON.stringify(je.selection?.target)}`):null,(Yn||t!==`start`&&U===`codex`&&w)&&(0,$.jsx)(sp,{connection:U===`codex`?V:null,sessionId:w??null,running:S,onPause:dr,onResume:()=>be([],null,null,{preservePrompt:!0,promptOverride:`Continue pursuing the current goal.`}),detailsOpen:kt,goalRuntime:h,objectiveId:rn,subagentRuntime:g,onToggleDetails:()=>At(e=>!e)},w??D),(0,$.jsx)(Eu,{}),(0,$.jsxs)(`div`,{className:`composer-input-shell`,ref:Ee,children:[ht&&n!==`team`&&(0,$.jsx)(km,{id:tn,ariaLabel:`Add to message`,className:`composer-add-command-menu`,menuIndex:at,menuRef:ze,sections:qn,style:ir,variant:`add`,onSelect:jr,onSelectIndex:ot}),Ht.length>0&&(0,$.jsx)(`div`,{className:`composer-attachments`,"aria-label":`Selected attachments`,children:Ht.map(e=>(0,$.jsx)(Je,{attachment:e,onRemove:()=>Wt(e.id)},e.id))}),Vt&&(0,$.jsx)(X,{error:Vt}),(0,$.jsxs)(`div`,{className:`composer-textarea-frame`,onCompositionStartCapture:vn.onCompositionStart,onCompositionEndCapture:vn.onCompositionEnd,onClick:e=>{e.target===e.currentTarget&&De.current?.focusAtPromptIndex(Xe)},children:[(0,$.jsx)(Hd,{next:vn}),(0,$.jsx)(dm,{ref:De,connectedAppMentions:d,ariaDescribedBy:vn.suggestion?vn.descriptionId:void 0,disabled:gn,onCursorChange:Ze,onKeyDown:t=>{vn.onKeyDown(t)||Ld(t,ht)||Rd(t,{open:An,matches:On,index:$e,setIndex:et,select:yr,dismiss:()=>ut(Dn)})||Rd(t,{open:Pn,matches:Nn,index:tt,setIndex:nt,select:Er,dismiss:()=>mt(Mn??c)})||Rd(t,{open:Hn,matches:Vn,index:rt,setIndex:it,select:wr,dismiss:()=>ft(In??c)})||((on||ln)&&t.key===`Backspace`&&Xe===(Ct??0)?(t.preventDefault(),sr()):pm(t.key,t.ctrlKey,t.metaKey,t.shiftKey,e,n,!!ve)?(t.preventDefault(),fm({attachmentsCount:Ht.length,hasSelectedInvocation:!!(on||ln),onSave:ve,onSaved:sr,prompt:c,saving:_t,setSaving:vt,showInfo:e=>ye(e,`info`)})):t.key===`Enter`&&!t.shiftKey&&(t.preventDefault(),pn||Rr()))},onPasteFiles:Ut,onPasteTextAsAttachment:Zt,onPromptChange:(e,t)=>{if(ht){let n=Math.max(0,Math.min(Be.current,e.length));t<n?(Be.current=t,ct(``)):ct(e.slice(n,t))}let r=n===`team`?null:vh(e,t,sn);if(r){let n=`${e.slice(0,r.start)}${e.slice(r.end)}`,i=r.start;Pe(e),Ze(t),window.requestAnimationFrame(()=>{St(r.command.id),bt(null),wt(i),ft(null),Pe(n),Ze(i),r.command.id===`submit-issue`&&lr(n),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(i,{afterToken:!0})})})}else Pe(e)},onTokenPositionChange:e=>{(on||ln)&&(e===null?sr():wt(e))},placeholder:vn.suggestion?``:Qt,prompt:c,token:fn})]}),(0,$.jsx)(sh,{trainingControl:n===`chat`&&ee?(0,$.jsx)(Qd,{context:je,disabled:v,placement:`top`}):null,surface:n,teamUseModel:i,teamUseModelLocked:a,onTeamUseModelChange:s,addFiles:Ut,addMenuId:tn,addMenuOpen:ht,addMenuRef:Re,busy:v,codexPermissionMode:ae,codexReasoningEffort:K,connection:V,contextStatusStyle:an,contextStatusTooltipId:nn,contextWindowStatus:m,disabled:_n,dropdownPlacement:`top`,fileInputRef:Ie,modelValue:en,modelOptions:Tn,hideModelControls:P,modelSelectionDisabled:F,allowedModelRefs:I,executionControl:L,openPondCommandAccessMode:q,showCommandAccess:$t,profileTarget:N?null:re,onCodexPermissionModeChange:fe,onCodexReasoningEffortChange:pe,onOpenPondCommandAccessModeChange:me,onProfileTargetChange:le,onModelChange:de,onOpenFilePicker:Dr,onProviderChange:oe,onProviderSetupOpen:se,onSend:()=>void Rr(),onStop:dr,onToggleAddMenu:()=>{let e=Math.max(0,Math.min(Xe,c.length));ht||(Be.current=e,ct(``),ot(0),gt(!0)),window.requestAnimationFrame(()=>{De.current?.focusAtPromptIndex(e)})},onTranscript:Br,voiceInputChannelKey:j,provider:U,providerSettings:H,providerOptions:wn,running:S,sendDisabled:mn,hasComposerInput:dn,sendTooltip:hn,showToast:ye,stopIcon:Qn,stopLabel:Zn})]})]})}var Lh=(0,Q.memo)(function({draftStore:e,...t}){let n=zh(t.onProviderChange),r=zh(t.onProviderSetupOpen),i=zh(t.onProfileTargetChange),a=zh(t.onWorkspaceTargetChange),o=zh(t.onSubmit),s=zh(t.onStop),c=t.contextWindowStatus,l=(0,Q.useMemo)(()=>({...c}),[c.usedTokens,c.maxTokens,c.percent,c.summary,c.tokensLabel,c.detail,c.tooltip,c.tone]);return(0,$.jsx)(Bh,{...t,draftStore:e,mentionApps:t.mentionApps?.length===0?Rh:t.mentionApps,contextWindowStatus:l,onProviderChange:n,onProviderSetupOpen:r,onProfileTargetChange:i,onWorkspaceTargetChange:a,onSubmit:o,onStop:s})}),Rh=[];function zh(e){let t=(0,Q.useRef)(e);(0,Q.useLayoutEffect)(()=>{t.current=e},[e]);let n=(0,Q.useCallback)((...e)=>t.current?.(...e),[]);return e&&n}var Bh=(0,Q.memo)(function({draftStore:e,...t}){let n=is(e),r=e.getScopeKey(),i=(0,Q.useCallback)(t=>{e.setForScope(r,t)},[r,e]);return(0,$.jsx)(Go,{id:`composer`,children:(0,$.jsx)(Ih,{...t,prompt:n,onPromptChange:i})})}),Vh=new Set(`div span p pre code h1 h2 h3 h4 h5 h6 br hr strong em b i ul ol li table thead tbody tfoot tr th td img section article header footer main figure figcaption`.split(` `)),Hh=new Set([`style`,`title`,`aria-label`,`alt`,`width`,`height`,`colspan`,`rowspan`]);function Uh(e){let t=new DOMParser().parseFromString(e,`text/html`);for(let e of t.body.querySelectorAll(`*`))if(!Vh.has(e.localName))e.remove();else for(let t=e.attributes.length-1;t>=0;t--){let n=e.attributes[t],r=e.localName===`img`&&n.name===`src`&&/^data:image\/(png|jpeg|gif|webp|avif);base64,/i.test(n.value);!Hh.has(n.name)&&!r&&e.removeAttribute(n.name)}return`<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'"><style>body{margin:8px;font:13px/1.5 system-ui;color-scheme:light dark;background:Canvas;color:CanvasText}img{max-width:100%;height:auto}</style></head><body>${t.body.innerHTML}</body></html>`}function Wh({preview:e,label:t}){let n=/^\s*<[a-z][\w-]*\b[^>]*>/i.test(e),r=(0,Q.useMemo)(()=>n?Uh(e):``,[n,e]);return n?(0,$.jsx)(`iframe`,{className:`native-question-preview`,title:`${t} preview`,sandbox:``,referrerPolicy:`no-referrer`,srcDoc:r}):(0,$.jsx)(`div`,{className:`native-question-preview`,children:(0,$.jsx)(wa,{content:e})})}function Gh({id:e,value:t,disabled:n,connection:r,showToast:i,onChange:a,activeVoiceChannel:o,onVoiceActiveChange:s}){let c=`question-answer:${(0,Q.useId)()}`,l=(0,Q.useRef)(null),u=(0,Q.useRef)({value:t,disabled:n,onChange:a});u.current={value:t,disabled:n,onChange:a};let d=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>(d.current=!0,()=>{d.current=!1,kf(c)}),[c]),(0,Q.useEffect)(()=>{n&&kf(c)},[c,n]);let f=(0,Q.useCallback)(e=>s(c,e),[c,s]),p=(0,Q.useCallback)((e,{submit:t})=>{if(!d.current||u.current.disabled)return;let n=yf(u.current.value,e,l.current?.selectionStart??u.current.value.length);u.current.onChange(n.value.slice(0,8e3),t)},[]);return(0,$.jsxs)(`div`,{className:`native-question-custom`,children:[(0,$.jsx)(`label`,{className:`sr-only`,htmlFor:e,children:`Your answer`}),(0,$.jsx)(`textarea`,{ref:l,id:e,maxLength:8e3,rows:2,value:t,placeholder:`Write your answer…`,disabled:n,onChange:e=>a(e.target.value)}),(0,$.jsx)(`div`,{className:`native-question-answer-controls`,children:n?null:(0,$.jsx)(th,{connection:r,showToast:i,buttonClassName:`native-question-mic`,disabled:n||!r||!!(o&&o!==c),transcriptionChannelKey:c,onActiveChange:f,onTranscript:p})})]})}function Kh({questions:e,answers:t,onChange:n,onSubmit:r,...i}){let a=(0,Q.useRef)(t);return a.current=t,(0,$.jsx)(`div`,{className:`native-question-fields`,children:e.map(e=>(0,$.jsx)(qh,{question:e,...i,onChange:(t,i=!1)=>{let o={...a.current,[e.question]:t};a.current=o,n(o),i&&r(o)}},e.question))})}function qh({question:e,disabled:t,connection:n,showToast:r,onChange:i,activeVoiceChannel:a,onVoiceActiveChange:o}){let s=(0,Q.useId)(),[c,l]=(0,Q.useState)([]),[u,d]=(0,Q.useState)(e.options.length===0),[f,p]=(0,Q.useState)(``);function m(t){let n=e.multiSelect&&!u?c.includes(t)?c.filter(e=>e!==t):[...c,t]:[t];l(n),d(!1),i(n.map(t=>e.options[t].label).join(`, `))}return(0,$.jsxs)(`fieldset`,{disabled:t,children:[(0,$.jsxs)(`legend`,{children:[e.header?(0,$.jsx)(`small`,{children:e.header}):null,e.question]}),(0,$.jsxs)(`div`,{className:`native-question-options`,children:[e.options.map((e,t)=>(0,$.jsxs)(`button`,{type:`button`,className:`native-question-option`,"aria-pressed":!u&&c.includes(t),onClick:()=>m(t),children:[(0,$.jsx)(`span`,{children:e.label}),e.description?(0,$.jsx)(`small`,{children:e.description}):null]},t)),e.options.length?(0,$.jsx)(`button`,{type:`button`,className:`native-question-option custom`,"aria-pressed":u,onClick:()=>{d(!0),i(f)},children:`Write your own answer`}):null]}),e.multiSelect&&!u?(0,$.jsx)(`small`,{children:`Select one or more.`}):null,u?(0,$.jsx)(Gh,{id:s,value:f,disabled:t,connection:n,showToast:r,activeVoiceChannel:a,onVoiceActiveChange:o,onChange:(e,t)=>{p(e),i(e,t)}},s):c.map(t=>{let n=e.options[t];return n.preview?(0,$.jsx)(Wh,{preview:n.preview,label:n.label},t):null})]})}function Jh({approval:e,questions:t,canAccept:n,canSkip:r,connection:i,showToast:a,onResolve:o}){let[s,c]=(0,Q.useState)({}),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(null),p=(0,Q.useRef)(!1),m=(0,Q.useCallback)((e,t)=>{f(n=>t?e:n===e?null:n)},[]),h=e=>t.every(t=>e[t.question]?.trim());async function g(t,i=s){if(!p.current&&(t!==`accept`||n&&h(i))&&(t!==`decline`||r)){p.current=!0,u(!0);try{await o(e.id,t,t===`accept`?i:void 0)}catch{p.current=!1,u(!1)}}}return(0,$.jsxs)(`section`,{className:`native-question-request`,"data-notification-approval":e.id,"aria-label":`Questions from agent`,"aria-busy":l,children:[(0,$.jsx)(`div`,{className:`native-question-body`,children:(0,$.jsx)(Kh,{questions:t,answers:s,disabled:l,connection:i,showToast:a,onChange:c,onSubmit:e=>void g(`accept`,e),activeVoiceChannel:d,onVoiceActiveChange:m})}),(0,$.jsxs)(`div`,{className:`native-question-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`native-question-skip`,disabled:l||!r,onClick:()=>void g(`decline`),children:`Skip`}),(0,$.jsxs)(`button`,{type:`button`,className:`native-question-send`,disabled:l||!n||!d&&!h(s),onClick:()=>{d&&jf(d)||g(`accept`)},children:[(0,$.jsx)(Ql,{size:14}),(0,$.jsx)(`span`,{children:l?`Sending`:`Send`})]})]})]})}function Yh({approval:e,onResolve:t,connection:n,showToast:r}){let[i,a]=(0,Q.useState)(null);if((0,Q.useEffect)(()=>{a(null)},[e?.id]),!e||e.kind===`create_plan`)return null;let o=Zh(e.detail),s=typeof e.providerRequestId==`string`&&e.providerRequestId.startsWith(`native-agent:`),c=[],l=[],u=null;if(s)try{let t=JSON.parse(e.detail);c=t.options??[],l=t.questions??[],(t.toolCall?.toolName??t.toolCall?.title)===`ExitPlanMode`&&(u=typeof t.toolCall?.rawInput?.plan==`string`?t.toolCall?.rawInput.plan:``)}catch{}if(l.length)return(0,$.jsx)(Jh,{approval:e,questions:l,canAccept:c.some(e=>e.kind===`allow_once`),canSkip:c.some(e=>e.kind===`reject_once`),connection:n,showToast:r,onResolve:t},e.id);let d=s?c.some(e=>e.kind===`allow_always`):e.kind!==`subagent_patch_apply`,f=c.find(e=>e.kind===`allow_always`)?.name;async function p(n){if(e&&!i){a(n);try{await t(e.id,n)}catch{a(null)}}}return(0,$.jsx)(`div`,{"data-notification-approval":e.id,className:`approval-request-shell ${u===null?``:`native-input-shell`}`,role:`status`,"aria-live":`polite`,children:(0,$.jsxs)(`section`,{className:`approval-request-card`,"aria-label":u===null?`${Xh(e.kind)} approval request`:`Plan review`,children:[(0,$.jsxs)(`div`,{className:`approval-request-copy`,children:[(0,$.jsx)(`div`,{className:`approval-request-header`,children:(0,$.jsx)(`span`,{children:u===null?Xh(e.kind):`Plan review`})}),u===null?(0,$.jsx)(`code`,{className:`approval-request-title`,title:e.title,children:e.title}):null,u===null&&o&&o!==e.title&&(0,$.jsxs)(`details`,{className:`approval-request-details`,children:[(0,$.jsx)(`summary`,{children:`Details`}),(0,$.jsx)(`pre`,{children:o})]}),u===null?null:(0,$.jsx)(`div`,{className:`native-plan-review`,children:u?(0,$.jsx)(wa,{content:u}):(0,$.jsx)(`p`,{children:`Claude is ready to leave plan mode. Review the proposed plan in the conversation before continuing.`})})]}),(0,$.jsxs)(`div`,{className:`approval-request-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`approval-action primary`,disabled:!!i||s&&!c.some(e=>e.kind===`allow_once`),onClick:()=>void p(`accept`),children:[(0,$.jsx)(Ro,{size:14}),(0,$.jsx)(`span`,{children:i===`accept`?`Sending`:u===null?`Approve`:`Approve plan`})]}),d?(0,$.jsxs)(`button`,{type:`button`,className:`approval-action`,title:s?f:`Approve for the rest of this session`,disabled:!!i,onClick:()=>void p(`acceptForSession`),children:[(0,$.jsx)(eu,{size:14}),(0,$.jsx)(`span`,{children:i===`acceptForSession`?`Approving`:s?f:`Session`})]}):null,(0,$.jsxs)(`button`,{type:`button`,className:`approval-action muted`,disabled:!!i||s&&!c.some(e=>e.kind===`reject_once`),onClick:()=>void p(`decline`),children:[(0,$.jsx)(tu,{size:14}),(0,$.jsx)(`span`,{children:i===`decline`?`Sending`:u===null?`Deny`:`Keep planning`})]}),(0,$.jsx)(`button`,{type:`button`,className:`approval-action icon-only`,title:s?`Dismiss request`:`Cancel task`,"aria-label":s?`Dismiss request`:`Cancel task`,disabled:!!i,onClick:()=>void p(`cancel`),children:(0,$.jsx)(Ua,{size:15})})]})]})})}function Xh(e){return e===`create_plan`?`Plan review`:e===`subagent_patch_apply`?`Subagent patch`:e===`file_change`||e===`legacy_patch`?`File change`:e===`permissions`?`Permissions`:e===`user_input`?`Input needed`:`Command`}function Zh(e){let t=e.trim();if(!t)return``;try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}}function Qh({resolution:e,onSelect:t,onClose:n}){let r=(0,Q.useRef)(null),i=(0,Q.useId)();return(0,Q.useEffect)(()=>{let e=r.current;return e?.showModal(),()=>e?.close()},[]),(0,$.jsxs)(`dialog`,{ref:r,className:`chat-file-resolution`,"aria-labelledby":i,onCancel:n,children:[(0,$.jsx)(`h2`,{id:i,children:`Choose a file`}),(0,$.jsxs)(`p`,{children:[`Matches for `,(0,$.jsx)(`strong`,{children:e.requestedPath}),` in this project's folders:`]}),e.truncated?(0,$.jsx)(`p`,{children:`The search reached its limit. More matches may exist.`}):null,(0,$.jsx)(`div`,{className:`chat-file-resolution-options`,children:e.candidates.map(e=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>t(e),children:e},e))}),(0,$.jsx)(`button`,{type:`button`,className:`git-dialog-secondary`,onClick:n,children:`Cancel`})]})}var $h=/\.(?:m4v|mov|mp4|webm)$/i;function eg(e){return $h.test(e.trim().split(/[?#]/,1)[0]??``)}function tg(e,t){let n=e.trim();if(!n||!eg(n))return null;if(/^file:\/\//i.test(n))try{n=decodeURIComponent(new URL(n).pathname)}catch{n=n.replace(/^file:\/\//i,``)}if(/^\//.test(n)||/^[A-Za-z]:[\\/]/.test(n))return n;let r=t?.trim().replace(/[\\/]+$/,``);return r?`${r}/${n.replace(/^\.\//,``)}`:null}function ng({conversationKey:e,connection:t,handleOpenBrowserLink:n,activeWorkspaceAppId:r,rightSidebarUsesSandbox:i,rightSidebarSandboxId:a,onShowDiffPanel:s,showToast:c,workspaceRootPath:l,setOpenDiffFileRequest:u}){let[d,f]=(0,Q.useState)(null),p=(0,Q.useRef)(0),m=(0,Q.useRef)(0),h=(0,Q.useRef)(0),g=ra(t);(0,Q.useEffect)(()=>(p.current++,f(null),()=>{p.current++}),[g,r,e,a]),(0,Q.useEffect)(()=>(m.current++,()=>{m.current++}),[g,e]);let _=(0,Q.useCallback)(async(e,d)=>{if(/[\\/]$/.test(e)){let t=/^(?:[~/\\]|[A-Za-z]:)/.test(e)?e:l?`${l}/${e}`:e;ga(t).then(e=>{e||c(`Open this folder in the desktop app on the machine where it was created.`,`error`)});return}let f=d?.local?null:d?.sandboxId??(i?a:null),p=f??(d?.local?va(e):r);if(fa(e)&&!d?.source&&t&&p){ya(t,p,e,f?`sandbox`:`local`).then(e=>n(e)).catch(e=>c(e instanceof Error?e.message:`Could not open HTML preview.`,`error`));return}let g=tg(e,l);if(g&&t){Eo.signLocalVideoUrl(t,{path:g}).then(({url:e})=>n(e)).catch(e=>{c(e instanceof Error?e.message:`Could not open this video.`,`error`)});return}if(/\.pptx$/i.test(e)&&o(()=>import(`./WorkspacePresentationPreview-sP7JUT7m.js`),__vite__mapDeps([69,1,2,3,16,20,4,5,6,21,22,13,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,18,42,43,44,45,46,47,48,19,49,50,51,52,53,54,55,56,70,71,72])).catch(()=>{}),/\.docx$/i.test(e)&&(o(()=>import(`./FilePagePreview-B7bWObJN.js`),__vite__mapDeps([73,1,2,3,16,20,4,5,6,21,22,13,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,18,42,43,44,45,46,47,48,19,49,50,51,52,53,54,55,56,74])).catch(()=>{}),o(()=>import(`./docx-preview-Blk_WGfs.js`),__vite__mapDeps([75,1,72])).catch(()=>{})),d?.sandboxId&&t){let n=m.current,r=++h.current;s(),u({id:++h.current,loadId:r,sandboxId:d.sandboxId,path:e,file:Xo(e),loading:!0});try{let i=await xa(t,d.sandboxId,e);if(n!==m.current)return;let a=bo(i.path)&&i.content?`data:image/${/\.jpe?g$/i.test(e)?`jpeg`:e.split(`.`).pop()};base64,${i.content}`:void 0;u({id:++h.current,loadId:r,sandboxId:d.sandboxId,path:i.path,file:i,imageUrl:a})}catch(t){n===m.current&&u({id:++h.current,loadId:r,sandboxId:d.sandboxId,path:e,file:Xo(e),error:t instanceof Error?t.message:`Could not open this file.`})}return}let _=ma(e,{workspaceRootPath:l}),v=d?.local?e:_?.path??e,y=va(v);if((d?.local||!r&&!i)&&t&&y){let e=m.current,n=++h.current;s(),u({id:++h.current,loadId:n,sandboxId:null,path:v,file:Xo(v),loading:!0});try{let r=bo(v)?await Eo.signLocalImageUrl(t,{path:v}):null,i=r?Xo(v):await Eo.workspaceFile(t,y,v);if(e!==m.current)return;u({id:++h.current,loadId:n,sandboxId:null,path:i.path,file:i,imageUrl:r?.url})}catch(t){e===m.current&&u({id:++h.current,loadId:n,sandboxId:null,path:v,file:Xo(v),error:t instanceof Error?t.message:`Could not open this file.`})}}else s(),u({id:++h.current,path:d?.source&&fa(e)?(_?.path??e).replace(/[?#].*$/,``):_?.path??e,source:d?.source})},[t,n,r,i,a,s,c,l,u]),v=(0,Q.useCallback)((e,a)=>{let o=++p.current;if(f(null),/^https?:\/\//i.test(e)){n(e);return}let s=!a?.sandboxId&&!!va(e)&&(!i||!/^\/workspace(?:\/|$)/.test(e));if(a?.local||a?.sandboxId||s||!t||!r||i){_(e,s?{...a,local:!0}:a);return}let l=ma(e)?.path??e,u=fa(l)?l.match(/[?#].*$/)?.[0]??``:``,d=u?l.slice(0,-u.length):l;Eo.resolveWorkspaceFile(t,r,d).then(t=>{o===p.current&&(t.status===`resolved`?_(t.kind===`directory`?`${t.path}/`:`${t.path}${u}`,a):t.candidates.length?f({requestedPath:e,candidates:t.candidates.map(e=>`${e}${u}`),truncated:t.truncated,source:a?.source}):c(t.truncated?`The project search reached its limit. Open this file using its full path.`:`Could not find ${e} in this project's folders. Try its full path.`,`error`))}).catch(e=>{o===p.current&&c(e instanceof Error?e.message:`Could not locate this file.`,`error`)})},[t,r,i,_,n,c]);return{handleOpenFileInSidebar:v,fileResolution:d,dismissFileResolution:(0,Q.useCallback)(()=>f(null),[]),selectFileResolution:(0,Q.useCallback)(e=>{let t=d?.source;f(null),v(e,{source:t})},[d,v])}}function rg(e){let t=[];if(e.localWorkspaceId&&t.push({value:`local`,label:`Local`}),(e.sandboxSourceAvailable??!!e.sandboxWorkspaceId)&&t.push({value:`sandbox`,label:`Sandbox`}),t.length===0)return{source:null,options:t};let n=new Set(t.map(e=>e.value));if(e.override&&n.has(e.override))return{source:e.override,options:t};let r=e.workspaceTarget===`local`?`local`:`sandbox`;return n.has(r)?{source:r,options:t}:{source:t[0].value,options:t}}var ig=new Set([`create`,`edit`,`help`,`list`]);function ag(e,t,n=null){return og(e)}function og(e){let t=e.trim();if(!t)return`/skill`;let[n=``]=t.split(/\s+/,1);return ig.has(n.toLowerCase())?`/skill ${t}`:`/skill create ${t}`}async function sg(e){let t=e.session?.currentProfile??null,n=e.session?await e.patchSession(e.session.id,e.ref):null;try{return{selected:await e.selectProfile(e.ref),session:n}}catch(r){if(n)try{await e.patchSession(n.id,t)}catch{}throw r}}function cg(e,t){if(!e||!t)return null;let n=new Set(e.sources.filter(e=>e.sessionId===t).map(e=>e.id));return n.size?e.creations.find(e=>e.request.sourceIds.some(e=>n.has(e)))??null:null}function lg(e){let[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(null),d=(0,Q.useRef)(null),f=(0,Q.useRef)(0),p=(0,Q.useCallback)(async(t,n={})=>{if(!e){i(null),c(`OpenPond App server is not connected.`);return}let r=f.current+1;f.current=r,n.silent||o(!0),c(null);try{let n=await Eo.getCreateImproveCandidateDiff(e,t.runId,t.candidateId),a=d.current;if(r!==f.current||a?.runId!==t.runId||a.candidateId!==t.candidateId)return;i(n)}catch(e){if(r!==f.current)return;c(e instanceof Error?e.message:String(e))}finally{r===f.current&&!n.silent&&o(!1)}},[e]),m=(0,Q.useCallback)(e=>{let t=d.current;e&&t?.runId===e.runId&&t.candidateId===e.candidateId||(d.current=e,n(e),u(null),e?(i(t=>t?.appId===ug(e)?t:null),p(e)):(f.current+=1,i(null),c(null),o(!1)))},[p]),h=(0,Q.useCallback)(async(e={})=>{let t=d.current;t&&await p(t,e)},[p]),g=(0,Q.useCallback)(e=>{u({id:Date.now(),path:e})},[]);return(0,Q.useEffect)(()=>{e||m(null)},[m,e]),{selection:t,diff:r,loading:a,error:s,openFileRequest:l,activate:m,refresh:h,openFile:g}}function ug(e){return`candidate:${e.runId}:${e.candidateId}`}function dg(e){let{activeModel:t,activeProvider:n,bootstrap:r,codexPermissionMode:i,codexReasoningEffort:a,connection:o,onOpenRightChatForSession:s,onPayload:c}=e,l=(0,Q.useCallback)(async e=>{if(!o||!r)throw Error(`OpenPond is still connecting.`);let i=r.profile;if(i.mode!==`local`||!i.repoPath)throw Error(`A local Git-backed Profile is required to change an Agent.`);let l=e.authoringModel??wi(n,t,r.providers);if(!l)throw Error(`Choose a model before changing an Agent.`);let u=await Eo.createSession(o,{provider:l.providerId,modelRef:l,systemKind:`openpond.lab`,hiddenFromDefaultSidebar:!0,title:`${e.operation===`create`?`New`:`Improve`} Agent · ${e.objective.slice(0,80)}`,cwd:i.repoPath,metadata:{source:e.operation===`create`?`lab_agent_create`:`lab_agent_improve`,profileId:i.activeProfile??`default`,targetAgentId:e.agentId??null}}),d=e.objective.trim();if(!d)throw Error(e.operation===`create`?`Describe what the Agent should do.`:`Describe what the Agent could do better.`);if(l.providerId===`codex`)throw Error(`Agent authoring uses OpenPond's bundled authoring skill. Choose a hosted model.`);let f=e.operation===`create`?`/agent create ${d}`:`/agent improve ${e.agentId??``} ${d}`,p=await Eo.sendTurn(o,u.id,{prompt:f,model:l.modelId,modelRef:l,approvalPolicy:`never`,sandbox:`workspace-write`,codexPermissionMode:`default`,codexReasoningEffort:a});if(p.status===`failed`)throw Error(p.error??`OpenPond could not complete the Agent authoring turn.`);c(await Eo.bootstrap(o)),s(u.id,u)},[t,n,r,i,a,o,s,c]);return{createAgentFromLab:(0,Q.useCallback)((e,t,n)=>l({objective:e,operation:`create`,authoringRunId:t,authoringModel:n}),[l]),improveAgentFromLab:(0,Q.useCallback)((e,t,n,r,i)=>l({agentId:e,agentName:n,objective:t,operation:`improve`,authoringRunId:r,authoringModel:i}),[l])}}function fg(e,t,n=!0){let r=u(),i=[`ponder-hosted-sandboxes`,ra(e),t],a=S({queryKey:i,enabled:n,staleTime:5e3,refetchInterval:n?3e4:!1,queryFn:({signal:t})=>Y(e,`/v1/ponder/local/hosted-sandboxes`,{signal:t})}),o=ds({mutationFn:async t=>{if(!a.data)throw Error(`Wait for hosted sandbox availability to load.`);return Y(e,`/v1/ponder/local/hosted-sandboxes`,{method:`POST`,body:JSON.stringify({enabled:t,revision:a.data.revision,...t?{teamId:a.data.account?.teamId??null,accountId:a.data.account?.id,apiBaseUrl:a.data.account?.apiBaseUrl}:{}})})},onSuccess:e=>r.setQueryData(i,e),onError:()=>{r.invalidateQueries({queryKey:i})}});return Ka(a.error),Ka(o.error),{state:a.data,loading:a.isPending,saving:o.isPending,setEnabled:e=>o.mutate(e),refetch:a.refetch}}function pg({connection:e,accountScopeKey:t}){let n=fg(e,t),r=!n.state||n.saving||!n.state.available&&!n.state.enabled;return(0,$.jsxs)(`div`,{className:`ponder-setup-card`,children:[(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`strong`,{children:`Hosted sandboxes`}),(0,$.jsx)(`input`,{type:`checkbox`,role:`switch`,"aria-label":`Hosted sandboxes`,checked:n.state?.enabled??!1,disabled:r,onChange:e=>n.setEnabled(e.currentTarget.checked)})]}),(0,$.jsx)(`p`,{children:`Allow Pal to send selected assignments and their required project context to hosted Work environments. Hosted usage may incur charges.`}),(0,$.jsx)(`small`,{children:n.loading?`Checking availability…`:n.state?.enabled?`Enabled for this account. Turning this off prevents new hosted assignments; existing work stays available.`:n.state?.reason??`Off. Turn on to allow hosted assignments.`}),!n.state&&!n.loading?(0,$.jsx)(`button`,{type:`button`,className:`git-dialog-secondary`,onClick:()=>void n.refetch(),children:`Check availability`}):null]})}function mg(e){let t=[],n=new Map,r=new Map;for(let i of e){if(i.source===`ponder-recommendation`)continue;let e=Wr.safeParse(i.metadata.ponderLocalMessage),a=e.success?e.data:null,o=i.metadata.ponderMessage;if(a||o){let e=a??o,s=a?.sessionId??o.conversationId,c=e.status===`resolved`||e.status===`completed`?`resolved`:e.status===`consumed`||e.status===`included`?`included`:e.status===`cancelled`?`cancelled`:e.status===`failed`||e.status===`rejected`?`rejected`:`pending`;if(t.push({id:i.id,role:`task_message`,content:e.body,timestamp:i.createdAt,taskMessagePresentation:{input:{body:e.body,state:c,error:null},direction:e.direction,peer:{sessionId:s,title:e.title,provider:a?`local`:`openpond`}}}),a&&r.set(s,a),a?.outputs.length||o?.outputFileIds.length){let e=`${i.id}:outputs`;t.push({id:e,role:`resources`,timestamp:i.createdAt}),n.set(e,i)}}else(i.role===`user`||i.role===`assistant`&&i.text.trim())&&t.push({id:i.id,role:i.role,content:i.text,timestamp:i.createdAt,finalAnswer:i.role===`assistant`,footerCacheSummary:i.metadata.kvCacheSummary})}return{messages:t,sources:n,localPeers:r}}function hg(e){return e.state===`proposed`&&[`waiting_input`,`waiting_approval`,`cancelled`].includes(e.target.status)}function gg({items:e,busy:t,editingId:n,onEdit:r,onSend:i,onDismiss:a,onOpen:o}){return e.length?(0,$.jsx)(`section`,{className:`ponder-recommendations`,"aria-label":`Pal recommendations`,children:e.map(e=>(0,$.jsxs)(`article`,{className:`ponder-recommendation`,"data-state":e.state,children:[(0,$.jsx)(`button`,{type:`button`,className:`ponder-recommendation-target`,onClick:()=>o(e.target.conversationId),children:e.target.title}),(0,$.jsx)(`p`,{children:e.summary}),e.submittedText||e.proposedText?(0,$.jsx)(`blockquote`,{children:e.submittedText??e.proposedText}):null,(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Why Pal suggested this`}),e.evidence.map(e=>(0,$.jsx)(`p`,{children:e.excerpt},e.id))]}),[`proposed`,`failed`,`stale`,`submitting`].includes(e.state)?(0,$.jsxs)(`div`,{className:`ponder-recommendation-actions`,children:[e.state===`proposed`&&e.proposedText?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,disabled:!!t,onClick:()=>r(e),children:n===e.id?`Editing below`:`Edit`}),(0,$.jsx)(`button`,{type:`button`,disabled:!!t||hg(e),onClick:()=>i(e),children:t===e.id?`Sending…`:n===e.id?`Send edited message`:`Send`})]}):null,(e.state===`failed`||e.state===`submitting`)&&e.submittedText&&e.submissionRevision!==null?(0,$.jsx)(`button`,{type:`button`,disabled:!!t,onClick:()=>i(e),children:t===e.id?`Retrying…`:`Retry reviewed message`}):null,hg(e)?(0,$.jsx)(`small`,{role:`status`,children:`Resolve this task's wait or cancellation before sending a new message.`}):null,e.state===`submitting`?(0,$.jsx)(`small`,{role:`status`,children:`Awaiting task acknowledgment`}):(0,$.jsx)(`button`,{type:`button`,disabled:!!t,onClick:()=>a(e),children:`Dismiss`}),e.state===`stale`?(0,$.jsx)(`small`,{role:`status`,children:`Task changed — review its latest state`}):null]}):(0,$.jsx)(`small`,{role:`status`,children:e.state===`submitted`?`Message submitted to the task`:e.state===`stale`?`Task changed — review the latest task before sending`:e.state.replaceAll(`_`,` `)}),e.error?(0,$.jsx)(`p`,{role:`alert`,children:e.error}):null]},e.id))}):null}function _g(e,t){let[n,r]=(0,Q.useState)([]),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(null),c=(0,Q.useRef)({connection:e,bindingId:t});c.current={connection:e,bindingId:t};let l=(0,Q.useRef)(!1),u=(0,Q.useRef)(!0),d=(0,Q.useCallback)(async n=>{if(!t)return;let i=await Y(e,`/v1/ponder/recommendations`,{signal:n});u.current&&!n?.aborted&&c.current.connection===e&&c.current.bindingId===t&&i.bindingId===t&&(r(i.items),a(null))},[e,t]);return(0,Q.useEffect)(()=>{if(u.current=!0,r([]),a(null),s(null),!t)return()=>{u.current=!1};let e=new AbortController,n=!1,i=async()=>{if(!n){n=!0;try{await d(e.signal)}catch(t){e.signal.aborted||a(t instanceof Error?t.message:`Unable to read recommendations.`)}finally{n=!1}}};i();let o=window.setInterval(()=>void i(),5e3);return()=>{u.current=!1,e.abort(),window.clearInterval(o)}},[t,d]),{items:n,error:i,busy:o,action:(0,Q.useCallback)(async(n,r,i)=>{if(l.current||!t)return!1;if(r===`send`&&hg(n))return a(`Resolve this task's wait or cancellation before sending a new message.`),!1;let o=r===`send`&&(n.state===`submitting`||n.state===`failed`);if(o&&(!n.submittedText||n.submissionRevision===null))return!1;let f=o?n.submissionRevision:n.revision,p=o?n.submittedText:i;l.current=!0,s(n.id);try{return await Y(e,`/v1/ponder/recommendations/${encodeURIComponent(n.id)}/action`,{method:`POST`,body:JSON.stringify({action:r,expectedRevision:f,...p===void 0?{}:{message:p}})}),!u.current||c.current.connection!==e||c.current.bindingId!==t?!1:(await d(),u.current&&c.current.connection===e&&c.current.bindingId===t)}catch(n){return c.current.connection===e&&c.current.bindingId===t&&a(n instanceof Error?n.message:`Recommendation action failed.`),!1}finally{l.current=!1,c.current.connection===e&&c.current.bindingId===t&&s(null)}},[t,e,d]),refresh:d}}function vg({connection:e,work:t,localWork:n,busy:r,onOpenWork:i,onOpenLocalWork:a,onOpenLocalOutput:o,onOpenOutput:s}){let[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(null),f=(0,Q.useRef)({connection:e,mounted:!0,inFlight:!1});f.current.connection!==e&&(f.current={connection:e,mounted:!0,inFlight:!1}),(0,Q.useEffect)(()=>{let e=f.current;return e.mounted=!0,l(null),d(null),()=>{e.mounted=!1}},[e]);let p=[...t.flatMap(e=>e.deliveries.filter(e=>e.status===`attention`&&e.attentionAt).map(t=>({task:e,delivery:t,kind:`hosted`}))),...n.flatMap(e=>e.deliveries.filter(e=>e.status===`attention`&&e.attentionAt).map(t=>({task:e,delivery:t,kind:`local`})))];async function m(t){let n=f.current;if(!t.attentionAt||n.inFlight)return;let r=()=>n.mounted&&f.current===n;n.inFlight=!0,l(t.inputId),d(null);try{await Y(e,`/v1/ponder/results/retry`,{method:`POST`,body:JSON.stringify({inputId:t.inputId,attentionAt:t.attentionAt,priorTurnId:t.ponderTurnId})})}catch(e){r()&&d(e instanceof Error&&e.message===`hosted_work_model_not_available`?`The selected model is unavailable. Choose an available model, then retry.`:`The discussion could not be started. Refresh and try again.`)}finally{n.inFlight=!1,r()&&l(null)}}return p.length===0?null:(0,$.jsxs)(`section`,{"aria-label":`Saved results needing discussion`,"aria-live":`polite`,children:[p.map(e=>(0,$.jsxs)(`div`,{className:`ponder-desktop-attention`,children:[(0,$.jsxs)(`p`,{children:[`The result from`,` `,(0,$.jsx)(`button`,{type:`button`,onClick:()=>e.kind===`hosted`?i(e.task.conversationId):a(e.task),children:e.task.title}),` `,`is saved.`,e.delivery.attentionReason===`model_unavailable`?` The selected model was unavailable.`:e.delivery.attentionReason===`chat_cancelled`?` The discussion was cancelled.`:` The discussion failed.`]}),e.delivery.outputs.map(t=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>e.kind===`local`?o({...e.task,turnId:e.delivery.localTurnId},t.id):s(t.id),children:[t.title,` · Download`]},t.id)),(0,$.jsx)(`button`,{type:`button`,disabled:r||c!==null,onClick:()=>void m(e.delivery),children:c===e.delivery.inputId?`Starting discussion…`:`Retry discussion`})]},e.delivery.inputId)),u?(0,$.jsx)(X,{error:u}):null]})}function yg({message:e,work:t,onOpenOutput:n,onOpenLocalOutput:r}){let i=Wr.safeParse(e.metadata.ponderLocalMessage),a=i.success?i.data:null;return(0,$.jsxs)(`div`,{className:`ponder-message-destination`,children:[e.metadata.ponderMessage?.outputFileIds.map(e=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>n(e),children:t.flatMap(e=>e.deliveries.flatMap(e=>e.outputs)).find(t=>t.id===e)?.title??`Saved file`},e)),a?.outputs.map(e=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>r(a,e.id),children:[e.title,` · Download`]},e.id))]})}function bg(e){let t=e.deliveries[0]?.outcome;if(t===`completed`)return`Completed`;if(t===`failed`)return`Failed`;if(t===`cancelled`)return`Stopped`;switch(e.status){case`ready`:return`Waiting to start on desktop`;case`dispatching`:return`Starting on desktop`;case`admitted`:return`Waiting for result`;case`completed`:return`Completed`;case`failed`:return`Failed to start`;case`cancelled`:return`Stopped`;case`expired`:return`Couldn’t start before the request expired`;case`attention`:return`Needs attention`;default:return`Checking task status`}}function xg({items:e,workflow:t,sessions:n,onOpenTask:r}){let i=t?new Set([t.prerequisite.sessionId,t.successor.sessionId,t.workflow?.preparationSessionId]):null,a=[...new Map([...e].reverse().filter(e=>e.sessionId&&(!i||i.has(e.sessionId))).map(e=>[e.sessionId,e])).values()].reverse();if(!a.length)return null;let o=new Map(n.map(e=>[e.id,e]));return(0,$.jsxs)(`div`,{className:`assistant-sources ponder-agent-sources`,"aria-label":`Conversations started`,children:[(0,$.jsx)(`h3`,{children:`Conversations started`}),(0,$.jsx)(`div`,{className:`assistant-source-stack`,children:a.map(e=>{let t=o.get(e.sessionId);return(0,$.jsxs)(`button`,{type:`button`,className:`assistant-source-pill`,title:`${e.title} · ${bg(e)}`,"aria-label":`Open ${e.title}`,onClick:()=>r(e),children:[t?(0,$.jsx)(Ho,{session:t}):(0,$.jsx)(Da,{size:14,"aria-hidden":`true`}),(0,$.jsx)(`span`,{children:e.title})]},e.sessionId)})})]})}async function Sg(e,t,n,r){if(!t.turnId)throw Error(`This local result has no completed task turn.`);if(await yu(e,t),!r())return;let i=await Y(e,`/v1/ponder/desktop/outputs`,{method:`POST`,body:JSON.stringify({operationId:t.operationId,turnId:t.turnId,outputId:n})});if(!r())return;let a=Uint8Array.from(atob(i.contentsBase64),e=>e.charCodeAt(0)),o=URL.createObjectURL(new Blob([a],{type:i.contentType})),s=document.createElement(`a`);s.href=o,s.download=i.filename,document.body.append(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(o),3e4)}function Cg(e){if(e instanceof Ti&&(e.message===`public_api_route_not_found`||e.message===`product_route_not_found`))return`Pal is available in this app, but the connected OpenPond service has not been updated yet.`;let t=e instanceof Error?e.message:String(e);return/<(?:!doctype|html|head|body)\b/i.test(t)||/\b50[234]\b/.test(t)?`Pal is temporarily unavailable. Please try again.`:t.length>240?`Pal couldn’t complete this action. Please try again.`:t}function wg({connection:e,accountScopeKey:t,localSessions:n,composer:r,onOpenWork:i,onOpenLocalWork:a,navigationVersion:o=0}){let[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(0),[y,b]=(0,Q.useState)(null);Ka(y?Cg(y):null);let x=yo(e,!!s,t,!1),S=x.data?.items??[],C=x.data?.localItems??[],w=x.data?.localHandoffs??[],T=_g(e,s?.bindingId??null);Ka(T.error?Cg(T.error):null),Ka(l?.activeTurn?.status===`failed`?Cg(l.activeTurn.errorText??`Pal couldn’t complete this request. Please try again.`):null);let[E,D]=(0,Q.useState)(null),O=E?T.items.find(e=>e.id===E.id):null,k=!(!E||O&&O.state===`proposed`&&O.revision===E.revision&&!hg(O)),A=(0,Q.useRef)(``),j=(0,Q.useRef)({connection:e,bindingId:s?.bindingId,destination:E?.id??`chat`,draft:d});j.current={connection:e,bindingId:s?.bindingId,destination:E?.id??`chat`,draft:d};let M=(0,Q.useRef)(!1),N=(0,Q.useRef)(!0);function P(){D(null),f(A.current)}function F(e){E||(A.current=d),D(e),f(e.proposedText??``)}async function I(e,t){let n=j.current,r=E?.id===e.id;await T.action(e,t,t===`send`?r?d:e.proposedText??void 0:void 0)&&r&&j.current.connection===n.connection&&j.current.bindingId===n.bindingId&&j.current.destination===n.destination&&(j.current.draft===n.draft?P():D(null))}(0,Q.useEffect)(()=>{N.current=!0;let t=!0;return c(null),u(null),b(null),f(``),A.current=``,g(!1),m(``),D(null),Y(e,`/v1/ponder`,{method:`POST`,body:`{}`}).then(e=>{t&&(c(e),b(null))}).catch(e=>{t&&b(Cg(e))}),()=>{t=!1,N.current=!1}},[e]),(0,Q.useEffect)(()=>{if(!s)return;let t=!0,n=!1,r=async()=>{if(!n){n=!0;try{let n=await Y(e,`/v1/ponder/conversations/${encodeURIComponent(s.conversationId)}`);t&&u(n)}catch(e){t&&b(Cg(e))}finally{n=!1}}};r();let i=window.setInterval(()=>void r(),3e3);return()=>{t=!1,window.clearInterval(i)}},[e,s]),(0,Q.useEffect)(()=>{x.error&&b(Cg(x.error))},[x.error]);async function L(t){let n=t.contentsBase64?Uint8Array.from(atob(t.contentsBase64),e=>e.charCodeAt(0)):t.text===void 0?null:new TextEncoder().encode(t.text);if(!n)throw Error(`Attachment ${t.name} has no content to upload.`);let r=await crypto.subtle.digest(`SHA-256`,n),i=btoa(String.fromCharCode(...new Uint8Array(r))),a=await Y(e,`/v1/ponder/work-inputs`,{method:`POST`,body:JSON.stringify({name:t.name,contentType:t.mediaType,sizeBytes:n.byteLength,sha256Base64:i})}),o=await fetch(a.upload.url,{method:a.upload.method,headers:a.upload.headers,body:new Blob([n],{type:t.mediaType})});if(!o.ok)throw Error(`Attachment upload failed (${o.status})`);return Y(e,`/v1/ponder/work-inputs/${encodeURIComponent(a.input.id)}/finalize`,{method:`POST`,body:`{}`})}async function ee(t=[],n){let r=(n?.promptOverride??d).trim();if(!s||!r||M.current)return!1;let i=j.current,a=()=>N.current&&j.current.connection===i.connection&&j.current.bindingId===i.bindingId&&j.current.destination===i.destination;M.current=!0,g(!0);try{if(E){if(k)throw Error(`Review the latest task state before sending this proposed message.`);if(t.length)throw Error(`Send task messages as text. Attachments can be sent in the task's own conversation.`);let e=await T.action(E,`send`,r);return a()?(e&&j.current.draft===i.draft&&P(),e):!1}let n=await Promise.all(t.map(L));if(!a())return!1;let o=await Y(e,`/v1/ponder/conversations/${encodeURIComponent(s.conversationId)}/turns`,{method:`POST`,headers:{"idempotency-key":crypto.randomUUID()},body:JSON.stringify({prompt:r,attachments:n})});return a()?(u(e=>e?{...e,activeTurn:o}:{id:s.conversationId,messages:[],activeTurn:o}),v(e=>e+1),j.current.draft===i.draft&&f(``),b(null),!0):!1}catch(e){return a()&&b(Cg(e)),!1}finally{M.current=!1,g(!1)}}async function R(t,n){if(t.wait)try{await Y(e,`/v1/ponder/turns/${encodeURIComponent(t.id)}/waits/${encodeURIComponent(t.wait.id)}/resolve`,{method:`POST`,body:JSON.stringify(n)}),m(``)}catch(e){b(Cg(e))}}async function z(t){try{await Y(e,`/v1/ponder/turns/${encodeURIComponent(t.id)}/cancel`,{method:`POST`,body:`{}`})}catch(e){b(Cg(e))}}async function B(t){let n=window.open(`about:blank`,`_blank`);try{let r=await Y(e,`/v1/ponder/work-outputs/${encodeURIComponent(t)}`);if(!r.downloadURL)throw Error(`This output is not available for download.`);n?n.location.replace(r.downloadURL):window.location.assign(r.downloadURL)}catch(e){n?.close(),b(Cg(e))}}async function V(t){if(!t.sessionId)return;let n=j.current,r=()=>N.current&&j.current.connection===n.connection&&j.current.bindingId===n.bindingId;try{if(await yu(e,t),!r())return;a(t.sessionId)}catch(e){r()&&b(Cg(e))}}async function H(t,n){let r=j.current,i=()=>N.current&&j.current.connection===r.connection&&j.current.bindingId===r.bindingId;try{await Sg(e,t,n,i)}catch(e){i()&&b(Cg(e))}}let U=!!(l?.activeTurn&&[`queued`,`running`,`retry_scheduled`].includes(l.activeTurn.status)),te=!!(l?.activeTurn&&[`queued`,`running`,`retry_scheduled`,`waiting_approval`,`waiting_input`].includes(l.activeTurn.status)),ne=(0,$.jsx)(xg,{items:C,workflow:w[0],sessions:n,onOpenTask:e=>void V(e)}),re=(0,Q.useMemo)(()=>mg(l?.messages??[]),[l?.messages]);return(0,$.jsx)(fd,{scroll:{navigationVersion:o,browserConversationId:l?.id??null,chatSubmissionVersion:_,chatMessages:re.messages,chatHistoryHasMore:!1,chatHistoryLoading:!1,pendingApproval:null,showChatThread:!0,showThinkingIndicator:U,turnRunning:te,view:`chat`},thread:{connection:e,usageSessionId:null,label:`Pal conversation`,loading:!l,onOpenSession:e=>{let t=re.localPeers.get(e);t?V(t):i(e)},renderMessage:e=>{let t=re.sources.get(e.message.id);return t?(0,$.jsx)(yg,{message:t,work:S,onOpenOutput:e=>void B(e),onOpenLocalOutput:(e,t)=>void H(e,t)}):void 0},beforeMessages:(0,$.jsxs)($.Fragment,{children:[!l&&!y&&(0,$.jsx)(`article`,{className:`activity-group thinking-row`,role:`status`,children:(0,$.jsx)(hu,{running:!0,children:`Loading conversation…`})}),(0,$.jsx)(vg,{connection:e,work:S,localWork:C,onOpenWork:i,onOpenLocalWork:e=>void V(e),onOpenLocalOutput:(e,t)=>void H(e,t),onOpenOutput:e=>void B(e),busy:h||te})]}),afterMessages:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(gg,{items:T.items,busy:T.busy,editingId:E?.id??null,onEdit:F,onSend:e=>{I(e,`send`)},onDismiss:e=>{I(e,`dismiss`)},onOpen:i}),ne,l?.activeTurn?.wait&&(0,$.jsxs)(`section`,{className:`ponder-desktop-attention`,children:[(0,$.jsx)(`strong`,{children:l.activeTurn.wait.title}),l.activeTurn.wait.kind===`approval`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>void R(l.activeTurn,{decision:`accepted`}),children:`Approve`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>void R(l.activeTurn,{decision:`declined`}),children:`Decline`})]}):l.activeTurn.wait.options.length>0?l.activeTurn.wait.options.map(e=>(0,$.jsx)(`button`,{type:`button`,onClick:()=>void R(l.activeTurn,{value:e}),children:e},e)):(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),R(l.activeTurn,{value:p})},children:[(0,$.jsx)(`input`,{"aria-label":`Response to Pal`,value:p,onChange:e=>m(e.target.value)}),(0,$.jsx)(`button`,{type:`submit`,disabled:!p.trim(),children:`Send response`})]})]}),l?.activeTurn?.outputs?.map(e=>e.downloadURL?(0,$.jsx)(`a`,{href:e.downloadURL,target:`_blank`,rel:`noreferrer`,children:e.name},e.id):(0,$.jsx)(`button`,{type:`button`,onClick:()=>void B(e.id),children:e.name},e.id))]})},composerPrefix:(0,$.jsx)($.Fragment,{children:E?(0,$.jsxs)(`div`,{className:`ponder-message-destination`,role:`status`,children:[(0,$.jsxs)(`span`,{children:[`Message to `,E.target.title,k?` — review the latest task state before sending`:``]}),(0,$.jsx)(`button`,{type:`button`,onClick:P,children:`Return to Pal chat`})]}):null}),composer:(0,$.jsx)(Ih,{...r,experience:`chat`,mode:`dock`,showProjectFooter:!1,hideModelControls:!0,connection:e,prompt:d,onPromptChange:f,busy:h||k||!!T.busy||!s,running:U&&!E,submissionScopeKey:`ponder:${s?.conversationId??`loading`}:${E?.id??`chat`}`,voiceInputChannelKey:`ponder:${s?.conversationId??`loading`}`,onSubmit:(e,t,n,r)=>ee(e,r?.promptOverride?{promptOverride:r.promptOverride}:void 0),onStop:()=>l?.activeTurn?z(l.activeTurn):void 0})})}function Tg({state:e,connection:t,accountScopeKey:n,onSetup:r}){let i=(0,Q.useId)(),a=(0,Q.useRef)(null),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)({}),u=fg(t,n,o),d=S({queryKey:[`account-remote-access`,ra(t)],enabled:o,staleTime:5e3,refetchInterval:o?1e4:!1,queryFn:({signal:e})=>Y(t,`/v1/account-remote-access`,{signal:AbortSignal.any([e,AbortSignal.timeout(15e3)])})});Ka(d.error?.message??null);let f=d.data?{connected:`Connected`,connecting:`Connecting`,reconnecting:`Reconnecting`,offline:`Offline`,off:`Off`,signed_out:`Sign in required`,update_required:`Update required`}[d.data.state]:d.isPending?`Checking connection…`:`Unknown`;return(0,Q.useEffect)(()=>{if(!o)return;function e(){let e=a.current?.getBoundingClientRect();if(!e)return;let t=Math.min(320,window.innerWidth-24);l({left:Math.max(12,Math.min(e.left,window.innerWidth-t-12)),bottom:window.innerHeight-e.top+8,width:t,maxHeight:Math.max(100,e.top-24)})}return e(),window.addEventListener(`resize`,e),window.addEventListener(`scroll`,e,!0),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`scroll`,e,!0)}},[o]),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{ref:a,type:`button`,className:`ponder-execution-control`,popoverTarget:i,children:`Pal`}),(0,$.jsxs)(`div`,{id:i,popover:`auto`,className:`ponder-connections`,style:c,onToggle:e=>s(e.newState===`open`),role:`dialog`,"aria-label":`Pal connections`,children:[(0,$.jsx)(`h3`,{children:`Connections`}),(0,$.jsxs)(`section`,{className:`ponder-access-section`,"aria-label":`Desktop and remote access`,children:[(0,$.jsxs)(`label`,{children:[(0,$.jsxs)(`span`,{children:[`This desktop`,(0,$.jsx)(`small`,{children:e?.session?`Pal runs here`:`Set up Pal to start`})]}),(0,$.jsx)(`input`,{type:`checkbox`,role:`switch`,"aria-label":`This desktop execution`,checked:!!e?.session,readOnly:!0,disabled:!0})]}),[`Web access`,`iOS access`].map(e=>(0,$.jsxs)(`div`,{className:`ponder-connection-card`,role:`group`,"aria-label":e,children:[(0,$.jsxs)(`span`,{children:[e,(0,$.jsx)(`small`,{children:f})]}),(0,$.jsx)(`span`,{className:`ponder-connection-dot${d.data?.state===`connected`?` connected`:``}`,role:`img`,"aria-label":`${e}: ${f}`,title:`Shared desktop relay connection`})]},e))]}),(0,$.jsxs)(`label`,{className:`ponder-hosted-sandboxes`,children:[(0,$.jsxs)(`span`,{children:[`Hosted sandboxes`,(0,$.jsx)(`small`,{children:u.loading?`Checking availability…`:u.state?.enabled?`Selected assignments may run in hosted Work.`:u.state?.reason??`Allow selected assignments and required project context to run in hosted Work. Usage may incur charges.`})]}),(0,$.jsx)(`input`,{type:`checkbox`,role:`switch`,"aria-label":`Hosted sandboxes enabled`,checked:u.state?.enabled??!1,disabled:!u.state||u.saving||!u.state.available&&!u.state.enabled,onChange:e=>u.setEnabled(e.currentTarget.checked)})]}),(0,$.jsx)(`button`,{type:`button`,onClick:r,children:`Pal settings`})]})]})}function Eg({children:e,onClose:t}){let n=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{let e=document.activeElement;return n.current?.showModal(),()=>{n.current?.close(),e instanceof HTMLElement&&e.isConnected&&e.focus()}},[]),(0,$.jsx)(`dialog`,{ref:n,className:`git-dialog ponder-setup`,"aria-labelledby":`ponder-setup-title`,onCancel:e=>{e.preventDefault(),t()},children:e})}function Dg(e){let{connection:t,composer:n}=e,r=(0,Q.useMemo)(()=>t,[t.serverUrl,t.token,t.platform,t.arch]),i=JSON.stringify([ra(r),e.accountScopeKey]),a=(0,Q.useRef)(i);a.current=i;let o=u(),s=[`ponder-local`,ra(r),e.accountScopeKey],c=[...s,`snapshot`],l=S({queryKey:c,staleTime:3e4,queryFn:()=>Y(r,`/v1/ponder/local?catalog=0`)}),d=S({queryKey:s,staleTime:3e4,queryFn:()=>Y(r,`/v1/ponder/local`)}),f=l.data,p=(0,Q.useMemo)(()=>f&&(!d.data||f.coordinator.revision>d.data.coordinator.revision)?{...f,supportedModelRefs:d.data?.supportedModelRefs??[]}:d.data??null,[f,d.data]);function m(e){o.setQueryData(s,e),o.setQueryData(c,e)}Ka(d.error?.message??null),Ka(l.error?.message??null);let[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(!1),y=(0,Q.useRef)(null),[b,x]=(0,Q.useState)(null);Ka(b);let[C,w]=(0,Q.useState)(!1),[T,E]=(0,Q.useState)(0),[D,O]=(0,Q.useState)(``),[k,A]=(0,Q.useState)(`openai`),[j,M]=(0,Q.useState)(``),N=Sd(r,h?null:p?.session?.id??null),P=Lf(r,h?null:p?.session?.id??null,N.events);Ka(N.error),Ka(P.error);let F=P.snapshot?!(!P.snapshot.activeTurnId||P.snapshot.paused):N.running;(0,Q.useEffect)(()=>{let e=P.acknowledgedInput;if(!e||e.sessionId!==p?.session?.id)return;let t=y.current;t&&typeof t==`object`&&t.scope!==i||(t?.acknowledge?.(!0),y.current=null,w(!1),O(t=>t.trim()===e.body.trim()?``:t),P.acknowledgeRetainedInput())},[P.acknowledgedInput,p?.session?.id,i]),(0,Q.useEffect)(()=>{g(!1),x(null),O(``),w(!1),y.current=null},[i]),(0,Q.useEffect)(()=>{p&&(v(!p.session),p.coordinator.modelRef&&(A(p.coordinator.modelRef.providerId),M(p.coordinator.modelRef.modelId)))},[p]);async function I(e=k,t=j){w(!0);try{let n=await Y(r,`/v1/ponder/local`,{method:`POST`,body:JSON.stringify({modelRef:{providerId:e,modelId:t}})});if(a.current!==i)return;m(n),A(e),M(t),v(!1),x(null)}catch(e){a.current===i&&x(ju(e))}finally{a.current===i&&w(!1)}}async function L(e,t){let r=p?.session,o=(t??D).trim();if(!r||!o||C||y.current)return!1;let s={scope:i,acknowledge:void 0};y.current=s;let c=new Promise(e=>{s.acknowledge=e});w(!0);try{let t={prompt:o,attachments:e,modelRef:p.coordinator.modelRef??void 0,approvalPolicy:`on-request`,sandbox:`workspace-write`,codexPermissionMode:`default`,codexReasoningEffort:n.codexReasoningEffort};return!await Promise.race([P.queue(t),c])||a.current!==i?!1:(E(e=>e+1),O(e=>e===D?``:e),x(null),!0)}catch(e){return a.current===i&&x(ju(e)),!1}finally{y.current===s&&(y.current=null),a.current===i&&w(!1)}}let ee=Object.values(n.providerSettings?.statuses??{}).filter(e=>e.available&&e.enabled&&p?.supportedModelRefs?.some(t=>t.providerId===e.id)).map(e=>({value:e.id,label:e.displayName})),R=Ci(k,n.providerSettings).filter(e=>p?.supportedModelRefs?.some(t=>t.providerId===k&&t.modelId===e.value));(0,Q.useEffect)(()=>{if(p?.session||!p?.supportedModelRefs.length)return;let e=p.supportedModelRefs,t=e.find(e=>e.providerId===`openai`&&e.modelId===`gpt-6.1-sol`)??e.find(e=>e.providerId===`anthropic`&&e.modelId===n.providerSettings?.statuses.anthropic?.defaultModel)??e.find(e=>e.providerId===n.provider&&e.modelId===n.model)??e[0];A(t.providerId),M(t.modelId)},[p,n.providerSettings,n.provider,n.model]);let z=$i(N.events),B=Xi({provider:p?.session?.provider??k,snapshot:z?.model===p?.coordinator.modelRef?.modelId?z:null,preferences:e.contextCompaction});return(0,$.jsxs)(`div`,{className:`ponder-workspace`,children:[(0,$.jsx)(`div`,{className:`ponder-main`,children:h?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`ponder-connection-bar`,children:(0,$.jsx)(`button`,{type:`button`,onClick:()=>g(!1),children:`Return to local Pal`})}),(0,$.jsx)(wg,{...e})]}):(0,$.jsx)(fd,{scroll:{navigationVersion:e.navigationVersion,browserConversationId:p?.session?.id??null,chatSubmissionVersion:T,chatMessages:N.messages,chatHistoryHasMore:N.hasMore,chatHistoryLoading:N.loading,onLoadMoreChatHistory:N.loadOlder,pendingApproval:null,showChatThread:!0,showThinkingIndicator:F,turnRunning:F,view:`chat`},thread:{...e.messageContext,connection:r,label:`Pal conversation`,loading:!p||N.loading,onOpenSession:t=>e.onOpenAgents(t),beforeMessages:(0,$.jsxs)($.Fragment,{children:[!p&&l.isError?(0,$.jsx)(`button`,{type:`button`,onClick:()=>void l.refetch(),children:`Retry opening Pal`}):null,p&&!p.session?(0,$.jsxs)(`div`,{className:`ponder-empty`,children:[(0,$.jsx)(`h2`,{children:`Meet Pal`}),(0,$.jsx)(`p`,{children:`Delegate work and keep your agents coordinated in one conversation.`}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>v(!0),children:`Set up local Pal`})]}):null,p?.session&&!N.loading&&N.messages.length===0?(0,$.jsxs)(`div`,{className:`ponder-empty`,children:[(0,$.jsx)(`h2`,{children:`What would you like to work on?`}),(0,$.jsx)(`p`,{children:`Tell Pal what you need. Delegated agents will appear on the right, and you can take control whenever you want.`})]}):null]})},composer:(0,$.jsx)(Ih,{...n,connection:r,experience:`chat`,mode:`dock`,placeholder:`Ask Pal to coordinate work…`,showProjectFooter:!1,provider:p?.session?.provider??k,model:p?.coordinator.modelRef?.modelId??j,contextWindowStatus:B,allowedModelRefs:p?.supportedModelRefs??[],modelSelectionDisabled:F,onProviderChange:(e,t)=>{t&&I(e,t)},onModelChange:e=>{I(p?.session?.provider??k,e)},executionControl:(0,$.jsx)(Tg,{state:p,connection:r,accountScopeKey:e.accountScopeKey,onSetup:()=>v(!0)}),goalSessionId:null,enableResourceContext:!1,taskSessionId:p?.session?.id,taskEvents:N.events,prompt:D,onPromptChange:O,busy:C||!p?.session,running:F,submissionScopeKey:`ponder-local:${p?.session?.id??`setup`}`,onSubmit:(e,t,n,r)=>L(e??[],r?.promptOverride),onStop:async()=>{if(p?.session)try{await co.interruptTurn(r,p.session.id)}catch(e){x(ju(e))}}})})}),_&&p?(0,$.jsxs)(Eg,{onClose:()=>v(!1),children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`h2`,{id:`ponder-setup-title`,children:`Welcome to Pal`}),(0,$.jsx)(`button`,{type:`button`,"aria-label":`Close setup`,onClick:()=>v(!1),children:(0,$.jsx)(Ua,{size:16})})]}),(0,$.jsx)(`p`,{children:`Pal stands for Ponder Assisted Learning. It coordinates your agents. Start on this desktop and keep your conversation here.`}),(0,$.jsxs)(`div`,{className:`ponder-setup-card`,children:[(0,$.jsx)(`h3`,{children:`On this desktop`}),(0,$.jsx)(`p`,{children:`Use your configured model. Your provider’s inference charges may apply.`}),(0,$.jsx)(Z,{label:`Pal provider`,value:k,options:ee,onChange:e=>{A(e),M(Ci(e,n.providerSettings)[0]?.value??``)}}),(0,$.jsx)(Z,{label:`Pal model`,value:j,options:R,onChange:M}),d.isError?(0,$.jsx)(`button`,{type:`button`,className:`git-dialog-secondary`,onClick:()=>void d.refetch(),children:`Retry loading models`}):null,(0,$.jsx)(`button`,{type:`button`,className:`git-dialog-primary`,disabled:C||!j||!ee.some(e=>e.value===k),onClick:()=>void I(k,j),children:p.session?`Save local model`:`Start locally`}),(0,$.jsx)(`button`,{type:`button`,className:`git-dialog-secondary`,onClick:()=>{v(!1),n.onProviderSetupOpen?.()},children:`Configure a provider`})]}),(0,$.jsx)(pg,{connection:r,accountScopeKey:e.accountScopeKey}),[[`remoteAccess`,`Web and iOS access`,`Access local Pal without a subscription while your desktop stays online.`],[`hostedCoordinator`,`Hosted Pal`,`Keep your coordinator available in the cloud. Activation uploads this Pal conversation.`]].map(([e,t,n])=>(0,$.jsxs)(`div`,{className:`ponder-setup-card`,children:[(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`strong`,{children:t}),(0,$.jsx)(`input`,{type:`checkbox`,role:`switch`,checked:!1,disabled:!0,"aria-label":t})]}),(0,$.jsx)(`p`,{children:n}),(0,$.jsx)(`small`,{children:p.capabilities[e].reason??`Setup is not available yet.`})]},e)),(0,$.jsx)(`button`,{type:`button`,className:`git-dialog-secondary`,onClick:()=>{g(!0),v(!1)},children:`Open existing hosted Pal`})]}):null]})}function Og({accountBaseUrl:e,onOpenBrowserLink:t,...n}){function r(r){if(!e)n.composer.showToast(`OpenPond account URL is unavailable for this Work task.`,`error`);else try{t(new URL(`/tasks/${encodeURIComponent(r)}`,e).toString(),{newTab:!0})}catch{n.composer.showToast(`OpenPond account URL is invalid for this Work task.`,`error`)}}return(0,$.jsx)(Dg,{...n,onOpenWork:r})}function kg(e){return JSON.stringify({account:e?.account.activeProfile??null,baseUrl:e?.account.baseUrl??null,owner:e?.account.profile?.id??null,state:e?.account.state??null,teamId:e?.preferences.defaultTeamId??null})}function Ag({expanded:e,terminalOpen:t,sideChatAvailable:n,onOpenFiles:r,onOpenAgents:i,onOpenReview:a,onOpenSideChat:o,onOpenTrainingDraft:s,trainingDraftAvailable:c,onResizeStart:l,onToggleExpanded:u,onToggleTerminal:d}){return(0,$.jsxs)(`aside`,{className:`workspace-diff-panel right-sidebar-home-panel ${e?`expanded`:``}`,"aria-label":`Right sidebar`,children:[e?null:(0,$.jsx)(`div`,{className:`workspace-diff-resize-handle`,role:`separator`,"aria-orientation":`vertical`,"aria-label":`Resize right sidebar`,onPointerDown:l}),(0,$.jsxs)(`div`,{className:`workspace-diff-topbar right-sidebar-home-topbar`,children:[(0,$.jsx)(`div`,{className:`workspace-diff-tabs`,role:`tablist`,"aria-label":`Right sidebar views`,children:(0,$.jsxs)(`button`,{type:`button`,className:`workspace-diff-tab active`,role:`tab`,"aria-selected":!0,children:[(0,$.jsx)(es,{size:14}),(0,$.jsx)(`span`,{children:`Workspace`})]})}),(0,$.jsx)(`div`,{className:`workspace-diff-toolbar-actions`,children:(0,$.jsx)(`button`,{type:`button`,className:`diff-icon-button`,title:e?`Dock sidebar`:`Expand sidebar`,"aria-label":e?`Dock sidebar`:`Expand sidebar`,onClick:u,children:e?(0,$.jsx)(da,{size:14}):(0,$.jsx)(Fa,{size:14})})})]}),(0,$.jsx)(`div`,{className:`right-sidebar-home-body`,children:(0,$.jsx)(jg,{terminalOpen:t,sideChatAvailable:n,onOpenFiles:r,onOpenAgents:i,onOpenReview:a,onOpenSideChat:o,onOpenTrainingDraft:s,trainingDraftAvailable:c,onToggleTerminal:d})})]})}function jg({terminalOpen:e,sideChatAvailable:t,onOpenFiles:n,onOpenFile:r,onOpenReview:i,onOpenExperiments:a,onOpenAgents:o,onOpenSideChat:s,onOpenTrainingDraft:c,trainingDraftAvailable:l,onToggleTerminal:u}){let d=[{id:`review`,label:`Review`,meta:`Diffs`,icon:oa,onSelect:i},{id:`files`,label:`Files`,meta:`Workspace`,icon:Na,onSelect:n},{id:`side-chat`,label:`Side chat`,meta:`Context`,icon:Ia,onSelect:s,disabled:!t},{id:`training-draft`,label:`Task draft`,meta:`Training`,icon:Ao,onSelect:c,disabled:!l},{id:`terminal`,label:e?`Hide terminal`:`Terminal`,meta:`Shell`,icon:Ha,onSelect:u}];return o&&d.push({id:`agents`,label:`Agents`,icon:Ia,onSelect:o}),a&&d.unshift({id:`experiments`,label:`Ponder`,meta:`Experiments and models`,icon:Ao,onSelect:a}),r&&d.splice(a?3:2,0,{id:`open-file`,label:`Open file`,icon:Na,onSelect:r}),(0,$.jsx)(`div`,{className:`right-sidebar-home-actions`,role:`menu`,"aria-label":`Workspace actions`,children:d.map(e=>(0,$.jsxs)(`button`,{type:`button`,className:`right-sidebar-home-row`,role:`menuitem`,disabled:e.disabled,onClick:e.onSelect,children:[(0,$.jsx)(e.icon,{size:15}),(0,$.jsx)(`span`,{children:e.label}),e.meta?(0,$.jsx)(`span`,{className:`right-sidebar-home-chip`,children:e.meta}):null]},e.id))})}var Mg=[];function Ng(e){let t=window.openpond?.browser,[n,r]=(0,Q.useState)(()=>({conversationId:e,activeTabId:null,tabs:Mg}));(0,Q.useEffect)(()=>{if(r({conversationId:e,activeTabId:null,tabs:Mg}),!t)return;let n=!1,i=!1;t.getState({conversationId:e}).then(e=>{!n&&!i&&r(e)});let a=t.onState(t=>{t.conversationId===e&&(i=!0,r(t))});return()=>{n=!0,a()}},[t,e]);let i=(0,Q.useMemo)(()=>n.tabs.find(e=>e.id===n.activeTabId)??null,[n.activeTabId,n.tabs]),a=(0,Q.useCallback)(async(n,r={})=>{if(!t)return!1;let i=no(n,{explicitFile:r.explicitFile});if(!i)return!1;let a=r.newTab?await t.newTab({conversationId:e,url:i,explicitFile:r.explicitFile}):await t.open({conversationId:e,url:i,explicitFile:r.explicitFile});if(!a.ok)throw Error(a.error||`Could not open browser.`);return!0},[t,e]),o=i?{conversationId:e,tabId:i.id}:null;return{activeTab:i,available:!!t,bridge:t,state:n,back:()=>t&&o?t.back(o):Promise.resolve({ok:!1}),clearData:()=>t?t.clearData({conversationId:e}):Promise.resolve({ok:!1}),closeTab:n=>t?t.closeTab({conversationId:e,tabId:n}):Promise.resolve({ok:!1}),forward:()=>t&&o?t.forward(o):Promise.resolve({ok:!1}),newTab:n=>t?t.newTab({conversationId:e,url:n}):Promise.resolve({ok:!1}),open:a,openExternal:()=>t&&o?t.openExternal(o):Promise.resolve({ok:!1}),reload:()=>t&&o?t.reload(o):Promise.resolve({ok:!1}),snapshot:(n={})=>t?t.snapshot({conversationId:e,...n}):Promise.resolve({ok:!1,output:`Desktop browser bridge unavailable.`}),moveCursor:n=>t?t.moveCursor({conversationId:e,...n}):Promise.resolve({ok:!1,output:`Desktop browser bridge unavailable.`}),click:n=>t?t.click({conversationId:e,...n}):Promise.resolve({ok:!1,output:`Desktop browser bridge unavailable.`}),typeText:n=>t?t.typeText({conversationId:e,...n}):Promise.resolve({ok:!1,output:`Desktop browser bridge unavailable.`}),key:n=>t?t.key({conversationId:e,...n}):Promise.resolve({ok:!1,output:`Desktop browser bridge unavailable.`}),scroll:n=>t?t.scroll({conversationId:e,...n}):Promise.resolve({ok:!1,output:`Desktop browser bridge unavailable.`}),selectTab:n=>t?t.selectTab({conversationId:e,tabId:n}):Promise.resolve({ok:!1}),setBounds:n=>t?t.setBounds({conversationId:e,bounds:n}):Promise.resolve({ok:!1}),stop:()=>t&&o?t.stop(o):Promise.resolve({ok:!1})}}function Pg({activeTab:e,documentName:t,snapshotActions:n,available:r,onBack:i,onClearData:a,onForward:o,onNavigate:s,onOpenExternal:c,onReload:l,onStop:u}){let[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{f(t??e?.url??``)},[e?.id,e?.url,t]);function h(e){e.preventDefault(),!t&&s(d)}return(0,$.jsxs)(`div`,{className:`browser-toolbar`,children:[(0,$.jsxs)(`div`,{className:`browser-nav-actions`,children:[(0,$.jsx)(`button`,{type:`button`,title:`Back`,"aria-label":`Back`,disabled:!e?.canGoBack,onClick:i,children:(0,$.jsx)(so,{size:15})}),(0,$.jsx)(`button`,{type:`button`,title:`Forward`,"aria-label":`Forward`,disabled:!e?.canGoForward,onClick:o,children:(0,$.jsx)(_a,{size:15})}),(0,$.jsx)(`button`,{type:`button`,title:e?.loading?`Stop`:`Reload`,"aria-label":e?.loading?`Stop`:`Reload`,disabled:!e,onClick:e?.loading?u:l,children:e?.loading?(0,$.jsx)(Va,{size:13}):(0,$.jsx)(Ba,{size:14})})]}),(0,$.jsx)(`form`,{className:`browser-address-form`,onSubmit:h,children:(0,$.jsx)(`input`,{"aria-label":`Browser address`,disabled:!r&&!t,readOnly:!!t,placeholder:`Search or enter address`,spellCheck:!1,value:d,onChange:e=>f(e.target.value)})}),(0,$.jsxs)(`div`,{className:`browser-panel-actions`,children:[n,(0,$.jsx)(`button`,{type:`button`,title:`Open external`,"aria-label":`Open external`,disabled:!e||!!t,onClick:c,children:(0,$.jsx)(Ma,{size:14})}),(0,$.jsxs)(`div`,{className:`browser-menu-anchor`,children:[(0,$.jsx)(`button`,{type:`button`,title:`Browser actions`,"aria-label":`Browser actions`,onClick:()=>m(e=>!e),children:(0,$.jsx)(Ko,{size:15})}),p&&(0,$.jsx)(`div`,{className:`browser-options-menu`,role:`menu`,children:(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{m(!1),a()},children:`Clear Browser Data...`})})]})]})]})}function Fg({conversationId:e,onOpenBrowser:t}){let n=Ng(e),r=Ga();return(0,$.jsx)(Pg,{activeTab:null,available:n.available,onBack:()=>{},onForward:()=>{},onReload:()=>{},onStop:()=>{},onOpenExternal:()=>{},onClearData:()=>{window.confirm(`Clear shared browser data? Cookies, logins, cache, and site storage will be removed for all chats. This chat's browser tabs will also close.`)&&n.clearData()},onNavigate:e=>{n.open(e,{explicitFile:!0,newTab:!0}).then(e=>{e&&t()}).catch(e=>r?.(e instanceof Error?e.message:`Could not open browser.`,`error`))}})}var Ig=(0,Q.lazy)(()=>o(()=>import(`./FilePagePreview-B7bWObJN.js`),__vite__mapDeps([73,1,2,3,16,20,4,5,6,21,22,13,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,18,42,43,44,45,46,47,48,19,49,50,51,52,53,54,55,56,74])));function Lg({path:e,connection:t,workspaceId:n,sandboxId:r,revision:i}){let a=(0,Q.useRef)(null),[o,s]=(0,Q.useState)(!1),c=bo(e),l=va(e)||n,u=`${ra(t)}:${l}:${r??``}:${e}`,d=ca(t,o&&c&&!r?l:null,e);(0,Q.useEffect)(()=>{let e=a.current;if(!e)return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&(s(!0),t.disconnect())});return t.observe(e),()=>t.disconnect()},[]);let f=S({queryKey:[`file-thumbnail`,u,i],enabled:!(!o||!t||c&&!r||!l&&!r),queryFn:()=>r?xa(t,r,e):Eo.workspaceFile(t,l,e),staleTime:i?1/0:15e3,gcTime:6e4}).data,p=c&&r&&f?.contentEncoding===`base64`&&f.content?`data:image/${/\.jpe?g$/i.test(e)?`jpeg`:e.split(`.`).pop()?.toLowerCase()};base64,${f.content}`:null;return(0,$.jsx)(`span`,{ref:a,className:`workspace-file-thumbnail`,children:d||p?(0,$.jsx)(`img`,{alt:``,src:d||p,loading:`lazy`}):f?.content&&(Do(f)||/\.(?:docx|pdf)$/i.test(f.path))?(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(ts,{size:28}),children:(0,$.jsx)(Ig,{file:f})}):f?.content&&f.contentEncoding!==`base64`?(0,$.jsx)(`pre`,{children:f.content.slice(0,1200)}):(0,$.jsx)(ts,{size:28})})}function Rg({chatMessages:e,connection:t,contextWindowStatus:n,expanded:r,runtimeEvents:i,sessionId:a,showToast:o,onResizeStart:s,onToggleExpanded:c,onUseOutput:l,onHandoffOutput:u,onReviseOutput:d,onAgentPackageInstalled:f}){let[p,m]=(0,Q.useState)(`outputs`),[h,g]=(0,Q.useState)(null),[_,v]=(0,Q.useState)(null),[y,b]=(0,Q.useState)(``),[x,S]=(0,Q.useState)({}),C=(0,Q.useMemo)(()=>Vg(i),[i]),w=(0,Q.useMemo)(()=>Ug(C),[C]),T=(0,Q.useMemo)(()=>zg(e),[e]),E=(0,Q.useMemo)(()=>Bg(e),[e]),D=(0,Q.useMemo)(()=>Gg(e),[e]);(0,Q.useEffect)(()=>()=>{_?.objectUrl&&URL.revokeObjectURL(_.objectUrl)},[_?.objectUrl]);async function O(e){if(!t||!a||e.kind!==`file`)return null;g(Hg(e));try{let n=await Eo.workspaceTool(t,a,{action:`work_output_read`,source:`ui_button`,args:{outputId:e.id,revision:e.revision}});if(!n.ok)throw Error(n.output);let r=Qg(n.data),i=typeof r.contentsBase64==`string`?r.contentsBase64:``;if(!i)throw Error(`The output did not include file data.`);return new File([Yg(i)],e.title,{type:e.contentType})}catch(e){return o(e instanceof Error?e.message:`Could not load the output.`,`error`),null}finally{g(null)}}async function k(e){let t=await O(e);if(!t)return;_?.objectUrl&&URL.revokeObjectURL(_.objectUrl);let n=e.kind===`file`&&(e.contentType.startsWith(`text/`)||e.contentType===`application/json`);b(``),v({output:e,file:t,text:n?await t.text():null,objectUrl:n?null:URL.createObjectURL(t)})}async function A(e){let t=await O(e);t&&(l(t),o(`Added the output to the task as input.`,`success`))}async function j(e,t){let n=t.kind===`file`?await O(t):null;(t.kind!==`file`||n)&&await u(e,t,n)}async function M(e){if(t&&a&&window.confirm(`Delete ${e.title} revision ${e.revision} from this device?`)){g(Hg(e));try{let n=await Eo.workspaceTool(t,a,{action:`work_output_delete`,source:`ui_button`,args:{outputId:e.id,revision:e.revision}});if(!n.ok)throw Error(n.output);_?.output.id===e.id&&v(null),o(`Work output deleted.`,`success`)}catch(e){o(e instanceof Error?e.message:`Could not delete the output.`,`error`)}finally{g(null)}}}async function N(e){if(!t||!a||!window.confirm(`Add ${e.title} version ${e.versionId} to your active Agents profile?`))return;let n=async n=>Eo.workspaceTool(t,a,{action:`work_agent_package_install`,source:`ui_button`,args:{outputId:e.id,revision:e.revision,overwrite:n}});g(Hg(e));try{let t;try{t=await n(!1)}catch(r){if(!(r instanceof Error?r.message:`Agent installation failed.`).includes(`already exists`)||!window.confirm(`${e.agentId} already exists. Replace its active checkout with this immutable version?`))throw r;t=await n(!0)}if(!t.ok)throw Error(t.output);await f?.(),o(`${e.title} was added to Agents. Its package remains available in this Work task.`,`success`)}catch(e){o(e instanceof Error?e.message:`Could not add the Agent package.`,`error`)}finally{g(null)}}return(0,$.jsxs)(`aside`,{className:`workspace-diff-panel work-sidebar-panel ${r?`expanded`:``}`,"aria-label":`Thread details`,children:[r?null:(0,$.jsx)(`div`,{className:`workspace-diff-resize-handle`,role:`separator`,"aria-orientation":`vertical`,"aria-label":`Resize Thread details`,onPointerDown:s}),(0,$.jsxs)(`div`,{className:`workspace-diff-topbar`,children:[(0,$.jsx)(`div`,{className:`workspace-diff-tabs`,role:`tablist`,"aria-label":`Thread details`,children:[[`outputs`,`Outputs`],[`activity`,`Activity`],[`context`,`Context`]].map(([e,t])=>(0,$.jsx)(`button`,{type:`button`,className:`workspace-diff-tab ${p===e?`active`:``}`,role:`tab`,"aria-selected":p===e,onClick:()=>m(e),children:t},e))}),(0,$.jsx)(`div`,{className:`workspace-diff-toolbar-actions`,children:(0,$.jsx)(`button`,{type:`button`,className:`diff-icon-button`,title:r?`Dock sidebar`:`Expand sidebar`,"aria-label":r?`Dock sidebar`:`Expand sidebar`,onClick:c,children:r?(0,$.jsx)(da,{size:14}):(0,$.jsx)(Fa,{size:14})})})]}),(0,$.jsxs)(`div`,{className:`work-sidebar-body`,children:[p===`outputs`?_?(0,$.jsxs)(`div`,{className:`work-output-preview`,children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`button`,{type:`button`,onClick:()=>{_.objectUrl&&URL.revokeObjectURL(_.objectUrl),v(null)},children:`Outputs`}),(0,$.jsxs)(`strong`,{children:[_.output.title,` · revision `,_.output.revision]})]}),_.text===null?_.output.kind===`file`&&_.output.contentType.startsWith(`image/`)&&_.objectUrl?(0,$.jsx)(`img`,{src:_.objectUrl,alt:_.output.title}):_.output.kind===`file`&&_.output.contentType===`application/pdf`&&_.objectUrl?(0,$.jsx)(`iframe`,{src:_.objectUrl,title:_.output.title}):_.output.kind===`file`&&_.output.contentType.startsWith(`audio/`)&&_.objectUrl?(0,$.jsx)(`audio`,{controls:!0,src:_.objectUrl}):_.output.kind===`file`&&_.output.contentType.startsWith(`video/`)&&_.objectUrl?(0,$.jsx)(`video`,{controls:!0,src:_.objectUrl}):(0,$.jsx)(`p`,{children:`This file type uses its native application for detailed review.`}):(0,$.jsx)(wa,{content:_.text}),(0,$.jsxs)(`section`,{className:`work-output-annotation`,children:[(0,$.jsx)(`label`,{htmlFor:`work-output-revision-note`,children:`Revision note`}),(0,$.jsx)(`textarea`,{id:`work-output-revision-note`,value:y,onChange:e=>b(e.target.value),placeholder:`Describe the exact change to make in the next revision.`}),(0,$.jsx)(`button`,{type:`button`,disabled:!y.trim(),onClick:()=>{d(_.output,_.file,y.trim()),o(`Prepared revision ${_.output.revision+1}.`,`success`)},children:`Revise this version`})]})]}):w.length>0?(0,$.jsx)(`div`,{className:`work-output-list`,children:w.map(e=>{let t=e.revisions.find(t=>t.revision===x[e.id])??e.revisions[0];return(0,$.jsxs)(`article`,{className:`work-output-card`,children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(ts,{size:16}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:t.title}),e.revisions.length>1?(0,$.jsxs)(`label`,{className:`work-output-version`,children:[(0,$.jsx)(`span`,{children:`Version`}),(0,$.jsx)(`select`,{value:t.revision,onChange:t=>S(n=>({...n,[e.id]:Number(t.target.value)})),children:e.revisions.map(e=>(0,$.jsxs)(`option`,{value:e.revision,children:[`Revision `,e.revision]},Hg(e)))})]}):(0,$.jsxs)(`small`,{children:[`Revision `,t.revision]}),(0,$.jsx)(`small`,{children:qg(t)})]})]}),t.validation.length>0?(0,$.jsxs)(`div`,{className:`work-output-validation`,children:[(0,$.jsx)(zo,{size:13}),(0,$.jsxs)(`span`,{children:[t.validation.filter(e=>e.status===`passed`).length,` `,`checks passed`]})]}):null,(0,$.jsxs)(`div`,{className:`work-output-actions`,children:[t.kind===`file`&&t.location.kind===`local`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>void ga(Xg(t)),children:[(0,$.jsx)(Na,{size:13}),`Reveal`]}),(0,$.jsx)(`button`,{type:`button`,onClick:async()=>{let e=await sa(Xg(t),t.title);e.ok?o(`Saved a copy of the Work output.`,`success`):e.canceled||o(`Could not save a copy of the Work output.`,`error`)},children:`Save as`})]}):null,t.kind===`file`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,disabled:h===Hg(t),onClick:()=>void k(t),children:`Preview`}),(0,$.jsxs)(`button`,{type:`button`,disabled:h===Hg(t),onClick:()=>void A(t),children:[(0,$.jsx)(La,{size:13}),`Use as input`]})]}):t.kind===`agent_package`?(0,$.jsx)(`button`,{type:`button`,disabled:h===Hg(t),onClick:()=>void N(t),children:`Add to Agents`}):`url`in t&&t.url?(0,$.jsx)(`button`,{type:`button`,onClick:()=>window.open(t.url,`_blank`,`noopener,noreferrer`),children:`Open`}):null,t.kind===`file`&&t.location.kind===`local`?(0,$.jsxs)(`button`,{type:`button`,className:`danger`,disabled:h===Hg(t),onClick:()=>void M(t),children:[(0,$.jsx)(la,{size:13}),`Delete`]}):null,(0,$.jsx)(`button`,{type:`button`,disabled:h===Hg(t),onClick:()=>void j(`work`,t),children:`Continue in new thread`})]})]},e.id)})}):E.length>0?(0,$.jsx)(`div`,{className:`work-output-list`,children:E.map(e=>(0,$.jsxs)(`article`,{className:`work-output-card`,children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(ts,{size:16}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:e.title}),(0,$.jsx)(`small`,{children:Jg(e.sizeBytes)})]})]}),(0,$.jsx)(`div`,{className:`work-output-actions`,children:(0,$.jsxs)(`button`,{type:`button`,onClick:()=>void ga(e.path),children:[(0,$.jsx)(Na,{size:13}),`Reveal`]})})]},e.path))}):(0,$.jsx)(Kg,{icon:ts,title:`No saved outputs yet`,detail:`Finished files and connected results will appear here.`}):null,p===`activity`?T.length>0?(0,$.jsx)(`div`,{className:`work-activity-list`,children:T.map(e=>(0,$.jsxs)(`details`,{className:`work-activity-row ${e.state??``}`,children:[(0,$.jsxs)(`summary`,{children:[(0,$.jsx)(rs,{size:14}),(0,$.jsx)(`span`,{children:e.label}),(0,$.jsx)(`small`,{children:e.state??`completed`})]}),(0,$.jsx)(`p`,{children:e.content}),e.detail?(0,$.jsx)(`pre`,{children:e.detail}):null]},e.id))}):(0,$.jsx)(Kg,{icon:rs,title:`No activity yet`,detail:`Commands, tool receipts, and checks appear while the thread runs.`}):null,p===`context`?(0,$.jsxs)(`div`,{className:`work-context`,children:[(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h3`,{children:`Model context`}),(0,$.jsx)(`p`,{children:n.summary}),(0,$.jsx)(`small`,{children:n.tokensLabel})]}),(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h3`,{children:`Task inputs and sources`}),D.length>0?(0,$.jsx)(`ul`,{children:D.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(La,{size:13}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:e.title}),(0,$.jsx)(`small`,{children:e.detail})]})]},e.key))}):(0,$.jsx)(`p`,{children:`No attached files or cited sources yet.`})]})]}):null]})]})}function zg(e){return e.flatMap(e=>e.activities??[]).filter(e=>e.kind!==`reasoning`).reverse()}function Bg(e){let t=new Map;for(let n of e)for(let e of n.activities??[])for(let n of e.artifacts??[])n.path&&n.sizeBytes!==null&&(t.delete(n.path),t.set(n.path,{path:n.path,title:n.title,sizeBytes:n.sizeBytes}));return[...t.values()].reverse()}function Vg(e){let t=new Map,n=new Set;for(let r of e){let e=Wg(r.data);if(r.action===`work_output_delete`&&r.status===`completed`)for(let r of e){let e=Hg(r);n.add(e),t.delete(e)}else if(r.action!==`work_output_read`)for(let r of e){let e=Hg(r);n.has(e)||t.set(e,r)}}return[...t.values()].sort((e,t)=>t.createdAt.localeCompare(e.createdAt)||t.revision-e.revision)}function Hg(e){return`${e.id}:${e.revision}`}function Ug(e){let t=new Map;for(let n of e){let e=t.get(n.id)??[];e.push(n),t.set(n.id,e)}return[...t.entries()].map(([e,t])=>({id:e,revisions:t.sort((e,t)=>t.revision-e.revision||t.createdAt.localeCompare(e.createdAt))})).sort((e,t)=>t.revisions[0].createdAt.localeCompare(e.revisions[0].createdAt))}function Wg(e,t=[],n=new Set,r=0){if(r>8||e==null)return t;let i=Ye.safeParse(e);if(i.success){let e=`${i.data.id}:${i.data.revision}`;return n.has(e)||(n.add(e),t.push(i.data)),t}if(Array.isArray(e)){for(let i of e)Wg(i,t,n,r+1);return t}if(typeof e==`object`)for(let i of Object.values(e))Wg(i,t,n,r+1);return t}function Gg(e){let t=new Map;for(let n of e){for(let e of n.attachments??[])t.set(`attachment:${e.id}`,{key:`attachment:${e.id}`,title:e.name,detail:`${e.mediaType} · ${Jg(e.sizeBytes)}`});for(let e of n.sources??[])t.set(`source:${e.id}`,{key:`source:${e.id}`,title:e.title,detail:e.sourceName??Zg(e.url)})}return[...t.values()]}function Kg({icon:e,title:t,detail:n}){return(0,$.jsxs)(`div`,{className:`work-sidebar-empty`,children:[(0,$.jsx)(e,{size:22}),(0,$.jsx)(`strong`,{children:t}),(0,$.jsx)(`p`,{children:n})]})}function qg(e){return e.kind===`deployment`?`Deployment`:e.kind===`source_change`?`Source change`:e.kind===`external_resource`?e.provider:e.kind===`agent_package`?`${e.actions.length} action${e.actions.length===1?``:`s`}`:e.location.kind===`local`?Jg(e.sizeBytes):e.location.kind===`managed`?`Managed file`:e.location.provider}function Jg(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1048576).toFixed(1)} MB`}function Yg(e){let t=window.atob(e),n=new ArrayBuffer(t.length),r=new Uint8Array(n);for(let e=0;e<t.length;e+=1)r[e]=t.charCodeAt(e);return n}function Xg(e){return e.kind===`file`&&e.location.kind===`local`?e.location.path:``}function Zg(e){try{return new URL(e).hostname||e}catch{return e}}function Qg(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function $g({messages:e,events:t,actions:n,onOpenFile:r,connection:i,workspaceId:a,sandboxId:o,sessionId:s,conversationId:c,onOpenBrowser:l}){let u=(0,Q.useContext)(gu),d=ra(i),f=t.filter(e=>e.name===`visual.published`||e.name===`workspace_action_result`||e.name===`tool.completed`||e.name===`turn.completed`).at(-1)?.id??``,p=S({queryKey:[`thread-html-visuals`,d,s,f],enabled:!!(i&&s),queryFn:async()=>Co.array().parse((await Y(i,`/v1/sessions/${encodeURIComponent(s)}/visuals`)).visuals),staleTime:15e3,refetchInterval:5e3}),m=(0,Q.useMemo)(()=>{let t=new Map;for(let e of p.data??[])t.set(e.visualId,e);for(let n of e)if(n.visual){let e=t.get(n.visual.visualId);(!e||e.output.revision<n.visual.output.revision)&&t.set(n.visual.visualId,n.visual)}return[...t.values()]},[e,p.data]),h=(0,Q.useMemo)(()=>Vg(t),[t]),g=S({queryKey:[`thread-output-files`,d,s,f],placeholderData:(e,t)=>t?.queryKey[1]===d&&t.queryKey[2]===s?e:void 0,enabled:!!(i&&s),queryFn:async()=>(await Eo.sessionFiles(i,s)).files,staleTime:15e3,refetchOnWindowFocus:!0,refetchInterval:5e3}),_=(0,Q.useMemo)(()=>{if(g.data)return g.data;let t=new Map(Bg(e).map(e=>[`${o??`local`}:${e.path}`,{...e,contentType:`application/octet-stream`,sandboxId:o??null}])),n=new Set;for(let e of h)n.has(e.id)||(n.add(e.id),e.kind===`file`&&e.location.kind===`local`&&t.set(`local:${e.location.path}`,{path:e.location.path,title:e.title,sizeBytes:e.sizeBytes,contentType:e.contentType,sandboxId:null}));return[...t.values()]},[e,h,o,g.data]);return(0,$.jsxs)(`div`,{className:`right-sidebar-new-tab`,children:[(0,$.jsx)(Fg,{conversationId:c,onOpenBrowser:l}),(0,$.jsxs)(`div`,{className:`right-sidebar-overview`,children:[(0,$.jsxs)(`section`,{className:`right-sidebar-overview-files`,"aria-label":`Outputs`,children:[(0,$.jsx)(`h3`,{children:`Outputs`}),_.length||m.length?(0,$.jsxs)($.Fragment,{children:[m.map(e=>(0,$.jsxs)(`div`,{className:`activity-artifact`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`activity-artifact-name`,onClick:()=>u?.(e),"aria-label":`Open ${e.output.title} in browser panel`,children:[(0,$.jsx)(Ta,{size:14,"aria-hidden":!0}),(0,$.jsx)(`strong`,{children:e.output.title})]}),(0,$.jsxs)(`span`,{className:`activity-artifact-actions`,children:[`HTML`,e.output.revision>1?` · Revision ${e.output.revision}`:``]})]},e.publicationId)),_.map(e=>(0,$.jsx)(Du,{artifact:e,onOpenFileInSidebar:t=>r(t,{sandboxId:e.sandboxId,local:!e.sandboxId}),preview:(0,$.jsx)(Lg,{revision:e.revision,path:e.path,connection:i,workspaceId:a,sandboxId:e.sandboxId})},`${e.sandboxId??`local`}:${e.path}`))]}):(0,$.jsx)(`p`,{className:`right-sidebar-output-empty`,children:`Outputs from this chat will appear here.`})]}),(0,$.jsxs)(`section`,{className:`right-sidebar-overview-tools`,"aria-label":`Tools`,children:[(0,$.jsx)(`h3`,{children:`Tools`}),n]})]})]})}function e_({value:e}){let{preservation:t,reload:n}=e;return(0,$.jsxs)(`section`,{"aria-label":`AlphaEdit measured comparisons`,children:[(0,$.jsx)(`h4`,{children:`Measured comparisons`}),(0,$.jsxs)(`p`,{children:[`Measured on reviewed training inputs; held-out quality is unmeasured. Before refers to the`,` `,e.startingState===`parent`?`retained parent patch`:`original base model`,`. Target NLL means are weighted over target tokens across all contexts.`]}),(0,$.jsx)(`div`,{className:`evaluation-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`caption`,{children:`Teacher-forced target NLL on reviewed edits`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:`Edit`}),(0,$.jsx)(`th`,{scope:`col`,children:`Contexts`}),(0,$.jsx)(`th`,{scope:`col`,children:`Target tokens`}),(0,$.jsx)(`th`,{scope:`col`,children:`Before NLL`}),(0,$.jsx)(`th`,{scope:`col`,children:`After NLL`}),(0,$.jsx)(`th`,{scope:`col`,children:`Reloaded NLL`})]})}),(0,$.jsx)(`tbody`,{children:e.edits.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.id}),(0,$.jsx)(`td`,{children:e.contextCount.toLocaleString()}),(0,$.jsx)(`td`,{children:e.targetTokens.toLocaleString()}),(0,$.jsx)(`td`,{children:e.beforeMeanTargetNll}),(0,$.jsx)(`td`,{children:e.afterMeanTargetNll}),(0,$.jsx)(`td`,{children:e.reloadedMeanTargetNll})]},e.id))})]})}),(0,$.jsx)(`div`,{className:`evaluation-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsxs)(`caption`,{children:[`Next-token distribution KL across `,e.vocabularySize.toLocaleString(),` vocabulary entries`]}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:`Comparison`}),(0,$.jsx)(`th`,{scope:`col`,children:`Measured inputs`}),(0,$.jsx)(`th`,{scope:`col`,children:`Mean KL`}),(0,$.jsx)(`th`,{scope:`col`,children:`Maximum KL`})]})}),(0,$.jsxs)(`tbody`,{children:[(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:`Preservation · KL(final edited || starting)`}),(0,$.jsxs)(`td`,{children:[t.examples.toLocaleString(),` reviewed examples ·`,` `,t.comparedPositions.toLocaleString(),` final non-padding positions`]}),(0,$.jsx)(`td`,{children:t.meanNextTokenKl}),(0,$.jsx)(`td`,{children:t.maximumNextTokenKl})]}),(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:`Reload · KL(reloaded patch || final edited)`}),(0,$.jsxs)(`td`,{children:[n.comparedTargetTokens.toLocaleString(),` target tokens ·`,` `,n.comparedPreservationPositions.toLocaleString(),` preservation positions`]}),(0,$.jsx)(`td`,{children:n.meanNextTokenKl}),(0,$.jsx)(`td`,{children:n.maximumNextTokenKl})]})]})]})}),(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Reload reference`}),(0,$.jsx)(`dd`,{children:`Final edited model`}),(0,$.jsx)(`dt`,{children:`Reload equivalence`}),(0,$.jsx)(`dd`,{children:n.equivalent?`Equivalent under recorded checks`:`Not equivalent under recorded checks`}),(0,$.jsx)(`dt`,{children:`Absolute tolerance`}),(0,$.jsx)(`dd`,{children:n.absoluteTolerance}),(0,$.jsx)(`dt`,{children:`Maximum absolute per-token target NLL difference`}),(0,$.jsx)(`dd`,{children:n.maximumAbsoluteTargetNllDifference}),(0,$.jsx)(`dt`,{children:`Maximum absolute log-probability difference`}),(0,$.jsx)(`dd`,{children:n.maximumAbsoluteLogProbabilityDifference})]})]})}function t_({result:e}){let t=e.schemaVersion===`openpond.alphaEditTrainingResult.v1`;return(0,$.jsxs)(ft,{title:t?`AlphaEdit result`:`Neuron training result`,children:[(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Duration`}),(0,$.jsxs)(`dd`,{children:[(e.durationMs/1e3).toLocaleString(),` seconds`]}),(0,$.jsx)(`dt`,{children:`Forward token work`}),(0,$.jsx)(`dd`,{children:e.forwardTokenWork.toLocaleString()}),e.schemaVersion===`openpond.alphaEditTrainingResult.v1`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Edits processed`}),(0,$.jsx)(`dd`,{children:e.editsProcessed}),(0,$.jsx)(`dt`,{children:`Latent optimizer steps`}),(0,$.jsx)(`dd`,{children:e.latentOptimizerSteps}),(0,$.jsx)(`dt`,{children:`Untouched weights before`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.untouchedWeightsHashBefore}),(0,$.jsx)(`dt`,{children:`Untouched weights after`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.untouchedWeightsHashAfter}),(0,$.jsx)(`dt`,{children:`Edited weights before`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.editedWeightsHashBefore}),(0,$.jsx)(`dt`,{children:`Edited weights after`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.editedWeightsHashAfter})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Selection`}),(0,$.jsxs)(`dd`,{children:[e.selection.source,` · `,e.selection.entries.length,` of`,` `,e.selection.eligibleCount.toLocaleString(),` eligible neurons`]}),(0,$.jsx)(`dt`,{children:`Optimizer steps`}),(0,$.jsx)(`dd`,{children:e.optimizerSteps}),(0,$.jsx)(`dt`,{children:`Examples processed`}),(0,$.jsx)(`dd`,{children:e.examplesProcessed}),(0,$.jsx)(`dt`,{children:`Trainable parameters`}),(0,$.jsx)(`dd`,{children:e.trainableParameterCount.toLocaleString()}),(0,$.jsx)(`dt`,{children:`Mean loss`}),(0,$.jsx)(`dd`,{children:e.meanLoss}),(0,$.jsx)(`dt`,{children:`Final loss`}),(0,$.jsx)(`dd`,{children:e.finalLoss}),(0,$.jsx)(`dt`,{children:`Mean preservation KL`}),(0,$.jsx)(`dd`,{children:e.meanPreservationKl??`Preservation disabled`}),(0,$.jsx)(`dt`,{children:`Base weights before`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.baseWeightsHashBefore}),(0,$.jsx)(`dt`,{children:`Base weights after`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.baseWeightsHashAfter})]})]}),e.schemaVersion===`openpond.alphaEditTrainingResult.v1`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(e_,{value:e.comparisons}),(0,$.jsx)(`div`,{className:`evaluation-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`caption`,{children:`Latent target optimization objective`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Edit`}),(0,$.jsx)(`th`,{children:`Initial loss`}),(0,$.jsx)(`th`,{children:`Final loss`}),(0,$.jsx)(`th`,{children:`Optimizer steps`})]})}),(0,$.jsx)(`tbody`,{children:e.targetLosses.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.id}),(0,$.jsx)(`td`,{children:e.initial}),(0,$.jsx)(`td`,{children:e.final}),(0,$.jsx)(`td`,{children:e.optimizerSteps})]},e.id))})]})}),(0,$.jsx)(`div`,{className:`evaluation-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`caption`,{children:`Layer evidence`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Layer`}),(0,$.jsx)(`th`,{children:`Preservation tokens`}),(0,$.jsx)(`th`,{children:`Nullspace rank`}),(0,$.jsx)(`th`,{children:`Update norm`}),(0,$.jsx)(`th`,{children:`Solve residual`}),(0,$.jsx)(`th`,{children:`Sequential keys`})]})}),(0,$.jsx)(`tbody`,{children:e.layerEvidence.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.layer}),(0,$.jsx)(`td`,{children:e.preservationTokens}),(0,$.jsx)(`td`,{children:e.nullspaceRank}),(0,$.jsx)(`td`,{children:e.updateFrobeniusNorm}),(0,$.jsx)(`td`,{children:e.solveRelativeResidual}),(0,$.jsx)(`td`,{children:e.sequentialKeyCount})]},e.layer))})]})})]}):(0,$.jsx)(`div`,{className:`evaluation-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`caption`,{children:`Selected neurons`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Layer`}),(0,$.jsx)(`th`,{children:`Neuron`}),(0,$.jsx)(`th`,{children:`Target activity`}),(0,$.jsx)(`th`,{children:`Background activity`}),(0,$.jsx)(`th`,{children:`Ratio`}),(0,$.jsx)(`th`,{children:`Gradient norm`}),(0,$.jsx)(`th`,{children:`Score`})]})}),(0,$.jsx)(`tbody`,{children:e.selection.entries.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.layer}),(0,$.jsx)(`td`,{children:e.neuron}),(0,$.jsx)(`td`,{children:e.targetMeanAbsolute}),(0,$.jsx)(`td`,{children:e.backgroundMeanAbsolute}),(0,$.jsx)(`td`,{children:e.backgroundTargetRatio}),(0,$.jsx)(`td`,{children:e.gradientNorm}),(0,$.jsx)(`td`,{children:e.score})]},`${e.layer}:${e.neuron}`))})]})}),(0,$.jsx)(`div`,{className:`evaluation-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`caption`,{children:`Committed output files`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`File`}),(0,$.jsx)(`th`,{children:`Bytes`}),(0,$.jsx)(`th`,{children:`SHA-256`})]})}),(0,$.jsx)(`tbody`,{children:e.artifact.files.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.path}),(0,$.jsx)(`td`,{children:e.sizeBytes.toLocaleString()}),(0,$.jsx)(`td`,{className:`saved-model-version-reference`,children:e.sha256})]},e.path))})]})}),(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Artifact`}),(0,$.jsx)(`dd`,{children:e.artifact.id}),(0,$.jsx)(`dt`,{children:`Artifact hash`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.artifact.contentHash}),(0,$.jsx)(`dt`,{children:`Result hash`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.contentHash})]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Complete retained evidence`}),(0,$.jsx)(`pre`,{className:`saved-model-version-reference`,children:JSON.stringify(e,null,2)})]})]})}function n_({input:e,id:t}){let n=typeof e.prompt==`string`?e.prompt:typeof e.request==`string`?e.request:null,r=Object.fromEntries(Object.entries(e).filter(([e])=>e!==`prompt`&&e!==`request`)),i=Object.keys(r).length>0;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{tabIndex:0,"aria-label":`Input for ${t}`,children:i?JSON.stringify(r,null,2):n??JSON.stringify(e,null,2)}),i&&n?(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Full prompt`}),(0,$.jsx)(`pre`,{children:n})]}):null]})}function r_({connection:e,dataset:t}){let[n,r]=(0,Q.useState)(0),i=S({queryKey:[`training-dataset-rows`,ra(e),cf(t),t.revision],staleTime:6e4,queryFn:async({signal:n})=>{let r=await ko(e,`dataset`,{action:`read`,id:t.id,expectedRevision:t.revision},n);if(cf(r.summary)!==cf(t)||r.summary.revision!==t.revision)throw Error(`Dataset rows do not match the selected revision.`);return r}}),a=i.data?.record.workspace.draft.tasks??[],o=Math.max(1,Math.ceil(a.length/5)),s=Math.min(n,o-1);return(0,$.jsxs)(`section`,{className:`dataset-row-preview`,"aria-label":`Examples from ${t.name}, revision ${t.revision}`,children:[(0,$.jsx)(X,{error:i.error?.message,children:i.error?(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void i.refetch(),children:`Retry rows`}):null}),(0,$.jsx)(`div`,{className:`training-table-wrap`,children:(0,$.jsxs)(`table`,{className:`training-data-table evaluation-workspace-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Example`}),(0,$.jsx)(`th`,{children:`Input`}),(0,$.jsx)(`th`,{children:`Split`})]})}),(0,$.jsx)(`tbody`,{children:a.slice(s*5,s*5+5).map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.id}),(0,$.jsxs)(`td`,{children:[(0,$.jsx)(n_,{input:e.input,id:e.id}),e.expectedOutput?(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Expected output`}),(0,$.jsx)(`pre`,{children:JSON.stringify(e.expectedOutput,null,2)})]}):null]}),(0,$.jsx)(`td`,{children:e.split})]},e.id))})]})}),i.isPending?(0,$.jsx)(`p`,{role:`status`,children:`Loading examples…`}):!a.length&&!i.error?(0,$.jsx)(`p`,{children:`No saved examples.`}):null,o>1?(0,$.jsxs)(`div`,{className:`training-rollout-pagination`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:!s,onClick:()=>r(s-1),children:`Previous`}),(0,$.jsxs)(`span`,{children:[s*5+1,`–`,Math.min(a.length,(s+1)*5),` of `,a.length]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:s+1===o,onClick:()=>r(s+1),children:`Next`})]}):null]})}function i_({title:e,children:t,open:n=!1,onOpenChange:r}){return(0,$.jsxs)(`details`,{className:`training-workspace-section`,open:n,onToggle:e=>r?.(e.currentTarget.open),children:[(0,$.jsx)(`summary`,{children:e}),(0,$.jsx)(`div`,{className:`training-workspace-section-content`,children:t})]})}function a_({dataset:e,graders:t,model:n,connection:r}){let[i,a]=(0,Q.useState)(!1),o=n?[{role:`Training`,dataset:n.trainingDataset},{role:`Evaluation`,dataset:n.evaluationDataset}].filter(e=>e.dataset):[];return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(i_,{title:`Dataset`,open:i,onOpenChange:a,children:[(0,$.jsx)(`div`,{className:`training-table-wrap`,children:(0,$.jsxs)(`table`,{className:`training-data-table evaluation-workspace-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[n?(0,$.jsx)(`th`,{children:`Use`}):null,(0,$.jsx)(`th`,{children:`Dataset`}),(0,$.jsx)(`th`,{children:`Revision`}),n?null:(0,$.jsx)(`th`,{children:`Examples`})]})}),(0,$.jsx)(`tbody`,{children:n?o.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.role}),(0,$.jsx)(`td`,{children:e.dataset.name}),(0,$.jsx)(`td`,{children:e.dataset.revision})]},e.role)):e?(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.name}),(0,$.jsx)(`td`,{children:e.revision}),(0,$.jsx)(`td`,{children:e.taskCount??`—`})]}):null})]})}),i&&e&&r&&!n?(0,$.jsx)(r_,{connection:r,dataset:e},`${e.id}:${e.revision}`):null,n?(0,$.jsx)(`p`,{className:`chat-context-note`,children:`Model configuration. Each training run retains its own input snapshot.`}):null,!e&&!o.length?(0,$.jsx)(`p`,{children:`No dataset configured.`}):null]}),(0,$.jsx)(i_,{title:`Graders`,children:t.length?(0,$.jsx)(`div`,{className:`training-table-wrap`,children:(0,$.jsxs)(`table`,{className:`training-data-table evaluation-workspace-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Grader`}),(0,$.jsx)(`th`,{children:`Type`}),(0,$.jsx)(`th`,{children:`Checks`})]})}),(0,$.jsx)(`tbody`,{children:t.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.name}),(0,$.jsx)(`td`,{children:e.graderType??`—`}),(0,$.jsx)(`td`,{children:e.checkState??e.state})]},e.id))})]})}):(0,$.jsx)(`p`,{children:n?`Inspect the model’s training dataset for its grader definitions.`:`No graders configured for this dataset revision.`})})]})}var o_=(0,Q.createContext)(null);function s_({targets:e}){let t=(0,Q.useContext)(o_);return t&&e?.length?(0,$.jsx)(c_,{...t,targets:e}):null}function c_({connection:e,teamId:t,jobId:n,targets:r}){let[i,a]=(0,Q.useState)(()=>JSON.stringify(r[0])),o=r.find(e=>JSON.stringify(e)===i)??r[0],s=S({queryKey:[`retained-run-feedback`,ra(e),t,n,o.kind,o.id,o.taskId??null],queryFn:async({signal:r})=>{let i=new URLSearchParams({teamId:t,kind:o.kind,id:o.id,...o.taskId?{taskId:o.taskId}:{}}),a=Zr.parse(await Y(e,`/v1/training/hosted-jobs/${encodeURIComponent(n)}/feedback?${i}`,{signal:r}));if(a.jobId!==n||a.id!==o.id||a.kind!==o.kind||a.taskId!==o.taskId)throw Error(`Grader feedback belongs to another run or attempt.`);return a},staleTime:1/0,gcTime:3e5,retry:!1});return(0,$.jsxs)(`section`,{className:`retained-run-feedback`,children:[(0,$.jsx)(`h3`,{children:`Retained grader feedback`}),r.length>1?(0,$.jsx)(Z,{label:`Feedback record`,value:JSON.stringify(o),options:r.map(e=>({value:JSON.stringify(e),label:e.kind===`trajectory`?`Trajectory ${e.id.slice(0,6)}…`:`Task ${e.taskId?.slice(0,6)}… · evaluation ${e.id.slice(0,6)}…`})),onChange:a}):null,(0,$.jsx)(X,{error:s.error}),s.isPending?(0,$.jsx)(`p`,{role:`status`,children:`Loading verified grader receipt…`}):null,s.isError?(0,$.jsx)(`button`,{className:`training-button secondary`,type:`button`,onClick:()=>void s.refetch(),children:`Retry grader feedback`}):null,s.data?(0,$.jsx)(u_,{value:s.data}):null]})}var l_=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:{};function u_({value:e}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[`Training reward: `,e.training.status,` · score `,e.training.score??`not retained`]}),(0,$.jsxs)(`p`,{children:[`Evaluation graders: `,e.evaluation.status,` · score `,e.evaluation.score??`not retained`,` · recorded aggregate acceptance `,e.evaluation.passed===null?`not retained`:String(e.evaluation.passed)]}),(0,$.jsxs)(`p`,{className:`training-muted`,children:[`Verified composition `,e.compositionSha256.slice(0,12),`…`]}),e.graders.length?null:(0,$.jsx)(`p`,{className:`training-muted`,children:`No grader records retained in this receipt; quality is not established.`}),e.graders.map(e=>(0,$.jsxs)(`article`,{children:[(0,$.jsxs)(`h4`,{children:[e.graderId,` · `,e.role]}),(0,$.jsxs)(`p`,{children:[e.status,` · raw score `,e.rawScore??`not retained`,` · normalized score `,e.normalizedScore??`not retained`,` · grader verdict `,e.passed===!0?`Passed`:e.passed===!1?`Failed`:`No verdict retained`]}),e.message?(0,$.jsx)(`p`,{children:e.message}):null,e.failureClass?(0,$.jsxs)(`p`,{children:[`Recorded failure: `,e.failureClass]}):null,e.feedback.map((e,t)=>(0,$.jsx)(d_,{text:e},t)),e.feedback.length?null:(0,$.jsx)(`p`,{className:`training-muted`,children:`No feedback text retained by this grader.`})]},`${e.role}:${e.graderId}`))]})}function d_({text:e}){let t={};try{t=l_(JSON.parse(e))}catch{}let n=l_(t.diagnostics).differences;return Array.isArray(n)?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dl`,{children:n.slice(0,80).map((e,t)=>{let n=l_(e);return(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`dt`,{children:[typeof n.kind==`string`?n.kind.replaceAll(`_`,` `):`Retained difference`,` · `,typeof n.path==`string`?n.path:`Path not retained`]}),(0,$.jsx)(`dd`,{children:(0,$.jsxs)(`pre`,{children:[`Expected: `,JSON.stringify(n.expected)??`Not retained`,`
11
11
  `,`Actual: `,JSON.stringify(n.actual)??`Not retained`]})})]},t)})}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Full retained grader message`}),(0,$.jsx)(`pre`,{children:e})]})]}):(0,$.jsx)(`pre`,{children:e})}var f_=(0,Q.createContext)(null);function p_({title:e,status:t,facts:n,feedback:r}){return(0,$.jsxs)(`section`,{"aria-label":`${e} evidence`,className:`run-evidence-panel`,children:[(0,$.jsxs)(`header`,{children:[(0,$.jsxs)(`h3`,{children:[e,` evidence`]}),(0,$.jsx)(`span`,{className:`training-muted`,children:t})]}),(0,$.jsx)(`p`,{className:`training-muted`,children:`Execution records describe what ran. Task acceptance and learning quality come from retained grader evidence.`}),n?.length?(0,$.jsx)(`dl`,{children:n.map((e,t)=>(0,$.jsxs)(`div`,{"data-severity":e.severity,children:[(0,$.jsx)(`dt`,{children:e.label}),(0,$.jsx)(`dd`,{children:e.value.length>360?(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Inspect retained details`}),(0,$.jsx)(`pre`,{children:e.value})]}):(0,$.jsx)(`pre`,{children:e.value})})]},`${e.label}:${t}`))}):(0,$.jsx)(`p`,{className:`training-muted`,children:`No additional diagnostic receipt retained for this stage.`}),(0,$.jsx)(s_,{targets:r})]})}var m_=new Map([[`Grade`,`Rollouts`],[`Save checkpoint`,`Update adapter`]]);function h_({nodes:e,live:t,loopLabel:n=`Training groups`,inference:r,groupLabel:i,policyLabel:a,continuation:o}){let s=(0,Q.useContext)(f_),[c,l]=(0,Q.useState)(null),u=e.filter(t=>!m_.has(t.label)||!e.some(e=>e.label===m_.get(t.label))),d=u.filter(e=>!e.inLoop&&u.indexOf(e)<u.findIndex(e=>e.inLoop)),f=u.filter(e=>e.inLoop),p=u.filter(e=>!e.inLoop&&!d.includes(e)),m=t&&e.some(e=>e.inLoop&&e.state===`active`),h=n=>{let i=e.find(e=>m_.get(e.label)===n.label);return(0,$.jsxs)(`li`,{className:`sidebar-run-cluster ${i?`has-branch`:``}`,children:[i?(0,$.jsxs)(`div`,{className:`sidebar-run-branch`,children:[(0,$.jsx)(g_,{node:{...i,compute:`cpu`},live:t}),(0,$.jsx)(Ql,{className:`sidebar-run-branch-arrow`,size:14,"aria-hidden":!0})]}):null,n.label===`Finish`&&o?(0,$.jsx)(ei,{continuation:o}):null,(0,$.jsx)(g_,{node:n,live:t}),n.label===`Prepare`&&r?(0,$.jsxs)(`div`,{className:`sidebar-run-worker`,children:[(0,$.jsx)(Ql,{size:14,"aria-hidden":!0}),(0,$.jsx)(g_,{node:{...r,compute:`gpu`},live:t})]}):null]},n.label)};return(0,$.jsxs)(f_.Provider,{value:s??l,children:[(0,$.jsxs)(`div`,{className:`run-flow sidebar-run-flow ${t?`live`:``}`,"aria-label":`Run stages`,children:[(0,$.jsxs)(`div`,{className:`run-flow-compute-legend`,"aria-label":`Compute colors`,children:[(0,$.jsx)(`span`,{className:`compute-gpu`,children:`GPU`}),(0,$.jsx)(`span`,{className:`compute-cpu`,children:`CPU`})]}),d.length?(0,$.jsx)(`ol`,{className:`sidebar-run-path`,children:d.map(h)}):null,f.length?(0,$.jsxs)($.Fragment,{children:[d.length?(0,$.jsx)(Zl,{className:`sidebar-run-next`,size:16,"aria-hidden":!0}):null,(0,$.jsxs)(`section`,{className:`sidebar-run-loop ${m?`active`:``}`,"aria-label":n,children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`span`,{children:n}),a?(0,$.jsxs)(`span`,{className:`training-policy-label`,children:[a,(0,$.jsx)(ui,{continuation:o})]}):null]}),(0,$.jsx)(`ol`,{className:`sidebar-run-path`,children:f.map(h)}),(0,$.jsx)(`div`,{className:`sidebar-run-return`,children:(0,$.jsx)(`span`,{children:i??`Repeat for each group`})})]})]}):null,p.length?(0,$.jsxs)($.Fragment,{children:[d.length||f.length?(0,$.jsx)(Zl,{className:`sidebar-run-next`,size:16,"aria-hidden":!0}):null,(0,$.jsx)(`ol`,{className:`sidebar-run-path sidebar-run-final`,children:p.map(h)})]}):null]}),c&&!s?(0,$.jsx)(p_,{...c}):null]})}function g_({node:e,live:t}){let[n,r]=(0,Q.useState)(!1),i=(0,Q.useContext)(f_),a=e.diagnostics?.filter(e=>e.severity!==`info`)??[],o=e.error&&!a.some(t=>t.value.includes(e.error))?e.error:null,s=a.length+ +!!o,c=[e.detail,...a.slice(0,2).map(e=>`${e.label}: ${e.value.slice(0,180)}`),o?.slice(0,200)].filter(Boolean).join(`. `),{triggerProps:l,tooltip:u,hideTooltip:d}=ti((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`strong`,{children:e.label}),(0,$.jsx)(`span`,{children:e.status}),c?(0,$.jsx)(`span`,{children:c}):null,(0,$.jsx)(`small`,{children:`Select to inspect retained evidence.`})]})),f={title:e.label,status:e.status,feedback:e.feedback,facts:[...e.diagnostics??[],...e.error?[{label:`Recorded stage failure`,value:e.error,severity:`error`}]:[]]},p=e.compute??([`Baseline evaluation`,`Rollouts`,`Update adapter`,`Activate policy`,`Evaluate`].includes(e.label)?`gpu`:void 0),m=t&&e.state===`active`,h=e.progress===void 0?void 0:Math.round(Math.min(1,Math.max(0,e.progress))*100);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`sidebar-run-card ${e.state} ${p?`compute-${p}`:``}`,"aria-current":m?`step`:void 0,children:[(0,$.jsx)(`button`,{...l,type:`button`,className:`sidebar-run-inspect`,onClick:()=>{d(),i?i(f):r(!0)},"aria-label":`Inspect ${e.label} evidence`}),(0,$.jsxs)(`div`,{className:`sidebar-run-card-heading`,children:[(0,$.jsx)(`strong`,{children:e.label}),p?(0,$.jsx)(`span`,{children:p.toUpperCase()}):null]}),(0,$.jsx)(`span`,{className:`sidebar-run-status`,children:e.status}),e.detail?(0,$.jsx)(`span`,{className:`sidebar-run-detail`,children:e.detail}):null,s?(0,$.jsxs)(`span`,{className:`sidebar-run-detail`,children:[s,` retained warnings or failures`]}):null,m||h!==void 0?(0,$.jsx)(`div`,{className:`sidebar-run-progress ${m&&h===void 0?`indeterminate`:``}`,role:h===void 0?void 0:`progressbar`,"aria-label":`${e.label} progress`,"aria-valuemin":h===void 0?void 0:0,"aria-valuemax":h===void 0?void 0:100,"aria-valuenow":h,children:(0,$.jsx)(`span`,{style:h===void 0?void 0:{width:`${h}%`}})}):null]}),u,n&&!i?(0,$.jsx)(p_,{...f}):null]})}function __(e){return(0,$.jsx)(h_,{...e})}var v_=[{label:`Prepare`,state:`pending`,status:`Not started`},{label:`Rollouts`,compute:`gpu`,state:`pending`,status:`Not started`,inLoop:!0},{label:`Grade`,compute:`cpu`,state:`pending`,status:`Not started`,inLoop:!0},{label:`Update adapter`,compute:`gpu`,state:`pending`,status:`Not started`,inLoop:!0},{label:`Save checkpoint`,compute:`cpu`,state:`pending`,status:`Not started`,inLoop:!0},{label:`Activate policy`,compute:`gpu`,state:`pending`,status:`Not started`,inLoop:!0},{label:`Evaluate`,compute:`gpu`,state:`pending`,status:`Not started`},{label:`Finish`,state:`pending`,status:`Not started`}];function y_(){return(0,$.jsx)(__,{nodes:v_,live:!1,loopLabel:`Training groups`,inference:{label:`GPU worker`,compute:`gpu`,state:`pending`,status:`Not allocated`}})}function b_({path:e}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`path`,{d:e,className:`run-flow-stream`}),[0,.6].map(t=>(0,$.jsx)(`circle`,{r:2.5,className:`run-flow-packet`,children:(0,$.jsx)(`animateMotion`,{dur:`1.2s`,begin:`-${t}s`,repeatCount:`indefinite`,path:e})},t))]})}function x_({node:e,x:t,y:n,width:r,animated:i}){let[a,o]=(0,Q.useState)(!1),s=(0,Q.useContext)(f_),c={title:e.label,status:e.status,feedback:e.feedback,facts:[...e.diagnostics??[],...e.error?[{label:`Recorded stage failure`,value:e.error,severity:`error`}]:[]]},l=()=>{p(),s?s(c):o(!0)},u=e.diagnostics?.filter(e=>e.severity!==`info`).slice(0,2).map(e=>`${e.label}: ${e.value.slice(0,180)}`).join(`. `),{triggerProps:d,tooltip:f,hideTooltip:p}=ti((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`strong`,{children:e.label}),(0,$.jsxs)(`span`,{children:[e.status,e.detail?` · ${e.detail}`:``]}),u||e.error?(0,$.jsx)(`span`,{children:u||e.error?.slice(0,240)}):null,(0,$.jsx)(`small`,{children:`Select to inspect retained evidence.`})]})),m=e.diagnostics?.filter(e=>e.severity!==`info`)??[],h=(0,Q.useId)().replace(/[^\w-]/g,``),g=r-28,_=e.state===`active`,v=e=>e.length>Math.floor((r-24)/6)?`${e.slice(0,Math.floor((r-24)/6)-1)}…`:e,y=e.compute??([`Grade`,`Save checkpoint`].includes(e.label)?`cpu`:[`Baseline evaluation`,`Rollouts`,`Update adapter`,`Activate policy`,`Evaluate`].includes(e.label)?`gpu`:void 0);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`g`,{...d,role:`button`,tabIndex:0,onClick:l,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),l())},"aria-label":`Inspect ${e.label} execution evidence`,className:`run-flow-node ${e.state} ${y?`compute-${y}`:``}`,"aria-current":_?`step`:void 0,children:[(0,$.jsx)(`rect`,{className:`run-flow-box`,x:t,y:n,width:r,height:72,rx:10}),m.length?(0,$.jsx)(`text`,{className:`run-flow-label`,x:t+r-31,y:n+13,children:`!`}):null,(0,$.jsx)(`text`,{className:`run-flow-label`,x:t+12,y:n+20,children:v(e.label)}),(0,$.jsx)(`text`,{className:`run-flow-status`,x:t+12,y:n+37,children:v(e.status)}),e.detail?(0,$.jsx)(`text`,{className:`run-flow-detail`,x:t+12,y:n+53,children:v(e.detail)}):null,_||e.progress!==void 0?(0,$.jsxs)(`g`,{clipPath:`url(#${h})`,children:[(0,$.jsx)(`clipPath`,{id:h,children:(0,$.jsx)(`rect`,{x:t+14,y:n+64,width:g,height:2,rx:1})}),(0,$.jsx)(`rect`,{className:`run-flow-track`,x:t+14,y:n+64,width:g,height:2}),e.progress===void 0?null:(0,$.jsx)(`rect`,{className:`run-flow-fill`,x:t+14,y:n+64,width:g*Math.min(1,Math.max(0,e.progress)),height:2}),_&&i?(0,$.jsx)(`rect`,{className:`run-flow-shimmer`,x:t+14,y:n+64,width:g/3,height:2,children:(0,$.jsx)(`animate`,{attributeName:`x`,from:t+14-g/3,to:t+14+g,dur:`1.4s`,repeatCount:`indefinite`})}):null]}):null]}),f,a&&!s?(0,$.jsx)(p_,{...c}):null]})}function S_({nodes:e,inference:t,live:n,loopLabel:r,groupLabel:i,policyLabel:a,continuation:o}){let s=(0,Q.useId)().replace(/[^\w-]/g,``),c=8,l=e.map((e,t)=>{let n=[`Grade`,`Save checkpoint`].includes(e.label);return!n&&t&&(c+=176),{x:c,y:n?40:140}}),u=c+140+8,d=l[e.findIndex(e=>e.label===`Finish`)],f=e.flatMap((e,t)=>e.inLoop?[t]:[]),p=f[0],m=f.at(-1),h=n&&f.some(t=>e[t]?.state===`active`),g=e.slice(1).map((e,t)=>{let r=l[t],i=l[t+1];return{id:`stage-${t}`,path:r.x===i.x?`M${r.x+70} ${r.y} V${i.y+72}`:`M${r.x+140} ${r.y+36} H${r.x+140+18} V${i.y+36} H${i.x}`,active:n&&e.state===`active`}});return t&&l[0]&&g.push({id:`gpu-prepare`,path:`M${l[0].x+70} 236 V212`,active:n&&t.state===`active`&&e[0]?.state===`active`}),p!==void 0&&m!==void 0&&h&&g.push({id:`loop`,path:`M${l[m].x+70} 212 V228 H${l[p].x+70} V212`,active:!0}),(0,$.jsxs)(`div`,{className:`console-run-flow`,"aria-label":`Training rollout flow`,children:[(0,$.jsxs)(`div`,{className:`run-flow-compute-legend`,"aria-label":`Compute colors`,children:[(0,$.jsx)(`span`,{className:`compute-gpu`,children:`GPU`}),(0,$.jsx)(`span`,{className:`compute-cpu`,children:`CPU`})]}),(0,$.jsxs)(`svg`,{className:`run-flow-diagram`,viewBox:`0 0 ${u} 320`,style:{minWidth:u*.75,maxWidth:u*1.35},role:`group`,"aria-label":e.map(e=>`${e.label}: ${e.status}`).join(`. `),children:[(0,$.jsx)(`defs`,{children:(0,$.jsx)(`marker`,{id:s,viewBox:`0 0 8 8`,refX:`6`,refY:`4`,markerWidth:`6`,markerHeight:`6`,orient:`auto-start-reverse`,children:(0,$.jsx)(`path`,{d:`M1 1 L7 4 L1 7`,className:`run-flow-arrow`})})}),p!==void 0&&m!==void 0?(0,$.jsxs)(`g`,{children:[(0,$.jsx)(`rect`,{className:`run-flow-loop ${h?`live`:``}`,x:l[p].x-20,y:4,width:l[m].x-l[p].x+140+40,height:228,rx:14}),(0,$.jsx)(`text`,{className:`run-flow-caption`,x:l[p].x-6,y:22,children:r}),(0,$.jsxs)(`text`,{className:`run-flow-caption`,x:l[m].x+140+6,y:22,textAnchor:`end`,children:[a,o?.optimizerMode===`reset`?(0,$.jsx)(`tspan`,{"aria-label":`Optimizer reset for this run`,children:` · optimizer reset`}):null]})]}):null,g.map(e=>(0,$.jsxs)(`g`,{children:[(0,$.jsx)(`path`,{className:`run-flow-wire`,d:e.path,markerEnd:`url(#${s})`}),e.active?(0,$.jsx)(b_,{path:e.path}):null]},e.id)),o&&d?(0,$.jsxs)(`g`,{className:`run-flow-adapter-stack`,"aria-label":`Continual adapter lineage`,children:[(0,$.jsx)(`rect`,{className:`run-flow-box`,x:d.x-12,y:4,width:132,height:64,rx:10}),(0,$.jsx)(`text`,{className:`run-flow-status`,x:d.x,y:24,children:`Frozen parent`}),(0,$.jsx)(`text`,{className:`run-flow-detail`,x:d.x,y:42,children:o.parentRank?`Rank ${o.parentRank}`:`Rank unavailable`}),(0,$.jsx)(`rect`,{className:`run-flow-box`,x:d.x,y:54,width:132,height:66,rx:10}),(0,$.jsx)(`text`,{className:`run-flow-label`,x:d.x+12,y:76,children:`Continual learning`}),(0,$.jsx)(`text`,{className:`run-flow-status`,x:d.x+12,y:93,children:`This update`}),(0,$.jsx)(`text`,{className:`run-flow-detail`,x:d.x+12,y:109,children:o.trainableRank?`Rank ${o.trainableRank}`:`Rank unavailable`}),(0,$.jsx)(`path`,{className:`run-flow-wire`,d:`M${d.x+70} 128 V140`,markerEnd:`url(#${s})`})]}):null,e.map((e,t)=>(0,$.jsx)(x_,{node:e,...l[t],width:140,animated:n},e.label)),t?(0,$.jsx)(x_,{node:{...t,compute:`gpu`},x:l[0]?.x??8,y:236,width:140,animated:n}):null]}),e.some(e=>e.error)?(0,$.jsxs)(`details`,{className:`sidebar-run-error`,children:[(0,$.jsx)(`summary`,{children:`Recorded stage failures`}),e.filter(e=>e.error).map(e=>(0,$.jsxs)(`p`,{children:[(0,$.jsx)(`strong`,{children:e.label}),`: `,e.error]},e.label))]}):null,(0,$.jsx)(`span`,{className:`training-muted`,children:i})]})}function C_({run:e,view:t,loading:n,error:r,onRefresh:i}){let a=uf(e.state),o=t?.cases??[],s=e.taskCount??o.length,c=o.filter(e=>e.output!==null).length,l=o.filter(e=>e.score!==null).length,u=o.filter(e=>![`pending`,`running`].includes(e.status)).length,d=o.filter(e=>e.status===`failed`),f=d.filter(e=>e.output===null),p=o.filter(e=>e.status===`cancelled`).length,m=/^failed$/i.test(e.state),h=e=>e.length?e.slice(0,3).map(e=>`${e.taskId}: ${e.error??e.status}`).join(`
12
- `)+(e.length>3?`\n${e.length-3} more failures in the retained results.`:``):void 0,g=a&&!o.some(e=>e.status!==`pending`),_=a&&!g&&c<s,v=a&&!g&&!_&&l<s,y=[{label:`Prepare`,state:g?`active`:o.length?`done`:`pending`,status:g?`Starting`:o.length?`Recorded`:`Waiting`},{label:`Rollouts`,state:f.length?`failed`:_?`active`:s>0&&c===s?`done`:a?`pending`:`missing`,status:f.length?`Error recorded`:_?`Generating answers`:`Model outputs`,error:h(f),detail:`${c}/${s} generated`,progress:s?c/s:0},{label:`Grade`,state:v?`active`:s>0&&l===s?`done`:a?`pending`:`missing`,status:v?`Scoring`:`Dataset graders`,detail:`${l}/${s} graded`,progress:s?l/s:0},{label:`Results`,state:m?`failed`:!a&&e.state===`completed`?`done`:a&&u===s?`active`:a?`pending`:`missing`,status:a?`Waiting for evidence`:m?`Failed`:e.state,error:m?h(d)??`The run ended with a failure. Inspect its retained cases and logs.`:void 0,detail:(e.score==null?`Score unavailable`:`Mean score ${e.score.toFixed(3)}`)+(m&&o.length?` · ${d.length} execution failure${d.length===1?``:`s`} · ${p} cancelled`:``)}];return(0,$.jsxs)(`section`,{className:`dataset-workspace-run`,"aria-label":`Selected experiment progress`,children:[(0,$.jsx)(__,{nodes:y,live:a&&!r}),r?(0,$.jsx)(X,{error:r.message,children:(0,$.jsx)(`button`,{className:`training-text-button`,onClick:i,children:`Retry`})}):n?(0,$.jsx)(`p`,{role:`status`,children:`Loading retained run evidence…`}):null]})}function w_({connection:e,run:t,view:n}){let r=n?.cases??[],i=r.filter(e=>e.score!==null).length;return r.length?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dataset-workspace-attempts`,"aria-label":`Rollout attempts`,children:r.map((e,t)=>(0,$.jsx)(`span`,{className:`dataset-workspace-attempt ${e.status===`running`?`active`:e.error?`failed`:e.score===null?`pending`:`scored`}`,style:e.score===null?void 0:{opacity:.35+.65*Math.max(0,Math.min(1,e.score))},title:`${e.taskId}: ${e.error??(e.score===null?e.status:`score ${e.score}`)}`,"aria-label":`Case ${t+1}: ${e.taskId}, ${e.score===null?e.status:`score ${e.score}`}`},e.id))}),i?(0,$.jsxs)(`details`,{className:`dataset-workspace-charts`,children:[(0,$.jsx)(`summary`,{children:`Score chart`}),(0,$.jsx)(Qr,{series:[{id:`evaluation.score`,label:`Case score`,xLabel:`Case`,bounds:r.every(e=>e.score===null||e.score>=0&&e.score<=1)?[0,1]:void 0,points:r.flatMap((e,t)=>e.score===null?[]:[{step:t+1,value:e.score}])}]})]}):null,(0,$.jsxs)(`details`,{className:`dataset-workspace-cases`,children:[(0,$.jsx)(`summary`,{children:`Answers and grader scores`}),(0,$.jsx)(`p`,{children:`Each row shows the model’s answer to one dataset task and the score given by its graders.`}),(0,$.jsx)(`div`,{className:`evaluation-table-scroll evaluation-table-frame`,children:(0,$.jsxs)(`table`,{className:`training-data-table evaluation-workspace-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Example`}),(0,$.jsx)(`th`,{children:`Status`}),(0,$.jsx)(`th`,{children:`Score`})]})}),(0,$.jsx)(`tbody`,{children:r.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsxs)(`td`,{children:[e.taskId,e.output===null?null:(0,$.jsxs)(`details`,{className:`dataset-workspace-example-answer`,children:[(0,$.jsx)(`summary`,{children:`Model answer`}),(0,$.jsx)(`pre`,{children:e.output})]})]}),(0,$.jsxs)(`td`,{children:[(0,$.jsx)(lt,{status:e.status}),e.error?(0,$.jsx)(`small`,{children:e.error}):null]}),(0,$.jsx)(`td`,{className:`evaluation-numeric`,children:e.score?.toFixed(3)??`—`})]},e.id))})]})})]}),(0,$.jsx)(T_,{connection:e,run:t,cases:r},cf(t))]}):null}function T_({connection:e,run:t,cases:n}){let[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(n[0]?.id??``),s=t.location===`local`&&!t.owner&&!t.profileRef,c=A({queryKey:[`dataset-workspace-logs`,ra(e),cf(t),a],enabled:r&&s&&!!a,initialPageParam:void 0,getNextPageParam:e=>e.trace.nextCursor??void 0,queryFn:async({signal:n,pageParam:r})=>Zc.parse(await ko(e,`experiment`,{action:`case`,payload:{id:t.id,receiptId:a,limit:100,...r?{afterSequence:r}:{}}},n)),refetchInterval:uf(t.state)?2e3:!1});return(0,$.jsxs)(`details`,{className:`dataset-workspace-logs`,onToggle:e=>i(e.currentTarget.open),children:[(0,$.jsx)(`summary`,{children:`Logs`}),s?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{compact:!0,floating:!0,label:`Log case`,value:a,options:n.map(e=>({value:e.id,label:e.taskId})),onChange:o}),c.error?(0,$.jsx)(X,{error:c.error.message}):c.isPending?(0,$.jsx)(`p`,{role:`status`,children:`Loading case trace…`}):(0,$.jsx)(`ol`,{children:c.data?.pages.flatMap(e=>e.trace.items).map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`strong`,{children:e.type.replaceAll(/[._]/g,` `)}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Details`}),(0,$.jsx)(`pre`,{children:JSON.stringify(e.payload,null,2)})]})]},e.sequence))}),c.hasNextPage?(0,$.jsx)(`button`,{className:`training-button secondary`,disabled:c.isFetchingNextPage,onClick:()=>void c.fetchNextPage(),children:`More logs`}):null]}):(0,$.jsx)(`ol`,{children:n.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`strong`,{children:e.taskId}),(0,$.jsx)(`span`,{children:e.error??e.status}),e.output?(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Output`}),(0,$.jsx)(`pre`,{children:e.output})]}):null]},e.id))})]})}var E_=z({job:Dr,events:F(zt).max(1e4),outputs:Yt,evals:Ps.nullable(),flow:$r.nullable(),flowError:U().nullable()}).strict(),D_=new Set([`completed`,`succeeded`,`failed`,`cancelled`,`budget_exhausted`]);function O_(e,t,n,r,i=!1){let a=u(),o=[`hosted-training-run`,ra(e),t,n,r??null],s=`/v1/training/hosted-jobs/${encodeURIComponent(n)}`,c=S({queryKey:[...o,`summary`],queryFn:async({signal:i})=>{let a=Dr.parse(await Y(e,`${s}/summary?teamId=${encodeURIComponent(t)}`,{signal:i}));if(a.id!==n||a.teamId!==t||r&&a.modelProjectId!==r)throw Error(`Run summary belongs to another workspace.`);return a},staleTime:3e4,gcTime:3e5,refetchInterval:e=>e.state.data&&!D_.has(e.state.data.state)?5e3:e.state.data?.usage&&!e.state.data.usage.complete?3e4:!1,refetchIntervalInBackground:!1}),l=S({queryKey:[...o,`logs`],queryFn:async({signal:n})=>$r.shape.logs.parse(await Y(e,`${s}/logs?teamId=${encodeURIComponent(t)}`,{signal:n})),enabled:i,staleTime:3e4,gcTime:3e5,refetchInterval:i&&c.data&&!D_.has(c.data.state)?5e3:!1,refetchIntervalInBackground:!1}),d=S({queryKey:[...o,`core`],queryFn:async({signal:i})=>{let a=E_.parse(await Y(e,`${s}?teamId=${encodeURIComponent(t)}&graph=false`,{signal:i}));if(a.job.id!==n||a.job.teamId!==t||r&&a.job.modelProjectId!==r)throw Error(`Run does not belong to this Model Project and workspace.`);return a},staleTime:3e4,gcTime:3e5,refetchInterval:e=>e.state.data&&(!D_.has(e.state.data.job.state)||Is(e.state.data.evals))?5e3:e.state.data?.job.usage&&!e.state.data.job.usage.complete?3e4:!1,refetchIntervalInBackground:!1}),f=S({queryKey:[...o,`flow`],queryFn:async({signal:i})=>{let a=$r.parse(await Y(e,`${s}/flow?teamId=${encodeURIComponent(t)}`,{signal:i}));if(a.jobId!==n||a.teamId!==t||r&&a.modelProjectId!==r)throw Error(`Run stages do not belong to this Model Project and workspace.`);return a},staleTime:3e4,gcTime:3e5,refetchInterval:e=>e.state.data?.live?5e3:!1,refetchIntervalInBackground:!1}),p=f.data&&(!d.data||f.data.modelProjectId===d.data.job.modelProjectId)?f.data:null,m=c.data&&(!d.data||c.data.version>=d.data.job.version)?c.data:d.data?.job??null;return{detail:d.data?{...d.data,flow:p}:null,flow:p,summary:m,logs:l.data??[],logsLoading:l.isPending,logsError:l.error?.message??null,loading:d.isPending,graphLoading:f.isPending,error:(!d.data&&!c.data?c.error?.message:null)??d.error?.message??f.error?.message??null,refresh:()=>Promise.all([c.refetch(),d.refetch(),f.refetch(),...i?[l.refetch()]:[]]),setDetail:e=>a.setQueryData([...o,`core`],e)}}function k_(e){let t=new Map;for(let n of e){let e=n.data,r=n.type===`rollout_metric`?[[`rollout.reward`,`Rollout reward`,e.reward??e.rewardMean]]:typeof e.metricId==`string`?[[e.metricId,e.metricId.replaceAll(/[._]/g,` `),e.value]]:[];for(let[i,a,o]of r){if(typeof o!=`number`||!Number.isFinite(o))continue;let r=typeof e.step==`number`?e.step:typeof e.rolloutGroupIndex==`number`?e.rolloutGroupIndex+1:n.sequence,s=t.get(i)??{id:i,label:a,xLabel:`Recorded step`,points:[]};s.points.push({step:r,value:o}),t.set(i,s)}}return[...t.values()]}function A_({evidence:e}){let t=(0,Q.useContext)(f_),[n,r]=(0,Q.useState)(null),i=t??r,a=e.groups.flatMap(e=>e.attempts.flatMap(e=>e.reward===null?[]:[e.reward])),o=Math.min(...a),s=Math.max(...a);return(0,$.jsxs)(`div`,{className:`training-rollout-groups`,"aria-label":`Attempts by rollout group`,children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`span`,{children:`Attempts by rollout group`}),(0,$.jsx)(`div`,{className:`training-rollout-legend`,children:[[`scored`,`Scored`],[`active`,`Running`],[`failed`,`Failed`],[``,`Planned`]].map(([e,t])=>(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`i`,{className:`training-rollout-cell ${e}`,"aria-hidden":!0}),t]},t))})]}),(0,$.jsx)(`ol`,{children:e.groups.map(t=>{let n=t.inherited,r=new Set(t.attempts.map(e=>e.slot)),a=Array.from({length:Math.min(1e3,t.plannedSlots)},(e,t)=>t).filter(e=>!r.has(e));return(0,$.jsxs)(`li`,{children:[(0,$.jsx)(j_,{group:t,onSelect:()=>i({title:`Rollouts`,groupIndex:t.index,status:t.state,facts:t.diagnostics})}),(0,$.jsxs)(`div`,{children:[t.replay?(0,$.jsxs)(`span`,{className:`training-muted`,children:[t.state===`consumed`?`Replayed`:`Replay pending`,` · prior output not restored`]}):null,n?(0,$.jsxs)(`span`,{className:`training-muted`,children:[`Inherited · `,n.optimizerDisposition===`applied`?`Update applied`:`Skipped · no signal`]}):t.optimizerDisposition?(0,$.jsx)(`span`,{className:`training-muted`,children:t.optimizerDisposition===`applied`?`Update applied`:`Skipped · no signal`}):null,t.attempts.map(n=>{let r=n.state.endsWith(`failed`)||[`cancelled`,`expired`,`timed_out`].includes(n.state),a=e.live&&[`running`,`leased`,`scoring`].includes(n.state),c=`Group ${t.index+1}, slot ${n.slot+1}, attempt ${n.attempt}: ${n.state}${n.reward===null?``:`, reward ${n.reward.toFixed(3)}`}`;return(0,$.jsx)(M_,{label:c,attempt:n,failed:r,active:a,opacity:n.reward===null?void 0:s>o?.35+.65*(n.reward-o)/(s-o):.8,onSelect:()=>i({title:`Rollouts`,groupIndex:t.index,status:c,facts:n.diagnostics,feedback:n.feedback})},n.id)}),a.map(e=>(0,$.jsx)(`span`,{role:`img`,"aria-label":`Group ${t.index+1}, slot ${e+1}: planned`,className:`training-rollout-cell`},`pending-${e}`))]}),(0,$.jsx)(`span`,{children:n?n.outputPolicyVersion===void 0?`v${n.inputPolicyVersion} unchanged`:`v${n.inputPolicyVersion} → v${n.outputPolicyVersion}`:t.meanReward===null?t.state:`avg ${t.meanReward.toFixed(3)}`})]},t.index)})}),n&&!t?(0,$.jsx)(p_,{...n}):null,e.groupCount>e.groups.length?(0,$.jsxs)(`p`,{children:[`Showing `,e.groups.length,` of `,e.groupCount,` rollout groups.`]}):null]})}function j_({group:e,onSelect:t}){let{triggerProps:n,tooltip:r,hideTooltip:i}=ti((0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`strong`,{children:[`Group `,e.index+1]}),(0,$.jsx)(`span`,{children:e.inherited?`Inherited source group · ${e.inherited.optimizerDisposition===`applied`?`Update applied`:`Skipped · no signal`}. No attempts were rerun here.`:`${e.state} · ${e.attempts.length} retained attempts · reward ${e.meanReward??`not scored`}`}),(0,$.jsx)(`small`,{children:`Select this group context.`})]}));return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{...n,className:`training-rollout-group-link`,type:`button`,onClick:()=>{i(),t()},children:[`Group `,e.index+1]}),r]})}function M_({label:e,attempt:t,failed:n,active:r,opacity:i,onSelect:a}){let o=t.diagnostics?.find(e=>e.severity!==`info`),{triggerProps:s,tooltip:c,hideTooltip:l}=ti((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`strong`,{children:e}),o?(0,$.jsxs)(`span`,{children:[o.label,`: `,o.value.slice(0,220)]}):null,(0,$.jsx)(`small`,{children:`Select to inspect retained attempt evidence.`})]}));return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{...s,type:`button`,onClick:()=>{l(),a()},"aria-label":e,className:`training-rollout-cell ${n?`failed`:r?`active`:t.reward===null?``:`scored`}`,style:{opacity:i}}),c]})}function N_({groups:e}){let[t,n]=(0,Q.useState)(!1),[r,i]=(0,Q.useState)(0),a=e.reduce((e,t)=>e+t.attempts.length,0);if(!a)return null;let o=Math.ceil(a/100)-1,s=Math.min(r,o),c=t?e.flatMap(e=>e.attempts.map(t=>({group:e.index,...t}))).slice(s*100,(s+1)*100):[];return(0,$.jsxs)(`details`,{className:`training-rollout-attempts`,onToggle:e=>n(e.currentTarget.open),children:[(0,$.jsxs)(`summary`,{children:[`Recorded attempts · `,a]}),t?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`training-table-wrap`,children:(0,$.jsxs)(`table`,{className:`training-data-table evaluation-workspace-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Group / slot`}),(0,$.jsx)(`th`,{children:`Attempt`}),(0,$.jsx)(`th`,{children:`State`}),(0,$.jsx)(`th`,{children:`Reward`}),(0,$.jsx)(`th`,{children:`Retained feedback`})]})}),(0,$.jsx)(`tbody`,{children:c.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsxs)(`td`,{children:[e.group+1,` / `,e.slot+1]}),(0,$.jsx)(`td`,{children:e.attempt}),(0,$.jsx)(`td`,{children:e.state.replaceAll(`_`,` `)}),(0,$.jsx)(`td`,{children:e.reward===null?`—`:e.reward.toFixed(3)}),(0,$.jsx)(`td`,{children:(0,$.jsx)(P_,{attempt:e})})]},e.id))})]})}),o>0?(0,$.jsxs)(`div`,{className:`training-rollout-pagination`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:!s,onClick:()=>i(s-1),children:`Previous`}),(0,$.jsxs)(`span`,{"aria-live":`polite`,children:[s*100+1,`–`,Math.min(a,(s+1)*100),` of `,a]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:s===o,onClick:()=>i(s+1),children:`Next`})]}):null]}):null]})}function P_({attempt:e}){let[t,n]=(0,Q.useState)(!1);return!e.diagnostics?.length&&!e.feedback?.length?(0,$.jsx)($.Fragment,{children:`No grading receipt retained`}):(0,$.jsxs)(`details`,{onToggle:e=>n(e.currentTarget.open),children:[(0,$.jsx)(`summary`,{children:`Inspect`}),t?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dl`,{children:e.diagnostics?.map((e,t)=>(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:e.label}),(0,$.jsx)(`dd`,{children:(0,$.jsx)(`pre`,{children:e.value})})]},t))}),(0,$.jsx)(s_,{targets:e.feedback})]}):null]})}function F_({evidence:e,stage:t,onStage:n,inspection:r,groupIndex:i,logs:a=[],logsLoading:o,logsError:s}){let c=[`Logs`,...e.nodes.map(e=>e.label)];c.includes(t)||c.push(t);let l=e.nodes.find(e=>e.label===t)??(e.inference?.label===t?e.inference:void 0),u=i!==void 0&&!l?.inLoop,d=e.groups.find(e=>e.index===i),f=d?.inherited,p=d?.replay;return(0,$.jsxs)(`section`,{className:`training-evidence-workspace`,children:[(0,$.jsx)(`nav`,{className:`evaluation-workspace-tabs`,"aria-label":`Run evidence tabs`,children:c.map(e=>(0,$.jsx)(`button`,{type:`button`,"aria-pressed":t===e,onClick:()=>n(e),children:e},e))}),t===`Logs`?(0,$.jsxs)(`section`,{"aria-label":`Run-wide logs`,children:[(0,$.jsx)(`p`,{className:`training-muted`,children:`Run-wide logs · entries retain their recorded context.`}),(0,$.jsx)(X,{error:s}),o?(0,$.jsx)(`p`,{role:`status`,children:`Loading retained logs…`}):null,!a.length&&!o?(0,$.jsx)(`p`,{className:`training-muted`,children:`No retained log entries loaded.`}):null,(0,$.jsx)(`ol`,{className:`training-evidence-logs`,children:a.map((e,t)=>(0,$.jsxs)(`li`,{"data-level":e.level,children:[(0,$.jsx)(`time`,{children:Sa(e.at)}),(0,$.jsx)(`strong`,{children:e.source}),(0,$.jsx)(`span`,{children:e.message})]},`${e.id}:${t}`))})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{className:`training-muted`,children:u?`Run-wide evidence. Baseline and final evaluations assess the run; they are not attributed to an individual group.`:i===void 0?`All retained groups`:`Group ${i+1} retained evidence`}),p&&e.recovery&&l?.inLoop?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{className:`training-muted`,children:`Replaying after checkpoint restore. Prior undurable output was not restored; current records belong to this attempt.`}),(0,$.jsx)(li,{recovery:e.recovery,sourceJobId:p.sourceJobId,compact:!0})]}):null,f&&e.recovery&&l?.inLoop?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{className:`training-muted`,children:`Inherited source evidence. Attempts and optimizer records were not re-executed in this recovery run.`}),(0,$.jsx)(li,{recovery:e.recovery,sourceJobId:f.sourceJobId,compact:!0})]}):null,r?(0,$.jsx)(p_,{...r}):l?(0,$.jsx)(p_,{title:l.label,status:l.status,facts:[...l.diagnostics??[],...l.error?[{label:`Recorded stage failure`,value:l.error,severity:`error`}]:[]],feedback:l.feedback}):(0,$.jsx)(`p`,{className:`training-muted`,children:`No retained evidence for this selection.`}),t===`Rollouts`?(0,$.jsx)(N_,{groups:e.groups}):null]})]})}function I_(e){return(0,$.jsx)(L_,{...e},`${e.teamId}:${e.jobId}`)}function L_({connection:e,teamId:t,projectId:n,jobId:r,onOpenRun:i,compact:a=!1,initialStatus:o}){let[s,c]=(0,Q.useState)(`Logs`),[l,u]=(0,Q.useState)(),[d,f]=(0,Q.useState)(null),{detail:p,flow:m,summary:h,logs:g,logsLoading:_,logsError:v,error:y}=O_(e,t,r,n,s===`Logs`),b=m?.groups.find(e=>e.index===l),x=m&&l!==void 0?{...m,groups:b?[b]:[],groupCount:+!!b,nodes:m.nodes.map(e=>e.inLoop?b?.nodes?.find(t=>t.label===e.label)??{label:e.label,inLoop:!0,state:`missing`,status:`Not recorded`,detail:`No linked group evidence`,diagnostics:[]}:{...e,detail:`Run-wide${e.detail?` · ${e.detail}`:``}`})}:m,S=e=>{e.groupIndex!==void 0&&u(e.groupIndex),c(e.title),f(e.groupIndex===void 0?null:e)},C=h??p?.job,w=C?.executionMode===`qualification`,T=C?.rolloutProgress,E=[...p?.events??[]].reverse().find(e=>e.type===`rollout_metric`&&typeof e.data.rolloutGroupIndex==`number`)?.data.rolloutGroupIndex,D=p?.events.at(-1),O=a?__:S_,k=m?.nodes.find(e=>e.state===`active`)?.label??(m&&!m.live?Ca(m.state):C?Ca(C.phase):o?Ca(o):`Training journey`);return(0,$.jsx)(o_.Provider,{value:{connection:e,teamId:t,jobId:r},children:(0,$.jsx)(f_.Provider,{value:S,children:(0,$.jsxs)(`section`,{className:`model-journey ${a?`compact`:``}`,"aria-label":`Training run stages`,children:[(0,$.jsxs)(`div`,{className:`model-journey-heading`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`span`,{className:`model-journey-eyebrow`,children:w?`Qualification run`:`Training journey`}),(0,$.jsxs)(`div`,{className:`model-journey-title-row`,children:[(0,$.jsx)(`h3`,{children:k}),(0,$.jsx)(Xr,{continuation:m?.continuation,recovery:m?.recovery,compact:!0})]})]}),(0,$.jsx)(`button`,{className:`training-button secondary`,onClick:i,type:`button`,children:`View run`})]}),m&&x?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{label:`Training group context`,value:l===void 0?`all`:String(l),options:[{value:`all`,label:`All groups · run overview`},...m.groups.map(e=>({value:String(e.index),label:`Group ${e.index+1} · ${e.replay?`Replay · ${e.state}`:e.inherited?`Inherited · ${e.inherited.optimizerDisposition===`applied`?`Update applied`:`Skipped · no signal`}`:e.optimizerDisposition===`skipped_no_signal`?`Skipped · no signal`:e.state}`}))],onChange:e=>{u(e===`all`?void 0:Number(e)),f(null)}}),(0,$.jsx)(`p`,{className:`training-muted`,children:l===void 0?`Run overview · all retained groups`:`Group scope · preparation and evaluations remain run-wide`}),(0,$.jsx)(li,{recovery:m.recovery}),(0,$.jsx)(O,{nodes:x.nodes,continuation:m.continuation,inference:m.inference,live:m.live&&!y,loopLabel:w?`Rollout + grading`:`Training loop`,groupLabel:l===void 0?`group ${m.groupsCompleted} of ${m.groupsTarget}`:`Group ${l+1} snapshot`,policyLabel:l===void 0?`policy v${m.policyVersion}`:`group ${l+1}`}),(0,$.jsx)(A_,{evidence:{...x,live:m.live&&!y}})]}):p?.flowError?(0,$.jsx)(X,{error:p.flowError}):null,(0,$.jsxs)(`div`,{className:`model-journey-facts`,"aria-live":`polite`,children:[(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`b`,{children:b?`Group ${b.index+1}`:T?`${T.groupsCompleted} / ${T.groupsTarget}`:`—`}),` `,b?b.state:`groups complete`,l===void 0&&typeof E==`number`?` · latest recorded group ${E+1}`:``]}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`b`,{children:b?b.nodes?.find(e=>e.label===`Update adapter`)?.detail??`No linked optimizer evidence`:T?Math.max(0,T.optimizerUpdatesApplied-(m?.recovery?.optimizerUpdatesApplied??0)):`—`}),` `,b?`optimizer outcome`:m?.recovery?`new weight updates`:`weight updates`]}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`b`,{children:T?.optimizerUpdatesSkipped??`—`}),` run-wide updates skipped`]}),(0,$.jsxs)(`span`,{children:[C?Ca(C.state):`Connecting`,(0,$.jsxs)(`small`,{className:`training-continual-status`,children:[(0,$.jsx)(ri,{enabled:m?!!m.continuation:void 0}),m?.recovery?(0,$.jsx)(`span`,{children:` · Checkpoint recovery`}):null]})]})]}),(0,$.jsx)(X,{error:y}),(0,$.jsx)(`p`,{className:`model-journey-note`,children:y?p||h||m?`Showing last received evidence.`:`No run evidence received yet.`:C?.terminalReason??D?.message??`Stages update from recorded run events and artifacts.`}),C?(0,$.jsxs)(`p`,{className:`model-journey-time`,children:[`Updated `,Sa(C.updatedAt),` · Stages reflect recorded evidence, not estimated progress.`]}):null,a&&p?(0,$.jsx)(Qr,{series:k_(l===void 0?p.events:p.events.filter(e=>e.data.rolloutGroupIndex===l))}):null,x?(0,$.jsx)(F_,{evidence:x,stage:s,groupIndex:l,inspection:d,onStage:e=>{c(e),f(null)},logs:g,logsLoading:_,logsError:v}):null]})})})}function R_(e,t=[]){let n=t.filter(e=>e.split===`train`),r=new Map(n.map(e=>[e.id,e])),i=new Map,a=new Set,o=new Map,s=new Set;for(let t of e){if(t.type!==`metric`)continue;let e=t.payload;if(e.metricKind===`rollout_trajectory`){let a=U_(e.rolloutGroupId)??`group-0`,o=i.get(a),s=H_(e.rolloutGroupIndex)??o?.groupIndex??i.size,c=U_(e.taskId),l=(c?r.get(c):null)??(n.length?n[s%n.length]??null:null),u=G_(l?.metadata),d={id:t.id,rolloutIndex:H_(e.rolloutIndex),workerSlot:H_(e.workerSlot),attempt:H_(e.attempt)??1,policyVersion:H_(e.policyVersion),reward:V_(e.reward),rewardEligible:e.rewardEligible===!0,terminalClass:U_(e.terminalClass),failure:U_(e.failureCode)??U_(e.failureClass),inputTokens:H_(e.inputTokens)??0,outputTokens:H_(e.outputTokens)??0,components:z_(e)};i.set(a,{id:a,groupIndex:s,taskId:c??l?.id??o?.taskId??null,taskLabel:q_(l)??o?.taskLabel??null,taskFamily:U_(e.taskFamily)??U_(e.scenarioFamily)??l?.clusterKey??U_(u.scenarioFamily)??o?.taskFamily??null,policyVersion:H_(e.policyVersion)??o?.policyVersion??null,trajectories:[...o?.trajectories??[],d]})}else if(e.metricKind===`optimizer_disposition`){let t=U_(e.rolloutGroupId);if(!t)continue;let n=U_(e.optimizerDisposition)??U_(e.disposition)??U_(e.remotePhase);n?.includes(`skipped`)&&a.add(t),n===`applied`&&o.set(t,H_(e.step))}else if(e.metricKind===`policy_optimization`){let t=H_(e.step),n=U_(e.rolloutGroupId);t!==null&&s.add(t),n&&o.set(n,t)}}return[...i.values()].sort((e,t)=>e.groupIndex-t.groupIndex).map(e=>{let t=e.trajectories.flatMap(e=>e.rewardEligible&&e.reward!==null?[e.reward]:[]),n=o.get(e.id),r=n===void 0?null:n;if(r===null&&!a.has(e.id)){let t=e.groupIndex+1;s.has(t)&&(r=t)}return{...e,optimizerDisposition:a.has(e.id)?`skipped`:r===null?`pending`:`applied`,optimizerStep:r,mean:B_(t),minimum:t.length?Math.min(...t):null,maximum:t.length?Math.max(...t):null}})}function z_(e){let t=[e.rewardComponents,e.rubricComponents,e.components].find(W_);return t?Object.entries(t).flatMap(([e,t])=>{if(typeof t==`number`&&Number.isFinite(t))return[{id:e,label:K_(e),score:t,passed:null,feedback:null}];if(!W_(t))return[];let n=[t.score,t.reward,t.value,t.rewardContribution].map(V_).find(e=>e!==null);return n===void 0?[]:[{id:e,label:U_(t.label)??U_(t.name)??K_(e),score:n,passed:typeof t.passed==`boolean`?t.passed:null,feedback:U_(t.feedback)}]}):[]}function B_(e){return e.length?e.reduce((e,t)=>e+t,0)/e.length:null}function V_(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function H_(e){let t=V_(e);return t!==null&&Number.isInteger(t)?t:null}function U_(e){return typeof e==`string`&&e.trim()?e.trim():null}function W_(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function G_(e){return W_(e)?e:{}}function K_(e){return e.replaceAll(/[._-]+/g,` `).replace(/^./,e=>e.toUpperCase())}function q_(e){if(!e)return null;let t=G_(e.input),n=[t.title,t.name,t.prompt,t.instruction,t.question,t.query].find(e=>typeof e==`string`&&!!e.trim());if(!n)return null;let r=n.trim().split(/\n\s*\n/,1)[0].replaceAll(/\s+/g,` `);return r.length>110?`${r.slice(0,107).trimEnd()}…`:r}var J_=new Set([`optimizer.reward`,`rollout.reward`]),Y_=[{key:`meanReward`,id:`optimizer.reward`,label:`Mean reward`},{key:`meanReturn`,id:`optimizer.return`,label:`Mean return`},{key:`learningRate`,id:`optimizer.learning_rate`,label:`Learning rate`,format:`scientific`},{key:`policyLoss`,id:`optimizer.policy_loss`,label:`Policy loss`},{key:`valueLoss`,id:`optimizer.value_loss`,label:`Value loss`},{key:`gradientNorm`,id:`optimizer.gradient_norm`,label:`Gradient norm`},{key:`kl`,id:`optimizer.kl`,label:`Policy update KL`},{key:`behaviorPolicyKlPreUpdate`,id:`optimizer.behavior_policy_kl`,label:`Behavior-policy KL (pre-update)`},{key:`entropy`,id:`optimizer.entropy`,label:`Entropy`},{key:`policyClipFraction`,id:`optimizer.policy_clip_fraction`,label:`Post-update clip fraction`,format:`percent`},{key:`behaviorPolicyClipFractionPreUpdate`,id:`optimizer.behavior_policy_clip_fraction`,label:`Behavior-policy clip fraction (pre-update)`,format:`percent`},{key:`valueClipFraction`,id:`optimizer.value_clip_fraction`,label:`Value clip fraction`,format:`percent`},{key:`explainedVariance`,id:`optimizer.explained_variance`,label:`Explained variance`}],X_=[{key:`loss`,id:`optimizer.loss`,label:`Loss`},{key:`reward`,id:`optimizer.reward`,label:`Reward`},{key:`policyLoss`,id:`optimizer.policy_loss`,label:`Policy loss`},{key:`advantageLoss`,id:`optimizer.advantage_loss`,label:`Advantage loss`},{key:`learningRate`,id:`optimizer.learning_rate`,label:`Learning rate`,format:`scientific`},{key:`gradientNorm`,id:`optimizer.gradient_norm`,label:`Gradient norm`},{key:`meanTokenAccuracy`,id:`train.token_accuracy`,label:`Token accuracy`,format:`percent`},{key:`preferenceAccuracy`,id:`train.preference_accuracy`,label:`Preference accuracy`,format:`percent`},{key:`preferenceMargin`,id:`train.preference_margin`,label:`Preference margin`},{key:`chosenReward`,id:`train.chosen_reward`,label:`Chosen reward`},{key:`rejectedReward`,id:`train.rejected_reward`,label:`Rejected reward`},{key:`entropy`,id:`optimizer.entropy`,label:`Entropy`}];function Z_({detail:e,loading:t,error:n,taskset:r=null}){Ka(n,{prefix:`Training metrics`});let i=(0,Q.useMemo)(()=>e?R_(e.events,r?.tasks):[],[e,r]),a=(0,Q.useMemo)(()=>e?$_(ev(e),i):[],[e,i]);if(n&&!e)return(0,$.jsx)(`div`,{className:`training-run-placeholder`,children:`Training metrics are unavailable.`});if(!e&&!t)return(0,$.jsx)(`div`,{className:`training-run-placeholder`,children:`Select a training run to inspect its metrics.`});let o=e?[`queued`,`starting`,`running`,`reconciling`].includes(e.job.status):!1;return(0,$.jsx)(Qr,{live:o,loading:t&&!e,series:a})}function Q_(e){let t=e.flatMap((e,t)=>e.mean===null?[]:[{step:t+1,value:e.mean}]);return t.length?{id:`optimizer.reward`,label:`Mean reward`,points:t,xLabel:`rollout group`}:null}function $_(e,t){let n=Q_(t);return n?[n,...e.filter(e=>!J_.has(e.id))]:e}function ev(e){let t=cv(e.job.metadata.rolloutProgress),n=av(e.job.metadata.optimizerUpdatesObserved)??av(t.optimizerUpdatesApplied),r=sv(e)===`grpo`&&n!==null?Math.max(0,n):null,i=rv(e.stepMetrics).filter(e=>r===null||e.step<=r),a=[...nv(rv(e.policyMetrics),Y_),...nv(i,X_),...iv(e.events)],o=new Map;for(let e of a){let t=o.get(e.id);(!t||e.points.length>t.points.length)&&o.set(e.id,e)}let s=[`optimizer.reward`,`rollout.reward`,`optimizer.kl`,`optimizer.loss`,`optimizer.learning_rate`];return[...o.values()].sort((e,t)=>tv(e.id,s)-tv(t.id,s)||e.label.localeCompare(t.label))}function tv(e,t){let n=t.indexOf(e);return n<0?999:n}function nv(e,t){return t.flatMap(t=>{let n=e.flatMap(e=>{let n=e[t.key];return typeof n==`number`&&Number.isFinite(n)?[{step:e.step,value:n}]:[]});return n.length?[{id:t.id,label:t.label,points:n,format:t.format}]:[]})}function rv(e){let t=new Map;for(let n of e)t.set(n.step,n);return[...t.values()].sort((e,t)=>e.step-t.step)}function iv(e){let t=new Map,n=new Map,r=(e,r,i,a)=>{t.set(e,[...t.get(e)??[],{step:i,value:a}]),n.set(e,r)},i=new Map;for(let t of e)if(t.type===`metric`){if(t.payload.metricKind===`managed_telemetry`){let e=typeof t.payload.metricId==`string`?t.payload.metricId:null,n=av(t.payload.value),i=av(t.payload.step)??t.sequence;e&&n!==null&&r(e,ov(e),i,n)}if(t.payload.metricKind===`rollout_trajectory`){let e=av(t.payload.rolloutIndex)??t.sequence,n=av(t.payload.reward);n!==null&&r(`rollout.reward`,`Rollout reward`,e,n);let a=typeof t.payload.rolloutGroupId==`string`?t.payload.rolloutGroupId:`group-0`,o=t.payload.rewardEligible===!1||typeof t.payload.failureClass==`string`||typeof t.payload.failureCode==`string`;i.set(a,[...i.get(a)??[],{reward:n,eligible:t.payload.rewardEligible===!0,resolved:n!==null||o,attempt:av(t.payload.attempt)??1,input:av(t.payload.inputTokens)??0,output:av(t.payload.outputTokens)??0}])}}return[...i.values()].forEach((e,t)=>{let n=e.filter(e=>e.resolved);if(!n.length)return;let i=n.flatMap(e=>e.eligible&&e.reward!==null?[e.reward]:[]),a=i.length?i.reduce((e,t)=>e+t,0)/i.length:0,o=i.length?i.reduce((e,t)=>e+(t-a)**2,0)/i.length:0,s=i.length?Math.max(...i):0;r(`attempt.valid_rate`,`Valid attempt rate`,t,i.length/n.length),r(`attempt.failure_count`,`Attempt failures`,t,n.length-i.length),r(`attempt.retry_count`,`Attempt retries`,t,n.reduce((e,t)=>e+Math.max(0,t.attempt-1),0)),r(`reward.variance`,`Reward variance`,t,o),r(`reward.best`,`Best reward`,t,s),r(`tokens.input`,`Input tokens`,t,e.reduce((e,t)=>e+t.input,0)),r(`tokens.output`,`Output tokens`,t,e.reduce((e,t)=>e+t.output,0))}),[...t].map(([e,t])=>({id:e,label:n.get(e)??ov(e),points:t,format:e.endsWith(`rate`)||e.includes(`fraction`)?`percent`:`number`}))}function av(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function ov(e){return e.replaceAll(/[._]/g,` `).replace(/^./,e=>e.toUpperCase())}function sv(e){let t=e.job.metadata.trainingMethod;if(typeof t==`string`)return t;let n=cv(e.job.metadata.sourceSnapshot);return typeof n.method==`string`?n.method:null}function cv(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function lv({connection:e,sessionId:t,resources:n,onRequest:r}){let i=n.focus.dataset,a=n.focus.scopeContext&&i?[...new Map(Gr(n.focus.scopeContext).filter(e=>e.id===n.scope?.id&&e.dataset&&cf(e.dataset)===cf(i)).flatMap(e=>e.training??[]).map(e=>[qr(e),e])).values()]:[],o=k(e,t),[s,c]=(0,Q.useState)(null),l=a.find(e=>qr(e)===n.scope?.selectedTrainingKey)??a.find(e=>e.location===`cloud`?![`completed`,`failed`,`cancelled`,`budget_exhausted`].includes(e.job.state):e.executionState===`running`)??a.at(-1);async function u(e){let t=a.find(t=>qr(t)===e);if(t){c(null);try{await o.select({kind:`training`,id:t.jobId,location:t.location,...t.location===`cloud`?{teamId:t.owner.teamId,apiOrigin:t.apiOrigin}:{}})}catch(e){c(e instanceof Error?e.message:`Run selection failed.`)}}}return(0,$.jsxs)(`section`,{className:`dataset-workspace-section`,"aria-label":`Dataset training`,children:[(0,$.jsxs)(`header`,{className:`dataset-workspace-section-heading`,children:[(0,$.jsxs)(`div`,{className:`dataset-workspace-title`,children:[(0,$.jsx)(`h2`,{children:a.length?`Training runs`:`Planned stages`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary icon-only`,"aria-label":`New training`,title:`New training`,onClick:()=>r(`New training`),children:(0,$.jsx)(za,{size:15})})]}),l?(0,$.jsx)(lt,{status:l.location===`cloud`?l.job.state:l.executionState}):null]}),(0,$.jsx)(X,{error:s}),a.length?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{compact:!0,floating:!0,label:`Training run`,value:l?qr(l):``,disabled:o.selecting,options:a.map(e=>({value:qr(e),label:e.location===`cloud`?`Hosted run ${e.jobId.slice(-8)}`:e.modelId,description:e.location===`cloud`?e.job.state:e.executionState})),onChange:e=>void u(e)}),l?.location===`cloud`?(0,$.jsx)(I_,{compact:!0,connection:e,teamId:l.owner.teamId,projectId:l.job.modelProjectId,jobId:l.jobId,onOpenRun:()=>r(`Check training`,void 0,l)},qr(l)):l?(0,$.jsx)(uv,{connection:e,training:l},qr(l)):null]}):(0,$.jsx)(`div`,{"aria-label":`Planned training stages`,children:(0,$.jsx)(y_,{})})]})}function uv({connection:e,training:t}){let n=S({queryKey:[`dataset-workspace-training`,ra(e),qr(t)],queryFn:async()=>{let n=vo.parse(await Eo.trainingRunDetail(e,t.jobId));if(n.job.id!==t.jobId)throw Error(`Training evidence does not match the attached job.`);return n},refetchInterval:e=>[`queued`,`starting`,`running`,`reconciling`,`cancelling`].includes(e.state.data?.job.status??t.executionState)?3e3:!1}),r=n.data,i=!!(r&&[`queued`,`starting`,`running`,`reconciling`].includes(r.job.status)&&!n.error);if(!r)return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{error:n.error?.message}),(0,$.jsx)(`p`,{role:`status`,children:`Loading training evidence…`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void n.refetch(),children:`Refresh`})]});let a=r.managedEvidence?.progress.committedOptimizerSteps??r.job.metadata.optimizerUpdatesObserved,o=typeof a==`number`&&a>0,s=r.events.some(e=>e.type===`metric`&&e.payload.metricKind===`rollout_trajectory`),c=r.job.status===`succeeded`,l=r.events.filter(e=>e.type===`metric`&&e.payload.metricKind===`rollout_trajectory`&&typeof e.payload.reward==`number`&&Number.isFinite(e.payload.reward)).length,u=r.events.some(e=>e.type===`checkpoint`)||!!r.managedEvidence?.checkpoint?.sha256,d=!!r.evaluation||!!r.managedEvidence?.evaluations.some(e=>e.kind===`candidate`),f=i?`pending`:`missing`,p=s||o||u||d;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ut,{name:t.modelId}),(0,$.jsx)(X,{error:n.error?.message}),(0,$.jsx)(__,{live:i,loopLabel:`Training loop`,nodes:[{label:`Prepare`,state:p?`done`:i?`active`:f,status:p?`Recorded`:r.job.startedAt?`Worker started`:`Waiting`},{label:`Rollouts`,state:s?`done`:f,status:s?`Recorded`:`Waiting for attempts`,inLoop:!0},{label:`Grade`,compute:`cpu`,state:l?`done`:f,status:l?`Recorded`:`No recorded grades`,detail:l?`${l} graded attempts`:void 0,inLoop:!0},{label:`Update adapter`,state:o?`done`:f,status:o?`Recorded`:`No recorded updates`,detail:o?`${a} updates`:void 0,inLoop:!0},{label:`Save checkpoint`,compute:`cpu`,state:u?`done`:f,status:u?`Recorded`:`No saved checkpoint recorded`,inLoop:!0},{label:`Evaluate`,state:d?`done`:f,status:d?`Recorded`:`No candidate evaluation recorded`},{label:`Finish`,state:c?`done`:r.job.status===`failed`?`failed`:f,status:r.job.status,error:r.job.error??void 0}]}),(0,$.jsx)(Qr,{series:ev(r)}),(0,$.jsxs)(`details`,{className:`dataset-workspace-logs`,children:[(0,$.jsx)(`summary`,{children:`Training events`}),(0,$.jsx)(`ol`,{children:r.events.slice(-100).map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`time`,{children:new Date(e.timestamp).toLocaleTimeString()}),(0,$.jsx)(`span`,{children:typeof e.payload.message==`string`?e.payload.message:e.type})]},e.id))})]})]})}function dv(e){return e===`small`||e===`small_experiment`}function fv(e){return{maxSteps:1,trainingExamples:e===`grpo`?1:e===`sft`?4:2,rolloutGroupSize:4,rolloutConcurrency:1}}function pv(e,t,n){if(!dv(e))return n;let r=fv(t);return{maxSteps:r.maxSteps,rolloutGroupSize:r.rolloutGroupSize,rolloutConcurrency:r.rolloutConcurrency}}function mv(e){let t=fv(`grpo`);return{...e,dataset:{...e.dataset,maxExamples:t.trainingExamples},rollout:{...e.rollout,groupSize:t.rolloutGroupSize,concurrency:t.rolloutConcurrency},optimizer:{...e.optimizer,maxSteps:t.maxSteps,iterations:2,gradientAccumulationSteps:t.rolloutGroupSize},resourceLimits:{...e.resourceLimits,maxRollouts:t.rolloutGroupSize},policyOptimization:null}}function hv(e){return[{id:`standard`,label:`Full run`,description:`Pre-fill the full training configuration, then adjust its limits.`},{id:e===`grpo`||e===`ppo`?`small_experiment`:`small`,label:`Smoke`,description:e===`grpo`?`Start with 1 prompt, 4 rollouts, 1 group, and 2 optimizer iterations.`:`Start with a small training batch and 1 optimizer step.`},{id:`custom`,label:`Custom`,description:`Choose prompts, rollouts, groups, and optimizer iterations.`}]}function gv(e,t,n){if(!dv(e))return null;let r=fv(t);return n.maxSteps>r.maxSteps||n.trainingExamples>r.trainingExamples||(t===`grpo`||t===`ppo`)&&(n.rolloutGroupSize>r.rolloutGroupSize||n.rolloutConcurrency>r.rolloutConcurrency||(n.optimizerIterations??2)>2||(n.maximumRollouts??4)>4)?`These settings exceed the training smoke test limits. Reduce them or select Custom.`:null}function _v({method:e,methods:t,onMethodChange:n,value:r,onChange:i,disabled:a,recommendedAvailable:o=!0,sizing:s,onSizingChange:c}){let l=hv(e).filter(e=>o||e.id!==`standard`),u=dv(r)?l.find(e=>dv(e.id)).id:r;return(0,$.jsxs)(`div`,{className:`model-build-field training-run-configuration`,children:[(0,$.jsx)(`span`,{children:`Run configuration`}),(0,$.jsx)(Z,{floating:!0,label:`Run configuration`,value:u,options:l.map(e=>({value:e.id,label:e.label})),onChange:e=>i(e),disabled:a}),s&&c?(0,$.jsxs)(`div`,{className:`training-run-quantities`,children:[[[`prompts`,`Prompts`,`Training prompts`,1,1e5],[`rollouts`,`Rollouts`,`Rollouts per prompt`,2,16],[`groups`,`Groups`,`Rollout groups`,1,1e5],[`iterations`,`Iterations`,`Optimizer iterations`,e===`grpo`?2:1,e===`grpo`?16:100],[`concurrency`,`Concurrent`,`Concurrent rollouts`,1,s.rollouts]].map(([e,t,n,r,i])=>(0,$.jsxs)(`label`,{title:n,children:[(0,$.jsx)(`span`,{children:t}),(0,$.jsx)(`input`,{"aria-label":n,type:`number`,min:r,max:i,step:1,value:Number.isFinite(s[e])?s[e]:``,disabled:a,onChange:t=>c({...s,[e]:t.target.valueAsNumber||r})})]},e)),(0,$.jsxs)(`div`,{className:`training-run-method`,children:[(0,$.jsx)(`span`,{children:`Method`}),(0,$.jsx)(Z,{compact:!0,floating:!0,floatingMenuWidth:140,label:`Training method`,value:e??``,options:(t??(e?[e]:[])).map(e=>({value:e,label:e.toUpperCase()})),disabled:a||!n||!t?.length,onChange:e=>n?.(e)})]})]}):null]})}function vv({connection:e,resources:t,onAddToChat:n,initialPreset:r}){let[i,a]=(0,Q.useState)({prompts:dv(r)?1:Math.max(1,t.focus.dataset?.taskCount??1),rollouts:4,groups:dv(r)?1:Math.max(1,t.focus.dataset?.taskCount??1),iterations:2,concurrency:1}),[o,s]=(0,Q.useState)(r),[c,l]=(0,Q.useState)(`grpo`),[u,d]=(0,Q.useState)(``),[f,p]=(0,Q.useState)(``),m=S({queryKey:[`dataset-training-catalog`,ra(e)],queryFn:async()=>ac.parse(await Eo.portableTrainingCatalog(e))}),h=(m.data?.targets??[]).find(e=>e.destinationId===`openpond_managed`),g=(m.data?.models??[]).filter(e=>e.compatibilities.some(e=>e.targetId===h?.id&&e.methods.includes(c)&&e.state!==`unsupported`)),_=g.find(e=>e.selectionKey===u),v=(h?.methods??[]).filter(e=>[`sft`,`dpo`,`grpo`,`ppo`].includes(e));(0,Q.useEffect)(()=>{if(m.data&&v.length&&!v.includes(c)){let e=v[0];l(e),s(t=>dv(t)?e===`grpo`||e===`ppo`?`small_experiment`:`small`:t),d(``)}},[m.data,c]);let y=h?.approvalPolicy?.minimumSpendUsd??.01,b=h?.approvalPolicy?.maximumSpendUsd,x=Number(f),C=!!(h?.available&&h.methods.includes(c)&&_&&f.trim()&&Number.isFinite(x)&&x>=y&&(b===void 0||x<=b)),w=t.focus.dataset,T=`Use ${i.prompts} training prompts, ${i.rollouts} rollouts per prompt, ${i.groups} rollout groups, ${i.iterations} optimizer iterations per group, and concurrency ${i.concurrency}. Retain held-out evaluation, tools, grading, checkpoint export, and the existing token/context limits.`,E=Object.values(i).every(e=>Number.isInteger(e)&&e>0)&&i.prompts<=1e5&&i.groups<=1e5&&i.iterations>=(c===`grpo`?2:1)&&i.iterations<=(c===`grpo`?16:100)&&i.rollouts>=2&&i.rollouts<=16&&Number.isInteger(i.concurrency)&&i.concurrency>=1&&i.concurrency<=16&&i.rollouts%i.concurrency===0,D=!!(w&&h?.available&&_&&E),O=`using ${c.toUpperCase()} for ${w?.name}, revision ${w?.revision}, using ${_?.modelId} on OpenPond Managed`;return(0,$.jsxs)(`div`,{className:`dataset-training-plan`,children:[m.error?(0,$.jsx)(X,{error:m.error.message,children:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void m.refetch(),children:`Retry`})}):null,(0,$.jsx)(_v,{method:c,methods:v.length?v:[`grpo`],onMethodChange:e=>{l(e),s(dv(o)?e===`grpo`||e===`ppo`?`small_experiment`:`small`:o),d(``)},value:o,sizing:i,onSizingChange:a,onChange:e=>{s(e),e!==`custom`&&a({prompts:dv(e)?1:Math.max(1,w?.taskCount??1),rollouts:4,groups:dv(e)?1:Math.max(1,w?.taskCount??1),iterations:2,concurrency:1})}}),(0,$.jsx)(`span`,{className:`dataset-training-field-label`,children:`Starting model`}),(0,$.jsx)(Z,{floating:!0,searchable:!0,label:`Training model`,value:_?.selectionKey??``,options:[{value:``,label:m.isPending?`Loading models…`:`Choose training model`,disabled:!0},...g.map(e=>({value:e.selectionKey,label:e.label,description:e.reason??e.modelId}))],onChange:d,disabled:m.isPending}),(0,$.jsxs)(`label`,{children:[`Maximum spend (USD)`,(0,$.jsxs)(`div`,{className:`training-spend-estimate`,children:[(0,$.jsx)(`input`,{"data-autofocus":!0,type:`number`,min:y,max:b,step:`0.01`,"aria-label":`Maximum training spend`,value:f,onChange:e=>p(e.target.value)}),(0,$.jsx)(`button`,{type:`button`,disabled:!D,onClick:()=>n(`Review the training cost ${O}. ${T} Keep this review attached to the selected experiment and inspect the pinned examples, splits, graders, and recipe before estimating. ${C?`Use $${x.toFixed(2)} as the maximum spend.`:`Ask me to choose a hard spend cap before any submission.`} Show the current provider estimate or exact quote when supported, its assumptions, what is included, and any separately billed preparation, evaluation, idle, or serving costs. If an estimate is unavailable, explain why and the next step. Do not upload data, start training, or allocate serving capacity.`),children:`Review cost in chat`})]})]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:!D||!C,onClick:()=>n(`Prepare a training plan ${O}, with a maximum spend of $${x.toFixed(2)}. ${T} Keep it attached to the selected experiment. Inspect its examples, splits, graders, and data permissions; show the recipe, required changes, and cost for review. Do not upload data or start training.`),children:`Prepare in chat`})]})}function yv({dialog:e,connection:t,resources:n,onClose:r,onAddToChat:i}){let[a,o]=(0,Q.useState)(e.text??``);return(0,$.jsxs)(qa,{ariaLabel:e.title,className:`training-dialog dataset-workspace-dialog`,onClose:r,children:[(0,$.jsxs)(`header`,{className:`training-dialog-header`,children:[(0,$.jsx)(`h2`,{children:e.title}),(0,$.jsx)(`button`,{className:`training-icon-button`,type:`button`,"aria-label":`Close dialog`,onClick:r,children:(0,$.jsx)(Ua,{size:18})})]}),e.title===`Add grader`?(0,$.jsx)(tf,{kind:`grader`,resources:n,busy:!1,onDraft:i}):e.title===`New training`?(0,$.jsx)(vv,{connection:t,resources:n,onAddToChat:i,initialPreset:`standard`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:`Review the request, then add it to chat.`}),(0,$.jsx)(`textarea`,{"data-autofocus":!0,"aria-label":`Chat request`,rows:6,value:a,onChange:e=>o(e.target.value)}),(0,$.jsxs)(`div`,{className:`training-dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:r,children:`Cancel`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:!a.trim(),onClick:()=>i(a),children:`Add to chat`})]})]})]})}function bv(e,t,n,r){let i=ra(e),a=u(),o=[`dataset-workspace-runs`,i,t?cf(t):null],s=A({queryKey:o,enabled:!(!e||!t||t.owner||t.profileRef),initialPageParam:void 0,getNextPageParam:e=>e.nextCursor??void 0,queryFn:async({signal:t,pageParam:n})=>{let r=await ko(e,`experiment`,{action:`list`,payload:{limit:100,...n?{afterId:n}:{}}},t);if(n&&r.nextCursor===n)throw Error(`Experiment history did not advance to its next page.`);return{...r,summaries:df(r.summaries)}},refetchInterval:e=>e.state.data?.pages.some(e=>e.summaries.some(e=>t&&lf(e,t)&&uf(e.state)))?2e3:1e4});(0,Q.useEffect)(()=>{s.hasNextPage&&!s.isFetchingNextPage&&!s.isFetchNextPageError&&s.fetchNextPage()},[s.hasNextPage,s.isFetchingNextPage,s.isFetchNextPageError,s.fetchNextPage]);let c=r.filter(e=>[`workspace_action_result`,`turn.completed`].includes(e.name)).at(-1)?.id;(0,Q.useEffect)(()=>{c&&a.invalidateQueries({queryKey:[`dataset-workspace-runs`,i]})},[c,i,a]);let l=new Map(s.data?.pages.flatMap(e=>e.items?.map(e=>[e.id,Date.parse(e.createdAt)])??[])??[]);return{rows:t?[...new Map([...n,...s.data?.pages.flatMap(e=>e.summaries)??[]].filter(e=>lf(e,t)).map(e=>[cf(e),e])).values()].sort((e,t)=>Number(uf(t.state))-Number(uf(e.state))||(l.get(t.id)??0)-(l.get(e.id)??0)):[],history:s}}function xv({connection:e,sessionId:t,resources:n,events:r,selectedExperiment:i,experimentName:a}){let o=n.focus.dataset,s=o?cf(o):``,[c,l]=(0,Q.useState)(null),u=bv(i===void 0?e:null,o,n.experiments,r),d=n.scope,f=d?.ordinal!==null&&d?.ordinal!==void 0,p=f?u.rows.filter(e=>d.runs.some(t=>cf(t)===cf(e))):u.rows,m=f&&!d.runs.length?d:null,h=i===void 0?m?null:p.find(e=>e.id===d?.selectedRunId)??p.find(e=>uf(e.state))??p[0]??(f?d.runs.at(-1)??null:null):i,g=Sv(e,h),_=g.data?.summary??h;(0,Q.useEffect)(()=>{l(null)},[s,d?.id]);let v=d?.ordinal,y=a??i?.name??(i===null?`Experiment draft`:v?`Experiment ${v}`:`Experiment`),b=o?`${o.name}, revision ${o.revision}`:`the selected Dataset`;function x(e,t,r){if([`Add grader`,`New training`].includes(e)){l({title:e});return}let i=t?`${o?.name}, revision ${t.datasetRevision}, run ${t.id}`:b,a=e===`Check graders`?`Test the graders for ${b} against their saved fixtures and known-good and known-bad answers. Report missing coverage and failures separately from model evaluation scores. Do not change the dataset, graders, or start training.`:e===`Diagnose`?`Diagnose ${i}. Inspect its retained results and failures, explain the cause and the next useful step without changing it.`:e===`Improve`?`Improve ${i}. Inspect its retained results, make a targeted change, validate it, and evaluate a comparison within the agreed budget. Preserve the original run and its inputs.`:e===`Run experiment`?`Run an experiment on ${b} with its Dataset graders${n.scope?.evaluationModel?` against ${n.scope.evaluationModel}`:``}. Use the selected execution destination and agreed budget; ask for any missing model or spending limit before starting.`:`Check this training job and show its progress, results, and any model it produced.`;l({title:e,text:a,run:t,training:r})}function S(e){Bd({sessionId:t,text:e,contexts:ff(n,c?.run,c?.training)}),l(null)}return(0,$.jsxs)(`div`,{className:`dataset-workspace`,"aria-label":`Experiment workspace`,children:[(0,$.jsxs)(`header`,{className:`dataset-workspace-section-heading`,children:[(0,$.jsx)(`div`,{className:`dataset-workspace-title`,children:(0,$.jsx)(`h2`,{children:y})}),(0,$.jsxs)(`div`,{className:`dataset-workspace-actions dataset-workspace-header-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:!o,onClick:()=>x(`Run experiment`),children:`Evaluate`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary dataset-action`,disabled:!o||!_,onClick:()=>x(`Diagnose`,_??void 0),children:`Diagnose`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary dataset-action`,disabled:!o||!_||uf(_.state),onClick:()=>x(`Improve`,_??void 0),children:`Improve`}),(0,$.jsxs)(`button`,{type:`button`,className:`training-button secondary dataset-action`,disabled:!o,onClick:()=>x(`Add grader`),children:[(0,$.jsx)(za,{size:13}),` Add grader`]})]})]}),n.error?(0,$.jsx)(X,{error:n.error}):null,o?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{className:`dataset-workspace-context`,children:[(0,$.jsx)(`span`,{children:`Dataset:`}),` `,o.name,` · revision `,o.revision]}),_?(0,$.jsx)(C_,{run:_,view:g.data?.view,loading:g.isPending,error:g.error,onRefresh:()=>void g.refetch()},`progress:${cf(_)}`):(0,$.jsx)(`p`,{children:`Evaluate this experiment, or configure a training run below.`}),u.history.error?(0,$.jsx)(X,{error:u.history.error.message,children:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void u.history.refetch(),children:`Retry`})}):null,(0,$.jsx)(a_,{connection:e,dataset:o,graders:n.graders}),_?(0,$.jsx)(i_,{title:`Results`,children:(0,$.jsx)(w_,{connection:e,run:_,view:g.data?.view},`evidence:${cf(_)}`)}):null,(0,$.jsx)(i_,{title:`Training`,children:(0,$.jsx)(lv,{connection:e,sessionId:t,resources:n,onRequest:x})})]}):(0,$.jsx)(`p`,{children:`Choose an experiment, or create one from a dataset.`}),c?(0,$.jsx)(yv,{dialog:c,connection:e,resources:n,onClose:()=>l(null),onAddToChat:S},c.title):null]})}function Sv(e,t){return S({queryKey:[`dataset-workspace-run`,ra(e),t?cf(t):null],enabled:!!t,queryFn:async({signal:n})=>{let r=await ko(e,`experiment`,{action:`result`,payload:{id:t.id}},n),i=Kr.parse(r.summary),a=Yr.parse(r.view);if(cf(i)!==cf(t)||i.datasetId!==t.datasetId||i.datasetRevision!==t.datasetRevision)throw Error(`Run evidence changed its Dataset pin.`);return{summary:i,view:a}},refetchInterval:e=>uf(e.state.data?.summary.state??t?.state??``)?2e3:!1})}function Cv(e){if(e?.startingModel)return e.startingModel;let t=e?.alphaEditForm?.baseModel??e?.neuronTrainingForm?.baseModel??e?.decisionForm?.baseModel??e?.engramForm?.baseModel??e?.activationForm?.baseModel??e?.trainingForm?.baseModel??e?.training?.baseModel;if(t&&e?.alphaEditForm?.startingModule)return{source:`alphaedit`,label:`Saved AlphaEdit matrices · ${e.alphaEditForm.startingModule.modelProjectId}`,inferenceModelId:null,baseModel:t,alphaedit:e.alphaEditForm.startingModule};if(t&&e?.decisionForm?.startingDecision)return{source:`decision`,label:`Saved Decision Model · ${e.decisionForm.startingDecision.modelProjectId}`,inferenceModelId:null,baseModel:t,decision:e.decisionForm.startingDecision};if(t&&e?.engramForm?.startingModule)return{source:`engram`,label:`Saved memory module · ${e.engramForm.startingModule.modelProjectId}`,inferenceModelId:null,baseModel:t,engram:e.engramForm.startingModule};if(t)return{source:`managed`,label:e?.trainingForm?.startingModelLabel??t.modelId,baseModel:t,inferenceModelId:null};let n=e?.evaluationForm?.form.modelId;return n?{source:`inference`,label:n,inferenceModelId:n,baseModel:null}:null}function wv(e){return e?J(e.source===`alphaedit`?[e.source,e.alphaedit,e.baseModel]:e.source===`neuron_training`?[e.source,e.neuronTraining,e.baseModel]:e.source===`decision`?[e.source,e.decision,e.baseModel]:e.source===`engram`?[e.source,e.engram,e.baseModel]:e.source===`steering`?[e.source,e.steering,e.baseModel]:e.source===`trained`?[e.source,e.trainedVersion.contentHash]:e.source===`managed`?[e.source,e.baseModel]:[e.source,e.inferenceModelId,e.baseModel]):``}var Tv=e=>e?J([e.id,e.revision,e.contentHash]):``;function Ev(e,t,n){let r=e?.request.policy;return{mode:r?.kind===`hosted_harness`?`model_harness_profile`:r?.kind===`hosted_chat`&&r.harness?`model_harness`:`model`,sourceId:r?.kind===`hosted_chat`&&r.harness?`harness-${r.harness.harnessRelease.contentHash}`:``,profileChoiceId:``,...r?.kind===`hosted_chat`?{temperature:r.temperature,topP:r.topP,localRuntime:r.localRuntime}:{},name:e?.request.name??`Evaluation`,release:e?.request.taskset??t,modelId:e&&`modelId`in e.request.policy?e.request.policy.modelId:``,budget:e?.maximumCostUsd??1,outputTokens:e?.request.policy.kind===`hosted_chat`?e.request.policy.maxOutputTokens:1024,prompt:e?.request.policy.kind===`hosted_chat`?e.request.policy.messages?.find(e=>e.role===`system`)?.content??``:``,targetId:e?.request.project?.targetId??n,seed:e?[...new Set(e.request.population.map(e=>e.seed))].join(`, `):`0`,graderChoices:{}}}var Dv=(0,Q.createContext)(null);function Ov({children:e,initialExperiment:t=null,initialRecord:n=null,onNewDraft:r,allowedOperationTypes:i=[`evaluate`,`sft`,`grpo`,`neuron_steering`,`inspect_activations`,`engram_adapter`,`decision_model`,`alphaedit`,`selective_neuron_training`]}){let a=(0,Q.useRef)(null),o=(0,Q.useCallback)(e=>(a.current=e,()=>{a.current===e&&(a.current=null)}),[]),[s,c]=(0,Q.useState)(t),[l,u]=(0,Q.useState)(n),[d,f]=(0,Q.useState)({}),p=(0,Q.useCallback)((e,t)=>f(n=>n[e]===t?n:{...n,[e]:t}),[]),[m,h]=(0,Q.useState)(t?.operationType??`evaluate`),[g,_]=(0,Q.useState)(()=>Cv(t)),v=(0,Q.useRef)(g);v.current=g;function y(e){(v.current?.source!==`alphaedit`||e===`alphaedit`)&&v.current?.source!==`neuron_training`&&(v.current?.source!==`decision`||e===`decision_model`)&&(v.current?.source!==`engram`||e===`engram_adapter`)&&(v.current?.source!==`steering`||e===`neuron_steering`)&&h(e)}let[b,x]=(0,Q.useState)(()=>Cv(t)?.baseModel??null),[S,C]=(0,Q.useState)(t?.trainingForm?.parent??null),[w,T]=(0,Q.useState)(null),[E,D]=(0,Q.useState)(()=>{let e=t?.evaluationForm?.form??(t?Ev(null,null,`model`):null),n=Cv(t);return e&&n?{...e,modelId:n.source===`inference`?n.inferenceModelId:``,localRuntime:n.source===`inference`?e.localRuntime:void 0}:e});function O(e,t){x(e),C(null),_(n=>e?{source:`managed`,baseModel:e,inferenceModelId:null,label:t??(n?.source===`managed`&&J(n.baseModel)===J(e)?n.label:e.modelId)}:null),D(e=>e&&{...e,modelId:``,localRuntime:void 0})}function k(e){_(e?{source:`inference`,label:e.name,inferenceModelId:e.id,baseModel:e.baseModel??null}:null),x(e?.baseModel??null),C(null),D(t=>t&&{...t,modelId:e?.id??``,localRuntime:void 0})}let A=(0,Q.useCallback)((e,t)=>{let n=v.current;if(!n||wv(n)!==e||n.source===`trained`||n.source===`steering`||n.source===`engram`||n.source===`decision`||n.source===`alphaedit`||n.source===`neuron_training`)return;let r=n.baseModel??t.baseModel;x(e=>J(e)===J(r)?e:r),D(e=>e&&(e.modelId!==(t.inferenceModelId??``)||e.localRuntime)?{...e,modelId:t.inferenceModelId??``,localRuntime:void 0}:e),n.source===`inference`?_(t=>t&&t.source===`inference`&&wv(t)===e&&J(t.baseModel)!==J(r)?{...t,baseModel:r}:t):_(n=>n&&n.source===`managed`&&wv(n)===e&&n.inferenceModelId!==t.inferenceModelId?{...n,inferenceModelId:t.inferenceModelId}:n)},[]),[j,M]=(0,Q.useState)(t?.evaluationForm?.source??null),[N,P]=(0,Q.useState)(()=>t?J({draft:t.evaluationForm?.form??Ev(null,null,`model`),selection:t.evaluationForm?.selection??null}):``),[F,I]=(0,Q.useState)(null),[L,ee]=(0,Q.useState)(t?.evaluationForm?.selection??null),R=e=>Tv(L?.release??null)===Tv(e);function z(e){ee(t=>Tv(t?.release??null)===Tv(e)?t:{release:e,mode:`all`,ids:[]})}function B(e=null,t=null,n=null,r=`model`){if(E&&j?.id===e?.id&&(!t||Tv(E.release)===Tv(t))){n&&I(n);return}T(null),c({schemaVersion:`openpond.experimentDraft.v1`,id:crypto.randomUUID(),operationType:`evaluate`,name:`Evaluation`}),u(null),f({}),x(null),_(null),C(null),y(`evaluate`);let i=Ev(e,t,r),a=i.release?{release:i.release,mode:e?`subset`:`all`,ids:e?[...new Set(e.request.population.map(e=>e.taskId))]:[]}:null;M(e),D(i),ee(a),_(i.modelId?{source:`inference`,label:i.modelId,inferenceModelId:i.modelId,baseModel:null}:null),P(J({draft:i,selection:a})),I(n)}function V(e,t,n){let r=e.evaluationForm,i=Cv(e),a=r?.form??Ev(null,null,`model`),o=i?{...a,modelId:i.source===`inference`?i.inferenceModelId:``,localRuntime:i.source===`inference`?a.localRuntime:void 0}:a;_(i),c(e),u(t),T(null),f({}),h(e.operationType),C(e.trainingForm?.parent??null),x(i?.baseModel??null),D(o),M(r?.source??null),ee(r?.selection??null),P(J({draft:o,selection:r?.selection??null})),I({...n,executionLocation:r?.executionLocation??`hosted`})}function H(e,t){V(e.draft,e,t)}async function U(e,t){let n=Kn.parse(e),i,o=()=>{r?i=r(n):V(n,null,t)};a.current?await a.current(o):o(),await i}function te(e){s?.id===e.id&&(u(e),e.draft.evaluationForm&&P(J({draft:e.draft.evaluationForm.form,selection:e.draft.evaluationForm.selection})))}function ne(e,t){E&&Tv(E.release)===Tv(e)?(y(`evaluate`),I(t)):B(null,e,t)}async function re(e,t,n){let r=!1,i=()=>{r=!0,ne(e,t),n&&`all`in n?W.selectAll(e,n.all):n&&W.toggle(e,n.id,n.checked)};return E&&Tv(E.release)!==Tv(e)&&a.current?await a.current(i):i(),r}let W={startingModel:g,chooseInferenceModel:k,applyModelCatalogLink:A,trainingParent:S,setTrainingParent:C,registerTransitionGuard:o,requestSelection:re,storedRecord:l,openDraft:U,openStored:H,acceptSaved:te,evaluationDirty:J({draft:E,selection:L})!==N,initialExperiment:s,allowedOperationTypes:i,operationDraftDirty:Object.values(d).some(Boolean),reportOperationDraftDirty:p,operationType:m,setOperationType:y,trainingBaseModel:b,setTrainingBaseModel:O,advancedTarget:w,openAdvanced:e=>{T(e),D(null),M(null),I(null)},draft:E,setDraft:D,existing:j,changeRelease:e=>{D(t=>t&&{...t,release:e}),Tv(E?.release??null)!==Tv(e)&&I(null),e&&z(e)},baseline:N,reviewRoute:F,selection:L,activate:z,open:B,openSelection:ne,close:()=>{c(null),u(null),f({}),x(null),_(null),C(null),T(null),D(null),M(null),I(null)},selected:(e,t)=>!R(e)||L.mode===`all`?!R(e)||!L.ids.includes(t):L.ids.includes(t),toggle:(e,t,n)=>ee(r=>{let i=Tv(r?.release??null)===Tv(e)?r:{release:e,mode:`all`,ids:[]},a=i.mode===`all`?!n:n;return{...i,ids:a?[...new Set([...i.ids,t])]:i.ids.filter(e=>e!==t)}}),selectAll:(e,t)=>ee({release:e,mode:t?`all`:`subset`,ids:[]}),count:(e,t)=>R(e)?L.mode===`all`?Math.max(0,t-L.ids.length):L.ids.length:t};return(0,$.jsx)(Dv.Provider,{value:W,children:e})}function kv(){let e=(0,Q.useContext)(Dv);if(!e)throw Error(`Evaluation setup requires workspace scope.`);return e}var Av=(0,Q.createContext)(!1),jv=()=>(0,Q.useContext)(Av),Mv=(0,Q.createContext)(null),Nv=(0,Q.createContext)(()=>{});function Pv(e){let t=(0,Q.useContext)(Nv);(0,Q.useEffect)(()=>{t(e)},[e,t])}var Fv=(0,Q.createContext)(null),Iv=()=>(0,Q.useContext)(Fv);function Lv({children:e,onControl:t}){let[n,r]=(0,Q.useState)(!1),[i,a]=(0,Q.useState)(440),[o,s]=(0,Q.useState)({}),c=(0,Q.useCallback)((e,t)=>(s(n=>({...n,[t]:e})),()=>s(e=>{let n={...e};return delete n[t],n})),[]),l=(0,Q.useMemo)(()=>{let e=new Map;for(let t of Object.values(o))for(let n of t)e.set(n.id,n);return[...e.values()]},[o]),u=(0,Q.useRef)([]),[d,f]=(0,Q.useState)(null),p=(0,Q.useRef)(new Map),m=(0,Q.useCallback)((e,t)=>(p.current.set(e,t),()=>{p.current.get(e)===t&&p.current.delete(e)}),[]),h=(0,Q.useCallback)(e=>a(Math.max(320,Math.min(800,e))),[]),g=(0,Q.useCallback)(e=>{u.current=[...u.current.filter(t=>t!==e),e],f(e),r(!0)},[]),_=(0,Q.useCallback)(e=>{u.current=u.current.filter(t=>t!==e),f(t=>t===e?u.current.at(-1)??null:t),u.current.length||r(!1)},[]),v=(0,Q.useCallback)(e=>{e.onSelect();let t=[...u.current].reverse().find(t=>t.startsWith(`${e.id}:`));t?g(t):(f(e.id),r(!0))},[g]),y=(0,Q.useCallback)(()=>{!n&&!u.current.length&&l[0]?v(l.find(e=>e.id===d)??l[0]):r(e=>!e)},[n,l,d,v]),b=(0,Q.useCallback)(()=>{let e=d?p.current.get(d):null;e?e():r(!1)},[d]);(0,Q.useEffect)(()=>(t?.({open:n,toggle:y}),()=>t?.(null)),[t,n,y]);let x=(0,Q.useMemo)(()=>({open:n,width:i,actions:l,active:d,toggle:y,dismiss:b,registerClose:m,resize:h,register:c,select:v,show:g,close:_}),[n,i,l,d,y,b,m,h,v,g,_]);return(0,$.jsx)(Fv.Provider,{value:x,children:e})}function Rv(e){let t=Iv(),n=t?.register,r=(0,Q.useId)(),i=(0,Q.useRef)(e);i.current=e;let a=e.map(e=>`${e.id}:${e.label}`).join(`|`);return(0,Q.useEffect)(()=>{if(n)return n(i.current.map(e=>({...e,onSelect:()=>i.current.find(t=>t.id===e.id)?.onSelect()})),r)},[n,a,r]),e=>{let n=i.current.find(t=>t.id===e);n&&(t?t.select(n):n.onSelect())}}function zv(){let e=Iv();return e?(0,$.jsxs)(`div`,{className:`evaluation-panel-toolbar`,children:[(0,$.jsx)(`nav`,{"aria-label":`Sidebar actions`,children:e.actions.map(t=>(0,$.jsx)(`button`,{type:`button`,"aria-pressed":e.active===t.id||e.active?.startsWith(`${t.id}:`),onClick:()=>e.select(t),children:t.label},t.id))}),(0,$.jsx)(`button`,{type:`button`,className:`evaluation-panel-icon`,"aria-label":`Collapse sidebar`,onClick:e.dismiss,children:(0,$.jsx)(es,{size:16})})]}):null}function Bv({children:e,label:t,action:n,onRequestClose:r,visible:i=!0}){let a=(0,Q.useContext)(Mv),o=Iv(),s=(0,Q.useId)(),c=n?`${n}:${s}`:s,l=o?.show,u=o?.close,d=(0,Q.useRef)(r);d.current=r;let f=o?.registerClose;return(0,Q.useEffect)(()=>{if(f&&r)return f(c,()=>d.current?.())},[f,c,!!r]),(0,Q.useEffect)(()=>(i?l?.(c):u?.(c),()=>u?.(c)),[l,u,c,i]),a?(0,vu.createPortal)((0,$.jsx)(`section`,{"aria-label":t,hidden:!i||!!(o&&o.active!==c),children:(0,$.jsx)(Av.Provider,{value:!0,children:e})}),a):null}function Vv(e){return JSON.stringify([e.key,e.actorId,e.connection.serverUrl,e.connection.token])}function Hv(e,t,n,r){if(!e.actorId)throw Error(`Sign in to use the evaluation owner controls.`);return Y(e.connection,`/v1/${t}`,{method:`POST`,body:JSON.stringify({teamId:e.teamId,projectId:e.projectId,request:n}),signal:r})}function Uv(e,t){return A({queryKey:[`reviewed-evaluation-operations`,Vv(e),t],initialPageParam:void 0,getNextPageParam:e=>e.nextCursor??void 0,queryFn:async({pageParam:n,signal:r})=>sl.parse(await e.pendingOperations(t,n,r)),refetchOnWindowFocus:!0})}function Wv({items:e,busy:t,error:n,onRestore:r,onDiscard:i,onLoadMore:a}){return(0,$.jsxs)(`section`,{"aria-label":`Retained reviewed operations`,children:[n?(0,$.jsx)(X,{error:n}):null,e.length?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h3`,{children:`Retained operations`}),(0,$.jsx)(`p`,{children:`Restore the original reviewed command before retrying an uncertain request. Changing the setup does not replace that command.`})]}):null,e.map(e=>(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`p`,{children:[e.id,` / `,e.phase??`recovery unavailable`,` / `,e.createdAt]}),e.recoveryReady?(0,$.jsx)(`button`,{type:`button`,disabled:t,onClick:()=>r(e),children:`Restore original command`}):(0,$.jsx)(`p`,{children:`The original command was not retained. Recover its actual receipt before starting another operation.`}),e.phase===`reviewed`?(0,$.jsx)(`button`,{type:`button`,disabled:t,onClick:()=>i(e),children:`Discard unstarted review`}):null]},e.id)),a?(0,$.jsx)(`button`,{type:`button`,disabled:t,onClick:a,children:`Load more retained operations`}):null]})}var Gv=U().trim().min(1).max(200),Kv=U().regex(/^[a-f0-9]{64}$/),qv=U().datetime(),Jv=z({operationId:Gv,id:Gv.optional(),expectedRevision:V().int().nonnegative(),teamId:Gv,projectId:Gv.nullable(),enabled:B(),configuration:Ts,cadence:I(`kind`,[z({kind:L(`interval`),seconds:V().int().min(60).max(31536e3)}).strict(),z({kind:L(`nightly`),calendar:ve}).strict()]),maximumTotalSpendUsd:V().finite().positive().max(1e4),maximumAttempts:V().int().min(1).max(20)}).strict().superRefine((e,t)=>{(e.configuration.request.teamId!==e.teamId||(e.configuration.request.project?.id??null)!==e.projectId)&&t.addIssue({code:`custom`,message:`The scheduled Experiment must retain its actual workspace and Project.`}),e.configuration.maximumCostUsd>e.maximumTotalSpendUsd&&t.addIssue({code:`custom`,message:`The run ceiling exceeds the approved cumulative schedule ceiling.`})}),Yv=z({id:Gv,scheduledAt:qv,coalescedThroughAt:qv,coalescedCount:V().int().nonnegative(),configurationHash:Kv,operationId:Gv,state:H([`reserved`,`dispatching`,`running`,`cleaning`,`completed`,`failed`,`cancelled`,`uncertain`]),executionId:Gv.nullable(),attempt:V().int().positive(),maximumCostUsd:V().finite().positive(),actualSpendUsd:V().finite().nonnegative().nullable(),cleanupComplete:B(),error:U().max(4e3).nullable()}).strict(),Xv=z({schemaVersion:L(`openpond.experimentEvaluationSchedule.v1`),id:Gv,revision:V().int().positive(),actorId:Gv,teamId:Gv,projectId:Gv.nullable(),operationId:Gv,requestHash:Kv,configuration:Ts,configurationHash:Kv,cadence:Jv.shape.cadence,state:H([`scheduled`,`disabled`,`blocked`]),nextRunAt:qv.nullable(),maximumTotalSpendUsd:V().finite().positive(),maximumAttempts:V().int().positive(),lastEvaluatedConfigurationHash:Kv.nullable(),newerUnevaluatedRelease:Ne.nullable(),fires:F(Yv).max(1e4),reason:U().max(4e3).nullable(),createdAt:qv,updatedAt:qv,contentHash:Kv}).strict();function Zv(e){let{operationId:t,request:n,...r}=e,{operationId:i,...a}=n;return je({...r,request:a})}function Qv(e){let t=Xv.parse(e);if(Be(t,`Scheduled Experiment`),t.configurationHash!==Zv(t.configuration)||t.configuration.request.teamId!==t.teamId||(t.configuration.request.project?.id??null)!==t.projectId)throw Error(`Scheduled Experiment immutable authority differs from its recipe.`);return t}var $v=z({teamId:Gv,id:Gv,operationId:Gv,expectedRevision:V().int().positive(),action:H([`cancel_active`,`retry_active`,`pause`])}).strict(),ey=I(`operation`,[z({operation:L(`publish`),request:Jv}).strict(),z({operation:L(`control`),request:$v}).strict(),z({operation:L(`read`),id:Gv}).strict(),z({operation:L(`list`),cursor:Gv.optional(),limit:V().int().min(1).max(100).default(50)}).strict()]),ty=(0,Q.createContext)(null);function ny({children:e,handle:t}){let n=(0,Q.useRef)(new Set),r=(0,Q.useRef)(!1),i=(0,Q.useRef)(!0);(0,Q.useEffect)(()=>(i.current=!0,()=>{i.current=!1}),[]);let a=(0,Q.useCallback)(e=>(n.current.add(e),()=>{n.current.delete(e)}),[]);return(0,Q.useImperativeHandle)(t,()=>({async requestLeave(e){if(!r.current){r.current=!0;try{for(let e of[...n.current].reverse())if(!await e())return;i.current&&await e()}finally{r.current=!1}}}}),[]),(0,$.jsx)(ty.Provider,{value:a,children:e})}function ry(e){let t=(0,Q.useContext)(ty),n=(0,Q.useRef)(e);n.current=e,(0,Q.useEffect)(()=>t?.(()=>n.current()),[t])}function iy(e){let t=(0,Q.useRef)(e);t.current=e;let n=(0,Q.useRef)(null),r=(0,Q.useRef)(!1),i=(0,Q.useRef)(!0),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(null);async function d(){return r.current?(r.current=!1,!0):t.current.busy?!1:!t.current.dirty||!n.current&&(u(null),o(!0),new Promise(e=>{n.current=e}))}ry(async()=>await d()&&i.current),(0,Q.useEffect)(()=>{i.current=!0;let e=uo(async e=>{if(t.current.retainForDestination?.(e)&&!t.current.busy)return!0;let n=await d();return n&&i.current&&t.current.onLeave?.(),n&&i.current}),r=e=>{t.current.dirty&&(e.preventDefault(),e.returnValue=``)};return window.addEventListener(`beforeunload`,r),()=>{i.current=!1,e(),window.removeEventListener(`beforeunload`,r);let t=n.current;n.current=null,t?.(!1)}},[]);let f=e=>{let t=n.current;n.current=null,i.current&&o(!1),t?.(e)};return{dialog:a?(0,$.jsxs)(qa,{ariaLabel:e.save?`Save ${e.name} before leaving`:`Discard ${e.name}`,className:`labs-rename-dialog labs-draft-exit-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:s,onClose:()=>f(!1),children:[(0,$.jsx)(`h2`,{children:e.save?`Save ${e.name} before leaving?`:`Discard ${e.name}?`}),(0,$.jsx)(`p`,{children:e.save?`Your changes can be saved before opening the next page.`:e.discardDescription??`This setup has not been saved. Keep editing or discard it to leave.`}),l?(0,$.jsx)(X,{error:l}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{className:`training-button secondary`,type:`button`,disabled:s,onClick:()=>f(!1),children:`Keep editing`}),(0,$.jsx)(`button`,{className:`training-button secondary`,type:`button`,disabled:s,onClick:()=>f(!0),children:`Discard changes`}),e.save?(0,$.jsx)(`button`,{className:`training-button`,type:`button`,disabled:s,onClick:async()=>{c(!0);try{let e=await t.current.save?.();i.current&&(e?f(!0):u(`The draft could not be saved. Your edits are still here.`))}catch(e){i.current&&u(e instanceof Error?e.message:`The draft could not be saved.`)}finally{i.current&&c(!1)}},children:s?`Saving…`:`Save and continue`}):null]})]}):null,allowNextNavigation(){r.current=!0},async requestLeave(e){await d()&&i.current&&e()}}}function ay({api:e,configuration:t,onOpenExperiment:n}){let[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(!1),l=iy({name:`evaluation schedule`,dirty:a,busy:s,onLeave:()=>i(!1)});return Rv(t?[{id:`scheduled-evaluations`,label:`Scheduled evaluations`,onSelect:()=>i(!0)}]:[]),(0,$.jsxs)($.Fragment,{children:[r&&t?(0,$.jsx)(Bv,{label:`Scheduled evaluations`,action:`scheduled-evaluations`,onRequestClose:()=>void l.requestLeave(()=>i(!1)),children:(0,$.jsx)(oy,{api:e,configuration:t,requestChange:e=>void l.requestLeave(e),onDirty:o,onBusy:c,onOpenExperiment:n},ie([Vv(e),Zv(t)]))}):null,l.dialog]})}function oy({api:e,configuration:t,onDirty:n,requestChange:r,onBusy:i,onOpenExperiment:a}){let o=u(),s=Vv(e),c=(0,Q.useRef)(s);c.current=s;let[l,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(`interval`),[g,_]=(0,Q.useState)(1440),[v,y]=(0,Q.useState)(`02:00`),[b,x]=(0,Q.useState)(Intl.DateTimeFormat().resolvedOptions().timeZone),[C,w]=(0,Q.useState)(t.maximumCostUsd),[T,E]=(0,Q.useState)(1),[D,O]=(0,Q.useState)(null),[k,j]=(0,Q.useState)(!1),M=(0,Q.useRef)(null),N=(0,Q.useRef)(null),P=(0,Q.useRef)(!0);(0,Q.useEffect)(()=>(P.current=!0,()=>{P.current=!1,N.current?.abort()}),[]),(0,Q.useEffect)(()=>(i(k),()=>i(!1)),[k,i]);let F=Uv(e,`experiment-evaluation-schedule`),I=F.data?.pages.flatMap(e=>e.items)??[];async function L(t){let r=s;j(!0);try{await e.recoverOperation(t).acknowledge(`reviewed`),P.current&&c.current===r&&(M.current?.operation.id===t.id&&(M.current=null),await F.refetch(),n(!1))}catch(e){P.current&&c.current===r&&O(e instanceof Error?e.message:String(e))}finally{P.current&&c.current===r&&j(!1)}}function ee(t){try{if(!t.recoveryReady||ie(t.reviewedIntent)!==t.intentHash)throw Error(`The original reviewed intent is unavailable.`);let r=ey.parse(t.command);if(r.operation!==`publish`&&r.operation!==`control`)throw Error(`The retained command is not an owner action.`);if(r.request.operationId!==t.id||r.request.teamId!==e.teamId)throw Error(`The retained command belongs to another owner scope.`);M.current={scope:s,request:r,operation:e.recoverOperation(t)},n(!0),O(null)}catch(e){O(e instanceof Error?e.message:String(e))}}let R=[`evaluation-schedules`,s],z=A({queryKey:R,initialPageParam:void 0,getNextPageParam:e=>e.nextCursor??void 0,queryFn:async({signal:t,pageParam:n})=>{let r=await Hv(e,`experiment-evaluation-schedules`,{operation:`list`,limit:100,...n?{cursor:n}:{}},t);return{items:r.items.map(Qv),nextCursor:r.nextCursor}},refetchInterval:5e3}),B=Zv(t),V=z.data?.pages.flatMap(e=>e.items).filter(e=>e.configurationHash===B)??[],H=S({queryKey:[...R,l?.id],enabled:!!l,queryFn:async({signal:t})=>Qv(await Hv(e,`experiment-evaluation-schedules`,{operation:`read`,id:l.id},t)),refetchInterval:3e3});(0,Q.useEffect)(()=>{H.data&&H.data.id===l?.id&&H.data.revision>=l.revision&&d(H.data)},[H.data,l]);function U(e){k||M.current||(e(),n(!0))}function te(e){d(e),p(e.state!==`disabled`),w(e.maximumTotalSpendUsd),E(e.maximumAttempts),h(e.cadence.kind),e.cadence.kind===`interval`?_(e.cadence.seconds/60):(y(e.cadence.calendar.localTime),x(e.cadence.calendar.timeZone)),n(!1)}async function ne(t,n){if(k)return;j(!0),O(null);let r=s,i=new AbortController;N.current=i;try{let a=M.current;if(a&&a.scope!==r)throw Error(`The pending schedule command belongs to another scope.`);if(!a){let i=await e.operation(`experiment-evaluation-schedule`,t);if(!P.current||c.current!==r)return;a={scope:r,request:n(i.id),operation:i},M.current=a}if(await a.operation.retainCommand(a.request,`dispatching`),!P.current||c.current!==r)return;let s=Qv(await Hv(e,`experiment-evaluation-schedules`,a.request,i.signal));if(!P.current||c.current!==r||(te(s),await a.operation.acknowledge(),!P.current||c.current!==r)||(M.current=null,await F.refetch(),!P.current||c.current!==r))return;await o.invalidateQueries({queryKey:R})}catch(e){P.current&&c.current===r&&O(e instanceof Error?e.message:String(e))}finally{P.current&&c.current===r&&j(!1),N.current===i&&(N.current=null)}}let re=m===`interval`?{kind:`interval`,seconds:Math.round(g*60)}:{kind:`nightly`,calendar:{localTime:v,timeZone:b}},W={id:l?.id,expectedRevision:l?.revision??0,teamId:e.teamId,projectId:e.projectId,configuration:t,enabled:f,cadence:re,maximumTotalSpendUsd:C,maximumAttempts:T};return(0,$.jsxs)(`div`,{className:`evaluation-form`,children:[(0,$.jsx)(`h2`,{children:`Scheduled evaluations`}),(0,$.jsx)(Wv,{items:I,busy:k,error:F.error?.message,onRestore:ee,onDiscard:e=>void L(e),onLoadMore:F.hasNextPage?()=>void F.fetchNextPage():void 0}),M.current?(0,$.jsxs)(`p`,{children:[`Frozen command: `,M.current.operation.id,`. This retry uses the original retained setup and limits, even if the current parent setup differs.`]}):null,(0,$.jsx)(`p`,{children:`Execution owner: this connected app server. It must remain running. Each occurrence evaluates this pinned recipe within the cumulative limits; no source release is advanced automatically.`}),(0,$.jsx)(`p`,{children:`Saved schedules run the exact reviewed Dataset, target and graders. New releases are shown for review and never selected automatically.`}),D??z.error?.message??H.error?.message?(0,$.jsx)(X,{error:D??z.error?.message??H.error?.message}):null,(0,$.jsxs)(`label`,{children:[`Existing schedule`,(0,$.jsxs)(`select`,{disabled:k||!!M.current,value:l?.id??``,onChange:e=>{let i=V.find(t=>t.id===e.target.value);r(()=>{i?te(i):(d(null),p(!1),h(`interval`),_(1440),y(`02:00`),x(Intl.DateTimeFormat().resolvedOptions().timeZone),w(t.maximumCostUsd),E(1),n(!1))})},children:[(0,$.jsx)(`option`,{value:``,children:`New schedule for this setup`}),V.map(e=>(0,$.jsxs)(`option`,{value:e.id,children:[e.id,` / `,e.state,` / revision `,e.revision]},e.id))]})]}),z.hasNextPage?(0,$.jsx)(`button`,{type:`button`,disabled:z.isFetchingNextPage,onClick:()=>void z.fetchNextPage(),children:`Load more schedules`}):null,(0,$.jsxs)(`fieldset`,{disabled:k||!!M.current,children:[(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:f,onChange:e=>U(()=>p(e.target.checked))}),`Enable scheduled evaluations`]}),(0,$.jsxs)(`label`,{children:[`Cadence`,(0,$.jsxs)(`select`,{value:m,onChange:e=>U(()=>h(e.target.value===`nightly`?`nightly`:`interval`)),children:[(0,$.jsx)(`option`,{value:`interval`,children:`Interval`}),(0,$.jsx)(`option`,{value:`nightly`,children:`Nightly`})]})]}),m===`interval`?(0,$.jsxs)(`label`,{children:[`Interval minutes`,(0,$.jsx)(`input`,{type:`number`,min:1,max:525600,value:g,onChange:e=>U(()=>_(Number(e.target.value)))})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[`Local time`,(0,$.jsx)(`input`,{type:`time`,value:v,onChange:e=>U(()=>y(e.target.value))})]}),(0,$.jsxs)(`label`,{children:[`Time zone`,(0,$.jsx)(`input`,{value:b,onChange:e=>U(()=>x(e.target.value))})]})]}),(0,$.jsxs)(`label`,{children:[`Cumulative budget USD`,(0,$.jsx)(`input`,{type:`number`,min:t.maximumCostUsd,value:C,onChange:e=>U(()=>w(Number(e.target.value)))})]}),(0,$.jsxs)(`label`,{children:[`Maximum attempts`,(0,$.jsx)(`input`,{type:`number`,min:1,max:20,value:T,onChange:e=>U(()=>E(Number(e.target.value)))})]})]}),(0,$.jsxs)(`p`,{children:[`Per-occurrence ceiling `,t.maximumCostUsd,` USD. Exact recipe`,` `,B,`.`]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:k||F.isPending||!!F.error,onClick:()=>void ne(W,e=>({operation:`publish`,request:{...W,operationId:e}})),children:M.current?`Retry retained command`:`Save schedule`}),l?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[l.state,` / next `,l.nextRunAt??`none`]}),l.reason?(0,$.jsx)(`p`,{children:l.reason}):null,l.newerUnevaluatedRelease?(0,$.jsxs)(`p`,{children:[`Newer unevaluated Dataset: `,l.newerUnevaluatedRelease.id,` /`,` `,l.newerUnevaluatedRelease.contentHash,`. Review a new setup before changing this schedule.`]}):null,[`pause`,`cancel_active`,`retry_active`].map(t=>(0,$.jsx)(`button`,{type:`button`,disabled:k||!!M.current,onClick:()=>void ne({id:l.id,revision:l.revision,action:t},n=>({operation:`control`,request:{teamId:e.teamId,id:l.id,expectedRevision:l.revision,operationId:n,action:t}})),children:t.replaceAll(`_`,` `)},t)),(0,$.jsx)(`ol`,{children:l.fires.map(e=>(0,$.jsxs)(`li`,{children:[e.scheduledAt,` / `,e.state,` /`,` `,e.actualSpendUsd===null?`Spend unresolved`:`${e.actualSpendUsd} USD`,` `,`/ cleanup `,e.cleanupComplete?`complete`:`pending`,e.coalescedCount?` / coalesced ${e.coalescedCount}`:``,e.executionId&&a?(0,$.jsx)(`button`,{type:`button`,onClick:()=>a(e.executionId),children:`Open actual Experiment`}):null,e.error?(0,$.jsx)(`p`,{children:e.error}):null]},e.id))})]}):null]})}var sy=I(`ready`,[z({ready:L(!1),reason:U(),choices:F(ee())}).strict(),z({ready:L(!0),version:U(),executableHash:U(),capabilityHash:U(),choices:F(z({id:U(),name:U(),configurationHash:U(),contextWindow:V(),outputLimit:V()}).strict())}).strict()]);function cy({api:e,policy:t,onChange:n}){let[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(0);(0,Q.useEffect)(()=>{let t=new AbortController;return i(null),o(null),e.local(`claudeReadiness`,{},t.signal).then(e=>{t.signal.aborted||i(sy.parse(e))}).catch(e=>{t.signal.aborted||o(e.message)}),()=>t.abort()},[e.key,s]);let l=t.kind===`hosted_chat`&&t.localRuntime?.providerId===`claude-code`?t.localRuntime:void 0;return(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h3`,{children:`Live Claude Code`}),(0,$.jsx)(`p`,{children:`Run the installed CLI in an isolated text-task session. This target has no filesystem tools or MCP servers. Actual events and human interventions are retained locally; team publication remains explicit.`}),a?(0,$.jsx)(X,{error:a}):null,r&&!r.ready?(0,$.jsx)(`p`,{children:r.reason}):null,r?.ready?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[`Installed interface `,r.version,`, exact executable and capabilities pinned`]}),(0,$.jsxs)(`label`,{children:[`Claude model`,(0,$.jsxs)(`select`,{value:l&&t.kind===`hosted_chat`?t.modelId:``,onChange:e=>{if(t.kind!==`hosted_chat`)return;let i=r.choices.find(t=>t.id===e.target.value);i&&n({...t,modelId:i.id,temperature:0,topP:1,maxOutputTokens:Math.min(t.maxOutputTokens,i.outputLimit),harness:void 0,candidate:void 0,localRuntime:{providerId:`claude-code`,configurationHash:i.configurationHash,executableHash:r.executableHash,version:r.version,capabilityHash:r.capabilityHash,maximumRequestCostUsd:.01,requestTimeoutMs:18e4,maximumTurns:5,holdOpen:!1}})},children:[(0,$.jsx)(`option`,{value:``,children:`Select an exact configured model`}),r.choices.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]})]}):null,(0,$.jsx)(`button`,{type:`button`,onClick:()=>c(e=>e+1),children:`Refresh installed interface`}),l&&t.kind===`hosted_chat`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[`CLI request budget ($)`,(0,$.jsx)(`input`,{type:`number`,min:1e-6,max:1e4,step:.001,value:l.maximumRequestCostUsd,onChange:e=>n({...t,localRuntime:{...l,maximumRequestCostUsd:Number(e.target.value)}})})]}),(0,$.jsxs)(`label`,{children:[`Turn limit`,(0,$.jsx)(`input`,{type:`number`,min:1,max:100,value:l.maximumTurns,onChange:e=>n({...t,localRuntime:{...l,maximumTurns:Number(e.target.value)}})})]}),(0,$.jsxs)(`label`,{children:[`Deadline (seconds)`,(0,$.jsx)(`input`,{type:`number`,min:1,max:300,value:l.requestTimeoutMs/1e3,onChange:e=>n({...t,localRuntime:{...l,requestTimeoutMs:Number(e.target.value)*1e3}})})]}),(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:l.holdOpen,onChange:e=>n({...t,localRuntime:{...l,holdOpen:e.target.checked}})}),`Keep the session open for explicit human messages and sealing`]}),(0,$.jsx)(`p`,{children:`CLI cost estimates and reported tokens are retained. Measured monetary cost remains unknown.`})]}):null]})}function ly(e){let t=e=>`/v1/training/candidate-evaluations/${encodeURIComponent(e)}`;function n(e,t,n){let r=gy.parse(e);if(r.teamId!==t||n&&r.id!==n)throw Error(`The preparation belongs to another workspace or candidate operation.`);return r}return{async options(t,n={}){let r=new URLSearchParams({teamId:t,...n}),i=my.parse(await e(`/v1/training/candidates?${r}`));if(i.teamId!==t)throw Error(`The candidate catalog belongs to another workspace.`);return i},async save(t){let r=hy.parse(t),i=n(await e(`/v1/training/candidate-evaluations?teamId=${encodeURIComponent(r.teamId)}`,{method:`POST`,body:JSON.stringify(r)}),r.teamId);if(i.requestHash!==je(r))throw Error(`The saved preparation differs from the selected candidate or frozen evaluation.`);return i},async get(r,i){return n(await e(`${t(i)}?teamId=${encodeURIComponent(r)}`),r,i)},async control(r,i,a,o){let s=_y.parse(o),c=n(await e(`${t(i)}/${a}?teamId=${encodeURIComponent(r)}`,{method:`POST`,body:JSON.stringify(s)}),r,i);if(c.requestHash!==s.requestHash)throw Error(`The command returned a different frozen evaluation.`);return c}}}var uy=U().trim().min(1).max(200),dy=U().regex(/^[a-f0-9]{64}$/),fy=z({id:uy,contentHash:dy}).strict(),py=z({artifact:fy,trainingJobId:uy,configurationId:uy,baseProfileId:uy,ready:B(),reason:U().max(1e3).nullable()}).strict(),my=z({teamId:uy,ownerUserId:uy,items:F(py).max(100),nextCursor:uy.nullable()}).strict(),hy=z({teamId:uy,operationId:uy,artifact:fy,configuration:Ts}).strict().superRefine((e,t)=>{(e.configuration.request.teamId!==e.teamId||e.configuration.request.policy.kind===`fixture`||e.configuration.request.policy.candidate)&&t.addIssue({code:`custom`,message:`Choose one exact model-backed evaluation before preparing the trained version.`})}),gy=z({schemaVersion:L(`openpond.candidateEvaluationPreparation.v1`),teamId:uy,ownerUserId:uy,id:uy,revision:V().int().positive(),requestHash:dy,request:hy,trainingJobId:uy,dispatchId:uy,lastOperationId:uy.nullable(),runtime:z({poolId:uy,endpointId:uy.nullable(),baseProfileId:uy,workerImageDigest:U().regex(/^sha256:[a-f0-9]{64}$/),modelId:uy.nullable()}).strict().nullable(),state:H([`configured`,`preparing`,`ready`,`dispatching`,`submitted`,`cleaning`,`completed`,`failed`,`cancelled`]),experimentId:uy.nullable(),authorizedAt:N().nullable(),cancelledAt:N().nullable(),reason:U().max(1e3).nullable(),createdAt:N(),updatedAt:N()}).strict().superRefine((e,t)=>{(e.requestHash!==je(e.request)||!e.runtime&&[`ready`,`dispatching`,`submitted`,`completed`].includes(e.state))&&t.addIssue({code:`custom`,message:`The exact candidate preparation request or runtime changed.`})}),_y=z({operationId:uy,expectedRevision:V().int().positive(),requestHash:dy}).strict();function vy({connection:e,teamId:t,actorId:n,projectId:r,configuration:i,retainOperation:a,onStarted:o,onBusyChange:s}){let c=JSON.stringify([e.serverUrl,e.token,t,n,r]),l=(0,Q.useMemo)(()=>ly(async(n,r)=>{let i=new URL(n,`https://candidate.invalid`);return i.searchParams.set(`teamId`,t),Y(e,`${i.pathname}?${i.searchParams}`,r)}),[e.serverUrl,e.token,t]),u=(0,Q.useRef)(c);u.current=c,(0,Q.useEffect)(()=>(u.current=c,()=>{u.current=`unmounted`}),[c]);let d=(0,Q.useRef)(null),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>(s?.(b),()=>s?.(!1)),[b,s]);let S=g?.scope===c?g.value:null;(0,Q.useEffect)(()=>{let e=!1;if(y(null),x(!1),h(``),d.current?.scope!==c&&(d.current=null),!n)return;async function i(){try{let i=[],a,o=new Set;for(let e=0;;e++){if(e>=100)throw Error(`Candidate catalog exceeds its bounded supported scope.`);let s=await l.options(t,{projectId:r??void 0,afterId:a});if(s.ownerUserId!==n)throw Error(`The candidate owner changed.`);if(i.push(...s.items),!s.nextCursor)break;if(o.has(s.nextCursor))throw Error(`Candidate pagination did not advance.`);o.add(s.nextCursor),a=s.nextCursor}e||p({scope:c,items:i})}catch(t){e||y(t instanceof Error?t.message:`Candidate catalog is unavailable.`)}}return i(),()=>{e=!0}},[l,t,n,r,c]),(0,Q.useEffect)(()=>{if(!S||![`preparing`,`dispatching`,`submitted`,`cleaning`].includes(S.state))return;let e=!1,r,i=async()=>{try{let r=await l.get(t,S.id);if(!e){if(r.ownerUserId!==n)throw Error(`The candidate owner changed.`);_({scope:c,value:r})}}catch(t){e||y(t instanceof Error?t.message:`Candidate status is unavailable.`)}e||(r=setTimeout(i,3e3))};return r=setTimeout(i,3e3),()=>{e=!0,clearTimeout(r)}},[l,t,c,S?.id,S?.state]);async function C(e){if(b||!n)return;let s=c,p=()=>{if(u.current!==s)throw Error(`The active account or Project changed. Reopen candidate evaluation setup.`)};x(!0),y(null);try{let s=S;if(!s){let e=f?.scope===c?f.items.find(e=>e.artifact.id===m):null;if(!e||!i)throw Error(`Choose a trained version and complete the exact evaluation cases, graders and budget.`);let o=await a(`candidate:save`,{teamId:t,actorId:n,projectId:r,artifact:e.artifact,configuration:i});if(p(),s=await l.save({teamId:t,operationId:o.id,artifact:e.artifact,configuration:i}),p(),s.ownerUserId!==n)throw Error(`The candidate owner changed.`);_({scope:c,value:s}),await o.acknowledge(),p()}let u=d.current?.scope===c?d.current:null;if(u&&u.action!==e)throw Error(`Resolve the retained uncertain action before choosing another action.`);if(!u){let i=await a(`candidate:control`,{teamId:t,actorId:n,projectId:r,id:s.id,action:e,expectedRevision:s.revision,requestHash:s.requestHash});p(),u={scope:c,id:s.id,action:e,control:{operationId:i.id,expectedRevision:s.revision,requestHash:s.requestHash},acknowledge:i.acknowledge},d.current=u}let h=await l.control(t,u.id,u.action,u.control);if(p(),h.ownerUserId!==n)throw Error(`The candidate owner changed.`);_({scope:c,value:h}),await u.acknowledge(),p(),d.current=null,h.experimentId&&o(h.experimentId)}catch(e){u.current===s&&y(e instanceof Error?e.message:`Candidate evaluation could not proceed.`)}finally{u.current===s&&x(!1)}}return(0,$.jsxs)(`section`,{children:[(0,$.jsxs)(`label`,{children:[`Trained version`,(0,$.jsxs)(`select`,{disabled:b||!!S,value:m,onChange:e=>h(e.target.value),children:[(0,$.jsx)(`option`,{value:``,children:`Select owned trained artifact`}),f?.scope===c?f.items.map(e=>(0,$.jsxs)(`option`,{value:e.artifact.id,children:[e.artifact.id,` / `,e.artifact.contentHash.slice(0,12),e.reason?` / ${e.reason}`:``]},e.artifact.id)):null]})]}),v?(0,$.jsx)(X,{error:v}):null,S?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{role:`status`,children:[[`preparing`,`dispatching`,`submitted`,`cleaning`].includes(S.state)?(0,$.jsx)(`span`,{className:`hosted-training-spinner`,"aria-hidden":`true`}):null,S.state,S.reason?` / ${S.reason}`:``]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Frozen evaluation setup`}),(0,$.jsx)(`pre`,{children:JSON.stringify(S.request.configuration,null,2)})]}),i&&JSON.stringify(i)!==JSON.stringify(S.request.configuration)?(0,$.jsx)(`p`,{children:`The parent setup changed. This preparation retains the reviewed setup shown here.`}):null]}):null,(0,$.jsxs)(`div`,{children:[d.current?.scope===c?(0,$.jsxs)(`button`,{type:`button`,disabled:b,onClick:()=>void C(d.current.action),children:[`Retry retained `,d.current.action,` action`]}):null,!S||[`configured`,`preparing`].includes(S.state)?(0,$.jsx)(`button`,{type:`button`,disabled:b||!i||!m,onClick:()=>void C(`prepare`),children:`Prepare exact version for evaluation`}):null,S&&[`ready`,`dispatching`].includes(S.state)?(0,$.jsx)(`button`,{type:`button`,disabled:b,onClick:()=>void C(`run`),children:`Run Experiment`}):null,S&&![`completed`,`failed`,`cancelled`].includes(S.state)?(0,$.jsx)(`button`,{type:`button`,disabled:b,onClick:()=>void C(`cancel`),children:`Cancel evaluation`}):null]})]})}var yy=F(z({id:U(),name:U(),providerId:L(`custom-openai-compatible`),configurationHash:U().regex(/^[a-f0-9]{64}$/),contextWindow:V().int().positive(),outputLimit:V().int().positive()}).strict());function by({api:e,policy:t,onChange:n}){let[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(0);(0,Q.useEffect)(()=>{let t=new AbortController;return i([]),o(null),e.local(`localInferenceChoices`,{},t.signal).then(e=>{t.signal.aborted||i(yy.parse(e))}).catch(e=>{t.signal.aborted||o(e.message)}),()=>t.abort()},[e.key,s]);let l=t.kind===`hosted_chat`&&t.localRuntime?.providerId===`custom-openai-compatible`?t.localRuntime:void 0;return(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h3`,{children:`Local inference`}),(0,$.jsx)(`p`,{children:`Select the configured loopback OpenAI-compatible endpoint. Reported tokens are retained; monetary cost remains unknown. Starting reserves your request allocation and sends no target request to OpenPond.`}),a?(0,$.jsx)(X,{error:a}):null,(0,$.jsxs)(`label`,{children:[`Local model`,(0,$.jsxs)(`select`,{value:l&&t.kind===`hosted_chat`?t.modelId:``,onChange:e=>{let i=r.find(t=>t.id===e.target.value);i&&t.kind===`hosted_chat`&&n({...t,modelId:i.id,localRuntime:{providerId:i.providerId,configurationHash:i.configurationHash,maximumRequestCostUsd:.001,requestTimeoutMs:9e4},maxOutputTokens:Math.min(t.maxOutputTokens,i.outputLimit),harness:void 0,candidate:void 0})},children:[(0,$.jsx)(`option`,{value:``,children:`Select local model`}),r.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>c(e=>e+1),children:`Refresh choices`}),!r.length&&!a?(0,$.jsx)(`p`,{children:`Configure the local provider in Settings and refresh its model catalog with context/output bounds before starting.`}):null,l&&t.kind===`hosted_chat`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[`Request allocation ($, reserved while measured cost is unknown)`,(0,$.jsx)(`input`,{type:`number`,min:1e-6,max:1e4,step:1e-6,value:l.maximumRequestCostUsd,onChange:e=>n({...t,localRuntime:{...l,maximumRequestCostUsd:Number(e.target.value)}})})]}),(0,$.jsxs)(`label`,{children:[`Request timeout (seconds)`,(0,$.jsx)(`input`,{type:`number`,min:1,max:300,value:l.requestTimeoutMs/1e3,onChange:e=>n({...t,localRuntime:{...l,requestTimeoutMs:Number(e.target.value)*1e3}})})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>{let{localRuntime:e,...r}=t;n(r)},children:`Use hosted model configuration`})]}):null]})}function xy({disabled:e=!1}){let t=kv(),n=t.startingModel?.source===`alphaedit`,r=t.startingModel?.source===`neuron_training`,i=n||r,a=t.startingModel?.source===`decision`,o=t.startingModel?.source===`engram`,s=t.startingModel?.source===`steering`,c=`This saved steering source requires a neuron steering experiment. Choose another starting model for this action.`;return(0,$.jsxs)(`label`,{children:[`Modification`,(0,$.jsx)(Z,{label:`Modification`,floating:!0,value:t.operationType,disabled:e,options:[{value:`alphaedit`,label:`AlphaEdit`,disabled:a||o||s||r||t.startingModel?.source===`trained`||!!t.trainingParent,description:`Edit facts using reviewed edit and preservation batches.`},{value:`selective_neuron_training`,label:`Neuron training`,disabled:i||a||o||s||t.startingModel?.source===`trained`||!!t.trainingParent,description:r?`The saved inference delta contains no optimizer state; choose a managed base explicitly for new training.`:`Select neuron columns from reviewed target and background domains.`},{value:`decision_model`,label:`Decision model`,disabled:i||o||s||t.startingModel?.source===`trained`||!!t.trainingParent,description:`Train or score typed decisions using an exact Decision adapter.`},{value:`evaluate`,label:`Evaluate`,disabled:i||a||o||s||!!t.trainingParent,description:s?c:t.trainingParent?`This draft retains a training checkpoint. Evaluate the trained version from its result.`:void 0},{value:`sft`,label:`SFT + LoRA`,disabled:i||a||o||s||!!t.trainingParent,description:s?c:t.trainingParent?`The current SFT worker starts from a pinned base; checkpoint continuation is unavailable.`:void 0},{value:`grpo`,label:`RL (GRPO) + LoRA`,disabled:i||a||o||s,description:s?c:void 0},{value:`neuron_steering`,label:`Neuron steering`,disabled:i||a||o||!!t.trainingParent,description:t.trainingParent?`The selected trained checkpoint has no qualified steering runtime.`:`Compile and review a bounded hosted execution; a qualified runtime is required.`},{value:`engram_adapter`,label:`Engram adapter`,disabled:i||a||s||t.startingModel?.source===`trained`||!!t.trainingParent,description:s?c:`Train a memory adapter from an exact qualified managed base and a reviewed supervised batch.`},{value:`inspect_activations`,label:`Inspect activations`,disabled:i||a||o||s||!!t.trainingParent,description:s?c:t.trainingParent?`The selected trained checkpoint has no qualified inspection runtime.`:`Compile and review a bounded hosted execution; a qualified runtime is required.`}].filter(e=>t.allowedOperationTypes.includes(e.value)),onChange:e=>t.setOperationType(e)})]})}function Sy({draft:e,patch:t,supportsSampling:n,profileSeeds:r,children:i}){let[a,o]=(0,Q.useState)(()=>e.mode!==`model`||!!e.localRuntime),s=e.mode===`model_harness_profile`,c=e.temperature!==void 0||e.topP!==void 0;return(0,$.jsxs)(`details`,{open:a,onToggle:e=>o(e.currentTarget.open),children:[(0,$.jsx)(`summary`,{children:`Advanced settings`}),s?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:`Profile execution uses its exact released model configuration and evaluation seeds. Its execution owner prepares those pins.`}),r?(0,$.jsxs)(`p`,{children:[`Released seeds: `,r.join(`, `)]}):null]}):(0,$.jsxs)($.Fragment,{children:[n||c?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:c,disabled:!n&&!c,onChange:e=>t(e.target.checked?{temperature:0,topP:1}:{temperature:void 0,topP:void 0})}),`Override sampling`]}),c?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[`Temperature`,(0,$.jsx)(`input`,{type:`number`,min:`0`,max:`2`,step:`0.1`,disabled:!n,value:e.temperature===null?``:e.temperature??0,onChange:e=>t({temperature:e.target.value===``?null:e.target.valueAsNumber})})]}),(0,$.jsxs)(`label`,{children:[`Top P`,(0,$.jsx)(`input`,{type:`number`,min:`0.01`,max:`1`,step:`0.01`,disabled:!n,value:e.topP===null?``:e.topP??1,onChange:e=>t({topP:e.target.value===``?null:e.target.valueAsNumber})})]}),n?null:(0,$.jsx)(`p`,{children:`This model does not support sampling overrides. Clear the override to continue.`})]}):null]}):null,(0,$.jsxs)(`label`,{children:[`Maximum output tokens`,(0,$.jsx)(`input`,{type:`number`,min:`1`,max:`4096`,value:e.outputTokens??``,onChange:e=>t({outputTokens:e.target.value===``?null:e.target.valueAsNumber})})]}),(0,$.jsxs)(`label`,{children:[`Environment seeds`,(0,$.jsx)(`input`,{inputMode:`text`,value:e.seed,onChange:e=>t({seed:e.target.value})}),(0,$.jsx)(`small`,{children:`Separate seeds with commas. Unchanged existing membership keeps each original task and seed pair.`})]}),(0,$.jsxs)(`label`,{children:[`System instructions`,(0,$.jsx)(`textarea`,{value:e.prompt,onChange:e=>t({prompt:e.target.value}),rows:6})]}),e.mode===`model_harness`?(0,$.jsx)(`p`,{children:`Released Harness instructions are immutable; additional system instructions must be empty.`}):null]}),i]})}function Cy({api:e,draft:t,patch:n,sources:r}){let i=r.targets.filter(e=>e.target.kind===`agent`),a=r.targets.filter(e=>e.target.kind===`harness`);return(0,$.jsxs)(ft,{title:`Execution`,children:[(0,$.jsxs)(`label`,{children:[`Execution selection`,(0,$.jsx)(Z,{label:`Execution selection`,value:t.mode,floating:!0,options:[{value:`model`,label:`Model only`},{value:`model_harness`,label:`Model + Harness`},{value:`model_harness_profile`,label:`Model + Harness + Profile`}],onChange:e=>n({mode:e,targetId:`model`,sourceId:``,profileChoiceId:``})})]}),t.mode===`model_harness`?(0,$.jsxs)(`label`,{children:[`Released Harness`,(0,$.jsx)(Z,{label:`Released Harness`,searchable:!0,floating:!0,value:t.sourceId||(e.location===`hosted`&&r.selected?.target.kind===`agent`?`target:${t.targetId}`:``),options:[{value:``,label:`Choose released Harness`},...e.location===`local`?(r.local.data?.harnesses??[]).map(e=>({value:e.id,label:e.name})):[...r.retainedHostedSource&&!r.hostedHarnesses.some(e=>e.id===t.sourceId)?[{value:t.sourceId,label:`Retained Harness · ${r.retainedHostedSource.harnessRelease.id}`}]:[],...r.hostedHarnesses.map(e=>({value:e.id,label:e.name,disabled:!e.ready,description:e.ready?void 0:e.reason??void 0})),...i.map((e,t)=>({value:`target:${e.id}`,label:e.name,description:`Project target`,separatorBefore:t===0}))]],onChange:e=>n(e.startsWith(`target:`)?{sourceId:``,targetId:e.slice(7)}:{sourceId:e,targetId:``})})]}):null,t.mode===`model_harness_profile`?(0,$.jsxs)(`label`,{children:[`Released Profile evaluation`,(0,$.jsx)(Z,{label:`Released Profile evaluation`,searchable:!0,floating:!0,value:e.location===`local`?r.profile?.id??t.profileChoiceId:t.targetId,options:[{value:``,label:`Choose compatible Profile evaluation`},...(e.location===`local`?r.compatibleProfiles:a).map(e=>({value:e.id,label:e.name}))],onChange:t=>n(e.location===`local`?{profileChoiceId:t}:{targetId:t})})]}):null,r.harnessSource?(0,$.jsxs)(`dl`,{children:[(0,$.jsx)(`dt`,{children:`Harness release`}),(0,$.jsxs)(`dd`,{children:[r.harnessSource.harnessRelease.id,` ·`,` `,r.harnessSource.harnessRelease.contentHash]}),(0,$.jsx)(`dt`,{children:`Agent snapshot`}),(0,$.jsxs)(`dd`,{children:[r.harnessSource.agentSnapshot.id,` ·`,` `,r.harnessSource.agentSnapshot.contentHash]}),(0,$.jsx)(`dt`,{children:`Source package`}),(0,$.jsx)(`dd`,{children:r.harnessSource.sourcePackageHash})]}):null,r.profile?(0,$.jsxs)(`dl`,{children:[(0,$.jsx)(`dt`,{children:`Profile`}),(0,$.jsxs)(`dd`,{children:[r.profile.profileRef.profileId,` · `,r.profile.sourceRevision]}),(0,$.jsx)(`dt`,{children:`Harness release`}),(0,$.jsxs)(`dd`,{children:[r.profile.harnessRelease.id,` · `,r.profile.harnessRelease.contentHash]}),(0,$.jsx)(`dt`,{children:`Evaluation definition`}),(0,$.jsxs)(`dd`,{children:[r.profile.definitionId,` · `,r.profile.definitionHash]})]}):null,r.profileTarget?(0,$.jsxs)(`dl`,{children:[(0,$.jsx)(`dt`,{children:`Profile`}),(0,$.jsxs)(`dd`,{children:[r.profileTarget.source.profileId,` · `,r.profileTarget.source.sourceRevision]}),(0,$.jsx)(`dt`,{children:`Harness release`}),(0,$.jsxs)(`dd`,{children:[r.profileTarget.source.harnessRelease.id,` ·`,` `,r.profileTarget.source.harnessRelease.contentHash]}),(0,$.jsx)(`dt`,{children:`Evaluation definition`}),(0,$.jsxs)(`dd`,{children:[r.profileTarget.source.definitionId,` ·`,` `,r.profileTarget.source.definitionHash]})]}):null,r.unavailable&&r.saved?.kind===`hosted_chat`&&r.saved.harness?(0,$.jsxs)(`p`,{children:[`Retained Harness: `,r.saved.harness.harnessRelease.id,` ·`,` `,r.saved.harness.harnessRelease.contentHash,`. Source package:`,` `,r.saved.harness.sourcePackageHash,`.`]}):null,r.unavailable&&r.saved?.kind===`hosted_harness`?(0,$.jsxs)(`p`,{children:[`Retained Profile: `,r.saved.source.profileId,` · `,r.saved.source.sourceRevision,`. Harness: `,r.saved.source.harnessRelease.id,` ·`,` `,r.saved.source.harnessRelease.contentHash,`.`]}):null,e.location===`local`&&r.local.isPending?(0,$.jsx)(`p`,{role:`status`,children:`Loading authorized local sources…`}):null,r.local.error?(0,$.jsx)(X,{error:r.local.error.message,children:(0,$.jsx)(`button`,{type:`button`,onClick:()=>void r.local.refetch(),children:`Retry source discovery`})}):null,r.unavailable?(0,$.jsx)(X,{error:r.unavailable}):null,e.location===`hosted`&&t.mode===`model_harness`?(0,$.jsxs)($.Fragment,{children:[r.hosted.isPending?(0,$.jsx)(`p`,{role:`status`,children:`Loading published Harness sources…`}):null,r.hosted.error?(0,$.jsx)(X,{error:r.hosted.error.message,children:(0,$.jsx)(`button`,{type:`button`,onClick:()=>void r.hosted.refetch(),children:`Retry source discovery`})}):null,r.hosted.hasNextPage?(0,$.jsx)(`button`,{type:`button`,disabled:r.hosted.isFetchingNextPage,onClick:()=>void r.hosted.fetchNextPage(),children:`Load more Harness sources`}):null,!r.hosted.isPending&&!r.hosted.error&&!r.hostedHarnesses.length?(0,$.jsx)(`p`,{children:`Publish a complete released Harness source in this workspace to select it here.`}):null]}):null]})}function wy(e,t,n,r){let i=S({queryKey:[`evaluation-workspace`,e.key,`localSources`],enabled:e.location===`local`,queryFn:async({signal:t})=>il.parse(await e.local(`sourceChoices`,{},t))}),a=A({queryKey:[`evaluation-workspace`,e.key,`harnessSources`],enabled:e.location===`hosted`&&n.mode===`model_harness`,initialPageParam:void 0,queryFn:async({pageParam:t,signal:n})=>cc.parse(await e.request(`harnessSources`,{cursor:t},n)),getNextPageParam:e=>e.nextCursor??void 0}),o=a.data?.pages.flatMap(e=>e.items).map(e=>({...e,id:`harness-${e.source.harnessRelease.contentHash}`}))??[],s=t?.projects.projects.find(t=>t.id===e.projectId)?.content.targets??[],c=s.find(e=>e.id===n.targetId),l=r?.request.policy,u=e.location===`local`?i.data?.harnesses.find(e=>e.id===n.sourceId):void 0,d=e.location===`hosted`?o.find(e=>e.id===n.sourceId&&e.ready):void 0,f=e.location===`hosted`&&l?.kind===`hosted_chat`&&l.harness&&n.sourceId===`harness-${l.harness.harnessRelease.contentHash}`&&!o.some(e=>e.id===n.sourceId)?l.harness:void 0,p=i.data?.profiles.filter(e=>e.taskset.id===n.release?.id&&e.taskset.contentHash===n.release.contentHash)??[],m=e.location===`local`?p.find(e=>e.id===n.profileChoiceId||!n.profileChoiceId&&l?.kind===`hosted_harness`&&e.profileRef.repositoryId===l.profileRepositoryId&&e.profileRef.profileId===l.source.profileId&&e.definitionHash===l.source.definitionHash&&ie(e.harnessRelease)===ie(l.source.harnessRelease)):void 0,h=n.mode===`model_harness`?e.location===`local`?u?.source:d?.source??f??(c?.target.kind===`agent`?c.target.source:void 0):void 0,g=n.mode===`model_harness_profile`&&c?.target.kind===`harness`?c.target:void 0;return{local:i,hosted:a,hostedHarnesses:o,retainedHostedSource:f,targets:s,selected:c,compatibleProfiles:p,profile:m,profileTarget:g,harnessSource:h,unavailable:n.mode===`model_harness`&&!h?`The exact Harness is unavailable or unsupported in this account, workspace and execution location. Choose an authorized released Harness.`:n.mode===`model_harness_profile`&&(e.location===`local`?!m:!g)?`The exact Profile composition is unavailable or incompatible with this Dataset. Choose its compatible released Profile evaluation.`:null,saved:l}}var Ty=[`input`,`output`,`expectedOutput`,`evaluatorContext`];function Ey({value:e,onChange:t}){let n=it.safeParse(e),r=(n,r)=>t(e.map((e,t)=>t===n?{...e,...r}:e));return(0,$.jsxs)(`fieldset`,{children:[(0,$.jsx)(`legend`,{children:`Grader field mappings`}),(0,$.jsx)(`p`,{children:`Mappings apply only to grading evidence. Private reference answers stay in the server’s evaluator context.`}),e.map((n,i)=>(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`label`,{children:[`Read from`,(0,$.jsx)(`select`,{value:n.source,onChange:e=>r(i,{source:e.target.value}),children:Ty.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))})]}),(0,$.jsxs)(`label`,{children:[`Source path`,(0,$.jsx)(`input`,{value:n.sourcePath.join(`.`),onChange:e=>r(i,{sourcePath:e.target.value?e.target.value.split(`.`):[]}),placeholder:`Empty path reads the whole selected value`})]}),(0,$.jsxs)(`label`,{children:[`Write to`,(0,$.jsx)(`select`,{value:n.destination,onChange:e=>r(i,{destination:e.target.value}),children:Ty.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))})]}),(0,$.jsxs)(`label`,{children:[`Destination path`,(0,$.jsx)(`input`,{value:n.path.join(`.`),onChange:e=>r(i,{path:e.target.value.split(`.`)}),required:!0})]}),(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,onClick:()=>t(e.filter((e,t)=>t!==i)),children:`Remove mapping`})]},i)),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>t([...e,{source:`output`,sourcePath:[`text`],destination:`output`,path:[`answer`]}]),children:`Add field mapping`}),n.success?null:(0,$.jsx)(X,{error:n.error.issues[0]?.message})]})}function Dy({graders:e,selected:t,onChange:n,onOpenGrader:r}){return(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h3`,{children:`Graders and field mappings`}),(0,$.jsx)(`p`,{children:`Select up to 100 exact released graders. Map Dataset and retained output fields when their schemas differ.`}),Dc(e).map(({key:e,grader:i,aliases:a})=>{let o=e=>a.some(t=>t.id===e.id&&t.version===e.version&&t.contentHash===e.contentHash),s=t.find(o);return(0,$.jsxs)(`details`,{children:[(0,$.jsxs)(`summary`,{children:[(0,$.jsxs)(`label`,{className:`evaluation-model-badge`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:!!s,onChange:e=>n(e.target.checked?[...t,{id:i.id,version:i.version,contentHash:i.contentHash,mappings:[]}]:t.filter(e=>!o(e)))}),` `,i.name??`Grader name unavailable`,` · Version`,` `,i.release?.revision??i.version]}),i.release&&r?(0,$.jsx)(`button`,{type:`button`,className:`evaluation-model-badge`,onClick:e=>{e.preventDefault(),r(i.release.id)},children:`Open grader`}):null]}),(0,$.jsxs)(`p`,{children:[`Feedback key: `,(0,$.jsx)(`code`,{children:i.feedbackKey})]}),(0,$.jsx)(`p`,{children:i.release?`${i.release.id} · Revision ${i.release.revision}`:`Dataset-owned grader`}),(0,$.jsx)(`code`,{children:i.release?.contentHash??i.contentHash}),(0,$.jsxs)(`p`,{children:[`Package `,a.length>1?`aliases`:`grader`,`:`,` `,a.map(e=>`${e.id} (version ${e.version}, ${e.contentHash})`).join(`; `)]}),s?(0,$.jsx)(Ey,{value:s.mappings,onChange:e=>n(t.map(t=>o(t)?{...t,mappings:e}:t))}):null]},e)})]})}var Oy=e=>JSON.stringify([e.id,e.revision,e.contentHash]);function ky({api:e,value:t,onChange:n,disabled:r,localChoices:i=[],localLoading:a=!1}){let[o,s]=(0,Q.useState)(),c=S({queryKey:[`evaluation-workspace`,e.key,`released-dataset-picker`,o],queryFn:({signal:t})=>e.request(`catalogDatasets`,{limit:100,...o?{afterId:o}:{}},t)}),l=i.find(e=>t!==null&&Oy(e.taskset)===Oy(t)),u=S({queryKey:[`evaluation-workspace`,e.key,`resolveDataset`,t?.contentHash],enabled:!!t&&!l&&!a,queryFn:({signal:n})=>e.request(`resolveDataset`,{release:t},n)}),d=[...i.map(e=>({id:e.id,name:e.name,release:e.taskset,taskCount:e.taskCount})),...u.data?[u.data]:[],...c.data?.items??[]].filter((e,t,n)=>n.findIndex(t=>Oy(t.release)===Oy(e.release))===t);return(0,$.jsxs)(`section`,{children:[(0,$.jsxs)(`label`,{children:[`Dataset version`,(0,$.jsx)(Z,{label:`Dataset version`,floating:!0,searchable:!0,disabled:r,value:t?Oy(t):``,options:[{value:``,label:`Choose a published dataset`},...t&&!d.some(e=>Oy(e.release)===Oy(t))?[{value:Oy(t),label:`${t.id} / Revision ${t.revision}`,disabled:!0}]:[],...d.map(e=>({value:Oy(e.release),label:`${e.name} / Revision ${e.release.revision} / ${e.taskCount} tasks`}))],onChange:e=>n(d.find(t=>Oy(t.release)===e)?.release??null)})]}),c.error??u.error?(0,$.jsx)(X,{error:c.error??u.error}):null,o?(0,$.jsx)(`button`,{type:`button`,onClick:()=>s(void 0),children:`First dataset page`}):null,c.data?.nextCursor?(0,$.jsx)(`button`,{type:`button`,onClick:()=>s(c.data.nextCursor),children:`More dataset versions`}):null,t?(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact Dataset release`}),(0,$.jsxs)(`p`,{children:[t.id,` / Revision `,t.revision]}),(0,$.jsx)(`code`,{children:t.contentHash})]}):null]})}function Ay(e,t,n,r=!0){return S({queryKey:[`evaluation-workspace`,e.key,`setup-population`,t?.contentHash,n],enabled:!!t&&r,queryFn:async({signal:r})=>{let i=[],a,o=null;do{let s=n?await e.local(`sourceDataset`,{id:n,view:`ids`,limit:1e4,...a?{afterId:a}:{}},r):await e.request(`datasetPopulation`,{release:t,view:`ids`,limit:1e4,...a?{afterId:a}:{}},r);if(s.taskCount>1e4)throw Error(`Choose a Dataset version with at most 10,000 tasks for one Experiment.`);if(o&&(s.taskCount!==o.taskCount||JSON.stringify(s.graders)!==JSON.stringify(o.graders)))throw Error(`The released Dataset population changed between pages.`);if(o??=s,i.push(...s.items),s.nextCursor&&s.nextCursor===a)throw Error(`Dataset population cursor did not advance.`);a=s.nextCursor??void 0}while(a);if(!o||i.length!==o.taskCount)throw Error(`Dataset population is incomplete.`);return{...o,items:i}}})}function jy(e){let t=[...new Set(e.seedText.split(/[\s,]+/).filter(Boolean))];if(!t.length||t.some(e=>!/^(0|[1-9][0-9]*)$/.test(e)||Number(e)>2147483647))throw Error(`Enter integer environment seeds from 0 to 2147483647, separated by commas.`);let n=new Set(e.taskIds),r=e.existing,i=r?[...new Set(r.request.population.map(e=>e.seed))]:[];if(r?.request.policy.kind===`hosted_chat`&&r.request.taskset.id===e.release.id&&r.request.taskset.revision===e.release.revision&&r.request.taskset.contentHash===e.release.contentHash&&JSON.stringify(t)===JSON.stringify(i))return r.request.population.filter(e=>n.has(e.taskId));if(n.size*t.length>1e4)throw Error(`One Experiment can contain at most 10,000 task/seed members.`);return[...n].flatMap(n=>t.map(t=>({receiptId:e.createReceiptId(n,t),taskId:n,seed:t,fixtureId:null})))}function My(e,t){let{registerTransitionGuard:n}=kv(),r=(0,Q.useRef)(e);r.current=e,(0,Q.useEffect)(()=>t?n(e=>r.current.requestLeave(e)):void 0,[t,n])}function Ny({api:e,inventory:t,route:n,navigate:r,onSaved:i,dispatch:a,onClose:o,onSaveDraft:s}){let c=kv(),l=c.draft,{name:u,release:d,modelId:f,prompt:p,seed:m}=l,h=l.budget??NaN,g=l.outputTokens??NaN,_=c.existing,v=e.location===`local`&&l.mode===`model`?l.localRuntime:void 0,y=e=>c.setDraft(t=>t&&{...t,...e}),b=t?.projects.projects.find(t=>t.id===e.projectId),x=wy(e,t,l,_),C=l.mode===`model_harness_profile`,w=x.unavailable,[T,E]=(0,Q.useState)(null),[D,O]=(0,Q.useState)(null),[k,A]=(0,Q.useState)(null),[j,M]=(0,Q.useState)(!1),[N,P]=(0,Q.useState)(!1),F=(0,Q.useRef)(!1),I=(0,Q.useRef)(null),L=x.local.data?.profiles.find(e=>e.taskset.id===d?.id&&e.taskset.contentHash===d.contentHash),ee=e.location!==`local`||l.mode===`model`||x.local.isSuccess,R=Ay(e,d,L?.id,ee),z=R.data?Dc(R.data.graders):[],B=d?l.graderChoices[d.contentHash]??(_?.request.taskset.contentHash===d.contentHash?_.graders.map(e=>({id:e.id,version:e.version,contentHash:e.contentHash,mappings:e.mappings??[]})):z.length<=100?z.map(({grader:e})=>({id:e.id,version:e.version,contentHash:e.contentHash,mappings:[]})):[]):[],V=null,H=B;if(R.data)try{H=Oc(B.map(e=>{let t=R.data.graders.find(t=>t.id===e.id&&t.version===e.version&&t.contentHash===e.contentHash);if(!t)throw Error(`A selected grader is no longer in this exact Dataset release. Choose its released grader again.`);return{...t,mappings:e.mappings}})).map(({id:e,version:t,contentHash:n,mappings:r})=>({id:e,version:t,contentHash:n,mappings:r}))}catch(e){V=e instanceof Error?e.message:String(e)}let U=S({queryKey:[`evaluation-workspace`,e.key,`modelChoices`,d?.contentHash],enabled:!!d&&!L&&ee,queryFn:({signal:t})=>e.request(`modelChoices`,{taskset:d},t)}),te=S({queryKey:[`evaluation-workspace`,e.key,`samplingModels`],queryFn:({signal:t})=>e.request(`graderModels`,{},t)}),ne=d&&!L?U.data?.models:te.data?.models,re=te.data?.models.find(e=>e.id===f)?.supportsSampling===!0,W=S({queryKey:[`evaluation-workspace`,e.key,`resolveDataset`,d?.contentHash],enabled:!!d&&!L&&ee,queryFn:({signal:t})=>e.request(`resolveDataset`,{release:d},t)}),G=iy({name:`Experiment setup`,dirty:c.evaluationDirty||c.operationDraftDirty,busy:j,onLeave:c.close,retainForDestination(t){let n=po(new URL(t,window.location.origin));return!(!n||![`datasets`,`graders`,`experiments`].includes(n.page)||n.collection===`drafts`&&n.resourceId!==c.initialExperiment?.id||(n.projectId??null)!==e.projectId||(n.executionLocation??`hosted`)!==e.location)}});My(G,c.operationType===`evaluate`);function ae(){if(!d||!W.data&&!L)return;if(L){G.allowNextNavigation(),r({...n,page:`datasets`,resourceId:L.id,datasetKind:`release`,revision:d.revision,contentHash:d.contentHash,detailTab:`tasks`,executionId:null,passId:null,after:null,query:``});return}let e=c.reviewRoute;G.allowNextNavigation(),r(e?{...e,detailTab:`tasks`,after:null}:{...n,page:`datasets`,resourceId:W.data.id,datasetKind:`release`,revision:d.revision,contentHash:d.contentHash,detailTab:`tasks`,collection:`default`,executionId:null,passId:null,after:null,query:``})}let K=e.location===`local`?e.localOperation:e.operation;async function q(){if(F.current)throw Error(`Experiment setup is already preparing.`);F.current=!0,M(!0),E(null);try{if(c.startingModel?.source===`steering`)throw Error(`This evaluation owner cannot apply the saved steering profile. Choose another starting model or use neuron steering.`);if(c.startingModel?.source===`trained`)throw Error(`Evaluate this exact checkpoint through trained-version preparation. Its base model is not a substitute.`);if(!u.trim())throw Error(`Name this Experiment.`);if(ue)throw Error(ue);if(w)throw Error(w);if(V)throw Error(V);if(l.mode===`model_harness`&&p.trim())throw Error(`Released Harness instructions are immutable. Clear the additional system instructions before running this composition.`);if(!C&&((l.temperature??0)!==0||(l.topP??1)!==1)&&!re)throw Error(`This model does not support sampling overrides. Clear them in Advanced settings or choose a supported model.`);let t,n=b?{id:b.id,revision:b.revision,contentHash:ie(b.content),targetId:l.mode===`model`?null:x.selected?.id??null}:void 0;if(C){let r=x.profile,i=x.profileTarget,a=e.location===`local`?r:i;if(!a)throw Error(`Choose an authorized compatible Profile evaluation.`);let o=await K(`prepareHarness`,{target:a,modelId:f,budget:h}),s=e.location===`local`&&r?{operationId:o.id,profileRepositoryId:r.profileRef.repositoryId,definitionId:r.definitionId,profileRef:r.profileRef,profileSource:{sourceRevision:r.sourceRevision,harnessRelease:r.harnessRelease},modelId:f,maximumCostUsd:h}:{operationId:o.id,profileRepositoryId:i.profileRepositoryId,definitionId:i.source.definitionId,modelId:f,maximumCostUsd:h},l=e.location===`local`?await e.local(`prepareHarness`,s):await e.request(`prepareHarness`,s);if(!d||l.request.taskset.id!==d.id||l.request.taskset.contentHash!==d.contentHash)throw Error(`This Profile evaluation is bound to a different Dataset release. Choose its exact compatible Dataset.`);if(l.request.population.some(e=>!c.selected(d,e.taskId)))throw Error(`This Profile evaluation requires all of its declared tasks and seeds. Restore its full task selection before running.`);if(R.data?.items.some(e=>c.selected(d,e.id)&&!l.request.population.some(t=>t.taskId===e.id)))throw Error(`This Profile evaluation supports only its declared task set. Review tasks and select exactly that set.`);t={...l.request,name:u.trim(),...n?{project:n}:{}}}else{if(!R.data||!d)throw Error(`Select a published Dataset version.`);let r=R.data.items.filter(e=>c.selected(d,e.id));if(!r.length)throw Error(`Select at least one task in the Dataset Tasks table.`);let i=jy({existing:_,release:d,taskIds:r.map(e=>e.id),seedText:m,createReceiptId:(t,n)=>`evaluation-${ie([e.key,u,d.contentHash,f,p,t,n]).slice(0,32)}`});if(!H.length||H.length>100)throw Error(`Select between one and 100 Dataset graders.`);if(!v&&!ne?.some(e=>e.id===f))throw Error(U.data?.unavailableReason??`Choose a supported hosted model.`);t={schemaVersion:`openpond.modelTasksetRunRequest.v1`,operationId:(await K(`setup`,{name:u,release:d,modelId:f,prompt:p,seed:m,taskIds:r.map(e=>e.id)})).id,teamId:e.teamId,modelProjectId:null,name:u.trim(),...n?{project:n}:{},taskset:d,policy:{kind:`hosted_chat`,...v?{localRuntime:v}:{},modelId:f,maxOutputTokens:g,temperature:l.temperature??0,topP:l.topP??1,...x.harnessSource?{harness:x.harnessSource}:{},...p.trim()?{messages:[{role:`system`,content:p}]}:{}},population:i}}let r={request:t,maximumCostUsd:h,graders:H,..._?{sourceExperimentId:_.id}:{}},i=await K(`run`,r),a=Ts.parse({...r,operationId:i.id,request:{...t,operationId:i.id}});return I.current=i,a}catch(e){throw E(e instanceof Error?e.message:String(e)),e}finally{F.current=!1,M(!1)}}async function oe(){try{let e=ce,t=await q();O({key:e,configuration:t}),A(e)}catch{}}async function se(){if(!(F.current||D?.key!==ce)){F.current=!0,M(!0),E(null);try{let t=D.configuration,n=t.request,r=I.current;if(!r||r.id!==t.operationId)throw Error(`The reviewed operation changed. Review this setup again.`);let o=a?(await a(t,r.id)).id:e.location===`local`?Uc.parse(await e.local(`runFromRelease`,zc.parse({configuration:t,..._?.packageHash&&_.request.taskset.contentHash===n.taskset.contentHash?{expectedPackageHash:_.packageHash}:{}}))).id:(await e.request(`run`,t)).summary.id;await r.acknowledge(),G.allowNextNavigation(),c.close(),i({id:o})}catch(e){E(e instanceof Error?e.message:String(e))}finally{F.current=!1,M(!1)}}}let ce=JSON.stringify({draft:l,graders:H,project:e.projectId,location:e.location,population:R.data?.items.filter(e=>d&&c.selected(d,e.id)).map(e=>e.id)}),le=d&&R.data?R.data.items.filter(e=>c.selected(d,e.id)).length:0,ue=null;try{if(!u.trim())throw Error(`Name this Experiment before reviewing.`);if(!d||!R.data||R.isFetching||R.error)throw Error(`Choose an exact Dataset version and wait for its complete task population.`);if(!ee||w)throw Error(w??`Wait for the authorized source choices.`);if(!v&&!ne?.some(e=>e.id===f))throw Error(`Choose a model from the authorized current catalog.`);if(!Number.isFinite(h)||h<=0||h>1e4)throw Error(`Set a whole Experiment ceiling greater than zero and at most $10,000.`);if(V||!H.length||H.length>100)throw Error(V??`Select between one and 100 released graders.`);let e=R.data.items.filter(e=>c.selected(d,e.id)).map(e=>e.id);if(!e.length)throw Error(`Select at least one Dataset task.`);if(C){if(x.profile&&(e.length!==x.profile.taskIds.length||x.profile.taskIds.some(t=>!e.includes(t))))throw Error(`This released Profile check evaluates exactly its declared task and seed set. Restore that selection before reviewing.`)}else{if(!Number.isInteger(g)||g<1||g>4096)throw Error(`Set maximum output tokens between one and 4096.`);let t=l.temperature??0,n=l.topP??1;if(l.temperature===null||l.topP===null||!Number.isFinite(t)||t<0||t>2||!Number.isFinite(n)||n<=0||n>1)throw Error(`Use valid sampling settings in Advanced.`);if((t!==0||n!==1)&&!re)throw Error(`Clear unsupported sampling overrides in Advanced.`);if(l.mode===`model_harness`&&p.trim())throw Error(`Released Harness instructions are immutable. Clear additional instructions in Advanced.`);jy({existing:_,release:d,taskIds:e,seedText:m,createReceiptId:(e,t)=>`${e}:${t}`})}}catch(e){ue=e instanceof Error?e.message:String(e)}async function de(){if(s&&c.initialExperiment&&!F.current){F.current=!0,M(!0),P(!0),E(null);try{let t={...l,...d?{graderChoices:{...l.graderChoices,[d.contentHash]:B}}:{}};c.setDraft(e=>e===l?t:e),await s(Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:c.initialExperiment.id,operationType:`evaluate`,name:u.trim()||`Evaluation`,...c.startingModel?{startingModel:c.startingModel}:{},evaluationForm:{form:t,selection:c.selection,source:_,executionLocation:e.location}}))}catch(e){E(e instanceof Error?e.message:String(e))}finally{F.current=!1,M(!1),P(!1)}}}return(0,$.jsxs)(Bv,{label:`Experiment setup`,action:`experiment`,onRequestClose:()=>void G.requestLeave(()=>{c.close(),o?.()}),children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`h2`,{children:_?`Run another Experiment`:`Run Experiment`}),o?(0,$.jsx)(`button`,{type:`button`,disabled:j,onClick:()=>void G.requestLeave(()=>{c.close(),o()}),children:`Close setup`}):null]}),(0,$.jsxs)(`form`,{noValidate:!0,onSubmit:e=>{e.preventDefault(),ue?E(ue):k===ce?se():oe()},children:[(0,$.jsxs)(ft,{title:`Model and budget`,children:[(0,$.jsxs)(`label`,{children:[`Model`,(0,$.jsx)(Z,{label:`Model`,value:f,disabled:!!v,searchable:!0,floating:!0,options:[{value:``,label:`Choose model`},...f&&!ne?.some(e=>e.id===f)?[{value:f,label:fe(te.data?.models.find(e=>e.id===f)?.name??f),disabled:!0}]:[],...(ne??[]).map(e=>({value:e.id,label:fe(e.name)}))],onChange:e=>y({modelId:e,localRuntime:void 0})})]}),!v&&L&&te.isSuccess&&!te.data.models.length?(0,$.jsx)(`p`,{role:`status`,children:`No models are available for this account. Choose a configured local provider below.`}):!v&&!L&&U.isSuccess&&(!U.data.available||!U.data.models.length)?(0,$.jsx)(`p`,{role:`status`,children:U.data.unavailableReason??`No models are available for this Dataset and account.`}):null,(0,$.jsx)(xy,{disabled:j}),(0,$.jsxs)(`label`,{children:[`Whole execution budget ($)`,(0,$.jsx)(`input`,{type:`number`,min:`0.000001`,max:`10000`,step:`0.000001`,value:l.budget??``,onChange:e=>y({budget:e.target.value===``?null:e.target.valueAsNumber}),required:!0})]})]}),(0,$.jsxs)(ft,{title:`Dataset`,children:[(0,$.jsx)(ky,{api:e,value:d,onChange:c.changeRelease,disabled:!1,localChoices:x.local.data?.profiles.filter(t=>!e.projectId||b?.content.resources.some(e=>e.kind===`dataset`&&e.release?.id===t.taskset.id&&e.release.contentHash===t.taskset.contentHash)),localLoading:!ee}),(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:j,onClick:()=>{G.allowNextNavigation(),r({...n,page:`datasets`,resourceId:null,datasetKind:void 0,detailTab:`tasks`,revision:void 0,contentHash:void 0,executionId:null,passId:null,after:null,query:``})},children:`Add Dataset`}),R.data&&d?(0,$.jsxs)(`p`,{children:[c.count(d,R.data.taskCount),` of `,R.data.taskCount,` tasks selected`,c.selection?.mode!==`subset`&&!c.selection?.ids.length?` / All tasks in this release`:``,` `,(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:!W.data&&!L||j,onClick:ae,children:`Review tasks`})]}):null]}),R.data?(0,$.jsx)(ft,{title:`Evaluation`,children:(0,$.jsx)(Dy,{graders:R.data.graders,onOpenGrader:e=>{G.allowNextNavigation(),r({...n,page:`graders`,resourceId:e,datasetKind:void 0,revision:void 0,contentHash:void 0,detailTab:`overview`,executionId:null,passId:null,after:null})},selected:B,onChange:e=>{d&&y({graderChoices:{...l.graderChoices,[d.contentHash]:e}})}})}):null,(0,$.jsxs)(Sy,{draft:l,patch:y,supportsSampling:re,profileSeeds:x.profile?.seeds,children:[e.location===`local`&&l.mode===`model`?(0,$.jsx)(by,{api:e,policy:{kind:`hosted_chat`,modelId:f,maxOutputTokens:g,temperature:l.temperature??0,topP:l.topP??1,...v?{localRuntime:v}:{}},onChange:e=>{e.kind===`hosted_chat`&&y({modelId:e.modelId,outputTokens:e.maxOutputTokens,localRuntime:e.localRuntime})}}):null,e.location===`local`&&l.mode===`model`?(0,$.jsx)(cy,{api:e,policy:{kind:`hosted_chat`,modelId:f,maxOutputTokens:g,temperature:l.temperature??0,topP:l.topP??1,...v?{localRuntime:v}:{}},onChange:e=>{e.kind===`hosted_chat`&&y({modelId:e.modelId,outputTokens:e.maxOutputTokens,localRuntime:e.localRuntime,temperature:e.temperature,topP:e.topP})}}):null,e.actorId&&!a&&!v?(0,$.jsx)(vy,{connection:e.connection,teamId:e.teamId,actorId:e.actorId,projectId:e.projectId,configuration:D?.key===ce?D.configuration:null,retainOperation:e.operation,onBusyChange:M,onStarted:e=>{G.allowNextNavigation(),c.close(),r({...n,page:`experiments`,resourceId:e,detailTab:`overview`,executionLocation:`hosted`,executionKind:void 0,passId:null,after:null,query:``,revision:void 0,contentHash:void 0,datasetKind:void 0})}}):null,(0,$.jsx)(Cy,{api:e,draft:l,patch:y,sources:x}),(0,$.jsx)(ft,{title:`Experiment`,children:(0,$.jsxs)(`label`,{children:[`Name`,(0,$.jsx)(`input`,{value:u,onChange:e=>y({name:e.target.value}),required:!0})]})})]}),k===ce&&!ue?(0,$.jsxs)(ft,{title:`Reviewed configuration`,children:[(0,$.jsxs)(`p`,{children:[le,` selected tasks /`,` `,(L?te.data?.models:U.data?.models)?.find(e=>e.id===f)?.name??(f||`Choose model`),` `,`/ $`,h,` whole-run ceiling`]}),(0,$.jsxs)(`p`,{children:[`Graders:`,` `,H.map(e=>R.data?.graders.find(t=>t.id===e.id&&t.version===e.version&&t.contentHash===e.contentHash)?.name??`Grader name unavailable`).join(`, `)||`No graders selected`]}),(0,$.jsx)(`p`,{children:`Start creates a new immutable Experiment after server admission. The original remains unchanged.`})]}):null,(0,$.jsxs)(`p`,{children:[e.location===`local`?`Local execution on this Desktop. Dataset bytes and private grading remain in its server. `:``,`Review this Dataset version, selected tasks, target, graders, and whole Experiment budget before starting.`]}),V?(0,$.jsx)(X,{error:V}):null,T||R.error||U.error||te.error||W.error?(0,$.jsx)(X,{error:T??R.error?.message??U.error?.message??te.error?.message??W.error?.message}):null,(0,$.jsx)(ay,{api:e,configuration:D?.key===ce?D.configuration:null}),s?(0,$.jsx)(`button`,{className:`training-button secondary`,type:`button`,disabled:j,onClick:()=>void de(),children:N?`Saving draft…`:`Save draft`}):null,(0,$.jsx)(`button`,{className:`training-button`,type:`submit`,disabled:j,children:j&&!N?k===ce?`Starting Experiment…`:`Reviewing Experiment…`:k===ce?`Start experiment`:`Review experiment`})]}),G.dialog]})}var Py={maxSteps:`Maximum optimizer steps`,learningRate:`Learning rate`,klFactor:`KL preservation weight`,latentWeightDecay:`Latent weight decay`,clampNormFactor:`Target norm clamp factor`,maxSequenceLength:`Maximum sequence tokens`,maxDurationSeconds:`Maximum duration (seconds)`,maxForwardTokenWork:`Maximum forward token work`,maxCheckpointBytes:`Maximum checkpoint bytes`,seed:`Seed`};function Fy({form:e,onChange:t}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:`Edit factual associations in the exact managed backbone. Preservation examples define the covariance used to constrain the weight update.`}),(0,$.jsxs)(`label`,{children:[`Rewrite layers (comma separated)`,(0,$.jsx)(`input`,{value:e.config.layers,maxLength:200,onChange:n=>t({...e,config:{...e.config,layers:n.target.value}})})]}),(0,$.jsxs)(`label`,{children:[`Loss layer`,(0,$.jsx)(`input`,{inputMode:`numeric`,value:e.config.lossLayer,maxLength:100,onChange:n=>t({...e,config:{...e.config,lossLayer:n.target.value}})})]}),(0,$.jsxs)(`label`,{children:[`Context template groups (JSON)`,(0,$.jsx)(`textarea`,{rows:4,value:e.config.contextTemplateGroups,maxLength:65536,onChange:n=>t({...e,config:{...e.config,contextTemplateGroups:n.target.value}})})]}),(0,$.jsxs)(`p`,{children:[`Each template contains one `,`{}`,` placeholder. The first group contains only the clean prompt template.`]}),(0,$.jsxs)(`label`,{children:[`Nullspace threshold`,(0,$.jsx)(`input`,{inputMode:`decimal`,value:e.config.nullspaceThreshold,maxLength:100,onChange:n=>t({...e,config:{...e.config,nullspaceThreshold:n.target.value}})})]}),(0,$.jsxs)(`label`,{children:[`L2 regularization`,(0,$.jsx)(`input`,{inputMode:`decimal`,value:e.config.l2,maxLength:100,onChange:n=>t({...e,config:{...e.config,l2:n.target.value}})})]}),Object.keys(Py).map(n=>(0,$.jsxs)(`label`,{children:[Py[n],(0,$.jsx)(`input`,{inputMode:`decimal`,value:e.training[n],maxLength:100,onChange:r=>t({...e,training:{...e.training,[n]:r.target.value}})})]},n))]})}function Iy(e,t){let n=Fn((n,r)=>{let[i,a]=n.split(`?`),o=new URLSearchParams(a);return o.set(`teamId`,e.teamId),Y(e.connection,`${i.replace(`/v1/training/experiment-drafts`,`/v1/training/setup/drafts`)}?${o}`,{...r,signal:t})});function r(t){if(!e.actorId||t.ownerUserId!==e.actorId||t.teamId!==e.teamId||e.projectId&&t.projectId!==e.projectId)throw Error(`The saved experiment belongs to another account or Project.`);return t}return{async get(t){return r(await n.getExperimentDraft(e.teamId,t))},async list(t={}){let i=await n.listExperimentDrafts(e.teamId,{...t,...e.projectId?{projectId:e.projectId}:{},limit:30});if(!e.actorId||i.ownerUserId!==e.actorId)throw Error(`The saved experiment list belongs to another account.`);return i.items.forEach(r),i},async save(e){let t=await n.saveExperimentDraft(e);return r(t.record),t}}}function Ly(e){let t=ra(e.connection);return(0,Q.useMemo)(()=>na(new pt({baseUrl:`https://desktop.openpond.invalid`,apiKey:`desktop-server-boundary`,scope:e.teamId,fetch:async(t,n)=>{let r=new URL(String(t)).pathname.split(`/`).at(-1);if(r!==`read`&&r!==`commands`)throw Error(`Unsupported workspace learning action.`);let i=await e.request(`learningRelay`,{endpoint:r,request:JSON.parse(String(n?.body))},n?.signal??void 0);return new Response(JSON.stringify(i),{status:200,headers:{"Content-Type":`application/json`}})}}),[`learning`,`hosted-evaluation-workspace`,t,e.key]),[e,t])}function Ry(e,t,n,r=[]){let i=Ly(e),a=A({queryKey:[`training-experiment-inputs`,e.accountKey,e.actorId,e.connection.serverUrl,e.teamId,e.projectId],enabled:t,initialPageParam:void 0,getNextPageParam:e=>e.nextCursor??void 0,queryFn:async({signal:t,pageParam:n})=>{let r=new URLSearchParams({teamId:e.teamId});e.projectId&&r.set(`projectId`,e.projectId),n&&r.set(`cursor`,n);let i=or.parse(await Y(e.connection,`/v1/training/setup/draft-inputs?${r}`,{signal:t}));if(i.teamId!==e.teamId||i.actorId!==e.actorId||i.projectId!==e.projectId||n&&i.nextCursor===n)throw Error(`Training inputs returned a different account, Project or cursor.`);return i}}),o=a.data?.pages[0],s=a.data?.pages.flatMap(e=>e.batches)??[],c=us({queries:[...new Map([n,...r].filter(e=>e!=null).map(e=>[e.contentHash,e])).values()].filter(e=>!s.some(t=>Se(t.reference,e))).map(e=>({queryKey:[...ta(i),`experiment-selected-batch`,e],enabled:t,queryFn:async({signal:t})=>{let n=await i.get(`batch`,e.id,e.revision,{signal:t});if(Fe(n),!Se(xe(n),e))throw Error(`The selected reviewed batch differs from its saved release.`);return{reference:xe(n),rewardBinding:n.rewardBinding,purpose:n.purpose,exampleCount:n.examples.length,sealedAt:n.sealedAt}},retry:!1}))}),l=[...new Map([...s,...c.flatMap(e=>e.data?[e.data]:[])].map(e=>[e.reference.contentHash,e])).values()];return{...a,models:o?.models??[],methods:o?.methods??[],billingModes:o?.billingModes,batches:l,error:a.error??c.find(e=>e.error)?.error??null,isSuccess:a.isSuccess&&c.every(e=>e.isSuccess),isPending:a.isPending||c.some(e=>e.isPending),refetch:async()=>Promise.all([a.refetch(),...c.map(e=>e.refetch())])}}function zy(e,t){let n=ml.parse({teamId:e.teamId,actorId:e.actorId,apiOrigin:t}),r={...n,projectId:e.projectId},i=`/v1/training/alphaedit-executions`;return{account:n,async capability(t,a){return Ct(await Y(e.connection,`${i}/capability`,{method:`POST`,signal:a,body:JSON.stringify({...r,capabilityQuery:t})}),t,n.actorId)},async compile(t){return Or(await Y(e.connection,`${i}/compile`,{method:`POST`,body:JSON.stringify({...r,command:t})}),t)},async mutate(t,a){let o=`action`in t?`${i}/${encodeURIComponent(t.id)}/${t.action}`:`${i}/prepare`,s=await jt(await Y(e.connection,o,{method:`POST`,body:JSON.stringify({...r,intentHash:a,command:t})}),t);if(s.execution.ownerUserId!==n.actorId||s.execution.projectId!==e.projectId)throw Error(`The execution receipt belongs to another account or Project.`);return s},async get(t,r){let a=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}}),o=await yt(await Y(e.connection,`${i}/${encodeURIComponent(t)}?${a}`,{signal:r}),{teamId:e.teamId,id:t,ownerUserId:n.actorId});if(e.projectId!==null&&o.projectId!==e.projectId)throw Error(`The execution belongs to another Project.`);return o},async list(t={},r){let a={...t,...e.projectId?{projectId:e.projectId}:{}},o=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}});for(let[e,t]of Object.entries(a))t!==void 0&&o.set(e,String(t));return sn(await Y(e.connection,`${i}?${o}`,{signal:r}),{teamId:e.teamId,ownerUserId:n.actorId,query:a})}}}function By(e,t=!0){return S({queryKey:[`alphaedit-experiment-account`,e.key,e.actorId],enabled:t&&e.location===`hosted`&&!!e.actorId,retry:!1,queryFn:async({signal:t})=>{let n=await e.request(`inventory`,{},t);if(n.teamId!==e.teamId)throw Error(`The workspace account changed.`);return zy(e,n.apiOrigin)}})}var Vy=[`training:prepare-alphaedit`,`training:start-alphaedit`,`training:cancel-alphaedit`];function Hy(e,t){let n=u(),r=J([e.key,e.accountKey,e.actorId,e.teamId,e.projectId,e.connection.serverUrl,t.draftId,t.executionId,t.method]),i=(0,Q.useRef)(r);i.current=r,(0,Q.useEffect)(()=>(i.current=r,()=>{i.current=``}),[r]);let a=()=>({identity:r,busy:!1,error:null,receipt:null,selected:null,original:null,preparationOperationId:null}),[o,s]=(0,Q.useState)(a),c=(0,Q.useRef)(new Set),l=o.identity===r?o:a();function d(e){i.current===r&&s(t=>({...t.identity===r?t:a(),...e}))}function f(){if(i.current!==r)throw Error(`Return to this experiment's original account before continuing.`)}let p=By(e,t.visible),m=p.data,h=S({queryKey:[`alphaedit-experiment-recovery`,r],enabled:t.visible&&e.location===`hosted`&&!!e.actorId&&!l.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[];for(let i of Vy){let a,o=new Set;for(let s=0;;s++){if(s>=100)throw Error(`The retained execution catalog exceeds its supported bound.`);let c=await e.pendingOperations(i,a,n);for(let n of c.items){let a=i===Vy[0]?Ll.parse(n.reviewedIntent):Rl.parse(n.reviewedIntent);if(a.account.actorId!==e.actorId||a.account.teamId!==e.teamId)throw Error(`The retained execution belongs to another account.`);if(!(t.draftId===null?`execution`in a&&a.execution.id===t.executionId:a.draftId===t.draftId))continue;let o=i===Vy[0]?Cr.parse(n.command??{...a.request,operationId:n.id}):Wt(n.command??{...a.request,operationId:n.id});r.push({intent:a,command:o,operation:e.recoverOperation(n)})}if(!c.nextCursor)break;if(o.has(c.nextCursor))throw Error(`The retained execution catalog repeated a cursor.`);o.add(c.nextCursor),a=c.nextCursor}}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),g=l.original??h.data?.[0]??null,_=t.executionId??l.selected??l.receipt?.execution.id??(g&&`execution`in g.intent?g.intent.execution.id:null),v=S({queryKey:[`managed-alphaedit-execution`,r,_],enabled:t.visible&&!!(m&&_),retry:!1,queryFn:({signal:e})=>{if(!m||!_)throw Error(`Select an execution first.`);return m.get(_,e)},refetchInterval:e=>e.state.error?!1:e.state.data&&![`completed`,`failed`,`cancelled`].includes(e.state.data.phase)?3e3:!1});async function y(t){let r=zy(e,t.intent.account.apiOrigin);if(J(r.account)!==J(t.intent.account))throw Error(`Return to this execution's original account before retrying.`);d({original:t}),await t.operation.retainCommand(t.command,`dispatching`),f();let i=await r.mutate(t.command,t.operation.intentHash);return f(),d({receipt:i,selected:i.execution.id,preparationOperationId:`action`in t.command?`preparationOperationId`in t.intent?t.intent.preparationOperationId:null:t.command.operationId}),await t.operation.acknowledge(),f(),d({original:null}),await h.refetch(),f(),n.invalidateQueries({queryKey:[`managed-alphaedit-execution`]}),n.invalidateQueries({queryKey:[`unified-experiments`]}),i}async function b(e){if(!c.current.has(r)){c.current.add(r),d({busy:!0,error:null});try{return f(),await e()}catch(e){return i.current===r&&d({error:e}),null}finally{c.current.delete(r),d({busy:!1})}}}async function x(n,r){return b(async()=>{if(g)return y(g);if(!m||!h.isSuccess||!t.draftId||n.id!==t.draftId||!n.alphaEditForm||!t.method)throw Error(`Load this saved experiment and original requests before preparing.`);let i=vt(n.alphaEditForm.maximumSpendUsd);await r(n),f();let a=await Iy(e).get(n.id);if(f(),a.status!==`draft`||a.projectId!==e.projectId||J(a.draft)!==J(n))throw Error(`The saved experiment changed. Reopen its exact current revision before preparing.`);let o=n.alphaEditForm.baseModel;if(!o||o.source!==`managed`||n.startingModel&&![`managed`,`alphaedit`].includes(n.startingModel.source))throw Error(`Choose a qualified exact AlphaEdit starting model.`);let s={teamId:e.teamId,modelId:o.modelId,source:o.source,...o.revision?{revision:o.revision}:{},...o.tokenizerRevision?{tokenizerRevision:o.tokenizerRevision}:{},...o.chatTemplateHash?{chatTemplateHash:o.chatTemplateHash}:{},...o.modelAssetId?{modelAssetId:o.modelAssetId}:{}},c={teamId:e.teamId,projectId:e.projectId,method:t.method,query:s,form:n.alphaEditForm},l=await m.compile(c);if(f(),l.actorId!==e.actorId||l.formHash!==await zr(n.alphaEditForm))throw Error(`The compilation differs from this exact saved form.`);let u=await an({teamId:e.teamId,projectId:e.projectId,operationId:crypto.randomUUID(),name:n.name,method:t.method,query:s,request:l.request,sourceForm:n.alphaEditForm,maximumSpendUsd:i}),{operationId:d,...p}=u,_=Ll.parse({account:m.account,draftId:n.id,request:p}),v=await e.operation(Vy[0],_);return f(),y({intent:_,operation:v,command:{...u,operationId:v.id}})})}async function C(n,r){return b(async()=>{if(g)return y(g);let i=r??v.data;if(!m||!h.isSuccess||!i||v.error)throw Error(`Read the exact execution before reviewing its next action.`);let{schemaVersion:a,request:o,sourceForm:s,result:c,resultRecordedAt:u,contentHash:d,...p}=i,_=hn.parse(p),b=n===`start`?{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n,approvedMaximumSpendUsd:i.plan.maximumSpendUsd,...i.plan.computePrice?{approvedPriceHash:await zr(i.plan.computePrice)}:{}}:{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n},x=Rl.parse({account:m.account,draftId:l.preparationOperationId?t.draftId:null,preparationOperationId:l.preparationOperationId,execution:_,request:b}),S=await e.operation(n===`start`?Vy[1]:Vy[2],x);return f(),y({intent:x,operation:S,command:Wt({...b,operationId:S.id})})})}return{prepare:x,control:C,retry:()=>b(()=>{if(!g)throw Error(`Reload the original execution request.`);return y(g)}),busy:l.busy,receipt:l.receipt,original:g,execution:v.data,ready:p.isSuccess&&h.isSuccess,recoveryReady:!!g||h.isSuccess,canControl:v.isSuccess&&!v.error,error:l.error??p.error??h.error??v.error,refresh:()=>{p.refetch(),e.actorId&&h.refetch(),m&&_&&v.refetch()},loading:v.isFetching||p.isFetching,selectedId:_}}function Uy(e){return e==null?`Use available credits`:`$${e} USD`}function Wy({price:e}){return e?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Usage rate`}),(0,$.jsxs)(`dd`,{children:[`$`,Number(e.appliedPrice.hourlyUsd).toLocaleString(void 0,{maximumFractionDigits:6}),`/hour`]}),(0,$.jsx)(`dt`,{children:`Billing`}),(0,$.jsx)(`dd`,{children:`Startup, model work and cleanup. Queue time and warm idle after completion are not billed.`})]}):null}function Gy(e){return e?`Start approves this request and usage rate. Credits are checked when compute is allocated. Work stops when credits or your spending limit run out. Saving and reviewing do not start compute.`:`Start this exact prepared request using workspace credits and capacity. The approved maximum includes the bounded execution; preparation does not reserve a worker.`}function Ky(e){return e===null?`Start using credits`:`Start with $${e} cap`}var qy=`training-alphaedit-result-save`;function Jy(e,t,n){let r=u(),i=J([e.key,ra(e.connection),t]),a=(0,Q.useRef)(i);a.current=i,(0,Q.useEffect)(()=>(a.current=i,()=>{a.current=``}),[i]);let o=()=>({identity:i,busy:!1,error:null,original:null,receipt:null}),[s,c]=(0,Q.useState)(o),l=(0,Q.useRef)(new Set),d=s.identity===i?s:o();function f(e){a.current===i&&c(t=>({...t.identity===i?t:o(),...e}))}function p(){if(a.current!==i)throw Error(`Return to this Model save's original account and result.`)}let m=n?.method===`alphaedit`&&n.phase===`completed`&&n.result!==null,h=By(e,m),g=S({queryKey:[`alphaedit-model-save-recovery`,i],enabled:!!e.actorId&&!d.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[],i=new Set,a;for(let o=0;;o++){if(o>=100)throw Error(`The retained Model save catalog exceeds its supported bound.`);let s=await e.pendingOperations(qy,a,n);for(let n of s.items){let i=Hl.parse(n.reviewedIntent);if(i.request.executionId!==t)continue;if(i.account.actorId!==e.actorId||i.account.teamId!==e.teamId||i.execution.projectId!==e.projectId)throw Error(`The retained Model save belongs to another creator or Project.`);let a=ir.parse(n.command??{...i.request,operationId:n.id});r.push({intent:i,command:a,operation:e.recoverOperation(n)})}if(!s.nextCursor)break;if(i.has(s.nextCursor))throw Error(`The retained Model save catalog repeated a cursor.`);i.add(s.nextCursor),a=s.nextCursor}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),_=d.original??g.data?.[0]??null,v=S({queryKey:[`alphaedit-model-save-options`,i,h.data?.account.apiOrigin,n?.result?.contentHash],enabled:m&&h.isSuccess&&g.isSuccess&&!_&&!d.busy,retry:!1,queryFn:async({signal:n})=>{if(!h.data)throw Error(`Read the configured result account first.`);let r=h.data.account,i=new URLSearchParams({...r,...e.projectId?{projectId:e.projectId}:{}}),a=Ul.parse(await Y(e.connection,`/v1/training/alphaedit-executions/${encodeURIComponent(t)}/model?${i}`,{signal:n}));if(J(a.account)!==J(r)||a.executionId!==t||a.projectId!==e.projectId)throw Error(`The Model targets differ from this exact result account or Project.`);return a}});async function y(n){f({original:n}),await n.operation.retainCommand(n.command,`dispatching`),p();let i=await Y(e.connection,`/v1/training/alphaedit-executions/${encodeURIComponent(n.command.executionId)}/model`,{method:`POST`,body:JSON.stringify({...n.intent.account,projectId:n.intent.execution.projectId,intentHash:n.operation.intentHash,command:n.command})}),a=await Hn(i,n.command);if(p(),a.actorId!==e.actorId||a.version.source.executionId!==t)throw Error(`The saved Model receipt belongs to another creator or Project.`);f({receipt:a});for(let e of[`saved-training-model`,`saved-model-serving`,`alphaedit-model-save-options`,`unified-experiments`,`model-projects`])r.invalidateQueries({queryKey:[e]});return await n.operation.acknowledge(),p(),f({original:null}),await g.refetch(),p(),a}async function b(r){if(l.current.has(i))return null;l.current.add(i),f({busy:!0,error:null});try{if(p(),_)return await y(_);if(!g.isSuccess)throw Error(`Reload the original Model saves before continuing.`);if(!m||!n?.result||!v.isSuccess||!h.isSuccess||!v.data)throw Error(`Read the completed AlphaEdit result and current Model targets before saving.`);let i=r.modelProjectId?v.data.models.find(e=>e.id===r.modelProjectId):null;if(r.modelProjectId&&!i)throw Error(`Refresh the Model targets before updating this Model.`);let{schemaVersion:a,request:o,sourceForm:s,result:c,resultRecordedAt:l,contentHash:u,...d}=n,f=Hl.parse({account:v.data.account,execution:hn.parse(d),request:{teamId:e.teamId,executionId:t,resultHash:n.result.contentHash,artifactHash:n.result.artifact.contentHash,name:r.name,modelProjectId:i?.id??null,expectedModelRevision:i?.revision??0}}),b=await e.operation(qy,f);return p(),await y({intent:f,operation:b,command:ir.parse({...f.request,operationId:b.id})})}catch(e){return a.current===i&&f({error:e}),null}finally{l.current.delete(i),f({busy:!1})}}return{save:b,busy:d.busy,receipt:d.receipt,original:_,options:v.data,freshReady:m&&g.isSuccess&&v.isSuccess&&h.isSuccess,recoveryReady:!!_||g.isSuccess,error:d.error??g.error??(m?v.error??h.error:null),refresh:()=>{g.refetch(),m&&!_&&(h.refetch(),h.data&&v.refetch())}}}function Yy({form:e,onChange:t}){let n=(n,r)=>t({...e,questions:e.questions.map((e,t)=>t===n?r:e)});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[`State (JSON)`,(0,$.jsx)(`textarea`,{rows:6,value:e.stateJson,maxLength:131072,onChange:n=>t({...e,stateJson:n.target.value})})]}),(0,$.jsx)(`p`,{children:`Provide unlabeled state and every allowed answer. Approved training targets stay outside scoring input and prompts.`}),e.questions.map((r,i)=>(0,$.jsxs)(`section`,{className:`evaluation-card`,children:[(0,$.jsxs)(`h3`,{children:[`Question `,i+1]}),(0,$.jsxs)(`label`,{children:[`Question ID`,(0,$.jsx)(`input`,{value:r.id,maxLength:80,onChange:e=>n(i,{...r,id:e.target.value})})]}),(0,$.jsxs)(`label`,{children:[`Question`,(0,$.jsx)(`textarea`,{value:r.description,maxLength:2e3,onChange:e=>n(i,{...r,description:e.target.value})})]}),(0,$.jsxs)(`label`,{children:[`Answer type`,(0,$.jsx)(Z,{floating:!0,label:`Question ${i+1} answer type`,value:r.type,options:[{value:`choice`,label:`Choice`},{value:`boolean`,label:`Boolean`},{value:`integer_levels`,label:`Integer levels`}],onChange:e=>{(e===`choice`||e===`boolean`||e===`integer_levels`)&&n(i,{...r,type:e,choices:e===`boolean`?[{value:`false`,description:`False`},{value:`true`,description:`True`}]:[{value:``,description:``},{value:``,description:``}]})}})]}),r.choices.map((e,t)=>(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsxs)(`label`,{children:[`Value`,(0,$.jsx)(`input`,{value:e.value,maxLength:256,disabled:r.type===`boolean`,inputMode:r.type===`integer_levels`?`numeric`:`text`,onChange:e=>n(i,{...r,choices:r.choices.map((n,r)=>r===t?{...n,value:e.target.value}:n)})})]}),(0,$.jsxs)(`label`,{children:[`Description`,(0,$.jsx)(`input`,{value:e.description,maxLength:2e3,onChange:e=>n(i,{...r,choices:r.choices.map((n,r)=>r===t?{...n,description:e.target.value}:n)})})]}),r.type===`boolean`?null:(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:r.choices.length<=2,onClick:()=>n(i,{...r,choices:r.choices.filter((e,n)=>n!==t)}),children:`Remove answer`})]},t)),r.type===`boolean`?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:r.choices.length>=26,onClick:()=>n(i,{...r,choices:[...r.choices,{value:``,description:``}]}),children:`Add answer`}),(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:e.questions.length<=1,onClick:()=>t({...e,questions:e.questions.filter((e,t)=>t!==i)}),children:`Remove question`})]},i)),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:e.questions.length>=8,onClick:()=>t({...e,questions:[...e.questions,{id:``,type:`choice`,description:``,choices:[{value:``,description:``},{value:``,description:``}]}]}),children:`Add question`}),Object.keys(e.limits).map(n=>(0,$.jsxs)(`label`,{children:[{maximumPromptTokens:`Maximum prompt tokens`,maximumForwardTokenWork:`Maximum forward token work`,maximumDurationSeconds:`Maximum duration (seconds)`}[n],(0,$.jsx)(`input`,{value:e.limits[n],inputMode:`numeric`,maxLength:100,onChange:r=>t({...e,limits:{...e.limits,[n]:r.target.value}})})]},n))]})}function Xy({form:e,onChange:t}){let n={learningRate:`Learning rate`,weightDecay:`Weight decay`,maxSteps:`Maximum optimizer steps`,gradientAccumulationSteps:`Gradient accumulation steps`,maximumPromptTokens:`Maximum prompt tokens`,seed:`Seed`,maxDurationSeconds:`Maximum duration (seconds)`,maxCheckpointBytes:`Maximum checkpoint bytes`};return(0,$.jsx)($.Fragment,{children:Object.keys(n).map(r=>(0,$.jsxs)(`label`,{children:[n[r],(0,$.jsx)(`input`,{value:e.training[r],inputMode:`decimal`,maxLength:100,onChange:n=>t({...e,training:{...e.training,[r]:n.target.value}})})]},r))})}function Zy({result:e}){return(0,$.jsxs)(ft,{title:e.schemaVersion===`openpond.decisionScoringResult.v1`?`Candidate probabilities`:`Decision training result`,children:[e.schemaVersion===`openpond.decisionScoringResult.v1`?e.distributions.map(e=>(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h3`,{children:e.questionId}),(0,$.jsxs)(`p`,{children:[`Prediction: `,String(e.prediction),e.expectedLevel===null?``:` · Expected level: ${e.expectedLevel.toFixed(4)}`,` · `,e.promptTokenCount,` prompt tokens`]}),(0,$.jsx)(`div`,{className:`evaluation-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Answer`}),(0,$.jsx)(`th`,{children:`Probability`}),(0,$.jsx)(`th`,{children:`Logit`}),(0,$.jsx)(`th`,{children:`Token ID`})]})}),(0,$.jsx)(`tbody`,{children:e.candidates.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:String(e.value)}),(0,$.jsxs)(`td`,{children:[(e.probability*100).toFixed(4),`%`]}),(0,$.jsx)(`td`,{children:e.logit.toFixed(6)}),(0,$.jsx)(`td`,{children:e.tokenId})]},e.code))})]})})]},e.questionId)):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dl`,{className:`evaluation-workspace-meta`,children:Object.entries({"Optimizer steps":e.optimizerSteps,"Examples processed":e.examplesProcessed,"Questions processed":e.questionRowsProcessed,"Target tokens":e.targetTokens,"Mean loss":e.meanLoss,"Final loss":e.finalLoss,"Trainable parameters":e.trainableParameterCount,"Frozen backbone before":e.frozenBackboneState.before,"Frozen backbone after":e.frozenBackboneState.after,"Adapter artifact":e.artifact.id,"Artifact hash":e.artifact.contentHash}).map(([e,t])=>(0,$.jsxs)(`div`,{style:{display:`contents`},children:[(0,$.jsx)(`dt`,{children:e}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:t})]},e))}),(0,$.jsx)(`div`,{className:`evaluation-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`File`}),(0,$.jsx)(`th`,{children:`Bytes`}),(0,$.jsx)(`th`,{children:`SHA-256`})]})}),(0,$.jsx)(`tbody`,{children:e.artifact.files.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.path}),(0,$.jsx)(`td`,{children:e.sizeBytes.toLocaleString()}),(0,$.jsx)(`td`,{className:`saved-model-version-reference`,children:e.sha256})]},e.path))})]})})]}),(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Duration`}),(0,$.jsxs)(`dd`,{children:[(e.durationMs/1e3).toLocaleString(),` seconds`]}),(0,$.jsx)(`dt`,{children:`Forward token work`}),(0,$.jsx)(`dd`,{children:e.forwardTokenWork.toLocaleString()}),(0,$.jsx)(`dt`,{children:`Result hash`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.contentHash})]})]})}function Qy(e=`train`){let t={baseModel:_n(),name:`Decision experiment`,maximumSpendUsd:``,parentArtifact:null};return e===`train`?{...t,mode:e,batch:null,training:{learningRate:`0.0001`,weightDecay:`0`,maxSteps:`16`,gradientAccumulationSteps:`1`,maximumPromptTokens:`2048`,seed:`0`,maxDurationSeconds:`3600`,maxCheckpointBytes:`268435456`}}:{...t,mode:e,stateJson:`{}`,questions:[$y()],limits:{maximumPromptTokens:`2048`,maximumForwardTokenWork:`16384`,maximumDurationSeconds:`120`}}}function $y(){return{id:``,type:`choice`,description:``,choices:[{value:``,description:``},{value:``,description:``}]}}function eb(e,t){let n=ml.parse({teamId:e.teamId,actorId:e.actorId,apiOrigin:t}),r={...n,projectId:e.projectId},i=`/v1/training/decision-executions`;return{account:n,async capability(t,a){return Bn(await Y(e.connection,`${i}/capability`,{method:`POST`,signal:a,body:JSON.stringify({...r,capabilityQuery:t})}),t,n.actorId)},async compile(t){return ln(await Y(e.connection,`${i}/compile`,{method:`POST`,body:JSON.stringify({...r,command:t})}),t,n.actorId)},async mutate(t,a){let o=`action`in t?`${i}/${encodeURIComponent(t.id)}/${t.action}`:`${i}/prepare`,s=await rr(await Y(e.connection,o,{method:`POST`,body:JSON.stringify({...r,intentHash:a,command:t})}),t);if(s.execution.ownerUserId!==n.actorId||s.execution.projectId!==e.projectId)throw Error(`The execution receipt belongs to another account or Project.`);return s},async get(t,r){let a=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}}),o=await At(await Y(e.connection,`${i}/${encodeURIComponent(t)}?${a}`,{signal:r}),{teamId:e.teamId,id:t,ownerUserId:n.actorId});if(e.projectId!==null&&o.projectId!==e.projectId)throw Error(`The execution belongs to another Project.`);return o},async list(t={},r){let a={...t,...e.projectId?{projectId:e.projectId}:{}},o=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}});for(let[e,t]of Object.entries(a))t!==void 0&&o.set(e,String(t));return Lt(await Y(e.connection,`${i}?${o}`,{signal:r}),{teamId:e.teamId,ownerUserId:n.actorId,query:a})}}}function tb(e,t=!0){return S({queryKey:[`decision-experiment-account`,e.key,e.actorId],enabled:t&&e.location===`hosted`&&!!e.actorId,retry:!1,queryFn:async({signal:t})=>{let n=await e.request(`inventory`,{},t);if(n.teamId!==e.teamId)throw Error(`The workspace account changed.`);return eb(e,n.apiOrigin)}})}var nb=`training-decision-score`;function rb(e,t){let n=J([e.key,e.actorId,e.connection.serverUrl,t]),r=(0,Q.useRef)(n),i=(0,Q.useRef)(new Set);r.current=n,(0,Q.useEffect)(()=>(r.current=n,()=>{r.current=``}),[n]);let a=u(),o=tb(e),[s,c]=(0,Q.useState)({identity:n,busy:!1,error:null,original:null,receipt:null}),l=s.identity===n?s:{identity:n,busy:!1,error:null,original:null,receipt:null};function d(e){r.current===n&&c(t=>({...t.identity===n?t:{identity:n,busy:!1,error:null,original:null,receipt:null},...e}))}function f(){if(r.current!==n)throw Error(`Return to the original account and exact Decision Model before continuing.`)}let p=S({queryKey:[`decision-score-recovery`,n],enabled:!!e.actorId&&!l.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[],i=new Set,a;for(let o=0;;o++){if(o>=100)throw Error(`The retained scoring catalog exceeds its supported bound.`);let s=await e.pendingOperations(nb,a,n);for(let n of s.items){let i=Il.parse(n.reviewedIntent);if(i.modelProjectId!==t)continue;if(i.account.teamId!==e.teamId||i.account.actorId!==e.actorId)throw Error(`The retained score belongs to another account.`);let a=n.command,o=In.parse(a?.request??{...i.request,requestId:n.id});if(a&&a.modelProjectId!==t||o.requestId!==n.id)throw Error(`The retained score differs from its original operation.`);r.push({intent:i,command:{modelProjectId:t,request:o},operation:e.recoverOperation(n)})}if(!s.nextCursor)break;if(i.has(s.nextCursor))throw Error(`The retained scoring catalog repeated a page.`);i.add(s.nextCursor),a=s.nextCursor}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))[0]??null}}),m=l.original??p.data??null;async function h(r){if(i.current.has(n))return null;i.current.add(n),d({busy:!0,error:null});try{f();let n=m;if(!n){if(!r||!o.data||!p.isSuccess)throw Error(`Load this Model's account and retained scoring operations first.`);let i=Il.parse({account:o.data.account,modelProjectId:t,request:r}),a=await e.operation(nb,i);f(),n={intent:i,operation:a,command:{modelProjectId:t,request:In.parse({...r,requestId:a.id})}}}d({original:n}),await n.operation.retainCommand(n.command,`dispatching`),f();let i=await Ht(await Y(e.connection,`/v1/training/saved-models/${encodeURIComponent(t)}/decisions`,{method:`POST`,body:JSON.stringify({...n.intent.account,projectId:e.projectId,intentHash:n.operation.intentHash,command:n.command.request})}),{modelProjectId:t,request:n.command.request,actorId:e.actorId});return f(),d({receipt:i}),await n.operation.acknowledge(),f(),d({original:null}),await p.refetch(),a.invalidateQueries({queryKey:[`saved-model-serving`]}),i}catch(e){return d({error:e}),null}finally{i.current.delete(n),d({busy:!1})}}return{run:h,original:m,receipt:l.receipt,busy:l.busy,error:l.error??p.error??o.error,ready:!!m||p.isSuccess&&o.isSuccess,refresh:()=>{p.refetch(),o.refetch()}}}function ib({api:e,version:t,active:n}){let r=rb(e,t.modelProjectId),[i,a]=(0,Q.useState)(()=>Qy(`score`)),o=(0,Q.useRef)(J(i)),s=iy({name:`Decision scoring input`,dirty:J(i)!==o.current,busy:r.busy}),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(null);return(0,$.jsxs)(`section`,{className:`training-detail-section`,"aria-label":`Score exact Decision Model`,children:[(0,$.jsx)(`h3`,{children:`Score this version`}),s.dialog,(0,$.jsx)(X,{error:u??r.error}),r.original?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{className:`saved-model-version-reference`,children:[`Original scoring request retained for saved version`,` `,r.original.command.request.versionHash,`.`]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Original scoring input and limits`}),(0,$.jsx)(`pre`,{children:JSON.stringify({input:r.original.command.request.input,limits:r.original.command.request.limits},null,2)})]})]}):null,(0,$.jsx)(`fieldset`,{disabled:r.busy||!!r.original,children:(0,$.jsx)(Yy,{form:i,onChange:a})}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{className:`training-button secondary`,onClick:r.refresh,disabled:r.busy,children:`Refresh scoring recovery`}),(0,$.jsx)(`button`,{className:`training-button`,disabled:r.busy||!r.ready||!r.original&&!n,onClick:()=>{if(r.original)r.run();else try{St(i),d(null),l(!0)}catch(e){d(e)}},children:r.original?`Retry original score`:`Review score`})]}),r.receipt?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{className:`saved-model-version-reference`,children:[`Recorded scores for saved version `,r.receipt.version.contentHash,`.`]}),(0,$.jsx)(Zy,{result:r.receipt.result})]}):null,c?(0,$.jsxs)(qa,{ariaLabel:`Score exact Decision Model`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:r.busy,onClose:()=>{r.busy||l(!1)},children:[(0,$.jsx)(`h2`,{children:`Score exact Decision Model`}),(0,$.jsx)(`p`,{children:`Score every allowed candidate using this saved adapter and the reviewed bounded limits.`}),(0,$.jsx)(`p`,{className:`saved-model-version-reference`,children:t.contentHash}),(0,$.jsx)(`pre`,{children:JSON.stringify(St(i),null,2)}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{disabled:r.busy,className:`training-button secondary`,onClick:()=>l(!1),children:`Close`}),(0,$.jsx)(`button`,{disabled:r.busy||!r.ready,className:`training-button`,onClick:()=>{r.run({schemaVersion:`openpond.decisionModelScoreRequest.v1`,teamId:e.teamId,versionHash:t.contentHash,...St(i)}).then(e=>{e&&(o.current=J(i),l(!1))})},children:`Score`})]})]}):null]})}var ab=`training-model-serving-control`,ob=ne([Yn,cn,Qn,En,er,nr]),sb=ne([ur,rn,vn,fr,bn,It]);async function cb(e,t,n){let r=t.request;return r.schemaVersion===`openpond.alphaEditModelServingControlRequest.v1`?Gt(e,{modelProjectId:t.modelProjectId,request:r,actorId:n}):r.schemaVersion===`openpond.neuronTrainingModelServingControlRequest.v1`?Mn(e,{modelProjectId:t.modelProjectId,request:r,actorId:n}):r.schemaVersion===`openpond.decisionModelServingControlRequest.v1`?Ut(e,{modelProjectId:t.modelProjectId,request:r,actorId:n}):r.schemaVersion===`openpond.engramModelServingControlRequest.v1`?Nt(e,{modelProjectId:t.modelProjectId,request:r,actorId:n}):r.schemaVersion===`openpond.steeringModelServingControlRequest.v1`?gn(e,{modelProjectId:t.modelProjectId,request:r,actorId:n}):bt(e,{modelProjectId:t.modelProjectId,request:r,actorId:n})}function lb(e,t,n,r,i,a,o){return n.schemaVersion===`openpond.alphaEditModelServing.v1`||n.schemaVersion===`openpond.neuronTrainingModelServing.v1`?ob.parse({schemaVersion:n.schemaVersion===`openpond.alphaEditModelServing.v1`?`openpond.alphaEditModelServingControlRequest.v1`:`openpond.neuronTrainingModelServingControlRequest.v1`,teamId:e.teamId,modelProjectId:t,expectedRevision:n.control?.revision??0,versionHash:n.version.contentHash,action:r,idleTimeoutSeconds:i}):n.schemaVersion===`openpond.decisionModelServing.v1`?ob.parse({schemaVersion:`openpond.decisionModelServingControlRequest.v1`,teamId:e.teamId,modelProjectId:t,expectedRevision:n.control?.revision??0,versionHash:n.version.contentHash,action:r,idleTimeoutSeconds:i}):n.schemaVersion===`openpond.engramModelServing.v1`?ob.parse({schemaVersion:`openpond.engramModelServingControlRequest.v1`,teamId:e.teamId,modelProjectId:t,expectedRevision:n.control?.revision??0,versionHash:n.version.contentHash,action:r,defaultEnabled:r===`stop`?n.control?.defaultEnabled:o,idleTimeoutSeconds:i}):n.schemaVersion===`openpond.steeringModelServing.v1`?ob.parse({schemaVersion:`openpond.steeringModelServingControlRequest.v1`,teamId:e.teamId,modelProjectId:t,expectedRevision:n.control?.revision??0,versionHash:n.version.contentHash,action:r,defaultPublication:r===`stop`?n.control?.defaultPublication:a,idleTimeoutSeconds:i}):ob.parse({schemaVersion:`openpond.trainingModelServingControlRequest.v1`,teamId:e.teamId,modelProjectId:t,expectedRevision:n.control?.revision??0,artifact:r===`stop`?n.control?.artifact:n.registry?.artifact,versionHash:r===`stop`?n.control?.versionHash:n.version.contentHash,action:r,idleTimeoutSeconds:i})}function ub(e,t){return!(e instanceof Ti)||e.status!==409||e.retryable!==!1||t.command.request.schemaVersion===`openpond.alphaEditModelServingControlRequest.v1`||t.command.request.schemaVersion===`openpond.neuronTrainingModelServingControlRequest.v1`||t.command.request.schemaVersion===`openpond.decisionModelServingControlRequest.v1`?!1:t.command.request.schemaVersion===`openpond.engramModelServingControlRequest.v1`?[`engram_serving_revision_conflict`,`engram_serving_runtime_unavailable`,`engram_serving_cleanup_pending`,`engram_serving_other_kind_active`,`engram_serving_version_changed`,`engram_serving_stop_required`,`engram_serving_stop_changed`].includes(e.code??``):(t.command.request.schemaVersion===`openpond.steeringModelServingControlRequest.v1`?[`steering_serving_revision_conflict`,`steering_serving_cleanup_pending`,`steering_serving_other_kind_active`,`steering_serving_version_changed`,`steering_serving_default_changed`,`steering_serving_runtime_unavailable`,`steering_serving_stop_required`,`steering_serving_stop_changed`]:[`model_serving_revision_conflict`,`model_serving_runtime_unavailable`,`model_serving_cleanup_pending`,`model_serving_version_changed`,`model_serving_candidate_not_qualified`,`model_serving_stop_changed`]).includes(e.code??``)}function db(e,t,n){let r=u(),i=JSON.stringify([e.key,ra(e.connection),t]),a=(0,Q.useRef)(i);a.current=i;let o=(0,Q.useRef)(!0),s=(0,Q.useRef)(new Set),c=()=>({scope:i,retained:null,busy:!1,error:null,receipt:null}),[l,d]=(0,Q.useState)(c),f=l.scope===i?l:c();(0,Q.useEffect)(()=>(o.current=!0,()=>{o.current=!1}),[]);let p=()=>o.current&&a.current===i;function m(e){p()&&d(t=>({...t.scope===i?t:c(),...e}))}let h=S({queryKey:[`model-serving-control-recovery`,i],retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r,i=[],a=new Set;for(let o=0;;o++){if(o>=100)throw Error(`The retained serving catalog exceeds its supported bound.`);let s=await e.pendingOperations(ab,r,n);for(let n of s.items){let r=ob.parse(n.reviewedIntent);if(r.modelProjectId!==t)continue;if(r.teamId!==e.teamId)throw Error(`The retained serving command belongs to another workspace.`);let{modelProjectId:a,...o}=r;i.push({command:sb.parse(n.command??{modelProjectId:a,request:{...o,operationId:n.id}}),operation:e.recoverOperation(n)})}if(!s.nextCursor)break;if(a.has(s.nextCursor))throw Error(`The retained serving catalog repeated a page.`);a.add(s.nextCursor),r=s.nextCursor}if(i.length>1)throw Error(`Resolve the original retained serving commands before reviewing another action.`);return i[0]??null}}),g=f.retained??h.data??null;async function _(a,o,c=null,l=!0){if(s.current.has(i)||!g&&!h.isSuccess)return null;s.current.add(i),m({busy:!0,error:null});let u=null;try{if(!e.actorId||!p())throw Error(`Choose an authenticated account before controlling serving.`);let i=g;if(!i){if(!n)throw Error(`Read the exact saved version before reviewing a fresh serving command.`);let r=lb(e,t,n,a,o,c,l),s=await e.operation(ab,r);if(!p())return null;let{modelProjectId:u,...d}=r;i={operation:s,command:sb.parse({modelProjectId:u,request:{...d,operationId:s.id}})}}if(m({retained:i}),await i.operation.retainCommand(i.command,`dispatching`),!p())return null;u=i;let s=await cb(await Y(e.connection,`/v1/training/saved-models/${encodeURIComponent(i.command.modelProjectId)}/serving?${new URLSearchParams({teamId:e.teamId,...i.command.request.schemaVersion===`openpond.alphaEditModelServingControlRequest.v1`||i.command.request.schemaVersion===`openpond.neuronTrainingModelServingControlRequest.v1`||i.command.request.schemaVersion===`openpond.decisionModelServingControlRequest.v1`?{intentHash:i.operation.intentHash,...e.projectId?{projectId:e.projectId}:{}}:{}})}`,{method:`POST`,body:JSON.stringify(i.command.request)}),i.command,e.actorId);if(!p())return null;m({receipt:s}),r.invalidateQueries({queryKey:[`saved-model-serving`]});try{await i.operation.acknowledge()}catch(e){return m({error:e}),null}return p()?(m({retained:null}),await h.refetch(),p()?s:null):null}catch(e){if(p()&&(m({error:e}),u&&ub(e,u)))try{await u.operation.acknowledge(),p()&&(m({retained:null}),await h.refetch(),r.invalidateQueries({queryKey:[`saved-model-serving`]}))}catch(e){m({error:e})}return null}finally{s.current.delete(i),m({busy:!1})}}return{run:_,busy:f.busy,receipt:f.receipt,retained:g,recoveryReady:!!g||h.isSuccess,refreshRecovery:h.refetch,error:f.error??h.error}}function fb({api:e,value:t,version:n,action:r,onClose:i}){let a=db(e,n.modelProjectId,t),[o,s]=(0,Q.useState)(t?.schemaVersion===`openpond.engramModelServing.v1`?t.defaultEnabled:t?.schemaVersion!==`openpond.steeringModelServing.v1`||t.defaultPublication!==null),c=a.retained?.command.request,l=c?.action??r,u=t&&(l===`activate`?(t.schemaVersion===`openpond.steeringModelServing.v1`||t.schemaVersion===`openpond.engramModelServing.v1`||t.schemaVersion===`openpond.decisionModelServing.v1`||t.schemaVersion===`openpond.alphaEditModelServing.v1`||t.schemaVersion===`openpond.neuronTrainingModelServing.v1`?t.availability.state===`qualified`&&!t.cleanup.some(e=>![`shared`,`released`].includes(e.capacityState)):t.registry?.qualified)&&t.control?.phase!==`stopping`:t.control?.desiredState===`active`&&t.control.versionHash===n.contentHash),d=iy({name:`Serving setup`,busy:a.busy,dirty:!!c||n.schemaVersion===`openpond.engramModelVersion.v1`&&o!==(t?.schemaVersion!==`openpond.engramModelServing.v1`||t.defaultEnabled)||n.schemaVersion===`openpond.steeringModelVersion.v1`&&o!==(t?.schemaVersion!==`openpond.steeringModelServing.v1`||t.defaultPublication!==null),discardDescription:c?`The original serving command stays in recovery so you can retry it after reopening this Model.`:void 0});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(qa,{ariaLabel:l===`activate`?`Activate Model`:`Stop Model`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:a.busy,onClose:()=>void d.requestLeave(i),children:[(0,$.jsx)(`h2`,{children:l===`activate`?`Activate Model`:`Stop Model`}),(0,$.jsx)(X,{error:a.error}),(0,$.jsx)(`p`,{children:l===`activate`?`Activate this exact saved version using workspace capacity and credits. This may allocate paid serving capacity.`:`Stop new requests to this Model. Outstanding requests finish before unused capacity can retire; shared capacity may remain in use.`}),(0,$.jsx)(`p`,{children:n.schemaVersion===`openpond.steeringModelVersion.v1`?n.publication.baseModel.modelId:n.schemaVersion===`openpond.engramModelVersion.v1`||n.schemaVersion===`openpond.decisionModelVersion.v1`||n.schemaVersion===`openpond.alphaEditModelVersion.v1`||n.schemaVersion===`openpond.neuronTrainingModelVersion.v1`?n.baseModel.modelId:n.request.baseModel.modelId}),(0,$.jsxs)(`p`,{className:`saved-model-version-reference`,children:[`Saved version `,c?.versionHash??n.contentHash]}),l===`activate`&&(c?c.schemaVersion===`openpond.steeringModelServingControlRequest.v1`||c.schemaVersion===`openpond.engramModelServingControlRequest.v1`:n.schemaVersion===`openpond.steeringModelVersion.v1`||n.schemaVersion===`openpond.engramModelVersion.v1`)?(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Default modification`}),(0,$.jsx)(Z,{label:`Default modification`,value:c?.schemaVersion===`openpond.engramModelServingControlRequest.v1`?c.defaultEnabled?`profile`:`off`:c?.schemaVersion===`openpond.steeringModelServingControlRequest.v1`?c.defaultPublication?`profile`:`off`:o?`profile`:`off`,options:[{value:`profile`,label:n.schemaVersion===`openpond.engramModelVersion.v1`?`Saved memory module`:`Saved profile`},{value:`off`,label:`Off`}],disabled:a.busy||!!c,onChange:e=>s(e===`profile`)})]}):null,l===`activate`?(0,$.jsxs)(`p`,{children:[`Idle timeout: `,(c?.idleTimeoutSeconds??300)/60,` minutes.`]}):null,c?(0,$.jsxs)(`p`,{children:[`Original `,c.action,` request retained.`]}):null,a.receipt?(0,$.jsx)(`p`,{role:`status`,children:`Request accepted. Retaining recovery until its acknowledgment completes.`}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:a.busy,onClick:()=>void d.requestLeave(i),children:`Close`}),a.recoveryReady?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void a.refreshRecovery(),children:`Reload retained commands`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:a.busy||!a.recoveryReady||!c&&!u,onClick:()=>void a.run(l,c?.idleTimeoutSeconds??(l===`stop`?t?.control?.idleTimeoutSeconds??300:300),n.schemaVersion===`openpond.steeringModelVersion.v1`&&o?{id:n.publication.id,revision:n.publication.revision,contentHash:n.publication.contentHash}:null,o).then(e=>{e&&(d.allowNextNavigation(),i())}),children:a.busy?`Applying…`:c?`Retry original ${c.action}`:l===`activate`?`Activate`:`Stop serving`})]})]}),d.dialog]})}var pb={unpublished:`Publication pending`,qualification_pending:`Qualification pending`,unavailable:`Unavailable`,inactive:`No active routing`,starting:`Starting`,active:`Active routing`,retiring:`Retiring capacity`},mb={qualified:`Qualified for this serving runtime.`,evaluation_pending:`Registry evaluation is pending.`,post_training_pending:`Required post-training checks are pending.`,evaluation_failed:`Registry evaluation did not pass.`,candidate_rejected:`This candidate was rejected.`,artifact_revoked:`This registry artifact was revoked.`,artifact_deleted:`This registry artifact was deleted.`,runtime_unavailable:`The published runtime does not match this saved base model.`};function hb({connection:e,version:t,api:n}){let{teamId:r,modelProjectId:i,contentHash:a}=t,[o,s]=(0,Q.useState)(null),c=S({queryKey:[`saved-model-serving`,ra(e),r,i,a],queryFn:async({signal:t})=>qn(await Y(e,`/v1/training/saved-models/${encodeURIComponent(i)}/serving?${new URLSearchParams({teamId:r,versionHash:a})}`,{signal:t}),{teamId:r,modelProjectId:i,versionHash:a}),staleTime:1e4,gcTime:3e5,retry:!1,refetchInterval:e=>{if(e.state.error)return!1;let t=e.state.data;return t?t.cleanup.some(e=>[`pending`,`retiring`].includes(e.capacityState))||[`starting`,`retiring`].includes(t.state)||t.control&&(t.control.desiredState===`stopped`||t.control.phase===`failed`)&&[`pending`,`retiring`].includes(t.control.capacityState)?5e3:t.cleanup.length?3e4:!1:!1},refetchIntervalInBackground:!1}),l=c.data,u=l&&!c.error&&(l.control?.desiredState===`active`?l.control.versionHash===a:l.schemaVersion===`openpond.steeringModelServing.v1`||l.schemaVersion===`openpond.engramModelServing.v1`||l.schemaVersion===`openpond.decisionModelServing.v1`||l.schemaVersion===`openpond.alphaEditModelServing.v1`||l.schemaVersion===`openpond.neuronTrainingModelServing.v1`?l.availability.state===`qualified`&&l.control?.phase!==`stopping`&&!l.cleanup.some(e=>![`shared`,`released`].includes(e.capacityState)):l.registry?.qualified&&l.control?.phase!==`stopping`);return(0,$.jsxs)(`section`,{"aria-label":`Serving state`,children:[(0,$.jsxs)(`div`,{className:`labs-project-trends-heading`,children:[(0,$.jsx)(`h3`,{children:`Serving`}),(0,$.jsx)(`button`,{className:`training-button secondary`,type:`button`,disabled:c.isFetching,onClick:()=>void c.refetch(),children:`Refresh serving state`})]}),(0,$.jsx)(X,{error:c.error}),c.isPending?(0,$.jsx)(`p`,{role:`status`,children:`Reading serving state…`}):null,n?(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{className:`training-button`,type:`button`,disabled:c.isFetching||!u,onClick:()=>s(l?.control?.desiredState===`active`?`stop`:`activate`),children:l?.control?.desiredState===`active`?`Stop serving`:l?.control?.phase===`stopping`?`Stopping…`:`Activate`}),(0,$.jsx)(`button`,{className:`training-button secondary`,type:`button`,onClick:()=>s(l?.control?.desiredState===`active`?`stop`:`activate`),children:`Review serving request`})]}):null,l?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`dl`,{className:`model-project-page-metrics`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Routing`}),(0,$.jsx)(`dd`,{children:(0,$.jsx)(ci,{label:pb[l.state],value:l.state})})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Active binding records`}),(0,$.jsx)(`dd`,{children:l.bindings.length})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Last verified inference`}),(0,$.jsx)(`dd`,{children:l.schemaVersion===`openpond.decisionModelServing.v1`?l.lastVerifiedScore?new Date(l.lastVerifiedScore.completedAt).toLocaleString():`No retained score`:l.lastVerifiedInference?new Date(l.lastVerifiedInference.completedAt).toLocaleString():`No retained evidence`})]}),l.control?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Serving request`}),(0,$.jsx)(`dd`,{children:l.control.phase})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Capacity`}),(0,$.jsx)(`dd`,{children:l.control.desiredState===`active`&&l.control.phase!==`failed`?`Managed by serving runtime`:{pending:`Cleanup pending`,shared:`Retained for current consumers`,retiring:`Retirement in progress`,released:`Retirement complete`}[l.control.capacityState]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Model ID`}),(0,$.jsx)(`dd`,{children:l.control.modelId})]})]}):null]}),l.schemaVersion===`openpond.trainingModelServing.v1`&&l.registry?(0,$.jsx)(`p`,{children:mb[l.registry.reason]}):l.schemaVersion===`openpond.steeringModelServing.v1`?(0,$.jsx)(`p`,{children:{qualified:`Qualified for this serving runtime.`,runtime_unavailable:`A compatible serving runtime has not been qualified.`,calibration_unavailable:`The original calibration is unavailable.`,profile_archived:`This saved profile is archived.`,model_mismatch:`The serving runtime differs from this exact model.`}[l.availability.reason]}):null,l.schemaVersion===`openpond.engramModelServing.v1`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:{qualified:`Qualified for this serving runtime.`,runtime_unavailable:`A compatible Engram serving runtime has not been qualified.`,module_unavailable:`The original trained memory module is unavailable.`,model_mismatch:`The serving runtime differs from this exact base model.`}[l.availability.reason]}),(0,$.jsxs)(`p`,{children:[`Default modification: `,l.defaultEnabled?`Saved memory module`:`Off`]})]}):null,l.schemaVersion===`openpond.steeringModelServing.v1`?(0,$.jsxs)(`p`,{children:[`Default modification: `,l.defaultPublication?`Saved profile`:`Off`]}):null,l.schemaVersion===`openpond.alphaEditModelServing.v1`||l.schemaVersion===`openpond.neuronTrainingModelServing.v1`||l.schemaVersion===`openpond.decisionModelServing.v1`?(0,$.jsxs)(`p`,{children:[`Qualification: `,l.availability.reason.replaceAll(`_`,` `)]}):null,l.control?.failureCode?(0,$.jsxs)(`p`,{children:[`Recorded serving outcome: `,(0,$.jsx)(`code`,{children:l.control.failureCode})]}):null,l.pools.length?(0,$.jsx)(`div`,{className:`training-table-wrap`,children:(0,$.jsxs)(`table`,{className:`training-data-table labs-managed-serving-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Provider`}),(0,$.jsx)(`th`,{children:`Pool state`}),(0,$.jsx)(`th`,{children:`Worker limit`}),(0,$.jsx)(`th`,{children:`Deployments`}),(0,$.jsx)(`th`,{children:`Active requests`}),(0,$.jsx)(`th`,{children:`Pending reconciliation`}),(0,$.jsx)(`th`,{children:`Retirement`})]})}),(0,$.jsx)(`tbody`,{children:l.pools.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.provider}),(0,$.jsx)(`td`,{children:e.state}),(0,$.jsx)(`td`,{children:e.workersMax}),(0,$.jsx)(`td`,{children:e.activeDeployments}),(0,$.jsx)(`td`,{children:e.activeRequests}),(0,$.jsx)(`td`,{children:e.unsettledRequests}),(0,$.jsx)(`td`,{children:e.retirementBlocked?`In use`:`No consumers recorded`})]},e.id))})]})}):null,l.cleanup.length?(0,$.jsx)(`div`,{className:`training-table-wrap`,children:(0,$.jsxs)(`table`,{className:`training-data-table labs-managed-serving-table`,children:[(0,$.jsx)(`caption`,{children:`Previous serving capacity`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Saved version`}),(0,$.jsx)(`th`,{children:`Request state`}),(0,$.jsx)(`th`,{children:`Capacity`})]})}),(0,$.jsx)(`tbody`,{children:l.cleanup.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.versionHash.slice(0,12)}),(0,$.jsx)(`td`,{children:e.phase}),(0,$.jsx)(`td`,{children:{pending:`Cleanup pending`,shared:`Retained for current consumers`,retiring:`Retirement in progress`,released:`Retirement complete`}[e.capacityState]})]},e.operationId))})]})}):null,(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Serving references`}),(0,$.jsx)(`pre`,{className:`saved-model-version-reference`,children:JSON.stringify({...l,version:l.schemaVersion===`openpond.trainingModelServing.v1`?{contentHash:l.version.contentHash,jobId:l.version.jobId,candidate:l.version.candidate}:l.schemaVersion===`openpond.engramModelServing.v1`||l.schemaVersion===`openpond.decisionModelServing.v1`||l.schemaVersion===`openpond.alphaEditModelServing.v1`||l.schemaVersion===`openpond.neuronTrainingModelServing.v1`?{contentHash:l.version.contentHash,source:l.version.source,artifact:{id:l.version.artifact.id,contentHash:l.version.artifact.contentHash}}:{contentHash:l.version.contentHash,publication:{id:l.version.publication.id,revision:l.version.publication.revision,contentHash:l.version.publication.contentHash}}},null,2)})]})]}):null,n&&t.schemaVersion===`openpond.decisionModelVersion.v1`?(0,$.jsx)(ib,{api:n,version:t,active:l?.schemaVersion===`openpond.decisionModelServing.v1`&&l.state===`active`},`${n.key}:${t.contentHash}`):null,n&&o?(0,$.jsx)(fb,{api:n,version:t,value:c.error?void 0:l,action:o,onClose:()=>s(null)},`${n.key}:${ra(n.connection)}:${i}:${a}`):null]})}function gb({api:e,id:t,execution:n,disabled:r=!1}){let i=Jy(e,t,n),a=kv(),[o,s]=(0,Q.useState)(null),c=`${e.key}:${t}`,l=(0,Q.useRef)(c);l.current=c,(0,Q.useEffect)(()=>(l.current=c,()=>{l.current=``}),[c]);async function u(){let t=i.receipt;if(!(!t||i.busy||i.original||r)){s(null);try{let n=Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:crypto.randomUUID(),operationType:`alphaedit`,name:`${t.model.name} AlphaEdit experiment`,startingModel:await Cn(t.version,{teamId:e.teamId,ownerUserId:e.actorId,label:`${t.model.name} / Saved AlphaEdit matrices`}),alphaEditForm:await Jn(yr(),t.version,{teamId:e.teamId,ownerUserId:e.actorId})});l.current===c&&await a.openDraft(n,as(`experiments`,null,{projectId:e.projectId,executionLocation:`hosted`}))}catch(e){l.current===c&&s(e)}}}let[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)((n?.name??`AlphaEdit Model`).slice(0,200)),[h,g]=(0,Q.useState)(``),_=i.original?.command,v=iy({name:`AlphaEdit Model save`,busy:i.busy,dirty:d&&(!!_||p!==(n?.name??`AlphaEdit Model`).slice(0,200)||!!h),discardDescription:_?`The original save remains recoverable from this execution after closing.`:void 0}),y=n?.method===`alphaedit`&&n.phase===`completed`&&n.result!==null,b=!i.recoveryReady&&i.error!==null;if(!y&&!_&&!i.receipt&&!b)return null;let x=i.receipt?.version;return(0,$.jsxs)(`section`,{className:`training-detail-section`,"aria-label":`Save AlphaEdit Model`,children:[(0,$.jsx)(X,{error:o??i.error}),i.recoveryReady?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Reload retained Model saves`}),i.receipt&&x?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[`Saved to `,i.receipt.model?.name,`. Exact version `,(0,$.jsx)(`code`,{children:x.contentHash}),`.`]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact saved version`}),(0,$.jsx)(`pre`,{className:`saved-model-version-reference`,children:JSON.stringify(x,null,2)})]}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void wo(as(`models`)),children:`Open Models`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:r||i.busy||!!_,onClick:()=>void u(),children:`New experiment from this saved version`})]}),(0,$.jsx)(hb,{connection:e.connection,version:x,api:e},`${e.key}:${x.contentHash}`)]}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:r||i.busy||!i.recoveryReady,onClick:()=>f(!0),children:_?`Recover Model save`:i.receipt?`Save model again`:`Save model`}),d?(0,$.jsxs)(qa,{ariaLabel:`Save AlphaEdit model`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:i.busy,onClose:()=>void v.requestLeave(()=>f(!1)),children:[(0,$.jsx)(`h2`,{children:`Save model`}),(0,$.jsx)(`p`,{children:`Save the exact learned modification from this completed result. Saving does not activate serving.`}),(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),i.save({name:p,modelProjectId:h||null}).then(e=>{e&&(v.allowNextNavigation(),f(!1))})},children:[(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Save destination`}),(0,$.jsx)(Z,{label:`Model destination`,value:_?.modelProjectId??(_?``:h),options:[{value:``,label:`Create new Model`},...(i.options?.models??[]).map(e=>({value:e.id,label:e.name,description:`Current revision ${e.revision}`})),..._?.modelProjectId&&!i.options?.models.some(e=>e.id===_.modelProjectId)?[{value:_.modelProjectId,label:`Original selected Model`}]:[]],disabled:i.busy||!!_||!i.freshReady,onChange:e=>{g(e);let t=i.options?.models.find(t=>t.id===e);t&&m(t.name)}})]}),(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Model name`}),(0,$.jsx)(`input`,{"data-autofocus":!0,value:_?.name??p,maxLength:200,disabled:i.busy||!!_,onChange:e=>m(e.target.value)})]}),_?(0,$.jsx)(`p`,{children:`Original result, module, destination and revision are retained. Retry sends the same operation.`}):null,i.receipt&&_?(0,$.jsx)(`p`,{role:`status`,children:`The Model was saved. Local acknowledgement is pending; retry preserves its exact receipt.`}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:()=>void v.requestLeave(()=>f(!1)),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Refresh targets and recovery`}),(0,$.jsx)(`button`,{type:`submit`,className:`training-button`,disabled:i.busy||r||!i.recoveryReady||!_&&!i.freshReady,children:i.busy?`Saving…`:_?`Retry original save`:`Save model`})]})]})]}):null,v.dialog]})}function _b({api:e,execution:t}){let n=k(e.connection,null),r=By(e),[i,a]=(0,Q.useState)(null),o=n.selection?.alphaEditResult?.id===t.id&&n.selection.alphaEditResult.result?.contentHash===t.result?.contentHash;async function s(){a(null);try{if(!r.data||t.phase!==`completed`||!t.result)throw Error(`Read the exact completed AlphaEdit result in its original account first.`);let i=fn.parse({kind:`alphaedit_result`,location:`cloud`,owner:{teamId:t.teamId,actorId:t.ownerUserId},apiOrigin:r.data.account.apiOrigin,projectId:t.projectId,executionId:t.id,inputHash:t.plan.inputHash,modelHash:t.result.modelHash,runtimeHash:t.plan.runtimeHash,resultHash:t.result.contentHash,artifact:t.result.artifact?{id:t.result.artifact.id,contentHash:t.result.artifact.contentHash}:null});await n.select({kind:`alphaedit_result`,id:t.id,location:`cloud`,teamId:e.teamId,apiOrigin:r.data.account.apiOrigin,result:i})}catch(e){a(e)}}return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{error:i??r.error}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:n.selecting||!r.isSuccess,onClick:()=>void s(),children:o?`Result selected for chat`:`Use result in chat`})]})}async function vb(e,t,n){return Rr(await Sb(e,`gpu-catalog`,t,n),t)}async function yb(e,t,n){return wr(await Sb(e,`estimate`,t,n),t)}async function bb(e,t,n){return xr(await Sb(e,`funding`,t,n),t,e.actorId??void 0)}async function xb(e,t){return Qt(await Sb(e,`funding-handoff`,t),t,e.actorId??void 0)}function Sb(e,t,n,r){return Y(e.connection,`/v1/training/setup/${t}?teamId=${encodeURIComponent(e.teamId)}`,{method:`POST`,body:JSON.stringify(n),signal:r})}function Cb(e){let{api:t,baseModel:n,selection:r,receipt:i}=e,[a,o]=(0,Q.useState)(0),s=e.recipe?.lora&&typeof e.recipe.lora==`object`&&`rank`in e.recipe.lora?e.recipe.lora.rank:void 0,c=Nr.safeParse({teamId:t.teamId,modelId:n?.modelId,modelRevision:n?.revision,tokenizerRevision:n?.tokenizerRevision,chatTemplateHash:n?.chatTemplateHash,method:e.method,loraRank:s,gpuCount:r.gpuCount??1}),l=c.success?c.data:null,u=S({queryKey:[`experiment-compute`,t.accountKey,t.actorId,t.connection.serverUrl,t.projectId,l],enabled:e.enabled&&l!==null&&i===null,queryFn:({signal:e})=>{if(!l)throw Error(`Choose a pinned model and valid LoRA rank before loading compute.`);return vb(t,l,e)},retry:!1,staleTime:0}),d=i?.state===`prepared`?{schemaVersion:`openpond.trainingEstimateRequest.v1`,teamId:t.teamId,source:{kind:`preparation`,id:i.plan.id,planHash:i.plan.contentHash,expectedRevision:i.revision},...i.plan.request.gpuSelection?{gpuSelection:i.plan.request.gpuSelection}:{}}:null,f=S({queryKey:[`experiment-estimate`,t.accountKey,t.actorId,t.connection.serverUrl,t.projectId,d],enabled:e.enabled&&d!==null,queryFn:({signal:e})=>{if(!d)throw Error(`Review the experiment before requesting an estimate.`);return yb(t,d,e)},retry:!1,staleTime:1/0,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),p=wb(u.data?.expiresAt),m=f.data?new Date(Math.min(Date.parse(f.data.expiresAt),f.data.pricing.quoteExpiresAt?Date.parse(f.data.pricing.quoteExpiresAt):1/0)).toISOString():void 0,h=wb(m);function g(){let e=f.data;if(!d||!e||f.isFetching||f.isError||f.dataUpdatedAt<=a||!m||Date.parse(m)<=Date.now())throw Error(`Refresh and review the current estimate before starting training.`);if(!e.gpu.resolved||![`available`,`limited`].includes(e.gpu.availability))throw Error(`Refresh compute availability before starting this experiment.`);return e.review}return{catalog:u,query:l,catalogExpired:p,estimate:f,estimateExpired:h,reviewedEstimate:g,requireFreshReview:()=>o(Date.now()),canStart:!!(d&&f.data?.gpu.resolved&&[`available`,`limited`].includes(f.data.gpu.availability)&&f.dataUpdatedAt>a&&!h&&!f.isFetching&&!f.isError)}}function wb(e){let[,t]=(0,Q.useState)(0);return(0,Q.useEffect)(()=>{if(!e)return;let n=Date.parse(e)-Date.now();if(n<=0)return;let r=setTimeout(()=>t(e=>e+1),Math.min(n+1,2147483647));return()=>clearTimeout(r)},[e]),!!(e&&Date.parse(e)<=Date.now())}function Tb(e,t,n,r=!1){let i=Number(t),a=!1;try{vt(t),a=!0}catch{}let o=!!(e.actorId&&(r?a:Number.isFinite(i)&&i>0&&i<=1e6)),s=S({queryKey:[`experiment-funding`,e.connection.serverUrl,e.accountKey,e.actorId,e.teamId,i],enabled:n&&o&&!r,queryFn:({signal:t})=>{if(!o)throw Error(`Enter a valid maximum spend before checking credits.`);return bb(e,{schemaVersion:`openpond.trainingFundingRequest.v1`,teamId:e.teamId,maximumSpendUsd:i},t)},retry:!1,staleTime:0}),c=wb(s.data?.expiresAt);function l(){if(r){if(!o)throw Error(`Choose a valid spending limit or use available credits.`)}else{if(!s.data||s.isFetching||s.isError||Date.parse(s.data.expiresAt)<=Date.now())throw Error(`Refresh credits before starting this experiment.`);if(s.data.state!==`covered`)throw Error(`This spending cap is not currently funded. Check credits and workspace limits before starting.`)}}async function u(){r||await s.refetch()}return{query:s,valid:o,expired:c,assertCovered:l,allocationAdmission:r,refresh:u,canStart:r?o:s.data?.state===`covered`&&!c&&!s.isFetching&&!s.isError}}var Eb=e=>new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,maximumFractionDigits:2}).format(Number(e));function Db({funding:e,busy:t,startAttempted:n,billingReturnPending:r,onOpenBilling:i,onRefresh:a}){let o=e.query.data;return e.allocationAdmission?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:`Credits are checked when compute is allocated. An optional spending limit caps total usage; it does not reserve that amount.`}),r?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:`Your experiment is saved. Return from Billing to review it before starting.`}),(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:t||n,onClick:()=>void a(),children:`Return from Billing`})]}):null,i?(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:t||n||!e.valid,onClick:()=>void i(),children:`Add credits`}):null]}):(0,$.jsxs)($.Fragment,{children:[e.query.isFetching?(0,$.jsx)(`p`,{role:`status`,children:`Checking credits…`}):null,o&&!e.query.isError?(0,$.jsxs)($.Fragment,{children:[o.availableUsageUsd===null?null:(0,$.jsxs)(`dl`,{className:`training-compute-summary`,children:[(0,$.jsx)(`dt`,{children:`Available usage`}),(0,$.jsx)(`dd`,{children:Eb(o.availableUsageUsd)})]}),(0,$.jsx)(`p`,{children:e.expired?`Refresh credits before starting.`:{covered:`Current credits cover this spending cap.`,insufficient_credit:`More credits are needed to cover this spending cap.`,member_limit:`This cap exceeds your workspace member spending limit.`,unavailable:`Workspace funding is unavailable for this cap.`}[o.state]}),!o.canPurchase&&o.state===`insufficient_credit`?(0,$.jsx)(`p`,{children:`A workspace billing owner can add credits.`}):null]}):null,r?(0,$.jsx)(`p`,{children:`Your experiment is saved. Finish in Billing, then return here to refresh credits and review the estimate.`}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:t||n||!e.valid||e.query.isFetching,onClick:()=>void a(),children:`Refresh credits`}),i&&o?.canPurchase?(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:t||n||!e.valid,onClick:()=>void i(),children:`Add credits`}):null,(0,$.jsx)(X,{error:e.query.error})]})}function Ob({owner:e,api:t,onOpenBilling:n=null,billingReturnPending:r=!1,onRefreshFunding:i,disabled:a=!1}){let o=e.busy||a,s=e.execution,c=e.original,l=(e.receipt&&(!s||e.receipt.execution.id===s.id&&e.receipt.execution.revision>s.revision)?e.receipt.execution:s)??(c&&`execution`in c.intent?c.intent.execution:null),[u,d]=(0,Q.useState)(null),f=Tb(t,l?.plan.maximumSpendUsd??``,!!l,!!l?.plan.computePrice),p=c?`action`in c.command?c.command.action:`prepare`:null;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{error:e.error}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o||e.loading,onClick:e.refresh,children:`Refresh execution and recovery`}),c?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||!e.recoveryReady,onClick:()=>void e.retry(),children:o?`Reconciling…`:`Retry original ${p}`}):null]}),c&&!(`action`in c.command)?(0,$.jsxs)(ft,{title:`Original preparation`,children:[(0,$.jsxs)(`p`,{children:[c.command.name,` · `,c.command.method,` · `,Uy(c.command.maximumSpendUsd)]}),(0,$.jsxs)(`p`,{children:[c.command.request.training.maxSteps,` training steps · batch`,` `,c.command.request.data.edits.batch.id,` ·`,` `,c.command.request.model.modelId,` · `,c.command.request.model.revision]})]}):null,l?(0,$.jsxs)(ft,{title:`Hosted execution`,children:[(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`State`}),(0,$.jsx)(`dd`,{children:l.phase}),(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(l.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:l.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Execution`}),(0,$.jsx)(`dd`,{children:l.id}),(0,$.jsx)(`dt`,{children:`Preparation expires`}),(0,$.jsx)(`dd`,{children:new Date(l.plan.expiresAt).toLocaleString()}),(0,$.jsx)(`dt`,{children:`Exact plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:l.plan.contentHash}),(0,$.jsx)(`dt`,{children:`Runtime`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:l.plan.runtimeHash})]}),s?(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[s.phase===`prepared`?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||e.loading||!e.ready||!e.canControl||!!c||Date.parse(s.plan.expiresAt)<=Date.now(),onClick:()=>d({action:`start`,value:s}),children:`Review Start`}):null,[`completed`,`cancelled`,`failed`].includes(s.phase)?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o||e.loading||!e.ready||!e.canControl||!!c,onClick:()=>d({action:`cancel`,value:s}),children:`Review Cancel`})]}):null]}):null,s?.phase===`completed`&&s.result?(0,$.jsx)(_b,{api:t,execution:s}):null,s?.result?(0,$.jsx)(t_,{result:s.result}):l?.phase===`completed`?(0,$.jsx)(`p`,{children:`No result bytes are available in this read. Retained execution identity remains available for recovery.`}):null,e.selectedId?(0,$.jsx)(gb,{api:t,id:e.selectedId,execution:s,disabled:o||!!c},`${t.key}:${e.selectedId}`):null,u&&s?(0,$.jsxs)(qa,{ariaLabel:u.action===`start`?`Start AlphaEdit experiment`:`Cancel AlphaEdit experiment`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:o,onClose:()=>{o||d(null)},children:[(0,$.jsx)(`h2`,{children:u.action===`start`?`Start AlphaEdit experiment`:`Cancel AlphaEdit experiment`}),(0,$.jsx)(`p`,{children:u.action===`start`?Gy(u.value.plan.computePrice):`Cancel this exact execution. In-flight work may need to stop and settle before capacity is released.`}),(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(u.value.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:u.value.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Training steps`}),(0,$.jsx)(`dd`,{children:u.value.request.training.maxSteps}),(0,$.jsx)(`dt`,{children:`Reviewed batch`}),(0,$.jsxs)(`dd`,{children:[u.value.request.data.edits.batch.id,` · release`,` `,u.value.request.data.edits.batch.revision]}),(0,$.jsx)(`dt`,{children:`Maximum duration`}),(0,$.jsxs)(`dd`,{children:[u.value.request.training.maxDurationSeconds,` seconds`]}),(0,$.jsx)(`dt`,{children:`Model`}),(0,$.jsxs)(`dd`,{children:[u.value.request.model.modelId,` · `,u.value.request.model.revision]}),(0,$.jsx)(`dt`,{children:`Plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:u.value.plan.contentHash})]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact prepared training request`}),(0,$.jsx)(`pre`,{children:JSON.stringify(u.value.request,null,2)})]}),u.action===`start`?(0,$.jsx)(Db,{funding:f,busy:o,startAttempted:!!c,billingReturnPending:r,onOpenBilling:n,onRefresh:i??(async()=>{await f.refresh()})}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o,onClick:()=>d(null),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||e.loading||!!c||!e.ready||!e.canControl||u.action===`start`&&(r||!f.canStart||Date.parse(u.value.plan.expiresAt)<=Date.now()),onClick:()=>void e.control(u.action,u.value).then(e=>{e&&d(null)}),children:o?`Applying…`:u.action===`start`?Ky(u.value.plan.maximumSpendUsd):`Cancel execution`})]})]}):null]})}var kb=(0,Q.lazy)(()=>o(()=>import(`./ExperimentTrainingDataWorkspace-WhwQ0QBi.js`),__vite__mapDeps([76,1,2,3,4,77,5,6,9,10,78,32,27,31,21,16,43,19,20,22,13,23,15,24,25,26,8,28,11,29,30,33,34,35,36,37,38,39,40,41,18,42,44,45,46,47,48,49,50,51,52,53,54,55,56,79,80])));function Ab({api:e,visible:t,onClose:n,onSaveDraft:r}){let i=kv(),[a,o]=(0,Q.useState)(()=>i.initialExperiment?.alphaEditForm??yr(i.trainingBaseModel)),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(`editsBatch`),[h,g]=(0,Q.useState)(!1),_=(0,Q.useRef)(null),v=(0,Q.useRef)(!1),y=(0,Q.useRef)(null),b=(0,Q.useRef)(!1),x=J([e.key,e.accountKey,e.actorId,e.teamId,e.projectId,e.connection.serverUrl,i.initialExperiment?.id]),C=(0,Q.useRef)(x);C.current=x,(0,Q.useEffect)(()=>(C.current=x,()=>{C.current=``}),[x]);function w(){if(C.current!==x)throw Error(`Return to this experiment's original account before continuing.`)}let T=Hy(e,{draftId:i.initialExperiment?.id??null,method:`alphaedit`,visible:t}),E=Ry(e,t,a.editsBatch,[a.preservationBatch]),D=By(e,t),O=i.trainingBaseModel,k=!i.startingModel||i.startingModel.source===`managed`||i.startingModel.source===`alphaedit`,A=wv(i.startingModel),j=(0,Q.useRef)(A);(0,Q.useEffect)(()=>{j.current!==A&&i.startingModel?.source!==`alphaedit`&&o(({startingModule:e,...t})=>({...t,parentArtifact:null})),j.current=A},[A,i.startingModel?.source]);let M=O?.source===`managed`&&k?{teamId:e.teamId,source:O.source,modelId:O.modelId,...O.revision?{revision:O.revision}:{},...O.tokenizerRevision?{tokenizerRevision:O.tokenizerRevision}:{},...O.chatTemplateHash?{chatTemplateHash:O.chatTemplateHash}:{},...O.modelAssetId?{modelAssetId:O.modelAssetId}:{}}:null,N=S({queryKey:[`alphaedit-execution-capability`,x,M],enabled:t&&!!(D.data&&M),retry:!1,staleTime:3e4,queryFn:({signal:e})=>{if(!D.data||!M)throw Error(`Choose an exact managed base before checking AlphaEdit availability.`);return D.data.capability(M,e)},refetchInterval:e=>!e.state.error&&6e4}),P=N.data&&!N.isError&&Date.parse(N.data.expiresAt)>Date.now()?N.data.execution:null,F=T.selectedId&&![`completed`,`failed`,`cancelled`].includes(T.execution?.phase??T.receipt?.execution.phase??`prepared`),I=s||T.busy,L=I||!!(T.original||F),ee=J({...a,baseModel:O,sourceKey:A}),R=(0,Q.useRef)(ee);R.current=ee;let z=(0,Q.useRef)(ee),B=Tb(e,a.maximumSpendUsd,t,!0),V=ee!==z.current,H=i.reportOperationDraftDirty;(0,Q.useEffect)(()=>{H(`alphaedit`,V)},[V,H]);let U=iy({name:`AlphaEdit experiment`,dirty:V||i.operationDraftDirty||i.evaluationDirty,busy:I,onLeave:n});My({...U,requestLeave:async e=>{d&&y.current?await y.current.requestLeave(()=>U.requestLeave(e)):await U.requestLeave(e)}},t);function te(e){o(t=>({...t,...e}))}function ne(){if(!i.initialExperiment)throw Error(`Open an experiment before saving its settings.`);if(!k)throw Error(`AlphaEdit requires its exact managed base. Choose another starting model.`);return Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:i.initialExperiment.id,operationType:`alphaedit`,name:a.name.trim()||`AlphaEdit experiment`,...i.startingModel?{startingModel:i.startingModel}:{},alphaEditForm:{...a,baseModel:O}})}async function re(t){if(!r)throw Error(`Load canonical draft storage before preparing.`);await r(t),w();let n=await Iy(e).get(t.id);if(w(),n.status!==`draft`||n.projectId!==e.projectId||J(n.draft)!==J(t))throw Error(`The saved experiment changed. Reopen its exact current revision before continuing.`);return z.current=ee,n}async function W(){if(!(b.current||L)){b.current=!0,c(!0),u(null);try{await re(ne())}catch(e){C.current===x&&u(e)}finally{b.current=!1,C.current===x&&c(!1)}}}async function ie(){if(b.current||T.busy||T.original)return;b.current=!0,c(!0),u(null);let t=null;try{let n=window.openpond?.browser;if(!n?.openExternal){if(t=window.open(`about:blank`,`_blank`),!t)throw Error(`Allow a new tab to open Billing, then try again.`);t.opener=null}let r=await re(ne());w();let i=vt(a.maximumSpendUsd),o=await xb(e,{schemaVersion:`openpond.trainingFundingHandoffRequest.v1`,teamId:e.teamId,maximumSpendUsd:i===null?null:Number(i),draft:{id:r.id,revision:r.revision,contentHash:r.contentHash,projectId:r.projectId}});if(w(),!o.canPurchase||!o.billingUrl)throw Error(`A workspace billing owner needs to add credits for this experiment.`);if(_.current={record:r,snapshot:ee},g(!0),n?.openExternal){let e=await n.openExternal({conversationId:`experiment-funding:${r.id}`,url:o.billingUrl});if(w(),!e.ok)throw Error(e.error??`Billing could not be opened. Your experiment is saved; try again.`)}else t&&=(t.location.replace(o.billingUrl),null)}catch(e){t?.close(),C.current===x&&(u(e),g(!1),_.current=null)}finally{b.current=!1,C.current===x&&c(!1)}}async function G(){if(!(v.current||C.current!==x)){v.current=!0;try{let t=_.current;if(t){let n=await Iy(e).get(t.record.id);if(w(),n.contentHash!==t.record.contentHash||n.status!==`draft`||R.current!==t.snapshot)throw Error(`This experiment changed while Billing was open. Your edits remain here; save and review them before preparing.`)}await B.refresh(),w()}catch(e){C.current===x&&u(e)}finally{v.current=!1,C.current===x&&(_.current=null,g(!1))}}}let ae=(0,Q.useRef)(G);ae.current=G,(0,Q.useEffect)(()=>{if(!h)return;let e=()=>{document.visibilityState===`visible`&&ae.current()};return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[h]);async function K(e){if(w(),L||!t)throw Error(`Return to the editable experiment before selecting data.`);if(Fe(e),e.purpose!==`supervised_training`||!e.sealedAt||!e.examples.length)throw Error(`Choose a sealed, reviewed supervised training batch.`);te({[p]:xe(e)}),f(!1)}let q=E.batches.filter(e=>e.purpose===`supervised_training`&&e.sealedAt&&e.exampleCount>0),oe=a.editsBatch?J(a.editsBatch):``,se=q.find(e=>J(e.reference)===oe),ce=q.map(e=>({value:J(e.reference),label:`${e.reference.id} · release ${e.reference.revision} · ${e.exampleCount} examples`}));oe&&!ce.some(e=>e.value===oe)&&ce.unshift({value:oe,label:`${a.editsBatch.id} · saved release ${a.editsBatch.revision}`,disabled:!0});let le=i.startingModel?.source===`trained`?`trained:${i.startingModel.trainedVersion.contentHash}`:i.startingModel?.source===`alphaedit`?`alphaedit:${i.startingModel.alphaedit.versionHash}`:i.startingModel?.source===`steering`?`steering:${i.startingModel.steering.versionHash}`:i.startingModel?.source===`inference`?`inference:${i.startingModel.inferenceModelId}`:O?J(O):``,ue=E.models.filter(e=>e.preference.source===`managed`).map(e=>({value:J(e.preference),label:e.name}));return le&&!ue.some(e=>e.value===le)&&ue.unshift({value:le,label:i.startingModel?.label??O?.modelId??`Saved starting model`,disabled:!0}),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{hidden:d,inert:d,children:(0,$.jsxs)(Bv,{label:`Experiment setup`,action:`experiment`,onRequestClose:()=>void U.requestLeave(n),children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`h2`,{children:`Run Experiment`}),(0,$.jsx)(`button`,{type:`button`,disabled:I,onClick:()=>void U.requestLeave(n),children:`Close setup`})]}),(0,$.jsx)(X,{error:l??E.error??N.error??D.error}),(0,$.jsxs)(`form`,{noValidate:!0,onSubmit:e=>{e.preventDefault(),W()},children:[(0,$.jsx)(ft,{title:`Starting model`,children:(0,$.jsxs)(`fieldset`,{disabled:L,children:[(0,$.jsxs)(`label`,{children:[`Model`,(0,$.jsx)(Z,{label:`AlphaEdit starting model`,floating:!0,searchable:!0,value:le,options:[{value:``,label:`Choose exact managed base`},...ue],onChange:e=>{if(e===le)return;let t=E.models.find(t=>J(t.preference)===e&&t.preference.source===`managed`);e&&!t?u(`Refresh the model list before changing this selection.`):(i.setTrainingBaseModel(t?.preference??null),o(({startingModule:e,...t})=>({...t,parentArtifact:null})))}})]}),(0,$.jsx)(xy,{disabled:L}),(0,$.jsx)(`p`,{children:`AlphaEdit edits factual associations in the exact managed backbone. Preparation resolves reviewed edit and preservation batches and the qualified runtime.`}),(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:I||E.isFetching,onClick:()=>void E.refetch(),children:`Refresh models and reviewed batches`}),P?(0,$.jsx)(`p`,{children:P.state===`unavailable`?P.reason:`A compatible AlphaEdit runtime is available. Preparation rechecks its exact identity.`}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:I||N.isFetching||!M,onClick:()=>{D.refetch(),N.refetch()},children:`Refresh runtime availability`})]})}),(0,$.jsx)(ft,{title:`Training data`,children:(0,$.jsxs)(`fieldset`,{disabled:L,children:[(0,$.jsxs)(`label`,{children:[`Reviewed edits batch`,(0,$.jsx)(Z,{label:`AlphaEdit reviewed edits`,floating:!0,searchable:!0,value:oe,options:[{value:``,label:`Choose sealed supervised batch`},...ce],onChange:e=>{let t=q.find(t=>J(t.reference)===e);e&&!t?u(`Refresh the reviewed batch before changing this selection.`):te({editsBatch:t?.reference??null})}})]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>{m(`editsBatch`),f(!0)},children:`Import or review edits`})]})}),(0,$.jsx)(ft,{title:`Preservation data`,children:(0,$.jsxs)(`fieldset`,{disabled:L,children:[(0,$.jsxs)(`label`,{children:[`Preservation batch`,(0,$.jsx)(Z,{label:`AlphaEdit preservation batch`,floating:!0,searchable:!0,value:a.preservationBatch?J(a.preservationBatch):``,options:[{value:``,label:`Choose reviewed preservation batch`},...ce],onChange:e=>{let t=q.find(t=>J(t.reference)===e);e&&!t?u(`Refresh this exact preservation release before choosing it.`):te({preservationBatch:t?.reference??null})}})]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>{m(`preservationBatch`),f(!0)},children:`Import or review preservation data`}),(0,$.jsx)(`p`,{children:`Edit input contains subject and promptTemplate. Its reviewed expected output is an object with a text field containing the literal target. Preservation input contains text; its expected output has the same text field and literal value.`})]})}),(0,$.jsx)(ft,{title:`Settings`,children:(0,$.jsxs)(`fieldset`,{disabled:L,children:[(0,$.jsxs)(`label`,{children:[`Experiment name`,(0,$.jsx)(`input`,{value:a.name,maxLength:500,onChange:e=>te({name:e.target.value})})]}),(0,$.jsx)(Fy,{form:a,onChange:o}),a.startingModule?(0,$.jsxs)(`p`,{children:[`Saved Model `,a.startingModule.modelProjectId,` · version`,` `,a.startingModule.versionHash]}):null,a.parentArtifact?(0,$.jsxs)(`p`,{children:[`Continue exact matrices and sequential state `,a.parentArtifact.id,` ·`,` `,a.parentArtifact.contentHash,`.`]}):null,(0,$.jsxs)(`label`,{children:[`Spending limit (USD, optional)`,(0,$.jsx)(`input`,{type:`text`,inputMode:`decimal`,maxLength:100,placeholder:`Use available credits`,value:a.maximumSpendUsd,onChange:e=>te({maximumSpendUsd:e.target.value})})]})]})}),(0,$.jsx)(Db,{funding:B,busy:I,startAttempted:!!T.original,billingReturnPending:h,onOpenBilling:r?ie:null,onRefresh:G}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`submit`,className:`training-button secondary`,disabled:L||!r,children:s?`Saving…`:`Save draft`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:L||h||!r||!T.ready||!E.isSuccess||P?.state!==`ready`||!se||!a.preservationBatch,onClick:()=>{u(null);try{T.prepare(ne(),re)}catch(e){u(e)}},children:`Compile and prepare`})]})]}),(0,$.jsx)(Ob,{owner:T,api:e,disabled:I,onOpenBilling:r?ie:null,billingReturnPending:h,onRefreshFunding:G}),U.dialog]})}),d?(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`p`,{role:`status`,children:`Opening training data…`}),children:(0,$.jsx)(kb,{api:e,method:`alphaedit`,navigation:y,onClose:()=>f(!1),onUseBatch:K,beforeImport:async()=>{if(w(),L)throw Error(`Finish the original operation before importing data.`);await re(ne()),w()}})}):null]})}var jb={count:`Selected neuron count`,maximumBackgroundTargetRatio:`Maximum background to target activation ratio`,gradientExamples:`Gradient selection examples`},Mb={learningRate:`Learning rate`,maxSteps:`Maximum optimizer steps`,gradientAccumulationSteps:`Gradient accumulation steps`,maxSequenceLength:`Maximum sequence tokens`,preservationWeight:`Preservation weight`,preservationExamplesPerStep:`Preservation examples per step`,seed:`Seed`,maxDurationSeconds:`Maximum duration (seconds)`,maxCheckpointBytes:`Maximum checkpoint bytes`,maximumForwardTokenWork:`Maximum forward token work`};function Nb({form:e,onChange:t}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:`Select neurons from reviewed target and background domains, then train only their output projection columns. The saved inference delta does not contain optimizer state.`}),(0,$.jsxs)(`label`,{children:[`Selection span`,(0,$.jsx)(Z,{floating:!0,label:`Selection span`,value:e.selection.span,options:[{value:`reply_prediction`,label:`Reply prediction`},{value:`reply_start`,label:`Reply start`},{value:`prompt`,label:`Prompt`}],onChange:n=>{(n===`reply_prediction`||n===`reply_start`||n===`prompt`)&&t({...e,selection:{...e.selection,span:n}})}})]}),(0,$.jsxs)(`label`,{children:[`Background statistic`,(0,$.jsx)(Z,{floating:!0,label:`Background statistic`,value:e.selection.backgroundStatistic,options:[{value:`max_domains`,label:`Maximum across domains`},{value:`mean_domains`,label:`Mean across domains`}],onChange:n=>{(n===`max_domains`||n===`mean_domains`)&&t({...e,selection:{...e.selection,backgroundStatistic:n}})}})]}),Object.keys(jb).map(n=>(0,$.jsxs)(`label`,{children:[jb[n],(0,$.jsx)(`input`,{inputMode:`decimal`,value:e.selection[n],maxLength:100,onChange:r=>t({...e,selection:{...e.selection,[n]:r.target.value}})})]},n)),(0,$.jsxs)(`label`,{children:[`Explicit coordinates (optional)`,(0,$.jsx)(`textarea`,{rows:5,value:e.selection.coordinates,maxLength:1e4,onChange:n=>t({...e,selection:{...e.selection,coordinates:n.target.value}})})]}),(0,$.jsx)(`p`,{children:`Leave blank for automatic selection. Otherwise enter one layer:neuron coordinate per line; distinct coordinates must match the selected count.`}),Object.keys(Mb).map(n=>(0,$.jsxs)(`label`,{children:[Mb[n],(0,$.jsx)(`input`,{inputMode:`decimal`,value:e.training[n],maxLength:100,onChange:r=>t({...e,training:{...e.training,[n]:r.target.value}})})]},n)),e.inspectionSource?(0,$.jsxs)(`p`,{className:`saved-model-version-reference`,children:[`Selection evidence: `,e.inspectionSource.result.executionId,` · model`,` `,e.inspectionSource.modelHash,`. The compiler reauthorizes this original inspection.`]}):null]})}function Pb(e,t){let n=ml.parse({teamId:e.teamId,actorId:e.actorId,apiOrigin:t}),r={...n,projectId:e.projectId},i=`/v1/training/neuron-training-executions`;return{account:n,async capability(t,a){return Dn(await Y(e.connection,`${i}/capability`,{method:`POST`,signal:a,body:JSON.stringify({...r,capabilityQuery:t})}),t,n.actorId)},async compile(t){return yn(await Y(e.connection,`${i}/compile`,{method:`POST`,body:JSON.stringify({...r,command:t})}),t)},async mutate(t,a){let o=`action`in t?`${i}/${encodeURIComponent(t.id)}/${t.action}`:`${i}/prepare`,s=await Tn(await Y(e.connection,o,{method:`POST`,body:JSON.stringify({...r,intentHash:a,command:t})}),t);if(s.execution.ownerUserId!==n.actorId||s.execution.projectId!==e.projectId)throw Error(`The execution receipt belongs to another account or Project.`);return s},async get(t,r){let a=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}}),o=await $n(await Y(e.connection,`${i}/${encodeURIComponent(t)}?${a}`,{signal:r}),{teamId:e.teamId,id:t,ownerUserId:n.actorId});if(e.projectId!==null&&o.projectId!==e.projectId)throw Error(`The execution belongs to another Project.`);return o},async list(t={},r){let a={...t,...e.projectId?{projectId:e.projectId}:{}},o=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}});for(let[e,t]of Object.entries(a))t!==void 0&&o.set(e,String(t));return cr(await Y(e.connection,`${i}?${o}`,{signal:r}),{teamId:e.teamId,ownerUserId:n.actorId,query:a})}}}function Fb(e,t=!0){return S({queryKey:[`neuron-training-experiment-account`,e.key,e.actorId],enabled:t&&e.location===`hosted`&&!!e.actorId,retry:!1,queryFn:async({signal:t})=>{let n=await e.request(`inventory`,{},t);if(n.teamId!==e.teamId)throw Error(`The workspace account changed.`);return Pb(e,n.apiOrigin)}})}var Ib=[`training:prepare-neuron-training`,`training:start-neuron-training`,`training:cancel-neuron-training`];function Lb(e,t){let n=u(),r=J([e.key,e.accountKey,e.actorId,e.teamId,e.projectId,e.connection.serverUrl,t.draftId,t.executionId,t.method]),i=(0,Q.useRef)(r);i.current=r,(0,Q.useEffect)(()=>(i.current=r,()=>{i.current=``}),[r]);let a=()=>({identity:r,busy:!1,error:null,receipt:null,selected:null,original:null,preparationOperationId:null}),[o,s]=(0,Q.useState)(a),c=(0,Q.useRef)(new Set),l=o.identity===r?o:a();function d(e){i.current===r&&s(t=>({...t.identity===r?t:a(),...e}))}function f(){if(i.current!==r)throw Error(`Return to this experiment's original account before continuing.`)}let p=Fb(e,t.visible),m=p.data,h=S({queryKey:[`neuron-training-experiment-recovery`,r],enabled:t.visible&&e.location===`hosted`&&!!e.actorId&&!l.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[];for(let i of Ib){let a,o=new Set;for(let s=0;;s++){if(s>=100)throw Error(`The retained execution catalog exceeds its supported bound.`);let c=await e.pendingOperations(i,a,n);for(let n of c.items){let a=i===Ib[0]?Wl.parse(n.reviewedIntent):Gl.parse(n.reviewedIntent);if(a.account.actorId!==e.actorId||a.account.teamId!==e.teamId)throw Error(`The retained execution belongs to another account.`);if(!(t.draftId===null?`execution`in a&&a.execution.id===t.executionId:a.draftId===t.draftId))continue;let o=i===Ib[0]?Er.parse(n.command??{...a.request,operationId:n.id}):Wt(n.command??{...a.request,operationId:n.id});r.push({intent:a,command:o,operation:e.recoverOperation(n)})}if(!c.nextCursor)break;if(o.has(c.nextCursor))throw Error(`The retained execution catalog repeated a cursor.`);o.add(c.nextCursor),a=c.nextCursor}}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),g=l.original??h.data?.[0]??null,_=t.executionId??l.selected??l.receipt?.execution.id??(g&&`execution`in g.intent?g.intent.execution.id:null),v=S({queryKey:[`managed-neuron-training-execution`,r,_],enabled:t.visible&&!!(m&&_),retry:!1,queryFn:({signal:e})=>{if(!m||!_)throw Error(`Select an execution first.`);return m.get(_,e)},refetchInterval:e=>e.state.error?!1:e.state.data&&![`completed`,`failed`,`cancelled`].includes(e.state.data.phase)?3e3:!1});async function y(t){let r=Pb(e,t.intent.account.apiOrigin);if(J(r.account)!==J(t.intent.account))throw Error(`Return to this execution's original account before retrying.`);d({original:t}),await t.operation.retainCommand(t.command,`dispatching`),f();let i=await r.mutate(t.command,t.operation.intentHash);return f(),d({receipt:i,selected:i.execution.id,preparationOperationId:`action`in t.command?`preparationOperationId`in t.intent?t.intent.preparationOperationId:null:t.command.operationId}),await t.operation.acknowledge(),f(),d({original:null}),await h.refetch(),f(),n.invalidateQueries({queryKey:[`managed-neuron-training-execution`]}),n.invalidateQueries({queryKey:[`unified-experiments`]}),i}async function b(e){if(!c.current.has(r)){c.current.add(r),d({busy:!0,error:null});try{return f(),await e()}catch(e){return i.current===r&&d({error:e}),null}finally{c.current.delete(r),d({busy:!1})}}}async function x(n,r){return b(async()=>{if(g)return y(g);if(!m||!h.isSuccess||!t.draftId||n.id!==t.draftId||!n.neuronTrainingForm||!t.method)throw Error(`Load this saved experiment and original requests before preparing.`);let i=vt(n.neuronTrainingForm.maximumSpendUsd);await r(n),f();let a=await Iy(e).get(n.id);if(f(),a.status!==`draft`||a.projectId!==e.projectId||J(a.draft)!==J(n))throw Error(`The saved experiment changed. Reopen its exact current revision before preparing.`);let o=n.neuronTrainingForm.baseModel;if(!o||o.source!==`managed`||n.startingModel&&![`managed`].includes(n.startingModel.source))throw Error(`Choose a qualified exact NeuronTraining starting model.`);let s={teamId:e.teamId,modelId:o.modelId,source:o.source,...o.revision?{revision:o.revision}:{},...o.tokenizerRevision?{tokenizerRevision:o.tokenizerRevision}:{},...o.chatTemplateHash?{chatTemplateHash:o.chatTemplateHash}:{},...o.modelAssetId?{modelAssetId:o.modelAssetId}:{}},c={teamId:e.teamId,projectId:e.projectId,method:t.method,query:s,form:n.neuronTrainingForm},l=await m.compile(c);if(f(),l.actorId!==e.actorId||l.formHash!==await zr(n.neuronTrainingForm))throw Error(`The compilation differs from this exact saved form.`);let u=await Wn({teamId:e.teamId,projectId:e.projectId,operationId:crypto.randomUUID(),name:n.name,method:t.method,query:s,request:l.request,sourceForm:n.neuronTrainingForm,maximumSpendUsd:i}),{operationId:d,...p}=u,_=Wl.parse({account:m.account,draftId:n.id,request:p}),v=await e.operation(Ib[0],_);return f(),y({intent:_,operation:v,command:{...u,operationId:v.id}})})}async function C(n,r){return b(async()=>{if(g)return y(g);let i=r??v.data;if(!m||!h.isSuccess||!i||v.error)throw Error(`Read the exact execution before reviewing its next action.`);let{schemaVersion:a,request:o,sourceForm:s,result:c,resultRecordedAt:u,contentHash:d,...p}=i,_=Rt.parse(p),b=n===`start`?{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n,approvedMaximumSpendUsd:i.plan.maximumSpendUsd,...i.plan.computePrice?{approvedPriceHash:await zr(i.plan.computePrice)}:{}}:{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n},x=Gl.parse({account:m.account,draftId:l.preparationOperationId?t.draftId:null,preparationOperationId:l.preparationOperationId,execution:_,request:b}),S=await e.operation(n===`start`?Ib[1]:Ib[2],x);return f(),y({intent:x,operation:S,command:Wt({...b,operationId:S.id})})})}return{prepare:x,control:C,retry:()=>b(()=>{if(!g)throw Error(`Reload the original execution request.`);return y(g)}),busy:l.busy,receipt:l.receipt,original:g,execution:v.data,ready:p.isSuccess&&h.isSuccess,recoveryReady:!!g||h.isSuccess,canControl:v.isSuccess&&!v.error,error:l.error??p.error??h.error??v.error,refresh:()=>{p.refetch(),e.actorId&&h.refetch(),m&&_&&v.refetch()},loading:v.isFetching||p.isFetching,selectedId:_}}var Rb=`training-neuron-training-result-save`;function zb(e,t,n){let r=u(),i=J([e.key,ra(e.connection),t]),a=(0,Q.useRef)(i);a.current=i,(0,Q.useEffect)(()=>(a.current=i,()=>{a.current=``}),[i]);let o=()=>({identity:i,busy:!1,error:null,original:null,receipt:null}),[s,c]=(0,Q.useState)(o),l=(0,Q.useRef)(new Set),d=s.identity===i?s:o();function f(e){a.current===i&&c(t=>({...t.identity===i?t:o(),...e}))}function p(){if(a.current!==i)throw Error(`Return to this Model save's original account and result.`)}let m=n?.method===`selective_neuron_training`&&n.phase===`completed`&&n.result!==null,h=Fb(e,m),g=S({queryKey:[`neuron-training-model-save-recovery`,i],enabled:!!e.actorId&&!d.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[],i=new Set,a;for(let o=0;;o++){if(o>=100)throw Error(`The retained Model save catalog exceeds its supported bound.`);let s=await e.pendingOperations(Rb,a,n);for(let n of s.items){let i=Yl.parse(n.reviewedIntent);if(i.request.executionId!==t)continue;if(i.account.actorId!==e.actorId||i.account.teamId!==e.teamId||i.execution.projectId!==e.projectId)throw Error(`The retained Model save belongs to another creator or Project.`);let a=kt.parse(n.command??{...i.request,operationId:n.id});r.push({intent:i,command:a,operation:e.recoverOperation(n)})}if(!s.nextCursor)break;if(i.has(s.nextCursor))throw Error(`The retained Model save catalog repeated a cursor.`);i.add(s.nextCursor),a=s.nextCursor}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),_=d.original??g.data?.[0]??null,v=S({queryKey:[`neuron-training-model-save-options`,i,h.data?.account.apiOrigin,n?.result?.contentHash],enabled:m&&h.isSuccess&&g.isSuccess&&!_&&!d.busy,retry:!1,queryFn:async({signal:n})=>{if(!h.data)throw Error(`Read the configured result account first.`);let r=h.data.account,i=new URLSearchParams({...r,...e.projectId?{projectId:e.projectId}:{}}),a=Xl.parse(await Y(e.connection,`/v1/training/neuron-training-executions/${encodeURIComponent(t)}/model?${i}`,{signal:n}));if(J(a.account)!==J(r)||a.executionId!==t||a.projectId!==e.projectId)throw Error(`The Model targets differ from this exact result account or Project.`);return a}});async function y(n){f({original:n}),await n.operation.retainCommand(n.command,`dispatching`),p();let i=await Y(e.connection,`/v1/training/neuron-training-executions/${encodeURIComponent(n.command.executionId)}/model`,{method:`POST`,body:JSON.stringify({...n.intent.account,projectId:n.intent.execution.projectId,intentHash:n.operation.intentHash,command:n.command})}),a=await tr(i,n.command);if(p(),a.actorId!==e.actorId||a.version.source.executionId!==t)throw Error(`The saved Model receipt belongs to another creator or Project.`);f({receipt:a});for(let e of[`saved-training-model`,`saved-model-serving`,`neuron-training-model-save-options`,`unified-experiments`,`model-projects`])r.invalidateQueries({queryKey:[e]});return await n.operation.acknowledge(),p(),f({original:null}),await g.refetch(),p(),a}async function b(r){if(l.current.has(i))return null;l.current.add(i),f({busy:!0,error:null});try{if(p(),_)return await y(_);if(!g.isSuccess)throw Error(`Reload the original Model saves before continuing.`);if(!m||!n?.result||!v.isSuccess||!h.isSuccess||!v.data)throw Error(`Read the completed NeuronTraining result and current Model targets before saving.`);let i=r.modelProjectId?v.data.models.find(e=>e.id===r.modelProjectId):null;if(r.modelProjectId&&!i)throw Error(`Refresh the Model targets before updating this Model.`);let{schemaVersion:a,request:o,sourceForm:s,result:c,resultRecordedAt:l,contentHash:u,...d}=n,f=Yl.parse({account:v.data.account,execution:Rt.parse(d),request:{teamId:e.teamId,executionId:t,resultHash:n.result.contentHash,artifactHash:n.result.artifact.contentHash,name:r.name,modelProjectId:i?.id??null,expectedModelRevision:i?.revision??0}}),b=await e.operation(Rb,f);return p(),await y({intent:f,operation:b,command:kt.parse({...f.request,operationId:b.id})})}catch(e){return a.current===i&&f({error:e}),null}finally{l.current.delete(i),f({busy:!1})}}return{save:b,busy:d.busy,receipt:d.receipt,original:_,options:v.data,freshReady:m&&g.isSuccess&&v.isSuccess&&h.isSuccess,recoveryReady:!!_||g.isSuccess,error:d.error??g.error??(m?v.error??h.error:null),refresh:()=>{g.refetch(),m&&!_&&(h.refetch(),h.data&&v.refetch())}}}function Bb({api:e,id:t,execution:n,disabled:r=!1}){let i=zb(e,t,n),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)((n?.name??`NeuronTraining Model`).slice(0,200)),[l,u]=(0,Q.useState)(``),d=i.original?.command,f=iy({name:`NeuronTraining Model save`,busy:i.busy,dirty:a&&(!!d||s!==(n?.name??`NeuronTraining Model`).slice(0,200)||!!l),discardDescription:d?`The original save remains recoverable from this execution after closing.`:void 0}),p=n?.method===`selective_neuron_training`&&n.phase===`completed`&&n.result!==null,m=!i.recoveryReady&&i.error!==null;if(!p&&!d&&!i.receipt&&!m)return null;let h=i.receipt?.version;return(0,$.jsxs)(`section`,{className:`training-detail-section`,"aria-label":`Save NeuronTraining Model`,children:[(0,$.jsx)(X,{error:i.error}),i.recoveryReady?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Reload retained Model saves`}),i.receipt&&h?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[`Saved to `,i.receipt.model?.name,`. Exact version `,(0,$.jsx)(`code`,{children:h.contentHash}),`.`]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact saved version`}),(0,$.jsx)(`pre`,{className:`saved-model-version-reference`,children:JSON.stringify(h,null,2)})]}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void wo(as(`models`)),children:`Open Models`}),(0,$.jsx)(`p`,{children:`The saved neuron delta supports inference. Training continuation requires optimizer state and is unavailable; choose a managed base explicitly for a fresh experiment.`})]}),(0,$.jsx)(hb,{connection:e.connection,version:h,api:e},`${e.key}:${h.contentHash}`)]}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:r||i.busy||!i.recoveryReady,onClick:()=>o(!0),children:d?`Recover Model save`:i.receipt?`Save model again`:`Save model`}),a?(0,$.jsxs)(qa,{ariaLabel:`Save NeuronTraining model`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:i.busy,onClose:()=>void f.requestLeave(()=>o(!1)),children:[(0,$.jsx)(`h2`,{children:`Save model`}),(0,$.jsx)(`p`,{children:`Save the exact learned modification from this completed result. Saving does not activate serving.`}),(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),i.save({name:s,modelProjectId:l||null}).then(e=>{e&&(f.allowNextNavigation(),o(!1))})},children:[(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Save destination`}),(0,$.jsx)(Z,{label:`Model destination`,value:d?.modelProjectId??(d?``:l),options:[{value:``,label:`Create new Model`},...(i.options?.models??[]).map(e=>({value:e.id,label:e.name,description:`Current revision ${e.revision}`})),...d?.modelProjectId&&!i.options?.models.some(e=>e.id===d.modelProjectId)?[{value:d.modelProjectId,label:`Original selected Model`}]:[]],disabled:i.busy||!!d||!i.freshReady,onChange:e=>{u(e);let t=i.options?.models.find(t=>t.id===e);t&&c(t.name)}})]}),(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Model name`}),(0,$.jsx)(`input`,{"data-autofocus":!0,value:d?.name??s,maxLength:200,disabled:i.busy||!!d,onChange:e=>c(e.target.value)})]}),d?(0,$.jsx)(`p`,{children:`Original result, module, destination and revision are retained. Retry sends the same operation.`}):null,i.receipt&&d?(0,$.jsx)(`p`,{role:`status`,children:`The Model was saved. Local acknowledgement is pending; retry preserves its exact receipt.`}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:()=>void f.requestLeave(()=>o(!1)),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Refresh targets and recovery`}),(0,$.jsx)(`button`,{type:`submit`,className:`training-button`,disabled:i.busy||r||!i.recoveryReady||!d&&!i.freshReady,children:i.busy?`Saving…`:d?`Retry original save`:`Save model`})]})]})]}):null,f.dialog]})}function Vb({api:e,execution:t}){let n=k(e.connection,null),r=Fb(e),[i,a]=(0,Q.useState)(null),o=n.selection?.neuronTrainingResult?.id===t.id&&n.selection.neuronTrainingResult.result?.contentHash===t.result?.contentHash;async function s(){a(null);try{if(!r.data||t.phase!==`completed`||!t.result)throw Error(`Read the exact completed NeuronTraining result in its original account first.`);let i=An.parse({kind:`neuron_training_result`,location:`cloud`,owner:{teamId:t.teamId,actorId:t.ownerUserId},apiOrigin:r.data.account.apiOrigin,projectId:t.projectId,executionId:t.id,inputHash:t.plan.inputHash,modelHash:t.result.modelHash,runtimeHash:t.plan.runtimeHash,resultHash:t.result.contentHash,artifact:t.result.artifact?{id:t.result.artifact.id,contentHash:t.result.artifact.contentHash}:null});await n.select({kind:`neuron_training_result`,id:t.id,location:`cloud`,teamId:e.teamId,apiOrigin:r.data.account.apiOrigin,result:i})}catch(e){a(e)}}return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{error:i??r.error}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:n.selecting||!r.isSuccess,onClick:()=>void s(),children:o?`Result selected for chat`:`Use result in chat`})]})}function Hb({owner:e,api:t,onOpenBilling:n=null,billingReturnPending:r=!1,onRefreshFunding:i,disabled:a=!1}){let o=e.busy||a,s=e.execution,c=e.original,l=(e.receipt&&(!s||e.receipt.execution.id===s.id&&e.receipt.execution.revision>s.revision)?e.receipt.execution:s)??(c&&`execution`in c.intent?c.intent.execution:null),[u,d]=(0,Q.useState)(null),f=Tb(t,l?.plan.maximumSpendUsd??``,!!l,!!l?.plan.computePrice),p=c?`action`in c.command?c.command.action:`prepare`:null;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{error:e.error}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o||e.loading,onClick:e.refresh,children:`Refresh execution and recovery`}),c?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||!e.recoveryReady,onClick:()=>void e.retry(),children:o?`Reconciling…`:`Retry original ${p}`}):null]}),c&&!(`action`in c.command)?(0,$.jsxs)(ft,{title:`Original preparation`,children:[(0,$.jsxs)(`p`,{children:[c.command.name,` · `,c.command.method,` · `,Uy(c.command.maximumSpendUsd)]}),(0,$.jsxs)(`p`,{children:[c.command.request.training.maxSteps,` training steps · batch`,` `,c.command.request.data.target.batch.id,` ·`,` `,c.command.request.model.modelId,` · `,c.command.request.model.revision]})]}):null,l?(0,$.jsxs)(ft,{title:`Hosted execution`,children:[(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`State`}),(0,$.jsx)(`dd`,{children:l.phase}),(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(l.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:l.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Execution`}),(0,$.jsx)(`dd`,{children:l.id}),(0,$.jsx)(`dt`,{children:`Preparation expires`}),(0,$.jsx)(`dd`,{children:new Date(l.plan.expiresAt).toLocaleString()}),(0,$.jsx)(`dt`,{children:`Exact plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:l.plan.contentHash}),(0,$.jsx)(`dt`,{children:`Runtime`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:l.plan.runtimeHash})]}),s?(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[s.phase===`prepared`?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||e.loading||!e.ready||!e.canControl||!!c||Date.parse(s.plan.expiresAt)<=Date.now(),onClick:()=>d({action:`start`,value:s}),children:`Review Start`}):null,[`completed`,`cancelled`,`failed`].includes(s.phase)?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o||e.loading||!e.ready||!e.canControl||!!c,onClick:()=>d({action:`cancel`,value:s}),children:`Review Cancel`})]}):null]}):null,s?.phase===`completed`&&s.result?(0,$.jsx)(Vb,{api:t,execution:s}):null,s?.result?(0,$.jsx)(t_,{result:s.result}):l?.phase===`completed`?(0,$.jsx)(`p`,{children:`No result bytes are available in this read. Retained execution identity remains available for recovery.`}):null,e.selectedId?(0,$.jsx)(Bb,{api:t,id:e.selectedId,execution:s,disabled:o||!!c},`${t.key}:${e.selectedId}`):null,u&&s?(0,$.jsxs)(qa,{ariaLabel:u.action===`start`?`Start NeuronTraining experiment`:`Cancel NeuronTraining experiment`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:o,onClose:()=>{o||d(null)},children:[(0,$.jsx)(`h2`,{children:u.action===`start`?`Start NeuronTraining experiment`:`Cancel NeuronTraining experiment`}),(0,$.jsx)(`p`,{children:u.action===`start`?Gy(u.value.plan.computePrice):`Cancel this exact execution. In-flight work may need to stop and settle before capacity is released.`}),(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(u.value.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:u.value.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Training steps`}),(0,$.jsx)(`dd`,{children:u.value.request.training.maxSteps}),(0,$.jsx)(`dt`,{children:`Reviewed batch`}),(0,$.jsxs)(`dd`,{children:[u.value.request.data.target.batch.id,` · release`,` `,u.value.request.data.target.batch.revision]}),(0,$.jsx)(`dt`,{children:`Maximum duration`}),(0,$.jsxs)(`dd`,{children:[u.value.request.training.maxDurationSeconds,` seconds`]}),(0,$.jsx)(`dt`,{children:`Model`}),(0,$.jsxs)(`dd`,{children:[u.value.request.model.modelId,` · `,u.value.request.model.revision]}),(0,$.jsx)(`dt`,{children:`Plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:u.value.plan.contentHash})]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact prepared training request`}),(0,$.jsx)(`pre`,{children:JSON.stringify(u.value.request,null,2)})]}),u.action===`start`?(0,$.jsx)(Db,{funding:f,busy:o,startAttempted:!!c,billingReturnPending:r,onOpenBilling:n,onRefresh:i??(async()=>{await f.refresh()})}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o,onClick:()=>d(null),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||e.loading||!!c||!e.ready||!e.canControl||u.action===`start`&&(r||!f.canStart||Date.parse(u.value.plan.expiresAt)<=Date.now()),onClick:()=>void e.control(u.action,u.value).then(e=>{e&&d(null)}),children:o?`Applying…`:u.action===`start`?Ky(u.value.plan.maximumSpendUsd):`Cancel execution`})]})]}):null]})}var Ub=(0,Q.lazy)(()=>o(()=>import(`./ExperimentTrainingDataWorkspace-WhwQ0QBi.js`),__vite__mapDeps([76,1,2,3,4,77,5,6,9,10,78,32,27,31,21,16,43,19,20,22,13,23,15,24,25,26,8,28,11,29,30,33,34,35,36,37,38,39,40,41,18,42,44,45,46,47,48,49,50,51,52,53,54,55,56,79,80])));function Wb({api:e,visible:t,onClose:n,onSaveDraft:r}){let i=kv(),[a,o]=(0,Q.useState)(()=>i.initialExperiment?.neuronTrainingForm??nn(i.trainingBaseModel)),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(`targetBatch`),[h,g]=(0,Q.useState)(!1),_=(0,Q.useRef)(null),v=(0,Q.useRef)(!1),y=(0,Q.useRef)(null),b=(0,Q.useRef)(!1),x=J([e.key,e.accountKey,e.actorId,e.teamId,e.projectId,e.connection.serverUrl,i.initialExperiment?.id]),C=(0,Q.useRef)(x);C.current=x,(0,Q.useEffect)(()=>(C.current=x,()=>{C.current=``}),[x]);function w(){if(C.current!==x)throw Error(`Return to this experiment's original account before continuing.`)}let T=Lb(e,{draftId:i.initialExperiment?.id??null,method:`selective_neuron_training`,visible:t}),E=Ry(e,t,a.targetBatch,[...a.background.map(e=>e.batch),a.preservationBatch]),D=Fb(e,t),O=i.trainingBaseModel,k=!i.startingModel||i.startingModel.source===`managed`,A=wv(i.startingModel),j=(0,Q.useRef)(A);(0,Q.useEffect)(()=>{j.current!==A&&o(({inspectionSource:e,...t})=>({...t,parentArtifact:null})),j.current=A},[A,i.startingModel?.source]);let M=O?.source===`managed`&&k?{teamId:e.teamId,source:O.source,modelId:O.modelId,...O.revision?{revision:O.revision}:{},...O.tokenizerRevision?{tokenizerRevision:O.tokenizerRevision}:{},...O.chatTemplateHash?{chatTemplateHash:O.chatTemplateHash}:{},...O.modelAssetId?{modelAssetId:O.modelAssetId}:{}}:null,N=S({queryKey:[`neuron-training-execution-capability`,x,M],enabled:t&&!!(D.data&&M),retry:!1,staleTime:3e4,queryFn:({signal:e})=>{if(!D.data||!M)throw Error(`Choose an exact managed base before checking NeuronTraining availability.`);return D.data.capability(M,e)},refetchInterval:e=>!e.state.error&&6e4}),P=N.data&&!N.isError&&Date.parse(N.data.expiresAt)>Date.now()?N.data.execution:null,F=T.selectedId&&![`completed`,`failed`,`cancelled`].includes(T.execution?.phase??T.receipt?.execution.phase??`prepared`),I=s||T.busy,L=I||!!(T.original||F),ee=J({...a,baseModel:O,sourceKey:A}),R=(0,Q.useRef)(ee);R.current=ee;let z=(0,Q.useRef)(ee),B=Tb(e,a.maximumSpendUsd,t,!0),V=ee!==z.current,H=i.reportOperationDraftDirty;(0,Q.useEffect)(()=>{H(`selective_neuron_training`,V)},[V,H]);let U=iy({name:`Neuron training experiment`,dirty:V||i.operationDraftDirty||i.evaluationDirty,busy:I,onLeave:n});My({...U,requestLeave:async e=>{d&&y.current?await y.current.requestLeave(()=>U.requestLeave(e)):await U.requestLeave(e)}},t);function te(e){o(t=>({...t,...e}))}function ne(){if(!i.initialExperiment)throw Error(`Open an experiment before saving its settings.`);if(!k)throw Error(`Neuron training requires its exact managed base. Choose another starting model.`);return Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:i.initialExperiment.id,operationType:`selective_neuron_training`,name:a.name.trim()||`Neuron training experiment`,...i.startingModel?{startingModel:i.startingModel}:{},neuronTrainingForm:{...a,baseModel:O}})}async function re(t){if(!r)throw Error(`Load canonical draft storage before preparing.`);await r(t),w();let n=await Iy(e).get(t.id);if(w(),n.status!==`draft`||n.projectId!==e.projectId||J(n.draft)!==J(t))throw Error(`The saved experiment changed. Reopen its exact current revision before continuing.`);return z.current=ee,n}async function W(){if(!(b.current||L)){b.current=!0,c(!0),u(null);try{await re(ne())}catch(e){C.current===x&&u(e)}finally{b.current=!1,C.current===x&&c(!1)}}}async function ie(){if(b.current||T.busy||T.original)return;b.current=!0,c(!0),u(null);let t=null;try{let n=window.openpond?.browser;if(!n?.openExternal){if(t=window.open(`about:blank`,`_blank`),!t)throw Error(`Allow a new tab to open Billing, then try again.`);t.opener=null}let r=await re(ne());w();let i=vt(a.maximumSpendUsd),o=await xb(e,{schemaVersion:`openpond.trainingFundingHandoffRequest.v1`,teamId:e.teamId,maximumSpendUsd:i===null?null:Number(i),draft:{id:r.id,revision:r.revision,contentHash:r.contentHash,projectId:r.projectId}});if(w(),!o.canPurchase||!o.billingUrl)throw Error(`A workspace billing owner needs to add credits for this experiment.`);if(_.current={record:r,snapshot:ee},g(!0),n?.openExternal){let e=await n.openExternal({conversationId:`experiment-funding:${r.id}`,url:o.billingUrl});if(w(),!e.ok)throw Error(e.error??`Billing could not be opened. Your experiment is saved; try again.`)}else t&&=(t.location.replace(o.billingUrl),null)}catch(e){t?.close(),C.current===x&&(u(e),g(!1),_.current=null)}finally{b.current=!1,C.current===x&&c(!1)}}async function G(){if(!(v.current||C.current!==x)){v.current=!0;try{let t=_.current;if(t){let n=await Iy(e).get(t.record.id);if(w(),n.contentHash!==t.record.contentHash||n.status!==`draft`||R.current!==t.snapshot)throw Error(`This experiment changed while Billing was open. Your edits remain here; save and review them before preparing.`)}await B.refresh(),w()}catch(e){C.current===x&&u(e)}finally{v.current=!1,C.current===x&&(_.current=null,g(!1))}}}let ae=(0,Q.useRef)(G);ae.current=G,(0,Q.useEffect)(()=>{if(!h)return;let e=()=>{document.visibilityState===`visible`&&ae.current()};return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[h]);async function K(e){if(w(),L||!t)throw Error(`Return to the editable experiment before selecting data.`);if(Fe(e),e.purpose!==`supervised_training`||!e.sealedAt||!e.examples.length)throw Error(`Choose a sealed, reviewed supervised training batch.`);te(typeof p==`number`?{background:a.background.map((t,n)=>n===p?{...t,batch:xe(e)}:t)}:{[p]:xe(e)}),f(!1)}let q=E.batches.filter(e=>e.purpose===`supervised_training`&&e.sealedAt&&e.exampleCount>0),oe=a.targetBatch?J(a.targetBatch):``,se=q.find(e=>J(e.reference)===oe),ce=q.map(e=>({value:J(e.reference),label:`${e.reference.id} · release ${e.reference.revision} · ${e.exampleCount} examples`}));oe&&!ce.some(e=>e.value===oe)&&ce.unshift({value:oe,label:`${a.targetBatch.id} · saved release ${a.targetBatch.revision}`,disabled:!0});let le=i.startingModel?.source===`trained`?`trained:${i.startingModel.trainedVersion.contentHash}`:i.startingModel?.source===`steering`?`steering:${i.startingModel.steering.versionHash}`:i.startingModel?.source===`inference`?`inference:${i.startingModel.inferenceModelId}`:O?J(O):``,ue=E.models.filter(e=>e.preference.source===`managed`).map(e=>({value:J(e.preference),label:e.name}));return le&&!ue.some(e=>e.value===le)&&ue.unshift({value:le,label:i.startingModel?.label??O?.modelId??`Saved starting model`,disabled:!0}),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{hidden:d,inert:d,children:(0,$.jsxs)(Bv,{label:`Experiment setup`,action:`experiment`,onRequestClose:()=>void U.requestLeave(n),children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`h2`,{children:`Run Experiment`}),(0,$.jsx)(`button`,{type:`button`,disabled:I,onClick:()=>void U.requestLeave(n),children:`Close setup`})]}),(0,$.jsx)(X,{error:l??E.error??N.error??D.error}),(0,$.jsxs)(`form`,{noValidate:!0,onSubmit:e=>{e.preventDefault(),W()},children:[(0,$.jsx)(ft,{title:`Starting model`,children:(0,$.jsxs)(`fieldset`,{disabled:L,children:[(0,$.jsxs)(`label`,{children:[`Model`,(0,$.jsx)(Z,{label:`Neuron training starting model`,floating:!0,searchable:!0,value:le,options:[{value:``,label:`Choose exact managed base`},...ue],onChange:e=>{if(e===le)return;let t=E.models.find(t=>J(t.preference)===e&&t.preference.source===`managed`);e&&!t?u(`Refresh the model list before changing this selection.`):(i.setTrainingBaseModel(t?.preference??null),o(({inspectionSource:e,...t})=>({...t,parentArtifact:null})))}})]}),(0,$.jsx)(xy,{disabled:L}),(0,$.jsx)(`p`,{children:`Select neurons from reviewed target and background domains, then train their output projection columns in the exact managed backbone. Saved neuron deltas cannot resume training.`}),(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:I||E.isFetching,onClick:()=>void E.refetch(),children:`Refresh models and reviewed batches`}),P?(0,$.jsx)(`p`,{children:P.state===`unavailable`?P.reason:`A compatible NeuronTraining runtime is available. Preparation rechecks its exact identity.`}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:I||N.isFetching||!M,onClick:()=>{D.refetch(),N.refetch()},children:`Refresh runtime availability`})]})}),(0,$.jsx)(ft,{title:`Training data`,children:(0,$.jsxs)(`fieldset`,{disabled:L,children:[(0,$.jsxs)(`label`,{children:[`Reviewed target batch`,(0,$.jsx)(Z,{label:`Neuron training target batch`,floating:!0,searchable:!0,value:oe,options:[{value:``,label:`Choose sealed supervised batch`},...ce],onChange:e=>{let t=q.find(t=>J(t.reference)===e);e&&!t?u(`Refresh the reviewed batch before changing this selection.`):te({targetBatch:t?.reference??null})}})]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>{m(`targetBatch`),f(!0)},children:`Import or review target data`})]})}),(0,$.jsx)(ft,{title:`Preservation data`,children:(0,$.jsxs)(`fieldset`,{disabled:L,children:[(0,$.jsxs)(`label`,{children:[`Preservation batch`,(0,$.jsx)(Z,{label:`Neuron training preservation batch`,floating:!0,searchable:!0,value:a.preservationBatch?J(a.preservationBatch):``,options:[{value:``,label:`No preservation batch`},...ce],onChange:e=>{let t=q.find(t=>J(t.reference)===e);e&&!t?u(`Refresh this exact preservation release before choosing it.`):te({preservationBatch:t?.reference??null})}})]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>{m(`preservationBatch`),f(!0)},children:`Import or review preservation data`}),(0,$.jsx)(`p`,{children:`Preservation data, weight and examples per step must be enabled together. Target and background batches contain reviewed supervised examples.`})]})}),(0,$.jsx)(ft,{title:`Background domains`,children:(0,$.jsxs)(`fieldset`,{disabled:L,children:[a.background.map((e,t)=>(0,$.jsxs)(`section`,{children:[(0,$.jsxs)(`label`,{children:[`Domain name`,(0,$.jsx)(`input`,{value:e.domain,maxLength:100,onChange:e=>te({background:a.background.map((n,r)=>r===t?{...n,domain:e.target.value}:n)})})]}),(0,$.jsxs)(`label`,{children:[`Background batch`,(0,$.jsx)(Z,{label:`Background batch ${t+1}`,floating:!0,searchable:!0,value:e.batch?J(e.batch):``,options:[{value:``,label:`Choose reviewed background batch`},...ce],onChange:e=>{let n=q.find(t=>J(t.reference)===e);e&&!n?u(`Refresh this exact background release before choosing it.`):te({background:a.background.map((e,r)=>r===t?{...e,batch:n?.reference??null}:e)})}})]}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>{m(t),f(!0)},children:`Import or review this domain`}),(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:a.background.length<=1,onClick:()=>te({background:a.background.filter((e,n)=>n!==t)}),children:`Remove domain`})]})]},t)),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:a.background.length>=8,onClick:()=>te({background:[...a.background,{domain:``,batch:null}]}),children:`Add background domain`})]})}),(0,$.jsx)(ft,{title:`Settings`,children:(0,$.jsxs)(`fieldset`,{disabled:L,children:[(0,$.jsxs)(`label`,{children:[`Experiment name`,(0,$.jsx)(`input`,{value:a.name,maxLength:500,onChange:e=>te({name:e.target.value})})]}),(0,$.jsx)(Nb,{form:a,onChange:o}),(0,$.jsxs)(`label`,{children:[`Spending limit (USD, optional)`,(0,$.jsx)(`input`,{type:`text`,inputMode:`decimal`,maxLength:100,placeholder:`Use available credits`,value:a.maximumSpendUsd,onChange:e=>te({maximumSpendUsd:e.target.value})})]})]})}),(0,$.jsx)(Db,{funding:B,busy:I,startAttempted:!!T.original,billingReturnPending:h,onOpenBilling:r?ie:null,onRefresh:G}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`submit`,className:`training-button secondary`,disabled:L||!r,children:s?`Saving…`:`Save draft`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:L||h||!r||!T.ready||!E.isSuccess||P?.state!==`ready`||!se||a.background.some(e=>!e.domain.trim()||!e.batch)||Number(a.training.preservationWeight)>0&&!a.preservationBatch,onClick:()=>{u(null);try{T.prepare(ne(),re)}catch(e){u(e)}},children:`Compile and prepare`})]})]}),(0,$.jsx)(Hb,{owner:T,api:e,disabled:I,onOpenBilling:r?ie:null,billingReturnPending:h,onRefreshFunding:G}),U.dialog]})}),d?(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`p`,{role:`status`,children:`Opening training data…`}),children:(0,$.jsx)(Ub,{api:e,method:`selective_neuron_training`,navigation:y,onClose:()=>f(!1),onUseBatch:K,beforeImport:async()=>{if(w(),L)throw Error(`Finish the original operation before importing data.`);await re(ne()),w()}})}):null]})}var Gb=[`training:prepare-decision`,`training:start-decision`,`training:cancel-decision`];function Kb(e,t){let n=u(),r=J([e.key,e.accountKey,e.actorId,e.teamId,e.projectId,e.connection.serverUrl,t.draftId,t.executionId,t.method]),i=(0,Q.useRef)(r);i.current=r,(0,Q.useEffect)(()=>(i.current=r,()=>{i.current=``}),[r]);let a=()=>({identity:r,busy:!1,error:null,receipt:null,selected:null,original:null,preparationOperationId:null}),[o,s]=(0,Q.useState)(a),c=(0,Q.useRef)(new Set),l=o.identity===r?o:a();function d(e){i.current===r&&s(t=>({...t.identity===r?t:a(),...e}))}function f(){if(i.current!==r)throw Error(`Return to this experiment's original account before continuing.`)}let p=tb(e,t.visible),m=p.data,h=S({queryKey:[`decision-experiment-recovery`,r],enabled:t.visible&&e.location===`hosted`&&!!e.actorId&&!l.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[];for(let i of Gb){let a,o=new Set;for(let s=0;;s++){if(s>=100)throw Error(`The retained execution catalog exceeds its supported bound.`);let c=await e.pendingOperations(i,a,n);for(let n of c.items){let a=i===Gb[0]?kl.parse(n.reviewedIntent):Al.parse(n.reviewedIntent);if(a.account.actorId!==e.actorId||a.account.teamId!==e.teamId)throw Error(`The retained execution belongs to another account.`);if(!(t.draftId===null?`execution`in a&&a.execution.id===t.executionId:a.draftId===t.draftId))continue;let o=i===Gb[0]?_r.parse(n.command??{...a.request,operationId:n.id}):Wt(n.command??{...a.request,operationId:n.id});r.push({intent:a,command:o,operation:e.recoverOperation(n)})}if(!c.nextCursor)break;if(o.has(c.nextCursor))throw Error(`The retained execution catalog repeated a cursor.`);o.add(c.nextCursor),a=c.nextCursor}}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),g=l.original??h.data?.[0]??null,_=t.executionId??l.selected??l.receipt?.execution.id??(g&&`execution`in g.intent?g.intent.execution.id:null),v=S({queryKey:[`managed-decision-execution`,r,_],enabled:t.visible&&!!(m&&_),retry:!1,queryFn:({signal:e})=>{if(!m||!_)throw Error(`Select an execution first.`);return m.get(_,e)},refetchInterval:e=>e.state.error?!1:e.state.data&&![`completed`,`failed`,`cancelled`].includes(e.state.data.phase)?3e3:!1});async function y(t){let r=eb(e,t.intent.account.apiOrigin);if(J(r.account)!==J(t.intent.account))throw Error(`Return to this execution's original account before retrying.`);d({original:t}),await t.operation.retainCommand(t.command,`dispatching`),f();let i=await r.mutate(t.command,t.operation.intentHash);return f(),d({receipt:i,selected:i.execution.id,preparationOperationId:`action`in t.command?`preparationOperationId`in t.intent?t.intent.preparationOperationId:null:t.command.operationId}),await t.operation.acknowledge(),f(),d({original:null}),await h.refetch(),f(),n.invalidateQueries({queryKey:[`managed-decision-execution`]}),n.invalidateQueries({queryKey:[`unified-experiments`]}),i}async function b(e){if(!c.current.has(r)){c.current.add(r),d({busy:!0,error:null});try{return f(),await e()}catch(e){return i.current===r&&d({error:e}),null}finally{c.current.delete(r),d({busy:!1})}}}async function x(n,r){return b(async()=>{if(g)return y(g);if(!m||!h.isSuccess||!t.draftId||n.id!==t.draftId||!n.decisionForm||!t.method)throw Error(`Load this saved experiment and original requests before preparing.`);let i=vt(n.decisionForm.maximumSpendUsd);await r(n),f();let a=await Iy(e).get(n.id);if(f(),a.status!==`draft`||a.projectId!==e.projectId||J(a.draft)!==J(n))throw Error(`The saved experiment changed. Reopen its exact current revision before preparing.`);let o=n.decisionForm.baseModel;if(!o||o.source!==`managed`||n.startingModel&&![`managed`,`decision`].includes(n.startingModel.source))throw Error(`Choose a qualified exact Decision starting model.`);let s={teamId:e.teamId,modelId:o.modelId,source:o.source,...o.revision?{revision:o.revision}:{},...o.tokenizerRevision?{tokenizerRevision:o.tokenizerRevision}:{},...o.chatTemplateHash?{chatTemplateHash:o.chatTemplateHash}:{},...o.modelAssetId?{modelAssetId:o.modelAssetId}:{}},c={teamId:e.teamId,projectId:e.projectId,method:t.method,mode:n.decisionForm.mode,query:s,form:n.decisionForm},l=await m.compile(c);if(f(),l.actorId!==e.actorId||l.formHash!==await zr(n.decisionForm))throw Error(`The compilation differs from this exact saved form.`);let u=await Ft({teamId:e.teamId,projectId:e.projectId,operationId:crypto.randomUUID(),name:n.name,method:t.method,mode:n.decisionForm.mode,query:s,request:l.request,sourceForm:n.decisionForm,maximumSpendUsd:i}),{operationId:d,...p}=u,_=kl.parse({account:m.account,draftId:n.id,request:p}),v=await e.operation(Gb[0],_);return f(),y({intent:_,operation:v,command:{...u,operationId:v.id}})})}async function C(n,r){return b(async()=>{if(g)return y(g);let i=r??v.data;if(!m||!h.isSuccess||!i||v.error)throw Error(`Read the exact execution before reviewing its next action.`);let{schemaVersion:a,request:o,sourceForm:s,result:c,resultRecordedAt:u,contentHash:d,...p}=i,_=Zt.parse(p),b=n===`start`?{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n,approvedMaximumSpendUsd:i.plan.maximumSpendUsd,...i.plan.computePrice?{approvedPriceHash:await zr(i.plan.computePrice)}:{}}:{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n},x=Al.parse({account:m.account,draftId:l.preparationOperationId?t.draftId:null,preparationOperationId:l.preparationOperationId,execution:_,request:b}),S=await e.operation(n===`start`?Gb[1]:Gb[2],x);return f(),y({intent:x,operation:S,command:Wt({...b,operationId:S.id})})})}return{prepare:x,control:C,retry:()=>b(()=>{if(!g)throw Error(`Reload the original execution request.`);return y(g)}),busy:l.busy,receipt:l.receipt,original:g,execution:v.data,ready:p.isSuccess&&h.isSuccess,recoveryReady:!!g||h.isSuccess,canControl:v.isSuccess&&!v.error,error:l.error??p.error??h.error??v.error,refresh:()=>{p.refetch(),e.actorId&&h.refetch(),m&&_&&v.refetch()},loading:v.isFetching||p.isFetching,selectedId:_}}function qb({api:e,execution:t}){let n=k(e.connection,null),r=tb(e),[i,a]=(0,Q.useState)(null),o=n.selection?.decisionResult?.id===t.id&&n.selection.decisionResult.result?.contentHash===t.result?.contentHash;async function s(){a(null);try{if(!r.data||t.phase!==`completed`||!t.result)throw Error(`Read the exact completed Decision result in its original account first.`);let i=un.parse({kind:`decision_result`,mode:t.mode,location:`cloud`,owner:{teamId:t.teamId,actorId:t.ownerUserId},apiOrigin:r.data.account.apiOrigin,projectId:t.projectId,executionId:t.id,inputHash:t.plan.inputHash,modelHash:t.result.modelHash,runtimeHash:t.plan.runtimeHash,resultHash:t.result.contentHash,artifact:t.result.artifact?{id:t.result.artifact.id,contentHash:t.result.artifact.contentHash}:null});await n.select({kind:`decision_result`,id:t.id,location:`cloud`,teamId:e.teamId,apiOrigin:r.data.account.apiOrigin,result:i})}catch(e){a(e)}}return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{error:i??r.error}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:n.selecting||!r.isSuccess,onClick:()=>void s(),children:o?`Result selected for chat`:`Use result in chat`})]})}var Jb=`training-decision-result-save`;function Yb(e,t,n){let r=u(),i=J([e.key,ra(e.connection),t]),a=(0,Q.useRef)(i);a.current=i,(0,Q.useEffect)(()=>(a.current=i,()=>{a.current=``}),[i]);let o=()=>({identity:i,busy:!1,error:null,original:null,receipt:null}),[s,c]=(0,Q.useState)(o),l=(0,Q.useRef)(new Set),d=s.identity===i?s:o();function f(e){a.current===i&&c(t=>({...t.identity===i?t:o(),...e}))}function p(){if(a.current!==i)throw Error(`Return to this Model save's original account and result.`)}let m=n?.method===`decision_model`&&n.phase===`completed`&&n.result?.schemaVersion===`openpond.decisionTrainingResult.v1`,h=tb(e,m),g=S({queryKey:[`decision-model-save-recovery`,i],enabled:!!e.actorId&&!d.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[],i=new Set,a;for(let o=0;;o++){if(o>=100)throw Error(`The retained Model save catalog exceeds its supported bound.`);let s=await e.pendingOperations(Jb,a,n);for(let n of s.items){let i=Pl.parse(n.reviewedIntent);if(i.request.executionId!==t)continue;if(i.account.actorId!==e.actorId||i.account.teamId!==e.teamId||i.execution.projectId!==e.projectId)throw Error(`The retained Model save belongs to another creator or Project.`);let a=sr.parse(n.command??{...i.request,operationId:n.id});r.push({intent:i,command:a,operation:e.recoverOperation(n)})}if(!s.nextCursor)break;if(i.has(s.nextCursor))throw Error(`The retained Model save catalog repeated a cursor.`);i.add(s.nextCursor),a=s.nextCursor}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),_=d.original??g.data?.[0]??null,v=S({queryKey:[`decision-model-save-options`,i,h.data?.account.apiOrigin,n?.result?.contentHash],enabled:m&&h.isSuccess&&g.isSuccess&&!_&&!d.busy,retry:!1,queryFn:async({signal:n})=>{if(!h.data)throw Error(`Read the configured result account first.`);let r=h.data.account,i=new URLSearchParams({...r,...e.projectId?{projectId:e.projectId}:{}}),a=Fl.parse(await Y(e.connection,`/v1/training/decision-executions/${encodeURIComponent(t)}/model?${i}`,{signal:n}));if(J(a.account)!==J(r)||a.executionId!==t||a.projectId!==e.projectId)throw Error(`The Model targets differ from this exact result account or Project.`);return a}});async function y(n){f({original:n}),await n.operation.retainCommand(n.command,`dispatching`),p();let i=await Y(e.connection,`/v1/training/decision-executions/${encodeURIComponent(n.command.executionId)}/model`,{method:`POST`,body:JSON.stringify({...n.intent.account,projectId:n.intent.execution.projectId,intentHash:n.operation.intentHash,command:n.command})}),a=await qt(i,n.command);if(p(),a.actorId!==e.actorId||a.version.source.executionId!==t)throw Error(`The saved Model receipt belongs to another creator or Project.`);f({receipt:a});for(let e of[`saved-training-model`,`saved-model-serving`,`decision-model-save-options`,`unified-experiments`,`model-projects`])r.invalidateQueries({queryKey:[e]});return await n.operation.acknowledge(),p(),f({original:null}),await g.refetch(),p(),a}async function b(r){if(l.current.has(i))return null;l.current.add(i),f({busy:!0,error:null});try{if(p(),_)return await y(_);if(!g.isSuccess)throw Error(`Reload the original Model saves before continuing.`);if(!m||n?.result?.schemaVersion!==`openpond.decisionTrainingResult.v1`||!v.isSuccess||!h.isSuccess||!v.data)throw Error(`Read the completed Decision result and current Model targets before saving.`);let i=r.modelProjectId?v.data.models.find(e=>e.id===r.modelProjectId):null;if(r.modelProjectId&&!i)throw Error(`Refresh the Model targets before updating this Model.`);let{schemaVersion:a,request:o,sourceForm:s,result:c,resultRecordedAt:l,contentHash:u,...d}=n,f=Pl.parse({account:v.data.account,execution:Zt.parse(d),request:{teamId:e.teamId,executionId:t,resultHash:n.result.contentHash,artifactHash:n.result.artifact.contentHash,name:r.name,modelProjectId:i?.id??null,expectedModelRevision:i?.revision??0}}),b=await e.operation(Jb,f);return p(),await y({intent:f,operation:b,command:sr.parse({...f.request,operationId:b.id})})}catch(e){return a.current===i&&f({error:e}),null}finally{l.current.delete(i),f({busy:!1})}}return{save:b,busy:d.busy,receipt:d.receipt,original:_,options:v.data,freshReady:m&&g.isSuccess&&v.isSuccess&&h.isSuccess,recoveryReady:!!_||g.isSuccess,error:d.error??g.error??(m?v.error??h.error:null),refresh:()=>{g.refetch(),m&&!_&&(h.refetch(),h.data&&v.refetch())}}}function Xb({api:e,id:t,execution:n,disabled:r=!1}){let i=Yb(e,t,n),a=kv(),[o,s]=(0,Q.useState)(null),c=`${e.key}:${t}`,l=(0,Q.useRef)(c);l.current=c,(0,Q.useEffect)(()=>(l.current=c,()=>{l.current=``}),[c]);async function u(){let t=i.receipt;if(!(!t||i.busy||i.original||r))try{let n=Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:crypto.randomUUID(),operationType:`decision_model`,name:`${t.model.name} Decision experiment`,startingModel:await Sr(t.version,{teamId:e.teamId,label:`${t.model.name} / Saved decision adapter`}),decisionForm:await Pn(Qy(),t.version,{teamId:e.teamId})});l.current===c&&await a.openDraft(n,as(`experiments`,null,{projectId:e.projectId,executionLocation:`hosted`}))}catch(e){l.current===c&&s(e)}}let[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)((n?.name??`Decision Model`).slice(0,200)),[h,g]=(0,Q.useState)(``),_=i.original?.command,v=iy({name:`Decision Model save`,busy:i.busy,dirty:d&&(!!_||p!==(n?.name??`Decision Model`).slice(0,200)||!!h),discardDescription:_?`The original save remains recoverable from this execution after closing.`:void 0}),y=n?.method===`decision_model`&&n.phase===`completed`&&n.result?.schemaVersion===`openpond.decisionTrainingResult.v1`,b=!i.recoveryReady&&i.error!==null;if(!y&&!_&&!i.receipt&&!b)return null;let x=i.receipt?.version;return(0,$.jsxs)(`section`,{className:`training-detail-section`,"aria-label":`Save Decision Model`,children:[(0,$.jsx)(X,{error:o??i.error}),i.recoveryReady?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Reload retained Model saves`}),i.receipt&&x?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[`Saved to `,i.receipt.model?.name,`. Exact version `,(0,$.jsx)(`code`,{children:x.contentHash}),`.`]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact saved version`}),(0,$.jsx)(`pre`,{className:`saved-model-version-reference`,children:JSON.stringify(x,null,2)})]}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void wo(as(`models`)),children:`Open Models`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:r||i.busy||!!_,onClick:()=>void u(),children:`New experiment from saved module`})]}),(0,$.jsx)(hb,{connection:e.connection,version:x,api:e},`${e.key}:${x.contentHash}`)]}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:r||i.busy||!i.recoveryReady,onClick:()=>f(!0),children:_?`Recover Model save`:i.receipt?`Save model again`:`Save model`}),d?(0,$.jsxs)(qa,{ariaLabel:`Save Decision model`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:i.busy,onClose:()=>void v.requestLeave(()=>f(!1)),children:[(0,$.jsx)(`h2`,{children:`Save model`}),(0,$.jsx)(`p`,{children:`Save the exact trained decision adapter from this completed result. Saving does not activate serving.`}),(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),i.save({name:p,modelProjectId:h||null}).then(e=>{e&&(v.allowNextNavigation(),f(!1))})},children:[(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Save destination`}),(0,$.jsx)(Z,{label:`Model destination`,value:_?.modelProjectId??(_?``:h),options:[{value:``,label:`Create new Model`},...(i.options?.models??[]).map(e=>({value:e.id,label:e.name,description:`Current revision ${e.revision}`})),..._?.modelProjectId&&!i.options?.models.some(e=>e.id===_.modelProjectId)?[{value:_.modelProjectId,label:`Original selected Model`}]:[]],disabled:i.busy||!!_||!i.freshReady,onChange:e=>{g(e);let t=i.options?.models.find(t=>t.id===e);t&&m(t.name)}})]}),(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Model name`}),(0,$.jsx)(`input`,{"data-autofocus":!0,value:_?.name??p,maxLength:200,disabled:i.busy||!!_,onChange:e=>m(e.target.value)})]}),_?(0,$.jsx)(`p`,{children:`Original result, module, destination and revision are retained. Retry sends the same operation.`}):null,i.receipt&&_?(0,$.jsx)(`p`,{role:`status`,children:`The Model was saved. Local acknowledgement is pending; retry preserves its exact receipt.`}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:()=>void v.requestLeave(()=>f(!1)),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Refresh targets and recovery`}),(0,$.jsx)(`button`,{type:`submit`,className:`training-button`,disabled:i.busy||r||!i.recoveryReady||!_&&!i.freshReady,children:i.busy?`Saving…`:_?`Retry original save`:`Save model`})]})]})]}):null,v.dialog]})}function Zb({owner:e,api:t,onOpenBilling:n=null,billingReturnPending:r=!1,onRefreshFunding:i,disabled:a=!1}){let o=e.busy||a,s=e.execution,c=e.original,l=(e.receipt&&(!s||e.receipt.execution.id===s.id&&e.receipt.execution.revision>s.revision)?e.receipt.execution:s)??(c&&`execution`in c.intent?c.intent.execution:null),[u,d]=(0,Q.useState)(null),f=Tb(t,l?.plan.maximumSpendUsd??``,!!l,!!l?.plan.computePrice),p=c?`action`in c.command?c.command.action:`prepare`:null;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{error:e.error}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o||e.loading,onClick:e.refresh,children:`Refresh execution and recovery`}),c?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||!e.recoveryReady,onClick:()=>void e.retry(),children:o?`Reconciling…`:`Retry original ${p}`}):null]}),c&&!(`action`in c.command)?(0,$.jsxs)(ft,{title:`Original preparation`,children:[(0,$.jsxs)(`p`,{children:[c.command.name,` · `,c.command.method,` · `,Uy(c.command.maximumSpendUsd)]}),(0,$.jsxs)(`p`,{children:[c.command.mode,` · `,c.command.request.model.source.modelId,` ·`,` `,c.command.request.model.source.revision]})]}):null,l?(0,$.jsxs)(ft,{title:`Hosted execution`,children:[(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`State`}),(0,$.jsx)(`dd`,{children:l.phase}),(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(l.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:l.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Execution`}),(0,$.jsx)(`dd`,{children:l.id}),(0,$.jsx)(`dt`,{children:`Preparation expires`}),(0,$.jsx)(`dd`,{children:new Date(l.plan.expiresAt).toLocaleString()}),(0,$.jsx)(`dt`,{children:`Exact plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:l.plan.contentHash}),(0,$.jsx)(`dt`,{children:`Runtime`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:l.plan.runtimeHash})]}),s?(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[s.phase===`prepared`?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||e.loading||!e.ready||!e.canControl||!!c||Date.parse(s.plan.expiresAt)<=Date.now(),onClick:()=>d({action:`start`,value:s}),children:`Review Start`}):null,[`completed`,`cancelled`,`failed`].includes(s.phase)?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o||e.loading||!e.ready||!e.canControl||!!c,onClick:()=>d({action:`cancel`,value:s}),children:`Review Cancel`})]}):null]}):null,s?.phase===`completed`&&s.result?(0,$.jsx)(qb,{api:t,execution:s}):null,s?.result?(0,$.jsx)(Zy,{result:s.result}):l?.phase===`completed`?(0,$.jsx)(`p`,{children:`No result bytes are available in this read. Retained execution identity remains available for recovery.`}):null,e.selectedId?(0,$.jsx)(Xb,{api:t,id:e.selectedId,execution:s,disabled:o||!!c},`${t.key}:${e.selectedId}`):null,u&&s?(0,$.jsxs)(qa,{ariaLabel:u.action===`start`?`Start Decision experiment`:`Cancel Decision experiment`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:o,onClose:()=>{o||d(null)},children:[(0,$.jsx)(`h2`,{children:u.action===`start`?`Start Decision experiment`:`Cancel Decision experiment`}),(0,$.jsx)(`p`,{children:u.action===`start`?Gy(u.value.plan.computePrice):`Cancel this exact execution. In-flight work may need to stop and settle before capacity is released.`}),(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(u.value.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:u.value.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Mode`}),(0,$.jsx)(`dd`,{children:u.value.mode}),u.value.request.schemaVersion===`openpond.decisionTrainingRequest.v1`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Training steps`}),(0,$.jsx)(`dd`,{children:u.value.request.training.maxSteps}),(0,$.jsx)(`dt`,{children:`Reviewed batch`}),(0,$.jsxs)(`dd`,{children:[u.value.request.data.batch.id,` · release`,` `,u.value.request.data.batch.revision]})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Questions`}),(0,$.jsx)(`dd`,{children:u.value.request.input.questions.length})]}),(0,$.jsx)(`dt`,{children:`Model`}),(0,$.jsxs)(`dd`,{children:[u.value.request.model.source.modelId,` ·`,` `,u.value.request.model.source.revision]}),(0,$.jsx)(`dt`,{children:`Plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:u.value.plan.contentHash})]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact prepared Decision request`}),(0,$.jsx)(`pre`,{children:JSON.stringify(u.value.request,null,2)})]}),u.action===`start`?(0,$.jsx)(Db,{funding:f,busy:o,startAttempted:!!c,billingReturnPending:r,onOpenBilling:n,onRefresh:i??(async()=>{await f.refresh()})}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o,onClick:()=>d(null),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||e.loading||!!c||!e.ready||!e.canControl||u.action===`start`&&(r||!f.canStart||Date.parse(u.value.plan.expiresAt)<=Date.now()),onClick:()=>void e.control(u.action,u.value).then(e=>{e&&d(null)}),children:o?`Applying…`:u.action===`start`?Ky(u.value.plan.maximumSpendUsd):`Cancel execution`})]})]}):null]})}var Qb=(0,Q.lazy)(()=>o(()=>import(`./ExperimentTrainingDataWorkspace-WhwQ0QBi.js`),__vite__mapDeps([76,1,2,3,4,77,5,6,9,10,78,32,27,31,21,16,43,19,20,22,13,23,15,24,25,26,8,28,11,29,30,33,34,35,36,37,38,39,40,41,18,42,44,45,46,47,48,49,50,51,52,53,54,55,56,79,80])));function $b({api:e,visible:t,onClose:n,onSaveDraft:r}){let i=kv(),[a,o]=(0,Q.useState)(()=>i.initialExperiment?.decisionForm??Qy()),s=(0,Q.useRef)({train:Qy(`train`),score:Qy(`score`)}),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(!1),g=(0,Q.useRef)(null),_=(0,Q.useRef)(!1),v=(0,Q.useRef)(null),y=(0,Q.useRef)(!1),b=J([e.key,e.accountKey,e.actorId,e.teamId,e.projectId,e.connection.serverUrl,i.initialExperiment?.id]),x=(0,Q.useRef)(b);x.current=b,(0,Q.useEffect)(()=>(x.current=b,()=>{x.current=``}),[b]);function C(){if(x.current!==b)throw Error(`Return to this experiment's original account before continuing.`)}let w=Kb(e,{draftId:i.initialExperiment?.id??null,method:`decision_model`,visible:t}),T=Ry(e,t&&a.mode===`train`,a.mode===`train`?a.batch:null),E=tb(e,t),D=i.trainingBaseModel??a.baseModel,O=!i.startingModel||i.startingModel.source===`managed`||i.startingModel.source===`decision`,k=wv(i.startingModel),A=(0,Q.useRef)(k);(0,Q.useEffect)(()=>{A.current!==k&&i.startingModel?.source!==`decision`&&o(({startingDecision:e,...t})=>({...t,parentArtifact:null})),A.current=k},[k,i.startingModel?.source]);let j=D?.source===`managed`&&O?{teamId:e.teamId,source:D.source,modelId:D.modelId,...D.revision?{revision:D.revision}:{},...D.tokenizerRevision?{tokenizerRevision:D.tokenizerRevision}:{},...D.chatTemplateHash?{chatTemplateHash:D.chatTemplateHash}:{},...D.modelAssetId?{modelAssetId:D.modelAssetId}:{}}:null,M=S({queryKey:[`decision-execution-capability`,b,j],enabled:t&&!!(E.data&&j),retry:!1,staleTime:3e4,queryFn:({signal:e})=>{if(!E.data||!j)throw Error(`Choose an exact managed base before checking Decision availability.`);return E.data.capability(j,e)},refetchInterval:e=>!e.state.error&&6e4}),N=M.data&&!M.isError&&Date.parse(M.data.expiresAt)>Date.now()?M.data.execution:null,P=w.selectedId&&![`completed`,`failed`,`cancelled`].includes(w.execution?.phase??w.receipt?.execution.phase??`prepared`),F=c||w.busy,I=F||!!(w.original||P),L=J({...a,baseModel:D,sourceKey:k}),ee=(0,Q.useRef)(L);ee.current=L;let R=(0,Q.useRef)(L),z=Tb(e,a.maximumSpendUsd,t,!0),B=L!==R.current,V=i.reportOperationDraftDirty;(0,Q.useEffect)(()=>{V(`decision_model`,B)},[B,V]);let H=iy({name:`Decision experiment`,dirty:B||i.operationDraftDirty||i.evaluationDirty,busy:F,onLeave:n});My({...H,requestLeave:async e=>{f&&v.current?await v.current.requestLeave(()=>H.requestLeave(e)):await H.requestLeave(e)}},t);function U(e){o(t=>({...t,...e}))}function te(){if(!i.initialExperiment)throw Error(`Open an experiment before saving its settings.`);if(!O)throw Error(`Decision requires its exact managed base. Choose another starting model.`);return Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:i.initialExperiment.id,operationType:`decision_model`,name:a.name.trim()||`Decision experiment`,...i.startingModel?{startingModel:i.startingModel}:{},decisionForm:{...a,baseModel:D}})}async function ne(t){if(!r)throw Error(`Load canonical draft storage before preparing.`);await r(t),C();let n=await Iy(e).get(t.id);if(C(),n.status!==`draft`||n.projectId!==e.projectId||J(n.draft)!==J(t))throw Error(`The saved experiment changed. Reopen its exact current revision before continuing.`);return R.current=L,n}async function re(){if(!(y.current||I)){y.current=!0,l(!0),d(null);try{await ne(te())}catch(e){x.current===b&&d(e)}finally{y.current=!1,x.current===b&&l(!1)}}}async function W(){if(y.current||w.busy||w.original)return;y.current=!0,l(!0),d(null);let t=null;try{let n=window.openpond?.browser;if(!n?.openExternal){if(t=window.open(`about:blank`,`_blank`),!t)throw Error(`Allow a new tab to open Billing, then try again.`);t.opener=null}let r=await ne(te());C();let i=vt(a.maximumSpendUsd),o=await xb(e,{schemaVersion:`openpond.trainingFundingHandoffRequest.v1`,teamId:e.teamId,maximumSpendUsd:i===null?null:Number(i),draft:{id:r.id,revision:r.revision,contentHash:r.contentHash,projectId:r.projectId}});if(C(),!o.canPurchase||!o.billingUrl)throw Error(`A workspace billing owner needs to add credits for this experiment.`);if(g.current={record:r,snapshot:L},h(!0),n?.openExternal){let e=await n.openExternal({conversationId:`experiment-funding:${r.id}`,url:o.billingUrl});if(C(),!e.ok)throw Error(e.error??`Billing could not be opened. Your experiment is saved; try again.`)}else t&&=(t.location.replace(o.billingUrl),null)}catch(e){t?.close(),x.current===b&&(d(e),h(!1),g.current=null)}finally{y.current=!1,x.current===b&&l(!1)}}async function ie(){if(!(_.current||x.current!==b)){_.current=!0;try{let t=g.current;if(t){let n=await Iy(e).get(t.record.id);if(C(),n.contentHash!==t.record.contentHash||n.status!==`draft`||ee.current!==t.snapshot)throw Error(`This experiment changed while Billing was open. Your edits remain here; save and review them before preparing.`)}await z.refresh(),C()}catch(e){x.current===b&&d(e)}finally{_.current=!1,x.current===b&&(g.current=null,h(!1))}}}let G=(0,Q.useRef)(ie);G.current=ie,(0,Q.useEffect)(()=>{if(!m)return;let e=()=>{document.visibilityState===`visible`&&G.current()};return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[m]);async function ae(e){if(C(),I||!t)throw Error(`Return to the editable experiment before selecting data.`);if(Fe(e),e.purpose!==`supervised_training`||!e.sealedAt||!e.examples.length)throw Error(`Choose a sealed, reviewed supervised training batch.`);o(t=>t.mode===`train`?{...t,batch:xe(e)}:t),p(!1)}let K=T.batches.filter(e=>e.purpose===`supervised_training`&&e.sealedAt&&e.exampleCount>0),q=a.mode===`train`?a.batch:null,oe=q?J(q):``,se=K.find(e=>J(e.reference)===oe),ce=K.map(e=>({value:J(e.reference),label:`${e.reference.id} · release ${e.reference.revision} · ${e.exampleCount} examples`}));oe&&!ce.some(e=>e.value===oe)&&ce.unshift({value:oe,label:`${q.id} · saved release ${q.revision}`,disabled:!0});let le=i.startingModel?.source===`decision`?`decision:${i.startingModel.decision.versionHash}`:i.startingModel?.source===`trained`?`trained:${i.startingModel.trainedVersion.contentHash}`:i.startingModel?.source===`engram`?`engram:${i.startingModel.engram.versionHash}`:i.startingModel?.source===`steering`?`steering:${i.startingModel.steering.versionHash}`:i.startingModel?.source===`inference`?`inference:${i.startingModel.inferenceModelId}`:D?J(D):``,ue=_n(),de=[{value:J(ue),label:ue.modelId}];return le&&!de.some(e=>e.value===le)&&de.unshift({value:le,label:i.startingModel?.label??D?.modelId??`Saved starting model`,disabled:!0}),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{hidden:f,inert:f,children:(0,$.jsxs)(Bv,{label:`Experiment setup`,action:`experiment`,onRequestClose:()=>void H.requestLeave(n),children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`h2`,{children:`Run Experiment`}),(0,$.jsx)(`button`,{type:`button`,disabled:F,onClick:()=>void H.requestLeave(n),children:`Close setup`})]}),(0,$.jsx)(X,{error:u??(a.mode===`train`?T.error:null)??M.error??E.error}),(0,$.jsxs)(`form`,{noValidate:!0,onSubmit:e=>{e.preventDefault(),re()},children:[(0,$.jsx)(ft,{title:`Starting model`,children:(0,$.jsxs)(`fieldset`,{disabled:I,children:[(0,$.jsxs)(`label`,{children:[`Model`,(0,$.jsx)(Z,{label:`Decision starting model`,floating:!0,searchable:!0,value:le,options:de,onChange:e=>{if(e===le)return;let t=e===J(ue)?{preference:ue}:null;e&&!t?d(`Refresh the model list before changing this selection.`):(i.setTrainingBaseModel(t?.preference??null),o(({startingDecision:e,...t})=>({...t,parentArtifact:null})))}})]}),(0,$.jsx)(xy,{disabled:I}),(0,$.jsxs)(`label`,{children:[`Mode`,(0,$.jsx)(Z,{floating:!0,label:`Decision mode`,value:a.mode,options:[{value:`train`,label:`Train`},{value:`score`,label:`Score`}],onChange:e=>{if(e===`train`||e===`score`){s.current[a.mode]=a;let{startingDecision:t,...n}=s.current[e];o({...n,baseModel:D,parentArtifact:a.parentArtifact,...a.startingDecision?{startingDecision:a.startingDecision}:{},name:a.name,maximumSpendUsd:a.maximumSpendUsd})}}})]}),(0,$.jsx)(`p`,{children:`Train from reviewed examples or score unlabeled state against every allowed candidate using this exact Decision adapter.`}),a.mode===`train`?(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:F||T.isFetching,onClick:()=>void T.refetch(),children:`Refresh reviewed batches`}):null,N?(0,$.jsx)(`p`,{children:N.state===`unavailable`?N.reason:`A compatible Decision runtime is available. Preparation rechecks its exact identity.`}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:F||M.isFetching||!j,onClick:()=>{E.refetch(),M.refetch()},children:`Refresh runtime availability`})]})}),a.mode===`train`?(0,$.jsx)(ft,{title:`Training data`,children:(0,$.jsxs)(`fieldset`,{disabled:I,children:[(0,$.jsxs)(`label`,{children:[`Reviewed batch`,(0,$.jsx)(Z,{label:`Decision reviewed batch`,floating:!0,searchable:!0,value:oe,options:[{value:``,label:`Choose sealed supervised batch`},...ce],onChange:e=>{let t=K.find(t=>J(t.reference)===e);e&&!t?d(`Refresh the reviewed batch before changing this selection.`):o(e=>e.mode===`train`?{...e,batch:t?.reference??null}:e)}})]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>p(!0),children:`Import or review data`})]})}):null,(0,$.jsx)(ft,{title:`Settings`,children:(0,$.jsxs)(`fieldset`,{disabled:I,children:[(0,$.jsxs)(`label`,{children:[`Experiment name`,(0,$.jsx)(`input`,{value:a.name,maxLength:500,onChange:e=>U({name:e.target.value})})]}),a.mode===`train`?(0,$.jsx)(Xy,{form:a,onChange:o}):(0,$.jsx)(Yy,{form:a,onChange:o}),a.startingDecision?(0,$.jsxs)(`p`,{children:[`Saved Model `,a.startingDecision.modelProjectId,` · version`,` `,a.startingDecision.versionHash]}):null,a.parentArtifact?(0,$.jsxs)(`p`,{children:[`Continue adapter `,a.parentArtifact.id,` · `,a.parentArtifact.contentHash,`. Optimizer state starts fresh.`]}):null,(0,$.jsxs)(`label`,{children:[`Spending limit (USD, optional)`,(0,$.jsx)(`input`,{type:`text`,inputMode:`decimal`,maxLength:100,placeholder:`Use available credits`,value:a.maximumSpendUsd,onChange:e=>U({maximumSpendUsd:e.target.value})})]})]})}),(0,$.jsx)(Db,{funding:z,busy:F,startAttempted:!!w.original,billingReturnPending:m,onOpenBilling:r?W:null,onRefresh:ie}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`submit`,className:`training-button secondary`,disabled:I||!r,children:c?`Saving…`:`Save draft`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:I||m||!r||!w.ready||N?.state!==`ready`||a.mode===`train`&&(!T.isSuccess||!se),onClick:()=>{d(null);try{w.prepare(te(),ne)}catch(e){d(e)}},children:`Compile and prepare`})]})]}),(0,$.jsx)(Zb,{owner:w,api:e,disabled:F,onOpenBilling:r?W:null,billingReturnPending:m,onRefreshFunding:ie}),H.dialog]})}),f?(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`p`,{role:`status`,children:`Opening training data…`}),children:(0,$.jsx)(Qb,{api:e,method:`decision_model`,navigation:v,onClose:()=>p(!1),onUseBatch:ae,beforeImport:async()=>{if(C(),I)throw Error(`Finish the original operation before importing data.`);await ne(te()),C()}})}):null]})}var ex=[{key:`learningRate`,label:`Learning rate`,inputMode:`decimal`},{key:`weightDecay`,label:`Weight decay`,inputMode:`decimal`},{key:`gradientAccumulationSteps`,label:`Gradient accumulation steps`,inputMode:`numeric`},{key:`maxSequenceLength`,label:`Maximum sequence tokens`,inputMode:`numeric`},{key:`seed`,label:`Seed`,inputMode:`numeric`},{key:`maxDurationSeconds`,label:`Maximum training seconds`,inputMode:`decimal`},{key:`maxCheckpointBytes`,label:`Maximum checkpoint bytes`,inputMode:`numeric`}];function tx({training:e,configuration:t,disabled:n=!1,onChange:r}){function i(t,n){r({...e,[t]:n})}return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Training steps`}),(0,$.jsx)(`input`,{type:`text`,inputMode:`numeric`,value:e.maxSteps,disabled:n,maxLength:100,onChange:e=>i(`maxSteps`,e.target.value)})]}),(0,$.jsxs)(`details`,{className:`model-training-settings`,children:[(0,$.jsx)(`summary`,{children:`Advanced Engram settings`}),(0,$.jsx)(`p`,{children:`Train the memory adapter with batch size 1 and gradient clipping at 1. The base weights stay frozen.`}),(0,$.jsx)(`div`,{className:`taskset-draft-field-grid`,children:ex.map(t=>(0,$.jsxs)(`label`,{className:`labs-model-create-field`,children:[(0,$.jsx)(`span`,{children:t.label}),(0,$.jsx)(`input`,{type:`text`,inputMode:t.inputMode,value:e[t.key],disabled:n,maxLength:100,onChange:e=>i(t.key,e.target.value)})]},t.key))}),(0,$.jsx)(`p`,{children:`Step, duration and checkpoint limits are validated before training. Preparation reviews the separate spend cap.`}),t?(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Fixed memory architecture`}),(0,$.jsxs)(`dl`,{children:[(0,$.jsx)(`dt`,{children:`Injection layers`}),(0,$.jsx)(`dd`,{children:t.injectLayers.join(`, `)}),(0,$.jsx)(`dt`,{children:`N-gram orders`}),(0,$.jsxs)(`dd`,{children:[`Suffix `,t.suffixOrders.join(`, `),`; previous group`,` `,t.previousOrders.join(`, `)]}),(0,$.jsx)(`dt`,{children:`Memory tables`}),(0,$.jsxs)(`dd`,{children:[t.numHashes,` hashes · `,t.tableSize.toLocaleString(),` rows · `,t.perHashDim,` dimensions per hash`]}),(0,$.jsx)(`dt`,{children:`Adapter`}),(0,$.jsxs)(`dd`,{children:[`FP32 · alpha `,t.alpha]})]})]}):null]})]})}function nx(){let e=wn;return Un.parse({baseModel:null,batch:null,name:``,maximumSpendUsd:``,training:{learningRate:String(e.learningRate),weightDecay:String(e.weightDecay),maxSteps:String(e.maxSteps),gradientAccumulationSteps:String(e.gradientAccumulationSteps),maxSequenceLength:String(e.maxSequenceLength),seed:String(e.seed),maxDurationSeconds:String(e.maxDurationSeconds),maxCheckpointBytes:String(e.maxCheckpointBytes)},parentArtifact:null})}function rx(e,t){let n=ml.parse({teamId:e.teamId,actorId:e.actorId,apiOrigin:t}),r={...n,projectId:e.projectId},i=`/v1/training/engram-executions`;return{account:n,async capability(t,a){return Ot(await Y(e.connection,`${i}/capability`,{method:`POST`,signal:a,body:JSON.stringify({...r,capabilityQuery:t})}),t,n.actorId)},async compile(t){return pn(await Y(e.connection,`${i}/compile`,{method:`POST`,body:JSON.stringify({...r,command:t})}),t)},async mutate(t,a){let o=`action`in t?`${i}/${encodeURIComponent(t.id)}/${t.action}`:`${i}/prepare`,s=await Jt(await Y(e.connection,o,{method:`POST`,body:JSON.stringify({...r,intentHash:a,command:t})}),t);if(s.execution.ownerUserId!==n.actorId||s.execution.projectId!==e.projectId)throw Error(`The execution receipt belongs to another account or Project.`);return s},async get(t,r){let a=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}}),o=await dn(await Y(e.connection,`${i}/${encodeURIComponent(t)}?${a}`,{signal:r}),{teamId:e.teamId,id:t,ownerUserId:n.actorId});if(o.projectId!==e.projectId)throw Error(`The execution belongs to another Project.`);return o},async list(t={},r){let a={...t,...e.projectId?{projectId:e.projectId}:{}},o=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}});for(let[e,t]of Object.entries(a))t!==void 0&&o.set(e,String(t));return mn(await Y(e.connection,`${i}?${o}`,{signal:r}),{teamId:e.teamId,ownerUserId:n.actorId,query:a})}}}function ix(e,t=!0){return S({queryKey:[`engram-experiment-account`,e.key,e.actorId],enabled:t&&e.location===`hosted`&&!!e.actorId,retry:!1,queryFn:async({signal:t})=>{let n=await e.request(`inventory`,{},t);if(n.teamId!==e.teamId)throw Error(`The workspace account changed.`);return rx(e,n.apiOrigin)}})}var ax=[`training:prepare-engram`,`training:start-engram`,`training:cancel-engram`];function ox(e,t){let n=u(),r=J([e.key,e.accountKey,e.actorId,e.teamId,e.projectId,e.connection.serverUrl,t.draftId,t.executionId,t.method]),i=(0,Q.useRef)(r);i.current=r,(0,Q.useEffect)(()=>(i.current=r,()=>{i.current=``}),[r]);let a=()=>({identity:r,busy:!1,error:null,receipt:null,selected:null,original:null,preparationOperationId:null}),[o,s]=(0,Q.useState)(a),c=(0,Q.useRef)(new Set),l=o.identity===r?o:a();function d(e){i.current===r&&s(t=>({...t.identity===r?t:a(),...e}))}function f(){if(i.current!==r)throw Error(`Return to this experiment's original account before continuing.`)}let p=ix(e,t.visible),m=p.data,h=S({queryKey:[`engram-experiment-recovery`,r],enabled:t.visible&&e.location===`hosted`&&!!e.actorId&&!l.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[];for(let i of ax){let a,o=new Set;for(let s=0;;s++){if(s>=100)throw Error(`The retained execution catalog exceeds its supported bound.`);let c=await e.pendingOperations(i,a,n);for(let n of c.items){let a=i===ax[0]?Sl.parse(n.reviewedIntent):Cl.parse(n.reviewedIntent);if(a.account.actorId!==e.actorId||a.account.teamId!==e.teamId)throw Error(`The retained execution belongs to another account.`);if(!(t.draftId===null?`execution`in a&&a.execution.id===t.executionId:a.draftId===t.draftId))continue;let o=i===ax[0]?Vn.parse(n.command??{...a.request,operationId:n.id}):Wt(n.command??{...a.request,operationId:n.id});r.push({intent:a,command:o,operation:e.recoverOperation(n)})}if(!c.nextCursor)break;if(o.has(c.nextCursor))throw Error(`The retained execution catalog repeated a cursor.`);o.add(c.nextCursor),a=c.nextCursor}}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),g=l.original??h.data?.[0]??null,_=t.executionId??l.selected??l.receipt?.execution.id??(g&&`execution`in g.intent?g.intent.execution.id:null),v=S({queryKey:[`managed-engram-execution`,r,_],enabled:t.visible&&!!(m&&_),retry:!1,queryFn:({signal:e})=>{if(!m||!_)throw Error(`Select an execution first.`);return m.get(_,e)},refetchInterval:e=>e.state.error?!1:e.state.data&&![`completed`,`failed`,`cancelled`].includes(e.state.data.phase)?3e3:!1});async function y(t){let r=rx(e,t.intent.account.apiOrigin);if(J(r.account)!==J(t.intent.account))throw Error(`Return to this execution's original account before retrying.`);d({original:t}),await t.operation.retainCommand(t.command,`dispatching`),f();let i=await r.mutate(t.command,t.operation.intentHash);return f(),d({receipt:i,selected:i.execution.id,preparationOperationId:`action`in t.command?`preparationOperationId`in t.intent?t.intent.preparationOperationId:null:t.command.operationId}),await t.operation.acknowledge(),f(),d({original:null}),await h.refetch(),f(),n.invalidateQueries({queryKey:[`managed-engram-execution`]}),n.invalidateQueries({queryKey:[`unified-experiments`]}),i}async function b(e){if(!c.current.has(r)){c.current.add(r),d({busy:!0,error:null});try{return f(),await e()}catch(e){return i.current===r&&d({error:e}),null}finally{c.current.delete(r),d({busy:!1})}}}async function x(n,r){return b(async()=>{if(g)return y(g);if(!m||!h.isSuccess||!t.draftId||n.id!==t.draftId||!n.engramForm||!t.method)throw Error(`Load this saved experiment and original requests before preparing.`);let i=vt(n.engramForm.maximumSpendUsd);await r(n),f();let a=await Iy(e).get(n.id);if(f(),a.status!==`draft`||a.projectId!==e.projectId||J(a.draft)!==J(n))throw Error(`The saved experiment changed. Reopen its exact current revision before preparing.`);let o=n.engramForm.baseModel;if(!o||o.source!==`managed`||n.startingModel&&![`managed`,`engram`].includes(n.startingModel.source))throw Error(`Choose a qualified exact Engram starting model.`);let s={teamId:e.teamId,modelId:o.modelId,source:o.source,...o.revision?{revision:o.revision}:{},...o.tokenizerRevision?{tokenizerRevision:o.tokenizerRevision}:{},...o.chatTemplateHash?{chatTemplateHash:o.chatTemplateHash}:{},...o.modelAssetId?{modelAssetId:o.modelAssetId}:{}},c={teamId:e.teamId,projectId:e.projectId,method:t.method,query:s,form:n.engramForm},l=await m.compile(c);if(f(),l.actorId!==e.actorId||l.formHash!==await zr(n.engramForm))throw Error(`The compilation differs from this exact saved form.`);let u=await ht({teamId:e.teamId,projectId:e.projectId,operationId:crypto.randomUUID(),name:n.name,method:t.method,query:s,request:l.request,sourceForm:n.engramForm,maximumSpendUsd:i}),{operationId:d,...p}=u,_=Sl.parse({account:m.account,draftId:n.id,request:p}),v=await e.operation(ax[0],_);return f(),y({intent:_,operation:v,command:{...u,operationId:v.id}})})}async function C(n,r){return b(async()=>{if(g)return y(g);let i=r??v.data;if(!m||!h.isSuccess||!i||v.error)throw Error(`Read the exact execution before reviewing its next action.`);let{schemaVersion:a,request:o,sourceForm:s,result:c,resultRecordedAt:u,contentHash:d,...p}=i,_=xt.parse(p),b=n===`start`?{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n,approvedMaximumSpendUsd:i.plan.maximumSpendUsd,...i.plan.computePrice?{approvedPriceHash:await zr(i.plan.computePrice)}:{}}:{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n},x=Cl.parse({account:m.account,draftId:l.preparationOperationId?t.draftId:null,preparationOperationId:l.preparationOperationId,execution:_,request:b}),S=await e.operation(n===`start`?ax[1]:ax[2],x);return f(),y({intent:x,operation:S,command:Wt({...b,operationId:S.id})})})}return{prepare:x,control:C,retry:()=>b(()=>{if(!g)throw Error(`Reload the original execution request.`);return y(g)}),busy:l.busy,receipt:l.receipt,original:g,execution:v.data,ready:p.isSuccess&&h.isSuccess,recoveryReady:!!g||h.isSuccess,canControl:v.isSuccess&&!v.error,error:l.error??p.error??h.error??v.error,refresh:()=>{p.refetch(),e.actorId&&h.refetch(),m&&_&&v.refetch()},loading:v.isFetching||p.isFetching,selectedId:_}}var sx=`training-engram-result-save`;function cx(e,t,n){let r=u(),i=J([e.key,ra(e.connection),t]),a=(0,Q.useRef)(i);a.current=i,(0,Q.useEffect)(()=>(a.current=i,()=>{a.current=``}),[i]);let o=()=>({identity:i,busy:!1,error:null,original:null,receipt:null}),[s,c]=(0,Q.useState)(o),l=(0,Q.useRef)(new Set),d=s.identity===i?s:o();function f(e){a.current===i&&c(t=>({...t.identity===i?t:o(),...e}))}function p(){if(a.current!==i)throw Error(`Return to this Model save's original account and result.`)}let m=n?.method===`engram_adapter`&&n.phase===`completed`&&n.result!==null,h=ix(e,m),g=S({queryKey:[`engram-model-save-recovery`,i],enabled:!!e.actorId&&!d.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[],i=new Set,a;for(let o=0;;o++){if(o>=100)throw Error(`The retained Model save catalog exceeds its supported bound.`);let s=await e.pendingOperations(sx,a,n);for(let n of s.items){let i=Dl.parse(n.reviewedIntent);if(i.request.executionId!==t)continue;if(i.account.actorId!==e.actorId||i.account.teamId!==e.teamId||i.execution.projectId!==e.projectId)throw Error(`The retained Model save belongs to another creator or Project.`);let a=jn.parse(n.command??{...i.request,operationId:n.id});r.push({intent:i,command:a,operation:e.recoverOperation(n)})}if(!s.nextCursor)break;if(i.has(s.nextCursor))throw Error(`The retained Model save catalog repeated a cursor.`);i.add(s.nextCursor),a=s.nextCursor}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),_=d.original??g.data?.[0]??null,v=S({queryKey:[`engram-model-save-options`,i,h.data?.account.apiOrigin,n?.result?.contentHash],enabled:m&&h.isSuccess&&g.isSuccess&&!_&&!d.busy,retry:!1,queryFn:async({signal:n})=>{if(!h.data)throw Error(`Read the configured result account first.`);let r=h.data.account,i=new URLSearchParams({...r,...e.projectId?{projectId:e.projectId}:{}}),a=Ol.parse(await Y(e.connection,`/v1/training/engram-executions/${encodeURIComponent(t)}/model?${i}`,{signal:n}));if(J(a.account)!==J(r)||a.executionId!==t||a.projectId!==e.projectId)throw Error(`The Model targets differ from this exact result account or Project.`);return a}});async function y(n){f({original:n}),await n.operation.retainCommand(n.command,`dispatching`),p();let i=await Y(e.connection,`/v1/training/engram-executions/${encodeURIComponent(n.command.executionId)}/model`,{method:`POST`,body:JSON.stringify({...n.intent.account,projectId:n.intent.execution.projectId,intentHash:n.operation.intentHash,command:n.command})}),a=await Bt(i,n.command);if(p(),a.actorId!==e.actorId||a.version.source.executionId!==t)throw Error(`The saved Model receipt belongs to another creator or Project.`);f({receipt:a});for(let e of[`saved-training-model`,`saved-model-serving`,`engram-model-save-options`,`unified-experiments`,`model-projects`])r.invalidateQueries({queryKey:[e]});return await n.operation.acknowledge(),p(),f({original:null}),await g.refetch(),p(),a}async function b(r){if(l.current.has(i))return null;l.current.add(i),f({busy:!0,error:null});try{if(p(),_)return await y(_);if(!g.isSuccess)throw Error(`Reload the original Model saves before continuing.`);if(!m||!n?.result||!v.isSuccess||!h.isSuccess||!v.data)throw Error(`Read the completed Engram result and current Model targets before saving.`);let i=r.modelProjectId?v.data.models.find(e=>e.id===r.modelProjectId):null;if(r.modelProjectId&&!i)throw Error(`Refresh the Model targets before updating this Model.`);let{schemaVersion:a,request:o,sourceForm:s,result:c,resultRecordedAt:l,contentHash:u,...d}=n,f=Dl.parse({account:v.data.account,execution:xt.parse(d),request:{teamId:e.teamId,executionId:t,resultHash:n.result.contentHash,artifactHash:n.result.artifact.contentHash,name:r.name,modelProjectId:i?.id??null,expectedModelRevision:i?.revision??0}}),b=await e.operation(sx,f);return p(),await y({intent:f,operation:b,command:jn.parse({...f.request,operationId:b.id})})}catch(e){return a.current===i&&f({error:e}),null}finally{l.current.delete(i),f({busy:!1})}}return{save:b,busy:d.busy,receipt:d.receipt,original:_,options:v.data,freshReady:m&&g.isSuccess&&v.isSuccess&&h.isSuccess,recoveryReady:!!_||g.isSuccess,error:d.error??g.error??(m?v.error??h.error:null),refresh:()=>{g.refetch(),m&&!_&&(h.refetch(),h.data&&v.refetch())}}}function lx({api:e,id:t,execution:n,disabled:r=!1}){let i=cx(e,t,n),a=kv(),[o,s]=(0,Q.useState)(null),c=`${e.key}:${t}`,l=(0,Q.useRef)(c);l.current=c,(0,Q.useEffect)(()=>(l.current=c,()=>{l.current=``}),[c]);async function u(){let t=i.receipt;if(!(!t||i.busy||i.original||r))try{let n=Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:crypto.randomUUID(),operationType:`engram_adapter`,name:`${t.model.name} Engram experiment`,startingModel:await $t(t.version,{teamId:e.teamId,label:`${t.model.name} / Saved memory module`}),engramForm:await gr(nx(),t.version,{teamId:e.teamId})});l.current===c&&await a.openDraft(n,as(`experiments`,null,{projectId:e.projectId,executionLocation:`hosted`}))}catch(e){l.current===c&&s(e)}}let[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)((n?.name??`Engram Model`).slice(0,200)),[h,g]=(0,Q.useState)(``),_=i.original?.command,v=iy({name:`Engram Model save`,busy:i.busy,dirty:d&&(!!_||p!==(n?.name??`Engram Model`).slice(0,200)||!!h),discardDescription:_?`The original save remains recoverable from this execution after closing.`:void 0}),y=n?.method===`engram_adapter`&&n.phase===`completed`&&n.result!==null,b=!i.recoveryReady&&i.error!==null;if(!y&&!_&&!i.receipt&&!b)return null;let x=i.receipt?.version;return(0,$.jsxs)(`section`,{className:`training-detail-section`,"aria-label":`Save Engram Model`,children:[(0,$.jsx)(X,{error:o??i.error}),i.recoveryReady?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Reload retained Model saves`}),i.receipt&&x?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[`Saved to `,i.receipt.model?.name,`. Exact version `,(0,$.jsx)(`code`,{children:x.contentHash}),`.`]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact saved version`}),(0,$.jsx)(`pre`,{className:`saved-model-version-reference`,children:JSON.stringify(x,null,2)})]}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void wo(as(`models`)),children:`Open Models`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:r||i.busy||!!_,onClick:()=>void u(),children:`New experiment from saved module`})]}),(0,$.jsx)(hb,{connection:e.connection,version:x,api:e},`${e.key}:${x.contentHash}`)]}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:r||i.busy||!i.recoveryReady,onClick:()=>f(!0),children:_?`Recover Model save`:i.receipt?`Save model again`:`Save model`}),d?(0,$.jsxs)(qa,{ariaLabel:`Save Engram model`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:i.busy,onClose:()=>void v.requestLeave(()=>f(!1)),children:[(0,$.jsx)(`h2`,{children:`Save model`}),(0,$.jsx)(`p`,{children:`Save the exact trained memory module from this completed result. Saving does not activate serving.`}),(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),i.save({name:p,modelProjectId:h||null}).then(e=>{e&&(v.allowNextNavigation(),f(!1))})},children:[(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Save destination`}),(0,$.jsx)(Z,{label:`Model destination`,value:_?.modelProjectId??(_?``:h),options:[{value:``,label:`Create new Model`},...(i.options?.models??[]).map(e=>({value:e.id,label:e.name,description:`Current revision ${e.revision}`})),..._?.modelProjectId&&!i.options?.models.some(e=>e.id===_.modelProjectId)?[{value:_.modelProjectId,label:`Original selected Model`}]:[]],disabled:i.busy||!!_||!i.freshReady,onChange:e=>{g(e);let t=i.options?.models.find(t=>t.id===e);t&&m(t.name)}})]}),(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Model name`}),(0,$.jsx)(`input`,{"data-autofocus":!0,value:_?.name??p,maxLength:200,disabled:i.busy||!!_,onChange:e=>m(e.target.value)})]}),_?(0,$.jsx)(`p`,{children:`Original result, module, destination and revision are retained. Retry sends the same operation.`}):null,i.receipt&&_?(0,$.jsx)(`p`,{role:`status`,children:`The Model was saved. Local acknowledgement is pending; retry preserves its exact receipt.`}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:()=>void v.requestLeave(()=>f(!1)),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Refresh targets and recovery`}),(0,$.jsx)(`button`,{type:`submit`,className:`training-button`,disabled:i.busy||r||!i.recoveryReady||!_&&!i.freshReady,children:i.busy?`Saving…`:_?`Retry original save`:`Save model`})]})]})]}):null,v.dialog]})}function ux({result:e}){let t=e.artifact,n=t.manifest;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ft,{title:`Training result`,children:(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Optimizer steps`}),(0,$.jsx)(`dd`,{children:e.optimizerSteps}),(0,$.jsx)(`dt`,{children:`Examples processed`}),(0,$.jsx)(`dd`,{children:e.examplesProcessed}),(0,$.jsx)(`dt`,{children:`Target tokens`}),(0,$.jsx)(`dd`,{children:e.targetTokens}),(0,$.jsx)(`dt`,{children:`Forward token work`}),(0,$.jsx)(`dd`,{children:e.forwardTokenWork}),(0,$.jsx)(`dt`,{children:`Mean loss`}),(0,$.jsx)(`dd`,{children:e.meanLoss}),(0,$.jsx)(`dt`,{children:`Final loss`}),(0,$.jsx)(`dd`,{children:e.finalLoss}),(0,$.jsx)(`dt`,{children:`Training duration`}),(0,$.jsxs)(`dd`,{children:[(e.durationMs/1e3).toLocaleString(),` seconds`]}),(0,$.jsx)(`dt`,{children:`Base optimizer parameters`}),(0,$.jsx)(`dd`,{children:e.baseOptimizerParameterCount}),(0,$.jsx)(`dt`,{children:`Base gradient parameters`}),(0,$.jsx)(`dd`,{children:e.baseGradientParameterCount}),(0,$.jsx)(`dt`,{children:`Frozen base before`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.baseWeightsHashBefore}),(0,$.jsx)(`dt`,{children:`Frozen base after`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.baseWeightsHashAfter}),(0,$.jsx)(`dt`,{children:`Result`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.contentHash})]})}),(0,$.jsxs)(ft,{title:`Memory module`,children:[(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Artifact`}),(0,$.jsx)(`dd`,{children:t.id}),(0,$.jsx)(`dt`,{children:`Manifest`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:t.contentHash}),(0,$.jsx)(`dt`,{children:`Runtime`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:n.pins.runtimeHash}),(0,$.jsx)(`dt`,{children:`Reviewed batch`}),(0,$.jsxs)(`dd`,{children:[n.pins.data.batch.id,` · release `,n.pins.data.batch.revision]}),(0,$.jsx)(`dt`,{children:`Parent adapter`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:n.pins.parentArtifactHash??`Fresh adapter`})]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Committed module files`}),(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`File`}),(0,$.jsx)(`th`,{children:`Bytes`}),(0,$.jsx)(`th`,{children:`SHA-256`})]})}),(0,$.jsx)(`tbody`,{children:t.files.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.path}),(0,$.jsx)(`td`,{children:e.sizeBytes.toLocaleString()}),(0,$.jsx)(`td`,{className:`saved-model-version-reference`,children:e.sha256})]},e.path))})]})]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Saved adapter tensors`}),(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Tensor`}),(0,$.jsx)(`th`,{children:`Shape`}),(0,$.jsx)(`th`,{children:`Type`})]})}),(0,$.jsx)(`tbody`,{children:n.payload.tensors.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.name}),(0,$.jsx)(`td`,{children:e.shape.join(` × `)}),(0,$.jsx)(`td`,{children:e.dtype})]},e.name))})]})]})]})]})}function dx({owner:e,api:t,onOpenBilling:n=null,billingReturnPending:r=!1,onRefreshFunding:i,disabled:a=!1}){let o=e.busy||a,s=e.execution,c=e.original,l=(e.receipt&&(!s||e.receipt.execution.id===s.id&&e.receipt.execution.revision>s.revision)?e.receipt.execution:s)??(c&&`execution`in c.intent?c.intent.execution:null),[u,d]=(0,Q.useState)(null),f=Tb(t,l?.plan.maximumSpendUsd??``,!!l,!!l?.plan.computePrice),p=c?`action`in c.command?c.command.action:`prepare`:null;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{error:e.error}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o||e.loading,onClick:e.refresh,children:`Refresh execution and recovery`}),c?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||!e.recoveryReady,onClick:()=>void e.retry(),children:o?`Reconciling…`:`Retry original ${p}`}):null]}),c&&!(`action`in c.command)?(0,$.jsxs)(ft,{title:`Original preparation`,children:[(0,$.jsxs)(`p`,{children:[c.command.name,` · `,c.command.method,` · `,Uy(c.command.maximumSpendUsd)]}),(0,$.jsxs)(`p`,{children:[c.command.request.training.maxSteps,` training steps ·`,` `,`batch `,c.command.request.data.batch.id,` ·`,` `,c.command.request.model.modelId,` · `,c.command.request.model.revision]})]}):null,l?(0,$.jsxs)(ft,{title:`Hosted execution`,children:[(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`State`}),(0,$.jsx)(`dd`,{children:l.phase}),(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(l.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:l.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Execution`}),(0,$.jsx)(`dd`,{children:l.id}),(0,$.jsx)(`dt`,{children:`Preparation expires`}),(0,$.jsx)(`dd`,{children:new Date(l.plan.expiresAt).toLocaleString()}),(0,$.jsx)(`dt`,{children:`Exact plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:l.plan.contentHash}),(0,$.jsx)(`dt`,{children:`Runtime`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:l.plan.runtimeHash})]}),s?(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[s.phase===`prepared`?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||e.loading||!e.ready||!e.canControl||!!c||Date.parse(s.plan.expiresAt)<=Date.now(),onClick:()=>d({action:`start`,value:s}),children:`Review Start`}):null,[`completed`,`cancelled`,`failed`].includes(s.phase)?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o||e.loading||!e.ready||!e.canControl||!!c,onClick:()=>d({action:`cancel`,value:s}),children:`Review Cancel`})]}):null]}):null,s?.result?(0,$.jsx)(ux,{result:s.result}):l?.phase===`completed`?(0,$.jsx)(`p`,{children:`No result bytes are available in this read. Retained execution identity remains available for recovery.`}):null,e.selectedId?(0,$.jsx)(lx,{api:t,id:e.selectedId,execution:s,disabled:o||!!c},`${t.key}:${e.selectedId}`):null,u&&s?(0,$.jsxs)(qa,{ariaLabel:u.action===`start`?`Start Engram experiment`:`Cancel Engram experiment`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:o,onClose:()=>{o||d(null)},children:[(0,$.jsx)(`h2`,{children:u.action===`start`?`Start Engram experiment`:`Cancel Engram experiment`}),(0,$.jsx)(`p`,{children:u.action===`start`?Gy(u.value.plan.computePrice):`Cancel this exact execution. In-flight work may need to stop and settle before capacity is released.`}),(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(u.value.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:u.value.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Training steps`}),(0,$.jsx)(`dd`,{children:u.value.request.training.maxSteps}),(0,$.jsx)(`dt`,{children:`Reviewed batch`}),(0,$.jsxs)(`dd`,{children:[u.value.request.data.batch.id,` · release `,u.value.request.data.batch.revision]}),(0,$.jsx)(`dt`,{children:`Maximum duration`}),(0,$.jsxs)(`dd`,{children:[u.value.request.training.maxDurationSeconds,` seconds`]}),(0,$.jsx)(`dt`,{children:`Model`}),(0,$.jsxs)(`dd`,{children:[u.value.request.model.modelId,` · `,u.value.request.model.revision]}),(0,$.jsx)(`dt`,{children:`Plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:u.value.plan.contentHash})]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact prepared training request`}),(0,$.jsx)(`pre`,{children:JSON.stringify(u.value.request,null,2)})]}),u.action===`start`?(0,$.jsx)(Db,{funding:f,busy:o,startAttempted:!!c,billingReturnPending:r,onOpenBilling:n,onRefresh:i??(async()=>{await f.refresh()})}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o,onClick:()=>d(null),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||e.loading||!!c||!e.ready||!e.canControl||u.action===`start`&&(r||!f.canStart||Date.parse(u.value.plan.expiresAt)<=Date.now()),onClick:()=>void e.control(u.action,u.value).then(e=>{e&&d(null)}),children:o?`Applying…`:u.action===`start`?Ky(u.value.plan.maximumSpendUsd):`Cancel execution`})]})]}):null]})}var fx=(0,Q.lazy)(()=>o(()=>import(`./ExperimentTrainingDataWorkspace-WhwQ0QBi.js`),__vite__mapDeps([76,1,2,3,4,77,5,6,9,10,78,32,27,31,21,16,43,19,20,22,13,23,15,24,25,26,8,28,11,29,30,33,34,35,36,37,38,39,40,41,18,42,44,45,46,47,48,49,50,51,52,53,54,55,56,79,80])));function px({api:e,visible:t,onClose:n,onSaveDraft:r}){let i=kv(),[a,o]=(0,Q.useState)(()=>i.initialExperiment?.engramForm??nx()),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(!1),h=(0,Q.useRef)(null),g=(0,Q.useRef)(!1),_=(0,Q.useRef)(null),v=(0,Q.useRef)(!1),y=J([e.key,e.accountKey,e.actorId,e.teamId,e.projectId,e.connection.serverUrl,i.initialExperiment?.id]),b=(0,Q.useRef)(y);b.current=y,(0,Q.useEffect)(()=>(b.current=y,()=>{b.current=``}),[y]);function x(){if(b.current!==y)throw Error(`Return to this experiment's original account before continuing.`)}let C=ox(e,{draftId:i.initialExperiment?.id??null,method:`engram_adapter`,visible:t}),w=Ry(e,t,a.batch),T=ix(e,t),E=i.trainingBaseModel,D=!i.startingModel||i.startingModel.source===`managed`||i.startingModel.source===`engram`,O=wv(i.startingModel),k=(0,Q.useRef)(O);(0,Q.useEffect)(()=>{k.current!==O&&i.startingModel?.source!==`engram`&&o(({startingModule:e,...t})=>({...t,parentArtifact:null})),k.current=O},[O,i.startingModel?.source]);let A=E?.source===`managed`&&D?{teamId:e.teamId,source:E.source,modelId:E.modelId,...E.revision?{revision:E.revision}:{},...E.tokenizerRevision?{tokenizerRevision:E.tokenizerRevision}:{},...E.chatTemplateHash?{chatTemplateHash:E.chatTemplateHash}:{},...E.modelAssetId?{modelAssetId:E.modelAssetId}:{}}:null,j=S({queryKey:[`engram-execution-capability`,y,A],enabled:t&&!!(T.data&&A),retry:!1,staleTime:3e4,queryFn:({signal:e})=>{if(!T.data||!A)throw Error(`Choose an exact managed base before checking Engram availability.`);return T.data.capability(A,e)},refetchInterval:e=>!e.state.error&&6e4}),M=j.data&&!j.isError&&Date.parse(j.data.expiresAt)>Date.now()?j.data.execution:null,N=C.selectedId&&![`completed`,`failed`,`cancelled`].includes(C.execution?.phase??C.receipt?.execution.phase??`prepared`),P=s||C.busy,F=P||!!(C.original||N),I=J({...a,baseModel:E,sourceKey:O}),L=(0,Q.useRef)(I);L.current=I;let ee=(0,Q.useRef)(I),R=Tb(e,a.maximumSpendUsd,t,!0),z=I!==ee.current,B=i.reportOperationDraftDirty;(0,Q.useEffect)(()=>{B(`engram_adapter`,z)},[z,B]);let V=iy({name:`Engram experiment`,dirty:z||i.operationDraftDirty||i.evaluationDirty,busy:P,onLeave:n});My({...V,requestLeave:async e=>{d&&_.current?await _.current.requestLeave(()=>V.requestLeave(e)):await V.requestLeave(e)}},t);function H(e){o(t=>({...t,...e}))}function U(){if(!i.initialExperiment)throw Error(`Open an experiment before saving its settings.`);if(!D)throw Error(`Engram requires its exact managed base. Choose another starting model.`);return Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:i.initialExperiment.id,operationType:`engram_adapter`,name:a.name.trim()||`Engram experiment`,...i.startingModel?{startingModel:i.startingModel}:{},engramForm:{...a,baseModel:E}})}async function te(t){if(!r)throw Error(`Load canonical draft storage before preparing.`);await r(t),x();let n=await Iy(e).get(t.id);if(x(),n.status!==`draft`||n.projectId!==e.projectId||J(n.draft)!==J(t))throw Error(`The saved experiment changed. Reopen its exact current revision before continuing.`);return ee.current=I,n}async function ne(){if(!(v.current||F)){v.current=!0,c(!0),u(null);try{await te(U())}catch(e){b.current===y&&u(e)}finally{v.current=!1,b.current===y&&c(!1)}}}async function re(){if(v.current||C.busy||C.original)return;v.current=!0,c(!0),u(null);let t=null;try{let n=window.openpond?.browser;if(!n?.openExternal){if(t=window.open(`about:blank`,`_blank`),!t)throw Error(`Allow a new tab to open Billing, then try again.`);t.opener=null}let r=await te(U());x();let i=vt(a.maximumSpendUsd),o=await xb(e,{schemaVersion:`openpond.trainingFundingHandoffRequest.v1`,teamId:e.teamId,maximumSpendUsd:i===null?null:Number(i),draft:{id:r.id,revision:r.revision,contentHash:r.contentHash,projectId:r.projectId}});if(x(),!o.canPurchase||!o.billingUrl)throw Error(`A workspace billing owner needs to add credits for this experiment.`);if(h.current={record:r,snapshot:I},m(!0),n?.openExternal){let e=await n.openExternal({conversationId:`experiment-funding:${r.id}`,url:o.billingUrl});if(x(),!e.ok)throw Error(e.error??`Billing could not be opened. Your experiment is saved; try again.`)}else t&&=(t.location.replace(o.billingUrl),null)}catch(e){t?.close(),b.current===y&&(u(e),m(!1),h.current=null)}finally{v.current=!1,b.current===y&&c(!1)}}async function W(){if(!(g.current||b.current!==y)){g.current=!0;try{let t=h.current;if(t){let n=await Iy(e).get(t.record.id);if(x(),n.contentHash!==t.record.contentHash||n.status!==`draft`||L.current!==t.snapshot)throw Error(`This experiment changed while Billing was open. Your edits remain here; save and review them before preparing.`)}await R.refresh(),x()}catch(e){b.current===y&&u(e)}finally{g.current=!1,b.current===y&&(h.current=null,m(!1))}}}let ie=(0,Q.useRef)(W);ie.current=W,(0,Q.useEffect)(()=>{if(!p)return;let e=()=>{document.visibilityState===`visible`&&ie.current()};return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[p]);async function G(e){if(x(),F||!t)throw Error(`Return to the editable experiment before selecting data.`);if(Fe(e),e.purpose!==`supervised_training`||!e.sealedAt||!e.examples.length)throw Error(`Choose a sealed, reviewed supervised training batch.`);H({batch:xe(e)}),f(!1)}let ae=w.batches.filter(e=>e.purpose===`supervised_training`&&e.sealedAt&&e.exampleCount>0),K=a.batch?J(a.batch):``,q=ae.find(e=>J(e.reference)===K),oe=ae.map(e=>({value:J(e.reference),label:`${e.reference.id} · release ${e.reference.revision} · ${e.exampleCount} examples`}));K&&!oe.some(e=>e.value===K)&&oe.unshift({value:K,label:`${a.batch.id} · saved release ${a.batch.revision}`,disabled:!0});let se=i.startingModel?.source===`trained`?`trained:${i.startingModel.trainedVersion.contentHash}`:i.startingModel?.source===`engram`?`engram:${i.startingModel.engram.versionHash}`:i.startingModel?.source===`steering`?`steering:${i.startingModel.steering.versionHash}`:i.startingModel?.source===`inference`?`inference:${i.startingModel.inferenceModelId}`:E?J(E):``,ce=w.models.filter(e=>e.preference.source===`managed`).map(e=>({value:J(e.preference),label:e.name}));return se&&!ce.some(e=>e.value===se)&&ce.unshift({value:se,label:i.startingModel?.label??E?.modelId??`Saved starting model`,disabled:!0}),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{hidden:d,inert:d,children:(0,$.jsxs)(Bv,{label:`Experiment setup`,action:`experiment`,onRequestClose:()=>void V.requestLeave(n),children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`h2`,{children:`Run Experiment`}),(0,$.jsx)(`button`,{type:`button`,disabled:P,onClick:()=>void V.requestLeave(n),children:`Close setup`})]}),(0,$.jsx)(X,{error:l??w.error??j.error??T.error}),(0,$.jsxs)(`form`,{noValidate:!0,onSubmit:e=>{e.preventDefault(),ne()},children:[(0,$.jsx)(ft,{title:`Starting model`,children:(0,$.jsxs)(`fieldset`,{disabled:F,children:[(0,$.jsxs)(`label`,{children:[`Model`,(0,$.jsx)(Z,{label:`Engram starting model`,floating:!0,searchable:!0,value:se,options:[{value:``,label:`Choose exact managed base`},...ce],onChange:e=>{if(e===se)return;let t=w.models.find(t=>J(t.preference)===e&&t.preference.source===`managed`);e&&!t?u(`Refresh the model list before changing this selection.`):(i.setTrainingBaseModel(t?.preference??null),o(({startingModule:e,...t})=>({...t,parentArtifact:null})))}})]}),(0,$.jsx)(xy,{disabled:F}),(0,$.jsx)(`p`,{children:`Engram trains a memory adapter on a frozen compatible base. Preparation resolves the exact reviewed data and qualified runtime.`}),(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:P||w.isFetching,onClick:()=>void w.refetch(),children:`Refresh models and reviewed batches`}),M?(0,$.jsx)(`p`,{children:M.state===`unavailable`?M.reason:`A compatible Engram runtime is available. Preparation rechecks its exact identity.`}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:P||j.isFetching||!A,onClick:()=>{T.refetch(),j.refetch()},children:`Refresh runtime availability`})]})}),(0,$.jsx)(ft,{title:`Training data`,children:(0,$.jsxs)(`fieldset`,{disabled:F,children:[(0,$.jsxs)(`label`,{children:[`Reviewed batch`,(0,$.jsx)(Z,{label:`Engram reviewed batch`,floating:!0,searchable:!0,value:K,options:[{value:``,label:`Choose sealed supervised batch`},...oe],onChange:e=>{let t=ae.find(t=>J(t.reference)===e);e&&!t?u(`Refresh the reviewed batch before changing this selection.`):H({batch:t?.reference??null})}})]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>f(!0),children:`Import or review data`})]})}),(0,$.jsx)(ft,{title:`Settings`,children:(0,$.jsxs)(`fieldset`,{disabled:F,children:[(0,$.jsxs)(`label`,{children:[`Experiment name`,(0,$.jsx)(`input`,{value:a.name,maxLength:500,onChange:e=>H({name:e.target.value})})]}),(0,$.jsx)(tx,{training:a.training,configuration:M?.state===`ready`?M.config:null,disabled:F,onChange:e=>H({training:e})}),a.startingModule?(0,$.jsxs)(`p`,{children:[`Saved Model `,a.startingModule.modelProjectId,` · version `,a.startingModule.versionHash]}):null,a.parentArtifact?(0,$.jsxs)(`p`,{children:[`Continue adapter `,a.parentArtifact.id,` · `,a.parentArtifact.contentHash,`. Optimizer state starts fresh.`]}):null,(0,$.jsxs)(`label`,{children:[`Spending limit (USD, optional)`,(0,$.jsx)(`input`,{type:`text`,inputMode:`decimal`,maxLength:100,placeholder:`Use available credits`,value:a.maximumSpendUsd,onChange:e=>H({maximumSpendUsd:e.target.value})})]})]})}),(0,$.jsx)(Db,{funding:R,busy:P,startAttempted:!!C.original,billingReturnPending:p,onOpenBilling:r?re:null,onRefresh:W}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`submit`,className:`training-button secondary`,disabled:F||!r,children:s?`Saving…`:`Save draft`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:F||p||!r||!C.ready||!w.isSuccess||M?.state!==`ready`||!q,onClick:()=>{u(null);try{C.prepare(U(),te)}catch(e){u(e)}},children:`Compile and prepare`})]})]}),(0,$.jsx)(dx,{owner:C,api:e,disabled:P,onOpenBilling:r?re:null,billingReturnPending:p,onRefreshFunding:W}),V.dialog]})}),d?(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`p`,{role:`status`,children:`Opening training data…`}),children:(0,$.jsx)(fx,{api:e,method:`engram_adapter`,navigation:_,onClose:()=>f(!1),onUseBatch:G,beforeImport:async()=>{if(x(),F)throw Error(`Finish the original operation before importing data.`);await te(U()),x()}})}):null]})}function mx({api:e,evidence:t,onOpenRun:n}){let r=kv(),i=(0,Q.useRef)(Vv(e));return i.current=Vv(e),Rv(t?[{id:`advanced-refiner`,label:`Evaluate Refiner`,onSelect:()=>{let n=Vv(e);ho(()=>{i.current===n&&r.openAdvanced({kind:`refiner_evaluation`,evidence:t})})}}]:[]),null}function hx({api:e,evidence:t,onDirty:n,onBusy:r,onOpenRun:i}){let a=Vv(e),o=(0,Q.useRef)(a);o.current=a;let s=(0,Q.useRef)(!0),c=(0,Q.useRef)(null),l=(0,Q.useRef)(null),d=(0,Q.useRef)(!1),f=u(),p=[`advanced-refiner-evaluations`,a,t.id,t.contentHash],m=S({queryKey:[...p,`options`],queryFn:async({signal:n})=>_o.parse(await Hv(e,`advanced-refiner-evaluations`,{operation:`options`,evidence:t},n))}),h=S({queryKey:[...p,`models`],queryFn:({signal:t})=>e.request(`graderModels`,{},t)}),g=Uv(e,`advanced-refiner-start`),_=g.data?.pages.flatMap(e=>e.items)??[];async function v(t){let r=a;re(!0);try{await e.recoverOperation(t).acknowledge(`reviewed`),s.current&&o.current===r&&(l.current?.operation.id===t.id&&(l.current=null,d.current=!1,H(null)),await g.refetch(),n(!1))}catch(e){s.current&&o.current===r&&G(e instanceof Error?e.message:String(e))}finally{s.current&&o.current===r&&re(!1)}}function y(t){try{if(!t.recoveryReady||ie(t.reviewedIntent)!==t.intentHash)throw Error(`The original reviewed intent is unavailable.`);let r=fo.parse(t.command);if(r.operation!==`start`)throw Error(`The retained command is not an advanced evaluation Start.`);let i=Zo(r.request.pin);if(i.operationId!==t.id||i.actorId!==e.actorId||i.teamId!==e.teamId||i.projectId!==e.projectId)throw Error(`The retained command belongs to another owner scope.`);l.current={scope:a,pin:i,operation:e.recoverOperation(t),request:r},d.current=t.phase===`dispatching`,H(i),n(!0),G(null)}catch(e){G(e instanceof Error?e.message:String(e))}}let b=S({queryKey:[...p,`history`],queryFn:({signal:t})=>Hv(e,`advanced-refiner-evaluations`,{operation:`list`},t),refetchInterval:5e3}),[x,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(``),[E,D]=(0,Q.useState)(`train`),[O,k]=(0,Q.useState)(`downstream_adaptation`),[A,j]=(0,Q.useState)(``),[M,N]=(0,Q.useState)(``),[P,F]=(0,Q.useState)(``),[I,L]=(0,Q.useState)(1),[ee,R]=(0,Q.useState)(30),[z,B]=(0,Q.useState)(10),[V,H]=(0,Q.useState)(null),[U,te]=(0,Q.useState)(null),[ne,re]=(0,Q.useState)(!1),[W,G]=(0,Q.useState)(null);(0,Q.useEffect)(()=>(s.current=!0,()=>{s.current=!1,c.current?.abort()}),[]),(0,Q.useEffect)(()=>(r(ne),()=>r(!1)),[ne,r]);let ae=m.data?.profiles.find(e=>e.id===x),K=ae?.components.find(e=>e.label===w),q=m.data?.refinerReleases.find(e=>e.id===A),oe=m.data?.models.filter(e=>e.profileId===ae?.profileRef.profileId)??[];function se(e){ne||l.current||(e(),H(null),n(!0))}let ce=S({queryKey:[...p,`run`,U?.id],enabled:!!U,queryFn:async({signal:t})=>Oo.parse(await Hv(e,`advanced-refiner-evaluations`,{operation:`read`,id:U.id},t)),refetchInterval:3e3});(0,Q.useEffect)(()=>{ce.data?.id===U?.id&&ce.data&&te(ce.data)},[ce.data,U?.id]);async function le(){if(ne||!ae||!K||!q)return;let r=a;re(!0),G(null);let i=new AbortController;c.current=i;try{let a={evidence:t,profileOptionId:ae.id,componentLabel:K.label,mode:O,adaptationSplit:E,refinerRelease:q,maximumCostUsd:I,maximumDurationMs:z*6e4,maximumModelSteps:ee,localModelId:M,modelId:P},c=await e.operation(`advanced-refiner-start`,a);if(!s.current||o.current!==r)return;let u=await Hv(e,`advanced-refiner-evaluations`,{operation:`prepare`,evidence:t,profileOptionId:ae.id,componentLabel:K.label,mode:O,adaptationSplit:E,operationId:c.id,refinerRelease:q,maximumCostUsd:I,maximumDurationMs:z*6e4,maximumModelSteps:ee},i.signal),d=Zo(u.pin);if(!s.current||o.current!==r)return;if(d.actorId!==e.actorId||d.teamId!==e.teamId||d.projectId!==e.projectId||d.operationId!==c.id)throw Error(`The reviewed evaluation belongs to another owner.`);if(H(d),l.current={scope:r,pin:d,operation:c,request:{operation:`start`,request:{pin:d,modelId:M,profileId:ae.profileRef.profileId,model:{providerId:`openpond`,modelId:P},seed:Number(K.binding.population[0].seed),reasoningEffort:null}}},await c.retainCommand(l.current.request,`reviewed`),!s.current||o.current!==r||(await g.refetch(),!s.current||o.current!==r))return;n(!0)}catch(e){s.current&&o.current===r&&G(e instanceof Error?e.message:String(e))}finally{s.current&&o.current===r&&re(!1),c.current===i&&(c.current=null)}}async function ue(){let e=l.current,t=a;if(!(ne||d.current||!e)){re(!0);try{if(await e.operation.acknowledge(`reviewed`),!s.current||o.current!==t||(await g.refetch(),!s.current||o.current!==t))return;l.current=null,H(null),n(!0)}catch(e){s.current&&o.current===t&&G(e instanceof Error?e.message:String(e))}finally{s.current&&o.current===t&&re(!1)}}}async function de(){let t=l.current;if(ne||!t||t.scope!==a)return;let r=a;re(!0),G(null);let i=new AbortController;c.current=i,d.current=!0;try{if(await t.operation.retainCommand(t.request,`dispatching`),!s.current||o.current!==r)return;let a=Oo.parse(await Hv(e,`advanced-refiner-evaluations`,t.request,i.signal));if(!s.current||o.current!==r)return;if(a.evaluation?.benchmarkId!==`harness-refiner`||a.evaluation.advancedEvaluation?.contentHash!==t.pin.contentHash)throw Error(`The run receipt differs from the frozen review.`);if(te(a),await t.operation.acknowledge(),!s.current||o.current!==r||(l.current=null,d.current=!1,await g.refetch(),!s.current||o.current!==r))return;n(!1),await f.invalidateQueries({queryKey:[...p,`history`]})}catch(e){s.current&&o.current===r&&G(e instanceof Error?e.message:String(e))}finally{s.current&&o.current===r&&re(!1),c.current===i&&(c.current=null)}}async function fe(t,n){if(ne)return;let r=a;re(!0),G(null);try{let i=await Hv(e,`advanced-refiner-evaluations`,{operation:t,id:n});if(!s.current||o.current!==r)return;t===`resume`&&te(Oo.parse(i)),await f.invalidateQueries({queryKey:[...p,`history`]})}catch(e){s.current&&o.current===r&&G(e instanceof Error?e.message:String(e))}finally{s.current&&o.current===r&&re(!1)}}let pe=W??m.error?.message??h.error?.message??b.error?.message??ce.error?.message;return(0,$.jsxs)(`div`,{className:`evaluation-form`,children:[(0,$.jsx)(`h2`,{children:`Evaluate Refiner`}),(0,$.jsx)(Wv,{items:_,busy:ne,error:g.error?.message,onRestore:y,onDiscard:e=>void v(e),onLoadMore:g.hasNextPage?()=>void g.fetchNextPage():void 0}),(0,$.jsx)(`p`,{children:`Review quality scores independent retained contexts. Downstream adaptation measures a sequential candidate trajectory against a separate private holdout. Both retain the original source and current owner boundaries.`}),pe?(0,$.jsx)(X,{error:pe}):null,(0,$.jsxs)(`fieldset`,{disabled:ne||!!l.current,children:[(0,$.jsxs)(`label`,{children:[`Profile`,(0,$.jsxs)(`select`,{value:x,onChange:e=>se(()=>{C(e.target.value),T(``),N(``)}),children:[(0,$.jsx)(`option`,{value:``,children:`Select actual source`}),m.data?.profiles.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),(0,$.jsxs)(`label`,{children:[`Component`,(0,$.jsxs)(`select`,{value:w,onChange:e=>se(()=>T(e.target.value)),children:[(0,$.jsx)(`option`,{value:``,children:`Select component`}),ae?.components.map(e=>(0,$.jsxs)(`option`,{value:e.label,children:[e.kind,` `,e.label]},e.label))]})]}),(0,$.jsxs)(`label`,{children:[`Target`,(0,$.jsxs)(`select`,{value:O,onChange:e=>se(()=>k(e.target.value===`review_quality`?`review_quality`:`downstream_adaptation`)),children:[(0,$.jsx)(`option`,{value:`downstream_adaptation`,children:`Downstream sequential adaptation`}),(0,$.jsx)(`option`,{value:`review_quality`,children:`Independent review quality`})]})]}),(0,$.jsxs)(`label`,{children:[`Adaptation split`,(0,$.jsx)(`select`,{value:E,onChange:e=>se(()=>D(e.target.value)),children:K?.adaptationSplits.map(e=>(0,$.jsxs)(`option`,{value:e.split,children:[e.split,` / `,e.taskIds.length,` cases`]},e.split))})]}),(0,$.jsxs)(`label`,{children:[`Refiner release`,(0,$.jsxs)(`select`,{value:A,onChange:e=>se(()=>j(e.target.value)),children:[(0,$.jsx)(`option`,{value:``,children:`Select exact release`}),m.data?.refinerReleases.map(e=>(0,$.jsxs)(`option`,{value:e.id,children:[e.id,` / `,e.contentHash.slice(0,12)]},e.contentHash))]})]}),(0,$.jsxs)(`label`,{children:[`Actual local evaluation configuration`,(0,$.jsxs)(`select`,{value:M,onChange:e=>se(()=>N(e.target.value)),children:[(0,$.jsx)(`option`,{value:``,children:`Select existing configuration`}),oe.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),ae&&!oe.length?(0,$.jsx)(`p`,{children:`Create an actual Model configuration for this Profile before evaluating. A hosted configuration is not a local execution owner.`}):null,(0,$.jsxs)(`label`,{children:[`Foreground and Refiner model`,(0,$.jsxs)(`select`,{value:P,onChange:e=>se(()=>F(e.target.value)),children:[(0,$.jsx)(`option`,{value:``,children:`Select admitted hosted model`}),h.data?.models.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),(0,$.jsxs)(`label`,{children:[`Whole run budget USD`,(0,$.jsx)(`input`,{type:`number`,min:`0.000001`,value:I,onChange:e=>se(()=>L(Number(e.target.value)))})]}),(0,$.jsxs)(`label`,{children:[`Maximum model requests`,(0,$.jsx)(`input`,{type:`number`,min:1,max:500,value:ee,onChange:e=>se(()=>R(Number(e.target.value)))})]}),(0,$.jsxs)(`label`,{children:[`Maximum minutes`,(0,$.jsx)(`input`,{type:`number`,min:1,max:1440,value:z,onChange:e=>se(()=>B(Number(e.target.value)))})]})]}),K&&!K.resettable?(0,$.jsx)(`p`,{children:`The selected environment cannot bound live external tool charges. Review a released resettable environment first.`}):null,O===`review_quality`&&K&&!K.reviewQuality?(0,$.jsx)(`p`,{children:`This Dataset needs separately grounded review labels and actual retained native context bindings.`}):null,V?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[`Frozen review `,V.contentHash,`. Source `,V.profileRef.profileId,` / `,V.baselineRelease.contentHash,`; evidence `,V.evidence.id,` / `,V.evidence.contentHash,`; Refiner `,V.refinerRelease.id,` / `,V.refinerRelease.contentHash,`. Adaptation`,` `,V.adaptationTaskIds.length,` / holdout `,V.holdoutTaskIds.length,`. All foreground, review and grade requests share`,` `,V.maximumCostUsd,` USD.`]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:ne,onClick:()=>void de(),children:`Start retained evaluation`}),(0,$.jsx)(`button`,{type:`button`,disabled:ne||d.current,onClick:()=>void ue(),children:`Edit setup`})]}):(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:ne||!ae||!K?.resettable||!q||!oe.some(e=>e.id===M)||!h.data?.models.some(e=>e.id===P)||O===`review_quality`&&!K?.reviewQuality,onClick:()=>void le(),children:`Review exact evaluation`}),U?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[`Actual Run `,U.id,` / `,U.status]}),U.failure?(0,$.jsx)(`p`,{children:U.failure}):null,U.receipt?.schemaVersion===`openpond.advancedRefinerReviewReceipt.v1`?(0,$.jsxs)(`p`,{children:[`Review score `,U.receipt.reviewScore??`unavailable`,` / no action `,U.receipt.noActionCases,` / routed`,` `,U.receipt.routedCases,` / proposals `,U.receipt.proposalCases,` `,`/ cleanup `,U.receipt.cleanupComplete?`complete`:`pending`,` / spend `,U.receipt.costUsd??`unresolved`]}):null,i?(0,$.jsx)(`button`,{type:`button`,onClick:()=>i(U.id),children:`Open actual Run`}):null,(0,$.jsx)(`button`,{type:`button`,disabled:ne,onClick:()=>void fe(`cancel`,U.id),children:`Cancel`}),(0,$.jsx)(`button`,{type:`button`,disabled:ne||![`failed`,`cancelled`].includes(U.status),onClick:()=>void fe(`resume`,U.id),children:`Resume retained run`})]}):null,(0,$.jsx)(`ol`,{children:b.data?.items.map(t=>(0,$.jsxs)(`li`,{children:[t.mode,` / `,t.status,t.failure?(0,$.jsx)(`p`,{children:t.failure}):null,(0,$.jsx)(`button`,{type:`button`,disabled:ne,onClick:()=>{let n=a;Hv(e,`advanced-refiner-evaluations`,{operation:`read`,id:t.id}).then(e=>{s.current&&o.current===n&&te(Oo.parse(e))}).catch(e=>{s.current&&o.current===n&&G(String(e))})},children:`Inspect actual Run`})]},t.id))})]})}function gx({api:e,target:t,onClose:n,onOpenRun:r}){let[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.useState)(!1),c=iy({name:`Refiner experiment`,dirty:i,busy:o,onLeave:n});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(Bv,{label:`New experiment / Refiner`,action:`advanced-refiner`,onRequestClose:()=>void c.requestLeave(n),children:[(0,$.jsx)(`p`,{children:`Target: improvement system. Review quality and downstream adaptation retain their own exact source, evidence, holdout and budget admission.`}),(0,$.jsx)(hx,{api:e,evidence:t.evidence,onDirty:a,onBusy:s,onOpenRun:r},ie([Vv(e),t]))]}),c.dialog]})}var _x=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:{},vx=$e.shape.lora.shape.targetModules.element.options,yx=[{section:`optimizer`,key:`learningRate`,label:`Learning rate`,min:Number.MIN_VALUE,max:.001,step:`any`},{section:`optimizer`,key:`epochs`,label:`Epochs`,min:Number.MIN_VALUE,max:10,step:`any`},{section:`optimizer`,key:`batchSize`,label:`Batch size`,min:1,max:32,step:1},{section:`optimizer`,key:`gradientAccumulationSteps`,label:`Gradient accumulation steps`,min:1,max:32,step:1},{section:`optimizer`,key:`seed`,label:`Seed`,min:-(2**31),max:2**31-1,step:1},{section:`dataset`,key:`maxSequenceLength`,label:`Maximum sequence tokens`,min:2,max:8192,step:1},{section:`lora`,key:`rank`,label:`LoRA rank`,min:1,max:64,step:1},{section:`lora`,key:`alpha`,label:`LoRA alpha`,min:Number.MIN_VALUE,max:1024,step:`any`},{section:`lora`,key:`dropout`,label:`LoRA dropout`,min:0,max:1,step:`any`}];function bx(e){let t=[$e.shape.optimizer.safeParse(e.optimizer),$e.shape.lora.safeParse(e.lora),$e.shape.dataset.omit({trainSplit:!0,validationSplit:!0}).safeParse(e.dataset)];for(let e of t)if(!e.success){let t=e.error.issues[0];return`${t?.path.join(`.`)||`SFT settings`}: ${t?.message??`Check this value.`}`}let n=_x(e.optimizer);if(Number(n.batchSize)*Number(n.gradientAccumulationSteps)>32)return`Managed SFT supports at most 32 accumulated examples.`;let r=_x(e.lora).targetModules;return Array.isArray(r)&&new Set(r).size!==r.length?`Choose each adapter target module once.`:null}function xx({recipe:e,onChange:t}){let n=_x(e.optimizer),r=_x(e.lora).targetModules,i=Array.isArray(r)?r.filter(e=>typeof e==`string`):[],a=typeof n.batchSize==`number`&&Number.isFinite(n.batchSize)&&typeof n.gradientAccumulationSteps==`number`&&Number.isFinite(n.gradientAccumulationSteps)?n.batchSize*n.gradientAccumulationSteps:null;function o(n,r,i){t({...e,[n]:{..._x(e[n]),[r]:i}})}let s=(t,n)=>{let r=_x(e[t])[n];return typeof r==`number`||typeof r==`string`?r:``};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Training steps`}),(0,$.jsx)(`input`,{type:`number`,min:1,max:128,step:1,value:s(`optimizer`,`maxSteps`),onChange:e=>o(`optimizer`,`maxSteps`,e.target.value===``?``:e.target.valueAsNumber)})]}),(0,$.jsxs)(`details`,{className:`model-training-settings`,children:[(0,$.jsx)(`summary`,{children:`Advanced SFT settings`}),(0,$.jsx)(`p`,{children:`SFT with LoRA. Available settings depend on the selected model and runtime.`}),(0,$.jsx)(`div`,{className:`taskset-draft-field-grid`,children:yx.map(e=>(0,$.jsxs)(`label`,{className:`labs-model-create-field`,children:[(0,$.jsx)(`span`,{children:e.label}),(0,$.jsx)(`input`,{type:`number`,min:e.min,max:e.max,step:e.step,value:s(e.section,e.key),onChange:t=>o(e.section,e.key,t.target.value===``?``:t.target.valueAsNumber)})]},`${e.section}.${e.key}`))}),(0,$.jsx)(`p`,{children:a===null?`Examples per optimizer update depend on batch size and gradient accumulation.`:`${a} example${a===1?``:`s`} per optimizer update`}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Adapter targets`}),i.map((e,t)=>(0,$.jsxs)(`div`,{className:`labs-model-create-select-row`,children:[(0,$.jsx)(Z,{floating:!0,label:`Adapter target ${t+1}`,value:e,options:[...vx.some(t=>t===e)?[]:[{value:e,label:`${e} (unavailable)`,disabled:!0}],...vx.map(t=>({value:t,label:t,disabled:t!==e&&i.includes(t)}))],onChange:e=>o(`lora`,`targetModules`,i.map((n,r)=>r===t?e:n))}),(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,"aria-label":`Remove adapter target ${e}`,disabled:i.length<=1,onClick:()=>o(`lora`,`targetModules`,i.filter((e,n)=>n!==t)),children:`Remove`})]},t)),i.length<vx.length?(0,$.jsx)(Z,{floating:!0,label:`Add adapter target`,value:``,options:[{value:``,label:`Add target module`,disabled:!0},...vx.filter(e=>!i.includes(e)).map(e=>({value:e,label:e}))],onChange:e=>o(`lora`,`targetModules`,[...i,e])}):null]})]})]})}var Sx=[{section:`optimizer`,key:`maxSteps`,label:`Training steps`,min:1,max:1e5,step:1},{section:`optimizer`,key:`learningRate`,label:`Learning rate`,min:Number.MIN_VALUE,step:`any`},{section:`rollout`,key:`maxOutputTokens`,label:`Maximum answer tokens`,min:1,max:8192,step:1}];function Cx(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function wx(e){if(e?.method===`sft`)return bx(e);if(e?.method!==`grpo`)return null;for(let t of Sx){let n=Cx(e[t.section])[t.key];if(typeof n!=`number`||!Number.isFinite(n)||n<t.min||`max`in t&&n>t.max||t.step===1&&!Number.isInteger(n))return`Enter a valid value for ${t.label.toLowerCase()}.`}return null}function Tx({recipe:e,onChange:t}){return e?.method===`sft`?(0,$.jsx)(xx,{recipe:e,onChange:t}):e?.method===`grpo`?(0,$.jsx)(Ex,{recipe:e,onChange:t}):null}function Ex({recipe:e,onChange:t}){let n=(0,Q.useRef)(e),[r,i]=(0,Q.useState)(!1),a=lo.safeParse(e),o=a.success?a.data:null,s=o&&gv(`small_experiment`,`grpo`,{maxSteps:o.optimizer.maxSteps,trainingExamples:o.dataset.maxExamples,rolloutGroupSize:o.rollout.groupSize,rolloutConcurrency:o.rollout.concurrency,optimizerIterations:o.optimizer.iterations,maximumRollouts:o.resourceLimits.maxRollouts})===null&&!r?`small_experiment`:`custom`;if(e?.method!==`grpo`)return null;function c(n,r,a){if(!e)return;let o=a===``?``:Number(a),s={...e,[n]:{...Cx(e[n]),[r]:o}};if(r===`maxSteps`&&typeof o==`number`){let t=Cx(e.rollout).groupSize;typeof t==`number`&&(s.resourceLimits={...Cx(e.resourceLimits),maxRollouts:o*t})}i(!0),t(s)}return(0,$.jsxs)($.Fragment,{children:[o?(0,$.jsx)(_v,{method:`grpo`,value:s,disabled:!o,sizing:o?{prompts:o.dataset.maxExamples,rollouts:o.rollout.groupSize,groups:o.optimizer.maxSteps,iterations:o.optimizer.iterations,concurrency:o.rollout.concurrency}:void 0,onSizingChange:e=>{o&&(i(!0),t({...o,dataset:{...o.dataset,maxExamples:e.prompts},rollout:{...o.rollout,groupSize:e.rollouts,concurrency:e.concurrency},optimizer:{...o.optimizer,maxSteps:e.groups,iterations:e.iterations},resourceLimits:{...o.resourceLimits,maxRollouts:e.rollouts*e.groups},policyOptimization:null}))},onChange:e=>{i(e===`custom`),e===`small_experiment`&&o?t(mv(o)):e===`standard`&&t(n.current)}}):(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Training steps`}),(0,$.jsx)(`input`,{type:`number`,min:1,max:1e5,value:typeof Cx(e.optimizer).maxSteps==`number`||typeof Cx(e.optimizer).maxSteps==`string`?String(Cx(e.optimizer).maxSteps):``,onChange:e=>c(`optimizer`,`maxSteps`,e.target.value)})]}),(0,$.jsxs)(`details`,{className:`model-training-settings`,children:[(0,$.jsx)(`summary`,{children:`Training settings`}),(0,$.jsx)(`p`,{children:`GRPO with LoRA. Review the cost and budget before starting a Run.`}),(0,$.jsx)(`div`,{className:`taskset-draft-field-grid`,children:Sx.map(t=>{let n=Cx(e[t.section])[t.key];return(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`span`,{children:t.label}),(0,$.jsx)(`input`,{type:`number`,min:t.min,max:`max`in t?t.max:void 0,step:t.step,value:typeof n==`number`||typeof n==`string`?n:``,onChange:e=>c(t.section,t.key,e.target.value)})]},t.key)})})]})]})}var Dx=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:{};function Ox(e){let t=e?.method===`sft`?e:void 0;return{schemaVersion:`openpond.sftRecipe.v1`,method:`sft`,parameterization:`lora`,...t?.baseModel?{baseModel:t.baseModel}:{},dataset:{completionOnly:!0,maxSequenceLength:8192,selectionStrategy:`stable_hash_top_n`,selectionSeed:17,...Dx(t?.dataset)},lora:{rank:16,alpha:32,dropout:0,targetModules:[`q_proj`,`k_proj`,`v_proj`,`o_proj`,`gate_proj`,`up_proj`,`down_proj`],...Dx(t?.lora)},optimizer:{learningRate:1e-4,epochs:3,maxSteps:30,batchSize:1,gradientAccumulationSteps:1,seed:17,...Dx(t?.optimizer)},resourceLimits:{cpuThreads:4,memoryBytes:48*1024**3,wallTimeMs:36e5,...Dx(t?.resourceLimits)}}}function kx(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function Ax(e,t=e?.method===`sft`?`sft`:`grpo`){if(t===`sft`)return Ox(e);let n=e?.method===`grpo`?e:void 0,r={schemaVersion:`openpond.rftRecipe.v1`,method:`grpo`,parameterization:`lora`,lora:{rank:2},rollout:{groupSize:8,concurrency:4,maxOutputTokens:1024,temperature:.8,topP:.95,seed:17},optimizer:{learningRate:1e-4,maxSteps:8,clipRange:.2,iterations:2,microbatchSize:1,gradientAccumulationSteps:8,advantageEpsilon:1e-8,adamw:{name:`adamw`,weightDecay:0,beta1:.9,beta2:.999,epsilon:1e-8}},loss:{method:`grpo`,klBeta:.01},resourceLimits:{wallTimeMs:396e4,maxRollouts:64,maxPayloadBytes:1e6},policyOptimization:null};return{...r,...n,lora:{...r.lora,...kx(n?.lora)},rollout:{...r.rollout,...kx(n?.rollout)},optimizer:{...r.optimizer,...kx(n?.optimizer),adamw:{...r.optimizer.adamw,...kx(kx(n?.optimizer).adamw)}},loss:{...r.loss,...kx(n?.loss)},resourceLimits:{...r.resourceLimits,...kx(n?.resourceLimits)}}}function jx(e){let{baseModel:t,reward:n,policyOptimization:r,...i}=Ax(e),{trainSplit:a,validationSplit:o,maxExamples:s,...c}=kx(i.dataset);return i.method===`sft`?{...i,dataset:{...c,...o?{validationSplit:o}:{}}}:{...i,dataset:c,policyOptimization:null}}var Mx=U().trim().min(1).max(500),Nx=Pr,Px=z({schemaVersion:L(`openpond.modelStarter.v1`),id:Mx,revision:V().int().positive(),name:U().trim().min(1).max(200),description:U().trim().min(1).max(2e3),category:H([`extraction`,`support`,`operations`,`knowledge`,`coding`,`writing`,`classification`]),taskset:Nx,taskDefinition:Nx,rewardBinding:Nx,rewards:F(Nx).min(1).max(100),assets:F(Nx).max(1e3),previewTaskIds:F(Mx).min(1).max(8),startingModel:Ur,supportedMethods:F(Lr).min(1).max(8),defaultMethod:Lr,provenance:z({author:U().min(1).max(200),license:U().min(1).max(200),sourceDescription:U().min(1).max(2e3)}).strict(),evidence:z({verifierFixtures:Nx.nullable(),baseline:Nx.nullable(),training:Nx.nullable(),evaluation:Nx.nullable()}).strict()}).strict().superRefine((e,t)=>{e.supportedMethods.includes(e.defaultMethod)||t.addIssue({code:`custom`,path:[`defaultMethod`],message:`The default method must be supported by the package.`});for(let n of[`rewards`,`assets`])new Set(e[n].map(e=>e.id)).size!==e[n].length&&t.addIssue({code:`custom`,path:[n],message:`Dependency identities must be unique.`});new Set(e.previewTaskIds).size!==e.previewTaskIds.length&&t.addIssue({code:`custom`,path:[`previewTaskIds`],message:`Preview tasks must be unique.`})}).safeExtend({contentHash:U().regex(/^[a-f0-9]{64}$/)});z({starter:Px,taskset:Le,taskDefinition:Ve,rewardBinding:Re,rewards:F(we).min(1).max(100),assets:F(ct).max(1e3),execution:Hr.optional()}).strict(),z({schemaVersion:L(`openpond.modelStarterPrivacyReview.v1`),disposition:L(`synthetic_only`),reviewedBy:U().trim().min(1).max(500),reviewedAt:N(),reviewedContentHash:U().regex(/^[a-f0-9]{64}$/),note:U().trim().min(1).max(2e3)}).strict(),z({profileId:Mx,modelId:Mx,name:U().trim().min(1).max(200),starter:Nx,startingModel:Ur,method:Lr,rewardBindingRef:Nx.nullable().optional(),recipe:Mr.nullable().optional(),managedGpuSelection:jr.shape.managedGpuSelection,continuationAdapterMode:jr.shape.continuationAdapterMode,learning:Vr.optional()}).strict().extend({schemaVersion:L(`openpond.modelStarterCreation.v1`),operationId:Mx}).strict();var Fx=`training:prepare-draft`,Ix=`training:control-preparation`;async function Lx(e,t,n,r){async function i(t){let n=[],i=new Set,a;for(let o=0;;o++){if(o>=100)throw Error(`The retained training catalog exceeds its supported bound.`);let s=await e.pendingOperations(t,a,r);if(n.push(...s.items),!s.nextCursor)return n;if(i.has(s.nextCursor))throw Error(`The retained training catalog repeated a page.`);i.add(s.nextCursor),a=s.nextCursor}}let[a,o]=await Promise.all([i(Fx),i(Ix)]),s=[];for(let r of a){let i=ll.parse(r.reviewedIntent);if(i.draftId!==t||i.request.settings.method!==n)continue;let a=Rn.parse({...i.request,operationId:r.id});if(i.request.teamId!==e.teamId||i.request.projectId!==e.projectId||r.intentHash!==ie(i)||r.command&&J(r.command)!==J(a))throw Error(`The retained training preparation changed its exact inputs or workspace.`);let o=e.recoverOperation(r);s.push({intent:i,request:a,operation:o,snapshot:J(i.form),acknowledge:o.acknowledge})}if(s.length>1)throw Error(`Resolve the original retained training review before preparing another run.`);let c=s[0]??null,l=[];for(let r of o){let i=dl.parse(r.reviewedIntent);if(i.draftId!==t||i.method!==n)continue;if(!c||i.preparationOperationId!==c.request.operationId)throw Error(`The retained training control is missing its original preparation. Recover that original review before starting another run.`);let a=ul.parse(r.command??i.command);if(r.intentHash!==ie(i)||J(a)!==J(i.command)||i.receipt.plan.creatorUserId!==e.actorId||i.receipt.plan.request.teamId!==e.teamId||i.receipt.plan.request.projectId!==e.projectId)throw Error(`The retained training control changed its creator, plan or estimate approval.`);l.push({intent:i,command:a,operation:e.recoverOperation(r),phase:r.phase})}if(l.length>1)throw Error(`Recover the original training control before submitting another action.`);return{review:c,control:l[0]??null}}function Rx(e,t,n,r){return S({queryKey:[`training-experiment-recovery`,e.key,ra(e.connection),t,n],enabled:r&&!!(t&&e.actorId),queryFn:({signal:r})=>Lx(e,t,n,r),staleTime:0,gcTime:0,retry:!1})}async function zx(e){let t=e.retained;if(t.snapshot===e.snapshot)return{kind:`unchanged`};let n=await Sn(await e.request(`prepare-draft`,t.request));if(J(n.request)!==J(t.request))throw Error(`The recovered preparation does not match its retained inputs.`);let r=n.preparation;if(r.state===`prepared`){let n=await vr(await e.request(`cancel`,{id:r.plan.id,control:{teamId:t.request.teamId,planHash:r.plan.contentHash,expectedRevision:r.revision}}));if(n.plan.contentHash!==r.plan.contentHash||n.plan.id!==r.plan.id||n.revision<=r.revision||n.state!==`cancelled`)throw Error(`The earlier preparation has not confirmed cancellation. Retry its retained request.`);r=n}return await t.acknowledge(),r.state===`submitted`&&r.jobId?{kind:`submitted`,jobId:r.jobId}:{kind:`cancelled`}}function Bx(e,t,n,r,i,a){let o=kv(),s=Ga(),c=o.initialExperiment?.operationType===t?o.initialExperiment:null,l=c?.training?.settings?.recipe?.dataset,u=l&&typeof l==`object`&&`validationSplit`in l&&l.validationSplit===`frozen_eval`?`frozen_eval`:`validation`,[d,f]=(0,Q.useState)(()=>c?.trainingForm?.recipe??c?.training?.settings?.recipe??Ax(null,t)),[p,m]=(0,Q.useState)(c?.trainingForm?c.trainingForm.batch:c?.training?.batch??null),h=Ry(e,n,p),[g,_]=(0,Q.useState)(c?.trainingForm?c.trainingForm.evaluation:c?.training?.settings?.evaluationTasksetRef??o.draft?.release??null),[v,y]=(0,Q.useState)(c?.trainingForm?.validationSplit??u),[b,x]=(0,Q.useState)(c?.trainingForm?.name??c?.name??(t===`sft`?`Supervised training`:`RL training`)),[S,C]=(0,Q.useState)(c?.trainingForm?.startingModelLabel),[w,T]=(0,Q.useState)(c?.trainingForm?.budget??String(c?.training?.maximumSpendUsd??1)),[E,D]=(0,Q.useState)(c?.trainingForm?.customerCapUsd??c?.training?.usageFunding?.customerCapUsd??``),[O,k]=(0,Q.useState)(c?.trainingForm?.billingMode??(c?.training?c.training.usageFunding?`actual_usage`:`prepaid_only`:null)),A=O??(h.billingModes?.[1].availability===`requires_preparation`?`actual_usage`:`prepaid_only`),[j,M]=(0,Q.useState)(c?.trainingForm?.gpuSelection??c?.training?.settings?.managedGpuSelection??{mode:`automatic`,objective:`balanced`,gpuCount:1}),[N,P]=(0,Q.useState)(null),[F,I]=(0,Q.useState)(null),[L,ee]=(0,Q.useState)(!1),[R,z]=(0,Q.useState)(null),B=(0,Q.useRef)(!1),V=(0,Q.useRef)(null),H=(0,Q.useRef)(null),U=Rx(e,o.initialExperiment?.id,t,n),[te,ne]=(0,Q.useState)(!1),re=Cb({api:e,method:t,enabled:n,baseModel:o.trainingBaseModel,recipe:d,selection:j,receipt:F}),W=Tb(e,F?.plan.usageQuote?F.plan.usageQuote.customerCapUsd??``:F?String(F.plan.request.maximumSpendUsd):A===`actual_usage`?E:w,n,F?!!F.plan.usageQuote:A===`actual_usage`),ie=(0,Q.useRef)(null),[G,ae]=(0,Q.useState)(!1),K=JSON.stringify([e.key,e.connection.serverUrl,e.actorId,o.initialExperiment?.id,ra(e.connection)]),q=(0,Q.useRef)(K);q.current=K,(0,Q.useEffect)(()=>(q.current=K,()=>{q.current=`unmounted`}),[K]);let oe={startingModel:o.startingModel,baseModel:o.trainingBaseModel,...o.trainingParent?{parent:o.trainingParent,startingModelLabel:S}:{},recipe:d,batch:p,evaluation:g,validationSplit:v,name:b,budget:w,customerCapUsd:E,billingMode:A,gpuSelection:j},se=J(oe),ce=(0,Q.useRef)(se),le=se!==ce.current||F!==null,ue=o.reportOperationDraftDirty;(0,Q.useEffect)(()=>{ue(t,le)},[t,le,ue]);let de=iy({name:`training experiment`,dirty:le||o.operationDraftDirty||o.evaluationDirty,busy:L,onLeave:r,retainForDestination(t){let n=po(new URL(t,window.location.origin));return!(!n||![`datasets`,`graders`,`experiments`].includes(n.page)||n.collection===`drafts`&&n.resourceId!==o.initialExperiment?.id||(n.projectId??null)!==e.projectId)}}),fe=h.batches.find(e=>p!==null&&e.reference.id===p.id&&e.reference.revision===p.revision&&e.reference.contentHash===p.contentHash),pe=L||F!==null;function me(){if(!o.initialExperiment)throw Error(`Open an experiment before saving.`);let e=Zn.parse({baseModel:o.trainingBaseModel,recipe:d,batch:p,evaluation:g,validationSplit:v,name:b,budget:w,customerCapUsd:E,billingMode:A,gpuSelection:j,...o.trainingParent?{parent:o.trainingParent,startingModelLabel:S}:{}});return Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:o.initialExperiment.id,operationType:t,name:b.trim()||(t===`sft`?`Supervised training`:`RL training`),trainingForm:e,...o.startingModel?{startingModel:o.startingModel}:{}})}function he(){if(q.current!==K)throw Error(`The active account changed. Reopen this experiment.`)}async function ge(){if(!a)throw Error(`Save this experiment before opening Billing.`);let t=me();await a(t),he();let n=await Iy(e).get(t.id);if(he(),n.status!==`draft`||J(n.draft)!==J(t))throw Error(`The saved experiment changed. Your edits remain here; reopen the current draft before continuing.`);return ce.current=se,n}async function _e(){if(!a||!o.initialExperiment||B.current||F)return!1;B.current=!0,ee(!0),z(null);try{return await ge(),!0}catch(e){return q.current===K&&z(e),!1}finally{B.current=!1,q.current===K&&ee(!1)}}async function ve(){if(B.current||te||F&&F.state!==`prepared`)return;B.current=!0,ee(!0),z(null);let t=null;try{let n=window.openpond?.browser;if(!n?.openExternal){if(t=window.open(`about:blank`,`_blank`),!t)throw Error(`Allow a new tab to open Billing, then try again.`);t.opener=null}let r=await ge(),i=W.allocationAdmission?vt(E):null,a=await xb(e,{schemaVersion:`openpond.trainingFundingHandoffRequest.v1`,teamId:e.teamId,maximumSpendUsd:W.allocationAdmission?i===null?null:Number(i):Number(w),draft:{id:r.id,revision:r.revision,contentHash:r.contentHash,projectId:r.projectId}});if(he(),!a.canPurchase||!a.billingUrl)throw Error(`A workspace billing owner needs to add credits for this experiment.`);if(ie.current=r,ae(!0),re.requireFreshReview(),n?.openExternal){let e=await n.openExternal({conversationId:`experiment-funding:${r.id}`,url:a.billingUrl});if(he(),!e.ok)throw Error(e.error??`Billing could not be opened. Your experiment is saved; try again.`)}else t&&=(t.location.replace(a.billingUrl),null)}catch(e){t?.close(),q.current===K&&z(e)}finally{B.current=!1,q.current===K&&ee(!1)}}async function ye(){if(!(B.current||te)){B.current=!0,ee(!0),z(null);try{if(ie.current){let t=ie.current,n=await Iy(e).get(t.id);if(he(),n.status!==`draft`||n.contentHash!==t.contentHash||n.revision!==t.revision)throw Error(`This experiment changed while Billing was open. Your edits remain here; reopen the saved draft before running.`)}let t=W.allocationAdmission?null:await W.query.refetch();if(he(),t?.error)throw t.error;if(F?.state===`prepared`){let e=await re.estimate.refetch();if(he(),e.error)throw e.error}(W.allocationAdmission||t?.data?.state===`covered`)&&(ie.current=null,ae(!1))}catch(e){q.current===K&&z(e)}finally{B.current=!1,q.current===K&&ee(!1)}}}let be=(0,Q.useRef)(ye);be.current=ye,(0,Q.useEffect)(()=>{if(!n)return;let e=()=>{ie.current&&document.visibilityState===`visible`&&be.current()};return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[K,n]);async function xe(n,r){if(B.current)return;B.current=!0,ee(!0),z(null);let a=()=>{if(q.current!==K)throw Error(`The active account changed. Reopen this experiment.`)};async function c(t,n){a();let r=await Y(e.connection,`/v1/training/setup/${t}?teamId=${encodeURIComponent(e.teamId)}`,{method:`POST`,body:JSON.stringify(n)});return a(),r}let l=!1;try{if(a(),!U.isSuccess)throw Error(`Load retained training reviews before continuing.`);let u=await U.refetch();if(a(),u.error||!u.data)throw u.error??Error(`Load retained training reviews before continuing.`);let p=u.data;if(V.current?.request.operationId===p.review?.request.operationId&&(H.current??=p.control),n===`recover`){let t=V.current??p.review;if(!t)throw Error(`No previous training review is retained for this experiment.`);V.current=t,H.current??=p.control,await t.operation.retainCommand(t.request,`dispatching`),a();let n=await Sn(await c(`prepare-draft`,t.request));if(J(n.request)!==J(t.request)||n.preparation.plan.creatorUserId!==e.actorId)throw Error(`The recovered training review differs from its retained request or creator.`);let r=n.preparation,i=H.current;if(i&&(r.plan.id!==i.command.id||r.plan.contentHash!==i.command.control.planHash||r.state===`prepared`&&r.revision!==i.command.control.expectedRevision))throw Error(`The original training control does not own this current preparation.`);let s=t.intent.form;o.setTrainingBaseModel(s.baseModel),o.setTrainingParent(s.parent??null),C(s.startingModelLabel),f(s.recipe),m(s.batch),_(s.evaluation),y(s.validationSplit),x(s.name),T(s.budget),D(s.customerCapUsd??r.plan.request.usageFunding?.customerCapUsd??``),k(r.plan.request.usageFunding?`actual_usage`:`prepaid_only`),M(s.gpuSelection??{mode:`automatic`,objective:`balanced`,gpuCount:1}),I(r),ne(i?.command.action===`start`),r.state!==`prepared`&&(await i?.operation.acknowledge(),await t.acknowledge(),a(),H.current=null,V.current=null,ne(!1),r.state===`submitted`?P(r.jobId):I(null),await U.refetch());return}if(!V.current&&p.review)throw Error(`Restore the previous training review before preparing or starting another request.`);if(H.current&&H.current.command.action!==n)throw Error(`Recover the original training control before changing its action.`);if(n===`prepare`){if(N&&!r?.newRun)throw Error(`The earlier preparation already started. Your edited settings remain here. Open the existing run or review these edits for a new run.`);if(r?.newRun&&P(null),V.current&&V.current.snapshot!==se){let e=await zx({retained:V.current,snapshot:se,request:c});if(a(),e.kind!==`unchanged`&&(V.current=null),e.kind===`submitted`)throw P(e.jobId),Error(`The earlier preparation already started. Your edited settings remain here. Open the existing run or review these edits for a new run.`)}if(V.current?.snapshot!==se){if(!e.actorId||!h.isSuccess)throw Error(`Load the current training inputs before reviewing this experiment.`);if(o.startingModel?.source===`steering`||o.startingModel?.source===`engram`)throw Error(`Training cannot consume this saved steering source. Choose another starting model instead of substituting its base.`);if(o.startingModel?.source===`trained`){await Xt(me(),{teamId:e.teamId});let n=o.startingModel.trainedVersion,r=o.trainingParent;if(t!==`grpo`||!r||r.jobId!==n.jobId||r.checkpointId!==n.candidate.checkpointId||J(r.artifact)!==J(n.candidate.artifact))throw Error(`This trained source requires its exact qualified GRPO parent. Choose another starting model for this method.`)}if(o.trainingParent&&t!==`grpo`)throw Error(`Checkpoint continuation currently requires GRPO.`);if(!h.methods.includes(t))throw Error(`This account has no available execution for the selected training method.`);let n=o.trainingBaseModel;if(!n||!h.models.some(e=>e.available&&J(e.preference)===J(n)))throw Error(`Choose an available pinned starting model.`);if(!fe||fe.purpose!==(t===`sft`?`supervised_training`:`reward_training`))throw Error(`Choose a reviewed batch matching this training method.`);if(!g)throw Error(`Choose the exact validation Dataset version.`);if(!b.trim())throw Error(`Enter a name for this experiment.`);let r=Number(w);if(!Number.isFinite(r)||r<=0||r>1e6)throw Error(`Enter a positive planning budget up to $1,000,000.`);if(A===`actual_usage`&&h.billingModes?.[1].availability!==`requires_preparation`)throw Error(`Actual-usage training is not qualified for this runtime. Select the available billing mode before preparing a new run.`);let i=A===`actual_usage`?{schemaVersion:`openpond.trainingUsageFundingRequest.v1`,billingMode:`actual_usage`,customerCapUsd:vt(E)}:void 0,s=(d.dataset&&typeof d.dataset==`object`?d.dataset:{}).maxExamples;if(typeof s!=`number`||!Number.isInteger(s)||s<1||s>fe.exampleCount||t===`sft`&&s>1e3)throw Error(`Choose a valid training example count within the reviewed batch and runtime limits.`);let c=wx(d);if(c)throw Error(c);if(!re.catalog.data||re.catalogExpired||re.catalog.isFetching||re.catalog.isError)throw Error(`Refresh compute availability before reviewing this experiment.`);if(!re.catalog.data.offerings.length||re.catalog.data.scope?.qualification!==`requires_preparation`)throw Error(`No qualified compute is currently available for this model and training setup.`);if(j.mode===`manual`&&!re.catalog.data.offerings.some(e=>e.availabilityId===j.availabilityId&&e.gpuType===j.gpuType))throw Error(`The selected GPU offering is unavailable. Refresh availability or choose another offering.`);let l={teamId:e.teamId,projectId:e.projectId,baseModel:n,...o.trainingParent?{parent:o.trainingParent}:{},batch:fe.reference,name:b.trim(),maximumSpendUsd:r,...i?{usageFunding:i}:{},gpuSelection:j,settings:{method:t,recipe:{...d,dataset:{...d.dataset&&typeof d.dataset==`object`?d.dataset:{},validationSplit:v}},evaluationTasksetRef:g,rewardBindingRef:fe.rewardBinding,managedRolloutPlacement:`remote`}},u=ll.parse({draftId:o.initialExperiment?.id,form:Zn.parse(oe),request:{...l,schemaVersion:`openpond.trainingExperimentSetupRequest.v1`}}),f=await e.operation(Fx,u);a();let p=Rn.parse({...u.request,operationId:f.id});V.current={snapshot:se,intent:u,request:p,operation:f,acknowledge:f.acknowledge}}let n=V.current;await n.operation.retainCommand(n.request,`dispatching`),a();let i=n.request,s=await Sn(await c(`prepare-draft`,i));if(J(s.request)!==J(i)||s.preparation.plan.creatorUserId!==e.actorId)throw Error(`The service prepared a different experiment draft.`);I(s.preparation),H.current=null,ne(!1)}else{if(!F)throw Error(`Review this experiment before starting it.`);if(F.state===`submitted`&&F.jobId){de.allowNextNavigation(),await i(F.jobId);return}if(!V.current)throw Error(`Recover the original preparation before submitting a control.`);if(!H.current){let r;if(n===`start`){if(G)throw Error(`Return from Billing and refresh credits before starting.`);W.assertCovered(),r=re.reviewedEstimate()}let i=dl.parse({draftId:o.initialExperiment?.id,method:t,preparationOperationId:V.current.request.operationId,receipt:F,command:{action:n,id:F.plan.id,control:{teamId:e.teamId,planHash:F.plan.contentHash,expectedRevision:F.revision,...F.plan.usageQuote?{usageQuoteHash:F.plan.usageQuote.contentHash}:{},...r?{estimateReview:r}:{}}}}),s=await e.operation(Ix,i);a(),H.current={intent:i,command:i.command,operation:s,phase:`reviewed`}}let r=H.current;n===`start`&&ne(!0),await r.operation.retainCommand(r.command,`dispatching`),a(),r.phase=`dispatching`;let{action:u,...d}=r.command;l=!0;let f=await vr(await c(u,d));if(f.plan.contentHash!==F.plan.contentHash||f.plan.request.teamId!==e.teamId)throw Error(`Training control returned a different preparation.`);if(I(f),ne(!1),n===`start`&&f.state===`submitted`&&f.jobId){let e=f.jobId;try{await r.operation.acknowledge(),await V.current?.acknowledge()}catch(t){Wa(t instanceof Error?t.message:String(t))||s?.(`Training started. Desktop recovery acknowledgement is still pending.`,`error`,{dedupeKey:`training-ack:${e}`})}a(),de.allowNextNavigation(),await i(e)}else if(n===`cancel`&&f.state===`cancelled`)await r.operation.acknowledge(),await V.current?.acknowledge(),a(),H.current=null,V.current=null,await U.refetch(),I(null);else throw Error(`The preparation did not reach the requested state. Retry the same control.`)}}catch(e){if(q.current===K&&l&&e instanceof Ti&&[400,403,404,409,422].includes(e.status)&&H.current&&V.current)try{let e=V.current,t=await Sn(await c(`prepare-draft`,e.request));if(J(t.request)!==J(e.request))throw Error(`The rejected training control did not reconcile its original preparation.`);let n=t.preparation;if(n.plan.contentHash!==F?.plan.contentHash||n.state===`prepared`&&n.revision!==H.current.command.control.expectedRevision)throw Error(`Refresh the original training review before changing its control.`);await H.current.operation.acknowledge(),a(),H.current=null,ne(!1),I(n),n.state!==`prepared`&&(await e.acknowledge(),a(),V.current=null,n.state===`submitted`?P(n.jobId):I(null),await U.refetch())}catch{}q.current===K&&z(e)}finally{B.current=!1,q.current===K&&ee(!1)}}return{inputs:h,recipe:d,setRecipe:f,batch:p,setBatch:m,selectedBatch:fe,evaluation:g,setEvaluation:_,validationSplit:v,setValidationSplit:y,name:b,setName:x,startingModelLabel:S,budget:w,setBudget:T,customerCapUsd:E,setCustomerCapUsd:D,billingMode:F?F.plan.usageQuote?`actual_usage`:`prepaid_only`:A,setBillingMode:k,gpuSelection:j,setGpuSelection:M,compute:re,funding:W,billingReturnPending:G,openBilling:a?ve:null,refreshCredits:ye,startAttempted:te,pendingAction:H.current?.command.action??null,recovery:U,requiresRecovery:!(V.current||!U.data?.review),canRecover:!!(!V.current&&U.data?.review||V.current&&F&&F.state!==`prepared`),receipt:F,recoveredJobId:N,openRecoveredJob:async()=>{N&&!B.current&&await de.requestLeave(()=>{de.allowNextNavigation(),Promise.resolve(i(N)).catch(e=>{q.current===K&&z(e)})})},busy:L,locked:pe,error:R??U.error,guard:de,assertCurrentScope:he,perform:xe,saveDraft:a?_e:null}}var Vx=e=>new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,maximumFractionDigits:4}).format(e),Hx=e=>e<60?`${Math.ceil(e)} sec`:`${Math.ceil(e/60)} min`;function Ux({compute:e,selection:t,onChange:n,locked:r,method:i,budget:a,onBudgetChange:o,actualUsage:s,actualUsageAvailable:c,onBillingModeChange:l,customerCapUsd:u,onCustomerCapChange:d,prepared:f,startAttempted:p,busy:m,children:h}){let g=e.catalog.data?.offerings??[],_=t.mode===`automatic`?`auto:${t.objective}`:`offer:${t.availabilityId}`,v=t.mode===`manual`?g.find(e=>e.availabilityId===t.availabilityId):null,y=e.estimate.data;return(0,$.jsxs)(ft,{title:`Compute and spending`,children:[(0,$.jsxs)(`fieldset`,{disabled:r,children:[(0,$.jsxs)(`label`,{children:[`GPUs`,(0,$.jsx)(Z,{label:`GPU count`,floating:!0,value:String(t.gpuCount??1),options:[{value:`1`,label:`1 GPU`},{value:`2`,label:`2 GPUs`,disabled:i!==`grpo`}],onChange:e=>n(t.mode===`automatic`?{...t,gpuCount:e===`2`?2:1}:{mode:`automatic`,objective:`balanced`,gpuCount:e===`2`?2:1})})]}),(0,$.jsxs)(`label`,{children:[`GPU`,(0,$.jsx)(Z,{label:`GPU offering`,floating:!0,searchable:!0,value:_,options:[{value:`auto:balanced`,label:`Automatic · Balanced`},{value:`auto:economical`,label:`Automatic · Lowest hourly cost`},{value:`auto:fast`,label:`Automatic · Performance`},...t.mode===`manual`&&!v?[{value:_,label:`${t.gpuType} · Selected offering`,disabled:!0}]:[],...g.map(t=>({value:`offer:${t.availabilityId}`,label:`${t.gpuType} · ${s?``:`${Vx(t.totalHourlyUsd)}/hr · `}${t.dataCenterId??t.region}`,disabled:e.catalogExpired||e.catalog.isError}))],onChange:e=>{let r=g.find(t=>`offer:${t.availabilityId}`===e);r?n({mode:`manual`,availabilityId:r.availabilityId,gpuType:r.gpuType,gpuCount:r.gpuCount===2?2:1}):[`auto:balanced`,`auto:economical`,`auto:fast`].includes(e)&&n({mode:`automatic`,objective:e===`auto:fast`?`fast`:e===`auto:economical`?`economical`:`balanced`,gpuCount:t.gpuCount??1})}})]}),(0,$.jsxs)(`label`,{children:[`Billing`,(0,$.jsx)(Z,{label:`Training billing`,floating:!0,value:s?`actual_usage`:`prepaid_only`,options:[{value:`prepaid_only`,label:`Reserved budget`},{value:`actual_usage`,label:c?`Actual usage`:`Actual usage · runtime qualification required`,disabled:!c}],onChange:e=>{(e===`prepaid_only`||e===`actual_usage`)&&l(e)}})]}),s?(0,$.jsxs)(`label`,{children:[`Spending limit ($, optional)`,(0,$.jsx)(`input`,{type:`number`,min:`0.000001`,max:`1000000`,step:`any`,value:u,placeholder:`Use available credits`,onChange:e=>d(e.target.value)})]}):null,(0,$.jsxs)(`label`,{children:[s?`Planning budget ($)`:`Maximum spend ($)`,(0,$.jsx)(`input`,{type:`number`,min:`0.000001`,max:`1000000`,step:`any`,value:a,onChange:e=>o(e.target.value)})]}),s?(0,$.jsx)(`p`,{children:`The planning budget configures the training plan. The optional spending limit above caps actual usage across all components.`}):null]}),f?(0,$.jsxs)($.Fragment,{children:[e.estimate.isFetching?(0,$.jsx)(`p`,{role:`status`,children:`Estimating this experiment…`}):null,y?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`dl`,{className:`training-compute-summary`,children:[(0,$.jsx)(`dt`,{children:`Resolved GPU`}),(0,$.jsx)(`dd`,{children:y.gpu.resolved?`${y.gpu.resolved.gpuCount} × ${y.gpu.resolved.gpuType}`:`Unavailable`}),(0,$.jsx)(`dt`,{children:`Compute and disk`}),(0,$.jsx)(`dd`,{children:y.gpu.customerHourlyUsd===null?`Unknown`:`${Vx(y.gpu.customerHourlyUsd)}/hr`}),(0,$.jsx)(`dt`,{children:`Execution time`}),(0,$.jsxs)(`dd`,{children:[y.executionSeconds.expected===null?`Unknown`:Hx(y.executionSeconds.expected),y.executionSeconds.planningRange?` (${Hx(y.executionSeconds.planningRange.low)}–${Hx(y.executionSeconds.planningRange.high)} observed)`:``]}),(0,$.jsx)(`dt`,{children:`Expected total`}),(0,$.jsx)(`dd`,{children:y.cost.expectedUsd===null?`Unknown`:Vx(y.cost.expectedUsd)}),(0,$.jsx)(`dt`,{children:`Cleanup reserve`}),(0,$.jsx)(`dd`,{children:y.cost.minimumCleanupReserveUsd===null?`Unknown`:Vx(y.cost.minimumCleanupReserveUsd)})]}),(0,$.jsxs)(`p`,{children:[s?`Review the component rates and whole-job spending limit before starting.`:`The spending cap is ${Vx(Number(a))}.`,` Hourly pricing is not an estimate of the total.`]}),e.estimateExpired?(0,$.jsx)(`p`,{children:`Estimate expired. Refresh before starting.`}):null,(0,$.jsxs)(`details`,{className:`training-evidence`,children:[(0,$.jsx)(`summary`,{children:`Estimate details`}),(0,$.jsxs)(`p`,{children:[y.calibration.completedSamples,` matching completed run`,y.calibration.completedSamples===1?``:`s`,`. Queue wait is separate.`]}),(0,$.jsx)(`p`,{children:`Cost breakdown`}),(0,$.jsx)(`dl`,{className:`training-compute-summary`,children:y.cost.components.map(e=>(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(`dt`,{children:[e.phase.replaceAll(`_`,` `),` · `,e.resource===`gpu`||e.resource===`cpu`?e.resource.toUpperCase():e.resource]}),(0,$.jsxs)(`dd`,{children:[e.expectedUsd===null?`Not yet estimated`:Vx(e.expectedUsd),e.planningRangeUsd?` (${Vx(e.planningRangeUsd.low)}–${Vx(e.planningRangeUsd.high)} planning range)`:``,e.expectedSeconds===null?null:(0,$.jsxs)(`p`,{children:[Hx(e.expectedSeconds),` allocated resource time`]}),e.reason?(0,$.jsx)(`p`,{children:e.reason}):null]})]},`${e.phase}:${e.resource}`))}),y.unknowns.length?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:`Not yet estimated`}),(0,$.jsx)(`ul`,{children:y.unknowns.map((e,t)=>(0,$.jsx)(`li`,{children:e},t))})]}):null,y.assumptions.length?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:`Assumptions`}),(0,$.jsx)(`ul`,{children:y.assumptions.map((e,t)=>(0,$.jsx)(`li`,{children:e},t))})]}):null]})]}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:m||e.estimate.isFetching||p,onClick:()=>void e.estimate.refetch(),children:`Refresh estimate`})]}):(0,$.jsxs)($.Fragment,{children:[e.catalog.isFetching?(0,$.jsx)(`p`,{role:`status`,children:`Checking GPU availability…`}):null,e.catalog.data&&!e.catalog.isError?(0,$.jsx)(`p`,{children:e.catalogExpired?`Availability needs refreshing.`:`${g.length} current offering${g.length===1?``:`s`}.`}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:r||!e.query||e.catalog.isFetching,onClick:()=>void e.catalog.refetch(),children:`Refresh availability`})]}),h,(0,$.jsx)(X,{error:f?e.estimate.error:e.catalog.error})]})}function Wx({judges:e}){return e.prices.length===0?null:(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Judge model rates`}),(0,$.jsx)(`p`,{children:`USD per million tokens, within the same spending limit.`}),e.prices.map(e=>(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`p`,{children:[e.displayName,` (`,e.modelId,`)`]}),(0,$.jsxs)(`ul`,{children:[(0,$.jsxs)(`li`,{children:[`Input: $`,e.inputUsdPerMillionTokens,`; cached input: $`,e.cachedInputUsdPerMillionTokens,`; output: $`,e.outputUsdPerMillionTokens,`.`]}),e.cacheWriteUsdPerMillionTokens===null?null:(0,$.jsxs)(`li`,{children:[`Cache writes: $`,e.cacheWriteUsdPerMillionTokens,`.`]}),e.cacheWriteOneHourUsdPerMillionTokens===null?null:(0,$.jsxs)(`li`,{children:[`One-hour cache writes: $`,e.cacheWriteOneHourUsdPerMillionTokens,`.`]}),e.longContext===null?null:(0,$.jsxs)(`li`,{children:[`Long context`,e.longContextThresholdTokens===null?``:` above ${e.longContextThresholdTokens.toLocaleString()} tokens`,`:`,` `,`input $`,e.longContext.inputUsdPerMillionTokens,`; cached input $`,e.longContext.cachedInputUsdPerMillionTokens,`; output $`,e.longContext.outputUsdPerMillionTokens,`.`,e.longContext.cacheWriteUsdPerMillionTokens===null?``:` Cache writes: $${e.longContext.cacheWriteUsdPerMillionTokens}.`]})]})]},e.acceptedPricingHash))]})}function Gx({quote:e}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:e.customerCapUsd===null?`Use available credits`:`$${e.customerCapUsd} total spending limit`}),(0,$.jsxs)(`ul`,{children:[(0,$.jsxs)(`li`,{children:[`Training compute: $`,e.gpu.hourlyUsd,`/hour, including startup.`]}),e.guests.map(e=>(0,$.jsxs)(`li`,{children:[`Training environment (`,e.resources.cpu,` CPU, `,e.resources.memoryGb,` GiB memory):`,` `,`$`,e.price.hourlyUsd,`/hour while active.`]},e.profileHash)),(0,$.jsxs)(`li`,{children:[`Retained objects: $`,e.storage.price.hourlyUsd,`/GiB-hour during training and through `,e.retentionDays,` days after its accepted execution deadline.`]}),e.judges.prices.length>0?(0,$.jsx)(`li`,{children:`Judge calls use the model rates below.`}):null]}),(0,$.jsx)(Wx,{judges:e.judges}),(0,$.jsx)(`p`,{children:`Stopped training compute has no warm-idle charge. Retained storage is billed separately within the same spending limit; running out of credit does not delete saved objects.`})]})}var Kx=(0,Q.lazy)(()=>o(()=>import(`./ExperimentTrainingDataWorkspace-WhwQ0QBi.js`),__vite__mapDeps([76,1,2,3,4,77,5,6,9,10,78,32,27,31,21,16,43,19,20,22,13,23,15,24,25,26,8,28,11,29,30,33,34,35,36,37,38,39,40,41,18,42,44,45,46,47,48,49,50,51,52,53,54,55,56,79,80])));function qx({api:e,method:t,visible:n,navigate:r,onClose:i,onSaveDraft:a,onStarted:o}){let s=kv(),[c,l]=(0,Q.useState)(!1),u=(0,Q.useRef)(null),d=(0,Q.useRef)(null),f=Bx(e,t,n,i,async t=>{o?await o(t):(s.close(),r(as(`runs`,null,{projectId:e.projectId,resourceId:`hosted-run:${t}`,detailTab:`details`})))},a),{inputs:p,locked:m,receipt:h}=f;My({...f.guard,async requestLeave(e){c&&u.current?await u.current.requestLeave(()=>f.guard.requestLeave(e)):await f.guard.requestLeave(e)}},n);let g=p.models.find(e=>J(e.preference)===J(s.trainingBaseModel)),_=f.recipe.dataset&&typeof f.recipe.dataset==`object`?f.recipe.dataset:{},v=_.maxExamples,y=p.batches.filter(e=>e.purpose===(t===`sft`?`supervised_training`:`reward_training`)),b=()=>{l(!1),requestAnimationFrame(()=>d.current?.focus())};function x(e){f.setBatch(e.reference),f.setRecipe({...f.recipe,dataset:{..._,maxExamples:Math.min(typeof v==`number`&&v>0?v:1e3,e.exampleCount,t===`sft`?1e3:1e5)}})}async function S(e){if(f.assertCurrentScope(),f.busy||h||!n)throw Error(`Return to the editable experiment before selecting training data.`);if(Fe(e),e.purpose!==(t===`sft`?`supervised_training`:`reward_training`))throw Error(`Choose a reviewed batch matching this experiment's training method.`);x({reference:xe(e),rewardBinding:e.rewardBinding,purpose:e.purpose,exampleCount:e.examples.length,sealedAt:e.sealedAt}),b()}return c?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(Bv,{label:`Experiment training data`,action:`experiment`,children:(0,$.jsx)(`p`,{role:`status`,children:`Opening training data…`})}),children:(0,$.jsx)(Kx,{api:e,method:t,navigation:u,onClose:b,onUseBatch:S},e.key)}),f.guard.dialog]}):(0,$.jsxs)(Bv,{label:`Experiment setup`,action:`experiment`,onRequestClose:()=>void f.guard.requestLeave(i),children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`h2`,{children:`Run Experiment`}),a?(0,$.jsx)(`button`,{type:`button`,disabled:f.busy,onClick:()=>void f.guard.requestLeave(i),children:`Close setup`}):null]}),(0,$.jsxs)(`form`,{noValidate:!0,onSubmit:e=>{e.preventDefault(),f.perform(f.pendingAction??(h?`start`:`prepare`))},children:[(0,$.jsx)(ft,{title:`Starting model`,children:(0,$.jsxs)(`fieldset`,{disabled:m,children:[(0,$.jsxs)(`label`,{children:[`Model`,(0,$.jsx)(Z,{floating:!0,searchable:!0,label:`Starting model`,value:s.trainingParent||s.startingModel?.source===`trained`||s.startingModel?.source===`steering`?`parent`:g?.id??(s.trainingBaseModel?`retained`:``),options:[{value:``,label:`Choose model`},...s.trainingParent||s.startingModel?.source===`trained`||s.startingModel?.source===`steering`?[{value:`parent`,label:s.startingModel?.label??f.startingModelLabel??`Selected trained checkpoint`}]:[],...s.trainingBaseModel&&!g?[{value:`retained`,label:s.trainingBaseModel.modelId,disabled:!0}]:[],...p.models.map(e=>({value:e.id,label:e.name,disabled:!e.available}))],onChange:e=>{e!==`parent`&&(s.setTrainingParent(null),s.setTrainingBaseModel(p.models.find(t=>t.id===e)?.preference??null))}})]}),s.trainingParent?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:`Starting from the selected trained checkpoint. The optimizer starts fresh.`}),t===`grpo`?(0,$.jsxs)(`label`,{children:[`LoRA continuation`,(0,$.jsx)(Z,{label:`LoRA continuation`,floating:!0,value:s.trainingParent.adapterMode,options:[{value:`shared`,label:`Shared · update the existing adapter`},{value:`residual_append`,label:`Stacked · freeze the parent and add an adapter`},{value:`sequential_merge`,label:`Merged · merge the parent, then train a new adapter`}],onChange:e=>{s.trainingParent&&(e===`shared`||e===`residual_append`||e===`sequential_merge`)&&s.setTrainingParent({...s.trainingParent,adapterMode:e})}})]}):null]}):null,(0,$.jsx)(xy,{disabled:m})]})}),(0,$.jsx)(ft,{title:`Training data`,children:(0,$.jsxs)(`fieldset`,{disabled:m,children:[(0,$.jsxs)(`label`,{children:[`Reviewed examples`,(0,$.jsx)(Z,{label:`Reviewed examples`,floating:!0,searchable:!0,value:f.batch?J(f.batch):``,options:[{value:``,label:`Choose reviewed batch`},...f.batch&&!y.some(e=>J(e.reference)===J(f.batch))?[{value:J(f.batch),label:`${f.batch.id} · r${f.batch.revision}`,disabled:!0}]:[],...y.map(e=>({value:J(e.reference),label:`${e.exampleCount} example${e.exampleCount===1?``:`s`} · ${e.reference.id} · r${e.reference.revision}`}))],onChange:e=>{let t=y.find(t=>J(t.reference)===e);t?x(t):f.setBatch(null)}})]}),f.selectedBatch?(0,$.jsxs)(`p`,{children:[f.selectedBatch.exampleCount,` reviewed example`,f.selectedBatch.exampleCount===1?``:`s`,`.`,` `,t===`sft`?`Supervised targets`:`Reward binding`,` `,`retained with this batch.`]}):null,p.hasNextPage?(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:p.isFetchingNextPage,onClick:()=>void p.fetchNextPage(),children:`More reviewed batches`}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,ref:d,onClick:()=>l(!0),children:`Import or review data`})]})}),(0,$.jsx)(ft,{title:`Validation`,children:(0,$.jsxs)(`fieldset`,{disabled:m,children:[(0,$.jsx)(ky,{api:e,value:f.evaluation,onChange:f.setEvaluation,disabled:m}),(0,$.jsxs)(`label`,{children:[`Optimizer validation split`,(0,$.jsx)(Z,{label:`Optimizer validation split`,floating:!0,value:f.validationSplit,options:[{value:`validation`,label:`Validation`},{value:`frozen_eval`,label:`Frozen evaluation`}],onChange:e=>f.setValidationSplit(e)})]}),(0,$.jsx)(`p`,{children:`This split is visible during optimization. Keep independent acceptance holdouts separate.`})]})}),(0,$.jsx)(ft,{title:`Training settings`,children:(0,$.jsxs)(`fieldset`,{disabled:m,children:[(0,$.jsxs)(`label`,{children:[`Training examples`,(0,$.jsx)(`input`,{type:`number`,min:1,max:Math.min(f.selectedBatch?.exampleCount??1e5,t===`sft`?1e3:1e5),step:1,value:typeof v==`number`||typeof v==`string`?v:``,onChange:e=>f.setRecipe({...f.recipe,dataset:{..._,maxExamples:e.target.value===``?``:e.target.valueAsNumber}})})]}),(0,$.jsx)(Tx,{recipe:f.recipe,onChange:e=>{e&&f.setRecipe(e)}}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Run details`}),(0,$.jsxs)(`label`,{children:[`Name`,(0,$.jsx)(`input`,{value:f.name,onChange:e=>f.setName(e.target.value),maxLength:191})]})]})]})}),(0,$.jsx)(Ux,{compute:f.compute,selection:f.gpuSelection,onChange:f.setGpuSelection,locked:m,method:t,budget:f.budget,onBudgetChange:f.setBudget,actualUsage:f.funding.allocationAdmission,actualUsageAvailable:p.billingModes?.[1].availability===`requires_preparation`,onBillingModeChange:f.setBillingMode,customerCapUsd:f.customerCapUsd,onCustomerCapChange:f.setCustomerCapUsd,prepared:h?.state===`prepared`,startAttempted:f.startAttempted,busy:f.busy,children:(0,$.jsx)(Db,{funding:f.funding,busy:f.busy,startAttempted:f.startAttempted,billingReturnPending:f.billingReturnPending,onOpenBilling:f.openBilling,onRefresh:f.refreshCredits})}),f.canRecover?(0,$.jsxs)(ft,{title:`Previous training review`,children:[(0,$.jsxs)(`p`,{children:[f.recovery.data?.review?.request.name,f.recovery.data?.review?.request.usageFunding?f.recovery.data.review.request.usageFunding.customerCapUsd===null?` · Use available credits`:` · $${f.recovery.data.review.request.usageFunding.customerCapUsd} spending limit`:` · $${f.recovery.data?.review?.request.maximumSpendUsd} maximum spend`]}),(0,$.jsx)(`p`,{children:`The original request is retained on this device. Restore it to check the current preparation or existing run.`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:f.busy,onClick:()=>void f.guard.requestLeave(()=>f.perform(`recover`)),children:`Restore previous review`})]}):null,h?(0,$.jsxs)(ft,{title:`Reviewed experiment`,children:[(0,$.jsxs)(`p`,{children:[h.plan.request.name,h.plan.usageQuote?null:` · $${h.plan.request.maximumSpendUsd} maximum spend`]}),h.plan.usageQuote?(0,$.jsx)(Gx,{quote:h.plan.usageQuote}):null,(0,$.jsx)(`p`,{children:h.state===`submitted`?`This experiment already has a training Job.`:h.state===`cancelled`?`Preparation cancelled. Finish editing to prepare another run.`:`Start training submits this preparation to hosted execution.`}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact inputs`}),(0,$.jsx)(`pre`,{children:JSON.stringify(h.plan.source,null,2)})]})]}):null,f.error||p.error?(0,$.jsx)(X,{error:f.error??p.error}):null,f.recovery.isError?(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:f.busy,onClick:()=>void f.recovery.refetch(),children:`Reload retained reviews`}):null,p.error?(0,$.jsx)(`button`,{className:`training-text-button`,type:`button`,onClick:()=>void p.refetch(),children:`Reload training inputs`}):null,p.isPending?(0,$.jsx)(`p`,{role:`status`,children:`Loading training inputs…`}):null,f.recoveredJobId?(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:f.busy,onClick:()=>void f.openRecoveredJob(),children:`Open existing training run`}):null,f.recoveredJobId?(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:f.busy,onClick:()=>void f.perform(`prepare`,{newRun:!0}),children:`Review edited settings for a new run`}):null,f.saveDraft?(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:m,onClick:()=>void f.saveDraft?.(),children:`Save draft`}):null,(0,$.jsx)(`button`,{className:`training-button`,type:`submit`,disabled:f.busy||!f.recovery.isSuccess||f.requiresRecovery||!!f.recoveredJobId||h?.state===`cancelled`||h?.state===`prepared`&&f.pendingAction!==`cancel`&&!f.startAttempted&&(!f.compute.canStart||!f.funding.canStart||f.billingReturnPending),children:f.busy?`Working…`:f.pendingAction===`cancel`?`Retry edit setup`:h?.state===`submitted`?`Open training run`:h?f.startAttempted?`Retry start`:`Start training`:`Review experiment`}),h?(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:f.busy||!!f.pendingAction||h.state===`submitted`,onClick:()=>void f.perform(`cancel`),children:`Edit setup`}):null]}),f.guard.dialog]})}function Jx(e,t,n){let r=t?{teamId:e.teamId,modelId:t.modelId,source:t.source,...t.revision?{revision:t.revision}:{},...t.tokenizerRevision?{tokenizerRevision:t.tokenizerRevision}:{},...t.chatTemplateHash?{chatTemplateHash:t.chatTemplateHash}:{},...t.modelAssetId?{modelAssetId:t.modelAssetId}:{}}:null,i=S({queryKey:[`model-modification-capabilities`,e.key,e.actorId,r],enabled:n&&r!==null,retry:!1,staleTime:3e4,refetchInterval:e=>!e.state.error&&6e4,queryFn:async({signal:t})=>{if(!r)throw Error(`Select a starting model before reading capabilities.`);return pr(await Y(e.connection,`/v1/training/setup/modification-capabilities?teamId=${encodeURIComponent(e.teamId)}`,{method:`POST`,body:JSON.stringify(r),signal:t}),r,e.actorId??void 0)}}),a=!!(i.data&&Date.parse(i.data.expiresAt)>Date.now());return{...i,current:a?i.data:void 0,canRefresh:!!r}}function Yx(e,t){let n=ml.parse({teamId:e.teamId,actorId:e.actorId,apiOrigin:t}),r={...n,projectId:e.projectId},i=`/v1/training/modification-executions`;return{account:n,async compile(t){return kn(await Y(e.connection,`${i}/compile`,{method:`POST`,body:JSON.stringify({...r,command:t})}),t)},async mutate(t,a){let o=`action`in t?`${i}/${encodeURIComponent(t.id)}/${t.action}`:`${i}/prepare`,s=await ar(await Y(e.connection,o,{method:`POST`,body:JSON.stringify({...r,intentHash:a,command:t})}),t);if(s.execution.ownerUserId!==n.actorId||s.execution.projectId!==e.projectId)throw Error(`The execution receipt belongs to another account or Project.`);return s},async get(t,r){let a=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}}),o=await dr(await Y(e.connection,`${i}/${encodeURIComponent(t)}?${a}`,{signal:r}),{teamId:e.teamId,id:t,ownerUserId:n.actorId});if(o.projectId!==e.projectId)throw Error(`The execution belongs to another Project.`);return o},async list(t={},r){let a={...t,...e.projectId?{projectId:e.projectId}:{}},o=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}});for(let[e,t]of Object.entries(a))t!==void 0&&o.set(e,String(t));return Xn(await Y(e.connection,`${i}?${o}`,{signal:r}),{teamId:e.teamId,ownerUserId:n.actorId,query:a})}}}function Xx(e,t=!0){return S({queryKey:[`activation-experiment-account`,e.key,e.actorId],enabled:t&&e.location===`hosted`&&!!e.actorId,retry:!1,queryFn:async({signal:t})=>{let n=await e.request(`inventory`,{},t);if(n.teamId!==e.teamId)throw Error(`The workspace account changed.`);return Yx(e,n.apiOrigin)}})}function Zx(e,t){return!(e instanceof Ti)||e.status!==409||e.retryable!==!1?!1:(`action`in t?[`modification_execution_revision_conflict`,`modification_execution_review_required`,`modification_execution_runtime_changed`,`modification_execution_funding_changed`,`modification_execution_project_archived`,`modification_execution_cancel_unavailable`]:[`modification_execution_runtime_unavailable`,`modification_execution_runtime_limits`,`modification_execution_capability_changed`,`modification_execution_project_archived`]).includes(e.code??``)}var Qx=[`training:prepare-modification`,`training:start-modification`,`training:cancel-modification`];function $x(e,t){let n=u(),r=J([e.key,e.connection.serverUrl,t.draftId,t.executionId,t.method]),i=(0,Q.useRef)(r);i.current=r,(0,Q.useEffect)(()=>(i.current=r,()=>{i.current=``}),[r]);let a=()=>({identity:r,busy:!1,error:null,receipt:null,selected:null,original:null,preparationOperationId:null}),[o,s]=(0,Q.useState)(a),c=(0,Q.useRef)(new Set),l=o.identity===r?o:a();function d(e){i.current===r&&s(t=>({...t.identity===r?t:a(),...e}))}function f(){if(i.current!==r)throw Error(`Return to this experiment's original account before continuing.`)}let p=Xx(e,t.visible),m=p.data,h=S({queryKey:[`activation-experiment-recovery`,r],enabled:t.visible&&e.location===`hosted`&&!!e.actorId&&!l.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[];for(let i of Qx){let a,o=new Set;for(let s=0;;s++){if(s>=100)throw Error(`The retained execution catalog exceeds its supported bound.`);let c=await e.pendingOperations(i,a,n);for(let n of c.items){let a=i===Qx[0]?hl.parse(n.reviewedIntent):gl.parse(n.reviewedIntent);if(a.account.actorId!==e.actorId||a.account.teamId!==e.teamId)throw Error(`The retained execution belongs to another account.`);if(!(t.draftId===null?`execution`in a&&a.execution.id===t.executionId:a.draftId===t.draftId))continue;let o=i===Qx[0]?Kt.parse(n.command??{...a.request,operationId:n.id}):Wt(n.command??{...a.request,operationId:n.id});r.push({intent:a,command:o,operation:e.recoverOperation(n)})}if(!c.nextCursor)break;if(o.has(c.nextCursor))throw Error(`The retained execution catalog repeated a cursor.`);o.add(c.nextCursor),a=c.nextCursor}}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),g=l.original??h.data?.[0]??null,_=t.executionId??l.selected??l.receipt?.execution.id??(g&&`execution`in g.intent?g.intent.execution.id:null),v=S({queryKey:[`managed-modification-execution`,r,_],enabled:t.visible&&!!(m&&_),retry:!1,queryFn:({signal:e})=>{if(!m||!_)throw Error(`Select an execution first.`);return m.get(_,e)},refetchInterval:e=>e.state.error?!1:e.state.data&&![`completed`,`failed`,`cancelled`].includes(e.state.data.phase)?3e3:!1});async function y(t){let r=Yx(e,t.intent.account.apiOrigin);if(J(r.account)!==J(t.intent.account))throw Error(`Return to this execution's original account before retrying.`);d({original:t}),await t.operation.retainCommand(t.command,`dispatching`),f();let i;try{i=await r.mutate(t.command,t.operation.intentHash),f()}catch(e){throw Zx(e,t.command)&&(await t.operation.acknowledge(),f(),d({original:null}),await h.refetch(),f(),n.invalidateQueries({queryKey:[`managed-modification-execution`]})),e}return d({receipt:i,selected:i.execution.id,preparationOperationId:`action`in t.command?`preparationOperationId`in t.intent?t.intent.preparationOperationId:null:t.command.operationId}),await t.operation.acknowledge(),f(),d({original:null}),await h.refetch(),f(),n.invalidateQueries({queryKey:[`managed-modification-execution`]}),n.invalidateQueries({queryKey:[`unified-experiments`]}),i}async function b(e){if(!c.current.has(r)){c.current.add(r),d({busy:!0,error:null});try{return f(),await e()}catch(e){return i.current===r&&d({error:e}),null}finally{c.current.delete(r),d({busy:!1})}}}async function x(n,r){return b(async()=>{if(g)return y(g);if(!m||!h.isSuccess||!t.draftId||n.id!==t.draftId||!n.activationForm||!t.method)throw Error(`Load this saved experiment and original requests before preparing.`);let i=vt(n.activationForm.maximumSpendUsd);await r(n),f();let a=await Iy(e).get(n.id);if(f(),a.status!==`draft`||a.projectId!==e.projectId||J(a.draft)!==J(n))throw Error(`The saved experiment changed. Reopen its exact current revision before preparing.`);let o=n.activationForm.baseModel;if(!o||n.startingModel?.source===`trained`)throw Error(`Choose a qualified exact activation starting model.`);let s={teamId:e.teamId,modelId:o.modelId,source:o.source,...o.revision?{revision:o.revision}:{},...o.tokenizerRevision?{tokenizerRevision:o.tokenizerRevision}:{},...o.chatTemplateHash?{chatTemplateHash:o.chatTemplateHash}:{},...o.modelAssetId?{modelAssetId:o.modelAssetId}:{}},c={teamId:e.teamId,projectId:e.projectId,method:t.method,query:s,form:n.activationForm},l=await m.compile(c);if(f(),l.actorId!==e.actorId||l.formHash!==await zr(n.activationForm))throw Error(`The compilation differs from this exact saved form.`);let u=await Ln({teamId:e.teamId,projectId:e.projectId,operationId:crypto.randomUUID(),name:n.name,method:t.method,query:s,request:l.request,sourceForm:n.activationForm,maximumSpendUsd:i}),{operationId:d,...p}=u,_=hl.parse({account:m.account,draftId:n.id,request:p}),v=await e.operation(Qx[0],_);return f(),y({intent:_,operation:v,command:{...u,operationId:v.id}})})}async function C(n,r){return b(async()=>{if(g)return y(g);let i=r??v.data;if(!m||!h.isSuccess||!i||v.error)throw Error(`Read the exact execution before reviewing its next action.`);let{schemaVersion:a,request:o,sourceForm:s,result:c,resultRecordedAt:u,contentHash:d,...p}=i,_=Vt.parse(p),b=n===`start`?{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n,approvedMaximumSpendUsd:i.plan.maximumSpendUsd,...i.plan.computePrice?{approvedPriceHash:await zr(i.plan.computePrice)}:{}}:{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n},x=gl.parse({account:m.account,draftId:l.preparationOperationId?t.draftId:null,preparationOperationId:l.preparationOperationId,execution:_,request:b}),S=await e.operation(n===`start`?Qx[1]:Qx[2],x);return f(),y({intent:x,operation:S,command:Wt({...b,operationId:S.id})})})}return{prepare:x,control:C,retry:()=>b(()=>{if(!g)throw Error(`Reload the original execution request.`);return y(g)}),busy:l.busy,receipt:l.receipt,original:g,execution:v.data,ready:p.isSuccess&&h.isSuccess,recoveryReady:h.isSuccess,canControl:v.isSuccess&&!v.error,error:l.error??p.error??h.error??v.error,refresh:()=>{p.refetch(),e.actorId&&h.refetch(),m&&_&&v.refetch()},loading:v.isFetching||p.isFetching,selectedId:_}}function eS(e,t){return{key:JSON.stringify([t.accountKey,t.actorId??null,t.teamId,t.projectId,t.executionLocation??`hosted`]),connection:e,actorId:t.actorId??null,teamId:t.teamId,projectId:t.projectId,location:t.executionLocation??`hosted`,accountKey:t.accountKey,localDatasets(t,n={},r,i){return Y(e,`/v1/local-datasets`,{method:`POST`,body:JSON.stringify({action:t,payload:n,...r?{id:r}:{}}),signal:i})},humanContext:t.actorId?{connection:e,scope:t.teamId,actorId:t.actorId,location:t.executionLocation??`hosted`}:null,local(n,r={},i){return Y(e,`/v1/local-experiments`,{method:`POST`,body:JSON.stringify({teamId:t.teamId,projectId:t.projectId,action:n,payload:r}),signal:i})},request(n,r,i){return Y(e,`/v1/training/evaluation-workspace`,{method:`POST`,body:JSON.stringify({teamId:t.teamId,projectId:t.projectId,operation:n,...r===void 0?{}:{value:r}}),signal:i})},async pendingOperations(n,r,i){return sl.parse(await Y(e,`/v1/training/evaluation-workspace`,{method:`POST`,body:JSON.stringify({teamId:t.teamId,projectId:t.projectId,operation:`pendingOperations`,value:{action:n,...r?{cursor:r}:{}}}),signal:i}))},recoverOperation(e){let t=ol.parse(e);return r(t.action,t.intentHash,{id:t.id,createdAt:t.createdAt})},operation(e,t){return n(e,t)},localOperation(e,t){return n(`local:${e}`,t)}};async function n(n,i){let a=al.safeParse(n).success,o=ie(i),s={teamId:t.teamId,projectId:t.projectId};return r(n,o,await Y(e,`/v1/training/evaluation-workspace`,{method:`POST`,body:JSON.stringify({...s,operation:`prepareOperation`,value:{action:n,intentHash:o,...a?{reviewedIntent:i}:{}}})}))}function r(n,r,i){let a=al.safeParse(n).success,o={teamId:t.teamId,projectId:t.projectId};return{...i,intentHash:r,async retainCommand(t,s=`reviewed`){if(!a)throw Error(`This evaluation operation has no reviewed command catalog.`);return Y(e,`/v1/training/evaluation-workspace`,{method:`POST`,body:JSON.stringify({...o,operation:`retainOperation`,value:{action:n,intentHash:r,id:i.id,command:t,phase:s}})})},async acknowledge(t){await Y(e,`/v1/training/evaluation-workspace`,{method:`POST`,body:JSON.stringify({...o,operation:`acknowledgeOperation`,value:{action:n,intentHash:r,id:i.id,...t?{expectedPhase:t}:{}}})})}}}}function tS(e,t){return eS(e.connection,{teamId:e.teamId,projectId:e.projectId,actorId:e.actorId,accountKey:e.accountKey,executionLocation:t})}function nS(e){let t=new Set(e.request.variants.filter(e=>e.profile===null).map(e=>e.id)),n=new Map;for(let r of e.result?.captures??[])t.has(r.variantId)&&n.set(`${r.layer}:${r.neuron}`,{layer:r.layer,neuron:r.neuron});return[...n.values()].sort((e,t)=>e.layer-t.layer||e.neuron-t.neuron)}function rS(e){let t=e.sourceForm?.baseModel,n=e.request.model;return e.phase===`completed`&&!!e.result&&t?.source===`managed`&&t.modelAssetId===null&&t.modelId===n.modelId&&t.revision===n.revision&&!e.sourceForm?.startingProfile&&n.adapter===null&&n.architecture===`dense_decoder`&&n.dtype===`bfloat16`&&n.quantization===`none`}async function iS(e,t,n){let r=mt.parse(n);if(!rS(e)||!e.result||!e.sourceForm?.baseModel)throw Error(`Choose a completed inspection of the exact unmodified dense base before training selected neurons.`);let i=await Et(e.result,e.request);if(r.owner.teamId!==e.teamId||r.owner.actorId!==e.ownerUserId||r.projectId!==e.projectId||r.executionId!==e.id||r.method!==e.method||r.inputHash!==e.plan.inputHash||r.runtimeHash!==e.plan.runtimeHash||r.resultHash!==i.contentHash)throw Error(`The selected inspection differs from its original account, Project or retained result.`);let a=new Set(nS(e).map(e=>`${e.layer}:${e.neuron}`)),o=[...new Map(t.map(e=>[`${e.layer}:${e.neuron}`,e])).values()].sort((e,t)=>e.layer-t.layer||e.neuron-t.neuron);if(!o.length||o.length>128||o.some(e=>!a.has(`${e.layer}:${e.neuron}`)))throw Error(`Select between 1 and 128 neurons observed under Off in this exact inspection.`);let s=e.sourceForm.baseModel,c=nn(s),l=`Train selected neurons · ${e.name}`.slice(0,500);return Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:crypto.randomUUID(),operationType:`selective_neuron_training`,name:l,startingModel:{source:`managed`,label:s.modelId,baseModel:s,inferenceModelId:null},neuronTrainingForm:{...c,name:l,selection:{...c.selection,count:String(o.length),coordinates:o.map(e=>`${e.layer}:${e.neuron}`).join(`
13
- `)},inspectionSource:{result:r,modelHash:await zr(e.request.model)}}})}function aS({execution:e,api:t,disabled:n=!1}){let r=kv(),i=(0,Q.useMemo)(()=>eS(t.connection,{teamId:t.teamId,actorId:t.actorId,accountKey:t.accountKey,projectId:e.projectId,executionLocation:`hosted`}),[t.key,e.projectId]),a=Xx(i,rS(e)),[o,s]=(0,Q.useState)([]),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(null),f=JSON.stringify([i.key,e.id,e.result?.contentHash]),p=(0,Q.useRef)(f);p.current=f,(0,Q.useEffect)(()=>(p.current=f,s([]),l(!1),d(null),()=>{p.current=``}),[f]);let m=(0,Q.useMemo)(()=>nS(e),[e]);if(!rS(e)||!m.length)return null;let h=m.filter(e=>o.includes(`${e.layer}:${e.neuron}`));async function g(){if(!c&&!n&&a.data&&h.length){l(!0),d(null);try{let t=await a.data.get(e.id);if(p.current!==f)return;if(t.result?.contentHash!==e.result?.contentHash)throw Error(`Refresh the original inspection before selecting its neurons.`);let n=mt.parse({kind:`managed_modification_result`,location:`cloud`,apiOrigin:a.data.account.apiOrigin,owner:{teamId:i.teamId,actorId:i.actorId},projectId:t.projectId,executionId:t.id,method:t.method,inputHash:t.plan.inputHash,runtimeHash:t.plan.runtimeHash,resultHash:t.result.contentHash}),o=await iS(t,h,n);if(p.current!==f)return;await r.openDraft(o,as(`experiments`,null,{projectId:t.projectId,executionLocation:`hosted`}))}catch(e){p.current===f&&d(e)}finally{p.current===f&&l(!1)}}}return(0,$.jsxs)(`section`,{"aria-label":`Train neurons from inspection`,children:[(0,$.jsx)(X,{error:u??a.error}),(0,$.jsx)(`div`,{className:`evaluation-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`caption`,{children:`Neurons observed under Off`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:`Select`}),(0,$.jsx)(`th`,{scope:`col`,children:`Layer`}),(0,$.jsx)(`th`,{scope:`col`,children:`Neuron`})]})}),(0,$.jsx)(`tbody`,{children:m.map(e=>{let t=`${e.layer}:${e.neuron}`,r=o.includes(t);return(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Train layer ${e.layer} neuron ${e.neuron}`,checked:r,disabled:c||n||!r&&o.length>=128,onChange:e=>s(n=>e.target.checked?[...n,t]:n.filter(e=>e!==t))})}),(0,$.jsx)(`td`,{children:e.layer}),(0,$.jsx)(`td`,{children:e.neuron})]},t)})})]})}),(0,$.jsxs)(`p`,{children:[h.length,` selected. The editor retains this inspection and exact base; choose reviewed target and background data before Run.`]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:c||n||!a.isSuccess||!h.length,onClick:()=>void g(),children:c?`Opening experiment…`:`Train selected neurons`})]})}var oS=`training-steering-result-save`;function sS(e){return e instanceof Ti&&e.status===409&&e.retryable===!1&&[`steering_profile_revision_conflict`,`steering_model_revision_conflict`,`steering_model_serving_in_use`,`steering_model_base_mismatch`,`steering_profile_result_changed`,`steering_profile_result_unavailable`].includes(e.code??``)}function cS(e,t,n){let r=u(),i=J([e.key,ra(e.connection),t]),a=(0,Q.useRef)(i);a.current=i,(0,Q.useEffect)(()=>(a.current=i,()=>{a.current=``}),[i]);let o=()=>({identity:i,busy:!1,error:null,original:null,receipt:null}),[s,c]=(0,Q.useState)(o),l=(0,Q.useRef)(new Set),d=s.identity===i?s:o();function f(e){a.current===i&&c(t=>({...t.identity===i?t:o(),...e}))}function p(){if(a.current!==i)throw Error(`Return to this Model save's original account and result.`)}let m=n?.method===`neuron_steering`&&n.phase===`completed`&&n.result!==null,h=Xx(e,m),g=S({queryKey:[`steering-model-save-recovery`,i],enabled:!!e.actorId&&!d.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[],i=new Set,a;for(let o=0;;o++){if(o>=100)throw Error(`The retained Model save catalog exceeds its supported bound.`);let s=await e.pendingOperations(oS,a,n);for(let n of s.items){let i=bl.parse(n.reviewedIntent);if(i.request.executionId!==t)continue;if(i.account.actorId!==e.actorId||i.account.teamId!==e.teamId||i.execution.projectId!==e.projectId)throw Error(`The retained Model save belongs to another creator or Project.`);let a=Pt.parse(n.command??{...i.request,operationId:n.id});r.push({intent:i,command:a,operation:e.recoverOperation(n)})}if(!s.nextCursor)break;if(i.has(s.nextCursor))throw Error(`The retained Model save catalog repeated a cursor.`);i.add(s.nextCursor),a=s.nextCursor}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),_=d.original??g.data?.[0]??null,v=S({queryKey:[`steering-model-save-options`,i,h.data?.account.apiOrigin,n?.result?.contentHash],enabled:m&&h.isSuccess&&g.isSuccess&&!_&&!d.busy,retry:!1,queryFn:async({signal:n})=>{if(!h.data)throw Error(`Read the configured result account first.`);let r=h.data.account,i=new URLSearchParams({...r,...e.projectId?{projectId:e.projectId}:{}}),a=xl.parse(await Y(e.connection,`/v1/training/modification-executions/${encodeURIComponent(t)}/model?${i}`,{signal:n}));if(J(a.account)!==J(r)||a.executionId!==t||a.projectId!==e.projectId)throw Error(`The Model targets differ from this exact result account or Project.`);return a}});async function y(t){f({original:t}),await t.operation.retainCommand(t.command,`dispatching`),p();let n;try{let r=await Y(e.connection,`/v1/training/modification-executions/${encodeURIComponent(t.command.executionId)}/model`,{method:`POST`,body:JSON.stringify({...t.intent.account,projectId:t.intent.execution.projectId,intentHash:t.operation.intentHash,command:t.command})});if(n=await hr(r,t.command),p(),n.actorId!==e.actorId||n.record.publication.projectId!==e.projectId)throw Error(`The saved Model receipt belongs to another creator or Project.`)}catch(e){throw sS(e)&&(await t.operation.acknowledge(),p(),f({original:null}),await g.refetch(),p(),v.refetch()),e}f({receipt:n});for(let e of[`saved-training-model`,`saved-model-serving`,`steering-model-save-options`,`unified-experiments`,`model-projects`])r.invalidateQueries({queryKey:[e]});return await t.operation.acknowledge(),p(),f({original:null}),await g.refetch(),p(),n}async function b(r){if(l.current.has(i))return null;l.current.add(i),f({busy:!0,error:null});try{if(p(),!g.isSuccess)throw Error(`Reload the original Model saves before continuing.`);if(_)return await y(_);if(!m||!n?.result||!v.isSuccess||!h.isSuccess||!v.data)throw Error(`Read the completed steering result and current Model targets before saving.`);let i=n.request.variants.find(e=>e.id===r.variantId);if(!i?.profile)throw Error(`Choose an exact saved profile variant; Off and inspection cannot be saved as a steering Model.`);let a=r.modelProjectId?v.data.models.find(e=>e.id===r.modelProjectId):null;if(r.modelProjectId&&!a)throw Error(`Refresh the Model targets before updating this Model.`);let{schemaVersion:o,request:s,sourceForm:c,result:l,resultRecordedAt:u,contentHash:d,...f}=n,b=bl.parse({account:v.data.account,execution:Vt.parse(f),request:{teamId:e.teamId,executionId:t,variantId:i.id,resultHash:n.result.contentHash,profileHash:i.profile.contentHash,name:r.name,modelProjectId:a?.id??null,expectedModelRevision:a?.revision??0}}),x=await e.operation(oS,b);return p(),await y({intent:b,operation:x,command:Pt.parse({...b.request,operationId:x.id})})}catch(e){return a.current===i&&f({error:e}),null}finally{l.current.delete(i),f({busy:!1})}}return{save:b,busy:d.busy,receipt:d.receipt,original:_,options:v.data,freshReady:m&&g.isSuccess&&v.isSuccess&&h.isSuccess,recoveryReady:g.isSuccess,error:d.error??g.error??(m?v.error??h.error:null),refresh:()=>{g.refetch(),m&&!_&&(h.refetch(),h.data&&v.refetch())}}}function lS({api:e,id:t,execution:n,disabled:r=!1}){let i=cS(e,t,n),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)((n?.name??`Steering Model`).slice(0,200)),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(``),p=n?.request.variants.filter(e=>e.profile!==null)??[],m=p.some(e=>e.id===l)?l:p[0]?.id??``,h=i.original?.command,g=iy({name:`Steering Model save`,busy:i.busy,dirty:a&&(!!h||s!==(n?.name??`Steering Model`).slice(0,200)||!!d||!!l),discardDescription:h?`The original save remains recoverable from this execution after closing.`:void 0});if(n?.method===`inspect_activations`)return null;let _=n?.method===`neuron_steering`&&n.phase===`completed`&&n.result!==null&&p.length>0,v=!i.recoveryReady&&i.error!==null;if(!_&&!h&&!i.receipt&&!v)return null;let y=i.receipt?.version;return(0,$.jsxs)(`section`,{className:`training-detail-section`,"aria-label":`Save steering Model`,children:[(0,$.jsx)(X,{error:i.error}),i.recoveryReady?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Reload retained Model saves`}),i.receipt&&y?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[`Saved to `,i.receipt.model?.name,`. Exact version `,(0,$.jsx)(`code`,{children:y.contentHash}),`.`]}),(0,$.jsx)(hb,{connection:e.connection,version:y,api:e},`${e.key}:${y.contentHash}`)]}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:r||i.busy||!i.recoveryReady,onClick:()=>o(!0),children:h?`Recover Model save`:i.receipt?`Save another variant`:`Save model`}),a?(0,$.jsxs)(qa,{ariaLabel:`Save steering model`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:i.busy,onClose:()=>void g.requestLeave(()=>o(!1)),children:[(0,$.jsx)(`h2`,{children:`Save model`}),(0,$.jsx)(`p`,{children:`Save one exact profile from the completed hosted result. Off remains the control comparison; saving does not activate serving.`}),(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),i.save({name:s,variantId:m,modelProjectId:d||null}).then(e=>{e&&(g.allowNextNavigation(),o(!1))})},children:[(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Profile variant`}),(0,$.jsx)(Z,{label:`Profile variant`,value:h?.variantId??m,options:h?[{value:h.variantId,label:h.variantId}]:p.map(e=>({value:e.id,label:e.id})),disabled:i.busy||!!h,onChange:u})]}),(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Save destination`}),(0,$.jsx)(Z,{label:`Model destination`,value:h?.modelProjectId??(h?``:d),options:[{value:``,label:`Create new Model`},...(i.options?.models??[]).map(e=>({value:e.id,label:e.name,description:`Current revision ${e.revision}`})),...h?.modelProjectId&&!i.options?.models.some(e=>e.id===h.modelProjectId)?[{value:h.modelProjectId,label:`Original selected Model`}]:[]],disabled:i.busy||!!h||!i.freshReady,onChange:e=>{f(e);let t=i.options?.models.find(t=>t.id===e);t&&c(t.name)}})]}),(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Model name`}),(0,$.jsx)(`input`,{"data-autofocus":!0,value:h?.name??s,maxLength:200,disabled:i.busy||!!h,onChange:e=>c(e.target.value)})]}),h?(0,$.jsx)(`p`,{children:`Original result, profile, destination and revision are retained. Retry sends the same operation.`}):null,i.receipt&&h?(0,$.jsx)(`p`,{role:`status`,children:`The Model was saved. Local acknowledgement is pending; retry preserves its exact receipt.`}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:()=>void g.requestLeave(()=>o(!1)),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Refresh targets and recovery`}),(0,$.jsx)(`button`,{type:`submit`,className:`training-button`,disabled:i.busy||r||!i.recoveryReady||!h&&!i.freshReady,children:i.busy?`Saving…`:h?`Retry original save`:`Save model`})]})]})]}):null,g.dialog]})}var uS=10;new Date(0).toISOString();function dS(e){return e.filter(e=>e.target.kind===`agent`&&[`ready_local`,`released`,`published_hosted`].includes(e.state)).map(e=>`${e.id}:${e.revision}:${e.state}`).sort().join(`|`)}function fS({rows:e,loading:t,busyAction:n,runs:r,state:i,emptyMessage:a=`No Models yet.`,onPull:o,onSelect:s,onUseModel:c,onConfigure:l}){return t?(0,$.jsxs)(`div`,{className:`labs-table-empty`,children:[(0,$.jsx)(Pa,{className:`spin`,size:16}),` Loading Models…`]}):e.length?(0,$.jsx)(`div`,{className:`training-table-wrap`,children:(0,$.jsxs)(`table`,{className:`training-data-table labs-models-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Model`}),(0,$.jsx)(`th`,{children:`Availability`}),(0,$.jsx)(`th`,{children:`Recent run`}),(0,$.jsx)(`th`,{children:`Updated`}),(0,$.jsx)(`th`,{children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Actions`})})]})}),(0,$.jsx)(`tbody`,{children:e.map(e=>{let t=e.local,a=e.hosted,u=t?oi(t,r,i):[],d=u.find(e=>e.current)??null,f=t?si(ii(t,r,i),u,ai(t,i)):[],p=f[0]??null,m=p?.lifecycleRun?.status??p?.job?.status??`not_run`,h=a?n===`pull-hosted-model-project:${a.project.id}`:!1,g=a?n===`open-hosted-model-project:${a.project.id}`:!1,_=a?a.localState===`not_pulled`||a.localState===`remote_ahead`:!1,v=t?.name??a.project.name,y=t?.description??a.project.objective??`No description`;return(0,$.jsxs)(`tr`,{onClick:()=>{g||s(e.key)},children:[(0,$.jsx)(`td`,{children:t?(0,$.jsxs)(`button`,{className:`labs-workproduct-link`,type:`button`,onClick:e=>{e.stopPropagation(),s(t.key)},children:[(0,$.jsx)(`strong`,{children:v}),(0,$.jsx)(`span`,{children:y})]}):(0,$.jsxs)(`button`,{type:`button`,disabled:g,className:`labs-workproduct-link labs-hosted-project-identity`,onClick:t=>{t.stopPropagation(),s(e.key)},children:[(0,$.jsx)(`strong`,{children:v}),(0,$.jsx)(`span`,{children:y}),(0,$.jsx)(`small`,{children:g?`Opening…`:a.project.portableProjectId})]})}),(0,$.jsx)(`td`,{children:(0,$.jsxs)(`div`,{className:`labs-model-table-summary`,children:[a?(0,$.jsx)(ci,{label:pS(a.localState),value:mS(a.localState)}):(0,$.jsx)(ci,{label:d?`Hosted`:`Local only`,value:d?`ready`:`not_run`}),(0,$.jsx)(`span`,{children:a?a.project.trainingSetup.baseModel?.modelId??a.project.defaultBaseModel?.modelId??`No base model`:d?`Release ${d.number}`:`No active release`})]})}),(0,$.jsx)(`td`,{children:(0,$.jsxs)(`div`,{className:`labs-model-table-summary`,children:[t?(0,$.jsx)(ci,{label:Ca(m),value:m}):(0,$.jsx)(ci,{label:a.project.trainingSetup.method?.toUpperCase()??`Configured`,value:`prepared`}),(0,$.jsx)(`span`,{children:t?gS(p?.lifecycleRun??null,f.length):`Hosted source r${a.project.sourceRevision}`})]})}),(0,$.jsx)(`td`,{children:_S(e.updatedAt)}),(0,$.jsx)(`td`,{children:(0,$.jsxs)(`div`,{className:`labs-workproduct-actions`,children:[a&&_?(0,$.jsxs)(`button`,{className:`training-button secondary labs-compact-button`,disabled:h,title:hS(a.localState),type:`button`,onClick:e=>{e.stopPropagation(),o(a)},children:[h?(0,$.jsx)(Pa,{className:`spin`,size:13}):(0,$.jsx)(ru,{size:13}),h?`Importing…`:a.localState===`remote_ahead`?`Update`:`Pull`]}):null,t&&(d||!_)?(0,$.jsx)(`button`,{className:`training-button secondary labs-compact-button labs-workproduct-use`,disabled:!d,title:d?`Chat with the active Version`:a?hS(a.localState):`Set a passing Version active before Chat`,type:`button`,onClick:e=>{e.stopPropagation(),c(t.id)},children:`Chat`}):null,t?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary labs-compact-button`,onClick:e=>{e.stopPropagation(),l(t.id)},children:`Configure`}),(0,$.jsx)(ka,{size:15})]}):null]})})]},e.key)})})]})}):(0,$.jsx)(`div`,{className:`labs-table-empty`,children:a})}function pS(e){return e===`not_pulled`?`Hosted`:e===`up_to_date`?`Local + hosted`:e===`remote_ahead`?`Update available`:e===`local_ahead`?`Local changes`:e===`diverged`?`Diverged`:`Local conflict`}function mS(e){return e===`up_to_date`?`ready`:e===`not_pulled`||e===`remote_ahead`?`prepared`:e===`local_ahead`?`running`:`failed`}function hS(e){return e===`not_pulled`?`Pull this hosted project locally`:e===`remote_ahead`?`Update the clean local copy from hosted`:e===`up_to_date`?`This project is current locally`:e===`local_ahead`?`Sync local changes before pulling`:`Resolve the local and hosted project conflict before pulling`}function gS(e,t){return e?.kind===`evaluation`?`${e.evaluation?.benchmarkId===`harness-refiner`?`Harness Refiner 08112026`:`Benchmark`} · ${e.receipt?.schemaVersion===`openpond.modelEvaluationReceipt.v1`?e.receipt.attempts?.length?(()=>{let t=ni(e.receipt);return`${t.passedTaskCount}/${t.comparedTaskCount} passed`})():yS(e.receipt.terminalClassification.replaceAll(`_`,` `)):e.receipt?.schemaVersion===`openpond.modelEvaluationStopReceipt.v1`?`Inconclusive`:e.evaluationProgress?`${yS(e.evaluationProgress.stage)} ${e.evaluationProgress.completedAttempts}/${e.evaluationProgress.totalAttempts}`:Ca(e.status)}`:`${t} ${t===1?`run`:`runs`}`}function _S(e){let t=new Date(e),n=new Date;return t.toDateString()===n.toDateString()?new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`2-digit`}).format(t):new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,...t.getFullYear()===n.getFullYear()?{}:{year:`2-digit`}}).format(t)}function vS({page:e,total:t,onChange:n}){let r=Math.max(1,Math.ceil(t/uS));return r<=1?null:(0,$.jsxs)(`nav`,{className:`labs-pagination`,"aria-label":`Pagination`,children:[(0,$.jsx)(`button`,{type:`button`,disabled:e<=1,onClick:()=>n(e-1),children:`Previous`}),(0,$.jsxs)(`span`,{children:[e,` of `,r]}),(0,$.jsx)(`button`,{type:`button`,disabled:e>=r,onClick:()=>n(e+1),children:`Next`})]})}function yS(e){return e&&`${e[0].toUpperCase()}${e.slice(1).replaceAll(`_`,` `)}`}function bS(e){return e?[...e.jobs.map(e=>`job:${e.id}:${e.status}`),...e.models.map(e=>`model:${e.id}:${e.status}:${e.artifactId}:${e.jobId}`)].sort().join(`|`):``}function xS({request:e,result:t,trainingAction:n}){let[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(1),d=e?.prompts.some(e=>e.id===r)?r:e?.prompts[0]?.id,f=e?.variants.some(e=>e.id===a)?a:e?.variants[0]?.id,p=e?.capture.flatMap(e=>e.neurons.map(t=>({value:`${e.layer}:${t}`,label:`Layer ${e.layer} · Neuron ${t}`})))??[],m=p.some(e=>e.value===s)?s:p[0]?.value,h=t?.captures.filter(e=>e.promptId===d&&e.variantId===f&&`${e.layer}:${e.neuron}`===m)??[],g=t?.outcomes.find(e=>e.promptId===d&&e.variantId===f),_=Math.min(l,Math.max(1,Math.ceil(h.length/10)));return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(ft,{title:`Activation capture`,children:[(0,$.jsxs)(`label`,{className:`model-build-field`,children:[`Prompt`,(0,$.jsx)(Z,{label:`Captured prompt`,floating:!0,value:d??``,options:e.prompts.map(e=>({value:e.id,label:e.id})),onChange:e=>{i(e),u(1)}})]}),(0,$.jsxs)(`label`,{className:`model-build-field`,children:[`Variant`,(0,$.jsx)(Z,{label:`Captured variant`,floating:!0,value:f??``,options:e.variants.map(e=>({value:e.id,label:e.profile?e.id:`${e.id} · Off`})),onChange:e=>{o(e),u(1)}})]}),(0,$.jsxs)(`label`,{className:`model-build-field`,children:[`Coordinate`,(0,$.jsx)(Z,{label:`Captured coordinate`,floating:!0,value:m??``,options:p,onChange:e=>{c(e),u(1)}})]})]}),n,(0,$.jsxs)(`p`,{children:[g?.generatedTokenIds.length??0,` generated tokens · `,g?.forwardTokenWork??0,` `,`forward-token work. Token IDs are retained against the exact tokenizer; no semantic feature labels are inferred.`]}),(0,$.jsx)(ft,{title:`Generated token comparison`,children:(0,$.jsx)(`div`,{className:`evaluation-table-scroll`,children:(0,$.jsxs)(`table`,{className:`training-data-table evaluation-workspace-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Variant`}),(0,$.jsx)(`th`,{children:`Generated token IDs`})]})}),(0,$.jsx)(`tbody`,{children:e.variants.map(e=>{let n=t.outcomes.find(t=>t.promptId===d&&t.variantId===e.id);return(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.profile?e.id:`${e.id} · Off`}),(0,$.jsx)(`td`,{children:(0,$.jsx)(`code`,{children:n?.generatedTokenIds.join(` `)||`—`})})]},e.id)})})]})})}),(0,$.jsxs)(ft,{title:`Activation values`,children:[(0,$.jsx)(`p`,{children:`Before and after values are inputs to down_proj for the selected variant. Token indices exclude prompt padding.`}),(0,$.jsx)(`div`,{className:`evaluation-table-scroll evaluation-table-frame`,children:(0,$.jsxs)(`table`,{className:`training-data-table evaluation-workspace-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Token index`}),(0,$.jsx)(`th`,{children:`Token ID`}),(0,$.jsx)(`th`,{children:`Before`}),(0,$.jsx)(`th`,{children:`After`}),(0,$.jsx)(`th`,{children:`Delta`})]})}),(0,$.jsx)(`tbody`,{children:h.slice((_-1)*10,_*10).map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.tokenIndex}),(0,$.jsx)(`td`,{children:e.tokenId}),(0,$.jsx)(`td`,{children:e.before.toPrecision(7)}),(0,$.jsx)(`td`,{children:e.after.toPrecision(7)}),(0,$.jsx)(`td`,{children:Number.isFinite(e.after-e.before)?(e.after-e.before).toPrecision(7):`Outside numeric range`})]},e.tokenIndex))})]})}),(0,$.jsx)(vS,{page:_,total:h.length,onChange:u})]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact configuration and evidence`}),(0,$.jsx)(`pre`,{children:JSON.stringify({model:e.model,variant:e.variants.find(e=>e.id===f),prompt:e.prompts.find(e=>e.id===d),outcome:g},null,2)})]})]})}function SS({owner:e,api:t}){let n=e.execution,r=e.original,i=(e.receipt&&(!n||e.receipt.execution.id===n.id&&e.receipt.execution.revision>n.revision)?e.receipt.execution:n)??(r&&`execution`in r.intent?r.intent.execution:null),[a,o]=(0,Q.useState)(null),s=r?`action`in r.command?r.command.action:`prepare`:null;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{error:e.error}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:e.busy||e.loading,onClick:e.refresh,children:`Refresh execution and recovery`}),r?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:e.busy||!e.recoveryReady,onClick:()=>void e.retry(),children:e.busy?`Reconciling…`:`Retry original ${s}`}):null]}),r&&!(`action`in r.command)?(0,$.jsxs)(ft,{title:`Original preparation`,children:[(0,$.jsxs)(`p`,{children:[r.command.name,` · `,r.command.method,` · `,Uy(r.command.maximumSpendUsd)]}),(0,$.jsxs)(`p`,{children:[r.command.request.prompts.length,` prompts ·`,` `,r.command.request.variants.length,` variants ·`,` `,r.command.request.model.modelId,` · `,r.command.request.model.revision]})]}):null,i?(0,$.jsxs)(ft,{title:`Hosted execution`,children:[(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`State`}),(0,$.jsx)(`dd`,{children:i.phase}),(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(i.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:i.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Execution`}),(0,$.jsx)(`dd`,{children:i.id}),(0,$.jsx)(`dt`,{children:`Preparation expires`}),(0,$.jsx)(`dd`,{children:new Date(i.plan.expiresAt).toLocaleString()}),(0,$.jsx)(`dt`,{children:`Exact plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:i.plan.contentHash})]}),n?(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[n.phase===`prepared`?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:e.busy||e.loading||!e.ready||!e.canControl||!!r||Date.parse(n.plan.expiresAt)<=Date.now(),onClick:()=>o({action:`start`,value:n}),children:`Review Start`}):null,[`completed`,`cancelled`,`failed`].includes(n.phase)?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:e.busy||e.loading||!e.ready||!e.canControl||!!r,onClick:()=>o({action:`cancel`,value:n}),children:`Review Cancel`})]}):null]}):null,n?.result?(0,$.jsx)(xS,{request:n.request,result:n.result,trainingAction:(0,$.jsx)(aS,{execution:n,api:t,disabled:e.busy||e.loading||!!r},n.result.contentHash)}):i?.phase===`completed`?(0,$.jsx)(`p`,{children:`No result bytes are available in this read. Retained execution identity remains available for recovery.`}):null,e.selectedId?(0,$.jsx)(lS,{api:t,id:e.selectedId,execution:n,disabled:e.busy||!!r},`${t.key}:${e.selectedId}`):null,a&&n?(0,$.jsxs)(qa,{ariaLabel:a.action===`start`?`Start activation experiment`:`Cancel activation experiment`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:e.busy,onClose:()=>{e.busy||o(null)},children:[(0,$.jsx)(`h2`,{children:a.action===`start`?`Start activation experiment`:`Cancel activation experiment`}),(0,$.jsx)(`p`,{children:a.action===`start`?Gy(a.value.plan.computePrice):`Cancel this exact execution. In-flight work may need to stop and settle before capacity is released.`}),(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(a.value.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:a.value.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Prompts`}),(0,$.jsx)(`dd`,{children:a.value.request.prompts.length}),(0,$.jsx)(`dt`,{children:`Variants`}),(0,$.jsx)(`dd`,{children:a.value.request.variants.length}),(0,$.jsx)(`dt`,{children:`Model`}),(0,$.jsxs)(`dd`,{children:[a.value.request.model.modelId,` · `,a.value.request.model.revision]}),(0,$.jsx)(`dt`,{children:`Plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:a.value.plan.contentHash})]}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:e.busy,onClick:()=>o(null),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:e.busy||e.loading||!!r||!e.ready||!e.canControl,onClick:()=>void e.control(a.action,a.value).then(e=>{e&&o(null)}),children:e.busy?`Applying…`:a.action===`start`?Ky(a.value.plan.maximumSpendUsd):`Cancel execution`})]})]}):null]})}function CS(){return{baseModel:null,prompts:[{id:crypto.randomUUID(),text:``}],coordinates:[{id:crypto.randomUUID(),layer:``,neuron:``,dose:`1`}],doseMultipliers:`-1, 0, 1`,normalization:{mode:`baseline_prompt_residual_median`,statistic:`midpoint_median_fp32`,sample:`non_padding_prompt_after_position_zero`},tokenScope:{phase:`prompt_and_decode`,positions:`all_non_padding`},maxNewTokens:`32`,maximumCapturedValues:`65536`,maximumForwardTokenWork:`1000000`,maximumDurationSeconds:`300`,maximumSpendUsd:``}}function wS({api:e,method:t,visible:n,onClose:r,onSaveDraft:i}){let a=kv(),o=a.initialExperiment?.operationType===t?a.initialExperiment:null,[s,c]=(0,Q.useState)(()=>o?.activationForm??CS()),[l,u]=(0,Q.useState)(o?.name??Tr(t)),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(null),h=Ry(e,n,null),g=Jx(e,a.startingModel?.source===`trained`||a.startingModel?.source===`engram`?null:a.trainingBaseModel,n),_=g.current?.methods.find(e=>e.method===t)?.execution,v=$x(e,{draftId:a.initialExperiment?.id??null,method:t,visible:n}),y=v.selectedId&&![`completed`,`failed`,`cancelled`].includes(v.execution?.phase??v.receipt?.execution.phase??`prepared`),b=d||v.busy,x=b||!!v.original||!!y,S=J({...s,baseModel:a.trainingBaseModel,name:l,startingModel:a.startingModel}),C=(0,Q.useRef)(S),w=(0,Q.useRef)(!1),T=J([e.key,e.connection.serverUrl,e.actorId,a.initialExperiment?.id]),E=(0,Q.useRef)(T);(0,Q.useEffect)(()=>(E.current=T,()=>{E.current=`unmounted`}),[T]);let D=S!==C.current,O=a.reportOperationDraftDirty;(0,Q.useEffect)(()=>{O(t,D)},[O,t,D]);let k=iy({name:`experiment setup`,dirty:D||a.operationDraftDirty||a.evaluationDirty,busy:b,onLeave:r,retainForDestination(t){let n=po(new URL(t,window.location.origin));return!(!n||![`datasets`,`graders`,`experiments`].includes(n.page)||n.collection===`drafts`&&n.resourceId!==a.initialExperiment?.id||(n.projectId??null)!==e.projectId)}});My(k,n);let A=e=>c(t=>({...t,...e})),j=a.startingModel?.source===`engram`?`engram:${a.startingModel.engram.versionHash}`:a.startingModel?.source===`steering`?`steering:${a.startingModel.steering.versionHash}`:a.startingModel?.source===`trained`?`trained:${a.startingModel.trainedVersion.contentHash}`:a.trainingBaseModel?J(a.trainingBaseModel):``,M=h.models.map(e=>({value:J(e.preference),label:e.name})),N=t===`neuron_steering`?[`layer`,`neuron`,`dose`]:[`layer`,`neuron`];j&&!M.some(e=>e.value===j)&&M.unshift({value:j,label:a.startingModel?.label??a.trainingBaseModel.modelId});function P(){if(!a.initialExperiment)throw Error(`Open the experiment before saving.`);return Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:a.initialExperiment.id,operationType:t,name:l.trim()||Tr(t),...a.startingModel?{startingModel:a.startingModel}:{},activationForm:{...s,baseModel:a.trainingBaseModel,maximumSpendUsd:s.maximumSpendUsd??``}})}async function F(e){if(!i)throw Error(`Load canonical draft storage before preparing.`);if(await i(e),E.current!==T)throw Error(`Return to the original experiment account before continuing.`);C.current=S}async function I(){m(null);try{await v.prepare(P(),F)}catch(e){m(e)}}async function L(){if(i&&a.initialExperiment&&!w.current){w.current=!0,f(!0),m(null);try{if(await F(P()),E.current!==T)return;C.current=S}catch(e){E.current===T&&m(e)}finally{w.current=!1,E.current===T&&f(!1)}}}return(0,$.jsxs)(Bv,{label:`Experiment setup`,action:`experiment`,onRequestClose:()=>void k.requestLeave(r),children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`h2`,{children:`Run Experiment`}),(0,$.jsx)(`button`,{type:`button`,disabled:b,onClick:()=>void k.requestLeave(r),children:`Close setup`})]}),(0,$.jsxs)(`form`,{noValidate:!0,onSubmit:e=>{e.preventDefault(),L()},children:[(0,$.jsx)(ft,{title:`Starting model`,children:(0,$.jsxs)(`fieldset`,{disabled:x,children:[(0,$.jsxs)(`label`,{children:[`Model`,(0,$.jsx)(Z,{label:`Starting model`,floating:!0,searchable:!0,value:j,disabled:h.isPending&&!j,options:[{value:``,label:h.isPending?`Loading models…`:h.isSuccess&&!M.length?`No catalog models available`:`Choose model`,disabled:h.isPending||h.isSuccess&&!M.length},...M],onChange:e=>{if(e===j)return;let t=h.models.find(t=>J(t.preference)===e);e&&!t?m(`Refresh the model list before changing this selection.`):(a.setTrainingBaseModel(t?.preference??null),c(({startingProfile:e,...t})=>t))}})]}),(0,$.jsx)(xy,{disabled:x}),(0,$.jsx)(`p`,{children:`Run compiles and prepares this exact saved configuration. Review the immutable plan before explicitly starting paid execution.`}),_?(0,$.jsx)(`p`,{children:_.state===`unavailable`?_.reason:`A compatible activation runtime is available. Preparation rechecks its exact identity.`}):null,g.isFetching?(0,$.jsx)(`span`,{role:`status`,children:`Checking runtime…`}):null]})}),(0,$.jsx)(ft,{title:`Prompts`,children:(0,$.jsxs)(`fieldset`,{disabled:x,children:[s.prompts.map((e,t)=>(0,$.jsxs)(`fieldset`,{children:[(0,$.jsxs)(`label`,{children:[`Prompt `,t+1,(0,$.jsx)(`textarea`,{rows:3,value:e.text,maxLength:16e3,onChange:t=>A({prompts:s.prompts.map(n=>n.id===e.id?{...n,text:t.target.value}:n)})})]}),(0,$.jsxs)(`button`,{type:`button`,className:`training-text-button`,onClick:()=>A({prompts:s.prompts.filter(t=>t.id!==e.id)}),children:[`Remove prompt `,t+1]})]},e.id)),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:s.prompts.length>=8,onClick:()=>A({prompts:[...s.prompts,{id:crypto.randomUUID(),text:``}]}),children:`Add prompt`})]})}),(0,$.jsx)(ft,{title:t===`neuron_steering`?`Steering coordinates`:`Capture coordinates`,children:(0,$.jsxs)(`fieldset`,{disabled:x,children:[(0,$.jsxs)(`p`,{children:[`Layer and neuron indices start at zero.`,t===`neuron_steering`?` Strength adds to the activation entering down_proj; weights stay unchanged.`:` Inspection records selected activations without changing weights.`]}),s.coordinates.map((e,t)=>(0,$.jsxs)(`fieldset`,{children:[(0,$.jsxs)(`legend`,{children:[`Coordinate `,t+1]}),(0,$.jsx)(`div`,{className:`activation-coordinate-fields`,children:N.map(n=>(0,$.jsxs)(`label`,{children:[n===`dose`?`Strength`:n===`layer`?`Layer`:`Neuron`,(0,$.jsx)(`input`,{"aria-label":`${n===`dose`?`Strength`:n===`layer`?`Layer`:`Neuron`} ${t+1}`,inputMode:n===`dose`?`decimal`:`numeric`,value:e[n],maxLength:100,onChange:t=>A({coordinates:s.coordinates.map(r=>r.id===e.id?{...r,[n]:t.target.value}:r)})})]},n))}),(0,$.jsxs)(`button`,{type:`button`,className:`training-text-button`,onClick:()=>A({coordinates:s.coordinates.filter(t=>t.id!==e.id)}),children:[`Remove coordinate `,t+1]})]},e.id)),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:s.coordinates.length>=64,onClick:()=>A({coordinates:[...s.coordinates,{id:crypto.randomUUID(),layer:``,neuron:``,dose:`1`}]}),children:`Add coordinate`}),t===`neuron_steering`?(0,$.jsxs)(`label`,{children:[`Dose multipliers`,(0,$.jsx)(`input`,{value:s.doseMultipliers,maxLength:1e3,onChange:e=>A({doseMultipliers:e.target.value})}),(0,$.jsx)(`small`,{children:`Comma-separated multipliers for the configured strengths. The comparison includes an unsteered baseline.`})]}):null]})}),(0,$.jsx)(ft,{title:`Advanced`,children:(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Capture and generation settings`}),(0,$.jsxs)(`fieldset`,{disabled:x,children:[t===`neuron_steering`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[`Apply during`,(0,$.jsx)(Z,{label:`Apply during`,floating:!0,value:s.tokenScope.phase,options:[{value:`prompt_and_decode`,label:`Prompt and generation`},{value:`prompt_only`,label:`Prompt only`},{value:`decode_only`,label:`Generation only`}],onChange:e=>A({tokenScope:{...s.tokenScope,phase:e}})})]}),(0,$.jsxs)(`label`,{children:[`Token positions`,(0,$.jsx)(Z,{label:`Token positions`,floating:!0,value:s.tokenScope.positions,options:[{value:`all_non_padding`,label:`All non-padding tokens`},{value:`after_position_zero`,label:`After the first token`}],onChange:e=>A({tokenScope:{...s.tokenScope,positions:e}})})]}),(0,$.jsx)(`p`,{children:s.normalization.mode===`baseline_prompt_residual_median`?`Normalization uses a separate unsteered prompt pass and its frozen FP32 midpoint residual median.`:`Fixed calibration retained: ${s.normalization.calibration.id} · r${s.normalization.calibration.revision}`})]}):null,[[`maxNewTokens`,`Maximum generated tokens`],[`maximumCapturedValues`,`Maximum captured values`],[`maximumForwardTokenWork`,`Maximum forward-token work`],[`maximumDurationSeconds`,`Maximum seconds`]].map(([e,t])=>(0,$.jsxs)(`label`,{children:[t,(0,$.jsx)(`input`,{inputMode:`numeric`,value:s[e],maxLength:100,onChange:t=>A({[e]:t.target.value})})]},e))]})]})}),(0,$.jsxs)(`label`,{children:[`Name`,(0,$.jsx)(`input`,{value:l,maxLength:500,disabled:x,onChange:e=>u(e.target.value)})]}),(0,$.jsxs)(`label`,{children:[`Spending limit (USD, optional)`,(0,$.jsx)(`input`,{inputMode:`decimal`,placeholder:`Use available credits`,value:s.maximumSpendUsd??``,maxLength:100,disabled:x,onChange:e=>A({maximumSpendUsd:e.target.value})})]}),(0,$.jsx)(X,{error:p??h.error??g.error}),h.error?(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,onClick:()=>void h.refetch(),children:`Retry model list`}):null,g.canRefresh?(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:g.isFetching,onClick:()=>void g.refetch(),children:`Refresh runtime availability`}):null,(0,$.jsx)(`button`,{type:`submit`,className:`training-button secondary`,disabled:x||!i,children:b?`Saving…`:`Save draft`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:x||!i||!v.ready||_?.state!==`ready`||a.startingModel?.source===`trained`,onClick:()=>void I(),children:`Run`})]}),(0,$.jsx)(SS,{api:e,owner:v}),k.dialog]})}function TS(e){let t=kv(),n=u(),r=Ga(),i=(0,Q.useRef)(t.storedRecord),a=(0,Q.useRef)(null),o=(0,Q.useRef)(!1),s=J([e.connection.serverUrl,e.accountKey,e.actorId,e.teamId,e.projectId,t.initialExperiment?.id]),c=(0,Q.useRef)(s);return(0,Q.useEffect)(()=>(c.current=s,()=>{c.current=`unmounted`}),[s]),async l=>{if(t.initialExperiment?.hostedEvaluationForm)throw Error(`Open this saved evaluation in its hosted editor to preserve its native settings.`);if(o.current)throw Error(`This experiment draft is already saving.`);if(!e.actorId||l.id!==t.initialExperiment?.id)throw Error(`Reopen this experiment in the current account before saving.`);o.current=!0;let u=()=>{if(c.current!==s)throw Error(`The active experiment or account changed.`)},d=Iy(e);try{if(u(),a.current){let e=await d.save(a.current);u(),i.current=e.record,a.current=null}if(!i.current||J(i.current.draft)!==J(l)){a.current={schemaVersion:`openpond.experimentDraftSave.v1`,teamId:e.teamId,operationId:crypto.randomUUID(),expectedRevision:i.current?.revision??0,projectId:i.current?.projectId??e.projectId,draft:l};let t=await d.save(a.current);u(),i.current=t.record,a.current=null}let o=await d.get(l.id);if(u(),o.contentHash!==i.current.contentHash)throw Error(`This draft changed elsewhere. Your edits are retained here. Reopen the saved draft to load its current revision.`);return t.acceptSaved(o),n.invalidateQueries({queryKey:[`unified-experiments`]}),r?.(`Experiment draft saved.`,`success`),o}finally{o.current=!1}}}function ES(e){let t=kv(),n=(0,Q.useMemo)(()=>tS(e.api,`hosted`),[e.api]),r=TS(e.api),i=e.onSaveDraft??(e.dispatch?void 0:r);return t.initialExperiment?.hostedEvaluationForm?(0,$.jsxs)(Bv,{label:`Experiment`,action:`experiment`,onRequestClose:()=>{t.close(),e.onClose?.()},children:[(0,$.jsx)(X,{error:`Open this saved evaluation in its hosted editor to preserve its native settings.`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>{t.close(),e.onClose?.()},children:`Close editor`})]}):t.advancedTarget?(0,$.jsx)(gx,{api:e.api,target:t.advancedTarget,onClose:()=>{t.close(),e.onClose?.()},onOpenRun:e.onAdvancedRun}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Q.Activity,{mode:t.operationType===`evaluate`?`visible`:`hidden`,children:(0,$.jsx)(Ny,{...e,onSaveDraft:i})}),[`sft`,`grpo`].map(n=>(0,$.jsx)(Q.Activity,{mode:t.operationType===n?`visible`:`hidden`,children:(0,$.jsx)(qx,{api:e.api,method:n,visible:t.operationType===n,onStarted:e.onTrainingStarted,navigate:e.navigate,onSaveDraft:i,onClose:()=>{t.close(),e.onClose?.()}},JSON.stringify([e.api.key,ra(e.api.connection),t.initialExperiment?.id,n]))},n)),(0,$.jsx)(Q.Activity,{mode:t.operationType===`alphaedit`?`visible`:`hidden`,children:(0,$.jsx)(Ab,{api:n,visible:t.operationType===`alphaedit`,onSaveDraft:i,onClose:()=>{t.close(),e.onClose?.()}},`${n.key}:${t.initialExperiment?.id}:alphaedit`)}),(0,$.jsx)(Q.Activity,{mode:t.operationType===`selective_neuron_training`?`visible`:`hidden`,children:(0,$.jsx)(Wb,{api:n,visible:t.operationType===`selective_neuron_training`,onSaveDraft:i,onClose:()=>{t.close(),e.onClose?.()}},`${n.key}:${t.initialExperiment?.id}:neuron-training`)}),(0,$.jsx)(Q.Activity,{mode:t.operationType===`decision_model`?`visible`:`hidden`,children:(0,$.jsx)($b,{api:n,visible:t.operationType===`decision_model`,onSaveDraft:i,onClose:()=>{t.close(),e.onClose?.()}},`${n.key}:${t.initialExperiment?.id}:decision`)}),(0,$.jsx)(Q.Activity,{mode:t.operationType===`engram_adapter`?`visible`:`hidden`,children:(0,$.jsx)(px,{api:n,visible:t.operationType===`engram_adapter`,onSaveDraft:i,onClose:()=>{t.close(),e.onClose?.()}},`${n.key}:${t.initialExperiment?.id}:engram`)}),[`neuron_steering`,`inspect_activations`].map(r=>(0,$.jsx)(Q.Activity,{mode:t.operationType===r?`visible`:`hidden`,children:(0,$.jsx)(wS,{api:n,method:r,visible:t.operationType===r,onSaveDraft:i,onClose:()=>{t.close(),e.onClose?.()}},`${n.key}:${t.initialExperiment?.id}:${r}`)},r))]})}function DS({connection:e,context:t,onClose:n}){let r=(0,Q.useContext)(E),i=t.selection?.draft,a=t.selection?.storedDraft,o=i?.evaluationForm?.executionLocation??(i?.operationType===`evaluate`?`local`:`hosted`),s=(0,Q.useMemo)(()=>r?.teamId&&r.actorId?eS(e,{...r,teamId:r.teamId,actorId:r.actorId,projectId:a?.projectId??null,executionLocation:o}):null,[e,r?.accountKey,r?.teamId,r?.actorId,a?.projectId,o]);return i?i.hostedEvaluationForm?(0,$.jsxs)(`div`,{className:`chat-experiment-tool-content`,children:[(0,$.jsx)(X,{error:`Open this saved evaluation in its hosted editor to preserve its native settings.`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:n,children:`Close editor`})]}):s?(0,$.jsx)(Ov,{initialExperiment:i,initialRecord:a,onNewDraft:async e=>{if(!await t.select({kind:`experiment`,id:e.id,location:`local`,draft:e},{newExperiment:!0}))throw Error(`The new experiment could not be selected. Your original editor remains available.`)},children:(0,$.jsx)(OS,{api:s,context:t,onClose:n})},`${s.key}:${i.id}`):(0,$.jsx)(`div`,{className:`chat-experiment-tool-content`,children:(0,$.jsx)(`p`,{children:`Select an OpenPond workspace to configure this experiment.`})}):null}function OS({api:e,context:t,onClose:n}){let r=kv(),i=(0,Q.useRef)(t.selection?.storedDraft??null),[a,o]=(0,Q.useState)(null),s=S({queryKey:[`evaluation-workspace`,e.key,`chat-inventory`],queryFn:({signal:t})=>e.request(`inventory`,{},t)}),c=e=>{wo({...e,area:`console`})};return(0,$.jsxs)(Mv.Provider,{value:a,children:[(0,$.jsx)(`div`,{ref:o,className:`evaluation-workspace-panel chat-experiment-editor`}),s.error?(0,$.jsx)(X,{error:s.error,children:(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,onClick:()=>void s.refetch(),children:`Retry workspace`})}):null,(0,$.jsx)(ES,{api:e,inventory:s.data??null,route:as(`experiments`,null,{projectId:e.projectId,executionLocation:e.location}),navigate:c,onClose:n,onTrainingStarted:async n=>{let i=s.data??await e.request(`inventory`);if(i.teamId!==e.teamId||!r.initialExperiment)throw Error(`The originating workspace changed.`);await t.associateTraining(n,i.apiOrigin,r.initialExperiment.id)},onSaveDraft:async e=>{let n=await t.saveDraft(e,i.current);return n.storedDraft&&(i.current=n.storedDraft,r.acceptSaved(n.storedDraft)),n},onSaved:({id:t})=>c(as(`experiments`,null,{resourceId:t,projectId:e.projectId,executionLocation:e.location,detailTab:`overview`}))},r.initialExperiment?.id)]})}var kS=`training-result-save`;function AS(e,t){let n=u(),r=JSON.stringify([e.key,ra(e.connection),t.job.id]),i=(0,Q.useRef)(r);i.current=r;let a=(0,Q.useRef)(!0),o=(0,Q.useRef)(!1),s=(0,Q.useRef)(null),[c,l]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(null);(0,Q.useEffect)(()=>(a.current=!0,()=>{a.current=!1}),[]);let _=()=>a.current&&i.current===r,v=S({queryKey:[`training-model-save-recovery`,r],queryFn:async({signal:n})=>{let r,i=[],a=new Set;for(let o=0;;o++){if(o>=100)throw Error(`The retained save catalog exceeds its supported bound.`);let s=await e.pendingOperations(kS,r,n);for(let n of s.items){let r=On.parse(n.reviewedIntent);if(r.jobId!==t.job.id)continue;if(r.teamId!==e.teamId)throw Error(`The retained Model save belongs to another workspace.`);let{jobId:a,...o}=r,s=n.command?mr.parse(n.command):mr.parse({jobId:a,request:{...o,operationId:n.id}});i.push({command:s,operation:e.recoverOperation(n)})}if(!s.nextCursor)break;if(a.has(s.nextCursor))throw Error(`The retained save catalog repeated a page.`);a.add(s.nextCursor),r=s.nextCursor}if(i.length>1)throw Error(`More than one Model save is retained for this run. Resolve the original commands before creating another save.`);return i[0]??null},staleTime:0,gcTime:0,retry:!1}),y=c??v.data??null;async function b(r){if(o.current||h||!v.isSuccess)return null;o.current=!0,f(!0),m(null);let i=!1;try{if(!e.actorId)throw Error(`Choose an authenticated account before saving a Model.`);if(!y&&!r.trim())throw Error(`Enter a Model name.`);if(!s.current){if(y)s.current=y;else{if(!t.model||!t.request||!t.candidate)throw Error(`Refresh the completed result before saving its Model.`);let n=On.parse({schemaVersion:`openpond.trainingResultSave.v1`,jobId:t.job.id,teamId:e.teamId,name:r,expectedModelRevision:t.model.revision,submissionHash:t.request.submissionHash,artifact:t.candidate.artifact,checkpointId:t.candidate.checkpointId}),i=await e.operation(kS,n);if(!_())return null;let{jobId:a,...o}=n;s.current={operation:i,command:mr.parse({jobId:a,request:{...o,operationId:i.id}})}}l(s.current)}let a=s.current;if(await a.operation.retainCommand(a.command,`dispatching`),!_())return null;i=!0;let o=await Tt(await Y(e.connection,`/v1/training/hosted-jobs/${encodeURIComponent(a.command.jobId)}/model?teamId=${encodeURIComponent(e.teamId)}`,{method:`POST`,body:JSON.stringify(a.command.request)}),{jobId:t.job.id,request:a.command.request,actorId:e.actorId});if(!_())return null;g(o),n.invalidateQueries({queryKey:[`hosted-training-result`]}),n.invalidateQueries({queryKey:[`saved-training-model`]});try{await a.operation.acknowledge()}catch(e){return _()&&m(e),{receipt:o,acknowledgementError:e}}return{receipt:o,acknowledgementError:null}}catch(e){if(_()&&(m(e),i&&e instanceof Ti&&[400,403,404,409,422].includes(e.status)&&s.current))try{await s.current.operation.acknowledge(),_()&&(s.current=null,l(null),await v.refetch())}catch(e){_()&&m(e)}return null}finally{o.current=!1,_()&&f(!1)}}return{save:b,busy:d,receipt:h,retained:y,error:p??v.error,recoveryReady:v.isSuccess,refreshRecovery:v.refetch}}function jS({api:e,result:t,onClose:n,onSaved:r}){let[i,a]=(0,Q.useState)(t.model?.name??t.name),o=AS(e,t),s=o.retained?.command.request,c=iy({name:`Model save`,busy:o.busy,dirty:!o.receipt&&(!!s||i!==(t.model?.name??t.name)),discardDescription:s?`The original save request stays in recovery. Reopening this result lets you retry that same request.`:void 0});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(qa,{ariaLabel:`Save model`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:o.busy,onClose:()=>void c.requestLeave(n),children:[(0,$.jsx)(`h2`,{children:`Save model`}),(0,$.jsxs)(`p`,{children:[`Save this checkpoint as a version of `,t.model?.name??t.name,`.`]}),(0,$.jsx)(X,{error:o.error}),(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),o.save(i).then(e=>{e&&(c.allowNextNavigation(),r(e.receipt,e.acknowledgementError))})},children:[(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Model name`}),(0,$.jsx)(`input`,{"data-autofocus":!0,maxLength:200,value:s?.name??i,disabled:o.busy||!o.recoveryReady||!!s,onChange:e=>a(e.target.value)})]}),s?(0,$.jsx)(`p`,{children:`Original save request retained.`}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o.busy,onClick:()=>void c.requestLeave(n),children:`Cancel`}),o.recoveryReady?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void o.refreshRecovery(),children:`Reload retained saves`}),(0,$.jsx)(`button`,{className:`training-button`,type:`submit`,disabled:o.busy||!o.recoveryReady,children:o.busy?`Saving…`:s?`Retry original save`:`Save model`})]})]})]}),c.dialog]})}var MS={not_finished:`Training has not produced a completed result yet.`,request_unavailable:`The original training request is unavailable for this run.`,qualification_only:`This run collected qualification evidence without training weights.`,not_model_training:`This run has no policy-model checkpoint.`,cleanup_pending:`Waiting for terminal cleanup evidence.`,artifact_pending:`Waiting for the final checkpoint publication.`,retained:`Final checkpoint retained.`},NS={base:`Standalone adapter`,residual_append:`Stacked adapter`,shared:`Shared adapter`,sequential_merge:`Sequential merge`};function PS({connection:e,teamId:t,actorId:n,jobId:r,version:i,api:a,onOpenModel:o}){let[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(null),h=S({queryKey:[`hosted-training-result`,a.key,ra(e),t,n,r,i],queryFn:async({signal:n})=>tn(await Y(e,`/v1/training/hosted-jobs/${encodeURIComponent(r)}/result?teamId=${encodeURIComponent(t)}`,{signal:n}),{teamId:t,jobId:r}),staleTime:3e4,gcTime:3e5}),g=h.data,_=g?.request,v=g?.candidate,y=g?.outputs.receipt,b=g?.model&&(!d||g.model.revision>=d.model.revision)?g.model.name:d?.model.name??`Model`;return(0,$.jsxs)(`section`,{className:`training-result-details`,"aria-label":`Model result`,children:[(0,$.jsxs)(`div`,{className:`training-result-heading`,children:[(0,$.jsx)(`h3`,{children:`Model result`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:h.isFetching,onClick:()=>void h.refetch(),children:`Refresh result`})]}),(0,$.jsx)(X,{error:p??h.error}),h.isPending?(0,$.jsx)(`p`,{role:`status`,children:`Loading model result…`}):null,g?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:MS[g.candidateState]}),d||g.savedVersion?(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsxs)(`span`,{children:[`Saved to `,b,`.`]}),o?(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:l,onClick:()=>{let e=d?.model.id??g.model?.id;e&&o&&(u(!0),m(null),o(e).catch(m).finally(()=>u(!1)))},children:l?`Opening…`:`View model`}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>c(!0),children:`Review save`})]}):v&&g.model?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,onClick:()=>c(!0),children:`Save model`}):null,_?(0,$.jsxs)(`dl`,{className:`model-project-page-metrics`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Base model`}),(0,$.jsx)(`dd`,{children:_.baseModel.modelId}),(0,$.jsx)(`small`,{children:_.baseModel.revision})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Method`}),(0,$.jsx)(`dd`,{children:String(_.recipe.method??`Training`)})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Configuration revision`}),(0,$.jsx)(`dd`,{children:_.source.modelProject.revision})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Dataset`}),(0,$.jsx)(`dd`,{children:_.source.taskset.id}),(0,$.jsxs)(`small`,{children:[`Revision `,_.source.taskset.revision]})]}),v?(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Composition`}),(0,$.jsx)(`dd`,{children:NS[v.composition]})]}):null,y?(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Cleanup`}),(0,$.jsx)(`dd`,{children:y.cleanupComplete?`Complete`:`Pending`})]}):null]}):null,v?(0,$.jsxs)(`p`,{children:[`Checkpoint `,(0,$.jsx)(`code`,{children:v.checkpointId}),v.parent?(0,$.jsxs)($.Fragment,{children:[` · Parent run `,(0,$.jsx)(`code`,{children:v.parent.jobId})]}):null]}):null,(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact settings and references`}),(0,$.jsx)(`pre`,{children:JSON.stringify({request:_,candidate:v,executionReceipt:y?{id:y.id,runtimeRelease:y.runtimeRelease,spendUsd:y.spendUsd,durationSeconds:y.durationSeconds}:null},null,2)})]})]}):null,s&&g?(0,$.jsx)(jS,{api:a,result:g,onClose:()=>c(!1),onSaved:(e,t)=>{f(e),m(t),c(!1),h.refetch()}}):null]})}function FS({connection:e,training:t}){let n=(0,Q.useContext)(D),{teamId:r,actorId:i}=t.owner,a=(0,Q.useMemo)(()=>eS(e,{teamId:r,actorId:i,accountKey:n,projectId:null}),[e,r,i,n]);return(0,$.jsx)(PS,{connection:e,teamId:r,actorId:i,jobId:t.jobId,version:t.job.version,api:a},`${a.key}:${t.apiOrigin}:${t.jobId}`)}function IS({connection:e,sessionId:t,events:n}){let r=k(e,t),i=Xd(r.selection?.resource||r.selection?.draft?e:null,t),[a,o]=(0,Q.useState)(null),s=r.selection,c=s?.training,[l,u]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{u(!1)},[s?.draft?.id]);let d=s?.draft?.startingModel?.baseModel??s?.draft?.alphaEditForm?.baseModel??s?.draft?.neuronTrainingForm?.baseModel??s?.draft?.decisionForm?.baseModel??s?.draft?.engramForm?.baseModel??s?.draft?.activationForm?.baseModel??(s?.draft?.trainingForm?s.draft.trainingForm.baseModel:s?.draft?.training?.baseModel),f=s?.draft?.alphaEditForm?Number(s.draft.alphaEditForm.maximumSpendUsd):s?.draft?.neuronTrainingForm?Number(s.draft.neuronTrainingForm.maximumSpendUsd):s?.draft?.decisionForm?Number(s.draft.decisionForm.maximumSpendUsd):s?.draft?.engramForm?Number(s.draft.engramForm.maximumSpendUsd):s?.draft?.activationForm?Number(s.draft.activationForm.maximumSpendUsd):s?.draft?.trainingForm?Number(s.draft.trainingForm.budget):s?.draft?.training?.maximumSpendUsd,p=s?.draft?.trainingForm?.billingMode===`actual_usage`?{cap:s.draft.trainingForm.customerCapUsd?.trim()??``,planning:s.draft.trainingForm.budget}:s?.draft?.training?.usageFunding?{cap:s.draft.training.usageFunding.customerCapUsd??``,planning:String(s.draft.training.maximumSpendUsd)}:null,m=s?.resource?.kind===`experiment`?s.resource:null,h=m?i.focus.experiment:i.focus.dataset,g=!!(s?.resource&&h&&cf(s.resource)===cf(h)&&s.resource.revision===h.revision),{select:_}=r,v=c?JSON.stringify(s.target):``,y=(r.runs.data?.runs??[]).map(e=>({value:JSON.stringify(e.target),label:e.label,description:e.detail}));c&&!y.some(e=>e.value===v)&&y.unshift({value:v,label:`${(c.location===`cloud`?c.job.createdAt:c.updatedAt).slice(0,16).replace(`T`,` `)} UTC`,description:c.location===`cloud`?c.job.state:c.executionState});async function b(e){try{o(null),await _(JSON.parse(e))}catch(e){o(String(e))}}let x=s?.resource?{...i,focus:{...i.focus,dataset:s.dataset??(s.resource.kind===`dataset`?s.resource:null),experiment:m},scope:g&&m||s.target.scopeId===i.scope?.id?i.scope:null,graders:s.graders??[]}:i;return(0,$.jsxs)(`div`,{className:`chat-experiment-tool`,children:[(0,$.jsx)(`header`,{className:`chat-experiment-tool-header`,children:(0,$.jsx)(Qd,{context:r})}),(0,$.jsx)(X,{error:a}),s?.alphaEditResult?.result?(0,$.jsxs)(`div`,{className:`chat-experiment-tool-content`,children:[(0,$.jsx)(`h2`,{children:s.label}),(0,$.jsx)(t_,{result:s.alphaEditResult.result})]}):s?.neuronTrainingResult?.result?(0,$.jsxs)(`div`,{className:`chat-experiment-tool-content`,children:[(0,$.jsx)(`h2`,{children:s.label}),(0,$.jsx)(t_,{result:s.neuronTrainingResult.result})]}):s?.decisionResult?.result?(0,$.jsxs)(`div`,{className:`chat-experiment-tool-content`,children:[(0,$.jsx)(`h2`,{children:s.label}),(0,$.jsxs)(`dl`,{className:`training-context-facts`,children:[(0,$.jsx)(`dt`,{children:`Mode`}),(0,$.jsx)(`dd`,{children:s.decisionResult.mode}),(0,$.jsx)(`dt`,{children:`Execution`}),(0,$.jsx)(`dd`,{children:s.decisionResult.id}),(0,$.jsx)(`dt`,{children:`Input hash`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:s.decisionResult.plan.inputHash})]}),(0,$.jsx)(Zy,{result:s.decisionResult.result})]}):s?.model?(0,$.jsxs)(`div`,{className:`chat-experiment-tool-content`,children:[(0,$.jsxs)(`dl`,{className:`training-context-facts`,children:[(0,$.jsx)(`dt`,{children:`Base model`}),(0,$.jsx)(`dd`,{children:s.model.baseModel??`—`})]}),(0,$.jsx)(Z,{floating:!0,label:`Training run`,value:v,disabled:r.runs.isPending||r.selecting,options:[...c?[]:[{value:``,label:r.runs.isFetching?`Loading training runs…`:y.length?`Choose training run`:`No training runs`,disabled:!0}],...y],onChange:e=>void b(e)}),(0,$.jsx)(X,{error:r.runs.error,children:r.runs.error?(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void r.runs.refetch(),children:`Retry training history`}):null}),c?c.location===`cloud`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(I_,{compact:!0,connection:e,teamId:c.owner.teamId,projectId:c.job.modelProjectId,jobId:c.jobId,onOpenRun:()=>window.location.assign(ao(as(`runs`,null,{area:`console`,resourceId:`hosted-run:${c.jobId}`})))}),(0,$.jsx)(FS,{connection:e,training:c})]}):(0,$.jsx)(uv,{connection:e,training:c}):(0,$.jsx)(y_,{}),(0,$.jsx)(a_,{connection:e,dataset:s.dataset,graders:s.graders??[],model:s.model}),(0,$.jsx)(i_,{title:`Experiments`,children:(0,$.jsx)(Z,{floating:!0,label:`Experiment`,value:``,options:[{value:``,label:`Experiment`,disabled:!0},...(r.catalog.data?.options??[]).filter(e=>e.target.kind===`experiment`).map(e=>({value:JSON.stringify(e.target),label:e.label,description:e.detail}))],onChange:e=>void b(e)})})]}):s?.draft&&(l||r.configureDraftId===s.draft.id)?(0,$.jsx)(DS,{connection:e,context:r,onClose:()=>{u(!1),r.closeDraftEditor()}}):s?.draft?(0,$.jsxs)(`div`,{className:`chat-experiment-tool-content`,children:[(0,$.jsx)(`h2`,{children:s.label}),(0,$.jsxs)(`dl`,{className:`training-context-facts`,children:[(0,$.jsx)(`dt`,{children:`Type`}),(0,$.jsx)(`dd`,{children:Tr(s.draft.operationType)}),(0,$.jsx)(`dt`,{children:`Status`}),(0,$.jsx)(`dd`,{children:`Draft`}),s.draft.operationType===`evaluate`?null:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Starting model`}),(0,$.jsx)(`dd`,{children:d?.modelId??`Not selected`}),s.draft.startingModel?.source===`alphaedit`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Saved AlphaEdit version`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:s.draft.startingModel.alphaedit.versionHash})]}):null,s.draft.startingModel?.source===`neuron_training`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Saved neuron training version`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:s.draft.startingModel.neuronTraining.versionHash})]}):null,s.draft.decisionForm?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Decision mode`}),(0,$.jsx)(`dd`,{children:s.draft.decisionForm.mode})]}):null,s.draft.startingModel?.source===`decision`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Saved Decision version`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:s.draft.startingModel.decision.versionHash}),(0,$.jsx)(`dt`,{children:`Adapter artifact`}),(0,$.jsx)(`dd`,{children:s.draft.startingModel.decision.artifact.id})]}):null,s.draft.startingModel?.source===`engram`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Saved module version`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:s.draft.startingModel.engram.versionHash}),(0,$.jsx)(`dt`,{children:`Module artifact`}),(0,$.jsx)(`dd`,{children:s.draft.startingModel.engram.artifact.id})]}):null,p?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Spending limit`}),(0,$.jsx)(`dd`,{children:p.cap?`$${p.cap}`:`Use available credits`}),(0,$.jsx)(`dt`,{children:`Planning budget`}),(0,$.jsx)(`dd`,{children:p.planning.trim()?`$${p.planning}`:`Not set`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:typeof f==`number`&&Number.isFinite(f)&&f>0?`$${f}`:`Not set`})]})]})]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>u(!0),children:`Configure experiment`})]}):s?.resource||s?.draft&&s.target.scopeId===i.scope?.id?(0,$.jsx)(xv,{connection:e,sessionId:t,resources:x,events:n,selectedExperiment:m,experimentName:s.target.kind===`dataset`?`Experiment draft`:s.label},JSON.stringify(s.target)):(0,$.jsx)(`div`,{className:`chat-experiment-tool-content`,children:(0,$.jsx)(`p`,{children:`Choose an experiment or model, or start a new experiment.`})})]})}function LS(e){return e.connection?(0,$.jsx)(IS,{connection:e.connection,sessionId:e.sessionId??null,events:e.events}):(0,$.jsx)(`p`,{children:`Connect to OpenPond to browse experiments.`})}function RS({activeTabId:e,tabs:t,onCloseTab:n,onNewTab:r,onSelectTab:i}){return(0,$.jsxs)(`div`,{className:`browser-tabs`,role:`tablist`,"aria-label":`Browser tabs`,children:[t.length?null:(0,$.jsxs)(`div`,{className:`browser-tab active`,children:[(0,$.jsx)(Mo,{size:13,"aria-hidden":!0}),(0,$.jsx)(`button`,{type:`button`,className:`browser-tab-main`,role:`tab`,"aria-selected":!0,children:`New tab`})]}),(0,$.jsx)(zS,{activeTabId:e,tabs:t,onSelectTab:i,onCloseTab:n}),(0,$.jsx)(`button`,{type:`button`,className:`browser-tab-add`,title:`New tab`,"aria-label":`New tab`,onClick:r,children:(0,$.jsx)(za,{size:14})})]})}function zS({activeTabId:e,tabs:t,onCloseTab:n,onSelectTab:r}){return(0,$.jsx)($.Fragment,{children:t.map(t=>(0,$.jsxs)(`div`,{className:`browser-tab ${t.id===e?`active`:``}`,children:[(0,$.jsx)(`span`,{className:`browser-tab-favicon`,"aria-hidden":`true`,children:t.faviconUrl?(0,$.jsx)(`img`,{alt:``,referrerPolicy:`no-referrer`,src:t.faviconUrl}):(0,$.jsx)(Mo,{size:13})}),(0,$.jsx)(`button`,{type:`button`,className:`browser-tab-main`,role:`tab`,"aria-selected":t.id===e,title:t.url,onClick:()=>r(t.id),children:BS(t)}),(0,$.jsx)(`button`,{type:`button`,className:`browser-tab-close`,title:`Close tab`,"aria-label":`Close tab`,onClick:()=>n(t.id),children:(0,$.jsx)(Ua,{size:12})})]},t.id))})}function BS(e){if(!e.url||e.url===`about:blank`)return`New tab`;if(e.title?.trim())return e.title.trim();try{return new URL(e.url).host||e.url}catch{return e.url||`New tab`}}var VS=(0,Q.lazy)(()=>o(()=>import(`./WorkspaceDiffPanel-B4e0lyF7.js`).then(e=>e.n).then(e=>({default:e.WorkspaceDiffPanel})),__vite__mapDeps([81,1,2,3,4,5,22,21,6,13,15,31,32,38,16,17,18,19,20,23,24,9,25,26,8,10,27,28,11,29,30,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,59,82,83,70]))),HS=(0,Q.lazy)(()=>o(()=>import(`./AppTerminalPanel-CKJIVpKa.js`).then(e=>({default:e.AppTerminalPanel})),__vite__mapDeps([84,1,2,3]))),US=(0,Q.lazy)(()=>o(()=>import(`./RightSidebarHomePanel-BfMMVkM1.js`).then(e=>({default:e.RightSidebarHomePanel})),[]));(0,Q.lazy)(()=>o(()=>import(`./WorkSidebarPanel-CY-AHZ4-.js`).then(e=>({default:e.WorkSidebarPanel})),[]));var WS=(0,Q.lazy)(()=>o(()=>import(`./CollaborationTabs-BU4uc4tZ.js`).then(e=>({default:e.CollaborationTabs})),__vite__mapDeps([85,2,1,3,16,20,4,5,6,21,22,13,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,18,42,43,44,45,46,47,48,19,49,50,51,52,53,54,55,56,86]))),GS=(0,Q.lazy)(()=>o(()=>import(`./AppsView-BsMyPX_3.js`).then(e=>({default:e.AppsView})),__vite__mapDeps([87,1,2,3,4,5,9,6,31,21,32,13,16,41,42,88,17,18,19,20,22,23,15,24,25,26,8,10,27,28,11,29,30,33,34,35,36,37,38,39,40,43,44,45,46,47,48,49,50,51,52,53,54,55,56,83,89,90,7,91,92,93]))),KS=(0,Q.lazy)(()=>o(()=>import(`./GetStartedView-CLVD-qEi.js`).then(e=>({default:e.GetStartedView})),__vite__mapDeps([94,1,2,3,22,5,21,6,13,16,17,18,19,20,4,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,61,95]))),qS=(0,Q.lazy)(()=>o(()=>import(`./LabsRoute-CbztQaEf.js`).then(e=>({default:e.LabsRoute})),__vite__mapDeps([96,1,2,3,4,97,5,28,6,9,26,21,8,10,11,30,24,38,20,22,13,23,15,25,27,29,31,32,33,34,35,36,37,16,39,40,41,18,42,43,44,45,46,47,48,19,49,50,51,52,53,54,55,56,77,78,79,80,7,12,98,17,57,99,100,82,64,90,101,68,61,102]))),JS=(0,Q.lazy)(()=>o(()=>import(`./ScheduledWorkPage-CAkSwM0T.js`).then(e=>({default:e.ScheduledWorkPage})),__vite__mapDeps([103,1,2,3,22,5,21,6,13,23,15,24,104,16,17,18,19,20,4,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,65,66,60,61,83,105]))),YS=(0,Q.lazy)(()=>o(()=>import(`./OutputsPage-Cmk15Vt_.js`).then(e=>({default:e.OutputsPage})),__vite__mapDeps([106,1,2,3,16,17,13,18,19,20,4,5,6,21,22,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,66,59,60]))),XS=(0,Q.lazy)(()=>o(()=>import(`./ProjectsPage-BZ3Eo3Mz.js`).then(e=>({default:e.ProjectsPage})),__vite__mapDeps([107,1,2,3,31,21,5,6,32,16,100,42,20,4,22,13,23,15,24,9,25,26,8,10,27,28,11,29,30,33,34,35,36,37,38,39,40,41,18,43,44,45,46,47,48,19,49,50,51,52,53,54,55,56,108]))),ZS=(0,Q.lazy)(()=>o(()=>import(`./LabSkillSidebar-C7IceJTJ.js`).then(e=>({default:e.LabSkillSidebar})),__vite__mapDeps([109,1,2,3,16,17,13,18,19,20,4,5,6,21,22,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,60,110]))),QS=(0,Q.lazy)(()=>o(()=>import(`./BrowserSidebar-BIIV4aq4.js`).then(e=>({default:e.BrowserSidebar})),__vite__mapDeps([111,1,2,3,16,17,13,18,19,20,4,5,6,21,22,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,62,63]))),$S=(0,Q.lazy)(()=>o(()=>import(`./RightChatPanelStack-C6H2vU9N.js`).then(e=>({default:e.RightChatPanelStack})),__vite__mapDeps([112,1,2,3,33,22,5,21,6,13,31,32,34,35,36,15,37,16,59,14,17,18,19,20,4,23,24,9,25,26,8,10,27,28,11,29,30,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,60,61,62,63,64,65,66,67]))),eC=(0,Q.lazy)(()=>o(()=>import(`./NativeSkillSidebar-Jzx1BeKV.js`).then(e=>({default:e.NativeSkillSidebar})),__vite__mapDeps([113,1,2,3,16,17,13,18,19,20,4,5,6,21,22,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,114]))),tC=(0,Q.lazy)(()=>o(()=>import(`./TeamChatView-DmHjr8W9.js`).then(e=>({default:e.TeamChatView})),__vite__mapDeps([115,1,2,3,16,17,13,18,19,20,4,5,6,21,22,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,116]))),nC=(0,Q.lazy)(()=>o(()=>import(`./TeamChatView-DmHjr8W9.js`).then(e=>({default:e.TeamChatProView})),__vite__mapDeps([115,1,2,3,16,17,13,18,19,20,4,5,6,21,22,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,116]))),rC=(0,Q.lazy)(()=>o(()=>import(`./CommunityView-CsSxJZGn.js`).then(e=>({default:e.CommunityView})),__vite__mapDeps([117,1,2,3,104,23,5,6,21,15,24,16,17,13,18,19,20,4,22,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,65,66,60,118,119,120]))),iC=(0,Q.lazy)(()=>o(()=>import(`./TeamChatView-DmHjr8W9.js`).then(e=>({default:e.TeamAiThreadPanel})),__vite__mapDeps([115,1,2,3,16,17,13,18,19,20,4,5,6,21,22,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,116]))),aC=(0,Q.lazy)(()=>o(()=>import(`./TeamChatView-DmHjr8W9.js`).then(e=>({default:e.TeamAgentConversationPanel})),__vite__mapDeps([115,1,2,3,16,17,13,18,19,20,4,5,6,21,22,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,116]))),oC=(0,Q.lazy)(()=>o(()=>import(`./TrainingDraftPanel-6tH2xSDj.js`).then(e=>({default:e.TrainingDraftPanel})),__vite__mapDeps([121,2,1,3,16,17,13,18,19,20,4,5,6,21,22,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56]))),sC=(0,Q.lazy)(()=>o(()=>import(`./TrainingCreationPanel-ClpylNsr.js`).then(e=>({default:e.TrainingCreationPanel})),__vite__mapDeps([122,1,2,3,16,43,19,20,4,5,6,21,22,13,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,18,42,44,45,46,47,48,49,50,51,52,53,54,55,56])));function cC({ponderNavigationVersion:e=0,ponderMode:t=null,onPonderModeChange:n,experience:r,view:i,teamChat:a,community:o,bootstrap:s,runtimeEvents:c,chatMessages:l,pendingUserMessage:u,contextWindowStatus:d,goalRuntime:f,subagentRuntime:p,selectedSessionId:m,composerDraftStore:h,mainComposerFocusRequestId:g,labCloseDetailRequestId:_,labCloseDetailKind:v,sideChatTrainingLaunchRequest:y,onSideChatTrainingLaunchHandled:b,mentionApps:x,connectedAppMentions:S,profileSkills:C,selectedMentionAppId:w,busy:T,turnRunning:O,activeProvider:k,activeModel:A,codexPermissionMode:j,codexReasoningEffort:M,openPondCommandAccessMode:N,pendingApproval:P,activeWorkspaceAppId:F,activeWorkspaceId:I,activeWorkspaceKind:L,projectTarget:ee,actionCatalog:R,workspaceTarget:z,connection:B,workspaceName:V,workspaceState:H,workspaceDiff:U,workspaceBusy:te,diffBusy:ne,forceChatThread:re=!1,diffPanelOpen:W,diffPanelExpanded:ie,rightPanelMode:G,rightPanelTabRequest:ae,rightChatPanels:K,runtimeEventStore:q,nativeSkillSidebar:oe,extensionSkillSidebar:se,workspaceDiffPanelViewState:ce,sidebarFileOpenRequest:le,sidebarFileBookmarks:ue,onSetSidebarFileStatus:de,browserConversationId:fe,terminalScope:pe,terminalTabs:he,terminalCwd:ge,pendingTerminalCommand:_e,terminalOpen:ve,onToggleTerminal:ye,onWorkspaceDiffPanelViewStateChange:be,training:xe,trainingSessions:Se,trainingChatHandoff:Ce,trainingDetailTasksetId:we,onTrainingDetailTasksetIdChange:Te,onTrainingChatTaskSelect:Ee,onTrainingChatHandoffDismiss:De,onOpenSession:Oe,cloudProjects:ke,projects:Ae,projectsAccountBaseUrl:je,projectsTeamName:Me,projectTaskCounts:Ne,onNewCloudProject:Pe,onNewLocalProject:Fe,onNewProjectTask:Ie,onToggleProjectPinned:Le,onUploadLocalProject:Re,chatHistoryHasMore:ze=!1,chatHistoryLoading:Be=!1,onDiffPanelResizeStart:Ve,canSyncWorkspace:He,startMessage:Ue,onPayload:We,onError:Ge,setView:Ke,onOpenProfileSettings:qe,onOpenProviderSettings:Je,onOpenTrainingSettings:Ye,onOpenDatasetStorageSettings:Xe,changeDraftProvider:Ze,changeProjectTarget:Qe,changeWorkspaceTarget:$e,setDraftProvider:et,setDraftModel:tt,onBeginNewChatWithModel:nt,changeCodexPermissionMode:rt,changeCodexReasoningEffort:it,changeOpenPondCommandAccessMode:at,resolveApproval:ot,answerCreateImproveQuestion:st,approveCreateImproveRun:ct,applyCreateImproveCandidate:lt,cancelCreateImproveRun:ut,openCreateImprovePullRequest:dt,pauseCreateImproveRun:ft,reconcileCreateImprovePullRequest:pt,rejectCreateImproveCandidate:mt,resumeCreateImproveRun:ht,reviseCreateImproveRun:gt,setMentionedAppId:_t,showToast:vt,onSaveTaskDraft:yt,sendPrompt:bt,stopTurn:xt,syncWorkspaceLocally:St,refreshWorkspaceDiff:Ct,onToggleDiffPanelExpanded:wt,onShowDiffPanel:Tt,onShowFilePreview:Et,onShowBrowserPanel:Dt,onShowTrainingDraftPanel:Ot,onShowFilesPanel:kt,onShowExperimentsPanel:At,onShowAgentsPanel:jt,onShowRightChatPanel:Mt,onAddRightChat:Nt,onOpenRightChatForSession:Pt,onLabDetailOpenChange:Ft,evaluationSidebarActive:It,onEvaluationSidebarControl:Lt,scheduledDetailOpen:Rt,onScheduledDetailOpenChange:zt,onTerminalTabsChange:Bt,onCloseRightChatPanel:Vt,onCloseNativeSkillSidebar:Ht,onActivateRightChatPanel:Ut,onRightChatModelChange:Wt,onRightChatPromptChange:Gt,onRightChatScrollStateChange:Kt,onRightChatProviderChange:qt,onSubmitRightChat:Jt,onStopRightChat:Yt,onCloseTerminal:Xt,onLoadMoreChatHistory:Zt}){let Qt=Ng(fe),[$t,en]=(0,Q.useState)(),[tn]=(0,Q.useState)(()=>new hd),nn=(0,Q.useRef)(null),rn=m&&!So(m)?m:null,an=Fd(q,rn),on=(0,Q.useMemo)(()=>rn?Io(c,an.events):c,[rn,an.events,c]),sn=(0,Q.useMemo)(()=>rn?Qi(tn.project(on),u):l,[tn,rn,u,on,l]),[cn,ln]=(0,Q.useState)(null),[un,dn]=(0,Q.useState)(0),fn=(0,Q.useRef)(``),pn=(0,Q.useCallback)(()=>fn.current,[]),[mn,hn]=(0,Q.useState)(null),gn=Pd(fe),[_n,vn]=(0,Q.useState)(null),[yn,bn]=(0,Q.useState)(null),[xn,Sn]=(0,Q.useState)(null),[Cn,wn]=(0,Q.useState)(null),[Tn,En]=(0,Q.useState)(null),[Dn,On]=(0,Q.useState)(null),[kn,An]=(0,Q.useState)([]);(0,Q.useEffect)(()=>{hn(null)},[fe]);let jn=(0,Q.useMemo)(()=>s?.sessions.find(e=>e.id===m)??null,[s?.sessions,m]),Mn=Se.find(e=>e.id===m)??jn,Nn=jn?.currentProfile??s?.profileLibrary?.lastUsed??null,Pn=kg(s),Fn=s?.preferences.defaultTeamId??null,In=s?.account.profile?.id??null,Ln=(0,Q.useMemo)(()=>({accountKey:Pn,teamId:Fn,actorId:In}),[Pn,Fn,In]),Rn=Nd({connection:B,sessionId:m,accountScope:Pn,active:i===`chat`,onOpen:At}),zn=$o(s?.profileLibrary??{lastUsed:null,profiles:[]},Nn)??s?.profile??null,Bn=(0,Q.useMemo)(()=>ro(zn,s?.extensionCatalog),[s?.extensionCatalog,zn]),Vn=(0,Q.useMemo)(()=>Yi(zn),[zn]),Hn=(0,Q.useCallback)(async(e,t=m)=>{if(!B||!s)return;let n=Lo(s.profileLibrary??{lastUsed:null,profiles:[]},e);if(n)try{let e=await sg({ref:n,session:t&&!So(t)?s.sessions.find(e=>e.id===t)??null:null,selectProfile:e=>Eo.profileSelect(B,e),patchSession:(e,t)=>Eo.patchSession(B,e,{currentProfile:t})}),r=s.sessions;e.session&&(r=r.map(t=>t.id===e.session.id?e.session:t)),We({...s,profile:e.selected.profile,profileLibrary:e.selected.library,sessions:r})}catch(e){let t=e instanceof Error?e.message:String(e);Ge(t),vt(t,`error`)}},[s,B,Ge,We,m,vt]);(0,Q.useEffect)(()=>{if(!Vo(le,fe))return;let{file:e,id:t}=le;if(hn({id:t,path:e.path}),!B)return;let n=!1;return(e.workspaceKind===`local`?Eo.workspaceFile(B,e.workspaceId,e.path).then(e=>e.content??``):Eo.sandboxDownloadFile(B,e.workspaceId,e.path).then(e=>{if(e.file.isBinary)throw Error(`Binary files cannot be attached to chat.`);return e.contents})).then(r=>{if(n)return;let i=e.path.split(`/`).at(-1)??e.path;ln({id:t,file:new File([r],i,{type:lC(e)})})}).catch(e=>{n||vt(e instanceof Error?e.message:String(e),`error`)}),()=>{n=!0}},[fe,B,vt,le]);let Un=r===`development`||r===`work`&&ee.value!==`none`,Wn=(0,Q.useMemo)(()=>{if(!Un)return[];let e=new Map(R.filter(e=>!Ji(e)).map(e=>[e.id,e]));for(let t of Vn)e.set(t.id,t);for(let t of kn)e.set(t.id,t);return[...e.values()]},[R,r,Un,kn,Vn]),Gn=lg(B),Kn=(0,Q.useCallback)(e=>{e?Gn.activate({runId:e.run.id,candidateId:e.candidate.id,title:e.run.objective,fileRootPath:e.fileRootPath,initialPath:e.initialPath}):Gn.activate(null)},[Gn.activate]),qn=(0,Q.useCallback)(()=>{Gn.selection?.initialPath&&Gn.openFile(Gn.selection.initialPath),Tt()},[Gn.openFile,Gn.selection?.initialPath,Tt]),Jn=(0,Q.useCallback)(e=>{bn(e),e&&Tt()},[Tt]),Yn=(0,Q.useCallback)(()=>{bn(null),ie&&wt()},[ie,wt]);(0,Q.useEffect)(()=>{i!==`labs`&&bn(null)},[i]);let Xn=(0,Q.useCallback)((e,t)=>{let n=Date.now(),r=R.find(t=>t.id===e)??null;h.set(``),_t(null),Ke(`chat`);let i=r=>{if(!(r.find(t=>t.id===e)??null))return!1;let i=r.map(n=>n.id===e?{...n,label:t}:n);return An(i),window.requestAnimationFrame(()=>{On({actionId:e,requestId:Math.max(Date.now(),n+1)})}),!0};B?Eo.profileCurrent(B).then(t=>{let n=t.actionCatalog.map(e=>Mi(e));!i(n)&&r?i([r]):n.some(t=>t.id===e)||vt(`This Agent is ready, but its default chat action is unavailable.`,`error`)}).catch(e=>{r||vt(e instanceof Error?e.message:String(e),`error`)}):r?i([r]):vt(`The Agent action catalog is still loading. Try Use again.`,`error`)},[R,h,B,_t,Ke,vt]),Zn=(0,Q.useCallback)((e,t)=>{h.set(e),_t(null),t&&Ze(t),Ke(`chat`)},[Ze,h,_t,Ke]),Qn=(0,Q.useMemo)(()=>di(s?.preferences),[s?.preferences]),$n=Qn.training,{createAgentFromLab:er,improveAgentFromLab:tr}=dg({activeModel:A,activeProvider:k,bootstrap:s,codexPermissionMode:j,codexReasoningEffort:M,connection:B,onOpenRightChatForSession:Pt,onPayload:We}),nr=(0,Q.useMemo)(()=>{let e=xe.payload?.tasksets??[];return e.some(e=>e.id===Cn)?Cn:e[0]?.id??null},[Cn,xe.payload?.tasksets]),rr=i===`labs`&&nr?`profiles/${s?.profile.activeProfile??`default`}/tasksets/${nr}`:null,ir=(0,Q.useMemo)(()=>{if(i!==`labs`||!nr||!xe.payload)return null;let e=xe.payload.tasksets.find(e=>e.id===nr);if(!e)return null;let t=xe.payload.plans.filter(t=>t.tasksetId===e.id),n=new Set(t.map(e=>e.id)),r=xe.payload.jobs.filter(e=>n.has(e.planId)).sort((e,t)=>t.createdAt.localeCompare(e.createdAt)),a=r.find(e=>e.id===Tn)??r[0]??null;return{taskset:e,plan:a?t.find(e=>e.id===a.planId)??null:t.sort((e,t)=>t.createdAt.localeCompare(e.createdAt))[0]??null,job:a,lineage:a?xe.payload.models.find(e=>e.jobId===a.id)??null:null,artifacts:a?xe.payload.artifacts.filter(e=>e.jobId===a.id):[]}},[nr,Tn,xe.payload,i]),ar=(0,Q.useMemo)(()=>cg(xe.payload,m),[m,xe.payload]),or=(0,Q.useMemo)(()=>ed(sn),[sn]),sr=!!f||!!or||!!p,cr=i===`labs`&&!!Gn.selection,lr=i===`labs`&&W&&G===`changes`&&!!yn,ur=(i===`chat`||i===`labs`)&&!!(F||mn?.file),dr=i===`chat`&&W&&G===`chat`&&K.length===0,fr=To(L)?I??id(V):null,pr=i===`chat`&&!!fr,mr=fr,hr=!!mr||z.value===`cloud`||z.value===`hybrid`,gr=(0,Q.useMemo)(()=>rg({workspaceTarget:z.value,localWorkspaceId:F,sandboxSourceAvailable:hr,sandboxWorkspaceId:mr,override:_n}),[F,hr,mr,_n,z.value]),_r=gr.source,vr=_r===`sandbox`,yr=(0,Q.useMemo)(()=>_r&&gr.options.length>1?{value:_r,options:gr.options,onChange:vn}:null,[_r,gr.options]);(0,Q.useEffect)(()=>{vn(null)},[F,fe,mr,z.value]);let br=!lr&&(cr||i===`chat`||ur||pr)&&W&&(G===`changes`||G===`home`&&i===`chat`||G===`goal`&&sr||dr),xr=i===`chat`&&W&&G===`browser`,Sr=(i===`chat`||i===`labs`)&&W&&G===`chat`&&K.length>0,Cr=i===`chat`&&W&&G===`training`,wr=i===`chat`&&W&&!!oe,Tr=i===`chat`&&W&&!!se,Er=i===`team`&&W&&G===`chat`&&!!a.aiThread,Dr=i===`team`&&W&&G===`chat`&&!!a.agentConversation,Or=Lu({supportedView:i===`chat`&&Un||i===`labs`,open:W,hasContentPanel:br||lr||xr||Sr||Cr||wr||Er||Dr}),kr=!It&&(br||lr||xr||Sr||Cr||wr||Er||Dr||Or),Ar=kr&&G!==`chat`&&ie,jr=s?.account.baseUrl??s?.account.activeProfile?.baseUrl??null,Mr=Gu({activeWorkspaceId:I,cloudProjects:ke}),Nr=i===`chat`&&O&&!P&&mu(sn),Pr=re||sn.length>0||Nr,Fr=m??`draft:${i}:${L??`none`}:${I??F??`none`}`;fn.current=Fr;let Ir=(0,$.jsx)(Pu,{activeModel:A,activeProvider:k,busy:O,handoff:Ce,onDismiss:De,onSelectTask:Ee}),Lr=(0,Q.useMemo)(()=>({onAnswerQuestion:st,onApprove:ct,onApplyCandidate:lt,onCancel:ut,onOpenPullRequest:dt,onPause:ft,onReconcilePullRequest:pt,onRejectCandidate:mt,onResume:ht,onRevise:gt}),[st,ct,lt,ut,dt,ft,pt,mt,ht,gt]),Rr=(0,Q.useMemo)(()=>or?{...or,...Lr}:null,[Lr,or]),zr=Ru(i,Pr),Br=(0,Q.useCallback)(async(e=[],t=null,n=null,i={})=>{let a=i.promptOverride??h.getSnapshot(),o=()=>{i.preservePrompt||(h.set(``),_t(null))};if(!t){let t=n?{command:n.id,args:a.trim()}:Ii(a);if(t){if(!Ui({id:t.command},r))return vt(`/${t.command} isn't available in ${r}.`,`info`),!1;if(t.command===`train`)return e.length>0?(vt(`/train uses the selected chat; add other chats from Models.`,`error`),!1):m?(o(),Sn({id:Date.now(),objective:t.args.trim()||null,initialSessionIds:[m]}),Ke(`labs`),!0):(o(),Sn({id:Date.now(),objective:t.args.trim()||null,initialSessionIds:[]}),Ke(`labs`),!0);if(!t.args&&t.command!==`skill`&&t.command!==`sync-cloud`)return vt(`Add instructions after /${t.command}.`,`info`),!1;if(e.length>0)return vt(`/${t.command} tasks do not accept attachments yet. Add file context in the task thread.`,`error`),!1;if(t.command===`submit-issue`)return zi(S)?(dn(e=>e+1),bt([],null,Hi(t.args),{clearPrompt:i.preservePrompt?()=>void 0:void 0,usageAttribution:nd(t,n?`composer_selection`:`prompt_parse`)})):(vt(`Connect the GitHub app before using /submit-issue.`,`error`),!1);if(rd(t)){let e=t.command===`skill`?ag(t.args,k,s?.profile.sourcePath??null):td(t);return dn(e=>e+1),bt([],null,e,{clearPrompt:i.preservePrompt?()=>void 0:void 0,usageAttribution:nd(t,n?`composer_selection`:`prompt_parse`)})}return dn(e=>e+1),bt([],null,td(t),{clearPrompt:i.preservePrompt?()=>void 0:void 0,usageAttribution:nd(t,n?`composer_selection`:`prompt_parse`)})}}return dn(e=>e+1),bt(e,t,i.promptOverride,{clearPrompt:i.preservePrompt?()=>void 0:void 0,displayPrompt:i.displayPrompt,turnMetadata:i.turnMetadata,sessionMetadata:i.sessionMetadata,onSessionCreated:i.onSessionCreated})},[A,k,L,s?.profile,S,h,r,bt,m,_t,Ke,vt,xe,i]),J=(0,Q.useCallback)(e=>{Ce&&e!==Ce.model.modelId&&De(),ki(k,e),et(k),tt(e)},[k,De,tt,et,Ce]),Vr=(0,Q.useCallback)((e,t)=>{Ce&&e!==Ce.model.providerId&&De(),Ze(e,t)},[Ze,De,Ce]),Hr=(0,Q.useCallback)((e,t)=>{ea({conversationId:fe,href:e,explicitFile:t?.explicitFile,newTab:t?.newTab}).then(e=>{e&&window.openpond?.browser&&(gn.showBrowser(),Dt())}).catch(e=>vt(e instanceof Error?e.message:`Could not open browser.`,`error`))},[fe,gn.showBrowser,Dt,vt]),Ur=ba({projectTargetDetail:ee.detail,projectTargetValue:ee.value,workspaceRepoPath:H?.repoPath,workspaceTargetValue:z.value}),{handleOpenFileInSidebar:Wr,fileResolution:Gr,dismissFileResolution:Kr,selectFileResolution:qr}=ng({conversationKey:fe,connection:B,handleOpenBrowserLink:Hr,activeWorkspaceAppId:F,rightSidebarUsesSandbox:vr,rightSidebarSandboxId:mr,onShowDiffPanel:Et,showToast:vt,workspaceRootPath:Ur,setOpenDiffFileRequest:hn});Au(q,i===`chat`?rn:null,Wr);let Jr=(0,Q.useCallback)(async e=>{if(!B||!e.filePreview&&!e.imagePreview)vt(`File content is not available for this attachment.`,`error`);else try{let t=e.name.trim().replace(/[\\/]+/g,`-`)||`attachment.txt`,n=`Attachments/${e.id.replace(/[^a-zA-Z0-9._-]+/g,`-`)||`file`}/${t}`,r={path:n,status:``,additions:0,deletions:0,patch:``,content:null},i,a;if(e.filePreview){let n=await Eo.chatAttachmentFile(B,e.filePreview);r.content=n.content,fa(t)&&(a=await aa(B,t,n.content))}else e.imagePreview&&(i=(await Eo.signChatAttachmentImageUrl(B,e.imagePreview)).url);a?Hr(a):Et(),hn({id:Date.now(),path:n,source:!!a,file:r,...i?{imageUrl:i}:{}})}catch(e){vt(e instanceof Error?e.message:`Could not open this attachment.`,`error`)}},[B,Hr,Et,vt]),Yr=te&&!!F&&!H;(0,Q.useEffect)(()=>{let e=on.filter(e=>e.sessionId===m&&e.source===`server`&&e.name===`workspace_action_result`).at(-1),t=e?`${m}:${e.id}`:null;if(!nn.current||nn.current.sessionId!==m){nn.current={sessionId:m,eventId:t};return}if(t===nn.current.eventId)return;nn.current={sessionId:m,eventId:t};let n=e?.data;i===`chat`&&n?.chatResourcePresentation!==`context`&&n?.chatResource?.kind===`experiment`&&uf(n.chatResource.state??``)&&At()},[on,m,i,At]);let Xr=Gn.selection?`candidate:${Gn.selection.runId}:${Gn.selection.candidateId}`:null,Zr=i===`chat`?(e,n)=>n===-2&&B?(0,$.jsx)(Md,{selectionRequest:t?$t:void 0,connection:B,accountScopeKey:Pn,ponder:!!t,parentSessionId:m,sessions:Se,onOpenChat:Oe}):(0,$.jsx)(n===-1?LS:$g,{conversationId:fe,onOpenBrowser:Dt,sessionId:m,connection:B,workspaceId:F,sandboxId:vr?mr:null,messages:sn,events:on,onOpenFile:Wr,actions:(0,$.jsx)(jg,{terminalOpen:ve,sideChatAvailable:!0,onOpenFile:e,onOpenFiles:kt,onOpenAgents:jt,onOpenExperiments:At,onOpenReview:Tt,onOpenSideChat:Nt,onOpenTrainingDraft:Ot,trainingDraftAvailable:!!m,onToggleTerminal:ye})}):null,Qr=(0,Q.useMemo)(()=>G===`home`&&i===`chat`?{id:-1,tab:`outputs`,overview:`new`}:ae,[i,G,ae]),$r=br?(0,$.jsx)(VS,{appId:cr?Xr:vr?null:F,workspaceId:cr?Xr:vr?mr:F,workspaceKind:cr?`local_project`:vr?null:`local_project`,connection:B,runtimeEvents:on,diff:cr?Gn.diff:vr?null:U,fileRootPath:cr?Gn.selection?.fileRootPath??null:vr?null:rr,filesWithPreview:cr,editorPreferences:s?.preferences.editor??null,loading:cr?Gn.loading:vr?te:ne||Yr,openFileRequest:cr?Gn.openFileRequest:G===`home`?null:mn,sidebarFileBookmarks:ue,sidebarFileSourceSessionId:m,onSetSidebarFileStatus:de,readOnly:cr,sideChatTabs:K.map(e=>({id:e.id,title:e.title,running:e.running})),sourceSwitcher:cr?null:yr,tabRequest:Qr,additionalTabs:i===`chat`?(0,$.jsx)(zS,{tabs:Qt.state.tabs,activeTabId:null,onSelectTab:e=>{Qt.selectTab(e),gn.showBrowser(),Dt()},onCloseTab:e=>void Qt.closeTab(e)}):void 0,renderOutputs:Zr??void 0,outputsLabel:Rn,viewState:ce,workspaceName:cr?Gn.selection?.title??`Change`:vr?V??`Sandbox`:V,workspaceInitialized:cr?!0:vr?!!mr:!!H?.initialized,workspaceError:cr?Gn.error:vr?null:H?.error??U?.error??null,expanded:ie,onResizeStart:Ve,onRefresh:e=>void(cr?Gn.refresh(e):Ct(e)),onToggleExpanded:wt,onOpenBrowser:Dt,onOpenBrowserUrl:Hr,onViewStateChange:be,onCloseSideChat:Vt,onOpenSideChat:i===`chat`?Nt:void 0,onSelectSideChat:e=>{Ut(e),Mt()},goalDetails:{active:G===`goal`,createRuntime:Rr,goalRuntime:f,subagentRuntime:p},sandboxFileSource:vr?{sandboxId:mr,emptyMessage:`No sandbox filesystem yet.`}:null,trainingSummary:ir}):null,ei=(0,Q.useCallback)(e=>{gn.open(e),Dt()},[gn.open,Dt]),ti=(0,Q.useCallback)(async(e,t,n)=>{if(!B||e.sessionId!==m)throw Error(`Open the originating conversation to select this resource.`);let r=await ko(B,`dataset`,{action:`context`,payload:{sessionId:e.sessionId}}),i=await ko(B,`dataset`,{action:`set_focus`,payload:{sessionId:e.sessionId,kind:t.kind,id:t.id,...t.revision?{revision:t.revision}:{},operationId:n,visualPublicationId:e.publicationId,expectedSelectionVersion:r.focus.scopeContext?.selectionVersion}}),a=t.kind===`dataset`?i.dataset:i.experiment;if(!a)throw Error(`Selected resource is unavailable.`);let o=`Selected ${t.kind}: ${a.name}${t.kind===`dataset`?` V${a.revision}`:``}.`;return await co.queueTaskInput(B,e.sessionId,me.parse({prompt:o,metadata:{chatExperimentScopeId:i.scopeContext?.activeScopeId,chatExperimentSelectionVersion:i.scopeContext?.selectionVersion,chatResourceFocus:{dataset:i.dataset,experiment:i.experiment},resourceSelection:{kind:t.kind,id:a.id,revision:a.revision,visualPublicationId:e.publicationId}}}),n),window.dispatchEvent(new CustomEvent(`openpond-resource-focus-changed`,{detail:{sessionId:e.sessionId}})),o},[B,m]),ni=xr?(0,$.jsx)(QS,{conversationId:fe,connection:B,visualTabs:gn,expanded:ie,onResizeStart:Ve}):null,ri=Er?(0,Q.createElement)(iC,{...a,key:a.aiThread?.conversationId,onResizeStart:Ve}):null,ii=Dr?(0,Q.createElement)(aC,{...a,key:a.agentConversation?.run.id,onResizeStart:Ve}):null,ai=Sr?(0,$.jsx)($S,{panels:K,runtimeEventStore:q,actionCatalog:Wn,createImproveActions:Lr,contextCompaction:Qn.contextCompaction,steerActiveResponses:Qn.steerActiveResponses,busy:T,codexPermissionMode:j,codexReasoningEffort:M,openPondCommandAccessMode:N,connection:B,connectedAppMentions:S,mentionApps:x,codexPersonalSkills:s?.codexPersonalSkills??[],profileSkills:C,profileLibrary:s?.profileLibrary??{lastUsed:null,profiles:[]},extensionCatalog:s?.extensionCatalog??null,projectTarget:ee,providerSettings:s?.providers??null,accountBaseUrl:jr,billingOrganizationSlug:Mr.organizationSlug,billingTeamId:Mr.teamId,showToast:vt,workspaceTarget:z,onAddChat:Nt,onActivatePanel:Ut,onClosePanel:Vt,onCodexPermissionModeChange:rt,onCodexReasoningEffortChange:it,onOpenPondCommandAccessModeChange:at,onModelChange:Wt,onOpenAttachmentInSidebar:Jr,onOpenFileInSidebar:Wr,onOpenProfileSettings:qe,onOpenSession:Oe,onOpenPonder:()=>n?.(`clean`),onProviderChange:qt,onProviderSetupOpen:Je,onPromptChange:Gt,onProfileTargetChange:(e,t)=>void Hn(t,e),onScrollStateChange:Kt,onProjectTargetChange:Qe,onResolveApproval:ot,onResizeStart:Ve,onSelectFiles:kt,onShowBrowserPanel:Dt,onStop:Yt,onSubmit:Jt,onWorkspaceTargetChange:e=>void $e(e)}):null,oi=ii??ri??ai??(wr&&oe?(0,$.jsx)(eC,{expanded:ie,skill:oe,onClose:Ht,onResizeStart:Ve,onToggleExpanded:wt}):null)??(Tr&&se?(0,$.jsx)(ZS,{connection:B,expanded:ie,selection:se,onClose:Ht,onResizeStart:Ve,onToggleExpanded:wt}):null)??(lr&&yn?(0,$.jsx)(ZS,{connection:B,expanded:ie,selection:yn,onClose:Yn,onResizeStart:Ve,onToggleExpanded:wt}):null)??$r??ni??(Cr?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(oC,{training:xe,sessionId:m,expanded:ie,onOpenTraining:()=>Ke(`labs`),onResizeStart:Ve,onToggleExpanded:wt})}):null)??(Or?(0,$.jsx)(US,{expanded:ie,terminalOpen:ve,sideChatAvailable:i===`chat`||i===`labs`,onOpenFiles:kt,onOpenAgents:jt,onOpenReview:Tt,onOpenSideChat:Nt,onOpenTrainingDraft:Ot,trainingDraftAvailable:!!m,onResizeStart:Ve,onToggleExpanded:wt,onToggleTerminal:ye}):null),si=(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(HS,{open:ve,connection:B,scope:pe,tabs:he,onTabsChange:Bt,cwd:ge,appId:F,workspaceName:V,queuedCommand:_e,onClose:Xt})});return(0,$.jsx)(D.Provider,{value:Pn,children:(0,$.jsx)(E.Provider,{value:Ln,children:(0,$.jsx)(gu.Provider,{value:ei,children:(0,$.jsx)(_u.Provider,{value:ti,children:(0,$.jsxs)(`main`,{tabIndex:-1,"data-thread-session":i===`chat`&&!t?m??void 0:void 0,className:`main-pane ${zr} ${ve?`terminal-open`:``} ${kr?`diff-open`:``} ${Ar?`diff-expanded`:``}`,children:[Gr?(0,$.jsx)(Qh,{resolution:Gr,onClose:Kr,onSelect:qr}):null,i===`team`||i===`community`?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(WS,{onSelect:Ke,view:i})}):null,i===`chat`&&t&&B&&s?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Og,{navigationVersion:e,messageContext:{accountBaseUrl:jr,activeWorkspaceAppId:F,billingOrganizationSlug:Mr.organizationSlug,billingTeamId:Mr.teamId,onOpenBrowserLink:Hr,onOpenAttachmentInSidebar:Jr,onOpenFileInSidebar:Wr,onOpenProfileSettings:qe,workspaceRootPath:Ur},onOpenAgents:e=>{e&&en(t=>({sessionId:e,version:(t?.version??0)+1})),jt()},contextCompaction:Qn.contextCompaction,accountScopeKey:Pn,connection:B,presentation:t,localSessions:Se,composer:{contextWindowStatus:d,providerSettings:s.providers??null,provider:k,model:A,projectTarget:ee,workspaceTarget:z,codexPermissionMode:j,codexReasoningEffort:M,openPondCommandAccessMode:N,onProviderChange:Vr,onProviderSetupOpen:Je,onProjectTargetChange:Qe,onWorkspaceTargetChange:e=>{$e(e)},onModelChange:J,onCodexPermissionModeChange:rt,onCodexReasoningEffortChange:it,onOpenPondCommandAccessModeChange:at,showToast:vt},accountBaseUrl:je,onOpenBrowserLink:Hr,onOpenLocalWork:Oe},Pn),si,(0,$.jsx)(Q.Suspense,{fallback:null,children:oi})]}):i===`apps`?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(GS,{payload:s,onPayload:We,account:s?.account??null,connection:B,defaultTeamId:s?.preferences.defaultTeamId??null,onToast:vt})}):i===`team`?(0,$.jsxs)(Q.Suspense,{fallback:null,children:[a.teamId?(0,$.jsx)(tC,{...a}):(0,$.jsx)(nC,{}),kr?oi:null]}):i===`community`?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(rC,{...o})}):i===`get-started`?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(KS,{})}):i===`scheduled`?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(JS,{connection:B,selectedProfileKey:Nn?JSON.stringify(Nn):null,onOpenSession:Oe,detailOpen:Rt,detailExpanded:ie,onDetailOpenChange:zt,onDetailResizeStart:Ve,onToggleDetailExpanded:wt},Pn)}):i===`outputs`?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(YS,{connection:B,onViewChat:Oe})}):i===`projects`?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(XS,{accountBaseUrl:je,connection:B,onNewCloudProject:Pe,onNewLocalProject:Fe,onNewTask:Ie,onTogglePinned:Le,onUploadLocalProject:Re,projects:Ae,taskCountByProjectId:Ne,teamName:Me},Pn)}):i===`labs`?Ar?(0,$.jsx)(Q.Suspense,{fallback:null,children:oi}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(qS,{account:s?.account??null,closeDetailRequestId:_,closeDetailKind:v,onNewModel:(e,t,n)=>{Sn({id:Date.now(),objective:null,initialSessionIds:[],initialTasksetId:e,learnedPreferenceReward:t,initialModelId:n})},onUseAgent:Xn,onCreateAgent:er,onImproveAgent:tr,onDetailOpenChange:Ft,onEvaluationSidebarControl:Lt,onSkillSelectionChange:Jn,onOpenRunConversation:Pt,onAnswerQuestion:st,onApplyCandidate:lt,onApprove:ct,onCancel:ut,candidateReview:{diff:Gn.diff,error:Gn.error,loading:Gn.loading},onCandidateReviewChange:Kn,onOpenPullRequest:dt,onOpenCandidateFiles:qn,onPause:ft,onReconcilePullRequest:pt,onRejectCandidate:mt,onResume:ht,onRevise:gt,profileView:{payload:s,connection:B,onPayload:We,onError:Ge,onToast:vt,onSkillCommand:Zn},training:{training:xe,sessions:Se,localProjects:s?.localProjects??[],connection:B,defaultModel:{providerId:k,modelId:A},onError:Ge,onToast:vt,onSettingsPreferences:e=>{s&&We({...s,preferences:e.preferences})},onOpenTrainingSettings:Ye,onOpenProviderSettings:Je,onOpenDatasetStorageSettings:Xe,onOpenChat:Oe,onChatWithModel:nt,onOpenTasksetFiles:kt,launchRequest:y??xn,onLaunchHandled:e=>{y?.id===e?b(e):Sn(t=>t?.id===e?null:t)},preferences:$n,settingsPreferences:Qn,providerSettings:s?.providers??null,reasoningEffort:M,selectedTasksetId:nr,onSelectedTasksetIdChange:wn,onSelectedTrainingJobIdChange:En,detailTasksetId:we,onDetailTasksetIdChange:Te}})}),si,kr?(0,$.jsx)(Q.Suspense,{fallback:null,children:oi}):null]}):Ar?(0,$.jsx)(Q.Suspense,{fallback:null,children:oi}):Pr?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(fd,{hasApproval:!!P,scroll:{browserConversationId:fe,chatSubmissionVersion:un,chatHistoryHasMore:ze,chatHistoryLoading:Be,chatMessages:sn,onLoadMoreChatHistory:Zt,pendingApproval:P,showChatThread:Pr,showThinkingIndicator:Nr,turnRunning:O,view:i},thread:{formalReviewTeamId:Qn.defaultTeamId??null,formalReviewActorId:s?.account.profile?.id??null,formalReviewScopeKey:Pn,onFormalReviewOpen:()=>Ke(`labs`),accountBaseUrl:jr,activeWorkspaceAppId:F,billingOrganizationSlug:Mr.organizationSlug,billingTeamId:Mr.teamId,connection:B,creation:ar,onOpenBrowserLink:Hr,onOpenAttachmentInSidebar:Jr,onOpenFileInSidebar:Wr,onOpenProfileSettings:qe,onResolveUserQuestion:async(e,t)=>{let n=t.action===`answer`?t.text:`Dismiss this question`;if(!await bt([],null,n,{displayPrompt:n,turnMetadata:{userQuestionResolution:t}}))throw Error(`The question response could not be sent.`)},onOpenSession:Oe,onOpenPonder:()=>n?.(`clean`),userAttachmentDisplay:k===`codex`?`compact`:`full`,workspaceRootPath:Ur},composerPrefix:(0,$.jsxs)($.Fragment,{children:[ar?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(sC,{compact:!0,creation:ar,training:xe,onOpenTraining:()=>Ke(`labs`)})}):null,Ir,(0,$.jsx)(Yh,{connection:B,showToast:vt,approval:P,onResolve:ot})]}),composer:(0,$.jsx)(Lh,{experience:r,readOnlyReason:typeof Mn?.metadata?.nativeReadOnlyReason==`string`?Mn.metadata.nativeReadOnlyReason:null,readOnlySession:Mn,onOpenNativeParent:Oe,draftStore:h,attachmentRequest:cn,mode:`dock`,focusRequestId:g,mentionApps:Un?x:[],connectedAppMentions:S,profileSkills:k===`codex`?s?.codexPersonalSkills??[]:Bn,selectedMentionAppId:w,contextWindowStatus:d,goalRuntime:f,subagentRuntime:p,createImproveRuntime:Un?Rr:null,busy:O,running:O,steerActiveResponses:Qn.steerActiveResponses,taskSessionId:rn,goalSessionId:m,taskEvents:on,submissionScopeKey:Fr,composerDraftStore:h,getCurrentSubmissionScopeKey:pn,voiceInputChannelKey:`main-composer:${Fr}`,showProjectFooter:!0,connection:B,providerSettings:s?.providers??null,provider:k,model:A,projectTarget:ee,profileTarget:null,actionCatalog:Wn,requestedAction:Dn,workspaceTarget:z,codexPermissionMode:j,codexReasoningEffort:M,openPondCommandAccessMode:N,onProviderChange:Vr,onProviderSetupOpen:Je,onProjectTargetChange:Qe,onProfileTargetChange:e=>void Hn(e),onWorkspaceTargetChange:e=>void $e(e),onModelChange:J,onCodexPermissionModeChange:rt,onCodexReasoningEffortChange:it,onOpenPondCommandAccessModeChange:at,onMentionAppSelect:_t,onSaveTaskDraft:yt,showToast:vt,onSubmit:Br,onStop:xt})}),si,(0,$.jsx)(Q.Suspense,{fallback:null,children:oi})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`section`,{className:`start-panel`,children:[(0,$.jsxs)(`div`,{className:`start-welcome`,children:[(0,$.jsx)(`h1`,{children:Ue}),He&&(0,$.jsx)(Iu,{busy:te,onSync:()=>void St()})]}),(0,$.jsxs)(`div`,{className:`composer-stack start`,children:[Ir,(0,$.jsx)(Yh,{connection:B,showToast:vt,approval:P,onResolve:ot}),(0,$.jsx)(Lh,{experience:r,draftStore:h,attachmentRequest:cn,mode:`start`,autoFocus:!0,focusRequestId:g,mentionApps:Un?x:[],connectedAppMentions:S,profileSkills:k===`codex`?s?.codexPersonalSkills??[]:Bn,selectedMentionAppId:w,contextWindowStatus:d,goalRuntime:f,subagentRuntime:p,createImproveRuntime:Un?Rr:null,busy:O,running:O,steerActiveResponses:Qn.steerActiveResponses,taskSessionId:rn,goalSessionId:m,taskEvents:on,submissionScopeKey:Fr,composerDraftStore:h,getCurrentSubmissionScopeKey:pn,voiceInputChannelKey:`main-composer:${Fr}`,connection:B,providerSettings:s?.providers??null,provider:k,model:A,showProjectFooter:!0,projectTarget:ee,profileTarget:null,actionCatalog:Wn,requestedAction:Dn,workspaceTarget:z,codexPermissionMode:j,codexReasoningEffort:M,openPondCommandAccessMode:N,onProviderChange:Vr,onProviderSetupOpen:Je,onProjectTargetChange:Qe,onProfileTargetChange:e=>void Hn(e),onWorkspaceTargetChange:e=>void $e(e),onModelChange:J,onCodexPermissionModeChange:rt,onCodexReasoningEffortChange:it,onOpenPondCommandAccessModeChange:at,onMentionAppSelect:_t,onSaveTaskDraft:yt,showToast:vt,onSubmit:Br,onStop:xt})]})]}),si,(0,$.jsx)(Q.Suspense,{fallback:null,children:oi})]})]})})})})})}function lC(e){let t=e.path.toLowerCase();return t.endsWith(`.md`)||t.endsWith(`.mdx`)?`text/markdown`:t.endsWith(`.json`)?`application/json`:t.endsWith(`.yaml`)||t.endsWith(`.yml`)?`application/yaml`:`text/plain`}export{Iv as $,Yc as $t,Ob as A,Tu as At,ky as B,uu as Bt,ix as C,Lm as Ct,Hb as D,ld as Dt,Kb as E,hd as Et,Hy as F,_u as Ft,ny as G,Ql as Gt,Ey as H,au as Ht,By as I,hu as It,Mv as J,tl as Jt,Bv as K,il as Kt,Ly as L,pu as Lt,tb as M,cC as MainPane,bu as Mt,Qy as N,yu as Nt,Lb as O,Au as Ot,Uy as P,gu as Pt,jv as Q,Uc as Qt,Iy as R,fu as Rt,ox as S,Rm as St,Zb as T,Fd as Tt,ay as U,ru as Ut,Dy as V,cu as Vt,iy as W,nu as Wt,Nv as X,Rc as Xt,zv as Y,Qc as Yt,Rv as Z,Wc as Zt,jx as _,js as _n,Ng as _t,SS as a,Cc as an,pv as at,mx as b,Yh as bt,vS as c,yc as cn,mv as ct,eS as d,Ls as dn,O_ as dt,Gc as en,Pv as et,tS as f,As as fn,Rg as ft,Ax as g,Is as gn,Pg as gt,Px as h,ks as hn,Vg as ht,CS as i,bc as in,dv as it,hb as j,Su as jt,Fb as k,Du as kt,dS as l,zs as ln,Z_ as lt,Xx as m,Ps as mn,zg as mt,PS as n,Ac as nn,kv as nt,xS as o,xc as on,hv as ot,$x as p,Fs as pn,Bg as pt,Lv as q,Zc as qt,ES as r,Sc as rn,_v as rt,fS as s,vc as sn,fv as st,RS as t,$c as tn,Ov as tt,bS as u,Rs as un,I_ as ut,Tx as v,Ts as vn,jg as vt,nx as w,dm as wt,dx as x,Ih as xt,wx as y,ds as yn,Ag as yt,Ay as z,mu as zt};
12
+ `)+(e.length>3?`\n${e.length-3} more failures in the retained results.`:``):void 0,g=a&&!o.some(e=>e.status!==`pending`),_=a&&!g&&c<s,v=a&&!g&&!_&&l<s,y=[{label:`Prepare`,state:g?`active`:o.length?`done`:`pending`,status:g?`Starting`:o.length?`Recorded`:`Waiting`},{label:`Rollouts`,state:f.length?`failed`:_?`active`:s>0&&c===s?`done`:a?`pending`:`missing`,status:f.length?`Error recorded`:_?`Generating answers`:`Model outputs`,error:h(f),detail:`${c}/${s} generated`,progress:s?c/s:0},{label:`Grade`,state:v?`active`:s>0&&l===s?`done`:a?`pending`:`missing`,status:v?`Scoring`:`Dataset graders`,detail:`${l}/${s} graded`,progress:s?l/s:0},{label:`Results`,state:m?`failed`:!a&&e.state===`completed`?`done`:a&&u===s?`active`:a?`pending`:`missing`,status:a?`Waiting for evidence`:m?`Failed`:e.state,error:m?h(d)??`The run ended with a failure. Inspect its retained cases and logs.`:void 0,detail:(e.score==null?`Score unavailable`:`Mean score ${e.score.toFixed(3)}`)+(m&&o.length?` · ${d.length} execution failure${d.length===1?``:`s`} · ${p} cancelled`:``)}];return(0,$.jsxs)(`section`,{className:`dataset-workspace-run`,"aria-label":`Selected experiment progress`,children:[(0,$.jsx)(__,{nodes:y,live:a&&!r}),r?(0,$.jsx)(X,{error:r.message,children:(0,$.jsx)(`button`,{className:`training-text-button`,onClick:i,children:`Retry`})}):n?(0,$.jsx)(`p`,{role:`status`,children:`Loading retained run evidence…`}):null]})}function w_({connection:e,run:t,view:n}){let r=n?.cases??[],i=r.filter(e=>e.score!==null).length;return r.length?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dataset-workspace-attempts`,"aria-label":`Rollout attempts`,children:r.map((e,t)=>(0,$.jsx)(`span`,{className:`dataset-workspace-attempt ${e.status===`running`?`active`:e.error?`failed`:e.score===null?`pending`:`scored`}`,style:e.score===null?void 0:{opacity:.35+.65*Math.max(0,Math.min(1,e.score))},title:`${e.taskId}: ${e.error??(e.score===null?e.status:`score ${e.score}`)}`,"aria-label":`Case ${t+1}: ${e.taskId}, ${e.score===null?e.status:`score ${e.score}`}`},e.id))}),i?(0,$.jsxs)(`details`,{className:`dataset-workspace-charts`,children:[(0,$.jsx)(`summary`,{children:`Score chart`}),(0,$.jsx)(Qr,{series:[{id:`evaluation.score`,label:`Case score`,xLabel:`Case`,bounds:r.every(e=>e.score===null||e.score>=0&&e.score<=1)?[0,1]:void 0,points:r.flatMap((e,t)=>e.score===null?[]:[{step:t+1,value:e.score}])}]})]}):null,(0,$.jsxs)(`details`,{className:`dataset-workspace-cases`,children:[(0,$.jsx)(`summary`,{children:`Answers and grader scores`}),(0,$.jsx)(`p`,{children:`Each row shows the model’s answer to one dataset task and the score given by its graders.`}),(0,$.jsx)(`div`,{className:`evaluation-table-scroll evaluation-table-frame`,children:(0,$.jsxs)(`table`,{className:`training-data-table evaluation-workspace-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Example`}),(0,$.jsx)(`th`,{children:`Status`}),(0,$.jsx)(`th`,{children:`Score`})]})}),(0,$.jsx)(`tbody`,{children:r.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsxs)(`td`,{children:[e.taskId,e.output===null?null:(0,$.jsxs)(`details`,{className:`dataset-workspace-example-answer`,children:[(0,$.jsx)(`summary`,{children:`Model answer`}),(0,$.jsx)(`pre`,{children:e.output})]})]}),(0,$.jsxs)(`td`,{children:[(0,$.jsx)(lt,{status:e.status}),e.error?(0,$.jsx)(`small`,{children:e.error}):null]}),(0,$.jsx)(`td`,{className:`evaluation-numeric`,children:e.score?.toFixed(3)??`—`})]},e.id))})]})})]}),(0,$.jsx)(T_,{connection:e,run:t,cases:r},cf(t))]}):null}function T_({connection:e,run:t,cases:n}){let[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(n[0]?.id??``),s=t.location===`local`&&!t.owner&&!t.profileRef,c=A({queryKey:[`dataset-workspace-logs`,ra(e),cf(t),a],enabled:r&&s&&!!a,initialPageParam:void 0,getNextPageParam:e=>e.trace.nextCursor??void 0,queryFn:async({signal:n,pageParam:r})=>Zc.parse(await ko(e,`experiment`,{action:`case`,payload:{id:t.id,receiptId:a,limit:100,...r?{afterSequence:r}:{}}},n)),refetchInterval:uf(t.state)?2e3:!1});return(0,$.jsxs)(`details`,{className:`dataset-workspace-logs`,onToggle:e=>i(e.currentTarget.open),children:[(0,$.jsx)(`summary`,{children:`Logs`}),s?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{compact:!0,floating:!0,label:`Log case`,value:a,options:n.map(e=>({value:e.id,label:e.taskId})),onChange:o}),c.error?(0,$.jsx)(X,{error:c.error.message}):c.isPending?(0,$.jsx)(`p`,{role:`status`,children:`Loading case trace…`}):(0,$.jsx)(`ol`,{children:c.data?.pages.flatMap(e=>e.trace.items).map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`strong`,{children:e.type.replaceAll(/[._]/g,` `)}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Details`}),(0,$.jsx)(`pre`,{children:JSON.stringify(e.payload,null,2)})]})]},e.sequence))}),c.hasNextPage?(0,$.jsx)(`button`,{className:`training-button secondary`,disabled:c.isFetchingNextPage,onClick:()=>void c.fetchNextPage(),children:`More logs`}):null]}):(0,$.jsx)(`ol`,{children:n.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`strong`,{children:e.taskId}),(0,$.jsx)(`span`,{children:e.error??e.status}),e.output?(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Output`}),(0,$.jsx)(`pre`,{children:e.output})]}):null]},e.id))})]})}var E_=z({job:Dr,events:F(zt).max(1e4),outputs:Yt,evals:Ps.nullable(),flow:$r.nullable(),flowError:U().nullable()}).strict(),D_=new Set([`completed`,`succeeded`,`failed`,`cancelled`,`budget_exhausted`]);function O_(e,t,n,r,i=!1){let a=u(),o=[`hosted-training-run`,ra(e),t,n,r??null],s=`/v1/training/hosted-jobs/${encodeURIComponent(n)}`,c=S({queryKey:[...o,`summary`],queryFn:async({signal:i})=>{let a=Dr.parse(await Y(e,`${s}/summary?teamId=${encodeURIComponent(t)}`,{signal:i}));if(a.id!==n||a.teamId!==t||r&&a.modelProjectId!==r)throw Error(`Run summary belongs to another workspace.`);return a},staleTime:3e4,gcTime:3e5,refetchInterval:e=>e.state.data&&!D_.has(e.state.data.state)?5e3:e.state.data?.usage&&!e.state.data.usage.complete?3e4:!1,refetchIntervalInBackground:!1}),l=S({queryKey:[...o,`logs`],queryFn:async({signal:n})=>$r.shape.logs.parse(await Y(e,`${s}/logs?teamId=${encodeURIComponent(t)}`,{signal:n})),enabled:i,staleTime:3e4,gcTime:3e5,refetchInterval:i&&c.data&&!D_.has(c.data.state)?5e3:!1,refetchIntervalInBackground:!1}),d=S({queryKey:[...o,`core`],queryFn:async({signal:i})=>{let a=E_.parse(await Y(e,`${s}?teamId=${encodeURIComponent(t)}&graph=false`,{signal:i}));if(a.job.id!==n||a.job.teamId!==t||r&&a.job.modelProjectId!==r)throw Error(`Run does not belong to this Model Project and workspace.`);return a},staleTime:3e4,gcTime:3e5,refetchInterval:e=>e.state.data&&(!D_.has(e.state.data.job.state)||Is(e.state.data.evals))?5e3:e.state.data?.job.usage&&!e.state.data.job.usage.complete?3e4:!1,refetchIntervalInBackground:!1}),f=S({queryKey:[...o,`flow`],queryFn:async({signal:i})=>{let a=$r.parse(await Y(e,`${s}/flow?teamId=${encodeURIComponent(t)}`,{signal:i}));if(a.jobId!==n||a.teamId!==t||r&&a.modelProjectId!==r)throw Error(`Run stages do not belong to this Model Project and workspace.`);return a},staleTime:3e4,gcTime:3e5,refetchInterval:e=>e.state.data?.live?5e3:!1,refetchIntervalInBackground:!1}),p=f.data&&(!d.data||f.data.modelProjectId===d.data.job.modelProjectId)?f.data:null,m=c.data&&(!d.data||c.data.version>=d.data.job.version)?c.data:d.data?.job??null;return{detail:d.data?{...d.data,flow:p}:null,flow:p,summary:m,logs:l.data??[],logsLoading:l.isPending,logsError:l.error?.message??null,loading:d.isPending,graphLoading:f.isPending,error:(!d.data&&!c.data?c.error?.message:null)??d.error?.message??f.error?.message??null,refresh:()=>Promise.all([c.refetch(),d.refetch(),f.refetch(),...i?[l.refetch()]:[]]),setDetail:e=>a.setQueryData([...o,`core`],e)}}function k_(e){let t=new Map;for(let n of e){let e=n.data,r=n.type===`rollout_metric`?[[`rollout.reward`,`Rollout reward`,e.reward??e.rewardMean]]:typeof e.metricId==`string`?[[e.metricId,e.metricId.replaceAll(/[._]/g,` `),e.value]]:[];for(let[i,a,o]of r){if(typeof o!=`number`||!Number.isFinite(o))continue;let r=typeof e.step==`number`?e.step:typeof e.rolloutGroupIndex==`number`?e.rolloutGroupIndex+1:n.sequence,s=t.get(i)??{id:i,label:a,xLabel:`Recorded step`,points:[]};s.points.push({step:r,value:o}),t.set(i,s)}}return[...t.values()]}function A_({evidence:e}){let t=(0,Q.useContext)(f_),[n,r]=(0,Q.useState)(null),i=t??r,a=e.groups.flatMap(e=>e.attempts.flatMap(e=>e.reward===null?[]:[e.reward])),o=Math.min(...a),s=Math.max(...a);return(0,$.jsxs)(`div`,{className:`training-rollout-groups`,"aria-label":`Attempts by rollout group`,children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`span`,{children:`Attempts by rollout group`}),(0,$.jsx)(`div`,{className:`training-rollout-legend`,children:[[`scored`,`Scored`],[`active`,`Running`],[`failed`,`Failed`],[``,`Planned`]].map(([e,t])=>(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`i`,{className:`training-rollout-cell ${e}`,"aria-hidden":!0}),t]},t))})]}),(0,$.jsx)(`ol`,{children:e.groups.map(t=>{let n=t.inherited,r=new Set(t.attempts.map(e=>e.slot)),a=Array.from({length:Math.min(1e3,t.plannedSlots)},(e,t)=>t).filter(e=>!r.has(e));return(0,$.jsxs)(`li`,{children:[(0,$.jsx)(j_,{group:t,onSelect:()=>i({title:`Rollouts`,groupIndex:t.index,status:t.state,facts:t.diagnostics})}),(0,$.jsxs)(`div`,{children:[t.replay?(0,$.jsxs)(`span`,{className:`training-muted`,children:[t.state===`consumed`?`Replayed`:`Replay pending`,` · prior output not restored`]}):null,n?(0,$.jsxs)(`span`,{className:`training-muted`,children:[`Inherited · `,n.optimizerDisposition===`applied`?`Update applied`:`Skipped · no signal`]}):t.optimizerDisposition?(0,$.jsx)(`span`,{className:`training-muted`,children:t.optimizerDisposition===`applied`?`Update applied`:`Skipped · no signal`}):null,t.attempts.map(n=>{let r=n.state.endsWith(`failed`)||[`cancelled`,`expired`,`timed_out`].includes(n.state),a=e.live&&[`running`,`leased`,`scoring`].includes(n.state),c=`Group ${t.index+1}, slot ${n.slot+1}, attempt ${n.attempt}: ${n.state}${n.reward===null?``:`, reward ${n.reward.toFixed(3)}`}`;return(0,$.jsx)(M_,{label:c,attempt:n,failed:r,active:a,opacity:n.reward===null?void 0:s>o?.35+.65*(n.reward-o)/(s-o):.8,onSelect:()=>i({title:`Rollouts`,groupIndex:t.index,status:c,facts:n.diagnostics,feedback:n.feedback})},n.id)}),a.map(e=>(0,$.jsx)(`span`,{role:`img`,"aria-label":`Group ${t.index+1}, slot ${e+1}: planned`,className:`training-rollout-cell`},`pending-${e}`))]}),(0,$.jsx)(`span`,{children:n?n.outputPolicyVersion===void 0?`v${n.inputPolicyVersion} unchanged`:`v${n.inputPolicyVersion} → v${n.outputPolicyVersion}`:t.meanReward===null?t.state:`avg ${t.meanReward.toFixed(3)}`})]},t.index)})}),n&&!t?(0,$.jsx)(p_,{...n}):null,e.groupCount>e.groups.length?(0,$.jsxs)(`p`,{children:[`Showing `,e.groups.length,` of `,e.groupCount,` rollout groups.`]}):null]})}function j_({group:e,onSelect:t}){let{triggerProps:n,tooltip:r,hideTooltip:i}=ti((0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`strong`,{children:[`Group `,e.index+1]}),(0,$.jsx)(`span`,{children:e.inherited?`Inherited source group · ${e.inherited.optimizerDisposition===`applied`?`Update applied`:`Skipped · no signal`}. No attempts were rerun here.`:`${e.state} · ${e.attempts.length} retained attempts · reward ${e.meanReward??`not scored`}`}),(0,$.jsx)(`small`,{children:`Select this group context.`})]}));return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{...n,className:`training-rollout-group-link`,type:`button`,onClick:()=>{i(),t()},children:[`Group `,e.index+1]}),r]})}function M_({label:e,attempt:t,failed:n,active:r,opacity:i,onSelect:a}){let o=t.diagnostics?.find(e=>e.severity!==`info`),{triggerProps:s,tooltip:c,hideTooltip:l}=ti((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`strong`,{children:e}),o?(0,$.jsxs)(`span`,{children:[o.label,`: `,o.value.slice(0,220)]}):null,(0,$.jsx)(`small`,{children:`Select to inspect retained attempt evidence.`})]}));return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{...s,type:`button`,onClick:()=>{l(),a()},"aria-label":e,className:`training-rollout-cell ${n?`failed`:r?`active`:t.reward===null?``:`scored`}`,style:{opacity:i}}),c]})}function N_({groups:e}){let[t,n]=(0,Q.useState)(!1),[r,i]=(0,Q.useState)(0),a=e.reduce((e,t)=>e+t.attempts.length,0);if(!a)return null;let o=Math.ceil(a/100)-1,s=Math.min(r,o),c=t?e.flatMap(e=>e.attempts.map(t=>({group:e.index,...t}))).slice(s*100,(s+1)*100):[];return(0,$.jsxs)(`details`,{className:`training-rollout-attempts`,onToggle:e=>n(e.currentTarget.open),children:[(0,$.jsxs)(`summary`,{children:[`Recorded attempts · `,a]}),t?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`training-table-wrap`,children:(0,$.jsxs)(`table`,{className:`training-data-table evaluation-workspace-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Group / slot`}),(0,$.jsx)(`th`,{children:`Attempt`}),(0,$.jsx)(`th`,{children:`State`}),(0,$.jsx)(`th`,{children:`Reward`}),(0,$.jsx)(`th`,{children:`Retained feedback`})]})}),(0,$.jsx)(`tbody`,{children:c.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsxs)(`td`,{children:[e.group+1,` / `,e.slot+1]}),(0,$.jsx)(`td`,{children:e.attempt}),(0,$.jsx)(`td`,{children:e.state.replaceAll(`_`,` `)}),(0,$.jsx)(`td`,{children:e.reward===null?`—`:e.reward.toFixed(3)}),(0,$.jsx)(`td`,{children:(0,$.jsx)(P_,{attempt:e})})]},e.id))})]})}),o>0?(0,$.jsxs)(`div`,{className:`training-rollout-pagination`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:!s,onClick:()=>i(s-1),children:`Previous`}),(0,$.jsxs)(`span`,{"aria-live":`polite`,children:[s*100+1,`–`,Math.min(a,(s+1)*100),` of `,a]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:s===o,onClick:()=>i(s+1),children:`Next`})]}):null]}):null]})}function P_({attempt:e}){let[t,n]=(0,Q.useState)(!1);return!e.diagnostics?.length&&!e.feedback?.length?(0,$.jsx)($.Fragment,{children:`No grading receipt retained`}):(0,$.jsxs)(`details`,{onToggle:e=>n(e.currentTarget.open),children:[(0,$.jsx)(`summary`,{children:`Inspect`}),t?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dl`,{children:e.diagnostics?.map((e,t)=>(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:e.label}),(0,$.jsx)(`dd`,{children:(0,$.jsx)(`pre`,{children:e.value})})]},t))}),(0,$.jsx)(s_,{targets:e.feedback})]}):null]})}function F_({evidence:e,stage:t,onStage:n,inspection:r,groupIndex:i,logs:a=[],logsLoading:o,logsError:s}){let c=[`Logs`,...e.nodes.map(e=>e.label)];c.includes(t)||c.push(t);let l=e.nodes.find(e=>e.label===t)??(e.inference?.label===t?e.inference:void 0),u=i!==void 0&&!l?.inLoop,d=e.groups.find(e=>e.index===i),f=d?.inherited,p=d?.replay;return(0,$.jsxs)(`section`,{className:`training-evidence-workspace`,children:[(0,$.jsx)(`nav`,{className:`evaluation-workspace-tabs`,"aria-label":`Run evidence tabs`,children:c.map(e=>(0,$.jsx)(`button`,{type:`button`,"aria-pressed":t===e,onClick:()=>n(e),children:e},e))}),t===`Logs`?(0,$.jsxs)(`section`,{"aria-label":`Run-wide logs`,children:[(0,$.jsx)(`p`,{className:`training-muted`,children:`Run-wide logs · entries retain their recorded context.`}),(0,$.jsx)(X,{error:s}),o?(0,$.jsx)(`p`,{role:`status`,children:`Loading retained logs…`}):null,!a.length&&!o?(0,$.jsx)(`p`,{className:`training-muted`,children:`No retained log entries loaded.`}):null,(0,$.jsx)(`ol`,{className:`training-evidence-logs`,children:a.map((e,t)=>(0,$.jsxs)(`li`,{"data-level":e.level,children:[(0,$.jsx)(`time`,{children:Sa(e.at)}),(0,$.jsx)(`strong`,{children:e.source}),(0,$.jsx)(`span`,{children:e.message})]},`${e.id}:${t}`))})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{className:`training-muted`,children:u?`Run-wide evidence. Baseline and final evaluations assess the run; they are not attributed to an individual group.`:i===void 0?`All retained groups`:`Group ${i+1} retained evidence`}),p&&e.recovery&&l?.inLoop?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{className:`training-muted`,children:`Replaying after checkpoint restore. Prior undurable output was not restored; current records belong to this attempt.`}),(0,$.jsx)(li,{recovery:e.recovery,sourceJobId:p.sourceJobId,compact:!0})]}):null,f&&e.recovery&&l?.inLoop?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{className:`training-muted`,children:`Inherited source evidence. Attempts and optimizer records were not re-executed in this recovery run.`}),(0,$.jsx)(li,{recovery:e.recovery,sourceJobId:f.sourceJobId,compact:!0})]}):null,r?(0,$.jsx)(p_,{...r}):l?(0,$.jsx)(p_,{title:l.label,status:l.status,facts:[...l.diagnostics??[],...l.error?[{label:`Recorded stage failure`,value:l.error,severity:`error`}]:[]],feedback:l.feedback}):(0,$.jsx)(`p`,{className:`training-muted`,children:`No retained evidence for this selection.`}),t===`Rollouts`?(0,$.jsx)(N_,{groups:e.groups}):null]})]})}function I_(e){return(0,$.jsx)(L_,{...e},`${e.teamId}:${e.jobId}`)}function L_({connection:e,teamId:t,projectId:n,jobId:r,onOpenRun:i,compact:a=!1,initialStatus:o}){let[s,c]=(0,Q.useState)(`Logs`),[l,u]=(0,Q.useState)(),[d,f]=(0,Q.useState)(null),{detail:p,flow:m,summary:h,logs:g,logsLoading:_,logsError:v,error:y}=O_(e,t,r,n,s===`Logs`),b=m?.groups.find(e=>e.index===l),x=m&&l!==void 0?{...m,groups:b?[b]:[],groupCount:+!!b,nodes:m.nodes.map(e=>e.inLoop?b?.nodes?.find(t=>t.label===e.label)??{label:e.label,inLoop:!0,state:`missing`,status:`Not recorded`,detail:`No linked group evidence`,diagnostics:[]}:{...e,detail:`Run-wide${e.detail?` · ${e.detail}`:``}`})}:m,S=e=>{e.groupIndex!==void 0&&u(e.groupIndex),c(e.title),f(e.groupIndex===void 0?null:e)},C=h??p?.job,w=C?.executionMode===`qualification`,T=C?.rolloutProgress,E=[...p?.events??[]].reverse().find(e=>e.type===`rollout_metric`&&typeof e.data.rolloutGroupIndex==`number`)?.data.rolloutGroupIndex,D=p?.events.at(-1),O=a?__:S_,k=m?.nodes.find(e=>e.state===`active`)?.label??(m&&!m.live?Ca(m.state):C?Ca(C.phase):o?Ca(o):`Training journey`);return(0,$.jsx)(o_.Provider,{value:{connection:e,teamId:t,jobId:r},children:(0,$.jsx)(f_.Provider,{value:S,children:(0,$.jsxs)(`section`,{className:`model-journey ${a?`compact`:``}`,"aria-label":`Training run stages`,children:[(0,$.jsxs)(`div`,{className:`model-journey-heading`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`span`,{className:`model-journey-eyebrow`,children:w?`Qualification run`:`Training journey`}),(0,$.jsxs)(`div`,{className:`model-journey-title-row`,children:[(0,$.jsx)(`h3`,{children:k}),(0,$.jsx)(Xr,{continuation:m?.continuation,recovery:m?.recovery,compact:!0})]})]}),(0,$.jsx)(`button`,{className:`training-button secondary`,onClick:i,type:`button`,children:`View run`})]}),m&&x?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{label:`Training group context`,value:l===void 0?`all`:String(l),options:[{value:`all`,label:`All groups · run overview`},...m.groups.map(e=>({value:String(e.index),label:`Group ${e.index+1} · ${e.replay?`Replay · ${e.state}`:e.inherited?`Inherited · ${e.inherited.optimizerDisposition===`applied`?`Update applied`:`Skipped · no signal`}`:e.optimizerDisposition===`skipped_no_signal`?`Skipped · no signal`:e.state}`}))],onChange:e=>{u(e===`all`?void 0:Number(e)),f(null)}}),(0,$.jsx)(`p`,{className:`training-muted`,children:l===void 0?`Run overview · all retained groups`:`Group scope · preparation and evaluations remain run-wide`}),(0,$.jsx)(li,{recovery:m.recovery}),(0,$.jsx)(O,{nodes:x.nodes,continuation:m.continuation,inference:m.inference,live:m.live&&!y,loopLabel:w?`Rollout + grading`:`Training loop`,groupLabel:l===void 0?`group ${m.groupsCompleted} of ${m.groupsTarget}`:`Group ${l+1} snapshot`,policyLabel:l===void 0?`policy v${m.policyVersion}`:`group ${l+1}`}),(0,$.jsx)(A_,{evidence:{...x,live:m.live&&!y}})]}):p?.flowError?(0,$.jsx)(X,{error:p.flowError}):null,(0,$.jsxs)(`div`,{className:`model-journey-facts`,"aria-live":`polite`,children:[(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`b`,{children:b?`Group ${b.index+1}`:T?`${T.groupsCompleted} / ${T.groupsTarget}`:`—`}),` `,b?b.state:`groups complete`,l===void 0&&typeof E==`number`?` · latest recorded group ${E+1}`:``]}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`b`,{children:b?b.nodes?.find(e=>e.label===`Update adapter`)?.detail??`No linked optimizer evidence`:T?Math.max(0,T.optimizerUpdatesApplied-(m?.recovery?.optimizerUpdatesApplied??0)):`—`}),` `,b?`optimizer outcome`:m?.recovery?`new weight updates`:`weight updates`]}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`b`,{children:T?.optimizerUpdatesSkipped??`—`}),` run-wide updates skipped`]}),(0,$.jsxs)(`span`,{children:[C?Ca(C.state):`Connecting`,(0,$.jsxs)(`small`,{className:`training-continual-status`,children:[(0,$.jsx)(ri,{enabled:m?!!m.continuation:void 0}),m?.recovery?(0,$.jsx)(`span`,{children:` · Checkpoint recovery`}):null]})]})]}),(0,$.jsx)(X,{error:y}),(0,$.jsx)(`p`,{className:`model-journey-note`,children:y?p||h||m?`Showing last received evidence.`:`No run evidence received yet.`:C?.terminalReason??D?.message??`Stages update from recorded run events and artifacts.`}),C?(0,$.jsxs)(`p`,{className:`model-journey-time`,children:[`Updated `,Sa(C.updatedAt),` · Stages reflect recorded evidence, not estimated progress.`]}):null,a&&p?(0,$.jsx)(Qr,{series:k_(l===void 0?p.events:p.events.filter(e=>e.data.rolloutGroupIndex===l))}):null,x?(0,$.jsx)(F_,{evidence:x,stage:s,groupIndex:l,inspection:d,onStage:e=>{c(e),f(null)},logs:g,logsLoading:_,logsError:v}):null]})})})}function R_(e,t=[]){let n=t.filter(e=>e.split===`train`),r=new Map(n.map(e=>[e.id,e])),i=new Map,a=new Set,o=new Map,s=new Set;for(let t of e){if(t.type!==`metric`)continue;let e=t.payload;if(e.metricKind===`rollout_trajectory`){let a=U_(e.rolloutGroupId)??`group-0`,o=i.get(a),s=H_(e.rolloutGroupIndex)??o?.groupIndex??i.size,c=U_(e.taskId),l=(c?r.get(c):null)??(n.length?n[s%n.length]??null:null),u=G_(l?.metadata),d={id:t.id,rolloutIndex:H_(e.rolloutIndex),workerSlot:H_(e.workerSlot),attempt:H_(e.attempt)??1,policyVersion:H_(e.policyVersion),reward:V_(e.reward),rewardEligible:e.rewardEligible===!0,terminalClass:U_(e.terminalClass),failure:U_(e.failureCode)??U_(e.failureClass),inputTokens:H_(e.inputTokens)??0,outputTokens:H_(e.outputTokens)??0,components:z_(e)};i.set(a,{id:a,groupIndex:s,taskId:c??l?.id??o?.taskId??null,taskLabel:q_(l)??o?.taskLabel??null,taskFamily:U_(e.taskFamily)??U_(e.scenarioFamily)??l?.clusterKey??U_(u.scenarioFamily)??o?.taskFamily??null,policyVersion:H_(e.policyVersion)??o?.policyVersion??null,trajectories:[...o?.trajectories??[],d]})}else if(e.metricKind===`optimizer_disposition`){let t=U_(e.rolloutGroupId);if(!t)continue;let n=U_(e.optimizerDisposition)??U_(e.disposition)??U_(e.remotePhase);n?.includes(`skipped`)&&a.add(t),n===`applied`&&o.set(t,H_(e.step))}else if(e.metricKind===`policy_optimization`){let t=H_(e.step),n=U_(e.rolloutGroupId);t!==null&&s.add(t),n&&o.set(n,t)}}return[...i.values()].sort((e,t)=>e.groupIndex-t.groupIndex).map(e=>{let t=e.trajectories.flatMap(e=>e.rewardEligible&&e.reward!==null?[e.reward]:[]),n=o.get(e.id),r=n===void 0?null:n;if(r===null&&!a.has(e.id)){let t=e.groupIndex+1;s.has(t)&&(r=t)}return{...e,optimizerDisposition:a.has(e.id)?`skipped`:r===null?`pending`:`applied`,optimizerStep:r,mean:B_(t),minimum:t.length?Math.min(...t):null,maximum:t.length?Math.max(...t):null}})}function z_(e){let t=[e.rewardComponents,e.rubricComponents,e.components].find(W_);return t?Object.entries(t).flatMap(([e,t])=>{if(typeof t==`number`&&Number.isFinite(t))return[{id:e,label:K_(e),score:t,passed:null,feedback:null}];if(!W_(t))return[];let n=[t.score,t.reward,t.value,t.rewardContribution].map(V_).find(e=>e!==null);return n===void 0?[]:[{id:e,label:U_(t.label)??U_(t.name)??K_(e),score:n,passed:typeof t.passed==`boolean`?t.passed:null,feedback:U_(t.feedback)}]}):[]}function B_(e){return e.length?e.reduce((e,t)=>e+t,0)/e.length:null}function V_(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function H_(e){let t=V_(e);return t!==null&&Number.isInteger(t)?t:null}function U_(e){return typeof e==`string`&&e.trim()?e.trim():null}function W_(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function G_(e){return W_(e)?e:{}}function K_(e){return e.replaceAll(/[._-]+/g,` `).replace(/^./,e=>e.toUpperCase())}function q_(e){if(!e)return null;let t=G_(e.input),n=[t.title,t.name,t.prompt,t.instruction,t.question,t.query].find(e=>typeof e==`string`&&!!e.trim());if(!n)return null;let r=n.trim().split(/\n\s*\n/,1)[0].replaceAll(/\s+/g,` `);return r.length>110?`${r.slice(0,107).trimEnd()}…`:r}var J_=new Set([`optimizer.reward`,`rollout.reward`]),Y_=[{key:`meanReward`,id:`optimizer.reward`,label:`Mean reward`},{key:`meanReturn`,id:`optimizer.return`,label:`Mean return`},{key:`learningRate`,id:`optimizer.learning_rate`,label:`Learning rate`,format:`scientific`},{key:`policyLoss`,id:`optimizer.policy_loss`,label:`Policy loss`},{key:`valueLoss`,id:`optimizer.value_loss`,label:`Value loss`},{key:`gradientNorm`,id:`optimizer.gradient_norm`,label:`Gradient norm`},{key:`kl`,id:`optimizer.kl`,label:`Policy update KL`},{key:`behaviorPolicyKlPreUpdate`,id:`optimizer.behavior_policy_kl`,label:`Behavior-policy KL (pre-update)`},{key:`entropy`,id:`optimizer.entropy`,label:`Entropy`},{key:`policyClipFraction`,id:`optimizer.policy_clip_fraction`,label:`Post-update clip fraction`,format:`percent`},{key:`behaviorPolicyClipFractionPreUpdate`,id:`optimizer.behavior_policy_clip_fraction`,label:`Behavior-policy clip fraction (pre-update)`,format:`percent`},{key:`valueClipFraction`,id:`optimizer.value_clip_fraction`,label:`Value clip fraction`,format:`percent`},{key:`explainedVariance`,id:`optimizer.explained_variance`,label:`Explained variance`}],X_=[{key:`loss`,id:`optimizer.loss`,label:`Loss`},{key:`reward`,id:`optimizer.reward`,label:`Reward`},{key:`policyLoss`,id:`optimizer.policy_loss`,label:`Policy loss`},{key:`advantageLoss`,id:`optimizer.advantage_loss`,label:`Advantage loss`},{key:`learningRate`,id:`optimizer.learning_rate`,label:`Learning rate`,format:`scientific`},{key:`gradientNorm`,id:`optimizer.gradient_norm`,label:`Gradient norm`},{key:`meanTokenAccuracy`,id:`train.token_accuracy`,label:`Token accuracy`,format:`percent`},{key:`preferenceAccuracy`,id:`train.preference_accuracy`,label:`Preference accuracy`,format:`percent`},{key:`preferenceMargin`,id:`train.preference_margin`,label:`Preference margin`},{key:`chosenReward`,id:`train.chosen_reward`,label:`Chosen reward`},{key:`rejectedReward`,id:`train.rejected_reward`,label:`Rejected reward`},{key:`entropy`,id:`optimizer.entropy`,label:`Entropy`}];function Z_({detail:e,loading:t,error:n,taskset:r=null}){Ka(n,{prefix:`Training metrics`});let i=(0,Q.useMemo)(()=>e?R_(e.events,r?.tasks):[],[e,r]),a=(0,Q.useMemo)(()=>e?$_(ev(e),i):[],[e,i]);if(n&&!e)return(0,$.jsx)(`div`,{className:`training-run-placeholder`,children:`Training metrics are unavailable.`});if(!e&&!t)return(0,$.jsx)(`div`,{className:`training-run-placeholder`,children:`Select a training run to inspect its metrics.`});let o=e?[`queued`,`starting`,`running`,`reconciling`].includes(e.job.status):!1;return(0,$.jsx)(Qr,{live:o,loading:t&&!e,series:a})}function Q_(e){let t=e.flatMap((e,t)=>e.mean===null?[]:[{step:t+1,value:e.mean}]);return t.length?{id:`optimizer.reward`,label:`Mean reward`,points:t,xLabel:`rollout group`}:null}function $_(e,t){let n=Q_(t);return n?[n,...e.filter(e=>!J_.has(e.id))]:e}function ev(e){let t=cv(e.job.metadata.rolloutProgress),n=av(e.job.metadata.optimizerUpdatesObserved)??av(t.optimizerUpdatesApplied),r=sv(e)===`grpo`&&n!==null?Math.max(0,n):null,i=rv(e.stepMetrics).filter(e=>r===null||e.step<=r),a=[...nv(rv(e.policyMetrics),Y_),...nv(i,X_),...iv(e.events)],o=new Map;for(let e of a){let t=o.get(e.id);(!t||e.points.length>t.points.length)&&o.set(e.id,e)}let s=[`optimizer.reward`,`rollout.reward`,`optimizer.kl`,`optimizer.loss`,`optimizer.learning_rate`];return[...o.values()].sort((e,t)=>tv(e.id,s)-tv(t.id,s)||e.label.localeCompare(t.label))}function tv(e,t){let n=t.indexOf(e);return n<0?999:n}function nv(e,t){return t.flatMap(t=>{let n=e.flatMap(e=>{let n=e[t.key];return typeof n==`number`&&Number.isFinite(n)?[{step:e.step,value:n}]:[]});return n.length?[{id:t.id,label:t.label,points:n,format:t.format}]:[]})}function rv(e){let t=new Map;for(let n of e)t.set(n.step,n);return[...t.values()].sort((e,t)=>e.step-t.step)}function iv(e){let t=new Map,n=new Map,r=(e,r,i,a)=>{t.set(e,[...t.get(e)??[],{step:i,value:a}]),n.set(e,r)},i=new Map;for(let t of e)if(t.type===`metric`){if(t.payload.metricKind===`managed_telemetry`){let e=typeof t.payload.metricId==`string`?t.payload.metricId:null,n=av(t.payload.value),i=av(t.payload.step)??t.sequence;e&&n!==null&&r(e,ov(e),i,n)}if(t.payload.metricKind===`rollout_trajectory`){let e=av(t.payload.rolloutIndex)??t.sequence,n=av(t.payload.reward);n!==null&&r(`rollout.reward`,`Rollout reward`,e,n);let a=typeof t.payload.rolloutGroupId==`string`?t.payload.rolloutGroupId:`group-0`,o=t.payload.rewardEligible===!1||typeof t.payload.failureClass==`string`||typeof t.payload.failureCode==`string`;i.set(a,[...i.get(a)??[],{reward:n,eligible:t.payload.rewardEligible===!0,resolved:n!==null||o,attempt:av(t.payload.attempt)??1,input:av(t.payload.inputTokens)??0,output:av(t.payload.outputTokens)??0}])}}return[...i.values()].forEach((e,t)=>{let n=e.filter(e=>e.resolved);if(!n.length)return;let i=n.flatMap(e=>e.eligible&&e.reward!==null?[e.reward]:[]),a=i.length?i.reduce((e,t)=>e+t,0)/i.length:0,o=i.length?i.reduce((e,t)=>e+(t-a)**2,0)/i.length:0,s=i.length?Math.max(...i):0;r(`attempt.valid_rate`,`Valid attempt rate`,t,i.length/n.length),r(`attempt.failure_count`,`Attempt failures`,t,n.length-i.length),r(`attempt.retry_count`,`Attempt retries`,t,n.reduce((e,t)=>e+Math.max(0,t.attempt-1),0)),r(`reward.variance`,`Reward variance`,t,o),r(`reward.best`,`Best reward`,t,s),r(`tokens.input`,`Input tokens`,t,e.reduce((e,t)=>e+t.input,0)),r(`tokens.output`,`Output tokens`,t,e.reduce((e,t)=>e+t.output,0))}),[...t].map(([e,t])=>({id:e,label:n.get(e)??ov(e),points:t,format:e.endsWith(`rate`)||e.includes(`fraction`)?`percent`:`number`}))}function av(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function ov(e){return e.replaceAll(/[._]/g,` `).replace(/^./,e=>e.toUpperCase())}function sv(e){let t=e.job.metadata.trainingMethod;if(typeof t==`string`)return t;let n=cv(e.job.metadata.sourceSnapshot);return typeof n.method==`string`?n.method:null}function cv(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function lv({connection:e,sessionId:t,resources:n,onRequest:r}){let i=n.focus.dataset,a=n.focus.scopeContext&&i?[...new Map(Gr(n.focus.scopeContext).filter(e=>e.id===n.scope?.id&&e.dataset&&cf(e.dataset)===cf(i)).flatMap(e=>e.training??[]).map(e=>[qr(e),e])).values()]:[],o=k(e,t),[s,c]=(0,Q.useState)(null),l=a.find(e=>qr(e)===n.scope?.selectedTrainingKey)??a.find(e=>e.location===`cloud`?![`completed`,`failed`,`cancelled`,`budget_exhausted`].includes(e.job.state):e.executionState===`running`)??a.at(-1);async function u(e){let t=a.find(t=>qr(t)===e);if(t){c(null);try{await o.select({kind:`training`,id:t.jobId,location:t.location,...t.location===`cloud`?{teamId:t.owner.teamId,apiOrigin:t.apiOrigin}:{}})}catch(e){c(e instanceof Error?e.message:`Run selection failed.`)}}}return(0,$.jsxs)(`section`,{className:`dataset-workspace-section`,"aria-label":`Dataset training`,children:[(0,$.jsxs)(`header`,{className:`dataset-workspace-section-heading`,children:[(0,$.jsxs)(`div`,{className:`dataset-workspace-title`,children:[(0,$.jsx)(`h2`,{children:a.length?`Training runs`:`Planned stages`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary icon-only`,"aria-label":`New training`,title:`New training`,onClick:()=>r(`New training`),children:(0,$.jsx)(za,{size:15})})]}),l?(0,$.jsx)(lt,{status:l.location===`cloud`?l.job.state:l.executionState}):null]}),(0,$.jsx)(X,{error:s}),a.length?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{compact:!0,floating:!0,label:`Training run`,value:l?qr(l):``,disabled:o.selecting,options:a.map(e=>({value:qr(e),label:e.location===`cloud`?`Hosted run ${e.jobId.slice(-8)}`:e.modelId,description:e.location===`cloud`?e.job.state:e.executionState})),onChange:e=>void u(e)}),l?.location===`cloud`?(0,$.jsx)(I_,{compact:!0,connection:e,teamId:l.owner.teamId,projectId:l.job.modelProjectId,jobId:l.jobId,onOpenRun:()=>r(`Check training`,void 0,l)},qr(l)):l?(0,$.jsx)(uv,{connection:e,training:l},qr(l)):null]}):(0,$.jsx)(`div`,{"aria-label":`Planned training stages`,children:(0,$.jsx)(y_,{})})]})}function uv({connection:e,training:t}){let n=S({queryKey:[`dataset-workspace-training`,ra(e),qr(t)],queryFn:async()=>{let n=vo.parse(await Eo.trainingRunDetail(e,t.jobId));if(n.job.id!==t.jobId)throw Error(`Training evidence does not match the attached job.`);return n},refetchInterval:e=>[`queued`,`starting`,`running`,`reconciling`,`cancelling`].includes(e.state.data?.job.status??t.executionState)?3e3:!1}),r=n.data,i=!!(r&&[`queued`,`starting`,`running`,`reconciling`].includes(r.job.status)&&!n.error);if(!r)return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{error:n.error?.message}),(0,$.jsx)(`p`,{role:`status`,children:`Loading training evidence…`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void n.refetch(),children:`Refresh`})]});let a=r.managedEvidence?.progress.committedOptimizerSteps??r.job.metadata.optimizerUpdatesObserved,o=typeof a==`number`&&a>0,s=r.events.some(e=>e.type===`metric`&&e.payload.metricKind===`rollout_trajectory`),c=r.job.status===`succeeded`,l=r.events.filter(e=>e.type===`metric`&&e.payload.metricKind===`rollout_trajectory`&&typeof e.payload.reward==`number`&&Number.isFinite(e.payload.reward)).length,u=r.events.some(e=>e.type===`checkpoint`)||!!r.managedEvidence?.checkpoint?.sha256,d=!!r.evaluation||!!r.managedEvidence?.evaluations.some(e=>e.kind===`candidate`),f=i?`pending`:`missing`,p=s||o||u||d;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ut,{name:t.modelId}),(0,$.jsx)(X,{error:n.error?.message}),(0,$.jsx)(__,{live:i,loopLabel:`Training loop`,nodes:[{label:`Prepare`,state:p?`done`:i?`active`:f,status:p?`Recorded`:r.job.startedAt?`Worker started`:`Waiting`},{label:`Rollouts`,state:s?`done`:f,status:s?`Recorded`:`Waiting for attempts`,inLoop:!0},{label:`Grade`,compute:`cpu`,state:l?`done`:f,status:l?`Recorded`:`No recorded grades`,detail:l?`${l} graded attempts`:void 0,inLoop:!0},{label:`Update adapter`,state:o?`done`:f,status:o?`Recorded`:`No recorded updates`,detail:o?`${a} updates`:void 0,inLoop:!0},{label:`Save checkpoint`,compute:`cpu`,state:u?`done`:f,status:u?`Recorded`:`No saved checkpoint recorded`,inLoop:!0},{label:`Evaluate`,state:d?`done`:f,status:d?`Recorded`:`No candidate evaluation recorded`},{label:`Finish`,state:c?`done`:r.job.status===`failed`?`failed`:f,status:r.job.status,error:r.job.error??void 0}]}),(0,$.jsx)(Qr,{series:ev(r)}),(0,$.jsxs)(`details`,{className:`dataset-workspace-logs`,children:[(0,$.jsx)(`summary`,{children:`Training events`}),(0,$.jsx)(`ol`,{children:r.events.slice(-100).map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`time`,{children:new Date(e.timestamp).toLocaleTimeString()}),(0,$.jsx)(`span`,{children:typeof e.payload.message==`string`?e.payload.message:e.type})]},e.id))})]})]})}function dv(e){return e===`small`||e===`small_experiment`}function fv(e){return{maxSteps:1,trainingExamples:e===`grpo`?1:e===`sft`?4:2,rolloutGroupSize:4,rolloutConcurrency:1}}function pv(e,t,n){if(!dv(e))return n;let r=fv(t);return{maxSteps:r.maxSteps,rolloutGroupSize:r.rolloutGroupSize,rolloutConcurrency:r.rolloutConcurrency}}function mv(e){let t=fv(`grpo`);return{...e,dataset:{...e.dataset,maxExamples:t.trainingExamples},rollout:{...e.rollout,groupSize:t.rolloutGroupSize,concurrency:t.rolloutConcurrency},optimizer:{...e.optimizer,maxSteps:t.maxSteps,iterations:2,gradientAccumulationSteps:t.rolloutGroupSize},resourceLimits:{...e.resourceLimits,maxRollouts:t.rolloutGroupSize},policyOptimization:null}}function hv(e){return[{id:`standard`,label:`Full run`,description:`Pre-fill the full training configuration, then adjust its limits.`},{id:e===`grpo`||e===`ppo`?`small_experiment`:`small`,label:`Smoke`,description:e===`grpo`?`Start with 1 prompt, 4 rollouts, 1 group, and 2 optimizer iterations.`:`Start with a small training batch and 1 optimizer step.`},{id:`custom`,label:`Custom`,description:`Choose prompts, rollouts, groups, and optimizer iterations.`}]}function gv(e,t,n){if(!dv(e))return null;let r=fv(t);return n.maxSteps>r.maxSteps||n.trainingExamples>r.trainingExamples||(t===`grpo`||t===`ppo`)&&(n.rolloutGroupSize>r.rolloutGroupSize||n.rolloutConcurrency>r.rolloutConcurrency||(n.optimizerIterations??2)>2||(n.maximumRollouts??4)>4)?`These settings exceed the training smoke test limits. Reduce them or select Custom.`:null}function _v({method:e,methods:t,onMethodChange:n,value:r,onChange:i,disabled:a,recommendedAvailable:o=!0,sizing:s,onSizingChange:c}){let l=hv(e).filter(e=>o||e.id!==`standard`),u=dv(r)?l.find(e=>dv(e.id)).id:r;return(0,$.jsxs)(`div`,{className:`model-build-field training-run-configuration`,children:[(0,$.jsx)(`span`,{children:`Run configuration`}),(0,$.jsx)(Z,{floating:!0,label:`Run configuration`,value:u,options:l.map(e=>({value:e.id,label:e.label})),onChange:e=>i(e),disabled:a}),s&&c?(0,$.jsxs)(`div`,{className:`training-run-quantities`,children:[[[`prompts`,`Prompts`,`Training prompts`,1,1e5],[`rollouts`,`Rollouts`,`Rollouts per prompt`,2,16],[`groups`,`Groups`,`Rollout groups`,1,1e5],[`iterations`,`Iterations`,`Optimizer iterations`,e===`grpo`?2:1,e===`grpo`?16:100],[`concurrency`,`Concurrent`,`Concurrent rollouts`,1,s.rollouts]].map(([e,t,n,r,i])=>(0,$.jsxs)(`label`,{title:n,children:[(0,$.jsx)(`span`,{children:t}),(0,$.jsx)(`input`,{"aria-label":n,type:`number`,min:r,max:i,step:1,value:Number.isFinite(s[e])?s[e]:``,disabled:a,onChange:t=>c({...s,[e]:t.target.valueAsNumber||r})})]},e)),(0,$.jsxs)(`div`,{className:`training-run-method`,children:[(0,$.jsx)(`span`,{children:`Method`}),(0,$.jsx)(Z,{compact:!0,floating:!0,floatingMenuWidth:140,label:`Training method`,value:e??``,options:(t??(e?[e]:[])).map(e=>({value:e,label:e.toUpperCase()})),disabled:a||!n||!t?.length,onChange:e=>n?.(e)})]})]}):null]})}function vv({connection:e,resources:t,onAddToChat:n,initialPreset:r}){let[i,a]=(0,Q.useState)({prompts:dv(r)?1:Math.max(1,t.focus.dataset?.taskCount??1),rollouts:4,groups:dv(r)?1:Math.max(1,t.focus.dataset?.taskCount??1),iterations:2,concurrency:1}),[o,s]=(0,Q.useState)(r),[c,l]=(0,Q.useState)(`grpo`),[u,d]=(0,Q.useState)(``),[f,p]=(0,Q.useState)(``),m=S({queryKey:[`dataset-training-catalog`,ra(e)],queryFn:async()=>ac.parse(await Eo.portableTrainingCatalog(e))}),h=(m.data?.targets??[]).find(e=>e.destinationId===`openpond_managed`),g=(m.data?.models??[]).filter(e=>e.compatibilities.some(e=>e.targetId===h?.id&&e.methods.includes(c)&&e.state!==`unsupported`)),_=g.find(e=>e.selectionKey===u),v=(h?.methods??[]).filter(e=>[`sft`,`dpo`,`grpo`,`ppo`].includes(e));(0,Q.useEffect)(()=>{if(m.data&&v.length&&!v.includes(c)){let e=v[0];l(e),s(t=>dv(t)?e===`grpo`||e===`ppo`?`small_experiment`:`small`:t),d(``)}},[m.data,c]);let y=h?.approvalPolicy?.minimumSpendUsd??.01,b=h?.approvalPolicy?.maximumSpendUsd,x=Number(f),C=!!(h?.available&&h.methods.includes(c)&&_&&f.trim()&&Number.isFinite(x)&&x>=y&&(b===void 0||x<=b)),w=t.focus.dataset,T=`Use ${i.prompts} training prompts, ${i.rollouts} rollouts per prompt, ${i.groups} rollout groups, ${i.iterations} optimizer iterations per group, and concurrency ${i.concurrency}. Retain held-out evaluation, tools, grading, checkpoint export, and the existing token/context limits.`,E=Object.values(i).every(e=>Number.isInteger(e)&&e>0)&&i.prompts<=1e5&&i.groups<=1e5&&i.iterations>=(c===`grpo`?2:1)&&i.iterations<=(c===`grpo`?16:100)&&i.rollouts>=2&&i.rollouts<=16&&Number.isInteger(i.concurrency)&&i.concurrency>=1&&i.concurrency<=16&&i.rollouts%i.concurrency===0,D=!!(w&&h?.available&&_&&E),O=`using ${c.toUpperCase()} for ${w?.name}, revision ${w?.revision}, using ${_?.modelId} on OpenPond Managed`;return(0,$.jsxs)(`div`,{className:`dataset-training-plan`,children:[m.error?(0,$.jsx)(X,{error:m.error.message,children:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void m.refetch(),children:`Retry`})}):null,(0,$.jsx)(_v,{method:c,methods:v.length?v:[`grpo`],onMethodChange:e=>{l(e),s(dv(o)?e===`grpo`||e===`ppo`?`small_experiment`:`small`:o),d(``)},value:o,sizing:i,onSizingChange:a,onChange:e=>{s(e),e!==`custom`&&a({prompts:dv(e)?1:Math.max(1,w?.taskCount??1),rollouts:4,groups:dv(e)?1:Math.max(1,w?.taskCount??1),iterations:2,concurrency:1})}}),(0,$.jsx)(`span`,{className:`dataset-training-field-label`,children:`Starting model`}),(0,$.jsx)(Z,{floating:!0,searchable:!0,label:`Training model`,value:_?.selectionKey??``,options:[{value:``,label:m.isPending?`Loading models…`:`Choose training model`,disabled:!0},...g.map(e=>({value:e.selectionKey,label:e.label,description:e.reason??e.modelId}))],onChange:d,disabled:m.isPending}),(0,$.jsxs)(`label`,{children:[`Maximum spend (USD)`,(0,$.jsxs)(`div`,{className:`training-spend-estimate`,children:[(0,$.jsx)(`input`,{"data-autofocus":!0,type:`number`,min:y,max:b,step:`0.01`,"aria-label":`Maximum training spend`,value:f,onChange:e=>p(e.target.value)}),(0,$.jsx)(`button`,{type:`button`,disabled:!D,onClick:()=>n(`Review the training cost ${O}. ${T} Keep this review attached to the selected experiment and inspect the pinned examples, splits, graders, and recipe before estimating. ${C?`Use $${x.toFixed(2)} as the maximum spend.`:`Ask me to choose a hard spend cap before any submission.`} Show the current provider estimate or exact quote when supported, its assumptions, what is included, and any separately billed preparation, evaluation, idle, or serving costs. If an estimate is unavailable, explain why and the next step. Do not upload data, start training, or allocate serving capacity.`),children:`Review cost in chat`})]})]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:!D||!C,onClick:()=>n(`Prepare a training plan ${O}, with a maximum spend of $${x.toFixed(2)}. ${T} Keep it attached to the selected experiment. Inspect its examples, splits, graders, and data permissions; show the recipe, required changes, and cost for review. Do not upload data or start training.`),children:`Prepare in chat`})]})}function yv({dialog:e,connection:t,resources:n,onClose:r,onAddToChat:i}){let[a,o]=(0,Q.useState)(e.text??``);return(0,$.jsxs)(qa,{ariaLabel:e.title,className:`training-dialog dataset-workspace-dialog`,onClose:r,children:[(0,$.jsxs)(`header`,{className:`training-dialog-header`,children:[(0,$.jsx)(`h2`,{children:e.title}),(0,$.jsx)(`button`,{className:`training-icon-button`,type:`button`,"aria-label":`Close dialog`,onClick:r,children:(0,$.jsx)(Ua,{size:18})})]}),e.title===`Add grader`?(0,$.jsx)(tf,{kind:`grader`,resources:n,busy:!1,onDraft:i}):e.title===`New training`?(0,$.jsx)(vv,{connection:t,resources:n,onAddToChat:i,initialPreset:`standard`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:`Review the request, then add it to chat.`}),(0,$.jsx)(`textarea`,{"data-autofocus":!0,"aria-label":`Chat request`,rows:6,value:a,onChange:e=>o(e.target.value)}),(0,$.jsxs)(`div`,{className:`training-dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:r,children:`Cancel`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:!a.trim(),onClick:()=>i(a),children:`Add to chat`})]})]})]})}function bv(e,t,n,r){let i=ra(e),a=u(),o=[`dataset-workspace-runs`,i,t?cf(t):null],s=A({queryKey:o,enabled:!(!e||!t||t.owner||t.profileRef),initialPageParam:void 0,getNextPageParam:e=>e.nextCursor??void 0,queryFn:async({signal:t,pageParam:n})=>{let r=await ko(e,`experiment`,{action:`list`,payload:{limit:100,...n?{afterId:n}:{}}},t);if(n&&r.nextCursor===n)throw Error(`Experiment history did not advance to its next page.`);return{...r,summaries:df(r.summaries)}},refetchInterval:e=>e.state.data?.pages.some(e=>e.summaries.some(e=>t&&lf(e,t)&&uf(e.state)))?2e3:1e4});(0,Q.useEffect)(()=>{s.hasNextPage&&!s.isFetchingNextPage&&!s.isFetchNextPageError&&s.fetchNextPage()},[s.hasNextPage,s.isFetchingNextPage,s.isFetchNextPageError,s.fetchNextPage]);let c=r.filter(e=>[`workspace_action_result`,`turn.completed`].includes(e.name)).at(-1)?.id;(0,Q.useEffect)(()=>{c&&a.invalidateQueries({queryKey:[`dataset-workspace-runs`,i]})},[c,i,a]);let l=new Map(s.data?.pages.flatMap(e=>e.items?.map(e=>[e.id,Date.parse(e.createdAt)])??[])??[]);return{rows:t?[...new Map([...n,...s.data?.pages.flatMap(e=>e.summaries)??[]].filter(e=>lf(e,t)).map(e=>[cf(e),e])).values()].sort((e,t)=>Number(uf(t.state))-Number(uf(e.state))||(l.get(t.id)??0)-(l.get(e.id)??0)):[],history:s}}function xv({connection:e,sessionId:t,resources:n,events:r,selectedExperiment:i,experimentName:a}){let o=n.focus.dataset,s=o?cf(o):``,[c,l]=(0,Q.useState)(null),u=bv(i===void 0?e:null,o,n.experiments,r),d=n.scope,f=d?.ordinal!==null&&d?.ordinal!==void 0,p=f?u.rows.filter(e=>d.runs.some(t=>cf(t)===cf(e))):u.rows,m=f&&!d.runs.length?d:null,h=i===void 0?m?null:p.find(e=>e.id===d?.selectedRunId)??p.find(e=>uf(e.state))??p[0]??(f?d.runs.at(-1)??null:null):i,g=Sv(e,h),_=g.data?.summary??h;(0,Q.useEffect)(()=>{l(null)},[s,d?.id]);let v=d?.ordinal,y=a??i?.name??(i===null?`Experiment draft`:v?`Experiment ${v}`:`Experiment`),b=o?`${o.name}, revision ${o.revision}`:`the selected Dataset`;function x(e,t,r){if([`Add grader`,`New training`].includes(e)){l({title:e});return}let i=t?`${o?.name}, revision ${t.datasetRevision}, run ${t.id}`:b,a=e===`Check graders`?`Test the graders for ${b} against their saved fixtures and known-good and known-bad answers. Report missing coverage and failures separately from model evaluation scores. Do not change the dataset, graders, or start training.`:e===`Diagnose`?`Diagnose ${i}. Inspect its retained results and failures, explain the cause and the next useful step without changing it.`:e===`Improve`?`Improve ${i}. Inspect its retained results, make a targeted change, validate it, and evaluate a comparison within the agreed budget. Preserve the original run and its inputs.`:e===`Run experiment`?`Run an experiment on ${b} with its Dataset graders${n.scope?.evaluationModel?` against ${n.scope.evaluationModel}`:``}. Use the selected execution destination and agreed budget; ask for any missing model or spending limit before starting.`:`Check this training job and show its progress, results, and any model it produced.`;l({title:e,text:a,run:t,training:r})}function S(e){Bd({sessionId:t,text:e,contexts:ff(n,c?.run,c?.training)}),l(null)}return(0,$.jsxs)(`div`,{className:`dataset-workspace`,"aria-label":`Experiment workspace`,children:[(0,$.jsxs)(`header`,{className:`dataset-workspace-section-heading`,children:[(0,$.jsx)(`div`,{className:`dataset-workspace-title`,children:(0,$.jsx)(`h2`,{children:y})}),(0,$.jsxs)(`div`,{className:`dataset-workspace-actions dataset-workspace-header-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:!o,onClick:()=>x(`Run experiment`),children:`Evaluate`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary dataset-action`,disabled:!o||!_,onClick:()=>x(`Diagnose`,_??void 0),children:`Diagnose`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary dataset-action`,disabled:!o||!_||uf(_.state),onClick:()=>x(`Improve`,_??void 0),children:`Improve`}),(0,$.jsxs)(`button`,{type:`button`,className:`training-button secondary dataset-action`,disabled:!o,onClick:()=>x(`Add grader`),children:[(0,$.jsx)(za,{size:13}),` Add grader`]})]})]}),n.error?(0,$.jsx)(X,{error:n.error}):null,o?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{className:`dataset-workspace-context`,children:[(0,$.jsx)(`span`,{children:`Dataset:`}),` `,o.name,` · revision `,o.revision]}),_?(0,$.jsx)(C_,{run:_,view:g.data?.view,loading:g.isPending,error:g.error,onRefresh:()=>void g.refetch()},`progress:${cf(_)}`):(0,$.jsx)(`p`,{children:`Evaluate this experiment, or configure a training run below.`}),u.history.error?(0,$.jsx)(X,{error:u.history.error.message,children:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void u.history.refetch(),children:`Retry`})}):null,(0,$.jsx)(a_,{connection:e,dataset:o,graders:n.graders}),_?(0,$.jsx)(i_,{title:`Results`,children:(0,$.jsx)(w_,{connection:e,run:_,view:g.data?.view},`evidence:${cf(_)}`)}):null,(0,$.jsx)(i_,{title:`Training`,children:(0,$.jsx)(lv,{connection:e,sessionId:t,resources:n,onRequest:x})})]}):(0,$.jsx)(`p`,{children:`Choose an experiment, or create one from a dataset.`}),c?(0,$.jsx)(yv,{dialog:c,connection:e,resources:n,onClose:()=>l(null),onAddToChat:S},c.title):null]})}function Sv(e,t){return S({queryKey:[`dataset-workspace-run`,ra(e),t?cf(t):null],enabled:!!t,queryFn:async({signal:n})=>{let r=await ko(e,`experiment`,{action:`result`,payload:{id:t.id}},n),i=Kr.parse(r.summary),a=Yr.parse(r.view);if(cf(i)!==cf(t)||i.datasetId!==t.datasetId||i.datasetRevision!==t.datasetRevision)throw Error(`Run evidence changed its Dataset pin.`);return{summary:i,view:a}},refetchInterval:e=>uf(e.state.data?.summary.state??t?.state??``)?2e3:!1})}function Cv(e){if(e?.startingModel)return e.startingModel;let t=e?.alphaEditForm?.baseModel??e?.neuronTrainingForm?.baseModel??e?.decisionForm?.baseModel??e?.engramForm?.baseModel??e?.activationForm?.baseModel??e?.trainingForm?.baseModel??e?.training?.baseModel;if(t&&e?.alphaEditForm?.startingModule)return{source:`alphaedit`,label:`Saved AlphaEdit matrices · ${e.alphaEditForm.startingModule.modelProjectId}`,inferenceModelId:null,baseModel:t,alphaedit:e.alphaEditForm.startingModule};if(t&&e?.decisionForm?.startingDecision)return{source:`decision`,label:`Saved Decision Model · ${e.decisionForm.startingDecision.modelProjectId}`,inferenceModelId:null,baseModel:t,decision:e.decisionForm.startingDecision};if(t&&e?.engramForm?.startingModule)return{source:`engram`,label:`Saved memory module · ${e.engramForm.startingModule.modelProjectId}`,inferenceModelId:null,baseModel:t,engram:e.engramForm.startingModule};if(t)return{source:`managed`,label:e?.trainingForm?.startingModelLabel??t.modelId,baseModel:t,inferenceModelId:null};let n=e?.evaluationForm?.form.modelId;return n?{source:`inference`,label:n,inferenceModelId:n,baseModel:null}:null}function wv(e){return e?J(e.source===`alphaedit`?[e.source,e.alphaedit,e.baseModel]:e.source===`neuron_training`?[e.source,e.neuronTraining,e.baseModel]:e.source===`decision`?[e.source,e.decision,e.baseModel]:e.source===`engram`?[e.source,e.engram,e.baseModel]:e.source===`steering`?[e.source,e.steering,e.baseModel]:e.source===`trained`?[e.source,e.trainedVersion.contentHash]:e.source===`managed`?[e.source,e.baseModel]:[e.source,e.inferenceModelId,e.baseModel]):``}var Tv=e=>e?J([e.id,e.revision,e.contentHash]):``;function Ev(e,t,n){let r=e?.request.policy;return{mode:r?.kind===`hosted_harness`?`model_harness_profile`:r?.kind===`hosted_chat`&&r.harness?`model_harness`:`model`,sourceId:r?.kind===`hosted_chat`&&r.harness?`harness-${r.harness.harnessRelease.contentHash}`:``,profileChoiceId:``,...r?.kind===`hosted_chat`?{temperature:r.temperature,topP:r.topP,localRuntime:r.localRuntime}:{},name:e?.request.name??`Evaluation`,release:e?.request.taskset??t,modelId:e&&`modelId`in e.request.policy?e.request.policy.modelId:``,budget:e?.maximumCostUsd??1,outputTokens:e?.request.policy.kind===`hosted_chat`?e.request.policy.maxOutputTokens:1024,prompt:e?.request.policy.kind===`hosted_chat`?e.request.policy.messages?.find(e=>e.role===`system`)?.content??``:``,targetId:e?.request.project?.targetId??n,seed:e?[...new Set(e.request.population.map(e=>e.seed))].join(`, `):`0`,graderChoices:{}}}var Dv=(0,Q.createContext)(null);function Ov({children:e,initialExperiment:t=null,initialRecord:n=null,onNewDraft:r,allowedOperationTypes:i=[`evaluate`,`sft`,`grpo`,`neuron_steering`,`inspect_activations`,`engram_adapter`,`decision_model`,`alphaedit`,`selective_neuron_training`]}){let a=(0,Q.useRef)(null),o=(0,Q.useCallback)(e=>(a.current=e,()=>{a.current===e&&(a.current=null)}),[]),[s,c]=(0,Q.useState)(t),[l,u]=(0,Q.useState)(n),[d,f]=(0,Q.useState)({}),p=(0,Q.useCallback)((e,t)=>f(n=>n[e]===t?n:{...n,[e]:t}),[]),[m,h]=(0,Q.useState)(t?.operationType??`evaluate`),[g,_]=(0,Q.useState)(()=>Cv(t)),v=(0,Q.useRef)(g);v.current=g;function y(e){(v.current?.source!==`alphaedit`||e===`alphaedit`)&&v.current?.source!==`neuron_training`&&(v.current?.source!==`decision`||e===`decision_model`)&&(v.current?.source!==`engram`||e===`engram_adapter`)&&(v.current?.source!==`steering`||e===`neuron_steering`)&&h(e)}let[b,x]=(0,Q.useState)(()=>Cv(t)?.baseModel??null),[S,C]=(0,Q.useState)(t?.trainingForm?.parent??null),[w,T]=(0,Q.useState)(null),[E,D]=(0,Q.useState)(()=>{let e=t?.evaluationForm?.form??(t?Ev(null,null,`model`):null),n=Cv(t);return e&&n?{...e,modelId:n.source===`inference`?n.inferenceModelId:``,localRuntime:n.source===`inference`?e.localRuntime:void 0}:e});function O(e,t){x(e),C(null),_(n=>e?{source:`managed`,baseModel:e,inferenceModelId:null,label:t??(n?.source===`managed`&&J(n.baseModel)===J(e)?n.label:e.modelId)}:null),D(e=>e&&{...e,modelId:``,localRuntime:void 0})}function k(e){_(e?{source:`inference`,label:e.name,inferenceModelId:e.id,baseModel:e.baseModel??null}:null),x(e?.baseModel??null),C(null),D(t=>t&&{...t,modelId:e?.id??``,localRuntime:void 0})}let A=(0,Q.useCallback)((e,t)=>{let n=v.current;if(!n||wv(n)!==e||n.source===`trained`||n.source===`steering`||n.source===`engram`||n.source===`decision`||n.source===`alphaedit`||n.source===`neuron_training`)return;let r=n.baseModel??t.baseModel;x(e=>J(e)===J(r)?e:r),D(e=>e&&(e.modelId!==(t.inferenceModelId??``)||e.localRuntime)?{...e,modelId:t.inferenceModelId??``,localRuntime:void 0}:e),n.source===`inference`?_(t=>t&&t.source===`inference`&&wv(t)===e&&J(t.baseModel)!==J(r)?{...t,baseModel:r}:t):_(n=>n&&n.source===`managed`&&wv(n)===e&&n.inferenceModelId!==t.inferenceModelId?{...n,inferenceModelId:t.inferenceModelId}:n)},[]),[j,M]=(0,Q.useState)(t?.evaluationForm?.source??null),[N,P]=(0,Q.useState)(()=>t?J({draft:t.evaluationForm?.form??Ev(null,null,`model`),selection:t.evaluationForm?.selection??null}):``),[F,I]=(0,Q.useState)(null),[L,ee]=(0,Q.useState)(t?.evaluationForm?.selection??null),R=e=>Tv(L?.release??null)===Tv(e);function z(e){ee(t=>Tv(t?.release??null)===Tv(e)?t:{release:e,mode:`all`,ids:[]})}function B(e=null,t=null,n=null,r=`model`){if(E&&j?.id===e?.id&&(!t||Tv(E.release)===Tv(t))){n&&I(n);return}T(null),c({schemaVersion:`openpond.experimentDraft.v1`,id:crypto.randomUUID(),operationType:`evaluate`,name:`Evaluation`}),u(null),f({}),x(null),_(null),C(null),y(`evaluate`);let i=Ev(e,t,r),a=i.release?{release:i.release,mode:e?`subset`:`all`,ids:e?[...new Set(e.request.population.map(e=>e.taskId))]:[]}:null;M(e),D(i),ee(a),_(i.modelId?{source:`inference`,label:i.modelId,inferenceModelId:i.modelId,baseModel:null}:null),P(J({draft:i,selection:a})),I(n)}function V(e,t,n){let r=e.evaluationForm,i=Cv(e),a=r?.form??Ev(null,null,`model`),o=i?{...a,modelId:i.source===`inference`?i.inferenceModelId:``,localRuntime:i.source===`inference`?a.localRuntime:void 0}:a;_(i),c(e),u(t),T(null),f({}),h(e.operationType),C(e.trainingForm?.parent??null),x(i?.baseModel??null),D(o),M(r?.source??null),ee(r?.selection??null),P(J({draft:o,selection:r?.selection??null})),I({...n,executionLocation:r?.executionLocation??`hosted`})}function H(e,t){V(e.draft,e,t)}async function U(e,t){let n=Kn.parse(e),i,o=()=>{r?i=r(n):V(n,null,t)};a.current?await a.current(o):o(),await i}function te(e){s?.id===e.id&&(u(e),e.draft.evaluationForm&&P(J({draft:e.draft.evaluationForm.form,selection:e.draft.evaluationForm.selection})))}function ne(e,t){E&&Tv(E.release)===Tv(e)?(y(`evaluate`),I(t)):B(null,e,t)}async function re(e,t,n){let r=!1,i=()=>{r=!0,ne(e,t),n&&`all`in n?W.selectAll(e,n.all):n&&W.toggle(e,n.id,n.checked)};return E&&Tv(E.release)!==Tv(e)&&a.current?await a.current(i):i(),r}let W={startingModel:g,chooseInferenceModel:k,applyModelCatalogLink:A,trainingParent:S,setTrainingParent:C,registerTransitionGuard:o,requestSelection:re,storedRecord:l,openDraft:U,openStored:H,acceptSaved:te,evaluationDirty:J({draft:E,selection:L})!==N,initialExperiment:s,allowedOperationTypes:i,operationDraftDirty:Object.values(d).some(Boolean),reportOperationDraftDirty:p,operationType:m,setOperationType:y,trainingBaseModel:b,setTrainingBaseModel:O,advancedTarget:w,openAdvanced:e=>{T(e),D(null),M(null),I(null)},draft:E,setDraft:D,existing:j,changeRelease:e=>{D(t=>t&&{...t,release:e}),Tv(E?.release??null)!==Tv(e)&&I(null),e&&z(e)},baseline:N,reviewRoute:F,selection:L,activate:z,open:B,openSelection:ne,close:()=>{c(null),u(null),f({}),x(null),_(null),C(null),T(null),D(null),M(null),I(null)},selected:(e,t)=>!R(e)||L.mode===`all`?!R(e)||!L.ids.includes(t):L.ids.includes(t),toggle:(e,t,n)=>ee(r=>{let i=Tv(r?.release??null)===Tv(e)?r:{release:e,mode:`all`,ids:[]},a=i.mode===`all`?!n:n;return{...i,ids:a?[...new Set([...i.ids,t])]:i.ids.filter(e=>e!==t)}}),selectAll:(e,t)=>ee({release:e,mode:t?`all`:`subset`,ids:[]}),count:(e,t)=>R(e)?L.mode===`all`?Math.max(0,t-L.ids.length):L.ids.length:t};return(0,$.jsx)(Dv.Provider,{value:W,children:e})}function kv(){let e=(0,Q.useContext)(Dv);if(!e)throw Error(`Evaluation setup requires workspace scope.`);return e}var Av=(0,Q.createContext)(!1),jv=()=>(0,Q.useContext)(Av),Mv=(0,Q.createContext)(null),Nv=(0,Q.createContext)(()=>{});function Pv(e){let t=(0,Q.useContext)(Nv);(0,Q.useEffect)(()=>{t(e)},[e,t])}var Fv=(0,Q.createContext)(null),Iv=()=>(0,Q.useContext)(Fv);function Lv({children:e,onControl:t}){let[n,r]=(0,Q.useState)(!1),[i,a]=(0,Q.useState)(440),[o,s]=(0,Q.useState)({}),c=(0,Q.useCallback)((e,t)=>(s(n=>({...n,[t]:e})),()=>s(e=>{let n={...e};return delete n[t],n})),[]),l=(0,Q.useMemo)(()=>{let e=new Map;for(let t of Object.values(o))for(let n of t)e.set(n.id,n);return[...e.values()]},[o]),u=(0,Q.useRef)([]),[d,f]=(0,Q.useState)(null),p=(0,Q.useRef)(new Map),m=(0,Q.useCallback)((e,t)=>(p.current.set(e,t),()=>{p.current.get(e)===t&&p.current.delete(e)}),[]),h=(0,Q.useCallback)(e=>a(Math.max(320,Math.min(800,e))),[]),g=(0,Q.useCallback)(e=>{u.current=[...u.current.filter(t=>t!==e),e],f(e),r(!0)},[]),_=(0,Q.useCallback)(e=>{u.current=u.current.filter(t=>t!==e),f(t=>t===e?u.current.at(-1)??null:t),u.current.length||r(!1)},[]),v=(0,Q.useCallback)(e=>{e.onSelect();let t=[...u.current].reverse().find(t=>t.startsWith(`${e.id}:`));t?g(t):(f(e.id),r(!0))},[g]),y=(0,Q.useCallback)(()=>{!n&&!u.current.length&&l[0]?v(l.find(e=>e.id===d)??l[0]):r(e=>!e)},[n,l,d,v]),b=(0,Q.useCallback)(()=>{let e=d?p.current.get(d):null;e?e():r(!1)},[d]);(0,Q.useEffect)(()=>(t?.({open:n,toggle:y}),()=>t?.(null)),[t,n,y]);let x=(0,Q.useMemo)(()=>({open:n,width:i,actions:l,active:d,toggle:y,dismiss:b,registerClose:m,resize:h,register:c,select:v,show:g,close:_}),[n,i,l,d,y,b,m,h,v,g,_]);return(0,$.jsx)(Fv.Provider,{value:x,children:e})}function Rv(e){let t=Iv(),n=t?.register,r=(0,Q.useId)(),i=(0,Q.useRef)(e);i.current=e;let a=e.map(e=>`${e.id}:${e.label}`).join(`|`);return(0,Q.useEffect)(()=>{if(n)return n(i.current.map(e=>({...e,onSelect:()=>i.current.find(t=>t.id===e.id)?.onSelect()})),r)},[n,a,r]),e=>{let n=i.current.find(t=>t.id===e);n&&(t?t.select(n):n.onSelect())}}function zv(){let e=Iv();return e?(0,$.jsxs)(`div`,{className:`evaluation-panel-toolbar`,children:[(0,$.jsx)(`nav`,{"aria-label":`Sidebar actions`,children:e.actions.map(t=>(0,$.jsx)(`button`,{type:`button`,"aria-pressed":e.active===t.id||e.active?.startsWith(`${t.id}:`),onClick:()=>e.select(t),children:t.label},t.id))}),(0,$.jsx)(`button`,{type:`button`,className:`evaluation-panel-icon`,"aria-label":`Collapse sidebar`,onClick:e.dismiss,children:(0,$.jsx)(es,{size:16})})]}):null}function Bv({children:e,label:t,action:n,onRequestClose:r,visible:i=!0}){let a=(0,Q.useContext)(Mv),o=Iv(),s=(0,Q.useId)(),c=n?`${n}:${s}`:s,l=o?.show,u=o?.close,d=(0,Q.useRef)(r);d.current=r;let f=o?.registerClose;return(0,Q.useEffect)(()=>{if(f&&r)return f(c,()=>d.current?.())},[f,c,!!r]),(0,Q.useEffect)(()=>(i?l?.(c):u?.(c),()=>u?.(c)),[l,u,c,i]),a?(0,vu.createPortal)((0,$.jsx)(`section`,{"aria-label":t,hidden:!i||!!(o&&o.active!==c),children:(0,$.jsx)(Av.Provider,{value:!0,children:e})}),a):null}function Vv(e){return JSON.stringify([e.key,e.actorId,e.connection.serverUrl,e.connection.token])}function Hv(e,t,n,r){if(!e.actorId)throw Error(`Sign in to use the evaluation owner controls.`);return Y(e.connection,`/v1/${t}`,{method:`POST`,body:JSON.stringify({teamId:e.teamId,projectId:e.projectId,request:n}),signal:r})}function Uv(e,t){return A({queryKey:[`reviewed-evaluation-operations`,Vv(e),t],initialPageParam:void 0,getNextPageParam:e=>e.nextCursor??void 0,queryFn:async({pageParam:n,signal:r})=>sl.parse(await e.pendingOperations(t,n,r)),refetchOnWindowFocus:!0})}function Wv({items:e,busy:t,error:n,onRestore:r,onDiscard:i,onLoadMore:a}){return(0,$.jsxs)(`section`,{"aria-label":`Retained reviewed operations`,children:[n?(0,$.jsx)(X,{error:n}):null,e.length?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h3`,{children:`Retained operations`}),(0,$.jsx)(`p`,{children:`Restore the original reviewed command before retrying an uncertain request. Changing the setup does not replace that command.`})]}):null,e.map(e=>(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`p`,{children:[e.id,` / `,e.phase??`recovery unavailable`,` / `,e.createdAt]}),e.recoveryReady?(0,$.jsx)(`button`,{type:`button`,disabled:t,onClick:()=>r(e),children:`Restore original command`}):(0,$.jsx)(`p`,{children:`The original command was not retained. Recover its actual receipt before starting another operation.`}),e.phase===`reviewed`?(0,$.jsx)(`button`,{type:`button`,disabled:t,onClick:()=>i(e),children:`Discard unstarted review`}):null]},e.id)),a?(0,$.jsx)(`button`,{type:`button`,disabled:t,onClick:a,children:`Load more retained operations`}):null]})}var Gv=U().trim().min(1).max(200),Kv=U().regex(/^[a-f0-9]{64}$/),qv=U().datetime(),Jv=z({operationId:Gv,id:Gv.optional(),expectedRevision:V().int().nonnegative(),teamId:Gv,projectId:Gv.nullable(),enabled:B(),configuration:Ts,cadence:I(`kind`,[z({kind:L(`interval`),seconds:V().int().min(60).max(31536e3)}).strict(),z({kind:L(`nightly`),calendar:ve}).strict()]),maximumTotalSpendUsd:V().finite().positive().max(1e4),maximumAttempts:V().int().min(1).max(20)}).strict().superRefine((e,t)=>{(e.configuration.request.teamId!==e.teamId||(e.configuration.request.project?.id??null)!==e.projectId)&&t.addIssue({code:`custom`,message:`The scheduled Experiment must retain its actual workspace and Project.`}),e.configuration.maximumCostUsd>e.maximumTotalSpendUsd&&t.addIssue({code:`custom`,message:`The run ceiling exceeds the approved cumulative schedule ceiling.`})}),Yv=z({id:Gv,scheduledAt:qv,coalescedThroughAt:qv,coalescedCount:V().int().nonnegative(),configurationHash:Kv,operationId:Gv,state:H([`reserved`,`dispatching`,`running`,`cleaning`,`completed`,`failed`,`cancelled`,`uncertain`]),executionId:Gv.nullable(),attempt:V().int().positive(),maximumCostUsd:V().finite().positive(),actualSpendUsd:V().finite().nonnegative().nullable(),cleanupComplete:B(),error:U().max(4e3).nullable()}).strict(),Xv=z({schemaVersion:L(`openpond.experimentEvaluationSchedule.v1`),id:Gv,revision:V().int().positive(),actorId:Gv,teamId:Gv,projectId:Gv.nullable(),operationId:Gv,requestHash:Kv,configuration:Ts,configurationHash:Kv,cadence:Jv.shape.cadence,state:H([`scheduled`,`disabled`,`blocked`]),nextRunAt:qv.nullable(),maximumTotalSpendUsd:V().finite().positive(),maximumAttempts:V().int().positive(),lastEvaluatedConfigurationHash:Kv.nullable(),newerUnevaluatedRelease:Ne.nullable(),fires:F(Yv).max(1e4),reason:U().max(4e3).nullable(),createdAt:qv,updatedAt:qv,contentHash:Kv}).strict();function Zv(e){let{operationId:t,request:n,...r}=e,{operationId:i,...a}=n;return je({...r,request:a})}function Qv(e){let t=Xv.parse(e);if(Be(t,`Scheduled Experiment`),t.configurationHash!==Zv(t.configuration)||t.configuration.request.teamId!==t.teamId||(t.configuration.request.project?.id??null)!==t.projectId)throw Error(`Scheduled Experiment immutable authority differs from its recipe.`);return t}var $v=z({teamId:Gv,id:Gv,operationId:Gv,expectedRevision:V().int().positive(),action:H([`cancel_active`,`retry_active`,`pause`])}).strict(),ey=I(`operation`,[z({operation:L(`publish`),request:Jv}).strict(),z({operation:L(`control`),request:$v}).strict(),z({operation:L(`read`),id:Gv}).strict(),z({operation:L(`list`),cursor:Gv.optional(),limit:V().int().min(1).max(100).default(50)}).strict()]),ty=(0,Q.createContext)(null);function ny({children:e,handle:t}){let n=(0,Q.useRef)(new Set),r=(0,Q.useRef)(!1),i=(0,Q.useRef)(!0);(0,Q.useEffect)(()=>(i.current=!0,()=>{i.current=!1}),[]);let a=(0,Q.useCallback)(e=>(n.current.add(e),()=>{n.current.delete(e)}),[]);return(0,Q.useImperativeHandle)(t,()=>({async requestLeave(e){if(!r.current){r.current=!0;try{for(let e of[...n.current].reverse())if(!await e())return;i.current&&await e()}finally{r.current=!1}}}}),[]),(0,$.jsx)(ty.Provider,{value:a,children:e})}function ry(e){let t=(0,Q.useContext)(ty),n=(0,Q.useRef)(e);n.current=e,(0,Q.useEffect)(()=>t?.(()=>n.current()),[t])}function iy(e){let t=(0,Q.useRef)(e);t.current=e;let n=(0,Q.useRef)(null),r=(0,Q.useRef)(!1),i=(0,Q.useRef)(!0),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(null);async function d(){return r.current?(r.current=!1,!0):t.current.busy?!1:!t.current.dirty||!n.current&&(u(null),o(!0),new Promise(e=>{n.current=e}))}ry(async()=>await d()&&i.current),(0,Q.useEffect)(()=>{i.current=!0;let e=uo(async e=>{if(t.current.retainForDestination?.(e)&&!t.current.busy)return!0;let n=await d();return n&&i.current&&t.current.onLeave?.(),n&&i.current}),r=e=>{t.current.dirty&&(e.preventDefault(),e.returnValue=``)};return window.addEventListener(`beforeunload`,r),()=>{i.current=!1,e(),window.removeEventListener(`beforeunload`,r);let t=n.current;n.current=null,t?.(!1)}},[]);let f=e=>{let t=n.current;n.current=null,i.current&&o(!1),t?.(e)};return{dialog:a?(0,$.jsxs)(qa,{ariaLabel:e.save?`Save ${e.name} before leaving`:`Discard ${e.name}`,className:`labs-rename-dialog labs-draft-exit-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:s,onClose:()=>f(!1),children:[(0,$.jsx)(`h2`,{children:e.save?`Save ${e.name} before leaving?`:`Discard ${e.name}?`}),(0,$.jsx)(`p`,{children:e.save?`Your changes can be saved before opening the next page.`:e.discardDescription??`This setup has not been saved. Keep editing or discard it to leave.`}),l?(0,$.jsx)(X,{error:l}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{className:`training-button secondary`,type:`button`,disabled:s,onClick:()=>f(!1),children:`Keep editing`}),(0,$.jsx)(`button`,{className:`training-button secondary`,type:`button`,disabled:s,onClick:()=>f(!0),children:`Discard changes`}),e.save?(0,$.jsx)(`button`,{className:`training-button`,type:`button`,disabled:s,onClick:async()=>{c(!0);try{let e=await t.current.save?.();i.current&&(e?f(!0):u(`The draft could not be saved. Your edits are still here.`))}catch(e){i.current&&u(e instanceof Error?e.message:`The draft could not be saved.`)}finally{i.current&&c(!1)}},children:s?`Saving…`:`Save and continue`}):null]})]}):null,allowNextNavigation(){r.current=!0},async requestLeave(e){await d()&&i.current&&e()}}}function ay({api:e,configuration:t,onOpenExperiment:n}){let[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(!1),l=iy({name:`evaluation schedule`,dirty:a,busy:s,onLeave:()=>i(!1)});return Rv(t?[{id:`scheduled-evaluations`,label:`Scheduled evaluations`,onSelect:()=>i(!0)}]:[]),(0,$.jsxs)($.Fragment,{children:[r&&t?(0,$.jsx)(Bv,{label:`Scheduled evaluations`,action:`scheduled-evaluations`,onRequestClose:()=>void l.requestLeave(()=>i(!1)),children:(0,$.jsx)(oy,{api:e,configuration:t,requestChange:e=>void l.requestLeave(e),onDirty:o,onBusy:c,onOpenExperiment:n},ie([Vv(e),Zv(t)]))}):null,l.dialog]})}function oy({api:e,configuration:t,onDirty:n,requestChange:r,onBusy:i,onOpenExperiment:a}){let o=u(),s=Vv(e),c=(0,Q.useRef)(s);c.current=s;let[l,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(`interval`),[g,_]=(0,Q.useState)(1440),[v,y]=(0,Q.useState)(`02:00`),[b,x]=(0,Q.useState)(Intl.DateTimeFormat().resolvedOptions().timeZone),[C,w]=(0,Q.useState)(t.maximumCostUsd),[T,E]=(0,Q.useState)(1),[D,O]=(0,Q.useState)(null),[k,j]=(0,Q.useState)(!1),M=(0,Q.useRef)(null),N=(0,Q.useRef)(null),P=(0,Q.useRef)(!0);(0,Q.useEffect)(()=>(P.current=!0,()=>{P.current=!1,N.current?.abort()}),[]),(0,Q.useEffect)(()=>(i(k),()=>i(!1)),[k,i]);let F=Uv(e,`experiment-evaluation-schedule`),I=F.data?.pages.flatMap(e=>e.items)??[];async function L(t){let r=s;j(!0);try{await e.recoverOperation(t).acknowledge(`reviewed`),P.current&&c.current===r&&(M.current?.operation.id===t.id&&(M.current=null),await F.refetch(),n(!1))}catch(e){P.current&&c.current===r&&O(e instanceof Error?e.message:String(e))}finally{P.current&&c.current===r&&j(!1)}}function ee(t){try{if(!t.recoveryReady||ie(t.reviewedIntent)!==t.intentHash)throw Error(`The original reviewed intent is unavailable.`);let r=ey.parse(t.command);if(r.operation!==`publish`&&r.operation!==`control`)throw Error(`The retained command is not an owner action.`);if(r.request.operationId!==t.id||r.request.teamId!==e.teamId)throw Error(`The retained command belongs to another owner scope.`);M.current={scope:s,request:r,operation:e.recoverOperation(t)},n(!0),O(null)}catch(e){O(e instanceof Error?e.message:String(e))}}let R=[`evaluation-schedules`,s],z=A({queryKey:R,initialPageParam:void 0,getNextPageParam:e=>e.nextCursor??void 0,queryFn:async({signal:t,pageParam:n})=>{let r=await Hv(e,`experiment-evaluation-schedules`,{operation:`list`,limit:100,...n?{cursor:n}:{}},t);return{items:r.items.map(Qv),nextCursor:r.nextCursor}},refetchInterval:5e3}),B=Zv(t),V=z.data?.pages.flatMap(e=>e.items).filter(e=>e.configurationHash===B)??[],H=S({queryKey:[...R,l?.id],enabled:!!l,queryFn:async({signal:t})=>Qv(await Hv(e,`experiment-evaluation-schedules`,{operation:`read`,id:l.id},t)),refetchInterval:3e3});(0,Q.useEffect)(()=>{H.data&&H.data.id===l?.id&&H.data.revision>=l.revision&&d(H.data)},[H.data,l]);function U(e){k||M.current||(e(),n(!0))}function te(e){d(e),p(e.state!==`disabled`),w(e.maximumTotalSpendUsd),E(e.maximumAttempts),h(e.cadence.kind),e.cadence.kind===`interval`?_(e.cadence.seconds/60):(y(e.cadence.calendar.localTime),x(e.cadence.calendar.timeZone)),n(!1)}async function ne(t,n){if(k)return;j(!0),O(null);let r=s,i=new AbortController;N.current=i;try{let a=M.current;if(a&&a.scope!==r)throw Error(`The pending schedule command belongs to another scope.`);if(!a){let i=await e.operation(`experiment-evaluation-schedule`,t);if(!P.current||c.current!==r)return;a={scope:r,request:n(i.id),operation:i},M.current=a}if(await a.operation.retainCommand(a.request,`dispatching`),!P.current||c.current!==r)return;let s=Qv(await Hv(e,`experiment-evaluation-schedules`,a.request,i.signal));if(!P.current||c.current!==r||(te(s),await a.operation.acknowledge(),!P.current||c.current!==r)||(M.current=null,await F.refetch(),!P.current||c.current!==r))return;await o.invalidateQueries({queryKey:R})}catch(e){P.current&&c.current===r&&O(e instanceof Error?e.message:String(e))}finally{P.current&&c.current===r&&j(!1),N.current===i&&(N.current=null)}}let re=m===`interval`?{kind:`interval`,seconds:Math.round(g*60)}:{kind:`nightly`,calendar:{localTime:v,timeZone:b}},W={id:l?.id,expectedRevision:l?.revision??0,teamId:e.teamId,projectId:e.projectId,configuration:t,enabled:f,cadence:re,maximumTotalSpendUsd:C,maximumAttempts:T};return(0,$.jsxs)(`div`,{className:`evaluation-form`,children:[(0,$.jsx)(`h2`,{children:`Scheduled evaluations`}),(0,$.jsx)(Wv,{items:I,busy:k,error:F.error?.message,onRestore:ee,onDiscard:e=>void L(e),onLoadMore:F.hasNextPage?()=>void F.fetchNextPage():void 0}),M.current?(0,$.jsxs)(`p`,{children:[`Frozen command: `,M.current.operation.id,`. This retry uses the original retained setup and limits, even if the current parent setup differs.`]}):null,(0,$.jsx)(`p`,{children:`Execution owner: this connected app server. It must remain running. Each occurrence evaluates this pinned recipe within the cumulative limits; no source release is advanced automatically.`}),(0,$.jsx)(`p`,{children:`Saved schedules run the exact reviewed Dataset, target and graders. New releases are shown for review and never selected automatically.`}),D??z.error?.message??H.error?.message?(0,$.jsx)(X,{error:D??z.error?.message??H.error?.message}):null,(0,$.jsxs)(`label`,{children:[`Existing schedule`,(0,$.jsxs)(`select`,{disabled:k||!!M.current,value:l?.id??``,onChange:e=>{let i=V.find(t=>t.id===e.target.value);r(()=>{i?te(i):(d(null),p(!1),h(`interval`),_(1440),y(`02:00`),x(Intl.DateTimeFormat().resolvedOptions().timeZone),w(t.maximumCostUsd),E(1),n(!1))})},children:[(0,$.jsx)(`option`,{value:``,children:`New schedule for this setup`}),V.map(e=>(0,$.jsxs)(`option`,{value:e.id,children:[e.id,` / `,e.state,` / revision `,e.revision]},e.id))]})]}),z.hasNextPage?(0,$.jsx)(`button`,{type:`button`,disabled:z.isFetchingNextPage,onClick:()=>void z.fetchNextPage(),children:`Load more schedules`}):null,(0,$.jsxs)(`fieldset`,{disabled:k||!!M.current,children:[(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:f,onChange:e=>U(()=>p(e.target.checked))}),`Enable scheduled evaluations`]}),(0,$.jsxs)(`label`,{children:[`Cadence`,(0,$.jsxs)(`select`,{value:m,onChange:e=>U(()=>h(e.target.value===`nightly`?`nightly`:`interval`)),children:[(0,$.jsx)(`option`,{value:`interval`,children:`Interval`}),(0,$.jsx)(`option`,{value:`nightly`,children:`Nightly`})]})]}),m===`interval`?(0,$.jsxs)(`label`,{children:[`Interval minutes`,(0,$.jsx)(`input`,{type:`number`,min:1,max:525600,value:g,onChange:e=>U(()=>_(Number(e.target.value)))})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[`Local time`,(0,$.jsx)(`input`,{type:`time`,value:v,onChange:e=>U(()=>y(e.target.value))})]}),(0,$.jsxs)(`label`,{children:[`Time zone`,(0,$.jsx)(`input`,{value:b,onChange:e=>U(()=>x(e.target.value))})]})]}),(0,$.jsxs)(`label`,{children:[`Cumulative budget USD`,(0,$.jsx)(`input`,{type:`number`,min:t.maximumCostUsd,value:C,onChange:e=>U(()=>w(Number(e.target.value)))})]}),(0,$.jsxs)(`label`,{children:[`Maximum attempts`,(0,$.jsx)(`input`,{type:`number`,min:1,max:20,value:T,onChange:e=>U(()=>E(Number(e.target.value)))})]})]}),(0,$.jsxs)(`p`,{children:[`Per-occurrence ceiling `,t.maximumCostUsd,` USD. Exact recipe`,` `,B,`.`]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:k||F.isPending||!!F.error,onClick:()=>void ne(W,e=>({operation:`publish`,request:{...W,operationId:e}})),children:M.current?`Retry retained command`:`Save schedule`}),l?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[l.state,` / next `,l.nextRunAt??`none`]}),l.reason?(0,$.jsx)(`p`,{children:l.reason}):null,l.newerUnevaluatedRelease?(0,$.jsxs)(`p`,{children:[`Newer unevaluated Dataset: `,l.newerUnevaluatedRelease.id,` /`,` `,l.newerUnevaluatedRelease.contentHash,`. Review a new setup before changing this schedule.`]}):null,[`pause`,`cancel_active`,`retry_active`].map(t=>(0,$.jsx)(`button`,{type:`button`,disabled:k||!!M.current,onClick:()=>void ne({id:l.id,revision:l.revision,action:t},n=>({operation:`control`,request:{teamId:e.teamId,id:l.id,expectedRevision:l.revision,operationId:n,action:t}})),children:t.replaceAll(`_`,` `)},t)),(0,$.jsx)(`ol`,{children:l.fires.map(e=>(0,$.jsxs)(`li`,{children:[e.scheduledAt,` / `,e.state,` /`,` `,e.actualSpendUsd===null?`Spend unresolved`:`${e.actualSpendUsd} USD`,` `,`/ cleanup `,e.cleanupComplete?`complete`:`pending`,e.coalescedCount?` / coalesced ${e.coalescedCount}`:``,e.executionId&&a?(0,$.jsx)(`button`,{type:`button`,onClick:()=>a(e.executionId),children:`Open actual Experiment`}):null,e.error?(0,$.jsx)(`p`,{children:e.error}):null]},e.id))})]}):null]})}var sy=I(`ready`,[z({ready:L(!1),reason:U(),choices:F(ee())}).strict(),z({ready:L(!0),version:U(),executableHash:U(),capabilityHash:U(),choices:F(z({id:U(),name:U(),configurationHash:U(),contextWindow:V(),outputLimit:V()}).strict())}).strict()]);function cy({api:e,policy:t,onChange:n}){let[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(0);(0,Q.useEffect)(()=>{let t=new AbortController;return i(null),o(null),e.local(`claudeReadiness`,{},t.signal).then(e=>{t.signal.aborted||i(sy.parse(e))}).catch(e=>{t.signal.aborted||o(e.message)}),()=>t.abort()},[e.key,s]);let l=t.kind===`hosted_chat`&&t.localRuntime?.providerId===`claude-code`?t.localRuntime:void 0;return(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h3`,{children:`Live Claude Code`}),(0,$.jsx)(`p`,{children:`Run the installed CLI in an isolated text-task session. This target has no filesystem tools or MCP servers. Actual events and human interventions are retained locally; team publication remains explicit.`}),a?(0,$.jsx)(X,{error:a}):null,r&&!r.ready?(0,$.jsx)(`p`,{children:r.reason}):null,r?.ready?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[`Installed interface `,r.version,`, exact executable and capabilities pinned`]}),(0,$.jsxs)(`label`,{children:[`Claude model`,(0,$.jsxs)(`select`,{value:l&&t.kind===`hosted_chat`?t.modelId:``,onChange:e=>{if(t.kind!==`hosted_chat`)return;let i=r.choices.find(t=>t.id===e.target.value);i&&n({...t,modelId:i.id,temperature:0,topP:1,maxOutputTokens:Math.min(t.maxOutputTokens,i.outputLimit),harness:void 0,candidate:void 0,localRuntime:{providerId:`claude-code`,configurationHash:i.configurationHash,executableHash:r.executableHash,version:r.version,capabilityHash:r.capabilityHash,maximumRequestCostUsd:.01,requestTimeoutMs:18e4,maximumTurns:5,holdOpen:!1}})},children:[(0,$.jsx)(`option`,{value:``,children:`Select an exact configured model`}),r.choices.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]})]}):null,(0,$.jsx)(`button`,{type:`button`,onClick:()=>c(e=>e+1),children:`Refresh installed interface`}),l&&t.kind===`hosted_chat`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[`CLI request budget ($)`,(0,$.jsx)(`input`,{type:`number`,min:1e-6,max:1e4,step:.001,value:l.maximumRequestCostUsd,onChange:e=>n({...t,localRuntime:{...l,maximumRequestCostUsd:Number(e.target.value)}})})]}),(0,$.jsxs)(`label`,{children:[`Turn limit`,(0,$.jsx)(`input`,{type:`number`,min:1,max:100,value:l.maximumTurns,onChange:e=>n({...t,localRuntime:{...l,maximumTurns:Number(e.target.value)}})})]}),(0,$.jsxs)(`label`,{children:[`Deadline (seconds)`,(0,$.jsx)(`input`,{type:`number`,min:1,max:300,value:l.requestTimeoutMs/1e3,onChange:e=>n({...t,localRuntime:{...l,requestTimeoutMs:Number(e.target.value)*1e3}})})]}),(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:l.holdOpen,onChange:e=>n({...t,localRuntime:{...l,holdOpen:e.target.checked}})}),`Keep the session open for explicit human messages and sealing`]}),(0,$.jsx)(`p`,{children:`CLI cost estimates and reported tokens are retained. Measured monetary cost remains unknown.`})]}):null]})}function ly(e){let t=e=>`/v1/training/candidate-evaluations/${encodeURIComponent(e)}`;function n(e,t,n){let r=gy.parse(e);if(r.teamId!==t||n&&r.id!==n)throw Error(`The preparation belongs to another workspace or candidate operation.`);return r}return{async options(t,n={}){let r=new URLSearchParams({teamId:t,...n}),i=my.parse(await e(`/v1/training/candidates?${r}`));if(i.teamId!==t)throw Error(`The candidate catalog belongs to another workspace.`);return i},async save(t){let r=hy.parse(t),i=n(await e(`/v1/training/candidate-evaluations?teamId=${encodeURIComponent(r.teamId)}`,{method:`POST`,body:JSON.stringify(r)}),r.teamId);if(i.requestHash!==je(r))throw Error(`The saved preparation differs from the selected candidate or frozen evaluation.`);return i},async get(r,i){return n(await e(`${t(i)}?teamId=${encodeURIComponent(r)}`),r,i)},async control(r,i,a,o){let s=_y.parse(o),c=n(await e(`${t(i)}/${a}?teamId=${encodeURIComponent(r)}`,{method:`POST`,body:JSON.stringify(s)}),r,i);if(c.requestHash!==s.requestHash)throw Error(`The command returned a different frozen evaluation.`);return c}}}var uy=U().trim().min(1).max(200),dy=U().regex(/^[a-f0-9]{64}$/),fy=z({id:uy,contentHash:dy}).strict(),py=z({artifact:fy,trainingJobId:uy,configurationId:uy,baseProfileId:uy,ready:B(),reason:U().max(1e3).nullable()}).strict(),my=z({teamId:uy,ownerUserId:uy,items:F(py).max(100),nextCursor:uy.nullable()}).strict(),hy=z({teamId:uy,operationId:uy,artifact:fy,configuration:Ts}).strict().superRefine((e,t)=>{(e.configuration.request.teamId!==e.teamId||e.configuration.request.policy.kind===`fixture`||e.configuration.request.policy.candidate)&&t.addIssue({code:`custom`,message:`Choose one exact model-backed evaluation before preparing the trained version.`})}),gy=z({schemaVersion:L(`openpond.candidateEvaluationPreparation.v1`),teamId:uy,ownerUserId:uy,id:uy,revision:V().int().positive(),requestHash:dy,request:hy,trainingJobId:uy,dispatchId:uy,lastOperationId:uy.nullable(),runtime:z({poolId:uy,endpointId:uy.nullable(),baseProfileId:uy,workerImageDigest:U().regex(/^sha256:[a-f0-9]{64}$/),modelId:uy.nullable()}).strict().nullable(),state:H([`configured`,`preparing`,`ready`,`dispatching`,`submitted`,`cleaning`,`completed`,`failed`,`cancelled`]),experimentId:uy.nullable(),authorizedAt:N().nullable(),cancelledAt:N().nullable(),reason:U().max(1e3).nullable(),createdAt:N(),updatedAt:N()}).strict().superRefine((e,t)=>{(e.requestHash!==je(e.request)||!e.runtime&&[`ready`,`dispatching`,`submitted`,`completed`].includes(e.state))&&t.addIssue({code:`custom`,message:`The exact candidate preparation request or runtime changed.`})}),_y=z({operationId:uy,expectedRevision:V().int().positive(),requestHash:dy}).strict();function vy({connection:e,teamId:t,actorId:n,projectId:r,configuration:i,retainOperation:a,onStarted:o,onBusyChange:s}){let c=JSON.stringify([e.serverUrl,e.token,t,n,r]),l=(0,Q.useMemo)(()=>ly(async(n,r)=>{let i=new URL(n,`https://candidate.invalid`);return i.searchParams.set(`teamId`,t),Y(e,`${i.pathname}?${i.searchParams}`,r)}),[e.serverUrl,e.token,t]),u=(0,Q.useRef)(c);u.current=c,(0,Q.useEffect)(()=>(u.current=c,()=>{u.current=`unmounted`}),[c]);let d=(0,Q.useRef)(null),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>(s?.(b),()=>s?.(!1)),[b,s]);let S=g?.scope===c?g.value:null;(0,Q.useEffect)(()=>{let e=!1;if(y(null),x(!1),h(``),d.current?.scope!==c&&(d.current=null),!n)return;async function i(){try{let i=[],a,o=new Set;for(let e=0;;e++){if(e>=100)throw Error(`Candidate catalog exceeds its bounded supported scope.`);let s=await l.options(t,{projectId:r??void 0,afterId:a});if(s.ownerUserId!==n)throw Error(`The candidate owner changed.`);if(i.push(...s.items),!s.nextCursor)break;if(o.has(s.nextCursor))throw Error(`Candidate pagination did not advance.`);o.add(s.nextCursor),a=s.nextCursor}e||p({scope:c,items:i})}catch(t){e||y(t instanceof Error?t.message:`Candidate catalog is unavailable.`)}}return i(),()=>{e=!0}},[l,t,n,r,c]),(0,Q.useEffect)(()=>{if(!S||![`preparing`,`dispatching`,`submitted`,`cleaning`].includes(S.state))return;let e=!1,r,i=async()=>{try{let r=await l.get(t,S.id);if(!e){if(r.ownerUserId!==n)throw Error(`The candidate owner changed.`);_({scope:c,value:r})}}catch(t){e||y(t instanceof Error?t.message:`Candidate status is unavailable.`)}e||(r=setTimeout(i,3e3))};return r=setTimeout(i,3e3),()=>{e=!0,clearTimeout(r)}},[l,t,c,S?.id,S?.state]);async function C(e){if(b||!n)return;let s=c,p=()=>{if(u.current!==s)throw Error(`The active account or Project changed. Reopen candidate evaluation setup.`)};x(!0),y(null);try{let s=S;if(!s){let e=f?.scope===c?f.items.find(e=>e.artifact.id===m):null;if(!e||!i)throw Error(`Choose a trained version and complete the exact evaluation cases, graders and budget.`);let o=await a(`candidate:save`,{teamId:t,actorId:n,projectId:r,artifact:e.artifact,configuration:i});if(p(),s=await l.save({teamId:t,operationId:o.id,artifact:e.artifact,configuration:i}),p(),s.ownerUserId!==n)throw Error(`The candidate owner changed.`);_({scope:c,value:s}),await o.acknowledge(),p()}let u=d.current?.scope===c?d.current:null;if(u&&u.action!==e)throw Error(`Resolve the retained uncertain action before choosing another action.`);if(!u){let i=await a(`candidate:control`,{teamId:t,actorId:n,projectId:r,id:s.id,action:e,expectedRevision:s.revision,requestHash:s.requestHash});p(),u={scope:c,id:s.id,action:e,control:{operationId:i.id,expectedRevision:s.revision,requestHash:s.requestHash},acknowledge:i.acknowledge},d.current=u}let h=await l.control(t,u.id,u.action,u.control);if(p(),h.ownerUserId!==n)throw Error(`The candidate owner changed.`);_({scope:c,value:h}),await u.acknowledge(),p(),d.current=null,h.experimentId&&o(h.experimentId)}catch(e){u.current===s&&y(e instanceof Error?e.message:`Candidate evaluation could not proceed.`)}finally{u.current===s&&x(!1)}}return(0,$.jsxs)(`section`,{children:[(0,$.jsxs)(`label`,{children:[`Trained version`,(0,$.jsxs)(`select`,{disabled:b||!!S,value:m,onChange:e=>h(e.target.value),children:[(0,$.jsx)(`option`,{value:``,children:`Select owned trained artifact`}),f?.scope===c?f.items.map(e=>(0,$.jsxs)(`option`,{value:e.artifact.id,children:[e.artifact.id,` / `,e.artifact.contentHash.slice(0,12),e.reason?` / ${e.reason}`:``]},e.artifact.id)):null]})]}),v?(0,$.jsx)(X,{error:v}):null,S?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{role:`status`,children:[[`preparing`,`dispatching`,`submitted`,`cleaning`].includes(S.state)?(0,$.jsx)(`span`,{className:`hosted-training-spinner`,"aria-hidden":`true`}):null,S.state,S.reason?` / ${S.reason}`:``]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Frozen evaluation setup`}),(0,$.jsx)(`pre`,{children:JSON.stringify(S.request.configuration,null,2)})]}),i&&JSON.stringify(i)!==JSON.stringify(S.request.configuration)?(0,$.jsx)(`p`,{children:`The parent setup changed. This preparation retains the reviewed setup shown here.`}):null]}):null,(0,$.jsxs)(`div`,{children:[d.current?.scope===c?(0,$.jsxs)(`button`,{type:`button`,disabled:b,onClick:()=>void C(d.current.action),children:[`Retry retained `,d.current.action,` action`]}):null,!S||[`configured`,`preparing`].includes(S.state)?(0,$.jsx)(`button`,{type:`button`,disabled:b||!i||!m,onClick:()=>void C(`prepare`),children:`Prepare exact version for evaluation`}):null,S&&[`ready`,`dispatching`].includes(S.state)?(0,$.jsx)(`button`,{type:`button`,disabled:b,onClick:()=>void C(`run`),children:`Run Experiment`}):null,S&&![`completed`,`failed`,`cancelled`].includes(S.state)?(0,$.jsx)(`button`,{type:`button`,disabled:b,onClick:()=>void C(`cancel`),children:`Cancel evaluation`}):null]})]})}var yy=F(z({id:U(),name:U(),providerId:L(`custom-openai-compatible`),configurationHash:U().regex(/^[a-f0-9]{64}$/),contextWindow:V().int().positive(),outputLimit:V().int().positive()}).strict());function by({api:e,policy:t,onChange:n}){let[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(0);(0,Q.useEffect)(()=>{let t=new AbortController;return i([]),o(null),e.local(`localInferenceChoices`,{},t.signal).then(e=>{t.signal.aborted||i(yy.parse(e))}).catch(e=>{t.signal.aborted||o(e.message)}),()=>t.abort()},[e.key,s]);let l=t.kind===`hosted_chat`&&t.localRuntime?.providerId===`custom-openai-compatible`?t.localRuntime:void 0;return(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h3`,{children:`Local inference`}),(0,$.jsx)(`p`,{children:`Select the configured loopback OpenAI-compatible endpoint. Reported tokens are retained; monetary cost remains unknown. Starting reserves your request allocation and sends no target request to OpenPond.`}),a?(0,$.jsx)(X,{error:a}):null,(0,$.jsxs)(`label`,{children:[`Local model`,(0,$.jsxs)(`select`,{value:l&&t.kind===`hosted_chat`?t.modelId:``,onChange:e=>{let i=r.find(t=>t.id===e.target.value);i&&t.kind===`hosted_chat`&&n({...t,modelId:i.id,localRuntime:{providerId:i.providerId,configurationHash:i.configurationHash,maximumRequestCostUsd:.001,requestTimeoutMs:9e4},maxOutputTokens:Math.min(t.maxOutputTokens,i.outputLimit),harness:void 0,candidate:void 0})},children:[(0,$.jsx)(`option`,{value:``,children:`Select local model`}),r.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>c(e=>e+1),children:`Refresh choices`}),!r.length&&!a?(0,$.jsx)(`p`,{children:`Configure the local provider in Settings and refresh its model catalog with context/output bounds before starting.`}):null,l&&t.kind===`hosted_chat`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[`Request allocation ($, reserved while measured cost is unknown)`,(0,$.jsx)(`input`,{type:`number`,min:1e-6,max:1e4,step:1e-6,value:l.maximumRequestCostUsd,onChange:e=>n({...t,localRuntime:{...l,maximumRequestCostUsd:Number(e.target.value)}})})]}),(0,$.jsxs)(`label`,{children:[`Request timeout (seconds)`,(0,$.jsx)(`input`,{type:`number`,min:1,max:300,value:l.requestTimeoutMs/1e3,onChange:e=>n({...t,localRuntime:{...l,requestTimeoutMs:Number(e.target.value)*1e3}})})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>{let{localRuntime:e,...r}=t;n(r)},children:`Use hosted model configuration`})]}):null]})}function xy({disabled:e=!1}){let t=kv(),n=t.startingModel?.source===`alphaedit`,r=t.startingModel?.source===`neuron_training`,i=n||r,a=t.startingModel?.source===`decision`,o=t.startingModel?.source===`engram`,s=t.startingModel?.source===`steering`,c=`This saved steering source requires a neuron steering experiment. Choose another starting model for this action.`;return(0,$.jsxs)(`label`,{children:[`Modification`,(0,$.jsx)(Z,{label:`Modification`,floating:!0,value:t.operationType,disabled:e,options:[{value:`alphaedit`,label:`AlphaEdit`,disabled:a||o||s||r||t.startingModel?.source===`trained`||!!t.trainingParent,description:`Edit facts using reviewed edit and preservation batches.`},{value:`selective_neuron_training`,label:`Neuron training`,disabled:i||a||o||s||t.startingModel?.source===`trained`||!!t.trainingParent,description:r?`The saved inference delta contains no optimizer state; choose a managed base explicitly for new training.`:`Select neuron columns from reviewed target and background domains.`},{value:`decision_model`,label:`Decision model`,disabled:i||o||s||t.startingModel?.source===`trained`||!!t.trainingParent,description:`Train or score typed decisions using an exact Decision adapter.`},{value:`evaluate`,label:`Evaluate`,disabled:i||a||o||s||!!t.trainingParent,description:s?c:t.trainingParent?`This draft retains a training checkpoint. Evaluate the trained version from its result.`:void 0},{value:`sft`,label:`SFT + LoRA`,disabled:i||a||o||s||!!t.trainingParent,description:s?c:t.trainingParent?`The current SFT worker starts from a pinned base; checkpoint continuation is unavailable.`:void 0},{value:`grpo`,label:`RL (GRPO) + LoRA`,disabled:i||a||o||s,description:s?c:void 0},{value:`neuron_steering`,label:`Neuron steering`,disabled:i||a||o||!!t.trainingParent,description:t.trainingParent?`The selected trained checkpoint has no qualified steering runtime.`:`Compile and review a bounded hosted execution; a qualified runtime is required.`},{value:`engram_adapter`,label:`Engram adapter`,disabled:i||a||s||t.startingModel?.source===`trained`||!!t.trainingParent,description:s?c:`Train a memory adapter from an exact qualified managed base and a reviewed supervised batch.`},{value:`inspect_activations`,label:`Inspect activations`,disabled:i||a||o||s||!!t.trainingParent,description:s?c:t.trainingParent?`The selected trained checkpoint has no qualified inspection runtime.`:`Compile and review a bounded hosted execution; a qualified runtime is required.`}].filter(e=>t.allowedOperationTypes.includes(e.value)),onChange:e=>t.setOperationType(e)})]})}function Sy({draft:e,patch:t,supportsSampling:n,profileSeeds:r,children:i}){let[a,o]=(0,Q.useState)(()=>e.mode!==`model`||!!e.localRuntime),s=e.mode===`model_harness_profile`,c=e.temperature!==void 0||e.topP!==void 0;return(0,$.jsxs)(`details`,{open:a,onToggle:e=>o(e.currentTarget.open),children:[(0,$.jsx)(`summary`,{children:`Advanced settings`}),s?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:`Profile execution uses its exact released model configuration and evaluation seeds. Its execution owner prepares those pins.`}),r?(0,$.jsxs)(`p`,{children:[`Released seeds: `,r.join(`, `)]}):null]}):(0,$.jsxs)($.Fragment,{children:[n||c?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:c,disabled:!n&&!c,onChange:e=>t(e.target.checked?{temperature:0,topP:1}:{temperature:void 0,topP:void 0})}),`Override sampling`]}),c?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[`Temperature`,(0,$.jsx)(`input`,{type:`number`,min:`0`,max:`2`,step:`0.1`,disabled:!n,value:e.temperature===null?``:e.temperature??0,onChange:e=>t({temperature:e.target.value===``?null:e.target.valueAsNumber})})]}),(0,$.jsxs)(`label`,{children:[`Top P`,(0,$.jsx)(`input`,{type:`number`,min:`0.01`,max:`1`,step:`0.01`,disabled:!n,value:e.topP===null?``:e.topP??1,onChange:e=>t({topP:e.target.value===``?null:e.target.valueAsNumber})})]}),n?null:(0,$.jsx)(`p`,{children:`This model does not support sampling overrides. Clear the override to continue.`})]}):null]}):null,(0,$.jsxs)(`label`,{children:[`Maximum output tokens`,(0,$.jsx)(`input`,{type:`number`,min:`1`,max:`4096`,value:e.outputTokens??``,onChange:e=>t({outputTokens:e.target.value===``?null:e.target.valueAsNumber})})]}),(0,$.jsxs)(`label`,{children:[`Environment seeds`,(0,$.jsx)(`input`,{inputMode:`text`,value:e.seed,onChange:e=>t({seed:e.target.value})}),(0,$.jsx)(`small`,{children:`Separate seeds with commas. Unchanged existing membership keeps each original task and seed pair.`})]}),(0,$.jsxs)(`label`,{children:[`System instructions`,(0,$.jsx)(`textarea`,{value:e.prompt,onChange:e=>t({prompt:e.target.value}),rows:6})]}),e.mode===`model_harness`?(0,$.jsx)(`p`,{children:`Released Harness instructions are immutable; additional system instructions must be empty.`}):null]}),i]})}function Cy({api:e,draft:t,patch:n,sources:r}){let i=r.targets.filter(e=>e.target.kind===`agent`),a=r.targets.filter(e=>e.target.kind===`harness`);return(0,$.jsxs)(ft,{title:`Execution`,children:[(0,$.jsxs)(`label`,{children:[`Execution selection`,(0,$.jsx)(Z,{label:`Execution selection`,value:t.mode,floating:!0,options:[{value:`model`,label:`Model only`},{value:`model_harness`,label:`Model + Harness`},{value:`model_harness_profile`,label:`Model + Harness + Profile`}],onChange:e=>n({mode:e,targetId:`model`,sourceId:``,profileChoiceId:``})})]}),t.mode===`model_harness`?(0,$.jsxs)(`label`,{children:[`Released Harness`,(0,$.jsx)(Z,{label:`Released Harness`,searchable:!0,floating:!0,value:t.sourceId||(e.location===`hosted`&&r.selected?.target.kind===`agent`?`target:${t.targetId}`:``),options:[{value:``,label:`Choose released Harness`},...e.location===`local`?(r.local.data?.harnesses??[]).map(e=>({value:e.id,label:e.name})):[...r.retainedHostedSource&&!r.hostedHarnesses.some(e=>e.id===t.sourceId)?[{value:t.sourceId,label:`Retained Harness · ${r.retainedHostedSource.harnessRelease.id}`}]:[],...r.hostedHarnesses.map(e=>({value:e.id,label:e.name,disabled:!e.ready,description:e.ready?void 0:e.reason??void 0})),...i.map((e,t)=>({value:`target:${e.id}`,label:e.name,description:`Project target`,separatorBefore:t===0}))]],onChange:e=>n(e.startsWith(`target:`)?{sourceId:``,targetId:e.slice(7)}:{sourceId:e,targetId:``})})]}):null,t.mode===`model_harness_profile`?(0,$.jsxs)(`label`,{children:[`Released Profile evaluation`,(0,$.jsx)(Z,{label:`Released Profile evaluation`,searchable:!0,floating:!0,value:e.location===`local`?r.profile?.id??t.profileChoiceId:t.targetId,options:[{value:``,label:`Choose compatible Profile evaluation`},...(e.location===`local`?r.compatibleProfiles:a).map(e=>({value:e.id,label:e.name}))],onChange:t=>n(e.location===`local`?{profileChoiceId:t}:{targetId:t})})]}):null,r.harnessSource?(0,$.jsxs)(`dl`,{children:[(0,$.jsx)(`dt`,{children:`Harness release`}),(0,$.jsxs)(`dd`,{children:[r.harnessSource.harnessRelease.id,` ·`,` `,r.harnessSource.harnessRelease.contentHash]}),(0,$.jsx)(`dt`,{children:`Agent snapshot`}),(0,$.jsxs)(`dd`,{children:[r.harnessSource.agentSnapshot.id,` ·`,` `,r.harnessSource.agentSnapshot.contentHash]}),(0,$.jsx)(`dt`,{children:`Source package`}),(0,$.jsx)(`dd`,{children:r.harnessSource.sourcePackageHash})]}):null,r.profile?(0,$.jsxs)(`dl`,{children:[(0,$.jsx)(`dt`,{children:`Profile`}),(0,$.jsxs)(`dd`,{children:[r.profile.profileRef.profileId,` · `,r.profile.sourceRevision]}),(0,$.jsx)(`dt`,{children:`Harness release`}),(0,$.jsxs)(`dd`,{children:[r.profile.harnessRelease.id,` · `,r.profile.harnessRelease.contentHash]}),(0,$.jsx)(`dt`,{children:`Evaluation definition`}),(0,$.jsxs)(`dd`,{children:[r.profile.definitionId,` · `,r.profile.definitionHash]})]}):null,r.profileTarget?(0,$.jsxs)(`dl`,{children:[(0,$.jsx)(`dt`,{children:`Profile`}),(0,$.jsxs)(`dd`,{children:[r.profileTarget.source.profileId,` · `,r.profileTarget.source.sourceRevision]}),(0,$.jsx)(`dt`,{children:`Harness release`}),(0,$.jsxs)(`dd`,{children:[r.profileTarget.source.harnessRelease.id,` ·`,` `,r.profileTarget.source.harnessRelease.contentHash]}),(0,$.jsx)(`dt`,{children:`Evaluation definition`}),(0,$.jsxs)(`dd`,{children:[r.profileTarget.source.definitionId,` ·`,` `,r.profileTarget.source.definitionHash]})]}):null,r.unavailable&&r.saved?.kind===`hosted_chat`&&r.saved.harness?(0,$.jsxs)(`p`,{children:[`Retained Harness: `,r.saved.harness.harnessRelease.id,` ·`,` `,r.saved.harness.harnessRelease.contentHash,`. Source package:`,` `,r.saved.harness.sourcePackageHash,`.`]}):null,r.unavailable&&r.saved?.kind===`hosted_harness`?(0,$.jsxs)(`p`,{children:[`Retained Profile: `,r.saved.source.profileId,` · `,r.saved.source.sourceRevision,`. Harness: `,r.saved.source.harnessRelease.id,` ·`,` `,r.saved.source.harnessRelease.contentHash,`.`]}):null,e.location===`local`&&r.local.isPending?(0,$.jsx)(`p`,{role:`status`,children:`Loading authorized local sources…`}):null,r.local.error?(0,$.jsx)(X,{error:r.local.error.message,children:(0,$.jsx)(`button`,{type:`button`,onClick:()=>void r.local.refetch(),children:`Retry source discovery`})}):null,r.unavailable?(0,$.jsx)(X,{error:r.unavailable}):null,e.location===`hosted`&&t.mode===`model_harness`?(0,$.jsxs)($.Fragment,{children:[r.hosted.isPending?(0,$.jsx)(`p`,{role:`status`,children:`Loading published Harness sources…`}):null,r.hosted.error?(0,$.jsx)(X,{error:r.hosted.error.message,children:(0,$.jsx)(`button`,{type:`button`,onClick:()=>void r.hosted.refetch(),children:`Retry source discovery`})}):null,r.hosted.hasNextPage?(0,$.jsx)(`button`,{type:`button`,disabled:r.hosted.isFetchingNextPage,onClick:()=>void r.hosted.fetchNextPage(),children:`Load more Harness sources`}):null,!r.hosted.isPending&&!r.hosted.error&&!r.hostedHarnesses.length?(0,$.jsx)(`p`,{children:`Publish a complete released Harness source in this workspace to select it here.`}):null]}):null]})}function wy(e,t,n,r){let i=S({queryKey:[`evaluation-workspace`,e.key,`localSources`],enabled:e.location===`local`,queryFn:async({signal:t})=>il.parse(await e.local(`sourceChoices`,{},t))}),a=A({queryKey:[`evaluation-workspace`,e.key,`harnessSources`],enabled:e.location===`hosted`&&n.mode===`model_harness`,initialPageParam:void 0,queryFn:async({pageParam:t,signal:n})=>cc.parse(await e.request(`harnessSources`,{cursor:t},n)),getNextPageParam:e=>e.nextCursor??void 0}),o=a.data?.pages.flatMap(e=>e.items).map(e=>({...e,id:`harness-${e.source.harnessRelease.contentHash}`}))??[],s=t?.projects.projects.find(t=>t.id===e.projectId)?.content.targets??[],c=s.find(e=>e.id===n.targetId),l=r?.request.policy,u=e.location===`local`?i.data?.harnesses.find(e=>e.id===n.sourceId):void 0,d=e.location===`hosted`?o.find(e=>e.id===n.sourceId&&e.ready):void 0,f=e.location===`hosted`&&l?.kind===`hosted_chat`&&l.harness&&n.sourceId===`harness-${l.harness.harnessRelease.contentHash}`&&!o.some(e=>e.id===n.sourceId)?l.harness:void 0,p=i.data?.profiles.filter(e=>e.taskset.id===n.release?.id&&e.taskset.contentHash===n.release.contentHash)??[],m=e.location===`local`?p.find(e=>e.id===n.profileChoiceId||!n.profileChoiceId&&l?.kind===`hosted_harness`&&e.profileRef.repositoryId===l.profileRepositoryId&&e.profileRef.profileId===l.source.profileId&&e.definitionHash===l.source.definitionHash&&ie(e.harnessRelease)===ie(l.source.harnessRelease)):void 0,h=n.mode===`model_harness`?e.location===`local`?u?.source:d?.source??f??(c?.target.kind===`agent`?c.target.source:void 0):void 0,g=n.mode===`model_harness_profile`&&c?.target.kind===`harness`?c.target:void 0;return{local:i,hosted:a,hostedHarnesses:o,retainedHostedSource:f,targets:s,selected:c,compatibleProfiles:p,profile:m,profileTarget:g,harnessSource:h,unavailable:n.mode===`model_harness`&&!h?`The exact Harness is unavailable or unsupported in this account, workspace and execution location. Choose an authorized released Harness.`:n.mode===`model_harness_profile`&&(e.location===`local`?!m:!g)?`The exact Profile composition is unavailable or incompatible with this Dataset. Choose its compatible released Profile evaluation.`:null,saved:l}}var Ty=[`input`,`output`,`expectedOutput`,`evaluatorContext`];function Ey({value:e,onChange:t}){let n=it.safeParse(e),r=(n,r)=>t(e.map((e,t)=>t===n?{...e,...r}:e));return(0,$.jsxs)(`fieldset`,{children:[(0,$.jsx)(`legend`,{children:`Grader field mappings`}),(0,$.jsx)(`p`,{children:`Mappings apply only to grading evidence. Private reference answers stay in the server’s evaluator context.`}),e.map((n,i)=>(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`label`,{children:[`Read from`,(0,$.jsx)(`select`,{value:n.source,onChange:e=>r(i,{source:e.target.value}),children:Ty.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))})]}),(0,$.jsxs)(`label`,{children:[`Source path`,(0,$.jsx)(`input`,{value:n.sourcePath.join(`.`),onChange:e=>r(i,{sourcePath:e.target.value?e.target.value.split(`.`):[]}),placeholder:`Empty path reads the whole selected value`})]}),(0,$.jsxs)(`label`,{children:[`Write to`,(0,$.jsx)(`select`,{value:n.destination,onChange:e=>r(i,{destination:e.target.value}),children:Ty.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))})]}),(0,$.jsxs)(`label`,{children:[`Destination path`,(0,$.jsx)(`input`,{value:n.path.join(`.`),onChange:e=>r(i,{path:e.target.value.split(`.`)}),required:!0})]}),(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,onClick:()=>t(e.filter((e,t)=>t!==i)),children:`Remove mapping`})]},i)),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>t([...e,{source:`output`,sourcePath:[`text`],destination:`output`,path:[`answer`]}]),children:`Add field mapping`}),n.success?null:(0,$.jsx)(X,{error:n.error.issues[0]?.message})]})}function Dy({graders:e,selected:t,onChange:n,onOpenGrader:r}){return(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h3`,{children:`Graders and field mappings`}),(0,$.jsx)(`p`,{children:`Select up to 100 exact released graders. Map Dataset and retained output fields when their schemas differ.`}),Dc(e).map(({key:e,grader:i,aliases:a})=>{let o=e=>a.some(t=>t.id===e.id&&t.version===e.version&&t.contentHash===e.contentHash),s=t.find(o);return(0,$.jsxs)(`details`,{children:[(0,$.jsxs)(`summary`,{children:[(0,$.jsxs)(`label`,{className:`evaluation-model-badge`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:!!s,onChange:e=>n(e.target.checked?[...t,{id:i.id,version:i.version,contentHash:i.contentHash,mappings:[]}]:t.filter(e=>!o(e)))}),` `,i.name??`Grader name unavailable`,` · Version`,` `,i.release?.revision??i.version]}),i.release&&r?(0,$.jsx)(`button`,{type:`button`,className:`evaluation-model-badge`,onClick:e=>{e.preventDefault(),r(i.release.id)},children:`Open grader`}):null]}),(0,$.jsxs)(`p`,{children:[`Feedback key: `,(0,$.jsx)(`code`,{children:i.feedbackKey})]}),(0,$.jsx)(`p`,{children:i.release?`${i.release.id} · Revision ${i.release.revision}`:`Dataset-owned grader`}),(0,$.jsx)(`code`,{children:i.release?.contentHash??i.contentHash}),(0,$.jsxs)(`p`,{children:[`Package `,a.length>1?`aliases`:`grader`,`:`,` `,a.map(e=>`${e.id} (version ${e.version}, ${e.contentHash})`).join(`; `)]}),s?(0,$.jsx)(Ey,{value:s.mappings,onChange:e=>n(t.map(t=>o(t)?{...t,mappings:e}:t))}):null]},e)})]})}var Oy=e=>JSON.stringify([e.id,e.revision,e.contentHash]);function ky({api:e,value:t,onChange:n,disabled:r,localChoices:i=[],localLoading:a=!1}){let[o,s]=(0,Q.useState)(),c=S({queryKey:[`evaluation-workspace`,e.key,`released-dataset-picker`,o],queryFn:({signal:t})=>e.request(`catalogDatasets`,{limit:100,...o?{afterId:o}:{}},t)}),l=i.find(e=>t!==null&&Oy(e.taskset)===Oy(t)),u=S({queryKey:[`evaluation-workspace`,e.key,`resolveDataset`,t?.contentHash],enabled:!!t&&!l&&!a,queryFn:({signal:n})=>e.request(`resolveDataset`,{release:t},n)}),d=[...i.map(e=>({id:e.id,name:e.name,release:e.taskset,taskCount:e.taskCount})),...u.data?[u.data]:[],...c.data?.items??[]].filter((e,t,n)=>n.findIndex(t=>Oy(t.release)===Oy(e.release))===t);return(0,$.jsxs)(`section`,{children:[(0,$.jsxs)(`label`,{children:[`Dataset version`,(0,$.jsx)(Z,{label:`Dataset version`,floating:!0,searchable:!0,disabled:r,value:t?Oy(t):``,options:[{value:``,label:`Choose a published dataset`},...t&&!d.some(e=>Oy(e.release)===Oy(t))?[{value:Oy(t),label:`${t.id} / Revision ${t.revision}`,disabled:!0}]:[],...d.map(e=>({value:Oy(e.release),label:`${e.name} / Revision ${e.release.revision} / ${e.taskCount} tasks`}))],onChange:e=>n(d.find(t=>Oy(t.release)===e)?.release??null)})]}),c.error??u.error?(0,$.jsx)(X,{error:c.error??u.error}):null,o?(0,$.jsx)(`button`,{type:`button`,onClick:()=>s(void 0),children:`First dataset page`}):null,c.data?.nextCursor?(0,$.jsx)(`button`,{type:`button`,onClick:()=>s(c.data.nextCursor),children:`More dataset versions`}):null,t?(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact Dataset release`}),(0,$.jsxs)(`p`,{children:[t.id,` / Revision `,t.revision]}),(0,$.jsx)(`code`,{children:t.contentHash})]}):null]})}function Ay(e,t,n,r=!0){return S({queryKey:[`evaluation-workspace`,e.key,`setup-population`,t?.contentHash,n],enabled:!!t&&r,queryFn:async({signal:r})=>{let i=[],a,o=null;do{let s=n?await e.local(`sourceDataset`,{id:n,view:`ids`,limit:1e4,...a?{afterId:a}:{}},r):await e.request(`datasetPopulation`,{release:t,view:`ids`,limit:1e4,...a?{afterId:a}:{}},r);if(s.taskCount>1e4)throw Error(`Choose a Dataset version with at most 10,000 tasks for one Experiment.`);if(o&&(s.taskCount!==o.taskCount||JSON.stringify(s.graders)!==JSON.stringify(o.graders)))throw Error(`The released Dataset population changed between pages.`);if(o??=s,i.push(...s.items),s.nextCursor&&s.nextCursor===a)throw Error(`Dataset population cursor did not advance.`);a=s.nextCursor??void 0}while(a);if(!o||i.length!==o.taskCount)throw Error(`Dataset population is incomplete.`);return{...o,items:i}}})}function jy(e){let t=[...new Set(e.seedText.split(/[\s,]+/).filter(Boolean))];if(!t.length||t.some(e=>!/^(0|[1-9][0-9]*)$/.test(e)||Number(e)>2147483647))throw Error(`Enter integer environment seeds from 0 to 2147483647, separated by commas.`);let n=new Set(e.taskIds),r=e.existing,i=r?[...new Set(r.request.population.map(e=>e.seed))]:[];if(r?.request.policy.kind===`hosted_chat`&&r.request.taskset.id===e.release.id&&r.request.taskset.revision===e.release.revision&&r.request.taskset.contentHash===e.release.contentHash&&JSON.stringify(t)===JSON.stringify(i))return r.request.population.filter(e=>n.has(e.taskId));if(n.size*t.length>1e4)throw Error(`One Experiment can contain at most 10,000 task/seed members.`);return[...n].flatMap(n=>t.map(t=>({receiptId:e.createReceiptId(n,t),taskId:n,seed:t,fixtureId:null})))}function My(e,t){let{registerTransitionGuard:n}=kv(),r=(0,Q.useRef)(e);r.current=e,(0,Q.useEffect)(()=>t?n(e=>r.current.requestLeave(e)):void 0,[t,n])}function Ny({api:e,inventory:t,route:n,navigate:r,onSaved:i,dispatch:a,onClose:o,onSaveDraft:s}){let c=kv(),l=c.draft,{name:u,release:d,modelId:f,prompt:p,seed:m}=l,h=l.budget??NaN,g=l.outputTokens??NaN,_=c.existing,v=e.location===`local`&&l.mode===`model`?l.localRuntime:void 0,y=e=>c.setDraft(t=>t&&{...t,...e}),b=t?.projects.projects.find(t=>t.id===e.projectId),x=wy(e,t,l,_),C=l.mode===`model_harness_profile`,w=x.unavailable,[T,E]=(0,Q.useState)(null),[D,O]=(0,Q.useState)(null),[k,A]=(0,Q.useState)(null),[j,M]=(0,Q.useState)(!1),[N,P]=(0,Q.useState)(!1),F=(0,Q.useRef)(!1),I=(0,Q.useRef)(null),L=x.local.data?.profiles.find(e=>e.taskset.id===d?.id&&e.taskset.contentHash===d.contentHash),ee=e.location!==`local`||l.mode===`model`||x.local.isSuccess,R=Ay(e,d,L?.id,ee),z=R.data?Dc(R.data.graders):[],B=d?l.graderChoices[d.contentHash]??(_?.request.taskset.contentHash===d.contentHash?_.graders.map(e=>({id:e.id,version:e.version,contentHash:e.contentHash,mappings:e.mappings??[]})):z.length<=100?z.map(({grader:e})=>({id:e.id,version:e.version,contentHash:e.contentHash,mappings:[]})):[]):[],V=null,H=B;if(R.data)try{H=Oc(B.map(e=>{let t=R.data.graders.find(t=>t.id===e.id&&t.version===e.version&&t.contentHash===e.contentHash);if(!t)throw Error(`A selected grader is no longer in this exact Dataset release. Choose its released grader again.`);return{...t,mappings:e.mappings}})).map(({id:e,version:t,contentHash:n,mappings:r})=>({id:e,version:t,contentHash:n,mappings:r}))}catch(e){V=e instanceof Error?e.message:String(e)}let U=S({queryKey:[`evaluation-workspace`,e.key,`modelChoices`,d?.contentHash],enabled:!!d&&!L&&ee,queryFn:({signal:t})=>e.request(`modelChoices`,{taskset:d},t)}),te=S({queryKey:[`evaluation-workspace`,e.key,`samplingModels`],queryFn:({signal:t})=>e.request(`graderModels`,{},t)}),ne=d&&!L?U.data?.models:te.data?.models,re=te.data?.models.find(e=>e.id===f)?.supportsSampling===!0,W=S({queryKey:[`evaluation-workspace`,e.key,`resolveDataset`,d?.contentHash],enabled:!!d&&!L&&ee,queryFn:({signal:t})=>e.request(`resolveDataset`,{release:d},t)}),G=iy({name:`Experiment setup`,dirty:c.evaluationDirty||c.operationDraftDirty,busy:j,onLeave:c.close,retainForDestination(t){let n=po(new URL(t,window.location.origin));return!(!n||![`datasets`,`graders`,`experiments`].includes(n.page)||n.collection===`drafts`&&n.resourceId!==c.initialExperiment?.id||(n.projectId??null)!==e.projectId||(n.executionLocation??`hosted`)!==e.location)}});My(G,c.operationType===`evaluate`);function ae(){if(!d||!W.data&&!L)return;if(L){G.allowNextNavigation(),r({...n,page:`datasets`,resourceId:L.id,datasetKind:`release`,revision:d.revision,contentHash:d.contentHash,detailTab:`tasks`,executionId:null,passId:null,after:null,query:``});return}let e=c.reviewRoute;G.allowNextNavigation(),r(e?{...e,detailTab:`tasks`,after:null}:{...n,page:`datasets`,resourceId:W.data.id,datasetKind:`release`,revision:d.revision,contentHash:d.contentHash,detailTab:`tasks`,collection:`default`,executionId:null,passId:null,after:null,query:``})}let K=e.location===`local`?e.localOperation:e.operation;async function q(){if(F.current)throw Error(`Experiment setup is already preparing.`);F.current=!0,M(!0),E(null);try{if(c.startingModel?.source===`steering`)throw Error(`This evaluation owner cannot apply the saved steering profile. Choose another starting model or use neuron steering.`);if(c.startingModel?.source===`trained`)throw Error(`Evaluate this exact checkpoint through trained-version preparation. Its base model is not a substitute.`);if(!u.trim())throw Error(`Name this Experiment.`);if(ue)throw Error(ue);if(w)throw Error(w);if(V)throw Error(V);if(l.mode===`model_harness`&&p.trim())throw Error(`Released Harness instructions are immutable. Clear the additional system instructions before running this composition.`);if(!C&&((l.temperature??0)!==0||(l.topP??1)!==1)&&!re)throw Error(`This model does not support sampling overrides. Clear them in Advanced settings or choose a supported model.`);let t,n=b?{id:b.id,revision:b.revision,contentHash:ie(b.content),targetId:l.mode===`model`?null:x.selected?.id??null}:void 0;if(C){let r=x.profile,i=x.profileTarget,a=e.location===`local`?r:i;if(!a)throw Error(`Choose an authorized compatible Profile evaluation.`);let o=await K(`prepareHarness`,{target:a,modelId:f,budget:h}),s=e.location===`local`&&r?{operationId:o.id,profileRepositoryId:r.profileRef.repositoryId,definitionId:r.definitionId,profileRef:r.profileRef,profileSource:{sourceRevision:r.sourceRevision,harnessRelease:r.harnessRelease},modelId:f,maximumCostUsd:h}:{operationId:o.id,profileRepositoryId:i.profileRepositoryId,definitionId:i.source.definitionId,modelId:f,maximumCostUsd:h},l=e.location===`local`?await e.local(`prepareHarness`,s):await e.request(`prepareHarness`,s);if(!d||l.request.taskset.id!==d.id||l.request.taskset.contentHash!==d.contentHash)throw Error(`This Profile evaluation is bound to a different Dataset release. Choose its exact compatible Dataset.`);if(l.request.population.some(e=>!c.selected(d,e.taskId)))throw Error(`This Profile evaluation requires all of its declared tasks and seeds. Restore its full task selection before running.`);if(R.data?.items.some(e=>c.selected(d,e.id)&&!l.request.population.some(t=>t.taskId===e.id)))throw Error(`This Profile evaluation supports only its declared task set. Review tasks and select exactly that set.`);t={...l.request,name:u.trim(),...n?{project:n}:{}}}else{if(!R.data||!d)throw Error(`Select a published Dataset version.`);let r=R.data.items.filter(e=>c.selected(d,e.id));if(!r.length)throw Error(`Select at least one task in the Dataset Tasks table.`);let i=jy({existing:_,release:d,taskIds:r.map(e=>e.id),seedText:m,createReceiptId:(t,n)=>`evaluation-${ie([e.key,u,d.contentHash,f,p,t,n]).slice(0,32)}`});if(!H.length||H.length>100)throw Error(`Select between one and 100 Dataset graders.`);if(!v&&!ne?.some(e=>e.id===f))throw Error(U.data?.unavailableReason??`Choose a supported hosted model.`);t={schemaVersion:`openpond.modelTasksetRunRequest.v1`,operationId:(await K(`setup`,{name:u,release:d,modelId:f,prompt:p,seed:m,taskIds:r.map(e=>e.id)})).id,teamId:e.teamId,modelProjectId:null,name:u.trim(),...n?{project:n}:{},taskset:d,policy:{kind:`hosted_chat`,...v?{localRuntime:v}:{},modelId:f,maxOutputTokens:g,temperature:l.temperature??0,topP:l.topP??1,...x.harnessSource?{harness:x.harnessSource}:{},...p.trim()?{messages:[{role:`system`,content:p}]}:{}},population:i}}let r={request:t,maximumCostUsd:h,graders:H,..._?{sourceExperimentId:_.id}:{}},i=await K(`run`,r),a=Ts.parse({...r,operationId:i.id,request:{...t,operationId:i.id}});return I.current=i,a}catch(e){throw E(e instanceof Error?e.message:String(e)),e}finally{F.current=!1,M(!1)}}async function oe(){try{let e=ce,t=await q();O({key:e,configuration:t}),A(e)}catch{}}async function se(){if(!(F.current||D?.key!==ce)){F.current=!0,M(!0),E(null);try{let t=D.configuration,n=t.request,r=I.current;if(!r||r.id!==t.operationId)throw Error(`The reviewed operation changed. Review this setup again.`);let o=a?(await a(t,r.id)).id:e.location===`local`?Uc.parse(await e.local(`runFromRelease`,zc.parse({configuration:t,..._?.packageHash&&_.request.taskset.contentHash===n.taskset.contentHash?{expectedPackageHash:_.packageHash}:{}}))).id:(await e.request(`run`,t)).summary.id;await r.acknowledge(),G.allowNextNavigation(),c.close(),i({id:o})}catch(e){E(e instanceof Error?e.message:String(e))}finally{F.current=!1,M(!1)}}}let ce=JSON.stringify({draft:l,graders:H,project:e.projectId,location:e.location,population:R.data?.items.filter(e=>d&&c.selected(d,e.id)).map(e=>e.id)}),le=d&&R.data?R.data.items.filter(e=>c.selected(d,e.id)).length:0,ue=null;try{if(!u.trim())throw Error(`Name this Experiment before reviewing.`);if(!d||!R.data||R.isFetching||R.error)throw Error(`Choose an exact Dataset version and wait for its complete task population.`);if(!ee||w)throw Error(w??`Wait for the authorized source choices.`);if(!v&&!ne?.some(e=>e.id===f))throw Error(`Choose a model from the authorized current catalog.`);if(!Number.isFinite(h)||h<=0||h>1e4)throw Error(`Set a whole Experiment ceiling greater than zero and at most $10,000.`);if(V||!H.length||H.length>100)throw Error(V??`Select between one and 100 released graders.`);let e=R.data.items.filter(e=>c.selected(d,e.id)).map(e=>e.id);if(!e.length)throw Error(`Select at least one Dataset task.`);if(C){if(x.profile&&(e.length!==x.profile.taskIds.length||x.profile.taskIds.some(t=>!e.includes(t))))throw Error(`This released Profile check evaluates exactly its declared task and seed set. Restore that selection before reviewing.`)}else{if(!Number.isInteger(g)||g<1||g>4096)throw Error(`Set maximum output tokens between one and 4096.`);let t=l.temperature??0,n=l.topP??1;if(l.temperature===null||l.topP===null||!Number.isFinite(t)||t<0||t>2||!Number.isFinite(n)||n<=0||n>1)throw Error(`Use valid sampling settings in Advanced.`);if((t!==0||n!==1)&&!re)throw Error(`Clear unsupported sampling overrides in Advanced.`);if(l.mode===`model_harness`&&p.trim())throw Error(`Released Harness instructions are immutable. Clear additional instructions in Advanced.`);jy({existing:_,release:d,taskIds:e,seedText:m,createReceiptId:(e,t)=>`${e}:${t}`})}}catch(e){ue=e instanceof Error?e.message:String(e)}async function de(){if(s&&c.initialExperiment&&!F.current){F.current=!0,M(!0),P(!0),E(null);try{let t={...l,...d?{graderChoices:{...l.graderChoices,[d.contentHash]:B}}:{}};c.setDraft(e=>e===l?t:e),await s(Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:c.initialExperiment.id,operationType:`evaluate`,name:u.trim()||`Evaluation`,...c.startingModel?{startingModel:c.startingModel}:{},evaluationForm:{form:t,selection:c.selection,source:_,executionLocation:e.location}}))}catch(e){E(e instanceof Error?e.message:String(e))}finally{F.current=!1,M(!1),P(!1)}}}return(0,$.jsxs)(Bv,{label:`Experiment setup`,action:`experiment`,onRequestClose:()=>void G.requestLeave(()=>{c.close(),o?.()}),children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`h2`,{children:_?`Run another Experiment`:`Run Experiment`}),o?(0,$.jsx)(`button`,{type:`button`,disabled:j,onClick:()=>void G.requestLeave(()=>{c.close(),o()}),children:`Close setup`}):null]}),(0,$.jsxs)(`form`,{noValidate:!0,onSubmit:e=>{e.preventDefault(),ue?E(ue):k===ce?se():oe()},children:[(0,$.jsxs)(ft,{title:`Model and budget`,children:[(0,$.jsxs)(`label`,{children:[`Model`,(0,$.jsx)(Z,{label:`Model`,value:f,disabled:!!v,searchable:!0,floating:!0,options:[{value:``,label:`Choose model`},...f&&!ne?.some(e=>e.id===f)?[{value:f,label:fe(te.data?.models.find(e=>e.id===f)?.name??f),disabled:!0}]:[],...(ne??[]).map(e=>({value:e.id,label:fe(e.name)}))],onChange:e=>y({modelId:e,localRuntime:void 0})})]}),!v&&L&&te.isSuccess&&!te.data.models.length?(0,$.jsx)(`p`,{role:`status`,children:`No models are available for this account. Choose a configured local provider below.`}):!v&&!L&&U.isSuccess&&(!U.data.available||!U.data.models.length)?(0,$.jsx)(`p`,{role:`status`,children:U.data.unavailableReason??`No models are available for this Dataset and account.`}):null,(0,$.jsx)(xy,{disabled:j}),(0,$.jsxs)(`label`,{children:[`Whole execution budget ($)`,(0,$.jsx)(`input`,{type:`number`,min:`0.000001`,max:`10000`,step:`0.000001`,value:l.budget??``,onChange:e=>y({budget:e.target.value===``?null:e.target.valueAsNumber}),required:!0})]})]}),(0,$.jsxs)(ft,{title:`Dataset`,children:[(0,$.jsx)(ky,{api:e,value:d,onChange:c.changeRelease,disabled:!1,localChoices:x.local.data?.profiles.filter(t=>!e.projectId||b?.content.resources.some(e=>e.kind===`dataset`&&e.release?.id===t.taskset.id&&e.release.contentHash===t.taskset.contentHash)),localLoading:!ee}),(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:j,onClick:()=>{G.allowNextNavigation(),r({...n,page:`datasets`,resourceId:null,datasetKind:void 0,detailTab:`tasks`,revision:void 0,contentHash:void 0,executionId:null,passId:null,after:null,query:``})},children:`Add Dataset`}),R.data&&d?(0,$.jsxs)(`p`,{children:[c.count(d,R.data.taskCount),` of `,R.data.taskCount,` tasks selected`,c.selection?.mode!==`subset`&&!c.selection?.ids.length?` / All tasks in this release`:``,` `,(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:!W.data&&!L||j,onClick:ae,children:`Review tasks`})]}):null]}),R.data?(0,$.jsx)(ft,{title:`Evaluation`,children:(0,$.jsx)(Dy,{graders:R.data.graders,onOpenGrader:e=>{G.allowNextNavigation(),r({...n,page:`graders`,resourceId:e,datasetKind:void 0,revision:void 0,contentHash:void 0,detailTab:`overview`,executionId:null,passId:null,after:null})},selected:B,onChange:e=>{d&&y({graderChoices:{...l.graderChoices,[d.contentHash]:e}})}})}):null,(0,$.jsxs)(Sy,{draft:l,patch:y,supportsSampling:re,profileSeeds:x.profile?.seeds,children:[e.location===`local`&&l.mode===`model`?(0,$.jsx)(by,{api:e,policy:{kind:`hosted_chat`,modelId:f,maxOutputTokens:g,temperature:l.temperature??0,topP:l.topP??1,...v?{localRuntime:v}:{}},onChange:e=>{e.kind===`hosted_chat`&&y({modelId:e.modelId,outputTokens:e.maxOutputTokens,localRuntime:e.localRuntime})}}):null,e.location===`local`&&l.mode===`model`?(0,$.jsx)(cy,{api:e,policy:{kind:`hosted_chat`,modelId:f,maxOutputTokens:g,temperature:l.temperature??0,topP:l.topP??1,...v?{localRuntime:v}:{}},onChange:e=>{e.kind===`hosted_chat`&&y({modelId:e.modelId,outputTokens:e.maxOutputTokens,localRuntime:e.localRuntime,temperature:e.temperature,topP:e.topP})}}):null,e.actorId&&!a&&!v?(0,$.jsx)(vy,{connection:e.connection,teamId:e.teamId,actorId:e.actorId,projectId:e.projectId,configuration:D?.key===ce?D.configuration:null,retainOperation:e.operation,onBusyChange:M,onStarted:e=>{G.allowNextNavigation(),c.close(),r({...n,page:`experiments`,resourceId:e,detailTab:`overview`,executionLocation:`hosted`,executionKind:void 0,passId:null,after:null,query:``,revision:void 0,contentHash:void 0,datasetKind:void 0})}}):null,(0,$.jsx)(Cy,{api:e,draft:l,patch:y,sources:x}),(0,$.jsx)(ft,{title:`Experiment`,children:(0,$.jsxs)(`label`,{children:[`Name`,(0,$.jsx)(`input`,{value:u,onChange:e=>y({name:e.target.value}),required:!0})]})})]}),k===ce&&!ue?(0,$.jsxs)(ft,{title:`Reviewed configuration`,children:[(0,$.jsxs)(`p`,{children:[le,` selected tasks /`,` `,(L?te.data?.models:U.data?.models)?.find(e=>e.id===f)?.name??(f||`Choose model`),` `,`/ $`,h,` whole-run ceiling`]}),(0,$.jsxs)(`p`,{children:[`Graders:`,` `,H.map(e=>R.data?.graders.find(t=>t.id===e.id&&t.version===e.version&&t.contentHash===e.contentHash)?.name??`Grader name unavailable`).join(`, `)||`No graders selected`]}),(0,$.jsx)(`p`,{children:`Start creates a new immutable Experiment after server admission. The original remains unchanged.`})]}):null,(0,$.jsxs)(`p`,{children:[e.location===`local`?`Local execution on this Desktop. Dataset bytes and private grading remain in its server. `:``,`Review this Dataset version, selected tasks, target, graders, and whole Experiment budget before starting.`]}),V?(0,$.jsx)(X,{error:V}):null,T||R.error||U.error||te.error||W.error?(0,$.jsx)(X,{error:T??R.error?.message??U.error?.message??te.error?.message??W.error?.message}):null,(0,$.jsx)(ay,{api:e,configuration:D?.key===ce?D.configuration:null}),s?(0,$.jsx)(`button`,{className:`training-button secondary`,type:`button`,disabled:j,onClick:()=>void de(),children:N?`Saving draft…`:`Save draft`}):null,(0,$.jsx)(`button`,{className:`training-button`,type:`submit`,disabled:j,children:j&&!N?k===ce?`Starting Experiment…`:`Reviewing Experiment…`:k===ce?`Start experiment`:`Review experiment`})]}),G.dialog]})}var Py={maxSteps:`Maximum optimizer steps`,learningRate:`Learning rate`,klFactor:`KL preservation weight`,latentWeightDecay:`Latent weight decay`,clampNormFactor:`Target norm clamp factor`,maxSequenceLength:`Maximum sequence tokens`,maxDurationSeconds:`Maximum duration (seconds)`,maxForwardTokenWork:`Maximum forward token work`,maxCheckpointBytes:`Maximum checkpoint bytes`,seed:`Seed`};function Fy({form:e,onChange:t}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:`Edit factual associations in the exact managed backbone. Preservation examples define the covariance used to constrain the weight update.`}),(0,$.jsxs)(`label`,{children:[`Rewrite layers (comma separated)`,(0,$.jsx)(`input`,{value:e.config.layers,maxLength:200,onChange:n=>t({...e,config:{...e.config,layers:n.target.value}})})]}),(0,$.jsxs)(`label`,{children:[`Loss layer`,(0,$.jsx)(`input`,{inputMode:`numeric`,value:e.config.lossLayer,maxLength:100,onChange:n=>t({...e,config:{...e.config,lossLayer:n.target.value}})})]}),(0,$.jsxs)(`label`,{children:[`Context template groups (JSON)`,(0,$.jsx)(`textarea`,{rows:4,value:e.config.contextTemplateGroups,maxLength:65536,onChange:n=>t({...e,config:{...e.config,contextTemplateGroups:n.target.value}})})]}),(0,$.jsxs)(`p`,{children:[`Each template contains one `,`{}`,` placeholder. The first group contains only the clean prompt template.`]}),(0,$.jsxs)(`label`,{children:[`Nullspace threshold`,(0,$.jsx)(`input`,{inputMode:`decimal`,value:e.config.nullspaceThreshold,maxLength:100,onChange:n=>t({...e,config:{...e.config,nullspaceThreshold:n.target.value}})})]}),(0,$.jsxs)(`label`,{children:[`L2 regularization`,(0,$.jsx)(`input`,{inputMode:`decimal`,value:e.config.l2,maxLength:100,onChange:n=>t({...e,config:{...e.config,l2:n.target.value}})})]}),Object.keys(Py).map(n=>(0,$.jsxs)(`label`,{children:[Py[n],(0,$.jsx)(`input`,{inputMode:`decimal`,value:e.training[n],maxLength:100,onChange:r=>t({...e,training:{...e.training,[n]:r.target.value}})})]},n))]})}function Iy(e,t){let n=Fn((n,r)=>{let[i,a]=n.split(`?`),o=new URLSearchParams(a);return o.set(`teamId`,e.teamId),Y(e.connection,`${i.replace(`/v1/training/experiment-drafts`,`/v1/training/setup/drafts`)}?${o}`,{...r,signal:t})});function r(t){if(!e.actorId||t.ownerUserId!==e.actorId||t.teamId!==e.teamId||e.projectId&&t.projectId!==e.projectId)throw Error(`The saved experiment belongs to another account or Project.`);return t}return{async get(t){return r(await n.getExperimentDraft(e.teamId,t))},async list(t={}){let i=await n.listExperimentDrafts(e.teamId,{...t,...e.projectId?{projectId:e.projectId}:{},limit:30});if(!e.actorId||i.ownerUserId!==e.actorId)throw Error(`The saved experiment list belongs to another account.`);return i.items.forEach(r),i},async save(e){let t=await n.saveExperimentDraft(e);return r(t.record),t}}}function Ly(e){let t=ra(e.connection);return(0,Q.useMemo)(()=>na(new pt({baseUrl:`https://desktop.openpond.invalid`,apiKey:`desktop-server-boundary`,scope:e.teamId,fetch:async(t,n)=>{let r=new URL(String(t)).pathname.split(`/`).at(-1);if(r!==`read`&&r!==`commands`)throw Error(`Unsupported workspace learning action.`);let i=await e.request(`learningRelay`,{endpoint:r,request:JSON.parse(String(n?.body))},n?.signal??void 0);return new Response(JSON.stringify(i),{status:200,headers:{"Content-Type":`application/json`}})}}),[`learning`,`hosted-evaluation-workspace`,t,e.key]),[e,t])}function Ry(e,t,n,r=[]){let i=Ly(e),a=A({queryKey:[`training-experiment-inputs`,e.accountKey,e.actorId,e.connection.serverUrl,e.teamId,e.projectId],enabled:t,initialPageParam:void 0,getNextPageParam:e=>e.nextCursor??void 0,queryFn:async({signal:t,pageParam:n})=>{let r=new URLSearchParams({teamId:e.teamId});e.projectId&&r.set(`projectId`,e.projectId),n&&r.set(`cursor`,n);let i=or.parse(await Y(e.connection,`/v1/training/setup/draft-inputs?${r}`,{signal:t}));if(i.teamId!==e.teamId||i.actorId!==e.actorId||i.projectId!==e.projectId||n&&i.nextCursor===n)throw Error(`Training inputs returned a different account, Project or cursor.`);return i}}),o=a.data?.pages[0],s=a.data?.pages.flatMap(e=>e.batches)??[],c=us({queries:[...new Map([n,...r].filter(e=>e!=null).map(e=>[e.contentHash,e])).values()].filter(e=>!s.some(t=>Se(t.reference,e))).map(e=>({queryKey:[...ta(i),`experiment-selected-batch`,e],enabled:t,queryFn:async({signal:t})=>{let n=await i.get(`batch`,e.id,e.revision,{signal:t});if(Fe(n),!Se(xe(n),e))throw Error(`The selected reviewed batch differs from its saved release.`);return{reference:xe(n),rewardBinding:n.rewardBinding,purpose:n.purpose,exampleCount:n.examples.length,sealedAt:n.sealedAt}},retry:!1}))}),l=[...new Map([...s,...c.flatMap(e=>e.data?[e.data]:[])].map(e=>[e.reference.contentHash,e])).values()];return{...a,models:o?.models??[],methods:o?.methods??[],billingModes:o?.billingModes,batches:l,error:a.error??c.find(e=>e.error)?.error??null,isSuccess:a.isSuccess&&c.every(e=>e.isSuccess),isPending:a.isPending||c.some(e=>e.isPending),refetch:async()=>Promise.all([a.refetch(),...c.map(e=>e.refetch())])}}function zy(e,t){let n=ml.parse({teamId:e.teamId,actorId:e.actorId,apiOrigin:t}),r={...n,projectId:e.projectId},i=`/v1/training/alphaedit-executions`;return{account:n,async capability(t,a){return Ct(await Y(e.connection,`${i}/capability`,{method:`POST`,signal:a,body:JSON.stringify({...r,capabilityQuery:t})}),t,n.actorId)},async compile(t){return Or(await Y(e.connection,`${i}/compile`,{method:`POST`,body:JSON.stringify({...r,command:t})}),t)},async mutate(t,a){let o=`action`in t?`${i}/${encodeURIComponent(t.id)}/${t.action}`:`${i}/prepare`,s=await jt(await Y(e.connection,o,{method:`POST`,body:JSON.stringify({...r,intentHash:a,command:t})}),t);if(s.execution.ownerUserId!==n.actorId||s.execution.projectId!==e.projectId)throw Error(`The execution receipt belongs to another account or Project.`);return s},async get(t,r){let a=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}}),o=await yt(await Y(e.connection,`${i}/${encodeURIComponent(t)}?${a}`,{signal:r}),{teamId:e.teamId,id:t,ownerUserId:n.actorId});if(e.projectId!==null&&o.projectId!==e.projectId)throw Error(`The execution belongs to another Project.`);return o},async list(t={},r){let a={...t,...e.projectId?{projectId:e.projectId}:{}},o=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}});for(let[e,t]of Object.entries(a))t!==void 0&&o.set(e,String(t));return sn(await Y(e.connection,`${i}?${o}`,{signal:r}),{teamId:e.teamId,ownerUserId:n.actorId,query:a})}}}function By(e,t=!0){return S({queryKey:[`alphaedit-experiment-account`,e.key,e.actorId],enabled:t&&e.location===`hosted`&&!!e.actorId,retry:!1,queryFn:async({signal:t})=>{let n=await e.request(`inventory`,{},t);if(n.teamId!==e.teamId)throw Error(`The workspace account changed.`);return zy(e,n.apiOrigin)}})}var Vy=[`training:prepare-alphaedit`,`training:start-alphaedit`,`training:cancel-alphaedit`];function Hy(e,t){let n=u(),r=J([e.key,e.accountKey,e.actorId,e.teamId,e.projectId,e.connection.serverUrl,t.draftId,t.executionId,t.method]),i=(0,Q.useRef)(r);i.current=r,(0,Q.useEffect)(()=>(i.current=r,()=>{i.current=``}),[r]);let a=()=>({identity:r,busy:!1,error:null,receipt:null,selected:null,original:null,preparationOperationId:null}),[o,s]=(0,Q.useState)(a),c=(0,Q.useRef)(new Set),l=o.identity===r?o:a();function d(e){i.current===r&&s(t=>({...t.identity===r?t:a(),...e}))}function f(){if(i.current!==r)throw Error(`Return to this experiment's original account before continuing.`)}let p=By(e,t.visible),m=p.data,h=S({queryKey:[`alphaedit-experiment-recovery`,r],enabled:t.visible&&e.location===`hosted`&&!!e.actorId&&!l.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[];for(let i of Vy){let a,o=new Set;for(let s=0;;s++){if(s>=100)throw Error(`The retained execution catalog exceeds its supported bound.`);let c=await e.pendingOperations(i,a,n);for(let n of c.items){let a=i===Vy[0]?Ll.parse(n.reviewedIntent):Rl.parse(n.reviewedIntent);if(a.account.actorId!==e.actorId||a.account.teamId!==e.teamId)throw Error(`The retained execution belongs to another account.`);if(!(t.draftId===null?`execution`in a&&a.execution.id===t.executionId:a.draftId===t.draftId))continue;let o=i===Vy[0]?Cr.parse(n.command??{...a.request,operationId:n.id}):Wt(n.command??{...a.request,operationId:n.id});r.push({intent:a,command:o,operation:e.recoverOperation(n)})}if(!c.nextCursor)break;if(o.has(c.nextCursor))throw Error(`The retained execution catalog repeated a cursor.`);o.add(c.nextCursor),a=c.nextCursor}}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),g=l.original??h.data?.[0]??null,_=t.executionId??l.selected??l.receipt?.execution.id??(g&&`execution`in g.intent?g.intent.execution.id:null),v=S({queryKey:[`managed-alphaedit-execution`,r,_],enabled:t.visible&&!!(m&&_),retry:!1,queryFn:({signal:e})=>{if(!m||!_)throw Error(`Select an execution first.`);return m.get(_,e)},refetchInterval:e=>e.state.error?!1:e.state.data&&![`completed`,`failed`,`cancelled`].includes(e.state.data.phase)?3e3:!1});async function y(t){let r=zy(e,t.intent.account.apiOrigin);if(J(r.account)!==J(t.intent.account))throw Error(`Return to this execution's original account before retrying.`);d({original:t}),await t.operation.retainCommand(t.command,`dispatching`),f();let i=await r.mutate(t.command,t.operation.intentHash);return f(),d({receipt:i,selected:i.execution.id,preparationOperationId:`action`in t.command?`preparationOperationId`in t.intent?t.intent.preparationOperationId:null:t.command.operationId}),await t.operation.acknowledge(),f(),d({original:null}),await h.refetch(),f(),n.invalidateQueries({queryKey:[`managed-alphaedit-execution`]}),n.invalidateQueries({queryKey:[`unified-experiments`]}),i}async function b(e){if(!c.current.has(r)){c.current.add(r),d({busy:!0,error:null});try{return f(),await e()}catch(e){return i.current===r&&d({error:e}),null}finally{c.current.delete(r),d({busy:!1})}}}async function x(n,r){return b(async()=>{if(g)return y(g);if(!m||!h.isSuccess||!t.draftId||n.id!==t.draftId||!n.alphaEditForm||!t.method)throw Error(`Load this saved experiment and original requests before preparing.`);let i=vt(n.alphaEditForm.maximumSpendUsd);await r(n),f();let a=await Iy(e).get(n.id);if(f(),a.status!==`draft`||a.projectId!==e.projectId||J(a.draft)!==J(n))throw Error(`The saved experiment changed. Reopen its exact current revision before preparing.`);let o=n.alphaEditForm.baseModel;if(!o||o.source!==`managed`||n.startingModel&&![`managed`,`alphaedit`].includes(n.startingModel.source))throw Error(`Choose a qualified exact AlphaEdit starting model.`);let s={teamId:e.teamId,modelId:o.modelId,source:o.source,...o.revision?{revision:o.revision}:{},...o.tokenizerRevision?{tokenizerRevision:o.tokenizerRevision}:{},...o.chatTemplateHash?{chatTemplateHash:o.chatTemplateHash}:{},...o.modelAssetId?{modelAssetId:o.modelAssetId}:{}},c={teamId:e.teamId,projectId:e.projectId,method:t.method,query:s,form:n.alphaEditForm},l=await m.compile(c);if(f(),l.actorId!==e.actorId||l.formHash!==await zr(n.alphaEditForm))throw Error(`The compilation differs from this exact saved form.`);let u=await an({teamId:e.teamId,projectId:e.projectId,operationId:crypto.randomUUID(),name:n.name,method:t.method,query:s,request:l.request,sourceForm:n.alphaEditForm,maximumSpendUsd:i}),{operationId:d,...p}=u,_=Ll.parse({account:m.account,draftId:n.id,request:p}),v=await e.operation(Vy[0],_);return f(),y({intent:_,operation:v,command:{...u,operationId:v.id}})})}async function C(n,r){return b(async()=>{if(g)return y(g);let i=r??v.data;if(!m||!h.isSuccess||!i||v.error)throw Error(`Read the exact execution before reviewing its next action.`);let{schemaVersion:a,request:o,sourceForm:s,result:c,resultRecordedAt:u,contentHash:d,...p}=i,_=hn.parse(p),b=n===`start`?{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n,approvedMaximumSpendUsd:i.plan.maximumSpendUsd,...i.plan.computePrice?{approvedPriceHash:await zr(i.plan.computePrice)}:{}}:{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n},x=Rl.parse({account:m.account,draftId:l.preparationOperationId?t.draftId:null,preparationOperationId:l.preparationOperationId,execution:_,request:b}),S=await e.operation(n===`start`?Vy[1]:Vy[2],x);return f(),y({intent:x,operation:S,command:Wt({...b,operationId:S.id})})})}return{prepare:x,control:C,retry:()=>b(()=>{if(!g)throw Error(`Reload the original execution request.`);return y(g)}),busy:l.busy,receipt:l.receipt,original:g,execution:v.data,ready:p.isSuccess&&h.isSuccess,recoveryReady:!!g||h.isSuccess,canControl:v.isSuccess&&!v.error,error:l.error??p.error??h.error??v.error,refresh:()=>{p.refetch(),e.actorId&&h.refetch(),m&&_&&v.refetch()},loading:v.isFetching||p.isFetching,selectedId:_}}function Uy(e){return e==null?`Use available credits`:`$${e} USD`}function Wy({price:e}){return e?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Usage rate`}),(0,$.jsxs)(`dd`,{children:[`$`,Number(e.appliedPrice.hourlyUsd).toLocaleString(void 0,{maximumFractionDigits:6}),`/hour`]}),(0,$.jsx)(`dt`,{children:`Billing`}),(0,$.jsx)(`dd`,{children:`Startup, model work and cleanup. Queue time and warm idle after completion are not billed.`})]}):null}function Gy(e){return e?`Start approves this request and usage rate. Credits are checked when compute is allocated. Work stops when credits or your spending limit run out. Saving and reviewing do not start compute.`:`Start this exact prepared request using workspace credits and capacity. The approved maximum includes the bounded execution; preparation does not reserve a worker.`}function Ky(e){return e===null?`Start using credits`:`Start with $${e} cap`}var qy=`training-alphaedit-result-save`;function Jy(e,t,n){let r=u(),i=J([e.key,ra(e.connection),t]),a=(0,Q.useRef)(i);a.current=i,(0,Q.useEffect)(()=>(a.current=i,()=>{a.current=``}),[i]);let o=()=>({identity:i,busy:!1,error:null,original:null,receipt:null}),[s,c]=(0,Q.useState)(o),l=(0,Q.useRef)(new Set),d=s.identity===i?s:o();function f(e){a.current===i&&c(t=>({...t.identity===i?t:o(),...e}))}function p(){if(a.current!==i)throw Error(`Return to this Model save's original account and result.`)}let m=n?.method===`alphaedit`&&n.phase===`completed`&&n.result!==null,h=By(e,m),g=S({queryKey:[`alphaedit-model-save-recovery`,i],enabled:!!e.actorId&&!d.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[],i=new Set,a;for(let o=0;;o++){if(o>=100)throw Error(`The retained Model save catalog exceeds its supported bound.`);let s=await e.pendingOperations(qy,a,n);for(let n of s.items){let i=Hl.parse(n.reviewedIntent);if(i.request.executionId!==t)continue;if(i.account.actorId!==e.actorId||i.account.teamId!==e.teamId||i.execution.projectId!==e.projectId)throw Error(`The retained Model save belongs to another creator or Project.`);let a=ir.parse(n.command??{...i.request,operationId:n.id});r.push({intent:i,command:a,operation:e.recoverOperation(n)})}if(!s.nextCursor)break;if(i.has(s.nextCursor))throw Error(`The retained Model save catalog repeated a cursor.`);i.add(s.nextCursor),a=s.nextCursor}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),_=d.original??g.data?.[0]??null,v=S({queryKey:[`alphaedit-model-save-options`,i,h.data?.account.apiOrigin,n?.result?.contentHash],enabled:m&&h.isSuccess&&g.isSuccess&&!_&&!d.busy,retry:!1,queryFn:async({signal:n})=>{if(!h.data)throw Error(`Read the configured result account first.`);let r=h.data.account,i=new URLSearchParams({...r,...e.projectId?{projectId:e.projectId}:{}}),a=Ul.parse(await Y(e.connection,`/v1/training/alphaedit-executions/${encodeURIComponent(t)}/model?${i}`,{signal:n}));if(J(a.account)!==J(r)||a.executionId!==t||a.projectId!==e.projectId)throw Error(`The Model targets differ from this exact result account or Project.`);return a}});async function y(n){f({original:n}),await n.operation.retainCommand(n.command,`dispatching`),p();let i=await Y(e.connection,`/v1/training/alphaedit-executions/${encodeURIComponent(n.command.executionId)}/model`,{method:`POST`,body:JSON.stringify({...n.intent.account,projectId:n.intent.execution.projectId,intentHash:n.operation.intentHash,command:n.command})}),a=await Hn(i,n.command);if(p(),a.actorId!==e.actorId||a.version.source.executionId!==t)throw Error(`The saved Model receipt belongs to another creator or Project.`);f({receipt:a});for(let e of[`saved-training-model`,`saved-model-serving`,`alphaedit-model-save-options`,`unified-experiments`,`model-projects`])r.invalidateQueries({queryKey:[e]});return await n.operation.acknowledge(),p(),f({original:null}),await g.refetch(),p(),a}async function b(r){if(l.current.has(i))return null;l.current.add(i),f({busy:!0,error:null});try{if(p(),_)return await y(_);if(!g.isSuccess)throw Error(`Reload the original Model saves before continuing.`);if(!m||!n?.result||!v.isSuccess||!h.isSuccess||!v.data)throw Error(`Read the completed AlphaEdit result and current Model targets before saving.`);let i=r.modelProjectId?v.data.models.find(e=>e.id===r.modelProjectId):null;if(r.modelProjectId&&!i)throw Error(`Refresh the Model targets before updating this Model.`);let{schemaVersion:a,request:o,sourceForm:s,result:c,resultRecordedAt:l,contentHash:u,...d}=n,f=Hl.parse({account:v.data.account,execution:hn.parse(d),request:{teamId:e.teamId,executionId:t,resultHash:n.result.contentHash,artifactHash:n.result.artifact.contentHash,name:r.name,modelProjectId:i?.id??null,expectedModelRevision:i?.revision??0}}),b=await e.operation(qy,f);return p(),await y({intent:f,operation:b,command:ir.parse({...f.request,operationId:b.id})})}catch(e){return a.current===i&&f({error:e}),null}finally{l.current.delete(i),f({busy:!1})}}return{save:b,busy:d.busy,receipt:d.receipt,original:_,options:v.data,freshReady:m&&g.isSuccess&&v.isSuccess&&h.isSuccess,recoveryReady:!!_||g.isSuccess,error:d.error??g.error??(m?v.error??h.error:null),refresh:()=>{g.refetch(),m&&!_&&(h.refetch(),h.data&&v.refetch())}}}function Yy({form:e,onChange:t}){let n=(n,r)=>t({...e,questions:e.questions.map((e,t)=>t===n?r:e)});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[`State (JSON)`,(0,$.jsx)(`textarea`,{rows:6,value:e.stateJson,maxLength:131072,onChange:n=>t({...e,stateJson:n.target.value})})]}),(0,$.jsx)(`p`,{children:`Provide unlabeled state and every allowed answer. Approved training targets stay outside scoring input and prompts.`}),e.questions.map((r,i)=>(0,$.jsxs)(`section`,{className:`evaluation-card`,children:[(0,$.jsxs)(`h3`,{children:[`Question `,i+1]}),(0,$.jsxs)(`label`,{children:[`Question ID`,(0,$.jsx)(`input`,{value:r.id,maxLength:80,onChange:e=>n(i,{...r,id:e.target.value})})]}),(0,$.jsxs)(`label`,{children:[`Question`,(0,$.jsx)(`textarea`,{value:r.description,maxLength:2e3,onChange:e=>n(i,{...r,description:e.target.value})})]}),(0,$.jsxs)(`label`,{children:[`Answer type`,(0,$.jsx)(Z,{floating:!0,label:`Question ${i+1} answer type`,value:r.type,options:[{value:`choice`,label:`Choice`},{value:`boolean`,label:`Boolean`},{value:`integer_levels`,label:`Integer levels`}],onChange:e=>{(e===`choice`||e===`boolean`||e===`integer_levels`)&&n(i,{...r,type:e,choices:e===`boolean`?[{value:`false`,description:`False`},{value:`true`,description:`True`}]:[{value:``,description:``},{value:``,description:``}]})}})]}),r.choices.map((e,t)=>(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsxs)(`label`,{children:[`Value`,(0,$.jsx)(`input`,{value:e.value,maxLength:256,disabled:r.type===`boolean`,inputMode:r.type===`integer_levels`?`numeric`:`text`,onChange:e=>n(i,{...r,choices:r.choices.map((n,r)=>r===t?{...n,value:e.target.value}:n)})})]}),(0,$.jsxs)(`label`,{children:[`Description`,(0,$.jsx)(`input`,{value:e.description,maxLength:2e3,onChange:e=>n(i,{...r,choices:r.choices.map((n,r)=>r===t?{...n,description:e.target.value}:n)})})]}),r.type===`boolean`?null:(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:r.choices.length<=2,onClick:()=>n(i,{...r,choices:r.choices.filter((e,n)=>n!==t)}),children:`Remove answer`})]},t)),r.type===`boolean`?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:r.choices.length>=26,onClick:()=>n(i,{...r,choices:[...r.choices,{value:``,description:``}]}),children:`Add answer`}),(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:e.questions.length<=1,onClick:()=>t({...e,questions:e.questions.filter((e,t)=>t!==i)}),children:`Remove question`})]},i)),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:e.questions.length>=8,onClick:()=>t({...e,questions:[...e.questions,{id:``,type:`choice`,description:``,choices:[{value:``,description:``},{value:``,description:``}]}]}),children:`Add question`}),Object.keys(e.limits).map(n=>(0,$.jsxs)(`label`,{children:[{maximumPromptTokens:`Maximum prompt tokens`,maximumForwardTokenWork:`Maximum forward token work`,maximumDurationSeconds:`Maximum duration (seconds)`}[n],(0,$.jsx)(`input`,{value:e.limits[n],inputMode:`numeric`,maxLength:100,onChange:r=>t({...e,limits:{...e.limits,[n]:r.target.value}})})]},n))]})}function Xy({form:e,onChange:t}){let n={learningRate:`Learning rate`,weightDecay:`Weight decay`,maxSteps:`Maximum optimizer steps`,gradientAccumulationSteps:`Gradient accumulation steps`,maximumPromptTokens:`Maximum prompt tokens`,seed:`Seed`,maxDurationSeconds:`Maximum duration (seconds)`,maxCheckpointBytes:`Maximum checkpoint bytes`};return(0,$.jsx)($.Fragment,{children:Object.keys(n).map(r=>(0,$.jsxs)(`label`,{children:[n[r],(0,$.jsx)(`input`,{value:e.training[r],inputMode:`decimal`,maxLength:100,onChange:n=>t({...e,training:{...e.training,[r]:n.target.value}})})]},r))})}function Zy({result:e}){return(0,$.jsxs)(ft,{title:e.schemaVersion===`openpond.decisionScoringResult.v1`?`Candidate probabilities`:`Decision training result`,children:[e.schemaVersion===`openpond.decisionScoringResult.v1`?e.distributions.map(e=>(0,$.jsxs)(`section`,{children:[(0,$.jsx)(`h3`,{children:e.questionId}),(0,$.jsxs)(`p`,{children:[`Prediction: `,String(e.prediction),e.expectedLevel===null?``:` · Expected level: ${e.expectedLevel.toFixed(4)}`,` · `,e.promptTokenCount,` prompt tokens`]}),(0,$.jsx)(`div`,{className:`evaluation-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Answer`}),(0,$.jsx)(`th`,{children:`Probability`}),(0,$.jsx)(`th`,{children:`Logit`}),(0,$.jsx)(`th`,{children:`Token ID`})]})}),(0,$.jsx)(`tbody`,{children:e.candidates.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:String(e.value)}),(0,$.jsxs)(`td`,{children:[(e.probability*100).toFixed(4),`%`]}),(0,$.jsx)(`td`,{children:e.logit.toFixed(6)}),(0,$.jsx)(`td`,{children:e.tokenId})]},e.code))})]})})]},e.questionId)):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dl`,{className:`evaluation-workspace-meta`,children:Object.entries({"Optimizer steps":e.optimizerSteps,"Examples processed":e.examplesProcessed,"Questions processed":e.questionRowsProcessed,"Target tokens":e.targetTokens,"Mean loss":e.meanLoss,"Final loss":e.finalLoss,"Trainable parameters":e.trainableParameterCount,"Frozen backbone before":e.frozenBackboneState.before,"Frozen backbone after":e.frozenBackboneState.after,"Adapter artifact":e.artifact.id,"Artifact hash":e.artifact.contentHash}).map(([e,t])=>(0,$.jsxs)(`div`,{style:{display:`contents`},children:[(0,$.jsx)(`dt`,{children:e}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:t})]},e))}),(0,$.jsx)(`div`,{className:`evaluation-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`File`}),(0,$.jsx)(`th`,{children:`Bytes`}),(0,$.jsx)(`th`,{children:`SHA-256`})]})}),(0,$.jsx)(`tbody`,{children:e.artifact.files.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.path}),(0,$.jsx)(`td`,{children:e.sizeBytes.toLocaleString()}),(0,$.jsx)(`td`,{className:`saved-model-version-reference`,children:e.sha256})]},e.path))})]})})]}),(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Duration`}),(0,$.jsxs)(`dd`,{children:[(e.durationMs/1e3).toLocaleString(),` seconds`]}),(0,$.jsx)(`dt`,{children:`Forward token work`}),(0,$.jsx)(`dd`,{children:e.forwardTokenWork.toLocaleString()}),(0,$.jsx)(`dt`,{children:`Result hash`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.contentHash})]})]})}function Qy(e=`train`){let t={baseModel:_n(),name:`Decision experiment`,maximumSpendUsd:``,parentArtifact:null};return e===`train`?{...t,mode:e,batch:null,training:{learningRate:`0.0001`,weightDecay:`0`,maxSteps:`16`,gradientAccumulationSteps:`1`,maximumPromptTokens:`2048`,seed:`0`,maxDurationSeconds:`3600`,maxCheckpointBytes:`268435456`}}:{...t,mode:e,stateJson:`{}`,questions:[$y()],limits:{maximumPromptTokens:`2048`,maximumForwardTokenWork:`16384`,maximumDurationSeconds:`120`}}}function $y(){return{id:``,type:`choice`,description:``,choices:[{value:``,description:``},{value:``,description:``}]}}function eb(e,t){let n=ml.parse({teamId:e.teamId,actorId:e.actorId,apiOrigin:t}),r={...n,projectId:e.projectId},i=`/v1/training/decision-executions`;return{account:n,async capability(t,a){return Bn(await Y(e.connection,`${i}/capability`,{method:`POST`,signal:a,body:JSON.stringify({...r,capabilityQuery:t})}),t,n.actorId)},async compile(t){return ln(await Y(e.connection,`${i}/compile`,{method:`POST`,body:JSON.stringify({...r,command:t})}),t,n.actorId)},async mutate(t,a){let o=`action`in t?`${i}/${encodeURIComponent(t.id)}/${t.action}`:`${i}/prepare`,s=await rr(await Y(e.connection,o,{method:`POST`,body:JSON.stringify({...r,intentHash:a,command:t})}),t);if(s.execution.ownerUserId!==n.actorId||s.execution.projectId!==e.projectId)throw Error(`The execution receipt belongs to another account or Project.`);return s},async get(t,r){let a=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}}),o=await At(await Y(e.connection,`${i}/${encodeURIComponent(t)}?${a}`,{signal:r}),{teamId:e.teamId,id:t,ownerUserId:n.actorId});if(e.projectId!==null&&o.projectId!==e.projectId)throw Error(`The execution belongs to another Project.`);return o},async list(t={},r){let a={...t,...e.projectId?{projectId:e.projectId}:{}},o=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}});for(let[e,t]of Object.entries(a))t!==void 0&&o.set(e,String(t));return Lt(await Y(e.connection,`${i}?${o}`,{signal:r}),{teamId:e.teamId,ownerUserId:n.actorId,query:a})}}}function tb(e,t=!0){return S({queryKey:[`decision-experiment-account`,e.key,e.actorId],enabled:t&&e.location===`hosted`&&!!e.actorId,retry:!1,queryFn:async({signal:t})=>{let n=await e.request(`inventory`,{},t);if(n.teamId!==e.teamId)throw Error(`The workspace account changed.`);return eb(e,n.apiOrigin)}})}var nb=`training-decision-score`;function rb(e,t){let n=J([e.key,e.actorId,e.connection.serverUrl,t]),r=(0,Q.useRef)(n),i=(0,Q.useRef)(new Set);r.current=n,(0,Q.useEffect)(()=>(r.current=n,()=>{r.current=``}),[n]);let a=u(),o=tb(e),[s,c]=(0,Q.useState)({identity:n,busy:!1,error:null,original:null,receipt:null}),l=s.identity===n?s:{identity:n,busy:!1,error:null,original:null,receipt:null};function d(e){r.current===n&&c(t=>({...t.identity===n?t:{identity:n,busy:!1,error:null,original:null,receipt:null},...e}))}function f(){if(r.current!==n)throw Error(`Return to the original account and exact Decision Model before continuing.`)}let p=S({queryKey:[`decision-score-recovery`,n],enabled:!!e.actorId&&!l.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[],i=new Set,a;for(let o=0;;o++){if(o>=100)throw Error(`The retained scoring catalog exceeds its supported bound.`);let s=await e.pendingOperations(nb,a,n);for(let n of s.items){let i=Il.parse(n.reviewedIntent);if(i.modelProjectId!==t)continue;if(i.account.teamId!==e.teamId||i.account.actorId!==e.actorId)throw Error(`The retained score belongs to another account.`);let a=n.command,o=In.parse(a?.request??{...i.request,requestId:n.id});if(a&&a.modelProjectId!==t||o.requestId!==n.id)throw Error(`The retained score differs from its original operation.`);r.push({intent:i,command:{modelProjectId:t,request:o},operation:e.recoverOperation(n)})}if(!s.nextCursor)break;if(i.has(s.nextCursor))throw Error(`The retained scoring catalog repeated a page.`);i.add(s.nextCursor),a=s.nextCursor}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))[0]??null}}),m=l.original??p.data??null;async function h(r){if(i.current.has(n))return null;i.current.add(n),d({busy:!0,error:null});try{f();let n=m;if(!n){if(!r||!o.data||!p.isSuccess)throw Error(`Load this Model's account and retained scoring operations first.`);let i=Il.parse({account:o.data.account,modelProjectId:t,request:r}),a=await e.operation(nb,i);f(),n={intent:i,operation:a,command:{modelProjectId:t,request:In.parse({...r,requestId:a.id})}}}d({original:n}),await n.operation.retainCommand(n.command,`dispatching`),f();let i=await Ht(await Y(e.connection,`/v1/training/saved-models/${encodeURIComponent(t)}/decisions`,{method:`POST`,body:JSON.stringify({...n.intent.account,projectId:e.projectId,intentHash:n.operation.intentHash,command:n.command.request})}),{modelProjectId:t,request:n.command.request,actorId:e.actorId});return f(),d({receipt:i}),await n.operation.acknowledge(),f(),d({original:null}),await p.refetch(),a.invalidateQueries({queryKey:[`saved-model-serving`]}),i}catch(e){return d({error:e}),null}finally{i.current.delete(n),d({busy:!1})}}return{run:h,original:m,receipt:l.receipt,busy:l.busy,error:l.error??p.error??o.error,ready:!!m||p.isSuccess&&o.isSuccess,refresh:()=>{p.refetch(),o.refetch()}}}function ib({api:e,version:t,active:n}){let r=rb(e,t.modelProjectId),[i,a]=(0,Q.useState)(()=>Qy(`score`)),o=(0,Q.useRef)(J(i)),s=iy({name:`Decision scoring input`,dirty:J(i)!==o.current,busy:r.busy}),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(null);return(0,$.jsxs)(`section`,{className:`training-detail-section`,"aria-label":`Score exact Decision Model`,children:[(0,$.jsx)(`h3`,{children:`Score this version`}),s.dialog,(0,$.jsx)(X,{error:u??r.error}),r.original?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{className:`saved-model-version-reference`,children:[`Original scoring request retained for saved version`,` `,r.original.command.request.versionHash,`.`]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Original scoring input and limits`}),(0,$.jsx)(`pre`,{children:JSON.stringify({input:r.original.command.request.input,limits:r.original.command.request.limits},null,2)})]})]}):null,(0,$.jsx)(`fieldset`,{disabled:r.busy||!!r.original,children:(0,$.jsx)(Yy,{form:i,onChange:a})}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{className:`training-button secondary`,onClick:r.refresh,disabled:r.busy,children:`Refresh scoring recovery`}),(0,$.jsx)(`button`,{className:`training-button`,disabled:r.busy||!r.ready||!r.original&&!n,onClick:()=>{if(r.original)r.run();else try{St(i),d(null),l(!0)}catch(e){d(e)}},children:r.original?`Retry original score`:`Review score`})]}),r.receipt?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{className:`saved-model-version-reference`,children:[`Recorded scores for saved version `,r.receipt.version.contentHash,`.`]}),(0,$.jsx)(Zy,{result:r.receipt.result})]}):null,c?(0,$.jsxs)(qa,{ariaLabel:`Score exact Decision Model`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:r.busy,onClose:()=>{r.busy||l(!1)},children:[(0,$.jsx)(`h2`,{children:`Score exact Decision Model`}),(0,$.jsx)(`p`,{children:`Score every allowed candidate using this saved adapter and the reviewed bounded limits.`}),(0,$.jsx)(`p`,{className:`saved-model-version-reference`,children:t.contentHash}),(0,$.jsx)(`pre`,{children:JSON.stringify(St(i),null,2)}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{disabled:r.busy,className:`training-button secondary`,onClick:()=>l(!1),children:`Close`}),(0,$.jsx)(`button`,{disabled:r.busy||!r.ready,className:`training-button`,onClick:()=>{r.run({schemaVersion:`openpond.decisionModelScoreRequest.v1`,teamId:e.teamId,versionHash:t.contentHash,...St(i)}).then(e=>{e&&(o.current=J(i),l(!1))})},children:`Score`})]})]}):null]})}var ab=`training-model-serving-control`,ob=ne([Yn,cn,Qn,En,er,nr]),sb=ne([ur,rn,vn,fr,bn,It]);async function cb(e,t,n){let r=t.request;return r.schemaVersion===`openpond.alphaEditModelServingControlRequest.v1`?Gt(e,{modelProjectId:t.modelProjectId,request:r,actorId:n}):r.schemaVersion===`openpond.neuronTrainingModelServingControlRequest.v1`?Mn(e,{modelProjectId:t.modelProjectId,request:r,actorId:n}):r.schemaVersion===`openpond.decisionModelServingControlRequest.v1`?Ut(e,{modelProjectId:t.modelProjectId,request:r,actorId:n}):r.schemaVersion===`openpond.engramModelServingControlRequest.v1`?Nt(e,{modelProjectId:t.modelProjectId,request:r,actorId:n}):r.schemaVersion===`openpond.steeringModelServingControlRequest.v1`?gn(e,{modelProjectId:t.modelProjectId,request:r,actorId:n}):bt(e,{modelProjectId:t.modelProjectId,request:r,actorId:n})}function lb(e,t,n,r,i,a,o){return n.schemaVersion===`openpond.alphaEditModelServing.v1`||n.schemaVersion===`openpond.neuronTrainingModelServing.v1`?ob.parse({schemaVersion:n.schemaVersion===`openpond.alphaEditModelServing.v1`?`openpond.alphaEditModelServingControlRequest.v1`:`openpond.neuronTrainingModelServingControlRequest.v1`,teamId:e.teamId,modelProjectId:t,expectedRevision:n.control?.revision??0,versionHash:n.version.contentHash,action:r,idleTimeoutSeconds:i}):n.schemaVersion===`openpond.decisionModelServing.v1`?ob.parse({schemaVersion:`openpond.decisionModelServingControlRequest.v1`,teamId:e.teamId,modelProjectId:t,expectedRevision:n.control?.revision??0,versionHash:n.version.contentHash,action:r,idleTimeoutSeconds:i}):n.schemaVersion===`openpond.engramModelServing.v1`?ob.parse({schemaVersion:`openpond.engramModelServingControlRequest.v1`,teamId:e.teamId,modelProjectId:t,expectedRevision:n.control?.revision??0,versionHash:n.version.contentHash,action:r,defaultEnabled:r===`stop`?n.control?.defaultEnabled:o,idleTimeoutSeconds:i}):n.schemaVersion===`openpond.steeringModelServing.v1`?ob.parse({schemaVersion:`openpond.steeringModelServingControlRequest.v1`,teamId:e.teamId,modelProjectId:t,expectedRevision:n.control?.revision??0,versionHash:n.version.contentHash,action:r,defaultPublication:r===`stop`?n.control?.defaultPublication:a,idleTimeoutSeconds:i}):ob.parse({schemaVersion:`openpond.trainingModelServingControlRequest.v1`,teamId:e.teamId,modelProjectId:t,expectedRevision:n.control?.revision??0,artifact:r===`stop`?n.control?.artifact:n.registry?.artifact,versionHash:r===`stop`?n.control?.versionHash:n.version.contentHash,action:r,idleTimeoutSeconds:i})}function ub(e,t){return!(e instanceof Ti)||e.status!==409||e.retryable!==!1||t.command.request.schemaVersion===`openpond.alphaEditModelServingControlRequest.v1`||t.command.request.schemaVersion===`openpond.neuronTrainingModelServingControlRequest.v1`||t.command.request.schemaVersion===`openpond.decisionModelServingControlRequest.v1`?!1:t.command.request.schemaVersion===`openpond.engramModelServingControlRequest.v1`?[`engram_serving_revision_conflict`,`engram_serving_runtime_unavailable`,`engram_serving_cleanup_pending`,`engram_serving_other_kind_active`,`engram_serving_version_changed`,`engram_serving_stop_required`,`engram_serving_stop_changed`].includes(e.code??``):(t.command.request.schemaVersion===`openpond.steeringModelServingControlRequest.v1`?[`steering_serving_revision_conflict`,`steering_serving_cleanup_pending`,`steering_serving_other_kind_active`,`steering_serving_version_changed`,`steering_serving_default_changed`,`steering_serving_runtime_unavailable`,`steering_serving_stop_required`,`steering_serving_stop_changed`]:[`model_serving_revision_conflict`,`model_serving_runtime_unavailable`,`model_serving_cleanup_pending`,`model_serving_version_changed`,`model_serving_candidate_not_qualified`,`model_serving_stop_changed`]).includes(e.code??``)}function db(e,t,n){let r=u(),i=JSON.stringify([e.key,ra(e.connection),t]),a=(0,Q.useRef)(i);a.current=i;let o=(0,Q.useRef)(!0),s=(0,Q.useRef)(new Set),c=()=>({scope:i,retained:null,busy:!1,error:null,receipt:null}),[l,d]=(0,Q.useState)(c),f=l.scope===i?l:c();(0,Q.useEffect)(()=>(o.current=!0,()=>{o.current=!1}),[]);let p=()=>o.current&&a.current===i;function m(e){p()&&d(t=>({...t.scope===i?t:c(),...e}))}let h=S({queryKey:[`model-serving-control-recovery`,i],retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r,i=[],a=new Set;for(let o=0;;o++){if(o>=100)throw Error(`The retained serving catalog exceeds its supported bound.`);let s=await e.pendingOperations(ab,r,n);for(let n of s.items){let r=ob.parse(n.reviewedIntent);if(r.modelProjectId!==t)continue;if(r.teamId!==e.teamId)throw Error(`The retained serving command belongs to another workspace.`);let{modelProjectId:a,...o}=r;i.push({command:sb.parse(n.command??{modelProjectId:a,request:{...o,operationId:n.id}}),operation:e.recoverOperation(n)})}if(!s.nextCursor)break;if(a.has(s.nextCursor))throw Error(`The retained serving catalog repeated a page.`);a.add(s.nextCursor),r=s.nextCursor}if(i.length>1)throw Error(`Resolve the original retained serving commands before reviewing another action.`);return i[0]??null}}),g=f.retained??h.data??null;async function _(a,o,c=null,l=!0){if(s.current.has(i)||!g&&!h.isSuccess)return null;s.current.add(i),m({busy:!0,error:null});let u=null;try{if(!e.actorId||!p())throw Error(`Choose an authenticated account before controlling serving.`);let i=g;if(!i){if(!n)throw Error(`Read the exact saved version before reviewing a fresh serving command.`);let r=lb(e,t,n,a,o,c,l),s=await e.operation(ab,r);if(!p())return null;let{modelProjectId:u,...d}=r;i={operation:s,command:sb.parse({modelProjectId:u,request:{...d,operationId:s.id}})}}if(m({retained:i}),await i.operation.retainCommand(i.command,`dispatching`),!p())return null;u=i;let s=await cb(await Y(e.connection,`/v1/training/saved-models/${encodeURIComponent(i.command.modelProjectId)}/serving?${new URLSearchParams({teamId:e.teamId,...i.command.request.schemaVersion===`openpond.alphaEditModelServingControlRequest.v1`||i.command.request.schemaVersion===`openpond.neuronTrainingModelServingControlRequest.v1`||i.command.request.schemaVersion===`openpond.decisionModelServingControlRequest.v1`?{intentHash:i.operation.intentHash,...e.projectId?{projectId:e.projectId}:{}}:{}})}`,{method:`POST`,body:JSON.stringify(i.command.request)}),i.command,e.actorId);if(!p())return null;m({receipt:s}),r.invalidateQueries({queryKey:[`saved-model-serving`]});try{await i.operation.acknowledge()}catch(e){return m({error:e}),null}return p()?(m({retained:null}),await h.refetch(),p()?s:null):null}catch(e){if(p()&&(m({error:e}),u&&ub(e,u)))try{await u.operation.acknowledge(),p()&&(m({retained:null}),await h.refetch(),r.invalidateQueries({queryKey:[`saved-model-serving`]}))}catch(e){m({error:e})}return null}finally{s.current.delete(i),m({busy:!1})}}return{run:_,busy:f.busy,receipt:f.receipt,retained:g,recoveryReady:!!g||h.isSuccess,refreshRecovery:h.refetch,error:f.error??h.error}}function fb({api:e,value:t,version:n,action:r,onClose:i}){let a=db(e,n.modelProjectId,t),[o,s]=(0,Q.useState)(t?.schemaVersion===`openpond.engramModelServing.v1`?t.defaultEnabled:t?.schemaVersion!==`openpond.steeringModelServing.v1`||t.defaultPublication!==null),c=a.retained?.command.request,l=c?.action??r,u=t&&(l===`activate`?(t.schemaVersion===`openpond.steeringModelServing.v1`||t.schemaVersion===`openpond.engramModelServing.v1`||t.schemaVersion===`openpond.decisionModelServing.v1`||t.schemaVersion===`openpond.alphaEditModelServing.v1`||t.schemaVersion===`openpond.neuronTrainingModelServing.v1`?t.availability.state===`qualified`&&!t.cleanup.some(e=>![`shared`,`released`].includes(e.capacityState)):t.registry?.qualified)&&t.control?.phase!==`stopping`:t.control?.desiredState===`active`&&t.control.versionHash===n.contentHash),d=iy({name:`Serving setup`,busy:a.busy,dirty:!!c||n.schemaVersion===`openpond.engramModelVersion.v1`&&o!==(t?.schemaVersion!==`openpond.engramModelServing.v1`||t.defaultEnabled)||n.schemaVersion===`openpond.steeringModelVersion.v1`&&o!==(t?.schemaVersion!==`openpond.steeringModelServing.v1`||t.defaultPublication!==null),discardDescription:c?`The original serving command stays in recovery so you can retry it after reopening this Model.`:void 0});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(qa,{ariaLabel:l===`activate`?`Activate Model`:`Stop Model`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:a.busy,onClose:()=>void d.requestLeave(i),children:[(0,$.jsx)(`h2`,{children:l===`activate`?`Activate Model`:`Stop Model`}),(0,$.jsx)(X,{error:a.error}),(0,$.jsx)(`p`,{children:l===`activate`?`Activate this exact saved version using workspace capacity and credits. This may allocate paid serving capacity.`:`Stop new requests to this Model. Outstanding requests finish before unused capacity can retire; shared capacity may remain in use.`}),(0,$.jsx)(`p`,{children:n.schemaVersion===`openpond.steeringModelVersion.v1`?n.publication.baseModel.modelId:n.schemaVersion===`openpond.engramModelVersion.v1`||n.schemaVersion===`openpond.decisionModelVersion.v1`||n.schemaVersion===`openpond.alphaEditModelVersion.v1`||n.schemaVersion===`openpond.neuronTrainingModelVersion.v1`?n.baseModel.modelId:n.request.baseModel.modelId}),(0,$.jsxs)(`p`,{className:`saved-model-version-reference`,children:[`Saved version `,c?.versionHash??n.contentHash]}),l===`activate`&&(c?c.schemaVersion===`openpond.steeringModelServingControlRequest.v1`||c.schemaVersion===`openpond.engramModelServingControlRequest.v1`:n.schemaVersion===`openpond.steeringModelVersion.v1`||n.schemaVersion===`openpond.engramModelVersion.v1`)?(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Default modification`}),(0,$.jsx)(Z,{label:`Default modification`,value:c?.schemaVersion===`openpond.engramModelServingControlRequest.v1`?c.defaultEnabled?`profile`:`off`:c?.schemaVersion===`openpond.steeringModelServingControlRequest.v1`?c.defaultPublication?`profile`:`off`:o?`profile`:`off`,options:[{value:`profile`,label:n.schemaVersion===`openpond.engramModelVersion.v1`?`Saved memory module`:`Saved profile`},{value:`off`,label:`Off`}],disabled:a.busy||!!c,onChange:e=>s(e===`profile`)})]}):null,l===`activate`?(0,$.jsxs)(`p`,{children:[`Idle timeout: `,(c?.idleTimeoutSeconds??300)/60,` minutes.`]}):null,c?(0,$.jsxs)(`p`,{children:[`Original `,c.action,` request retained.`]}):null,a.receipt?(0,$.jsx)(`p`,{role:`status`,children:`Request accepted. Retaining recovery until its acknowledgment completes.`}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:a.busy,onClick:()=>void d.requestLeave(i),children:`Close`}),a.recoveryReady?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void a.refreshRecovery(),children:`Reload retained commands`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:a.busy||!a.recoveryReady||!c&&!u,onClick:()=>void a.run(l,c?.idleTimeoutSeconds??(l===`stop`?t?.control?.idleTimeoutSeconds??300:300),n.schemaVersion===`openpond.steeringModelVersion.v1`&&o?{id:n.publication.id,revision:n.publication.revision,contentHash:n.publication.contentHash}:null,o).then(e=>{e&&(d.allowNextNavigation(),i())}),children:a.busy?`Applying…`:c?`Retry original ${c.action}`:l===`activate`?`Activate`:`Stop serving`})]})]}),d.dialog]})}var pb={unpublished:`Publication pending`,qualification_pending:`Qualification pending`,unavailable:`Unavailable`,inactive:`No active routing`,starting:`Starting`,active:`Active routing`,retiring:`Retiring capacity`},mb={qualified:`Qualified for this serving runtime.`,evaluation_pending:`Registry evaluation is pending.`,post_training_pending:`Required post-training checks are pending.`,evaluation_failed:`Registry evaluation did not pass.`,candidate_rejected:`This candidate was rejected.`,artifact_revoked:`This registry artifact was revoked.`,artifact_deleted:`This registry artifact was deleted.`,runtime_unavailable:`The published runtime does not match this saved base model.`};function hb({connection:e,version:t,api:n}){let{teamId:r,modelProjectId:i,contentHash:a}=t,[o,s]=(0,Q.useState)(null),c=S({queryKey:[`saved-model-serving`,ra(e),r,i,a],queryFn:async({signal:t})=>qn(await Y(e,`/v1/training/saved-models/${encodeURIComponent(i)}/serving?${new URLSearchParams({teamId:r,versionHash:a})}`,{signal:t}),{teamId:r,modelProjectId:i,versionHash:a}),staleTime:1e4,gcTime:3e5,retry:!1,refetchInterval:e=>{if(e.state.error)return!1;let t=e.state.data;return t?t.cleanup.some(e=>[`pending`,`retiring`].includes(e.capacityState))||[`starting`,`retiring`].includes(t.state)||t.control&&(t.control.desiredState===`stopped`||t.control.phase===`failed`)&&[`pending`,`retiring`].includes(t.control.capacityState)?5e3:t.cleanup.length?3e4:!1:!1},refetchIntervalInBackground:!1}),l=c.data,u=l&&!c.error&&(l.control?.desiredState===`active`?l.control.versionHash===a:l.schemaVersion===`openpond.steeringModelServing.v1`||l.schemaVersion===`openpond.engramModelServing.v1`||l.schemaVersion===`openpond.decisionModelServing.v1`||l.schemaVersion===`openpond.alphaEditModelServing.v1`||l.schemaVersion===`openpond.neuronTrainingModelServing.v1`?l.availability.state===`qualified`&&l.control?.phase!==`stopping`&&!l.cleanup.some(e=>![`shared`,`released`].includes(e.capacityState)):l.registry?.qualified&&l.control?.phase!==`stopping`);return(0,$.jsxs)(`section`,{"aria-label":`Serving state`,children:[(0,$.jsxs)(`div`,{className:`labs-project-trends-heading`,children:[(0,$.jsx)(`h3`,{children:`Serving`}),(0,$.jsx)(`button`,{className:`training-button secondary`,type:`button`,disabled:c.isFetching,onClick:()=>void c.refetch(),children:`Refresh serving state`})]}),(0,$.jsx)(X,{error:c.error}),c.isPending?(0,$.jsx)(`p`,{role:`status`,children:`Reading serving state…`}):null,n?(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{className:`training-button`,type:`button`,disabled:c.isFetching||!u,onClick:()=>s(l?.control?.desiredState===`active`?`stop`:`activate`),children:l?.control?.desiredState===`active`?`Stop serving`:l?.control?.phase===`stopping`?`Stopping…`:`Activate`}),(0,$.jsx)(`button`,{className:`training-button secondary`,type:`button`,onClick:()=>s(l?.control?.desiredState===`active`?`stop`:`activate`),children:`Review serving request`})]}):null,l?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`dl`,{className:`model-project-page-metrics`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Routing`}),(0,$.jsx)(`dd`,{children:(0,$.jsx)(ci,{label:pb[l.state],value:l.state})})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Active binding records`}),(0,$.jsx)(`dd`,{children:l.bindings.length})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Last verified inference`}),(0,$.jsx)(`dd`,{children:l.schemaVersion===`openpond.decisionModelServing.v1`?l.lastVerifiedScore?new Date(l.lastVerifiedScore.completedAt).toLocaleString():`No retained score`:l.lastVerifiedInference?new Date(l.lastVerifiedInference.completedAt).toLocaleString():`No retained evidence`})]}),l.control?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Serving request`}),(0,$.jsx)(`dd`,{children:l.control.phase})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Capacity`}),(0,$.jsx)(`dd`,{children:l.control.desiredState===`active`&&l.control.phase!==`failed`?`Managed by serving runtime`:{pending:`Cleanup pending`,shared:`Retained for current consumers`,retiring:`Retirement in progress`,released:`Retirement complete`}[l.control.capacityState]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Model ID`}),(0,$.jsx)(`dd`,{children:l.control.modelId})]})]}):null]}),l.schemaVersion===`openpond.trainingModelServing.v1`&&l.registry?(0,$.jsx)(`p`,{children:mb[l.registry.reason]}):l.schemaVersion===`openpond.steeringModelServing.v1`?(0,$.jsx)(`p`,{children:{qualified:`Qualified for this serving runtime.`,runtime_unavailable:`A compatible serving runtime has not been qualified.`,calibration_unavailable:`The original calibration is unavailable.`,profile_archived:`This saved profile is archived.`,model_mismatch:`The serving runtime differs from this exact model.`}[l.availability.reason]}):null,l.schemaVersion===`openpond.engramModelServing.v1`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:{qualified:`Qualified for this serving runtime.`,runtime_unavailable:`A compatible Engram serving runtime has not been qualified.`,module_unavailable:`The original trained memory module is unavailable.`,model_mismatch:`The serving runtime differs from this exact base model.`}[l.availability.reason]}),(0,$.jsxs)(`p`,{children:[`Default modification: `,l.defaultEnabled?`Saved memory module`:`Off`]})]}):null,l.schemaVersion===`openpond.steeringModelServing.v1`?(0,$.jsxs)(`p`,{children:[`Default modification: `,l.defaultPublication?`Saved profile`:`Off`]}):null,l.schemaVersion===`openpond.alphaEditModelServing.v1`||l.schemaVersion===`openpond.neuronTrainingModelServing.v1`||l.schemaVersion===`openpond.decisionModelServing.v1`?(0,$.jsxs)(`p`,{children:[`Qualification: `,l.availability.reason.replaceAll(`_`,` `)]}):null,l.control?.failureCode?(0,$.jsxs)(`p`,{children:[`Recorded serving outcome: `,(0,$.jsx)(`code`,{children:l.control.failureCode})]}):null,l.pools.length?(0,$.jsx)(`div`,{className:`training-table-wrap`,children:(0,$.jsxs)(`table`,{className:`training-data-table labs-managed-serving-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Provider`}),(0,$.jsx)(`th`,{children:`Pool state`}),(0,$.jsx)(`th`,{children:`Worker limit`}),(0,$.jsx)(`th`,{children:`Deployments`}),(0,$.jsx)(`th`,{children:`Active requests`}),(0,$.jsx)(`th`,{children:`Pending reconciliation`}),(0,$.jsx)(`th`,{children:`Retirement`})]})}),(0,$.jsx)(`tbody`,{children:l.pools.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.provider}),(0,$.jsx)(`td`,{children:e.state}),(0,$.jsx)(`td`,{children:e.workersMax}),(0,$.jsx)(`td`,{children:e.activeDeployments}),(0,$.jsx)(`td`,{children:e.activeRequests}),(0,$.jsx)(`td`,{children:e.unsettledRequests}),(0,$.jsx)(`td`,{children:e.retirementBlocked?`In use`:`No consumers recorded`})]},e.id))})]})}):null,l.cleanup.length?(0,$.jsx)(`div`,{className:`training-table-wrap`,children:(0,$.jsxs)(`table`,{className:`training-data-table labs-managed-serving-table`,children:[(0,$.jsx)(`caption`,{children:`Previous serving capacity`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Saved version`}),(0,$.jsx)(`th`,{children:`Request state`}),(0,$.jsx)(`th`,{children:`Capacity`})]})}),(0,$.jsx)(`tbody`,{children:l.cleanup.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.versionHash.slice(0,12)}),(0,$.jsx)(`td`,{children:e.phase}),(0,$.jsx)(`td`,{children:{pending:`Cleanup pending`,shared:`Retained for current consumers`,retiring:`Retirement in progress`,released:`Retirement complete`}[e.capacityState]})]},e.operationId))})]})}):null,(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Serving references`}),(0,$.jsx)(`pre`,{className:`saved-model-version-reference`,children:JSON.stringify({...l,version:l.schemaVersion===`openpond.trainingModelServing.v1`?{contentHash:l.version.contentHash,jobId:l.version.jobId,candidate:l.version.candidate}:l.schemaVersion===`openpond.engramModelServing.v1`||l.schemaVersion===`openpond.decisionModelServing.v1`||l.schemaVersion===`openpond.alphaEditModelServing.v1`||l.schemaVersion===`openpond.neuronTrainingModelServing.v1`?{contentHash:l.version.contentHash,source:l.version.source,artifact:{id:l.version.artifact.id,contentHash:l.version.artifact.contentHash}}:{contentHash:l.version.contentHash,publication:{id:l.version.publication.id,revision:l.version.publication.revision,contentHash:l.version.publication.contentHash}}},null,2)})]})]}):null,n&&t.schemaVersion===`openpond.decisionModelVersion.v1`?(0,$.jsx)(ib,{api:n,version:t,active:l?.schemaVersion===`openpond.decisionModelServing.v1`&&l.state===`active`},`${n.key}:${t.contentHash}`):null,n&&o?(0,$.jsx)(fb,{api:n,version:t,value:c.error?void 0:l,action:o,onClose:()=>s(null)},`${n.key}:${ra(n.connection)}:${i}:${a}`):null]})}function gb({api:e,id:t,execution:n,disabled:r=!1}){let i=Jy(e,t,n),a=kv(),[o,s]=(0,Q.useState)(null),c=`${e.key}:${t}`,l=(0,Q.useRef)(c);l.current=c,(0,Q.useEffect)(()=>(l.current=c,()=>{l.current=``}),[c]);async function u(){let t=i.receipt;if(!(!t||i.busy||i.original||r)){s(null);try{let n=Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:crypto.randomUUID(),operationType:`alphaedit`,name:`${t.model.name} AlphaEdit experiment`,startingModel:await Cn(t.version,{teamId:e.teamId,ownerUserId:e.actorId,label:`${t.model.name} / Saved AlphaEdit matrices`}),alphaEditForm:await Jn(yr(),t.version,{teamId:e.teamId,ownerUserId:e.actorId})});l.current===c&&await a.openDraft(n,as(`experiments`,null,{projectId:e.projectId,executionLocation:`hosted`}))}catch(e){l.current===c&&s(e)}}}let[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)((n?.name??`AlphaEdit Model`).slice(0,200)),[h,g]=(0,Q.useState)(``),_=i.original?.command,v=iy({name:`AlphaEdit Model save`,busy:i.busy,dirty:d&&(!!_||p!==(n?.name??`AlphaEdit Model`).slice(0,200)||!!h),discardDescription:_?`The original save remains recoverable from this execution after closing.`:void 0}),y=n?.method===`alphaedit`&&n.phase===`completed`&&n.result!==null,b=!i.recoveryReady&&i.error!==null;if(!y&&!_&&!i.receipt&&!b)return null;let x=i.receipt?.version;return(0,$.jsxs)(`section`,{className:`training-detail-section`,"aria-label":`Save AlphaEdit Model`,children:[(0,$.jsx)(X,{error:o??i.error}),i.recoveryReady?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Reload retained Model saves`}),i.receipt&&x?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[`Saved to `,i.receipt.model?.name,`. Exact version `,(0,$.jsx)(`code`,{children:x.contentHash}),`.`]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact saved version`}),(0,$.jsx)(`pre`,{className:`saved-model-version-reference`,children:JSON.stringify(x,null,2)})]}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void wo(as(`models`)),children:`Open Models`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:r||i.busy||!!_,onClick:()=>void u(),children:`New experiment from this saved version`})]}),(0,$.jsx)(hb,{connection:e.connection,version:x,api:e},`${e.key}:${x.contentHash}`)]}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:r||i.busy||!i.recoveryReady,onClick:()=>f(!0),children:_?`Recover Model save`:i.receipt?`Save model again`:`Save model`}),d?(0,$.jsxs)(qa,{ariaLabel:`Save AlphaEdit model`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:i.busy,onClose:()=>void v.requestLeave(()=>f(!1)),children:[(0,$.jsx)(`h2`,{children:`Save model`}),(0,$.jsx)(`p`,{children:`Save the exact learned modification from this completed result. Saving does not activate serving.`}),(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),i.save({name:p,modelProjectId:h||null}).then(e=>{e&&(v.allowNextNavigation(),f(!1))})},children:[(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Save destination`}),(0,$.jsx)(Z,{label:`Model destination`,value:_?.modelProjectId??(_?``:h),options:[{value:``,label:`Create new Model`},...(i.options?.models??[]).map(e=>({value:e.id,label:e.name,description:`Current revision ${e.revision}`})),..._?.modelProjectId&&!i.options?.models.some(e=>e.id===_.modelProjectId)?[{value:_.modelProjectId,label:`Original selected Model`}]:[]],disabled:i.busy||!!_||!i.freshReady,onChange:e=>{g(e);let t=i.options?.models.find(t=>t.id===e);t&&m(t.name)}})]}),(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Model name`}),(0,$.jsx)(`input`,{"data-autofocus":!0,value:_?.name??p,maxLength:200,disabled:i.busy||!!_,onChange:e=>m(e.target.value)})]}),_?(0,$.jsx)(`p`,{children:`Original result, module, destination and revision are retained. Retry sends the same operation.`}):null,i.receipt&&_?(0,$.jsx)(`p`,{role:`status`,children:`The Model was saved. Local acknowledgement is pending; retry preserves its exact receipt.`}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:()=>void v.requestLeave(()=>f(!1)),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Refresh targets and recovery`}),(0,$.jsx)(`button`,{type:`submit`,className:`training-button`,disabled:i.busy||r||!i.recoveryReady||!_&&!i.freshReady,children:i.busy?`Saving…`:_?`Retry original save`:`Save model`})]})]})]}):null,v.dialog]})}function _b({api:e,execution:t}){let n=k(e.connection,null),r=By(e),[i,a]=(0,Q.useState)(null),o=n.selection?.alphaEditResult?.id===t.id&&n.selection.alphaEditResult.result?.contentHash===t.result?.contentHash;async function s(){a(null);try{if(!r.data||t.phase!==`completed`||!t.result)throw Error(`Read the exact completed AlphaEdit result in its original account first.`);let i=fn.parse({kind:`alphaedit_result`,location:`cloud`,owner:{teamId:t.teamId,actorId:t.ownerUserId},apiOrigin:r.data.account.apiOrigin,projectId:t.projectId,executionId:t.id,inputHash:t.plan.inputHash,modelHash:t.result.modelHash,runtimeHash:t.plan.runtimeHash,resultHash:t.result.contentHash,artifact:t.result.artifact?{id:t.result.artifact.id,contentHash:t.result.artifact.contentHash}:null});await n.select({kind:`alphaedit_result`,id:t.id,location:`cloud`,teamId:e.teamId,apiOrigin:r.data.account.apiOrigin,result:i})}catch(e){a(e)}}return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{error:i??r.error}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:n.selecting||!r.isSuccess,onClick:()=>void s(),children:o?`Result selected for chat`:`Use result in chat`})]})}async function vb(e,t,n){return Rr(await Sb(e,`gpu-catalog`,t,n),t)}async function yb(e,t,n){return wr(await Sb(e,`estimate`,t,n),t)}async function bb(e,t,n){return xr(await Sb(e,`funding`,t,n),t,e.actorId??void 0)}async function xb(e,t){return Qt(await Sb(e,`funding-handoff`,t),t,e.actorId??void 0)}function Sb(e,t,n,r){return Y(e.connection,`/v1/training/setup/${t}?teamId=${encodeURIComponent(e.teamId)}`,{method:`POST`,body:JSON.stringify(n),signal:r})}function Cb(e){let{api:t,baseModel:n,selection:r,receipt:i}=e,[a,o]=(0,Q.useState)(0),s=e.recipe?.lora&&typeof e.recipe.lora==`object`&&`rank`in e.recipe.lora?e.recipe.lora.rank:void 0,c=Nr.safeParse({teamId:t.teamId,modelId:n?.modelId,modelRevision:n?.revision,tokenizerRevision:n?.tokenizerRevision,chatTemplateHash:n?.chatTemplateHash,method:e.method,loraRank:s,gpuCount:r.gpuCount??1}),l=c.success?c.data:null,u=S({queryKey:[`experiment-compute`,t.accountKey,t.actorId,t.connection.serverUrl,t.projectId,l],enabled:e.enabled&&l!==null&&i===null,queryFn:({signal:e})=>{if(!l)throw Error(`Choose a pinned model and valid LoRA rank before loading compute.`);return vb(t,l,e)},retry:!1,staleTime:0}),d=i?.state===`prepared`?{schemaVersion:`openpond.trainingEstimateRequest.v1`,teamId:t.teamId,source:{kind:`preparation`,id:i.plan.id,planHash:i.plan.contentHash,expectedRevision:i.revision},...i.plan.request.gpuSelection?{gpuSelection:i.plan.request.gpuSelection}:{}}:null,f=S({queryKey:[`experiment-estimate`,t.accountKey,t.actorId,t.connection.serverUrl,t.projectId,d],enabled:e.enabled&&d!==null,queryFn:({signal:e})=>{if(!d)throw Error(`Review the experiment before requesting an estimate.`);return yb(t,d,e)},retry:!1,staleTime:1/0,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),p=wb(u.data?.expiresAt),m=f.data?new Date(Math.min(Date.parse(f.data.expiresAt),f.data.pricing.quoteExpiresAt?Date.parse(f.data.pricing.quoteExpiresAt):1/0)).toISOString():void 0,h=wb(m);function g(){let e=f.data;if(!d||!e||f.isFetching||f.isError||f.dataUpdatedAt<=a||!m||Date.parse(m)<=Date.now())throw Error(`Refresh and review the current estimate before starting training.`);if(!e.gpu.resolved||![`available`,`limited`].includes(e.gpu.availability))throw Error(`Refresh compute availability before starting this experiment.`);return e.review}return{catalog:u,query:l,catalogExpired:p,estimate:f,estimateExpired:h,reviewedEstimate:g,requireFreshReview:()=>o(Date.now()),canStart:!!(d&&f.data?.gpu.resolved&&[`available`,`limited`].includes(f.data.gpu.availability)&&f.dataUpdatedAt>a&&!h&&!f.isFetching&&!f.isError)}}function wb(e){let[,t]=(0,Q.useState)(0);return(0,Q.useEffect)(()=>{if(!e)return;let n=Date.parse(e)-Date.now();if(n<=0)return;let r=setTimeout(()=>t(e=>e+1),Math.min(n+1,2147483647));return()=>clearTimeout(r)},[e]),!!(e&&Date.parse(e)<=Date.now())}function Tb(e,t,n,r=!1){let i=Number(t),a=!1;try{vt(t),a=!0}catch{}let o=!!(e.actorId&&(r?a:Number.isFinite(i)&&i>0&&i<=1e6)),s=S({queryKey:[`experiment-funding`,e.connection.serverUrl,e.accountKey,e.actorId,e.teamId,i],enabled:n&&o&&!r,queryFn:({signal:t})=>{if(!o)throw Error(`Enter a valid maximum spend before checking credits.`);return bb(e,{schemaVersion:`openpond.trainingFundingRequest.v1`,teamId:e.teamId,maximumSpendUsd:i},t)},retry:!1,staleTime:0}),c=wb(s.data?.expiresAt);function l(){if(r){if(!o)throw Error(`Choose a valid spending limit or use available credits.`)}else{if(!s.data||s.isFetching||s.isError||Date.parse(s.data.expiresAt)<=Date.now())throw Error(`Refresh credits before starting this experiment.`);if(s.data.state!==`covered`)throw Error(`This spending cap is not currently funded. Check credits and workspace limits before starting.`)}}async function u(){r||await s.refetch()}return{query:s,valid:o,expired:c,assertCovered:l,allocationAdmission:r,refresh:u,canStart:r?o:s.data?.state===`covered`&&!c&&!s.isFetching&&!s.isError}}var Eb=e=>new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,maximumFractionDigits:2}).format(Number(e));function Db({funding:e,busy:t,startAttempted:n,billingReturnPending:r,onOpenBilling:i,onRefresh:a}){let o=e.query.data;return e.allocationAdmission?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:`Credits are checked when compute is allocated. An optional spending limit caps total usage; it does not reserve that amount.`}),r?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:`Your experiment is saved. Return from Billing to review it before starting.`}),(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:t||n,onClick:()=>void a(),children:`Return from Billing`})]}):null,i?(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:t||n||!e.valid,onClick:()=>void i(),children:`Add credits`}):null]}):(0,$.jsxs)($.Fragment,{children:[e.query.isFetching?(0,$.jsx)(`p`,{role:`status`,children:`Checking credits…`}):null,o&&!e.query.isError?(0,$.jsxs)($.Fragment,{children:[o.availableUsageUsd===null?null:(0,$.jsxs)(`dl`,{className:`training-compute-summary`,children:[(0,$.jsx)(`dt`,{children:`Available usage`}),(0,$.jsx)(`dd`,{children:Eb(o.availableUsageUsd)})]}),(0,$.jsx)(`p`,{children:e.expired?`Refresh credits before starting.`:{covered:`Current credits cover this spending cap.`,insufficient_credit:`More credits are needed to cover this spending cap.`,member_limit:`This cap exceeds your workspace member spending limit.`,unavailable:`Workspace funding is unavailable for this cap.`}[o.state]}),!o.canPurchase&&o.state===`insufficient_credit`?(0,$.jsx)(`p`,{children:`A workspace billing owner can add credits.`}):null]}):null,r?(0,$.jsx)(`p`,{children:`Your experiment is saved. Finish in Billing, then return here to refresh credits and review the estimate.`}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:t||n||!e.valid||e.query.isFetching,onClick:()=>void a(),children:`Refresh credits`}),i&&o?.canPurchase?(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:t||n||!e.valid,onClick:()=>void i(),children:`Add credits`}):null,(0,$.jsx)(X,{error:e.query.error})]})}function Ob({owner:e,api:t,onOpenBilling:n=null,billingReturnPending:r=!1,onRefreshFunding:i,disabled:a=!1}){let o=e.busy||a,s=e.execution,c=e.original,l=(e.receipt&&(!s||e.receipt.execution.id===s.id&&e.receipt.execution.revision>s.revision)?e.receipt.execution:s)??(c&&`execution`in c.intent?c.intent.execution:null),[u,d]=(0,Q.useState)(null),f=Tb(t,l?.plan.maximumSpendUsd??``,!!l,!!l?.plan.computePrice),p=c?`action`in c.command?c.command.action:`prepare`:null;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{error:e.error}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o||e.loading,onClick:e.refresh,children:`Refresh execution and recovery`}),c?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||!e.recoveryReady,onClick:()=>void e.retry(),children:o?`Reconciling…`:`Retry original ${p}`}):null]}),c&&!(`action`in c.command)?(0,$.jsxs)(ft,{title:`Original preparation`,children:[(0,$.jsxs)(`p`,{children:[c.command.name,` · `,c.command.method,` · `,Uy(c.command.maximumSpendUsd)]}),(0,$.jsxs)(`p`,{children:[c.command.request.training.maxSteps,` training steps · batch`,` `,c.command.request.data.edits.batch.id,` ·`,` `,c.command.request.model.modelId,` · `,c.command.request.model.revision]})]}):null,l?(0,$.jsxs)(ft,{title:`Hosted execution`,children:[(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`State`}),(0,$.jsx)(`dd`,{children:l.phase}),(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(l.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:l.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Execution`}),(0,$.jsx)(`dd`,{children:l.id}),(0,$.jsx)(`dt`,{children:`Preparation expires`}),(0,$.jsx)(`dd`,{children:new Date(l.plan.expiresAt).toLocaleString()}),(0,$.jsx)(`dt`,{children:`Exact plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:l.plan.contentHash}),(0,$.jsx)(`dt`,{children:`Runtime`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:l.plan.runtimeHash})]}),s?(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[s.phase===`prepared`?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||e.loading||!e.ready||!e.canControl||!!c||Date.parse(s.plan.expiresAt)<=Date.now(),onClick:()=>d({action:`start`,value:s}),children:`Review Start`}):null,[`completed`,`cancelled`,`failed`].includes(s.phase)?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o||e.loading||!e.ready||!e.canControl||!!c,onClick:()=>d({action:`cancel`,value:s}),children:`Review Cancel`})]}):null]}):null,s?.phase===`completed`&&s.result?(0,$.jsx)(_b,{api:t,execution:s}):null,s?.result?(0,$.jsx)(t_,{result:s.result}):l?.phase===`completed`?(0,$.jsx)(`p`,{children:`No result bytes are available in this read. Retained execution identity remains available for recovery.`}):null,e.selectedId?(0,$.jsx)(gb,{api:t,id:e.selectedId,execution:s,disabled:o||!!c},`${t.key}:${e.selectedId}`):null,u&&s?(0,$.jsxs)(qa,{ariaLabel:u.action===`start`?`Start AlphaEdit experiment`:`Cancel AlphaEdit experiment`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:o,onClose:()=>{o||d(null)},children:[(0,$.jsx)(`h2`,{children:u.action===`start`?`Start AlphaEdit experiment`:`Cancel AlphaEdit experiment`}),(0,$.jsx)(`p`,{children:u.action===`start`?Gy(u.value.plan.computePrice):`Cancel this exact execution. In-flight work may need to stop and settle before capacity is released.`}),(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(u.value.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:u.value.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Training steps`}),(0,$.jsx)(`dd`,{children:u.value.request.training.maxSteps}),(0,$.jsx)(`dt`,{children:`Reviewed batch`}),(0,$.jsxs)(`dd`,{children:[u.value.request.data.edits.batch.id,` · release`,` `,u.value.request.data.edits.batch.revision]}),(0,$.jsx)(`dt`,{children:`Maximum duration`}),(0,$.jsxs)(`dd`,{children:[u.value.request.training.maxDurationSeconds,` seconds`]}),(0,$.jsx)(`dt`,{children:`Model`}),(0,$.jsxs)(`dd`,{children:[u.value.request.model.modelId,` · `,u.value.request.model.revision]}),(0,$.jsx)(`dt`,{children:`Plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:u.value.plan.contentHash})]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact prepared training request`}),(0,$.jsx)(`pre`,{children:JSON.stringify(u.value.request,null,2)})]}),u.action===`start`?(0,$.jsx)(Db,{funding:f,busy:o,startAttempted:!!c,billingReturnPending:r,onOpenBilling:n,onRefresh:i??(async()=>{await f.refresh()})}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o,onClick:()=>d(null),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||e.loading||!!c||!e.ready||!e.canControl||u.action===`start`&&(r||!f.canStart||Date.parse(u.value.plan.expiresAt)<=Date.now()),onClick:()=>void e.control(u.action,u.value).then(e=>{e&&d(null)}),children:o?`Applying…`:u.action===`start`?Ky(u.value.plan.maximumSpendUsd):`Cancel execution`})]})]}):null]})}var kb=(0,Q.lazy)(()=>o(()=>import(`./ExperimentTrainingDataWorkspace-CfOyoMrq.js`),__vite__mapDeps([76,1,2,3,4,77,5,6,9,10,78,32,27,31,21,16,43,19,20,22,13,23,15,24,25,26,8,28,11,29,30,33,34,35,36,37,38,39,40,41,18,42,44,45,46,47,48,49,50,51,52,53,54,55,56,79,80])));function Ab({api:e,visible:t,onClose:n,onSaveDraft:r}){let i=kv(),[a,o]=(0,Q.useState)(()=>i.initialExperiment?.alphaEditForm??yr(i.trainingBaseModel)),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(`editsBatch`),[h,g]=(0,Q.useState)(!1),_=(0,Q.useRef)(null),v=(0,Q.useRef)(!1),y=(0,Q.useRef)(null),b=(0,Q.useRef)(!1),x=J([e.key,e.accountKey,e.actorId,e.teamId,e.projectId,e.connection.serverUrl,i.initialExperiment?.id]),C=(0,Q.useRef)(x);C.current=x,(0,Q.useEffect)(()=>(C.current=x,()=>{C.current=``}),[x]);function w(){if(C.current!==x)throw Error(`Return to this experiment's original account before continuing.`)}let T=Hy(e,{draftId:i.initialExperiment?.id??null,method:`alphaedit`,visible:t}),E=Ry(e,t,a.editsBatch,[a.preservationBatch]),D=By(e,t),O=i.trainingBaseModel,k=!i.startingModel||i.startingModel.source===`managed`||i.startingModel.source===`alphaedit`,A=wv(i.startingModel),j=(0,Q.useRef)(A);(0,Q.useEffect)(()=>{j.current!==A&&i.startingModel?.source!==`alphaedit`&&o(({startingModule:e,...t})=>({...t,parentArtifact:null})),j.current=A},[A,i.startingModel?.source]);let M=O?.source===`managed`&&k?{teamId:e.teamId,source:O.source,modelId:O.modelId,...O.revision?{revision:O.revision}:{},...O.tokenizerRevision?{tokenizerRevision:O.tokenizerRevision}:{},...O.chatTemplateHash?{chatTemplateHash:O.chatTemplateHash}:{},...O.modelAssetId?{modelAssetId:O.modelAssetId}:{}}:null,N=S({queryKey:[`alphaedit-execution-capability`,x,M],enabled:t&&!!(D.data&&M),retry:!1,staleTime:3e4,queryFn:({signal:e})=>{if(!D.data||!M)throw Error(`Choose an exact managed base before checking AlphaEdit availability.`);return D.data.capability(M,e)},refetchInterval:e=>!e.state.error&&6e4}),P=N.data&&!N.isError&&Date.parse(N.data.expiresAt)>Date.now()?N.data.execution:null,F=T.selectedId&&![`completed`,`failed`,`cancelled`].includes(T.execution?.phase??T.receipt?.execution.phase??`prepared`),I=s||T.busy,L=I||!!(T.original||F),ee=J({...a,baseModel:O,sourceKey:A}),R=(0,Q.useRef)(ee);R.current=ee;let z=(0,Q.useRef)(ee),B=Tb(e,a.maximumSpendUsd,t,!0),V=ee!==z.current,H=i.reportOperationDraftDirty;(0,Q.useEffect)(()=>{H(`alphaedit`,V)},[V,H]);let U=iy({name:`AlphaEdit experiment`,dirty:V||i.operationDraftDirty||i.evaluationDirty,busy:I,onLeave:n});My({...U,requestLeave:async e=>{d&&y.current?await y.current.requestLeave(()=>U.requestLeave(e)):await U.requestLeave(e)}},t);function te(e){o(t=>({...t,...e}))}function ne(){if(!i.initialExperiment)throw Error(`Open an experiment before saving its settings.`);if(!k)throw Error(`AlphaEdit requires its exact managed base. Choose another starting model.`);return Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:i.initialExperiment.id,operationType:`alphaedit`,name:a.name.trim()||`AlphaEdit experiment`,...i.startingModel?{startingModel:i.startingModel}:{},alphaEditForm:{...a,baseModel:O}})}async function re(t){if(!r)throw Error(`Load canonical draft storage before preparing.`);await r(t),w();let n=await Iy(e).get(t.id);if(w(),n.status!==`draft`||n.projectId!==e.projectId||J(n.draft)!==J(t))throw Error(`The saved experiment changed. Reopen its exact current revision before continuing.`);return z.current=ee,n}async function W(){if(!(b.current||L)){b.current=!0,c(!0),u(null);try{await re(ne())}catch(e){C.current===x&&u(e)}finally{b.current=!1,C.current===x&&c(!1)}}}async function ie(){if(b.current||T.busy||T.original)return;b.current=!0,c(!0),u(null);let t=null;try{let n=window.openpond?.browser;if(!n?.openExternal){if(t=window.open(`about:blank`,`_blank`),!t)throw Error(`Allow a new tab to open Billing, then try again.`);t.opener=null}let r=await re(ne());w();let i=vt(a.maximumSpendUsd),o=await xb(e,{schemaVersion:`openpond.trainingFundingHandoffRequest.v1`,teamId:e.teamId,maximumSpendUsd:i===null?null:Number(i),draft:{id:r.id,revision:r.revision,contentHash:r.contentHash,projectId:r.projectId}});if(w(),!o.canPurchase||!o.billingUrl)throw Error(`A workspace billing owner needs to add credits for this experiment.`);if(_.current={record:r,snapshot:ee},g(!0),n?.openExternal){let e=await n.openExternal({conversationId:`experiment-funding:${r.id}`,url:o.billingUrl});if(w(),!e.ok)throw Error(e.error??`Billing could not be opened. Your experiment is saved; try again.`)}else t&&=(t.location.replace(o.billingUrl),null)}catch(e){t?.close(),C.current===x&&(u(e),g(!1),_.current=null)}finally{b.current=!1,C.current===x&&c(!1)}}async function G(){if(!(v.current||C.current!==x)){v.current=!0;try{let t=_.current;if(t){let n=await Iy(e).get(t.record.id);if(w(),n.contentHash!==t.record.contentHash||n.status!==`draft`||R.current!==t.snapshot)throw Error(`This experiment changed while Billing was open. Your edits remain here; save and review them before preparing.`)}await B.refresh(),w()}catch(e){C.current===x&&u(e)}finally{v.current=!1,C.current===x&&(_.current=null,g(!1))}}}let ae=(0,Q.useRef)(G);ae.current=G,(0,Q.useEffect)(()=>{if(!h)return;let e=()=>{document.visibilityState===`visible`&&ae.current()};return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[h]);async function K(e){if(w(),L||!t)throw Error(`Return to the editable experiment before selecting data.`);if(Fe(e),e.purpose!==`supervised_training`||!e.sealedAt||!e.examples.length)throw Error(`Choose a sealed, reviewed supervised training batch.`);te({[p]:xe(e)}),f(!1)}let q=E.batches.filter(e=>e.purpose===`supervised_training`&&e.sealedAt&&e.exampleCount>0),oe=a.editsBatch?J(a.editsBatch):``,se=q.find(e=>J(e.reference)===oe),ce=q.map(e=>({value:J(e.reference),label:`${e.reference.id} · release ${e.reference.revision} · ${e.exampleCount} examples`}));oe&&!ce.some(e=>e.value===oe)&&ce.unshift({value:oe,label:`${a.editsBatch.id} · saved release ${a.editsBatch.revision}`,disabled:!0});let le=i.startingModel?.source===`trained`?`trained:${i.startingModel.trainedVersion.contentHash}`:i.startingModel?.source===`alphaedit`?`alphaedit:${i.startingModel.alphaedit.versionHash}`:i.startingModel?.source===`steering`?`steering:${i.startingModel.steering.versionHash}`:i.startingModel?.source===`inference`?`inference:${i.startingModel.inferenceModelId}`:O?J(O):``,ue=E.models.filter(e=>e.preference.source===`managed`).map(e=>({value:J(e.preference),label:e.name}));return le&&!ue.some(e=>e.value===le)&&ue.unshift({value:le,label:i.startingModel?.label??O?.modelId??`Saved starting model`,disabled:!0}),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{hidden:d,inert:d,children:(0,$.jsxs)(Bv,{label:`Experiment setup`,action:`experiment`,onRequestClose:()=>void U.requestLeave(n),children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`h2`,{children:`Run Experiment`}),(0,$.jsx)(`button`,{type:`button`,disabled:I,onClick:()=>void U.requestLeave(n),children:`Close setup`})]}),(0,$.jsx)(X,{error:l??E.error??N.error??D.error}),(0,$.jsxs)(`form`,{noValidate:!0,onSubmit:e=>{e.preventDefault(),W()},children:[(0,$.jsx)(ft,{title:`Starting model`,children:(0,$.jsxs)(`fieldset`,{disabled:L,children:[(0,$.jsxs)(`label`,{children:[`Model`,(0,$.jsx)(Z,{label:`AlphaEdit starting model`,floating:!0,searchable:!0,value:le,options:[{value:``,label:`Choose exact managed base`},...ue],onChange:e=>{if(e===le)return;let t=E.models.find(t=>J(t.preference)===e&&t.preference.source===`managed`);e&&!t?u(`Refresh the model list before changing this selection.`):(i.setTrainingBaseModel(t?.preference??null),o(({startingModule:e,...t})=>({...t,parentArtifact:null})))}})]}),(0,$.jsx)(xy,{disabled:L}),(0,$.jsx)(`p`,{children:`AlphaEdit edits factual associations in the exact managed backbone. Preparation resolves reviewed edit and preservation batches and the qualified runtime.`}),(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:I||E.isFetching,onClick:()=>void E.refetch(),children:`Refresh models and reviewed batches`}),P?(0,$.jsx)(`p`,{children:P.state===`unavailable`?P.reason:`A compatible AlphaEdit runtime is available. Preparation rechecks its exact identity.`}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:I||N.isFetching||!M,onClick:()=>{D.refetch(),N.refetch()},children:`Refresh runtime availability`})]})}),(0,$.jsx)(ft,{title:`Training data`,children:(0,$.jsxs)(`fieldset`,{disabled:L,children:[(0,$.jsxs)(`label`,{children:[`Reviewed edits batch`,(0,$.jsx)(Z,{label:`AlphaEdit reviewed edits`,floating:!0,searchable:!0,value:oe,options:[{value:``,label:`Choose sealed supervised batch`},...ce],onChange:e=>{let t=q.find(t=>J(t.reference)===e);e&&!t?u(`Refresh the reviewed batch before changing this selection.`):te({editsBatch:t?.reference??null})}})]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>{m(`editsBatch`),f(!0)},children:`Import or review edits`})]})}),(0,$.jsx)(ft,{title:`Preservation data`,children:(0,$.jsxs)(`fieldset`,{disabled:L,children:[(0,$.jsxs)(`label`,{children:[`Preservation batch`,(0,$.jsx)(Z,{label:`AlphaEdit preservation batch`,floating:!0,searchable:!0,value:a.preservationBatch?J(a.preservationBatch):``,options:[{value:``,label:`Choose reviewed preservation batch`},...ce],onChange:e=>{let t=q.find(t=>J(t.reference)===e);e&&!t?u(`Refresh this exact preservation release before choosing it.`):te({preservationBatch:t?.reference??null})}})]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>{m(`preservationBatch`),f(!0)},children:`Import or review preservation data`}),(0,$.jsx)(`p`,{children:`Edit input contains subject and promptTemplate. Its reviewed expected output is an object with a text field containing the literal target. Preservation input contains text; its expected output has the same text field and literal value.`})]})}),(0,$.jsx)(ft,{title:`Settings`,children:(0,$.jsxs)(`fieldset`,{disabled:L,children:[(0,$.jsxs)(`label`,{children:[`Experiment name`,(0,$.jsx)(`input`,{value:a.name,maxLength:500,onChange:e=>te({name:e.target.value})})]}),(0,$.jsx)(Fy,{form:a,onChange:o}),a.startingModule?(0,$.jsxs)(`p`,{children:[`Saved Model `,a.startingModule.modelProjectId,` · version`,` `,a.startingModule.versionHash]}):null,a.parentArtifact?(0,$.jsxs)(`p`,{children:[`Continue exact matrices and sequential state `,a.parentArtifact.id,` ·`,` `,a.parentArtifact.contentHash,`.`]}):null,(0,$.jsxs)(`label`,{children:[`Spending limit (USD, optional)`,(0,$.jsx)(`input`,{type:`text`,inputMode:`decimal`,maxLength:100,placeholder:`Use available credits`,value:a.maximumSpendUsd,onChange:e=>te({maximumSpendUsd:e.target.value})})]})]})}),(0,$.jsx)(Db,{funding:B,busy:I,startAttempted:!!T.original,billingReturnPending:h,onOpenBilling:r?ie:null,onRefresh:G}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`submit`,className:`training-button secondary`,disabled:L||!r,children:s?`Saving…`:`Save draft`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:L||h||!r||!T.ready||!E.isSuccess||P?.state!==`ready`||!se||!a.preservationBatch,onClick:()=>{u(null);try{T.prepare(ne(),re)}catch(e){u(e)}},children:`Compile and prepare`})]})]}),(0,$.jsx)(Ob,{owner:T,api:e,disabled:I,onOpenBilling:r?ie:null,billingReturnPending:h,onRefreshFunding:G}),U.dialog]})}),d?(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`p`,{role:`status`,children:`Opening training data…`}),children:(0,$.jsx)(kb,{api:e,method:`alphaedit`,navigation:y,onClose:()=>f(!1),onUseBatch:K,beforeImport:async()=>{if(w(),L)throw Error(`Finish the original operation before importing data.`);await re(ne()),w()}})}):null]})}var jb={count:`Selected neuron count`,maximumBackgroundTargetRatio:`Maximum background to target activation ratio`,gradientExamples:`Gradient selection examples`},Mb={learningRate:`Learning rate`,maxSteps:`Maximum optimizer steps`,gradientAccumulationSteps:`Gradient accumulation steps`,maxSequenceLength:`Maximum sequence tokens`,preservationWeight:`Preservation weight`,preservationExamplesPerStep:`Preservation examples per step`,seed:`Seed`,maxDurationSeconds:`Maximum duration (seconds)`,maxCheckpointBytes:`Maximum checkpoint bytes`,maximumForwardTokenWork:`Maximum forward token work`};function Nb({form:e,onChange:t}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:`Select neurons from reviewed target and background domains, then train only their output projection columns. The saved inference delta does not contain optimizer state.`}),(0,$.jsxs)(`label`,{children:[`Selection span`,(0,$.jsx)(Z,{floating:!0,label:`Selection span`,value:e.selection.span,options:[{value:`reply_prediction`,label:`Reply prediction`},{value:`reply_start`,label:`Reply start`},{value:`prompt`,label:`Prompt`}],onChange:n=>{(n===`reply_prediction`||n===`reply_start`||n===`prompt`)&&t({...e,selection:{...e.selection,span:n}})}})]}),(0,$.jsxs)(`label`,{children:[`Background statistic`,(0,$.jsx)(Z,{floating:!0,label:`Background statistic`,value:e.selection.backgroundStatistic,options:[{value:`max_domains`,label:`Maximum across domains`},{value:`mean_domains`,label:`Mean across domains`}],onChange:n=>{(n===`max_domains`||n===`mean_domains`)&&t({...e,selection:{...e.selection,backgroundStatistic:n}})}})]}),Object.keys(jb).map(n=>(0,$.jsxs)(`label`,{children:[jb[n],(0,$.jsx)(`input`,{inputMode:`decimal`,value:e.selection[n],maxLength:100,onChange:r=>t({...e,selection:{...e.selection,[n]:r.target.value}})})]},n)),(0,$.jsxs)(`label`,{children:[`Explicit coordinates (optional)`,(0,$.jsx)(`textarea`,{rows:5,value:e.selection.coordinates,maxLength:1e4,onChange:n=>t({...e,selection:{...e.selection,coordinates:n.target.value}})})]}),(0,$.jsx)(`p`,{children:`Leave blank for automatic selection. Otherwise enter one layer:neuron coordinate per line; distinct coordinates must match the selected count.`}),Object.keys(Mb).map(n=>(0,$.jsxs)(`label`,{children:[Mb[n],(0,$.jsx)(`input`,{inputMode:`decimal`,value:e.training[n],maxLength:100,onChange:r=>t({...e,training:{...e.training,[n]:r.target.value}})})]},n)),e.inspectionSource?(0,$.jsxs)(`p`,{className:`saved-model-version-reference`,children:[`Selection evidence: `,e.inspectionSource.result.executionId,` · model`,` `,e.inspectionSource.modelHash,`. The compiler reauthorizes this original inspection.`]}):null]})}function Pb(e,t){let n=ml.parse({teamId:e.teamId,actorId:e.actorId,apiOrigin:t}),r={...n,projectId:e.projectId},i=`/v1/training/neuron-training-executions`;return{account:n,async capability(t,a){return Dn(await Y(e.connection,`${i}/capability`,{method:`POST`,signal:a,body:JSON.stringify({...r,capabilityQuery:t})}),t,n.actorId)},async compile(t){return yn(await Y(e.connection,`${i}/compile`,{method:`POST`,body:JSON.stringify({...r,command:t})}),t)},async mutate(t,a){let o=`action`in t?`${i}/${encodeURIComponent(t.id)}/${t.action}`:`${i}/prepare`,s=await Tn(await Y(e.connection,o,{method:`POST`,body:JSON.stringify({...r,intentHash:a,command:t})}),t);if(s.execution.ownerUserId!==n.actorId||s.execution.projectId!==e.projectId)throw Error(`The execution receipt belongs to another account or Project.`);return s},async get(t,r){let a=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}}),o=await $n(await Y(e.connection,`${i}/${encodeURIComponent(t)}?${a}`,{signal:r}),{teamId:e.teamId,id:t,ownerUserId:n.actorId});if(e.projectId!==null&&o.projectId!==e.projectId)throw Error(`The execution belongs to another Project.`);return o},async list(t={},r){let a={...t,...e.projectId?{projectId:e.projectId}:{}},o=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}});for(let[e,t]of Object.entries(a))t!==void 0&&o.set(e,String(t));return cr(await Y(e.connection,`${i}?${o}`,{signal:r}),{teamId:e.teamId,ownerUserId:n.actorId,query:a})}}}function Fb(e,t=!0){return S({queryKey:[`neuron-training-experiment-account`,e.key,e.actorId],enabled:t&&e.location===`hosted`&&!!e.actorId,retry:!1,queryFn:async({signal:t})=>{let n=await e.request(`inventory`,{},t);if(n.teamId!==e.teamId)throw Error(`The workspace account changed.`);return Pb(e,n.apiOrigin)}})}var Ib=[`training:prepare-neuron-training`,`training:start-neuron-training`,`training:cancel-neuron-training`];function Lb(e,t){let n=u(),r=J([e.key,e.accountKey,e.actorId,e.teamId,e.projectId,e.connection.serverUrl,t.draftId,t.executionId,t.method]),i=(0,Q.useRef)(r);i.current=r,(0,Q.useEffect)(()=>(i.current=r,()=>{i.current=``}),[r]);let a=()=>({identity:r,busy:!1,error:null,receipt:null,selected:null,original:null,preparationOperationId:null}),[o,s]=(0,Q.useState)(a),c=(0,Q.useRef)(new Set),l=o.identity===r?o:a();function d(e){i.current===r&&s(t=>({...t.identity===r?t:a(),...e}))}function f(){if(i.current!==r)throw Error(`Return to this experiment's original account before continuing.`)}let p=Fb(e,t.visible),m=p.data,h=S({queryKey:[`neuron-training-experiment-recovery`,r],enabled:t.visible&&e.location===`hosted`&&!!e.actorId&&!l.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[];for(let i of Ib){let a,o=new Set;for(let s=0;;s++){if(s>=100)throw Error(`The retained execution catalog exceeds its supported bound.`);let c=await e.pendingOperations(i,a,n);for(let n of c.items){let a=i===Ib[0]?Wl.parse(n.reviewedIntent):Gl.parse(n.reviewedIntent);if(a.account.actorId!==e.actorId||a.account.teamId!==e.teamId)throw Error(`The retained execution belongs to another account.`);if(!(t.draftId===null?`execution`in a&&a.execution.id===t.executionId:a.draftId===t.draftId))continue;let o=i===Ib[0]?Er.parse(n.command??{...a.request,operationId:n.id}):Wt(n.command??{...a.request,operationId:n.id});r.push({intent:a,command:o,operation:e.recoverOperation(n)})}if(!c.nextCursor)break;if(o.has(c.nextCursor))throw Error(`The retained execution catalog repeated a cursor.`);o.add(c.nextCursor),a=c.nextCursor}}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),g=l.original??h.data?.[0]??null,_=t.executionId??l.selected??l.receipt?.execution.id??(g&&`execution`in g.intent?g.intent.execution.id:null),v=S({queryKey:[`managed-neuron-training-execution`,r,_],enabled:t.visible&&!!(m&&_),retry:!1,queryFn:({signal:e})=>{if(!m||!_)throw Error(`Select an execution first.`);return m.get(_,e)},refetchInterval:e=>e.state.error?!1:e.state.data&&![`completed`,`failed`,`cancelled`].includes(e.state.data.phase)?3e3:!1});async function y(t){let r=Pb(e,t.intent.account.apiOrigin);if(J(r.account)!==J(t.intent.account))throw Error(`Return to this execution's original account before retrying.`);d({original:t}),await t.operation.retainCommand(t.command,`dispatching`),f();let i=await r.mutate(t.command,t.operation.intentHash);return f(),d({receipt:i,selected:i.execution.id,preparationOperationId:`action`in t.command?`preparationOperationId`in t.intent?t.intent.preparationOperationId:null:t.command.operationId}),await t.operation.acknowledge(),f(),d({original:null}),await h.refetch(),f(),n.invalidateQueries({queryKey:[`managed-neuron-training-execution`]}),n.invalidateQueries({queryKey:[`unified-experiments`]}),i}async function b(e){if(!c.current.has(r)){c.current.add(r),d({busy:!0,error:null});try{return f(),await e()}catch(e){return i.current===r&&d({error:e}),null}finally{c.current.delete(r),d({busy:!1})}}}async function x(n,r){return b(async()=>{if(g)return y(g);if(!m||!h.isSuccess||!t.draftId||n.id!==t.draftId||!n.neuronTrainingForm||!t.method)throw Error(`Load this saved experiment and original requests before preparing.`);let i=vt(n.neuronTrainingForm.maximumSpendUsd);await r(n),f();let a=await Iy(e).get(n.id);if(f(),a.status!==`draft`||a.projectId!==e.projectId||J(a.draft)!==J(n))throw Error(`The saved experiment changed. Reopen its exact current revision before preparing.`);let o=n.neuronTrainingForm.baseModel;if(!o||o.source!==`managed`||n.startingModel&&![`managed`].includes(n.startingModel.source))throw Error(`Choose a qualified exact NeuronTraining starting model.`);let s={teamId:e.teamId,modelId:o.modelId,source:o.source,...o.revision?{revision:o.revision}:{},...o.tokenizerRevision?{tokenizerRevision:o.tokenizerRevision}:{},...o.chatTemplateHash?{chatTemplateHash:o.chatTemplateHash}:{},...o.modelAssetId?{modelAssetId:o.modelAssetId}:{}},c={teamId:e.teamId,projectId:e.projectId,method:t.method,query:s,form:n.neuronTrainingForm},l=await m.compile(c);if(f(),l.actorId!==e.actorId||l.formHash!==await zr(n.neuronTrainingForm))throw Error(`The compilation differs from this exact saved form.`);let u=await Wn({teamId:e.teamId,projectId:e.projectId,operationId:crypto.randomUUID(),name:n.name,method:t.method,query:s,request:l.request,sourceForm:n.neuronTrainingForm,maximumSpendUsd:i}),{operationId:d,...p}=u,_=Wl.parse({account:m.account,draftId:n.id,request:p}),v=await e.operation(Ib[0],_);return f(),y({intent:_,operation:v,command:{...u,operationId:v.id}})})}async function C(n,r){return b(async()=>{if(g)return y(g);let i=r??v.data;if(!m||!h.isSuccess||!i||v.error)throw Error(`Read the exact execution before reviewing its next action.`);let{schemaVersion:a,request:o,sourceForm:s,result:c,resultRecordedAt:u,contentHash:d,...p}=i,_=Rt.parse(p),b=n===`start`?{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n,approvedMaximumSpendUsd:i.plan.maximumSpendUsd,...i.plan.computePrice?{approvedPriceHash:await zr(i.plan.computePrice)}:{}}:{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n},x=Gl.parse({account:m.account,draftId:l.preparationOperationId?t.draftId:null,preparationOperationId:l.preparationOperationId,execution:_,request:b}),S=await e.operation(n===`start`?Ib[1]:Ib[2],x);return f(),y({intent:x,operation:S,command:Wt({...b,operationId:S.id})})})}return{prepare:x,control:C,retry:()=>b(()=>{if(!g)throw Error(`Reload the original execution request.`);return y(g)}),busy:l.busy,receipt:l.receipt,original:g,execution:v.data,ready:p.isSuccess&&h.isSuccess,recoveryReady:!!g||h.isSuccess,canControl:v.isSuccess&&!v.error,error:l.error??p.error??h.error??v.error,refresh:()=>{p.refetch(),e.actorId&&h.refetch(),m&&_&&v.refetch()},loading:v.isFetching||p.isFetching,selectedId:_}}var Rb=`training-neuron-training-result-save`;function zb(e,t,n){let r=u(),i=J([e.key,ra(e.connection),t]),a=(0,Q.useRef)(i);a.current=i,(0,Q.useEffect)(()=>(a.current=i,()=>{a.current=``}),[i]);let o=()=>({identity:i,busy:!1,error:null,original:null,receipt:null}),[s,c]=(0,Q.useState)(o),l=(0,Q.useRef)(new Set),d=s.identity===i?s:o();function f(e){a.current===i&&c(t=>({...t.identity===i?t:o(),...e}))}function p(){if(a.current!==i)throw Error(`Return to this Model save's original account and result.`)}let m=n?.method===`selective_neuron_training`&&n.phase===`completed`&&n.result!==null,h=Fb(e,m),g=S({queryKey:[`neuron-training-model-save-recovery`,i],enabled:!!e.actorId&&!d.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[],i=new Set,a;for(let o=0;;o++){if(o>=100)throw Error(`The retained Model save catalog exceeds its supported bound.`);let s=await e.pendingOperations(Rb,a,n);for(let n of s.items){let i=Yl.parse(n.reviewedIntent);if(i.request.executionId!==t)continue;if(i.account.actorId!==e.actorId||i.account.teamId!==e.teamId||i.execution.projectId!==e.projectId)throw Error(`The retained Model save belongs to another creator or Project.`);let a=kt.parse(n.command??{...i.request,operationId:n.id});r.push({intent:i,command:a,operation:e.recoverOperation(n)})}if(!s.nextCursor)break;if(i.has(s.nextCursor))throw Error(`The retained Model save catalog repeated a cursor.`);i.add(s.nextCursor),a=s.nextCursor}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),_=d.original??g.data?.[0]??null,v=S({queryKey:[`neuron-training-model-save-options`,i,h.data?.account.apiOrigin,n?.result?.contentHash],enabled:m&&h.isSuccess&&g.isSuccess&&!_&&!d.busy,retry:!1,queryFn:async({signal:n})=>{if(!h.data)throw Error(`Read the configured result account first.`);let r=h.data.account,i=new URLSearchParams({...r,...e.projectId?{projectId:e.projectId}:{}}),a=Xl.parse(await Y(e.connection,`/v1/training/neuron-training-executions/${encodeURIComponent(t)}/model?${i}`,{signal:n}));if(J(a.account)!==J(r)||a.executionId!==t||a.projectId!==e.projectId)throw Error(`The Model targets differ from this exact result account or Project.`);return a}});async function y(n){f({original:n}),await n.operation.retainCommand(n.command,`dispatching`),p();let i=await Y(e.connection,`/v1/training/neuron-training-executions/${encodeURIComponent(n.command.executionId)}/model`,{method:`POST`,body:JSON.stringify({...n.intent.account,projectId:n.intent.execution.projectId,intentHash:n.operation.intentHash,command:n.command})}),a=await tr(i,n.command);if(p(),a.actorId!==e.actorId||a.version.source.executionId!==t)throw Error(`The saved Model receipt belongs to another creator or Project.`);f({receipt:a});for(let e of[`saved-training-model`,`saved-model-serving`,`neuron-training-model-save-options`,`unified-experiments`,`model-projects`])r.invalidateQueries({queryKey:[e]});return await n.operation.acknowledge(),p(),f({original:null}),await g.refetch(),p(),a}async function b(r){if(l.current.has(i))return null;l.current.add(i),f({busy:!0,error:null});try{if(p(),_)return await y(_);if(!g.isSuccess)throw Error(`Reload the original Model saves before continuing.`);if(!m||!n?.result||!v.isSuccess||!h.isSuccess||!v.data)throw Error(`Read the completed NeuronTraining result and current Model targets before saving.`);let i=r.modelProjectId?v.data.models.find(e=>e.id===r.modelProjectId):null;if(r.modelProjectId&&!i)throw Error(`Refresh the Model targets before updating this Model.`);let{schemaVersion:a,request:o,sourceForm:s,result:c,resultRecordedAt:l,contentHash:u,...d}=n,f=Yl.parse({account:v.data.account,execution:Rt.parse(d),request:{teamId:e.teamId,executionId:t,resultHash:n.result.contentHash,artifactHash:n.result.artifact.contentHash,name:r.name,modelProjectId:i?.id??null,expectedModelRevision:i?.revision??0}}),b=await e.operation(Rb,f);return p(),await y({intent:f,operation:b,command:kt.parse({...f.request,operationId:b.id})})}catch(e){return a.current===i&&f({error:e}),null}finally{l.current.delete(i),f({busy:!1})}}return{save:b,busy:d.busy,receipt:d.receipt,original:_,options:v.data,freshReady:m&&g.isSuccess&&v.isSuccess&&h.isSuccess,recoveryReady:!!_||g.isSuccess,error:d.error??g.error??(m?v.error??h.error:null),refresh:()=>{g.refetch(),m&&!_&&(h.refetch(),h.data&&v.refetch())}}}function Bb({api:e,id:t,execution:n,disabled:r=!1}){let i=zb(e,t,n),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)((n?.name??`NeuronTraining Model`).slice(0,200)),[l,u]=(0,Q.useState)(``),d=i.original?.command,f=iy({name:`NeuronTraining Model save`,busy:i.busy,dirty:a&&(!!d||s!==(n?.name??`NeuronTraining Model`).slice(0,200)||!!l),discardDescription:d?`The original save remains recoverable from this execution after closing.`:void 0}),p=n?.method===`selective_neuron_training`&&n.phase===`completed`&&n.result!==null,m=!i.recoveryReady&&i.error!==null;if(!p&&!d&&!i.receipt&&!m)return null;let h=i.receipt?.version;return(0,$.jsxs)(`section`,{className:`training-detail-section`,"aria-label":`Save NeuronTraining Model`,children:[(0,$.jsx)(X,{error:i.error}),i.recoveryReady?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Reload retained Model saves`}),i.receipt&&h?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[`Saved to `,i.receipt.model?.name,`. Exact version `,(0,$.jsx)(`code`,{children:h.contentHash}),`.`]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact saved version`}),(0,$.jsx)(`pre`,{className:`saved-model-version-reference`,children:JSON.stringify(h,null,2)})]}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void wo(as(`models`)),children:`Open Models`}),(0,$.jsx)(`p`,{children:`The saved neuron delta supports inference. Training continuation requires optimizer state and is unavailable; choose a managed base explicitly for a fresh experiment.`})]}),(0,$.jsx)(hb,{connection:e.connection,version:h,api:e},`${e.key}:${h.contentHash}`)]}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:r||i.busy||!i.recoveryReady,onClick:()=>o(!0),children:d?`Recover Model save`:i.receipt?`Save model again`:`Save model`}),a?(0,$.jsxs)(qa,{ariaLabel:`Save NeuronTraining model`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:i.busy,onClose:()=>void f.requestLeave(()=>o(!1)),children:[(0,$.jsx)(`h2`,{children:`Save model`}),(0,$.jsx)(`p`,{children:`Save the exact learned modification from this completed result. Saving does not activate serving.`}),(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),i.save({name:s,modelProjectId:l||null}).then(e=>{e&&(f.allowNextNavigation(),o(!1))})},children:[(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Save destination`}),(0,$.jsx)(Z,{label:`Model destination`,value:d?.modelProjectId??(d?``:l),options:[{value:``,label:`Create new Model`},...(i.options?.models??[]).map(e=>({value:e.id,label:e.name,description:`Current revision ${e.revision}`})),...d?.modelProjectId&&!i.options?.models.some(e=>e.id===d.modelProjectId)?[{value:d.modelProjectId,label:`Original selected Model`}]:[]],disabled:i.busy||!!d||!i.freshReady,onChange:e=>{u(e);let t=i.options?.models.find(t=>t.id===e);t&&c(t.name)}})]}),(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Model name`}),(0,$.jsx)(`input`,{"data-autofocus":!0,value:d?.name??s,maxLength:200,disabled:i.busy||!!d,onChange:e=>c(e.target.value)})]}),d?(0,$.jsx)(`p`,{children:`Original result, module, destination and revision are retained. Retry sends the same operation.`}):null,i.receipt&&d?(0,$.jsx)(`p`,{role:`status`,children:`The Model was saved. Local acknowledgement is pending; retry preserves its exact receipt.`}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:()=>void f.requestLeave(()=>o(!1)),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Refresh targets and recovery`}),(0,$.jsx)(`button`,{type:`submit`,className:`training-button`,disabled:i.busy||r||!i.recoveryReady||!d&&!i.freshReady,children:i.busy?`Saving…`:d?`Retry original save`:`Save model`})]})]})]}):null,f.dialog]})}function Vb({api:e,execution:t}){let n=k(e.connection,null),r=Fb(e),[i,a]=(0,Q.useState)(null),o=n.selection?.neuronTrainingResult?.id===t.id&&n.selection.neuronTrainingResult.result?.contentHash===t.result?.contentHash;async function s(){a(null);try{if(!r.data||t.phase!==`completed`||!t.result)throw Error(`Read the exact completed NeuronTraining result in its original account first.`);let i=An.parse({kind:`neuron_training_result`,location:`cloud`,owner:{teamId:t.teamId,actorId:t.ownerUserId},apiOrigin:r.data.account.apiOrigin,projectId:t.projectId,executionId:t.id,inputHash:t.plan.inputHash,modelHash:t.result.modelHash,runtimeHash:t.plan.runtimeHash,resultHash:t.result.contentHash,artifact:t.result.artifact?{id:t.result.artifact.id,contentHash:t.result.artifact.contentHash}:null});await n.select({kind:`neuron_training_result`,id:t.id,location:`cloud`,teamId:e.teamId,apiOrigin:r.data.account.apiOrigin,result:i})}catch(e){a(e)}}return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{error:i??r.error}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:n.selecting||!r.isSuccess,onClick:()=>void s(),children:o?`Result selected for chat`:`Use result in chat`})]})}function Hb({owner:e,api:t,onOpenBilling:n=null,billingReturnPending:r=!1,onRefreshFunding:i,disabled:a=!1}){let o=e.busy||a,s=e.execution,c=e.original,l=(e.receipt&&(!s||e.receipt.execution.id===s.id&&e.receipt.execution.revision>s.revision)?e.receipt.execution:s)??(c&&`execution`in c.intent?c.intent.execution:null),[u,d]=(0,Q.useState)(null),f=Tb(t,l?.plan.maximumSpendUsd??``,!!l,!!l?.plan.computePrice),p=c?`action`in c.command?c.command.action:`prepare`:null;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{error:e.error}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o||e.loading,onClick:e.refresh,children:`Refresh execution and recovery`}),c?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||!e.recoveryReady,onClick:()=>void e.retry(),children:o?`Reconciling…`:`Retry original ${p}`}):null]}),c&&!(`action`in c.command)?(0,$.jsxs)(ft,{title:`Original preparation`,children:[(0,$.jsxs)(`p`,{children:[c.command.name,` · `,c.command.method,` · `,Uy(c.command.maximumSpendUsd)]}),(0,$.jsxs)(`p`,{children:[c.command.request.training.maxSteps,` training steps · batch`,` `,c.command.request.data.target.batch.id,` ·`,` `,c.command.request.model.modelId,` · `,c.command.request.model.revision]})]}):null,l?(0,$.jsxs)(ft,{title:`Hosted execution`,children:[(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`State`}),(0,$.jsx)(`dd`,{children:l.phase}),(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(l.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:l.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Execution`}),(0,$.jsx)(`dd`,{children:l.id}),(0,$.jsx)(`dt`,{children:`Preparation expires`}),(0,$.jsx)(`dd`,{children:new Date(l.plan.expiresAt).toLocaleString()}),(0,$.jsx)(`dt`,{children:`Exact plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:l.plan.contentHash}),(0,$.jsx)(`dt`,{children:`Runtime`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:l.plan.runtimeHash})]}),s?(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[s.phase===`prepared`?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||e.loading||!e.ready||!e.canControl||!!c||Date.parse(s.plan.expiresAt)<=Date.now(),onClick:()=>d({action:`start`,value:s}),children:`Review Start`}):null,[`completed`,`cancelled`,`failed`].includes(s.phase)?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o||e.loading||!e.ready||!e.canControl||!!c,onClick:()=>d({action:`cancel`,value:s}),children:`Review Cancel`})]}):null]}):null,s?.phase===`completed`&&s.result?(0,$.jsx)(Vb,{api:t,execution:s}):null,s?.result?(0,$.jsx)(t_,{result:s.result}):l?.phase===`completed`?(0,$.jsx)(`p`,{children:`No result bytes are available in this read. Retained execution identity remains available for recovery.`}):null,e.selectedId?(0,$.jsx)(Bb,{api:t,id:e.selectedId,execution:s,disabled:o||!!c},`${t.key}:${e.selectedId}`):null,u&&s?(0,$.jsxs)(qa,{ariaLabel:u.action===`start`?`Start NeuronTraining experiment`:`Cancel NeuronTraining experiment`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:o,onClose:()=>{o||d(null)},children:[(0,$.jsx)(`h2`,{children:u.action===`start`?`Start NeuronTraining experiment`:`Cancel NeuronTraining experiment`}),(0,$.jsx)(`p`,{children:u.action===`start`?Gy(u.value.plan.computePrice):`Cancel this exact execution. In-flight work may need to stop and settle before capacity is released.`}),(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(u.value.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:u.value.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Training steps`}),(0,$.jsx)(`dd`,{children:u.value.request.training.maxSteps}),(0,$.jsx)(`dt`,{children:`Reviewed batch`}),(0,$.jsxs)(`dd`,{children:[u.value.request.data.target.batch.id,` · release`,` `,u.value.request.data.target.batch.revision]}),(0,$.jsx)(`dt`,{children:`Maximum duration`}),(0,$.jsxs)(`dd`,{children:[u.value.request.training.maxDurationSeconds,` seconds`]}),(0,$.jsx)(`dt`,{children:`Model`}),(0,$.jsxs)(`dd`,{children:[u.value.request.model.modelId,` · `,u.value.request.model.revision]}),(0,$.jsx)(`dt`,{children:`Plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:u.value.plan.contentHash})]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact prepared training request`}),(0,$.jsx)(`pre`,{children:JSON.stringify(u.value.request,null,2)})]}),u.action===`start`?(0,$.jsx)(Db,{funding:f,busy:o,startAttempted:!!c,billingReturnPending:r,onOpenBilling:n,onRefresh:i??(async()=>{await f.refresh()})}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o,onClick:()=>d(null),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||e.loading||!!c||!e.ready||!e.canControl||u.action===`start`&&(r||!f.canStart||Date.parse(u.value.plan.expiresAt)<=Date.now()),onClick:()=>void e.control(u.action,u.value).then(e=>{e&&d(null)}),children:o?`Applying…`:u.action===`start`?Ky(u.value.plan.maximumSpendUsd):`Cancel execution`})]})]}):null]})}var Ub=(0,Q.lazy)(()=>o(()=>import(`./ExperimentTrainingDataWorkspace-CfOyoMrq.js`),__vite__mapDeps([76,1,2,3,4,77,5,6,9,10,78,32,27,31,21,16,43,19,20,22,13,23,15,24,25,26,8,28,11,29,30,33,34,35,36,37,38,39,40,41,18,42,44,45,46,47,48,49,50,51,52,53,54,55,56,79,80])));function Wb({api:e,visible:t,onClose:n,onSaveDraft:r}){let i=kv(),[a,o]=(0,Q.useState)(()=>i.initialExperiment?.neuronTrainingForm??nn(i.trainingBaseModel)),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(`targetBatch`),[h,g]=(0,Q.useState)(!1),_=(0,Q.useRef)(null),v=(0,Q.useRef)(!1),y=(0,Q.useRef)(null),b=(0,Q.useRef)(!1),x=J([e.key,e.accountKey,e.actorId,e.teamId,e.projectId,e.connection.serverUrl,i.initialExperiment?.id]),C=(0,Q.useRef)(x);C.current=x,(0,Q.useEffect)(()=>(C.current=x,()=>{C.current=``}),[x]);function w(){if(C.current!==x)throw Error(`Return to this experiment's original account before continuing.`)}let T=Lb(e,{draftId:i.initialExperiment?.id??null,method:`selective_neuron_training`,visible:t}),E=Ry(e,t,a.targetBatch,[...a.background.map(e=>e.batch),a.preservationBatch]),D=Fb(e,t),O=i.trainingBaseModel,k=!i.startingModel||i.startingModel.source===`managed`,A=wv(i.startingModel),j=(0,Q.useRef)(A);(0,Q.useEffect)(()=>{j.current!==A&&o(({inspectionSource:e,...t})=>({...t,parentArtifact:null})),j.current=A},[A,i.startingModel?.source]);let M=O?.source===`managed`&&k?{teamId:e.teamId,source:O.source,modelId:O.modelId,...O.revision?{revision:O.revision}:{},...O.tokenizerRevision?{tokenizerRevision:O.tokenizerRevision}:{},...O.chatTemplateHash?{chatTemplateHash:O.chatTemplateHash}:{},...O.modelAssetId?{modelAssetId:O.modelAssetId}:{}}:null,N=S({queryKey:[`neuron-training-execution-capability`,x,M],enabled:t&&!!(D.data&&M),retry:!1,staleTime:3e4,queryFn:({signal:e})=>{if(!D.data||!M)throw Error(`Choose an exact managed base before checking NeuronTraining availability.`);return D.data.capability(M,e)},refetchInterval:e=>!e.state.error&&6e4}),P=N.data&&!N.isError&&Date.parse(N.data.expiresAt)>Date.now()?N.data.execution:null,F=T.selectedId&&![`completed`,`failed`,`cancelled`].includes(T.execution?.phase??T.receipt?.execution.phase??`prepared`),I=s||T.busy,L=I||!!(T.original||F),ee=J({...a,baseModel:O,sourceKey:A}),R=(0,Q.useRef)(ee);R.current=ee;let z=(0,Q.useRef)(ee),B=Tb(e,a.maximumSpendUsd,t,!0),V=ee!==z.current,H=i.reportOperationDraftDirty;(0,Q.useEffect)(()=>{H(`selective_neuron_training`,V)},[V,H]);let U=iy({name:`Neuron training experiment`,dirty:V||i.operationDraftDirty||i.evaluationDirty,busy:I,onLeave:n});My({...U,requestLeave:async e=>{d&&y.current?await y.current.requestLeave(()=>U.requestLeave(e)):await U.requestLeave(e)}},t);function te(e){o(t=>({...t,...e}))}function ne(){if(!i.initialExperiment)throw Error(`Open an experiment before saving its settings.`);if(!k)throw Error(`Neuron training requires its exact managed base. Choose another starting model.`);return Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:i.initialExperiment.id,operationType:`selective_neuron_training`,name:a.name.trim()||`Neuron training experiment`,...i.startingModel?{startingModel:i.startingModel}:{},neuronTrainingForm:{...a,baseModel:O}})}async function re(t){if(!r)throw Error(`Load canonical draft storage before preparing.`);await r(t),w();let n=await Iy(e).get(t.id);if(w(),n.status!==`draft`||n.projectId!==e.projectId||J(n.draft)!==J(t))throw Error(`The saved experiment changed. Reopen its exact current revision before continuing.`);return z.current=ee,n}async function W(){if(!(b.current||L)){b.current=!0,c(!0),u(null);try{await re(ne())}catch(e){C.current===x&&u(e)}finally{b.current=!1,C.current===x&&c(!1)}}}async function ie(){if(b.current||T.busy||T.original)return;b.current=!0,c(!0),u(null);let t=null;try{let n=window.openpond?.browser;if(!n?.openExternal){if(t=window.open(`about:blank`,`_blank`),!t)throw Error(`Allow a new tab to open Billing, then try again.`);t.opener=null}let r=await re(ne());w();let i=vt(a.maximumSpendUsd),o=await xb(e,{schemaVersion:`openpond.trainingFundingHandoffRequest.v1`,teamId:e.teamId,maximumSpendUsd:i===null?null:Number(i),draft:{id:r.id,revision:r.revision,contentHash:r.contentHash,projectId:r.projectId}});if(w(),!o.canPurchase||!o.billingUrl)throw Error(`A workspace billing owner needs to add credits for this experiment.`);if(_.current={record:r,snapshot:ee},g(!0),n?.openExternal){let e=await n.openExternal({conversationId:`experiment-funding:${r.id}`,url:o.billingUrl});if(w(),!e.ok)throw Error(e.error??`Billing could not be opened. Your experiment is saved; try again.`)}else t&&=(t.location.replace(o.billingUrl),null)}catch(e){t?.close(),C.current===x&&(u(e),g(!1),_.current=null)}finally{b.current=!1,C.current===x&&c(!1)}}async function G(){if(!(v.current||C.current!==x)){v.current=!0;try{let t=_.current;if(t){let n=await Iy(e).get(t.record.id);if(w(),n.contentHash!==t.record.contentHash||n.status!==`draft`||R.current!==t.snapshot)throw Error(`This experiment changed while Billing was open. Your edits remain here; save and review them before preparing.`)}await B.refresh(),w()}catch(e){C.current===x&&u(e)}finally{v.current=!1,C.current===x&&(_.current=null,g(!1))}}}let ae=(0,Q.useRef)(G);ae.current=G,(0,Q.useEffect)(()=>{if(!h)return;let e=()=>{document.visibilityState===`visible`&&ae.current()};return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[h]);async function K(e){if(w(),L||!t)throw Error(`Return to the editable experiment before selecting data.`);if(Fe(e),e.purpose!==`supervised_training`||!e.sealedAt||!e.examples.length)throw Error(`Choose a sealed, reviewed supervised training batch.`);te(typeof p==`number`?{background:a.background.map((t,n)=>n===p?{...t,batch:xe(e)}:t)}:{[p]:xe(e)}),f(!1)}let q=E.batches.filter(e=>e.purpose===`supervised_training`&&e.sealedAt&&e.exampleCount>0),oe=a.targetBatch?J(a.targetBatch):``,se=q.find(e=>J(e.reference)===oe),ce=q.map(e=>({value:J(e.reference),label:`${e.reference.id} · release ${e.reference.revision} · ${e.exampleCount} examples`}));oe&&!ce.some(e=>e.value===oe)&&ce.unshift({value:oe,label:`${a.targetBatch.id} · saved release ${a.targetBatch.revision}`,disabled:!0});let le=i.startingModel?.source===`trained`?`trained:${i.startingModel.trainedVersion.contentHash}`:i.startingModel?.source===`steering`?`steering:${i.startingModel.steering.versionHash}`:i.startingModel?.source===`inference`?`inference:${i.startingModel.inferenceModelId}`:O?J(O):``,ue=E.models.filter(e=>e.preference.source===`managed`).map(e=>({value:J(e.preference),label:e.name}));return le&&!ue.some(e=>e.value===le)&&ue.unshift({value:le,label:i.startingModel?.label??O?.modelId??`Saved starting model`,disabled:!0}),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{hidden:d,inert:d,children:(0,$.jsxs)(Bv,{label:`Experiment setup`,action:`experiment`,onRequestClose:()=>void U.requestLeave(n),children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`h2`,{children:`Run Experiment`}),(0,$.jsx)(`button`,{type:`button`,disabled:I,onClick:()=>void U.requestLeave(n),children:`Close setup`})]}),(0,$.jsx)(X,{error:l??E.error??N.error??D.error}),(0,$.jsxs)(`form`,{noValidate:!0,onSubmit:e=>{e.preventDefault(),W()},children:[(0,$.jsx)(ft,{title:`Starting model`,children:(0,$.jsxs)(`fieldset`,{disabled:L,children:[(0,$.jsxs)(`label`,{children:[`Model`,(0,$.jsx)(Z,{label:`Neuron training starting model`,floating:!0,searchable:!0,value:le,options:[{value:``,label:`Choose exact managed base`},...ue],onChange:e=>{if(e===le)return;let t=E.models.find(t=>J(t.preference)===e&&t.preference.source===`managed`);e&&!t?u(`Refresh the model list before changing this selection.`):(i.setTrainingBaseModel(t?.preference??null),o(({inspectionSource:e,...t})=>({...t,parentArtifact:null})))}})]}),(0,$.jsx)(xy,{disabled:L}),(0,$.jsx)(`p`,{children:`Select neurons from reviewed target and background domains, then train their output projection columns in the exact managed backbone. Saved neuron deltas cannot resume training.`}),(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:I||E.isFetching,onClick:()=>void E.refetch(),children:`Refresh models and reviewed batches`}),P?(0,$.jsx)(`p`,{children:P.state===`unavailable`?P.reason:`A compatible NeuronTraining runtime is available. Preparation rechecks its exact identity.`}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:I||N.isFetching||!M,onClick:()=>{D.refetch(),N.refetch()},children:`Refresh runtime availability`})]})}),(0,$.jsx)(ft,{title:`Training data`,children:(0,$.jsxs)(`fieldset`,{disabled:L,children:[(0,$.jsxs)(`label`,{children:[`Reviewed target batch`,(0,$.jsx)(Z,{label:`Neuron training target batch`,floating:!0,searchable:!0,value:oe,options:[{value:``,label:`Choose sealed supervised batch`},...ce],onChange:e=>{let t=q.find(t=>J(t.reference)===e);e&&!t?u(`Refresh the reviewed batch before changing this selection.`):te({targetBatch:t?.reference??null})}})]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>{m(`targetBatch`),f(!0)},children:`Import or review target data`})]})}),(0,$.jsx)(ft,{title:`Preservation data`,children:(0,$.jsxs)(`fieldset`,{disabled:L,children:[(0,$.jsxs)(`label`,{children:[`Preservation batch`,(0,$.jsx)(Z,{label:`Neuron training preservation batch`,floating:!0,searchable:!0,value:a.preservationBatch?J(a.preservationBatch):``,options:[{value:``,label:`No preservation batch`},...ce],onChange:e=>{let t=q.find(t=>J(t.reference)===e);e&&!t?u(`Refresh this exact preservation release before choosing it.`):te({preservationBatch:t?.reference??null})}})]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>{m(`preservationBatch`),f(!0)},children:`Import or review preservation data`}),(0,$.jsx)(`p`,{children:`Preservation data, weight and examples per step must be enabled together. Target and background batches contain reviewed supervised examples.`})]})}),(0,$.jsx)(ft,{title:`Background domains`,children:(0,$.jsxs)(`fieldset`,{disabled:L,children:[a.background.map((e,t)=>(0,$.jsxs)(`section`,{children:[(0,$.jsxs)(`label`,{children:[`Domain name`,(0,$.jsx)(`input`,{value:e.domain,maxLength:100,onChange:e=>te({background:a.background.map((n,r)=>r===t?{...n,domain:e.target.value}:n)})})]}),(0,$.jsxs)(`label`,{children:[`Background batch`,(0,$.jsx)(Z,{label:`Background batch ${t+1}`,floating:!0,searchable:!0,value:e.batch?J(e.batch):``,options:[{value:``,label:`Choose reviewed background batch`},...ce],onChange:e=>{let n=q.find(t=>J(t.reference)===e);e&&!n?u(`Refresh this exact background release before choosing it.`):te({background:a.background.map((e,r)=>r===t?{...e,batch:n?.reference??null}:e)})}})]}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>{m(t),f(!0)},children:`Import or review this domain`}),(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:a.background.length<=1,onClick:()=>te({background:a.background.filter((e,n)=>n!==t)}),children:`Remove domain`})]})]},t)),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:a.background.length>=8,onClick:()=>te({background:[...a.background,{domain:``,batch:null}]}),children:`Add background domain`})]})}),(0,$.jsx)(ft,{title:`Settings`,children:(0,$.jsxs)(`fieldset`,{disabled:L,children:[(0,$.jsxs)(`label`,{children:[`Experiment name`,(0,$.jsx)(`input`,{value:a.name,maxLength:500,onChange:e=>te({name:e.target.value})})]}),(0,$.jsx)(Nb,{form:a,onChange:o}),(0,$.jsxs)(`label`,{children:[`Spending limit (USD, optional)`,(0,$.jsx)(`input`,{type:`text`,inputMode:`decimal`,maxLength:100,placeholder:`Use available credits`,value:a.maximumSpendUsd,onChange:e=>te({maximumSpendUsd:e.target.value})})]})]})}),(0,$.jsx)(Db,{funding:B,busy:I,startAttempted:!!T.original,billingReturnPending:h,onOpenBilling:r?ie:null,onRefresh:G}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`submit`,className:`training-button secondary`,disabled:L||!r,children:s?`Saving…`:`Save draft`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:L||h||!r||!T.ready||!E.isSuccess||P?.state!==`ready`||!se||a.background.some(e=>!e.domain.trim()||!e.batch)||Number(a.training.preservationWeight)>0&&!a.preservationBatch,onClick:()=>{u(null);try{T.prepare(ne(),re)}catch(e){u(e)}},children:`Compile and prepare`})]})]}),(0,$.jsx)(Hb,{owner:T,api:e,disabled:I,onOpenBilling:r?ie:null,billingReturnPending:h,onRefreshFunding:G}),U.dialog]})}),d?(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`p`,{role:`status`,children:`Opening training data…`}),children:(0,$.jsx)(Ub,{api:e,method:`selective_neuron_training`,navigation:y,onClose:()=>f(!1),onUseBatch:K,beforeImport:async()=>{if(w(),L)throw Error(`Finish the original operation before importing data.`);await re(ne()),w()}})}):null]})}var Gb=[`training:prepare-decision`,`training:start-decision`,`training:cancel-decision`];function Kb(e,t){let n=u(),r=J([e.key,e.accountKey,e.actorId,e.teamId,e.projectId,e.connection.serverUrl,t.draftId,t.executionId,t.method]),i=(0,Q.useRef)(r);i.current=r,(0,Q.useEffect)(()=>(i.current=r,()=>{i.current=``}),[r]);let a=()=>({identity:r,busy:!1,error:null,receipt:null,selected:null,original:null,preparationOperationId:null}),[o,s]=(0,Q.useState)(a),c=(0,Q.useRef)(new Set),l=o.identity===r?o:a();function d(e){i.current===r&&s(t=>({...t.identity===r?t:a(),...e}))}function f(){if(i.current!==r)throw Error(`Return to this experiment's original account before continuing.`)}let p=tb(e,t.visible),m=p.data,h=S({queryKey:[`decision-experiment-recovery`,r],enabled:t.visible&&e.location===`hosted`&&!!e.actorId&&!l.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[];for(let i of Gb){let a,o=new Set;for(let s=0;;s++){if(s>=100)throw Error(`The retained execution catalog exceeds its supported bound.`);let c=await e.pendingOperations(i,a,n);for(let n of c.items){let a=i===Gb[0]?kl.parse(n.reviewedIntent):Al.parse(n.reviewedIntent);if(a.account.actorId!==e.actorId||a.account.teamId!==e.teamId)throw Error(`The retained execution belongs to another account.`);if(!(t.draftId===null?`execution`in a&&a.execution.id===t.executionId:a.draftId===t.draftId))continue;let o=i===Gb[0]?_r.parse(n.command??{...a.request,operationId:n.id}):Wt(n.command??{...a.request,operationId:n.id});r.push({intent:a,command:o,operation:e.recoverOperation(n)})}if(!c.nextCursor)break;if(o.has(c.nextCursor))throw Error(`The retained execution catalog repeated a cursor.`);o.add(c.nextCursor),a=c.nextCursor}}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),g=l.original??h.data?.[0]??null,_=t.executionId??l.selected??l.receipt?.execution.id??(g&&`execution`in g.intent?g.intent.execution.id:null),v=S({queryKey:[`managed-decision-execution`,r,_],enabled:t.visible&&!!(m&&_),retry:!1,queryFn:({signal:e})=>{if(!m||!_)throw Error(`Select an execution first.`);return m.get(_,e)},refetchInterval:e=>e.state.error?!1:e.state.data&&![`completed`,`failed`,`cancelled`].includes(e.state.data.phase)?3e3:!1});async function y(t){let r=eb(e,t.intent.account.apiOrigin);if(J(r.account)!==J(t.intent.account))throw Error(`Return to this execution's original account before retrying.`);d({original:t}),await t.operation.retainCommand(t.command,`dispatching`),f();let i=await r.mutate(t.command,t.operation.intentHash);return f(),d({receipt:i,selected:i.execution.id,preparationOperationId:`action`in t.command?`preparationOperationId`in t.intent?t.intent.preparationOperationId:null:t.command.operationId}),await t.operation.acknowledge(),f(),d({original:null}),await h.refetch(),f(),n.invalidateQueries({queryKey:[`managed-decision-execution`]}),n.invalidateQueries({queryKey:[`unified-experiments`]}),i}async function b(e){if(!c.current.has(r)){c.current.add(r),d({busy:!0,error:null});try{return f(),await e()}catch(e){return i.current===r&&d({error:e}),null}finally{c.current.delete(r),d({busy:!1})}}}async function x(n,r){return b(async()=>{if(g)return y(g);if(!m||!h.isSuccess||!t.draftId||n.id!==t.draftId||!n.decisionForm||!t.method)throw Error(`Load this saved experiment and original requests before preparing.`);let i=vt(n.decisionForm.maximumSpendUsd);await r(n),f();let a=await Iy(e).get(n.id);if(f(),a.status!==`draft`||a.projectId!==e.projectId||J(a.draft)!==J(n))throw Error(`The saved experiment changed. Reopen its exact current revision before preparing.`);let o=n.decisionForm.baseModel;if(!o||o.source!==`managed`||n.startingModel&&![`managed`,`decision`].includes(n.startingModel.source))throw Error(`Choose a qualified exact Decision starting model.`);let s={teamId:e.teamId,modelId:o.modelId,source:o.source,...o.revision?{revision:o.revision}:{},...o.tokenizerRevision?{tokenizerRevision:o.tokenizerRevision}:{},...o.chatTemplateHash?{chatTemplateHash:o.chatTemplateHash}:{},...o.modelAssetId?{modelAssetId:o.modelAssetId}:{}},c={teamId:e.teamId,projectId:e.projectId,method:t.method,mode:n.decisionForm.mode,query:s,form:n.decisionForm},l=await m.compile(c);if(f(),l.actorId!==e.actorId||l.formHash!==await zr(n.decisionForm))throw Error(`The compilation differs from this exact saved form.`);let u=await Ft({teamId:e.teamId,projectId:e.projectId,operationId:crypto.randomUUID(),name:n.name,method:t.method,mode:n.decisionForm.mode,query:s,request:l.request,sourceForm:n.decisionForm,maximumSpendUsd:i}),{operationId:d,...p}=u,_=kl.parse({account:m.account,draftId:n.id,request:p}),v=await e.operation(Gb[0],_);return f(),y({intent:_,operation:v,command:{...u,operationId:v.id}})})}async function C(n,r){return b(async()=>{if(g)return y(g);let i=r??v.data;if(!m||!h.isSuccess||!i||v.error)throw Error(`Read the exact execution before reviewing its next action.`);let{schemaVersion:a,request:o,sourceForm:s,result:c,resultRecordedAt:u,contentHash:d,...p}=i,_=Zt.parse(p),b=n===`start`?{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n,approvedMaximumSpendUsd:i.plan.maximumSpendUsd,...i.plan.computePrice?{approvedPriceHash:await zr(i.plan.computePrice)}:{}}:{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n},x=Al.parse({account:m.account,draftId:l.preparationOperationId?t.draftId:null,preparationOperationId:l.preparationOperationId,execution:_,request:b}),S=await e.operation(n===`start`?Gb[1]:Gb[2],x);return f(),y({intent:x,operation:S,command:Wt({...b,operationId:S.id})})})}return{prepare:x,control:C,retry:()=>b(()=>{if(!g)throw Error(`Reload the original execution request.`);return y(g)}),busy:l.busy,receipt:l.receipt,original:g,execution:v.data,ready:p.isSuccess&&h.isSuccess,recoveryReady:!!g||h.isSuccess,canControl:v.isSuccess&&!v.error,error:l.error??p.error??h.error??v.error,refresh:()=>{p.refetch(),e.actorId&&h.refetch(),m&&_&&v.refetch()},loading:v.isFetching||p.isFetching,selectedId:_}}function qb({api:e,execution:t}){let n=k(e.connection,null),r=tb(e),[i,a]=(0,Q.useState)(null),o=n.selection?.decisionResult?.id===t.id&&n.selection.decisionResult.result?.contentHash===t.result?.contentHash;async function s(){a(null);try{if(!r.data||t.phase!==`completed`||!t.result)throw Error(`Read the exact completed Decision result in its original account first.`);let i=un.parse({kind:`decision_result`,mode:t.mode,location:`cloud`,owner:{teamId:t.teamId,actorId:t.ownerUserId},apiOrigin:r.data.account.apiOrigin,projectId:t.projectId,executionId:t.id,inputHash:t.plan.inputHash,modelHash:t.result.modelHash,runtimeHash:t.plan.runtimeHash,resultHash:t.result.contentHash,artifact:t.result.artifact?{id:t.result.artifact.id,contentHash:t.result.artifact.contentHash}:null});await n.select({kind:`decision_result`,id:t.id,location:`cloud`,teamId:e.teamId,apiOrigin:r.data.account.apiOrigin,result:i})}catch(e){a(e)}}return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{error:i??r.error}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:n.selecting||!r.isSuccess,onClick:()=>void s(),children:o?`Result selected for chat`:`Use result in chat`})]})}var Jb=`training-decision-result-save`;function Yb(e,t,n){let r=u(),i=J([e.key,ra(e.connection),t]),a=(0,Q.useRef)(i);a.current=i,(0,Q.useEffect)(()=>(a.current=i,()=>{a.current=``}),[i]);let o=()=>({identity:i,busy:!1,error:null,original:null,receipt:null}),[s,c]=(0,Q.useState)(o),l=(0,Q.useRef)(new Set),d=s.identity===i?s:o();function f(e){a.current===i&&c(t=>({...t.identity===i?t:o(),...e}))}function p(){if(a.current!==i)throw Error(`Return to this Model save's original account and result.`)}let m=n?.method===`decision_model`&&n.phase===`completed`&&n.result?.schemaVersion===`openpond.decisionTrainingResult.v1`,h=tb(e,m),g=S({queryKey:[`decision-model-save-recovery`,i],enabled:!!e.actorId&&!d.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[],i=new Set,a;for(let o=0;;o++){if(o>=100)throw Error(`The retained Model save catalog exceeds its supported bound.`);let s=await e.pendingOperations(Jb,a,n);for(let n of s.items){let i=Pl.parse(n.reviewedIntent);if(i.request.executionId!==t)continue;if(i.account.actorId!==e.actorId||i.account.teamId!==e.teamId||i.execution.projectId!==e.projectId)throw Error(`The retained Model save belongs to another creator or Project.`);let a=sr.parse(n.command??{...i.request,operationId:n.id});r.push({intent:i,command:a,operation:e.recoverOperation(n)})}if(!s.nextCursor)break;if(i.has(s.nextCursor))throw Error(`The retained Model save catalog repeated a cursor.`);i.add(s.nextCursor),a=s.nextCursor}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),_=d.original??g.data?.[0]??null,v=S({queryKey:[`decision-model-save-options`,i,h.data?.account.apiOrigin,n?.result?.contentHash],enabled:m&&h.isSuccess&&g.isSuccess&&!_&&!d.busy,retry:!1,queryFn:async({signal:n})=>{if(!h.data)throw Error(`Read the configured result account first.`);let r=h.data.account,i=new URLSearchParams({...r,...e.projectId?{projectId:e.projectId}:{}}),a=Fl.parse(await Y(e.connection,`/v1/training/decision-executions/${encodeURIComponent(t)}/model?${i}`,{signal:n}));if(J(a.account)!==J(r)||a.executionId!==t||a.projectId!==e.projectId)throw Error(`The Model targets differ from this exact result account or Project.`);return a}});async function y(n){f({original:n}),await n.operation.retainCommand(n.command,`dispatching`),p();let i=await Y(e.connection,`/v1/training/decision-executions/${encodeURIComponent(n.command.executionId)}/model`,{method:`POST`,body:JSON.stringify({...n.intent.account,projectId:n.intent.execution.projectId,intentHash:n.operation.intentHash,command:n.command})}),a=await qt(i,n.command);if(p(),a.actorId!==e.actorId||a.version.source.executionId!==t)throw Error(`The saved Model receipt belongs to another creator or Project.`);f({receipt:a});for(let e of[`saved-training-model`,`saved-model-serving`,`decision-model-save-options`,`unified-experiments`,`model-projects`])r.invalidateQueries({queryKey:[e]});return await n.operation.acknowledge(),p(),f({original:null}),await g.refetch(),p(),a}async function b(r){if(l.current.has(i))return null;l.current.add(i),f({busy:!0,error:null});try{if(p(),_)return await y(_);if(!g.isSuccess)throw Error(`Reload the original Model saves before continuing.`);if(!m||n?.result?.schemaVersion!==`openpond.decisionTrainingResult.v1`||!v.isSuccess||!h.isSuccess||!v.data)throw Error(`Read the completed Decision result and current Model targets before saving.`);let i=r.modelProjectId?v.data.models.find(e=>e.id===r.modelProjectId):null;if(r.modelProjectId&&!i)throw Error(`Refresh the Model targets before updating this Model.`);let{schemaVersion:a,request:o,sourceForm:s,result:c,resultRecordedAt:l,contentHash:u,...d}=n,f=Pl.parse({account:v.data.account,execution:Zt.parse(d),request:{teamId:e.teamId,executionId:t,resultHash:n.result.contentHash,artifactHash:n.result.artifact.contentHash,name:r.name,modelProjectId:i?.id??null,expectedModelRevision:i?.revision??0}}),b=await e.operation(Jb,f);return p(),await y({intent:f,operation:b,command:sr.parse({...f.request,operationId:b.id})})}catch(e){return a.current===i&&f({error:e}),null}finally{l.current.delete(i),f({busy:!1})}}return{save:b,busy:d.busy,receipt:d.receipt,original:_,options:v.data,freshReady:m&&g.isSuccess&&v.isSuccess&&h.isSuccess,recoveryReady:!!_||g.isSuccess,error:d.error??g.error??(m?v.error??h.error:null),refresh:()=>{g.refetch(),m&&!_&&(h.refetch(),h.data&&v.refetch())}}}function Xb({api:e,id:t,execution:n,disabled:r=!1}){let i=Yb(e,t,n),a=kv(),[o,s]=(0,Q.useState)(null),c=`${e.key}:${t}`,l=(0,Q.useRef)(c);l.current=c,(0,Q.useEffect)(()=>(l.current=c,()=>{l.current=``}),[c]);async function u(){let t=i.receipt;if(!(!t||i.busy||i.original||r))try{let n=Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:crypto.randomUUID(),operationType:`decision_model`,name:`${t.model.name} Decision experiment`,startingModel:await Sr(t.version,{teamId:e.teamId,label:`${t.model.name} / Saved decision adapter`}),decisionForm:await Pn(Qy(),t.version,{teamId:e.teamId})});l.current===c&&await a.openDraft(n,as(`experiments`,null,{projectId:e.projectId,executionLocation:`hosted`}))}catch(e){l.current===c&&s(e)}}let[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)((n?.name??`Decision Model`).slice(0,200)),[h,g]=(0,Q.useState)(``),_=i.original?.command,v=iy({name:`Decision Model save`,busy:i.busy,dirty:d&&(!!_||p!==(n?.name??`Decision Model`).slice(0,200)||!!h),discardDescription:_?`The original save remains recoverable from this execution after closing.`:void 0}),y=n?.method===`decision_model`&&n.phase===`completed`&&n.result?.schemaVersion===`openpond.decisionTrainingResult.v1`,b=!i.recoveryReady&&i.error!==null;if(!y&&!_&&!i.receipt&&!b)return null;let x=i.receipt?.version;return(0,$.jsxs)(`section`,{className:`training-detail-section`,"aria-label":`Save Decision Model`,children:[(0,$.jsx)(X,{error:o??i.error}),i.recoveryReady?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Reload retained Model saves`}),i.receipt&&x?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[`Saved to `,i.receipt.model?.name,`. Exact version `,(0,$.jsx)(`code`,{children:x.contentHash}),`.`]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact saved version`}),(0,$.jsx)(`pre`,{className:`saved-model-version-reference`,children:JSON.stringify(x,null,2)})]}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void wo(as(`models`)),children:`Open Models`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:r||i.busy||!!_,onClick:()=>void u(),children:`New experiment from saved module`})]}),(0,$.jsx)(hb,{connection:e.connection,version:x,api:e},`${e.key}:${x.contentHash}`)]}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:r||i.busy||!i.recoveryReady,onClick:()=>f(!0),children:_?`Recover Model save`:i.receipt?`Save model again`:`Save model`}),d?(0,$.jsxs)(qa,{ariaLabel:`Save Decision model`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:i.busy,onClose:()=>void v.requestLeave(()=>f(!1)),children:[(0,$.jsx)(`h2`,{children:`Save model`}),(0,$.jsx)(`p`,{children:`Save the exact trained decision adapter from this completed result. Saving does not activate serving.`}),(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),i.save({name:p,modelProjectId:h||null}).then(e=>{e&&(v.allowNextNavigation(),f(!1))})},children:[(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Save destination`}),(0,$.jsx)(Z,{label:`Model destination`,value:_?.modelProjectId??(_?``:h),options:[{value:``,label:`Create new Model`},...(i.options?.models??[]).map(e=>({value:e.id,label:e.name,description:`Current revision ${e.revision}`})),..._?.modelProjectId&&!i.options?.models.some(e=>e.id===_.modelProjectId)?[{value:_.modelProjectId,label:`Original selected Model`}]:[]],disabled:i.busy||!!_||!i.freshReady,onChange:e=>{g(e);let t=i.options?.models.find(t=>t.id===e);t&&m(t.name)}})]}),(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Model name`}),(0,$.jsx)(`input`,{"data-autofocus":!0,value:_?.name??p,maxLength:200,disabled:i.busy||!!_,onChange:e=>m(e.target.value)})]}),_?(0,$.jsx)(`p`,{children:`Original result, module, destination and revision are retained. Retry sends the same operation.`}):null,i.receipt&&_?(0,$.jsx)(`p`,{role:`status`,children:`The Model was saved. Local acknowledgement is pending; retry preserves its exact receipt.`}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:()=>void v.requestLeave(()=>f(!1)),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Refresh targets and recovery`}),(0,$.jsx)(`button`,{type:`submit`,className:`training-button`,disabled:i.busy||r||!i.recoveryReady||!_&&!i.freshReady,children:i.busy?`Saving…`:_?`Retry original save`:`Save model`})]})]})]}):null,v.dialog]})}function Zb({owner:e,api:t,onOpenBilling:n=null,billingReturnPending:r=!1,onRefreshFunding:i,disabled:a=!1}){let o=e.busy||a,s=e.execution,c=e.original,l=(e.receipt&&(!s||e.receipt.execution.id===s.id&&e.receipt.execution.revision>s.revision)?e.receipt.execution:s)??(c&&`execution`in c.intent?c.intent.execution:null),[u,d]=(0,Q.useState)(null),f=Tb(t,l?.plan.maximumSpendUsd??``,!!l,!!l?.plan.computePrice),p=c?`action`in c.command?c.command.action:`prepare`:null;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{error:e.error}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o||e.loading,onClick:e.refresh,children:`Refresh execution and recovery`}),c?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||!e.recoveryReady,onClick:()=>void e.retry(),children:o?`Reconciling…`:`Retry original ${p}`}):null]}),c&&!(`action`in c.command)?(0,$.jsxs)(ft,{title:`Original preparation`,children:[(0,$.jsxs)(`p`,{children:[c.command.name,` · `,c.command.method,` · `,Uy(c.command.maximumSpendUsd)]}),(0,$.jsxs)(`p`,{children:[c.command.mode,` · `,c.command.request.model.source.modelId,` ·`,` `,c.command.request.model.source.revision]})]}):null,l?(0,$.jsxs)(ft,{title:`Hosted execution`,children:[(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`State`}),(0,$.jsx)(`dd`,{children:l.phase}),(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(l.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:l.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Execution`}),(0,$.jsx)(`dd`,{children:l.id}),(0,$.jsx)(`dt`,{children:`Preparation expires`}),(0,$.jsx)(`dd`,{children:new Date(l.plan.expiresAt).toLocaleString()}),(0,$.jsx)(`dt`,{children:`Exact plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:l.plan.contentHash}),(0,$.jsx)(`dt`,{children:`Runtime`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:l.plan.runtimeHash})]}),s?(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[s.phase===`prepared`?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||e.loading||!e.ready||!e.canControl||!!c||Date.parse(s.plan.expiresAt)<=Date.now(),onClick:()=>d({action:`start`,value:s}),children:`Review Start`}):null,[`completed`,`cancelled`,`failed`].includes(s.phase)?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o||e.loading||!e.ready||!e.canControl||!!c,onClick:()=>d({action:`cancel`,value:s}),children:`Review Cancel`})]}):null]}):null,s?.phase===`completed`&&s.result?(0,$.jsx)(qb,{api:t,execution:s}):null,s?.result?(0,$.jsx)(Zy,{result:s.result}):l?.phase===`completed`?(0,$.jsx)(`p`,{children:`No result bytes are available in this read. Retained execution identity remains available for recovery.`}):null,e.selectedId?(0,$.jsx)(Xb,{api:t,id:e.selectedId,execution:s,disabled:o||!!c},`${t.key}:${e.selectedId}`):null,u&&s?(0,$.jsxs)(qa,{ariaLabel:u.action===`start`?`Start Decision experiment`:`Cancel Decision experiment`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:o,onClose:()=>{o||d(null)},children:[(0,$.jsx)(`h2`,{children:u.action===`start`?`Start Decision experiment`:`Cancel Decision experiment`}),(0,$.jsx)(`p`,{children:u.action===`start`?Gy(u.value.plan.computePrice):`Cancel this exact execution. In-flight work may need to stop and settle before capacity is released.`}),(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(u.value.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:u.value.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Mode`}),(0,$.jsx)(`dd`,{children:u.value.mode}),u.value.request.schemaVersion===`openpond.decisionTrainingRequest.v1`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Training steps`}),(0,$.jsx)(`dd`,{children:u.value.request.training.maxSteps}),(0,$.jsx)(`dt`,{children:`Reviewed batch`}),(0,$.jsxs)(`dd`,{children:[u.value.request.data.batch.id,` · release`,` `,u.value.request.data.batch.revision]})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Questions`}),(0,$.jsx)(`dd`,{children:u.value.request.input.questions.length})]}),(0,$.jsx)(`dt`,{children:`Model`}),(0,$.jsxs)(`dd`,{children:[u.value.request.model.source.modelId,` ·`,` `,u.value.request.model.source.revision]}),(0,$.jsx)(`dt`,{children:`Plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:u.value.plan.contentHash})]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact prepared Decision request`}),(0,$.jsx)(`pre`,{children:JSON.stringify(u.value.request,null,2)})]}),u.action===`start`?(0,$.jsx)(Db,{funding:f,busy:o,startAttempted:!!c,billingReturnPending:r,onOpenBilling:n,onRefresh:i??(async()=>{await f.refresh()})}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o,onClick:()=>d(null),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||e.loading||!!c||!e.ready||!e.canControl||u.action===`start`&&(r||!f.canStart||Date.parse(u.value.plan.expiresAt)<=Date.now()),onClick:()=>void e.control(u.action,u.value).then(e=>{e&&d(null)}),children:o?`Applying…`:u.action===`start`?Ky(u.value.plan.maximumSpendUsd):`Cancel execution`})]})]}):null]})}var Qb=(0,Q.lazy)(()=>o(()=>import(`./ExperimentTrainingDataWorkspace-CfOyoMrq.js`),__vite__mapDeps([76,1,2,3,4,77,5,6,9,10,78,32,27,31,21,16,43,19,20,22,13,23,15,24,25,26,8,28,11,29,30,33,34,35,36,37,38,39,40,41,18,42,44,45,46,47,48,49,50,51,52,53,54,55,56,79,80])));function $b({api:e,visible:t,onClose:n,onSaveDraft:r}){let i=kv(),[a,o]=(0,Q.useState)(()=>i.initialExperiment?.decisionForm??Qy()),s=(0,Q.useRef)({train:Qy(`train`),score:Qy(`score`)}),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(!1),g=(0,Q.useRef)(null),_=(0,Q.useRef)(!1),v=(0,Q.useRef)(null),y=(0,Q.useRef)(!1),b=J([e.key,e.accountKey,e.actorId,e.teamId,e.projectId,e.connection.serverUrl,i.initialExperiment?.id]),x=(0,Q.useRef)(b);x.current=b,(0,Q.useEffect)(()=>(x.current=b,()=>{x.current=``}),[b]);function C(){if(x.current!==b)throw Error(`Return to this experiment's original account before continuing.`)}let w=Kb(e,{draftId:i.initialExperiment?.id??null,method:`decision_model`,visible:t}),T=Ry(e,t&&a.mode===`train`,a.mode===`train`?a.batch:null),E=tb(e,t),D=i.trainingBaseModel??a.baseModel,O=!i.startingModel||i.startingModel.source===`managed`||i.startingModel.source===`decision`,k=wv(i.startingModel),A=(0,Q.useRef)(k);(0,Q.useEffect)(()=>{A.current!==k&&i.startingModel?.source!==`decision`&&o(({startingDecision:e,...t})=>({...t,parentArtifact:null})),A.current=k},[k,i.startingModel?.source]);let j=D?.source===`managed`&&O?{teamId:e.teamId,source:D.source,modelId:D.modelId,...D.revision?{revision:D.revision}:{},...D.tokenizerRevision?{tokenizerRevision:D.tokenizerRevision}:{},...D.chatTemplateHash?{chatTemplateHash:D.chatTemplateHash}:{},...D.modelAssetId?{modelAssetId:D.modelAssetId}:{}}:null,M=S({queryKey:[`decision-execution-capability`,b,j],enabled:t&&!!(E.data&&j),retry:!1,staleTime:3e4,queryFn:({signal:e})=>{if(!E.data||!j)throw Error(`Choose an exact managed base before checking Decision availability.`);return E.data.capability(j,e)},refetchInterval:e=>!e.state.error&&6e4}),N=M.data&&!M.isError&&Date.parse(M.data.expiresAt)>Date.now()?M.data.execution:null,P=w.selectedId&&![`completed`,`failed`,`cancelled`].includes(w.execution?.phase??w.receipt?.execution.phase??`prepared`),F=c||w.busy,I=F||!!(w.original||P),L=J({...a,baseModel:D,sourceKey:k}),ee=(0,Q.useRef)(L);ee.current=L;let R=(0,Q.useRef)(L),z=Tb(e,a.maximumSpendUsd,t,!0),B=L!==R.current,V=i.reportOperationDraftDirty;(0,Q.useEffect)(()=>{V(`decision_model`,B)},[B,V]);let H=iy({name:`Decision experiment`,dirty:B||i.operationDraftDirty||i.evaluationDirty,busy:F,onLeave:n});My({...H,requestLeave:async e=>{f&&v.current?await v.current.requestLeave(()=>H.requestLeave(e)):await H.requestLeave(e)}},t);function U(e){o(t=>({...t,...e}))}function te(){if(!i.initialExperiment)throw Error(`Open an experiment before saving its settings.`);if(!O)throw Error(`Decision requires its exact managed base. Choose another starting model.`);return Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:i.initialExperiment.id,operationType:`decision_model`,name:a.name.trim()||`Decision experiment`,...i.startingModel?{startingModel:i.startingModel}:{},decisionForm:{...a,baseModel:D}})}async function ne(t){if(!r)throw Error(`Load canonical draft storage before preparing.`);await r(t),C();let n=await Iy(e).get(t.id);if(C(),n.status!==`draft`||n.projectId!==e.projectId||J(n.draft)!==J(t))throw Error(`The saved experiment changed. Reopen its exact current revision before continuing.`);return R.current=L,n}async function re(){if(!(y.current||I)){y.current=!0,l(!0),d(null);try{await ne(te())}catch(e){x.current===b&&d(e)}finally{y.current=!1,x.current===b&&l(!1)}}}async function W(){if(y.current||w.busy||w.original)return;y.current=!0,l(!0),d(null);let t=null;try{let n=window.openpond?.browser;if(!n?.openExternal){if(t=window.open(`about:blank`,`_blank`),!t)throw Error(`Allow a new tab to open Billing, then try again.`);t.opener=null}let r=await ne(te());C();let i=vt(a.maximumSpendUsd),o=await xb(e,{schemaVersion:`openpond.trainingFundingHandoffRequest.v1`,teamId:e.teamId,maximumSpendUsd:i===null?null:Number(i),draft:{id:r.id,revision:r.revision,contentHash:r.contentHash,projectId:r.projectId}});if(C(),!o.canPurchase||!o.billingUrl)throw Error(`A workspace billing owner needs to add credits for this experiment.`);if(g.current={record:r,snapshot:L},h(!0),n?.openExternal){let e=await n.openExternal({conversationId:`experiment-funding:${r.id}`,url:o.billingUrl});if(C(),!e.ok)throw Error(e.error??`Billing could not be opened. Your experiment is saved; try again.`)}else t&&=(t.location.replace(o.billingUrl),null)}catch(e){t?.close(),x.current===b&&(d(e),h(!1),g.current=null)}finally{y.current=!1,x.current===b&&l(!1)}}async function ie(){if(!(_.current||x.current!==b)){_.current=!0;try{let t=g.current;if(t){let n=await Iy(e).get(t.record.id);if(C(),n.contentHash!==t.record.contentHash||n.status!==`draft`||ee.current!==t.snapshot)throw Error(`This experiment changed while Billing was open. Your edits remain here; save and review them before preparing.`)}await z.refresh(),C()}catch(e){x.current===b&&d(e)}finally{_.current=!1,x.current===b&&(g.current=null,h(!1))}}}let G=(0,Q.useRef)(ie);G.current=ie,(0,Q.useEffect)(()=>{if(!m)return;let e=()=>{document.visibilityState===`visible`&&G.current()};return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[m]);async function ae(e){if(C(),I||!t)throw Error(`Return to the editable experiment before selecting data.`);if(Fe(e),e.purpose!==`supervised_training`||!e.sealedAt||!e.examples.length)throw Error(`Choose a sealed, reviewed supervised training batch.`);o(t=>t.mode===`train`?{...t,batch:xe(e)}:t),p(!1)}let K=T.batches.filter(e=>e.purpose===`supervised_training`&&e.sealedAt&&e.exampleCount>0),q=a.mode===`train`?a.batch:null,oe=q?J(q):``,se=K.find(e=>J(e.reference)===oe),ce=K.map(e=>({value:J(e.reference),label:`${e.reference.id} · release ${e.reference.revision} · ${e.exampleCount} examples`}));oe&&!ce.some(e=>e.value===oe)&&ce.unshift({value:oe,label:`${q.id} · saved release ${q.revision}`,disabled:!0});let le=i.startingModel?.source===`decision`?`decision:${i.startingModel.decision.versionHash}`:i.startingModel?.source===`trained`?`trained:${i.startingModel.trainedVersion.contentHash}`:i.startingModel?.source===`engram`?`engram:${i.startingModel.engram.versionHash}`:i.startingModel?.source===`steering`?`steering:${i.startingModel.steering.versionHash}`:i.startingModel?.source===`inference`?`inference:${i.startingModel.inferenceModelId}`:D?J(D):``,ue=_n(),de=[{value:J(ue),label:ue.modelId}];return le&&!de.some(e=>e.value===le)&&de.unshift({value:le,label:i.startingModel?.label??D?.modelId??`Saved starting model`,disabled:!0}),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{hidden:f,inert:f,children:(0,$.jsxs)(Bv,{label:`Experiment setup`,action:`experiment`,onRequestClose:()=>void H.requestLeave(n),children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`h2`,{children:`Run Experiment`}),(0,$.jsx)(`button`,{type:`button`,disabled:F,onClick:()=>void H.requestLeave(n),children:`Close setup`})]}),(0,$.jsx)(X,{error:u??(a.mode===`train`?T.error:null)??M.error??E.error}),(0,$.jsxs)(`form`,{noValidate:!0,onSubmit:e=>{e.preventDefault(),re()},children:[(0,$.jsx)(ft,{title:`Starting model`,children:(0,$.jsxs)(`fieldset`,{disabled:I,children:[(0,$.jsxs)(`label`,{children:[`Model`,(0,$.jsx)(Z,{label:`Decision starting model`,floating:!0,searchable:!0,value:le,options:de,onChange:e=>{if(e===le)return;let t=e===J(ue)?{preference:ue}:null;e&&!t?d(`Refresh the model list before changing this selection.`):(i.setTrainingBaseModel(t?.preference??null),o(({startingDecision:e,...t})=>({...t,parentArtifact:null})))}})]}),(0,$.jsx)(xy,{disabled:I}),(0,$.jsxs)(`label`,{children:[`Mode`,(0,$.jsx)(Z,{floating:!0,label:`Decision mode`,value:a.mode,options:[{value:`train`,label:`Train`},{value:`score`,label:`Score`}],onChange:e=>{if(e===`train`||e===`score`){s.current[a.mode]=a;let{startingDecision:t,...n}=s.current[e];o({...n,baseModel:D,parentArtifact:a.parentArtifact,...a.startingDecision?{startingDecision:a.startingDecision}:{},name:a.name,maximumSpendUsd:a.maximumSpendUsd})}}})]}),(0,$.jsx)(`p`,{children:`Train from reviewed examples or score unlabeled state against every allowed candidate using this exact Decision adapter.`}),a.mode===`train`?(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:F||T.isFetching,onClick:()=>void T.refetch(),children:`Refresh reviewed batches`}):null,N?(0,$.jsx)(`p`,{children:N.state===`unavailable`?N.reason:`A compatible Decision runtime is available. Preparation rechecks its exact identity.`}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:F||M.isFetching||!j,onClick:()=>{E.refetch(),M.refetch()},children:`Refresh runtime availability`})]})}),a.mode===`train`?(0,$.jsx)(ft,{title:`Training data`,children:(0,$.jsxs)(`fieldset`,{disabled:I,children:[(0,$.jsxs)(`label`,{children:[`Reviewed batch`,(0,$.jsx)(Z,{label:`Decision reviewed batch`,floating:!0,searchable:!0,value:oe,options:[{value:``,label:`Choose sealed supervised batch`},...ce],onChange:e=>{let t=K.find(t=>J(t.reference)===e);e&&!t?d(`Refresh the reviewed batch before changing this selection.`):o(e=>e.mode===`train`?{...e,batch:t?.reference??null}:e)}})]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>p(!0),children:`Import or review data`})]})}):null,(0,$.jsx)(ft,{title:`Settings`,children:(0,$.jsxs)(`fieldset`,{disabled:I,children:[(0,$.jsxs)(`label`,{children:[`Experiment name`,(0,$.jsx)(`input`,{value:a.name,maxLength:500,onChange:e=>U({name:e.target.value})})]}),a.mode===`train`?(0,$.jsx)(Xy,{form:a,onChange:o}):(0,$.jsx)(Yy,{form:a,onChange:o}),a.startingDecision?(0,$.jsxs)(`p`,{children:[`Saved Model `,a.startingDecision.modelProjectId,` · version`,` `,a.startingDecision.versionHash]}):null,a.parentArtifact?(0,$.jsxs)(`p`,{children:[`Continue adapter `,a.parentArtifact.id,` · `,a.parentArtifact.contentHash,`. Optimizer state starts fresh.`]}):null,(0,$.jsxs)(`label`,{children:[`Spending limit (USD, optional)`,(0,$.jsx)(`input`,{type:`text`,inputMode:`decimal`,maxLength:100,placeholder:`Use available credits`,value:a.maximumSpendUsd,onChange:e=>U({maximumSpendUsd:e.target.value})})]})]})}),(0,$.jsx)(Db,{funding:z,busy:F,startAttempted:!!w.original,billingReturnPending:m,onOpenBilling:r?W:null,onRefresh:ie}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`submit`,className:`training-button secondary`,disabled:I||!r,children:c?`Saving…`:`Save draft`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:I||m||!r||!w.ready||N?.state!==`ready`||a.mode===`train`&&(!T.isSuccess||!se),onClick:()=>{d(null);try{w.prepare(te(),ne)}catch(e){d(e)}},children:`Compile and prepare`})]})]}),(0,$.jsx)(Zb,{owner:w,api:e,disabled:F,onOpenBilling:r?W:null,billingReturnPending:m,onRefreshFunding:ie}),H.dialog]})}),f?(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`p`,{role:`status`,children:`Opening training data…`}),children:(0,$.jsx)(Qb,{api:e,method:`decision_model`,navigation:v,onClose:()=>p(!1),onUseBatch:ae,beforeImport:async()=>{if(C(),I)throw Error(`Finish the original operation before importing data.`);await ne(te()),C()}})}):null]})}var ex=[{key:`learningRate`,label:`Learning rate`,inputMode:`decimal`},{key:`weightDecay`,label:`Weight decay`,inputMode:`decimal`},{key:`gradientAccumulationSteps`,label:`Gradient accumulation steps`,inputMode:`numeric`},{key:`maxSequenceLength`,label:`Maximum sequence tokens`,inputMode:`numeric`},{key:`seed`,label:`Seed`,inputMode:`numeric`},{key:`maxDurationSeconds`,label:`Maximum training seconds`,inputMode:`decimal`},{key:`maxCheckpointBytes`,label:`Maximum checkpoint bytes`,inputMode:`numeric`}];function tx({training:e,configuration:t,disabled:n=!1,onChange:r}){function i(t,n){r({...e,[t]:n})}return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Training steps`}),(0,$.jsx)(`input`,{type:`text`,inputMode:`numeric`,value:e.maxSteps,disabled:n,maxLength:100,onChange:e=>i(`maxSteps`,e.target.value)})]}),(0,$.jsxs)(`details`,{className:`model-training-settings`,children:[(0,$.jsx)(`summary`,{children:`Advanced Engram settings`}),(0,$.jsx)(`p`,{children:`Train the memory adapter with batch size 1 and gradient clipping at 1. The base weights stay frozen.`}),(0,$.jsx)(`div`,{className:`taskset-draft-field-grid`,children:ex.map(t=>(0,$.jsxs)(`label`,{className:`labs-model-create-field`,children:[(0,$.jsx)(`span`,{children:t.label}),(0,$.jsx)(`input`,{type:`text`,inputMode:t.inputMode,value:e[t.key],disabled:n,maxLength:100,onChange:e=>i(t.key,e.target.value)})]},t.key))}),(0,$.jsx)(`p`,{children:`Step, duration and checkpoint limits are validated before training. Preparation reviews the separate spend cap.`}),t?(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Fixed memory architecture`}),(0,$.jsxs)(`dl`,{children:[(0,$.jsx)(`dt`,{children:`Injection layers`}),(0,$.jsx)(`dd`,{children:t.injectLayers.join(`, `)}),(0,$.jsx)(`dt`,{children:`N-gram orders`}),(0,$.jsxs)(`dd`,{children:[`Suffix `,t.suffixOrders.join(`, `),`; previous group`,` `,t.previousOrders.join(`, `)]}),(0,$.jsx)(`dt`,{children:`Memory tables`}),(0,$.jsxs)(`dd`,{children:[t.numHashes,` hashes · `,t.tableSize.toLocaleString(),` rows · `,t.perHashDim,` dimensions per hash`]}),(0,$.jsx)(`dt`,{children:`Adapter`}),(0,$.jsxs)(`dd`,{children:[`FP32 · alpha `,t.alpha]})]})]}):null]})]})}function nx(){let e=wn;return Un.parse({baseModel:null,batch:null,name:``,maximumSpendUsd:``,training:{learningRate:String(e.learningRate),weightDecay:String(e.weightDecay),maxSteps:String(e.maxSteps),gradientAccumulationSteps:String(e.gradientAccumulationSteps),maxSequenceLength:String(e.maxSequenceLength),seed:String(e.seed),maxDurationSeconds:String(e.maxDurationSeconds),maxCheckpointBytes:String(e.maxCheckpointBytes)},parentArtifact:null})}function rx(e,t){let n=ml.parse({teamId:e.teamId,actorId:e.actorId,apiOrigin:t}),r={...n,projectId:e.projectId},i=`/v1/training/engram-executions`;return{account:n,async capability(t,a){return Ot(await Y(e.connection,`${i}/capability`,{method:`POST`,signal:a,body:JSON.stringify({...r,capabilityQuery:t})}),t,n.actorId)},async compile(t){return pn(await Y(e.connection,`${i}/compile`,{method:`POST`,body:JSON.stringify({...r,command:t})}),t)},async mutate(t,a){let o=`action`in t?`${i}/${encodeURIComponent(t.id)}/${t.action}`:`${i}/prepare`,s=await Jt(await Y(e.connection,o,{method:`POST`,body:JSON.stringify({...r,intentHash:a,command:t})}),t);if(s.execution.ownerUserId!==n.actorId||s.execution.projectId!==e.projectId)throw Error(`The execution receipt belongs to another account or Project.`);return s},async get(t,r){let a=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}}),o=await dn(await Y(e.connection,`${i}/${encodeURIComponent(t)}?${a}`,{signal:r}),{teamId:e.teamId,id:t,ownerUserId:n.actorId});if(o.projectId!==e.projectId)throw Error(`The execution belongs to another Project.`);return o},async list(t={},r){let a={...t,...e.projectId?{projectId:e.projectId}:{}},o=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}});for(let[e,t]of Object.entries(a))t!==void 0&&o.set(e,String(t));return mn(await Y(e.connection,`${i}?${o}`,{signal:r}),{teamId:e.teamId,ownerUserId:n.actorId,query:a})}}}function ix(e,t=!0){return S({queryKey:[`engram-experiment-account`,e.key,e.actorId],enabled:t&&e.location===`hosted`&&!!e.actorId,retry:!1,queryFn:async({signal:t})=>{let n=await e.request(`inventory`,{},t);if(n.teamId!==e.teamId)throw Error(`The workspace account changed.`);return rx(e,n.apiOrigin)}})}var ax=[`training:prepare-engram`,`training:start-engram`,`training:cancel-engram`];function ox(e,t){let n=u(),r=J([e.key,e.accountKey,e.actorId,e.teamId,e.projectId,e.connection.serverUrl,t.draftId,t.executionId,t.method]),i=(0,Q.useRef)(r);i.current=r,(0,Q.useEffect)(()=>(i.current=r,()=>{i.current=``}),[r]);let a=()=>({identity:r,busy:!1,error:null,receipt:null,selected:null,original:null,preparationOperationId:null}),[o,s]=(0,Q.useState)(a),c=(0,Q.useRef)(new Set),l=o.identity===r?o:a();function d(e){i.current===r&&s(t=>({...t.identity===r?t:a(),...e}))}function f(){if(i.current!==r)throw Error(`Return to this experiment's original account before continuing.`)}let p=ix(e,t.visible),m=p.data,h=S({queryKey:[`engram-experiment-recovery`,r],enabled:t.visible&&e.location===`hosted`&&!!e.actorId&&!l.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[];for(let i of ax){let a,o=new Set;for(let s=0;;s++){if(s>=100)throw Error(`The retained execution catalog exceeds its supported bound.`);let c=await e.pendingOperations(i,a,n);for(let n of c.items){let a=i===ax[0]?Sl.parse(n.reviewedIntent):Cl.parse(n.reviewedIntent);if(a.account.actorId!==e.actorId||a.account.teamId!==e.teamId)throw Error(`The retained execution belongs to another account.`);if(!(t.draftId===null?`execution`in a&&a.execution.id===t.executionId:a.draftId===t.draftId))continue;let o=i===ax[0]?Vn.parse(n.command??{...a.request,operationId:n.id}):Wt(n.command??{...a.request,operationId:n.id});r.push({intent:a,command:o,operation:e.recoverOperation(n)})}if(!c.nextCursor)break;if(o.has(c.nextCursor))throw Error(`The retained execution catalog repeated a cursor.`);o.add(c.nextCursor),a=c.nextCursor}}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),g=l.original??h.data?.[0]??null,_=t.executionId??l.selected??l.receipt?.execution.id??(g&&`execution`in g.intent?g.intent.execution.id:null),v=S({queryKey:[`managed-engram-execution`,r,_],enabled:t.visible&&!!(m&&_),retry:!1,queryFn:({signal:e})=>{if(!m||!_)throw Error(`Select an execution first.`);return m.get(_,e)},refetchInterval:e=>e.state.error?!1:e.state.data&&![`completed`,`failed`,`cancelled`].includes(e.state.data.phase)?3e3:!1});async function y(t){let r=rx(e,t.intent.account.apiOrigin);if(J(r.account)!==J(t.intent.account))throw Error(`Return to this execution's original account before retrying.`);d({original:t}),await t.operation.retainCommand(t.command,`dispatching`),f();let i=await r.mutate(t.command,t.operation.intentHash);return f(),d({receipt:i,selected:i.execution.id,preparationOperationId:`action`in t.command?`preparationOperationId`in t.intent?t.intent.preparationOperationId:null:t.command.operationId}),await t.operation.acknowledge(),f(),d({original:null}),await h.refetch(),f(),n.invalidateQueries({queryKey:[`managed-engram-execution`]}),n.invalidateQueries({queryKey:[`unified-experiments`]}),i}async function b(e){if(!c.current.has(r)){c.current.add(r),d({busy:!0,error:null});try{return f(),await e()}catch(e){return i.current===r&&d({error:e}),null}finally{c.current.delete(r),d({busy:!1})}}}async function x(n,r){return b(async()=>{if(g)return y(g);if(!m||!h.isSuccess||!t.draftId||n.id!==t.draftId||!n.engramForm||!t.method)throw Error(`Load this saved experiment and original requests before preparing.`);let i=vt(n.engramForm.maximumSpendUsd);await r(n),f();let a=await Iy(e).get(n.id);if(f(),a.status!==`draft`||a.projectId!==e.projectId||J(a.draft)!==J(n))throw Error(`The saved experiment changed. Reopen its exact current revision before preparing.`);let o=n.engramForm.baseModel;if(!o||o.source!==`managed`||n.startingModel&&![`managed`,`engram`].includes(n.startingModel.source))throw Error(`Choose a qualified exact Engram starting model.`);let s={teamId:e.teamId,modelId:o.modelId,source:o.source,...o.revision?{revision:o.revision}:{},...o.tokenizerRevision?{tokenizerRevision:o.tokenizerRevision}:{},...o.chatTemplateHash?{chatTemplateHash:o.chatTemplateHash}:{},...o.modelAssetId?{modelAssetId:o.modelAssetId}:{}},c={teamId:e.teamId,projectId:e.projectId,method:t.method,query:s,form:n.engramForm},l=await m.compile(c);if(f(),l.actorId!==e.actorId||l.formHash!==await zr(n.engramForm))throw Error(`The compilation differs from this exact saved form.`);let u=await ht({teamId:e.teamId,projectId:e.projectId,operationId:crypto.randomUUID(),name:n.name,method:t.method,query:s,request:l.request,sourceForm:n.engramForm,maximumSpendUsd:i}),{operationId:d,...p}=u,_=Sl.parse({account:m.account,draftId:n.id,request:p}),v=await e.operation(ax[0],_);return f(),y({intent:_,operation:v,command:{...u,operationId:v.id}})})}async function C(n,r){return b(async()=>{if(g)return y(g);let i=r??v.data;if(!m||!h.isSuccess||!i||v.error)throw Error(`Read the exact execution before reviewing its next action.`);let{schemaVersion:a,request:o,sourceForm:s,result:c,resultRecordedAt:u,contentHash:d,...p}=i,_=xt.parse(p),b=n===`start`?{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n,approvedMaximumSpendUsd:i.plan.maximumSpendUsd,...i.plan.computePrice?{approvedPriceHash:await zr(i.plan.computePrice)}:{}}:{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n},x=Cl.parse({account:m.account,draftId:l.preparationOperationId?t.draftId:null,preparationOperationId:l.preparationOperationId,execution:_,request:b}),S=await e.operation(n===`start`?ax[1]:ax[2],x);return f(),y({intent:x,operation:S,command:Wt({...b,operationId:S.id})})})}return{prepare:x,control:C,retry:()=>b(()=>{if(!g)throw Error(`Reload the original execution request.`);return y(g)}),busy:l.busy,receipt:l.receipt,original:g,execution:v.data,ready:p.isSuccess&&h.isSuccess,recoveryReady:!!g||h.isSuccess,canControl:v.isSuccess&&!v.error,error:l.error??p.error??h.error??v.error,refresh:()=>{p.refetch(),e.actorId&&h.refetch(),m&&_&&v.refetch()},loading:v.isFetching||p.isFetching,selectedId:_}}var sx=`training-engram-result-save`;function cx(e,t,n){let r=u(),i=J([e.key,ra(e.connection),t]),a=(0,Q.useRef)(i);a.current=i,(0,Q.useEffect)(()=>(a.current=i,()=>{a.current=``}),[i]);let o=()=>({identity:i,busy:!1,error:null,original:null,receipt:null}),[s,c]=(0,Q.useState)(o),l=(0,Q.useRef)(new Set),d=s.identity===i?s:o();function f(e){a.current===i&&c(t=>({...t.identity===i?t:o(),...e}))}function p(){if(a.current!==i)throw Error(`Return to this Model save's original account and result.`)}let m=n?.method===`engram_adapter`&&n.phase===`completed`&&n.result!==null,h=ix(e,m),g=S({queryKey:[`engram-model-save-recovery`,i],enabled:!!e.actorId&&!d.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[],i=new Set,a;for(let o=0;;o++){if(o>=100)throw Error(`The retained Model save catalog exceeds its supported bound.`);let s=await e.pendingOperations(sx,a,n);for(let n of s.items){let i=Dl.parse(n.reviewedIntent);if(i.request.executionId!==t)continue;if(i.account.actorId!==e.actorId||i.account.teamId!==e.teamId||i.execution.projectId!==e.projectId)throw Error(`The retained Model save belongs to another creator or Project.`);let a=jn.parse(n.command??{...i.request,operationId:n.id});r.push({intent:i,command:a,operation:e.recoverOperation(n)})}if(!s.nextCursor)break;if(i.has(s.nextCursor))throw Error(`The retained Model save catalog repeated a cursor.`);i.add(s.nextCursor),a=s.nextCursor}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),_=d.original??g.data?.[0]??null,v=S({queryKey:[`engram-model-save-options`,i,h.data?.account.apiOrigin,n?.result?.contentHash],enabled:m&&h.isSuccess&&g.isSuccess&&!_&&!d.busy,retry:!1,queryFn:async({signal:n})=>{if(!h.data)throw Error(`Read the configured result account first.`);let r=h.data.account,i=new URLSearchParams({...r,...e.projectId?{projectId:e.projectId}:{}}),a=Ol.parse(await Y(e.connection,`/v1/training/engram-executions/${encodeURIComponent(t)}/model?${i}`,{signal:n}));if(J(a.account)!==J(r)||a.executionId!==t||a.projectId!==e.projectId)throw Error(`The Model targets differ from this exact result account or Project.`);return a}});async function y(n){f({original:n}),await n.operation.retainCommand(n.command,`dispatching`),p();let i=await Y(e.connection,`/v1/training/engram-executions/${encodeURIComponent(n.command.executionId)}/model`,{method:`POST`,body:JSON.stringify({...n.intent.account,projectId:n.intent.execution.projectId,intentHash:n.operation.intentHash,command:n.command})}),a=await Bt(i,n.command);if(p(),a.actorId!==e.actorId||a.version.source.executionId!==t)throw Error(`The saved Model receipt belongs to another creator or Project.`);f({receipt:a});for(let e of[`saved-training-model`,`saved-model-serving`,`engram-model-save-options`,`unified-experiments`,`model-projects`])r.invalidateQueries({queryKey:[e]});return await n.operation.acknowledge(),p(),f({original:null}),await g.refetch(),p(),a}async function b(r){if(l.current.has(i))return null;l.current.add(i),f({busy:!0,error:null});try{if(p(),_)return await y(_);if(!g.isSuccess)throw Error(`Reload the original Model saves before continuing.`);if(!m||!n?.result||!v.isSuccess||!h.isSuccess||!v.data)throw Error(`Read the completed Engram result and current Model targets before saving.`);let i=r.modelProjectId?v.data.models.find(e=>e.id===r.modelProjectId):null;if(r.modelProjectId&&!i)throw Error(`Refresh the Model targets before updating this Model.`);let{schemaVersion:a,request:o,sourceForm:s,result:c,resultRecordedAt:l,contentHash:u,...d}=n,f=Dl.parse({account:v.data.account,execution:xt.parse(d),request:{teamId:e.teamId,executionId:t,resultHash:n.result.contentHash,artifactHash:n.result.artifact.contentHash,name:r.name,modelProjectId:i?.id??null,expectedModelRevision:i?.revision??0}}),b=await e.operation(sx,f);return p(),await y({intent:f,operation:b,command:jn.parse({...f.request,operationId:b.id})})}catch(e){return a.current===i&&f({error:e}),null}finally{l.current.delete(i),f({busy:!1})}}return{save:b,busy:d.busy,receipt:d.receipt,original:_,options:v.data,freshReady:m&&g.isSuccess&&v.isSuccess&&h.isSuccess,recoveryReady:!!_||g.isSuccess,error:d.error??g.error??(m?v.error??h.error:null),refresh:()=>{g.refetch(),m&&!_&&(h.refetch(),h.data&&v.refetch())}}}function lx({api:e,id:t,execution:n,disabled:r=!1}){let i=cx(e,t,n),a=kv(),[o,s]=(0,Q.useState)(null),c=`${e.key}:${t}`,l=(0,Q.useRef)(c);l.current=c,(0,Q.useEffect)(()=>(l.current=c,()=>{l.current=``}),[c]);async function u(){let t=i.receipt;if(!(!t||i.busy||i.original||r))try{let n=Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:crypto.randomUUID(),operationType:`engram_adapter`,name:`${t.model.name} Engram experiment`,startingModel:await $t(t.version,{teamId:e.teamId,label:`${t.model.name} / Saved memory module`}),engramForm:await gr(nx(),t.version,{teamId:e.teamId})});l.current===c&&await a.openDraft(n,as(`experiments`,null,{projectId:e.projectId,executionLocation:`hosted`}))}catch(e){l.current===c&&s(e)}}let[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)((n?.name??`Engram Model`).slice(0,200)),[h,g]=(0,Q.useState)(``),_=i.original?.command,v=iy({name:`Engram Model save`,busy:i.busy,dirty:d&&(!!_||p!==(n?.name??`Engram Model`).slice(0,200)||!!h),discardDescription:_?`The original save remains recoverable from this execution after closing.`:void 0}),y=n?.method===`engram_adapter`&&n.phase===`completed`&&n.result!==null,b=!i.recoveryReady&&i.error!==null;if(!y&&!_&&!i.receipt&&!b)return null;let x=i.receipt?.version;return(0,$.jsxs)(`section`,{className:`training-detail-section`,"aria-label":`Save Engram Model`,children:[(0,$.jsx)(X,{error:o??i.error}),i.recoveryReady?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Reload retained Model saves`}),i.receipt&&x?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[`Saved to `,i.receipt.model?.name,`. Exact version `,(0,$.jsx)(`code`,{children:x.contentHash}),`.`]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact saved version`}),(0,$.jsx)(`pre`,{className:`saved-model-version-reference`,children:JSON.stringify(x,null,2)})]}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void wo(as(`models`)),children:`Open Models`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:r||i.busy||!!_,onClick:()=>void u(),children:`New experiment from saved module`})]}),(0,$.jsx)(hb,{connection:e.connection,version:x,api:e},`${e.key}:${x.contentHash}`)]}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:r||i.busy||!i.recoveryReady,onClick:()=>f(!0),children:_?`Recover Model save`:i.receipt?`Save model again`:`Save model`}),d?(0,$.jsxs)(qa,{ariaLabel:`Save Engram model`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:i.busy,onClose:()=>void v.requestLeave(()=>f(!1)),children:[(0,$.jsx)(`h2`,{children:`Save model`}),(0,$.jsx)(`p`,{children:`Save the exact trained memory module from this completed result. Saving does not activate serving.`}),(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),i.save({name:p,modelProjectId:h||null}).then(e=>{e&&(v.allowNextNavigation(),f(!1))})},children:[(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Save destination`}),(0,$.jsx)(Z,{label:`Model destination`,value:_?.modelProjectId??(_?``:h),options:[{value:``,label:`Create new Model`},...(i.options?.models??[]).map(e=>({value:e.id,label:e.name,description:`Current revision ${e.revision}`})),..._?.modelProjectId&&!i.options?.models.some(e=>e.id===_.modelProjectId)?[{value:_.modelProjectId,label:`Original selected Model`}]:[]],disabled:i.busy||!!_||!i.freshReady,onChange:e=>{g(e);let t=i.options?.models.find(t=>t.id===e);t&&m(t.name)}})]}),(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Model name`}),(0,$.jsx)(`input`,{"data-autofocus":!0,value:_?.name??p,maxLength:200,disabled:i.busy||!!_,onChange:e=>m(e.target.value)})]}),_?(0,$.jsx)(`p`,{children:`Original result, module, destination and revision are retained. Retry sends the same operation.`}):null,i.receipt&&_?(0,$.jsx)(`p`,{role:`status`,children:`The Model was saved. Local acknowledgement is pending; retry preserves its exact receipt.`}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:()=>void v.requestLeave(()=>f(!1)),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Refresh targets and recovery`}),(0,$.jsx)(`button`,{type:`submit`,className:`training-button`,disabled:i.busy||r||!i.recoveryReady||!_&&!i.freshReady,children:i.busy?`Saving…`:_?`Retry original save`:`Save model`})]})]})]}):null,v.dialog]})}function ux({result:e}){let t=e.artifact,n=t.manifest;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ft,{title:`Training result`,children:(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Optimizer steps`}),(0,$.jsx)(`dd`,{children:e.optimizerSteps}),(0,$.jsx)(`dt`,{children:`Examples processed`}),(0,$.jsx)(`dd`,{children:e.examplesProcessed}),(0,$.jsx)(`dt`,{children:`Target tokens`}),(0,$.jsx)(`dd`,{children:e.targetTokens}),(0,$.jsx)(`dt`,{children:`Forward token work`}),(0,$.jsx)(`dd`,{children:e.forwardTokenWork}),(0,$.jsx)(`dt`,{children:`Mean loss`}),(0,$.jsx)(`dd`,{children:e.meanLoss}),(0,$.jsx)(`dt`,{children:`Final loss`}),(0,$.jsx)(`dd`,{children:e.finalLoss}),(0,$.jsx)(`dt`,{children:`Training duration`}),(0,$.jsxs)(`dd`,{children:[(e.durationMs/1e3).toLocaleString(),` seconds`]}),(0,$.jsx)(`dt`,{children:`Base optimizer parameters`}),(0,$.jsx)(`dd`,{children:e.baseOptimizerParameterCount}),(0,$.jsx)(`dt`,{children:`Base gradient parameters`}),(0,$.jsx)(`dd`,{children:e.baseGradientParameterCount}),(0,$.jsx)(`dt`,{children:`Frozen base before`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.baseWeightsHashBefore}),(0,$.jsx)(`dt`,{children:`Frozen base after`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.baseWeightsHashAfter}),(0,$.jsx)(`dt`,{children:`Result`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:e.contentHash})]})}),(0,$.jsxs)(ft,{title:`Memory module`,children:[(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Artifact`}),(0,$.jsx)(`dd`,{children:t.id}),(0,$.jsx)(`dt`,{children:`Manifest`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:t.contentHash}),(0,$.jsx)(`dt`,{children:`Runtime`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:n.pins.runtimeHash}),(0,$.jsx)(`dt`,{children:`Reviewed batch`}),(0,$.jsxs)(`dd`,{children:[n.pins.data.batch.id,` · release `,n.pins.data.batch.revision]}),(0,$.jsx)(`dt`,{children:`Parent adapter`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:n.pins.parentArtifactHash??`Fresh adapter`})]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Committed module files`}),(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`File`}),(0,$.jsx)(`th`,{children:`Bytes`}),(0,$.jsx)(`th`,{children:`SHA-256`})]})}),(0,$.jsx)(`tbody`,{children:t.files.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.path}),(0,$.jsx)(`td`,{children:e.sizeBytes.toLocaleString()}),(0,$.jsx)(`td`,{className:`saved-model-version-reference`,children:e.sha256})]},e.path))})]})]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Saved adapter tensors`}),(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Tensor`}),(0,$.jsx)(`th`,{children:`Shape`}),(0,$.jsx)(`th`,{children:`Type`})]})}),(0,$.jsx)(`tbody`,{children:n.payload.tensors.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.name}),(0,$.jsx)(`td`,{children:e.shape.join(` × `)}),(0,$.jsx)(`td`,{children:e.dtype})]},e.name))})]})]})]})]})}function dx({owner:e,api:t,onOpenBilling:n=null,billingReturnPending:r=!1,onRefreshFunding:i,disabled:a=!1}){let o=e.busy||a,s=e.execution,c=e.original,l=(e.receipt&&(!s||e.receipt.execution.id===s.id&&e.receipt.execution.revision>s.revision)?e.receipt.execution:s)??(c&&`execution`in c.intent?c.intent.execution:null),[u,d]=(0,Q.useState)(null),f=Tb(t,l?.plan.maximumSpendUsd??``,!!l,!!l?.plan.computePrice),p=c?`action`in c.command?c.command.action:`prepare`:null;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{error:e.error}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o||e.loading,onClick:e.refresh,children:`Refresh execution and recovery`}),c?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||!e.recoveryReady,onClick:()=>void e.retry(),children:o?`Reconciling…`:`Retry original ${p}`}):null]}),c&&!(`action`in c.command)?(0,$.jsxs)(ft,{title:`Original preparation`,children:[(0,$.jsxs)(`p`,{children:[c.command.name,` · `,c.command.method,` · `,Uy(c.command.maximumSpendUsd)]}),(0,$.jsxs)(`p`,{children:[c.command.request.training.maxSteps,` training steps ·`,` `,`batch `,c.command.request.data.batch.id,` ·`,` `,c.command.request.model.modelId,` · `,c.command.request.model.revision]})]}):null,l?(0,$.jsxs)(ft,{title:`Hosted execution`,children:[(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`State`}),(0,$.jsx)(`dd`,{children:l.phase}),(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(l.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:l.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Execution`}),(0,$.jsx)(`dd`,{children:l.id}),(0,$.jsx)(`dt`,{children:`Preparation expires`}),(0,$.jsx)(`dd`,{children:new Date(l.plan.expiresAt).toLocaleString()}),(0,$.jsx)(`dt`,{children:`Exact plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:l.plan.contentHash}),(0,$.jsx)(`dt`,{children:`Runtime`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:l.plan.runtimeHash})]}),s?(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[s.phase===`prepared`?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||e.loading||!e.ready||!e.canControl||!!c||Date.parse(s.plan.expiresAt)<=Date.now(),onClick:()=>d({action:`start`,value:s}),children:`Review Start`}):null,[`completed`,`cancelled`,`failed`].includes(s.phase)?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o||e.loading||!e.ready||!e.canControl||!!c,onClick:()=>d({action:`cancel`,value:s}),children:`Review Cancel`})]}):null]}):null,s?.result?(0,$.jsx)(ux,{result:s.result}):l?.phase===`completed`?(0,$.jsx)(`p`,{children:`No result bytes are available in this read. Retained execution identity remains available for recovery.`}):null,e.selectedId?(0,$.jsx)(lx,{api:t,id:e.selectedId,execution:s,disabled:o||!!c},`${t.key}:${e.selectedId}`):null,u&&s?(0,$.jsxs)(qa,{ariaLabel:u.action===`start`?`Start Engram experiment`:`Cancel Engram experiment`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:o,onClose:()=>{o||d(null)},children:[(0,$.jsx)(`h2`,{children:u.action===`start`?`Start Engram experiment`:`Cancel Engram experiment`}),(0,$.jsx)(`p`,{children:u.action===`start`?Gy(u.value.plan.computePrice):`Cancel this exact execution. In-flight work may need to stop and settle before capacity is released.`}),(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(u.value.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:u.value.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Training steps`}),(0,$.jsx)(`dd`,{children:u.value.request.training.maxSteps}),(0,$.jsx)(`dt`,{children:`Reviewed batch`}),(0,$.jsxs)(`dd`,{children:[u.value.request.data.batch.id,` · release `,u.value.request.data.batch.revision]}),(0,$.jsx)(`dt`,{children:`Maximum duration`}),(0,$.jsxs)(`dd`,{children:[u.value.request.training.maxDurationSeconds,` seconds`]}),(0,$.jsx)(`dt`,{children:`Model`}),(0,$.jsxs)(`dd`,{children:[u.value.request.model.modelId,` · `,u.value.request.model.revision]}),(0,$.jsx)(`dt`,{children:`Plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:u.value.plan.contentHash})]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact prepared training request`}),(0,$.jsx)(`pre`,{children:JSON.stringify(u.value.request,null,2)})]}),u.action===`start`?(0,$.jsx)(Db,{funding:f,busy:o,startAttempted:!!c,billingReturnPending:r,onOpenBilling:n,onRefresh:i??(async()=>{await f.refresh()})}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o,onClick:()=>d(null),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:o||e.loading||!!c||!e.ready||!e.canControl||u.action===`start`&&(r||!f.canStart||Date.parse(u.value.plan.expiresAt)<=Date.now()),onClick:()=>void e.control(u.action,u.value).then(e=>{e&&d(null)}),children:o?`Applying…`:u.action===`start`?Ky(u.value.plan.maximumSpendUsd):`Cancel execution`})]})]}):null]})}var fx=(0,Q.lazy)(()=>o(()=>import(`./ExperimentTrainingDataWorkspace-CfOyoMrq.js`),__vite__mapDeps([76,1,2,3,4,77,5,6,9,10,78,32,27,31,21,16,43,19,20,22,13,23,15,24,25,26,8,28,11,29,30,33,34,35,36,37,38,39,40,41,18,42,44,45,46,47,48,49,50,51,52,53,54,55,56,79,80])));function px({api:e,visible:t,onClose:n,onSaveDraft:r}){let i=kv(),[a,o]=(0,Q.useState)(()=>i.initialExperiment?.engramForm??nx()),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(!1),h=(0,Q.useRef)(null),g=(0,Q.useRef)(!1),_=(0,Q.useRef)(null),v=(0,Q.useRef)(!1),y=J([e.key,e.accountKey,e.actorId,e.teamId,e.projectId,e.connection.serverUrl,i.initialExperiment?.id]),b=(0,Q.useRef)(y);b.current=y,(0,Q.useEffect)(()=>(b.current=y,()=>{b.current=``}),[y]);function x(){if(b.current!==y)throw Error(`Return to this experiment's original account before continuing.`)}let C=ox(e,{draftId:i.initialExperiment?.id??null,method:`engram_adapter`,visible:t}),w=Ry(e,t,a.batch),T=ix(e,t),E=i.trainingBaseModel,D=!i.startingModel||i.startingModel.source===`managed`||i.startingModel.source===`engram`,O=wv(i.startingModel),k=(0,Q.useRef)(O);(0,Q.useEffect)(()=>{k.current!==O&&i.startingModel?.source!==`engram`&&o(({startingModule:e,...t})=>({...t,parentArtifact:null})),k.current=O},[O,i.startingModel?.source]);let A=E?.source===`managed`&&D?{teamId:e.teamId,source:E.source,modelId:E.modelId,...E.revision?{revision:E.revision}:{},...E.tokenizerRevision?{tokenizerRevision:E.tokenizerRevision}:{},...E.chatTemplateHash?{chatTemplateHash:E.chatTemplateHash}:{},...E.modelAssetId?{modelAssetId:E.modelAssetId}:{}}:null,j=S({queryKey:[`engram-execution-capability`,y,A],enabled:t&&!!(T.data&&A),retry:!1,staleTime:3e4,queryFn:({signal:e})=>{if(!T.data||!A)throw Error(`Choose an exact managed base before checking Engram availability.`);return T.data.capability(A,e)},refetchInterval:e=>!e.state.error&&6e4}),M=j.data&&!j.isError&&Date.parse(j.data.expiresAt)>Date.now()?j.data.execution:null,N=C.selectedId&&![`completed`,`failed`,`cancelled`].includes(C.execution?.phase??C.receipt?.execution.phase??`prepared`),P=s||C.busy,F=P||!!(C.original||N),I=J({...a,baseModel:E,sourceKey:O}),L=(0,Q.useRef)(I);L.current=I;let ee=(0,Q.useRef)(I),R=Tb(e,a.maximumSpendUsd,t,!0),z=I!==ee.current,B=i.reportOperationDraftDirty;(0,Q.useEffect)(()=>{B(`engram_adapter`,z)},[z,B]);let V=iy({name:`Engram experiment`,dirty:z||i.operationDraftDirty||i.evaluationDirty,busy:P,onLeave:n});My({...V,requestLeave:async e=>{d&&_.current?await _.current.requestLeave(()=>V.requestLeave(e)):await V.requestLeave(e)}},t);function H(e){o(t=>({...t,...e}))}function U(){if(!i.initialExperiment)throw Error(`Open an experiment before saving its settings.`);if(!D)throw Error(`Engram requires its exact managed base. Choose another starting model.`);return Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:i.initialExperiment.id,operationType:`engram_adapter`,name:a.name.trim()||`Engram experiment`,...i.startingModel?{startingModel:i.startingModel}:{},engramForm:{...a,baseModel:E}})}async function te(t){if(!r)throw Error(`Load canonical draft storage before preparing.`);await r(t),x();let n=await Iy(e).get(t.id);if(x(),n.status!==`draft`||n.projectId!==e.projectId||J(n.draft)!==J(t))throw Error(`The saved experiment changed. Reopen its exact current revision before continuing.`);return ee.current=I,n}async function ne(){if(!(v.current||F)){v.current=!0,c(!0),u(null);try{await te(U())}catch(e){b.current===y&&u(e)}finally{v.current=!1,b.current===y&&c(!1)}}}async function re(){if(v.current||C.busy||C.original)return;v.current=!0,c(!0),u(null);let t=null;try{let n=window.openpond?.browser;if(!n?.openExternal){if(t=window.open(`about:blank`,`_blank`),!t)throw Error(`Allow a new tab to open Billing, then try again.`);t.opener=null}let r=await te(U());x();let i=vt(a.maximumSpendUsd),o=await xb(e,{schemaVersion:`openpond.trainingFundingHandoffRequest.v1`,teamId:e.teamId,maximumSpendUsd:i===null?null:Number(i),draft:{id:r.id,revision:r.revision,contentHash:r.contentHash,projectId:r.projectId}});if(x(),!o.canPurchase||!o.billingUrl)throw Error(`A workspace billing owner needs to add credits for this experiment.`);if(h.current={record:r,snapshot:I},m(!0),n?.openExternal){let e=await n.openExternal({conversationId:`experiment-funding:${r.id}`,url:o.billingUrl});if(x(),!e.ok)throw Error(e.error??`Billing could not be opened. Your experiment is saved; try again.`)}else t&&=(t.location.replace(o.billingUrl),null)}catch(e){t?.close(),b.current===y&&(u(e),m(!1),h.current=null)}finally{v.current=!1,b.current===y&&c(!1)}}async function W(){if(!(g.current||b.current!==y)){g.current=!0;try{let t=h.current;if(t){let n=await Iy(e).get(t.record.id);if(x(),n.contentHash!==t.record.contentHash||n.status!==`draft`||L.current!==t.snapshot)throw Error(`This experiment changed while Billing was open. Your edits remain here; save and review them before preparing.`)}await R.refresh(),x()}catch(e){b.current===y&&u(e)}finally{g.current=!1,b.current===y&&(h.current=null,m(!1))}}}let ie=(0,Q.useRef)(W);ie.current=W,(0,Q.useEffect)(()=>{if(!p)return;let e=()=>{document.visibilityState===`visible`&&ie.current()};return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[p]);async function G(e){if(x(),F||!t)throw Error(`Return to the editable experiment before selecting data.`);if(Fe(e),e.purpose!==`supervised_training`||!e.sealedAt||!e.examples.length)throw Error(`Choose a sealed, reviewed supervised training batch.`);H({batch:xe(e)}),f(!1)}let ae=w.batches.filter(e=>e.purpose===`supervised_training`&&e.sealedAt&&e.exampleCount>0),K=a.batch?J(a.batch):``,q=ae.find(e=>J(e.reference)===K),oe=ae.map(e=>({value:J(e.reference),label:`${e.reference.id} · release ${e.reference.revision} · ${e.exampleCount} examples`}));K&&!oe.some(e=>e.value===K)&&oe.unshift({value:K,label:`${a.batch.id} · saved release ${a.batch.revision}`,disabled:!0});let se=i.startingModel?.source===`trained`?`trained:${i.startingModel.trainedVersion.contentHash}`:i.startingModel?.source===`engram`?`engram:${i.startingModel.engram.versionHash}`:i.startingModel?.source===`steering`?`steering:${i.startingModel.steering.versionHash}`:i.startingModel?.source===`inference`?`inference:${i.startingModel.inferenceModelId}`:E?J(E):``,ce=w.models.filter(e=>e.preference.source===`managed`).map(e=>({value:J(e.preference),label:e.name}));return se&&!ce.some(e=>e.value===se)&&ce.unshift({value:se,label:i.startingModel?.label??E?.modelId??`Saved starting model`,disabled:!0}),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{hidden:d,inert:d,children:(0,$.jsxs)(Bv,{label:`Experiment setup`,action:`experiment`,onRequestClose:()=>void V.requestLeave(n),children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`h2`,{children:`Run Experiment`}),(0,$.jsx)(`button`,{type:`button`,disabled:P,onClick:()=>void V.requestLeave(n),children:`Close setup`})]}),(0,$.jsx)(X,{error:l??w.error??j.error??T.error}),(0,$.jsxs)(`form`,{noValidate:!0,onSubmit:e=>{e.preventDefault(),ne()},children:[(0,$.jsx)(ft,{title:`Starting model`,children:(0,$.jsxs)(`fieldset`,{disabled:F,children:[(0,$.jsxs)(`label`,{children:[`Model`,(0,$.jsx)(Z,{label:`Engram starting model`,floating:!0,searchable:!0,value:se,options:[{value:``,label:`Choose exact managed base`},...ce],onChange:e=>{if(e===se)return;let t=w.models.find(t=>J(t.preference)===e&&t.preference.source===`managed`);e&&!t?u(`Refresh the model list before changing this selection.`):(i.setTrainingBaseModel(t?.preference??null),o(({startingModule:e,...t})=>({...t,parentArtifact:null})))}})]}),(0,$.jsx)(xy,{disabled:F}),(0,$.jsx)(`p`,{children:`Engram trains a memory adapter on a frozen compatible base. Preparation resolves the exact reviewed data and qualified runtime.`}),(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:P||w.isFetching,onClick:()=>void w.refetch(),children:`Refresh models and reviewed batches`}),M?(0,$.jsx)(`p`,{children:M.state===`unavailable`?M.reason:`A compatible Engram runtime is available. Preparation rechecks its exact identity.`}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:P||j.isFetching||!A,onClick:()=>{T.refetch(),j.refetch()},children:`Refresh runtime availability`})]})}),(0,$.jsx)(ft,{title:`Training data`,children:(0,$.jsxs)(`fieldset`,{disabled:F,children:[(0,$.jsxs)(`label`,{children:[`Reviewed batch`,(0,$.jsx)(Z,{label:`Engram reviewed batch`,floating:!0,searchable:!0,value:K,options:[{value:``,label:`Choose sealed supervised batch`},...oe],onChange:e=>{let t=ae.find(t=>J(t.reference)===e);e&&!t?u(`Refresh the reviewed batch before changing this selection.`):H({batch:t?.reference??null})}})]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>f(!0),children:`Import or review data`})]})}),(0,$.jsx)(ft,{title:`Settings`,children:(0,$.jsxs)(`fieldset`,{disabled:F,children:[(0,$.jsxs)(`label`,{children:[`Experiment name`,(0,$.jsx)(`input`,{value:a.name,maxLength:500,onChange:e=>H({name:e.target.value})})]}),(0,$.jsx)(tx,{training:a.training,configuration:M?.state===`ready`?M.config:null,disabled:F,onChange:e=>H({training:e})}),a.startingModule?(0,$.jsxs)(`p`,{children:[`Saved Model `,a.startingModule.modelProjectId,` · version `,a.startingModule.versionHash]}):null,a.parentArtifact?(0,$.jsxs)(`p`,{children:[`Continue adapter `,a.parentArtifact.id,` · `,a.parentArtifact.contentHash,`. Optimizer state starts fresh.`]}):null,(0,$.jsxs)(`label`,{children:[`Spending limit (USD, optional)`,(0,$.jsx)(`input`,{type:`text`,inputMode:`decimal`,maxLength:100,placeholder:`Use available credits`,value:a.maximumSpendUsd,onChange:e=>H({maximumSpendUsd:e.target.value})})]})]})}),(0,$.jsx)(Db,{funding:R,busy:P,startAttempted:!!C.original,billingReturnPending:p,onOpenBilling:r?re:null,onRefresh:W}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`submit`,className:`training-button secondary`,disabled:F||!r,children:s?`Saving…`:`Save draft`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:F||p||!r||!C.ready||!w.isSuccess||M?.state!==`ready`||!q,onClick:()=>{u(null);try{C.prepare(U(),te)}catch(e){u(e)}},children:`Compile and prepare`})]})]}),(0,$.jsx)(dx,{owner:C,api:e,disabled:P,onOpenBilling:r?re:null,billingReturnPending:p,onRefreshFunding:W}),V.dialog]})}),d?(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`p`,{role:`status`,children:`Opening training data…`}),children:(0,$.jsx)(fx,{api:e,method:`engram_adapter`,navigation:_,onClose:()=>f(!1),onUseBatch:G,beforeImport:async()=>{if(x(),F)throw Error(`Finish the original operation before importing data.`);await te(U()),x()}})}):null]})}function mx({api:e,evidence:t,onOpenRun:n}){let r=kv(),i=(0,Q.useRef)(Vv(e));return i.current=Vv(e),Rv(t?[{id:`advanced-refiner`,label:`Evaluate Refiner`,onSelect:()=>{let n=Vv(e);ho(()=>{i.current===n&&r.openAdvanced({kind:`refiner_evaluation`,evidence:t})})}}]:[]),null}function hx({api:e,evidence:t,onDirty:n,onBusy:r,onOpenRun:i}){let a=Vv(e),o=(0,Q.useRef)(a);o.current=a;let s=(0,Q.useRef)(!0),c=(0,Q.useRef)(null),l=(0,Q.useRef)(null),d=(0,Q.useRef)(!1),f=u(),p=[`advanced-refiner-evaluations`,a,t.id,t.contentHash],m=S({queryKey:[...p,`options`],queryFn:async({signal:n})=>_o.parse(await Hv(e,`advanced-refiner-evaluations`,{operation:`options`,evidence:t},n))}),h=S({queryKey:[...p,`models`],queryFn:({signal:t})=>e.request(`graderModels`,{},t)}),g=Uv(e,`advanced-refiner-start`),_=g.data?.pages.flatMap(e=>e.items)??[];async function v(t){let r=a;re(!0);try{await e.recoverOperation(t).acknowledge(`reviewed`),s.current&&o.current===r&&(l.current?.operation.id===t.id&&(l.current=null,d.current=!1,H(null)),await g.refetch(),n(!1))}catch(e){s.current&&o.current===r&&G(e instanceof Error?e.message:String(e))}finally{s.current&&o.current===r&&re(!1)}}function y(t){try{if(!t.recoveryReady||ie(t.reviewedIntent)!==t.intentHash)throw Error(`The original reviewed intent is unavailable.`);let r=fo.parse(t.command);if(r.operation!==`start`)throw Error(`The retained command is not an advanced evaluation Start.`);let i=Zo(r.request.pin);if(i.operationId!==t.id||i.actorId!==e.actorId||i.teamId!==e.teamId||i.projectId!==e.projectId)throw Error(`The retained command belongs to another owner scope.`);l.current={scope:a,pin:i,operation:e.recoverOperation(t),request:r},d.current=t.phase===`dispatching`,H(i),n(!0),G(null)}catch(e){G(e instanceof Error?e.message:String(e))}}let b=S({queryKey:[...p,`history`],queryFn:({signal:t})=>Hv(e,`advanced-refiner-evaluations`,{operation:`list`},t),refetchInterval:5e3}),[x,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(``),[E,D]=(0,Q.useState)(`train`),[O,k]=(0,Q.useState)(`downstream_adaptation`),[A,j]=(0,Q.useState)(``),[M,N]=(0,Q.useState)(``),[P,F]=(0,Q.useState)(``),[I,L]=(0,Q.useState)(1),[ee,R]=(0,Q.useState)(30),[z,B]=(0,Q.useState)(10),[V,H]=(0,Q.useState)(null),[U,te]=(0,Q.useState)(null),[ne,re]=(0,Q.useState)(!1),[W,G]=(0,Q.useState)(null);(0,Q.useEffect)(()=>(s.current=!0,()=>{s.current=!1,c.current?.abort()}),[]),(0,Q.useEffect)(()=>(r(ne),()=>r(!1)),[ne,r]);let ae=m.data?.profiles.find(e=>e.id===x),K=ae?.components.find(e=>e.label===w),q=m.data?.refinerReleases.find(e=>e.id===A),oe=m.data?.models.filter(e=>e.profileId===ae?.profileRef.profileId)??[];function se(e){ne||l.current||(e(),H(null),n(!0))}let ce=S({queryKey:[...p,`run`,U?.id],enabled:!!U,queryFn:async({signal:t})=>Oo.parse(await Hv(e,`advanced-refiner-evaluations`,{operation:`read`,id:U.id},t)),refetchInterval:3e3});(0,Q.useEffect)(()=>{ce.data?.id===U?.id&&ce.data&&te(ce.data)},[ce.data,U?.id]);async function le(){if(ne||!ae||!K||!q)return;let r=a;re(!0),G(null);let i=new AbortController;c.current=i;try{let a={evidence:t,profileOptionId:ae.id,componentLabel:K.label,mode:O,adaptationSplit:E,refinerRelease:q,maximumCostUsd:I,maximumDurationMs:z*6e4,maximumModelSteps:ee,localModelId:M,modelId:P},c=await e.operation(`advanced-refiner-start`,a);if(!s.current||o.current!==r)return;let u=await Hv(e,`advanced-refiner-evaluations`,{operation:`prepare`,evidence:t,profileOptionId:ae.id,componentLabel:K.label,mode:O,adaptationSplit:E,operationId:c.id,refinerRelease:q,maximumCostUsd:I,maximumDurationMs:z*6e4,maximumModelSteps:ee},i.signal),d=Zo(u.pin);if(!s.current||o.current!==r)return;if(d.actorId!==e.actorId||d.teamId!==e.teamId||d.projectId!==e.projectId||d.operationId!==c.id)throw Error(`The reviewed evaluation belongs to another owner.`);if(H(d),l.current={scope:r,pin:d,operation:c,request:{operation:`start`,request:{pin:d,modelId:M,profileId:ae.profileRef.profileId,model:{providerId:`openpond`,modelId:P},seed:Number(K.binding.population[0].seed),reasoningEffort:null}}},await c.retainCommand(l.current.request,`reviewed`),!s.current||o.current!==r||(await g.refetch(),!s.current||o.current!==r))return;n(!0)}catch(e){s.current&&o.current===r&&G(e instanceof Error?e.message:String(e))}finally{s.current&&o.current===r&&re(!1),c.current===i&&(c.current=null)}}async function ue(){let e=l.current,t=a;if(!(ne||d.current||!e)){re(!0);try{if(await e.operation.acknowledge(`reviewed`),!s.current||o.current!==t||(await g.refetch(),!s.current||o.current!==t))return;l.current=null,H(null),n(!0)}catch(e){s.current&&o.current===t&&G(e instanceof Error?e.message:String(e))}finally{s.current&&o.current===t&&re(!1)}}}async function de(){let t=l.current;if(ne||!t||t.scope!==a)return;let r=a;re(!0),G(null);let i=new AbortController;c.current=i,d.current=!0;try{if(await t.operation.retainCommand(t.request,`dispatching`),!s.current||o.current!==r)return;let a=Oo.parse(await Hv(e,`advanced-refiner-evaluations`,t.request,i.signal));if(!s.current||o.current!==r)return;if(a.evaluation?.benchmarkId!==`harness-refiner`||a.evaluation.advancedEvaluation?.contentHash!==t.pin.contentHash)throw Error(`The run receipt differs from the frozen review.`);if(te(a),await t.operation.acknowledge(),!s.current||o.current!==r||(l.current=null,d.current=!1,await g.refetch(),!s.current||o.current!==r))return;n(!1),await f.invalidateQueries({queryKey:[...p,`history`]})}catch(e){s.current&&o.current===r&&G(e instanceof Error?e.message:String(e))}finally{s.current&&o.current===r&&re(!1),c.current===i&&(c.current=null)}}async function fe(t,n){if(ne)return;let r=a;re(!0),G(null);try{let i=await Hv(e,`advanced-refiner-evaluations`,{operation:t,id:n});if(!s.current||o.current!==r)return;t===`resume`&&te(Oo.parse(i)),await f.invalidateQueries({queryKey:[...p,`history`]})}catch(e){s.current&&o.current===r&&G(e instanceof Error?e.message:String(e))}finally{s.current&&o.current===r&&re(!1)}}let pe=W??m.error?.message??h.error?.message??b.error?.message??ce.error?.message;return(0,$.jsxs)(`div`,{className:`evaluation-form`,children:[(0,$.jsx)(`h2`,{children:`Evaluate Refiner`}),(0,$.jsx)(Wv,{items:_,busy:ne,error:g.error?.message,onRestore:y,onDiscard:e=>void v(e),onLoadMore:g.hasNextPage?()=>void g.fetchNextPage():void 0}),(0,$.jsx)(`p`,{children:`Review quality scores independent retained contexts. Downstream adaptation measures a sequential candidate trajectory against a separate private holdout. Both retain the original source and current owner boundaries.`}),pe?(0,$.jsx)(X,{error:pe}):null,(0,$.jsxs)(`fieldset`,{disabled:ne||!!l.current,children:[(0,$.jsxs)(`label`,{children:[`Profile`,(0,$.jsxs)(`select`,{value:x,onChange:e=>se(()=>{C(e.target.value),T(``),N(``)}),children:[(0,$.jsx)(`option`,{value:``,children:`Select actual source`}),m.data?.profiles.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),(0,$.jsxs)(`label`,{children:[`Component`,(0,$.jsxs)(`select`,{value:w,onChange:e=>se(()=>T(e.target.value)),children:[(0,$.jsx)(`option`,{value:``,children:`Select component`}),ae?.components.map(e=>(0,$.jsxs)(`option`,{value:e.label,children:[e.kind,` `,e.label]},e.label))]})]}),(0,$.jsxs)(`label`,{children:[`Target`,(0,$.jsxs)(`select`,{value:O,onChange:e=>se(()=>k(e.target.value===`review_quality`?`review_quality`:`downstream_adaptation`)),children:[(0,$.jsx)(`option`,{value:`downstream_adaptation`,children:`Downstream sequential adaptation`}),(0,$.jsx)(`option`,{value:`review_quality`,children:`Independent review quality`})]})]}),(0,$.jsxs)(`label`,{children:[`Adaptation split`,(0,$.jsx)(`select`,{value:E,onChange:e=>se(()=>D(e.target.value)),children:K?.adaptationSplits.map(e=>(0,$.jsxs)(`option`,{value:e.split,children:[e.split,` / `,e.taskIds.length,` cases`]},e.split))})]}),(0,$.jsxs)(`label`,{children:[`Refiner release`,(0,$.jsxs)(`select`,{value:A,onChange:e=>se(()=>j(e.target.value)),children:[(0,$.jsx)(`option`,{value:``,children:`Select exact release`}),m.data?.refinerReleases.map(e=>(0,$.jsxs)(`option`,{value:e.id,children:[e.id,` / `,e.contentHash.slice(0,12)]},e.contentHash))]})]}),(0,$.jsxs)(`label`,{children:[`Actual local evaluation configuration`,(0,$.jsxs)(`select`,{value:M,onChange:e=>se(()=>N(e.target.value)),children:[(0,$.jsx)(`option`,{value:``,children:`Select existing configuration`}),oe.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),ae&&!oe.length?(0,$.jsx)(`p`,{children:`Create an actual Model configuration for this Profile before evaluating. A hosted configuration is not a local execution owner.`}):null,(0,$.jsxs)(`label`,{children:[`Foreground and Refiner model`,(0,$.jsxs)(`select`,{value:P,onChange:e=>se(()=>F(e.target.value)),children:[(0,$.jsx)(`option`,{value:``,children:`Select admitted hosted model`}),h.data?.models.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),(0,$.jsxs)(`label`,{children:[`Whole run budget USD`,(0,$.jsx)(`input`,{type:`number`,min:`0.000001`,value:I,onChange:e=>se(()=>L(Number(e.target.value)))})]}),(0,$.jsxs)(`label`,{children:[`Maximum model requests`,(0,$.jsx)(`input`,{type:`number`,min:1,max:500,value:ee,onChange:e=>se(()=>R(Number(e.target.value)))})]}),(0,$.jsxs)(`label`,{children:[`Maximum minutes`,(0,$.jsx)(`input`,{type:`number`,min:1,max:1440,value:z,onChange:e=>se(()=>B(Number(e.target.value)))})]})]}),K&&!K.resettable?(0,$.jsx)(`p`,{children:`The selected environment cannot bound live external tool charges. Review a released resettable environment first.`}):null,O===`review_quality`&&K&&!K.reviewQuality?(0,$.jsx)(`p`,{children:`This Dataset needs separately grounded review labels and actual retained native context bindings.`}):null,V?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[`Frozen review `,V.contentHash,`. Source `,V.profileRef.profileId,` / `,V.baselineRelease.contentHash,`; evidence `,V.evidence.id,` / `,V.evidence.contentHash,`; Refiner `,V.refinerRelease.id,` / `,V.refinerRelease.contentHash,`. Adaptation`,` `,V.adaptationTaskIds.length,` / holdout `,V.holdoutTaskIds.length,`. All foreground, review and grade requests share`,` `,V.maximumCostUsd,` USD.`]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:ne,onClick:()=>void de(),children:`Start retained evaluation`}),(0,$.jsx)(`button`,{type:`button`,disabled:ne||d.current,onClick:()=>void ue(),children:`Edit setup`})]}):(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:ne||!ae||!K?.resettable||!q||!oe.some(e=>e.id===M)||!h.data?.models.some(e=>e.id===P)||O===`review_quality`&&!K?.reviewQuality,onClick:()=>void le(),children:`Review exact evaluation`}),U?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[`Actual Run `,U.id,` / `,U.status]}),U.failure?(0,$.jsx)(`p`,{children:U.failure}):null,U.receipt?.schemaVersion===`openpond.advancedRefinerReviewReceipt.v1`?(0,$.jsxs)(`p`,{children:[`Review score `,U.receipt.reviewScore??`unavailable`,` / no action `,U.receipt.noActionCases,` / routed`,` `,U.receipt.routedCases,` / proposals `,U.receipt.proposalCases,` `,`/ cleanup `,U.receipt.cleanupComplete?`complete`:`pending`,` / spend `,U.receipt.costUsd??`unresolved`]}):null,i?(0,$.jsx)(`button`,{type:`button`,onClick:()=>i(U.id),children:`Open actual Run`}):null,(0,$.jsx)(`button`,{type:`button`,disabled:ne,onClick:()=>void fe(`cancel`,U.id),children:`Cancel`}),(0,$.jsx)(`button`,{type:`button`,disabled:ne||![`failed`,`cancelled`].includes(U.status),onClick:()=>void fe(`resume`,U.id),children:`Resume retained run`})]}):null,(0,$.jsx)(`ol`,{children:b.data?.items.map(t=>(0,$.jsxs)(`li`,{children:[t.mode,` / `,t.status,t.failure?(0,$.jsx)(`p`,{children:t.failure}):null,(0,$.jsx)(`button`,{type:`button`,disabled:ne,onClick:()=>{let n=a;Hv(e,`advanced-refiner-evaluations`,{operation:`read`,id:t.id}).then(e=>{s.current&&o.current===n&&te(Oo.parse(e))}).catch(e=>{s.current&&o.current===n&&G(String(e))})},children:`Inspect actual Run`})]},t.id))})]})}function gx({api:e,target:t,onClose:n,onOpenRun:r}){let[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.useState)(!1),c=iy({name:`Refiner experiment`,dirty:i,busy:o,onLeave:n});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(Bv,{label:`New experiment / Refiner`,action:`advanced-refiner`,onRequestClose:()=>void c.requestLeave(n),children:[(0,$.jsx)(`p`,{children:`Target: improvement system. Review quality and downstream adaptation retain their own exact source, evidence, holdout and budget admission.`}),(0,$.jsx)(hx,{api:e,evidence:t.evidence,onDirty:a,onBusy:s,onOpenRun:r},ie([Vv(e),t]))]}),c.dialog]})}var _x=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:{},vx=$e.shape.lora.shape.targetModules.element.options,yx=[{section:`optimizer`,key:`learningRate`,label:`Learning rate`,min:Number.MIN_VALUE,max:.001,step:`any`},{section:`optimizer`,key:`epochs`,label:`Epochs`,min:Number.MIN_VALUE,max:10,step:`any`},{section:`optimizer`,key:`batchSize`,label:`Batch size`,min:1,max:32,step:1},{section:`optimizer`,key:`gradientAccumulationSteps`,label:`Gradient accumulation steps`,min:1,max:32,step:1},{section:`optimizer`,key:`seed`,label:`Seed`,min:-(2**31),max:2**31-1,step:1},{section:`dataset`,key:`maxSequenceLength`,label:`Maximum sequence tokens`,min:2,max:8192,step:1},{section:`lora`,key:`rank`,label:`LoRA rank`,min:1,max:64,step:1},{section:`lora`,key:`alpha`,label:`LoRA alpha`,min:Number.MIN_VALUE,max:1024,step:`any`},{section:`lora`,key:`dropout`,label:`LoRA dropout`,min:0,max:1,step:`any`}];function bx(e){let t=[$e.shape.optimizer.safeParse(e.optimizer),$e.shape.lora.safeParse(e.lora),$e.shape.dataset.omit({trainSplit:!0,validationSplit:!0}).safeParse(e.dataset)];for(let e of t)if(!e.success){let t=e.error.issues[0];return`${t?.path.join(`.`)||`SFT settings`}: ${t?.message??`Check this value.`}`}let n=_x(e.optimizer);if(Number(n.batchSize)*Number(n.gradientAccumulationSteps)>32)return`Managed SFT supports at most 32 accumulated examples.`;let r=_x(e.lora).targetModules;return Array.isArray(r)&&new Set(r).size!==r.length?`Choose each adapter target module once.`:null}function xx({recipe:e,onChange:t}){let n=_x(e.optimizer),r=_x(e.lora).targetModules,i=Array.isArray(r)?r.filter(e=>typeof e==`string`):[],a=typeof n.batchSize==`number`&&Number.isFinite(n.batchSize)&&typeof n.gradientAccumulationSteps==`number`&&Number.isFinite(n.gradientAccumulationSteps)?n.batchSize*n.gradientAccumulationSteps:null;function o(n,r,i){t({...e,[n]:{..._x(e[n]),[r]:i}})}let s=(t,n)=>{let r=_x(e[t])[n];return typeof r==`number`||typeof r==`string`?r:``};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Training steps`}),(0,$.jsx)(`input`,{type:`number`,min:1,max:128,step:1,value:s(`optimizer`,`maxSteps`),onChange:e=>o(`optimizer`,`maxSteps`,e.target.value===``?``:e.target.valueAsNumber)})]}),(0,$.jsxs)(`details`,{className:`model-training-settings`,children:[(0,$.jsx)(`summary`,{children:`Advanced SFT settings`}),(0,$.jsx)(`p`,{children:`SFT with LoRA. Available settings depend on the selected model and runtime.`}),(0,$.jsx)(`div`,{className:`taskset-draft-field-grid`,children:yx.map(e=>(0,$.jsxs)(`label`,{className:`labs-model-create-field`,children:[(0,$.jsx)(`span`,{children:e.label}),(0,$.jsx)(`input`,{type:`number`,min:e.min,max:e.max,step:e.step,value:s(e.section,e.key),onChange:t=>o(e.section,e.key,t.target.value===``?``:t.target.valueAsNumber)})]},`${e.section}.${e.key}`))}),(0,$.jsx)(`p`,{children:a===null?`Examples per optimizer update depend on batch size and gradient accumulation.`:`${a} example${a===1?``:`s`} per optimizer update`}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Adapter targets`}),i.map((e,t)=>(0,$.jsxs)(`div`,{className:`labs-model-create-select-row`,children:[(0,$.jsx)(Z,{floating:!0,label:`Adapter target ${t+1}`,value:e,options:[...vx.some(t=>t===e)?[]:[{value:e,label:`${e} (unavailable)`,disabled:!0}],...vx.map(t=>({value:t,label:t,disabled:t!==e&&i.includes(t)}))],onChange:e=>o(`lora`,`targetModules`,i.map((n,r)=>r===t?e:n))}),(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,"aria-label":`Remove adapter target ${e}`,disabled:i.length<=1,onClick:()=>o(`lora`,`targetModules`,i.filter((e,n)=>n!==t)),children:`Remove`})]},t)),i.length<vx.length?(0,$.jsx)(Z,{floating:!0,label:`Add adapter target`,value:``,options:[{value:``,label:`Add target module`,disabled:!0},...vx.filter(e=>!i.includes(e)).map(e=>({value:e,label:e}))],onChange:e=>o(`lora`,`targetModules`,[...i,e])}):null]})]})]})}var Sx=[{section:`optimizer`,key:`maxSteps`,label:`Training steps`,min:1,max:1e5,step:1},{section:`optimizer`,key:`learningRate`,label:`Learning rate`,min:Number.MIN_VALUE,step:`any`},{section:`rollout`,key:`maxOutputTokens`,label:`Maximum answer tokens`,min:1,max:8192,step:1}];function Cx(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function wx(e){if(e?.method===`sft`)return bx(e);if(e?.method!==`grpo`)return null;for(let t of Sx){let n=Cx(e[t.section])[t.key];if(typeof n!=`number`||!Number.isFinite(n)||n<t.min||`max`in t&&n>t.max||t.step===1&&!Number.isInteger(n))return`Enter a valid value for ${t.label.toLowerCase()}.`}return null}function Tx({recipe:e,onChange:t}){return e?.method===`sft`?(0,$.jsx)(xx,{recipe:e,onChange:t}):e?.method===`grpo`?(0,$.jsx)(Ex,{recipe:e,onChange:t}):null}function Ex({recipe:e,onChange:t}){let n=(0,Q.useRef)(e),[r,i]=(0,Q.useState)(!1),a=lo.safeParse(e),o=a.success?a.data:null,s=o&&gv(`small_experiment`,`grpo`,{maxSteps:o.optimizer.maxSteps,trainingExamples:o.dataset.maxExamples,rolloutGroupSize:o.rollout.groupSize,rolloutConcurrency:o.rollout.concurrency,optimizerIterations:o.optimizer.iterations,maximumRollouts:o.resourceLimits.maxRollouts})===null&&!r?`small_experiment`:`custom`;if(e?.method!==`grpo`)return null;function c(n,r,a){if(!e)return;let o=a===``?``:Number(a),s={...e,[n]:{...Cx(e[n]),[r]:o}};if(r===`maxSteps`&&typeof o==`number`){let t=Cx(e.rollout).groupSize;typeof t==`number`&&(s.resourceLimits={...Cx(e.resourceLimits),maxRollouts:o*t})}i(!0),t(s)}return(0,$.jsxs)($.Fragment,{children:[o?(0,$.jsx)(_v,{method:`grpo`,value:s,disabled:!o,sizing:o?{prompts:o.dataset.maxExamples,rollouts:o.rollout.groupSize,groups:o.optimizer.maxSteps,iterations:o.optimizer.iterations,concurrency:o.rollout.concurrency}:void 0,onSizingChange:e=>{o&&(i(!0),t({...o,dataset:{...o.dataset,maxExamples:e.prompts},rollout:{...o.rollout,groupSize:e.rollouts,concurrency:e.concurrency},optimizer:{...o.optimizer,maxSteps:e.groups,iterations:e.iterations},resourceLimits:{...o.resourceLimits,maxRollouts:e.rollouts*e.groups},policyOptimization:null}))},onChange:e=>{i(e===`custom`),e===`small_experiment`&&o?t(mv(o)):e===`standard`&&t(n.current)}}):(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Training steps`}),(0,$.jsx)(`input`,{type:`number`,min:1,max:1e5,value:typeof Cx(e.optimizer).maxSteps==`number`||typeof Cx(e.optimizer).maxSteps==`string`?String(Cx(e.optimizer).maxSteps):``,onChange:e=>c(`optimizer`,`maxSteps`,e.target.value)})]}),(0,$.jsxs)(`details`,{className:`model-training-settings`,children:[(0,$.jsx)(`summary`,{children:`Training settings`}),(0,$.jsx)(`p`,{children:`GRPO with LoRA. Review the cost and budget before starting a Run.`}),(0,$.jsx)(`div`,{className:`taskset-draft-field-grid`,children:Sx.map(t=>{let n=Cx(e[t.section])[t.key];return(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`span`,{children:t.label}),(0,$.jsx)(`input`,{type:`number`,min:t.min,max:`max`in t?t.max:void 0,step:t.step,value:typeof n==`number`||typeof n==`string`?n:``,onChange:e=>c(t.section,t.key,e.target.value)})]},t.key)})})]})]})}var Dx=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:{},Ox=[{id:`Qwen/Qwen3.5-4B`,revision:`851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a`,chatTemplateHash:`a4aee8afcf2e0711942cf848899be66016f8d14a889ff9ede07bca099c28f715`,rank:16,memoryBytes:24e9},{id:`Qwen/Qwen3.5-9B`,revision:`c202236235762e1c871ad0ccb60c8ee5ba337b9a`,chatTemplateHash:`a4aee8afcf2e0711942cf848899be66016f8d14a889ff9ede07bca099c28f715`,rank:16,memoryBytes:48e9},{id:`Qwen/Qwen3.8-27B`,revision:`1d4bf0f2ff6012fd82039f2fa52739d0dd7c60c0`,chatTemplateHash:`c3cf9e34abf4f9e36c2d72165aa9c132d3e2a725b6c2586aaa3a8af9d7a81041`,rank:8,memoryBytes:8e10}];function kx(e,t){let n=e?.method===`sft`?e:void 0,r=t?{id:t.modelId,revision:t.revision,tokenizerRevision:t.tokenizerRevision,chatTemplateHash:t.chatTemplateHash}:Dx(n?.baseModel),i=Ox.find(e=>e.id===r.id&&e.revision===r.revision&&e.revision===r.tokenizerRevision&&e.chatTemplateHash===r.chatTemplateHash),a=i?.rank??16;return{schemaVersion:`openpond.sftRecipe.v1`,method:`sft`,parameterization:`lora`,...n?.baseModel?{baseModel:n.baseModel}:{},dataset:{completionOnly:!0,maxSequenceLength:8192,selectionStrategy:`stable_hash_top_n`,selectionSeed:17,...Dx(n?.dataset)},lora:{rank:a,alpha:a*2,dropout:0,targetModules:i?[`down_proj`,`gate_proj`,`up_proj`]:[`q_proj`,`k_proj`,`v_proj`,`o_proj`,`gate_proj`,`up_proj`,`down_proj`],...Dx(n?.lora)},optimizer:{learningRate:1e-4,epochs:3,maxSteps:30,batchSize:1,gradientAccumulationSteps:1,seed:17,...Dx(n?.optimizer)},resourceLimits:{cpuThreads:4,memoryBytes:i?.memoryBytes??48*1024**3,wallTimeMs:36e5,...Dx(n?.resourceLimits)}}}function Ax(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function jx(e,t=e?.method===`sft`?`sft`:`grpo`,n){if(t===`sft`)return kx(e,n);let r=e?.method===`grpo`?e:void 0,i={schemaVersion:`openpond.rftRecipe.v1`,method:`grpo`,parameterization:`lora`,lora:{rank:2},rollout:{groupSize:8,concurrency:4,maxOutputTokens:1024,temperature:.8,topP:.95,seed:17},optimizer:{learningRate:1e-4,maxSteps:8,clipRange:.2,iterations:2,microbatchSize:1,gradientAccumulationSteps:8,advantageEpsilon:1e-8,adamw:{name:`adamw`,weightDecay:0,beta1:.9,beta2:.999,epsilon:1e-8}},loss:{method:`grpo`,klBeta:.01},resourceLimits:{wallTimeMs:396e4,maxRollouts:64,maxPayloadBytes:1e6},policyOptimization:null};return{...i,...r,lora:{...i.lora,...Ax(r?.lora)},rollout:{...i.rollout,...Ax(r?.rollout)},optimizer:{...i.optimizer,...Ax(r?.optimizer),adamw:{...i.optimizer.adamw,...Ax(Ax(r?.optimizer).adamw)}},loss:{...i.loss,...Ax(r?.loss)},resourceLimits:{...i.resourceLimits,...Ax(r?.resourceLimits)}}}function Mx(e){let{baseModel:t,reward:n,policyOptimization:r,...i}=jx(e),{trainSplit:a,validationSplit:o,maxExamples:s,...c}=Ax(i.dataset);return i.method===`sft`?{...i,dataset:{...c,...o?{validationSplit:o}:{}}}:{...i,dataset:c,policyOptimization:null}}var Nx=U().trim().min(1).max(500),Px=Pr,Fx=z({schemaVersion:L(`openpond.modelStarter.v1`),id:Nx,revision:V().int().positive(),name:U().trim().min(1).max(200),description:U().trim().min(1).max(2e3),category:H([`extraction`,`support`,`operations`,`knowledge`,`coding`,`writing`,`classification`]),taskset:Px,taskDefinition:Px,rewardBinding:Px,rewards:F(Px).min(1).max(100),assets:F(Px).max(1e3),previewTaskIds:F(Nx).min(1).max(8),startingModel:Ur,supportedMethods:F(Lr).min(1).max(8),defaultMethod:Lr,provenance:z({author:U().min(1).max(200),license:U().min(1).max(200),sourceDescription:U().min(1).max(2e3)}).strict(),evidence:z({verifierFixtures:Px.nullable(),baseline:Px.nullable(),training:Px.nullable(),evaluation:Px.nullable()}).strict()}).strict().superRefine((e,t)=>{e.supportedMethods.includes(e.defaultMethod)||t.addIssue({code:`custom`,path:[`defaultMethod`],message:`The default method must be supported by the package.`});for(let n of[`rewards`,`assets`])new Set(e[n].map(e=>e.id)).size!==e[n].length&&t.addIssue({code:`custom`,path:[n],message:`Dependency identities must be unique.`});new Set(e.previewTaskIds).size!==e.previewTaskIds.length&&t.addIssue({code:`custom`,path:[`previewTaskIds`],message:`Preview tasks must be unique.`})}).safeExtend({contentHash:U().regex(/^[a-f0-9]{64}$/)});z({starter:Fx,taskset:Le,taskDefinition:Ve,rewardBinding:Re,rewards:F(we).min(1).max(100),assets:F(ct).max(1e3),execution:Hr.optional()}).strict(),z({schemaVersion:L(`openpond.modelStarterPrivacyReview.v1`),disposition:L(`synthetic_only`),reviewedBy:U().trim().min(1).max(500),reviewedAt:N(),reviewedContentHash:U().regex(/^[a-f0-9]{64}$/),note:U().trim().min(1).max(2e3)}).strict(),z({profileId:Nx,modelId:Nx,name:U().trim().min(1).max(200),starter:Px,startingModel:Ur,method:Lr,rewardBindingRef:Px.nullable().optional(),recipe:Mr.nullable().optional(),managedGpuSelection:jr.shape.managedGpuSelection,continuationAdapterMode:jr.shape.continuationAdapterMode,learning:Vr.optional()}).strict().extend({schemaVersion:L(`openpond.modelStarterCreation.v1`),operationId:Nx}).strict();var Ix=`training:prepare-draft`,Lx=`training:control-preparation`;async function Rx(e,t,n,r){async function i(t){let n=[],i=new Set,a;for(let o=0;;o++){if(o>=100)throw Error(`The retained training catalog exceeds its supported bound.`);let s=await e.pendingOperations(t,a,r);if(n.push(...s.items),!s.nextCursor)return n;if(i.has(s.nextCursor))throw Error(`The retained training catalog repeated a page.`);i.add(s.nextCursor),a=s.nextCursor}}let[a,o]=await Promise.all([i(Ix),i(Lx)]),s=[];for(let r of a){let i=ll.parse(r.reviewedIntent);if(i.draftId!==t||i.request.settings.method!==n)continue;let a=Rn.parse({...i.request,operationId:r.id});if(i.request.teamId!==e.teamId||i.request.projectId!==e.projectId||r.intentHash!==ie(i)||r.command&&J(r.command)!==J(a))throw Error(`The retained training preparation changed its exact inputs or workspace.`);let o=e.recoverOperation(r);s.push({intent:i,request:a,operation:o,snapshot:J(i.form),acknowledge:o.acknowledge})}if(s.length>1)throw Error(`Resolve the original retained training review before preparing another run.`);let c=s[0]??null,l=[];for(let r of o){let i=dl.parse(r.reviewedIntent);if(i.draftId!==t||i.method!==n)continue;if(!c||i.preparationOperationId!==c.request.operationId)throw Error(`The retained training control is missing its original preparation. Recover that original review before starting another run.`);let a=ul.parse(r.command??i.command);if(r.intentHash!==ie(i)||J(a)!==J(i.command)||i.receipt.plan.creatorUserId!==e.actorId||i.receipt.plan.request.teamId!==e.teamId||i.receipt.plan.request.projectId!==e.projectId)throw Error(`The retained training control changed its creator, plan or estimate approval.`);l.push({intent:i,command:a,operation:e.recoverOperation(r),phase:r.phase})}if(l.length>1)throw Error(`Recover the original training control before submitting another action.`);return{review:c,control:l[0]??null}}function zx(e,t,n,r){return S({queryKey:[`training-experiment-recovery`,e.key,ra(e.connection),t,n],enabled:r&&!!(t&&e.actorId),queryFn:({signal:r})=>Rx(e,t,n,r),staleTime:0,gcTime:0,retry:!1})}async function Bx(e){let t=e.retained;if(t.snapshot===e.snapshot)return{kind:`unchanged`};let n=await Sn(await e.request(`prepare-draft`,t.request));if(J(n.request)!==J(t.request))throw Error(`The recovered preparation does not match its retained inputs.`);let r=n.preparation;if(r.state===`prepared`){let n=await vr(await e.request(`cancel`,{id:r.plan.id,control:{teamId:t.request.teamId,planHash:r.plan.contentHash,expectedRevision:r.revision}}));if(n.plan.contentHash!==r.plan.contentHash||n.plan.id!==r.plan.id||n.revision<=r.revision||n.state!==`cancelled`)throw Error(`The earlier preparation has not confirmed cancellation. Retry its retained request.`);r=n}return await t.acknowledge(),r.state===`submitted`&&r.jobId?{kind:`submitted`,jobId:r.jobId}:{kind:`cancelled`}}function Vx(e,t,n,r,i,a){let o=kv(),s=Ga(),c=o.initialExperiment?.operationType===t?o.initialExperiment:null,l=c?.training?.settings?.recipe?.dataset,u=l&&typeof l==`object`&&`validationSplit`in l&&l.validationSplit===`frozen_eval`?`frozen_eval`:`validation`,[d,f]=(0,Q.useState)(()=>c?.trainingForm?.recipe??c?.training?.settings?.recipe??jx(null,t,o.trainingBaseModel)),[p,m]=(0,Q.useState)(c?.trainingForm?c.trainingForm.batch:c?.training?.batch??null),h=Ry(e,n,p),[g,_]=(0,Q.useState)(c?.trainingForm?c.trainingForm.evaluation:c?.training?.settings?.evaluationTasksetRef??o.draft?.release??null),[v,y]=(0,Q.useState)(c?.trainingForm?.validationSplit??u),[b,x]=(0,Q.useState)(c?.trainingForm?.name??c?.name??(t===`sft`?`Supervised training`:`RL training`)),[S,C]=(0,Q.useState)(c?.trainingForm?.startingModelLabel),[w,T]=(0,Q.useState)(c?.trainingForm?.budget??String(c?.training?.maximumSpendUsd??1)),[E,D]=(0,Q.useState)(c?.trainingForm?.customerCapUsd??c?.training?.usageFunding?.customerCapUsd??``),[O,k]=(0,Q.useState)(c?.trainingForm?.billingMode??(c?.training?c.training.usageFunding?`actual_usage`:`prepaid_only`:null)),A=O??(h.billingModes?.[1].availability===`requires_preparation`?`actual_usage`:`prepaid_only`),[j,M]=(0,Q.useState)(c?.trainingForm?.gpuSelection??c?.training?.settings?.managedGpuSelection??{mode:`automatic`,objective:`balanced`,gpuCount:1}),[N,P]=(0,Q.useState)(null),[F,I]=(0,Q.useState)(null),[L,ee]=(0,Q.useState)(!1),[R,z]=(0,Q.useState)(null),B=(0,Q.useRef)(!1),V=(0,Q.useRef)(null),H=(0,Q.useRef)(null),U=zx(e,o.initialExperiment?.id,t,n),[te,ne]=(0,Q.useState)(!1),re=Cb({api:e,method:t,enabled:n,baseModel:o.trainingBaseModel,recipe:d,selection:j,receipt:F}),W=Tb(e,F?.plan.usageQuote?F.plan.usageQuote.customerCapUsd??``:F?String(F.plan.request.maximumSpendUsd):A===`actual_usage`?E:w,n,F?!!F.plan.usageQuote:A===`actual_usage`),ie=(0,Q.useRef)(null),[G,ae]=(0,Q.useState)(!1),K=JSON.stringify([e.key,e.connection.serverUrl,e.actorId,o.initialExperiment?.id,ra(e.connection)]),q=(0,Q.useRef)(K);q.current=K,(0,Q.useEffect)(()=>(q.current=K,()=>{q.current=`unmounted`}),[K]);let oe={startingModel:o.startingModel,baseModel:o.trainingBaseModel,...o.trainingParent?{parent:o.trainingParent,startingModelLabel:S}:{},recipe:d,batch:p,evaluation:g,validationSplit:v,name:b,budget:w,customerCapUsd:E,billingMode:A,gpuSelection:j},se=J(oe),ce=(0,Q.useRef)(se),le=se!==ce.current||F!==null,ue=o.reportOperationDraftDirty;(0,Q.useEffect)(()=>{ue(t,le)},[t,le,ue]);let de=iy({name:`training experiment`,dirty:le||o.operationDraftDirty||o.evaluationDirty,busy:L,onLeave:r,retainForDestination(t){let n=po(new URL(t,window.location.origin));return!(!n||![`datasets`,`graders`,`experiments`].includes(n.page)||n.collection===`drafts`&&n.resourceId!==o.initialExperiment?.id||(n.projectId??null)!==e.projectId)}}),fe=h.batches.find(e=>p!==null&&e.reference.id===p.id&&e.reference.revision===p.revision&&e.reference.contentHash===p.contentHash),pe=L||F!==null;function me(){if(!o.initialExperiment)throw Error(`Open an experiment before saving.`);let e=Zn.parse({baseModel:o.trainingBaseModel,recipe:d,batch:p,evaluation:g,validationSplit:v,name:b,budget:w,customerCapUsd:E,billingMode:A,gpuSelection:j,...o.trainingParent?{parent:o.trainingParent,startingModelLabel:S}:{}});return Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:o.initialExperiment.id,operationType:t,name:b.trim()||(t===`sft`?`Supervised training`:`RL training`),trainingForm:e,...o.startingModel?{startingModel:o.startingModel}:{}})}function he(){if(q.current!==K)throw Error(`The active account changed. Reopen this experiment.`)}async function ge(){if(!a)throw Error(`Save this experiment before opening Billing.`);let t=me();await a(t),he();let n=await Iy(e).get(t.id);if(he(),n.status!==`draft`||J(n.draft)!==J(t))throw Error(`The saved experiment changed. Your edits remain here; reopen the current draft before continuing.`);return ce.current=se,n}async function _e(){if(!a||!o.initialExperiment||B.current||F)return!1;B.current=!0,ee(!0),z(null);try{return await ge(),!0}catch(e){return q.current===K&&z(e),!1}finally{B.current=!1,q.current===K&&ee(!1)}}async function ve(){if(B.current||te||F&&F.state!==`prepared`)return;B.current=!0,ee(!0),z(null);let t=null;try{let n=window.openpond?.browser;if(!n?.openExternal){if(t=window.open(`about:blank`,`_blank`),!t)throw Error(`Allow a new tab to open Billing, then try again.`);t.opener=null}let r=await ge(),i=W.allocationAdmission?vt(E):null,a=await xb(e,{schemaVersion:`openpond.trainingFundingHandoffRequest.v1`,teamId:e.teamId,maximumSpendUsd:W.allocationAdmission?i===null?null:Number(i):Number(w),draft:{id:r.id,revision:r.revision,contentHash:r.contentHash,projectId:r.projectId}});if(he(),!a.canPurchase||!a.billingUrl)throw Error(`A workspace billing owner needs to add credits for this experiment.`);if(ie.current=r,ae(!0),re.requireFreshReview(),n?.openExternal){let e=await n.openExternal({conversationId:`experiment-funding:${r.id}`,url:a.billingUrl});if(he(),!e.ok)throw Error(e.error??`Billing could not be opened. Your experiment is saved; try again.`)}else t&&=(t.location.replace(a.billingUrl),null)}catch(e){t?.close(),q.current===K&&z(e)}finally{B.current=!1,q.current===K&&ee(!1)}}async function ye(){if(!(B.current||te)){B.current=!0,ee(!0),z(null);try{if(ie.current){let t=ie.current,n=await Iy(e).get(t.id);if(he(),n.status!==`draft`||n.contentHash!==t.contentHash||n.revision!==t.revision)throw Error(`This experiment changed while Billing was open. Your edits remain here; reopen the saved draft before running.`)}let t=W.allocationAdmission?null:await W.query.refetch();if(he(),t?.error)throw t.error;if(F?.state===`prepared`){let e=await re.estimate.refetch();if(he(),e.error)throw e.error}(W.allocationAdmission||t?.data?.state===`covered`)&&(ie.current=null,ae(!1))}catch(e){q.current===K&&z(e)}finally{B.current=!1,q.current===K&&ee(!1)}}}let be=(0,Q.useRef)(ye);be.current=ye,(0,Q.useEffect)(()=>{if(!n)return;let e=()=>{ie.current&&document.visibilityState===`visible`&&be.current()};return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[K,n]);async function xe(n,r){if(B.current)return;B.current=!0,ee(!0),z(null);let a=()=>{if(q.current!==K)throw Error(`The active account changed. Reopen this experiment.`)};async function c(t,n){a();let r=await Y(e.connection,`/v1/training/setup/${t}?teamId=${encodeURIComponent(e.teamId)}`,{method:`POST`,body:JSON.stringify(n)});return a(),r}let l=!1;try{if(a(),!U.isSuccess)throw Error(`Load retained training reviews before continuing.`);let u=await U.refetch();if(a(),u.error||!u.data)throw u.error??Error(`Load retained training reviews before continuing.`);let p=u.data;if(V.current?.request.operationId===p.review?.request.operationId&&(H.current??=p.control),n===`recover`){let t=V.current??p.review;if(!t)throw Error(`No previous training review is retained for this experiment.`);V.current=t,H.current??=p.control,await t.operation.retainCommand(t.request,`dispatching`),a();let n=await Sn(await c(`prepare-draft`,t.request));if(J(n.request)!==J(t.request)||n.preparation.plan.creatorUserId!==e.actorId)throw Error(`The recovered training review differs from its retained request or creator.`);let r=n.preparation,i=H.current;if(i&&(r.plan.id!==i.command.id||r.plan.contentHash!==i.command.control.planHash||r.state===`prepared`&&r.revision!==i.command.control.expectedRevision))throw Error(`The original training control does not own this current preparation.`);let s=t.intent.form;o.setTrainingBaseModel(s.baseModel),o.setTrainingParent(s.parent??null),C(s.startingModelLabel),f(s.recipe),m(s.batch),_(s.evaluation),y(s.validationSplit),x(s.name),T(s.budget),D(s.customerCapUsd??r.plan.request.usageFunding?.customerCapUsd??``),k(r.plan.request.usageFunding?`actual_usage`:`prepaid_only`),M(s.gpuSelection??{mode:`automatic`,objective:`balanced`,gpuCount:1}),I(r),ne(i?.command.action===`start`),r.state!==`prepared`&&(await i?.operation.acknowledge(),await t.acknowledge(),a(),H.current=null,V.current=null,ne(!1),r.state===`submitted`?P(r.jobId):I(null),await U.refetch());return}if(!V.current&&p.review)throw Error(`Restore the previous training review before preparing or starting another request.`);if(H.current&&H.current.command.action!==n)throw Error(`Recover the original training control before changing its action.`);if(n===`prepare`){if(N&&!r?.newRun)throw Error(`The earlier preparation already started. Your edited settings remain here. Open the existing run or review these edits for a new run.`);if(r?.newRun&&P(null),V.current&&V.current.snapshot!==se){let e=await Bx({retained:V.current,snapshot:se,request:c});if(a(),e.kind!==`unchanged`&&(V.current=null),e.kind===`submitted`)throw P(e.jobId),Error(`The earlier preparation already started. Your edited settings remain here. Open the existing run or review these edits for a new run.`)}if(V.current?.snapshot!==se){if(!e.actorId||!h.isSuccess)throw Error(`Load the current training inputs before reviewing this experiment.`);if(o.startingModel?.source===`steering`||o.startingModel?.source===`engram`)throw Error(`Training cannot consume this saved steering source. Choose another starting model instead of substituting its base.`);if(o.startingModel?.source===`trained`){await Xt(me(),{teamId:e.teamId});let n=o.startingModel.trainedVersion,r=o.trainingParent;if(t!==`grpo`||!r||r.jobId!==n.jobId||r.checkpointId!==n.candidate.checkpointId||J(r.artifact)!==J(n.candidate.artifact))throw Error(`This trained source requires its exact qualified GRPO parent. Choose another starting model for this method.`)}if(o.trainingParent&&t!==`grpo`)throw Error(`Checkpoint continuation currently requires GRPO.`);if(!h.methods.includes(t))throw Error(`This account has no available execution for the selected training method.`);let n=o.trainingBaseModel;if(!n||!h.models.some(e=>e.available&&J(e.preference)===J(n)))throw Error(`Choose an available pinned starting model.`);if(!fe||fe.purpose!==(t===`sft`?`supervised_training`:`reward_training`))throw Error(`Choose a reviewed batch matching this training method.`);if(!g)throw Error(`Choose the exact validation Dataset version.`);if(!b.trim())throw Error(`Enter a name for this experiment.`);let r=Number(w);if(!Number.isFinite(r)||r<=0||r>1e6)throw Error(`Enter a positive planning budget up to $1,000,000.`);if(A===`actual_usage`&&h.billingModes?.[1].availability!==`requires_preparation`)throw Error(`Actual-usage training is not qualified for this runtime. Select the available billing mode before preparing a new run.`);let i=A===`actual_usage`?{schemaVersion:`openpond.trainingUsageFundingRequest.v1`,billingMode:`actual_usage`,customerCapUsd:vt(E)}:void 0,s=(d.dataset&&typeof d.dataset==`object`?d.dataset:{}).maxExamples;if(typeof s!=`number`||!Number.isInteger(s)||s<1||s>fe.exampleCount||t===`sft`&&s>1e3)throw Error(`Choose a valid training example count within the reviewed batch and runtime limits.`);let c=wx(d);if(c)throw Error(c);if(!re.catalog.data||re.catalogExpired||re.catalog.isFetching||re.catalog.isError)throw Error(`Refresh compute availability before reviewing this experiment.`);if(!re.catalog.data.offerings.length||re.catalog.data.scope?.qualification!==`requires_preparation`)throw Error(`No qualified compute is currently available for this model and training setup.`);if(j.mode===`manual`&&!re.catalog.data.offerings.some(e=>e.availabilityId===j.availabilityId&&e.gpuType===j.gpuType))throw Error(`The selected GPU offering is unavailable. Refresh availability or choose another offering.`);let l={teamId:e.teamId,projectId:e.projectId,baseModel:n,...o.trainingParent?{parent:o.trainingParent}:{},batch:fe.reference,name:b.trim(),maximumSpendUsd:r,...i?{usageFunding:i}:{},gpuSelection:j,settings:{method:t,recipe:{...d,dataset:{...d.dataset&&typeof d.dataset==`object`?d.dataset:{},validationSplit:v}},evaluationTasksetRef:g,rewardBindingRef:fe.rewardBinding,managedRolloutPlacement:`remote`}},u=ll.parse({draftId:o.initialExperiment?.id,form:Zn.parse(oe),request:{...l,schemaVersion:`openpond.trainingExperimentSetupRequest.v1`}}),f=await e.operation(Ix,u);a();let p=Rn.parse({...u.request,operationId:f.id});V.current={snapshot:se,intent:u,request:p,operation:f,acknowledge:f.acknowledge}}let n=V.current;await n.operation.retainCommand(n.request,`dispatching`),a();let i=n.request,s=await Sn(await c(`prepare-draft`,i));if(J(s.request)!==J(i)||s.preparation.plan.creatorUserId!==e.actorId)throw Error(`The service prepared a different experiment draft.`);I(s.preparation),H.current=null,ne(!1)}else{if(!F)throw Error(`Review this experiment before starting it.`);if(F.state===`submitted`&&F.jobId){de.allowNextNavigation(),await i(F.jobId);return}if(!V.current)throw Error(`Recover the original preparation before submitting a control.`);if(!H.current){let r;if(n===`start`){if(G)throw Error(`Return from Billing and refresh credits before starting.`);W.assertCovered(),r=re.reviewedEstimate()}let i=dl.parse({draftId:o.initialExperiment?.id,method:t,preparationOperationId:V.current.request.operationId,receipt:F,command:{action:n,id:F.plan.id,control:{teamId:e.teamId,planHash:F.plan.contentHash,expectedRevision:F.revision,...F.plan.usageQuote?{usageQuoteHash:F.plan.usageQuote.contentHash}:{},...r?{estimateReview:r}:{}}}}),s=await e.operation(Lx,i);a(),H.current={intent:i,command:i.command,operation:s,phase:`reviewed`}}let r=H.current;n===`start`&&ne(!0),await r.operation.retainCommand(r.command,`dispatching`),a(),r.phase=`dispatching`;let{action:u,...d}=r.command;l=!0;let f=await vr(await c(u,d));if(f.plan.contentHash!==F.plan.contentHash||f.plan.request.teamId!==e.teamId)throw Error(`Training control returned a different preparation.`);if(I(f),ne(!1),n===`start`&&f.state===`submitted`&&f.jobId){let e=f.jobId;try{await r.operation.acknowledge(),await V.current?.acknowledge()}catch(t){Wa(t instanceof Error?t.message:String(t))||s?.(`Training started. Desktop recovery acknowledgement is still pending.`,`error`,{dedupeKey:`training-ack:${e}`})}a(),de.allowNextNavigation(),await i(e)}else if(n===`cancel`&&f.state===`cancelled`)await r.operation.acknowledge(),await V.current?.acknowledge(),a(),H.current=null,V.current=null,await U.refetch(),I(null);else throw Error(`The preparation did not reach the requested state. Retry the same control.`)}}catch(e){if(q.current===K&&l&&e instanceof Ti&&[400,403,404,409,422].includes(e.status)&&H.current&&V.current)try{let e=V.current,t=await Sn(await c(`prepare-draft`,e.request));if(J(t.request)!==J(e.request))throw Error(`The rejected training control did not reconcile its original preparation.`);let n=t.preparation;if(n.plan.contentHash!==F?.plan.contentHash||n.state===`prepared`&&n.revision!==H.current.command.control.expectedRevision)throw Error(`Refresh the original training review before changing its control.`);await H.current.operation.acknowledge(),a(),H.current=null,ne(!1),I(n),n.state!==`prepared`&&(await e.acknowledge(),a(),V.current=null,n.state===`submitted`?P(n.jobId):I(null),await U.refetch())}catch{}q.current===K&&z(e)}finally{B.current=!1,q.current===K&&ee(!1)}}return{inputs:h,recipe:d,setRecipe:f,batch:p,setBatch:m,selectedBatch:fe,evaluation:g,setEvaluation:_,validationSplit:v,setValidationSplit:y,name:b,setName:x,startingModelLabel:S,budget:w,setBudget:T,customerCapUsd:E,setCustomerCapUsd:D,billingMode:F?F.plan.usageQuote?`actual_usage`:`prepaid_only`:A,setBillingMode:k,gpuSelection:j,setGpuSelection:M,compute:re,funding:W,billingReturnPending:G,openBilling:a?ve:null,refreshCredits:ye,startAttempted:te,pendingAction:H.current?.command.action??null,recovery:U,requiresRecovery:!(V.current||!U.data?.review),canRecover:!!(!V.current&&U.data?.review||V.current&&F&&F.state!==`prepared`),receipt:F,recoveredJobId:N,openRecoveredJob:async()=>{N&&!B.current&&await de.requestLeave(()=>{de.allowNextNavigation(),Promise.resolve(i(N)).catch(e=>{q.current===K&&z(e)})})},busy:L,locked:pe,error:R??U.error,guard:de,assertCurrentScope:he,perform:xe,saveDraft:a?_e:null}}var Hx=e=>new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,maximumFractionDigits:4}).format(e),Ux=e=>e<60?`${Math.ceil(e)} sec`:`${Math.ceil(e/60)} min`;function Wx({compute:e,selection:t,onChange:n,locked:r,method:i,budget:a,onBudgetChange:o,actualUsage:s,actualUsageAvailable:c,onBillingModeChange:l,customerCapUsd:u,onCustomerCapChange:d,prepared:f,startAttempted:p,busy:m,children:h}){let g=e.catalog.data?.offerings??[],_=t.mode===`automatic`?`auto:${t.objective}`:`offer:${t.availabilityId}`,v=t.mode===`manual`?g.find(e=>e.availabilityId===t.availabilityId):null,y=e.estimate.data;return(0,$.jsxs)(ft,{title:`Compute and spending`,children:[(0,$.jsxs)(`fieldset`,{disabled:r,children:[(0,$.jsxs)(`label`,{children:[`GPUs`,(0,$.jsx)(Z,{label:`GPU count`,floating:!0,value:String(t.gpuCount??1),options:[{value:`1`,label:`1 GPU`},{value:`2`,label:`2 GPUs`,disabled:i!==`grpo`}],onChange:e=>n(t.mode===`automatic`?{...t,gpuCount:e===`2`?2:1}:{mode:`automatic`,objective:`balanced`,gpuCount:e===`2`?2:1})})]}),(0,$.jsxs)(`label`,{children:[`GPU`,(0,$.jsx)(Z,{label:`GPU offering`,floating:!0,searchable:!0,value:_,options:[{value:`auto:balanced`,label:`Automatic · Balanced`},{value:`auto:economical`,label:`Automatic · Lowest hourly cost`},{value:`auto:fast`,label:`Automatic · Performance`},...t.mode===`manual`&&!v?[{value:_,label:`${t.gpuType} · Selected offering`,disabled:!0}]:[],...g.map(t=>({value:`offer:${t.availabilityId}`,label:`${t.gpuType} · ${s?``:`${Hx(t.totalHourlyUsd)}/hr · `}${t.dataCenterId??t.region}`,disabled:e.catalogExpired||e.catalog.isError}))],onChange:e=>{let r=g.find(t=>`offer:${t.availabilityId}`===e);r?n({mode:`manual`,availabilityId:r.availabilityId,gpuType:r.gpuType,gpuCount:r.gpuCount===2?2:1}):[`auto:balanced`,`auto:economical`,`auto:fast`].includes(e)&&n({mode:`automatic`,objective:e===`auto:fast`?`fast`:e===`auto:economical`?`economical`:`balanced`,gpuCount:t.gpuCount??1})}})]}),(0,$.jsxs)(`label`,{children:[`Billing`,(0,$.jsx)(Z,{label:`Training billing`,floating:!0,value:s?`actual_usage`:`prepaid_only`,options:[{value:`prepaid_only`,label:`Reserved budget`},{value:`actual_usage`,label:c?`Actual usage`:`Actual usage · runtime qualification required`,disabled:!c}],onChange:e=>{(e===`prepaid_only`||e===`actual_usage`)&&l(e)}})]}),s?(0,$.jsxs)(`label`,{children:[`Spending limit ($, optional)`,(0,$.jsx)(`input`,{type:`number`,min:`0.000001`,max:`1000000`,step:`any`,value:u,placeholder:`Use available credits`,onChange:e=>d(e.target.value)})]}):null,(0,$.jsxs)(`label`,{children:[s?`Planning budget ($)`:`Maximum spend ($)`,(0,$.jsx)(`input`,{type:`number`,min:`0.000001`,max:`1000000`,step:`any`,value:a,onChange:e=>o(e.target.value)})]}),s?(0,$.jsx)(`p`,{children:`The planning budget configures the training plan. The optional spending limit above caps actual usage across all components.`}):null]}),f?(0,$.jsxs)($.Fragment,{children:[e.estimate.isFetching?(0,$.jsx)(`p`,{role:`status`,children:`Estimating this experiment…`}):null,y?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`dl`,{className:`training-compute-summary`,children:[(0,$.jsx)(`dt`,{children:`Resolved GPU`}),(0,$.jsx)(`dd`,{children:y.gpu.resolved?`${y.gpu.resolved.gpuCount} × ${y.gpu.resolved.gpuType}`:`Unavailable`}),(0,$.jsx)(`dt`,{children:`Compute and disk`}),(0,$.jsx)(`dd`,{children:y.gpu.customerHourlyUsd===null?`Unknown`:`${Hx(y.gpu.customerHourlyUsd)}/hr`}),(0,$.jsx)(`dt`,{children:`Execution time`}),(0,$.jsxs)(`dd`,{children:[y.executionSeconds.expected===null?`Unknown`:Ux(y.executionSeconds.expected),y.executionSeconds.planningRange?` (${Ux(y.executionSeconds.planningRange.low)}–${Ux(y.executionSeconds.planningRange.high)} observed)`:``]}),(0,$.jsx)(`dt`,{children:`Expected total`}),(0,$.jsx)(`dd`,{children:y.cost.expectedUsd===null?`Unknown`:Hx(y.cost.expectedUsd)}),(0,$.jsx)(`dt`,{children:`Cleanup reserve`}),(0,$.jsx)(`dd`,{children:y.cost.minimumCleanupReserveUsd===null?`Unknown`:Hx(y.cost.minimumCleanupReserveUsd)})]}),(0,$.jsxs)(`p`,{children:[s?`Review the component rates and whole-job spending limit before starting.`:`The spending cap is ${Hx(Number(a))}.`,` Hourly pricing is not an estimate of the total.`]}),e.estimateExpired?(0,$.jsx)(`p`,{children:`Estimate expired. Refresh before starting.`}):null,(0,$.jsxs)(`details`,{className:`training-evidence`,children:[(0,$.jsx)(`summary`,{children:`Estimate details`}),(0,$.jsxs)(`p`,{children:[y.calibration.completedSamples,` matching completed run`,y.calibration.completedSamples===1?``:`s`,`. Queue wait is separate.`]}),(0,$.jsx)(`p`,{children:`Cost breakdown`}),(0,$.jsx)(`dl`,{className:`training-compute-summary`,children:y.cost.components.map(e=>(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(`dt`,{children:[e.phase.replaceAll(`_`,` `),` · `,e.resource===`gpu`||e.resource===`cpu`?e.resource.toUpperCase():e.resource]}),(0,$.jsxs)(`dd`,{children:[e.expectedUsd===null?`Not yet estimated`:Hx(e.expectedUsd),e.planningRangeUsd?` (${Hx(e.planningRangeUsd.low)}–${Hx(e.planningRangeUsd.high)} planning range)`:``,e.expectedSeconds===null?null:(0,$.jsxs)(`p`,{children:[Ux(e.expectedSeconds),` allocated resource time`]}),e.reason?(0,$.jsx)(`p`,{children:e.reason}):null]})]},`${e.phase}:${e.resource}`))}),y.unknowns.length?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:`Not yet estimated`}),(0,$.jsx)(`ul`,{children:y.unknowns.map((e,t)=>(0,$.jsx)(`li`,{children:e},t))})]}):null,y.assumptions.length?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:`Assumptions`}),(0,$.jsx)(`ul`,{children:y.assumptions.map((e,t)=>(0,$.jsx)(`li`,{children:e},t))})]}):null]})]}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:m||e.estimate.isFetching||p,onClick:()=>void e.estimate.refetch(),children:`Refresh estimate`})]}):(0,$.jsxs)($.Fragment,{children:[e.catalog.isFetching?(0,$.jsx)(`p`,{role:`status`,children:`Checking GPU availability…`}):null,e.catalog.data&&!e.catalog.isError?(0,$.jsx)(`p`,{children:e.catalogExpired?`Availability needs refreshing.`:`${g.length} current offering${g.length===1?``:`s`}.`}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:r||!e.query||e.catalog.isFetching,onClick:()=>void e.catalog.refetch(),children:`Refresh availability`})]}),h,(0,$.jsx)(X,{error:f?e.estimate.error:e.catalog.error})]})}function Gx({judges:e}){return e.prices.length===0?null:(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Judge model rates`}),(0,$.jsx)(`p`,{children:`USD per million tokens, within the same spending limit.`}),e.prices.map(e=>(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`p`,{children:[e.displayName,` (`,e.modelId,`)`]}),(0,$.jsxs)(`ul`,{children:[(0,$.jsxs)(`li`,{children:[`Input: $`,e.inputUsdPerMillionTokens,`; cached input: $`,e.cachedInputUsdPerMillionTokens,`; output: $`,e.outputUsdPerMillionTokens,`.`]}),e.cacheWriteUsdPerMillionTokens===null?null:(0,$.jsxs)(`li`,{children:[`Cache writes: $`,e.cacheWriteUsdPerMillionTokens,`.`]}),e.cacheWriteOneHourUsdPerMillionTokens===null?null:(0,$.jsxs)(`li`,{children:[`One-hour cache writes: $`,e.cacheWriteOneHourUsdPerMillionTokens,`.`]}),e.longContext===null?null:(0,$.jsxs)(`li`,{children:[`Long context`,e.longContextThresholdTokens===null?``:` above ${e.longContextThresholdTokens.toLocaleString()} tokens`,`:`,` `,`input $`,e.longContext.inputUsdPerMillionTokens,`; cached input $`,e.longContext.cachedInputUsdPerMillionTokens,`; output $`,e.longContext.outputUsdPerMillionTokens,`.`,e.longContext.cacheWriteUsdPerMillionTokens===null?``:` Cache writes: $${e.longContext.cacheWriteUsdPerMillionTokens}.`]})]})]},e.acceptedPricingHash))]})}function Kx({quote:e}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:e.customerCapUsd===null?`Use available credits`:`$${e.customerCapUsd} total spending limit`}),(0,$.jsxs)(`ul`,{children:[(0,$.jsxs)(`li`,{children:[`Training compute: $`,e.gpu.hourlyUsd,`/hour, including startup.`]}),e.guests.map(e=>(0,$.jsxs)(`li`,{children:[`Training environment (`,e.resources.cpu,` CPU, `,e.resources.memoryGb,` GiB memory):`,` `,`$`,e.price.hourlyUsd,`/hour while active.`]},e.profileHash)),(0,$.jsxs)(`li`,{children:[`Retained objects: $`,e.storage.price.hourlyUsd,`/GiB-hour during training and through `,e.retentionDays,` days after its accepted execution deadline.`]}),e.judges.prices.length>0?(0,$.jsx)(`li`,{children:`Judge calls use the model rates below.`}):null]}),(0,$.jsx)(Gx,{judges:e.judges}),(0,$.jsx)(`p`,{children:`Stopped training compute has no warm-idle charge. Retained storage is billed separately within the same spending limit; running out of credit does not delete saved objects.`})]})}var qx=(0,Q.lazy)(()=>o(()=>import(`./ExperimentTrainingDataWorkspace-CfOyoMrq.js`),__vite__mapDeps([76,1,2,3,4,77,5,6,9,10,78,32,27,31,21,16,43,19,20,22,13,23,15,24,25,26,8,28,11,29,30,33,34,35,36,37,38,39,40,41,18,42,44,45,46,47,48,49,50,51,52,53,54,55,56,79,80])));function Jx({api:e,method:t,visible:n,navigate:r,onClose:i,onSaveDraft:a,onStarted:o}){let s=kv(),[c,l]=(0,Q.useState)(!1),u=(0,Q.useRef)(null),d=(0,Q.useRef)(null),f=Vx(e,t,n,i,async t=>{o?await o(t):(s.close(),r(as(`runs`,null,{projectId:e.projectId,resourceId:`hosted-run:${t}`,detailTab:`details`})))},a),{inputs:p,locked:m,receipt:h}=f;My({...f.guard,async requestLeave(e){c&&u.current?await u.current.requestLeave(()=>f.guard.requestLeave(e)):await f.guard.requestLeave(e)}},n);let g=p.models.find(e=>J(e.preference)===J(s.trainingBaseModel)),_=f.recipe.dataset&&typeof f.recipe.dataset==`object`?f.recipe.dataset:{},v=_.maxExamples,y=p.batches.filter(e=>e.purpose===(t===`sft`?`supervised_training`:`reward_training`)),b=()=>{l(!1),requestAnimationFrame(()=>d.current?.focus())};function x(e){f.setBatch(e.reference),f.setRecipe({...f.recipe,dataset:{..._,maxExamples:Math.min(typeof v==`number`&&v>0?v:1e3,e.exampleCount,t===`sft`?1e3:1e5)}})}async function S(e){if(f.assertCurrentScope(),f.busy||h||!n)throw Error(`Return to the editable experiment before selecting training data.`);if(Fe(e),e.purpose!==(t===`sft`?`supervised_training`:`reward_training`))throw Error(`Choose a reviewed batch matching this experiment's training method.`);x({reference:xe(e),rewardBinding:e.rewardBinding,purpose:e.purpose,exampleCount:e.examples.length,sealedAt:e.sealedAt}),b()}return c?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(Bv,{label:`Experiment training data`,action:`experiment`,children:(0,$.jsx)(`p`,{role:`status`,children:`Opening training data…`})}),children:(0,$.jsx)(qx,{api:e,method:t,navigation:u,onClose:b,onUseBatch:S},e.key)}),f.guard.dialog]}):(0,$.jsxs)(Bv,{label:`Experiment setup`,action:`experiment`,onRequestClose:()=>void f.guard.requestLeave(i),children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`h2`,{children:`Run Experiment`}),a?(0,$.jsx)(`button`,{type:`button`,disabled:f.busy,onClick:()=>void f.guard.requestLeave(i),children:`Close setup`}):null]}),(0,$.jsxs)(`form`,{noValidate:!0,onSubmit:e=>{e.preventDefault(),f.perform(f.pendingAction??(h?`start`:`prepare`))},children:[(0,$.jsx)(ft,{title:`Starting model`,children:(0,$.jsxs)(`fieldset`,{disabled:m,children:[(0,$.jsxs)(`label`,{children:[`Model`,(0,$.jsx)(Z,{floating:!0,searchable:!0,label:`Starting model`,value:s.trainingParent||s.startingModel?.source===`trained`||s.startingModel?.source===`steering`?`parent`:g?.id??(s.trainingBaseModel?`retained`:``),options:[{value:``,label:`Choose model`},...s.trainingParent||s.startingModel?.source===`trained`||s.startingModel?.source===`steering`?[{value:`parent`,label:s.startingModel?.label??f.startingModelLabel??`Selected trained checkpoint`}]:[],...s.trainingBaseModel&&!g?[{value:`retained`,label:s.trainingBaseModel.modelId,disabled:!0}]:[],...p.models.map(e=>({value:e.id,label:e.name,disabled:!e.available}))],onChange:e=>{e!==`parent`&&(s.setTrainingParent(null),s.setTrainingBaseModel(p.models.find(t=>t.id===e)?.preference??null))}})]}),s.trainingParent?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:`Starting from the selected trained checkpoint. The optimizer starts fresh.`}),t===`grpo`?(0,$.jsxs)(`label`,{children:[`LoRA continuation`,(0,$.jsx)(Z,{label:`LoRA continuation`,floating:!0,value:s.trainingParent.adapterMode,options:[{value:`shared`,label:`Shared · update the existing adapter`},{value:`residual_append`,label:`Stacked · freeze the parent and add an adapter`},{value:`sequential_merge`,label:`Merged · merge the parent, then train a new adapter`}],onChange:e=>{s.trainingParent&&(e===`shared`||e===`residual_append`||e===`sequential_merge`)&&s.setTrainingParent({...s.trainingParent,adapterMode:e})}})]}):null]}):null,(0,$.jsx)(xy,{disabled:m})]})}),(0,$.jsx)(ft,{title:`Training data`,children:(0,$.jsxs)(`fieldset`,{disabled:m,children:[(0,$.jsxs)(`label`,{children:[`Reviewed examples`,(0,$.jsx)(Z,{label:`Reviewed examples`,floating:!0,searchable:!0,value:f.batch?J(f.batch):``,options:[{value:``,label:`Choose reviewed batch`},...f.batch&&!y.some(e=>J(e.reference)===J(f.batch))?[{value:J(f.batch),label:`${f.batch.id} · r${f.batch.revision}`,disabled:!0}]:[],...y.map(e=>({value:J(e.reference),label:`${e.exampleCount} example${e.exampleCount===1?``:`s`} · ${e.reference.id} · r${e.reference.revision}`}))],onChange:e=>{let t=y.find(t=>J(t.reference)===e);t?x(t):f.setBatch(null)}})]}),f.selectedBatch?(0,$.jsxs)(`p`,{children:[f.selectedBatch.exampleCount,` reviewed example`,f.selectedBatch.exampleCount===1?``:`s`,`.`,` `,t===`sft`?`Supervised targets`:`Reward binding`,` `,`retained with this batch.`]}):null,p.hasNextPage?(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:p.isFetchingNextPage,onClick:()=>void p.fetchNextPage(),children:`More reviewed batches`}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,ref:d,onClick:()=>l(!0),children:`Import or review data`})]})}),(0,$.jsx)(ft,{title:`Validation`,children:(0,$.jsxs)(`fieldset`,{disabled:m,children:[(0,$.jsx)(ky,{api:e,value:f.evaluation,onChange:f.setEvaluation,disabled:m}),(0,$.jsxs)(`label`,{children:[`Optimizer validation split`,(0,$.jsx)(Z,{label:`Optimizer validation split`,floating:!0,value:f.validationSplit,options:[{value:`validation`,label:`Validation`},{value:`frozen_eval`,label:`Frozen evaluation`}],onChange:e=>f.setValidationSplit(e)})]}),(0,$.jsx)(`p`,{children:`This split is visible during optimization. Keep independent acceptance holdouts separate.`})]})}),(0,$.jsx)(ft,{title:`Training settings`,children:(0,$.jsxs)(`fieldset`,{disabled:m,children:[(0,$.jsxs)(`label`,{children:[`Training examples`,(0,$.jsx)(`input`,{type:`number`,min:1,max:Math.min(f.selectedBatch?.exampleCount??1e5,t===`sft`?1e3:1e5),step:1,value:typeof v==`number`||typeof v==`string`?v:``,onChange:e=>f.setRecipe({...f.recipe,dataset:{..._,maxExamples:e.target.value===``?``:e.target.valueAsNumber}})})]}),(0,$.jsx)(Tx,{recipe:f.recipe,onChange:e=>{e&&f.setRecipe(e)}}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Run details`}),(0,$.jsxs)(`label`,{children:[`Name`,(0,$.jsx)(`input`,{value:f.name,onChange:e=>f.setName(e.target.value),maxLength:191})]})]})]})}),(0,$.jsx)(Wx,{compute:f.compute,selection:f.gpuSelection,onChange:f.setGpuSelection,locked:m,method:t,budget:f.budget,onBudgetChange:f.setBudget,actualUsage:f.funding.allocationAdmission,actualUsageAvailable:p.billingModes?.[1].availability===`requires_preparation`,onBillingModeChange:f.setBillingMode,customerCapUsd:f.customerCapUsd,onCustomerCapChange:f.setCustomerCapUsd,prepared:h?.state===`prepared`,startAttempted:f.startAttempted,busy:f.busy,children:(0,$.jsx)(Db,{funding:f.funding,busy:f.busy,startAttempted:f.startAttempted,billingReturnPending:f.billingReturnPending,onOpenBilling:f.openBilling,onRefresh:f.refreshCredits})}),f.canRecover?(0,$.jsxs)(ft,{title:`Previous training review`,children:[(0,$.jsxs)(`p`,{children:[f.recovery.data?.review?.request.name,f.recovery.data?.review?.request.usageFunding?f.recovery.data.review.request.usageFunding.customerCapUsd===null?` · Use available credits`:` · $${f.recovery.data.review.request.usageFunding.customerCapUsd} spending limit`:` · $${f.recovery.data?.review?.request.maximumSpendUsd} maximum spend`]}),(0,$.jsx)(`p`,{children:`The original request is retained on this device. Restore it to check the current preparation or existing run.`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:f.busy,onClick:()=>void f.guard.requestLeave(()=>f.perform(`recover`)),children:`Restore previous review`})]}):null,h?(0,$.jsxs)(ft,{title:`Reviewed experiment`,children:[(0,$.jsxs)(`p`,{children:[h.plan.request.name,h.plan.usageQuote?null:` · $${h.plan.request.maximumSpendUsd} maximum spend`]}),h.plan.usageQuote?(0,$.jsx)(Kx,{quote:h.plan.usageQuote}):null,(0,$.jsx)(`p`,{children:h.state===`submitted`?`This experiment already has a training Job.`:h.state===`cancelled`?`Preparation cancelled. Finish editing to prepare another run.`:`Start training submits this preparation to hosted execution.`}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact inputs`}),(0,$.jsx)(`pre`,{children:JSON.stringify(h.plan.source,null,2)})]})]}):null,f.error||p.error?(0,$.jsx)(X,{error:f.error??p.error}):null,f.recovery.isError?(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:f.busy,onClick:()=>void f.recovery.refetch(),children:`Reload retained reviews`}):null,p.error?(0,$.jsx)(`button`,{className:`training-text-button`,type:`button`,onClick:()=>void p.refetch(),children:`Reload training inputs`}):null,p.isPending?(0,$.jsx)(`p`,{role:`status`,children:`Loading training inputs…`}):null,f.recoveredJobId?(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:f.busy,onClick:()=>void f.openRecoveredJob(),children:`Open existing training run`}):null,f.recoveredJobId?(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:f.busy,onClick:()=>void f.perform(`prepare`,{newRun:!0}),children:`Review edited settings for a new run`}):null,f.saveDraft?(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:m,onClick:()=>void f.saveDraft?.(),children:`Save draft`}):null,(0,$.jsx)(`button`,{className:`training-button`,type:`submit`,disabled:f.busy||!f.recovery.isSuccess||f.requiresRecovery||!!f.recoveredJobId||h?.state===`cancelled`||h?.state===`prepared`&&f.pendingAction!==`cancel`&&!f.startAttempted&&(!f.compute.canStart||!f.funding.canStart||f.billingReturnPending),children:f.busy?`Working…`:f.pendingAction===`cancel`?`Retry edit setup`:h?.state===`submitted`?`Open training run`:h?f.startAttempted?`Retry start`:`Start training`:`Review experiment`}),h?(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:f.busy||!!f.pendingAction||h.state===`submitted`,onClick:()=>void f.perform(`cancel`),children:`Edit setup`}):null]}),f.guard.dialog]})}function Yx(e,t,n){let r=t?{teamId:e.teamId,modelId:t.modelId,source:t.source,...t.revision?{revision:t.revision}:{},...t.tokenizerRevision?{tokenizerRevision:t.tokenizerRevision}:{},...t.chatTemplateHash?{chatTemplateHash:t.chatTemplateHash}:{},...t.modelAssetId?{modelAssetId:t.modelAssetId}:{}}:null,i=S({queryKey:[`model-modification-capabilities`,e.key,e.actorId,r],enabled:n&&r!==null,retry:!1,staleTime:3e4,refetchInterval:e=>!e.state.error&&6e4,queryFn:async({signal:t})=>{if(!r)throw Error(`Select a starting model before reading capabilities.`);return pr(await Y(e.connection,`/v1/training/setup/modification-capabilities?teamId=${encodeURIComponent(e.teamId)}`,{method:`POST`,body:JSON.stringify(r),signal:t}),r,e.actorId??void 0)}}),a=!!(i.data&&Date.parse(i.data.expiresAt)>Date.now());return{...i,current:a?i.data:void 0,canRefresh:!!r}}function Xx(e,t){let n=ml.parse({teamId:e.teamId,actorId:e.actorId,apiOrigin:t}),r={...n,projectId:e.projectId},i=`/v1/training/modification-executions`;return{account:n,async compile(t){return kn(await Y(e.connection,`${i}/compile`,{method:`POST`,body:JSON.stringify({...r,command:t})}),t)},async mutate(t,a){let o=`action`in t?`${i}/${encodeURIComponent(t.id)}/${t.action}`:`${i}/prepare`,s=await ar(await Y(e.connection,o,{method:`POST`,body:JSON.stringify({...r,intentHash:a,command:t})}),t);if(s.execution.ownerUserId!==n.actorId||s.execution.projectId!==e.projectId)throw Error(`The execution receipt belongs to another account or Project.`);return s},async get(t,r){let a=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}}),o=await dr(await Y(e.connection,`${i}/${encodeURIComponent(t)}?${a}`,{signal:r}),{teamId:e.teamId,id:t,ownerUserId:n.actorId});if(o.projectId!==e.projectId)throw Error(`The execution belongs to another Project.`);return o},async list(t={},r){let a={...t,...e.projectId?{projectId:e.projectId}:{}},o=new URLSearchParams({...n,...e.projectId?{projectId:e.projectId}:{}});for(let[e,t]of Object.entries(a))t!==void 0&&o.set(e,String(t));return Xn(await Y(e.connection,`${i}?${o}`,{signal:r}),{teamId:e.teamId,ownerUserId:n.actorId,query:a})}}}function Zx(e,t=!0){return S({queryKey:[`activation-experiment-account`,e.key,e.actorId],enabled:t&&e.location===`hosted`&&!!e.actorId,retry:!1,queryFn:async({signal:t})=>{let n=await e.request(`inventory`,{},t);if(n.teamId!==e.teamId)throw Error(`The workspace account changed.`);return Xx(e,n.apiOrigin)}})}function Qx(e,t){return!(e instanceof Ti)||e.status!==409||e.retryable!==!1?!1:(`action`in t?[`modification_execution_revision_conflict`,`modification_execution_review_required`,`modification_execution_runtime_changed`,`modification_execution_funding_changed`,`modification_execution_project_archived`,`modification_execution_cancel_unavailable`]:[`modification_execution_runtime_unavailable`,`modification_execution_runtime_limits`,`modification_execution_capability_changed`,`modification_execution_project_archived`]).includes(e.code??``)}var $x=[`training:prepare-modification`,`training:start-modification`,`training:cancel-modification`];function eS(e,t){let n=u(),r=J([e.key,e.connection.serverUrl,t.draftId,t.executionId,t.method]),i=(0,Q.useRef)(r);i.current=r,(0,Q.useEffect)(()=>(i.current=r,()=>{i.current=``}),[r]);let a=()=>({identity:r,busy:!1,error:null,receipt:null,selected:null,original:null,preparationOperationId:null}),[o,s]=(0,Q.useState)(a),c=(0,Q.useRef)(new Set),l=o.identity===r?o:a();function d(e){i.current===r&&s(t=>({...t.identity===r?t:a(),...e}))}function f(){if(i.current!==r)throw Error(`Return to this experiment's original account before continuing.`)}let p=Zx(e,t.visible),m=p.data,h=S({queryKey:[`activation-experiment-recovery`,r],enabled:t.visible&&e.location===`hosted`&&!!e.actorId&&!l.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[];for(let i of $x){let a,o=new Set;for(let s=0;;s++){if(s>=100)throw Error(`The retained execution catalog exceeds its supported bound.`);let c=await e.pendingOperations(i,a,n);for(let n of c.items){let a=i===$x[0]?hl.parse(n.reviewedIntent):gl.parse(n.reviewedIntent);if(a.account.actorId!==e.actorId||a.account.teamId!==e.teamId)throw Error(`The retained execution belongs to another account.`);if(!(t.draftId===null?`execution`in a&&a.execution.id===t.executionId:a.draftId===t.draftId))continue;let o=i===$x[0]?Kt.parse(n.command??{...a.request,operationId:n.id}):Wt(n.command??{...a.request,operationId:n.id});r.push({intent:a,command:o,operation:e.recoverOperation(n)})}if(!c.nextCursor)break;if(o.has(c.nextCursor))throw Error(`The retained execution catalog repeated a cursor.`);o.add(c.nextCursor),a=c.nextCursor}}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),g=l.original??h.data?.[0]??null,_=t.executionId??l.selected??l.receipt?.execution.id??(g&&`execution`in g.intent?g.intent.execution.id:null),v=S({queryKey:[`managed-modification-execution`,r,_],enabled:t.visible&&!!(m&&_),retry:!1,queryFn:({signal:e})=>{if(!m||!_)throw Error(`Select an execution first.`);return m.get(_,e)},refetchInterval:e=>e.state.error?!1:e.state.data&&![`completed`,`failed`,`cancelled`].includes(e.state.data.phase)?3e3:!1});async function y(t){let r=Xx(e,t.intent.account.apiOrigin);if(J(r.account)!==J(t.intent.account))throw Error(`Return to this execution's original account before retrying.`);d({original:t}),await t.operation.retainCommand(t.command,`dispatching`),f();let i;try{i=await r.mutate(t.command,t.operation.intentHash),f()}catch(e){throw Qx(e,t.command)&&(await t.operation.acknowledge(),f(),d({original:null}),await h.refetch(),f(),n.invalidateQueries({queryKey:[`managed-modification-execution`]})),e}return d({receipt:i,selected:i.execution.id,preparationOperationId:`action`in t.command?`preparationOperationId`in t.intent?t.intent.preparationOperationId:null:t.command.operationId}),await t.operation.acknowledge(),f(),d({original:null}),await h.refetch(),f(),n.invalidateQueries({queryKey:[`managed-modification-execution`]}),n.invalidateQueries({queryKey:[`unified-experiments`]}),i}async function b(e){if(!c.current.has(r)){c.current.add(r),d({busy:!0,error:null});try{return f(),await e()}catch(e){return i.current===r&&d({error:e}),null}finally{c.current.delete(r),d({busy:!1})}}}async function x(n,r){return b(async()=>{if(g)return y(g);if(!m||!h.isSuccess||!t.draftId||n.id!==t.draftId||!n.activationForm||!t.method)throw Error(`Load this saved experiment and original requests before preparing.`);let i=vt(n.activationForm.maximumSpendUsd);await r(n),f();let a=await Iy(e).get(n.id);if(f(),a.status!==`draft`||a.projectId!==e.projectId||J(a.draft)!==J(n))throw Error(`The saved experiment changed. Reopen its exact current revision before preparing.`);let o=n.activationForm.baseModel;if(!o||n.startingModel?.source===`trained`)throw Error(`Choose a qualified exact activation starting model.`);let s={teamId:e.teamId,modelId:o.modelId,source:o.source,...o.revision?{revision:o.revision}:{},...o.tokenizerRevision?{tokenizerRevision:o.tokenizerRevision}:{},...o.chatTemplateHash?{chatTemplateHash:o.chatTemplateHash}:{},...o.modelAssetId?{modelAssetId:o.modelAssetId}:{}},c={teamId:e.teamId,projectId:e.projectId,method:t.method,query:s,form:n.activationForm},l=await m.compile(c);if(f(),l.actorId!==e.actorId||l.formHash!==await zr(n.activationForm))throw Error(`The compilation differs from this exact saved form.`);let u=await Ln({teamId:e.teamId,projectId:e.projectId,operationId:crypto.randomUUID(),name:n.name,method:t.method,query:s,request:l.request,sourceForm:n.activationForm,maximumSpendUsd:i}),{operationId:d,...p}=u,_=hl.parse({account:m.account,draftId:n.id,request:p}),v=await e.operation($x[0],_);return f(),y({intent:_,operation:v,command:{...u,operationId:v.id}})})}async function C(n,r){return b(async()=>{if(g)return y(g);let i=r??v.data;if(!m||!h.isSuccess||!i||v.error)throw Error(`Read the exact execution before reviewing its next action.`);let{schemaVersion:a,request:o,sourceForm:s,result:c,resultRecordedAt:u,contentHash:d,...p}=i,_=Vt.parse(p),b=n===`start`?{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n,approvedMaximumSpendUsd:i.plan.maximumSpendUsd,...i.plan.computePrice?{approvedPriceHash:await zr(i.plan.computePrice)}:{}}:{teamId:e.teamId,id:i.id,expectedRevision:i.revision,planHash:i.plan.contentHash,action:n},x=gl.parse({account:m.account,draftId:l.preparationOperationId?t.draftId:null,preparationOperationId:l.preparationOperationId,execution:_,request:b}),S=await e.operation(n===`start`?$x[1]:$x[2],x);return f(),y({intent:x,operation:S,command:Wt({...b,operationId:S.id})})})}return{prepare:x,control:C,retry:()=>b(()=>{if(!g)throw Error(`Reload the original execution request.`);return y(g)}),busy:l.busy,receipt:l.receipt,original:g,execution:v.data,ready:p.isSuccess&&h.isSuccess,recoveryReady:h.isSuccess,canControl:v.isSuccess&&!v.error,error:l.error??p.error??h.error??v.error,refresh:()=>{p.refetch(),e.actorId&&h.refetch(),m&&_&&v.refetch()},loading:v.isFetching||p.isFetching,selectedId:_}}function tS(e,t){return{key:JSON.stringify([t.accountKey,t.actorId??null,t.teamId,t.projectId,t.executionLocation??`hosted`]),connection:e,actorId:t.actorId??null,teamId:t.teamId,projectId:t.projectId,location:t.executionLocation??`hosted`,accountKey:t.accountKey,localDatasets(t,n={},r,i){return Y(e,`/v1/local-datasets`,{method:`POST`,body:JSON.stringify({action:t,payload:n,...r?{id:r}:{}}),signal:i})},humanContext:t.actorId?{connection:e,scope:t.teamId,actorId:t.actorId,location:t.executionLocation??`hosted`}:null,local(n,r={},i){return Y(e,`/v1/local-experiments`,{method:`POST`,body:JSON.stringify({teamId:t.teamId,projectId:t.projectId,action:n,payload:r}),signal:i})},request(n,r,i){return Y(e,`/v1/training/evaluation-workspace`,{method:`POST`,body:JSON.stringify({teamId:t.teamId,projectId:t.projectId,operation:n,...r===void 0?{}:{value:r}}),signal:i})},async pendingOperations(n,r,i){return sl.parse(await Y(e,`/v1/training/evaluation-workspace`,{method:`POST`,body:JSON.stringify({teamId:t.teamId,projectId:t.projectId,operation:`pendingOperations`,value:{action:n,...r?{cursor:r}:{}}}),signal:i}))},recoverOperation(e){let t=ol.parse(e);return r(t.action,t.intentHash,{id:t.id,createdAt:t.createdAt})},operation(e,t){return n(e,t)},localOperation(e,t){return n(`local:${e}`,t)}};async function n(n,i){let a=al.safeParse(n).success,o=ie(i),s={teamId:t.teamId,projectId:t.projectId};return r(n,o,await Y(e,`/v1/training/evaluation-workspace`,{method:`POST`,body:JSON.stringify({...s,operation:`prepareOperation`,value:{action:n,intentHash:o,...a?{reviewedIntent:i}:{}}})}))}function r(n,r,i){let a=al.safeParse(n).success,o={teamId:t.teamId,projectId:t.projectId};return{...i,intentHash:r,async retainCommand(t,s=`reviewed`){if(!a)throw Error(`This evaluation operation has no reviewed command catalog.`);return Y(e,`/v1/training/evaluation-workspace`,{method:`POST`,body:JSON.stringify({...o,operation:`retainOperation`,value:{action:n,intentHash:r,id:i.id,command:t,phase:s}})})},async acknowledge(t){await Y(e,`/v1/training/evaluation-workspace`,{method:`POST`,body:JSON.stringify({...o,operation:`acknowledgeOperation`,value:{action:n,intentHash:r,id:i.id,...t?{expectedPhase:t}:{}}})})}}}}function nS(e,t){return tS(e.connection,{teamId:e.teamId,projectId:e.projectId,actorId:e.actorId,accountKey:e.accountKey,executionLocation:t})}function rS(e){let t=new Set(e.request.variants.filter(e=>e.profile===null).map(e=>e.id)),n=new Map;for(let r of e.result?.captures??[])t.has(r.variantId)&&n.set(`${r.layer}:${r.neuron}`,{layer:r.layer,neuron:r.neuron});return[...n.values()].sort((e,t)=>e.layer-t.layer||e.neuron-t.neuron)}function iS(e){let t=e.sourceForm?.baseModel,n=e.request.model;return e.phase===`completed`&&!!e.result&&t?.source===`managed`&&t.modelAssetId===null&&t.modelId===n.modelId&&t.revision===n.revision&&!e.sourceForm?.startingProfile&&n.adapter===null&&n.architecture===`dense_decoder`&&n.dtype===`bfloat16`&&n.quantization===`none`}async function aS(e,t,n){let r=mt.parse(n);if(!iS(e)||!e.result||!e.sourceForm?.baseModel)throw Error(`Choose a completed inspection of the exact unmodified dense base before training selected neurons.`);let i=await Et(e.result,e.request);if(r.owner.teamId!==e.teamId||r.owner.actorId!==e.ownerUserId||r.projectId!==e.projectId||r.executionId!==e.id||r.method!==e.method||r.inputHash!==e.plan.inputHash||r.runtimeHash!==e.plan.runtimeHash||r.resultHash!==i.contentHash)throw Error(`The selected inspection differs from its original account, Project or retained result.`);let a=new Set(rS(e).map(e=>`${e.layer}:${e.neuron}`)),o=[...new Map(t.map(e=>[`${e.layer}:${e.neuron}`,e])).values()].sort((e,t)=>e.layer-t.layer||e.neuron-t.neuron);if(!o.length||o.length>128||o.some(e=>!a.has(`${e.layer}:${e.neuron}`)))throw Error(`Select between 1 and 128 neurons observed under Off in this exact inspection.`);let s=e.sourceForm.baseModel,c=nn(s),l=`Train selected neurons · ${e.name}`.slice(0,500);return Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:crypto.randomUUID(),operationType:`selective_neuron_training`,name:l,startingModel:{source:`managed`,label:s.modelId,baseModel:s,inferenceModelId:null},neuronTrainingForm:{...c,name:l,selection:{...c.selection,count:String(o.length),coordinates:o.map(e=>`${e.layer}:${e.neuron}`).join(`
13
+ `)},inspectionSource:{result:r,modelHash:await zr(e.request.model)}}})}function oS({execution:e,api:t,disabled:n=!1}){let r=kv(),i=(0,Q.useMemo)(()=>tS(t.connection,{teamId:t.teamId,actorId:t.actorId,accountKey:t.accountKey,projectId:e.projectId,executionLocation:`hosted`}),[t.key,e.projectId]),a=Zx(i,iS(e)),[o,s]=(0,Q.useState)([]),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(null),f=JSON.stringify([i.key,e.id,e.result?.contentHash]),p=(0,Q.useRef)(f);p.current=f,(0,Q.useEffect)(()=>(p.current=f,s([]),l(!1),d(null),()=>{p.current=``}),[f]);let m=(0,Q.useMemo)(()=>rS(e),[e]);if(!iS(e)||!m.length)return null;let h=m.filter(e=>o.includes(`${e.layer}:${e.neuron}`));async function g(){if(!c&&!n&&a.data&&h.length){l(!0),d(null);try{let t=await a.data.get(e.id);if(p.current!==f)return;if(t.result?.contentHash!==e.result?.contentHash)throw Error(`Refresh the original inspection before selecting its neurons.`);let n=mt.parse({kind:`managed_modification_result`,location:`cloud`,apiOrigin:a.data.account.apiOrigin,owner:{teamId:i.teamId,actorId:i.actorId},projectId:t.projectId,executionId:t.id,method:t.method,inputHash:t.plan.inputHash,runtimeHash:t.plan.runtimeHash,resultHash:t.result.contentHash}),o=await aS(t,h,n);if(p.current!==f)return;await r.openDraft(o,as(`experiments`,null,{projectId:t.projectId,executionLocation:`hosted`}))}catch(e){p.current===f&&d(e)}finally{p.current===f&&l(!1)}}}return(0,$.jsxs)(`section`,{"aria-label":`Train neurons from inspection`,children:[(0,$.jsx)(X,{error:u??a.error}),(0,$.jsx)(`div`,{className:`evaluation-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evaluation-table`,children:[(0,$.jsx)(`caption`,{children:`Neurons observed under Off`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:`Select`}),(0,$.jsx)(`th`,{scope:`col`,children:`Layer`}),(0,$.jsx)(`th`,{scope:`col`,children:`Neuron`})]})}),(0,$.jsx)(`tbody`,{children:m.map(e=>{let t=`${e.layer}:${e.neuron}`,r=o.includes(t);return(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:(0,$.jsx)(`input`,{type:`checkbox`,"aria-label":`Train layer ${e.layer} neuron ${e.neuron}`,checked:r,disabled:c||n||!r&&o.length>=128,onChange:e=>s(n=>e.target.checked?[...n,t]:n.filter(e=>e!==t))})}),(0,$.jsx)(`td`,{children:e.layer}),(0,$.jsx)(`td`,{children:e.neuron})]},t)})})]})}),(0,$.jsxs)(`p`,{children:[h.length,` selected. The editor retains this inspection and exact base; choose reviewed target and background data before Run.`]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:c||n||!a.isSuccess||!h.length,onClick:()=>void g(),children:c?`Opening experiment…`:`Train selected neurons`})]})}var sS=`training-steering-result-save`;function cS(e){return e instanceof Ti&&e.status===409&&e.retryable===!1&&[`steering_profile_revision_conflict`,`steering_model_revision_conflict`,`steering_model_serving_in_use`,`steering_model_base_mismatch`,`steering_profile_result_changed`,`steering_profile_result_unavailable`].includes(e.code??``)}function lS(e,t,n){let r=u(),i=J([e.key,ra(e.connection),t]),a=(0,Q.useRef)(i);a.current=i,(0,Q.useEffect)(()=>(a.current=i,()=>{a.current=``}),[i]);let o=()=>({identity:i,busy:!1,error:null,original:null,receipt:null}),[s,c]=(0,Q.useState)(o),l=(0,Q.useRef)(new Set),d=s.identity===i?s:o();function f(e){a.current===i&&c(t=>({...t.identity===i?t:o(),...e}))}function p(){if(a.current!==i)throw Error(`Return to this Model save's original account and result.`)}let m=n?.method===`neuron_steering`&&n.phase===`completed`&&n.result!==null,h=Zx(e,m),g=S({queryKey:[`steering-model-save-recovery`,i],enabled:!!e.actorId&&!d.busy,retry:!1,staleTime:0,gcTime:0,queryFn:async({signal:n})=>{let r=[],i=new Set,a;for(let o=0;;o++){if(o>=100)throw Error(`The retained Model save catalog exceeds its supported bound.`);let s=await e.pendingOperations(sS,a,n);for(let n of s.items){let i=bl.parse(n.reviewedIntent);if(i.request.executionId!==t)continue;if(i.account.actorId!==e.actorId||i.account.teamId!==e.teamId||i.execution.projectId!==e.projectId)throw Error(`The retained Model save belongs to another creator or Project.`);let a=Pt.parse(n.command??{...i.request,operationId:n.id});r.push({intent:i,command:a,operation:e.recoverOperation(n)})}if(!s.nextCursor)break;if(i.has(s.nextCursor))throw Error(`The retained Model save catalog repeated a cursor.`);i.add(s.nextCursor),a=s.nextCursor}return r.sort((e,t)=>e.operation.createdAt.localeCompare(t.operation.createdAt))}}),_=d.original??g.data?.[0]??null,v=S({queryKey:[`steering-model-save-options`,i,h.data?.account.apiOrigin,n?.result?.contentHash],enabled:m&&h.isSuccess&&g.isSuccess&&!_&&!d.busy,retry:!1,queryFn:async({signal:n})=>{if(!h.data)throw Error(`Read the configured result account first.`);let r=h.data.account,i=new URLSearchParams({...r,...e.projectId?{projectId:e.projectId}:{}}),a=xl.parse(await Y(e.connection,`/v1/training/modification-executions/${encodeURIComponent(t)}/model?${i}`,{signal:n}));if(J(a.account)!==J(r)||a.executionId!==t||a.projectId!==e.projectId)throw Error(`The Model targets differ from this exact result account or Project.`);return a}});async function y(t){f({original:t}),await t.operation.retainCommand(t.command,`dispatching`),p();let n;try{let r=await Y(e.connection,`/v1/training/modification-executions/${encodeURIComponent(t.command.executionId)}/model`,{method:`POST`,body:JSON.stringify({...t.intent.account,projectId:t.intent.execution.projectId,intentHash:t.operation.intentHash,command:t.command})});if(n=await hr(r,t.command),p(),n.actorId!==e.actorId||n.record.publication.projectId!==e.projectId)throw Error(`The saved Model receipt belongs to another creator or Project.`)}catch(e){throw cS(e)&&(await t.operation.acknowledge(),p(),f({original:null}),await g.refetch(),p(),v.refetch()),e}f({receipt:n});for(let e of[`saved-training-model`,`saved-model-serving`,`steering-model-save-options`,`unified-experiments`,`model-projects`])r.invalidateQueries({queryKey:[e]});return await t.operation.acknowledge(),p(),f({original:null}),await g.refetch(),p(),n}async function b(r){if(l.current.has(i))return null;l.current.add(i),f({busy:!0,error:null});try{if(p(),!g.isSuccess)throw Error(`Reload the original Model saves before continuing.`);if(_)return await y(_);if(!m||!n?.result||!v.isSuccess||!h.isSuccess||!v.data)throw Error(`Read the completed steering result and current Model targets before saving.`);let i=n.request.variants.find(e=>e.id===r.variantId);if(!i?.profile)throw Error(`Choose an exact saved profile variant; Off and inspection cannot be saved as a steering Model.`);let a=r.modelProjectId?v.data.models.find(e=>e.id===r.modelProjectId):null;if(r.modelProjectId&&!a)throw Error(`Refresh the Model targets before updating this Model.`);let{schemaVersion:o,request:s,sourceForm:c,result:l,resultRecordedAt:u,contentHash:d,...f}=n,b=bl.parse({account:v.data.account,execution:Vt.parse(f),request:{teamId:e.teamId,executionId:t,variantId:i.id,resultHash:n.result.contentHash,profileHash:i.profile.contentHash,name:r.name,modelProjectId:a?.id??null,expectedModelRevision:a?.revision??0}}),x=await e.operation(sS,b);return p(),await y({intent:b,operation:x,command:Pt.parse({...b.request,operationId:x.id})})}catch(e){return a.current===i&&f({error:e}),null}finally{l.current.delete(i),f({busy:!1})}}return{save:b,busy:d.busy,receipt:d.receipt,original:_,options:v.data,freshReady:m&&g.isSuccess&&v.isSuccess&&h.isSuccess,recoveryReady:g.isSuccess,error:d.error??g.error??(m?v.error??h.error:null),refresh:()=>{g.refetch(),m&&!_&&(h.refetch(),h.data&&v.refetch())}}}function uS({api:e,id:t,execution:n,disabled:r=!1}){let i=lS(e,t,n),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)((n?.name??`Steering Model`).slice(0,200)),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(``),p=n?.request.variants.filter(e=>e.profile!==null)??[],m=p.some(e=>e.id===l)?l:p[0]?.id??``,h=i.original?.command,g=iy({name:`Steering Model save`,busy:i.busy,dirty:a&&(!!h||s!==(n?.name??`Steering Model`).slice(0,200)||!!d||!!l),discardDescription:h?`The original save remains recoverable from this execution after closing.`:void 0});if(n?.method===`inspect_activations`)return null;let _=n?.method===`neuron_steering`&&n.phase===`completed`&&n.result!==null&&p.length>0,v=!i.recoveryReady&&i.error!==null;if(!_&&!h&&!i.receipt&&!v)return null;let y=i.receipt?.version;return(0,$.jsxs)(`section`,{className:`training-detail-section`,"aria-label":`Save steering Model`,children:[(0,$.jsx)(X,{error:i.error}),i.recoveryReady?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Reload retained Model saves`}),i.receipt&&y?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{children:[`Saved to `,i.receipt.model?.name,`. Exact version `,(0,$.jsx)(`code`,{children:y.contentHash}),`.`]}),(0,$.jsx)(hb,{connection:e.connection,version:y,api:e},`${e.key}:${y.contentHash}`)]}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:r||i.busy||!i.recoveryReady,onClick:()=>o(!0),children:h?`Recover Model save`:i.receipt?`Save another variant`:`Save model`}),a?(0,$.jsxs)(qa,{ariaLabel:`Save steering model`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:i.busy,onClose:()=>void g.requestLeave(()=>o(!1)),children:[(0,$.jsx)(`h2`,{children:`Save model`}),(0,$.jsx)(`p`,{children:`Save one exact profile from the completed hosted result. Off remains the control comparison; saving does not activate serving.`}),(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),i.save({name:s,variantId:m,modelProjectId:d||null}).then(e=>{e&&(g.allowNextNavigation(),o(!1))})},children:[(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Profile variant`}),(0,$.jsx)(Z,{label:`Profile variant`,value:h?.variantId??m,options:h?[{value:h.variantId,label:h.variantId}]:p.map(e=>({value:e.id,label:e.id})),disabled:i.busy||!!h,onChange:u})]}),(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Save destination`}),(0,$.jsx)(Z,{label:`Model destination`,value:h?.modelProjectId??(h?``:d),options:[{value:``,label:`Create new Model`},...(i.options?.models??[]).map(e=>({value:e.id,label:e.name,description:`Current revision ${e.revision}`})),...h?.modelProjectId&&!i.options?.models.some(e=>e.id===h.modelProjectId)?[{value:h.modelProjectId,label:`Original selected Model`}]:[]],disabled:i.busy||!!h||!i.freshReady,onChange:e=>{f(e);let t=i.options?.models.find(t=>t.id===e);t&&c(t.name)}})]}),(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Model name`}),(0,$.jsx)(`input`,{"data-autofocus":!0,value:h?.name??s,maxLength:200,disabled:i.busy||!!h,onChange:e=>c(e.target.value)})]}),h?(0,$.jsx)(`p`,{children:`Original result, profile, destination and revision are retained. Retry sends the same operation.`}):null,i.receipt&&h?(0,$.jsx)(`p`,{role:`status`,children:`The Model was saved. Local acknowledgement is pending; retry preserves its exact receipt.`}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:()=>void g.requestLeave(()=>o(!1)),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:i.busy,onClick:i.refresh,children:`Refresh targets and recovery`}),(0,$.jsx)(`button`,{type:`submit`,className:`training-button`,disabled:i.busy||r||!i.recoveryReady||!h&&!i.freshReady,children:i.busy?`Saving…`:h?`Retry original save`:`Save model`})]})]})]}):null,g.dialog]})}var dS=10;new Date(0).toISOString();function fS(e){return e.filter(e=>e.target.kind===`agent`&&[`ready_local`,`released`,`published_hosted`].includes(e.state)).map(e=>`${e.id}:${e.revision}:${e.state}`).sort().join(`|`)}function pS({rows:e,loading:t,busyAction:n,runs:r,state:i,emptyMessage:a=`No Models yet.`,onPull:o,onSelect:s,onUseModel:c,onConfigure:l}){return t?(0,$.jsxs)(`div`,{className:`labs-table-empty`,children:[(0,$.jsx)(Pa,{className:`spin`,size:16}),` Loading Models…`]}):e.length?(0,$.jsx)(`div`,{className:`training-table-wrap`,children:(0,$.jsxs)(`table`,{className:`training-data-table labs-models-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Model`}),(0,$.jsx)(`th`,{children:`Availability`}),(0,$.jsx)(`th`,{children:`Recent run`}),(0,$.jsx)(`th`,{children:`Updated`}),(0,$.jsx)(`th`,{children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Actions`})})]})}),(0,$.jsx)(`tbody`,{children:e.map(e=>{let t=e.local,a=e.hosted,u=t?oi(t,r,i):[],d=u.find(e=>e.current)??null,f=t?si(ii(t,r,i),u,ai(t,i)):[],p=f[0]??null,m=p?.lifecycleRun?.status??p?.job?.status??`not_run`,h=a?n===`pull-hosted-model-project:${a.project.id}`:!1,g=a?n===`open-hosted-model-project:${a.project.id}`:!1,_=a?a.localState===`not_pulled`||a.localState===`remote_ahead`:!1,v=t?.name??a.project.name,y=t?.description??a.project.objective??`No description`;return(0,$.jsxs)(`tr`,{onClick:()=>{g||s(e.key)},children:[(0,$.jsx)(`td`,{children:t?(0,$.jsxs)(`button`,{className:`labs-workproduct-link`,type:`button`,onClick:e=>{e.stopPropagation(),s(t.key)},children:[(0,$.jsx)(`strong`,{children:v}),(0,$.jsx)(`span`,{children:y})]}):(0,$.jsxs)(`button`,{type:`button`,disabled:g,className:`labs-workproduct-link labs-hosted-project-identity`,onClick:t=>{t.stopPropagation(),s(e.key)},children:[(0,$.jsx)(`strong`,{children:v}),(0,$.jsx)(`span`,{children:y}),(0,$.jsx)(`small`,{children:g?`Opening…`:a.project.portableProjectId})]})}),(0,$.jsx)(`td`,{children:(0,$.jsxs)(`div`,{className:`labs-model-table-summary`,children:[a?(0,$.jsx)(ci,{label:mS(a.localState),value:hS(a.localState)}):(0,$.jsx)(ci,{label:d?`Hosted`:`Local only`,value:d?`ready`:`not_run`}),(0,$.jsx)(`span`,{children:a?a.project.trainingSetup.baseModel?.modelId??a.project.defaultBaseModel?.modelId??`No base model`:d?`Release ${d.number}`:`No active release`})]})}),(0,$.jsx)(`td`,{children:(0,$.jsxs)(`div`,{className:`labs-model-table-summary`,children:[t?(0,$.jsx)(ci,{label:Ca(m),value:m}):(0,$.jsx)(ci,{label:a.project.trainingSetup.method?.toUpperCase()??`Configured`,value:`prepared`}),(0,$.jsx)(`span`,{children:t?_S(p?.lifecycleRun??null,f.length):`Hosted source r${a.project.sourceRevision}`})]})}),(0,$.jsx)(`td`,{children:vS(e.updatedAt)}),(0,$.jsx)(`td`,{children:(0,$.jsxs)(`div`,{className:`labs-workproduct-actions`,children:[a&&_?(0,$.jsxs)(`button`,{className:`training-button secondary labs-compact-button`,disabled:h,title:gS(a.localState),type:`button`,onClick:e=>{e.stopPropagation(),o(a)},children:[h?(0,$.jsx)(Pa,{className:`spin`,size:13}):(0,$.jsx)(ru,{size:13}),h?`Importing…`:a.localState===`remote_ahead`?`Update`:`Pull`]}):null,t&&(d||!_)?(0,$.jsx)(`button`,{className:`training-button secondary labs-compact-button labs-workproduct-use`,disabled:!d,title:d?`Chat with the active Version`:a?gS(a.localState):`Set a passing Version active before Chat`,type:`button`,onClick:e=>{e.stopPropagation(),c(t.id)},children:`Chat`}):null,t?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary labs-compact-button`,onClick:e=>{e.stopPropagation(),l(t.id)},children:`Configure`}),(0,$.jsx)(ka,{size:15})]}):null]})})]},e.key)})})]})}):(0,$.jsx)(`div`,{className:`labs-table-empty`,children:a})}function mS(e){return e===`not_pulled`?`Hosted`:e===`up_to_date`?`Local + hosted`:e===`remote_ahead`?`Update available`:e===`local_ahead`?`Local changes`:e===`diverged`?`Diverged`:`Local conflict`}function hS(e){return e===`up_to_date`?`ready`:e===`not_pulled`||e===`remote_ahead`?`prepared`:e===`local_ahead`?`running`:`failed`}function gS(e){return e===`not_pulled`?`Pull this hosted project locally`:e===`remote_ahead`?`Update the clean local copy from hosted`:e===`up_to_date`?`This project is current locally`:e===`local_ahead`?`Sync local changes before pulling`:`Resolve the local and hosted project conflict before pulling`}function _S(e,t){return e?.kind===`evaluation`?`${e.evaluation?.benchmarkId===`harness-refiner`?`Harness Refiner 08112026`:`Benchmark`} · ${e.receipt?.schemaVersion===`openpond.modelEvaluationReceipt.v1`?e.receipt.attempts?.length?(()=>{let t=ni(e.receipt);return`${t.passedTaskCount}/${t.comparedTaskCount} passed`})():bS(e.receipt.terminalClassification.replaceAll(`_`,` `)):e.receipt?.schemaVersion===`openpond.modelEvaluationStopReceipt.v1`?`Inconclusive`:e.evaluationProgress?`${bS(e.evaluationProgress.stage)} ${e.evaluationProgress.completedAttempts}/${e.evaluationProgress.totalAttempts}`:Ca(e.status)}`:`${t} ${t===1?`run`:`runs`}`}function vS(e){let t=new Date(e),n=new Date;return t.toDateString()===n.toDateString()?new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`2-digit`}).format(t):new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,...t.getFullYear()===n.getFullYear()?{}:{year:`2-digit`}}).format(t)}function yS({page:e,total:t,onChange:n}){let r=Math.max(1,Math.ceil(t/dS));return r<=1?null:(0,$.jsxs)(`nav`,{className:`labs-pagination`,"aria-label":`Pagination`,children:[(0,$.jsx)(`button`,{type:`button`,disabled:e<=1,onClick:()=>n(e-1),children:`Previous`}),(0,$.jsxs)(`span`,{children:[e,` of `,r]}),(0,$.jsx)(`button`,{type:`button`,disabled:e>=r,onClick:()=>n(e+1),children:`Next`})]})}function bS(e){return e&&`${e[0].toUpperCase()}${e.slice(1).replaceAll(`_`,` `)}`}function xS(e){return e?[...e.jobs.map(e=>`job:${e.id}:${e.status}`),...e.models.map(e=>`model:${e.id}:${e.status}:${e.artifactId}:${e.jobId}`)].sort().join(`|`):``}function SS({request:e,result:t,trainingAction:n}){let[r,i]=(0,Q.useState)(``),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(1),d=e?.prompts.some(e=>e.id===r)?r:e?.prompts[0]?.id,f=e?.variants.some(e=>e.id===a)?a:e?.variants[0]?.id,p=e?.capture.flatMap(e=>e.neurons.map(t=>({value:`${e.layer}:${t}`,label:`Layer ${e.layer} · Neuron ${t}`})))??[],m=p.some(e=>e.value===s)?s:p[0]?.value,h=t?.captures.filter(e=>e.promptId===d&&e.variantId===f&&`${e.layer}:${e.neuron}`===m)??[],g=t?.outcomes.find(e=>e.promptId===d&&e.variantId===f),_=Math.min(l,Math.max(1,Math.ceil(h.length/10)));return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(ft,{title:`Activation capture`,children:[(0,$.jsxs)(`label`,{className:`model-build-field`,children:[`Prompt`,(0,$.jsx)(Z,{label:`Captured prompt`,floating:!0,value:d??``,options:e.prompts.map(e=>({value:e.id,label:e.id})),onChange:e=>{i(e),u(1)}})]}),(0,$.jsxs)(`label`,{className:`model-build-field`,children:[`Variant`,(0,$.jsx)(Z,{label:`Captured variant`,floating:!0,value:f??``,options:e.variants.map(e=>({value:e.id,label:e.profile?e.id:`${e.id} · Off`})),onChange:e=>{o(e),u(1)}})]}),(0,$.jsxs)(`label`,{className:`model-build-field`,children:[`Coordinate`,(0,$.jsx)(Z,{label:`Captured coordinate`,floating:!0,value:m??``,options:p,onChange:e=>{c(e),u(1)}})]})]}),n,(0,$.jsxs)(`p`,{children:[g?.generatedTokenIds.length??0,` generated tokens · `,g?.forwardTokenWork??0,` `,`forward-token work. Token IDs are retained against the exact tokenizer; no semantic feature labels are inferred.`]}),(0,$.jsx)(ft,{title:`Generated token comparison`,children:(0,$.jsx)(`div`,{className:`evaluation-table-scroll`,children:(0,$.jsxs)(`table`,{className:`training-data-table evaluation-workspace-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Variant`}),(0,$.jsx)(`th`,{children:`Generated token IDs`})]})}),(0,$.jsx)(`tbody`,{children:e.variants.map(e=>{let n=t.outcomes.find(t=>t.promptId===d&&t.variantId===e.id);return(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.profile?e.id:`${e.id} · Off`}),(0,$.jsx)(`td`,{children:(0,$.jsx)(`code`,{children:n?.generatedTokenIds.join(` `)||`—`})})]},e.id)})})]})})}),(0,$.jsxs)(ft,{title:`Activation values`,children:[(0,$.jsx)(`p`,{children:`Before and after values are inputs to down_proj for the selected variant. Token indices exclude prompt padding.`}),(0,$.jsx)(`div`,{className:`evaluation-table-scroll evaluation-table-frame`,children:(0,$.jsxs)(`table`,{className:`training-data-table evaluation-workspace-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Token index`}),(0,$.jsx)(`th`,{children:`Token ID`}),(0,$.jsx)(`th`,{children:`Before`}),(0,$.jsx)(`th`,{children:`After`}),(0,$.jsx)(`th`,{children:`Delta`})]})}),(0,$.jsx)(`tbody`,{children:h.slice((_-1)*10,_*10).map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.tokenIndex}),(0,$.jsx)(`td`,{children:e.tokenId}),(0,$.jsx)(`td`,{children:e.before.toPrecision(7)}),(0,$.jsx)(`td`,{children:e.after.toPrecision(7)}),(0,$.jsx)(`td`,{children:Number.isFinite(e.after-e.before)?(e.after-e.before).toPrecision(7):`Outside numeric range`})]},e.tokenIndex))})]})}),(0,$.jsx)(yS,{page:_,total:h.length,onChange:u})]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact configuration and evidence`}),(0,$.jsx)(`pre`,{children:JSON.stringify({model:e.model,variant:e.variants.find(e=>e.id===f),prompt:e.prompts.find(e=>e.id===d),outcome:g},null,2)})]})]})}function CS({owner:e,api:t}){let n=e.execution,r=e.original,i=(e.receipt&&(!n||e.receipt.execution.id===n.id&&e.receipt.execution.revision>n.revision)?e.receipt.execution:n)??(r&&`execution`in r.intent?r.intent.execution:null),[a,o]=(0,Q.useState)(null),s=r?`action`in r.command?r.command.action:`prepare`:null;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(X,{error:e.error}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:e.busy||e.loading,onClick:e.refresh,children:`Refresh execution and recovery`}),r?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:e.busy||!e.recoveryReady,onClick:()=>void e.retry(),children:e.busy?`Reconciling…`:`Retry original ${s}`}):null]}),r&&!(`action`in r.command)?(0,$.jsxs)(ft,{title:`Original preparation`,children:[(0,$.jsxs)(`p`,{children:[r.command.name,` · `,r.command.method,` · `,Uy(r.command.maximumSpendUsd)]}),(0,$.jsxs)(`p`,{children:[r.command.request.prompts.length,` prompts ·`,` `,r.command.request.variants.length,` variants ·`,` `,r.command.request.model.modelId,` · `,r.command.request.model.revision]})]}):null,i?(0,$.jsxs)(ft,{title:`Hosted execution`,children:[(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`State`}),(0,$.jsx)(`dd`,{children:i.phase}),(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(i.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:i.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Execution`}),(0,$.jsx)(`dd`,{children:i.id}),(0,$.jsx)(`dt`,{children:`Preparation expires`}),(0,$.jsx)(`dd`,{children:new Date(i.plan.expiresAt).toLocaleString()}),(0,$.jsx)(`dt`,{children:`Exact plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:i.plan.contentHash})]}),n?(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[n.phase===`prepared`?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:e.busy||e.loading||!e.ready||!e.canControl||!!r||Date.parse(n.plan.expiresAt)<=Date.now(),onClick:()=>o({action:`start`,value:n}),children:`Review Start`}):null,[`completed`,`cancelled`,`failed`].includes(n.phase)?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:e.busy||e.loading||!e.ready||!e.canControl||!!r,onClick:()=>o({action:`cancel`,value:n}),children:`Review Cancel`})]}):null]}):null,n?.result?(0,$.jsx)(SS,{request:n.request,result:n.result,trainingAction:(0,$.jsx)(oS,{execution:n,api:t,disabled:e.busy||e.loading||!!r},n.result.contentHash)}):i?.phase===`completed`?(0,$.jsx)(`p`,{children:`No result bytes are available in this read. Retained execution identity remains available for recovery.`}):null,e.selectedId?(0,$.jsx)(uS,{api:t,id:e.selectedId,execution:n,disabled:e.busy||!!r},`${t.key}:${e.selectedId}`):null,a&&n?(0,$.jsxs)(qa,{ariaLabel:a.action===`start`?`Start activation experiment`:`Cancel activation experiment`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:e.busy,onClose:()=>{e.busy||o(null)},children:[(0,$.jsx)(`h2`,{children:a.action===`start`?`Start activation experiment`:`Cancel activation experiment`}),(0,$.jsx)(`p`,{children:a.action===`start`?Gy(a.value.plan.computePrice):`Cancel this exact execution. In-flight work may need to stop and settle before capacity is released.`}),(0,$.jsxs)(`dl`,{className:`evaluation-workspace-meta`,children:[(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:Uy(a.value.plan.maximumSpendUsd)}),(0,$.jsx)(Wy,{price:a.value.plan.computePrice}),(0,$.jsx)(`dt`,{children:`Prompts`}),(0,$.jsx)(`dd`,{children:a.value.request.prompts.length}),(0,$.jsx)(`dt`,{children:`Variants`}),(0,$.jsx)(`dd`,{children:a.value.request.variants.length}),(0,$.jsx)(`dt`,{children:`Model`}),(0,$.jsxs)(`dd`,{children:[a.value.request.model.modelId,` · `,a.value.request.model.revision]}),(0,$.jsx)(`dt`,{children:`Plan`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:a.value.plan.contentHash})]}),(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:e.busy,onClick:()=>o(null),children:`Close`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:e.busy||e.loading||!!r||!e.ready||!e.canControl,onClick:()=>void e.control(a.action,a.value).then(e=>{e&&o(null)}),children:e.busy?`Applying…`:a.action===`start`?Ky(a.value.plan.maximumSpendUsd):`Cancel execution`})]})]}):null]})}function wS(){return{baseModel:null,prompts:[{id:crypto.randomUUID(),text:``}],coordinates:[{id:crypto.randomUUID(),layer:``,neuron:``,dose:`1`}],doseMultipliers:`-1, 0, 1`,normalization:{mode:`baseline_prompt_residual_median`,statistic:`midpoint_median_fp32`,sample:`non_padding_prompt_after_position_zero`},tokenScope:{phase:`prompt_and_decode`,positions:`all_non_padding`},maxNewTokens:`32`,maximumCapturedValues:`65536`,maximumForwardTokenWork:`1000000`,maximumDurationSeconds:`300`,maximumSpendUsd:``}}function TS({api:e,method:t,visible:n,onClose:r,onSaveDraft:i}){let a=kv(),o=a.initialExperiment?.operationType===t?a.initialExperiment:null,[s,c]=(0,Q.useState)(()=>o?.activationForm??wS()),[l,u]=(0,Q.useState)(o?.name??Tr(t)),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(null),h=Ry(e,n,null),g=Yx(e,a.startingModel?.source===`trained`||a.startingModel?.source===`engram`?null:a.trainingBaseModel,n),_=g.current?.methods.find(e=>e.method===t)?.execution,v=eS(e,{draftId:a.initialExperiment?.id??null,method:t,visible:n}),y=v.selectedId&&![`completed`,`failed`,`cancelled`].includes(v.execution?.phase??v.receipt?.execution.phase??`prepared`),b=d||v.busy,x=b||!!v.original||!!y,S=J({...s,baseModel:a.trainingBaseModel,name:l,startingModel:a.startingModel}),C=(0,Q.useRef)(S),w=(0,Q.useRef)(!1),T=J([e.key,e.connection.serverUrl,e.actorId,a.initialExperiment?.id]),E=(0,Q.useRef)(T);(0,Q.useEffect)(()=>(E.current=T,()=>{E.current=`unmounted`}),[T]);let D=S!==C.current,O=a.reportOperationDraftDirty;(0,Q.useEffect)(()=>{O(t,D)},[O,t,D]);let k=iy({name:`experiment setup`,dirty:D||a.operationDraftDirty||a.evaluationDirty,busy:b,onLeave:r,retainForDestination(t){let n=po(new URL(t,window.location.origin));return!(!n||![`datasets`,`graders`,`experiments`].includes(n.page)||n.collection===`drafts`&&n.resourceId!==a.initialExperiment?.id||(n.projectId??null)!==e.projectId)}});My(k,n);let A=e=>c(t=>({...t,...e})),j=a.startingModel?.source===`engram`?`engram:${a.startingModel.engram.versionHash}`:a.startingModel?.source===`steering`?`steering:${a.startingModel.steering.versionHash}`:a.startingModel?.source===`trained`?`trained:${a.startingModel.trainedVersion.contentHash}`:a.trainingBaseModel?J(a.trainingBaseModel):``,M=h.models.map(e=>({value:J(e.preference),label:e.name})),N=t===`neuron_steering`?[`layer`,`neuron`,`dose`]:[`layer`,`neuron`];j&&!M.some(e=>e.value===j)&&M.unshift({value:j,label:a.startingModel?.label??a.trainingBaseModel.modelId});function P(){if(!a.initialExperiment)throw Error(`Open the experiment before saving.`);return Kn.parse({schemaVersion:`openpond.experimentDraft.v1`,id:a.initialExperiment.id,operationType:t,name:l.trim()||Tr(t),...a.startingModel?{startingModel:a.startingModel}:{},activationForm:{...s,baseModel:a.trainingBaseModel,maximumSpendUsd:s.maximumSpendUsd??``}})}async function F(e){if(!i)throw Error(`Load canonical draft storage before preparing.`);if(await i(e),E.current!==T)throw Error(`Return to the original experiment account before continuing.`);C.current=S}async function I(){m(null);try{await v.prepare(P(),F)}catch(e){m(e)}}async function L(){if(i&&a.initialExperiment&&!w.current){w.current=!0,f(!0),m(null);try{if(await F(P()),E.current!==T)return;C.current=S}catch(e){E.current===T&&m(e)}finally{w.current=!1,E.current===T&&f(!1)}}}return(0,$.jsxs)(Bv,{label:`Experiment setup`,action:`experiment`,onRequestClose:()=>void k.requestLeave(r),children:[(0,$.jsxs)(`header`,{children:[(0,$.jsx)(`h2`,{children:`Run Experiment`}),(0,$.jsx)(`button`,{type:`button`,disabled:b,onClick:()=>void k.requestLeave(r),children:`Close setup`})]}),(0,$.jsxs)(`form`,{noValidate:!0,onSubmit:e=>{e.preventDefault(),L()},children:[(0,$.jsx)(ft,{title:`Starting model`,children:(0,$.jsxs)(`fieldset`,{disabled:x,children:[(0,$.jsxs)(`label`,{children:[`Model`,(0,$.jsx)(Z,{label:`Starting model`,floating:!0,searchable:!0,value:j,disabled:h.isPending&&!j,options:[{value:``,label:h.isPending?`Loading models…`:h.isSuccess&&!M.length?`No catalog models available`:`Choose model`,disabled:h.isPending||h.isSuccess&&!M.length},...M],onChange:e=>{if(e===j)return;let t=h.models.find(t=>J(t.preference)===e);e&&!t?m(`Refresh the model list before changing this selection.`):(a.setTrainingBaseModel(t?.preference??null),c(({startingProfile:e,...t})=>t))}})]}),(0,$.jsx)(xy,{disabled:x}),(0,$.jsx)(`p`,{children:`Run compiles and prepares this exact saved configuration. Review the immutable plan before explicitly starting paid execution.`}),_?(0,$.jsx)(`p`,{children:_.state===`unavailable`?_.reason:`A compatible activation runtime is available. Preparation rechecks its exact identity.`}):null,g.isFetching?(0,$.jsx)(`span`,{role:`status`,children:`Checking runtime…`}):null]})}),(0,$.jsx)(ft,{title:`Prompts`,children:(0,$.jsxs)(`fieldset`,{disabled:x,children:[s.prompts.map((e,t)=>(0,$.jsxs)(`fieldset`,{children:[(0,$.jsxs)(`label`,{children:[`Prompt `,t+1,(0,$.jsx)(`textarea`,{rows:3,value:e.text,maxLength:16e3,onChange:t=>A({prompts:s.prompts.map(n=>n.id===e.id?{...n,text:t.target.value}:n)})})]}),(0,$.jsxs)(`button`,{type:`button`,className:`training-text-button`,onClick:()=>A({prompts:s.prompts.filter(t=>t.id!==e.id)}),children:[`Remove prompt `,t+1]})]},e.id)),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:s.prompts.length>=8,onClick:()=>A({prompts:[...s.prompts,{id:crypto.randomUUID(),text:``}]}),children:`Add prompt`})]})}),(0,$.jsx)(ft,{title:t===`neuron_steering`?`Steering coordinates`:`Capture coordinates`,children:(0,$.jsxs)(`fieldset`,{disabled:x,children:[(0,$.jsxs)(`p`,{children:[`Layer and neuron indices start at zero.`,t===`neuron_steering`?` Strength adds to the activation entering down_proj; weights stay unchanged.`:` Inspection records selected activations without changing weights.`]}),s.coordinates.map((e,t)=>(0,$.jsxs)(`fieldset`,{children:[(0,$.jsxs)(`legend`,{children:[`Coordinate `,t+1]}),(0,$.jsx)(`div`,{className:`activation-coordinate-fields`,children:N.map(n=>(0,$.jsxs)(`label`,{children:[n===`dose`?`Strength`:n===`layer`?`Layer`:`Neuron`,(0,$.jsx)(`input`,{"aria-label":`${n===`dose`?`Strength`:n===`layer`?`Layer`:`Neuron`} ${t+1}`,inputMode:n===`dose`?`decimal`:`numeric`,value:e[n],maxLength:100,onChange:t=>A({coordinates:s.coordinates.map(r=>r.id===e.id?{...r,[n]:t.target.value}:r)})})]},n))}),(0,$.jsxs)(`button`,{type:`button`,className:`training-text-button`,onClick:()=>A({coordinates:s.coordinates.filter(t=>t.id!==e.id)}),children:[`Remove coordinate `,t+1]})]},e.id)),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:s.coordinates.length>=64,onClick:()=>A({coordinates:[...s.coordinates,{id:crypto.randomUUID(),layer:``,neuron:``,dose:`1`}]}),children:`Add coordinate`}),t===`neuron_steering`?(0,$.jsxs)(`label`,{children:[`Dose multipliers`,(0,$.jsx)(`input`,{value:s.doseMultipliers,maxLength:1e3,onChange:e=>A({doseMultipliers:e.target.value})}),(0,$.jsx)(`small`,{children:`Comma-separated multipliers for the configured strengths. The comparison includes an unsteered baseline.`})]}):null]})}),(0,$.jsx)(ft,{title:`Advanced`,children:(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Capture and generation settings`}),(0,$.jsxs)(`fieldset`,{disabled:x,children:[t===`neuron_steering`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[`Apply during`,(0,$.jsx)(Z,{label:`Apply during`,floating:!0,value:s.tokenScope.phase,options:[{value:`prompt_and_decode`,label:`Prompt and generation`},{value:`prompt_only`,label:`Prompt only`},{value:`decode_only`,label:`Generation only`}],onChange:e=>A({tokenScope:{...s.tokenScope,phase:e}})})]}),(0,$.jsxs)(`label`,{children:[`Token positions`,(0,$.jsx)(Z,{label:`Token positions`,floating:!0,value:s.tokenScope.positions,options:[{value:`all_non_padding`,label:`All non-padding tokens`},{value:`after_position_zero`,label:`After the first token`}],onChange:e=>A({tokenScope:{...s.tokenScope,positions:e}})})]}),(0,$.jsx)(`p`,{children:s.normalization.mode===`baseline_prompt_residual_median`?`Normalization uses a separate unsteered prompt pass and its frozen FP32 midpoint residual median.`:`Fixed calibration retained: ${s.normalization.calibration.id} · r${s.normalization.calibration.revision}`})]}):null,[[`maxNewTokens`,`Maximum generated tokens`],[`maximumCapturedValues`,`Maximum captured values`],[`maximumForwardTokenWork`,`Maximum forward-token work`],[`maximumDurationSeconds`,`Maximum seconds`]].map(([e,t])=>(0,$.jsxs)(`label`,{children:[t,(0,$.jsx)(`input`,{inputMode:`numeric`,value:s[e],maxLength:100,onChange:t=>A({[e]:t.target.value})})]},e))]})]})}),(0,$.jsxs)(`label`,{children:[`Name`,(0,$.jsx)(`input`,{value:l,maxLength:500,disabled:x,onChange:e=>u(e.target.value)})]}),(0,$.jsxs)(`label`,{children:[`Spending limit (USD, optional)`,(0,$.jsx)(`input`,{inputMode:`decimal`,placeholder:`Use available credits`,value:s.maximumSpendUsd??``,maxLength:100,disabled:x,onChange:e=>A({maximumSpendUsd:e.target.value})})]}),(0,$.jsx)(X,{error:p??h.error??g.error}),h.error?(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,onClick:()=>void h.refetch(),children:`Retry model list`}):null,g.canRefresh?(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,disabled:g.isFetching,onClick:()=>void g.refetch(),children:`Refresh runtime availability`}):null,(0,$.jsx)(`button`,{type:`submit`,className:`training-button secondary`,disabled:x||!i,children:b?`Saving…`:`Save draft`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button`,disabled:x||!i||!v.ready||_?.state!==`ready`||a.startingModel?.source===`trained`,onClick:()=>void I(),children:`Run`})]}),(0,$.jsx)(CS,{api:e,owner:v}),k.dialog]})}function ES(e){let t=kv(),n=u(),r=Ga(),i=(0,Q.useRef)(t.storedRecord),a=(0,Q.useRef)(null),o=(0,Q.useRef)(!1),s=J([e.connection.serverUrl,e.accountKey,e.actorId,e.teamId,e.projectId,t.initialExperiment?.id]),c=(0,Q.useRef)(s);return(0,Q.useEffect)(()=>(c.current=s,()=>{c.current=`unmounted`}),[s]),async l=>{if(t.initialExperiment?.hostedEvaluationForm)throw Error(`Open this saved evaluation in its hosted editor to preserve its native settings.`);if(o.current)throw Error(`This experiment draft is already saving.`);if(!e.actorId||l.id!==t.initialExperiment?.id)throw Error(`Reopen this experiment in the current account before saving.`);o.current=!0;let u=()=>{if(c.current!==s)throw Error(`The active experiment or account changed.`)},d=Iy(e);try{if(u(),a.current){let e=await d.save(a.current);u(),i.current=e.record,a.current=null}if(!i.current||J(i.current.draft)!==J(l)){a.current={schemaVersion:`openpond.experimentDraftSave.v1`,teamId:e.teamId,operationId:crypto.randomUUID(),expectedRevision:i.current?.revision??0,projectId:i.current?.projectId??e.projectId,draft:l};let t=await d.save(a.current);u(),i.current=t.record,a.current=null}let o=await d.get(l.id);if(u(),o.contentHash!==i.current.contentHash)throw Error(`This draft changed elsewhere. Your edits are retained here. Reopen the saved draft to load its current revision.`);return t.acceptSaved(o),n.invalidateQueries({queryKey:[`unified-experiments`]}),r?.(`Experiment draft saved.`,`success`),o}finally{o.current=!1}}}function DS(e){let t=kv(),n=(0,Q.useMemo)(()=>nS(e.api,`hosted`),[e.api]),r=ES(e.api),i=e.onSaveDraft??(e.dispatch?void 0:r);return t.initialExperiment?.hostedEvaluationForm?(0,$.jsxs)(Bv,{label:`Experiment`,action:`experiment`,onRequestClose:()=>{t.close(),e.onClose?.()},children:[(0,$.jsx)(X,{error:`Open this saved evaluation in its hosted editor to preserve its native settings.`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>{t.close(),e.onClose?.()},children:`Close editor`})]}):t.advancedTarget?(0,$.jsx)(gx,{api:e.api,target:t.advancedTarget,onClose:()=>{t.close(),e.onClose?.()},onOpenRun:e.onAdvancedRun}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Q.Activity,{mode:t.operationType===`evaluate`?`visible`:`hidden`,children:(0,$.jsx)(Ny,{...e,onSaveDraft:i})}),[`sft`,`grpo`].map(n=>(0,$.jsx)(Q.Activity,{mode:t.operationType===n?`visible`:`hidden`,children:(0,$.jsx)(Jx,{api:e.api,method:n,visible:t.operationType===n,onStarted:e.onTrainingStarted,navigate:e.navigate,onSaveDraft:i,onClose:()=>{t.close(),e.onClose?.()}},JSON.stringify([e.api.key,ra(e.api.connection),t.initialExperiment?.id,n]))},n)),(0,$.jsx)(Q.Activity,{mode:t.operationType===`alphaedit`?`visible`:`hidden`,children:(0,$.jsx)(Ab,{api:n,visible:t.operationType===`alphaedit`,onSaveDraft:i,onClose:()=>{t.close(),e.onClose?.()}},`${n.key}:${t.initialExperiment?.id}:alphaedit`)}),(0,$.jsx)(Q.Activity,{mode:t.operationType===`selective_neuron_training`?`visible`:`hidden`,children:(0,$.jsx)(Wb,{api:n,visible:t.operationType===`selective_neuron_training`,onSaveDraft:i,onClose:()=>{t.close(),e.onClose?.()}},`${n.key}:${t.initialExperiment?.id}:neuron-training`)}),(0,$.jsx)(Q.Activity,{mode:t.operationType===`decision_model`?`visible`:`hidden`,children:(0,$.jsx)($b,{api:n,visible:t.operationType===`decision_model`,onSaveDraft:i,onClose:()=>{t.close(),e.onClose?.()}},`${n.key}:${t.initialExperiment?.id}:decision`)}),(0,$.jsx)(Q.Activity,{mode:t.operationType===`engram_adapter`?`visible`:`hidden`,children:(0,$.jsx)(px,{api:n,visible:t.operationType===`engram_adapter`,onSaveDraft:i,onClose:()=>{t.close(),e.onClose?.()}},`${n.key}:${t.initialExperiment?.id}:engram`)}),[`neuron_steering`,`inspect_activations`].map(r=>(0,$.jsx)(Q.Activity,{mode:t.operationType===r?`visible`:`hidden`,children:(0,$.jsx)(TS,{api:n,method:r,visible:t.operationType===r,onSaveDraft:i,onClose:()=>{t.close(),e.onClose?.()}},`${n.key}:${t.initialExperiment?.id}:${r}`)},r))]})}function OS({connection:e,context:t,onClose:n}){let r=(0,Q.useContext)(E),i=t.selection?.draft,a=t.selection?.storedDraft,o=i?.evaluationForm?.executionLocation??(i?.operationType===`evaluate`?`local`:`hosted`),s=(0,Q.useMemo)(()=>r?.teamId&&r.actorId?tS(e,{...r,teamId:r.teamId,actorId:r.actorId,projectId:a?.projectId??null,executionLocation:o}):null,[e,r?.accountKey,r?.teamId,r?.actorId,a?.projectId,o]);return i?i.hostedEvaluationForm?(0,$.jsxs)(`div`,{className:`chat-experiment-tool-content`,children:[(0,$.jsx)(X,{error:`Open this saved evaluation in its hosted editor to preserve its native settings.`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:n,children:`Close editor`})]}):s?(0,$.jsx)(Ov,{initialExperiment:i,initialRecord:a,onNewDraft:async e=>{if(!await t.select({kind:`experiment`,id:e.id,location:`local`,draft:e},{newExperiment:!0}))throw Error(`The new experiment could not be selected. Your original editor remains available.`)},children:(0,$.jsx)(kS,{api:s,context:t,onClose:n})},`${s.key}:${i.id}`):(0,$.jsx)(`div`,{className:`chat-experiment-tool-content`,children:(0,$.jsx)(`p`,{children:`Select an OpenPond workspace to configure this experiment.`})}):null}function kS({api:e,context:t,onClose:n}){let r=kv(),i=(0,Q.useRef)(t.selection?.storedDraft??null),[a,o]=(0,Q.useState)(null),s=S({queryKey:[`evaluation-workspace`,e.key,`chat-inventory`],queryFn:({signal:t})=>e.request(`inventory`,{},t)}),c=e=>{wo({...e,area:`console`})};return(0,$.jsxs)(Mv.Provider,{value:a,children:[(0,$.jsx)(`div`,{ref:o,className:`evaluation-workspace-panel chat-experiment-editor`}),s.error?(0,$.jsx)(X,{error:s.error,children:(0,$.jsx)(`button`,{type:`button`,className:`training-text-button`,onClick:()=>void s.refetch(),children:`Retry workspace`})}):null,(0,$.jsx)(DS,{api:e,inventory:s.data??null,route:as(`experiments`,null,{projectId:e.projectId,executionLocation:e.location}),navigate:c,onClose:n,onTrainingStarted:async n=>{let i=s.data??await e.request(`inventory`);if(i.teamId!==e.teamId||!r.initialExperiment)throw Error(`The originating workspace changed.`);await t.associateTraining(n,i.apiOrigin,r.initialExperiment.id)},onSaveDraft:async e=>{let n=await t.saveDraft(e,i.current);return n.storedDraft&&(i.current=n.storedDraft,r.acceptSaved(n.storedDraft)),n},onSaved:({id:t})=>c(as(`experiments`,null,{resourceId:t,projectId:e.projectId,executionLocation:e.location,detailTab:`overview`}))},r.initialExperiment?.id)]})}var AS=`training-result-save`;function jS(e,t){let n=u(),r=JSON.stringify([e.key,ra(e.connection),t.job.id]),i=(0,Q.useRef)(r);i.current=r;let a=(0,Q.useRef)(!0),o=(0,Q.useRef)(!1),s=(0,Q.useRef)(null),[c,l]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(null);(0,Q.useEffect)(()=>(a.current=!0,()=>{a.current=!1}),[]);let _=()=>a.current&&i.current===r,v=S({queryKey:[`training-model-save-recovery`,r],queryFn:async({signal:n})=>{let r,i=[],a=new Set;for(let o=0;;o++){if(o>=100)throw Error(`The retained save catalog exceeds its supported bound.`);let s=await e.pendingOperations(AS,r,n);for(let n of s.items){let r=On.parse(n.reviewedIntent);if(r.jobId!==t.job.id)continue;if(r.teamId!==e.teamId)throw Error(`The retained Model save belongs to another workspace.`);let{jobId:a,...o}=r,s=n.command?mr.parse(n.command):mr.parse({jobId:a,request:{...o,operationId:n.id}});i.push({command:s,operation:e.recoverOperation(n)})}if(!s.nextCursor)break;if(a.has(s.nextCursor))throw Error(`The retained save catalog repeated a page.`);a.add(s.nextCursor),r=s.nextCursor}if(i.length>1)throw Error(`More than one Model save is retained for this run. Resolve the original commands before creating another save.`);return i[0]??null},staleTime:0,gcTime:0,retry:!1}),y=c??v.data??null;async function b(r){if(o.current||h||!v.isSuccess)return null;o.current=!0,f(!0),m(null);let i=!1;try{if(!e.actorId)throw Error(`Choose an authenticated account before saving a Model.`);if(!y&&!r.trim())throw Error(`Enter a Model name.`);if(!s.current){if(y)s.current=y;else{if(!t.model||!t.request||!t.candidate)throw Error(`Refresh the completed result before saving its Model.`);let n=On.parse({schemaVersion:`openpond.trainingResultSave.v1`,jobId:t.job.id,teamId:e.teamId,name:r,expectedModelRevision:t.model.revision,submissionHash:t.request.submissionHash,artifact:t.candidate.artifact,checkpointId:t.candidate.checkpointId}),i=await e.operation(AS,n);if(!_())return null;let{jobId:a,...o}=n;s.current={operation:i,command:mr.parse({jobId:a,request:{...o,operationId:i.id}})}}l(s.current)}let a=s.current;if(await a.operation.retainCommand(a.command,`dispatching`),!_())return null;i=!0;let o=await Tt(await Y(e.connection,`/v1/training/hosted-jobs/${encodeURIComponent(a.command.jobId)}/model?teamId=${encodeURIComponent(e.teamId)}`,{method:`POST`,body:JSON.stringify(a.command.request)}),{jobId:t.job.id,request:a.command.request,actorId:e.actorId});if(!_())return null;g(o),n.invalidateQueries({queryKey:[`hosted-training-result`]}),n.invalidateQueries({queryKey:[`saved-training-model`]});try{await a.operation.acknowledge()}catch(e){return _()&&m(e),{receipt:o,acknowledgementError:e}}return{receipt:o,acknowledgementError:null}}catch(e){if(_()&&(m(e),i&&e instanceof Ti&&[400,403,404,409,422].includes(e.status)&&s.current))try{await s.current.operation.acknowledge(),_()&&(s.current=null,l(null),await v.refetch())}catch(e){_()&&m(e)}return null}finally{o.current=!1,_()&&f(!1)}}return{save:b,busy:d,receipt:h,retained:y,error:p??v.error,recoveryReady:v.isSuccess,refreshRecovery:v.refetch}}function MS({api:e,result:t,onClose:n,onSaved:r}){let[i,a]=(0,Q.useState)(t.model?.name??t.name),o=jS(e,t),s=o.retained?.command.request,c=iy({name:`Model save`,busy:o.busy,dirty:!o.receipt&&(!!s||i!==(t.model?.name??t.name)),discardDescription:s?`The original save request stays in recovery. Reopening this result lets you retry that same request.`:void 0});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(qa,{ariaLabel:`Save model`,className:`labs-rename-dialog`,backdropClassName:`labs-rename-backdrop`,dismissDisabled:o.busy,onClose:()=>void c.requestLeave(n),children:[(0,$.jsx)(`h2`,{children:`Save model`}),(0,$.jsxs)(`p`,{children:[`Save this checkpoint as a version of `,t.model?.name??t.name,`.`]}),(0,$.jsx)(X,{error:o.error}),(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),o.save(i).then(e=>{e&&(c.allowNextNavigation(),r(e.receipt,e.acknowledgementError))})},children:[(0,$.jsxs)(`label`,{className:`model-build-field`,children:[(0,$.jsx)(`span`,{children:`Model name`}),(0,$.jsx)(`input`,{"data-autofocus":!0,maxLength:200,value:s?.name??i,disabled:o.busy||!o.recoveryReady||!!s,onChange:e=>a(e.target.value)})]}),s?(0,$.jsx)(`p`,{children:`Original save request retained.`}):null,(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:o.busy,onClick:()=>void c.requestLeave(n),children:`Cancel`}),o.recoveryReady?null:(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void o.refreshRecovery(),children:`Reload retained saves`}),(0,$.jsx)(`button`,{className:`training-button`,type:`submit`,disabled:o.busy||!o.recoveryReady,children:o.busy?`Saving…`:s?`Retry original save`:`Save model`})]})]})]}),c.dialog]})}var NS={not_finished:`Training has not produced a completed result yet.`,request_unavailable:`The original training request is unavailable for this run.`,qualification_only:`This run collected qualification evidence without training weights.`,not_model_training:`This run has no policy-model checkpoint.`,cleanup_pending:`Waiting for terminal cleanup evidence.`,artifact_pending:`Waiting for the final checkpoint publication.`,retained:`Final checkpoint retained.`},PS={base:`Standalone adapter`,residual_append:`Stacked adapter`,shared:`Shared adapter`,sequential_merge:`Sequential merge`};function FS({connection:e,teamId:t,actorId:n,jobId:r,version:i,api:a,onOpenModel:o}){let[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(null),h=S({queryKey:[`hosted-training-result`,a.key,ra(e),t,n,r,i],queryFn:async({signal:n})=>tn(await Y(e,`/v1/training/hosted-jobs/${encodeURIComponent(r)}/result?teamId=${encodeURIComponent(t)}`,{signal:n}),{teamId:t,jobId:r}),staleTime:3e4,gcTime:3e5}),g=h.data,_=g?.request,v=g?.candidate,y=g?.outputs.receipt,b=g?.model&&(!d||g.model.revision>=d.model.revision)?g.model.name:d?.model.name??`Model`;return(0,$.jsxs)(`section`,{className:`training-result-details`,"aria-label":`Model result`,children:[(0,$.jsxs)(`div`,{className:`training-result-heading`,children:[(0,$.jsx)(`h3`,{children:`Model result`}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:h.isFetching,onClick:()=>void h.refetch(),children:`Refresh result`})]}),(0,$.jsx)(X,{error:p??h.error}),h.isPending?(0,$.jsx)(`p`,{role:`status`,children:`Loading model result…`}):null,g?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:NS[g.candidateState]}),d||g.savedVersion?(0,$.jsxs)(`div`,{className:`model-build-actions`,children:[(0,$.jsxs)(`span`,{children:[`Saved to `,b,`.`]}),o?(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,disabled:l,onClick:()=>{let e=d?.model.id??g.model?.id;e&&o&&(u(!0),m(null),o(e).catch(m).finally(()=>u(!1)))},children:l?`Opening…`:`View model`}):null,(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>c(!0),children:`Review save`})]}):v&&g.model?(0,$.jsx)(`button`,{type:`button`,className:`training-button`,onClick:()=>c(!0),children:`Save model`}):null,_?(0,$.jsxs)(`dl`,{className:`model-project-page-metrics`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Base model`}),(0,$.jsx)(`dd`,{children:_.baseModel.modelId}),(0,$.jsx)(`small`,{children:_.baseModel.revision})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Method`}),(0,$.jsx)(`dd`,{children:String(_.recipe.method??`Training`)})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Configuration revision`}),(0,$.jsx)(`dd`,{children:_.source.modelProject.revision})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Dataset`}),(0,$.jsx)(`dd`,{children:_.source.taskset.id}),(0,$.jsxs)(`small`,{children:[`Revision `,_.source.taskset.revision]})]}),v?(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Composition`}),(0,$.jsx)(`dd`,{children:PS[v.composition]})]}):null,y?(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Cleanup`}),(0,$.jsx)(`dd`,{children:y.cleanupComplete?`Complete`:`Pending`})]}):null]}):null,v?(0,$.jsxs)(`p`,{children:[`Checkpoint `,(0,$.jsx)(`code`,{children:v.checkpointId}),v.parent?(0,$.jsxs)($.Fragment,{children:[` · Parent run `,(0,$.jsx)(`code`,{children:v.parent.jobId})]}):null]}):null,(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{children:`Exact settings and references`}),(0,$.jsx)(`pre`,{children:JSON.stringify({request:_,candidate:v,executionReceipt:y?{id:y.id,runtimeRelease:y.runtimeRelease,spendUsd:y.spendUsd,durationSeconds:y.durationSeconds}:null},null,2)})]})]}):null,s&&g?(0,$.jsx)(MS,{api:a,result:g,onClose:()=>c(!1),onSaved:(e,t)=>{f(e),m(t),c(!1),h.refetch()}}):null]})}function IS({connection:e,training:t}){let n=(0,Q.useContext)(D),{teamId:r,actorId:i}=t.owner,a=(0,Q.useMemo)(()=>tS(e,{teamId:r,actorId:i,accountKey:n,projectId:null}),[e,r,i,n]);return(0,$.jsx)(FS,{connection:e,teamId:r,actorId:i,jobId:t.jobId,version:t.job.version,api:a},`${a.key}:${t.apiOrigin}:${t.jobId}`)}function LS({connection:e,sessionId:t,events:n}){let r=k(e,t),i=Xd(r.selection?.resource||r.selection?.draft?e:null,t),[a,o]=(0,Q.useState)(null),s=r.selection,c=s?.training,[l,u]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{u(!1)},[s?.draft?.id]);let d=s?.draft?.startingModel?.baseModel??s?.draft?.alphaEditForm?.baseModel??s?.draft?.neuronTrainingForm?.baseModel??s?.draft?.decisionForm?.baseModel??s?.draft?.engramForm?.baseModel??s?.draft?.activationForm?.baseModel??(s?.draft?.trainingForm?s.draft.trainingForm.baseModel:s?.draft?.training?.baseModel),f=s?.draft?.alphaEditForm?Number(s.draft.alphaEditForm.maximumSpendUsd):s?.draft?.neuronTrainingForm?Number(s.draft.neuronTrainingForm.maximumSpendUsd):s?.draft?.decisionForm?Number(s.draft.decisionForm.maximumSpendUsd):s?.draft?.engramForm?Number(s.draft.engramForm.maximumSpendUsd):s?.draft?.activationForm?Number(s.draft.activationForm.maximumSpendUsd):s?.draft?.trainingForm?Number(s.draft.trainingForm.budget):s?.draft?.training?.maximumSpendUsd,p=s?.draft?.trainingForm?.billingMode===`actual_usage`?{cap:s.draft.trainingForm.customerCapUsd?.trim()??``,planning:s.draft.trainingForm.budget}:s?.draft?.training?.usageFunding?{cap:s.draft.training.usageFunding.customerCapUsd??``,planning:String(s.draft.training.maximumSpendUsd)}:null,m=s?.resource?.kind===`experiment`?s.resource:null,h=m?i.focus.experiment:i.focus.dataset,g=!!(s?.resource&&h&&cf(s.resource)===cf(h)&&s.resource.revision===h.revision),{select:_}=r,v=c?JSON.stringify(s.target):``,y=(r.runs.data?.runs??[]).map(e=>({value:JSON.stringify(e.target),label:e.label,description:e.detail}));c&&!y.some(e=>e.value===v)&&y.unshift({value:v,label:`${(c.location===`cloud`?c.job.createdAt:c.updatedAt).slice(0,16).replace(`T`,` `)} UTC`,description:c.location===`cloud`?c.job.state:c.executionState});async function b(e){try{o(null),await _(JSON.parse(e))}catch(e){o(String(e))}}let x=s?.resource?{...i,focus:{...i.focus,dataset:s.dataset??(s.resource.kind===`dataset`?s.resource:null),experiment:m},scope:g&&m||s.target.scopeId===i.scope?.id?i.scope:null,graders:s.graders??[]}:i;return(0,$.jsxs)(`div`,{className:`chat-experiment-tool`,children:[(0,$.jsx)(`header`,{className:`chat-experiment-tool-header`,children:(0,$.jsx)(Qd,{context:r})}),(0,$.jsx)(X,{error:a}),s?.alphaEditResult?.result?(0,$.jsxs)(`div`,{className:`chat-experiment-tool-content`,children:[(0,$.jsx)(`h2`,{children:s.label}),(0,$.jsx)(t_,{result:s.alphaEditResult.result})]}):s?.neuronTrainingResult?.result?(0,$.jsxs)(`div`,{className:`chat-experiment-tool-content`,children:[(0,$.jsx)(`h2`,{children:s.label}),(0,$.jsx)(t_,{result:s.neuronTrainingResult.result})]}):s?.decisionResult?.result?(0,$.jsxs)(`div`,{className:`chat-experiment-tool-content`,children:[(0,$.jsx)(`h2`,{children:s.label}),(0,$.jsxs)(`dl`,{className:`training-context-facts`,children:[(0,$.jsx)(`dt`,{children:`Mode`}),(0,$.jsx)(`dd`,{children:s.decisionResult.mode}),(0,$.jsx)(`dt`,{children:`Execution`}),(0,$.jsx)(`dd`,{children:s.decisionResult.id}),(0,$.jsx)(`dt`,{children:`Input hash`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:s.decisionResult.plan.inputHash})]}),(0,$.jsx)(Zy,{result:s.decisionResult.result})]}):s?.model?(0,$.jsxs)(`div`,{className:`chat-experiment-tool-content`,children:[(0,$.jsxs)(`dl`,{className:`training-context-facts`,children:[(0,$.jsx)(`dt`,{children:`Base model`}),(0,$.jsx)(`dd`,{children:s.model.baseModel??`—`})]}),(0,$.jsx)(Z,{floating:!0,label:`Training run`,value:v,disabled:r.runs.isPending||r.selecting,options:[...c?[]:[{value:``,label:r.runs.isFetching?`Loading training runs…`:y.length?`Choose training run`:`No training runs`,disabled:!0}],...y],onChange:e=>void b(e)}),(0,$.jsx)(X,{error:r.runs.error,children:r.runs.error?(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>void r.runs.refetch(),children:`Retry training history`}):null}),c?c.location===`cloud`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(I_,{compact:!0,connection:e,teamId:c.owner.teamId,projectId:c.job.modelProjectId,jobId:c.jobId,onOpenRun:()=>window.location.assign(ao(as(`runs`,null,{area:`console`,resourceId:`hosted-run:${c.jobId}`})))}),(0,$.jsx)(IS,{connection:e,training:c})]}):(0,$.jsx)(uv,{connection:e,training:c}):(0,$.jsx)(y_,{}),(0,$.jsx)(a_,{connection:e,dataset:s.dataset,graders:s.graders??[],model:s.model}),(0,$.jsx)(i_,{title:`Experiments`,children:(0,$.jsx)(Z,{floating:!0,label:`Experiment`,value:``,options:[{value:``,label:`Experiment`,disabled:!0},...(r.catalog.data?.options??[]).filter(e=>e.target.kind===`experiment`).map(e=>({value:JSON.stringify(e.target),label:e.label,description:e.detail}))],onChange:e=>void b(e)})})]}):s?.draft&&(l||r.configureDraftId===s.draft.id)?(0,$.jsx)(OS,{connection:e,context:r,onClose:()=>{u(!1),r.closeDraftEditor()}}):s?.draft?(0,$.jsxs)(`div`,{className:`chat-experiment-tool-content`,children:[(0,$.jsx)(`h2`,{children:s.label}),(0,$.jsxs)(`dl`,{className:`training-context-facts`,children:[(0,$.jsx)(`dt`,{children:`Type`}),(0,$.jsx)(`dd`,{children:Tr(s.draft.operationType)}),(0,$.jsx)(`dt`,{children:`Status`}),(0,$.jsx)(`dd`,{children:`Draft`}),s.draft.operationType===`evaluate`?null:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Starting model`}),(0,$.jsx)(`dd`,{children:d?.modelId??`Not selected`}),s.draft.startingModel?.source===`alphaedit`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Saved AlphaEdit version`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:s.draft.startingModel.alphaedit.versionHash})]}):null,s.draft.startingModel?.source===`neuron_training`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Saved neuron training version`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:s.draft.startingModel.neuronTraining.versionHash})]}):null,s.draft.decisionForm?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Decision mode`}),(0,$.jsx)(`dd`,{children:s.draft.decisionForm.mode})]}):null,s.draft.startingModel?.source===`decision`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Saved Decision version`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:s.draft.startingModel.decision.versionHash}),(0,$.jsx)(`dt`,{children:`Adapter artifact`}),(0,$.jsx)(`dd`,{children:s.draft.startingModel.decision.artifact.id})]}):null,s.draft.startingModel?.source===`engram`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Saved module version`}),(0,$.jsx)(`dd`,{className:`saved-model-version-reference`,children:s.draft.startingModel.engram.versionHash}),(0,$.jsx)(`dt`,{children:`Module artifact`}),(0,$.jsx)(`dd`,{children:s.draft.startingModel.engram.artifact.id})]}):null,p?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Spending limit`}),(0,$.jsx)(`dd`,{children:p.cap?`$${p.cap}`:`Use available credits`}),(0,$.jsx)(`dt`,{children:`Planning budget`}),(0,$.jsx)(`dd`,{children:p.planning.trim()?`$${p.planning}`:`Not set`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`dt`,{children:`Maximum spend`}),(0,$.jsx)(`dd`,{children:typeof f==`number`&&Number.isFinite(f)&&f>0?`$${f}`:`Not set`})]})]})]}),(0,$.jsx)(`button`,{type:`button`,className:`training-button secondary`,onClick:()=>u(!0),children:`Configure experiment`})]}):s?.resource||s?.draft&&s.target.scopeId===i.scope?.id?(0,$.jsx)(xv,{connection:e,sessionId:t,resources:x,events:n,selectedExperiment:m,experimentName:s.target.kind===`dataset`?`Experiment draft`:s.label},JSON.stringify(s.target)):(0,$.jsx)(`div`,{className:`chat-experiment-tool-content`,children:(0,$.jsx)(`p`,{children:`Choose an experiment or model, or start a new experiment.`})})]})}function RS(e){return e.connection?(0,$.jsx)(LS,{connection:e.connection,sessionId:e.sessionId??null,events:e.events}):(0,$.jsx)(`p`,{children:`Connect to OpenPond to browse experiments.`})}function zS({activeTabId:e,tabs:t,onCloseTab:n,onNewTab:r,onSelectTab:i}){return(0,$.jsxs)(`div`,{className:`browser-tabs`,role:`tablist`,"aria-label":`Browser tabs`,children:[t.length?null:(0,$.jsxs)(`div`,{className:`browser-tab active`,children:[(0,$.jsx)(Mo,{size:13,"aria-hidden":!0}),(0,$.jsx)(`button`,{type:`button`,className:`browser-tab-main`,role:`tab`,"aria-selected":!0,children:`New tab`})]}),(0,$.jsx)(BS,{activeTabId:e,tabs:t,onSelectTab:i,onCloseTab:n}),(0,$.jsx)(`button`,{type:`button`,className:`browser-tab-add`,title:`New tab`,"aria-label":`New tab`,onClick:r,children:(0,$.jsx)(za,{size:14})})]})}function BS({activeTabId:e,tabs:t,onCloseTab:n,onSelectTab:r}){return(0,$.jsx)($.Fragment,{children:t.map(t=>(0,$.jsxs)(`div`,{className:`browser-tab ${t.id===e?`active`:``}`,children:[(0,$.jsx)(`span`,{className:`browser-tab-favicon`,"aria-hidden":`true`,children:t.faviconUrl?(0,$.jsx)(`img`,{alt:``,referrerPolicy:`no-referrer`,src:t.faviconUrl}):(0,$.jsx)(Mo,{size:13})}),(0,$.jsx)(`button`,{type:`button`,className:`browser-tab-main`,role:`tab`,"aria-selected":t.id===e,title:t.url,onClick:()=>r(t.id),children:VS(t)}),(0,$.jsx)(`button`,{type:`button`,className:`browser-tab-close`,title:`Close tab`,"aria-label":`Close tab`,onClick:()=>n(t.id),children:(0,$.jsx)(Ua,{size:12})})]},t.id))})}function VS(e){if(!e.url||e.url===`about:blank`)return`New tab`;if(e.title?.trim())return e.title.trim();try{return new URL(e.url).host||e.url}catch{return e.url||`New tab`}}var HS=(0,Q.lazy)(()=>o(()=>import(`./WorkspaceDiffPanel-xk-ve1MO.js`).then(e=>e.n).then(e=>({default:e.WorkspaceDiffPanel})),__vite__mapDeps([81,1,2,3,4,5,22,21,6,13,15,31,32,38,16,17,18,19,20,23,24,9,25,26,8,10,27,28,11,29,30,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,59,82,83,70]))),US=(0,Q.lazy)(()=>o(()=>import(`./AppTerminalPanel-DfYpUDKT.js`).then(e=>({default:e.AppTerminalPanel})),__vite__mapDeps([84,1,2,3]))),WS=(0,Q.lazy)(()=>o(()=>import(`./RightSidebarHomePanel-C0etQXpt.js`).then(e=>({default:e.RightSidebarHomePanel})),[]));(0,Q.lazy)(()=>o(()=>import(`./WorkSidebarPanel-BaNuXoZc.js`).then(e=>({default:e.WorkSidebarPanel})),[]));var GS=(0,Q.lazy)(()=>o(()=>import(`./CollaborationTabs-BpmKjNAC.js`).then(e=>({default:e.CollaborationTabs})),__vite__mapDeps([85,2,1,3,16,20,4,5,6,21,22,13,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,18,42,43,44,45,46,47,48,19,49,50,51,52,53,54,55,56,86]))),KS=(0,Q.lazy)(()=>o(()=>import(`./AppsView-B20RHDCy.js`).then(e=>({default:e.AppsView})),__vite__mapDeps([87,1,2,3,4,5,9,6,31,21,32,13,16,41,42,88,17,18,19,20,22,23,15,24,25,26,8,10,27,28,11,29,30,33,34,35,36,37,38,39,40,43,44,45,46,47,48,49,50,51,52,53,54,55,56,83,89,90,7,91,92,93]))),qS=(0,Q.lazy)(()=>o(()=>import(`./GetStartedView-BYbFl93M.js`).then(e=>({default:e.GetStartedView})),__vite__mapDeps([94,1,2,3,22,5,21,6,13,16,17,18,19,20,4,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,61,95]))),JS=(0,Q.lazy)(()=>o(()=>import(`./LabsRoute-DzEbPpMK.js`).then(e=>({default:e.LabsRoute})),__vite__mapDeps([96,1,2,3,4,97,5,28,6,9,26,21,8,10,11,30,24,38,20,22,13,23,15,25,27,29,31,32,33,34,35,36,37,16,39,40,41,18,42,43,44,45,46,47,48,19,49,50,51,52,53,54,55,56,77,78,79,80,7,12,98,17,57,99,100,82,64,90,101,68,61,102]))),YS=(0,Q.lazy)(()=>o(()=>import(`./ScheduledWorkPage-DI0mgt82.js`).then(e=>({default:e.ScheduledWorkPage})),__vite__mapDeps([103,1,2,3,22,5,21,6,13,23,15,24,104,16,17,18,19,20,4,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,65,66,60,61,83,105]))),XS=(0,Q.lazy)(()=>o(()=>import(`./OutputsPage-Dz190U9t.js`).then(e=>({default:e.OutputsPage})),__vite__mapDeps([106,1,2,3,16,17,13,18,19,20,4,5,6,21,22,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,66,59,60]))),ZS=(0,Q.lazy)(()=>o(()=>import(`./ProjectsPage-DVkYvLtd.js`).then(e=>({default:e.ProjectsPage})),__vite__mapDeps([107,1,2,3,31,21,5,6,32,16,100,42,20,4,22,13,23,15,24,9,25,26,8,10,27,28,11,29,30,33,34,35,36,37,38,39,40,41,18,43,44,45,46,47,48,19,49,50,51,52,53,54,55,56,108]))),QS=(0,Q.lazy)(()=>o(()=>import(`./LabSkillSidebar-CqHeZzoj.js`).then(e=>({default:e.LabSkillSidebar})),__vite__mapDeps([109,1,2,3,16,17,13,18,19,20,4,5,6,21,22,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,60,110]))),$S=(0,Q.lazy)(()=>o(()=>import(`./BrowserSidebar-Ce0ToS2O.js`).then(e=>({default:e.BrowserSidebar})),__vite__mapDeps([111,1,2,3,16,17,13,18,19,20,4,5,6,21,22,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,62,63]))),eC=(0,Q.lazy)(()=>o(()=>import(`./RightChatPanelStack-CP4leenI.js`).then(e=>({default:e.RightChatPanelStack})),__vite__mapDeps([112,1,2,3,33,22,5,21,6,13,31,32,34,35,36,15,37,16,59,14,17,18,19,20,4,23,24,9,25,26,8,10,27,28,11,29,30,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,60,61,62,63,64,65,66,67]))),tC=(0,Q.lazy)(()=>o(()=>import(`./NativeSkillSidebar-DkkD1uH2.js`).then(e=>({default:e.NativeSkillSidebar})),__vite__mapDeps([113,1,2,3,16,17,13,18,19,20,4,5,6,21,22,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,114]))),nC=(0,Q.lazy)(()=>o(()=>import(`./TeamChatView-BBEomfQ7.js`).then(e=>({default:e.TeamChatView})),__vite__mapDeps([115,1,2,3,16,17,13,18,19,20,4,5,6,21,22,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,116]))),rC=(0,Q.lazy)(()=>o(()=>import(`./TeamChatView-BBEomfQ7.js`).then(e=>({default:e.TeamChatProView})),__vite__mapDeps([115,1,2,3,16,17,13,18,19,20,4,5,6,21,22,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,116]))),iC=(0,Q.lazy)(()=>o(()=>import(`./CommunityView-ggdn8pcH.js`).then(e=>({default:e.CommunityView})),__vite__mapDeps([117,1,2,3,104,23,5,6,21,15,24,16,17,13,18,19,20,4,22,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,65,66,60,118,119,120]))),aC=(0,Q.lazy)(()=>o(()=>import(`./TeamChatView-BBEomfQ7.js`).then(e=>({default:e.TeamAiThreadPanel})),__vite__mapDeps([115,1,2,3,16,17,13,18,19,20,4,5,6,21,22,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,116]))),oC=(0,Q.lazy)(()=>o(()=>import(`./TeamChatView-BBEomfQ7.js`).then(e=>({default:e.TeamAgentConversationPanel})),__vite__mapDeps([115,1,2,3,16,17,13,18,19,20,4,5,6,21,22,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,116]))),sC=(0,Q.lazy)(()=>o(()=>import(`./TrainingDraftPanel-BAuh_BF3.js`).then(e=>({default:e.TrainingDraftPanel})),__vite__mapDeps([121,2,1,3,16,17,13,18,19,20,4,5,6,21,22,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56]))),cC=(0,Q.lazy)(()=>o(()=>import(`./TrainingCreationPanel-Ds4PLfsd.js`).then(e=>({default:e.TrainingCreationPanel})),__vite__mapDeps([122,1,2,3,16,43,19,20,4,5,6,21,22,13,23,15,24,9,25,26,8,10,27,28,11,29,30,31,32,33,34,35,36,37,38,39,40,41,18,42,44,45,46,47,48,49,50,51,52,53,54,55,56])));function lC({ponderNavigationVersion:e=0,ponderMode:t=null,onPonderModeChange:n,experience:r,view:i,teamChat:a,community:o,bootstrap:s,runtimeEvents:c,chatMessages:l,pendingUserMessage:u,contextWindowStatus:d,goalRuntime:f,subagentRuntime:p,selectedSessionId:m,composerDraftStore:h,mainComposerFocusRequestId:g,labCloseDetailRequestId:_,labCloseDetailKind:v,sideChatTrainingLaunchRequest:y,onSideChatTrainingLaunchHandled:b,mentionApps:x,connectedAppMentions:S,profileSkills:C,selectedMentionAppId:w,busy:T,turnRunning:O,activeProvider:k,activeModel:A,codexPermissionMode:j,codexReasoningEffort:M,openPondCommandAccessMode:N,pendingApproval:P,activeWorkspaceAppId:F,activeWorkspaceId:I,activeWorkspaceKind:L,projectTarget:ee,actionCatalog:R,workspaceTarget:z,connection:B,workspaceName:V,workspaceState:H,workspaceDiff:U,workspaceBusy:te,diffBusy:ne,forceChatThread:re=!1,diffPanelOpen:W,diffPanelExpanded:ie,rightPanelMode:G,rightPanelTabRequest:ae,rightChatPanels:K,runtimeEventStore:q,nativeSkillSidebar:oe,extensionSkillSidebar:se,workspaceDiffPanelViewState:ce,sidebarFileOpenRequest:le,sidebarFileBookmarks:ue,onSetSidebarFileStatus:de,browserConversationId:fe,terminalScope:pe,terminalTabs:he,terminalCwd:ge,pendingTerminalCommand:_e,terminalOpen:ve,onToggleTerminal:ye,onWorkspaceDiffPanelViewStateChange:be,training:xe,trainingSessions:Se,trainingChatHandoff:Ce,trainingDetailTasksetId:we,onTrainingDetailTasksetIdChange:Te,onTrainingChatTaskSelect:Ee,onTrainingChatHandoffDismiss:De,onOpenSession:Oe,cloudProjects:ke,projects:Ae,projectsAccountBaseUrl:je,projectsTeamName:Me,projectTaskCounts:Ne,onNewCloudProject:Pe,onNewLocalProject:Fe,onNewProjectTask:Ie,onToggleProjectPinned:Le,onUploadLocalProject:Re,chatHistoryHasMore:ze=!1,chatHistoryLoading:Be=!1,onDiffPanelResizeStart:Ve,canSyncWorkspace:He,startMessage:Ue,onPayload:We,onError:Ge,setView:Ke,onOpenProfileSettings:qe,onOpenProviderSettings:Je,onOpenTrainingSettings:Ye,onOpenDatasetStorageSettings:Xe,changeDraftProvider:Ze,changeProjectTarget:Qe,changeWorkspaceTarget:$e,setDraftProvider:et,setDraftModel:tt,onBeginNewChatWithModel:nt,changeCodexPermissionMode:rt,changeCodexReasoningEffort:it,changeOpenPondCommandAccessMode:at,resolveApproval:ot,answerCreateImproveQuestion:st,approveCreateImproveRun:ct,applyCreateImproveCandidate:lt,cancelCreateImproveRun:ut,openCreateImprovePullRequest:dt,pauseCreateImproveRun:ft,reconcileCreateImprovePullRequest:pt,rejectCreateImproveCandidate:mt,resumeCreateImproveRun:ht,reviseCreateImproveRun:gt,setMentionedAppId:_t,showToast:vt,onSaveTaskDraft:yt,sendPrompt:bt,stopTurn:xt,syncWorkspaceLocally:St,refreshWorkspaceDiff:Ct,onToggleDiffPanelExpanded:wt,onShowDiffPanel:Tt,onShowFilePreview:Et,onShowBrowserPanel:Dt,onShowTrainingDraftPanel:Ot,onShowFilesPanel:kt,onShowExperimentsPanel:At,onShowAgentsPanel:jt,onShowRightChatPanel:Mt,onAddRightChat:Nt,onOpenRightChatForSession:Pt,onLabDetailOpenChange:Ft,evaluationSidebarActive:It,onEvaluationSidebarControl:Lt,scheduledDetailOpen:Rt,onScheduledDetailOpenChange:zt,onTerminalTabsChange:Bt,onCloseRightChatPanel:Vt,onCloseNativeSkillSidebar:Ht,onActivateRightChatPanel:Ut,onRightChatModelChange:Wt,onRightChatPromptChange:Gt,onRightChatScrollStateChange:Kt,onRightChatProviderChange:qt,onSubmitRightChat:Jt,onStopRightChat:Yt,onCloseTerminal:Xt,onLoadMoreChatHistory:Zt}){let Qt=Ng(fe),[$t,en]=(0,Q.useState)(),[tn]=(0,Q.useState)(()=>new hd),nn=(0,Q.useRef)(null),rn=m&&!So(m)?m:null,an=Fd(q,rn),on=(0,Q.useMemo)(()=>rn?Io(c,an.events):c,[rn,an.events,c]),sn=(0,Q.useMemo)(()=>rn?Qi(tn.project(on),u):l,[tn,rn,u,on,l]),[cn,ln]=(0,Q.useState)(null),[un,dn]=(0,Q.useState)(0),fn=(0,Q.useRef)(``),pn=(0,Q.useCallback)(()=>fn.current,[]),[mn,hn]=(0,Q.useState)(null),gn=Pd(fe),[_n,vn]=(0,Q.useState)(null),[yn,bn]=(0,Q.useState)(null),[xn,Sn]=(0,Q.useState)(null),[Cn,wn]=(0,Q.useState)(null),[Tn,En]=(0,Q.useState)(null),[Dn,On]=(0,Q.useState)(null),[kn,An]=(0,Q.useState)([]);(0,Q.useEffect)(()=>{hn(null)},[fe]);let jn=(0,Q.useMemo)(()=>s?.sessions.find(e=>e.id===m)??null,[s?.sessions,m]),Mn=Se.find(e=>e.id===m)??jn,Nn=jn?.currentProfile??s?.profileLibrary?.lastUsed??null,Pn=kg(s),Fn=s?.preferences.defaultTeamId??null,In=s?.account.profile?.id??null,Ln=(0,Q.useMemo)(()=>({accountKey:Pn,teamId:Fn,actorId:In}),[Pn,Fn,In]),Rn=Nd({connection:B,sessionId:m,accountScope:Pn,active:i===`chat`,onOpen:At}),zn=$o(s?.profileLibrary??{lastUsed:null,profiles:[]},Nn)??s?.profile??null,Bn=(0,Q.useMemo)(()=>ro(zn,s?.extensionCatalog),[s?.extensionCatalog,zn]),Vn=(0,Q.useMemo)(()=>Yi(zn),[zn]),Hn=(0,Q.useCallback)(async(e,t=m)=>{if(!B||!s)return;let n=Lo(s.profileLibrary??{lastUsed:null,profiles:[]},e);if(n)try{let e=await sg({ref:n,session:t&&!So(t)?s.sessions.find(e=>e.id===t)??null:null,selectProfile:e=>Eo.profileSelect(B,e),patchSession:(e,t)=>Eo.patchSession(B,e,{currentProfile:t})}),r=s.sessions;e.session&&(r=r.map(t=>t.id===e.session.id?e.session:t)),We({...s,profile:e.selected.profile,profileLibrary:e.selected.library,sessions:r})}catch(e){let t=e instanceof Error?e.message:String(e);Ge(t),vt(t,`error`)}},[s,B,Ge,We,m,vt]);(0,Q.useEffect)(()=>{if(!Vo(le,fe))return;let{file:e,id:t}=le;if(hn({id:t,path:e.path}),!B)return;let n=!1;return(e.workspaceKind===`local`?Eo.workspaceFile(B,e.workspaceId,e.path).then(e=>e.content??``):Eo.sandboxDownloadFile(B,e.workspaceId,e.path).then(e=>{if(e.file.isBinary)throw Error(`Binary files cannot be attached to chat.`);return e.contents})).then(r=>{if(n)return;let i=e.path.split(`/`).at(-1)??e.path;ln({id:t,file:new File([r],i,{type:uC(e)})})}).catch(e=>{n||vt(e instanceof Error?e.message:String(e),`error`)}),()=>{n=!0}},[fe,B,vt,le]);let Un=r===`development`||r===`work`&&ee.value!==`none`,Wn=(0,Q.useMemo)(()=>{if(!Un)return[];let e=new Map(R.filter(e=>!Ji(e)).map(e=>[e.id,e]));for(let t of Vn)e.set(t.id,t);for(let t of kn)e.set(t.id,t);return[...e.values()]},[R,r,Un,kn,Vn]),Gn=lg(B),Kn=(0,Q.useCallback)(e=>{e?Gn.activate({runId:e.run.id,candidateId:e.candidate.id,title:e.run.objective,fileRootPath:e.fileRootPath,initialPath:e.initialPath}):Gn.activate(null)},[Gn.activate]),qn=(0,Q.useCallback)(()=>{Gn.selection?.initialPath&&Gn.openFile(Gn.selection.initialPath),Tt()},[Gn.openFile,Gn.selection?.initialPath,Tt]),Jn=(0,Q.useCallback)(e=>{bn(e),e&&Tt()},[Tt]),Yn=(0,Q.useCallback)(()=>{bn(null),ie&&wt()},[ie,wt]);(0,Q.useEffect)(()=>{i!==`labs`&&bn(null)},[i]);let Xn=(0,Q.useCallback)((e,t)=>{let n=Date.now(),r=R.find(t=>t.id===e)??null;h.set(``),_t(null),Ke(`chat`);let i=r=>{if(!(r.find(t=>t.id===e)??null))return!1;let i=r.map(n=>n.id===e?{...n,label:t}:n);return An(i),window.requestAnimationFrame(()=>{On({actionId:e,requestId:Math.max(Date.now(),n+1)})}),!0};B?Eo.profileCurrent(B).then(t=>{let n=t.actionCatalog.map(e=>Mi(e));!i(n)&&r?i([r]):n.some(t=>t.id===e)||vt(`This Agent is ready, but its default chat action is unavailable.`,`error`)}).catch(e=>{r||vt(e instanceof Error?e.message:String(e),`error`)}):r?i([r]):vt(`The Agent action catalog is still loading. Try Use again.`,`error`)},[R,h,B,_t,Ke,vt]),Zn=(0,Q.useCallback)((e,t)=>{h.set(e),_t(null),t&&Ze(t),Ke(`chat`)},[Ze,h,_t,Ke]),Qn=(0,Q.useMemo)(()=>di(s?.preferences),[s?.preferences]),$n=Qn.training,{createAgentFromLab:er,improveAgentFromLab:tr}=dg({activeModel:A,activeProvider:k,bootstrap:s,codexPermissionMode:j,codexReasoningEffort:M,connection:B,onOpenRightChatForSession:Pt,onPayload:We}),nr=(0,Q.useMemo)(()=>{let e=xe.payload?.tasksets??[];return e.some(e=>e.id===Cn)?Cn:e[0]?.id??null},[Cn,xe.payload?.tasksets]),rr=i===`labs`&&nr?`profiles/${s?.profile.activeProfile??`default`}/tasksets/${nr}`:null,ir=(0,Q.useMemo)(()=>{if(i!==`labs`||!nr||!xe.payload)return null;let e=xe.payload.tasksets.find(e=>e.id===nr);if(!e)return null;let t=xe.payload.plans.filter(t=>t.tasksetId===e.id),n=new Set(t.map(e=>e.id)),r=xe.payload.jobs.filter(e=>n.has(e.planId)).sort((e,t)=>t.createdAt.localeCompare(e.createdAt)),a=r.find(e=>e.id===Tn)??r[0]??null;return{taskset:e,plan:a?t.find(e=>e.id===a.planId)??null:t.sort((e,t)=>t.createdAt.localeCompare(e.createdAt))[0]??null,job:a,lineage:a?xe.payload.models.find(e=>e.jobId===a.id)??null:null,artifacts:a?xe.payload.artifacts.filter(e=>e.jobId===a.id):[]}},[nr,Tn,xe.payload,i]),ar=(0,Q.useMemo)(()=>cg(xe.payload,m),[m,xe.payload]),or=(0,Q.useMemo)(()=>ed(sn),[sn]),sr=!!f||!!or||!!p,cr=i===`labs`&&!!Gn.selection,lr=i===`labs`&&W&&G===`changes`&&!!yn,ur=(i===`chat`||i===`labs`)&&!!(F||mn?.file),dr=i===`chat`&&W&&G===`chat`&&K.length===0,fr=To(L)?I??id(V):null,pr=i===`chat`&&!!fr,mr=fr,hr=!!mr||z.value===`cloud`||z.value===`hybrid`,gr=(0,Q.useMemo)(()=>rg({workspaceTarget:z.value,localWorkspaceId:F,sandboxSourceAvailable:hr,sandboxWorkspaceId:mr,override:_n}),[F,hr,mr,_n,z.value]),_r=gr.source,vr=_r===`sandbox`,yr=(0,Q.useMemo)(()=>_r&&gr.options.length>1?{value:_r,options:gr.options,onChange:vn}:null,[_r,gr.options]);(0,Q.useEffect)(()=>{vn(null)},[F,fe,mr,z.value]);let br=!lr&&(cr||i===`chat`||ur||pr)&&W&&(G===`changes`||G===`home`&&i===`chat`||G===`goal`&&sr||dr),xr=i===`chat`&&W&&G===`browser`,Sr=(i===`chat`||i===`labs`)&&W&&G===`chat`&&K.length>0,Cr=i===`chat`&&W&&G===`training`,wr=i===`chat`&&W&&!!oe,Tr=i===`chat`&&W&&!!se,Er=i===`team`&&W&&G===`chat`&&!!a.aiThread,Dr=i===`team`&&W&&G===`chat`&&!!a.agentConversation,Or=Lu({supportedView:i===`chat`&&Un||i===`labs`,open:W,hasContentPanel:br||lr||xr||Sr||Cr||wr||Er||Dr}),kr=!It&&(br||lr||xr||Sr||Cr||wr||Er||Dr||Or),Ar=kr&&G!==`chat`&&ie,jr=s?.account.baseUrl??s?.account.activeProfile?.baseUrl??null,Mr=Gu({activeWorkspaceId:I,cloudProjects:ke}),Nr=i===`chat`&&O&&!P&&mu(sn),Pr=re||sn.length>0||Nr,Fr=m??`draft:${i}:${L??`none`}:${I??F??`none`}`;fn.current=Fr;let Ir=(0,$.jsx)(Pu,{activeModel:A,activeProvider:k,busy:O,handoff:Ce,onDismiss:De,onSelectTask:Ee}),Lr=(0,Q.useMemo)(()=>({onAnswerQuestion:st,onApprove:ct,onApplyCandidate:lt,onCancel:ut,onOpenPullRequest:dt,onPause:ft,onReconcilePullRequest:pt,onRejectCandidate:mt,onResume:ht,onRevise:gt}),[st,ct,lt,ut,dt,ft,pt,mt,ht,gt]),Rr=(0,Q.useMemo)(()=>or?{...or,...Lr}:null,[Lr,or]),zr=Ru(i,Pr),Br=(0,Q.useCallback)(async(e=[],t=null,n=null,i={})=>{let a=i.promptOverride??h.getSnapshot(),o=()=>{i.preservePrompt||(h.set(``),_t(null))};if(!t){let t=n?{command:n.id,args:a.trim()}:Ii(a);if(t){if(!Ui({id:t.command},r))return vt(`/${t.command} isn't available in ${r}.`,`info`),!1;if(t.command===`train`)return e.length>0?(vt(`/train uses the selected chat; add other chats from Models.`,`error`),!1):m?(o(),Sn({id:Date.now(),objective:t.args.trim()||null,initialSessionIds:[m]}),Ke(`labs`),!0):(o(),Sn({id:Date.now(),objective:t.args.trim()||null,initialSessionIds:[]}),Ke(`labs`),!0);if(!t.args&&t.command!==`skill`&&t.command!==`sync-cloud`)return vt(`Add instructions after /${t.command}.`,`info`),!1;if(e.length>0)return vt(`/${t.command} tasks do not accept attachments yet. Add file context in the task thread.`,`error`),!1;if(t.command===`submit-issue`)return zi(S)?(dn(e=>e+1),bt([],null,Hi(t.args),{clearPrompt:i.preservePrompt?()=>void 0:void 0,usageAttribution:nd(t,n?`composer_selection`:`prompt_parse`)})):(vt(`Connect the GitHub app before using /submit-issue.`,`error`),!1);if(rd(t)){let e=t.command===`skill`?ag(t.args,k,s?.profile.sourcePath??null):td(t);return dn(e=>e+1),bt([],null,e,{clearPrompt:i.preservePrompt?()=>void 0:void 0,usageAttribution:nd(t,n?`composer_selection`:`prompt_parse`)})}return dn(e=>e+1),bt([],null,td(t),{clearPrompt:i.preservePrompt?()=>void 0:void 0,usageAttribution:nd(t,n?`composer_selection`:`prompt_parse`)})}}return dn(e=>e+1),bt(e,t,i.promptOverride,{clearPrompt:i.preservePrompt?()=>void 0:void 0,displayPrompt:i.displayPrompt,turnMetadata:i.turnMetadata,sessionMetadata:i.sessionMetadata,onSessionCreated:i.onSessionCreated})},[A,k,L,s?.profile,S,h,r,bt,m,_t,Ke,vt,xe,i]),J=(0,Q.useCallback)(e=>{Ce&&e!==Ce.model.modelId&&De(),ki(k,e),et(k),tt(e)},[k,De,tt,et,Ce]),Vr=(0,Q.useCallback)((e,t)=>{Ce&&e!==Ce.model.providerId&&De(),Ze(e,t)},[Ze,De,Ce]),Hr=(0,Q.useCallback)((e,t)=>{ea({conversationId:fe,href:e,explicitFile:t?.explicitFile,newTab:t?.newTab}).then(e=>{e&&window.openpond?.browser&&(gn.showBrowser(),Dt())}).catch(e=>vt(e instanceof Error?e.message:`Could not open browser.`,`error`))},[fe,gn.showBrowser,Dt,vt]),Ur=ba({projectTargetDetail:ee.detail,projectTargetValue:ee.value,workspaceRepoPath:H?.repoPath,workspaceTargetValue:z.value}),{handleOpenFileInSidebar:Wr,fileResolution:Gr,dismissFileResolution:Kr,selectFileResolution:qr}=ng({conversationKey:fe,connection:B,handleOpenBrowserLink:Hr,activeWorkspaceAppId:F,rightSidebarUsesSandbox:vr,rightSidebarSandboxId:mr,onShowDiffPanel:Et,showToast:vt,workspaceRootPath:Ur,setOpenDiffFileRequest:hn});Au(q,i===`chat`?rn:null,Wr);let Jr=(0,Q.useCallback)(async e=>{if(!B||!e.filePreview&&!e.imagePreview)vt(`File content is not available for this attachment.`,`error`);else try{let t=e.name.trim().replace(/[\\/]+/g,`-`)||`attachment.txt`,n=`Attachments/${e.id.replace(/[^a-zA-Z0-9._-]+/g,`-`)||`file`}/${t}`,r={path:n,status:``,additions:0,deletions:0,patch:``,content:null},i,a;if(e.filePreview){let n=await Eo.chatAttachmentFile(B,e.filePreview);r.content=n.content,fa(t)&&(a=await aa(B,t,n.content))}else e.imagePreview&&(i=(await Eo.signChatAttachmentImageUrl(B,e.imagePreview)).url);a?Hr(a):Et(),hn({id:Date.now(),path:n,source:!!a,file:r,...i?{imageUrl:i}:{}})}catch(e){vt(e instanceof Error?e.message:`Could not open this attachment.`,`error`)}},[B,Hr,Et,vt]),Yr=te&&!!F&&!H;(0,Q.useEffect)(()=>{let e=on.filter(e=>e.sessionId===m&&e.source===`server`&&e.name===`workspace_action_result`).at(-1),t=e?`${m}:${e.id}`:null;if(!nn.current||nn.current.sessionId!==m){nn.current={sessionId:m,eventId:t};return}if(t===nn.current.eventId)return;nn.current={sessionId:m,eventId:t};let n=e?.data;i===`chat`&&n?.chatResourcePresentation!==`context`&&n?.chatResource?.kind===`experiment`&&uf(n.chatResource.state??``)&&At()},[on,m,i,At]);let Xr=Gn.selection?`candidate:${Gn.selection.runId}:${Gn.selection.candidateId}`:null,Zr=i===`chat`?(e,n)=>n===-2&&B?(0,$.jsx)(Md,{selectionRequest:t?$t:void 0,connection:B,accountScopeKey:Pn,ponder:!!t,parentSessionId:m,sessions:Se,onOpenChat:Oe}):(0,$.jsx)(n===-1?RS:$g,{conversationId:fe,onOpenBrowser:Dt,sessionId:m,connection:B,workspaceId:F,sandboxId:vr?mr:null,messages:sn,events:on,onOpenFile:Wr,actions:(0,$.jsx)(jg,{terminalOpen:ve,sideChatAvailable:!0,onOpenFile:e,onOpenFiles:kt,onOpenAgents:jt,onOpenExperiments:At,onOpenReview:Tt,onOpenSideChat:Nt,onOpenTrainingDraft:Ot,trainingDraftAvailable:!!m,onToggleTerminal:ye})}):null,Qr=(0,Q.useMemo)(()=>G===`home`&&i===`chat`?{id:-1,tab:`outputs`,overview:`new`}:ae,[i,G,ae]),$r=br?(0,$.jsx)(HS,{appId:cr?Xr:vr?null:F,workspaceId:cr?Xr:vr?mr:F,workspaceKind:cr?`local_project`:vr?null:`local_project`,connection:B,runtimeEvents:on,diff:cr?Gn.diff:vr?null:U,fileRootPath:cr?Gn.selection?.fileRootPath??null:vr?null:rr,filesWithPreview:cr,editorPreferences:s?.preferences.editor??null,loading:cr?Gn.loading:vr?te:ne||Yr,openFileRequest:cr?Gn.openFileRequest:G===`home`?null:mn,sidebarFileBookmarks:ue,sidebarFileSourceSessionId:m,onSetSidebarFileStatus:de,readOnly:cr,sideChatTabs:K.map(e=>({id:e.id,title:e.title,running:e.running})),sourceSwitcher:cr?null:yr,tabRequest:Qr,additionalTabs:i===`chat`?(0,$.jsx)(BS,{tabs:Qt.state.tabs,activeTabId:null,onSelectTab:e=>{Qt.selectTab(e),gn.showBrowser(),Dt()},onCloseTab:e=>void Qt.closeTab(e)}):void 0,renderOutputs:Zr??void 0,outputsLabel:Rn,viewState:ce,workspaceName:cr?Gn.selection?.title??`Change`:vr?V??`Sandbox`:V,workspaceInitialized:cr?!0:vr?!!mr:!!H?.initialized,workspaceError:cr?Gn.error:vr?null:H?.error??U?.error??null,expanded:ie,onResizeStart:Ve,onRefresh:e=>void(cr?Gn.refresh(e):Ct(e)),onToggleExpanded:wt,onOpenBrowser:Dt,onOpenBrowserUrl:Hr,onViewStateChange:be,onCloseSideChat:Vt,onOpenSideChat:i===`chat`?Nt:void 0,onSelectSideChat:e=>{Ut(e),Mt()},goalDetails:{active:G===`goal`,createRuntime:Rr,goalRuntime:f,subagentRuntime:p},sandboxFileSource:vr?{sandboxId:mr,emptyMessage:`No sandbox filesystem yet.`}:null,trainingSummary:ir}):null,ei=(0,Q.useCallback)(e=>{gn.open(e),Dt()},[gn.open,Dt]),ti=(0,Q.useCallback)(async(e,t,n)=>{if(!B||e.sessionId!==m)throw Error(`Open the originating conversation to select this resource.`);let r=await ko(B,`dataset`,{action:`context`,payload:{sessionId:e.sessionId}}),i=await ko(B,`dataset`,{action:`set_focus`,payload:{sessionId:e.sessionId,kind:t.kind,id:t.id,...t.revision?{revision:t.revision}:{},operationId:n,visualPublicationId:e.publicationId,expectedSelectionVersion:r.focus.scopeContext?.selectionVersion}}),a=t.kind===`dataset`?i.dataset:i.experiment;if(!a)throw Error(`Selected resource is unavailable.`);let o=`Selected ${t.kind}: ${a.name}${t.kind===`dataset`?` V${a.revision}`:``}.`;return await co.queueTaskInput(B,e.sessionId,me.parse({prompt:o,metadata:{chatExperimentScopeId:i.scopeContext?.activeScopeId,chatExperimentSelectionVersion:i.scopeContext?.selectionVersion,chatResourceFocus:{dataset:i.dataset,experiment:i.experiment},resourceSelection:{kind:t.kind,id:a.id,revision:a.revision,visualPublicationId:e.publicationId}}}),n),window.dispatchEvent(new CustomEvent(`openpond-resource-focus-changed`,{detail:{sessionId:e.sessionId}})),o},[B,m]),ni=xr?(0,$.jsx)($S,{conversationId:fe,connection:B,visualTabs:gn,expanded:ie,onResizeStart:Ve}):null,ri=Er?(0,Q.createElement)(aC,{...a,key:a.aiThread?.conversationId,onResizeStart:Ve}):null,ii=Dr?(0,Q.createElement)(oC,{...a,key:a.agentConversation?.run.id,onResizeStart:Ve}):null,ai=Sr?(0,$.jsx)(eC,{panels:K,runtimeEventStore:q,actionCatalog:Wn,createImproveActions:Lr,contextCompaction:Qn.contextCompaction,steerActiveResponses:Qn.steerActiveResponses,busy:T,codexPermissionMode:j,codexReasoningEffort:M,openPondCommandAccessMode:N,connection:B,connectedAppMentions:S,mentionApps:x,codexPersonalSkills:s?.codexPersonalSkills??[],profileSkills:C,profileLibrary:s?.profileLibrary??{lastUsed:null,profiles:[]},extensionCatalog:s?.extensionCatalog??null,projectTarget:ee,providerSettings:s?.providers??null,accountBaseUrl:jr,billingOrganizationSlug:Mr.organizationSlug,billingTeamId:Mr.teamId,showToast:vt,workspaceTarget:z,onAddChat:Nt,onActivatePanel:Ut,onClosePanel:Vt,onCodexPermissionModeChange:rt,onCodexReasoningEffortChange:it,onOpenPondCommandAccessModeChange:at,onModelChange:Wt,onOpenAttachmentInSidebar:Jr,onOpenFileInSidebar:Wr,onOpenProfileSettings:qe,onOpenSession:Oe,onOpenPonder:()=>n?.(`clean`),onProviderChange:qt,onProviderSetupOpen:Je,onPromptChange:Gt,onProfileTargetChange:(e,t)=>void Hn(t,e),onScrollStateChange:Kt,onProjectTargetChange:Qe,onResolveApproval:ot,onResizeStart:Ve,onSelectFiles:kt,onShowBrowserPanel:Dt,onStop:Yt,onSubmit:Jt,onWorkspaceTargetChange:e=>void $e(e)}):null,oi=ii??ri??ai??(wr&&oe?(0,$.jsx)(tC,{expanded:ie,skill:oe,onClose:Ht,onResizeStart:Ve,onToggleExpanded:wt}):null)??(Tr&&se?(0,$.jsx)(QS,{connection:B,expanded:ie,selection:se,onClose:Ht,onResizeStart:Ve,onToggleExpanded:wt}):null)??(lr&&yn?(0,$.jsx)(QS,{connection:B,expanded:ie,selection:yn,onClose:Yn,onResizeStart:Ve,onToggleExpanded:wt}):null)??$r??ni??(Cr?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(sC,{training:xe,sessionId:m,expanded:ie,onOpenTraining:()=>Ke(`labs`),onResizeStart:Ve,onToggleExpanded:wt})}):null)??(Or?(0,$.jsx)(WS,{expanded:ie,terminalOpen:ve,sideChatAvailable:i===`chat`||i===`labs`,onOpenFiles:kt,onOpenAgents:jt,onOpenReview:Tt,onOpenSideChat:Nt,onOpenTrainingDraft:Ot,trainingDraftAvailable:!!m,onResizeStart:Ve,onToggleExpanded:wt,onToggleTerminal:ye}):null),si=(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(US,{open:ve,connection:B,scope:pe,tabs:he,onTabsChange:Bt,cwd:ge,appId:F,workspaceName:V,queuedCommand:_e,onClose:Xt})});return(0,$.jsx)(D.Provider,{value:Pn,children:(0,$.jsx)(E.Provider,{value:Ln,children:(0,$.jsx)(gu.Provider,{value:ei,children:(0,$.jsx)(_u.Provider,{value:ti,children:(0,$.jsxs)(`main`,{tabIndex:-1,"data-thread-session":i===`chat`&&!t?m??void 0:void 0,className:`main-pane ${zr} ${ve?`terminal-open`:``} ${kr?`diff-open`:``} ${Ar?`diff-expanded`:``}`,children:[Gr?(0,$.jsx)(Qh,{resolution:Gr,onClose:Kr,onSelect:qr}):null,i===`team`||i===`community`?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(GS,{onSelect:Ke,view:i})}):null,i===`chat`&&t&&B&&s?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Og,{navigationVersion:e,messageContext:{accountBaseUrl:jr,activeWorkspaceAppId:F,billingOrganizationSlug:Mr.organizationSlug,billingTeamId:Mr.teamId,onOpenBrowserLink:Hr,onOpenAttachmentInSidebar:Jr,onOpenFileInSidebar:Wr,onOpenProfileSettings:qe,workspaceRootPath:Ur},onOpenAgents:e=>{e&&en(t=>({sessionId:e,version:(t?.version??0)+1})),jt()},contextCompaction:Qn.contextCompaction,accountScopeKey:Pn,connection:B,presentation:t,localSessions:Se,composer:{contextWindowStatus:d,providerSettings:s.providers??null,provider:k,model:A,projectTarget:ee,workspaceTarget:z,codexPermissionMode:j,codexReasoningEffort:M,openPondCommandAccessMode:N,onProviderChange:Vr,onProviderSetupOpen:Je,onProjectTargetChange:Qe,onWorkspaceTargetChange:e=>{$e(e)},onModelChange:J,onCodexPermissionModeChange:rt,onCodexReasoningEffortChange:it,onOpenPondCommandAccessModeChange:at,showToast:vt},accountBaseUrl:je,onOpenBrowserLink:Hr,onOpenLocalWork:Oe},Pn),si,(0,$.jsx)(Q.Suspense,{fallback:null,children:oi})]}):i===`apps`?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(KS,{payload:s,onPayload:We,account:s?.account??null,connection:B,defaultTeamId:s?.preferences.defaultTeamId??null,onToast:vt})}):i===`team`?(0,$.jsxs)(Q.Suspense,{fallback:null,children:[a.teamId?(0,$.jsx)(nC,{...a}):(0,$.jsx)(rC,{}),kr?oi:null]}):i===`community`?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(iC,{...o})}):i===`get-started`?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(qS,{})}):i===`scheduled`?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(YS,{connection:B,selectedProfileKey:Nn?JSON.stringify(Nn):null,onOpenSession:Oe,detailOpen:Rt,detailExpanded:ie,onDetailOpenChange:zt,onDetailResizeStart:Ve,onToggleDetailExpanded:wt},Pn)}):i===`outputs`?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(XS,{connection:B,onViewChat:Oe})}):i===`projects`?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(ZS,{accountBaseUrl:je,connection:B,onNewCloudProject:Pe,onNewLocalProject:Fe,onNewTask:Ie,onTogglePinned:Le,onUploadLocalProject:Re,projects:Ae,taskCountByProjectId:Ne,teamName:Me},Pn)}):i===`labs`?Ar?(0,$.jsx)(Q.Suspense,{fallback:null,children:oi}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(JS,{account:s?.account??null,closeDetailRequestId:_,closeDetailKind:v,onNewModel:(e,t,n)=>{Sn({id:Date.now(),objective:null,initialSessionIds:[],initialTasksetId:e,learnedPreferenceReward:t,initialModelId:n})},onUseAgent:Xn,onCreateAgent:er,onImproveAgent:tr,onDetailOpenChange:Ft,onEvaluationSidebarControl:Lt,onSkillSelectionChange:Jn,onOpenRunConversation:Pt,onAnswerQuestion:st,onApplyCandidate:lt,onApprove:ct,onCancel:ut,candidateReview:{diff:Gn.diff,error:Gn.error,loading:Gn.loading},onCandidateReviewChange:Kn,onOpenPullRequest:dt,onOpenCandidateFiles:qn,onPause:ft,onReconcilePullRequest:pt,onRejectCandidate:mt,onResume:ht,onRevise:gt,profileView:{payload:s,connection:B,onPayload:We,onError:Ge,onToast:vt,onSkillCommand:Zn},training:{training:xe,sessions:Se,localProjects:s?.localProjects??[],connection:B,defaultModel:{providerId:k,modelId:A},onError:Ge,onToast:vt,onSettingsPreferences:e=>{s&&We({...s,preferences:e.preferences})},onOpenTrainingSettings:Ye,onOpenProviderSettings:Je,onOpenDatasetStorageSettings:Xe,onOpenChat:Oe,onChatWithModel:nt,onOpenTasksetFiles:kt,launchRequest:y??xn,onLaunchHandled:e=>{y?.id===e?b(e):Sn(t=>t?.id===e?null:t)},preferences:$n,settingsPreferences:Qn,providerSettings:s?.providers??null,reasoningEffort:M,selectedTasksetId:nr,onSelectedTasksetIdChange:wn,onSelectedTrainingJobIdChange:En,detailTasksetId:we,onDetailTasksetIdChange:Te}})}),si,kr?(0,$.jsx)(Q.Suspense,{fallback:null,children:oi}):null]}):Ar?(0,$.jsx)(Q.Suspense,{fallback:null,children:oi}):Pr?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(fd,{hasApproval:!!P,scroll:{browserConversationId:fe,chatSubmissionVersion:un,chatHistoryHasMore:ze,chatHistoryLoading:Be,chatMessages:sn,onLoadMoreChatHistory:Zt,pendingApproval:P,showChatThread:Pr,showThinkingIndicator:Nr,turnRunning:O,view:i},thread:{formalReviewTeamId:Qn.defaultTeamId??null,formalReviewActorId:s?.account.profile?.id??null,formalReviewScopeKey:Pn,onFormalReviewOpen:()=>Ke(`labs`),accountBaseUrl:jr,activeWorkspaceAppId:F,billingOrganizationSlug:Mr.organizationSlug,billingTeamId:Mr.teamId,connection:B,creation:ar,onOpenBrowserLink:Hr,onOpenAttachmentInSidebar:Jr,onOpenFileInSidebar:Wr,onOpenProfileSettings:qe,onResolveUserQuestion:async(e,t)=>{let n=t.action===`answer`?t.text:`Dismiss this question`;if(!await bt([],null,n,{displayPrompt:n,turnMetadata:{userQuestionResolution:t}}))throw Error(`The question response could not be sent.`)},onOpenSession:Oe,onOpenPonder:()=>n?.(`clean`),userAttachmentDisplay:k===`codex`?`compact`:`full`,workspaceRootPath:Ur},composerPrefix:(0,$.jsxs)($.Fragment,{children:[ar?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(cC,{compact:!0,creation:ar,training:xe,onOpenTraining:()=>Ke(`labs`)})}):null,Ir,(0,$.jsx)(Yh,{connection:B,showToast:vt,approval:P,onResolve:ot})]}),composer:(0,$.jsx)(Lh,{experience:r,readOnlyReason:typeof Mn?.metadata?.nativeReadOnlyReason==`string`?Mn.metadata.nativeReadOnlyReason:null,readOnlySession:Mn,onOpenNativeParent:Oe,draftStore:h,attachmentRequest:cn,mode:`dock`,focusRequestId:g,mentionApps:Un?x:[],connectedAppMentions:S,profileSkills:k===`codex`?s?.codexPersonalSkills??[]:Bn,selectedMentionAppId:w,contextWindowStatus:d,goalRuntime:f,subagentRuntime:p,createImproveRuntime:Un?Rr:null,busy:O,running:O,steerActiveResponses:Qn.steerActiveResponses,taskSessionId:rn,goalSessionId:m,taskEvents:on,submissionScopeKey:Fr,composerDraftStore:h,getCurrentSubmissionScopeKey:pn,voiceInputChannelKey:`main-composer:${Fr}`,showProjectFooter:!0,connection:B,providerSettings:s?.providers??null,provider:k,model:A,projectTarget:ee,profileTarget:null,actionCatalog:Wn,requestedAction:Dn,workspaceTarget:z,codexPermissionMode:j,codexReasoningEffort:M,openPondCommandAccessMode:N,onProviderChange:Vr,onProviderSetupOpen:Je,onProjectTargetChange:Qe,onProfileTargetChange:e=>void Hn(e),onWorkspaceTargetChange:e=>void $e(e),onModelChange:J,onCodexPermissionModeChange:rt,onCodexReasoningEffortChange:it,onOpenPondCommandAccessModeChange:at,onMentionAppSelect:_t,onSaveTaskDraft:yt,showToast:vt,onSubmit:Br,onStop:xt})}),si,(0,$.jsx)(Q.Suspense,{fallback:null,children:oi})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`section`,{className:`start-panel`,children:[(0,$.jsxs)(`div`,{className:`start-welcome`,children:[(0,$.jsx)(`h1`,{children:Ue}),He&&(0,$.jsx)(Iu,{busy:te,onSync:()=>void St()})]}),(0,$.jsxs)(`div`,{className:`composer-stack start`,children:[Ir,(0,$.jsx)(Yh,{connection:B,showToast:vt,approval:P,onResolve:ot}),(0,$.jsx)(Lh,{experience:r,draftStore:h,attachmentRequest:cn,mode:`start`,autoFocus:!0,focusRequestId:g,mentionApps:Un?x:[],connectedAppMentions:S,profileSkills:k===`codex`?s?.codexPersonalSkills??[]:Bn,selectedMentionAppId:w,contextWindowStatus:d,goalRuntime:f,subagentRuntime:p,createImproveRuntime:Un?Rr:null,busy:O,running:O,steerActiveResponses:Qn.steerActiveResponses,taskSessionId:rn,goalSessionId:m,taskEvents:on,submissionScopeKey:Fr,composerDraftStore:h,getCurrentSubmissionScopeKey:pn,voiceInputChannelKey:`main-composer:${Fr}`,connection:B,providerSettings:s?.providers??null,provider:k,model:A,showProjectFooter:!0,projectTarget:ee,profileTarget:null,actionCatalog:Wn,requestedAction:Dn,workspaceTarget:z,codexPermissionMode:j,codexReasoningEffort:M,openPondCommandAccessMode:N,onProviderChange:Vr,onProviderSetupOpen:Je,onProjectTargetChange:Qe,onProfileTargetChange:e=>void Hn(e),onWorkspaceTargetChange:e=>void $e(e),onModelChange:J,onCodexPermissionModeChange:rt,onCodexReasoningEffortChange:it,onOpenPondCommandAccessModeChange:at,onMentionAppSelect:_t,onSaveTaskDraft:yt,showToast:vt,onSubmit:Br,onStop:xt})]})]}),si,(0,$.jsx)(Q.Suspense,{fallback:null,children:oi})]})]})})})})})}function uC(e){let t=e.path.toLowerCase();return t.endsWith(`.md`)||t.endsWith(`.mdx`)?`text/markdown`:t.endsWith(`.json`)?`application/json`:t.endsWith(`.yaml`)||t.endsWith(`.yml`)?`application/yaml`:`text/plain`}export{Iv as $,Yc as $t,Ob as A,Tu as At,ky as B,uu as Bt,ix as C,Lm as Ct,Hb as D,ld as Dt,Kb as E,hd as Et,Hy as F,_u as Ft,ny as G,Ql as Gt,Ey as H,au as Ht,By as I,hu as It,Mv as J,tl as Jt,Bv as K,il as Kt,Ly as L,pu as Lt,tb as M,lC as MainPane,bu as Mt,Qy as N,yu as Nt,Lb as O,Au as Ot,Uy as P,gu as Pt,jv as Q,Uc as Qt,Iy as R,fu as Rt,ox as S,Rm as St,Zb as T,Fd as Tt,ay as U,ru as Ut,Dy as V,cu as Vt,iy as W,nu as Wt,Nv as X,Rc as Xt,zv as Y,Qc as Yt,Rv as Z,Wc as Zt,Mx as _,js as _n,Ng as _t,CS as a,Cc as an,pv as at,mx as b,Yh as bt,yS as c,yc as cn,mv as ct,tS as d,Ls as dn,O_ as dt,Gc as en,Pv as et,nS as f,As as fn,Rg as ft,jx as g,Is as gn,Pg as gt,Fx as h,ks as hn,Vg as ht,wS as i,bc as in,dv as it,hb as j,Su as jt,Fb as k,Du as kt,fS as l,zs as ln,Z_ as lt,Zx as m,Ps as mn,zg as mt,FS as n,Ac as nn,kv as nt,SS as o,xc as on,hv as ot,eS as p,Fs as pn,Bg as pt,Lv as q,Zc as qt,DS as r,Sc as rn,_v as rt,pS as s,vc as sn,fv as st,zS as t,$c as tn,Ov as tt,xS as u,Rs as un,I_ as ut,Tx as v,Ts as vn,jg as vt,nx as w,dm as wt,dx as x,Ih as xt,wx as y,ds as yn,Ag as yt,Ay as z,mu as zt};