openpond 0.2.70 → 0.2.72

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 (361) hide show
  1. package/dist/app-server.js +1 -1
  2. package/dist/chunks/{acp-QTA6IU6W.js → acp-7A2UPCG5.js} +1 -1
  3. package/dist/chunks/{acp-agent-N77HPAYQ.js → acp-agent-AGALGR6V.js} +1 -1
  4. package/dist/chunks/{actions-command-BZQCUDMD.js → actions-command-AXGXBU75.js} +1 -1
  5. package/dist/chunks/{app-layer-YQQNLIXA.js → app-layer-DUCNCJ2X.js} +1 -1
  6. package/dist/chunks/{app-server-evaluations-RRLYWLPK.js → app-server-evaluations-SNWXULKD.js} +1 -1
  7. package/dist/chunks/{app-server-harness-services-XXM336NU.js → app-server-harness-services-YNMGMKPK.js} +1 -1
  8. package/dist/chunks/app-server-runtime-BKJ7L6JZ.js +2 -0
  9. package/dist/chunks/{apps-WG7WY5CB.js → apps-2OWE23BH.js} +1 -1
  10. package/dist/chunks/{chunk-ZDEIVUUI.js → chunk-27OJ2OLP.js} +1 -1
  11. package/dist/chunks/{chunk-NSSZ2ZIU.js → chunk-2EAZB2MW.js} +1 -1
  12. package/dist/chunks/{chunk-DRLP7GIU.js → chunk-2GEZ3ZY7.js} +1 -1
  13. package/dist/chunks/{chunk-PAYFJHPO.js → chunk-2PVW2XFF.js} +1 -1
  14. package/dist/chunks/chunk-2Q2AWPP2.js +2 -0
  15. package/dist/chunks/{chunk-Y2WNZWT2.js → chunk-2Q6FTL4C.js} +1 -1
  16. package/dist/chunks/{chunk-KP2MYTP5.js → chunk-2QHB5P2K.js} +1 -1
  17. package/dist/chunks/{chunk-HG2YFMVU.js → chunk-2THZ6GZY.js} +1 -1
  18. package/dist/chunks/{chunk-DXJC3QW7.js → chunk-3VT2PPKW.js} +1 -1
  19. package/dist/chunks/{chunk-4BUM6JEC.js → chunk-4JKWCLTQ.js} +1 -1
  20. package/dist/chunks/{chunk-AQUZCWM3.js → chunk-5TPJ5ECJ.js} +1 -1
  21. package/dist/chunks/{chunk-RCQYEHHD.js → chunk-5TTQCT3G.js} +1 -1
  22. package/dist/chunks/{chunk-NMMHXYDJ.js → chunk-5WFKBZCU.js} +1 -1
  23. package/dist/chunks/{chunk-P4QM63L3.js → chunk-5ZBDHIIE.js} +1 -1
  24. package/dist/chunks/{chunk-WD4KAKEX.js → chunk-64EDQ7UV.js} +1 -1
  25. package/dist/chunks/{chunk-KU4TPDPH.js → chunk-6LAGMWJE.js} +1 -1
  26. package/dist/chunks/{chunk-VJYOKU3C.js → chunk-6OD2FKUS.js} +1 -1
  27. package/dist/chunks/{chunk-65FJWWXG.js → chunk-6YR5IYHH.js} +1 -1
  28. package/dist/chunks/{chunk-AUO5DCEU.js → chunk-73COPJ32.js} +1 -1
  29. package/dist/chunks/{chunk-SSHE6B7Z.js → chunk-AITV76GO.js} +1 -1
  30. package/dist/chunks/{chunk-PLROXHG2.js → chunk-ATI52WMB.js} +1 -1
  31. package/dist/chunks/chunk-AWD72O3G.js +2 -0
  32. package/dist/chunks/{chunk-DKOVZ6R2.js → chunk-BQNU4HZW.js} +1 -1
  33. package/dist/chunks/{chunk-UANH7U3Y.js → chunk-BTEBZYK3.js} +1 -1
  34. package/dist/chunks/{chunk-3Z4VM2LF.js → chunk-BUMCJHQP.js} +1 -1
  35. package/dist/chunks/{chunk-BU6MW65V.js → chunk-BYVE4TMU.js} +1 -1
  36. package/dist/chunks/{chunk-PNPV2LDE.js → chunk-BZS2PA4O.js} +1 -1
  37. package/dist/chunks/{chunk-AFYYIJ6K.js → chunk-C7NQPICU.js} +1 -1
  38. package/dist/chunks/{chunk-EWH64WRR.js → chunk-CAYKEJJY.js} +1 -1
  39. package/dist/chunks/{chunk-K7KBFM2T.js → chunk-CBD554GZ.js} +1 -1
  40. package/dist/chunks/{chunk-7RJOCGQ6.js → chunk-CHRED2FK.js} +1 -1
  41. package/dist/chunks/{chunk-3A2Y7UK3.js → chunk-CQRA5TXF.js} +1 -1
  42. package/dist/chunks/{chunk-GYYJ47GX.js → chunk-CWE2N3JI.js} +1 -1
  43. package/dist/chunks/{chunk-ZYLLPRPU.js → chunk-CX4T7I47.js} +1 -1
  44. package/dist/chunks/{chunk-TAXCMCYZ.js → chunk-CX4U32VO.js} +4 -4
  45. package/dist/chunks/{chunk-7TM25J6S.js → chunk-DFSQ5HZ7.js} +2 -2
  46. package/dist/chunks/{chunk-2PXKSAG6.js → chunk-DLOJG7LP.js} +1 -1
  47. package/dist/chunks/{chunk-BGMAWETL.js → chunk-DNRC6TPJ.js} +1 -1
  48. package/dist/chunks/{chunk-5FSPDSAO.js → chunk-DUR32LJG.js} +1 -1
  49. package/dist/chunks/{chunk-FHDH4OUA.js → chunk-EHMA5XS7.js} +1 -1
  50. package/dist/chunks/{chunk-Z33RVGP6.js → chunk-ENY24ZBB.js} +1 -1
  51. package/dist/chunks/{chunk-JVNKSU27.js → chunk-F3IEAU7O.js} +1 -1
  52. package/dist/chunks/{chunk-M4A7G4S5.js → chunk-FOAM3YZQ.js} +1 -1
  53. package/dist/chunks/{chunk-VJR2GNRY.js → chunk-FVMTQSVW.js} +1 -1
  54. package/dist/chunks/{chunk-YI6ME6PU.js → chunk-GG6PM7TB.js} +1 -1
  55. package/dist/chunks/{chunk-DDOIPTOM.js → chunk-GMA365GI.js} +1 -1
  56. package/dist/chunks/{chunk-KCLMA2IH.js → chunk-GPGXBKXU.js} +1 -1
  57. package/dist/chunks/{chunk-JVMSN7LH.js → chunk-GR4MJJCE.js} +1 -1
  58. package/dist/chunks/{chunk-7OFD6TFD.js → chunk-HA762QYM.js} +1 -1
  59. package/dist/chunks/{chunk-Q7FBVLLB.js → chunk-HBGTHOOB.js} +1 -1
  60. package/dist/chunks/{chunk-AFH462DO.js → chunk-HT6ILPD6.js} +1 -1
  61. package/dist/chunks/{chunk-XYZV3FKD.js → chunk-I6KTJ3GH.js} +1 -1
  62. package/dist/chunks/{chunk-OUJ63LMU.js → chunk-IA6CTX7A.js} +1 -1
  63. package/dist/chunks/{chunk-XHACK2KR.js → chunk-IUYGQO2K.js} +1 -1
  64. package/dist/chunks/{chunk-55YD4UTW.js → chunk-IV2HEX3I.js} +1 -1
  65. package/dist/chunks/{chunk-MOXIGLN2.js → chunk-JALL5NPH.js} +1 -1
  66. package/dist/chunks/{chunk-U7X5ZLAL.js → chunk-JCHLDNCX.js} +1 -1
  67. package/dist/chunks/{chunk-7PKDJHT6.js → chunk-JH4RACOB.js} +1 -1
  68. package/dist/chunks/{chunk-MIFVX5PK.js → chunk-JSDGOQ5U.js} +1 -1
  69. package/dist/chunks/{chunk-65WRWLUD.js → chunk-JVEIK4RH.js} +1 -1
  70. package/dist/chunks/{chunk-PPF6EBTQ.js → chunk-K3WM4NEC.js} +1 -1
  71. package/dist/chunks/{chunk-CCZ276IA.js → chunk-KOIXRLZZ.js} +1 -1
  72. package/dist/chunks/{chunk-6C6ZCYTL.js → chunk-KRJZ5CW3.js} +1 -1
  73. package/dist/chunks/{chunk-CUB6PWAJ.js → chunk-KTQWWCP2.js} +6 -6
  74. package/dist/chunks/{chunk-Y4E5AAI7.js → chunk-KUEVP7WM.js} +1 -1
  75. package/dist/chunks/{chunk-U7D6Q744.js → chunk-L5L3H6CI.js} +1 -1
  76. package/dist/chunks/{chunk-VWWKWYSQ.js → chunk-LHTRQAPZ.js} +1 -1
  77. package/dist/chunks/{chunk-QLGP2OAQ.js → chunk-MLLMLXKG.js} +1 -1
  78. package/dist/chunks/{chunk-QUNQM2E3.js → chunk-MPEK4ZNY.js} +1 -1
  79. package/dist/chunks/{chunk-EGP6DF34.js → chunk-MPXOPL7R.js} +2 -2
  80. package/dist/chunks/{chunk-PHZZBXDO.js → chunk-MQMMJKOZ.js} +1 -1
  81. package/dist/chunks/{chunk-B66QCXH2.js → chunk-MWPMYCYB.js} +1 -1
  82. package/dist/chunks/{chunk-5G7BQAUA.js → chunk-N5FT6PTI.js} +1 -1
  83. package/dist/chunks/{chunk-SDHG6CKU.js → chunk-NDNSLCPE.js} +1 -1
  84. package/dist/chunks/{chunk-WCNPGKST.js → chunk-O4YHISU2.js} +1 -1
  85. package/dist/chunks/{chunk-IO5DZUKL.js → chunk-OI4DAZ4U.js} +1 -1
  86. package/dist/chunks/{chunk-Q73RKX7I.js → chunk-OIIE5GUK.js} +1 -1
  87. package/dist/chunks/{chunk-N5EAVX4G.js → chunk-OOKHHOIU.js} +1 -1
  88. package/dist/chunks/{chunk-7OKZCJHS.js → chunk-OXRN2257.js} +1 -1
  89. package/dist/chunks/{chunk-HES4VP3D.js → chunk-PYPXP5R3.js} +1 -1
  90. package/dist/chunks/{chunk-ZK3ET5EP.js → chunk-QKBMXL4D.js} +3 -3
  91. package/dist/chunks/{chunk-YAA7F5LI.js → chunk-QKGNAYSC.js} +1 -1
  92. package/dist/chunks/{chunk-KDER7R45.js → chunk-RIFWD5XM.js} +1 -1
  93. package/dist/chunks/{chunk-WZ35ICTE.js → chunk-RWBP2H4M.js} +1 -1
  94. package/dist/chunks/{chunk-SO4GMSNP.js → chunk-S5ACNR5Y.js} +1 -1
  95. package/dist/chunks/{chunk-M4ZHFDRJ.js → chunk-SRK4WX7D.js} +1 -1
  96. package/dist/chunks/{chunk-XY7HFXLH.js → chunk-SVLVIYH2.js} +1 -1
  97. package/dist/chunks/{chunk-FNGZ4UDZ.js → chunk-T6ML5SCD.js} +1 -1
  98. package/dist/chunks/{chunk-CO23RRN7.js → chunk-TD5YYA5Z.js} +1 -1
  99. package/dist/chunks/{chunk-7NCM6GBN.js → chunk-TOWY6Y23.js} +1 -1
  100. package/dist/chunks/{chunk-OXQ2WFIH.js → chunk-TR5UC5AF.js} +1 -1
  101. package/dist/chunks/{chunk-JQOVC35K.js → chunk-UCPD526R.js} +1 -1
  102. package/dist/chunks/{chunk-Y4I6CFZJ.js → chunk-UGDBMRCT.js} +1 -1
  103. package/dist/chunks/{chunk-E2JB5OCO.js → chunk-UZE3C2SF.js} +1 -1
  104. package/dist/chunks/{chunk-PACLKDTN.js → chunk-V4VM2R6D.js} +1 -1
  105. package/dist/chunks/{chunk-XOPHFUUY.js → chunk-VMBWCIGG.js} +1 -1
  106. package/dist/chunks/{chunk-CIZI6Z7D.js → chunk-VMW23TIZ.js} +1 -1
  107. package/dist/chunks/{chunk-4G3GTEVS.js → chunk-VSQPWLAG.js} +1 -1
  108. package/dist/chunks/{chunk-54755JYM.js → chunk-VXFGSFIE.js} +2 -2
  109. package/dist/chunks/{chunk-R2FYCJL6.js → chunk-W4JBPYGW.js} +1 -1
  110. package/dist/chunks/{chunk-JZKTBYNB.js → chunk-WMJEQK4G.js} +1 -1
  111. package/dist/chunks/{chunk-ESYPMD7Q.js → chunk-X2MJFTLS.js} +1 -1
  112. package/dist/chunks/{chunk-67U7PAMU.js → chunk-X7ZMUWJO.js} +1 -1
  113. package/dist/chunks/{chunk-WGQ3FMRF.js → chunk-XKDOPNQ5.js} +1 -1
  114. package/dist/chunks/{chunk-EYTTZ5H4.js → chunk-XLZMSD5K.js} +1 -1
  115. package/dist/chunks/{chunk-ZIQJDTQB.js → chunk-XTT3K3TR.js} +1 -1
  116. package/dist/chunks/{chunk-Q7P34B2O.js → chunk-YFHQRDNQ.js} +1 -1
  117. package/dist/chunks/{chunk-UGFSAG4U.js → chunk-YG3HITOU.js} +1 -1
  118. package/dist/chunks/{chunk-DWF3FCY4.js → chunk-Z5R4OSGC.js} +1 -1
  119. package/dist/chunks/{chunk-JT5YQ52I.js → chunk-Z6HWSTEP.js} +1 -1
  120. package/dist/chunks/{chunk-4PUOWSDE.js → chunk-ZEOYNUHL.js} +1 -1
  121. package/dist/chunks/{chunk-4KTGYHCE.js → chunk-ZMRP2A7K.js} +1 -1
  122. package/dist/chunks/{chunk-OL3L3U36.js → chunk-ZSWATWK2.js} +1 -1
  123. package/dist/chunks/cli-KXU5DNVV.js +2 -0
  124. package/dist/chunks/{command-5AXJMFYC.js → command-X35I53H3.js} +3 -3
  125. package/dist/chunks/{configuration-command-5LUNWPOL.js → configuration-command-VJUK34UQ.js} +1 -1
  126. package/dist/chunks/{connected-app-executor-DHXZE4X3.js → connected-app-executor-JBFJF2H5.js} +1 -1
  127. package/dist/chunks/{connected-evidence-NWMPICKJ.js → connected-evidence-CQ533AML.js} +1 -1
  128. package/dist/chunks/{connected-starting-assets-NRVXIKQ2.js → connected-starting-assets-RL5X6LZ7.js} +1 -1
  129. package/dist/chunks/{continual-UCKQ2QLH.js → continual-PHGIZFF6.js} +1 -1
  130. package/dist/chunks/{core-commands-ZPBX35M2.js → core-commands-5DYMDWXY.js} +1 -1
  131. package/dist/chunks/{dataset-preparation-authoring-UUYFWWCT.js → dataset-preparation-authoring-UDSX33YK.js} +1 -1
  132. package/dist/chunks/{datasets-6K3ZANIV.js → datasets-BW4JFUUU.js} +1 -1
  133. package/dist/chunks/{desktop-test-57INNJ76.js → desktop-test-RIG4CB2Z.js} +1 -1
  134. package/dist/chunks/{dist-2MKJC6HN.js → dist-C5XFRP53.js} +1 -1
  135. package/dist/chunks/{evaluation-coordination-B7CN4R2D.js → evaluation-coordination-6QJ6XTUX.js} +1 -1
  136. package/dist/chunks/{experiment-improvements-G357VLDB.js → experiment-improvements-2XF63AQ4.js} +1 -1
  137. package/dist/chunks/{experiments-BHQO26LJ.js → experiments-3S2BVNK6.js} +1 -1
  138. package/dist/chunks/{experiments-signal-BI6NKETB.js → experiments-signal-IRBHGGW5.js} +1 -1
  139. package/dist/chunks/{help-UQN5RUPA.js → help-Q2VMJVTR.js} +1 -1
  140. package/dist/chunks/host-profile-evaluation-tools-5LZQHA32.js +2 -0
  141. package/dist/chunks/{host-profile-external-dataset-KSEPXY2S.js → host-profile-external-dataset-C6ZPMTX6.js} +1 -1
  142. package/dist/chunks/{hosted-app-server-composition-WDDO6F23.js → hosted-app-server-composition-AYZM2HY6.js} +1 -1
  143. package/dist/chunks/{hosted-experiment-improvement-VVYXQ65K.js → hosted-experiment-improvement-SMZJYRJ7.js} +1 -1
  144. package/dist/chunks/hosted-harness-runtime-QWIFAITG.js +2 -0
  145. package/dist/chunks/{hosted-profile-candidate-PTGQLPZO.js → hosted-profile-candidate-WOMWAE5N.js} +1 -1
  146. package/dist/chunks/{hosted-profile-compiler-FS5R6CHJ.js → hosted-profile-compiler-NZ2BXN32.js} +1 -1
  147. package/dist/chunks/{hosted-profile-evaluation-control-UUEZEMXU.js → hosted-profile-evaluation-control-3ECFFM7E.js} +1 -1
  148. package/dist/chunks/{hosted-profile-evaluation-inspection-4F7OEF4T.js → hosted-profile-evaluation-inspection-TM7RKONG.js} +1 -1
  149. package/dist/chunks/{hosted-profile-evaluation-preparation-LIJJZDHQ.js → hosted-profile-evaluation-preparation-2MZIRT75.js} +1 -1
  150. package/dist/chunks/{hosted-tasksets-KCLNMPG5.js → hosted-tasksets-IUK3VWSL.js} +1 -1
  151. package/dist/chunks/{human-review-PX6DBIFT.js → human-review-PG4WWVWV.js} +1 -1
  152. package/dist/chunks/{import-2HEYPHPW.js → import-FAZAVZBF.js} +1 -1
  153. package/dist/chunks/{learning-Y3UKNUGE.js → learning-3XDYMYBE.js} +1 -1
  154. package/dist/chunks/{learning-LSXBL5DB.js → learning-OR4CYV4B.js} +1 -1
  155. package/dist/chunks/local-harness-improvement-runtime-OYLTKMJU.js +2 -0
  156. package/dist/chunks/local-harness-taskset-review-I7YU4RZI.js +2 -0
  157. package/dist/chunks/{model-projects-6YWVD2TS.js → model-projects-POZRHXTF.js} +1 -1
  158. package/dist/chunks/{opchat-66BCRKEZ.js → opchat-TCZA6373.js} +1 -1
  159. package/dist/chunks/{opchat-bounded-chat-KQWXZVFN.js → opchat-bounded-chat-GMYDXLWB.js} +1 -1
  160. package/dist/chunks/{organizations-IOYWDOCC.js → organizations-PYKGA2P2.js} +1 -1
  161. package/dist/chunks/{profile-YH6G3ZTD.js → profile-GYYI555I.js} +1 -1
  162. package/dist/chunks/project-action-payload-FE6M2OXJ.js +2 -0
  163. package/dist/chunks/{project-agent-RYVMKW2F.js → project-agent-4ISJFMJD.js} +1 -1
  164. package/dist/chunks/{published-experiment-source-SDXUVPE7.js → published-experiment-source-E2YAJCLM.js} +1 -1
  165. package/dist/chunks/{refiner-profile-service-56VYLZQJ.js → refiner-profile-service-LKGXD5WJ.js} +1 -1
  166. package/dist/chunks/{runtime-ISLJIGWC.js → runtime-UDLOZD4Y.js} +2 -2
  167. package/dist/chunks/{sandbox-command-DI45NRTV.js → sandbox-command-4J6DAY7T.js} +1 -1
  168. package/dist/chunks/{sandbox-template-T42MDUSR.js → sandbox-template-TSXWJMWG.js} +1 -1
  169. package/dist/chunks/saved-work-QTEBKVUB.js +2 -0
  170. package/dist/chunks/{send-turn-YLY3YNEQ.js → send-turn-4MH4WMLW.js} +1 -1
  171. package/dist/chunks/{setup-D6TY2GWV.js → setup-IVT2FQSE.js} +1 -1
  172. package/dist/chunks/{src-7RN7BF4W.js → src-DC7N2H7A.js} +111 -113
  173. package/dist/chunks/{src-LF5X4RNQ.js → src-TOSQX36I.js} +1 -1
  174. package/dist/chunks/{standalone-experiment-turn-owner-TW5MTWIO.js → standalone-experiment-turn-owner-UYPA6XHW.js} +1 -1
  175. package/dist/chunks/{store-chat-resources-IRHBW2EC.js → store-chat-resources-QLXKKYYC.js} +1 -1
  176. package/dist/chunks/{store-continual-support-reviews-3KK42L4I.js → store-continual-support-reviews-4F2BOG3H.js} +1 -1
  177. package/dist/chunks/{store-conversation-serving-IVURK52V.js → store-conversation-serving-EUD47W6X.js} +1 -1
  178. package/dist/chunks/{store-create-improve-UTCLBXF2.js → store-create-improve-QUOTNNIM.js} +1 -1
  179. package/dist/chunks/{store-datasets-4AQOVAQY.js → store-datasets-ZUC7CNVO.js} +1 -1
  180. package/dist/chunks/{store-evaluation-results-PK2P3IMH.js → store-evaluation-results-LHHPHESK.js} +1 -1
  181. package/dist/chunks/{store-harness-workspaces-YEXB4IRV.js → store-harness-workspaces-TKX5PZWP.js} +1 -1
  182. package/dist/chunks/{store-human-review-O4BVHP25.js → store-human-review-7WZWRJ6X.js} +1 -1
  183. package/dist/chunks/{store-learned-preference-migration-validation-44SVX6YB.js → store-learned-preference-migration-validation-MVNKBR4X.js} +1 -1
  184. package/dist/chunks/{store-learning-SIUQIY5C.js → store-learning-WLUW2PWE.js} +1 -1
  185. package/dist/chunks/{store-learning-credentials-BUHR7SN6.js → store-learning-credentials-FDKCEDHK.js} +1 -1
  186. package/dist/chunks/{store-local-experiments-BHVTKPPE.js → store-local-experiments-HB53QFLL.js} +1 -1
  187. package/dist/chunks/{store-model-batch-review-RVAYUVK2.js → store-model-batch-review-O3I6GIAA.js} +1 -1
  188. package/dist/chunks/{store-model-configuration-AYFGMC5D.js → store-model-configuration-CDIGNU6Q.js} +1 -1
  189. package/dist/chunks/{store-model-project-preparation-5DEIS7TB.js → store-model-project-preparation-QMQ2HMJV.js} +1 -1
  190. package/dist/chunks/{store-modification-recordings-LCPK6K2T.js → store-modification-recordings-W4VEZKKQ.js} +1 -1
  191. package/dist/chunks/{store-preference-comparison-5YVIQNVB.js → store-preference-comparison-JKURBESE.js} +1 -1
  192. package/dist/chunks/{store-sidebar-file-bookmarks-WLMYDA4E.js → store-sidebar-file-bookmarks-KAEDHVVF.js} +1 -1
  193. package/dist/chunks/{store-sidebar-preferences-AFMYIDWT.js → store-sidebar-preferences-QPBLTHY6.js} +1 -1
  194. package/dist/chunks/{store-subagents-KFPVSTRO.js → store-subagents-ZELQP3MX.js} +1 -1
  195. package/dist/chunks/{store-task-inbox-L6IQTY26.js → store-task-inbox-4ZDQR2E7.js} +1 -1
  196. package/dist/chunks/{store-task-inventory-QWS2C656.js → store-task-inventory-CTIJDLYE.js} +1 -1
  197. package/dist/chunks/{store-taskset-drafts-EAOOY6CR.js → store-taskset-drafts-FRPBYLTW.js} +1 -1
  198. package/dist/chunks/{store-training-FYXZU2FE.js → store-training-WQAYUT7B.js} +1 -1
  199. package/dist/chunks/{store-training-jobs-3N3VKPIY.js → store-training-jobs-O5EHGTH7.js} +1 -1
  200. package/dist/chunks/{store-training-models-VOFVGPZR.js → store-training-models-YSZMC66T.js} +1 -1
  201. package/dist/chunks/{taskset-HNDIGYQG.js → taskset-OVYM4QMS.js} +1 -1
  202. package/dist/chunks/{taskset-packages-WMG5DUBN.js → taskset-packages-FUQWNTSB.js} +1 -1
  203. package/dist/chunks/{taskset-packages-T6B6HYKZ.js → taskset-packages-GM6IUOTY.js} +1 -1
  204. package/dist/chunks/{teams-bot-Z5CZLWE4.js → teams-bot-U2M3ORWR.js} +1 -1
  205. package/dist/chunks/{tool-learning-ZQ6NSJ5K.js → tool-learning-NXVR4YPA.js} +1 -1
  206. package/dist/chunks/{training-JTYQA7GA.js → training-EQ7G5FDY.js} +1 -1
  207. package/dist/chunks/training-LQUAL4Y4.js +2 -0
  208. package/dist/chunks/training-PEZYJ2SN.js +2 -0
  209. package/dist/chunks/{training-hosted-36SZFS4U.js → training-hosted-XKSUTMLQ.js} +1 -1
  210. package/dist/chunks/{training-hosted-alphaedit-HSMRDJTD.js → training-hosted-alphaedit-VCOEYLKK.js} +1 -1
  211. package/dist/chunks/{training-hosted-decision-7JALOU6O.js → training-hosted-decision-IKWWXA56.js} +1 -1
  212. package/dist/chunks/{training-hosted-engram-SXO75MFG.js → training-hosted-engram-3TOPPVSW.js} +1 -1
  213. package/dist/chunks/{training-hosted-learning-E2N32YU5.js → training-hosted-learning-UEBGSSNC.js} +1 -1
  214. package/dist/chunks/{training-hosted-modification-comparison-TXFDJFTG.js → training-hosted-modification-comparison-C6S4JFHW.js} +1 -1
  215. package/dist/chunks/{training-hosted-neuron-training-J42WK4EH.js → training-hosted-neuron-training-EP2U4PHG.js} +1 -1
  216. package/dist/chunks/{training-hosted-serving-report-BAEABGJH.js → training-hosted-serving-report-KJMRZJLQ.js} +1 -1
  217. package/dist/chunks/{training-hosted-steering-T556BUBG.js → training-hosted-steering-I27DV6A2.js} +1 -1
  218. package/dist/chunks/{training-model-start-P3PXDWNT.js → training-model-start-NWXNGRDC.js} +1 -1
  219. package/dist/chunks/{workspaces-EK62ANTB.js → workspaces-FVQYJPOS.js} +1 -1
  220. package/dist/cli.js +1 -1
  221. package/dist/index.js +1 -1
  222. package/dist/skills/manifest.json +3 -3
  223. package/dist/skills/openpond-cli/references/experiments-and-training.md +19 -0
  224. package/dist/web/assets/App-QM6Y2Eod.js +54 -0
  225. package/dist/web/assets/{AppDialog-x1HU1uLv.js → AppDialog-C8um481a.js} +1 -1
  226. package/dist/web/assets/{AppTerminalPanel-CNIKmqKc.js → AppTerminalPanel-OwNr-bp6.js} +2 -2
  227. package/dist/web/assets/{AppToastContext-DNWd43HS.js → AppToastContext-BQ4iRFif.js} +1 -1
  228. package/dist/web/assets/{AppsView-BvOD83Z1.js → AppsView-mk8m_Cra.js} +1 -1
  229. package/dist/web/assets/{AttachmentTypeIcon-BLdDr3JZ.js → AttachmentTypeIcon-SITPqTtF.js} +1 -1
  230. package/dist/web/assets/{BrowserSidebar-Ar0FlFKg.js → BrowserSidebar-BghdIKTB.js} +1 -1
  231. package/dist/web/assets/{CartesianChart-tS7f1HZv.js → CartesianChart-BdRx7q_O.js} +1 -1
  232. package/dist/web/assets/{ChatTimelineEntry-z7_kur3h.js → ChatTimelineEntry-BBOnAzJB.js} +1 -1
  233. package/dist/web/assets/{CollaborationTabs-CaiFEKrv.js → CollaborationTabs-Beja-9s5.js} +1 -1
  234. package/dist/web/assets/{CommandMenu-BpubEqaA.js → CommandMenu-CQtrSUpu.js} +1 -1
  235. package/dist/web/assets/{CommunityView-TGR4s99l.js → CommunityView-LPTAakS-.js} +1 -1
  236. package/dist/web/assets/{ComposerAttachments-DPWCjKXz.js → ComposerAttachments-DI-Gr7Zw.js} +1 -1
  237. package/dist/web/assets/{ComposerCreateImproveStrip-Drji01_6.js → ComposerCreateImproveStrip-CY5Uw1yc.js} +1 -1
  238. package/dist/web/assets/{ConversationImportsSettings-B_oW0cz7.js → ConversationImportsSettings-DFwhKERw.js} +1 -1
  239. package/dist/web/assets/{DatasetReviewImport-Dr3unJSY.js → DatasetReviewImport-C9xraQk7.js} +1 -1
  240. package/dist/web/assets/{ExperimentTrainingDataWorkspace-DObvpJAw.js → ExperimentTrainingDataWorkspace-Cx58S6R_.js} +2 -2
  241. package/dist/web/assets/{FilePagePreview-9kkXbARN.js → FilePagePreview-dlbmR8s8.js} +2 -2
  242. package/dist/web/assets/{GetStartedView-Dv2b_SlH.js → GetStartedView-BkTV_shK.js} +1 -1
  243. package/dist/web/assets/{GettingStartedDialog-sPaPMc61.js → GettingStartedDialog-DulDLYnr.js} +1 -1
  244. package/dist/web/assets/{HostedModelLearningReview-BlwhGxS6.js → HostedModelLearningReview--fXJEOfI.js} +1 -1
  245. package/dist/web/assets/{HostedModelLearningSettings-B5ahk3je.js → HostedModelLearningSettings-BEb7B_PC.js} +1 -1
  246. package/dist/web/assets/{HtmlVisual-rGsClq0p.js → HtmlVisual-BS61T2qR.js} +1 -1
  247. package/dist/web/assets/{LabModelVersionDetailPage-Da7AwZWV.js → LabModelVersionDetailPage-CmzUIDbR.js} +1 -1
  248. package/dist/web/assets/{LabModelWorkspace-DTeYViWH.js → LabModelWorkspace-DoAnQKWk.js} +1 -1
  249. package/dist/web/assets/{LabSkillSidebar-BieHbNl6.js → LabSkillSidebar-DJTm7ZQs.js} +1 -1
  250. package/dist/web/assets/{LabsRoute-D3XqPB0-.js → LabsRoute-DNtBot4a.js} +4 -4
  251. package/dist/web/assets/{LearningBatchesPage-CCBuf2u4.js → LearningBatchesPage-C_oQjciE.js} +1 -1
  252. package/dist/web/assets/{MainChatThread-B6BQJfcq.js → MainChatThread-D9e-to8e.js} +2 -2
  253. package/dist/web/assets/{MainPane-D3fQou29.js → MainPane-mWeD0M-f.js} +6 -6
  254. package/dist/web/assets/{ModelProjectPageHeader-BZn9Lu_J.js → ModelProjectPageHeader-BecKU_2p.js} +1 -1
  255. package/dist/web/assets/{NativeSetupTerminal-Bglqab_g.js → NativeSetupTerminal-DO0DN4fH.js} +2 -2
  256. package/dist/web/assets/{NativeSkillSidebar-pUGRdnV_.js → NativeSkillSidebar-jnxgQASC.js} +1 -1
  257. package/dist/web/assets/{NewProjectDialog-BpHN38MA.js → NewProjectDialog-ByHR4vMf.js} +1 -1
  258. package/dist/web/assets/{OutputsPage-LunDCQ6w.js → OutputsPage-DZY4BUCy.js} +1 -1
  259. package/dist/web/assets/{PageChrome-DThEcWAx.js → PageChrome-DjPuwWsn.js} +1 -1
  260. package/dist/web/assets/{ProjectsPage-vct_TQgL.js → ProjectsPage-DKbwhIM4.js} +1 -1
  261. package/dist/web/assets/{RightChatPanelStack-CgFK7DY0.js → RightChatPanelStack-BARH0XuL.js} +1 -1
  262. package/dist/web/assets/RightSidebarHomePanel-qKL8dZrN.js +1 -0
  263. package/dist/web/assets/{ScheduledWorkPage-mmaZfybl.js → ScheduledWorkPage-CElrmRz9.js} +1 -1
  264. package/dist/web/assets/{SettingsView-CJfeRsWR.js → SettingsView-CsFSjE9s.js} +3 -3
  265. package/dist/web/assets/{TasksetDraftEditorPrimitives-CuimAfkv.js → TasksetDraftEditorPrimitives-DJoYkvWq.js} +1 -1
  266. package/dist/web/assets/{TeamChatView-BcK0lF1b.js → TeamChatView-D9Y4e98Y.js} +1 -1
  267. package/dist/web/assets/{TerminalOverlay-0pzEvy-C.js → TerminalOverlay-CUO8yZjy.js} +1 -1
  268. package/dist/web/assets/{TrainingCreationPanel-CcyzFz7l.js → TrainingCreationPanel-_mnLQ1HA.js} +1 -1
  269. package/dist/web/assets/{TrainingDraftPanel-DSLZXdLz.js → TrainingDraftPanel-CCqQTHo5.js} +1 -1
  270. package/dist/web/assets/{UsageSettingsSection-BT9pcnCn.js → UsageSettingsSection-CdWq5oYC.js} +1 -1
  271. package/dist/web/assets/WorkSidebarPanel-DRXaK-E6.js +1 -0
  272. package/dist/web/assets/{WorkspaceDiffPanel-Bbz5qrVA.js → WorkspaceDiffPanel-CdHr8bX6.js} +3 -3
  273. package/dist/web/assets/{WorkspaceEnvironmentMenu-6hXpvMTl.js → WorkspaceEnvironmentMenu-BnUh4dg9.js} +1 -1
  274. package/dist/web/assets/{WorkspaceFileLocation-BijVemBl.js → WorkspaceFileLocation-VzrSq_Ki.js} +1 -1
  275. package/dist/web/assets/{WorkspaceGitDialogs-BOO0E5i9.js → WorkspaceGitDialogs-nwvQOm9r.js} +1 -1
  276. package/dist/web/assets/{WorkspaceMonacoEditor-B_YzK7Do.js → WorkspaceMonacoEditor-m3bCIpZe.js} +3 -3
  277. package/dist/web/assets/{WorkspacePdfPreview-CFti1fvu.js → WorkspacePdfPreview-u6Iv0qr0.js} +2 -2
  278. package/dist/web/assets/{WorkspacePresentationPreview-DPAhNaV6.js → WorkspacePresentationPreview-CjvTjhUO.js} +1 -1
  279. package/dist/web/assets/{bot-BE2rL_qv.js → bot-DiDSZBLn.js} +1 -1
  280. package/dist/web/assets/{chat-resources-Beh5lB36.js → chat-resources-CmBtWC5V.js} +1 -1
  281. package/dist/web/assets/chevron-down-CqxKXYPf.js +1 -0
  282. package/dist/web/assets/chevron-right-ClP6ukIq.js +1 -0
  283. package/dist/web/assets/chevron-up-DY7wpdJ1.js +1 -0
  284. package/dist/web/assets/{chunk-C3TS766N-j1MK0e3c.js → chunk-C3TS766N-DSA4vs-Y.js} +1 -1
  285. package/dist/web/assets/{client-BnJhN-14.js → client-_uDCFdg5.js} +1 -1
  286. package/dist/web/assets/{client-choice-storage-CQ0CNkzG.js → client-choice-storage-CRKZpilL.js} +1 -1
  287. package/dist/web/assets/{cloud-upload-DFjZE4O4.js → cloud-upload-CWamjPts.js} +1 -1
  288. package/dist/web/assets/{copy-CGrLUtw5.js → copy-B56YjDkW.js} +1 -1
  289. package/dist/web/assets/{cssMode-DvRw2fUx.js → cssMode-BuC9qQvo.js} +1 -1
  290. package/dist/web/assets/{external-link-3ZnEFUXd.js → external-link-BSn21e-y.js} +1 -1
  291. package/dist/web/assets/{folder-open-i9n8450i.js → folder-open-CaJGWSr2.js} +1 -1
  292. package/dist/web/assets/{folder-plus-cu8Md_ej.js → folder-plus-eTUep-az.js} +1 -1
  293. package/dist/web/assets/{git-commit-horizontal-CwckmC09.js → git-commit-horizontal-Buk_hy6T.js} +1 -1
  294. package/dist/web/assets/{htmlMode-8VF4Ovtw.js → htmlMode-D7kF2kDL.js} +1 -1
  295. package/dist/web/assets/{icons-4yRSxBZj.js → icons-B4B5eUyR.js} +1 -1
  296. package/dist/web/assets/{image-D-umhyyK.js → image--4h1aK2l.js} +1 -1
  297. package/dist/web/assets/{index-DiVhx1GM.js → index-CCaTs7xt.js} +2 -2
  298. package/dist/web/assets/{info-Dq2RsPDJ.js → info-DjMTH4sJ.js} +1 -1
  299. package/dist/web/assets/{jsonMode-CvCYQHkB.js → jsonMode-BVX_7KjE.js} +1 -1
  300. package/dist/web/assets/loader-circle-DNHvEoaP.js +1 -0
  301. package/dist/web/assets/{lspLanguageFeatures-CjufNNFF.js → lspLanguageFeatures-RBOb-3wX.js} +1 -1
  302. package/dist/web/assets/{maximize-2-CKY8dua6.js → maximize-2-Cjg-f1xT.js} +1 -1
  303. package/dist/web/assets/{message-square-CVDgKlKX.js → message-square-oIMQDMc3.js} +1 -1
  304. package/dist/web/assets/{monaco.contribution-BYAgjZbj.js → monaco.contribution-CIbGU5-C.js} +2 -2
  305. package/dist/web/assets/{monaco.contribution-PjJ1258q.js → monaco.contribution-CIwt2mTE.js} +2 -2
  306. package/dist/web/assets/{monaco.contribution-BYY3-y9l.js → monaco.contribution-Dd1cPdSS.js} +2 -2
  307. package/dist/web/assets/{monaco.contribution-Bh0CKj9i.js → monaco.contribution-KRLNg324.js} +2 -2
  308. package/dist/web/assets/{monitor-UYe42gew.js → monitor-BWaitd6I.js} +1 -1
  309. package/dist/web/assets/{paperclip-DrlSVUoz.js → paperclip-FYK6OySO.js} +1 -1
  310. package/dist/web/assets/{pdf-BMhday2W.js → pdf-DbwlsqZP.js} +1 -1
  311. package/dist/web/assets/play-DieChKfF.js +1 -0
  312. package/dist/web/assets/plus-DkfcQyma.js +1 -0
  313. package/dist/web/assets/{presentation-DcZKqH7w.js → presentation-B6MaAPC7.js} +1 -1
  314. package/dist/web/assets/{python-CiA01i07.js → python-DRYJxjiM.js} +1 -1
  315. package/dist/web/assets/{refresh-cw-00D-GDnF.js → refresh-cw-DOVpqCfJ.js} +1 -1
  316. package/dist/web/assets/{save-CXe7bqR7.js → save-BuyyyR4Q.js} +1 -1
  317. package/dist/web/assets/{settings-lists-B5J40WM6.js → settings-lists-BeAdxSjx.js} +1 -1
  318. package/dist/web/assets/square-D0YnIVh6.js +1 -0
  319. package/dist/web/assets/{square-terminal-DxC7TTds.js → square-terminal-DTOIZy6_.js} +1 -1
  320. package/dist/web/assets/{submit-issue-command-Dq3TqJLV.js → submit-issue-command-V--K9lVQ.js} +1 -1
  321. package/dist/web/assets/{toggleHighContrast-BH3Jckfo.js → toggleHighContrast-nNzCoE0h.js} +1 -1
  322. package/dist/web/assets/training-DZgfVcI-.js +1 -0
  323. package/dist/web/assets/{training-model-data-B6IZ3x-t.js → training-model-data-CWoTokkb.js} +1 -1
  324. package/dist/web/assets/{tsMode-DXkj4bqC.js → tsMode-BfVi5_FZ.js} +1 -1
  325. package/dist/web/assets/{upload-B3KRHVHl.js → upload-C2MnlWjj.js} +1 -1
  326. package/dist/web/assets/{useAccountSettings-BGRkTRrp.js → useAccountSettings-QwRbZIKu.js} +1 -1
  327. package/dist/web/assets/{useAgentInventory-D_1AlAZJ.js → useAgentInventory-B7xEgMCA.js} +1 -1
  328. package/dist/web/assets/{useChatContextSelection-hoMSuUSE.js → useChatContextSelection-O6wo4EqD.js} +1 -1
  329. package/dist/web/assets/{useLocalAgentSchedules-DxTER7Ow.js → useLocalAgentSchedules-DpHnOGoV.js} +1 -1
  330. package/dist/web/assets/{useQuery-DkPec_9x.js → useQuery-CvZ8bzdW.js} +1 -1
  331. package/dist/web/assets/{wifi-off-CMzpvbWl.js → wifi-off-B8d12Alh.js} +1 -1
  332. package/dist/web/assets/{workers-ziY_bTv2.js → workers-sIVKxb8c.js} +1 -1
  333. package/dist/web/assets/x-BvVvVB-j.js +1 -0
  334. package/dist/web/assets/{yaml-mSvqVSko.js → yaml-8-aLM3zj.js} +1 -1
  335. package/dist/web/index.html +1 -1
  336. package/docs/command-reference.md +1 -0
  337. package/package.json +1 -1
  338. package/dist/chunks/app-server-runtime-B7AMBGQZ.js +0 -2
  339. package/dist/chunks/chunk-6D3FI2XT.js +0 -2
  340. package/dist/chunks/chunk-VEBW7NKD.js +0 -2
  341. package/dist/chunks/cli-ALEEFAJ7.js +0 -2
  342. package/dist/chunks/host-profile-evaluation-tools-UF4ATIUF.js +0 -2
  343. package/dist/chunks/hosted-harness-runtime-MMTLCL23.js +0 -2
  344. package/dist/chunks/local-harness-improvement-runtime-3YJQRYXC.js +0 -2
  345. package/dist/chunks/local-harness-taskset-review-E5GN5LTR.js +0 -2
  346. package/dist/chunks/project-action-payload-53OH6WDH.js +0 -2
  347. package/dist/chunks/saved-work-54I5ZJTC.js +0 -2
  348. package/dist/chunks/training-5NT2YB2L.js +0 -2
  349. package/dist/chunks/training-UY6KRG4M.js +0 -2
  350. package/dist/web/assets/App-CXhxya9x.js +0 -54
  351. package/dist/web/assets/RightSidebarHomePanel-BJmzUcmy.js +0 -1
  352. package/dist/web/assets/WorkSidebarPanel-CP-nHAsJ.js +0 -1
  353. package/dist/web/assets/chevron-down-Bn8yph2O.js +0 -1
  354. package/dist/web/assets/chevron-right-BU-jUmb2.js +0 -1
  355. package/dist/web/assets/chevron-up-DacwuDJZ.js +0 -1
  356. package/dist/web/assets/loader-circle-DBl6qqtR.js +0 -1
  357. package/dist/web/assets/play-DIqZnaNf.js +0 -1
  358. package/dist/web/assets/plus-CFNxAPMK.js +0 -1
  359. package/dist/web/assets/square-DJEaBefe.js +0 -1
  360. package/dist/web/assets/training-DWfghwfZ.js +0 -1
  361. package/dist/web/assets/x-omjwMPbJ.js +0 -1
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as j}from"./chunk-Y4I6CFZJ.js";import{j as y}from"./chunk-BU6MW65V.js";import{f as i,m as s}from"./chunk-HIQPGYVH.js";import{c as H,d as w,f as k}from"./chunk-LK77GI6M.js";import{Bb as h,Eb as I,Fb as E,oa as v,pa as g,wb as f}from"./chunk-ZY32SZ2P.js";import{A as e}from"./chunk-X2J2P5ZT.js";import{a as m}from"./chunk-FTQLQJQV.js";var A=e.object({sourcePass:i,graders:j.shape.graders,mappings:j.shape.mappings,maximumCostUsd:e.number().finite().positive().max(1e4)}).strict(),C=e.object({externalDatasetBinding:v,scoring:A.optional(),modelId:e.string().min(1).max(300),maximumCostUsd:e.number().finite().positive().max(1e4)}).strict(),R=e.object({source:e.enum(["local","github","openpond_git"]),repositoryId:e.string().trim().min(1),profileId:e.string().trim().min(1)}).strict(),n=e.string().min(1).max(240),c=e.string().regex(/^[a-f0-9]{64}$/),x=e.object({schemaVersion:e.literal("openpond.experimentImprovement.v1"),id:n,operationId:n,requestHash:c,actorId:n,teamId:n,projectId:n.nullable(),ownerWorkspaceId:n,ownerRevision:e.number().int().nonnegative(),ownerSourceRevision:e.string().min(1).max(500),baseRelease:i,profileRef:R,baseProfileSourceRevision:e.string().min(1).max(500),evidence:e.object({manifest:f,result:h}).strict(),component:e.object({kind:e.enum(["skill","workflow","agent","instruction"]),path:e.string().min(1).max(2e3),workflowId:n.optional()}).strict(),mode:e.enum(["manual","llm_assisted"]),status:e.enum(["draft","authoring_queued","authoring","frozen","testing","ready_for_review","adopting","accepted","rolled_back","declined","failed","cancelled"]),revision:e.number().int().positive(),limits:e.object({maximumCostUsd:e.number().finite().positive(),maximumAuthoringSteps:e.number().int().min(1).max(500),maximumDurationMs:e.number().int().min(1e3).max(864e5)}).strict(),authoringSteps:e.number().int().nonnegative().max(500),work:e.object({sessionId:n,turnId:n,revision:e.number().int().positive(),startedAt:e.string().datetime()}).strict().nullable(),frozen:e.object({release:i,sourceRevision:e.string().min(1).max(500),profileSourceRevision:e.string().min(1).max(500),authoringHash:c,partitionHash:c,executableSourceHash:c,protectedClosureHash:c,candidateRevision:e.number().int().positive(),diff:e.array(e.object({path:e.string(),before:c.nullable(),after:c.nullable()}).strict()).max(1e4)}).strict().nullable(),test:e.object({recipe:C,recipeHash:e.string().regex(/^[a-f0-9]{64}$/),baselineOperationId:e.string(),candidateOperationId:e.string(),cancelRequestedAt:e.string().datetime().nullable(),dispatching:e.object({kind:e.enum(["baseline","candidate"]),token:n,pid:e.number().int().positive(),processStart:e.string().nullable(),startedAt:e.string().datetime()}).strict().nullable()}).strict().nullable(),comparison:e.object({baseline:e.object({manifest:f,result:h}).strict(),candidate:e.object({manifest:f,result:h}).strict(),frozenHash:c,humanProjection:w.optional()}).strict().nullable(),adoptionIntent:e.object({operationId:n,expectedOwnerRevision:e.number().int().nonnegative(),frozenHash:c,humanProjection:w.optional()}).strict().nullable(),acceptance:i.nullable(),rollback:i.nullable(),error:e.string().max(2e3).nullable(),createdAt:e.string().datetime(),updatedAt:e.string().datetime(),contentHash:c}).strict();function D(r){let t=x.parse(r),{contentHash:l,...b}=t;if(s(b)!==l)throw new Error("Improvement state integrity failed.");if(I(t.evidence),t.evidence.manifest.teamId!==t.teamId||t.evidence.result.status!=="completed"||!t.evidence.result.cases.some(o=>o.status==="completed"))throw new Error("Improvement requires usable completed owner evidence.");if(t.test&&(s(t.test.recipe)!==t.test.recipeHash||g(t.test.recipe.externalDatasetBinding).profileId!==t.profileRef.profileId))throw new Error("The test recipe changed its exact selected Profile.");if(t.comparison?.humanProjection){let o=k(t.comparison.humanProjection);if(o.teamId!==t.teamId||o.projectId!==t.projectId||s(o.baseline)!==s(t.comparison.baseline)||s(o.candidate)!==s(t.comparison.candidate))throw new Error("Human comparison projection differs from its exact owner evidence.")}if(t.comparison&&(I(t.comparison.baseline),I(t.comparison.candidate),!t.frozen||t.comparison.frozenHash!==s(t.frozen)||!E(t.comparison.baseline,t.comparison.candidate).comparable))throw new Error("Improvement comparison is not bound to a comparable frozen candidate.");if(t.status==="ready_for_review"&&(!t.frozen||!t.comparison))throw new Error("Improvement is missing qualification.");if(t.status==="adopting"&&(!t.adoptionIntent||!t.frozen||t.adoptionIntent.frozenHash!==s(t.frozen)))throw new Error("Improvement adoption intent is not bound to its tested revision.");if(t.status==="accepted"&&(!t.acceptance||!t.comparison||!t.frozen))throw new Error("Improvement acceptance is missing its exact qualification receipt.");if(t.status==="rolled_back"&&(!t.acceptance||!t.rollback))throw new Error("Profile rollback is missing its durable owner receipt.");return t}m(D,"verifyExperimentImprovementState");function X(r){return D({...r,contentHash:s(r)})}m(X,"sealExperimentImprovementState");var Y=e.object({states:e.array(x).max(50),nextCursor:n.nullable()}).strict(),T=e.object({operationId:n,ownerWorkspaceId:n,expectedOwnerRevision:e.number().int().nonnegative(),baseRelease:i,profileRef:R,profileSourceRevision:e.string().min(1).max(500),projectId:n.nullable(),evidence:i,component:x.shape.component,mode:x.shape.mode,limits:x.shape.limits}).strict(),Z=e.discriminatedUnion("operation",[e.object({operation:e.literal("list"),limit:e.number().int().min(1).max(50).default(30),cursor:n.optional()}).strict(),e.object({operation:e.literal("options"),evidence:i}).strict(),e.object({operation:e.literal("start"),request:T}).strict(),e.object({operation:e.enum(["read","humanComparisonOptions"]),id:n}).strict(),e.object({operation:e.literal("instructions"),id:n}).strict(),e.object({operation:e.literal("edit"),id:n,revision:e.number().int().positive(),expectedFileHash:c,text:e.string().max(25e4)}).strict(),e.object({operation:e.literal("mode"),id:n,revision:e.number().int().positive(),mode:e.enum(["manual","llm_assisted"])}).strict(),e.object({operation:e.literal("author"),id:n,revision:e.number().int().positive(),modelId:n,prompt:e.string().min(1).max(2e4)}).strict(),e.object({operation:e.enum(["freeze","finishAuthoring","useCandidate","discard","cancel","rollback"]),id:n,revision:e.number().int().positive()}).strict(),e.object({operation:e.literal("test"),id:n,revision:e.number().int().positive(),recipe:C}).strict(),e.object({operation:e.literal("compare"),id:n,revision:e.number().int().positive(),baseline:i,candidate:i,humanSelections:H.optional()}).strict()]),S=e.object({teamId:n,evidence:i,scoring:A.optional(),profiles:e.array(e.object({id:c,name:e.string(),profileRef:R,ownerWorkspaceId:n,ownerRevision:e.number().int().nonnegative(),baseRelease:i,profileSourceRevision:e.string(),components:e.array(e.object({kind:e.enum(["skill","instruction","agent","workflow"]),path:e.string(),agentId:e.string().optional(),workflowId:e.string().optional(),label:e.string(),binding:v}).strict()).max(500)}).strict()).max(100)}).strict(),O=e.object({candidateId:n,actorId:n,teamId:n,projectId:n.nullable(),candidateRevision:e.number().int().positive(),recipeHash:c,baseline:e.object({manifest:f,result:h}).strict(),candidate:e.object({manifest:f,result:h}).strict(),contentHash:c}).strict();function U(r){let t=O.parse(r),{contentHash:l,...b}=t;if(s(b)!==l)throw new Error("Accepted Human discovery integrity failed.");for(let o of[t.baseline,t.candidate])if(I(o),o.manifest.teamId!==t.teamId||o.manifest.lineage?.humanProjection)throw new Error("Discovery must retain original owner evidence.");return t}m(U,"verifyExperimentImprovementHumanOptions");function ee(r,t){if(!r.test||r.test.cancelRequestedAt)throw new Error("The paired test is unavailable.");let l={candidateId:r.id,actorId:r.actorId,teamId:r.teamId,projectId:r.projectId,candidateRevision:r.revision,recipeHash:r.test.recipeHash,...t};return U({...l,contentHash:s(l)})}m(ee,"sealExperimentImprovementHumanOptions");var a=e.string().trim().min(1).max(240),d=e.string().regex(/^[a-f0-9]{64}$/),_=e.object({schemaVersion:e.literal("openpond.advancedRefinerEvaluation.v1"),operationId:a,actorId:a,teamId:a,projectId:a.nullable(),mode:e.enum(["review_quality","downstream_adaptation"]),profileRef:e.object({source:e.enum(["local","github","openpond_git"]),repositoryId:a,profileId:a}).strict(),sourceRevision:e.string().min(1).max(500),baselineRelease:i,refinerRelease:i,evidence:i,externalDatasetBinding:v,adaptationDatasetBinding:v,privateClosureHash:d,adaptationTaskIds:e.array(a).min(1).max(1e4),holdoutTaskIds:e.array(a).min(1).max(1e4),adaptationSplit:e.enum(["train","validation","test","frozen_eval"]),holdoutSplit:e.enum(["train","validation","test","frozen_eval"]),environmentPolicy:e.discriminatedUnion("kind",[e.object({kind:e.literal("resettable"),environmentHash:d}).strict(),e.object({kind:e.literal("frozen_observations"),environmentHash:d}).strict()]),maximumCostUsd:e.number().finite().positive().max(1e4),maximumDurationMs:e.number().int().min(1e3).max(864e5),maximumModelSteps:e.number().int().min(1).max(1e3),contentHash:d}).strict();function M(r){let t=_.parse(r),{contentHash:l,...b}=t;if(s(b)!==l)throw new Error("Advanced Refiner evaluation admission changed.");let o=g(t.externalDatasetBinding);if(o.profileId!==t.profileRef.profileId||o.protectedProfileClosureHash!==t.privateClosureHash)throw new Error("Advanced evaluation changed its Profile or protected evaluator closure.");if(t.adaptationSplit===t.holdoutSplit||new Set([...t.adaptationTaskIds,...t.holdoutTaskIds]).size!==t.adaptationTaskIds.length+t.holdoutTaskIds.length)throw new Error("Adaptation and private holdout must be disjoint ordered cases.");let p=g(t.adaptationDatasetBinding);if(p.profileId!==o.profileId||p.packageHash!==o.packageHash||s(p.dataset)!==s(o.dataset)||s(p.target)!==s(o.target)||p.protectedProfileClosureHash!==o.protectedProfileClosureHash)throw new Error("This native advanced adapter needs separate adaptation and holdout recipes from the same exact released package and target.");if(p.split!==t.adaptationSplit||o.split!==t.holdoutSplit)throw new Error("Advanced split policies differ from their exact admitted recipes.");let q=new Set(o.population.map(u=>u.taskId)),z=new Set(p.population.map(u=>u.taskId));if(t.holdoutTaskIds.some(u=>!q.has(u))||t.adaptationTaskIds.some(u=>!z.has(u)))throw new Error("Advanced evaluation selected cases outside its exact Dataset recipe.");return t}m(M,"verifyAdvancedRefinerEvaluationPin");function ce(r){return M({...r,contentHash:s(r)})}m(ce,"sealAdvancedRefinerEvaluationPin");var B=e.object({pin:_,modelId:a,profileId:a,model:y,seed:e.number().int(),reasoningEffort:e.enum(["none","off","low","medium","high","xhigh","max"]).nullable()}).strict(),V=e.discriminatedUnion("operation",[e.object({operation:e.literal("start"),request:B}).strict(),e.object({operation:e.enum(["read","cancel","resume"]),id:a}).strict(),e.object({operation:e.literal("list")}).strict()]),W=e.object({taskId:a,sourceCaseHash:d,reviewSessionId:a,reviewTurnId:a,inputHarness:i,trigger:i,decision:e.enum(["no_action","route_deterministically","queue_refiner"]),outcome:i.nullable(),proposal:i.nullable(),validations:e.array(i).max(100),grade:e.object({id:a,contentHash:d,score:e.number().min(0).max(1).nullable(),passed:e.boolean(),failureClass:e.string().nullable()}).strict(),resetComplete:e.boolean()}).strict(),$=e.object({schemaVersion:e.literal("openpond.advancedRefinerReviewReceipt.v1"),id:a,runId:a,pinHash:d,ownerActorId:a,teamId:a,privateClosureHash:d,refinerRelease:i,cases:e.array(W).min(1).max(1e4),reviewScore:e.number().min(0).max(1).nullable(),completedCases:e.number().int().nonnegative(),noActionCases:e.number().int().nonnegative(),routedCases:e.number().int().nonnegative(),proposalCases:e.number().int().nonnegative(),costUsd:e.number().finite().nonnegative().nullable(),cleanupComplete:e.boolean(),createdAt:e.string().datetime(),contentHash:d}).strict();function de(r){return $.parse({...r,contentHash:s(r)})}m(de,"sealAdvancedRefinerReviewReceipt");var P=S.shape.profiles.element,me=S.extend({profiles:e.array(P.extend({components:e.array(P.shape.components.element.extend({adaptationSplits:e.array(e.object({split:e.enum(["train","validation","test","frozen_eval"]),taskIds:e.array(a)})),environmentHash:d,resettable:e.boolean(),reviewQuality:e.boolean()}))})),refinerReleases:e.array(i),activeRefiner:i.nullable(),models:e.array(e.object({id:a,profileId:a,name:e.string(),location:e.enum(["local","hosted"])}))}),L=e.object({operation:e.literal("prepare"),evidence:i,profileOptionId:a,componentLabel:a,mode:e.enum(["review_quality","downstream_adaptation"]),adaptationSplit:e.enum(["train","validation","test","frozen_eval"]),operationId:a,refinerRelease:i,maximumCostUsd:e.number().positive(),maximumDurationMs:e.number().int().positive(),maximumModelSteps:e.number().int().positive()}).strict(),le=e.union([V,L,e.object({operation:e.literal("options"),evidence:i}).strict()]),pe=e.object({modelRequests:e.number().int().nonnegative(),knownSpendUsd:e.number().nonnegative(),totalSpendUsd:e.number().nonnegative().nullable(),heldUsd:e.number().nonnegative(),uncertainRequests:e.number().int().nonnegative()}).strict();export{C as a,x as b,D as c,X as d,Y as e,T as f,Z as g,S as h,U as i,ee as j,_ as k,M as l,ce as m,B as n,V as o,W as p,$ as q,de as r,L as s,pe as t};
2
+ import{a as j}from"./chunk-UGDBMRCT.js";import{j as y}from"./chunk-BYVE4TMU.js";import{f as i,m as s}from"./chunk-HIQPGYVH.js";import{c as H,d as w,f as k}from"./chunk-LK77GI6M.js";import{Bb as h,Eb as I,Fb as E,oa as v,pa as g,wb as f}from"./chunk-ZY32SZ2P.js";import{A as e}from"./chunk-X2J2P5ZT.js";import{a as m}from"./chunk-FTQLQJQV.js";var A=e.object({sourcePass:i,graders:j.shape.graders,mappings:j.shape.mappings,maximumCostUsd:e.number().finite().positive().max(1e4)}).strict(),C=e.object({externalDatasetBinding:v,scoring:A.optional(),modelId:e.string().min(1).max(300),maximumCostUsd:e.number().finite().positive().max(1e4)}).strict(),R=e.object({source:e.enum(["local","github","openpond_git"]),repositoryId:e.string().trim().min(1),profileId:e.string().trim().min(1)}).strict(),n=e.string().min(1).max(240),c=e.string().regex(/^[a-f0-9]{64}$/),x=e.object({schemaVersion:e.literal("openpond.experimentImprovement.v1"),id:n,operationId:n,requestHash:c,actorId:n,teamId:n,projectId:n.nullable(),ownerWorkspaceId:n,ownerRevision:e.number().int().nonnegative(),ownerSourceRevision:e.string().min(1).max(500),baseRelease:i,profileRef:R,baseProfileSourceRevision:e.string().min(1).max(500),evidence:e.object({manifest:f,result:h}).strict(),component:e.object({kind:e.enum(["skill","workflow","agent","instruction"]),path:e.string().min(1).max(2e3),workflowId:n.optional()}).strict(),mode:e.enum(["manual","llm_assisted"]),status:e.enum(["draft","authoring_queued","authoring","frozen","testing","ready_for_review","adopting","accepted","rolled_back","declined","failed","cancelled"]),revision:e.number().int().positive(),limits:e.object({maximumCostUsd:e.number().finite().positive(),maximumAuthoringSteps:e.number().int().min(1).max(500),maximumDurationMs:e.number().int().min(1e3).max(864e5)}).strict(),authoringSteps:e.number().int().nonnegative().max(500),work:e.object({sessionId:n,turnId:n,revision:e.number().int().positive(),startedAt:e.string().datetime()}).strict().nullable(),frozen:e.object({release:i,sourceRevision:e.string().min(1).max(500),profileSourceRevision:e.string().min(1).max(500),authoringHash:c,partitionHash:c,executableSourceHash:c,protectedClosureHash:c,candidateRevision:e.number().int().positive(),diff:e.array(e.object({path:e.string(),before:c.nullable(),after:c.nullable()}).strict()).max(1e4)}).strict().nullable(),test:e.object({recipe:C,recipeHash:e.string().regex(/^[a-f0-9]{64}$/),baselineOperationId:e.string(),candidateOperationId:e.string(),cancelRequestedAt:e.string().datetime().nullable(),dispatching:e.object({kind:e.enum(["baseline","candidate"]),token:n,pid:e.number().int().positive(),processStart:e.string().nullable(),startedAt:e.string().datetime()}).strict().nullable()}).strict().nullable(),comparison:e.object({baseline:e.object({manifest:f,result:h}).strict(),candidate:e.object({manifest:f,result:h}).strict(),frozenHash:c,humanProjection:w.optional()}).strict().nullable(),adoptionIntent:e.object({operationId:n,expectedOwnerRevision:e.number().int().nonnegative(),frozenHash:c,humanProjection:w.optional()}).strict().nullable(),acceptance:i.nullable(),rollback:i.nullable(),error:e.string().max(2e3).nullable(),createdAt:e.string().datetime(),updatedAt:e.string().datetime(),contentHash:c}).strict();function D(r){let t=x.parse(r),{contentHash:l,...b}=t;if(s(b)!==l)throw new Error("Improvement state integrity failed.");if(I(t.evidence),t.evidence.manifest.teamId!==t.teamId||t.evidence.result.status!=="completed"||!t.evidence.result.cases.some(o=>o.status==="completed"))throw new Error("Improvement requires usable completed owner evidence.");if(t.test&&(s(t.test.recipe)!==t.test.recipeHash||g(t.test.recipe.externalDatasetBinding).profileId!==t.profileRef.profileId))throw new Error("The test recipe changed its exact selected Profile.");if(t.comparison?.humanProjection){let o=k(t.comparison.humanProjection);if(o.teamId!==t.teamId||o.projectId!==t.projectId||s(o.baseline)!==s(t.comparison.baseline)||s(o.candidate)!==s(t.comparison.candidate))throw new Error("Human comparison projection differs from its exact owner evidence.")}if(t.comparison&&(I(t.comparison.baseline),I(t.comparison.candidate),!t.frozen||t.comparison.frozenHash!==s(t.frozen)||!E(t.comparison.baseline,t.comparison.candidate).comparable))throw new Error("Improvement comparison is not bound to a comparable frozen candidate.");if(t.status==="ready_for_review"&&(!t.frozen||!t.comparison))throw new Error("Improvement is missing qualification.");if(t.status==="adopting"&&(!t.adoptionIntent||!t.frozen||t.adoptionIntent.frozenHash!==s(t.frozen)))throw new Error("Improvement adoption intent is not bound to its tested revision.");if(t.status==="accepted"&&(!t.acceptance||!t.comparison||!t.frozen))throw new Error("Improvement acceptance is missing its exact qualification receipt.");if(t.status==="rolled_back"&&(!t.acceptance||!t.rollback))throw new Error("Profile rollback is missing its durable owner receipt.");return t}m(D,"verifyExperimentImprovementState");function X(r){return D({...r,contentHash:s(r)})}m(X,"sealExperimentImprovementState");var Y=e.object({states:e.array(x).max(50),nextCursor:n.nullable()}).strict(),T=e.object({operationId:n,ownerWorkspaceId:n,expectedOwnerRevision:e.number().int().nonnegative(),baseRelease:i,profileRef:R,profileSourceRevision:e.string().min(1).max(500),projectId:n.nullable(),evidence:i,component:x.shape.component,mode:x.shape.mode,limits:x.shape.limits}).strict(),Z=e.discriminatedUnion("operation",[e.object({operation:e.literal("list"),limit:e.number().int().min(1).max(50).default(30),cursor:n.optional()}).strict(),e.object({operation:e.literal("options"),evidence:i}).strict(),e.object({operation:e.literal("start"),request:T}).strict(),e.object({operation:e.enum(["read","humanComparisonOptions"]),id:n}).strict(),e.object({operation:e.literal("instructions"),id:n}).strict(),e.object({operation:e.literal("edit"),id:n,revision:e.number().int().positive(),expectedFileHash:c,text:e.string().max(25e4)}).strict(),e.object({operation:e.literal("mode"),id:n,revision:e.number().int().positive(),mode:e.enum(["manual","llm_assisted"])}).strict(),e.object({operation:e.literal("author"),id:n,revision:e.number().int().positive(),modelId:n,prompt:e.string().min(1).max(2e4)}).strict(),e.object({operation:e.enum(["freeze","finishAuthoring","useCandidate","discard","cancel","rollback"]),id:n,revision:e.number().int().positive()}).strict(),e.object({operation:e.literal("test"),id:n,revision:e.number().int().positive(),recipe:C}).strict(),e.object({operation:e.literal("compare"),id:n,revision:e.number().int().positive(),baseline:i,candidate:i,humanSelections:H.optional()}).strict()]),S=e.object({teamId:n,evidence:i,scoring:A.optional(),profiles:e.array(e.object({id:c,name:e.string(),profileRef:R,ownerWorkspaceId:n,ownerRevision:e.number().int().nonnegative(),baseRelease:i,profileSourceRevision:e.string(),components:e.array(e.object({kind:e.enum(["skill","instruction","agent","workflow"]),path:e.string(),agentId:e.string().optional(),workflowId:e.string().optional(),label:e.string(),binding:v}).strict()).max(500)}).strict()).max(100)}).strict(),O=e.object({candidateId:n,actorId:n,teamId:n,projectId:n.nullable(),candidateRevision:e.number().int().positive(),recipeHash:c,baseline:e.object({manifest:f,result:h}).strict(),candidate:e.object({manifest:f,result:h}).strict(),contentHash:c}).strict();function U(r){let t=O.parse(r),{contentHash:l,...b}=t;if(s(b)!==l)throw new Error("Accepted Human discovery integrity failed.");for(let o of[t.baseline,t.candidate])if(I(o),o.manifest.teamId!==t.teamId||o.manifest.lineage?.humanProjection)throw new Error("Discovery must retain original owner evidence.");return t}m(U,"verifyExperimentImprovementHumanOptions");function ee(r,t){if(!r.test||r.test.cancelRequestedAt)throw new Error("The paired test is unavailable.");let l={candidateId:r.id,actorId:r.actorId,teamId:r.teamId,projectId:r.projectId,candidateRevision:r.revision,recipeHash:r.test.recipeHash,...t};return U({...l,contentHash:s(l)})}m(ee,"sealExperimentImprovementHumanOptions");var a=e.string().trim().min(1).max(240),d=e.string().regex(/^[a-f0-9]{64}$/),_=e.object({schemaVersion:e.literal("openpond.advancedRefinerEvaluation.v1"),operationId:a,actorId:a,teamId:a,projectId:a.nullable(),mode:e.enum(["review_quality","downstream_adaptation"]),profileRef:e.object({source:e.enum(["local","github","openpond_git"]),repositoryId:a,profileId:a}).strict(),sourceRevision:e.string().min(1).max(500),baselineRelease:i,refinerRelease:i,evidence:i,externalDatasetBinding:v,adaptationDatasetBinding:v,privateClosureHash:d,adaptationTaskIds:e.array(a).min(1).max(1e4),holdoutTaskIds:e.array(a).min(1).max(1e4),adaptationSplit:e.enum(["train","validation","test","frozen_eval"]),holdoutSplit:e.enum(["train","validation","test","frozen_eval"]),environmentPolicy:e.discriminatedUnion("kind",[e.object({kind:e.literal("resettable"),environmentHash:d}).strict(),e.object({kind:e.literal("frozen_observations"),environmentHash:d}).strict()]),maximumCostUsd:e.number().finite().positive().max(1e4),maximumDurationMs:e.number().int().min(1e3).max(864e5),maximumModelSteps:e.number().int().min(1).max(1e3),contentHash:d}).strict();function M(r){let t=_.parse(r),{contentHash:l,...b}=t;if(s(b)!==l)throw new Error("Advanced Refiner evaluation admission changed.");let o=g(t.externalDatasetBinding);if(o.profileId!==t.profileRef.profileId||o.protectedProfileClosureHash!==t.privateClosureHash)throw new Error("Advanced evaluation changed its Profile or protected evaluator closure.");if(t.adaptationSplit===t.holdoutSplit||new Set([...t.adaptationTaskIds,...t.holdoutTaskIds]).size!==t.adaptationTaskIds.length+t.holdoutTaskIds.length)throw new Error("Adaptation and private holdout must be disjoint ordered cases.");let p=g(t.adaptationDatasetBinding);if(p.profileId!==o.profileId||p.packageHash!==o.packageHash||s(p.dataset)!==s(o.dataset)||s(p.target)!==s(o.target)||p.protectedProfileClosureHash!==o.protectedProfileClosureHash)throw new Error("This native advanced adapter needs separate adaptation and holdout recipes from the same exact released package and target.");if(p.split!==t.adaptationSplit||o.split!==t.holdoutSplit)throw new Error("Advanced split policies differ from their exact admitted recipes.");let q=new Set(o.population.map(u=>u.taskId)),z=new Set(p.population.map(u=>u.taskId));if(t.holdoutTaskIds.some(u=>!q.has(u))||t.adaptationTaskIds.some(u=>!z.has(u)))throw new Error("Advanced evaluation selected cases outside its exact Dataset recipe.");return t}m(M,"verifyAdvancedRefinerEvaluationPin");function ce(r){return M({...r,contentHash:s(r)})}m(ce,"sealAdvancedRefinerEvaluationPin");var B=e.object({pin:_,modelId:a,profileId:a,model:y,seed:e.number().int(),reasoningEffort:e.enum(["none","off","low","medium","high","xhigh","max"]).nullable()}).strict(),V=e.discriminatedUnion("operation",[e.object({operation:e.literal("start"),request:B}).strict(),e.object({operation:e.enum(["read","cancel","resume"]),id:a}).strict(),e.object({operation:e.literal("list")}).strict()]),W=e.object({taskId:a,sourceCaseHash:d,reviewSessionId:a,reviewTurnId:a,inputHarness:i,trigger:i,decision:e.enum(["no_action","route_deterministically","queue_refiner"]),outcome:i.nullable(),proposal:i.nullable(),validations:e.array(i).max(100),grade:e.object({id:a,contentHash:d,score:e.number().min(0).max(1).nullable(),passed:e.boolean(),failureClass:e.string().nullable()}).strict(),resetComplete:e.boolean()}).strict(),$=e.object({schemaVersion:e.literal("openpond.advancedRefinerReviewReceipt.v1"),id:a,runId:a,pinHash:d,ownerActorId:a,teamId:a,privateClosureHash:d,refinerRelease:i,cases:e.array(W).min(1).max(1e4),reviewScore:e.number().min(0).max(1).nullable(),completedCases:e.number().int().nonnegative(),noActionCases:e.number().int().nonnegative(),routedCases:e.number().int().nonnegative(),proposalCases:e.number().int().nonnegative(),costUsd:e.number().finite().nonnegative().nullable(),cleanupComplete:e.boolean(),createdAt:e.string().datetime(),contentHash:d}).strict();function de(r){return $.parse({...r,contentHash:s(r)})}m(de,"sealAdvancedRefinerReviewReceipt");var P=S.shape.profiles.element,me=S.extend({profiles:e.array(P.extend({components:e.array(P.shape.components.element.extend({adaptationSplits:e.array(e.object({split:e.enum(["train","validation","test","frozen_eval"]),taskIds:e.array(a)})),environmentHash:d,resettable:e.boolean(),reviewQuality:e.boolean()}))})),refinerReleases:e.array(i),activeRefiner:i.nullable(),models:e.array(e.object({id:a,profileId:a,name:e.string(),location:e.enum(["local","hosted"])}))}),L=e.object({operation:e.literal("prepare"),evidence:i,profileOptionId:a,componentLabel:a,mode:e.enum(["review_quality","downstream_adaptation"]),adaptationSplit:e.enum(["train","validation","test","frozen_eval"]),operationId:a,refinerRelease:i,maximumCostUsd:e.number().positive(),maximumDurationMs:e.number().int().positive(),maximumModelSteps:e.number().int().positive()}).strict(),le=e.union([V,L,e.object({operation:e.literal("options"),evidence:i}).strict()]),pe=e.object({modelRequests:e.number().int().nonnegative(),knownSpendUsd:e.number().nonnegative(),totalSpendUsd:e.number().nonnegative().nullable(),heldUsd:e.number().nonnegative(),uncertainRequests:e.number().int().nonnegative()}).strict();export{C as a,x as b,D as c,X as d,Y as e,T as f,Z as g,S as h,U as i,ee as j,_ as k,M as l,ce as m,B as n,V as o,W as p,$ as q,de as r,L as s,pe as t};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as As,b as Ms}from"./chunk-CO23RRN7.js";import{a as Es,e as $e,f as Cs,g as Tt}from"./chunk-3Z4VM2LF.js";import{a as xs,c as Is}from"./chunk-XVDFJ3ZF.js";import{h as ne}from"./chunk-RCQYEHHD.js";import{a as ee,b as _s}from"./chunk-SDHG6CKU.js";import{b as ys,c as bs,d as yt}from"./chunk-GYYJ47GX.js";import{a as ws,b as vs,c as Ts,d as qe,e as Ss,g as vt}from"./chunk-WCNPGKST.js";import{a as wt,c as Rs}from"./chunk-AFH462DO.js";import{b as Kr,e as Xr,f as lt,g as ut}from"./chunk-CIZI6Z7D.js";import{F as gt,G as fs,H as ht,I as kt,J as gs,K as hs,N as ks,x as ps}from"./chunk-MOXIGLN2.js";import{a as ve}from"./chunk-7KWD2I6W.js";import{g as pt,i as ft}from"./chunk-2ACX7IW5.js";import{s as br}from"./chunk-OFJPOTES.js";import{d as Ne}from"./chunk-U7D6Q744.js";import{ja as rs,qa as ss,sa as os,x as ts}from"./chunk-HG2YFMVU.js";import{M as V,N as as,O as ns,P as is,Q as mt,R as ds,S as q,T as cs,U as je,V as ls,X as us,Y as Vt,Z as ms}from"./chunk-7OKZCJHS.js";import{l as Ft}from"./chunk-7NCM6GBN.js";import{d as Zr,f as W,g as Qr,i as es}from"./chunk-JT5YQ52I.js";import{k as Nr}from"./chunk-WGQ3FMRF.js";import{c as ct}from"./chunk-JVMSN7LH.js";import{Ba as Gr,Ca as Re,Ha as Yr,Ia as De,K as qr,L as $r,M as Lr,N as Ur,P as Br,aa as Wr,ba as Fr,ia as Vr,ua as zr,wa as we,xa as Jr}from"./chunk-BU6MW65V.js";import{x as ae}from"./chunk-DXJC3QW7.js";import{C as Or,S as Hr,T as Dr,Tb as jr}from"./chunk-D6L6UNUQ.js";import{f as Rr}from"./chunk-AJXWJLZA.js";import{L,M as Ar,Ob as Pr,R as Wt,S as oe,X as dt,Y as Mr,ba as He,d as Er,g as Cr,pb as ke,qb as ye}from"./chunk-4PUOWSDE.js";import{bb as be,cb as Ir,ea as it,v as Ge}from"./chunk-ZY32SZ2P.js";import{l as _r,m as xr}from"./chunk-OTDDXEQ6.js";import{i as Tr,m as se,n as k}from"./chunk-RCT3O3HQ.js";import{m as Sr}from"./chunk-UGOK7VTC.js";import{A as P}from"./chunk-X2J2P5ZT.js";import{a as d}from"./chunk-FTQLQJQV.js";var zt={buildIntent:"verifiable_reward",methodHint:"grpo"};async function ii(e){let t=await aa(e.store,e.workspaceId,e.reviewRef),r=`harness-review-${k({review:t.contentHash,strategy:zt}).slice(0,24)}`,s=(await e.store.listTaskCreationSnapshots(e.profileId)).find(c=>c.request.candidateId===r);if(s)return s;let[a,o,n]=await Promise.all([e.store.listHarnessImprovementArtifacts(e.workspaceId,"route_decision",1e3),e.store.listHarnessImprovementArtifacts(e.workspaceId,"trigger_decision",1e3),e.store.listHarnessImprovementArtifacts(e.workspaceId,"observation",1e3)]),i=new Map(a.map(c=>[_e(c),c])),u=new Map(o.map(c=>[_e(c),c])),f=new Map(n.map(c=>[_e(c),c])),p=new Map;for(let c of t.selectedEvidence){if(c.kind!=="route_decision")continue;let m=i.get(_e(c.evidence)),g=m?u.get(_e(m.trigger)):null;if(!m||!g)throw new Error(`Harness review evidence ${c.evidence.id} cannot be reconstructed.`);let h=g.observations.map(y=>f.get(_e(y))??null).filter(y=>y?.runRef===c.sourceRef);if(!h.length)throw new Error(`Harness review source ${c.sourceRef} has no exact observation evidence.`);let w=p.get(c.sourceRef)??{turnIds:new Set,evidenceRefs:[],sourcePolicies:[]};for(let y of h)w.turnIds.add(y.turnId);w.evidenceRefs.push(c.evidence),w.sourcePolicies.push(c.sourcePolicy),p.set(c.sourceRef,w)}if(!p.size)throw new Error("Harness Taskset review has no reconstructable source runs.");let l=[];for(let[c,m]of[...p.entries()].sort(([g],[h])=>g.localeCompare(h))){let g=await e.taskCreator.addSessionSource({profileId:e.profileId,sessionId:c,turnIds:[...m.turnIds].sort(),consentScope:"selected_turns"}),h=Array.isArray(g.metadata.harnessEvaluationReviews)?g.metadata.harnessEvaluationReviews:[],w={...g,metadata:{...g.metadata,harnessEvaluationReviews:Gt([...h,{id:t.id,contentHash:t.contentHash,workspaceId:t.workspaceRef,harnessRelease:t.harnessRelease,claimFingerprint:t.claim?.fingerprint??null,evidenceRefs:m.evidenceRefs,sourcePolicies:m.sourcePolicies}])}};l.push(await e.store.upsertTrainingSource(w))}return e.startCreation({profileId:e.profileId,sourceIds:l.map(c=>c.id),surface:"task_candidate",mode:"customize",entryMode:"automated",resourceIntent:"workproduct",buildIntent:zt.buildIntent,buildSpecification:null,objective:t.claim?.statement??t.reason,methodHint:zt.methodHint,preferredBaseModelId:null,preferredBaseModel:null,candidateId:r,analysisModel:e.analysisModel??null,analysisReasoningEffort:e.analysisReasoningEffort??null,createImproveRunId:null,targetIntent:{kind:"model",id:null,displayName:null,operation:"create"}})}d(ii,"startHarnessReviewTasksetAuthoring");function di(e){let t=e.flatMap(o=>Array.isArray(o.metadata.harnessEvaluationReviews)?o.metadata.harnessEvaluationReviews.filter(Jt):[]);if(!t.length)return null;let r=`${String(t[0].id)}:${String(t[0].contentHash)}`,s=t.filter(o=>`${String(o.id)}:${String(o.contentHash)}`===r);if(s.length!==e.length)return null;let a=s[0];return{review:{id:String(a.id),contentHash:String(a.contentHash),workspaceId:String(a.workspaceId),harnessRelease:a.harnessRelease,claimFingerprint:typeof a.claimFingerprint=="string"?a.claimFingerprint:null},evidenceRefs:Gt(s.flatMap(o=>Array.isArray(o.evidenceRefs)?o.evidenceRefs:[])),sourcePolicies:Gt(s.flatMap(o=>Array.isArray(o.sourcePolicies)?o.sourcePolicies:[]))}}d(di,"harnessReviewLineageFromSources");async function Ps(e){let t=e.taskset.metadata.harnessEvaluationLineage;if(!Jt(t)||!Jt(t.review))return null;let r=String(t.review.workspaceId??""),s={id:String(t.review.id??""),contentHash:String(t.review.contentHash??"")};if(!r||!s.id||!s.contentHash)throw new Error("Taskset Harness Evaluation lineage is incomplete.");let a=await e.store.listHarnessImprovementArtifacts(r,"evaluation_review",1e3),o=a.find(c=>_e(c)===_e(s));if(!o)throw new Error("Originating Harness Evaluation review was not found.");let n=e.evaluationResult?{id:e.evaluationResult.id,contentHash:e.evaluationResult.contentHash}:null,i={id:e.taskset.id,contentHash:e.taskset.contentHash},u=k({originRef:s,tasksetRef:i,evaluationRef:n}),f=a.find(c=>c.metadata.downstreamLinkKey===u);if(f)return f;let p=(e.now??(()=>new Date().toISOString()))(),l=Rr({schemaVersion:"openpond.harnessEvaluationReviewReceipt.v1",id:`evaluation-review-link-${u.slice(0,24)}`,ownerScope:o.ownerScope,workspaceRef:o.workspaceRef,harnessRelease:o.harnessRelease,previousWatermark:o.nextWatermark,nextWatermark:{cursor:k({cursor:o.nextWatermark.cursor,tasksetRef:i,evaluationRef:n}),throughCreatedAt:p},selectedEvidence:o.selectedEvidence,excludedEvidence:o.excludedEvidence,claim:o.claim,classification:"taskset",triage:o.triage,reason:n?"The approved Taskset completed a real baseline Evaluation.":"The approved Harness review materialized one immutable Taskset.",nextAuthority:"human_review",maxEstimatedCostUsd:o.maxEstimatedCostUsd,tasksetProposal:i,evaluation:n,trainingQualification:null,policyVersion:o.policyVersion,createdAt:p,metadata:{originReview:s,downstreamLinkKey:u,tasksetRevision:e.taskset.revision}});return await e.store.saveHarnessImprovementArtifact(r,"evaluation_review",l),l}d(Ps,"linkHarnessReviewTaskset");async function aa(e,t,r){let s=await e.getHarnessWorkspace(t);if(!s)throw new Error(`Harness workspace ${t} was not found.`);let a=(await e.listHarnessImprovementArtifacts(t,"evaluation_review",1e3)).find(n=>n.id===r.id&&n.contentHash===r.contentHash);if(!a||a.schemaVersion!=="openpond.harnessEvaluationReviewReceipt.v1")throw new Error("Harness Evaluation review was not found.");let o=a;if(o.classification!=="taskset"||o.nextAuthority!=="human_review")throw new Error("Only a human-review Taskset recommendation can enter Taskset authoring.");if(o.tasksetProposal)throw new Error("Harness Evaluation review already has a materialized Taskset link.");if(o.ownerScope.kind!==s.ownerScope.kind||o.ownerScope.id!==s.ownerScope.id)throw new Error("Harness Evaluation review owner scope does not match its workspace.");return o}d(aa,"requireTasksetReview");function _e(e){return`${e.id}:${e.contentHash}`}d(_e,"artifactKey");function Jt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}d(Jt,"isRecord");function Gt(e){let t=new Set;return e.filter(r=>{let s=JSON.stringify(r);return t.has(s)?!1:(t.add(s),!0)})}d(Gt,"uniqueObjects");import{randomUUID as na}from"node:crypto";function bt(e){let t=St(St(St(e.metadata).billing).pricing);return{version:Le(t.version,"pricing version"),source:Le(t.source,"pricing source"),effectiveAt:Le(t.effectiveAt,"pricing effective date"),inputUsdPerMillionTokens:Ue(t.inputUsdPerMillionTokens,"input token rate"),cachedInputUsdPerMillionTokens:Ue(t.cachedInputUsdPerMillionTokens,"cached input token rate"),outputUsdPerMillionTokens:Ue(t.outputUsdPerMillionTokens,"output token rate")}}d(bt,"hostedTokenPricingFromCatalog");function mi(e){let t=St(e);try{return{version:Le(t.version,"pricing version"),source:Le(t.source,"pricing source"),effectiveAt:Le(t.effectiveAt,"pricing effective date"),inputUsdPerMillionTokens:Ue(t.inputUsdPerMillionTokens,"input token rate"),cachedInputUsdPerMillionTokens:Ue(t.cachedInputUsdPerMillionTokens,"cached input token rate"),outputUsdPerMillionTokens:Ue(t.outputUsdPerMillionTokens,"output token rate")}}catch{return null}}d(mi,"hostedTokenPricingFromValue");function xe(e,t){let r=ve(e);if(r.promptTokens===null&&r.completionTokens===null)return null;let s=r.cachedPromptTokens??0;return((r.uncachedPromptTokens??r.promptTokens??0)*t.inputUsdPerMillionTokens+s*t.cachedInputUsdPerMillionTokens+(r.completionTokens??0)*t.outputUsdPerMillionTokens)/1e6}d(xe,"hostedUsageCostUsd");function St(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}d(St,"record");function Le(e,t){if(typeof e=="string"&&e.trim())return e.trim();throw new Error(`Hosted model catalog is missing ${t}.`)}d(Le,"requiredString");function Ue(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e;throw new Error(`Hosted model catalog is missing ${t}.`)}d(Ue,"requiredRate");function Ds(e={}){let t=e.catalog??pt,r=e.stream??ft;return{async prepare(s){if(s.providerId!=="openpond")throw new Error("The selected judge provider is not connected to the hosted judge transport.");if(s.revision!==null)throw new Error("This judge transport cannot enforce a model revision; select a provider with revision support.");let a=await t();if(a.error)throw new Error(`Judge model catalog unavailable: ${a.error}`);let o=a.models.find(l=>l.id===s.modelId);if(!o)throw new Error("The selected judge model is unavailable.");let n=Os(o.raw),i=bt(n),u=Hs(n.context_window,"context window"),f=Math.min(4096,Hs(n.output_limit,"output limit")),p=(u*Math.max(i.inputUsdPerMillionTokens,i.cachedInputUsdPerMillionTokens)+f*i.outputUsdPerMillionTokens)/1e6;if(!(p>0))throw new Error("The judge model must have a positive known charge ceiling.");return{maximumChargeUsd:p,async dispatch(l){l?.throwIfAborted();let c="",m=null,g=null,h=null,w=!1;for await(let _ of r({model:s.modelId,messages:[{role:"system",content:s.system},{role:"user",content:s.data}],requestId:`learning-judge-${na()}`,maxTokens:f,temperature:s.temperature,signal:l})){let x=Os(_.raw);if(typeof x.model=="string"){if(m!==null&&x.model!==m)throw new Error("Judge response model identity changed during streaming.");m=x.model}if(typeof x.id=="string"){if(g!==null&&g!==x.id)throw new Error("Judge response identity changed during streaming.");g=x.id}if(_.type==="text_delta"&&(c+=_.text),c.length>1e5)throw new Error("Judge response exceeds the retained response limit.");_.type==="usage"&&(h=_.usage),_.type==="finish"&&(w=!0)}if(!w||!m||!g)throw new Error("Judge response did not include a complete model receipt.");let y=ve(h),S=y.promptTokens!==null&&y.completionTokens!==null?xe(h,i):null;return{text:c,modelId:m,modelRevision:null,responseId:g,inputTokens:y.promptTokens,outputTokens:y.completionTokens,costUsd:S}}}},async cancel({run:s}){return!s.judgeCalls?.some(a=>a.status==="reserved")}}}d(Ds,"createLearningHostedJudgeProvider");function Os(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}d(Os,"record");function Hs(e,t){if(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)throw new Error(`Judge catalog is missing its ${t}.`);return e}d(Hs,"positiveInteger");function xi(e,t=Ds()){return{execute(r){if(r.definition.execution.environment.entrypoint==="openpond.javascript-environment.v1")throw new Error("Tool Tasksets require grading an owner-recorded environment attempt.");let s=Pr({repository:e,scope:r.scope,run:r.run});return Ir({binding:r.binding,rewards:r.rewards,task:dt(r.evidence,r.definition),evidence:Mr(r.evidence,r.run.output),evaluatorContext:r.evidence.submission.evaluatorContext,signal:r.signal,modelJudge:Er({readRubric:d(a=>e.transaction(r.scope,async o=>oe(await ke(o,"asset",a.id,1),a)),"readRubric"),async executeBudgeted(a,o){let n=await t.prepare(a,{scope:r.scope,run:r.run});return Cr({store:s,maximumCharge:d(()=>n.maximumChargeUsd,"maximumCharge"),dispatch:d((u,f)=>n.dispatch(f),"dispatch")})(`grade-${k(a)}`,a,o)}}),customVerifier:d(async({grader:a,task:o,evidence:n})=>{let i=await Ye({repository:e,scope:r.scope,grader:a,task:o,evidence:n,evaluatorContext:r.evidence.submission.evaluatorContext,timeoutMs:r.run.timeoutMs,signal:r.signal});return{score:i.score,passed:i.passed,rewardEligible:a.rewardEligible,failureClass:null,feedback:[i.feedback],visibleEvidenceRefs:[],privilegedEvidenceRefs:i.evidenceRefs}},"customVerifier")})},async cancel({scope:r,run:s}){let a=await e.transaction(r,o=>ke(o,"grade",s.id));return a.judgeCalls?.some(o=>o.status==="reserved")?!1:t.cancel({scope:r,run:a})}}}d(xi,"createLocalTaskGradeExecutor");async function Ye(e){let t=await e.repository.transaction(e.scope,async r=>oe(await ke(r,"asset",e.grader.verifierRef.id,1),e.grader.verifierRef));return $e({source:t,exportName:e.grader.exportName,runtime:e.grader.runtime,timeoutMs:Math.min(e.grader.timeoutMs,e.timeoutMs??e.grader.timeoutMs),signal:e.signal,value:{task:e.task,attempt:e.evidence,input:e.task.input,output:e.evidence.output,expectedOutput:e.task.expectedOutput,evaluatorContext:e.evaluatorContext,infrastructureError:e.evidence.infrastructureError??null}})}d(Ye,"executeLocalLearningVerifier");import ia from"node:path";async function js(e,t,r){if(!r)throw new Error("Ordinary tool execution requires its owner's package directory.");let s=De({taskset:e,adapterId:qe(e)}),a=await vt({root:ia.join(r,"training","tasksets",ee(e)),content:{schemaVersion:"openpond.tasksetPackage.v1",taskset:s.tasksetRelease,environment:s.environmentRelease,verifierSet:s.verifierSetRelease},sources:ct.parse(e.metadata.portableFileInventory)}),o=Fr(a);if(!o)throw new Error("The Taskset does not declare a JavaScript execution graph.");let n=a.taskset.tasks.find(f=>f.id===t.id);if(!n)throw new Error("The selected task is missing from its executable package.");let i=o.assets.find(f=>f.id===o.execution.javascript.module.id),u=o.assets.find(f=>f.id===n.privilegedContextRef);return{execution:o.execution,module:i,initialState:JSON.parse(u.text),definition:L(a.taskset),instructions:Vr(a),task:n}}d(js,"loadOrdinaryToolEnvironment");var J="openpond.javascript-environment.v1";async function Be(e,t,r,s){let a=t.tasks.find(o=>o.id===r.id);if(!a||k(a)!==k(r))throw new Error("Tool task differs from the selected immutable Taskset.");return t.metadata.taskDefinition===void 0?js(t,r,s):e.learningRepository().transaction(t.profileId,async o=>{let n=await ye(o,"definition",ae.parse(t.metadata.taskDefinition)),i=n.execution.environment;if(i.entrypoint!==J||t.environment.entrypoint!==J||t.environment.kind!=="agent"||t.environment.stateful!==i.stateful||t.environment.defaultTimeoutMs!==i.defaultTimeoutMs||t.environment.networkPolicy!==i.networkPolicy||t.environment.deterministicSeeds!==i.deterministicSeeds||k(t.environment.toolNames)!==k(n.execution.tools.map(v=>v.name))||k(t.environment.metadata.portableTools)!==k(n.execution.tools)||k(t.policy)!==k(n.execution.policy)||k(t.metadata.rewardBinding)!==k(n.rewardBinding))throw new Error("Tool Taskset context differs from its pinned task definition.");let u=await ye(o,"binding",n.rewardBinding),f=await Promise.all(u.sources.map(v=>ye(o,"reward",v.reward))),p=it.parse({id:r.id,clusterKey:r.clusterKey,split:r.split,input:r.input,expectedOutput:r.expectedOutput,policyVisibleContext:r.policyVisibleContext,privilegedContextRef:r.privilegedContextRef,artifactRefs:[],tags:r.tags}),l={...n.execution,graders:be(u,f),tasks:[p]},c=await ke(o,"asset",Ur(l),1),m=$r.parse(JSON.parse(oe(c,c.asset))),g=[m.javascript.module,m.environment.actionSchemaRef,m.environment.observationSchemaRef,m.environment.stateSchemaRef].filter(v=>v!==null),h=[...new Set([...g.map(v=>v.id),r.privilegedContextRef].filter(v=>v!==null))],w=await Promise.all(h.map(v=>ke(o,"asset",v,1))),y=Br(l,c,w);if(k(t.environment.metadata.portableExecutionResources)!==k({environment:y.environment,verifierSet:y.verifierSet}))throw new Error("Tool Taskset publication differs from its private execution resources.");let S=w.find(v=>v.id===y.javascript.module.id),_=w.find(v=>v.id===r.privilegedContextRef),x=JSON.parse(oe(_,_.asset));return{execution:y,module:S,initialState:x,definition:L(n),instructions:n.instructions,task:p}})}d(Be,"loadStarterToolEnvironment");function Ns(e){let t=Wt({text:e.instructions,path:"policy/instructions.txt",mediaType:"text/plain",visibility:"policy"}),r=Wt({text:JSON.stringify({environment:L(e.execution.environment),verifierSet:L(e.execution.verifierSet),javascript:L(e.execution.javascript)}),path:"environment/dependencies.json",mediaType:"application/json",visibility:"host_private"}),s=_r({schemaVersion:"openpond.agentSnapshot.v2",id:`starter-agent-${e.definition.contentHash}`,sourceRelease:{id:e.definition.id,contentHash:e.definition.contentHash},instructions:[t.asset],skills:[],agents:[],toolDeclarations:e.execution.javascript.tools,capabilityRequirements:[],dependencyLock:r.asset,portability:{portable:!0,blockers:[],localOnlyAssetRefs:[],hostPrivateAssetRefs:[e.module.id,r.id]},metadata:{execution:J}}),a=xr({schemaVersion:"openpond.harnessRelease.v2",id:`starter-harness-${s.contentHash}`,agentSnapshot:{id:s.id,contentHash:s.contentHash},program:e.module.asset,tools:e.execution.javascript.tools,lifecycle:{create:!0,reset:!0,step:!0,collect:!0,destroy:!0,resetScope:"attempt"},graderInterface:{visibleEvidence:["output"],privilegedEvidence:["environment_state","private_verifier"],privateVerifierIsolation:!0},files:[t.asset,r.asset,e.module.asset],metadata:{execution:J}});return{agentSnapshot:s,harnessRelease:a,instructionContext:void 0}}d(Ns,"compileStarterToolHarness");import Rt from"node:path";import{constants as qs}from"node:fs";import{open as da,realpath as $s}from"node:fs/promises";var ca=P.string().regex(/^[a-f0-9]{64}$/),la=P.object({schemaVersion:P.literal("openpond.starterToolAttempt.v1"),requestId:P.string(),taskset:ae,taskHash:ca,model:P.unknown(),seed:P.number().int(),attempt:P.number().int(),definition:ae,policySource:P.enum(["model","fixture"]),environment:ae,verifierSet:ae,result:qr}).strict();async function _t(e){let{store:t,taskset:r,task:s,attempt:a}=e,o=await Be(t,r,s,e.storeDir),i=(await t.listTaskAttemptArtifacts({attemptId:a.id})).filter(S=>S.kind==="environment_state"&&S.tasksetId===r.id&&S.taskId===s.id&&S.attemptId===a.id&&a.artifactRefs.includes(S.id)&&a.privilegedOutcomeRef===S.id);if(i.length!==1)throw new Error("Tool grading requires exactly one owner-recorded environment artifact.");let u=i[0],f=await $s(Rt.join(e.storeDir,"training","evaluation-artifacts")),p=await $s(Rt.dirname(u.path)),l=Rt.relative(f,p);if(!l||l.startsWith("..")||Rt.isAbsolute(l))throw new Error("Tool evidence is outside the execution owner's artifact directory.");let c=await da(u.path,qs.O_RDONLY|qs.O_NOFOLLOW),m;try{let S=await c.stat();if(!S.isFile()||S.size>33554432||S.size!==u.sizeBytes)throw new Error("Tool evidence exceeds its declared byte boundary.");m=await c.readFile()}finally{await c.close()}if(m.byteLength!==u.sizeBytes||se(m)!==u.sha256)throw new Error("Owner-recorded tool evidence bytes changed.");let g=la.parse(JSON.parse(m.toString("utf8"))),{contentHash:h,...w}=g.result,y=g.result;if(k(w)!==h||!y.snapshot||!y.environmentCleanupComplete||!["completed","budget_exhausted","policy_failure"].includes(y.status)||k(g.taskset)!==k(L(r))||g.taskHash!==k(s)||k(g.model)!==k(a.modelRef)||g.seed!==a.seed||g.attempt!==a.attempt||a.tasksetId!==r.id||a.taskId!==s.id||a.split!==s.split||k(g.definition)!==k(o.definition)||k(g.environment)!==k(L(o.execution.environment))||k(g.verifierSet)!==k(L(o.execution.verifierSet))||y.taskId!==s.id||y.snapshot.seed!==a.seed||y.snapshot.inputHash!==k(s.input)||k(y.snapshot.definition)!==k(L(o.execution.javascript))||y.snapshot.finalStateHash!==k(y.snapshot.state)||k(a.output)!==k({text:y.output??""})||a.metadata.environmentAttemptHash!==h)throw new Error("Tool evidence differs from the selected task, model or recorded attempt.");if(a.metadata.policySource!==g.policySource)throw new Error("Tool evidence policy source changed.");return{environment:{status:y.status,collected:y.collected,definition:y.snapshot.definition,initialStateHash:y.snapshot.initialStateHash,finalStateHash:y.snapshot.finalStateHash,finalState:y.snapshot.state,events:y.snapshot.events}}}d(_t,"readStarterToolEvidence");async function Te(e,t){if(t.metadata.learning!==void 0)return He.parse(t.metadata.learning);if(t.metadata.rewardBinding===void 0)return;let r=ae.parse(t.metadata.rewardBinding);return e.learningRepository().transaction(t.profileId,async s=>{let a=await ye(s,"binding",r),o=[...new Map(a.sources.map(i=>[`${i.reward.id}:${i.reward.revision}:${i.reward.contentHash}`,i.reward])).values()],n=await Promise.all(o.map(i=>ye(s,"reward",i)));return{binding:a,rewards:n}})}d(Te,"resolveTasksetRewardBinding");async function ua(e,t,r){let s=await Te(e,t);if(!s)return{rewardExecution:void 0,verifierAssets:[]};let a=[...s.rewards.flatMap(i=>i.assets),...be(s.binding,s.rewards).flatMap(i=>i.kind==="custom_verifier"?[i.verifierRef]:i.kind==="model_judge"?[i.rubricRef]:[])],o=t.metadata.learning===void 0?void 0:await wt(r,t);if(o){let i=[...new Map(a.map(u=>{let f=o.learningResources.assets.find(p=>p.id===u.id);if(!f)throw new Error("Imported batch verifier is missing from its package.");return oe(f,u),[f.id,f]})).values()];return{rewardExecution:s,verifierAssets:i}}let n=await e.learningRepository().transaction(t.profileId,async i=>{let u=new Map;for(let f of a){let p=await ke(i,"asset",f.id,1);oe(p,f),u.set(p.id,p)}return[...u.values()]});return{rewardExecution:s,verifierAssets:n}}d(ua,"resolveTasksetTrainingReward");async function gd(e,t,r){let s=await ua(e,t,r.storeDir);if(!s.rewardExecution)return s;let a=be(s.rewardExecution.binding,s.rewardExecution.rewards);if(!s.rewardExecution.binding.sources.some(o=>o.role==="evaluation"&&o.weight>0))throw new Error("Managed training requires a positively weighted evaluation Reward source for retained validation.");if(a.some(o=>o.kind==="custom_verifier"&&o.runtime==="sandbox_process"))throw new Error("Managed preparation requires a qualified isolated sandbox for process verifiers.");if(r.placement!=="remote"||t.environment.kind==="work"||t.capabilities.requiresState||t.capabilities.requiresTools||a.some(o=>o.kind==="human"||o.kind==="model_judge"&&(!o.model||o.calibrationStatus!=="passed"))||t.tasks.some(o=>o.privilegedContextRef!==null)||!s.rewardExecution.binding.sources.some(o=>o.role==="training"&&o.weight>0)||r.hasLearnedPreferenceReward)throw new Error("This Reward binding requires an additional managed execution adapter.");return s}d(gd,"resolveManagedTasksetReward");async function Ls(e,t,r){let s=await Te(e,t);if(!s)throw new Error("The Taskset has no published Reward binding.");let a=be(s.binding,s.rewards);return async({grader:o,task:n,attempt:i,signal:u})=>{let f=t.tasks.find(m=>m.id===n.id);if(!f||k(f)!==k(n))throw new Error("Task differs from the selected immutable Taskset.");let p=null;if(t.environment.entrypoint===J){if(!r)throw new Error("Tool grading requires the execution owner's artifact directory.");p=await _t({store:e,storeDir:r,taskset:t,task:n,attempt:i})}else if(n.privilegedContextRef!==null)throw new Error("This authored Taskset requires a private evaluator-context resolver.");let l=a.find(m=>m.id===o.id);if(l?.kind!=="custom_verifier")throw new Error("The verifier is absent from the published Reward binding.");let c=it.parse({id:n.id,clusterKey:n.clusterKey,split:n.split,input:n.input,expectedOutput:n.expectedOutput,policyVisibleContext:n.policyVisibleContext,privilegedContextRef:n.privilegedContextRef,artifactRefs:[],tags:n.tags});return Ye({repository:e.learningRepository(),scope:t.profileId,grader:l,task:c,evidence:{output:i.output,artifactRefs:i.artifactRefs,runtimeEventRefs:i.runtimeEventRefs,infrastructureError:i.infrastructureError},evaluatorContext:p,signal:u})}}d(Ls,"createTasksetBindingVerifier");async function Ie(e,t,r){let s=r?ae.parse(r):null;if(s&&s.id!==t)throw new Error("Taskset execution reference differs from the requested Taskset.");let a=s?await e.getTasksetRevision(s.id,s.revision):await e.getTaskset(t);if(!a||s&&(a.contentHash!==s.contentHash||Re(a)!==s.contentHash))throw new Error("Taskset execution revision is unavailable or differs from its immutable hash.");return a}d(Ie,"requireLocalTasksetRevision");async function Sd(e,t,r){let s=await e.releaseForTaskset(t);return s||De({taskset:t,rewardExecution:r?await Te(r,t):void 0,adapterId:qe(t)}).tasksetRelease}d(Sd,"requireReleasedTaskset");import{createHash as ma}from"node:crypto";function Us(e,t,r){if(t.metadata.importedPackageHash!==e.contentHash)throw new Error("The Work projection differs from the admitted published package.");let s=e.taskset.tasks.find(n=>n.id===r.id);if(!s||s.split!==r.split||k(r.metadata.portableTaskRecord)!==k(s))throw new Error("The Work task differs from its exact released population.");let a=0,o=(r.assets??[]).map(n=>{let i=s.artifactRefs.find(l=>l.id===n.id&&l.contentHash===n.sha256&&l.path===n.artifactRef),u=i&&e.files.find(l=>k(l.asset)===k(i));if(!i||!u||i.visibility!=="policy")throw new Error("The Work task requests an unavailable or private evaluator file.");let f=Buffer.from(Wr(u));if(ma("sha256").update(f).digest("hex")!==n.sha256||f.length!==n.sizeBytes||n.split!==r.split)throw new Error("The published Work input manifest changed.");if(a+=f.length,a>25e7)throw new Error("Published Work inputs exceed the admitted 250 MB ceiling.");return{...n,assetId:n.id,storageName:n.stagingPath??n.fileName,bytes:f,sizeBytes:f.length}});if(o.length!==s.artifactRefs.length)throw new Error("The exact policy-visible Work asset population is incomplete.");return o}d(Us,"advancedPublishedWorkAssets");async function Yt(e,t=pt,r=!1){if(e.kind==="hosted_harness")return Yt({kind:"hosted_chat",modelId:e.modelId,...Nr(e)},t);if(e.kind!=="hosted_chat")throw new ne("local_target_not_qualified","Select an explicit model target for local execution.",422);if(e.harness&&!r)throw new ne("local_harness_not_qualified","This released Harness requires its native turn executor; it cannot run as a model-only case.",422);let s=await t();if(s.error)throw new ne("local_model_catalog_unavailable",s.error,422);let a=s.models.find(c=>c.id===e.modelId);if(!a)throw new ne("local_model_unavailable","The selected model is unavailable.",422);let o=Bs(a.raw),n=bt(o),i=Bs(o.capabilities).samplingParameters===!0;if(!i&&(e.temperature!==0||e.topP!==1))throw new ne("local_sampling_unsupported","This model uses provider-managed sampling. Custom temperature or top P requires an explicit supported capability.",422);let u=Ws(o.context_window),f=Ws(o.output_limit);if(e.maxOutputTokens>f)throw new ne("local_model_output_limit","The model cannot accept the configured output limit.",422);let p={providerId:"openpond",modelId:e.modelId,maxOutputTokens:e.maxOutputTokens,...i?{temperature:e.temperature,topP:e.topP}:{},messages:e.messages??[]},l=(u*Math.max(n.inputUsdPerMillionTokens,n.cachedInputUsdPerMillionTokens)+e.maxOutputTokens*n.outputUsdPerMillionTokens)/1e6;if(!(l>0))throw new ne("local_model_charge_unknown","The model must publish an enforceable positive request ceiling.",422);return{model:{...p,configurationHash:k({configuration:p,contextWindow:u,outputLimit:f,pricing:n})},pricing:n,maximumChargeUsd:l}}d(Yt,"prepareLocalExperimentModel");function Nd(e){let t=e.admission.streamFactory?.(e)??e.admission.stream??e.stream??ft;return async function*(r){if(!r.requestId)throw new ne("local_request_identity_missing","Every local model dispatch requires a stable request identity.");let s=e.admission.model;if(r.model!==s.modelId||r.maxTokens!==s.maxOutputTokens||r.temperature!==s.temperature||r.topP!==s.topP)throw new ne("local_model_configuration_conflict","The native model request changed its admitted model, output limit or sampling configuration.",422);let a=xs();a?.assertExecution(e.executionId);let o={teamId:e.teamId,id:e.executionId,ownerId:e.ownerId,requestId:r.requestId};await e.store.reserveLocalCharge({...o,caseId:e.caseId,maximumUsd:e.admission.maximumChargeUsd}),r.signal?.aborted&&(await e.store.settleLocalCharge({...o,costUsd:null,usage:null,notDispatched:!0}),r.signal.throwIfAborted());try{await e.store.markLocalChargeDispatched(o.teamId,o.id,o.requestId,o.ownerId)}catch(p){throw a&&await e.store.settleLocalCharge({...o,costUsd:null,usage:null,notDispatched:!0}),p}await e.store.appendLocalExperimentEvent({...o,caseId:e.caseId,type:"model.dispatch",payload:{requestId:o.requestId,model:r.model,messages:r.messages}});let n=null,i=!1,u=!1,f;try{for await(let p of t(r)){u=!0,p.type==="usage"&&(n=p.usage),p.type==="finish"&&(i=!0);let l=p.type==="text_delta"?{requestId:o.requestId,text:p.text}:p.type==="tool_call_delta"?{requestId:o.requestId,toolCalls:p.toolCalls}:p.type==="usage"?{requestId:o.requestId,usage:ve(p.usage)}:p.type==="finish"?{requestId:o.requestId,finishReason:p.finishReason}:null;l&&await e.store.appendLocalExperimentEvent({...o,caseId:e.caseId,type:`model.${p.type}`,payload:l}),yield p}}catch(p){throw!u&&p instanceof Is&&p.executionId===o.id&&p.requestId===o.requestId&&(f=p),p}finally{let p=ve(n),l=e.admission.pricing&&i&&p.promptTokens!==null&&p.completionTokens!==null?xe(n,e.admission.pricing):null;await e.store.settleLocalCharge({...o,costUsd:l,confirmedTransportNotInvoked:f,usage:n===null?null:{promptTokens:p.promptTokens,completionTokens:p.completionTokens,cachedPromptTokens:p.cachedPromptTokens,uncachedPromptTokens:p.uncachedPromptTokens}})}}}d(Nd,"createLocalBudgetedModelStream");function Bs(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}d(Bs,"record");function Ws(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)throw new ne("local_model_bound_unknown","The model catalog is missing an enforceable context/output bound.",422);return e}d(Ws,"positive");import{AsyncLocalStorage as pa}from"node:async_hooks";import fa from"node:path";var Fs=new pa;function Vs(){return Fs.getStore()}d(Vs,"currentAdvancedRefinerBoundary");function Jd(e){let t=Sr(fa.join(e.storeDir,"library","harnesses","advanced-refiner-paid-calls.sqlite"));t.exec(`CREATE TABLE IF NOT EXISTS advanced_refiner_budgets(id TEXT PRIMARY KEY,actor_id TEXT NOT NULL,team_id TEXT NOT NULL,pin_hash TEXT NOT NULL,maximum_spend REAL NOT NULL,maximum_steps INTEGER NOT NULL,expires_at TEXT NOT NULL);
2
+ import{a as As,b as Ms}from"./chunk-TD5YYA5Z.js";import{a as Es,e as $e,f as Cs,g as Tt}from"./chunk-BUMCJHQP.js";import{a as xs,c as Is}from"./chunk-XVDFJ3ZF.js";import{h as ne}from"./chunk-5TTQCT3G.js";import{a as ee,b as _s}from"./chunk-NDNSLCPE.js";import{b as ys,c as bs,d as yt}from"./chunk-CWE2N3JI.js";import{a as ws,b as vs,c as Ts,d as qe,e as Ss,g as vt}from"./chunk-O4YHISU2.js";import{a as wt,c as Rs}from"./chunk-HT6ILPD6.js";import{b as Kr,e as Xr,f as lt,g as ut}from"./chunk-VMW23TIZ.js";import{F as gt,G as fs,H as ht,I as kt,J as gs,K as hs,N as ks,x as ps}from"./chunk-JALL5NPH.js";import{a as ve}from"./chunk-7KWD2I6W.js";import{g as pt,i as ft}from"./chunk-2ACX7IW5.js";import{s as br}from"./chunk-OFJPOTES.js";import{d as Ne}from"./chunk-L5L3H6CI.js";import{ja as rs,qa as ss,sa as os,x as ts}from"./chunk-2THZ6GZY.js";import{M as V,N as as,O as ns,P as is,Q as mt,R as ds,S as q,T as cs,U as je,V as ls,X as us,Y as Vt,Z as ms}from"./chunk-OXRN2257.js";import{l as Ft}from"./chunk-TOWY6Y23.js";import{d as Zr,f as W,g as Qr,i as es}from"./chunk-Z6HWSTEP.js";import{k as Nr}from"./chunk-XKDOPNQ5.js";import{c as ct}from"./chunk-GR4MJJCE.js";import{Ba as Gr,Ca as Re,Ha as Yr,Ia as De,K as qr,L as $r,M as Lr,N as Ur,P as Br,aa as Wr,ba as Fr,ia as Vr,ua as zr,wa as we,xa as Jr}from"./chunk-BYVE4TMU.js";import{x as ae}from"./chunk-3VT2PPKW.js";import{C as Or,S as Hr,T as Dr,Tb as jr}from"./chunk-D6L6UNUQ.js";import{f as Rr}from"./chunk-AJXWJLZA.js";import{L,M as Ar,Ob as Pr,R as Wt,S as oe,X as dt,Y as Mr,ba as He,d as Er,g as Cr,pb as ke,qb as ye}from"./chunk-ZEOYNUHL.js";import{bb as be,cb as Ir,ea as it,v as Ge}from"./chunk-ZY32SZ2P.js";import{l as _r,m as xr}from"./chunk-OTDDXEQ6.js";import{i as Tr,m as se,n as k}from"./chunk-RCT3O3HQ.js";import{m as Sr}from"./chunk-UGOK7VTC.js";import{A as P}from"./chunk-X2J2P5ZT.js";import{a as d}from"./chunk-FTQLQJQV.js";var zt={buildIntent:"verifiable_reward",methodHint:"grpo"};async function ii(e){let t=await aa(e.store,e.workspaceId,e.reviewRef),r=`harness-review-${k({review:t.contentHash,strategy:zt}).slice(0,24)}`,s=(await e.store.listTaskCreationSnapshots(e.profileId)).find(c=>c.request.candidateId===r);if(s)return s;let[a,o,n]=await Promise.all([e.store.listHarnessImprovementArtifacts(e.workspaceId,"route_decision",1e3),e.store.listHarnessImprovementArtifacts(e.workspaceId,"trigger_decision",1e3),e.store.listHarnessImprovementArtifacts(e.workspaceId,"observation",1e3)]),i=new Map(a.map(c=>[_e(c),c])),u=new Map(o.map(c=>[_e(c),c])),f=new Map(n.map(c=>[_e(c),c])),p=new Map;for(let c of t.selectedEvidence){if(c.kind!=="route_decision")continue;let m=i.get(_e(c.evidence)),g=m?u.get(_e(m.trigger)):null;if(!m||!g)throw new Error(`Harness review evidence ${c.evidence.id} cannot be reconstructed.`);let h=g.observations.map(y=>f.get(_e(y))??null).filter(y=>y?.runRef===c.sourceRef);if(!h.length)throw new Error(`Harness review source ${c.sourceRef} has no exact observation evidence.`);let w=p.get(c.sourceRef)??{turnIds:new Set,evidenceRefs:[],sourcePolicies:[]};for(let y of h)w.turnIds.add(y.turnId);w.evidenceRefs.push(c.evidence),w.sourcePolicies.push(c.sourcePolicy),p.set(c.sourceRef,w)}if(!p.size)throw new Error("Harness Taskset review has no reconstructable source runs.");let l=[];for(let[c,m]of[...p.entries()].sort(([g],[h])=>g.localeCompare(h))){let g=await e.taskCreator.addSessionSource({profileId:e.profileId,sessionId:c,turnIds:[...m.turnIds].sort(),consentScope:"selected_turns"}),h=Array.isArray(g.metadata.harnessEvaluationReviews)?g.metadata.harnessEvaluationReviews:[],w={...g,metadata:{...g.metadata,harnessEvaluationReviews:Gt([...h,{id:t.id,contentHash:t.contentHash,workspaceId:t.workspaceRef,harnessRelease:t.harnessRelease,claimFingerprint:t.claim?.fingerprint??null,evidenceRefs:m.evidenceRefs,sourcePolicies:m.sourcePolicies}])}};l.push(await e.store.upsertTrainingSource(w))}return e.startCreation({profileId:e.profileId,sourceIds:l.map(c=>c.id),surface:"task_candidate",mode:"customize",entryMode:"automated",resourceIntent:"workproduct",buildIntent:zt.buildIntent,buildSpecification:null,objective:t.claim?.statement??t.reason,methodHint:zt.methodHint,preferredBaseModelId:null,preferredBaseModel:null,candidateId:r,analysisModel:e.analysisModel??null,analysisReasoningEffort:e.analysisReasoningEffort??null,createImproveRunId:null,targetIntent:{kind:"model",id:null,displayName:null,operation:"create"}})}d(ii,"startHarnessReviewTasksetAuthoring");function di(e){let t=e.flatMap(o=>Array.isArray(o.metadata.harnessEvaluationReviews)?o.metadata.harnessEvaluationReviews.filter(Jt):[]);if(!t.length)return null;let r=`${String(t[0].id)}:${String(t[0].contentHash)}`,s=t.filter(o=>`${String(o.id)}:${String(o.contentHash)}`===r);if(s.length!==e.length)return null;let a=s[0];return{review:{id:String(a.id),contentHash:String(a.contentHash),workspaceId:String(a.workspaceId),harnessRelease:a.harnessRelease,claimFingerprint:typeof a.claimFingerprint=="string"?a.claimFingerprint:null},evidenceRefs:Gt(s.flatMap(o=>Array.isArray(o.evidenceRefs)?o.evidenceRefs:[])),sourcePolicies:Gt(s.flatMap(o=>Array.isArray(o.sourcePolicies)?o.sourcePolicies:[]))}}d(di,"harnessReviewLineageFromSources");async function Ps(e){let t=e.taskset.metadata.harnessEvaluationLineage;if(!Jt(t)||!Jt(t.review))return null;let r=String(t.review.workspaceId??""),s={id:String(t.review.id??""),contentHash:String(t.review.contentHash??"")};if(!r||!s.id||!s.contentHash)throw new Error("Taskset Harness Evaluation lineage is incomplete.");let a=await e.store.listHarnessImprovementArtifacts(r,"evaluation_review",1e3),o=a.find(c=>_e(c)===_e(s));if(!o)throw new Error("Originating Harness Evaluation review was not found.");let n=e.evaluationResult?{id:e.evaluationResult.id,contentHash:e.evaluationResult.contentHash}:null,i={id:e.taskset.id,contentHash:e.taskset.contentHash},u=k({originRef:s,tasksetRef:i,evaluationRef:n}),f=a.find(c=>c.metadata.downstreamLinkKey===u);if(f)return f;let p=(e.now??(()=>new Date().toISOString()))(),l=Rr({schemaVersion:"openpond.harnessEvaluationReviewReceipt.v1",id:`evaluation-review-link-${u.slice(0,24)}`,ownerScope:o.ownerScope,workspaceRef:o.workspaceRef,harnessRelease:o.harnessRelease,previousWatermark:o.nextWatermark,nextWatermark:{cursor:k({cursor:o.nextWatermark.cursor,tasksetRef:i,evaluationRef:n}),throughCreatedAt:p},selectedEvidence:o.selectedEvidence,excludedEvidence:o.excludedEvidence,claim:o.claim,classification:"taskset",triage:o.triage,reason:n?"The approved Taskset completed a real baseline Evaluation.":"The approved Harness review materialized one immutable Taskset.",nextAuthority:"human_review",maxEstimatedCostUsd:o.maxEstimatedCostUsd,tasksetProposal:i,evaluation:n,trainingQualification:null,policyVersion:o.policyVersion,createdAt:p,metadata:{originReview:s,downstreamLinkKey:u,tasksetRevision:e.taskset.revision}});return await e.store.saveHarnessImprovementArtifact(r,"evaluation_review",l),l}d(Ps,"linkHarnessReviewTaskset");async function aa(e,t,r){let s=await e.getHarnessWorkspace(t);if(!s)throw new Error(`Harness workspace ${t} was not found.`);let a=(await e.listHarnessImprovementArtifacts(t,"evaluation_review",1e3)).find(n=>n.id===r.id&&n.contentHash===r.contentHash);if(!a||a.schemaVersion!=="openpond.harnessEvaluationReviewReceipt.v1")throw new Error("Harness Evaluation review was not found.");let o=a;if(o.classification!=="taskset"||o.nextAuthority!=="human_review")throw new Error("Only a human-review Taskset recommendation can enter Taskset authoring.");if(o.tasksetProposal)throw new Error("Harness Evaluation review already has a materialized Taskset link.");if(o.ownerScope.kind!==s.ownerScope.kind||o.ownerScope.id!==s.ownerScope.id)throw new Error("Harness Evaluation review owner scope does not match its workspace.");return o}d(aa,"requireTasksetReview");function _e(e){return`${e.id}:${e.contentHash}`}d(_e,"artifactKey");function Jt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}d(Jt,"isRecord");function Gt(e){let t=new Set;return e.filter(r=>{let s=JSON.stringify(r);return t.has(s)?!1:(t.add(s),!0)})}d(Gt,"uniqueObjects");import{randomUUID as na}from"node:crypto";function bt(e){let t=St(St(St(e.metadata).billing).pricing);return{version:Le(t.version,"pricing version"),source:Le(t.source,"pricing source"),effectiveAt:Le(t.effectiveAt,"pricing effective date"),inputUsdPerMillionTokens:Ue(t.inputUsdPerMillionTokens,"input token rate"),cachedInputUsdPerMillionTokens:Ue(t.cachedInputUsdPerMillionTokens,"cached input token rate"),outputUsdPerMillionTokens:Ue(t.outputUsdPerMillionTokens,"output token rate")}}d(bt,"hostedTokenPricingFromCatalog");function mi(e){let t=St(e);try{return{version:Le(t.version,"pricing version"),source:Le(t.source,"pricing source"),effectiveAt:Le(t.effectiveAt,"pricing effective date"),inputUsdPerMillionTokens:Ue(t.inputUsdPerMillionTokens,"input token rate"),cachedInputUsdPerMillionTokens:Ue(t.cachedInputUsdPerMillionTokens,"cached input token rate"),outputUsdPerMillionTokens:Ue(t.outputUsdPerMillionTokens,"output token rate")}}catch{return null}}d(mi,"hostedTokenPricingFromValue");function xe(e,t){let r=ve(e);if(r.promptTokens===null&&r.completionTokens===null)return null;let s=r.cachedPromptTokens??0;return((r.uncachedPromptTokens??r.promptTokens??0)*t.inputUsdPerMillionTokens+s*t.cachedInputUsdPerMillionTokens+(r.completionTokens??0)*t.outputUsdPerMillionTokens)/1e6}d(xe,"hostedUsageCostUsd");function St(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}d(St,"record");function Le(e,t){if(typeof e=="string"&&e.trim())return e.trim();throw new Error(`Hosted model catalog is missing ${t}.`)}d(Le,"requiredString");function Ue(e,t){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e;throw new Error(`Hosted model catalog is missing ${t}.`)}d(Ue,"requiredRate");function Ds(e={}){let t=e.catalog??pt,r=e.stream??ft;return{async prepare(s){if(s.providerId!=="openpond")throw new Error("The selected judge provider is not connected to the hosted judge transport.");if(s.revision!==null)throw new Error("This judge transport cannot enforce a model revision; select a provider with revision support.");let a=await t();if(a.error)throw new Error(`Judge model catalog unavailable: ${a.error}`);let o=a.models.find(l=>l.id===s.modelId);if(!o)throw new Error("The selected judge model is unavailable.");let n=Os(o.raw),i=bt(n),u=Hs(n.context_window,"context window"),f=Math.min(4096,Hs(n.output_limit,"output limit")),p=(u*Math.max(i.inputUsdPerMillionTokens,i.cachedInputUsdPerMillionTokens)+f*i.outputUsdPerMillionTokens)/1e6;if(!(p>0))throw new Error("The judge model must have a positive known charge ceiling.");return{maximumChargeUsd:p,async dispatch(l){l?.throwIfAborted();let c="",m=null,g=null,h=null,w=!1;for await(let _ of r({model:s.modelId,messages:[{role:"system",content:s.system},{role:"user",content:s.data}],requestId:`learning-judge-${na()}`,maxTokens:f,temperature:s.temperature,signal:l})){let x=Os(_.raw);if(typeof x.model=="string"){if(m!==null&&x.model!==m)throw new Error("Judge response model identity changed during streaming.");m=x.model}if(typeof x.id=="string"){if(g!==null&&g!==x.id)throw new Error("Judge response identity changed during streaming.");g=x.id}if(_.type==="text_delta"&&(c+=_.text),c.length>1e5)throw new Error("Judge response exceeds the retained response limit.");_.type==="usage"&&(h=_.usage),_.type==="finish"&&(w=!0)}if(!w||!m||!g)throw new Error("Judge response did not include a complete model receipt.");let y=ve(h),S=y.promptTokens!==null&&y.completionTokens!==null?xe(h,i):null;return{text:c,modelId:m,modelRevision:null,responseId:g,inputTokens:y.promptTokens,outputTokens:y.completionTokens,costUsd:S}}}},async cancel({run:s}){return!s.judgeCalls?.some(a=>a.status==="reserved")}}}d(Ds,"createLearningHostedJudgeProvider");function Os(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}d(Os,"record");function Hs(e,t){if(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)throw new Error(`Judge catalog is missing its ${t}.`);return e}d(Hs,"positiveInteger");function xi(e,t=Ds()){return{execute(r){if(r.definition.execution.environment.entrypoint==="openpond.javascript-environment.v1")throw new Error("Tool Tasksets require grading an owner-recorded environment attempt.");let s=Pr({repository:e,scope:r.scope,run:r.run});return Ir({binding:r.binding,rewards:r.rewards,task:dt(r.evidence,r.definition),evidence:Mr(r.evidence,r.run.output),evaluatorContext:r.evidence.submission.evaluatorContext,signal:r.signal,modelJudge:Er({readRubric:d(a=>e.transaction(r.scope,async o=>oe(await ke(o,"asset",a.id,1),a)),"readRubric"),async executeBudgeted(a,o){let n=await t.prepare(a,{scope:r.scope,run:r.run});return Cr({store:s,maximumCharge:d(()=>n.maximumChargeUsd,"maximumCharge"),dispatch:d((u,f)=>n.dispatch(f),"dispatch")})(`grade-${k(a)}`,a,o)}}),customVerifier:d(async({grader:a,task:o,evidence:n})=>{let i=await Ye({repository:e,scope:r.scope,grader:a,task:o,evidence:n,evaluatorContext:r.evidence.submission.evaluatorContext,timeoutMs:r.run.timeoutMs,signal:r.signal});return{score:i.score,passed:i.passed,rewardEligible:a.rewardEligible,failureClass:null,feedback:[i.feedback],visibleEvidenceRefs:[],privilegedEvidenceRefs:i.evidenceRefs}},"customVerifier")})},async cancel({scope:r,run:s}){let a=await e.transaction(r,o=>ke(o,"grade",s.id));return a.judgeCalls?.some(o=>o.status==="reserved")?!1:t.cancel({scope:r,run:a})}}}d(xi,"createLocalTaskGradeExecutor");async function Ye(e){let t=await e.repository.transaction(e.scope,async r=>oe(await ke(r,"asset",e.grader.verifierRef.id,1),e.grader.verifierRef));return $e({source:t,exportName:e.grader.exportName,runtime:e.grader.runtime,timeoutMs:Math.min(e.grader.timeoutMs,e.timeoutMs??e.grader.timeoutMs),signal:e.signal,value:{task:e.task,attempt:e.evidence,input:e.task.input,output:e.evidence.output,expectedOutput:e.task.expectedOutput,evaluatorContext:e.evaluatorContext,infrastructureError:e.evidence.infrastructureError??null}})}d(Ye,"executeLocalLearningVerifier");import ia from"node:path";async function js(e,t,r){if(!r)throw new Error("Ordinary tool execution requires its owner's package directory.");let s=De({taskset:e,adapterId:qe(e)}),a=await vt({root:ia.join(r,"training","tasksets",ee(e)),content:{schemaVersion:"openpond.tasksetPackage.v1",taskset:s.tasksetRelease,environment:s.environmentRelease,verifierSet:s.verifierSetRelease},sources:ct.parse(e.metadata.portableFileInventory)}),o=Fr(a);if(!o)throw new Error("The Taskset does not declare a JavaScript execution graph.");let n=a.taskset.tasks.find(f=>f.id===t.id);if(!n)throw new Error("The selected task is missing from its executable package.");let i=o.assets.find(f=>f.id===o.execution.javascript.module.id),u=o.assets.find(f=>f.id===n.privilegedContextRef);return{execution:o.execution,module:i,initialState:JSON.parse(u.text),definition:L(a.taskset),instructions:Vr(a),task:n}}d(js,"loadOrdinaryToolEnvironment");var J="openpond.javascript-environment.v1";async function Be(e,t,r,s){let a=t.tasks.find(o=>o.id===r.id);if(!a||k(a)!==k(r))throw new Error("Tool task differs from the selected immutable Taskset.");return t.metadata.taskDefinition===void 0?js(t,r,s):e.learningRepository().transaction(t.profileId,async o=>{let n=await ye(o,"definition",ae.parse(t.metadata.taskDefinition)),i=n.execution.environment;if(i.entrypoint!==J||t.environment.entrypoint!==J||t.environment.kind!=="agent"||t.environment.stateful!==i.stateful||t.environment.defaultTimeoutMs!==i.defaultTimeoutMs||t.environment.networkPolicy!==i.networkPolicy||t.environment.deterministicSeeds!==i.deterministicSeeds||k(t.environment.toolNames)!==k(n.execution.tools.map(v=>v.name))||k(t.environment.metadata.portableTools)!==k(n.execution.tools)||k(t.policy)!==k(n.execution.policy)||k(t.metadata.rewardBinding)!==k(n.rewardBinding))throw new Error("Tool Taskset context differs from its pinned task definition.");let u=await ye(o,"binding",n.rewardBinding),f=await Promise.all(u.sources.map(v=>ye(o,"reward",v.reward))),p=it.parse({id:r.id,clusterKey:r.clusterKey,split:r.split,input:r.input,expectedOutput:r.expectedOutput,policyVisibleContext:r.policyVisibleContext,privilegedContextRef:r.privilegedContextRef,artifactRefs:[],tags:r.tags}),l={...n.execution,graders:be(u,f),tasks:[p]},c=await ke(o,"asset",Ur(l),1),m=$r.parse(JSON.parse(oe(c,c.asset))),g=[m.javascript.module,m.environment.actionSchemaRef,m.environment.observationSchemaRef,m.environment.stateSchemaRef].filter(v=>v!==null),h=[...new Set([...g.map(v=>v.id),r.privilegedContextRef].filter(v=>v!==null))],w=await Promise.all(h.map(v=>ke(o,"asset",v,1))),y=Br(l,c,w);if(k(t.environment.metadata.portableExecutionResources)!==k({environment:y.environment,verifierSet:y.verifierSet}))throw new Error("Tool Taskset publication differs from its private execution resources.");let S=w.find(v=>v.id===y.javascript.module.id),_=w.find(v=>v.id===r.privilegedContextRef),x=JSON.parse(oe(_,_.asset));return{execution:y,module:S,initialState:x,definition:L(n),instructions:n.instructions,task:p}})}d(Be,"loadStarterToolEnvironment");function Ns(e){let t=Wt({text:e.instructions,path:"policy/instructions.txt",mediaType:"text/plain",visibility:"policy"}),r=Wt({text:JSON.stringify({environment:L(e.execution.environment),verifierSet:L(e.execution.verifierSet),javascript:L(e.execution.javascript)}),path:"environment/dependencies.json",mediaType:"application/json",visibility:"host_private"}),s=_r({schemaVersion:"openpond.agentSnapshot.v2",id:`starter-agent-${e.definition.contentHash}`,sourceRelease:{id:e.definition.id,contentHash:e.definition.contentHash},instructions:[t.asset],skills:[],agents:[],toolDeclarations:e.execution.javascript.tools,capabilityRequirements:[],dependencyLock:r.asset,portability:{portable:!0,blockers:[],localOnlyAssetRefs:[],hostPrivateAssetRefs:[e.module.id,r.id]},metadata:{execution:J}}),a=xr({schemaVersion:"openpond.harnessRelease.v2",id:`starter-harness-${s.contentHash}`,agentSnapshot:{id:s.id,contentHash:s.contentHash},program:e.module.asset,tools:e.execution.javascript.tools,lifecycle:{create:!0,reset:!0,step:!0,collect:!0,destroy:!0,resetScope:"attempt"},graderInterface:{visibleEvidence:["output"],privilegedEvidence:["environment_state","private_verifier"],privateVerifierIsolation:!0},files:[t.asset,r.asset,e.module.asset],metadata:{execution:J}});return{agentSnapshot:s,harnessRelease:a,instructionContext:void 0}}d(Ns,"compileStarterToolHarness");import Rt from"node:path";import{constants as qs}from"node:fs";import{open as da,realpath as $s}from"node:fs/promises";var ca=P.string().regex(/^[a-f0-9]{64}$/),la=P.object({schemaVersion:P.literal("openpond.starterToolAttempt.v1"),requestId:P.string(),taskset:ae,taskHash:ca,model:P.unknown(),seed:P.number().int(),attempt:P.number().int(),definition:ae,policySource:P.enum(["model","fixture"]),environment:ae,verifierSet:ae,result:qr}).strict();async function _t(e){let{store:t,taskset:r,task:s,attempt:a}=e,o=await Be(t,r,s,e.storeDir),i=(await t.listTaskAttemptArtifacts({attemptId:a.id})).filter(S=>S.kind==="environment_state"&&S.tasksetId===r.id&&S.taskId===s.id&&S.attemptId===a.id&&a.artifactRefs.includes(S.id)&&a.privilegedOutcomeRef===S.id);if(i.length!==1)throw new Error("Tool grading requires exactly one owner-recorded environment artifact.");let u=i[0],f=await $s(Rt.join(e.storeDir,"training","evaluation-artifacts")),p=await $s(Rt.dirname(u.path)),l=Rt.relative(f,p);if(!l||l.startsWith("..")||Rt.isAbsolute(l))throw new Error("Tool evidence is outside the execution owner's artifact directory.");let c=await da(u.path,qs.O_RDONLY|qs.O_NOFOLLOW),m;try{let S=await c.stat();if(!S.isFile()||S.size>33554432||S.size!==u.sizeBytes)throw new Error("Tool evidence exceeds its declared byte boundary.");m=await c.readFile()}finally{await c.close()}if(m.byteLength!==u.sizeBytes||se(m)!==u.sha256)throw new Error("Owner-recorded tool evidence bytes changed.");let g=la.parse(JSON.parse(m.toString("utf8"))),{contentHash:h,...w}=g.result,y=g.result;if(k(w)!==h||!y.snapshot||!y.environmentCleanupComplete||!["completed","budget_exhausted","policy_failure"].includes(y.status)||k(g.taskset)!==k(L(r))||g.taskHash!==k(s)||k(g.model)!==k(a.modelRef)||g.seed!==a.seed||g.attempt!==a.attempt||a.tasksetId!==r.id||a.taskId!==s.id||a.split!==s.split||k(g.definition)!==k(o.definition)||k(g.environment)!==k(L(o.execution.environment))||k(g.verifierSet)!==k(L(o.execution.verifierSet))||y.taskId!==s.id||y.snapshot.seed!==a.seed||y.snapshot.inputHash!==k(s.input)||k(y.snapshot.definition)!==k(L(o.execution.javascript))||y.snapshot.finalStateHash!==k(y.snapshot.state)||k(a.output)!==k({text:y.output??""})||a.metadata.environmentAttemptHash!==h)throw new Error("Tool evidence differs from the selected task, model or recorded attempt.");if(a.metadata.policySource!==g.policySource)throw new Error("Tool evidence policy source changed.");return{environment:{status:y.status,collected:y.collected,definition:y.snapshot.definition,initialStateHash:y.snapshot.initialStateHash,finalStateHash:y.snapshot.finalStateHash,finalState:y.snapshot.state,events:y.snapshot.events}}}d(_t,"readStarterToolEvidence");async function Te(e,t){if(t.metadata.learning!==void 0)return He.parse(t.metadata.learning);if(t.metadata.rewardBinding===void 0)return;let r=ae.parse(t.metadata.rewardBinding);return e.learningRepository().transaction(t.profileId,async s=>{let a=await ye(s,"binding",r),o=[...new Map(a.sources.map(i=>[`${i.reward.id}:${i.reward.revision}:${i.reward.contentHash}`,i.reward])).values()],n=await Promise.all(o.map(i=>ye(s,"reward",i)));return{binding:a,rewards:n}})}d(Te,"resolveTasksetRewardBinding");async function ua(e,t,r){let s=await Te(e,t);if(!s)return{rewardExecution:void 0,verifierAssets:[]};let a=[...s.rewards.flatMap(i=>i.assets),...be(s.binding,s.rewards).flatMap(i=>i.kind==="custom_verifier"?[i.verifierRef]:i.kind==="model_judge"?[i.rubricRef]:[])],o=t.metadata.learning===void 0?void 0:await wt(r,t);if(o){let i=[...new Map(a.map(u=>{let f=o.learningResources.assets.find(p=>p.id===u.id);if(!f)throw new Error("Imported batch verifier is missing from its package.");return oe(f,u),[f.id,f]})).values()];return{rewardExecution:s,verifierAssets:i}}let n=await e.learningRepository().transaction(t.profileId,async i=>{let u=new Map;for(let f of a){let p=await ke(i,"asset",f.id,1);oe(p,f),u.set(p.id,p)}return[...u.values()]});return{rewardExecution:s,verifierAssets:n}}d(ua,"resolveTasksetTrainingReward");async function gd(e,t,r){let s=await ua(e,t,r.storeDir);if(!s.rewardExecution)return s;let a=be(s.rewardExecution.binding,s.rewardExecution.rewards);if(!s.rewardExecution.binding.sources.some(o=>o.role==="evaluation"&&o.weight>0))throw new Error("Managed training requires a positively weighted evaluation Reward source for retained validation.");if(a.some(o=>o.kind==="custom_verifier"&&o.runtime==="sandbox_process"))throw new Error("Managed preparation requires a qualified isolated sandbox for process verifiers.");if(r.placement!=="remote"||t.environment.kind==="work"||t.capabilities.requiresState||t.capabilities.requiresTools||a.some(o=>o.kind==="human"||o.kind==="model_judge"&&(!o.model||o.calibrationStatus!=="passed"))||t.tasks.some(o=>o.privilegedContextRef!==null)||!s.rewardExecution.binding.sources.some(o=>o.role==="training"&&o.weight>0)||r.hasLearnedPreferenceReward)throw new Error("This Reward binding requires an additional managed execution adapter.");return s}d(gd,"resolveManagedTasksetReward");async function Ls(e,t,r){let s=await Te(e,t);if(!s)throw new Error("The Taskset has no published Reward binding.");let a=be(s.binding,s.rewards);return async({grader:o,task:n,attempt:i,signal:u})=>{let f=t.tasks.find(m=>m.id===n.id);if(!f||k(f)!==k(n))throw new Error("Task differs from the selected immutable Taskset.");let p=null;if(t.environment.entrypoint===J){if(!r)throw new Error("Tool grading requires the execution owner's artifact directory.");p=await _t({store:e,storeDir:r,taskset:t,task:n,attempt:i})}else if(n.privilegedContextRef!==null)throw new Error("This authored Taskset requires a private evaluator-context resolver.");let l=a.find(m=>m.id===o.id);if(l?.kind!=="custom_verifier")throw new Error("The verifier is absent from the published Reward binding.");let c=it.parse({id:n.id,clusterKey:n.clusterKey,split:n.split,input:n.input,expectedOutput:n.expectedOutput,policyVisibleContext:n.policyVisibleContext,privilegedContextRef:n.privilegedContextRef,artifactRefs:[],tags:n.tags});return Ye({repository:e.learningRepository(),scope:t.profileId,grader:l,task:c,evidence:{output:i.output,artifactRefs:i.artifactRefs,runtimeEventRefs:i.runtimeEventRefs,infrastructureError:i.infrastructureError},evaluatorContext:p,signal:u})}}d(Ls,"createTasksetBindingVerifier");async function Ie(e,t,r){let s=r?ae.parse(r):null;if(s&&s.id!==t)throw new Error("Taskset execution reference differs from the requested Taskset.");let a=s?await e.getTasksetRevision(s.id,s.revision):await e.getTaskset(t);if(!a||s&&(a.contentHash!==s.contentHash||Re(a)!==s.contentHash))throw new Error("Taskset execution revision is unavailable or differs from its immutable hash.");return a}d(Ie,"requireLocalTasksetRevision");async function Sd(e,t,r){let s=await e.releaseForTaskset(t);return s||De({taskset:t,rewardExecution:r?await Te(r,t):void 0,adapterId:qe(t)}).tasksetRelease}d(Sd,"requireReleasedTaskset");import{createHash as ma}from"node:crypto";function Us(e,t,r){if(t.metadata.importedPackageHash!==e.contentHash)throw new Error("The Work projection differs from the admitted published package.");let s=e.taskset.tasks.find(n=>n.id===r.id);if(!s||s.split!==r.split||k(r.metadata.portableTaskRecord)!==k(s))throw new Error("The Work task differs from its exact released population.");let a=0,o=(r.assets??[]).map(n=>{let i=s.artifactRefs.find(l=>l.id===n.id&&l.contentHash===n.sha256&&l.path===n.artifactRef),u=i&&e.files.find(l=>k(l.asset)===k(i));if(!i||!u||i.visibility!=="policy")throw new Error("The Work task requests an unavailable or private evaluator file.");let f=Buffer.from(Wr(u));if(ma("sha256").update(f).digest("hex")!==n.sha256||f.length!==n.sizeBytes||n.split!==r.split)throw new Error("The published Work input manifest changed.");if(a+=f.length,a>25e7)throw new Error("Published Work inputs exceed the admitted 250 MB ceiling.");return{...n,assetId:n.id,storageName:n.stagingPath??n.fileName,bytes:f,sizeBytes:f.length}});if(o.length!==s.artifactRefs.length)throw new Error("The exact policy-visible Work asset population is incomplete.");return o}d(Us,"advancedPublishedWorkAssets");async function Yt(e,t=pt,r=!1){if(e.kind==="hosted_harness")return Yt({kind:"hosted_chat",modelId:e.modelId,...Nr(e)},t);if(e.kind!=="hosted_chat")throw new ne("local_target_not_qualified","Select an explicit model target for local execution.",422);if(e.harness&&!r)throw new ne("local_harness_not_qualified","This released Harness requires its native turn executor; it cannot run as a model-only case.",422);let s=await t();if(s.error)throw new ne("local_model_catalog_unavailable",s.error,422);let a=s.models.find(c=>c.id===e.modelId);if(!a)throw new ne("local_model_unavailable","The selected model is unavailable.",422);let o=Bs(a.raw),n=bt(o),i=Bs(o.capabilities).samplingParameters===!0;if(!i&&(e.temperature!==0||e.topP!==1))throw new ne("local_sampling_unsupported","This model uses provider-managed sampling. Custom temperature or top P requires an explicit supported capability.",422);let u=Ws(o.context_window),f=Ws(o.output_limit);if(e.maxOutputTokens>f)throw new ne("local_model_output_limit","The model cannot accept the configured output limit.",422);let p={providerId:"openpond",modelId:e.modelId,maxOutputTokens:e.maxOutputTokens,...i?{temperature:e.temperature,topP:e.topP}:{},messages:e.messages??[]},l=(u*Math.max(n.inputUsdPerMillionTokens,n.cachedInputUsdPerMillionTokens)+e.maxOutputTokens*n.outputUsdPerMillionTokens)/1e6;if(!(l>0))throw new ne("local_model_charge_unknown","The model must publish an enforceable positive request ceiling.",422);return{model:{...p,configurationHash:k({configuration:p,contextWindow:u,outputLimit:f,pricing:n})},pricing:n,maximumChargeUsd:l}}d(Yt,"prepareLocalExperimentModel");function Nd(e){let t=e.admission.streamFactory?.(e)??e.admission.stream??e.stream??ft;return async function*(r){if(!r.requestId)throw new ne("local_request_identity_missing","Every local model dispatch requires a stable request identity.");let s=e.admission.model;if(r.model!==s.modelId||r.maxTokens!==s.maxOutputTokens||r.temperature!==s.temperature||r.topP!==s.topP)throw new ne("local_model_configuration_conflict","The native model request changed its admitted model, output limit or sampling configuration.",422);let a=xs();a?.assertExecution(e.executionId);let o={teamId:e.teamId,id:e.executionId,ownerId:e.ownerId,requestId:r.requestId};await e.store.reserveLocalCharge({...o,caseId:e.caseId,maximumUsd:e.admission.maximumChargeUsd}),r.signal?.aborted&&(await e.store.settleLocalCharge({...o,costUsd:null,usage:null,notDispatched:!0}),r.signal.throwIfAborted());try{await e.store.markLocalChargeDispatched(o.teamId,o.id,o.requestId,o.ownerId)}catch(p){throw a&&await e.store.settleLocalCharge({...o,costUsd:null,usage:null,notDispatched:!0}),p}await e.store.appendLocalExperimentEvent({...o,caseId:e.caseId,type:"model.dispatch",payload:{requestId:o.requestId,model:r.model,messages:r.messages}});let n=null,i=!1,u=!1,f;try{for await(let p of t(r)){u=!0,p.type==="usage"&&(n=p.usage),p.type==="finish"&&(i=!0);let l=p.type==="text_delta"?{requestId:o.requestId,text:p.text}:p.type==="tool_call_delta"?{requestId:o.requestId,toolCalls:p.toolCalls}:p.type==="usage"?{requestId:o.requestId,usage:ve(p.usage)}:p.type==="finish"?{requestId:o.requestId,finishReason:p.finishReason}:null;l&&await e.store.appendLocalExperimentEvent({...o,caseId:e.caseId,type:`model.${p.type}`,payload:l}),yield p}}catch(p){throw!u&&p instanceof Is&&p.executionId===o.id&&p.requestId===o.requestId&&(f=p),p}finally{let p=ve(n),l=e.admission.pricing&&i&&p.promptTokens!==null&&p.completionTokens!==null?xe(n,e.admission.pricing):null;await e.store.settleLocalCharge({...o,costUsd:l,confirmedTransportNotInvoked:f,usage:n===null?null:{promptTokens:p.promptTokens,completionTokens:p.completionTokens,cachedPromptTokens:p.cachedPromptTokens,uncachedPromptTokens:p.uncachedPromptTokens}})}}}d(Nd,"createLocalBudgetedModelStream");function Bs(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}d(Bs,"record");function Ws(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)throw new ne("local_model_bound_unknown","The model catalog is missing an enforceable context/output bound.",422);return e}d(Ws,"positive");import{AsyncLocalStorage as pa}from"node:async_hooks";import fa from"node:path";var Fs=new pa;function Vs(){return Fs.getStore()}d(Vs,"currentAdvancedRefinerBoundary");function Jd(e){let t=Sr(fa.join(e.storeDir,"library","harnesses","advanced-refiner-paid-calls.sqlite"));t.exec(`CREATE TABLE IF NOT EXISTS advanced_refiner_budgets(id TEXT PRIMARY KEY,actor_id TEXT NOT NULL,team_id TEXT NOT NULL,pin_hash TEXT NOT NULL,maximum_spend REAL NOT NULL,maximum_steps INTEGER NOT NULL,expires_at TEXT NOT NULL);
3
3
  CREATE TABLE IF NOT EXISTS advanced_refiner_calls(run_id TEXT NOT NULL,id TEXT NOT NULL,intent_hash TEXT NOT NULL,ceiling REAL NOT NULL,state TEXT NOT NULL,actual_spend REAL,result TEXT,PRIMARY KEY(run_id,id));`);function r(a){t.exec("BEGIN IMMEDIATE");try{let o=a();return t.exec("COMMIT"),o}catch(o){throw t.exec("ROLLBACK"),o}}d(r,"transaction");async function s(a,o,n){let i=Ft(o);await e.authorize(i),r(()=>{let l=t.prepare("SELECT * FROM advanced_refiner_budgets WHERE id=?").get(a);if(l){if(l.actor_id!==i.actorId||l.team_id!==i.teamId||l.pin_hash!==i.contentHash)throw new Error("Advanced Run budget belongs to another immutable admission.");return}t.prepare("INSERT INTO advanced_refiner_budgets VALUES(?,?,?,?,?,?,?)").run(a,i.actorId,i.teamId,i.contentHash,i.maximumCostUsd,i.maximumModelSteps,new Date(Date.now()+i.maximumDurationMs).toISOString())});let u=t.prepare("SELECT expires_at FROM advanced_refiner_budgets WHERE id=?").get(a),f=Date.parse(String(u.expires_at))-Date.now();if(f<=0)throw new Error("The immutable advanced evaluation duration is exhausted.");let p={runId:a,pin:i,signal:AbortSignal.timeout(f),authorize:d(()=>e.authorize(i),"authorize"),async resolveWorkAssets(l,c){await e.authorize(i),p.signal.throwIfAborted();let m=await e.packageForPin(i),g=Us(m,l,c);return await e.authorize(i),p.signal.throwIfAborted(),g},async call(l,c,m,g,h){if(await e.authorize(i),!Number.isInteger(g)||g<1)throw new Error("Advanced paid requests require a finite enforced token ceiling.");let w=c.model;if(w?.providerId!=="openpond"||!w.modelId)throw new Error("Advanced paid calls require an explicitly qualified hosted model.");let y=w.modelId,S=e.prepareModel?await e.prepareModel(y,g,m):await(async()=>{let C=await Yt({kind:"hosted_chat",modelId:y,maxOutputTokens:g,temperature:0,topP:1});if(k(C.pricing)!==k(m))throw new Error("The actual model pricing differs from its reviewed request pin.");return{configurationHash:C.model.configurationHash,maximumChargeUsd:C.maximumChargeUsd}})();if(!/^[a-f0-9]{64}$/.test(S.configurationHash)||!Number.isFinite(S.maximumChargeUsd)||S.maximumChargeUsd<=0)throw new Error("The actual owner model ceiling is unavailable.");let _=k({intent:c,pricing:m,maximumOutputTokens:g,modelConfigurationHash:S.configurationHash}),x=S.maximumChargeUsd,v=r(()=>{let C=t.prepare("SELECT * FROM advanced_refiner_budgets WHERE id=?").get(a);if(!C||String(C.expires_at)<=new Date().toISOString())throw new Error("The immutable advanced evaluation duration is exhausted.");let E=t.prepare("SELECT * FROM advanced_refiner_calls WHERE run_id=? AND id=?").get(a,l);if(E){if(E.intent_hash!==_)throw new Error("Advanced provider request ID retains another exact payload.");if(E.state!=="completed")throw new Error("This paid request has an unknown outcome; recover its actual provider receipt before resuming.");return JSON.parse(String(E.result))}let T=t.prepare("SELECT COUNT(*) AS steps,COALESCE(SUM(COALESCE(actual_spend,ceiling)),0) AS spent,SUM(CASE WHEN state NOT IN ('completed','not_dispatched') THEN 1 ELSE 0 END) AS unknown FROM advanced_refiner_calls WHERE run_id=?").get(a);if(Number(T.unknown)>0)throw new Error("A prior advanced paid request is unsettled; no fresh request is allowed.");if(Number(T.steps)>=i.maximumModelSteps||Number(T.spent)+x>i.maximumCostUsd+1e-9)throw new Error("The advanced evaluation step or cumulative spend ceiling is exhausted.");t.prepare("INSERT INTO advanced_refiner_calls(run_id,id,intent_hash,ceiling,state) VALUES(?,?,?,?,?)").run(a,l,_,x,"reserved")});if(v!==void 0)return await e.authorize(i),p.signal.throwIfAborted(),v;let M=!1;try{if(await e.authorize(i),p.signal.throwIfAborted(),t.prepare("UPDATE advanced_refiner_calls SET state='dispatched' WHERE run_id=? AND id=? AND intent_hash=? AND state='reserved'").run(a,l,_).changes!==1)throw new Error("The retained advanced request admission changed.");M=!0;let E=await h();if(E.costUsd===null||!Number.isFinite(E.costUsd)||E.costUsd<0||E.costUsd>x+1e-9)throw new Error("The actual provider receipt cannot settle its admitted request ceiling.");let T=JSON.stringify(E.value);if(Buffer.byteLength(T)>8*1024*1024)throw new Error("The advanced provider response exceeds the retained output bound.");return r(()=>{if(t.prepare("UPDATE advanced_refiner_calls SET state='completed',actual_spend=?,result=? WHERE run_id=? AND id=? AND intent_hash=? AND state='dispatched'").run(E.costUsd,T,a,l,_).changes!==1)throw new Error("The advanced request settlement changed concurrently.")}),await e.authorize(i),E.value}catch(C){throw M?t.prepare("UPDATE advanced_refiner_calls SET state='unknown' WHERE run_id=? AND id=? AND state='dispatched'").run(a,l):t.prepare("UPDATE advanced_refiner_calls SET state='not_dispatched',actual_spend=0 WHERE run_id=? AND id=? AND state='reserved'").run(a,l),C}}};return Fs.run(p,n)}return d(s,"run"),{run:s,async authorize(a){await e.authorize(Ft(a))},read(a,o){return t.prepare("SELECT * FROM advanced_refiner_budgets WHERE id=? AND actor_id=? AND team_id=? AND pin_hash=?").get(a,o.actorId,o.teamId,o.contentHash)?t.prepare("SELECT id,intent_hash,ceiling,state,actual_spend FROM advanced_refiner_calls WHERE run_id=? ORDER BY id").all(a):null},accounting(a,o){let n=this.read(a,o)??[],i=n.filter(f=>f.state!=="completed"&&f.state!=="not_dispatched"),u=n.reduce((f,p)=>f+Number(p.actual_spend??0),0);return{modelRequests:n.filter(f=>f.state!=="not_dispatched").length,knownSpendUsd:u,totalSpendUsd:i.length?null:u,heldUsd:i.reduce((f,p)=>f+Number(p.ceiling),0),uncertainRequests:i.filter(f=>f.state!=="reserved").length}},close(){t.close()}}}d(Jd,"createAdvancedRefinerPaidBoundary");import ra from"node:path";function xt(e,t,r){let s=new Date().toISOString();return W.parse({schemaVersion:"openpond.taskAttempt.v1",id:`fixture_attempt_${t.id}_${r}`,tasksetId:e,taskId:t.taskId,split:Ke(t)??"frozen_eval",attempt:r,seed:0,modelRef:null,startedAt:s,completedAt:s,output:t.output,runtimeEventRefs:[],artifactRefs:[],privilegedOutcomeRef:null,infrastructureError:t.infrastructureError,costUsd:0,latencyMs:0,userInterventions:0,metadata:{fixtureLabel:t.label}})}d(xt,"fixtureAttempt");function Ke(e){let t=e&&typeof e=="object"&&!Array.isArray(e)&&"metadata"in e&&e.metadata&&typeof e.metadata=="object"&&!Array.isArray(e.metadata)?e.metadata.artifactSplit:null;return t==="train"||t==="validation"||t==="test"||t==="frozen_eval"?t:null}d(Ke,"artifactSplit");function Js(e){let t=Gr(e.taskset),r=t.issues.filter(b=>b.severity==="error").map(b=>({code:b.code,message:b.message,path:b.path})),s=t.issues.filter(b=>b.severity==="warning").map(b=>({code:b.code,message:b.message,path:b.path})),a=typeof e.taskset.metadata.trainingMethod=="string"?e.taskset.metadata.trainingMethod:null,o=ga(a),n=o==="sft",i=o==="dpo",u=o==="grpo"||o==="ppo",f=new Set(e.taskset.learningSignals.demonstrations.filter(b=>b.approved&&b.taskId).map(b=>b.taskId)),p=e.taskset.metadata.learning===void 0?null:He.parse(e.taskset.metadata.learning),l=d(b=>p?p.admissions.some(B=>B.taskId===b.id&&B.supervisedTarget!==null):b.expectedOutput!=null,"hasSupervisedTarget"),c=e.taskset.datasetArtifact,m=new Set(zs(e.taskset.metadata.approvedArtifactSignals)),g=!!c?.schema.fields.some(b=>b.semanticRole==="demonstration"||b.semanticRole==="expected_output"||b.semanticRole==="chosen"),h=e.taskset.tasks.filter(b=>b.split==="train"&&(l(b)||u)),w=n?h.filter(b=>f.has(b.id)):h,y=e.taskset.tasks.filter(b=>b.split==="train"&&l(b)&&!f.has(b.id)),S=e.taskset.tasks.filter(b=>b.split==="frozen_eval"&&(b.expectedOutput||u)),_=c&&g?c.splitCounts.train??0:0,x=c&&g?c.splitCounts.frozen_eval??0:0,v=c?m.has(o??""):!1,M=c?v?_:0:w.length,C=e.taskset.learningSignals.preferences.filter(b=>b.approved).length,E=Yr(e.taskset),T=E?E.binding.sources.filter(b=>b.role==="training"&&b.weight>0&&(!b.taskIds||w.some(B=>b.taskIds.includes(B.id)))).length:e.taskset.learningSignals.rewards.filter(b=>b.approved&&b.executable).length,A=i?C:u?T?M:0:M,R=c?x:S.length;A===0&&r.push(n?{code:"sft_demonstrations_missing",message:"At least one explicitly approved training demonstration is required.",path:"learningSignals.demonstrations"}:i?{code:"dpo_preferences_missing",message:"At least one approved chosen/rejected response pair is required for DPO.",path:"learningSignals.preferences"}:{code:"online_reward_missing",message:`${o?.toUpperCase()??"Online training"} requires an executable reward-bearing task.`,path:"learningSignals.rewards"});let j=c?n&&!v?_:0:y.length;n&&j&&r.push({code:"sft_demonstrations_unapproved",message:`${j} training example${j===1?" is":"s are"} not explicitly approved.`,path:c?"metadata.approvedArtifactSignals":"learningSignals.demonstrations"}),R===0&&s.push({code:"frozen_eval_missing",message:"At least one independent evaluation example is recommended before making quality claims.",path:c?"datasetArtifact.splitCounts.frozen_eval":"tasks"});let $=new Set(w.map(b=>b.clusterKey)),z=new Set(S.map(b=>b.clusterKey)),U=c&&e.taskset.metadata.splitIsolationVerified===!0;(c?!U||A===0||R===0:$.size===0||z.size===0||[...$].some(b=>z.has(b)))&&s.push({code:"independent_evaluation_missing",message:"Independent source clusters are recommended before using evaluation results for quality claims.",path:c?"metadata.splitIsolationVerified":"tasks"}),(c?e.taskset.metadata.artifactRowsVerified!==!0:e.taskset.tasks.some(b=>typeof b.metadata.exampleOrigin!="string"))&&r.push({code:"example_provenance_missing",message:"Every training and evaluation example must record whether it was extracted, corrected, synthetic, or expert-authored.",path:c?"metadata.artifactRowsVerified":"tasks.metadata.exampleOrigin"});let Q=ha(e.taskset.metadata.diagnosis);(!Q||typeof Q.summary!="string"||!Array.isArray(Q.stableBehavior))&&s.push({code:"capability_diagnosis_missing",message:"A capability diagnosis is recommended to separate stable behavior from changing knowledge.",path:"metadata.diagnosis"}),Q?.trainingEligible===!1&&s.push({code:"training_not_recommended",message:"The capability diagnosis does not recommend storing this behavior in model weights.",path:"metadata.diagnosis.trainingEligible"});let me=e.taskset.graders.some(b=>b.rewardEligible&&(b.kind!=="model_judge"||b.metadata.calibrationIsAdvisory!==!0));me&&!e.graderAudit&&s.push({code:"grader_audit_missing",message:"Optional grader calibration evidence has not been recorded.",path:"graderFixtures"}),me&&e.graderAudit&&e.graderAudit.tasksetHash!==e.taskset.contentHash&&s.push({code:"grader_audit_stale",message:"Optional grader calibration evidence predates this immutable Taskset revision.",path:"graderFixtures"}),me&&e.graderAudit&&!e.graderAudit.passed&&s.push({code:"grader_audit_failed",message:"The grader did not match every optional calibration fixture's expected outcome.",path:"graderFixtures"}),me&&e.graderAudit&&!e.graderAudit.hackingChecksPassed&&s.push({code:"grader_adversarial_calibration_failed",message:"Adversarial or prompt-injection calibration fixtures did not match their expected grader outcomes.",path:"graders"}),me&&e.graderAudit&&!e.graderAudit.leakageChecksPassed&&r.push({code:"environment_leakage",message:"Environment or privileged-state leakage checks failed.",path:"environment"}),me&&e.graderAudit&&!e.graderAudit.infrastructureSafetyPassed&&r.push({code:"infrastructure_reward",message:"An infrastructure failure produced a score or eligible reward.",path:"graderFixtures"});let tt=e.taskset.graders.some(b=>b.rewardEligible);u&&!tt&&r.push({code:"online_reward_grader_missing",message:`${o?.toUpperCase()} requires a user-selected reward-eligible grader.`,path:"graders"});let ie=o??(A>0&&e.taskset.capabilities.compatibleMethods.includes("sft")?"sft":"none"),I=e.taskset.learningSignals.demonstrations.filter(b=>b.approved).map(b=>b.id),N=ie==="none"?null:{primaryMethod:ie,bootstrap:ie==="grpo"&&I.length?{method:"sft",purpose:"trajectory_bootstrap",demonstrationRefs:I,limitations:["The SFT bootstrap imitates approved trajectories; it does not optimize verifier reward.","Completing the bootstrap does not satisfy the primary GRPO recommendation."]}:null},K=r.length===0,pe=r.length>0,rt=["sft","dpo","grpo","ppo"].map(b=>{let B=[],X=[];b==="sft"&&I.length===0&&(B.push("demonstrations_missing"),X.push("Add at least one approved prompt/response demonstration.")),b==="dpo"&&C===0&&(B.push("preference_pairs_missing"),X.push("Add at least one approved chosen/rejected response pair.")),(b==="grpo"||b==="ppo")&&T===0&&(B.push("executable_reward_missing"),X.push("Implement and validate an executable scalar reward.")),b==="ppo"&&(B.push("value_model_required"),X.push("Choose and bind a value/critic model before PPO can execute.")),R===0&&(B.push("frozen_eval_missing"),X.push("Add an independent frozen-evaluation split.")),pe&&B.length===0&&(B.push("taskset_not_ready"),X.push("Resolve the Dataset validation and grader-audit blockers."));let Me=B.filter(fe=>fe!=="value_model_required");return{method:b,status:Me.length?"needs_dataset_work":b===ie?"recommended":"compatible",reasonCodes:B,reasons:X}});return zr.parse({schemaVersion:"openpond.tasksetReadiness.v1",tasksetId:e.taskset.id,tasksetHash:e.taskset.contentHash,ready:K,recommendedMethod:ie,trainingPath:N,methodReadiness:rt,compatibleDestinationClasses:K?ie==="grpo"?["export","custom","hosted_managed"]:["export","custom"]:["export"],blockers:r,advisories:s,warnings:[...t.issues.filter(b=>b.severity==="warning").map(b=>b.message),...ie==="grpo"?["GRPO is readiness-compatible but not executable in the local CPU fixture."]:[],...zs(e.taskset.metadata.warnings)],generatedAt:e.generatedAt??new Date().toISOString(),metadata:{reportHash:k([e.taskset.contentHash,r])}})}d(Js,"buildTasksetReadiness");function ga(e){return e==="sft"||e==="dpo"||e==="grpo"||e==="ppo"||e==="sdft"||e==="opsd"||e==="sdpo"?e:null}d(ga,"trainingPathMethod");function ha(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}d(ha,"metadataRecord");function zs(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()):[]}d(zs,"metadataStrings");import eo from"node:path";function Gs(e,t,r){let s=He.parse(t.metadata.learning),a=be(s.binding,s.rewards);return async({grader:o,task:n,attempt:i,signal:u})=>{let f=s.admissions.find(h=>h.taskId===n.id),p=a.find(h=>h.id===o.id);if(!f||p?.kind!=="custom_verifier")throw new Error("Prepared batch has no matching verifier admission.");let l=await wt(r,t),c=l?l.learningResources?.evidence.find(h=>Ar(L(h),f.evidence)):await e.learningRepository().transaction(t.profileId,h=>ye(h,"evidence",f.evidence));if(!c)throw new Error("Imported batch evidence is missing from its package.");let m=dt(c,s.definition),g=d(h=>({id:h.id,input:h.input,expectedOutput:h.expectedOutput,policyVisibleContext:h.policyVisibleContext,privilegedContextRef:h.privilegedContextRef}),"selected");if(k(g(n))!==k(g(m)))throw new Error("Prepared task differs from its admitted evaluator context.");if(l){let h=l.learningResources?.assets.find(w=>w.id===p.verifierRef.id);if(!h)throw new Error("Imported batch verifier is missing from its package.");return $e({source:oe(h,p.verifierRef),exportName:p.exportName,timeoutMs:p.timeoutMs,signal:u,value:{task:m,attempt:{output:i.output,artifactRefs:i.artifactRefs,runtimeEventRefs:i.runtimeEventRefs,infrastructureError:i.infrastructureError},input:m.input,output:i.output,expectedOutput:m.expectedOutput,evaluatorContext:c.submission.evaluatorContext,infrastructureError:i.infrastructureError??null}})}return Ye({repository:e.learningRepository(),scope:t.profileId,grader:p,task:m,evidence:{output:i.output,artifactRefs:i.artifactRefs,runtimeEventRefs:i.runtimeEventRefs,infrastructureError:i.infrastructureError},evaluatorContext:c.submission.evaluatorContext,signal:u})}}d(Gs,"createLearningBatchVerifier");import{readFile as ka,realpath as Ys}from"node:fs/promises";import Ks from"node:path";async function Xs(e){let t=await Ys(e.allowedRoot),r=await Ys(Ks.resolve(t,e.grader.module));if(r!==t&&!r.startsWith(`${t}${Ks.sep}`))throw new Error("Verifier module is outside the approved Taskset root.");let s=await ka(r);if(e.grader.metadata.portableVerifierRef!==void 0){let o=Tr.parse(e.grader.metadata.portableVerifierRef);if(o.sizeBytes!==s.length||o.contentHash!==se(s))throw new Error("Verifier source differs from its immutable Taskset release.")}let a=new TextDecoder("utf-8",{fatal:!0}).decode(s);return $e({source:a,exportName:e.grader.exportName,runtime:e.grader.runtime,timeoutMs:e.grader.timeoutMs,signal:e.signal,value:{task:e.task,attempt:e.attempt,input:e.task.input,expectedOutput:e.task.expectedOutput,output:e.attempt.output,infrastructureError:e.attempt.infrastructureError,...e.evaluatorContext?{evaluatorContext:e.evaluatorContext}:{}}})}d(Xs,"runSandboxedVerifier");import{constants as Kt}from"node:fs";import{open as ya,realpath as Zs}from"node:fs/promises";import We from"node:path";async function It(e,t){let r=De({taskset:t,adapterId:qe(t)});if(typeof t.metadata.importedPackageHash=="string"){let s=await Rs(e,t.metadata.importedPackageHash);if(s.taskset.contentHash!==r.tasksetRelease.contentHash)throw new Error("Evaluation Taskset differs from its pinned portable package.");let a=ct.parse(t.metadata.portableFileInventory??[]),{files:o,contentHash:n,...i}=s,u=await vt({root:We.join(e,"training","tasksets",ee(t)),content:i,sources:o.map(f=>({asset:f.asset,sourcePath:a.find(p=>p.asset.id===f.asset.id)?.sourcePath??f.asset.path})),fileOrder:o.map(f=>f.asset.id)});if(u.contentHash!==s.contentHash)throw new Error("Evaluation package changed during capture.");return u}return _s({storeDir:e,taskset:t,content:{schemaVersion:"openpond.tasksetPackage.v1",taskset:r.tasksetRelease,environment:r.environmentRelease,verifierSet:r.verifierSetRelease}})}d(It,"captureTasksetEvaluationPackage");function Qs(e){return async({grader:t,task:r,attempt:s,signal:a})=>{let o=e.taskset.tasks.find(l=>l.id===r.id),n=e.taskset.graders.find(l=>l.id===t.id);if(!o||k(o)!==k(r)||!n||k(n)!==k(t)||s.tasksetId!==e.taskset.id||s.taskId!==r.id||s.split!==r.split)throw new Error("Process grading differs from the selected Taskset revision or attempt.");let i=e.packageValue.taskset.tasks.find(l=>l.id===r.id),u=e.packageValue.taskset.graders.find(l=>l.id===t.id);if(!i||u?.kind!=="custom_verifier"||u.runtime!=="sandbox_process")throw new Error("The process verifier is absent from the immutable package.");let f=e.fixtures?.get(s.id);if(f&&f.attemptHash!==k(s))throw new Error("Fixture attempt changed before private grading.");let p=f?.artifacts??await wa(e.store,e.storeDir,e.taskset,s);return Es({packageValue:e.packageValue,grader:u,task:i,evidence:{output:s.output,artifactRefs:s.artifactRefs,runtimeEventRefs:s.runtimeEventRefs,infrastructureError:s.infrastructureError,artifacts:p},signal:a,authorize:d(async()=>{a?.throwIfAborted()},"authorize")})}}d(Qs,"createTasksetProcessVerifier");async function wa(e,t,r,s){let a=await e.listTaskAttemptArtifacts({attemptId:s.id}),o=[],n=0;if(new Set(s.artifactRefs).size!==s.artifactRefs.length)throw new Error("Attempt contains duplicate artifact references.");for(let i of s.artifactRefs){let u=a.filter(g=>g.id===i&&g.tasksetId===r.id&&g.taskId===s.taskId&&g.attemptId===s.id);if(u.length!==1)throw new Error("Attempt artifact is not recorded by its execution owner.");let f=u[0];if(f.kind!=="output_artifact")continue;if(o.length>=16||(n+=f.sizeBytes)>2e7)throw new Error("Attempt artifacts exceed their byte boundary.");let p=await Zs(t),l=await Zs(We.dirname(f.path));if(![We.join(p,"training/evaluation-artifacts"),We.join(p,"work/outputs")].some(g=>l===g||l.startsWith(`${g}${We.sep}`)))throw new Error("Attempt artifact is outside the execution owner's output directories.");let c=await ya(f.path,Kt.O_RDONLY|Kt.O_NOFOLLOW|Kt.O_NONBLOCK),m;try{let g=await c.stat();if(!g.isFile()||g.size!==f.sizeBytes)throw new Error("Owner-recorded artifact size changed.");m=Buffer.alloc(g.size);let h=0;for(;h<m.length;){let w=await c.read(m,h,m.length-h,h);if(!w.bytesRead)throw new Error("Owner-recorded artifact changed during capture.");h+=w.bytesRead}if((await c.read(Buffer.alloc(1),0,1,h)).bytesRead)throw new Error("Owner-recorded artifact changed during capture.")}finally{await c.close()}if(se(m)!==f.sha256)throw new Error("Owner-recorded artifact bytes changed.");o.push({reference:{id:f.id,contentHash:f.sha256,mediaType:f.mediaType??"application/octet-stream",sizeBytes:f.sizeBytes},title:We.basename(typeof f.metadata.requiredOutputPath=="string"?f.metadata.requiredOutputPath:f.path),contentType:f.mediaType??"application/octet-stream",base64:m.toString("base64")})}return o}d(wa,"readOwnedOutputArtifacts");async function Et(e,t,r){if(!t.graders.some(p=>p.kind==="custom_verifier"))return;let s=t.graders.some(p=>p.kind==="custom_verifier"&&p.runtime==="sandbox_process"),a=t.metadata.learning!==void 0?await Gs(e.store,t,e.storeDir):t.metadata.rewardBinding!==void 0?await Ls(e.store,t,e.storeDir):void 0;if(a&&!s)return a;let o=e.storeDir?null:await(e.loadProfileState??br)(),n=e.storeDir?eo.join(e.storeDir,"training","tasksets",ee(t)):o?.sourcePath?eo.join(o.sourcePath,"tasksets",t.id):null,i=typeof t.metadata.creationSnapshotId=="string"?t.metadata.creationSnapshotId:null,u=i?await e.store.getTaskDesignProposal(i):null;if(n&&t.purpose!=="benchmark"&&t.environment.metadata.runtimeSourceTasksetId===void 0&&await ut(t,n,{generatedFiles:u?.generatedFiles??[]}),s&&!e.storeDir)throw new Error("Process grading requires the execution owner's package directory.");let f=s?Qs({store:e.store,storeDir:e.storeDir,taskset:t,packageValue:r?.packageValue??await It(e.storeDir,t),fixtures:r?.fixtures}):void 0;return n?async({grader:p,task:l,attempt:c,signal:m})=>{let g=t.graders.find(w=>w.id===p.id);if(!g||g.kind!=="custom_verifier")throw new Error("Verifier is not declared by this Taskset revision.");if(g.runtime==="sandbox_process")return f({grader:p,task:l,attempt:c,signal:m});if(a)return a({grader:g,task:l,attempt:c,signal:m});let h;if(t.environment.entrypoint===J&&!c.infrastructureError){if(!e.storeDir)throw new Error("Tool grading requires the execution owner's artifact directory.");h=await _t({store:e.store,storeDir:e.storeDir,taskset:t,task:l,attempt:c})}return Xs({grader:g,task:l,attempt:c,allowedRoot:n,signal:m,evaluatorContext:h})}:void 0}d(Et,"createTasksetEvaluationVerifier");var va=new Set(["correct","incorrect","parse_failure","budget_exhausted","tool_schema_violation","infrastructure_failure","cancelled"]);async function to(e){let t=Sa(e.attempt);if(t){let f=k(e.graders),p=`Taskset Work attempt ended with ${t.failureClass}: `+t.message;return{schemaVersion:"openpond.gradeResult.v1",id:`grade_${k([e.attempt.id,f,t]).slice(0,24)}`,attemptId:e.attempt.id,graderSetHash:f,score:null,passed:!1,components:e.graders.map(l=>({graderId:l.id,graderVersion:l.version,score:0,passed:!1,hardGate:l.hardGate,rewardEligible:!1,feedback:p,evidenceRefs:e.attempt.artifactRefs,judge:l.kind==="model_judge"?l.judge:null,calibrationStatus:l.kind==="model_judge"?l.calibrationStatus:"not_applicable"})),failureClass:t.failureClass,feedback:[p],rewardEligible:!1,createdAt:e.now?.()??new Date().toISOString()}}let r=e.learning?null:ba(e.attempt.metadata);if(!r)try{return await lt(e)}catch(f){return Ta({attempt:e.attempt,graders:e.graders,now:e.now,error:f})}let s=k(e.graders),a=r.rewardEligible?r.outcome==="correct"?1:0:null,o=r.outcome==="correct",n=Ra(r.outcome),i=`Cross-System trajectory verifier outcome: ${r.outcome}.`,u=e.graders.map(f=>({graderId:f.id,graderVersion:f.version,score:a??0,passed:o,hardGate:f.hardGate,rewardEligible:r.rewardEligible&&f.rewardEligible,feedback:i,evidenceRefs:e.attempt.artifactRefs,judge:f.kind==="model_judge"?f.judge:null,calibrationStatus:f.kind==="model_judge"?f.calibrationStatus:"not_applicable"}));return{schemaVersion:"openpond.gradeResult.v1",id:`grade_${k([e.attempt.id,s,r]).slice(0,24)}`,attemptId:e.attempt.id,graderSetHash:s,score:a,passed:o,components:u,failureClass:n,feedback:[i],rewardEligible:r.rewardEligible,createdAt:e.now?.()??new Date().toISOString()}}d(to,"gradeTasksetEvaluationAttempt");function Ta(e){let t=k(e.graders),r=(e.error instanceof Error?e.error.message:String(e.error)).slice(0,19e3),s=`Taskset grader failed: ${r}`;return{schemaVersion:"openpond.gradeResult.v1",id:`grade_${k([e.attempt.id,t,"grader_failure",r]).slice(0,24)}`,attemptId:e.attempt.id,graderSetHash:t,score:null,passed:!1,components:e.graders.map(a=>({graderId:a.id,graderVersion:a.version,score:0,passed:!1,hardGate:a.hardGate,rewardEligible:!1,feedback:s,evidenceRefs:e.attempt.artifactRefs,judge:a.kind==="model_judge"?a.judge:null,calibrationStatus:a.kind==="model_judge"?a.calibrationStatus:"not_applicable"})),failureClass:"grader_failure",feedback:[s],rewardEligible:!1,createdAt:e.now?.()??new Date().toISOString()}}d(Ta,"graderFailureResult");function Sa(e){if(e.metadata.execution!=="taskset_work"||!e.infrastructureError)return null;let t=Zr.safeParse(e.metadata.failureClass);if(!t.success||t.data==="policy_failure"||t.data==="grader_failure")throw new Error("Taskset Work attempt is missing a trusted execution failure class.");return{failureClass:t.data,message:e.infrastructureError}}d(Sa,"tasksetWorkFailure");function ba(e){if(e.execution!=="post_training_evaluation_tool_loop")return null;let t=e.verifierOutcome,r=e.verifierReward,s=e.verifierRewardEligible;if(typeof t!="string"||!va.has(t)||typeof s!="boolean"||r!==null&&typeof r!="number")throw new Error("Cross-System evaluation attempt is missing trusted verifier metadata.");if(s!==(t==="correct"||t==="incorrect"||t==="parse_failure")||s&&typeof r!="number"||!s&&r!==null)throw new Error("Cross-System evaluation verifier metadata is internally inconsistent.");return{outcome:t,reward:r,rewardEligible:s}}d(ba,"crossSystemGrade");function Ra(e){return e==="correct"?null:e==="infrastructure_failure"?"infrastructure_failure":e==="cancelled"?"cancelled":"policy_failure"}d(Ra,"failureClassFor");import Xe from"node:path";import{mkdir as ro,readFile as _a,writeFile as so}from"node:fs/promises";async function te(e){let t=Xe.join(e.storeDir,"training","evaluation-artifacts",e.tasksetId),r=Xe.join(t,`${e.attemptId}-${oo(e.fileLabel??e.kind)}.json`),s=Buffer.from(`${JSON.stringify({schemaVersion:"openpond.rawEvaluationArtifact.v1",requestId:e.requestId,...e.payload},null,2)}
4
4
  `,"utf8");return await ro(t,{recursive:!0}),await so(r,s,{mode:384}),Xt({...e,file:r,bytes:s,mediaType:"application/json"})}d(te,"persistJsonTaskAttemptArtifact");async function Zc(e){let t=e.extension.replace(/^\.+/,"");if(!/^[a-z0-9]{1,12}$/i.test(t))throw new Error("Task Attempt artifact extension is invalid.");let r=Xe.join(e.storeDir,"training","evaluation-artifacts",e.tasksetId);await ro(r,{recursive:!0});let s=Xe.join(r,`${e.attemptId}-${oo(e.fileLabel)}.${t}`);return await so(s,e.bytes,{mode:384}),Xt({...e,file:s})}d(Zc,"persistBinaryTaskAttemptArtifact");function oo(e){let t=e.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!t)throw new Error("Evaluation artifact file label is empty.");return t}d(oo,"safeFileLabel");async function ao(e){let t=await _a(e.path),r=se(t);if(t.byteLength!==e.expectedSizeBytes||r!==e.expectedSha256)throw new Error(`Saved Work output ${Xe.basename(e.path)} no longer matches its OutputRef.`);return Xt({...e,file:e.path,bytes:t,kind:"output_artifact",metadata:{...e.metadata,source:"openpond-work",outputValidated:!0}})}d(ao,"persistTaskAttemptOutputArtifact");async function Xt(e){let t=se(e.bytes),r=Qr.parse({schemaVersion:"openpond.taskAttemptArtifact.v1",id:`attempt_artifact_${k([e.attemptId,e.kind,e.file,t]).slice(0,24)}`,tasksetId:e.tasksetId,taskId:e.taskId,attemptId:e.attemptId,kind:e.kind,path:e.file,mediaType:e.mediaType,sha256:t,sizeBytes:e.bytes.byteLength,createdAt:e.timestamp(),metadata:{requestId:e.requestId,localOnly:!0,containsPrivilegedOutcome:!1,...e.metadata}});return e.store.saveTaskAttemptArtifact(r)}d(Xt,"saveArtifact");function Zt(e){let t=new Set(e.approvedTrajectoryIds),r=new Map(e.tasks.map(a=>[a.id,a])),s=new Map(e.results.map(a=>[a.trajectoryId,a]));return e.trajectories.flatMap(a=>{let o=s.get(a.id),n=r.get(a.taskId);return!t.has(a.id)||!n||o?.outcome!=="correct"||!o.rewardEligible?[]:[us.parse({schemaVersion:V,id:`cso_bootstrap_${a.id}`,taskId:n.id,worldId:a.worldId,trajectoryId:a.id,toolContractHash:q,approval:{status:"approved",approvedBy:e.approvedBy,approvedAt:e.approvedAt},messages:xa(n,a)})]})}d(Zt,"buildCrossSystemBootstrapDataset");function xa(e,t){let r=[{role:"system",content:cs},{role:"user",content:e.prompt}];for(let s of t.steps)s.kind==="model"&&s.content.trim()&&r.push({role:"assistant",content:s.content}),s.kind==="tool_call"&&r.push({role:"assistant",content:null,tool_calls:[{id:s.callId,type:"function",function:{name:s.name,arguments:JSON.stringify(s.arguments)}}]}),s.kind==="tool_result"&&r.push({role:"tool",tool_call_id:s.callId,content:JSON.stringify({ok:s.ok,result:s.result,error:s.error})}),s.kind==="final"&&r.push({role:"assistant",content:s.content});return r}d(xa,"trajectoryMessages");import _n from"node:path";import{mkdir as Ia,mkdtemp as Ea,rm as Ca}from"node:fs/promises";import Aa from"node:path";async function no(e,t,r){await Ia(e,{recursive:!0});let s=await Ea(Aa.join(e,".authoring-"));try{return await ut(t,s,{generatedFiles:r}),await Qt(e,t,s)}finally{await Ca(s,{recursive:!0,force:!0})}}d(no,"materializeGeneratedTasksetPackage");async function Qt(e,t,r){let s=await Kr(r),a=await Ss(t,r),o=`authored-${k(a.taskset)}`,n=we.parse({...a.taskset,environment:{...a.taskset.environment,metadata:{...a.taskset.environment.metadata,runtimeSourceTasksetId:o}}}),i=we.parse({...n,contentHash:Re(n)});return await ys(e,{taskset:i,generatedFiles:a.generatedFiles},o,{source:{directory:r,packageHash:s},verify:d(u=>yt(u,i),"verify")}),i}d(Qt,"materializeTasksetRevisionFromSource");import{Buffer as tr}from"node:buffer";import{spawn as Ma}from"node:child_process";var io=String.raw`
5
5
  import contextlib, io, json, math, statistics, decimal, datetime, collections, itertools, functools, sys
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{ja as h}from"./chunk-HG2YFMVU.js";import{m as f}from"./chunk-RCT3O3HQ.js";import{A as e}from"./chunk-X2J2P5ZT.js";import{a as m}from"./chunk-FTQLQJQV.js";var g=e.object({schemaVersion:e.literal("openpond.profileWorkCompletion.v1"),sessionId:e.string().min(1),turnId:e.string().min(1),responsePath:e.string().min(1),responseSha256:e.string().regex(/^[a-f0-9]{64}$/),responseBytes:e.number().int().min(1).max(1048576),responseChunks:e.array(e.string().max(65536)).min(1).max(32),outputs:e.array(e.object({id:e.string(),revision:e.number().int(),sha256:e.string(),sizeBytes:e.number().int(),contentType:e.string(),sourceTaskId:e.string(),sourceTurnId:e.string(),title:e.string()}).strict()).min(1).max(100)}).strict();function W(s){let u=new TextDecoder("utf-8",{fatal:!0}).decode(s.response),i=[];for(let r=0;r<u.length;r+=65536)i.push(u.slice(r,r+65536));return g.parse({schemaVersion:"openpond.profileWorkCompletion.v1",sessionId:s.sessionId,turnId:s.turnId,responsePath:s.responsePath,responseSha256:f(s.response),responseBytes:s.response.length,responseChunks:i,outputs:s.outputs.map(({id:r,revision:t,sha256:a,sizeBytes:p,contentType:c,sourceTaskId:o,sourceTurnId:d,title:n})=>({id:r,revision:t,sha256:a,sizeBytes:p,contentType:c,sourceTaskId:o,sourceTurnId:d,title:n}))})}m(W,"createProfileWorkCompletion");function _(s){let u=s.filter(o=>o.name==="tool.completed"&&o.action==="work_finish"&&o.status==="completed");if(!u.length)return null;if(u.length!==1)throw new Error("The case has multiple Work completion receipts.");let i=u[0],r=i.data,t=g.parse(r?.result);if(t.sessionId!==i.sessionId||t.turnId!==i.turnId)throw new Error("Work completion belongs to another case or turn.");let a=t.responseChunks.join(""),p=Buffer.from(a,"utf8");if(p.length!==t.responseBytes||f(p)!==t.responseSha256)throw new Error("Work completion response differs from its sealed content.");if(new Set(t.outputs.map(o=>`${o.id}/${o.revision}`)).size!==t.outputs.length)throw new Error("Work completion repeats a saved output.");let c=s.slice(0,s.indexOf(i));for(let o of t.outputs){if(o.sourceTaskId!==t.sessionId||o.sourceTurnId!==t.turnId)throw new Error("Work completion output belongs to another case or turn.");if(c.filter(n=>n.name==="workspace_action_result"&&n.action==="work_output_save"&&n.status==="completed"&&n.sessionId===t.sessionId&&n.turnId===t.turnId).flatMap(n=>{let l=h.safeParse(n.data?.outputRef);return l.success&&Object.entries(o).every(([k,I])=>l.data[k]===I)?[l.data]:[]}).length!==1)throw new Error("Work completion lacks an exact prior saved-output receipt.")}return a}m(_,"completedProfileWorkResponse");export{W as a,_ as b};
2
+ import{ja as h}from"./chunk-2THZ6GZY.js";import{m as f}from"./chunk-RCT3O3HQ.js";import{A as e}from"./chunk-X2J2P5ZT.js";import{a as m}from"./chunk-FTQLQJQV.js";var g=e.object({schemaVersion:e.literal("openpond.profileWorkCompletion.v1"),sessionId:e.string().min(1),turnId:e.string().min(1),responsePath:e.string().min(1),responseSha256:e.string().regex(/^[a-f0-9]{64}$/),responseBytes:e.number().int().min(1).max(1048576),responseChunks:e.array(e.string().max(65536)).min(1).max(32),outputs:e.array(e.object({id:e.string(),revision:e.number().int(),sha256:e.string(),sizeBytes:e.number().int(),contentType:e.string(),sourceTaskId:e.string(),sourceTurnId:e.string(),title:e.string()}).strict()).min(1).max(100)}).strict();function W(s){let u=new TextDecoder("utf-8",{fatal:!0}).decode(s.response),i=[];for(let r=0;r<u.length;r+=65536)i.push(u.slice(r,r+65536));return g.parse({schemaVersion:"openpond.profileWorkCompletion.v1",sessionId:s.sessionId,turnId:s.turnId,responsePath:s.responsePath,responseSha256:f(s.response),responseBytes:s.response.length,responseChunks:i,outputs:s.outputs.map(({id:r,revision:t,sha256:a,sizeBytes:p,contentType:c,sourceTaskId:o,sourceTurnId:d,title:n})=>({id:r,revision:t,sha256:a,sizeBytes:p,contentType:c,sourceTaskId:o,sourceTurnId:d,title:n}))})}m(W,"createProfileWorkCompletion");function _(s){let u=s.filter(o=>o.name==="tool.completed"&&o.action==="work_finish"&&o.status==="completed");if(!u.length)return null;if(u.length!==1)throw new Error("The case has multiple Work completion receipts.");let i=u[0],r=i.data,t=g.parse(r?.result);if(t.sessionId!==i.sessionId||t.turnId!==i.turnId)throw new Error("Work completion belongs to another case or turn.");let a=t.responseChunks.join(""),p=Buffer.from(a,"utf8");if(p.length!==t.responseBytes||f(p)!==t.responseSha256)throw new Error("Work completion response differs from its sealed content.");if(new Set(t.outputs.map(o=>`${o.id}/${o.revision}`)).size!==t.outputs.length)throw new Error("Work completion repeats a saved output.");let c=s.slice(0,s.indexOf(i));for(let o of t.outputs){if(o.sourceTaskId!==t.sessionId||o.sourceTurnId!==t.turnId)throw new Error("Work completion output belongs to another case or turn.");if(c.filter(n=>n.name==="workspace_action_result"&&n.action==="work_output_save"&&n.status==="completed"&&n.sessionId===t.sessionId&&n.turnId===t.turnId).flatMap(n=>{let l=h.safeParse(n.data?.outputRef);return l.success&&Object.entries(o).every(([k,I])=>l.data[k]===I)?[l.data]:[]}).length!==1)throw new Error("Work completion lacks an exact prior saved-output receipt.")}return a}m(_,"completedProfileWorkResponse");export{W as a,_ as b};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{t as _,w as C}from"./chunk-WGQ3FMRF.js";import{f as R,m}from"./chunk-HIQPGYVH.js";import{Sa as A}from"./chunk-ZY32SZ2P.js";import{A as e}from"./chunk-X2J2P5ZT.js";import{a as l}from"./chunk-FTQLQJQV.js";var u=e.string().trim().min(1).max(200),P=e.object({operationId:u,execution:R,executionKind:e.literal("recorded_evidence").optional(),graders:e.array(A).min(1).max(100),maximumCostUsd:e.number().finite().min(1e-6).max(1e4),mappings:e.array(e.object({graderId:u,fields:_}).strict()).max(100).optional()}).strict().superRefine((a,n)=>{new Set(a.graders.map(o=>o.id)).size!==a.graders.length&&n.addIssue({code:"custom",path:["graders"],message:"Select each grader once."}),a.mappings&&(new Set(a.mappings.map(o=>o.graderId)).size!==a.mappings.length||a.mappings.some(o=>!a.graders.some(c=>c.id===o.graderId)))&&n.addIssue({code:"custom",path:["mappings"],message:"Map each selected grader at most once."})}),q=e.object({schemaVersion:e.literal("openpond.experimentScoringPass.v1"),id:u,teamId:u,revision:e.number().int().positive(),request:P,graders:e.array(C).min(1).max(100),status:e.enum(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:e.number().int().min(1).max(1e4),counts:e.object({pending:e.number().int().nonnegative(),running:e.number().int().nonnegative(),scored:e.number().int().nonnegative(),unavailable:e.number().int().nonnegative(),failed:e.number().int().nonnegative(),cancelled:e.number().int().nonnegative()}).strict(),resultAvailable:e.boolean(),createdAt:e.iso.datetime(),startedAt:e.iso.datetime().nullable(),completedAt:e.iso.datetime().nullable(),error:e.object({code:u,message:e.string().max(2e3)}).strict().nullable()}).strict(),L=q.extend({contentHash:e.string().regex(/^[a-f0-9]{64}$/)});function O(a){let n=L.parse(a),{contentHash:o,...c}=n;if(m(c)!==o||Object.values(n.counts).reduce((r,d)=>r+d,0)!==n.totalCount)throw new Error("Scoring pass integrity or population accounting failed.");let t=["completed","failed","cancelled"].includes(n.status);if(t&&(!n.completedAt||n.counts.pending||n.counts.running)||!t&&(n.completedAt!==null||n.resultAvailable)||n.status==="completed"&&!n.resultAvailable)throw new Error("Scoring pass lifecycle differs from its retained result.");if(n.graders.length!==n.request.graders.length||new Set(n.graders.map(r=>r.feedbackKey)).size!==n.graders.length||n.graders.some((r,d)=>m(r.release)!==m(n.request.graders[d])||m(r.mappings??[])!==m(n.request.mappings?.find(f=>f.graderId===r.release?.id)?.fields??[])))throw new Error("Scoring pass graders differ from their exact admission.");return n}l(O,"verifyExperimentScoringPass");var I=8388608;async function B(a,n,o,c){let t=new AbortController,r=o.signal,d=l(()=>t.abort(r?.reason),"forward");r?.aborted?d():r?.addEventListener("abort",d,{once:!0});let f=setTimeout(()=>t.abort(new Error("Connected evidence request timed out.")),6e4),s,h=l(()=>{s&&s.cancel(t.signal.reason).catch(()=>{})},"abortReader");t.signal.addEventListener("abort",h,{once:!0});let v=new Promise((w,g)=>{let p=l(()=>g(t.signal.reason??new DOMException("Request aborted","AbortError")),"abort");t.signal.aborted?p():t.signal.addEventListener("abort",p,{once:!0})});try{let w=a(n,{...o,signal:t.signal}).then(i=>{if(t.signal.aborted)throw i.body?.cancel(t.signal.reason).catch(()=>{}),t.signal.reason;return i}),g=await Promise.race([w,v]),p=g.headers.get("content-length");if(s=g.body?.getReader(),t.signal.aborted)throw await s?.cancel(t.signal.reason),t.signal.reason;if(p&&Number(p)>I)throw await s?.cancel(),c(502,"connected_response_too_large","Connected evidence response exceeds 8 MiB.");let x=[],b=0;if(s)for(;;){let i=await Promise.race([s.read(),v]);if(i.done)break;if(b+=i.value.byteLength,b>I)throw await s.cancel(),c(502,"connected_response_too_large","Connected evidence response exceeds 8 MiB.");x.push(i.value)}let S=new Uint8Array(b),E=0;for(let i of x)S.set(i,E),E+=i.byteLength;let y;try{y=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(S))}catch{throw c(502,"connected_response_invalid","Connected evidence response is not valid JSON.")}return{response:g,value:y}}finally{clearTimeout(f),r?.removeEventListener("abort",d),t.signal.removeEventListener("abort",h),s?.releaseLock()}}l(B,"fetchConnectedJson");export{P as a,O as b,B as c};
2
+ import{t as _,w as C}from"./chunk-XKDOPNQ5.js";import{f as R,m}from"./chunk-HIQPGYVH.js";import{Sa as A}from"./chunk-ZY32SZ2P.js";import{A as e}from"./chunk-X2J2P5ZT.js";import{a as l}from"./chunk-FTQLQJQV.js";var u=e.string().trim().min(1).max(200),P=e.object({operationId:u,execution:R,executionKind:e.literal("recorded_evidence").optional(),graders:e.array(A).min(1).max(100),maximumCostUsd:e.number().finite().min(1e-6).max(1e4),mappings:e.array(e.object({graderId:u,fields:_}).strict()).max(100).optional()}).strict().superRefine((a,n)=>{new Set(a.graders.map(o=>o.id)).size!==a.graders.length&&n.addIssue({code:"custom",path:["graders"],message:"Select each grader once."}),a.mappings&&(new Set(a.mappings.map(o=>o.graderId)).size!==a.mappings.length||a.mappings.some(o=>!a.graders.some(c=>c.id===o.graderId)))&&n.addIssue({code:"custom",path:["mappings"],message:"Map each selected grader at most once."})}),q=e.object({schemaVersion:e.literal("openpond.experimentScoringPass.v1"),id:u,teamId:u,revision:e.number().int().positive(),request:P,graders:e.array(C).min(1).max(100),status:e.enum(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:e.number().int().min(1).max(1e4),counts:e.object({pending:e.number().int().nonnegative(),running:e.number().int().nonnegative(),scored:e.number().int().nonnegative(),unavailable:e.number().int().nonnegative(),failed:e.number().int().nonnegative(),cancelled:e.number().int().nonnegative()}).strict(),resultAvailable:e.boolean(),createdAt:e.iso.datetime(),startedAt:e.iso.datetime().nullable(),completedAt:e.iso.datetime().nullable(),error:e.object({code:u,message:e.string().max(2e3)}).strict().nullable()}).strict(),L=q.extend({contentHash:e.string().regex(/^[a-f0-9]{64}$/)});function O(a){let n=L.parse(a),{contentHash:o,...c}=n;if(m(c)!==o||Object.values(n.counts).reduce((r,d)=>r+d,0)!==n.totalCount)throw new Error("Scoring pass integrity or population accounting failed.");let t=["completed","failed","cancelled"].includes(n.status);if(t&&(!n.completedAt||n.counts.pending||n.counts.running)||!t&&(n.completedAt!==null||n.resultAvailable)||n.status==="completed"&&!n.resultAvailable)throw new Error("Scoring pass lifecycle differs from its retained result.");if(n.graders.length!==n.request.graders.length||new Set(n.graders.map(r=>r.feedbackKey)).size!==n.graders.length||n.graders.some((r,d)=>m(r.release)!==m(n.request.graders[d])||m(r.mappings??[])!==m(n.request.mappings?.find(f=>f.graderId===r.release?.id)?.fields??[])))throw new Error("Scoring pass graders differ from their exact admission.");return n}l(O,"verifyExperimentScoringPass");var I=8388608;async function B(a,n,o,c){let t=new AbortController,r=o.signal,d=l(()=>t.abort(r?.reason),"forward");r?.aborted?d():r?.addEventListener("abort",d,{once:!0});let f=setTimeout(()=>t.abort(new Error("Connected evidence request timed out.")),6e4),s,h=l(()=>{s&&s.cancel(t.signal.reason).catch(()=>{})},"abortReader");t.signal.addEventListener("abort",h,{once:!0});let v=new Promise((w,g)=>{let p=l(()=>g(t.signal.reason??new DOMException("Request aborted","AbortError")),"abort");t.signal.aborted?p():t.signal.addEventListener("abort",p,{once:!0})});try{let w=a(n,{...o,signal:t.signal}).then(i=>{if(t.signal.aborted)throw i.body?.cancel(t.signal.reason).catch(()=>{}),t.signal.reason;return i}),g=await Promise.race([w,v]),p=g.headers.get("content-length");if(s=g.body?.getReader(),t.signal.aborted)throw await s?.cancel(t.signal.reason),t.signal.reason;if(p&&Number(p)>I)throw await s?.cancel(),c(502,"connected_response_too_large","Connected evidence response exceeds 8 MiB.");let x=[],b=0;if(s)for(;;){let i=await Promise.race([s.read(),v]);if(i.done)break;if(b+=i.value.byteLength,b>I)throw await s.cancel(),c(502,"connected_response_too_large","Connected evidence response exceeds 8 MiB.");x.push(i.value)}let S=new Uint8Array(b),E=0;for(let i of x)S.set(i,E),E+=i.byteLength;let y;try{y=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(S))}catch{throw c(502,"connected_response_invalid","Connected evidence response is not valid JSON.")}return{response:g,value:y}}finally{clearTimeout(f),r?.removeEventListener("abort",d),t.signal.removeEventListener("abort",h),s?.releaseLock()}}l(B,"fetchConnectedJson");export{P as a,O as b,B as c};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as Ae}from"./chunk-GW766ZSO.js";import{B as O,a as Ce,b as Pe}from"./chunk-OFJPOTES.js";import{b as be}from"./chunk-YU3C6U5V.js";import{d as H}from"./chunk-U7D6Q744.js";import{a as re,b as ye,j as A}from"./chunk-6ESBAHWK.js";import{f as Ie}from"./chunk-JT5YQ52I.js";import{D as we}from"./chunk-2MEOUS24.js";import{n as $}from"./chunk-RCT3O3HQ.js";import{a as o}from"./chunk-FTQLQJQV.js";import{existsSync as z}from"node:fs";import{cp as xe,mkdir as Ee,readFile as Oe}from"node:fs/promises";import k from"node:path";import{existsSync as L}from"node:fs";import{readFile as K}from"node:fs/promises";import q from"node:path";async function F(e){await V(e.target);let t={},a=new Set([`${e.target.sourceRootRelativePath}/.openpond/agent-inspect.json`,`${e.target.sourceRootRelativePath}/.openpond/action-registry.json`,`${e.target.sourceRootRelativePath}/.openpond/eval-results.json`]),n=[{name:"inspect",command:"inspect",args:["--json"]},{name:"build",command:"build"},{name:"validate",command:"validate",args:["--json"]},{name:"eval",command:"eval",args:["--json"]},{name:"direct-run",command:"run",args:[e.target.defaultAction,"--json","--input",JSON.stringify({prompt:e.snapshot.objective,channel:"openpond_chat"})]}];for(let r of n){let s=await O({cwd:e.target.sourceRoot,command:r.command,args:r.args,...r.command==="eval"&&e.requireEvalPass===!1?{throwOnFailure:!1}:{}});if(s.code!==0&&!(r.command==="eval"&&e.requireEvalPass===!1))throw new Error(s.stderr.trim()||s.stdout.trim()||`${r.command} failed with exit code ${s.code??"unknown"}`);let i=lt(s.stdout),d=mt(i);d&&a.add(q.join(e.target.sourceRootRelativePath,d)),t[r.name]={summary:pt(r.name,i),traceArtifactRef:d,stdout:s.stdout.trim().slice(0,4e3),stderr:s.stderr.trim().slice(0,4e3)}}return await dt(e.target,e.requireEvalPass!==!1),{checkRefs:[...a],metadata:t}}o(F,"runLocalCreatePipelineChecks");async function V(e){if(!L(e.sourceRoot))throw new Error(`Codex did not create the expected agent source root: ${e.sourceRoot}`);let t=q.join(e.sourceRoot,"agent","agent.ts");if(!L(t))throw new Error(`Codex did not create the expected SDK agent source: ${t}`);let a=q.join(e.repoPath,"openpond-profile.json");if(!L(a))throw new Error(`Codex did not update the profile repo manifest: ${a}`);let n=q.join(e.sourcePath,"settings","profile.yaml");if(!L(n))throw new Error(`Codex did not update the profile manifest: ${n}`);let s=JSON.parse(await K(a,"utf8")).profiles?.[e.activeProfile];if(!s)throw new Error(`openpond-profile.json does not register profile ${e.activeProfile}.`);if(!s.enabledAgents?.includes(e.agentId))throw new Error(`openpond-profile.json does not enable generated agent ${e.agentId}.`);let i=await K(n,"utf8");if(!i.includes(`id: ${e.agentId}`)&&!i.includes(`id: "${e.agentId}"`))throw new Error(`settings/profile.yaml does not register generated agent ${e.agentId}.`);let d=e.agentId==="default"?["agent/agent.ts","agent"]:[`agents/${e.agentId}`];if(!d.some(u=>i.includes(u)))throw new Error(`settings/profile.yaml does not point ${e.agentId} at ${d[0]}.`)}o(V,"assertLocalCreateSourceLayout");async function dt(e,t=!0){let a=q.join(e.sourceRoot,".openpond","action-registry.json"),n=q.join(e.sourceRoot,".openpond","eval-results.json");if(!L(a))throw new Error(`Generated source did not produce an action registry: ${a}`);if(!L(n))throw new Error(`Generated source did not produce eval results: ${n}`);let r=JSON.parse(await K(a,"utf8")),s=Array.isArray(r.actions)?r.actions:[];if(!new Set(s.map(c=>typeof c.id=="string"?c.id:null).filter(c=>!!c)).has(e.defaultAction))throw new Error(`Generated action registry does not expose default action ${e.defaultAction}.`);let d=s.filter(c=>typeof c.id=="string"&&(!W(c.label)||!W(c.description)||typeof c.timeoutSeconds!="number"));if(d.length>0)throw new Error(`Generated action registry has actions missing labels, descriptions, or timeout policies: ${d.map(c=>c.id).join(", ")}`);let u=Ce({actionCatalog:s.filter(c=>typeof c.id=="string").map(c=>({id:c.id,name:W(c.name),setupRequirements:ut(c.setupRequirements)??[]})),actionId:e.defaultAction});if(u.blockingRequirements.length>0)throw new Error(`Generated default action ${e.defaultAction} has unresolved required setup and cannot be ready_local: ${u.blockingRequirements.map(Pe).join("; ")}. Mark built-in/local fixture requirements ready or optional when they are satisfied, or leave the pipeline blocked until the setup is configured.`);let m=JSON.parse(await K(n,"utf8"));if(typeof m.summary?.total!="number"||m.summary.total<1)throw new Error("Generated source must define at least one deterministic SDK eval.");if(t&&m.summary.failed!==0)throw new Error("Generated source evals did not all pass.")}o(dt,"assertGeneratedSdkArtifacts");function lt(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;try{return JSON.parse(t)}catch{return null}}o(lt,"parseJsonOutput");function E(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}o(E,"asRecord");function ut(e){return Array.isArray(e)?e.filter(t=>!!E(t)):null}o(ut,"recordArray");function mt(e){let t=E(e),a=W(t?.traceArtifactRef);return a?.startsWith(".openpond/")?a:null}o(mt,"traceRefFromCommandResult");function pt(e,t){let a=E(t);return a?e==="inspect"?{actionCount:Array.isArray(a.actionCatalog)?a.actionCatalog.length:null,defaultAction:E(a.agent)?.defaultAction??null,projectName:E(a.project)?.name??null}:e==="validate"?{status:a.status??null,errors:E(a.summary)?.errors??null,warnings:E(a.summary)?.warnings??null}:e==="eval"?E(a.summary):e==="direct-run"?{hasResult:!!E(a.result),resultKeys:Object.keys(E(a.result)??{})}:null:null}o(pt,"summaryFromCommandResult");function W(e){return typeof e=="string"&&e.trim()?e.trim():null}o(W,"stringValue");var gt="Approved local Create plans require model-backed SDK source application; no source mutation was performed.",ft=1800*1e3,Te=".openpond-harness-source-application.json",ht=300*1e3,vt=2*1e3,Rt=5*1e3;async function He(e,t={}){if(!kt(e))return e;let a=t.now??(()=>new Date().toISOString()),n=e.adapter;if(n.kind!=="local")return e;if(!t.session||!t.turn||!t.ensureCodexRuntime||!t.appendRuntimeEvent||!t.setProviderTurnId)return Y(e,{now:a(),reason:gt,metadata:{reason:"model_backed_source_application_required",sourcePath:n.sourcePath??null,repoPath:n.repoPath??null,activeProfile:n.activeProfile??null,operation:e.operation,requestedAgentId:e.target.kind==="agent"?e.target.id:null}});let r;try{r=se(e)}catch(i){return Y(e,{now:a(),reason:i instanceof Error?i.message:String(i),metadata:{reason:"local_create_target_unresolved"}})}try{await ie({snapshot:e,session:t.session,turn:t.turn,target:r,ensureCodexRuntime:t.ensureCodexRuntime,appendRuntimeEvent:t.appendRuntimeEvent,setProviderTurnId:t.setProviderTurnId,model:t.model??we,codexReasoningEffort:t.codexReasoningEffort})}catch(i){return Y(e,{now:a(),reason:i instanceof Error?i.message:String(i),metadata:{reason:"model_backed_source_application_failed",target:r}})}let s=oe(e,{state:"running_checks",now:a(),blockedReason:null,sourceRefs:[r.sourceRootRelativePath,k.join(r.profileRelativePath,"settings","profile.yaml"),"openpond-profile.json"],metadata:{localCreatePipeline:{status:"running_checks",target:r}},candidates:[{id:Se(e.id),target:{kind:"agent",id:r.agentId,displayName:e.target.displayName,defaultActionKey:r.defaultAction},status:"checking",git:null,parentCandidateId:null,tasksetRef:e.tasksetRef,authoringModelRef:t.model??null,allowedPaths:e.plan?.sourcePlan.map(i=>i.path)??[],sourceRefs:[r.sourceRootRelativePath,k.join(r.profileRelativePath,"settings","profile.yaml"),"openpond-profile.json"],artifactRefs:[],checkRefs:[],evaluationReceiptRefs:[],createdAt:e.createdAt,updatedAt:a(),metadata:{sourceAuthority:e.adapter.sourceAuthority}}]});await t.onSnapshot?.(s);try{let i=await(t.runChecks??F)({snapshot:s,target:r}),d=a(),u=Se(e.id),m=`agent_eval_${e.id}`;return oe(s,{state:"ready_local",now:d,blockedReason:null,checkRefs:i.checkRefs,candidates:s.candidates.map(c=>c.id===u?{...c,status:"accepted",checkRefs:X(c.checkRefs,i.checkRefs),evaluationReceiptRefs:X(c.evaluationReceiptRefs,[m]),updatedAt:d}:c),evaluationReceipts:[...s.evaluationReceipts.filter(c=>c.id!==m),{id:m,candidateId:u,target:{kind:"agent",id:r.agentId,displayName:e.target.displayName,defaultActionKey:r.defaultAction},evaluatorKind:"agent_sdk",subject:"candidate",sourceCommit:e.adapter.kind==="local"?e.adapter.localHead:null,sourceBranch:null,tasksetId:e.tasksetRef?.id??null,tasksetHash:e.tasksetRef?.contentHash??null,taskAttemptRefs:i.checkRefs.filter(c=>c.includes("eval")),status:"passed",publishGate:"passed",summaryCounts:null,evalRefs:i.checkRefs.filter(c=>c.includes("eval")),artifactRefs:i.checkRefs,summary:wt(i.metadata),createdAt:d,metadata:i.metadata??{}}],metadata:{localCreatePipeline:{status:"ready_local",target:r,checks:i.metadata??{}}}})}catch(i){return Y(s,{now:a(),reason:i instanceof Error?i.message:String(i),metadata:{reason:"local_create_checks_failed",target:r}})}}o(He,"applyApprovedLocalCreateImproveRun");function kt(e){return e.state==="applying_source"&&e.plan?.status==="approved"&&e.adapter.kind==="local"&&e.target.kind==="agent"}o(kt,"shouldApplyLocalCreatePipeline");function oe(e,t){return A(e,{state:t.state,blockedReason:t.blockedReason===void 0?e.blockedReason:t.blockedReason,checkRefs:X(e.checkRefs,t.checkRefs??[]),sourceRefs:X(e.sourceRefs,t.sourceRefs??[]),candidates:t.candidates??e.candidates,evaluationReceipts:t.evaluationReceipts??e.evaluationReceipts,metadata:{...e.metadata,...t.metadata??{}},updatedAt:t.now})}o(oe,"transitionCreatePipeline");function Y(e,t){return oe(e,{state:"blocked",now:t.now,blockedReason:t.reason,metadata:{localCreatePipeline:{status:"blocked",...t.metadata}}})}o(Y,"blockLocalCreatePipeline");function X(e,t){return Array.from(new Set([...e,...t].filter(Boolean)))}o(X,"mergeRefs");function Se(e){return`agent_candidate_${e}`}o(Se,"agentCandidateId");function wt(e){let t=M(e?.eval),a=typeof t?.total=="number"?t.total:null;return a===null?"Agent SDK checks and deterministic Evals passed.":`${a} Agent SDK Eval${a===1?"":"s"} passed.`}o(wt,"checkSummary");function se(e){let t=e.adapter;if(t.kind!=="local")throw new Error("Create/Improve target must use the local adapter.");if(e.target.kind!=="agent")throw new Error("Local agent source application requires an Agent target.");let a=t.sourcePath?.trim(),n=t.repoPath?.trim();if(!a)throw new Error("Local Create approval is missing a profile source path.");if(!n)throw new Error("Local Create approval is missing a profile repo path.");let r=t.activeProfile?.trim()||"default",s=k.resolve(a),i=k.resolve(n),d=qe(e.target.id)??xt(e)??St(e.objective),u=Tt(Et(e.plan?.defaultChatAction.key)??"chat",d),m=e.operation==="improve"&&d==="default"?s:k.join(s,"agents",d);return{activeProfile:r,agentId:d,defaultAction:u,repoPath:i,sourcePath:s,workspaceRoot:i,profileRelativePath:je(k.relative(i,s)),sourceRoot:m,sourceRootRelativePath:je(k.relative(i,m))}}o(se,"resolveLocalCreatePipelineTarget");async function ie(e){if(!z(e.target.workspaceRoot))throw new Error(`Profile repo path does not exist: ${e.target.workspaceRoot}`);if(!z(e.target.sourcePath))throw new Error(`Profile source path does not exist: ${e.target.sourcePath}`);if(await Ct(e.snapshot,e.target)){await e.appendRuntimeEvent(H({sessionId:e.session.id,turnId:e.turn.id,name:"create_improve.updated",source:"server",appId:e.session.appId,status:"completed",output:`Applied prepared harness ${e.snapshot.operation==="improve"?"Improve":"Create"} source for ${e.target.agentId}; running local checks.`,data:{phase:"prepared_source_apply_completed",runId:e.snapshot.id,target:e.target}}));return}await e.appendRuntimeEvent(H({sessionId:e.session.id,turnId:e.turn.id,name:"create_improve.updated",source:"server",appId:e.session.appId,status:"started",output:`Applying approved ${e.snapshot.operation==="improve"?"Improve":"Create"} plan with Codex in ${e.target.sourceRootRelativePath}.`,data:{phase:"source_apply_started",runId:e.snapshot.id,target:e.target}}));let t={...e.session,provider:"codex",cwd:e.target.workspaceRoot,workspaceKind:"local_project",workspaceId:e.session.workspaceId??`openpond-profile:${e.target.activeProfile}`,workspaceName:e.session.workspaceName??`OpenPond profile ${e.target.activeProfile}`},a=e.session.provider==="codex"?e.model:null,n=await e.ensureCodexRuntime(t,{approvalPolicy:"never",sandbox:"workspace-write",model:a,codexPermissionMode:"auto-review",codexReasoningEffort:e.codexReasoningEffort}),r=await n.client.startTurn({threadId:n.threadId,prompt:At(e.snapshot,e.target),cwd:e.target.workspaceRoot,model:a,approvalPolicy:"never",sandbox:"workspace-write"});await e.setProviderTurnId(r.turnId);try{await n.client.waitForTurn(r.turnId,ft)}catch(s){if(!$e(s,r.turnId)&&!It(s))throw s;let i=$e(s,r.turnId)?"timed out":"exited cleanly before returning a turn completion";if(await e.appendRuntimeEvent(H({sessionId:e.session.id,turnId:e.turn.id,name:"create_improve.updated",source:"server",appId:e.session.appId,status:"started",output:`Codex source application ${i}; checking for completed generated source before blocking.`,data:{phase:"source_apply_recovery_started",runId:e.snapshot.id,providerTurnId:r.turnId,reason:i,target:e.target}})),!await yt(e.target))throw s;await e.appendRuntimeEvent(H({sessionId:e.session.id,turnId:e.turn.id,name:"create_improve.updated",source:"server",appId:e.session.appId,status:"completed",output:`Recovered completed ${e.snapshot.operation==="improve"?"Improve":"Create"} source after Codex source application ${i} for ${e.target.agentId}; running local checks.`,data:{phase:"source_apply_recovered",runId:e.snapshot.id,providerTurnId:r.turnId,reason:i,target:e.target}}))}await e.appendRuntimeEvent(H({sessionId:e.session.id,turnId:e.turn.id,name:"create_improve.updated",source:"provider",appId:e.session.appId,status:"completed",output:`Codex completed approved ${e.snapshot.operation==="improve"?"Improve":"Create"} source application for ${e.target.agentId}.`,data:{phase:"source_apply_completed",runId:e.snapshot.id,providerTurnId:r.turnId,target:e.target}}))}o(ie,"runModelBackedLocalCreateSourceApplication");async function Ct(e,t,a=process.env){if(!Ae(a))return!1;let n=k.join(t.workspaceRoot,Te);if(!z(n))return!1;let r=JSON.parse(await Oe(n,"utf8")),s=M(r);if(s?.schema!=="openpond.harnessPreparedSource.v1")throw new Error(`${Te} must use schema openpond.harnessPreparedSource.v1.`);let i=M(s.agents),d=M(i?.[t.agentId]),u=Pt(d?.[e.operation]);if(!u)return!1;let m=ne(t.workspaceRoot,u.source,"source");if(!z(m))throw new Error(`Prepared harness source does not exist: ${u.source}`);await Ee(t.sourceRoot,{recursive:!0}),await xe(m,t.sourceRoot,{recursive:!0,force:!0});for(let c of u.registrations??[]){let g=ne(t.workspaceRoot,c.source,"registration source"),l=ne(t.workspaceRoot,c.target,"registration target");if(!z(g))throw new Error(`Prepared harness registration source does not exist: ${c.source}`);await Ee(k.dirname(l),{recursive:!0}),await xe(g,l,{force:!0})}return!0}o(Ct,"applyPreparedHarnessSourceApplication");function Pt(e){let t=M(e);if(!t||typeof t.source!="string"||!t.source.trim())return null;if(t.registrations!==void 0&&!Array.isArray(t.registrations))throw new Error("Prepared harness source registrations must be an array.");let a=(t.registrations??[]).map(n=>{let r=M(n);if(!r||typeof r.source!="string"||!r.source.trim()||typeof r.target!="string"||!r.target.trim())throw new Error("Prepared harness source registrations require source and target paths.");return{source:r.source,target:r.target}});return{source:t.source,registrations:a}}o(Pt,"asHarnessPreparedSourceOperation");function ne(e,t,a){if(k.isAbsolute(t))throw new Error(`Prepared harness ${a} must be relative to the profile repo.`);let n=k.resolve(e),r=k.resolve(n,t);if(r!==n&&!r.startsWith(`${n}${k.sep}`))throw new Error(`Prepared harness ${a} must stay inside the profile repo.`);return r}o(ne,"resolveHarnessManifestPath");function $e(e,t){return(e instanceof Error?e.message:String(e))===`codex turn ${t} timed out`}o($e,"isCodexTurnTimeoutError");function It(e){return(e instanceof Error?e.message:String(e)).startsWith("codex app-server exited with code 0")}o(It,"isCodexAppServerCleanExitError");async function yt(e){let t=Date.now()+ht;for(;Date.now()<t;){if(await bt(e))return!0;await Le(vt)}return!1}o(yt,"waitForTimedOutSourceApplication");async function bt(e){try{await V(e);let t=await _e(e);await Le(Rt),await V(e);let a=await _e(e);return t===a}catch{return!1}}o(bt,"localCreateSourceLayoutIsStable");async function _e(e){let t=[k.join(e.sourceRoot,"agent","agent.ts"),k.join(e.sourceRoot,"package.json"),k.join(e.repoPath,"openpond-profile.json"),k.join(e.sourcePath,"settings","profile.yaml")];return(await Promise.all(t.map(async n=>{let r=await Oe(n,"utf8");return`${n}:${r.length}:${r}`}))).join(`
2
+ import{a as Ae}from"./chunk-GW766ZSO.js";import{B as O,a as Ce,b as Pe}from"./chunk-OFJPOTES.js";import{b as be}from"./chunk-YU3C6U5V.js";import{d as H}from"./chunk-L5L3H6CI.js";import{a as re,b as ye,j as A}from"./chunk-6ESBAHWK.js";import{f as Ie}from"./chunk-Z6HWSTEP.js";import{D as we}from"./chunk-2MEOUS24.js";import{n as $}from"./chunk-RCT3O3HQ.js";import{a as o}from"./chunk-FTQLQJQV.js";import{existsSync as z}from"node:fs";import{cp as xe,mkdir as Ee,readFile as Oe}from"node:fs/promises";import k from"node:path";import{existsSync as L}from"node:fs";import{readFile as K}from"node:fs/promises";import q from"node:path";async function F(e){await V(e.target);let t={},a=new Set([`${e.target.sourceRootRelativePath}/.openpond/agent-inspect.json`,`${e.target.sourceRootRelativePath}/.openpond/action-registry.json`,`${e.target.sourceRootRelativePath}/.openpond/eval-results.json`]),n=[{name:"inspect",command:"inspect",args:["--json"]},{name:"build",command:"build"},{name:"validate",command:"validate",args:["--json"]},{name:"eval",command:"eval",args:["--json"]},{name:"direct-run",command:"run",args:[e.target.defaultAction,"--json","--input",JSON.stringify({prompt:e.snapshot.objective,channel:"openpond_chat"})]}];for(let r of n){let s=await O({cwd:e.target.sourceRoot,command:r.command,args:r.args,...r.command==="eval"&&e.requireEvalPass===!1?{throwOnFailure:!1}:{}});if(s.code!==0&&!(r.command==="eval"&&e.requireEvalPass===!1))throw new Error(s.stderr.trim()||s.stdout.trim()||`${r.command} failed with exit code ${s.code??"unknown"}`);let i=lt(s.stdout),d=mt(i);d&&a.add(q.join(e.target.sourceRootRelativePath,d)),t[r.name]={summary:pt(r.name,i),traceArtifactRef:d,stdout:s.stdout.trim().slice(0,4e3),stderr:s.stderr.trim().slice(0,4e3)}}return await dt(e.target,e.requireEvalPass!==!1),{checkRefs:[...a],metadata:t}}o(F,"runLocalCreatePipelineChecks");async function V(e){if(!L(e.sourceRoot))throw new Error(`Codex did not create the expected agent source root: ${e.sourceRoot}`);let t=q.join(e.sourceRoot,"agent","agent.ts");if(!L(t))throw new Error(`Codex did not create the expected SDK agent source: ${t}`);let a=q.join(e.repoPath,"openpond-profile.json");if(!L(a))throw new Error(`Codex did not update the profile repo manifest: ${a}`);let n=q.join(e.sourcePath,"settings","profile.yaml");if(!L(n))throw new Error(`Codex did not update the profile manifest: ${n}`);let s=JSON.parse(await K(a,"utf8")).profiles?.[e.activeProfile];if(!s)throw new Error(`openpond-profile.json does not register profile ${e.activeProfile}.`);if(!s.enabledAgents?.includes(e.agentId))throw new Error(`openpond-profile.json does not enable generated agent ${e.agentId}.`);let i=await K(n,"utf8");if(!i.includes(`id: ${e.agentId}`)&&!i.includes(`id: "${e.agentId}"`))throw new Error(`settings/profile.yaml does not register generated agent ${e.agentId}.`);let d=e.agentId==="default"?["agent/agent.ts","agent"]:[`agents/${e.agentId}`];if(!d.some(u=>i.includes(u)))throw new Error(`settings/profile.yaml does not point ${e.agentId} at ${d[0]}.`)}o(V,"assertLocalCreateSourceLayout");async function dt(e,t=!0){let a=q.join(e.sourceRoot,".openpond","action-registry.json"),n=q.join(e.sourceRoot,".openpond","eval-results.json");if(!L(a))throw new Error(`Generated source did not produce an action registry: ${a}`);if(!L(n))throw new Error(`Generated source did not produce eval results: ${n}`);let r=JSON.parse(await K(a,"utf8")),s=Array.isArray(r.actions)?r.actions:[];if(!new Set(s.map(c=>typeof c.id=="string"?c.id:null).filter(c=>!!c)).has(e.defaultAction))throw new Error(`Generated action registry does not expose default action ${e.defaultAction}.`);let d=s.filter(c=>typeof c.id=="string"&&(!W(c.label)||!W(c.description)||typeof c.timeoutSeconds!="number"));if(d.length>0)throw new Error(`Generated action registry has actions missing labels, descriptions, or timeout policies: ${d.map(c=>c.id).join(", ")}`);let u=Ce({actionCatalog:s.filter(c=>typeof c.id=="string").map(c=>({id:c.id,name:W(c.name),setupRequirements:ut(c.setupRequirements)??[]})),actionId:e.defaultAction});if(u.blockingRequirements.length>0)throw new Error(`Generated default action ${e.defaultAction} has unresolved required setup and cannot be ready_local: ${u.blockingRequirements.map(Pe).join("; ")}. Mark built-in/local fixture requirements ready or optional when they are satisfied, or leave the pipeline blocked until the setup is configured.`);let m=JSON.parse(await K(n,"utf8"));if(typeof m.summary?.total!="number"||m.summary.total<1)throw new Error("Generated source must define at least one deterministic SDK eval.");if(t&&m.summary.failed!==0)throw new Error("Generated source evals did not all pass.")}o(dt,"assertGeneratedSdkArtifacts");function lt(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;try{return JSON.parse(t)}catch{return null}}o(lt,"parseJsonOutput");function E(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}o(E,"asRecord");function ut(e){return Array.isArray(e)?e.filter(t=>!!E(t)):null}o(ut,"recordArray");function mt(e){let t=E(e),a=W(t?.traceArtifactRef);return a?.startsWith(".openpond/")?a:null}o(mt,"traceRefFromCommandResult");function pt(e,t){let a=E(t);return a?e==="inspect"?{actionCount:Array.isArray(a.actionCatalog)?a.actionCatalog.length:null,defaultAction:E(a.agent)?.defaultAction??null,projectName:E(a.project)?.name??null}:e==="validate"?{status:a.status??null,errors:E(a.summary)?.errors??null,warnings:E(a.summary)?.warnings??null}:e==="eval"?E(a.summary):e==="direct-run"?{hasResult:!!E(a.result),resultKeys:Object.keys(E(a.result)??{})}:null:null}o(pt,"summaryFromCommandResult");function W(e){return typeof e=="string"&&e.trim()?e.trim():null}o(W,"stringValue");var gt="Approved local Create plans require model-backed SDK source application; no source mutation was performed.",ft=1800*1e3,Te=".openpond-harness-source-application.json",ht=300*1e3,vt=2*1e3,Rt=5*1e3;async function He(e,t={}){if(!kt(e))return e;let a=t.now??(()=>new Date().toISOString()),n=e.adapter;if(n.kind!=="local")return e;if(!t.session||!t.turn||!t.ensureCodexRuntime||!t.appendRuntimeEvent||!t.setProviderTurnId)return Y(e,{now:a(),reason:gt,metadata:{reason:"model_backed_source_application_required",sourcePath:n.sourcePath??null,repoPath:n.repoPath??null,activeProfile:n.activeProfile??null,operation:e.operation,requestedAgentId:e.target.kind==="agent"?e.target.id:null}});let r;try{r=se(e)}catch(i){return Y(e,{now:a(),reason:i instanceof Error?i.message:String(i),metadata:{reason:"local_create_target_unresolved"}})}try{await ie({snapshot:e,session:t.session,turn:t.turn,target:r,ensureCodexRuntime:t.ensureCodexRuntime,appendRuntimeEvent:t.appendRuntimeEvent,setProviderTurnId:t.setProviderTurnId,model:t.model??we,codexReasoningEffort:t.codexReasoningEffort})}catch(i){return Y(e,{now:a(),reason:i instanceof Error?i.message:String(i),metadata:{reason:"model_backed_source_application_failed",target:r}})}let s=oe(e,{state:"running_checks",now:a(),blockedReason:null,sourceRefs:[r.sourceRootRelativePath,k.join(r.profileRelativePath,"settings","profile.yaml"),"openpond-profile.json"],metadata:{localCreatePipeline:{status:"running_checks",target:r}},candidates:[{id:Se(e.id),target:{kind:"agent",id:r.agentId,displayName:e.target.displayName,defaultActionKey:r.defaultAction},status:"checking",git:null,parentCandidateId:null,tasksetRef:e.tasksetRef,authoringModelRef:t.model??null,allowedPaths:e.plan?.sourcePlan.map(i=>i.path)??[],sourceRefs:[r.sourceRootRelativePath,k.join(r.profileRelativePath,"settings","profile.yaml"),"openpond-profile.json"],artifactRefs:[],checkRefs:[],evaluationReceiptRefs:[],createdAt:e.createdAt,updatedAt:a(),metadata:{sourceAuthority:e.adapter.sourceAuthority}}]});await t.onSnapshot?.(s);try{let i=await(t.runChecks??F)({snapshot:s,target:r}),d=a(),u=Se(e.id),m=`agent_eval_${e.id}`;return oe(s,{state:"ready_local",now:d,blockedReason:null,checkRefs:i.checkRefs,candidates:s.candidates.map(c=>c.id===u?{...c,status:"accepted",checkRefs:X(c.checkRefs,i.checkRefs),evaluationReceiptRefs:X(c.evaluationReceiptRefs,[m]),updatedAt:d}:c),evaluationReceipts:[...s.evaluationReceipts.filter(c=>c.id!==m),{id:m,candidateId:u,target:{kind:"agent",id:r.agentId,displayName:e.target.displayName,defaultActionKey:r.defaultAction},evaluatorKind:"agent_sdk",subject:"candidate",sourceCommit:e.adapter.kind==="local"?e.adapter.localHead:null,sourceBranch:null,tasksetId:e.tasksetRef?.id??null,tasksetHash:e.tasksetRef?.contentHash??null,taskAttemptRefs:i.checkRefs.filter(c=>c.includes("eval")),status:"passed",publishGate:"passed",summaryCounts:null,evalRefs:i.checkRefs.filter(c=>c.includes("eval")),artifactRefs:i.checkRefs,summary:wt(i.metadata),createdAt:d,metadata:i.metadata??{}}],metadata:{localCreatePipeline:{status:"ready_local",target:r,checks:i.metadata??{}}}})}catch(i){return Y(s,{now:a(),reason:i instanceof Error?i.message:String(i),metadata:{reason:"local_create_checks_failed",target:r}})}}o(He,"applyApprovedLocalCreateImproveRun");function kt(e){return e.state==="applying_source"&&e.plan?.status==="approved"&&e.adapter.kind==="local"&&e.target.kind==="agent"}o(kt,"shouldApplyLocalCreatePipeline");function oe(e,t){return A(e,{state:t.state,blockedReason:t.blockedReason===void 0?e.blockedReason:t.blockedReason,checkRefs:X(e.checkRefs,t.checkRefs??[]),sourceRefs:X(e.sourceRefs,t.sourceRefs??[]),candidates:t.candidates??e.candidates,evaluationReceipts:t.evaluationReceipts??e.evaluationReceipts,metadata:{...e.metadata,...t.metadata??{}},updatedAt:t.now})}o(oe,"transitionCreatePipeline");function Y(e,t){return oe(e,{state:"blocked",now:t.now,blockedReason:t.reason,metadata:{localCreatePipeline:{status:"blocked",...t.metadata}}})}o(Y,"blockLocalCreatePipeline");function X(e,t){return Array.from(new Set([...e,...t].filter(Boolean)))}o(X,"mergeRefs");function Se(e){return`agent_candidate_${e}`}o(Se,"agentCandidateId");function wt(e){let t=M(e?.eval),a=typeof t?.total=="number"?t.total:null;return a===null?"Agent SDK checks and deterministic Evals passed.":`${a} Agent SDK Eval${a===1?"":"s"} passed.`}o(wt,"checkSummary");function se(e){let t=e.adapter;if(t.kind!=="local")throw new Error("Create/Improve target must use the local adapter.");if(e.target.kind!=="agent")throw new Error("Local agent source application requires an Agent target.");let a=t.sourcePath?.trim(),n=t.repoPath?.trim();if(!a)throw new Error("Local Create approval is missing a profile source path.");if(!n)throw new Error("Local Create approval is missing a profile repo path.");let r=t.activeProfile?.trim()||"default",s=k.resolve(a),i=k.resolve(n),d=qe(e.target.id)??xt(e)??St(e.objective),u=Tt(Et(e.plan?.defaultChatAction.key)??"chat",d),m=e.operation==="improve"&&d==="default"?s:k.join(s,"agents",d);return{activeProfile:r,agentId:d,defaultAction:u,repoPath:i,sourcePath:s,workspaceRoot:i,profileRelativePath:je(k.relative(i,s)),sourceRoot:m,sourceRootRelativePath:je(k.relative(i,m))}}o(se,"resolveLocalCreatePipelineTarget");async function ie(e){if(!z(e.target.workspaceRoot))throw new Error(`Profile repo path does not exist: ${e.target.workspaceRoot}`);if(!z(e.target.sourcePath))throw new Error(`Profile source path does not exist: ${e.target.sourcePath}`);if(await Ct(e.snapshot,e.target)){await e.appendRuntimeEvent(H({sessionId:e.session.id,turnId:e.turn.id,name:"create_improve.updated",source:"server",appId:e.session.appId,status:"completed",output:`Applied prepared harness ${e.snapshot.operation==="improve"?"Improve":"Create"} source for ${e.target.agentId}; running local checks.`,data:{phase:"prepared_source_apply_completed",runId:e.snapshot.id,target:e.target}}));return}await e.appendRuntimeEvent(H({sessionId:e.session.id,turnId:e.turn.id,name:"create_improve.updated",source:"server",appId:e.session.appId,status:"started",output:`Applying approved ${e.snapshot.operation==="improve"?"Improve":"Create"} plan with Codex in ${e.target.sourceRootRelativePath}.`,data:{phase:"source_apply_started",runId:e.snapshot.id,target:e.target}}));let t={...e.session,provider:"codex",cwd:e.target.workspaceRoot,workspaceKind:"local_project",workspaceId:e.session.workspaceId??`openpond-profile:${e.target.activeProfile}`,workspaceName:e.session.workspaceName??`OpenPond profile ${e.target.activeProfile}`},a=e.session.provider==="codex"?e.model:null,n=await e.ensureCodexRuntime(t,{approvalPolicy:"never",sandbox:"workspace-write",model:a,codexPermissionMode:"auto-review",codexReasoningEffort:e.codexReasoningEffort}),r=await n.client.startTurn({threadId:n.threadId,prompt:At(e.snapshot,e.target),cwd:e.target.workspaceRoot,model:a,approvalPolicy:"never",sandbox:"workspace-write"});await e.setProviderTurnId(r.turnId);try{await n.client.waitForTurn(r.turnId,ft)}catch(s){if(!$e(s,r.turnId)&&!It(s))throw s;let i=$e(s,r.turnId)?"timed out":"exited cleanly before returning a turn completion";if(await e.appendRuntimeEvent(H({sessionId:e.session.id,turnId:e.turn.id,name:"create_improve.updated",source:"server",appId:e.session.appId,status:"started",output:`Codex source application ${i}; checking for completed generated source before blocking.`,data:{phase:"source_apply_recovery_started",runId:e.snapshot.id,providerTurnId:r.turnId,reason:i,target:e.target}})),!await yt(e.target))throw s;await e.appendRuntimeEvent(H({sessionId:e.session.id,turnId:e.turn.id,name:"create_improve.updated",source:"server",appId:e.session.appId,status:"completed",output:`Recovered completed ${e.snapshot.operation==="improve"?"Improve":"Create"} source after Codex source application ${i} for ${e.target.agentId}; running local checks.`,data:{phase:"source_apply_recovered",runId:e.snapshot.id,providerTurnId:r.turnId,reason:i,target:e.target}}))}await e.appendRuntimeEvent(H({sessionId:e.session.id,turnId:e.turn.id,name:"create_improve.updated",source:"provider",appId:e.session.appId,status:"completed",output:`Codex completed approved ${e.snapshot.operation==="improve"?"Improve":"Create"} source application for ${e.target.agentId}.`,data:{phase:"source_apply_completed",runId:e.snapshot.id,providerTurnId:r.turnId,target:e.target}}))}o(ie,"runModelBackedLocalCreateSourceApplication");async function Ct(e,t,a=process.env){if(!Ae(a))return!1;let n=k.join(t.workspaceRoot,Te);if(!z(n))return!1;let r=JSON.parse(await Oe(n,"utf8")),s=M(r);if(s?.schema!=="openpond.harnessPreparedSource.v1")throw new Error(`${Te} must use schema openpond.harnessPreparedSource.v1.`);let i=M(s.agents),d=M(i?.[t.agentId]),u=Pt(d?.[e.operation]);if(!u)return!1;let m=ne(t.workspaceRoot,u.source,"source");if(!z(m))throw new Error(`Prepared harness source does not exist: ${u.source}`);await Ee(t.sourceRoot,{recursive:!0}),await xe(m,t.sourceRoot,{recursive:!0,force:!0});for(let c of u.registrations??[]){let g=ne(t.workspaceRoot,c.source,"registration source"),l=ne(t.workspaceRoot,c.target,"registration target");if(!z(g))throw new Error(`Prepared harness registration source does not exist: ${c.source}`);await Ee(k.dirname(l),{recursive:!0}),await xe(g,l,{force:!0})}return!0}o(Ct,"applyPreparedHarnessSourceApplication");function Pt(e){let t=M(e);if(!t||typeof t.source!="string"||!t.source.trim())return null;if(t.registrations!==void 0&&!Array.isArray(t.registrations))throw new Error("Prepared harness source registrations must be an array.");let a=(t.registrations??[]).map(n=>{let r=M(n);if(!r||typeof r.source!="string"||!r.source.trim()||typeof r.target!="string"||!r.target.trim())throw new Error("Prepared harness source registrations require source and target paths.");return{source:r.source,target:r.target}});return{source:t.source,registrations:a}}o(Pt,"asHarnessPreparedSourceOperation");function ne(e,t,a){if(k.isAbsolute(t))throw new Error(`Prepared harness ${a} must be relative to the profile repo.`);let n=k.resolve(e),r=k.resolve(n,t);if(r!==n&&!r.startsWith(`${n}${k.sep}`))throw new Error(`Prepared harness ${a} must stay inside the profile repo.`);return r}o(ne,"resolveHarnessManifestPath");function $e(e,t){return(e instanceof Error?e.message:String(e))===`codex turn ${t} timed out`}o($e,"isCodexTurnTimeoutError");function It(e){return(e instanceof Error?e.message:String(e)).startsWith("codex app-server exited with code 0")}o(It,"isCodexAppServerCleanExitError");async function yt(e){let t=Date.now()+ht;for(;Date.now()<t;){if(await bt(e))return!0;await Le(vt)}return!1}o(yt,"waitForTimedOutSourceApplication");async function bt(e){try{await V(e);let t=await _e(e);await Le(Rt),await V(e);let a=await _e(e);return t===a}catch{return!1}}o(bt,"localCreateSourceLayoutIsStable");async function _e(e){let t=[k.join(e.sourceRoot,"agent","agent.ts"),k.join(e.sourceRoot,"package.json"),k.join(e.repoPath,"openpond-profile.json"),k.join(e.sourcePath,"settings","profile.yaml")];return(await Promise.all(t.map(async n=>{let r=await Oe(n,"utf8");return`${n}:${r.length}:${r}`}))).join(`
3
3
  ---
4
4
  `)}o(_e,"sourceLayoutFingerprint");function Le(e){return new Promise(t=>setTimeout(t,e))}o(Le,"sleep");function At(e,t){return[`Apply this already-approved OpenPond ${e.operation==="improve"?"Improve":"Create"} plan by editing the local profile repo source.`,"","This is the source-materialization step, not another plan review. Make the file changes, inspect the existing profile shape first, and leave the repo with a valid openpond-agent-sdk source project.","","Hard requirements:",`- Current working directory is the profile repo root: ${t.workspaceRoot}`,`- Active profile source path relative to cwd: ${t.profileRelativePath}`,`- Target agent id: ${t.agentId}`,`- Target generated source root: ${t.sourceRootRelativePath}`,`- Default action to expose: ${t.defaultAction}`,`- For a create request, create the new SDK project under ${t.profileRelativePath}/agents/<agent-id>; do not overwrite ${t.profileRelativePath}/agent/agent.ts or unrelated existing agents.`,"- For an edit request, only edit the approved target agent source and shared profile registration files required for that edit.",`- Update openpond-profile.json and ${t.profileRelativePath}/settings/profile.yaml so the generated agent is registered, enabled, and catalog-discoverable.`,"- The generated source must be an actual openpond-agent-sdk project with package.json, tsconfig.json when needed, agent/agent.ts, deterministic evals, and action metadata.","- Preserve the approved objective and any captured conversation context in source metadata, instructions, fixture comments, or eval intent so source readback can prove what was captured.","- Treat plan.metadata.actionShape as the approved public action-shape decision when actionShapeDecisionSource is request_metadata or another explicit planner source.","- If plan.metadata.actionShapeDecisionSource is default_chat_fallback, use the approved objective and captured context to choose the actual generated public actions: keep chat-only for conversational assistants, create direct actions for explicit repeatable runs/workflows/artifact transforms, and expose both when the user needs normal chat plus a repeatable catalog action.","- When refining a default fallback during source materialization, encode the chosen public actions in generated SDK action metadata and evals; do not use business-example hardcoding.","- Every public action must have a stable action id, label, description, input/output schema when useful, timeout policy, artifact policy, setup requirement metadata, and deterministic eval coverage.","- The default action must be invocable through the local profile setup gate after checks. Do not leave built-in openpond_chat or committed local fixture/artifact requirements as unresolved required setup; mark those rows ready/satisfied or optional when the generated source already provides them.","- If the approved objective names multiple capabilities or direct action ids, implement each requested public action instead of collapsing everything into a single chat-only action.","- If a capability writes an artifact, declare it in the action artifact policy and assert it from at least one eval.","- Package scripts must be portable from the generated source root; do not hardcode absolute machine-local paths to this repository or CLI.","- Do not hardcode secrets, API keys, provider tokens, or user credentials in source, evals, traces, fixtures, or comments.","- Use realistic deterministic fixture-backed behavior when external systems are unavailable. Declare setup requirements rather than pretending live integrations exist.","- Run or prepare the source so these commands can pass from the target source root: inspect, build, validate, eval, and run of the default action.","","Approved Create request and plan:",JSON.stringify({run:e,plan:e.plan,questions:e.questions,workflowCapture:e.workflowCapture},null,2)].join(`
5
5
  `)}o(At,"localCreatePipelinePrompt");function xt(e){for(let t of e.plan?.sourcePlan??[]){let a=/^agents\/([^/]+)/.exec(t.path),n=qe(a?.[1]);if(n)return n}return null}o(xt,"agentIdFromSourcePlan");function qe(e){let t=e?.trim();return t&&t.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||null}o(qe,"normalizeAgentId");function Et(e){return e?.trim()||null}o(Et,"normalizeActionId");function M(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}o(M,"asRecord");function Tt(e,t){let a=`${t}.`;return e.startsWith(a)?e.slice(a.length)||"chat":e}o(Tt,"sourceActionIdForAgent");function St(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64).replace(/-+$/g,"")||"generated-agent"}o(St,"slugFromObjective");function je(e){return e.replace(/\\/g,"/")||"."}o(je,"normalizeRelativePath");import de from"node:path";function Pa(e){let t=e.sources.length?e.sources.map(r=>({kind:"conversation",id:r.id,sourceHash:r.sourceHash,excerptRef:`training-source:${r.id}`})):[{kind:"manual_intent",id:`manual_intent_${$(e.objective).slice(0,24)}`,sourceHash:$({objective:e.objective}),excerptRef:null}],a={consent:{status:"granted",scope:e.sources.length?"selected_turns":"direct_intent",reviewedBy:"local_user",reviewedAt:e.timestamp},sources:t,reviewerIntent:e.objective},n=$(a);return re.parse({schemaVersion:"openpond.createImprove.evidenceSnapshot.v1",id:`evidence_snapshot_${n.slice(0,24)}`,contentHash:n,...a,createdAt:e.timestamp,metadata:{immutable:!0,sourceCount:t.length}})}o(Pa,"createEvidenceSnapshot");function Ia(e){let t={runId:e.run.id,candidateId:e.candidateId,tasksetId:e.run.tasksetRef?.id??null,tasksetRevision:e.run.tasksetRef?.revision??null,tasksetHash:e.run.tasksetRef?.contentHash??null,outcome:e.outcome,reason:e.reason,receiptRefs:e.receiptRefs},a=$(t);return re.parse({schemaVersion:"openpond.createImprove.evidenceSnapshot.v1",id:`evidence_outcome_${a.slice(0,24)}`,contentHash:a,consent:{status:"granted",scope:"direct_intent",reviewedBy:e.run.actor.id??"local_user",reviewedAt:e.timestamp},sources:[{kind:"artifact",id:`${e.outcome}:${e.run.id}:${e.candidateId}`,sourceHash:a,excerptRef:e.receiptRefs[0]??null}],reviewerIntent:e.reason,createdAt:e.timestamp,metadata:{immutable:!0,evidenceKind:"candidate_outcome",outcome:e.outcome,priorTasksetRevision:e.run.tasksetRef?.revision??null,recommendedNextTasksetRevision:e.run.tasksetRef?e.run.tasksetRef.revision+1:1,receiptRefs:e.receiptRefs}})}o(Ia,"createOutcomeEvidenceSnapshot");function ya(e){let t=e.proposal?$t(e.proposal):{kind:"model",rationale:["A reviewed training plan selected Model execution for this Taskset."],confidence:1};return ye.parse({schemaVersion:"openpond.createImprove.tasksetRef.v1",id:e.taskset.id,revision:e.taskset.revision,contentHash:e.taskset.contentHash,evidenceSnapshotIds:e.evidenceSnapshotIds,policyBoundary:e.taskset.policy,targetRecommendation:t,authoringSplitRefs:e.taskset.tasks.filter(a=>a.split==="train"||a.split==="validation").map(a=>a.id),privateSplitRefs:e.taskset.tasks.filter(a=>a.split==="test"||a.split==="frozen_eval").map(a=>a.id),approvedBy:"local_user",approvedAt:e.approvedAt,metadata:{immutable:!0,taskCreationProposalId:e.proposal?.id??null}})}o(ya,"createTasksetRef");function Me(e,t){if(e.id!==t.id||e.revision!==t.revision||e.contentHash!==t.contentHash)throw new Error(`Taskset lineage mismatch: the run approved ${e.id}@${e.revision} (${e.contentHash}), but execution resolved ${t.id}@${t.revision} (${t.contentHash}).`)}o(Me,"assertTasksetRefMatches");function $t(e){let t=_t(e);return{kind:t,rationale:e.diagnosis.rationale.length?e.diagnosis.rationale:[`${t} best matches the reviewed behavior boundary.`],confidence:e.diagnosis.confidence}}o($t,"recommendationForProposal");function _t(e){return e.diagnosis.trainingEligible?"model":e.diagnosis.intervention==="retrieval"?"configuration":"agent"}o(_t,"targetKindForProposal");async function Ge(e){let t=e.run.tasksetRef;if(!t)throw new Error("Agent Taskset execution requires an approved Taskset ref.");if(Me(t,e.taskset),e.taskset.environment.kind!=="agent")throw new Error(`Taskset ${e.taskset.id} is not an Agent-shaped Taskset.`);let a=new Set(t.privateSplitRefs),n=e.taskset.tasks.filter(c=>a.has(c.id));if(!n.length||n.length!==a.size)throw new Error("The approved Agent Taskset private split could not be resolved exactly.");let r={tasksetId:t.id,tasksetRevision:t.revision,tasksetHash:t.contentHash,taskRefs:n.map(c=>c.id),seed:0,timeoutMs:e.taskset.environment.defaultTimeoutMs,entrypoint:e.taskset.environment.entrypoint,evaluator:"openpond-agent-sdk-taskset.v1"},s=$(r),i=[],d=[],u=[];for(let c of n){let g=new Date().toISOString(),l=Date.now(),p=await(e.execute??O)({cwd:e.cwd,command:"run",args:[e.taskset.environment.entrypoint,"--json","--input",JSON.stringify({...c.input,channel:"manual"})],timeoutMs:e.taskset.environment.defaultTimeoutMs,throwOnFailure:!1}),x=p.code===0?jt(p.stdout):null,b=`agent_task_attempt_${$([e.run.id,e.subject,e.sourceCommit,t.contentHash,c.id,0]).slice(0,24)}`,f=Ot(x?.traceArtifactRef),P=Ie.parse({schemaVersion:"openpond.taskAttempt.v1",id:b,tasksetId:e.taskset.id,taskId:c.id,split:c.split,attempt:0,seed:0,modelRef:null,startedAt:g,completedAt:new Date().toISOString(),output:ce(x?.result),runtimeEventRefs:f?[f]:[],artifactRefs:f?[f]:[],privilegedOutcomeRef:c.privilegedContextRef,infrastructureError:p.code===0?null:p.stderr.trim().slice(0,1e4)||`Agent SDK action exited with code ${String(p.code)}.`,costUsd:0,latencyMs:Math.max(0,Date.now()-l),userInterventions:0,metadata:{executor:"openpond-agent-sdk",trustedTasksetExecution:!0,tasksetRevision:t.revision,tasksetHash:t.contentHash,sourceCommit:e.sourceCommit,subject:e.subject,executionContractHash:s}}),R=await e.gradeAttempt({tasksetId:e.taskset.id,taskId:c.id,attempt:P});d.push(P.id),i.push(R),f&&u.push(f)}let m=i.filter(c=>c.passed).length;return{taskAttemptRefs:d,gradeRefs:i.map(c=>c.id),taskRefs:n.map(c=>c.id),artifactRefs:[...new Set(u)],total:i.length,passed:m,failed:i.length-m,executionContractHash:s}}o(Ge,"executeAgentTasksetEvaluation");function jt(e){let t=e.trim();if(!t)return null;try{return ce(JSON.parse(t))}catch{let a=t.indexOf("{"),n=t.lastIndexOf("}");if(a<0||n<=a)return null;try{return ce(JSON.parse(t.slice(a,n+1)))}catch{return null}}}o(jt,"parseAgentRunPayload");function ce(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}o(ce,"recordValue");function Ot(e){return typeof e=="string"&&e.trim()?e.trim():null}o(Ot,"stringValue");async function le(e){let t=await(e.execute??O)({cwd:e.cwd,command:"eval",args:["--json"],throwOnFailure:!1}),a=qt(t.stdout),n=G(a.summary?.total)??0,r=G(a.summary?.passed)??0,s=G(a.summary?.failed)??Math.max(0,n-r),i=a.publishGate?.status==="passed"?"passed":"failed",d=Array.isArray(a.results)?a.results:[],u=d.map(R=>I(R.name)).filter(R=>!!R),m=new Set([de.posix.join(e.sourceRef,".openpond/eval-results.json")]);for(let R of d){let _=I(R.traceArtifactRef);_&&m.add(de.posix.join(e.sourceRef,Ne(_)));for(let J of De(R.artifacts))m.add(de.posix.join(e.sourceRef,Ne(J)))}let c=e.run.tasksetRef?await Ge({run:e.run,taskset:Ht(e.taskset),cwd:e.cwd,sourceCommit:e.sourceCommit,subject:e.subject,gradeAttempt:Lt(e.gradeAttempt),execute:e.execute}):null;for(let R of c?.artifactRefs??[])m.add(R);let g=n+(c?.total??0),l=r+(c?.passed??0),p=s+(c?.failed??0),x=[...new Set([...u,...c?.taskRefs??[]])],b=i==="passed"&&(c?.failed??0)===0?"passed":"failed",f=t.code===0&&p===0&&b==="passed"?"passed":"failed",P=e.timestamp??new Date().toISOString();return{id:`agent_eval_${e.run.id}_${e.subject}_${e.sourceCommit.slice(0,12)}`,candidateId:e.candidateId,target:e.run.target,evaluatorKind:"agent_sdk",subject:e.subject,sourceCommit:e.sourceCommit,sourceBranch:e.sourceBranch,tasksetId:e.run.tasksetRef?.id??null,tasksetHash:e.run.tasksetRef?.contentHash??null,taskAttemptRefs:c?.taskAttemptRefs??u,status:f,publishGate:b,summaryCounts:{total:g,passed:l,failed:p},evalRefs:x,artifactRefs:[...m],summary:`${e.subject==="active"?"Active":e.subject==="candidate"?"Candidate":"Post-release"} Agent SDK and Taskset Evals: ${l}/${g} passed${b==="failed"?"; publish gate failed":""}.`,createdAt:P,metadata:{schemaVersion:I(a.schemaVersion),schema:I(a.schema),project:{name:I(a.project?.name),version:I(a.project?.version)},source:{configPath:I(a.source?.configPath),configHash:I(a.source?.configHash)},publishGate:{total:G(a.publishGate?.total),passed:G(a.publishGate?.passed),failed:G(a.publishGate?.failed),blockingFailures:De(a.publishGate?.blockingFailures)},command:{code:t.code,timedOut:t.timedOut,stderr:t.stderr.trim().slice(0,4e3)},trustedTasksetExecution:!!c,tasksetRevision:e.run.tasksetRef?.revision??null,executionContractHash:c?.executionContractHash??null,gradeRefs:c?.gradeRefs??[],results:d.map(R=>({name:I(R.name),status:I(R.status),error:I(R.error),traceArtifactRef:I(R.traceArtifactRef)}))}}}o(le,"runNormalizedAgentEvaluation");function Ht(e){if(!e)throw new Error("The approved Agent Taskset could not be resolved for evaluation.");return e}o(Ht,"requireTaskset");function Lt(e){if(!e)throw new Error("Trusted Taskset grading is unavailable for Agent evaluation.");return e}o(Lt,"requireGradeAttempt");function qt(e){let t=e.trim();if(!t)throw new Error("Agent SDK Eval returned no JSON output.");try{return JSON.parse(t)}catch{let a=t.indexOf("{"),n=t.lastIndexOf("}");if(a>=0&&n>a)try{return JSON.parse(t.slice(a,n+1))}catch{}throw new Error("Agent SDK Eval returned invalid JSON output.")}}o(qt,"parseAgentEvalPayload");function Ne(e){return e.replace(/^\.\//,"").replaceAll("\\","/")}o(Ne,"normalizeRef");function I(e){return typeof e=="string"&&e.trim()?e.trim():null}o(I,"stringValue");function G(e){return typeof e=="number"&&Number.isFinite(e)?e:null}o(G,"numberValue");function De(e){return Array.isArray(e)?e.map(I).filter(t=>!!t):[]}o(De,"stringArray");import{existsSync as Z}from"node:fs";import{mkdir as Xe,realpath as Qe,rm as he,writeFile as Ft}from"node:fs/promises";import Ze from"node:os";import S from"node:path";import{existsSync as ue}from"node:fs";import{cp as Mt,lstat as Gt,mkdir as Be,rm as Nt,symlink as Dt,writeFile as Bt}from"node:fs/promises";import w from"node:path";function Ue(e,t){let a=C(t.profileRelativePath),n=[C(t.sourceRootRelativePath),w.posix.join(a,"evals"),w.posix.join(a,"settings"),w.posix.join(a,"package.json"),w.posix.join(a,"tsconfig.json"),w.posix.join(a,"openpond.lock"),w.posix.join(a,".gitignore"),"openpond-profile.json"],r=(e.plan?.sourcePlan??[]).flatMap(s=>{let i=C(s.path);return i?i==="."||i.startsWith(`${a}/`)?[i]:[w.posix.join(a,i),i]:[]});return[...new Set([...n,...r])]}o(Ue,"allowedAgentImprovementPaths");function Je(e,t){let a=C(e);return t.some(n=>a===n||a.startsWith(`${n}/`))}o(Je,"pathAllowed");function me(e){return C(e).split("/").some(a=>a==="node_modules"||a===".openpond"||a==="artifacts")}o(me,"isCandidateRuntimePath");function Fe(e){return e.split(/\r?\n/).map(t=>t.trimEnd()).filter(Boolean).map(t=>{let a=t.slice(3),n=a.split(" -> ");return C(n.at(-1)??a)})}o(Fe,"parseGitStatusPaths");async function pe(e,t,a){let n=await e("git",["diff","--name-only","-z",a,"--","."],t);return h(n,"Unable to inspect Agent candidate paths."),[...new Set(n.stdout.split("\0").map(C).filter(r=>r!=="."&&!me(r)))]}o(pe,"gitChangedPaths");async function ge(e){for(let t of e.paths){let a=await B(e.command,e.repoPath,["rev-parse",`${e.commit}:${t}`]),n=w.join(e.repoPath,...t.split("/"));if(!a){if(ue(n))return!1;continue}if(!ue(n))return!1;let r=await B(e.command,e.repoPath,["hash-object","--",t]);if(!r||r!==a)return!1}return!0}o(ge,"workingTreeMatchesCommit");async function ze(e,t){let a=new Set(["node_modules",w.posix.join(C(e.profileRelativePath),"node_modules"),w.posix.join(C(e.sourceRootRelativePath),"node_modules")]);for(let n of a){let r=w.join(e.repoPath,...n.split("/")),s=w.join(t,...n.split("/"));!await Jt(r)||ue(s)||(await Be(w.dirname(s),{recursive:!0}),await Dt(r,s,process.platform==="win32"?"junction":"dir"))}}o(ze,"linkCandidateDependencies");async function We(e){let t=await e.command("git",["diff","--binary","HEAD","--",".",":(exclude)**/tasksets/**"],e.repoPath);if(h(t,"Unable to capture active Profile changes."),t.stdout){let i=w.join(e.workspaceRoot,"active-profile.patch");await Bt(i,t.stdout,"utf8");let d=await e.command("git",["apply","--whitespace=nowarn",i],e.worktreePath);h(d,"Unable to apply active Profile changes to the candidate baseline."),await Nt(i,{force:!0})}let a=await e.command("git",["ls-files","--others","--exclude-standard","-z"],e.repoPath);h(a,"Unable to inspect untracked Profile source.");for(let i of a.stdout.split("\0").filter(Ut)){let d=w.join(e.repoPath,...i.split("/")),u=w.join(e.worktreePath,...i.split("/"));await Be(w.dirname(u),{recursive:!0}),await Mt(d,u,{recursive:!0,preserveTimestamps:!0})}let n=await e.command("git",["add","-A"],e.worktreePath);h(n,"Unable to stage the active Profile snapshot.");let r=await e.command("git",["diff","--cached","--quiet"],e.worktreePath);if(r.code===0)return;r.code!==1&&h(r,"Unable to inspect the active Profile snapshot.");let s=await e.command("git",["commit","-m","Snapshot active Profile before OpenPond improvement"],e.worktreePath,Q());h(s,"Unable to commit the active Profile snapshot.")}o(We,"snapshotActiveProfileChanges");function Ut(e){return e?!C(e).split("/").some(a=>a==="node_modules"||a===".openpond"||a==="artifacts"||a==="tasksets"):!1}o(Ut,"snapshotEligiblePath");function Q(){return{GIT_AUTHOR_NAME:process.env.GIT_AUTHOR_NAME||"OpenPond",GIT_AUTHOR_EMAIL:process.env.GIT_AUTHOR_EMAIL||"openpond@example.invalid",GIT_COMMITTER_NAME:process.env.GIT_COMMITTER_NAME||"OpenPond",GIT_COMMITTER_EMAIL:process.env.GIT_COMMITTER_EMAIL||"openpond@example.invalid"}}o(Q,"gitIdentityEnv");async function Jt(e){try{return(await Gt(e)).isDirectory()}catch{return!1}}o(Jt,"directoryExists");async function Ke(e,t,a){let n=await e("gh",["pr","list","--head",a,"--state","all","--json","number,url,state,mergedAt,mergeCommit,baseRefName,headRefName","--limit","20"],t);h(n,"Unable to inspect existing Agent improvement pull requests.");let r=JSON.parse(n.stdout);return Array.isArray(r)?r.filter(s=>!!(s&&typeof s=="object")):[]}o(Ke,"listPullRequestsForBranch");function fe(e,t=new Date().toISOString(),a=new Date().toISOString()){let n=typeof e.number=="number"?e.number:Number(e.number),r=typeof e.state=="string"?e.state.toLowerCase():"",i=N(e.mergedAt)||r==="merged"?"merged":r==="open"?"open":"closed",d=e.mergeCommit&&typeof e.mergeCommit=="object"?e.mergeCommit:null,u=N(d?.oid)??N(e.mergeCommit),m=N(e.url),c=N(e.baseRefName),g=N(e.headRefName);if(!Number.isInteger(n)||n<=0||!m||!c||!g)throw new Error("GitHub returned an incomplete pull request payload.");return{provider:"github",number:n,url:m,state:i,baseBranch:c,headBranch:g,mergeCommit:u,openedAt:t,updatedAt:a}}o(fe,"normalizePullRequest");function Ve(e,t){return`openpond/improve/${D(t)}/${D(e.id).slice(0,36)}`}o(Ve,"candidateBranch");function U(e){if(!e.worktreePath)throw new Error("Agent candidate worktree is unavailable.");return e.worktreePath}o(U,"requireWorktreePath");function Ye(e){let t=e.replace(/^git@github\.com:/i,"").replace(/^https?:\/\/github\.com\//i,"").replace(/\.git$/i,"").replace(/^\/+|\/+$/g,"");return/^[^/]+\/[^/]+$/.test(t)?t:null}o(Ye,"githubRepoFromRemote");function C(e){return e.replaceAll("\\","/").replace(/^\.\//,"").replace(/^\/+|\/+$/g,"")||"."}o(C,"normalizeRepoPath");function D(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"candidate"}o(D,"safePathSegment");async function y(e,t,a,n){let r=await e("git",a,t);h(r,n);let s=r.stdout.trim();if(!s)throw new Error(n);return s}o(y,"requiredGitText");async function B(e,t,a){let n=await e("git",a,t);return n.code===0&&n.stdout.trim()?n.stdout.trim():null}o(B,"optionalGitText");function h(e,t){if(e.code!==0)throw new Error(e.stderr.trim()||e.stdout.trim()||t)}o(h,"assertCommand");function N(e){return typeof e=="string"&&e.trim()?e.trim():null}o(N,"stringValue");function T(e,t,a,n={}){return be(e,t,a,n)}o(T,"defaultCommandRunner");function et(e,t){let a=U(t);if(!Z(a))throw new Error("The existing Agent candidate worktree is no longer available.");let n=C(e.profileRelativePath),r=C(e.sourceRootRelativePath);return{target:{...e,repoPath:a,workspaceRoot:a,sourcePath:S.join(a,...n.split("/")),sourceRoot:S.join(a,...r.split("/"))},git:t}}o(et,"restoreAgentImprovementWorkspace");async function tt(e){let t=e.command??T,a=await y(t,e.target.repoPath,["rev-parse","--show-toplevel"],"Profile source is not a Git repository."),[n,r]=await Promise.all([Qe(a),Qe(e.target.repoPath)]);if(n!==r)throw new Error("Profile repo path does not match the Git repository root.");let s=await t("git",["status","--porcelain=v1","-uall"],a);h(s,"Unable to inspect Profile Git status.");let[i,d,u]=await Promise.all([y(t,a,["rev-parse","HEAD"],"Profile Git repo has no HEAD commit."),y(t,a,["branch","--show-current"],"Profile Git repo must be on a branch."),B(t,a,["remote","get-url","origin"])]);if(e.run.adapter.kind==="local"&&e.run.adapter.localHead&&e.run.adapter.localHead!==i)throw new Error(`Profile source changed from ${e.run.adapter.localHead.slice(0,12)} to ${i.slice(0,12)}. Re-plan the improvement against the current source.`);let m=Ve(e.run,e.target.agentId),c=S.join(Ze.tmpdir(),"openpond-agent-improvements",D(S.basename(a)||"profile"),D(e.run.id)),g=S.join(c,"repo");await Xe(c,{recursive:!0});let l=await t("git",["show-ref","--verify","--quiet",`refs/heads/${m}`],a);if(Z(g)&&await B(t,g,["branch","--show-current"])!==m&&(await t("git",["worktree","remove","--force",g],a),await he(c,{recursive:!0,force:!0}),await Xe(c,{recursive:!0})),!Z(g)){let P=l.code===0?["worktree","add",g,m]:["worktree","add","-b",m,g,i],R=await t("git",P,a);h(R,"Unable to create the Agent candidate worktree.")}s.stdout.trim()&&await We({command:t,repoPath:a,worktreePath:g,workspaceRoot:c});let p=await y(t,g,["rev-parse","HEAD"],"Agent candidate worktree has no baseline commit.");if(await y(t,g,["rev-parse","HEAD"],"Agent candidate worktree has no HEAD commit.")!==p)throw new Error("Agent candidate baseline could not be resolved.");await ze(e.target,g);let b=C(e.target.profileRelativePath),f=C(e.target.sourceRootRelativePath);return{target:{...e.target,repoPath:g,workspaceRoot:g,sourcePath:S.join(g,...b.split("/")),sourceRoot:S.join(g,...f.split("/"))},git:{baseBranch:d,baseCommit:p,branch:m,headCommit:null,remoteName:"origin",remoteUrl:u,worktreePath:g,changedPaths:[],diffStat:null,pullRequest:null}}}o(tt,"prepareAgentImprovementWorkspace");async function at(e){let t=e.command??T,a=U(e.workspace.git),n=await t("git",["status","--porcelain=v1","-uall"],a);h(n,"Unable to inspect Agent candidate changes.");let r=Fe(n.stdout).filter(g=>!me(g));if(r.length===0)throw new Error("The Agent improvement produced no source changes.");let s=Ue(e.run,e.activeTarget),i=r.filter(g=>!Je(g,s));if(i.length>0)throw new Error(`Agent candidate changed paths outside the approved scope: ${i.join(", ")}`);let d=await t("git",["add","--",...r],a);h(d,"Unable to stage Agent candidate changes.");let u=await t("git",["commit","-m",`Improve ${e.run.target.displayName??e.activeTarget.agentId} via OpenPond`],a,Q());h(u,"Unable to commit Agent candidate changes.");let m=await y(t,a,["rev-parse","HEAD"],"Agent candidate commit was not created."),c=await B(t,a,["diff","--stat",`${e.workspace.git.baseCommit}..${m}`]);return{...e.workspace.git,headCommit:m,changedPaths:r,diffStat:c}}o(at,"commitAgentImprovementCandidate");async function Va(e){let t=e.command??T,a=U(e.git);if(!e.git.headCommit)throw new Error("Agent candidate has no commit to push.");if(!e.git.remoteUrl||!Ye(e.git.remoteUrl))throw new Error("Agent candidate is ready locally. Configure a GitHub origin remote before opening a pull request.");let n=await t("git",["push","--set-upstream",e.git.remoteName,e.git.branch],a);h(n,"Unable to push the Agent candidate branch.");let r=await Ke(t,a,e.git.branch);if(r.length>0)return fe(r[0],e.timestamp);let s=`Improve ${e.run.target.displayName??e.run.target.id??"Agent"}`,i=["## OpenPond Agent improvement","",e.run.objective,"","## Evaluation","",e.evaluationSummary,"",`Create/Improve run: \`${e.run.id}\``,`Base commit: \`${e.git.baseCommit}\``,`Candidate commit: \`${e.git.headCommit}\``].join(`
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{b}from"./chunk-JQOVC35K.js";import{ja as M}from"./chunk-HG2YFMVU.js";import{Qb as x,m as T,v as A}from"./chunk-D6L6UNUQ.js";import{n as c,o as S}from"./chunk-RCT3O3HQ.js";import{A as I}from"./chunk-X2J2P5ZT.js";import{a as R}from"./chunk-FTQLQJQV.js";function j(e,a,i){if(a==="agent_action"){let n=e.find(u=>u.name==="workspace_action_result"&&u.action==="profile_workflow_action")?.output;if(typeof n!="string")throw new Error("Profile Agent action evaluation did not produce a released action result.");return n}if(i==="completed"){let n=[...e].reverse().find(s=>s.name==="turn.completed"),r=n?.data?.providerResponse,o=n?.data;if(!r&&o?.turn?.status==="completed"){let s=[...e].reverse().find(t=>P(t)!==null);if(!s)throw new Error("Native Profile evaluation has no retained final answer.");let d=P(s);return e.filter(t=>P(t)===d).map(t=>t.output??"").join("")}if(typeof r?.requestId!="string"||!r.requestId||typeof r.contentHash!="string")throw new Error("Profile evaluation has no retained final provider response.");let p=e.filter(s=>s.name==="assistant.delta"&&s.data?.providerRequestId===r.requestId).map(s=>s.output??"").join("");if(c(p)!==r.contentHash)throw new Error("Profile evaluation final provider response differs from its retained trace.");return b(e)??p}return e.filter(n=>n.name==="assistant.delta"&&typeof n.output=="string").map(n=>n.output??"").join("")}R(j,"profileEvaluationOutput");function P(e){let a=e.data;return e.name==="assistant.delta"&&a?.provider==="codex"&&a.phase==="final_answer"&&typeof a.itemId=="string"?a.itemId:null}R(P,"nativeFinalAnswerItemId");async function _(e){let{store:a,manifest:i,receipt:n}=e;if(!n.metadata.retainedEvidenceRef)return null;let u=x.parse(n.metadata.retainedEvidenceRef),[r,o]=await Promise.all([a.getSession(u.sessionId),a.getTurn(u.turnId)]),p=r?.metadata?.profileEvaluationRun,s=i.profileEvaluation;if(!r||!o||o.sessionId!==r.id||!s||!r.currentProfile||c(r.currentProfile)!==c(e.profileRef)||c(p)!==c({id:i.id,contentHash:i.contentHash})||r.metadata?.taskId!==n.taskId||r.metadata?.seed!==n.seed||!o.completedAt||o.completedAt!==n.completedAt||o.startedAt!==n.startedAt||!o.harnessSnapshot||o.harnessSnapshot.harnessRelease.id!==s.harnessRelease.id||o.harnessSnapshot.harnessRelease.contentHash!==s.harnessRelease.contentHash||i.policy.kind!=="model"||!o.modelRef||o.modelRef.providerId!==i.policy.model.provider||o.modelRef.modelId!==i.policy.model.model)throw new Error("Retained Profile policy turn differs from its admitted case.");let d=await a.runtimeEventsForTurn(o.id);if(d.some(v=>v.turnId!==o.id)||c(d)!==n.traceHash)throw new Error("Retained Profile policy trace differs from its immutable receipt.");let t=j(d,s.target.kind,o.status);if(n.outputHash!==null&&c({text:t})!==n.outputHash)throw new Error("Retained Profile output differs from its immutable receipt.");let m=n.artifactRefs.flatMap(v=>{let y=d.filter(l=>(l.action==="work_output_save"||l.action==="sandbox_save_output")&&l.status==="completed").flatMap(l=>{let C=l.data&&typeof l.data=="object"?l.data:{},k=M.safeParse(C.outputRef);return k.success?[k.data]:[]}).filter(l=>l.sourceTaskId===r.id&&l.sourceTurnId===o.id&&`${r.id}/${l.id}/${l.revision}/${l.title}`===v.id&&l.sha256===v.contentHash&&l.sizeBytes===v.sizeBytes&&l.contentType===v.mediaType);if(y.length!==1)throw new Error("The case output has no unique sealed saved-file identity.");let h=y[0];if(h.location.kind!=="managed")return[];let H=`/api/work/outputs/${encodeURIComponent(h.location.fileId)}`;if(h.location.downloadPath!==H)throw new Error("The saved output has no canonical managed download route.");return[{id:h.id,title:h.title,revision:h.revision,contentType:h.contentType,sizeBytes:h.sizeBytes,sha256:h.sha256,downloadPath:H}]}),f=await a.listModelUsageRecords({sessionId:r.id,turnId:o.id,limit:1e4}),E=e.eventAfterId?d.findIndex(v=>v.id===e.eventAfterId):-1;if(e.eventAfterId&&E<0)throw new Error("Profile trace cursor is unavailable in this case.");let g=E+1,q=Math.max(1,Math.min(250,e.eventLimit??100)),w=d.slice(g,g+q);return{ref:u,prompt:o.prompt,output:n.outputHash===null?null:{text:t},partialOutput:n.outputHash===null&&t?{text:t}:null,error:o.error,events:w,eventCount:d.length,nextEventCursor:g+w.length<d.length?w.at(-1).id:null,files:m,usage:f,usageCoverage:f.length===1e4?"partial":"complete"}}R(_,"readProfileEvaluationPolicyEvidence");var W=I.object({runId:I.string().trim().min(1).max(240),receiptId:I.string().trim().min(1).max(500).optional(),eventAfterId:I.string().trim().min(1).max(500).optional(),eventLimit:I.number().int().min(1).max(250).optional(),manifest:A.optional()}).strict().refine(e=>e.receiptId||!e.eventAfterId&&!e.eventLimit,"Select a case before requesting its trace page.").refine(e=>!e.manifest||e.receiptId,"Interrupted-run inspection requires one exact case.");async function D(e){let a=await e.store.getProfileEvaluationRun(e.runId);if(a&&c(a.profileRef)!==c(e.profileRef))throw new Error("Profile evaluation run is unavailable in the selected Profile.");let i=a?.manifest??e.manifest;if(!i||!a&&!e.receiptId)throw new Error("Profile evaluation run is unavailable in the selected Profile.");if(a){if(e.manifest&&e.manifest.contentHash!==a.manifest.contentHash)throw new Error("Profile evaluation run differs from its pinned manifest.")}else if(S(i,"Interrupted Profile evaluation manifest"),i.id!==e.runId||i.profileEvaluation?.profileId!==e.profileRef.profileId||e.profileRef.source==="openpond_git"&&i.metadata.profileRepositoryId!==e.profileRef.repositoryId)throw new Error("Profile evaluation run is unavailable in the selected Profile.");let n=i.population.map((r,o)=>({member:r,index:o})).filter(({member:r})=>!e.receiptId||r.receiptId===e.receiptId);if(e.receiptId&&n.length!==1)throw new Error("Profile evaluation case is unavailable in the selected run.");let u=await Promise.all(n.map(async({member:r,index:o})=>{let p=a?null:await e.store.getProfileEvaluationReceipt(r.receiptId),s=a?.receiptRefs[o]??(p?{id:p.id,contentHash:p.contentHash}:null),d=a?.gradeRefs[o]??p?.graderEvidenceRefs[0];if(!s||!d)throw new Error("Profile evaluation run has incomplete case evidence.");let[t,m]=await Promise.all([e.store.getProfileEvaluationReceipt(s.id),e.store.getProfileEvaluationGrade(d.contentHash)]);if(!t||!a&&!T(t)||t.contentHash!==s.contentHash||t.id!==r.receiptId||t.taskId!==r.taskId||t.seed!==r.seed||t.runManifest.id!==i.id||t.runManifest.contentHash!==i.contentHash||!m||m.contentHash!==d.contentHash||!t.graderEvidenceRefs.some(f=>f.id===d.id&&f.contentHash===d.contentHash))throw new Error("Profile evaluation case evidence differs from its retained run.");return{taskId:r.taskId,seed:r.seed,receiptId:t.id,receiptHash:t.contentHash,traceHash:t.traceHash,outputHash:t.outputHash,score:m.score,passed:m.passed,gradingStatus:m.gradingStatus,failureClass:m.failureClass,artifactCount:t.artifactRefs.length,latencyMs:t.latencyMs,costUsd:t.costUsd,terminal:t.terminal,feedback:m.components.map(f=>({graderId:f.graderId,graderVersion:f.graderVersion,score:f.score,passed:f.passed,feedback:f.feedback})),...e.receiptId?{receipt:t,evidence:await _({store:e.store,profileRef:e.profileRef,manifest:i,receipt:t,eventAfterId:e.eventAfterId,eventLimit:e.eventLimit})}:{}}}));return{runId:i.id,sourceRevision:i.profileEvaluation?.sourceRevision??null,cases:u}}R(D,"inspectProfileEvaluationRun");export{j as a,W as b,D as c};
2
+ import{b}from"./chunk-UCPD526R.js";import{ja as M}from"./chunk-2THZ6GZY.js";import{Qb as x,m as T,v as A}from"./chunk-D6L6UNUQ.js";import{n as c,o as S}from"./chunk-RCT3O3HQ.js";import{A as I}from"./chunk-X2J2P5ZT.js";import{a as R}from"./chunk-FTQLQJQV.js";function j(e,a,i){if(a==="agent_action"){let n=e.find(u=>u.name==="workspace_action_result"&&u.action==="profile_workflow_action")?.output;if(typeof n!="string")throw new Error("Profile Agent action evaluation did not produce a released action result.");return n}if(i==="completed"){let n=[...e].reverse().find(s=>s.name==="turn.completed"),r=n?.data?.providerResponse,o=n?.data;if(!r&&o?.turn?.status==="completed"){let s=[...e].reverse().find(t=>P(t)!==null);if(!s)throw new Error("Native Profile evaluation has no retained final answer.");let d=P(s);return e.filter(t=>P(t)===d).map(t=>t.output??"").join("")}if(typeof r?.requestId!="string"||!r.requestId||typeof r.contentHash!="string")throw new Error("Profile evaluation has no retained final provider response.");let p=e.filter(s=>s.name==="assistant.delta"&&s.data?.providerRequestId===r.requestId).map(s=>s.output??"").join("");if(c(p)!==r.contentHash)throw new Error("Profile evaluation final provider response differs from its retained trace.");return b(e)??p}return e.filter(n=>n.name==="assistant.delta"&&typeof n.output=="string").map(n=>n.output??"").join("")}R(j,"profileEvaluationOutput");function P(e){let a=e.data;return e.name==="assistant.delta"&&a?.provider==="codex"&&a.phase==="final_answer"&&typeof a.itemId=="string"?a.itemId:null}R(P,"nativeFinalAnswerItemId");async function _(e){let{store:a,manifest:i,receipt:n}=e;if(!n.metadata.retainedEvidenceRef)return null;let u=x.parse(n.metadata.retainedEvidenceRef),[r,o]=await Promise.all([a.getSession(u.sessionId),a.getTurn(u.turnId)]),p=r?.metadata?.profileEvaluationRun,s=i.profileEvaluation;if(!r||!o||o.sessionId!==r.id||!s||!r.currentProfile||c(r.currentProfile)!==c(e.profileRef)||c(p)!==c({id:i.id,contentHash:i.contentHash})||r.metadata?.taskId!==n.taskId||r.metadata?.seed!==n.seed||!o.completedAt||o.completedAt!==n.completedAt||o.startedAt!==n.startedAt||!o.harnessSnapshot||o.harnessSnapshot.harnessRelease.id!==s.harnessRelease.id||o.harnessSnapshot.harnessRelease.contentHash!==s.harnessRelease.contentHash||i.policy.kind!=="model"||!o.modelRef||o.modelRef.providerId!==i.policy.model.provider||o.modelRef.modelId!==i.policy.model.model)throw new Error("Retained Profile policy turn differs from its admitted case.");let d=await a.runtimeEventsForTurn(o.id);if(d.some(v=>v.turnId!==o.id)||c(d)!==n.traceHash)throw new Error("Retained Profile policy trace differs from its immutable receipt.");let t=j(d,s.target.kind,o.status);if(n.outputHash!==null&&c({text:t})!==n.outputHash)throw new Error("Retained Profile output differs from its immutable receipt.");let m=n.artifactRefs.flatMap(v=>{let y=d.filter(l=>(l.action==="work_output_save"||l.action==="sandbox_save_output")&&l.status==="completed").flatMap(l=>{let C=l.data&&typeof l.data=="object"?l.data:{},k=M.safeParse(C.outputRef);return k.success?[k.data]:[]}).filter(l=>l.sourceTaskId===r.id&&l.sourceTurnId===o.id&&`${r.id}/${l.id}/${l.revision}/${l.title}`===v.id&&l.sha256===v.contentHash&&l.sizeBytes===v.sizeBytes&&l.contentType===v.mediaType);if(y.length!==1)throw new Error("The case output has no unique sealed saved-file identity.");let h=y[0];if(h.location.kind!=="managed")return[];let H=`/api/work/outputs/${encodeURIComponent(h.location.fileId)}`;if(h.location.downloadPath!==H)throw new Error("The saved output has no canonical managed download route.");return[{id:h.id,title:h.title,revision:h.revision,contentType:h.contentType,sizeBytes:h.sizeBytes,sha256:h.sha256,downloadPath:H}]}),f=await a.listModelUsageRecords({sessionId:r.id,turnId:o.id,limit:1e4}),E=e.eventAfterId?d.findIndex(v=>v.id===e.eventAfterId):-1;if(e.eventAfterId&&E<0)throw new Error("Profile trace cursor is unavailable in this case.");let g=E+1,q=Math.max(1,Math.min(250,e.eventLimit??100)),w=d.slice(g,g+q);return{ref:u,prompt:o.prompt,output:n.outputHash===null?null:{text:t},partialOutput:n.outputHash===null&&t?{text:t}:null,error:o.error,events:w,eventCount:d.length,nextEventCursor:g+w.length<d.length?w.at(-1).id:null,files:m,usage:f,usageCoverage:f.length===1e4?"partial":"complete"}}R(_,"readProfileEvaluationPolicyEvidence");var W=I.object({runId:I.string().trim().min(1).max(240),receiptId:I.string().trim().min(1).max(500).optional(),eventAfterId:I.string().trim().min(1).max(500).optional(),eventLimit:I.number().int().min(1).max(250).optional(),manifest:A.optional()}).strict().refine(e=>e.receiptId||!e.eventAfterId&&!e.eventLimit,"Select a case before requesting its trace page.").refine(e=>!e.manifest||e.receiptId,"Interrupted-run inspection requires one exact case.");async function D(e){let a=await e.store.getProfileEvaluationRun(e.runId);if(a&&c(a.profileRef)!==c(e.profileRef))throw new Error("Profile evaluation run is unavailable in the selected Profile.");let i=a?.manifest??e.manifest;if(!i||!a&&!e.receiptId)throw new Error("Profile evaluation run is unavailable in the selected Profile.");if(a){if(e.manifest&&e.manifest.contentHash!==a.manifest.contentHash)throw new Error("Profile evaluation run differs from its pinned manifest.")}else if(S(i,"Interrupted Profile evaluation manifest"),i.id!==e.runId||i.profileEvaluation?.profileId!==e.profileRef.profileId||e.profileRef.source==="openpond_git"&&i.metadata.profileRepositoryId!==e.profileRef.repositoryId)throw new Error("Profile evaluation run is unavailable in the selected Profile.");let n=i.population.map((r,o)=>({member:r,index:o})).filter(({member:r})=>!e.receiptId||r.receiptId===e.receiptId);if(e.receiptId&&n.length!==1)throw new Error("Profile evaluation case is unavailable in the selected run.");let u=await Promise.all(n.map(async({member:r,index:o})=>{let p=a?null:await e.store.getProfileEvaluationReceipt(r.receiptId),s=a?.receiptRefs[o]??(p?{id:p.id,contentHash:p.contentHash}:null),d=a?.gradeRefs[o]??p?.graderEvidenceRefs[0];if(!s||!d)throw new Error("Profile evaluation run has incomplete case evidence.");let[t,m]=await Promise.all([e.store.getProfileEvaluationReceipt(s.id),e.store.getProfileEvaluationGrade(d.contentHash)]);if(!t||!a&&!T(t)||t.contentHash!==s.contentHash||t.id!==r.receiptId||t.taskId!==r.taskId||t.seed!==r.seed||t.runManifest.id!==i.id||t.runManifest.contentHash!==i.contentHash||!m||m.contentHash!==d.contentHash||!t.graderEvidenceRefs.some(f=>f.id===d.id&&f.contentHash===d.contentHash))throw new Error("Profile evaluation case evidence differs from its retained run.");return{taskId:r.taskId,seed:r.seed,receiptId:t.id,receiptHash:t.contentHash,traceHash:t.traceHash,outputHash:t.outputHash,score:m.score,passed:m.passed,gradingStatus:m.gradingStatus,failureClass:m.failureClass,artifactCount:t.artifactRefs.length,latencyMs:t.latencyMs,costUsd:t.costUsd,terminal:t.terminal,feedback:m.components.map(f=>({graderId:f.graderId,graderVersion:f.graderVersion,score:f.score,passed:f.passed,feedback:f.feedback})),...e.receiptId?{receipt:t,evidence:await _({store:e.store,profileRef:e.profileRef,manifest:i,receipt:t,eventAfterId:e.eventAfterId,eventLimit:e.eventLimit})}:{}}}));return{runId:i.id,sourceRevision:i.profileEvaluation?.sourceRevision??null,cases:u}}R(D,"inspectProfileEvaluationRun");export{j as a,W as b,D as c};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{Gg as l,Jg as h,Kg as E,Lg as w,Rg as f,aa as d,fe as u,ra as p}from"./chunk-6D3FI2XT.js";import{c as i,f as m,h as g}from"./chunk-3M53YXEI.js";import{a as c}from"./chunk-FTQLQJQV.js";var M=new Set(["hosted-engram-capability","hosted-compile-engram","hosted-prepare-engram","hosted-start-engram","hosted-cancel-engram","hosted-engram-execution","hosted-engram-executions","hosted-save-engram-model","hosted-control-engram-serving"]);async function k(x){let{action:r,target:s,teamId:n,options:o,client:t,readInput:y}=x;if(r==="hosted-engram-execution"){if(!s)throw new Error("Supply the original Engram execution ID.");return t.getEngramExecution(n,s)}if(r==="hosted-engram-executions"){if(s)throw new Error("List Engram executions using filters.");let e=f.parse(Object.fromEntries(Object.entries({id:i(o,"id")||void 0,projectId:i(o,"projectId")||void 0,phase:i(o,"phase")||void 0,cursor:i(o,"cursor")||void 0,limit:g(o.limit,"--limit")}).filter(([,I])=>I!==void 0)));return t.listEngramExecutions(n,e)}let a=await y();if(r==="hosted-control-engram-serving"){let e=p.parse(a);if(e.request.teamId!==n)throw new Error("Use the Model's original workspace.");if(e.request.action==="activate"&&!m(o.yes))throw new Error("Activating billed serving capacity requires --yes.");return t.controlEngramModelServing(e.modelProjectId,e.request)}if(r==="hosted-engram-capability"){let e=u.parse(a);if(e.teamId!==n)throw new Error("Use this input's original workspace.");return t.engramExecutionCapability(e)}if(r==="hosted-compile-engram"){let e=l.parse(a);if(e.teamId!==n)throw new Error("Use this input's original workspace.");return t.compileEngramExecution(e)}if(r==="hosted-prepare-engram"){let e=h.parse(a);if(e.teamId!==n)throw new Error("Use this input's original workspace.");return t.prepareEngramExecution(e)}if(r==="hosted-start-engram"){let e=E.parse(a);if(e.teamId!==n)throw new Error("Use this execution's original workspace.");if(!m(o.yes))throw new Error("Starting paid Engram training requires --yes.");return t.startEngramExecution(e)}if(r==="hosted-cancel-engram"){let e=w.parse(a);if(e.teamId!==n)throw new Error("Use this execution's original workspace.");return t.cancelEngramExecution(e)}if(r==="hosted-save-engram-model"){let e=d.parse(a);if(e.teamId!==n)throw new Error("Use this result's original workspace.");return t.saveEngramResultModel(e)}throw new Error("Unsupported Engram command.")}c(k,"runHostedEngramCommand");export{M as a,k as b};
2
+ import{Hg as l,Kg as h,Lg as E,Mg as w,Sg as f,aa as d,fe as u,ra as p}from"./chunk-AWD72O3G.js";import{c as i,f as m,h as g}from"./chunk-3M53YXEI.js";import{a as c}from"./chunk-FTQLQJQV.js";var M=new Set(["hosted-engram-capability","hosted-compile-engram","hosted-prepare-engram","hosted-start-engram","hosted-cancel-engram","hosted-engram-execution","hosted-engram-executions","hosted-save-engram-model","hosted-control-engram-serving"]);async function k(x){let{action:r,target:s,teamId:n,options:o,client:t,readInput:y}=x;if(r==="hosted-engram-execution"){if(!s)throw new Error("Supply the original Engram execution ID.");return t.getEngramExecution(n,s)}if(r==="hosted-engram-executions"){if(s)throw new Error("List Engram executions using filters.");let e=f.parse(Object.fromEntries(Object.entries({id:i(o,"id")||void 0,projectId:i(o,"projectId")||void 0,phase:i(o,"phase")||void 0,cursor:i(o,"cursor")||void 0,limit:g(o.limit,"--limit")}).filter(([,I])=>I!==void 0)));return t.listEngramExecutions(n,e)}let a=await y();if(r==="hosted-control-engram-serving"){let e=p.parse(a);if(e.request.teamId!==n)throw new Error("Use the Model's original workspace.");if(e.request.action==="activate"&&!m(o.yes))throw new Error("Activating billed serving capacity requires --yes.");return t.controlEngramModelServing(e.modelProjectId,e.request)}if(r==="hosted-engram-capability"){let e=u.parse(a);if(e.teamId!==n)throw new Error("Use this input's original workspace.");return t.engramExecutionCapability(e)}if(r==="hosted-compile-engram"){let e=l.parse(a);if(e.teamId!==n)throw new Error("Use this input's original workspace.");return t.compileEngramExecution(e)}if(r==="hosted-prepare-engram"){let e=h.parse(a);if(e.teamId!==n)throw new Error("Use this input's original workspace.");return t.prepareEngramExecution(e)}if(r==="hosted-start-engram"){let e=E.parse(a);if(e.teamId!==n)throw new Error("Use this execution's original workspace.");if(!m(o.yes))throw new Error("Starting paid Engram training requires --yes.");return t.startEngramExecution(e)}if(r==="hosted-cancel-engram"){let e=w.parse(a);if(e.teamId!==n)throw new Error("Use this execution's original workspace.");return t.cancelEngramExecution(e)}if(r==="hosted-save-engram-model"){let e=d.parse(a);if(e.teamId!==n)throw new Error("Use this result's original workspace.");return t.saveEngramResultModel(e)}throw new Error("Unsupported Engram command.")}c(k,"runHostedEngramCommand");export{M as a,k as b};