openpond 0.2.45 → 0.2.46

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 (238) hide show
  1. package/RELEASE.md +16 -13
  2. package/dist/app-server.d.ts +10474 -10090
  3. package/dist/app-server.js +1 -1
  4. package/dist/chunks/actions-command-I3NI75P2.js +2 -0
  5. package/dist/chunks/{app-layer-MDJFV3HZ.js → app-layer-B3SMVO4B.js} +1 -1
  6. package/dist/chunks/app-server-runtime-FL2CHQU2.js +2 -0
  7. package/dist/chunks/apps-OA2VX34V.js +2 -0
  8. package/dist/chunks/{chunk-4EGDKOYP.js → chunk-33AO3P6X.js} +1 -1
  9. package/dist/chunks/chunk-4UTIEH5H.js +16 -0
  10. package/dist/chunks/{chunk-J65BMG5Q.js → chunk-4VKNBADF.js} +1 -1
  11. package/dist/chunks/{chunk-B6LYKEMU.js → chunk-5OGRWWEH.js} +1 -1
  12. package/dist/chunks/chunk-5ZZM3TUN.js +24 -0
  13. package/dist/chunks/chunk-6JBWHR6T.js +5 -0
  14. package/dist/chunks/{chunk-DXAZUJPA.js → chunk-6SJZXZNA.js} +1 -1
  15. package/dist/chunks/{chunk-TVQE3JMI.js → chunk-6WLJWRMF.js} +1 -1
  16. package/dist/chunks/chunk-BKMGBIBT.js +2 -0
  17. package/dist/chunks/chunk-BQNK2NMB.js +21 -0
  18. package/dist/chunks/{chunk-VESOG2SS.js → chunk-BUFQKDAW.js} +1 -1
  19. package/dist/chunks/{chunk-DWGB536R.js → chunk-D6E7JBBQ.js} +7 -7
  20. package/dist/chunks/chunk-D6MQTNJ3.js +9 -0
  21. package/dist/chunks/chunk-DNXKIIV7.js +3 -0
  22. package/dist/chunks/{chunk-EG55BFQ4.js → chunk-EWS7MXTM.js} +1 -1
  23. package/dist/chunks/{chunk-GEDEVI4Y.js → chunk-F2AG46CV.js} +1 -1
  24. package/dist/chunks/{chunk-CR6CDOKS.js → chunk-F5DUN73H.js} +2 -2
  25. package/dist/chunks/chunk-FKCWOASO.js +49 -0
  26. package/dist/chunks/chunk-FOEUDMME.js +2678 -0
  27. package/dist/chunks/chunk-H6W55CQG.js +2 -0
  28. package/dist/chunks/chunk-HK3WGUKK.js +17 -0
  29. package/dist/chunks/{chunk-25GCTLAZ.js → chunk-HO5L2FUU.js} +1 -1
  30. package/dist/chunks/{chunk-XPB6NY7L.js → chunk-HP2D3W2B.js} +3 -3
  31. package/dist/chunks/chunk-ICZEOMPO.js +2 -0
  32. package/dist/chunks/{chunk-IYRHG54Q.js → chunk-IV7F74JJ.js} +1 -1
  33. package/dist/chunks/{chunk-U6SFIFDM.js → chunk-JBHAU7PH.js} +39 -39
  34. package/dist/chunks/chunk-JO7GRBOG.js +2 -0
  35. package/dist/chunks/{chunk-KPDWQCF6.js → chunk-KE5RH6JA.js} +1 -1
  36. package/dist/chunks/chunk-KUKOZJIR.js +2 -0
  37. package/dist/chunks/chunk-L4BYPZ4U.js +22 -0
  38. package/dist/chunks/{chunk-Z2BYC6TP.js → chunk-LZSY5IM3.js} +1 -1
  39. package/dist/chunks/{chunk-TNXILYI6.js → chunk-M7PBDRKC.js} +1 -1
  40. package/dist/chunks/{chunk-OJVIH7J6.js → chunk-MCRA6ZGJ.js} +1 -1
  41. package/dist/chunks/{chunk-YWX7FKLM.js → chunk-OGXSE57Z.js} +1 -1
  42. package/dist/chunks/{chunk-HZP5U2AA.js → chunk-P653BXMY.js} +1 -1
  43. package/dist/chunks/chunk-PMZH2TKS.js +4 -0
  44. package/dist/chunks/chunk-TYWBEJOA.js +3 -0
  45. package/dist/chunks/chunk-USWZ3KUC.js +2 -0
  46. package/dist/chunks/chunk-UWO34HP6.js +33 -0
  47. package/dist/chunks/{chunk-5ZFEQLRI.js → chunk-VW7D3DRM.js} +1 -1
  48. package/dist/chunks/chunk-W4IL6TWB.js +186 -0
  49. package/dist/chunks/chunk-WVNN3RB2.js +2 -0
  50. package/dist/chunks/{chunk-VVV5I22A.js → chunk-WWABOVRW.js} +2 -2
  51. package/dist/chunks/{chunk-B3O2GAQH.js → chunk-XLDW5NN3.js} +1 -1
  52. package/dist/chunks/chunk-YSYXIJ46.js +8 -0
  53. package/dist/chunks/{chunk-V62BHD5G.js → chunk-ZC57DX6D.js} +1 -1
  54. package/dist/chunks/{chunk-FXIUKYUR.js → chunk-ZJY2L43W.js} +3 -3
  55. package/dist/chunks/cli-5QR7QNQJ.js +2 -0
  56. package/dist/chunks/{configuration-command-75ZCMZ6X.js → configuration-command-MVZS625X.js} +1 -1
  57. package/dist/chunks/connected-evidence-7LHUZ2UI.js +2 -0
  58. package/dist/chunks/{continual-WWPXK2LO.js → continual-K5JNHNQH.js} +3 -3
  59. package/dist/chunks/core-commands-J2SJM5I5.js +2 -0
  60. package/dist/chunks/datasets-KDN2EXHE.js +2 -0
  61. package/dist/chunks/desktop-test-WIOEKMPR.js +3 -0
  62. package/dist/chunks/dist-3MTJ7VM6.js +2 -0
  63. package/dist/chunks/{dist-ELWB75PL.js → dist-JBE7DPFZ.js} +1 -1
  64. package/dist/chunks/evaluation-coordination-NGYHL7HG.js +2 -0
  65. package/dist/chunks/experiment-improvements-2M7GRGWS.js +2 -0
  66. package/dist/chunks/experiments-B6CRZ3GI.js +2 -0
  67. package/dist/chunks/{extension-3M2CSWZB.js → extension-RZTMK3ON.js} +1 -1
  68. package/dist/chunks/{help-RLRU33WN.js → help-EISFHH2F.js} +1 -1
  69. package/dist/chunks/hosted-experiment-improvement-6CHH65DX.js +3 -0
  70. package/dist/chunks/hosted-harness-runtime-PAYMAXH7.js +2 -0
  71. package/dist/chunks/hosted-profile-candidate-HYEISIAC.js +3 -0
  72. package/dist/chunks/hosted-profile-compiler-KQREWJA5.js +2 -0
  73. package/dist/chunks/hosted-profile-evaluation-control-LV6YXOG7.js +2 -0
  74. package/dist/chunks/hosted-profile-evaluation-inspection-A62UYFEP.js +3 -0
  75. package/dist/chunks/hosted-profile-evaluation-preparation-OR4OLYEX.js +3 -0
  76. package/dist/chunks/human-review-J6JGNRBR.js +2 -0
  77. package/dist/chunks/import-YHSX6SBZ.js +4 -0
  78. package/dist/chunks/learning-REL6GGNA.js +2 -0
  79. package/dist/chunks/opchat-CUZUU2WM.js +3 -0
  80. package/dist/chunks/organizations-VT27V4B2.js +2 -0
  81. package/dist/chunks/{profile-DC4UEVVG.js → profile-N2E5ASHQ.js} +1 -1
  82. package/dist/chunks/project-agent-XMXOBJSC.js +2 -0
  83. package/dist/chunks/sandbox-command-NC665ZZ5.js +2 -0
  84. package/dist/chunks/{sandbox-template-DFHWHCIQ.js → sandbox-template-OTP6S3RU.js} +1 -1
  85. package/dist/chunks/src-TNWF3IC5.js +329 -0
  86. package/dist/chunks/{src-CREVQF7M.js → src-WM35IF4W.js} +5 -5
  87. package/dist/chunks/{taskset-TB2ICAZU.js → taskset-COAPMTT3.js} +1 -1
  88. package/dist/chunks/{teams-bot-BNBL57S5.js → teams-bot-ACWJ7PJP.js} +1 -1
  89. package/dist/chunks/{training-FW5FOGR3.js → training-4JUK7YQV.js} +1 -1
  90. package/dist/cli.js +1 -1
  91. package/dist/index.js +1 -1
  92. package/dist/web/assets/App-CdDQ-lXE.css +1 -0
  93. package/dist/web/assets/App-D2f8_mGk.js +235 -0
  94. package/dist/web/assets/{AppDialog-Cgn_fTGR.js → AppDialog-CaxeNfsu.js} +1 -1
  95. package/dist/web/assets/{AppTerminalPanel-cNYkSvM2.js → AppTerminalPanel-dtK0ZPer.js} +2 -2
  96. package/dist/web/assets/{AppsView-9zpKBSLv.js → AppsView-DwK1UBJP.js} +1 -1
  97. package/dist/web/assets/BrowserSidebar-Cj9VnkgU.js +1 -0
  98. package/dist/web/assets/{CartesianChart-Bg3Lm5mZ.js → CartesianChart-Drfk6jTn.js} +1 -1
  99. package/dist/web/assets/{CollaborationTabs-BIfgIy5X.js → CollaborationTabs-Czh2noeb.js} +1 -1
  100. package/dist/web/assets/{CommandMenu-D9BimyPx.js → CommandMenu-D-M-xomh.js} +1 -1
  101. package/dist/web/assets/CommunityView-BrdxUI5Z.js +1 -0
  102. package/dist/web/assets/ComposerCreateImproveStrip-CJ8nkYJf.js +1 -0
  103. package/dist/web/assets/GetStartedView-u7Jw7YA1.js +1 -0
  104. package/dist/web/assets/HostedModelLearningReview-D0a2nwse.js +1 -0
  105. package/dist/web/assets/HostedModelLearningSettings-CQQGyjxi.js +1 -0
  106. package/dist/web/assets/LabModelVersionDetailPage-Cxlc4sSC.js +1 -0
  107. package/dist/web/assets/LabSkillSidebar-BnJkDb0c.js +1 -0
  108. package/dist/web/assets/LabsRoute-hHwZNbqN.js +99 -0
  109. package/dist/web/assets/MainChatThread-r_TYiTnW.js +2 -0
  110. package/dist/web/assets/MainPane-DJcd4tPk.js +19 -0
  111. package/dist/web/assets/MainPane-DOWsSew1.css +1 -0
  112. package/dist/web/assets/{MarkdownText-De0WzrEw.js → MarkdownText-BxPHz4je.js} +1 -1
  113. package/dist/web/assets/{NativeSkillSidebar-B4jtf5RO.js → NativeSkillSidebar-CCHK6kMG.js} +1 -1
  114. package/dist/web/assets/{NewExperienceSwitcher-Bg1DVr96.js → NewExperienceSwitcher-CuKWTDZj.js} +1 -1
  115. package/dist/web/assets/{NewProjectDialog-i_wvIBw-.js → NewProjectDialog-CS6sw2oD.js} +1 -1
  116. package/dist/web/assets/OutputsPage-JDM5bfLJ.js +1 -0
  117. package/dist/web/assets/{ProjectsPage-BD0eml0M.js → ProjectsPage-B3zTBHOA.js} +1 -1
  118. package/dist/web/assets/RightChatPanelStack-L8S3yj1u.js +1 -0
  119. package/dist/web/assets/{RightSidebarHomePanel-BTpU5wGh.js → RightSidebarHomePanel-BWJQKFUp.js} +1 -1
  120. package/dist/web/assets/ScheduledWorkPage-qX12p4B0.js +1 -0
  121. package/dist/web/assets/SettingsView-0KMs-r2I.js +9 -0
  122. package/dist/web/assets/SettingsView-CVsuQeCZ.css +1 -0
  123. package/dist/web/assets/{TeamChatView-5LjuRNd6.js → TeamChatView-DakXCNQE.js} +2 -2
  124. package/dist/web/assets/{TerminalOverlay-BCWBSotQ.js → TerminalOverlay-DaonK5C0.js} +12 -12
  125. package/dist/web/assets/{TrainingCreationPanel-hvOHRVJx.js → TrainingCreationPanel-CUvSsSwp.js} +1 -1
  126. package/dist/web/assets/{TrainingDraftPanel-CGEHGljE.js → TrainingDraftPanel-DNivtVwd.js} +1 -1
  127. package/dist/web/assets/{UsageSettingsSection-B8nbqhag.js → UsageSettingsSection-rbmuoPoE.js} +1 -1
  128. package/dist/web/assets/WorkSidebarPanel-DrYt9xzv.js +1 -0
  129. package/dist/web/assets/WorkspaceDiffPanel-CThoTqe4.js +14 -0
  130. package/dist/web/assets/WorkspaceEnvironmentMenu-DeODKxvW.js +32 -0
  131. package/dist/web/assets/{WorkspaceGitDialogs-Dyx4Rbiy.js → WorkspaceGitDialogs-CBarJYF-.js} +1 -1
  132. package/dist/web/assets/{WorkspaceMonacoEditor-B1dKexHo.js → WorkspaceMonacoEditor-Hmu5m_sO.js} +3 -3
  133. package/dist/web/assets/{arrow-up-right-CCj7SOGp.js → arrow-up-right-BV2IHfb9.js} +1 -1
  134. package/dist/web/assets/chunk-YTGRET2L-PKzEfYnf.js +1 -0
  135. package/dist/web/assets/{clipboard-BY6ELc9Z.js → clipboard-DDIvAWKp.js} +1 -1
  136. package/dist/web/assets/{cloud-upload-BOka5EKK.js → cloud-upload-Dv6kFnfC.js} +1 -1
  137. package/dist/web/assets/{cssMode-C34j8ti5.js → cssMode-BK0jFqWW.js} +1 -1
  138. package/dist/web/assets/{folder-open-CX2jidFj.js → folder-open-B9ixJQJX.js} +1 -1
  139. package/dist/web/assets/{folder-plus-Dh2Q9LP3.js → folder-plus-DqSKvtNB.js} +1 -1
  140. package/dist/web/assets/{git-commit-horizontal-CfevriuT.js → git-commit-horizontal-C1lQvfxe.js} +1 -1
  141. package/dist/web/assets/{htmlMode-BORwVkZg.js → htmlMode-CCV301b6.js} +1 -1
  142. package/dist/web/assets/index-1cMIFBxZ.css +1 -0
  143. package/dist/web/assets/{index-BBjRfC--.js → index-DIaKfM8a.js} +2 -2
  144. package/dist/web/assets/{info-Bv3dbs3G.js → info-BEvaynAD.js} +1 -1
  145. package/dist/web/assets/{jsonMode-BYWtZ6AK.js → jsonMode-Co4pyN4F.js} +1 -1
  146. package/dist/web/assets/{lspLanguageFeatures-CEAdFSpU.js → lspLanguageFeatures-CSU0G5da.js} +1 -1
  147. package/dist/web/assets/{minimize-2-MhorZwY5.js → minimize-2-DT8t8wwP.js} +1 -1
  148. package/dist/web/assets/{monaco.contribution-CDhPpbIo.js → monaco.contribution-CBwGIQY1.js} +2 -2
  149. package/dist/web/assets/{monaco.contribution-ZUUVx_3M.js → monaco.contribution-Cr0AaHCD.js} +2 -2
  150. package/dist/web/assets/{monaco.contribution-CN7AWJNd.js → monaco.contribution-DSBAb_PC.js} +2 -2
  151. package/dist/web/assets/{monaco.contribution-DHA7FuJX.js → monaco.contribution-DUZrs1D-.js} +2 -2
  152. package/dist/web/assets/{monitor-DLcrkfM5.js → monitor-DGqnfsK9.js} +1 -1
  153. package/dist/web/assets/play-C1XWyKh6.js +1 -0
  154. package/dist/web/assets/{python-CXwvPmc4.js → python-Z1foxLdf.js} +1 -1
  155. package/dist/web/assets/{save-DaN65kMq.js → save-CX2kF74j.js} +1 -1
  156. package/dist/web/assets/{square-zRgIUdSv.js → square-DMkXeYeV.js} +1 -1
  157. package/dist/web/assets/{toggleHighContrast-DWeRZFzr.js → toggleHighContrast-CRMVp779.js} +1 -1
  158. package/dist/web/assets/{tsMode-nLBhKngY.js → tsMode-Czu8YAqh.js} +1 -1
  159. package/dist/web/assets/{upload-BfUu4Eu1.js → upload-giKOPnl1.js} +1 -1
  160. package/dist/web/assets/{useLocalAgentSchedules-BCITWhg2.js → useLocalAgentSchedules-BHxWmOeC.js} +1 -1
  161. package/dist/web/assets/{useSessionTurnCache-BQMWfV8u.js → useSessionTurnCache-CUYFsu_W.js} +1 -1
  162. package/dist/web/assets/{wifi-off-bdka5es5.js → wifi-off-DbDXaV1N.js} +1 -1
  163. package/dist/web/assets/{workers-z7XHFFNs.js → workers-Cno4XklJ.js} +1 -1
  164. package/dist/web/assets/{yaml-BTr4i4DD.js → yaml-C28t_C6h.js} +1 -1
  165. package/dist/web/index.html +2 -2
  166. package/docs/command-reference.md +22 -0
  167. package/package.json +1 -2
  168. package/dist/chunks/actions-command-CRDLSPFA.js +0 -2
  169. package/dist/chunks/app-server-runtime-PJONTCCO.js +0 -2
  170. package/dist/chunks/apps-MD2DKEDW.js +0 -2
  171. package/dist/chunks/chunk-3BJ4P5LI.js +0 -520
  172. package/dist/chunks/chunk-3SRIPOJQ.js +0 -2
  173. package/dist/chunks/chunk-65BW2QXY.js +0 -2
  174. package/dist/chunks/chunk-6BL2ZIAP.js +0 -184
  175. package/dist/chunks/chunk-6QUICEQA.js +0 -5
  176. package/dist/chunks/chunk-7D2WMUWK.js +0 -3
  177. package/dist/chunks/chunk-7KIBRK3A.js +0 -4
  178. package/dist/chunks/chunk-ALZRXBEC.js +0 -33
  179. package/dist/chunks/chunk-CXS3WXL3.js +0 -2
  180. package/dist/chunks/chunk-ELNJUG64.js +0 -17
  181. package/dist/chunks/chunk-H3C4ZYEA.js +0 -16
  182. package/dist/chunks/chunk-HUBI3RUK.js +0 -2
  183. package/dist/chunks/chunk-KOR2AZVB.js +0 -24
  184. package/dist/chunks/chunk-M2YXYBSP.js +0 -2
  185. package/dist/chunks/chunk-MTJNKRXL.js +0 -22
  186. package/dist/chunks/chunk-NXUCGKY2.js +0 -5
  187. package/dist/chunks/chunk-PDIT2QS7.js +0 -8
  188. package/dist/chunks/chunk-QVRNOGAU.js +0 -21
  189. package/dist/chunks/chunk-V6WBSW5Q.js +0 -3
  190. package/dist/chunks/chunk-VFTUP5NQ.js +0 -2
  191. package/dist/chunks/chunk-XWLI7WJH.js +0 -2160
  192. package/dist/chunks/cli-BKBH6FZY.js +0 -2
  193. package/dist/chunks/connected-evidence-UPUVVQ6P.js +0 -2
  194. package/dist/chunks/core-commands-SS2GV7WU.js +0 -2
  195. package/dist/chunks/datasets-TCLXV34N.js +0 -2
  196. package/dist/chunks/desktop-test-7ZHZHUB6.js +0 -3
  197. package/dist/chunks/dist-VDN6E54A.js +0 -2
  198. package/dist/chunks/evaluation-coordination-ZX5GLMRC.js +0 -2
  199. package/dist/chunks/experiment-improvements-O6DCQXCX.js +0 -2
  200. package/dist/chunks/experiments-JOQOBQXY.js +0 -2
  201. package/dist/chunks/hosted-experiment-improvement-IKO677PI.js +0 -3
  202. package/dist/chunks/hosted-harness-runtime-H2Q2SNZT.js +0 -2
  203. package/dist/chunks/hosted-profile-candidate-FHHSLJNO.js +0 -3
  204. package/dist/chunks/hosted-profile-compiler-5B256VV3.js +0 -2
  205. package/dist/chunks/hosted-profile-evaluation-control-Z25TZOW4.js +0 -2
  206. package/dist/chunks/hosted-profile-evaluation-inspection-MFYPLTZQ.js +0 -3
  207. package/dist/chunks/hosted-profile-evaluation-preparation-MAB2PSCC.js +0 -3
  208. package/dist/chunks/human-review-6H3BW7OZ.js +0 -2
  209. package/dist/chunks/learning-Y6WNDVQW.js +0 -2
  210. package/dist/chunks/opchat-3E4FH3DC.js +0 -3
  211. package/dist/chunks/organizations-PRVCUPMN.js +0 -2
  212. package/dist/chunks/project-agent-ZX3CELKI.js +0 -2
  213. package/dist/chunks/sandbox-command-HHQMZK3G.js +0 -2
  214. package/dist/chunks/src-MAZ7OBVY.js +0 -327
  215. package/dist/web/assets/App-BgeSqoRS.css +0 -1
  216. package/dist/web/assets/App-C6EWFrLP.js +0 -227
  217. package/dist/web/assets/BrowserSidebar-Xo21N1ej.js +0 -1
  218. package/dist/web/assets/CommunityView-BoW-yLju.js +0 -1
  219. package/dist/web/assets/ComposerCreateImproveStrip-BIKVEgr1.js +0 -1
  220. package/dist/web/assets/GetStartedView-B99v4-hh.js +0 -1
  221. package/dist/web/assets/HostedModelLearningReview-DEScpX2Z.js +0 -1
  222. package/dist/web/assets/HostedModelLearningSettings-4HT5eEiL.js +0 -1
  223. package/dist/web/assets/LabModelVersionDetailPage-DkYdI7gr.js +0 -1
  224. package/dist/web/assets/LabSkillSidebar-Bp5XYipm.js +0 -1
  225. package/dist/web/assets/LabsRoute-VopO7n34.js +0 -105
  226. package/dist/web/assets/MainChatThread-3Gg0oDZT.js +0 -2
  227. package/dist/web/assets/MainPane-CUqMVG9-.js +0 -19
  228. package/dist/web/assets/OutputsPage-CZiPxLyN.js +0 -1
  229. package/dist/web/assets/RightChatPanelStack-CEBFPHKP.js +0 -1
  230. package/dist/web/assets/ScheduledWorkPage-Y6XGoh-X.js +0 -1
  231. package/dist/web/assets/SettingsView-C7av3zwv.css +0 -1
  232. package/dist/web/assets/SettingsView-Kh14f463.js +0 -9
  233. package/dist/web/assets/WorkSidebarPanel-B6hlPEIs.js +0 -1
  234. package/dist/web/assets/WorkspaceDiffPanel-q8A15-0x.js +0 -14
  235. package/dist/web/assets/WorkspaceEnvironmentMenu-BiFTPWtC.js +0 -32
  236. package/dist/web/assets/chunk-DJWHN7NU-1eQoMoKO.js +0 -1
  237. package/dist/web/assets/index-B9VSiz_z.css +0 -1
  238. package/dist/web/assets/refresh-cw-BTfIxHb3.js +0 -1
@@ -0,0 +1,9 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{b as e}from"./chunk-ES2ISFJC.js";import{a as o}from"./chunk-FTQLQJQV.js";import{createHash as je}from"node:crypto";function B(i){if(i===null||typeof i=="boolean"||typeof i=="string")return i;if(typeof i=="number"){if(!Number.isFinite(i))throw new Error("Canonical JSON cannot encode a non-finite number.");return i}if(Array.isArray(i))return i.map(B);if(typeof i=="object"){let t={};for(let r of Object.keys(i).sort()){let n=i[r];n!==void 0&&(t[r]=B(n))}return t}throw new Error(`Canonical JSON cannot encode ${typeof i}.`)}o(B,"canonicalJson");function j(i){return je("sha256").update(JSON.stringify(B(i)),"utf8").digest("hex")}o(j,"canonicalHash");function Ye(i){if(!i.maxContextTokens||!i.usableContextTokens)return{shouldCompact:!1,projectedTokens:i.projectedTokens,thresholdTokens:Number.MAX_SAFE_INTEGER,usableContextTokens:0,maxContextTokens:0,tokenSource:"heuristic"};let t=Math.max(.01,Math.min(1,(i.triggerPercent??85)/100)),r=Math.max(1,Math.floor(i.usableContextTokens*t));return{shouldCompact:i.projectedTokens>=r,projectedTokens:i.projectedTokens,thresholdTokens:r,usableContextTokens:i.usableContextTokens,maxContextTokens:i.maxContextTokens,tokenSource:"heuristic"}}o(Ye,"agentCompactionDecision");async function Ze(i){await i.started();try{return await i.compact()}catch(t){throw await i.failed(t),t}}o(Ze,"runAgentCompaction");async function et(i){let t=i.host.projectEvents(i.events),r=i.host.selectEvents(t,i.maxContextTokens),{summaryEvents:n,preservedEvents:s,preservedEventIds:c}=r;if(n.length===0)throw new Error("There is not enough prior context to compact.");let l=i.host.normalizeRecords(n),d=i.host.normalizeRecords(s),h=i.host.buildFileLedger(i.host.normalizeRecords(t)),m=i.host.serializeRecords(l,i.host.inputCharBudget(i.maxContextTokens));if(!m.text.trim())throw new Error("There is not enough prior context to compact.");let w=i.host.buildSummaryMessages({serializedHistory:m.text,fileLedger:h}),g=Date.now(),T=(await i.host.streamSummary({model:i.model,messages:w,signal:i.signal})).trim(),N=Date.now()-g;if(!T)throw new Error("Compaction summary was empty.");let f=i.host.estimateProjection({events:t,preservedEvents:s,summary:T}),v=i.host.createMetrics({sourceEvents:t.length,summarizedEvents:n.length,preservedEvents:s.length,sourceRecords:m.sourceRecordCount,includedRecords:m.includedRecordCount,omittedRecords:m.omittedRecordCount,preservedRecords:d.length,truncatedRecords:m.truncatedRecordCount,summaryInputTruncated:m.inputTruncated,sourceSelectionStrategy:m.selectionStrategy,summaryInputChars:m.inputChars,retainedTailTokens:r.retainedTailTokens,retainedTailBudgetTokens:r.retainedTailBudgetTokens,finalProviderContextTokens:f.inputTokensAfter,durationMs:N,fileLedgerEntries:h.length,splitTurnId:r.splitTurnId});return{summary:T,model:i.model,compactedThroughEventId:t[t.length-1]?.id??null,compactedThroughTurnId:i.host.lastTurnId(t),preservedFromEventId:s[0]?.id??null,preservedEventIds:c,preservedResourceRefs:i.host.durableResourceRefs(i.events),sourceEventCount:n.length,preservedEventCount:s.length,fileLedger:h,inputTokensBefore:f.inputTokensBefore,inputTokensAfter:f.inputTokensAfter,maxContextTokens:i.maxContextTokens,tokenSource:"heuristic",metrics:v}}o(et,"runAgentCompactionProgram");var Se=e.enum(["thread.started","thread.resumed","turn.started","turn.steered","turn.interrupted","turn.completed","turn.failed","item.started","item.delta","item.completed","assistant.reasoning.delta","assistant.delta","tool.started","tool.completed","approval.requested","approval.resolved","user_input.requested","user_input.resolved","compaction.started","compaction.completed","harness.admitted","harness.refiner.queued","harness.refiner.started","harness.refiner.completed","harness.refiner.failed","diagnostic"]),Ee=e.object({sequence:e.number().int().nonnegative(),name:Se,source:e.enum(["runtime","provider","tool","host","refiner"]),status:e.string().trim().min(1).nullable().default(null),threadId:e.string().trim().min(1),turnId:e.string().trim().min(1).nullable().default(null),callId:e.string().trim().min(1).nullable().default(null),output:e.string().nullable().default(null),error:e.string().nullable().default(null),data:e.record(e.string(),e.unknown()).default({})}).strict();function st(i){return j(Ee.parse(i))}o(st,"canonicalEventHash");var C="2026-09-20",lt=["initialize","initialized","runtime/capabilities","thread/start","thread/resume","thread/read","turn/start","turn/steer","task/inbox","task/queue","task/inputUpdate","turn/interrupt","approval/resolve","userInput/resolve","profile/workflows","profile/evaluations","profile/trainingSource","profile/evaluations/prepare","profile/evaluations/run","profile/evaluations/runSuite","profile/evaluations/executeCase","profile/evaluations/executeRun","profile/evaluations/compare","profile/evaluations/report","experiments/executeCase","experiments/cancelCase","harness/inspect","harness/proposalReview","harness/review","harness/acceptEvaluationReview","harness/materializeEvaluationTaskset","harness/runEvaluationBaseline","harness/validate","harness/backgroundReview","harness/diff","harness/rollback","refiner/inspect","refiner/update","refiner/activate","refiner/rollback"],Q=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number()]),method:e.string().trim().min(1),params:e.unknown().optional()}).strict(),W=e.object({jsonrpc:e.literal("2.0"),method:e.string().trim().min(1),params:e.unknown().optional()}).strict(),$=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number()]),result:e.unknown()}).strict(),U=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number(),e.null()]),error:e.object({code:e.number().int(),message:e.string(),data:e.unknown().optional()}).strict()}).strict(),ut=e.union([Q,W,$,U]),_e=e.object({protocolVersion:e.string().trim().min(1),client:e.object({name:e.string().trim().min(1),version:e.string().trim().min(1)}).strict(),capabilities:e.record(e.string(),e.unknown()).default({})}).strict(),H=class{static{o(this,"AgentJsonRpcDispatcher")}#e;#t=null;#r=!1;constructor(t){this.#e=t}get initialized(){return this.#r}async handle(t){let r=W.safeParse(t);if(r.success&&!("id"in t)){if(r.data.method==="initialized"){if(!this.#t)throw new S(-32002,"initialize must be called first");this.#r=!0}return null}let n=Q.safeParse(t);if(!n.success)return K(null,-32600,"Invalid Request",n.error.flatten());let s=n.data;try{let c=await this.#n(s.method,s.params);return{jsonrpc:"2.0",id:s.id,result:c}}catch(c){let l=c instanceof S?c:new S(-32603,c instanceof Error?c.message:String(c));return K(s.id,l.code,l.message,l.data)}}async#n(t,r){if(t==="initialize"){let n=_e.parse(r);if(n.protocolVersion!==C)throw new S(-32001,"Incompatible agent protocol version",{requested:n.protocolVersion,supported:C});return this.#t=n,{protocolVersion:C,server:{name:"openpond-app-server",version:"1"},capabilities:await this.#e.capabilities()}}if(!this.#r)throw new S(-32002,"initialized notification is required");switch(t){case"runtime/capabilities":return this.#e.capabilities(r);case"thread/start":return this.#e.threadStart(r);case"thread/resume":return this.#e.threadResume(r);case"thread/read":return this.#e.threadRead(r);case"turn/start":return this.#e.turnStart(r);case"turn/steer":return this.#e.turnSteer(r);case"task/inbox":return this.#e.taskInbox(r);case"task/queue":return this.#e.taskQueue(r);case"task/inputUpdate":return this.#e.taskInputUpdate(r);case"turn/interrupt":return this.#e.turnInterrupt(r);case"approval/resolve":return this.#e.approvalResolve(r);case"userInput/resolve":return this.#e.userInputResolve(r);case"profile/workflows":return this.#e.profileWorkflows(r);case"profile/evaluations":return this.#e.profileEvaluations(r);case"profile/trainingSource":return this.#e.profileTrainingSource(r);case"profile/evaluations/prepare":return this.#e.profileEvaluationPrepare(r);case"profile/evaluations/run":return this.#e.profileEvaluationRun(r);case"experiments/executeCase":{if(!this.#e.experimentExecuteCase)throw new Error("Experiment execution is unavailable in this runtime.");return this.#e.experimentExecuteCase(r)}case"experiments/cancelCase":{if(!this.#e.experimentCancelCase)throw new Error("Experiment cancellation is unavailable in this runtime.");return this.#e.experimentCancelCase(r)}case"profile/evaluations/runSuite":return this.#e.profileEvaluationRunSuite(r);case"profile/evaluations/executeCase":return this.#e.profileEvaluationExecuteCase(r);case"profile/evaluations/executeRun":return this.#e.profileEvaluationExecuteRun(r);case"profile/evaluations/compare":return this.#e.profileEvaluationCompare(r);case"profile/evaluations/report":return this.#e.profileEvaluationReport(r);case"harness/inspect":return this.#e.harnessInspect(r);case"harness/proposalReview":return this.#e.harnessProposalReview(r);case"harness/review":return this.#e.harnessReview(r);case"harness/acceptEvaluationReview":return this.#e.harnessAcceptEvaluationReview(r);case"harness/materializeEvaluationTaskset":return this.#e.harnessMaterializeEvaluationTaskset(r);case"harness/runEvaluationBaseline":return this.#e.harnessRunEvaluationBaseline(r);case"harness/validate":return this.#e.harnessValidate(r);case"harness/backgroundReview":return this.#e.harnessBackgroundReview(r);case"harness/diff":return this.#e.harnessDiff(r);case"harness/rollback":return this.#e.harnessRollback(r);case"refiner/inspect":return this.#e.refinerInspect(r);case"refiner/update":return this.#e.refinerUpdate(r);case"refiner/activate":return this.#e.refinerActivate(r);case"refiner/rollback":return this.#e.refinerRollback(r);default:throw new S(-32601,`Method not found: ${t}`)}}},S=class extends Error{static{o(this,"JsonRpcDispatchError")}code;data;constructor(t,r,n){super(r),this.code=t,this.data=n}};function K(i,t,r,n){return{jsonrpc:"2.0",id:i,error:{code:t,message:r,...n===void 0?{}:{data:n}}}}o(K,"jsonRpcError");var X=class{static{o(this,"AgentRpcClient")}#e;#t;constructor(t){this.#e=t.request.bind(t),this.#t=t.notify.bind(t)}async initialize(t,r={}){let n=await this.#e("initialize",{protocolVersion:C,client:t,capabilities:r});return await this.#t("initialized"),n}capabilities=o((t={})=>this.#e("runtime/capabilities",t),"capabilities");threadStart=o(t=>this.#e("thread/start",t),"threadStart");threadResume=o(t=>this.#e("thread/resume",t),"threadResume");threadRead=o(t=>this.#e("thread/read",t),"threadRead");turnStart=o(t=>this.#e("turn/start",t),"turnStart");turnSteer=o(t=>this.#e("turn/steer",t),"turnSteer");taskInbox=o(t=>this.#e("task/inbox",t),"taskInbox");taskQueue=o(t=>this.#e("task/queue",t),"taskQueue");taskInputUpdate=o(t=>this.#e("task/inputUpdate",t),"taskInputUpdate");turnInterrupt=o(t=>this.#e("turn/interrupt",t),"turnInterrupt");approvalResolve=o(t=>this.#e("approval/resolve",t),"approvalResolve");userInputResolve=o(t=>this.#e("userInput/resolve",t),"userInputResolve");profileWorkflows=o(t=>this.#e("profile/workflows",t),"profileWorkflows");profileEvaluations=o(t=>this.#e("profile/evaluations",t),"profileEvaluations");profileEvaluationPrepare=o(t=>this.#e("profile/evaluations/prepare",t),"profileEvaluationPrepare");profileEvaluationRun=o(t=>this.#e("profile/evaluations/run",t),"profileEvaluationRun");profileEvaluationRunSuite=o(t=>this.#e("profile/evaluations/runSuite",t),"profileEvaluationRunSuite");profileEvaluationExecuteCase=o(t=>this.#e("profile/evaluations/executeCase",t),"profileEvaluationExecuteCase");profileEvaluationExecuteRun=o(t=>this.#e("profile/evaluations/executeRun",t),"profileEvaluationExecuteRun");profileEvaluationCompare=o(t=>this.#e("profile/evaluations/compare",t),"profileEvaluationCompare");experimentExecuteCase=o(t=>this.#e("experiments/executeCase",t),"experimentExecuteCase");experimentCancelCase=o(t=>this.#e("experiments/cancelCase",t),"experimentCancelCase");harnessInspect=o((t={})=>this.#e("harness/inspect",t),"harnessInspect");harnessProposalReview=o((t={})=>this.#e("harness/proposalReview",t),"harnessProposalReview");harnessReview=o((t={})=>this.#e("harness/review",t),"harnessReview");harnessAcceptEvaluationReview=o((t={})=>this.#e("harness/acceptEvaluationReview",t),"harnessAcceptEvaluationReview");harnessMaterializeEvaluationTaskset=o((t={})=>this.#e("harness/materializeEvaluationTaskset",t),"harnessMaterializeEvaluationTaskset");harnessRunEvaluationBaseline=o((t={})=>this.#e("harness/runEvaluationBaseline",t),"harnessRunEvaluationBaseline");harnessValidate=o((t={})=>this.#e("harness/validate",t),"harnessValidate");harnessBackgroundReview=o((t={})=>this.#e("harness/backgroundReview",t),"harnessBackgroundReview");harnessDiff=o((t={})=>this.#e("harness/diff",t),"harnessDiff");harnessRollback=o((t={})=>this.#e("harness/rollback",t),"harnessRollback");refinerInspect=o(t=>this.#e("refiner/inspect",t),"refinerInspect");refinerUpdate=o(t=>this.#e("refiner/update",t),"refinerUpdate");refinerActivate=o(t=>this.#e("refiner/activate",t),"refinerActivate");refinerRollback=o(t=>this.#e("refiner/rollback",t),"refinerRollback")};var J=e.object({caseId:e.string().trim().min(1).max(191),admissionHash:e.string().regex(/^[a-f0-9]{64}$/),definitionHash:e.string().regex(/^[a-f0-9]{64}$/),ordinal:e.number().int().nonnegative(),operation:e.enum(["create","reset","step","collect","destroy"]),value:e.record(e.string(),e.unknown()),timeoutMs:e.number().int().min(1).max(3e4)}).strict();var u=e.string().trim().min(1).max(200),V=e.string().trim().min(1).max(32e3),q=e.number().int().nonnegative(),Y=e.object({id:u,sessionId:u,senderSessionId:u.nullable(),senderKind:e.enum(["user","task","runtime"]),kind:e.enum(["steer","message","followup","queued","result"]),body:V,payload:e.record(e.string(),e.unknown()),idempotencyKey:u,replyTo:u.nullable(),expectedTurnId:u.nullable()}).strict(),Re=e.discriminatedUnion("action",[e.object({action:e.literal("resume"),expectedRevision:e.number().int().positive()}).strict(),e.object({action:e.literal("cancel"),expectedRevision:e.number().int().positive()}).strict(),e.object({action:e.literal("edit"),expectedRevision:e.number().int().positive(),body:V}).strict(),e.object({action:e.literal("steer"),expectedRevision:e.number().int().positive(),expectedTurnId:u}).strict()]),Z=e.object({id:u,sessionId:u,turnId:u,targetSessionId:u.nullable(),targetTurnId:u.nullable(),targetInputId:u.nullable(),afterSequence:q,deadline:e.string(),state:e.enum(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:e.string(),updatedAt:e.string()}).strict(),ee=e.record(e.string(),e.unknown()),Te=e.enum(["queued","running","completed","failed","cancelled","needs_resume"]),Ce=e.object({parentSessionId:u.nullable().optional(),childSessionId:u.nullable().optional(),status:e.array(Te).nullable().optional(),afterId:e.string().max(200),limit:e.number().int().min(1).max(10)}).strict(),te=e.discriminatedUnion("action",[e.object({action:e.literal("recoverTaskInboxOwners"),ownerId:u}).strict(),e.object({action:e.literal("hasTaskCompletion"),turnId:u}).strict(),e.object({action:e.literal("taskInboxSnapshot"),sessionId:u}).strict(),e.object({action:e.literal("taskInboxSnapshotInputs"),sessionId:u,afterSequence:q}).strict(),e.object({action:e.literal("declareTaskWork"),sessionId:u,turnId:u,ownerId:u,areas:e.array(V).max(100)}).strict(),e.object({action:e.literal("taskWorkAreas"),sessionId:u}).strict(),e.object({action:e.literal("admitTaskInput"),input:Y}).strict(),e.object({action:e.literal("admitTaskInputs"),inputs:e.array(Y).max(50)}).strict(),e.object({action:e.literal("rejectTaskInput"),id:u,error:V}).strict(),e.object({action:e.literal("getTaskInput"),id:u}).strict(),e.object({action:e.literal("taskInputsForSession"),sessionId:u,query:e.object({afterSequence:q.optional(),pendingOnly:e.boolean().optional(),limit:e.number().int().min(1).max(500).optional()}).strict()}).strict(),e.object({action:e.literal("mutateTaskInput"),sessionId:u,inputId:u,change:Re}).strict(),e.object({action:e.literal("openTaskInboxTurn"),sessionId:u,turnId:u,ownerId:u}).strict(),e.object({action:e.literal("renewTaskInboxTurn"),sessionId:u,turnId:u,ownerId:u}).strict(),e.object({action:e.literal("pendingTaskInputs"),sessionId:u,turnId:u,afterSequence:q}).strict(),e.object({action:e.literal("taskAssignmentInputs"),turnId:u,afterSequence:q}).strict(),e.object({action:e.literal("pauseTaskInboxTurn"),sessionId:u,turnId:u,ownerId:u}).strict(),e.object({action:e.literal("includeTaskInputs"),sessionId:u,turnId:u,ownerId:u,requestId:u}).strict(),e.object({action:e.literal("settleTaskInputRequest"),requestId:u,outcome:e.enum(["resolved","failed","replaced"])}).strict(),e.object({action:e.literal("sealTaskInboxTurn"),sessionId:u,turnId:u,ownerId:u}).strict(),e.object({action:e.literal("sealNativeTaskInboxTurn"),sessionId:u,turnId:u,ownerId:u}).strict(),e.object({action:e.literal("closeTaskInboxTurn"),sessionId:u,turnId:u,ownerId:u,outcome:e.enum(["completed","failed","interrupted"])}).strict(),e.object({action:e.literal("taskInboxPaused"),sessionId:u}).strict(),e.object({action:e.literal("reserveTaskFollowup"),sessionId:u,turnId:u,ownerId:u}).strict(),e.object({action:e.literal("taskInboxWakeTargets"),afterSessionId:e.string().max(200)}).strict(),e.object({action:e.literal("createTaskWait"),value:Z}).strict(),e.object({action:e.literal("settleTaskWait"),id:u,state:Z.shape.state}).strict(),e.object({action:e.literal("taskWaitsForSession"),sessionId:u,afterId:e.string().max(200)}).strict(),e.object({action:e.literal("commitSubagentCompletion"),value:ee,turnId:u}).strict(),e.object({action:e.literal("pendingTaskCompletions"),afterTurnId:e.string().max(200)}).strict(),e.object({action:e.literal("settleTaskCompletion"),turnId:u,inputId:u}).strict(),e.object({action:e.literal("upsertSubagentRun"),value:ee}).strict(),e.object({action:e.literal("getSubagentRun"),id:u}).strict(),e.object({action:e.literal("listSubagentRuns"),query:Ce}).strict()]);var P=e.string().trim().min(1).max(191),re=e.object({createdAt:e.string().min(1),id:P}).strict(),ne=e.enum(["trigger_decision","route_decision","refiner_outcome","proposal","targeted_validation","apply_receipt"]),ie=e.discriminatedUnion("action",[e.object({action:e.literal("active_release"),workspaceId:P}).strict(),e.object({action:e.literal("put_artifact"),workspaceId:P,kind:ne,artifact:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("artifact_page"),workspaceId:P,kind:ne,before:re.nullable(),limit:e.number().int().min(1).max(200)}).strict(),e.object({action:e.literal("pending_trigger_page"),workspaceId:P,before:re.nullable(),limit:e.number().int().min(1).max(200)}).strict()]);var b=e.string().trim().min(1).max(240),se=e.string().regex(/^[a-f0-9]{64}$/),oe=e.enum(["run_overlay","observation","trigger_decision","route_decision","proposal","targeted_validation","apply_receipt","refiner_outcome"]),ae=e.object({createdAt:e.string().datetime(),id:b}).strict(),ce=e.discriminatedUnion("action",[e.object({action:e.literal("artifact_put"),workspaceId:b,kind:oe,artifact:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("artifact_page"),workspaceId:b,kind:oe,before:ae.nullable(),limit:e.number().int().min(1).max(100)}).strict(),e.object({action:e.literal("pending_page"),workspaceId:b,before:ae.nullable(),limit:e.number().int().min(1).max(100)}).strict(),e.object({action:e.literal("workspace_get"),workspaceId:b}).strict(),e.object({action:e.literal("background_get"),workspaceId:b}).strict(),e.object({action:e.literal("overlay_get"),runId:b}).strict(),e.object({action:e.literal("overlay_freeze"),runId:b,expectedRevision:e.number().int().nonnegative(),overlay:e.record(e.string(),e.unknown()),proposal:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("memory_get"),workspaceId:b,sessionId:b,key:b}).strict(),e.object({action:e.literal("memory_page"),workspaceId:b,sessionId:b,before:e.object({updatedAt:e.string().datetime(),key:b}).strict().nullable(),limit:e.number().int().min(1).max(20),includeDeleted:e.boolean()}).strict(),e.object({action:e.literal("memory_write"),sessionId:b,input:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("release_get"),contentHash:se}).strict(),e.object({action:e.literal("release_put"),record:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("session_get"),sessionId:b}).strict(),e.object({action:e.literal("turn_get"),turnId:b}).strict(),e.object({action:e.literal("turn_page"),sessionId:b,before:e.number().int().positive().nullable(),limit:e.number().int().min(1).max(100)}).strict(),e.object({action:e.literal("event_page"),turnId:b,afterSequence:e.number().int().nonnegative(),names:e.array(b).max(40),limit:e.number().int().min(1).max(100)}).strict(),e.object({action:e.literal("event_append"),event:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("usage_put"),record:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("snapshot_restore"),turnId:b,expectedHash:se,snapshot:e.record(e.string(),e.unknown())}).strict()]);var y=e.string().trim().min(1).max(200),le=e.string().regex(/^[a-f0-9]{64}$/),qe=e.object({kind:e.enum(["structural","visual","test","user_review"]),status:e.enum(["passed","failed","not_run"]),label:e.string().trim().min(1).max(240),detail:e.string().trim().max(4e3).nullable().optional(),ref:e.string().trim().max(4096).nullable().optional()}),ue=e.object({id:y,title:e.string().trim().min(1).max(240),sourceTaskId:y,sourceTurnId:y,revision:e.number().int().positive(),createdAt:e.string().datetime(),contentType:e.string().trim().min(1).max(200),sizeBytes:e.number().int().min(1).max(1e7),sha256:le,validation:e.array(qe).max(32)}).strict(),de=e.object({sessionId:y,turnId:y,output:ue}).strict(),pe=e.object({uploadId:y,index:e.number().int().min(0).max(1024),offset:e.number().int().min(0).max(1e7),sha256:le,contentsBase64:e.string().min(1).max(131072)}).strict(),me=e.object({uploadId:y}).strict(),Pe=ue.pick({id:!0,title:!0,sourceTaskId:!0,sourceTurnId:!0,revision:!0,createdAt:!0,validation:!0}),he=e.object({sessionId:y,turnId:y,output:Pe,sandboxPath:e.string().trim().min(1).max(4096)}).strict();var A=e.string().trim().min(1).max(200),Ae=e.object({type:e.enum(["create","get","start","stop","exec","open_port","list_files","download_file","upload_file","search_files","delete_file","stat_file","mkdir","move_file","process_start","process_get","git_status","git_diff","git_export_patch","git_branch","git_commit","git_pull","git_push"]),sandboxId:A.optional(),payload:e.unknown().optional(),processId:A.optional(),failOnUnpreservedChanges:e.boolean().optional()}).strict().superRefine((i,t)=>{i.type!=="create"&&!i.sandboxId&&t.addIssue({code:"custom",message:"Sandbox identity is required."}),i.type==="create"&&i.sandboxId&&t.addIssue({code:"custom",message:"Create cannot target a sandbox identity."}),i.type==="process_get"&&!i.processId&&t.addIssue({code:"custom",message:"Process identity is required."})}),fe=e.object({action:Ae}).strict(),be=e.object({sessionId:A,turnId:A,name:A}).strict();var p=1,a=e.string().trim().min(1).max(191),E=e.number().int().min(1).max(200),Ht=e.object({teamId:a,ownerUserId:a,workspaceId:a,conversationId:a,turnId:a,attempt:e.number().int().min(1),leaseGeneration:e.number().int().min(1)}).strict(),ge=e.discriminatedUnion("operation",[e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/list"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/read"),params:e.object({fileId:a,revision:e.number().int().min(1),offset:e.number().int().min(0).max(1e7).optional(),maxChars:e.number().int().min(1).max(1e5).optional(),firstPage:e.number().int().min(1).max(1e3).optional(),pageCount:e.number().int().min(1).max(10).optional()}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("profile.externalDataset.authorize"),params:e.object({bindingHash:e.string().regex(/^[a-f0-9]{64}$/),manifestHash:e.string().regex(/^[a-f0-9]{64}$/).optional(),taskId:a.optional(),seed:e.string().min(1).max(500).optional()}).strict().refine(i=>!!i.taskId==!!i.seed,"Case authority requires both task and seed.")}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("experiment/environment"),params:J}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("experiment/policy"),params:e.object({caseId:a,admissionHash:e.string().regex(/^[a-f0-9]{64}$/),ordinal:e.number().int().nonnegative(),messages:e.array(e.record(e.string(),e.unknown())).max(2e3),tools:e.array(e.record(e.string(),e.unknown())).max(200)}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("sandbox/request"),params:fe}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("embedding/authorize"),params:be}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/begin"),params:de}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/chunk"),params:pe}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/complete"),params:me}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/saveSandboxFile"),params:he}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("settings/get"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/get"),params:e.object({reference:e.object({id:a,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict().nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/overlay/get"),params:e.object({runId:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/overlay/put"),params:e.object({runId:a,expectedRevision:e.number().int().min(0).nullable(),overlay:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/overlay/freezeProposal"),params:e.object({runId:a,expectedRevision:e.number().int().min(0),overlay:e.record(e.string(),e.unknown()),proposal:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/memory/get"),params:e.object({workspaceId:a,key:e.string().min(1).max(120)}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/memory/list"),params:e.object({workspaceId:a,includeDeleted:e.boolean(),before:e.object({updatedAt:e.string(),key:e.string()}).strict().nullable(),limit:E}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/memory/search"),params:e.object({workspaceId:a,query:e.string().trim().min(1).max(500),limit:e.number().int().min(1).max(20)}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/memory/write"),params:e.object({input:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/state/read"),params:e.object({workspaceId:a,kind:e.enum(["selection","workspace_settings","evaluation_review_settings","candidates","cross_run_requests"]),afterId:a.nullable(),limit:e.number().int().min(1).max(100)}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("profile-evaluations/execute"),params:e.discriminatedUnion("action",[e.object({action:e.literal("get"),kind:e.enum(["grade","receipt","run","comparison","suite"]),id:a}).strict(),e.object({action:e.literal("page"),kind:e.enum(["grade","receipt","run","comparison","suite"]),profileKey:e.string().regex(/^[a-f0-9]{64}$/),before:e.object({createdAt:e.string(),id:a}).strict().nullable(),limit:e.number().int().min(1).max(100)}).strict(),e.object({action:e.literal("put"),kind:e.enum(["grade","receipt","run","comparison","suite"]),payload:e.record(e.string(),e.unknown()),profileKey:e.string().regex(/^[a-f0-9]{64}$/).nullable(),createdAt:e.string()}).strict()])}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/workspace/transition"),params:e.discriminatedUnion("action",[e.object({action:e.literal("advance"),receiptId:a,workspaceId:a,proposal:e.record(e.string(),e.unknown()),validations:e.array(e.record(e.string(),e.unknown())).max(100),nextRelease:e.object({id:a,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),nextSourceRevision:e.string().min(1),now:e.string()}).strict(),e.object({action:e.literal("reviewedAdvance"),receiptId:a,workspaceId:a,proposal:e.record(e.string(),e.unknown()),validations:e.array(e.record(e.string(),e.unknown())).max(100),nextRelease:e.object({id:a,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),nextSourceRevision:e.string().min(1),reviewer:a,now:e.string()}).strict(),e.object({action:e.literal("rollback"),receiptId:a,workspaceId:a,expectedWorkspaceRevision:e.number().int().nonnegative(),expectedChannelRevision:e.number().int().nonnegative(),targetRelease:e.object({id:a,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),targetSourceRevision:e.string().min(1),rollbackOf:e.object({id:a,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),now:e.string()}).strict()])}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("task-inbox/execute"),params:te}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/review/execute"),params:ce}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("refiner/execute"),params:e.object({action:ie}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("create-improve/execute"),params:e.discriminatedUnion("action",[e.object({action:e.literal("get"),runId:a}).strict(),e.object({action:e.literal("page"),query:e.object({profileId:a.nullable(),targetKind:a.nullable(),targetId:a.nullable(),state:e.array(a).max(20)}).strict(),before:e.object({updatedAt:e.string(),id:a}).strict().nullable(),limit:E}).strict(),e.object({action:e.literal("put"),run:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("mutate"),mutation:e.record(e.string(),e.unknown()),next:e.record(e.string(),e.unknown())}).strict()])}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("approval/get"),params:e.object({approvalId:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("approval/upsert"),params:e.object({approval:e.record(e.string(),e.unknown()),expectedRevision:e.number().int().min(1).nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("usage/getByRequestId"),params:e.object({requestId:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("usage/upsert"),params:e.object({record:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("usage/page"),params:e.object({query:e.object({sessionId:a.optional(),turnId:a.optional(),provider:a.optional(),model:a.optional(),startedAtFrom:e.string().optional(),startedAtTo:e.string().optional(),visibility:e.enum(["user_facing","background","system"]).optional(),status:e.enum(["started","completed","failed","interrupted","missing"]).optional()}).strict(),before:e.object({startedAt:e.string(),requestOrdinal:e.number().int().min(0),id:a}).strict().nullable(),limit:E}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("capabilities"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("session/count"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("session/get"),params:e.object({sessionId:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("session/page"),params:e.object({afterId:a.nullable(),limit:E}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("session/put"),params:e.object({sessionId:a,expectedRevision:e.number().int().min(1).nullable(),session:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("turn/count"),params:e.object({sessionId:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("turn/wakeCount"),params:e.object({sessionId:a,key:e.enum(["messageId","fromRunId"]),value:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("turn/get"),params:e.object({turnId:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("turn/put"),params:e.object({sessionId:a,turnId:a,expectedRevision:e.number().int().min(1).nullable(),turn:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("turn/latest"),params:e.object({sessionId:a,status:e.enum(["in_progress","completed","failed","interrupted"]).nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("turn/page"),params:e.object({sessionId:a,beforeSortIndex:e.number().int().min(0).nullable().optional(),limit:E}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("thread/turnPage"),params:e.object({sessionId:a,beforeSortIndex:e.number().int().min(0).nullable().optional(),limit:E}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("event/append"),params:e.object({event:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("events/page"),params:e.object({sessionId:a.nullable(),afterSequence:e.number().int().min(0),beforeSequence:e.number().int().min(1).nullable().optional(),limit:E,excludeReasoningDeltas:e.boolean().optional()}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("events/latestAssistantText"),params:e.object({sessionId:a}).strict()}).strict()]),Vt=e.object({contractVersion:e.literal(p),operations:e.array(e.enum(["experiment/policy","experiment/environment","sandbox/request","embedding/authorize","output/begin","output/chunk","output/complete","output/saveSandboxFile","output/list","output/read","settings/get","harness/get","harness/overlay/get","harness/overlay/put","harness/overlay/freezeProposal","harness/memory/get","harness/memory/list","harness/memory/search","harness/memory/write","harness/state/read","profile-evaluations/execute","harness/review/execute","harness/workspace/transition","task-inbox/execute","refiner/execute","create-improve/execute","approval/get","approval/upsert","usage/getByRequestId","usage/upsert","usage/page","session/count","session/get","session/page","session/put","turn/count","turn/wakeCount","turn/get","turn/put","turn/latest","turn/page","thread/turnPage","event/append","events/page","events/latestAssistantText"])).max(50),allowedTools:e.array(a).max(128),maxPageSize:E,maxRequestBytes:e.number().int().min(1).max(8388608),maxInFlight:e.number().int().min(1).max(64)}).strict();var we=class{static{o(this,"AgentHostStorageClient")}#e=new Map;#t=null;#r=1;bind(t){if(this.#t)throw new Error("Host storage client is already bound.");this.#t=t}async request(t,r=15e3){let n=ge.parse(t);if(!this.#t)throw new Error("Host storage transport is unavailable.");if(this.#e.size>=32)throw new Error("Host storage request limit exceeded.");let s=`host-storage:${this.#r++}`,c={jsonrpc:"2.0",id:s,method:"host/storage",params:n},l=n.operation==="experiment/policy"||n.operation==="experiment/environment";if(Buffer.byteLength(JSON.stringify(c))>(l?8388608:256e3))throw new Error("Host storage request is too large.");let d=new Promise((h,m)=>{let w=n.operation==="sandbox/request"||l?3e5:6e4,g=setTimeout(()=>{this.#e.delete(s),m(new Error("Host storage request timed out."))},Math.max(1,Math.min(w,r)));this.#e.set(s,{resolve:h,reject:m,timer:g,maxResponseBytes:n.operation==="experiment/environment"?16e5:1e6})});try{await this.#t(c)}catch(h){let m=this.#e.get(s);m&&(clearTimeout(m.timer),this.#e.delete(s),m.reject(h instanceof Error?h:new Error(String(h))))}return d}accept(t){let r=$.safeParse(t),n=r.success?null:U.safeParse(t),s=r.success?r.data:n?.success?n.data:null;if(!s||typeof s.id!="string"||!s.id.startsWith("host-storage:"))return!1;let c=this.#e.get(s.id);return c?(clearTimeout(c.timer),this.#e.delete(s.id),Buffer.byteLength(JSON.stringify(s))>c.maxResponseBytes?(c.reject(new Error("Host storage response is too large.")),!0):("error"in s?c.reject(new Error(`Host storage request failed: ${s.error.message}`)):c.resolve(s.result),!0)):!0}close(){this.#t=null;for(let t of this.#e.values())clearTimeout(t.timer),t.reject(new Error("Host storage transport closed."));this.#e.clear()}};import{once as ze}from"node:events";import{createInterface as He}from"node:readline";async function Ft(i){let t=null,r=Promise.resolve(),n=[],s=o(f=>(r=r.then(async()=>{i.writable.write(`${JSON.stringify(f)}
3
+ `)||await ze(i.writable,"drain")}),r),"write");i.hostStorageClient?.bind(f=>s(f));let c=o(()=>{if(!(!t?.initialized||n.length===0))for(let f of n.splice(0))s(f)},"flushPendingNotifications"),l,d=new Set,h=He({input:i.readable,crlfDelay:1/0}),m=[],w=!1,g=null,T=o(async f=>{let v=t;if(!v)throw new Error("Agent runtime dispatcher is unavailable.");let k=(async()=>{let G=await v.handle(f);G&&await s(G),c()})(),F=f&&typeof f=="object"&&"method"in f?f.method:null;if(F==="initialize"||F==="initialized"){await k;return}d.add(k),k.finally(()=>d.delete(k))},"dispatch"),N=(async()=>{let f=typeof i.host=="function"?await i.host():i.host;for(t=new H(f),l=f.subscribe?.(v=>{if(!t?.initialized){n.push(v);return}s(v)});m.length>0;)await T(m.shift());w=!0})().catch(f=>{g=f,h.close()});try{for await(let f of h){if(!f.trim())continue;if(Buffer.byteLength(f,"utf8")>1e6){await s({jsonrpc:"2.0",id:null,error:{code:-32600,message:"Request exceeds the JSONL size limit"}});continue}let v;try{v=JSON.parse(f)}catch{await s({jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}});continue}if(!i.hostStorageClient?.accept(v))if(w)await T(v);else if(m.length>=64){let k=v&&typeof v=="object"&&"id"in v?v.id:null;(typeof k=="string"||typeof k=="number")&&await s({jsonrpc:"2.0",id:k,error:{code:-32e3,message:"Runtime startup request limit exceeded"}})}else m.push(v)}if(await N,g)throw g;await Promise.all(d),await r}finally{i.hostStorageClient?.close(),l?.()}}o(Ft,"runAgentJsonlServer");var O=e.object({threadId:e.string().trim().min(1)}).passthrough(),Ve=O.extend({includeHistory:e.boolean().optional()}),Oe=e.object({session:e.unknown()}).strict(),z=O.extend({input:e.unknown()}),Me=z.extend({idempotencyKey:e.string().trim().min(1).max(200)}),Le=z.extend({inputId:e.string().trim().min(1)}),Ne=O.extend({reason:e.string().trim().min(1).optional()}),Be=e.object({approvalId:e.string().trim().min(1),input:e.unknown()}).strict();function tr(i){let t=o(async(n,s,c)=>{let l=performance.now();i.telemetry?.({method:n,phase:"started",threadId:s,durationMs:null,errorClass:null});try{let d=await c();return i.telemetry?.({method:n,phase:"completed",threadId:s,durationMs:performance.now()-l,errorClass:null}),d}catch(d){throw i.telemetry?.({method:n,phase:"failed",threadId:s,durationMs:performance.now()-l,errorClass:d instanceof Error?d.name:"UnknownError"}),d}},"run"),r=o(async(n,s="thread/read")=>{let{threadId:c,includeHistory:l}=Ve.parse(n);return t(s,c,async()=>{if(l===!1)return{thread:await i.readThread(c),turns:[],events:[]};let[d,h,m]=await Promise.all([i.readThread(c),i.listTurns(c),i.listEvents(c)]);return{thread:d,turns:h,events:m}})},"threadRead");return{capabilities:o(n=>t("runtime/capabilities",null,()=>i.capabilities(n)),"capabilities"),threadStart:o(async n=>t("thread/start",null,async()=>({thread:await i.createThread(Oe.parse(n).session)})),"threadStart"),threadResume:o(n=>r(n,"thread/resume"),"threadResume"),threadRead:r,turnStart:o(async n=>{let s=z.parse(n);return t("turn/start",s.threadId,async()=>({turn:await i.startTurn(s.threadId,s.input)}))},"turnStart"),turnSteer:o(async n=>{let s=z.parse(n);return t("turn/steer",s.threadId,async()=>({receipt:await i.steerTurn(s.threadId,s.input)}))},"turnSteer"),taskInbox:o(async n=>{let{threadId:s}=O.parse(n);return t("task/inbox",s,()=>i.readTaskInbox(s))},"taskInbox"),taskQueue:o(async n=>{let s=Me.parse(n);return t("task/queue",s.threadId,()=>i.queueTaskInput(s.threadId,s.input,s.idempotencyKey))},"taskQueue"),taskInputUpdate:o(async n=>{let s=Le.parse(n);return t("task/inputUpdate",s.threadId,()=>i.updateTaskInput(s.threadId,s.inputId,s.input))},"taskInputUpdate"),turnInterrupt:o(async n=>{let s=Ne.parse(n);return t("turn/interrupt",s.threadId,async()=>({turn:await i.interruptTurn(s.threadId,s.reason)}))},"turnInterrupt"),approvalResolve:o(async n=>{let s=Be.parse(n);return t("approval/resolve",null,async()=>({approval:await i.resolveApproval(s.approvalId,s.input)}))},"approvalResolve"),userInputResolve:o(async n=>{let s=z.parse(n);return t("userInput/resolve",s.threadId,async()=>(i.isTurnActive(s.threadId)&&await i.waitForTurnSettlement(s.threadId),{turn:await i.startTurn(s.threadId,s.input)}))},"userInputResolve"),profileWorkflows:o(()=>t("profile/workflows",null,()=>i.listProfileWorkflows()),"profileWorkflows"),profileEvaluations:o(n=>t("profile/evaluations",null,()=>i.listProfileEvaluations(n)),"profileEvaluations"),profileTrainingSource:o(()=>t("profile/trainingSource",null,()=>i.loadProfileTrainingSource()),"profileTrainingSource"),profileEvaluationPrepare:o(n=>t("profile/evaluations/prepare",null,()=>i.prepareProfileEvaluationRun(n)),"profileEvaluationPrepare"),profileEvaluationRun:o(n=>t("profile/evaluations/run",null,()=>i.runPreparedProfileEvaluation(n)),"profileEvaluationRun"),...i.executeExperimentCase?{experimentExecuteCase:o(n=>t("experiments/executeCase",null,()=>i.executeExperimentCase(n)),"experimentExecuteCase")}:{},...i.cancelExperimentCase?{experimentCancelCase:o(n=>t("experiments/cancelCase",null,()=>i.cancelExperimentCase(n)),"experimentCancelCase")}:{},profileEvaluationRunSuite:o(n=>t("profile/evaluations/runSuite",null,()=>i.runProfileEvaluationSuite(n)),"profileEvaluationRunSuite"),profileEvaluationExecuteCase:o(n=>t("profile/evaluations/executeCase",null,()=>i.executeProfileEvaluationCase(n)),"profileEvaluationExecuteCase"),profileEvaluationExecuteRun:o(n=>t("profile/evaluations/executeRun",null,()=>i.executeProfileEvaluationRun(n)),"profileEvaluationExecuteRun"),profileEvaluationCompare:o(n=>t("profile/evaluations/compare",null,()=>i.compareProfileEvaluationRuns(n)),"profileEvaluationCompare"),profileEvaluationReport:o(n=>t("profile/evaluations/report",null,()=>i.buildProfileEvaluationReport(n)),"profileEvaluationReport"),harnessInspect:o(()=>t("harness/inspect",null,()=>i.inspectHarness()),"harnessInspect"),harnessProposalReview:o(n=>t("harness/proposalReview",null,()=>i.reviewHarnessProposal(n)),"harnessProposalReview"),harnessReview:o(n=>t("harness/review",null,()=>i.reviewHarness(n)),"harnessReview"),harnessAcceptEvaluationReview:o(n=>t("harness/acceptEvaluationReview",null,()=>i.acceptHarnessEvaluationReview(n)),"harnessAcceptEvaluationReview"),harnessMaterializeEvaluationTaskset:o(n=>t("harness/materializeEvaluationTaskset",null,()=>i.materializeHarnessEvaluationTaskset(n)),"harnessMaterializeEvaluationTaskset"),harnessRunEvaluationBaseline:o(n=>t("harness/runEvaluationBaseline",null,()=>i.runHarnessEvaluationBaseline(n)),"harnessRunEvaluationBaseline"),harnessValidate:o(()=>t("harness/validate",null,()=>i.validateHarness()),"harnessValidate"),harnessBackgroundReview:o(n=>t("harness/backgroundReview",null,()=>i.updateHarnessBackgroundReview(n)),"harnessBackgroundReview"),harnessDiff:o(n=>t("harness/diff",null,()=>i.diffHarness(n)),"harnessDiff"),harnessRollback:o(n=>t("harness/rollback",null,()=>i.rollbackHarness(n)),"harnessRollback"),refinerInspect:o(()=>t("refiner/inspect",null,()=>i.inspectRefiner()),"refinerInspect"),refinerUpdate:o(n=>t("refiner/update",null,()=>i.updateRefiner(n)),"refinerUpdate"),refinerActivate:o(n=>t("refiner/activate",null,()=>i.activateRefiner(n)),"refinerActivate"),refinerRollback:o(n=>t("refiner/rollback",null,()=>i.rollbackRefiner(n)),"refinerRollback"),subscribe:i.subscribeEvents&&i.eventNotification?n=>i.subscribeEvents(s=>n(i.eventNotification(s))):void 0}}o(tr,"createAgentRuntimeService");var _=e.string().regex(/^[a-f0-9]{64}$/),$e=e.object({harnessReleaseHash:_,instructionsHash:_,skillHashes:e.record(e.string(),_),agentAssetHashes:e.record(e.string(),_),toolCatalogHash:_,memoryRevision:e.number().int().nonnegative().nullable()}).strict(),Ue=e.object({protocolVersion:e.string().trim().min(1),threadId:e.string().trim().min(1),turnId:e.string().trim().min(1),harnessReleaseHash:_,toolCatalogHash:_,context:e.record(e.string(),e.unknown()),pendingInteraction:e.record(e.string(),e.unknown()).nullable(),usage:e.record(e.string(),e.unknown())}).strict();function or(i){return j($e.parse(i))}o(or,"effectiveSurfaceHash");function ar(i){return j(Ue.parse(i))}o(ar,"checkpointHash");function cr(i){return[i.system,...i.harnessInstructions,...i.skillInstructions,...i.hostInstructions??[]].map(t=>t.trim()).filter(Boolean).join(`
4
+
5
+ `)}o(cr,"materializeAgentPrompt");function mr(i){let t=new Map;for(let l of i){let d=l.name.trim();if(!d)throw new Error("Agent tool names cannot be empty.");if(t.has(d))throw new Error(`Duplicate agent tool: ${d}.`);if(!l.unavailableReason&&!l.execute)throw new Error(`Agent tool ${d} is declared as available without an executor.`);t.set(d,{...l,name:d})}let r=[...t.values()].sort((l,d)=>l.name.localeCompare(d.name)),n=r.filter(l=>!l.unavailableReason).map(l=>({name:l.name,description:l.description,inputSchema:e.toJSONSchema(l.inputSchema,{target:"draft-7",unrepresentable:"any"})})),s=r.map(l=>({name:l.name,displayLabel:l.displayLabel??l.name,placement:l.placement,available:!l.unavailableReason,unavailableReason:l.unavailableReason??null})),c=j({modelTools:n,capabilities:s});return{byName:t,tools:r,modelTools:n,capabilities:s,hash:c}}o(mr,"createAgentToolCatalog");async function hr(i,t){let r=i.byName.get(t.name);if(!r)throw new Error(`Unknown agent tool: ${t.name}.`);if(r.unavailableReason)throw new Error(`Agent tool ${t.name} is unavailable: ${r.unavailableReason}`);if(!r.execute)throw new Error(`Agent tool ${t.name} has no executor.`);return r.execute(r.inputSchema.parse(t.arguments),t.context)}o(hr,"executeAgentTool");function fr(i){let t=new Set,r=[...i].map(c=>{let l=c.name.trim();if(!l)throw new Error("Agent tool names cannot be empty.");if(t.has(l))throw new Error(`Duplicate agent tool: ${l}.`);if(t.add(l),!c.unavailableReason&&!c.executorAvailable)throw new Error(`Agent tool ${l} is declared as available without an executor.`);return{...c,name:l}}).sort((c,l)=>c.name.localeCompare(l.name)),n=r.filter(c=>!c.unavailableReason).map(c=>({name:c.name,description:c.description,inputSchema:c.inputSchema})),s=r.map(c=>({name:c.name,displayLabel:c.displayLabel??c.name,placement:c.placement,available:!c.unavailableReason,unavailableReason:c.unavailableReason??null}));return{byName:new Map(r.map(c=>[c.name,c])),tools:r,modelTools:n,capabilities:s,hash:j({modelTools:n,capabilities:s})}}o(fr,"createAgentToolCatalogProjection");async function br(i,t){let r=i.byName.get(t.name);if(!r)throw new Error(`Unknown agent tool: ${t.name}.`);if(r.unavailableReason)throw new Error(`Agent tool ${t.name} is unavailable: ${r.unavailableReason}`);if(!r.execute)throw new Error(`Agent tool ${t.name} has no executor.`);let n=r.validateArguments?r.validateArguments(t.arguments):t.arguments;return r.execute(n,t.context)}o(br,"executeProjectedAgentTool");var ve=class{static{o(this,"TaskSignals")}#e=new Map;notify(t){for(let r of[...this.#e.get(t)??[]])r()}subscribe(t,r){let n=this.#e.get(t);return n||this.#e.set(t,n=new Set),n.add(r),()=>{n.delete(r),n.size===0&&this.#e.delete(t)}}async wait(t){let r=o(()=>{},"wake"),n=0,s=o(()=>{n+=1,r()},"changed"),c=[...new Set(t.taskIds)].map(d=>this.subscribe(d,s)),l=setTimeout(s,Math.max(0,t.deadline-Date.now()));t.signal.addEventListener("abort",s);try{for(;;){t.signal.throwIfAborted();let d=n,h=await t.read();if(h!==null)return h;if(Date.now()>=t.deadline)return null;n===d&&await new Promise(m=>{r=m,(n!==d||t.signal.aborted)&&m()})}}finally{clearTimeout(l),t.signal.removeEventListener("abort",s);for(let d of c)d()}}},xe=class{static{o(this,"TaskSerialExecutor")}#e=new Map;async run(t,r){let s=(this.#e.get(t)??Promise.resolve()).then(r),c=s.then(()=>{},()=>{});this.#e.set(t,c);try{return await s}finally{this.#e.get(t)===c&&this.#e.delete(t)}}};var M=class extends Error{static{o(this,"AcpRpcError")}code;data;constructor(t,r,n){super(r),this.code=t,this.data=n,this.name="AcpRpcError"}};import{execFile as Je}from"node:child_process";function I(i,t){if(i.pid){if(process.platform==="win32"){Je("taskkill",["/PID",String(i.pid),"/T",...t==="SIGKILL"?["/F"]:[]],{windowsHide:!0},()=>{});return}try{process.kill(-i.pid,t)}catch(r){if(r.code!=="ESRCH")throw r}}}o(I,"signalNativeProcess");import{spawn as De}from"node:child_process";import{StringDecoder as Fe}from"node:string_decoder";var D=8*1024*1024,L={outcome:{outcome:"cancelled"}};function R(i){return i!==null&&typeof i=="object"&&!Array.isArray(i)}o(R,"object");var Ie=class{static{o(this,"AcpClient")}options;child=null;pending=new Map;sessions=new Set;activePrompts=new Set;permissions=new Map;nextId=1;buffer="";decoder=new Fe("utf8");initialized=null;updateQueue=Promise.resolve();stopped=!1;constructor(t){this.options=t}initialize(){return this.initialized?this.initialized:(this.initialized=this.connect(),this.initialized)}async connect(){if(this.stopped)throw new Error("ACP client is closed; reconnect with a new client.");let t=De(this.options.command,this.options.args,{cwd:this.options.cwd,env:this.options.env??process.env,stdio:["pipe","pipe","pipe"],shell:!1,detached:process.platform!=="win32"});this.child=t,t.stdout.on("data",r=>this.consume(this.decoder.write(r))),t.stderr.resume(),t.stdin.on("error",r=>this.fail(r)),t.on("error",r=>this.fail(r)),t.on("exit",(r,n)=>this.fail(new Error(`ACP agent exited (${n??r??"unknown"}).`)));try{let r=await this.request("initialize",{protocolVersion:1,clientInfo:{name:"openpond",title:"OpenPond",version:"1"},clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}});if(r.protocolVersion!==1)throw new Error(`Unsupported ACP protocol version: ${r.protocolVersion}`);return r}catch(r){throw await this.stop(),r}}async authenticate(t){let n=(await this.initialize()).authMethods?.find(s=>s.id===t);if(!n)throw new Error("The agent did not advertise this authentication method.");if(n.type==="terminal")throw new Error("Run the agent's terminal login, then reconnect.");await this.request("authenticate",{methodId:t})}async createSession(t,r=[]){await this.initialize();let n=await this.request("session/new",{cwd:t,mcpServers:r});if(typeof n.sessionId!="string"||!n.sessionId)throw new Error("Agent returned no native session identity.");return this.sessions.add(n.sessionId),n}async loadSession(t,r,n=[]){if(!(await this.initialize()).agentCapabilities?.loadSession)throw new Error("This agent does not support native session loading.");this.sessions.add(t);try{let c=await this.request("session/load",{sessionId:t,cwd:r,mcpServers:n});return await this.updateQueue,{...c,sessionId:t}}catch(c){throw this.sessions.delete(t),c}}async setModel(t,r){this.assertSession(t),await this.request("session/set_model",{sessionId:t,modelId:r})}async setMode(t,r){this.assertSession(t),await this.request("session/set_mode",{sessionId:t,modeId:r})}async setConfigOption(t,r,n){return this.assertSession(t),await this.request("session/set_config_option",{sessionId:t,configId:r,value:n})}async prompt(t,r,n){if(this.assertSession(t),n?.aborted)throw new Error("ACP prompt cancelled.");if(this.activePrompts.has(t))throw new Error("A prompt is already active for this native session.");this.activePrompts.add(t);let s,c=o(()=>{this.cancel(t),s=setTimeout(()=>{this.stop()},5e3),s.unref()},"abort");n?.addEventListener("abort",c,{once:!0});try{let l=await this.request("session/prompt",{sessionId:t,prompt:r},0);return await this.updateQueue,n?.aborted?{...l,stopReason:"cancelled"}:l}catch(l){if(n?.aborted)return{stopReason:"cancelled"};throw l}finally{s&&clearTimeout(s),n?.removeEventListener("abort",c),this.activePrompts.delete(t),this.cancelPermissions(t)}}cancel(t){this.cancelPermissions(t),this.sessions.has(t)&&this.child&&this.write({jsonrpc:"2.0",method:"session/cancel",params:{sessionId:t}})}async stop(){if(this.stopped)return;this.stopped=!0;let t=this.child;this.fail(new Error("ACP connection closed.")),!(!t||t.exitCode!==null||t.signalCode!==null)&&await new Promise(r=>{let n=setTimeout(()=>I(t,"SIGKILL"),2e3);n.unref(),t.once("exit",()=>{clearTimeout(n),r()}),I(t,"SIGTERM")})}assertSession(t){if(!this.sessions.has(t))throw new Error("Session does not belong to this ACP connection.")}request(t,r,n=this.options.requestTimeoutMs??3e4){let s=this.nextId++;return new Promise((c,l)=>{let d=n>0?setTimeout(()=>{this.pending.delete(s),l(new Error(`ACP request timed out: ${t}`))},n):void 0;d?.unref(),this.pending.set(s,{resolve:c,reject:l,timer:d});try{this.write({jsonrpc:"2.0",id:s,method:t,params:r})}catch(h){d&&clearTimeout(d),this.pending.delete(s),l(h)}})}write(t){if(!this.child||this.child.stdin.destroyed)throw new Error("ACP connection is not running.");let r=JSON.stringify(t);if(Buffer.byteLength(r)>D)throw new Error("ACP frame exceeds the size limit.");this.child.stdin.write(`${r}
6
+ `)}consume(t){this.buffer+=t;let r;for(;(r=this.buffer.indexOf(`
7
+ `))!==-1;){let n=this.buffer.slice(0,r);if(this.buffer=this.buffer.slice(r+1),!!n.trim())try{if(Buffer.byteLength(n)>D)throw new Error("ACP frame exceeds the size limit.");this.receive(JSON.parse(n))}catch{this.fail(new Error("Invalid ACP protocol frame.")),this.stop();return}}Buffer.byteLength(this.buffer)>D&&(this.fail(new Error("ACP frame exceeds the size limit.")),this.stop())}receive(t){if(!R(t)||t.jsonrpc!=="2.0")throw new Error("Invalid JSON-RPC envelope.");if(typeof t.method=="string"){if("id"in t){this.handleRequest(t);return}if(t.method==="session/update"&&R(t.params)){let{sessionId:n,update:s}=t.params;if(typeof n!="string"||!this.sessions.has(n)||!R(s))return;this.updateQueue=this.updateQueue.then(async()=>{await this.options.onUpdate?.(n,s)}),this.updateQueue.catch(c=>{this.fail(c),this.stop()})}return}if(typeof t.id!="number")return;let r=this.pending.get(t.id);r&&(this.pending.delete(t.id),r.timer&&clearTimeout(r.timer),R(t.error)?r.reject(new M(Number(t.error.code),String(t.error.message),t.error.data)):r.resolve(t.result))}async handleRequest(t){let r=t.id;if(!(typeof r!="number"&&typeof r!="string"))try{if(t.method!=="session/request_permission"){this.write({jsonrpc:"2.0",id:r,error:{code:-32601,message:"Client method not supported."}});return}let n=t.params;if(!R(n)||typeof n.sessionId!="string"||!Array.isArray(n.options)||!R(n.toolCall))throw new Error("Invalid permission request.");if(this.assertSession(n.sessionId),!this.activePrompts.has(n.sessionId)){this.write({jsonrpc:"2.0",id:r,result:L});return}let s=new AbortController,c=this.permissions.get(n.sessionId)??new Set;c.add(s),this.permissions.set(n.sessionId,c);let l=L;try{if(this.options.onPermission&&(l=await Promise.race([this.options.onPermission(n,s.signal),new Promise(d=>s.signal.addEventListener("abort",()=>d(L),{once:!0}))])),s.signal.aborted&&(l=L),l.outcome.outcome==="selected"){let d=l.outcome.optionId;if(!n.options.some(h=>R(h)&&h.optionId===d))throw new Error("Permission option was not advertised by the agent.")}}finally{c.delete(s),c.size||this.permissions.delete(n.sessionId)}this.child&&this.write({jsonrpc:"2.0",id:r,result:l})}catch{this.child&&this.write({jsonrpc:"2.0",id:r,error:{code:-32602,message:"Invalid or expired client request."}})}}cancelPermissions(t){for(let r of this.permissions.get(t)??[])r.abort();this.permissions.delete(t)}fail(t){let r=this.child,n=!!r;this.child=null,r&&(I(r,"SIGTERM"),setTimeout(()=>I(r,"SIGKILL"),2e3).unref());for(let s of this.pending.values())s.timer&&clearTimeout(s.timer),s.reject(t);this.pending.clear();for(let s of this.sessions)this.cancelPermissions(s);this.sessions.clear(),n&&this.options.onExit?.(t)}};import{spawn as Ge}from"node:child_process";import{randomUUID as ye}from"node:crypto";import{StringDecoder as Ke}from"node:string_decoder";var x=o(i=>i&&typeof i=="object"&&!Array.isArray(i)?i:{},"record"),ke=class{static{o(this,"ClaudeCliClient")}options;child=null;sessionId=null;pending=new Map;turn=null;permissions=new Set;updates=Promise.resolve();closed=!1;model="default";constructor(t){this.options=t}async initialize(){return{protocolVersion:1,agentCapabilities:{loadSession:!0,mcpCapabilities:{http:!0},promptCapabilities:{image:!0,embeddedContext:!0}},authMethods:[],agentInfo:{name:"Claude Code CLI",version:"native"}}}async authenticate(t){throw new Error("Use Claude Code's native login, then reconnect.")}async createSession(t,r=[]){return this.start(ye(),t,!1,r)}async loadSession(t,r,n=[]){return this.start(t,r,!0,n)}async start(t,r,n,s){if(this.child||this.closed)throw new Error("Claude connection already owns a session or is closed.");if(!/^[a-f0-9-]{36}$/i.test(t))throw new Error("Invalid native Claude session identity.");this.sessionId=t;let c=Object.fromEntries(s.map(m=>[String(m.name),{type:"http",url:m.url,headers:Object.fromEntries((Array.isArray(m.headers)?m.headers:[]).map(w=>{let g=x(w);return[String(g.name),String(g.value)]}))}])),l=Ge(this.options.command,["--print","--verbose","--input-format","stream-json","--output-format","stream-json","--include-partial-messages","--permission-prompt-tool","stdio",...s.length?["--mcp-config",JSON.stringify({mcpServers:c})]:[],n?"--resume":"--session-id",t],{cwd:r,env:this.options.env??process.env,stdio:["pipe","pipe","pipe"],shell:!1,detached:process.platform!=="win32"});this.child=l;let d=new Ke("utf8"),h="";l.stderr.resume(),l.stdout.on("data",m=>{h+=d.write(m);let w;for(;(w=h.indexOf(`
8
+ `))>=0;){let g=h.slice(0,w);if(h=h.slice(w+1),!!g.trim())try{if(Buffer.byteLength(g)>8*1024*1024)throw new Error("Oversized frame");this.receive(x(JSON.parse(g)))}catch{this.fail(new Error("Invalid Claude CLI protocol frame.")),this.stop();return}}Buffer.byteLength(h)>8*1024*1024&&(this.fail(new Error("Claude CLI frame exceeds limit.")),this.stop())}),l.on("error",m=>this.fail(m)),l.stdin.on("error",m=>this.fail(m)),l.on("exit",m=>{this.fail(new Error(`Claude CLI exited (${m??"signal"}).`)),I(l,"SIGTERM"),setTimeout(()=>I(l,"SIGKILL"),2e3).unref(),this.child=null});try{let m=await this.control({subtype:"initialize",hooks:null}),w=Array.isArray(m.models)?m.models.map(x).filter(g=>typeof g.value=="string"):[];return{sessionId:t,models:{currentModelId:this.model,availableModels:w.map(g=>({modelId:String(g.value),name:String(g.displayName??g.value)}))},modes:{currentModeId:String(m.current_permission_mode??"manual"),availableModes:[{id:"manual",name:"Ask for permissions"},{id:"plan",name:"Plan"}]}}}catch(m){throw await this.stop(),m}}async setModel(t,r){this.assertSession(t),await this.control({subtype:"set_model",model:r}),this.model=r}async setMode(t,r){if(this.assertSession(t),!["manual","plan"].includes(r))throw new Error("Unsupported Claude permission mode.");await this.control({subtype:"set_permission_mode",mode:r})}async prompt(t,r,n){if(this.assertSession(t),this.turn)throw new Error("A prompt is already active for this native session.");if(n?.aborted)throw new Error("Claude turn cancelled.");let s=new Promise((d,h)=>{this.turn={resolve:d,reject:h}}),c,l=o(()=>{for(let d of this.permissions)d.abort();this.control({subtype:"interrupt"}).catch(()=>{}),c=setTimeout(()=>{this.stop()},5e3),c.unref()},"abort");n?.addEventListener("abort",l,{once:!0});try{this.write({type:"user",session_id:t,parent_tool_use_id:null,message:{role:"user",content:r.map(h=>h.type==="image"?{type:"image",source:{type:"base64",media_type:h.mimeType,data:h.data}}:h)}});let d=await s;return await this.updates,n?.aborted?{stopReason:"cancelled"}:d}catch(d){if(n?.aborted)return{stopReason:"cancelled"};throw d}finally{n?.removeEventListener("abort",l),c&&clearTimeout(c),this.turn=null;for(let d of this.permissions)d.abort();this.permissions.clear()}}assertSession(t){if(!this.child||this.sessionId!==t||this.closed)throw new Error("Session does not belong to this Claude connection.")}write(t){if(!this.child||this.child.stdin.destroyed)throw new Error("Claude connection is closed.");let r=JSON.stringify(t);if(Buffer.byteLength(r)>8*1024*1024)throw new Error("Claude input exceeds limit.");this.child.stdin.write(`${r}
9
+ `)}control(t){let r=ye();return new Promise((n,s)=>{let c=setTimeout(()=>{this.pending.delete(r),s(new Error(`Claude control request timed out: ${t.subtype}`))},this.options.requestTimeoutMs??3e4);c.unref(),this.pending.set(r,{resolve:n,reject:s,timer:c});try{this.write({type:"control_request",request_id:r,request:t})}catch(l){clearTimeout(c),this.pending.delete(r),s(l)}})}emit(t){if(!this.turn||!this.sessionId)return;let r=this.sessionId;this.updates=this.updates.then(async()=>{await this.options.onUpdate?.(r,t)}),this.updates.catch(n=>{this.fail(n),this.stop()})}receive(t){if(typeof t.session_id=="string"&&t.session_id!==this.sessionId){this.fail(new Error("Claude changed native session identity.")),this.stop();return}if(t.type==="control_response"){let r=x(t.response),n=String(r.request_id),s=this.pending.get(n);if(!s)return;clearTimeout(s.timer),this.pending.delete(n),r.subtype==="error"?s.reject(new Error(String(r.error??"Claude control failed."))):s.resolve(x(r.response))}else if(t.type==="control_request")this.permission(t);else if(t.type==="stream_event"){let r=x(t.event),n=x(r.delta),s=x(r.content_block);r.type==="content_block_delta"&&(n.type==="text_delta"||n.type==="thinking_delta")&&this.emit({sessionUpdate:n.type==="text_delta"?"agent_message_chunk":"agent_thought_chunk",content:{type:"text",text:n.text??n.thinking??""}}),r.type==="content_block_start"&&s.type==="tool_use"&&this.emit({sessionUpdate:"tool_call",toolCallId:s.id,title:s.name,kind:"other",status:"in_progress",rawInput:s.input})}else if(t.type==="assistant"){let r=x(t.message).content;for(let n of Array.isArray(r)?r.map(x):[])n.type==="tool_use"&&this.emit({sessionUpdate:"tool_call_update",toolCallId:n.id,title:n.name,status:"in_progress",rawInput:n.input})}else if(t.type==="user"){let r=x(t.message).content;for(let n of Array.isArray(r)?r.map(x):[])n.type==="tool_result"&&this.emit({sessionUpdate:"tool_call_update",toolCallId:n.tool_use_id,status:n.is_error?"failed":"completed",content:n.content})}else if(t.type==="result"){if(t.session_id&&t.session_id!==this.sessionId){this.fail(new Error("Claude changed native session identity."));return}this.emit({sessionUpdate:"usage_update",usage:t.usage,totalCostUsd:t.total_cost_usd}),t.is_error?this.turn?.reject(new Error(Array.isArray(t.errors)?t.errors.map(String).join("; "):"Claude turn failed.")):this.turn?.resolve({stopReason:"end_turn"})}}async permission(t){let r=x(t.request),n=String(t.request_id);if(r.subtype!=="can_use_tool"||!this.turn||!this.sessionId){this.write({type:"control_response",response:{subtype:"error",request_id:n,error:"Unsupported or inactive control request."}});return}let s=new AbortController;this.permissions.add(s);try{let c=x(r.input),l=r.tool_name==="AskUserQuestion"&&Array.isArray(c.questions)?c.questions:void 0,d=new Promise(w=>s.signal.addEventListener("abort",()=>w({outcome:{outcome:"cancelled"}}),{once:!0})),h=await Promise.race([d,this.options.onPermission?.({sessionId:this.sessionId,toolCall:{toolCallId:r.tool_use_id,title:r.title??r.tool_name,rawInput:r.input},questions:l,options:[{optionId:"allow",name:"Allow once",kind:"allow_once"},{optionId:"deny",name:"Deny",kind:"reject_once"}]},s.signal)]),m=!s.signal.aborted&&h?.outcome.outcome==="selected"&&h.outcome.optionId==="allow";this.child&&this.write({type:"control_response",response:{subtype:"success",request_id:n,response:m?{behavior:"allow",updatedInput:l?{...c,answers:h?.answers}:r.input}:{behavior:"deny",message:"Permission declined or turn cancelled."}}})}catch{this.child&&this.write({type:"control_response",response:{subtype:"success",request_id:n,response:{behavior:"deny",message:"Permission could not be resolved."}}})}finally{this.permissions.delete(s)}}fail(t){for(let r of this.pending.values())clearTimeout(r.timer),r.reject(t);this.pending.clear(),this.turn?.reject(t),this.turn=null;for(let r of this.permissions)r.abort();this.permissions.clear(),this.options.onExit?.(t)}async stop(){if(this.closed)return;this.closed=!0,this.fail(new Error("Claude connection closed."));let t=this.child;!t||t.exitCode!==null||t.signalCode!==null||(await new Promise(r=>{let n=setTimeout(()=>I(t,"SIGKILL"),2e3);n.unref(),t.once("exit",()=>{clearTimeout(n),r()}),I(t,"SIGTERM")}),this.child=null)}};export{B as a,j as b,Ye as c,Ze as d,et as e,Se as f,Ee as g,st as h,C as i,lt as j,Q as k,W as l,$ as m,U as n,ut as o,_e as p,H as q,X as r,J as s,te as t,ie as u,ce as v,ue as w,de as x,pe as y,me as z,Pe as A,he as B,Ae as C,fe as D,be as E,p as F,Ht as G,ge as H,Vt as I,we as J,Ft as K,tr as L,$e as M,Ue as N,or as O,ar as P,cr as Q,mr as R,hr as S,fr as T,br as U,ve as V,xe as W,M as X,Ie as Y,ke as Z};
@@ -0,0 +1,3 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{ka as P,ma as h,na as E}from"./chunk-JO7GRBOG.js";import{a as u,l as f}from"./chunk-P653BXMY.js";import{b as d}from"./chunk-ES2ISFJC.js";import{a as c}from"./chunk-FTQLQJQV.js";var S=d.object({id:u,runIds:d.array(u).min(2).max(100)}).strict();function j(r){return async s=>{let i=S.parse(s),l=await r.selectedProfile();if(!l)throw new Error("Select a Profile before comparing its evaluation runs.");let a=[];for(let e of i.runIds){let t=await r.store.getProfileEvaluationRun(e);if(!t||f(t.profileRef)!==f(l.ref))throw new Error(`Profile evaluation run ${e} is unavailable in the selected Profile.`);a.push({manifest:t.manifest,result:t.metric})}let o=await r.store.getProfileEvaluationComparison(i.id),n=P({id:i.id,members:a,createdAt:o?.createdAt??new Date().toISOString()});return r.store.saveProfileEvaluationComparison(l.ref,n)}}c(j,"createProfileEvaluationComparisonService");import{promises as m}from"node:fs";import v from"node:path";var y=d.object({id:u,evidenceKind:d.enum(["run","suite","comparison"]),evidenceId:u}).strict();function w(r){return v.join(r,"evals","reports")}c(w,"reportDirectory");async function R(r){let s=await m.lstat(r).catch(i=>{if(i.code==="ENOENT")return null;throw i});if(s&&(!s.isDirectory()||s.isSymbolicLink()))throw new Error("Profile evaluation report directory must be a regular directory.");s||await m.mkdir(r)}c(R,"ensureRegularDirectory");async function k(r){let s,i;if(r.evidenceKind==="run")s=[r.evidenceId],i="";else if(r.evidenceKind==="suite"){let o=await r.store.getProfileEvaluationSuiteRun(r.evidenceId);if(!o||o.profileId!==r.profileRef.profileId)throw new Error("Profile evaluation suite is unavailable.");s=o.members.map(n=>n.runManifest.id),i=o.contentHash}else{let o=await r.store.getProfileEvaluationComparison(r.evidenceId);if(!o)throw new Error("Profile evaluation comparison is unavailable.");s=o.members.map(n=>n.runManifest.id),i=o.contentHash}let l=await Promise.all(s.map(o=>r.store.getProfileEvaluationRun(o)));if(l.some(o=>!o||f(o.profileRef)!==f(r.profileRef)))throw new Error("Profile evaluation report is missing authorized run evidence.");let a=l;if(r.evidenceKind==="run"&&(i=a[0].contentHash),r.evidenceKind!=="run"){let o=r.evidenceKind==="suite"?(await r.store.getProfileEvaluationSuiteRun(r.evidenceId)).members.map(n=>n.runHash):(await r.store.getProfileEvaluationComparison(r.evidenceId)).members.map(n=>n.metricResultHash);for(let[n,e]of a.entries())if(r.evidenceKind==="suite"&&o[n]!==e.contentHash||r.evidenceKind==="comparison"&&o[n]!==e.metric.contentHash)throw new Error("Profile evaluation report evidence differs from retained member runs.")}return{runs:a,primary:{kind:r.evidenceKind,id:r.evidenceId,contentHash:i}}}c(k,"loadRuns");async function H(r){let s=y.parse(r.request),{runs:i,primary:l}=await k({store:r.store,profileRef:r.profileRef,evidenceKind:s.evidenceKind,evidenceId:s.evidenceId}),a=c(e=>[...new Map(e.map(t=>[f(t),t])).values()],"unique"),o=a(i.map(e=>f(e.manifest.metricPolicy))),n=i.map(e=>e.metric.value).filter(e=>e!==null);return h({schemaVersion:"openpond.profileEvaluationReport.v1",id:s.id,createdAt:new Date().toISOString(),testedSources:a(i.map(e=>({profileId:e.manifest.profileEvaluation.profileId,sourceRevision:e.manifest.profileEvaluation.sourceRevision,harnessRelease:e.manifest.profileEvaluation.harnessRelease}))),tasksetReleases:a(i.map(e=>e.manifest.tasksetRelease)),metricPolicyHashes:o,modelConfigurationHashes:a(i.map(e=>e.manifest.policy.kind==="model"?e.manifest.policy.configurationHash:f(e.manifest.policy))),evidence:[l,...i.filter(e=>l.kind!=="run"||e.manifest.id!==l.id).map(e=>({kind:"run",id:e.manifest.id,contentHash:e.contentHash}))],summary:{totalChecks:i.length,passedChecks:i.filter(e=>e.passed).length,failedChecks:i.filter(e=>!e.passed&&e.metric.value!==null).length,unscoredChecks:i.filter(e=>!e.passed&&e.metric.value===null).length,meanScore:o.length===1&&n.length===i.length?n.reduce((e,t)=>e+t,0)/n.length:null}})}c(H,"buildProfileEvaluationReport");function q(r){return{list:c(async()=>{let l=await r.selectedProfile();if(!l)return[];let a=w(l.sourcePath),o=await m.lstat(a).catch(t=>{if(t.code==="ENOENT")return null;throw t});if(!o)return[];if(!o.isDirectory()||o.isSymbolicLink())throw new Error("Profile evaluation report directory is unsafe.");let n=await m.readdir(a,{withFileTypes:!0});return(await Promise.all(n.filter(t=>t.name.endsWith(".json")).map(async t=>{if(!t.isFile()||t.isSymbolicLink())throw new Error("Profile evaluation report must be a regular file.");let p=E(JSON.parse(await m.readFile(v.join(a,t.name),"utf8")));if(`${p.id}.json`!==t.name||p.testedSources.some(g=>g.profileId!==l.ref.profileId))throw new Error("Profile evaluation report differs from its source location.");return p}))).sort((t,p)=>p.createdAt.localeCompare(t.createdAt))},"list"),save:c(async l=>{let a=await r.selectedProfile();if(!a?.gitBacked)throw new Error("Select a Git-backed Profile before saving an evaluation report.");let o=await H({store:r.store,profileRef:a.ref,request:l}),n=v.join(a.sourcePath,"evals");await R(n);let e=w(a.sourcePath);return await R(e),await m.writeFile(v.join(e,`${o.id}.json`),`${JSON.stringify(o,null,2)}
3
+ `,{flag:"wx"}),o},"save")}}c(q,"createProfileEvaluationReportService");export{j as a,H as b,q as c};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{e as g,g as $,h as O,i as C}from"./chunk-V6WBSW5Q.js";import{a as w}from"./chunk-3M53YXEI.js";import{a as r}from"./chunk-FTQLQJQV.js";var L=Symbol("openpondCliOptionValues"),a=class extends Error{static{r(this,"CliUsageError")}exitCode=2;constructor(t){super(t),this.name="CliUsageError"}},K=new Set(["maxOutputBytes","timeoutSec"]);function k(n){let t=[...n],o="",i={},e={},u=[];for(;t.length>0;){let s=t.shift();if(s==="--"){u.push(...t);break}if(s.startsWith("--")){let f=s.indexOf("="),c=f>=0?s.slice(2,f):s.slice(2),p=N(c),d=f>=0?s.slice(f+1):P(t,p,o);h(i,e,p,d,o)}else _(s)?y(s,t,i,e):o?u.push(s):o=s}return Object.defineProperty(i,L,{value:e,enumerable:!1,configurable:!1,writable:!1}),V(o,i),{command:o,options:i,rest:u}}r(k,"parseArgs");function N(n){return n.replace(/-([a-z])/g,(t,o)=>o.toUpperCase())}r(N,"normalizeCliOptionKey");function _(n){return/^-[^-].*/.test(n)&&!S(n)}r(_,"isShortOptionToken");function y(n,t,o,i){let e=n.slice(1);if(!e)return;let u=e.indexOf("="),s=u>=0?e.slice(0,u):e,f=u>=0?e.slice(u+1):null;if(s.length!==1){for(let d of s){let m=g[d];if(!m)throw new a(`unknown short option -${d}`);if(C(m)!=="boolean")throw new a(`short option -${d} requires its own value`);h(o,i,m,"true")}return}let c=g[s];if(!c)throw new a(`unknown short option -${s}`);let p=f??P(t,c);h(o,i,c,p)}r(y,"parseShortOptionToken");function P(n,t,o){let i=I(t,o);if(i==="boolean")return n[0]&&x(n[0])?n.shift():"true";if(i){let e=n.shift();if(e===void 0||R(e)&&!S(e))throw e!==void 0&&n.unshift(e),new a(`${l(t)} must be ${b(i)}`);return e}return n[0]&&!n[0].startsWith("--")?n.shift():"true"}r(P,"readOptionValue");function h(n,t,o,i,e){T(o,i,e),n[o]=i,(t[o]??=[]).push(i)}r(h,"setParsedOption");function T(n,t,o){let i=I(n,o);if(i){if(i==="boolean"){if(!x(t))throw new a(`${l(n)} must be a boolean`);return}if(t.trim().length===0||t==="true")throw new a(`${l(n)} must be ${b(i)}`);if(i==="number"||i==="integer"){let e=Number(t);if(!Number.isFinite(e))throw new a(`${l(n)} must be ${b(i)}`);if(i==="integer"&&!Number.isInteger(e))throw new a(`${l(n)} must be an integer`);if(i==="integer"&&K.has(n)&&e<=0)throw new a(`${l(n)} must be a positive integer`);return}if(i==="json")try{w(t,l(n))}catch(e){throw new a(e instanceof Error?e.message:String(e))}}}r(T,"validateParsedOptionValue");function I(n,t){return t?O(t,n):C(n)}r(I,"typedOptionKind");function l(n){return n.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}r(l,"cliOptionLabel");function E(n){return n==="json"?"JSON value":n}r(E,"optionKindLabel");function b(n){let t=E(n);return/^[aeiou]/i.test(t)?`an ${t}`:`a ${t}`}r(b,"optionKindPhrase");function x(n){return/^(true|false|1|0|yes|no)$/i.test(n)}r(x,"isBooleanLiteral");function R(n){return n.startsWith("-")&&n!=="-"}r(R,"isOptionLike");function S(n){return/^-\d+(?:\.\d+)?$/.test(n)}r(S,"isNegativeNumber");function V(n,t){let o=n?$(n):null;for(let i of Object.keys(t))if(!O(n,i)){let e=l(i),u=o?` for ${o.name}`:"";throw new a(`unknown option --${e}${u}`)}}r(V,"validateCommandOptions");export{a,k as b};
2
+ import{e as g,g as $,h as O,i as C}from"./chunk-TYWBEJOA.js";import{a as w}from"./chunk-3M53YXEI.js";import{a as r}from"./chunk-FTQLQJQV.js";var L=Symbol("openpondCliOptionValues"),a=class extends Error{static{r(this,"CliUsageError")}exitCode=2;constructor(t){super(t),this.name="CliUsageError"}},K=new Set(["maxOutputBytes","timeoutSec"]);function k(n){let t=[...n],o="",i={},e={},u=[];for(;t.length>0;){let s=t.shift();if(s==="--"){u.push(...t);break}if(s.startsWith("--")){let f=s.indexOf("="),c=f>=0?s.slice(2,f):s.slice(2),p=N(c),d=f>=0?s.slice(f+1):P(t,p,o);h(i,e,p,d,o)}else _(s)?y(s,t,i,e):o?u.push(s):o=s}return Object.defineProperty(i,L,{value:e,enumerable:!1,configurable:!1,writable:!1}),V(o,i),{command:o,options:i,rest:u}}r(k,"parseArgs");function N(n){return n.replace(/-([a-z])/g,(t,o)=>o.toUpperCase())}r(N,"normalizeCliOptionKey");function _(n){return/^-[^-].*/.test(n)&&!S(n)}r(_,"isShortOptionToken");function y(n,t,o,i){let e=n.slice(1);if(!e)return;let u=e.indexOf("="),s=u>=0?e.slice(0,u):e,f=u>=0?e.slice(u+1):null;if(s.length!==1){for(let d of s){let m=g[d];if(!m)throw new a(`unknown short option -${d}`);if(C(m)!=="boolean")throw new a(`short option -${d} requires its own value`);h(o,i,m,"true")}return}let c=g[s];if(!c)throw new a(`unknown short option -${s}`);let p=f??P(t,c);h(o,i,c,p)}r(y,"parseShortOptionToken");function P(n,t,o){let i=I(t,o);if(i==="boolean")return n[0]&&x(n[0])?n.shift():"true";if(i){let e=n.shift();if(e===void 0||R(e)&&!S(e))throw e!==void 0&&n.unshift(e),new a(`${l(t)} must be ${b(i)}`);return e}return n[0]&&!n[0].startsWith("--")?n.shift():"true"}r(P,"readOptionValue");function h(n,t,o,i,e){T(o,i,e),n[o]=i,(t[o]??=[]).push(i)}r(h,"setParsedOption");function T(n,t,o){let i=I(n,o);if(i){if(i==="boolean"){if(!x(t))throw new a(`${l(n)} must be a boolean`);return}if(t.trim().length===0||t==="true")throw new a(`${l(n)} must be ${b(i)}`);if(i==="number"||i==="integer"){let e=Number(t);if(!Number.isFinite(e))throw new a(`${l(n)} must be ${b(i)}`);if(i==="integer"&&!Number.isInteger(e))throw new a(`${l(n)} must be an integer`);if(i==="integer"&&K.has(n)&&e<=0)throw new a(`${l(n)} must be a positive integer`);return}if(i==="json")try{w(t,l(n))}catch(e){throw new a(e instanceof Error?e.message:String(e))}}}r(T,"validateParsedOptionValue");function I(n,t){return t?O(t,n):C(n)}r(I,"typedOptionKind");function l(n){return n.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}r(l,"cliOptionLabel");function E(n){return n==="json"?"JSON value":n}r(E,"optionKindLabel");function b(n){let t=E(n);return/^[aeiou]/i.test(t)?`an ${t}`:`a ${t}`}r(b,"optionKindPhrase");function x(n){return/^(true|false|1|0|yes|no)$/i.test(n)}r(x,"isBooleanLiteral");function R(n){return n.startsWith("-")&&n!=="-"}r(R,"isOptionLike");function S(n){return/^-\d+(?:\.\d+)?$/.test(n)}r(S,"isNegativeNumber");function V(n,t){let o=n?$(n):null;for(let i of Object.keys(t))if(!O(n,i)){let e=l(i),u=o?` for ${o.name}`:"";throw new a(`unknown option --${e}${u}`)}}r(V,"validateCommandOptions");export{a,k as b};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{L as r}from"./chunk-6QUICEQA.js";import{P as o}from"./chunk-XWLI7WJH.js";import{d as t}from"./chunk-QVRNOGAU.js";import{e as a}from"./chunk-HZP5U2AA.js";import{b as e}from"./chunk-ES2ISFJC.js";var s=e.object({profileRef:r,manifest:o,metric:t,gradeRefs:e.array(a),receiptRefs:e.array(a),passRate:e.number().min(0).max(1),passed:e.boolean(),completedAt:e.string().datetime(),contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict();export{s as a};
2
+ import{L as r}from"./chunk-6JBWHR6T.js";import{r as o}from"./chunk-JO7GRBOG.js";import{l as t}from"./chunk-BQNK2NMB.js";import{e as a}from"./chunk-P653BXMY.js";import{b as e}from"./chunk-ES2ISFJC.js";var s=e.object({profileRef:r,manifest:o,metric:t,gradeRefs:e.array(a),receiptRefs:e.array(a),passRate:e.number().min(0).max(1),passed:e.boolean(),completedAt:e.string().datetime(),contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict();export{s as a};
@@ -1,11 +1,11 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as be,b as Ae,c as Ie,d as ve}from"./chunk-V62BHD5G.js";import{c as O,i as L}from"./chunk-DXAZUJPA.js";import{a as Oe}from"./chunk-6FA3GG5B.js";import{f as Re}from"./chunk-H7IWJN7L.js";import{a as s}from"./chunk-FTQLQJQV.js";var W=class extends Error{static{s(this,"OpenPondProfileSetupRequiredError")}code="agent_source_setup_required";details;constructor(t,n){let o=n.blockingRequirements.map(r=>r.label);super(["agent_source_setup_required",`Profile action ${t} has unresolved required setup.`,o.length?`Missing setup: ${o.join(", ")}`:""].filter(Boolean).join(`
2
+ import{a as be,b as Ae,c as Ie,d as ve}from"./chunk-ZC57DX6D.js";import{a as Re}from"./chunk-6FA3GG5B.js";import{c as O,i as L}from"./chunk-6SJZXZNA.js";import{f as Oe}from"./chunk-H7IWJN7L.js";import{a as s}from"./chunk-FTQLQJQV.js";var W=class extends Error{static{s(this,"OpenPondProfileSetupRequiredError")}code="agent_source_setup_required";details;constructor(t,n){let o=n.blockingRequirements.map(r=>r.label);super(["agent_source_setup_required",`Profile action ${t} has unresolved required setup.`,o.length?`Missing setup: ${o.join(", ")}`:""].filter(Boolean).join(`
3
3
  `)),this.name="OpenPondProfileSetupRequiredError",this.details={error:"agent_source_setup_required",actionId:t,setupGate:n,missing:o,blockingSetupRequirements:n.blockingRequirements,setupRequirements:n.requirements}}};function K(e){let t=new Map;for(let a of e.sourceSetupRequirements??[]){let l=bt(a);if(e.actionId&&l&&l!==e.actionId&&h(a.actionName)!==e.actionId&&h(a.sourceActionId)!==e.actionId)continue;let c=Ee({record:a,source:"source_upload_metadata",actionId:l});c&&t.set(c.ref,c)}for(let a of e.actionCatalog)if(!(e.actionId&&a.id!==e.actionId&&a.name!==e.actionId))for(let l of a.setupRequirements??[]){let c=Ee({record:l,source:"action_catalog",actionId:a.id});c&&t.set(c.ref,c)}let n=Array.from(t.values()),o=n.filter(a=>a.blocking),r=n.filter(a=>!a.required&&!ne(a.status)).length,i=n.filter(a=>ne(a.status)).length;return{status:It(o),requirementCount:n.length,blockingCount:o.length,optionalMissingCount:r,readyCount:i,requirements:n,blockingRequirements:o}}s(K,"buildOpenPondProfileSetupGate");function oe(e,t){if(t.blockingRequirements.length>0)throw new W(e,t)}s(oe,"assertOpenPondProfileActionReady");function Rt(e){let t=e.actionId?`${e.actionId}: `:"",n=e.required?"required":"optional";return`${t}${e.label} (${n}, ${e.status})`}s(Rt,"formatOpenPondProfileSetupRequirement");function Ee(e){let t=e.source==="action_catalog"&&h(e.record.source)==="source_upload_metadata"?"source_upload_metadata":e.source,n=h(e.record.kind)??h(e.record.type),o=h(e.record.label)??h(e.record.name)??h(e.record.key)??h(e.record.provider)??h(e.record.tool)??h(e.record.command)??h(e.record.packageName)??h(e.record.path)??h(e.record.repo)??h(e.record.url)??h(e.record.id)??n??"setup requirement",r=e.record.required!==!1,i=At(e.record);return{ref:[t,e.actionId??"source",n??"requirement",o].join(":"),source:t,actionId:e.actionId,kind:n,label:o,status:i,required:r,blocking:r&&!ne(i)}}s(Ee,"setupRequirementFromRecord");function bt(e){return h(e.actionId)??h(e.sourceActionId)??h(e.actionName)}s(bt,"setupRequirementActionId");function At(e){let t=h(e.status)??h(e.state);return t?t==="satisfied"||t==="connected"||t==="provided"?"ready":t:typeof e.satisfied=="boolean"?e.satisfied?"ready":"setup_required":typeof e.ready=="boolean"&&e.ready?"ready":"setup_required"}s(At,"setupStatus");function It(e){return e.length===0?"ready":e.some(t=>["blocked","unsupported","unsupported_dependency","stale"].includes(t.status))?"blocked":"setup_required"}s(It,"gateStatus");function ne(e){return e==="ready"||e==="disabled"}s(ne,"isReadyStatus");function h(e){return typeof e=="string"&&e.trim()?e.trim():null}s(h,"text");import{stat as qt}from"node:fs/promises";import se from"node:path";import{spawn as vt}from"node:child_process";import{existsSync as re}from"node:fs";import{readFile as Et,rm as Kn,writeFile as _e}from"node:fs/promises";import ie from"node:path";var Le=["**/node_modules/","**/.bun/","**/.env","**/.env.*","**/.openpond/traces/","**/.openpond/vendor/","**/.openpond/eval-results.json","**/.openpond/artifact-index.json","**/.openpond/source-upload-cache.json",""].join(`
4
4
  `);async function Me(e){if(!re(ie.join(e,".git"))){let i=await R(e,["init","-b","main"]);if(i.code!==0)throw new Error(H("git init",i))}let t=ie.join(e,".gitignore");if(re(t)?await xt(t):await _e(t,Le,"utf8"),await _t(e))return;let n=await N(e);if(!n.dirty&&n.files.length===0)return;let o=await R(e,["add","-A"]);if(o.code!==0)throw new Error(H("git add",o));let r=await R(e,["commit","-m","Initialize OpenPond profile"],{env:{...process.env,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"}});if(r.code!==0&&!/nothing to commit/i.test(r.stdout+r.stderr))throw new Error(H("git commit",r))}s(Me,"ensureProfileGitRepo");async function xt(e){let t=await Et(e,"utf8").catch(()=>""),n=Le.split(/\r?\n/).map(r=>r.trim()).filter(Boolean).filter(r=>!t.split(/\r?\n/).some(i=>i.trim()===r));if(n.length===0)return;let o=t.endsWith(`
5
5
  `)||t.length===0?"":`
6
6
  `;await _e(e,`${t}${o}${n.join(`
7
7
  `)}
8
- `,"utf8")}s(xt,"ensureProfileGitignoreRules");async function N(e){if(!re(ie.join(e,".git")))return{isRepo:!1,branch:null,head:null,shortHead:null,dirty:!1,upstream:null,ahead:null,behind:null,remoteUrl:null,files:[],error:null};let t=await R(e,["rev-parse","--is-inside-work-tree"]);if(t.code!==0||t.stdout.trim()!=="true")return{isRepo:!1,branch:null,head:null,shortHead:null,dirty:!1,upstream:null,ahead:null,behind:null,remoteUrl:null,files:[],error:t.stderr.trim()||t.stdout.trim()||"not a Git work tree"};let[n,o,r,i,a]=await Promise.all([B(e,["branch","--show-current"]),B(e,["rev-parse","HEAD"]),R(e,["status","--porcelain=v1","-uall"]),B(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"]),B(e,["remote","get-url","origin"])]),l=r.code===0?Mt(r.stdout):[],c=i?await Lt(e):{ahead:null,behind:null},d=o||null;return{isRepo:!0,branch:n||null,head:d,shortHead:d?d.slice(0,12):null,dirty:l.length>0,upstream:i,ahead:c.ahead,behind:c.behind,remoteUrl:a,files:l,error:r.code===0?null:H("git status",r)}}s(N,"loadProfileGitState");async function $e(e,t){let n=await N(e);if(!n.isRepo)throw new Error(n.error??"Active OpenPond profile source is not a Git repo.");if(!n.dirty)return{committed:!1,stdout:"",stderr:"",state:n};let o=await R(e,["add","-A"]);if(o.code!==0)throw new Error(H("git add",o));let r=await R(e,["commit","-m",t]);if(r.code!==0)throw new Error(H("git commit",r));return{committed:!0,stdout:r.stdout,stderr:r.stderr,state:await N(e)}}s($e,"commitProfileChanges");async function qe(e){return B(e,["rev-parse","HEAD"])}s(qe,"profileGitHead");async function _t(e){return(await R(e,["rev-parse","--verify","HEAD"])).code===0}s(_t,"hasGitHead");async function Lt(e){let t=await R(e,["rev-list","--left-right","--count","@{u}...HEAD"]);if(t.code!==0)return{ahead:null,behind:null};let[n,o]=t.stdout.trim().split(/\s+/),r=n?Number.parseInt(n,10):Number.NaN,i=o?Number.parseInt(o,10):Number.NaN;return{ahead:Number.isFinite(i)?i:null,behind:Number.isFinite(r)?r:null}}s(Lt,"loadAheadBehind");async function B(e,t){let n=await R(e,t);return n.code!==0?null:n.stdout.trim()||null}s(B,"gitText");function Mt(e){return e.split(/\r?\n/).map(t=>t.trimEnd()).filter(Boolean).map(t=>{let n=t[0]??" ",o=t[1]??" ",r=`${n}${o}`.trim()||"changed",i=t.slice(3),a=i.split(" -> "),l=n===" "?null:n,c=o===" "?null:o,d=a.length===2?a[1]:i,g=a.length===2?a[0]:null;return{path:xe(d),originalPath:g?xe(g):null,indexStatus:l,worktreeStatus:c,status:r,category:$t(l,c)}})}s(Mt,"parsePorcelainStatus");function $t(e,t){return e==="?"&&t==="?"?"untracked":e==="R"||t==="R"?"renamed":e==="A"||t==="A"?"added":e==="D"||t==="D"?"deleted":e==="M"||t==="M"?"modified":"changed"}s($t,"gitChangeCategory");function xe(e){let t=e.trim();if(!t.startsWith('"')||!t.endsWith('"'))return t;try{return JSON.parse(t)}catch{return t.slice(1,-1)}}s(xe,"unquoteGitPath");function H(e,t){return t.stderr.trim()||t.stdout.trim()||`${e} failed with exit code ${t.code??"unknown"}`}s(H,"gitFailureMessage");async function R(e,t,n={}){return new Promise((o,r)=>{let i=vt("git",t,{cwd:e,env:n.env,stdio:"pipe"}),a="",l="";i.stdout?.on("data",c=>{a+=String(c)}),i.stderr?.on("data",c=>{l+=String(c)}),i.on("error",r),i.on("close",c=>{o({code:c,stdout:a,stderr:l})}),n.input!==void 0?i.stdin?.end(n.input):i.stdin?.end()})}s(R,"runGitCommand");var ae=1500,Te=8*1024*1024,le=100*1024*1024,ce=8,jt={maxFiles:ae,maxFileBytes:Te,maxTotalBytes:le,concurrency:ce},Ft={mode:"single_json_payload",chunkingSupported:!1};async function Tt(e){let t=await R(e,["ls-files","-z"]);if(t.code!==0)throw new Error(t.stderr.trim()||t.stdout.trim()||"git ls-files failed for profile source upload");let n=t.stdout.split("\0").map(c=>c.trim()).filter(Boolean).filter(c=>{let d=c.replace(/\\/g,"/");return Fe(d)&&!Gt(d)}).sort();if(n.length===0)throw new Error("No committed profile source files found to upload.");if(n.length>ae)throw new Error(`Too many profile source files to upload: ${n.length} > ${ae}`);let o=(await je(n,ce,async c=>{let d=se.resolve(e,c),g=se.relative(e,d).replace(/\\/g,"/");if(!Fe(g))throw new Error(`Profile source path escapes repo: ${c}`);let P=await qt(d);if(!P.isFile())return null;if(P.size>Te)throw new Error(`Profile source file is too large: ${c} (${P.size} bytes)`);return{path:g,absolutePath:d,size:P.size,mtimeMs:Math.trunc(P.mtimeMs),ctimeMs:Math.trunc(P.ctimeMs)}})).filter(c=>c!==null),r=0;for(let c of o)if(r+=c.size,r>le)throw new Error(`Profile source upload is too large: ${r} > ${le}`);let i=await Ae(e),a=await je(o,ce,async c=>Ie(c,i));await ve(e,a).catch(()=>{});let l=a.map(c=>c.entry);return{entries:l,fileCount:l.length,totalBytes:r,limits:jt,transport:Ft}}s(Tt,"collectProfileSourceUploadEntries");async function je(e,t,n){let o=new Array(e.length),r=0,i=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:i},async()=>{for(;r<e.length;){let a=r;r+=1,o[a]=await n(e[a],a)}})),o}s(je,"mapWithConcurrency");function Fe(e){return e.length>0&&!e.includes("\0")&&!se.isAbsolute(e)&&!e.split(/[\\/]+/).some(t=>!t||t==="."||t==="..")}s(Fe,"isSafeProfileSourcePath");function Gt(e){return e.split(/[\\/]+/).some((t,n,o)=>{let r=t.toLowerCase();if(r===".git"||r==="node_modules"||r===".bun"||r===".env"||r.startsWith(".env.")||e.replace(/\\/g,"/")===be)return!0;if(r!==".openpond")return!1;let i=o[n+1]?.toLowerCase();return i==="goals"||i==="traces"||i==="vendor"||i==="eval-results.json"||i==="artifact-index.json"})}s(Gt,"shouldSkipProfileSourcePath");function Ht(e){let t=y(e.checkResult),n=y(t?.deployPlan)??y(e.deployPlan),o=y(n?.source),r=y(n?.checks),i=y(t?.sourceCheckStatus);return{status:e.status,agentId:e.agentId,deployPlanStatus:f(n?.status),canRun:Ge(n?.canRun),canDeploy:Ge(n?.canDeploy),sourceRef:f(o?.sourceRef),sourceCommitSha:f(o?.sourceCommitSha),manifestHash:f(o?.manifestHash),manifestPath:f(o?.manifestPath),setupCommands:b(r?.setupCommands),validationCommands:b(r?.validationCommands),requiredChecks:b(r?.requiredChecks),evalNames:b(r?.evalNames),blockedReasons:b(n?.blockedReasons),staleReasons:b(n?.staleReasons),runtimeId:f(i?.latestRuntimeId),sandboxId:f(i?.latestSandboxId),traceArtifactRefs:b(i?.traceArtifactRefs),evalResultArtifactRefs:b(i?.evalResultArtifactRefs),validatorArtifactRefs:b(i?.validatorArtifactRefs),checkedAt:e.checkedAt??new Date().toISOString(),error:e.error??null}}s(Ht,"hostedSourceCheckStatusFromPayload");function Nt(e){let t=y(e.publishResult),n=y(t?.activeManifestSnapshot)??y(t?.manifestSnapshot)??y(t?.snapshot);return{status:e.status??"published",agentId:e.agentId,snapshotId:f(n?.id),sourceRef:f(n?.sourceRef),sourceCommitSha:f(n?.sourceCommitSha),manifestHash:f(n?.manifestHash),manifestPath:f(n?.manifestPath),buildStatus:f(n?.buildStatus),validationStatus:f(n?.validationStatus),evalStatus:f(n?.evalStatus),publishedAt:f(t?.publishedAt)??f(n?.publishedAt),error:e.error??null}}s(Nt,"hostedPublishStatusFromPayload");function Ut(e){let t=y(e.runResult),n=y(t?.run),o=y(n?.runtimeSource),r=y(n?.metadata),i=y(r?.sourceSummary),a=y(r?.setupGate),l=y(r?.responseSummary),c=y(r?.traceSummary),d=y(r?.evalSummary);return{status:f(n?.status)??(e.error?"failed":"running"),agentId:f(n?.agentId)??e.agentId,runId:f(n?.id),runtimeId:f(n?.runtimeId),sandboxId:f(n?.sandboxId),sourceRef:f(o?.sourceRef)??f(i?.sourceRef)??f(r?.sourceRef),sourceCommitSha:f(o?.sourceCommitSha)??f(i?.sourceCommitSha)??f(r?.hostedHead),manifestHash:f(o?.manifestHash)??f(i?.manifestHash),setupGateStatus:f(a?.status),setupRequirementRefs:Bt(a),artifactRefs:b(l?.artifactRefs),traceArtifactRefs:b(c?.artifactRefs),evalArtifactRefs:b(d?.artifactRefs),startedAt:f(n?.createdAt),completedAt:f(n?.completedAt),error:e.error??null}}s(Ut,"hostedRunSummaryFromPayload");function Dt(e){return e?.status?e.status==="succeeded"||e.status==="passed"?"passed":e.status==="failed"||e.status==="cancelled"?"failed":"running":"not_started"}s(Dt,"hostedRunStatusFromRunSummary");function Bt(e){return e?(Array.isArray(e.requirements)?e.requirements:Array.isArray(e.blockingRequirements)?e.blockingRequirements:[]).map(n=>{let o=y(n);return f(o?.ref)??f(o?.id)??f(o?.label)}).filter(n=>!!n):[]}s(Bt,"setupRequirementRefs");function y(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}s(y,"record");function f(e){return typeof e=="string"&&e.trim()?e.trim():null}s(f,"text");function Ge(e){return typeof e=="boolean"?e:null}s(Ge,"booleanValue");function b(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}s(b,"textArray");import{createRequire as st}from"node:module";import{createHash as et,randomUUID as tt}from"node:crypto";import{spawn as hn}from"node:child_process";import{existsSync as k}from"node:fs";import{cp as yn,mkdir as v,readFile as at,readdir as lt,rename as Pe,rm as he,symlink as wn,writeFile as D}from"node:fs/promises";import u from"node:path";function ue(e=null){return{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!0,error:e}}s(ue,"emptyProfileCatalogState");function de(e=null){return{skillCount:0,generatedAt:null,stale:!0,error:e}}s(de,"emptyProfileSkillCatalogState");function fe(){return{status:"ready",requirementCount:0,blockingCount:0,optionalMissingCount:0,readyCount:0,requirements:[],blockingRequirements:[]}}s(fe,"emptyProfileSetupGate");function Y(){return{changedAgents:[],newAgents:[],deletedAgents:[],changedSkills:[],changedActions:[],changedExtensions:[],setupChanges:[],envRequirementChanges:[],files:[]}}s(Y,"emptyProfileDiffSummary");function pe(e=null){return{state:e?"error":"none",message:e??"No active OpenPond profile.",agentCount:0,actionCount:0,defaultAction:null,checkFresh:!1,checkStaleReason:e??"No active profile.",localHead:null,hostedHead:null}}s(pe,"emptyProfileSummary");import{existsSync as U}from"node:fs";import{readFile as zt,stat as Jt}from"node:fs/promises";import V from"node:path";var He=".openpond/agent-manifest.json",Ne=".openpond/action-registry.json",Wt=".openpond/source-upload-metadata.json",Kt=".openpond/agent-package-origin.json";async function Be(e){return Je({agentId:"default",sourcePath:e,preferred:!0})}s(Be,"loadProfileActionCatalog");async function ze(e){if(e.length===0)return{catalog:{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!1,error:null},actionCatalog:[],sourceSetupRequirements:[]};let t=[...e.filter(l=>l.preferred),...e.filter(l=>!l.preferred)],n=await Promise.all(t.map(Je)),o=new Map,r=[];for(let l of n)for(let c of l.actionCatalog){let d=o.has(c.id)?`${c.agentId??"agent"}.${c.sourceActionId??c.id}`:c.id,g=d===c.id?c:{...c,id:d};o.set(d,g),r.push(g)}let i=Vt(n.map(l=>l.catalog.generatedAt)),a=n.map(l=>l.catalog.error).filter(Boolean);return{catalog:{actionCount:r.length,generatedAt:i,manifestPath:n.find(l=>l.catalog.manifestPath)?.catalog.manifestPath??null,registryPath:n.find(l=>l.catalog.registryPath)?.catalog.registryPath??null,stale:n.some(l=>l.catalog.stale),error:a.length>0?a.join("; "):null},actionCatalog:r,sourceSetupRequirements:n.flatMap(l=>l.sourceSetupRequirements)}}s(ze,"loadProfileActionCatalogForSources");async function Je(e){let t=e.sourcePath,n=V.join(t,He),o=V.join(t,Ne),r=V.join(t,Wt),i=V.join(t,Kt);try{let a=await X(n),l=await X(o),c=await X(r),d=w(await X(i)),g=w(w(a)?.inputSchemas),P=De(w(c)?.setupRequirements)??[],x=Xt(P),S=new Map;for(let m of[...ge(w(a)?.actionCatalog),...ge(w(l)?.actions),...ge(w(a)?.actions)]){let $=p(m.id)??p(m.name);if(!$)continue;let C=S.get($),kt=Zt({sourceRequirementsByAction:x,actionId:$,actionName:p(m.name)}),Ct=Qt(De(m.setupRequirements)??C?.setupRequirements??[],kt),Ot={id:$,agentId:e.agentId,sourcePath:t,sourceActionId:$,name:p(m.name)??C?.name??$,label:p(m.label)??C?.label??rn($),description:p(m.description)??C?.description??null,visibility:p(m.visibility)??C?.visibility??"default",inputSchema:on(m.inputSchema,g)??C?.inputSchema??null,outputSchema:We(m.outputSchema)??C?.outputSchema??null,approvalPolicy:w(m.approvalPolicy)??C?.approvalPolicy??null,artifactPolicy:w(m.artifactPolicy)??C?.artifactPolicy??null,setupRequirements:Ct,mcp:w(m.mcp)??C?.mcp??null,schedulePolicy:w(m.schedulePolicy)??C?.schedulePolicy??null,trace:Yt(w(m.trace)??C?.trace??null,d),implementation:w(m.implementation)??C?.implementation??null,invokesModel:typeof m.invokesModel=="boolean"?m.invokesModel:C?.invokesModel};S.set($,Ot)}let M=Array.from(S.values()).filter(m=>m.visibility!=="internal"&&m.visibility!=="debug"),G=[...a?[]:[He],...l?[]:[Ne]],_=await nn([n,o]);return{catalog:{actionCount:M.length,generatedAt:_,manifestPath:U(n)?n:null,registryPath:U(o)?o:null,stale:G.length>0,error:G.length>0?tn(e,G):null},actionCatalog:M,sourceSetupRequirements:P}}catch(a){return{catalog:{actionCount:0,generatedAt:null,manifestPath:U(n)?n:null,registryPath:U(o)?o:null,stale:!0,error:a instanceof Error?a.message:String(a)},actionCatalog:[],sourceSetupRequirements:[]}}}s(Je,"loadProfileActionCatalogSource");function Yt(e,t){if(!t)return e;let n=p(t.versionId),o=p(t.digest);return!n||!o?e:{...e??{},agentVersionId:n,agentPackageDigest:o,validationReceiptIds:Ue(t.validationReceiptIds),evalReceiptIds:Ue(t.evalReceiptIds)}}s(Yt,"mergeAgentPackageTrace");function Ue(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}s(Ue,"stringArray");function Vt(e){let t=0;for(let n of e){if(!n)continue;let o=Date.parse(n);Number.isFinite(o)&&(t=Math.max(t,o))}return t>0?new Date(t).toISOString():null}s(Vt,"latestIso");function Xt(e){let t=new Map;for(let n of e){let o=[p(n.actionId),p(n.sourceActionId),p(n.actionName)].filter(r=>!!r);for(let r of o){let i=t.get(r)??[];i.push(n),t.set(r,i)}}return t}s(Xt,"sourceSetupRequirementsByAction");function Zt(e){return[...e.sourceRequirementsByAction.get(e.actionId)??[],...e.actionName&&e.actionName!==e.actionId?e.sourceRequirementsByAction.get(e.actionName)??[]:[]].map(n=>({...n,source:"source_upload_metadata"}))}s(Zt,"setupRequirementsForActionSource");function Qt(e,t){if(t.length===0)return e;let n=[],o=new Set;for(let r of[...e,...t]){let i=en(r);o.has(i)||(o.add(i),n.push(r))}return n}s(Qt,"mergeSetupRequirements");function en(e){return[p(e.actionId)??p(e.sourceActionId)??p(e.actionName)??"",p(e.kind)??p(e.type)??"",p(e.name)??p(e.key)??p(e.provider)??p(e.tool)??p(e.command)??p(e.packageName)??p(e.path)??p(e.repo)??p(e.url)??p(e.id)??""].join(":")}s(en,"setupRequirementIdentity");function tn(e,t){return[`Profile agent ${e.agentId} at ${e.sourcePath} is missing SDK catalog artifact(s): ${t.join(", ")}.`,"Run `openpond profile check --kind all` after source materialization so each enabled profile agent has inspect/build artifacts."].join(" ")}s(tn,"missingSourceArtifactsMessage");async function X(e){return U(e)?JSON.parse(await zt(e,"utf8")):null}s(X,"readJsonIfExists");async function nn(e){let t=0;for(let n of e){if(!U(n))continue;let o=await Jt(n);t=Math.max(t,o.mtimeMs)}return t>0?new Date(t).toISOString():null}s(nn,"latestMtime");function w(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}s(w,"asRecord");function ge(e){return Array.isArray(e)?e.filter(t=>!!w(t)):[]}s(ge,"records");function De(e){return Array.isArray(e)?e.filter(t=>!!w(t)):null}s(De,"recordArray");function p(e){return typeof e=="string"&&e.trim()?e.trim():null}s(p,"text");function We(e){return p(e)??w(e)}s(We,"schemaValue");function on(e,t){let n=We(e);return typeof n!="string"?n:w(t?.[n])??n}s(on,"resolvedSchemaValue");function rn(e){let t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}s(rn,"titleFromActionId");import{createHash as sn}from"node:crypto";import{existsSync as Xe}from"node:fs";import{readdir as Ze,readFile as an,stat as ln}from"node:fs/promises";import q from"node:path";var me="skills",Z="SKILL.md",Ke=8e4;async function Qe(e){let t=q.join(e,me);if(!Xe(t))return{skillCatalog:Ye({stale:!1}),skills:[]};try{let n=await Ze(t,{withFileTypes:!0}),o=(await Promise.all(n.filter(i=>i.isDirectory()).map(i=>un(e,i.name)))).sort((i,a)=>i.name.localeCompare(a.name)||i.path.localeCompare(a.path));fn(o);let r=await pn(e,o);return{skillCatalog:{skillCount:o.length,generatedAt:r,stale:!1,error:null},skills:o}}catch(n){return{skillCatalog:Ye({stale:!0,error:n instanceof Error?n.message:String(n)}),skills:[]}}}s(Qe,"loadProfileSkills");function cn(e){let t=[],n=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/.exec(e);if(!n)return{name:null,description:null,body:e.trim(),messages:["SKILL.md must start with YAML frontmatter bounded by ---."]};let o=n[1]??"",r=(n[2]??"").trim(),i;try{i=Oe.load(o)}catch(d){t.push(`SKILL.md frontmatter is invalid YAML: ${d instanceof Error?d.message:String(d)}`)}let a=mn(i),l=Ve(a?.name),c=Ve(a?.description);return l||t.push("Skill frontmatter must include a non-empty name."),c||t.push("Skill frontmatter must include a non-empty description."),r||t.push("Skill body must be non-empty markdown."),{name:l,description:c,body:r,messages:t}}s(cn,"parseProfileSkillMarkdown");function Ye(e={}){return{skillCount:0,generatedAt:null,stale:e.stale??!0,error:e.error??null}}s(Ye,"emptyProfileSkillCatalogState");async function un(e,t){let n=q.join(me,t,Z).replace(/\\/g,"/"),o=q.join(e,n),r=[],i=q.join(e,me,t),a=await dn(i),l="";Xe(o)?l=await an(o,"utf8"):r.push(`Missing ${Z}.`),l.length>Ke&&r.push(`Skill markdown exceeds the limit of ${Ke} characters.`);let c=cn(l);r.push(...c.messages);let d=c.name??t,g=c.description??"";return gn(d)||r.push("Skill name must be lowercase kebab-case."),d!==t&&r.push(`Skill name must match its directory name (${t}).`),{name:d,description:g,path:n,scope:"profile",enabled:r.length===0,sourcePath:e,charCount:l.length,sourceHash:Pn(l),validationStatus:r.length>0?"error":"valid",validationMessages:r,resourceFiles:a.filter(P=>P!==Z)}}s(un,"loadProfileSkillDirectory");async function dn(e){let t=[];async function n(o,r){let i=await Ze(o,{withFileTypes:!0});await Promise.all(i.map(async a=>{let l=r?`${r}/${a.name}`:a.name;a.isDirectory()?await n(q.join(o,a.name),l):a.isFile()&&t.push(l)}))}return s(n,"visit"),await n(e,""),t.sort()}s(dn,"listPackageFiles");function fn(e){let t=new Map;for(let n of e)t.set(n.name,(t.get(n.name)??0)+1);for(let n of e)(t.get(n.name)??0)<=1||(n.enabled=!1,n.validationStatus="error",n.validationMessages=[...n.validationMessages,`Duplicate skill name: ${n.name}`])}s(fn,"markDuplicateSkillNames");async function pn(e,t){let n=0;for(let o of t){let r=q.dirname(q.join(e,o.path)),i=[Z,...o.resourceFiles];for(let a of i){let l=await ln(q.join(r,a)).catch(()=>null);l?.isFile()&&(n=Math.max(n,l.mtimeMs))}}return n>0?new Date(n).toISOString():null}s(pn,"latestSkillMtime");function gn(e){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)}s(gn,"isKebabCaseSkillName");function mn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}s(mn,"asRecord");function Ve(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}s(Ve,"text");function Pn(e){return sn("sha256").update(e).digest("hex")}s(Pn,"sha256Hex");var F="openpond-profile.json",Sn="settings/profile.yaml",ct="default",E="default";function kn(e,t){let n=e?.defaultAgent??E,o=e?.enabledAgents&&e.enabledAgents.length>0?e.enabledAgents:[n];return{...e??{},path:t,defaultAgent:n,enabledAgents:o}}s(kn,"mergeProfileRepoManifestEntry");function ee(e,t,n){let o=A(e);if(e){let l=o.findIndex(d=>u.resolve(d.repoPath)===u.resolve(e.repoPath)&&d.profile===e.profile),c={source:o[l]?.source??"local",repositoryId:o[l]?.repositoryId??u.resolve(e.repoPath),repoPath:u.resolve(e.repoPath),profile:e.profile,...e.lastCheck?{lastCheck:e.lastCheck}:{},...e.lastPush?{lastPush:e.lastPush}:{}};l>=0?o[l]=c:o.push(c)}let r=o.findIndex(l=>u.resolve(l.repoPath)===u.resolve(t)&&l.profile===n),i=r>=0?o[r]:{source:"local",repositoryId:u.resolve(t),repoPath:u.resolve(t),profile:n};return r<0&&o.push(i),{repoPath:u.resolve(t),profile:n,mode:"local",profiles:o,...i.lastCheck?{lastCheck:i.lastCheck}:{},...i.lastPush?{lastPush:i.lastPush}:{}}}s(ee,"mergeActiveLocalProfileConfig");function A(e){if(!e)return[];let t=e.profiles?.map(n=>({...n}))??[];return t.some(n=>u.resolve(n.repoPath)===u.resolve(e.repoPath)&&n.profile===e.profile)||t.push({source:"local",repositoryId:u.resolve(e.repoPath),repoPath:u.resolve(e.repoPath),profile:e.profile,...e.lastCheck?{lastCheck:e.lastCheck}:{},...e.lastPush?{lastPush:e.lastPush}:{}}),t}s(A,"profileConfigEntries");var Cn=st(import.meta.url);function On(){return u.join(Re(),"library","profiles","default-repo")}s(On,"defaultLocalProfileRepoPath");function ut(e=null){return{mode:"none",repoPath:null,activeProfile:null,sourcePath:null,manifestPath:null,agents:[],skills:[],evals:[],git:null,catalog:ue(e),skillCatalog:de(e),actionCatalog:[],sourceSetupRequirements:[],setupGate:fe(),diff:Y(),hosted:null,summary:pe(e),lastCheck:null,error:e}}s(ut,"emptyProfileState");async function qo(e={}){let t=u.resolve(e.repoPath??On()),n=ke(e.profile),o=u.join("profiles",n),r=u.join(t,o),i=e.template??"blank-agent",a=i==="blank-profile";await v(t,{recursive:!0});let l=k(u.join(t,F)),c=await T(t).catch(()=>Tn(n,o));if(a&&l&&c.profiles[n])throw new Error(`Profile "${n}" already exists in ${t}.`);c.defaultProfile=c.defaultProfile||n,c.profiles[n]=kn(c.profiles[n],o),a&&(c.profiles[n].enabledAgents=[]),a?await v(r,{recursive:!0}):await In(r,i,!!e.force),await pt(r),await vn(t,r,n,{includeDefaultAgent:!a}),await Q(t,c),await Me(t);let d=(await O()).openpondProfile;return await L({openpondProfile:ee(d,t,n)}),j()}s(qo,"initLocalProfileRepo");async function jo(e,t,n){let o=u.resolve(e),r=await T(o),i=ke(t??r.defaultProfile);Ce(r,o,i);let a=(await O()).openpondProfile,l=ee(a,o,i);return dt(l,o,i,n),await L({openpondProfile:l}),j()}s(jo,"loadLocalProfileRepo");async function Fo(e,t,n){let o=u.resolve(e),r=await T(o),i=ke(t??r.defaultProfile);Ce(r,o,i);let a=(await O()).openpondProfile,l=ee(a,o,i);return dt(l,o,i,n),a&&(l.repoPath=a.repoPath,l.profile=a.profile,l.lastCheck=a.lastCheck,l.lastPush=a.lastPush),await L({openpondProfile:l}),bn(ye({repoPath:o,profile:i,source:n?.source,repositoryId:n?.repositoryId}))}s(Fo,"registerLocalProfileRepo");function dt(e,t,n,o){o&&(e.profiles=A(e).map(r=>u.resolve(r.repoPath)===t&&r.profile===n?{...r,source:o.source,repositoryId:o.repositoryId}:r))}s(dt,"applyProfileIdentity");async function To(e,t){let n=e.trim(),o=Fn(t);if(!n)throw new Error("Agent ID is required.");let i=(await O()).openpondProfile;if(!i)throw new Error("No active local Profile.");let a=await T(i.repoPath),l=a.profiles[i.profile];if(!l)throw new Error(`Profile "${i.profile}" was not found.`);let c=l.defaultAgent??E;if(!(l.enabledAgents??[c]).includes(n))throw new Error(`Agent "${n}" was not found in Profile "${i.profile}".`);let g={...l.agentNames??{}};return o===n?delete g[n]:g[n]=o,Object.keys(g).length?l.agentNames=g:delete l.agentNames,await Q(i.repoPath,a),j()}s(To,"renameActiveProfileAgent");async function Go(e){let t=e.agentPackage;if(Gn(t),!/^[a-z0-9][a-z0-9._-]{0,190}$/.test(t.agentId))throw new Error("Agent package ID is not safe for a local Profile.");let n=await te(),o=n.state.sourcePath;await pt(o);let r=u.join(o,"agents");await v(r,{recursive:!0});let i=u.join(r,t.agentId),a=k(i);if(a&&e.overwrite!==!0)throw new Error(`Agent "${t.agentId}" already exists. Confirm replacement to install this version.`);let l=u.join(r,`.${t.agentId}.${tt()}.installing`),c=u.join(r,`.${t.agentId}.${tt()}.backup`),d=await T(n.config.repoPath),g=JSON.stringify(d),P=!1,x=!1;try{await Hn(l,t),a&&(await Pe(i,c),P=!0),await Pe(l,i),x=!0;let S=d.profiles[n.config.profile];if(!S)throw new Error(`Profile "${n.config.profile}" was not found.`);let M=new Set(S.enabledAgents??[]);M.add(t.agentId),S.enabledAgents=[...M],S.defaultAgent||(S.defaultAgent=t.agentId),S.agentNames={...S.agentNames??{},[t.agentId]:t.title},await Q(n.config.repoPath,d),P&&await he(c,{recursive:!0,force:!0})}catch(S){throw await he(l,{recursive:!0,force:!0}),x&&await he(i,{recursive:!0,force:!0}),P&&k(c)&&await Pe(c,i),JSON.stringify(d)!==g&&await Q(n.config.repoPath,JSON.parse(g)).catch(()=>{}),S}return{state:await j(),agentId:t.agentId,versionId:t.versionId,digest:t.digest}}s(Go,"installAgentPackageIntoActiveProfile");async function j(){let t=(await O()).openpondProfile;return t?z(t):ut()}s(j,"loadOpenPondProfileState");function ye(e){return{source:e.source??"local",repositoryId:e.repositoryId?.trim()||u.resolve(e.repoPath),profileId:e.profile}}s(ye,"openPondProfileRef");async function Rn(){let e=(await O()).openpondProfile;if(!e)return{lastUsed:null,profiles:[]};let t=A(e),n=await Promise.all(t.map(async o=>{let r=await z({repoPath:o.repoPath,profile:o.profile,mode:"local",...o.lastCheck?{lastCheck:o.lastCheck}:{},...o.lastPush?{lastPush:o.lastPush}:{}});return{ref:ye(o),name:o.profile,repoPath:o.repoPath,sourcePath:r.sourcePath,state:r}}));return{lastUsed:ye({repoPath:e.repoPath,profile:e.profile,source:A(e).find(o=>u.resolve(o.repoPath)===u.resolve(e.repoPath)&&o.profile===e.profile)?.source,repositoryId:A(e).find(o=>u.resolve(o.repoPath)===u.resolve(e.repoPath)&&o.profile===e.profile)?.repositoryId}),profiles:n}}s(Rn,"loadOpenPondProfileLibrary");async function bn(e){if(!e)return j();let t=(await O()).openpondProfile,n=A(t).find(o=>o.source===e.source&&o.repositoryId===e.repositoryId&&o.profile===e.profileId);return n?z({repoPath:n.repoPath,profile:n.profile,mode:"local",...n.lastCheck?{lastCheck:n.lastCheck}:{},...n.lastPush?{lastPush:n.lastPush}:{}}):ut(`Profile "${e.profileId}" is not installed on this device.`)}s(bn,"loadOpenPondProfileStateForRef");async function Ho(e){let t=(await O()).openpondProfile,n=A(t).find(o=>o.source===e.source&&o.repositoryId===e.repositoryId&&o.profile===e.profileId);if(!n)throw new Error(`Profile "${e.profileId}" is not installed on this device.`);return await L({openpondProfile:ee(t,n.repoPath,n.profile)}),j()}s(Ho,"selectOpenPondProfile");async function No(e){let t=(await O()).openpondProfile;if(!t)return{lastUsed:null,profiles:[]};let n=A(t).filter(i=>i.source!==e.source||i.repositoryId!==e.repositoryId||i.profile!==e.profileId);if(n.length===0)return await L({openpondProfile:null}),{lastUsed:null,profiles:[]};let r=u.resolve(t.repoPath)===u.resolve(A(t).find(i=>i.source===e.source&&i.repositoryId===e.repositoryId&&i.profile===e.profileId)?.repoPath??"")&&t.profile===e.profileId?n[0]:n.find(i=>u.resolve(i.repoPath)===u.resolve(t.repoPath)&&i.profile===t.profile)??n[0];return await L({openpondProfile:{repoPath:r.repoPath,profile:r.profile,mode:"local",profiles:n,...r.lastCheck?{lastCheck:r.lastCheck}:{},...r.lastPush?{lastPush:r.lastPush}:{}}}),Rn()}s(No,"removeOpenPondProfile");async function Uo(e,t){return z({mode:"local",repoPath:e,profile:t})}s(Uo,"inspectOpenPondProfileSource");async function z(e){try{let t=await T(e.repoPath),n=Ce(t,e.repoPath,e.profile),o=await xn(t,e.profile),r=mt({manifest:t,profile:e.profile,profileSourcePath:n,agents:o}),[i,a,l,c]=await Promise.all([N(e.repoPath),ze(r),Qe(n),_n(n,r)]),d=ot(e),g=qn(i,e.profile),P=K({actionCatalog:a.actionCatalog,sourceSetupRequirements:a.sourceSetupRequirements}),x=Ln({agents:o,actionCatalog:a.actionCatalog,catalog:a.catalog,diff:g,git:i,hosted:d,lastCheck:e.lastCheck??null,error:null});return{mode:"local",repoPath:e.repoPath,activeProfile:e.profile,sourcePath:n,manifestPath:u.join(e.repoPath,F),agents:o,skills:l.skills,evals:c,git:i,catalog:a.catalog,skillCatalog:l.skillCatalog,actionCatalog:a.actionCatalog,sourceSetupRequirements:a.sourceSetupRequirements,setupGate:P,diff:g,hosted:d,summary:x,lastCheck:e.lastCheck??null,error:null}}catch(t){let n=await N(e.repoPath).catch(()=>null),o=t instanceof Error?t.message:String(t);return{mode:"local",repoPath:e.repoPath,activeProfile:e.profile,sourcePath:null,manifestPath:u.join(e.repoPath,F),agents:[],skills:[],evals:[],git:n,catalog:ue(o),skillCatalog:de(o),actionCatalog:[],sourceSetupRequirements:[],setupGate:fe(),diff:Y(),hosted:ot(e),summary:pe(o),lastCheck:e.lastCheck??null,error:o}}}s(z,"loadOpenPondProfileStateForConfig");async function Do(e){return z({repoPath:u.resolve(e.repoPath),profile:e.profileId,mode:"local"})}s(Do,"loadOpenPondProfileStateFromSource");async function te(){let e=(await O()).openpondProfile;if(!e)throw new Error("No active OpenPond profile. Run `openpond init` or `openpond profile load --path <dir>`.");let t=await j();if(t.error)throw new Error(t.error);if(!t.sourcePath)throw new Error("Active OpenPond profile has no source path.");return{config:e,state:t}}s(te,"requireActiveLocalProfile");async function Bo(e){let t=await te(),n=e.command==="run"?e.args??[]:[],o=e.command==="run"?t.state.actionCatalog.find(l=>l.id===n[0]):null,r=u.resolve(e.cwd??o?.sourcePath??t.state.sourcePath),i=e.command==="run"?nt(r,e.args??[],o?.sourceActionId??null):null;if(e.command==="run"&&i){let l=i[0],c=u.resolve(t.state.sourcePath)===r?{actionCatalog:t.state.actionCatalog,sourceSetupRequirements:t.state.sourceSetupRequirements}:await Be(r);oe(l,K({actionCatalog:c.actionCatalog,sourceSetupRequirements:c.sourceSetupRequirements,actionId:l}))}let a=await ft({command:e.command,args:e.command==="run"?i??nt(r,e.args??[]):e.args,cwd:r,inherit:e.inherit,throwOnFailure:!1});if((e.command==="inspect"||e.command==="build"||e.command==="validate"||e.command==="eval")&&await Se(e.command,a.code),a.code!==0){let l=a.stderr.trim()||a.stdout.trim();throw new Error(l||`${e.command} failed with exit code ${a.code??"unknown"}`)}return a}s(Bo,"runProfileSdkCommand");async function ft(e){let t=u.resolve(e.cwd),n=Un(),o=e.command==="run"?[...n.args,e.command,...e.args??[]]:[...n.args,e.command,"--cwd",t,...e.args??[]],r=await wt(n.command,o,{cwd:t,inherit:e.inherit,timeoutMs:e.timeoutMs,maxOutputBytes:e.maxOutputBytes});if(e.throwOnFailure!==!1&&r.code!==0){let i=St(r,e.command);throw new Error(i||`${e.command} failed with exit code ${r.code??"unknown"}`)}return r}s(ft,"runAgentSdkProjectCommand");function nt(e,t,n=null){let[o,...r]=t;if(!o||o.startsWith("--"))throw new Error("run requires an action name");return[n??o,"--cwd",e,...r]}s(nt,"runCommandArgs");async function zo(e){let t=!e||e==="all"?["inspect","build","validate","eval"]:[e],n=await te(),o=await T(n.config.repoPath),r=mt({manifest:o,profile:n.config.profile,profileSourcePath:n.state.sourcePath,agents:n.state.agents});if(r.length===0){if(t.some(i=>i!=="inspect"&&i!=="build"&&i!=="validate"&&i!=="eval"))throw new Error("check kind must be one of inspect, build, validate, eval, all");await Se("validate",0);return}for(let i of t){if(i!=="inspect"&&i!=="build"&&i!=="validate"&&i!=="eval")throw new Error("check kind must be one of inspect, build, validate, eval, all");for(let a of r)await An({command:i,source:a,profileSourcePath:n.state.sourcePath,sourceCount:r.length})}}s(zo,"runProfileCheck");async function An(e){let t=e.command==="inspect"||e.command==="validate"||e.command==="eval"?["--json"]:[];if(e.sourceCount>1){let o=u.relative(e.profileSourcePath,e.source.sourcePath)||".";console.log(`
8
+ `,"utf8")}s(xt,"ensureProfileGitignoreRules");async function N(e){if(!re(ie.join(e,".git")))return{isRepo:!1,branch:null,head:null,shortHead:null,dirty:!1,upstream:null,ahead:null,behind:null,remoteUrl:null,files:[],error:null};let t=await R(e,["rev-parse","--is-inside-work-tree"]);if(t.code!==0||t.stdout.trim()!=="true")return{isRepo:!1,branch:null,head:null,shortHead:null,dirty:!1,upstream:null,ahead:null,behind:null,remoteUrl:null,files:[],error:t.stderr.trim()||t.stdout.trim()||"not a Git work tree"};let[n,o,r,i,a]=await Promise.all([B(e,["branch","--show-current"]),B(e,["rev-parse","HEAD"]),R(e,["status","--porcelain=v1","-uall"]),B(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"]),B(e,["remote","get-url","origin"])]),l=r.code===0?Mt(r.stdout):[],c=i?await Lt(e):{ahead:null,behind:null},d=o||null;return{isRepo:!0,branch:n||null,head:d,shortHead:d?d.slice(0,12):null,dirty:l.length>0,upstream:i,ahead:c.ahead,behind:c.behind,remoteUrl:a,files:l,error:r.code===0?null:H("git status",r)}}s(N,"loadProfileGitState");async function $e(e,t){let n=await N(e);if(!n.isRepo)throw new Error(n.error??"Active OpenPond profile source is not a Git repo.");if(!n.dirty)return{committed:!1,stdout:"",stderr:"",state:n};let o=await R(e,["add","-A"]);if(o.code!==0)throw new Error(H("git add",o));let r=await R(e,["commit","-m",t]);if(r.code!==0)throw new Error(H("git commit",r));return{committed:!0,stdout:r.stdout,stderr:r.stderr,state:await N(e)}}s($e,"commitProfileChanges");async function qe(e){return B(e,["rev-parse","HEAD"])}s(qe,"profileGitHead");async function _t(e){return(await R(e,["rev-parse","--verify","HEAD"])).code===0}s(_t,"hasGitHead");async function Lt(e){let t=await R(e,["rev-list","--left-right","--count","@{u}...HEAD"]);if(t.code!==0)return{ahead:null,behind:null};let[n,o]=t.stdout.trim().split(/\s+/),r=n?Number.parseInt(n,10):Number.NaN,i=o?Number.parseInt(o,10):Number.NaN;return{ahead:Number.isFinite(i)?i:null,behind:Number.isFinite(r)?r:null}}s(Lt,"loadAheadBehind");async function B(e,t){let n=await R(e,t);return n.code!==0?null:n.stdout.trim()||null}s(B,"gitText");function Mt(e){return e.split(/\r?\n/).map(t=>t.trimEnd()).filter(Boolean).map(t=>{let n=t[0]??" ",o=t[1]??" ",r=`${n}${o}`.trim()||"changed",i=t.slice(3),a=i.split(" -> "),l=n===" "?null:n,c=o===" "?null:o,d=a.length===2?a[1]:i,g=a.length===2?a[0]:null;return{path:xe(d),originalPath:g?xe(g):null,indexStatus:l,worktreeStatus:c,status:r,category:$t(l,c)}})}s(Mt,"parsePorcelainStatus");function $t(e,t){return e==="?"&&t==="?"?"untracked":e==="R"||t==="R"?"renamed":e==="A"||t==="A"?"added":e==="D"||t==="D"?"deleted":e==="M"||t==="M"?"modified":"changed"}s($t,"gitChangeCategory");function xe(e){let t=e.trim();if(!t.startsWith('"')||!t.endsWith('"'))return t;try{return JSON.parse(t)}catch{return t.slice(1,-1)}}s(xe,"unquoteGitPath");function H(e,t){return t.stderr.trim()||t.stdout.trim()||`${e} failed with exit code ${t.code??"unknown"}`}s(H,"gitFailureMessage");async function R(e,t,n={}){return new Promise((o,r)=>{let i=vt("git",t,{cwd:e,env:n.env,stdio:"pipe"}),a="",l="";i.stdout?.on("data",c=>{a+=String(c)}),i.stderr?.on("data",c=>{l+=String(c)}),i.on("error",r),i.on("close",c=>{o({code:c,stdout:a,stderr:l})}),n.input!==void 0?i.stdin?.end(n.input):i.stdin?.end()})}s(R,"runGitCommand");var ae=1500,Te=8*1024*1024,le=100*1024*1024,ce=8,jt={maxFiles:ae,maxFileBytes:Te,maxTotalBytes:le,concurrency:ce},Ft={mode:"single_json_payload",chunkingSupported:!1};async function Tt(e){let t=await R(e,["ls-files","-z"]);if(t.code!==0)throw new Error(t.stderr.trim()||t.stdout.trim()||"git ls-files failed for profile source upload");let n=t.stdout.split("\0").map(c=>c.trim()).filter(Boolean).filter(c=>{let d=c.replace(/\\/g,"/");return Fe(d)&&!Gt(d)}).sort();if(n.length===0)throw new Error("No committed profile source files found to upload.");if(n.length>ae)throw new Error(`Too many profile source files to upload: ${n.length} > ${ae}`);let o=(await je(n,ce,async c=>{let d=se.resolve(e,c),g=se.relative(e,d).replace(/\\/g,"/");if(!Fe(g))throw new Error(`Profile source path escapes repo: ${c}`);let P=await qt(d);if(!P.isFile())return null;if(P.size>Te)throw new Error(`Profile source file is too large: ${c} (${P.size} bytes)`);return{path:g,absolutePath:d,size:P.size,mtimeMs:Math.trunc(P.mtimeMs),ctimeMs:Math.trunc(P.ctimeMs)}})).filter(c=>c!==null),r=0;for(let c of o)if(r+=c.size,r>le)throw new Error(`Profile source upload is too large: ${r} > ${le}`);let i=await Ae(e),a=await je(o,ce,async c=>Ie(c,i));await ve(e,a).catch(()=>{});let l=a.map(c=>c.entry);return{entries:l,fileCount:l.length,totalBytes:r,limits:jt,transport:Ft}}s(Tt,"collectProfileSourceUploadEntries");async function je(e,t,n){let o=new Array(e.length),r=0,i=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:i},async()=>{for(;r<e.length;){let a=r;r+=1,o[a]=await n(e[a],a)}})),o}s(je,"mapWithConcurrency");function Fe(e){return e.length>0&&!e.includes("\0")&&!se.isAbsolute(e)&&!e.split(/[\\/]+/).some(t=>!t||t==="."||t==="..")}s(Fe,"isSafeProfileSourcePath");function Gt(e){return e.split(/[\\/]+/).some((t,n,o)=>{let r=t.toLowerCase();if(r===".git"||r==="node_modules"||r===".bun"||r===".env"||r.startsWith(".env.")||e.replace(/\\/g,"/")===be)return!0;if(r!==".openpond")return!1;let i=o[n+1]?.toLowerCase();return i==="goals"||i==="traces"||i==="vendor"||i==="eval-results.json"||i==="artifact-index.json"})}s(Gt,"shouldSkipProfileSourcePath");function Ht(e){let t=y(e.checkResult),n=y(t?.deployPlan)??y(e.deployPlan),o=y(n?.source),r=y(n?.checks),i=y(t?.sourceCheckStatus);return{status:e.status,agentId:e.agentId,deployPlanStatus:f(n?.status),canRun:Ge(n?.canRun),canDeploy:Ge(n?.canDeploy),sourceRef:f(o?.sourceRef),sourceCommitSha:f(o?.sourceCommitSha),manifestHash:f(o?.manifestHash),manifestPath:f(o?.manifestPath),setupCommands:b(r?.setupCommands),validationCommands:b(r?.validationCommands),requiredChecks:b(r?.requiredChecks),evalNames:b(r?.evalNames),blockedReasons:b(n?.blockedReasons),staleReasons:b(n?.staleReasons),runtimeId:f(i?.latestRuntimeId),sandboxId:f(i?.latestSandboxId),traceArtifactRefs:b(i?.traceArtifactRefs),evalResultArtifactRefs:b(i?.evalResultArtifactRefs),validatorArtifactRefs:b(i?.validatorArtifactRefs),checkedAt:e.checkedAt??new Date().toISOString(),error:e.error??null}}s(Ht,"hostedSourceCheckStatusFromPayload");function Nt(e){let t=y(e.publishResult),n=y(t?.activeManifestSnapshot)??y(t?.manifestSnapshot)??y(t?.snapshot);return{status:e.status??"published",agentId:e.agentId,snapshotId:f(n?.id),sourceRef:f(n?.sourceRef),sourceCommitSha:f(n?.sourceCommitSha),manifestHash:f(n?.manifestHash),manifestPath:f(n?.manifestPath),buildStatus:f(n?.buildStatus),validationStatus:f(n?.validationStatus),evalStatus:f(n?.evalStatus),publishedAt:f(t?.publishedAt)??f(n?.publishedAt),error:e.error??null}}s(Nt,"hostedPublishStatusFromPayload");function Ut(e){let t=y(e.runResult),n=y(t?.run),o=y(n?.runtimeSource),r=y(n?.metadata),i=y(r?.sourceSummary),a=y(r?.setupGate),l=y(r?.responseSummary),c=y(r?.traceSummary),d=y(r?.evalSummary);return{status:f(n?.status)??(e.error?"failed":"running"),agentId:f(n?.agentId)??e.agentId,runId:f(n?.id),runtimeId:f(n?.runtimeId),sandboxId:f(n?.sandboxId),sourceRef:f(o?.sourceRef)??f(i?.sourceRef)??f(r?.sourceRef),sourceCommitSha:f(o?.sourceCommitSha)??f(i?.sourceCommitSha)??f(r?.hostedHead),manifestHash:f(o?.manifestHash)??f(i?.manifestHash),setupGateStatus:f(a?.status),setupRequirementRefs:Bt(a),artifactRefs:b(l?.artifactRefs),traceArtifactRefs:b(c?.artifactRefs),evalArtifactRefs:b(d?.artifactRefs),startedAt:f(n?.createdAt),completedAt:f(n?.completedAt),error:e.error??null}}s(Ut,"hostedRunSummaryFromPayload");function Dt(e){return e?.status?e.status==="succeeded"||e.status==="passed"?"passed":e.status==="failed"||e.status==="cancelled"?"failed":"running":"not_started"}s(Dt,"hostedRunStatusFromRunSummary");function Bt(e){return e?(Array.isArray(e.requirements)?e.requirements:Array.isArray(e.blockingRequirements)?e.blockingRequirements:[]).map(n=>{let o=y(n);return f(o?.ref)??f(o?.id)??f(o?.label)}).filter(n=>!!n):[]}s(Bt,"setupRequirementRefs");function y(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}s(y,"record");function f(e){return typeof e=="string"&&e.trim()?e.trim():null}s(f,"text");function Ge(e){return typeof e=="boolean"?e:null}s(Ge,"booleanValue");function b(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}s(b,"textArray");import{createRequire as st}from"node:module";import{createHash as et,randomUUID as tt}from"node:crypto";import{spawn as hn}from"node:child_process";import{existsSync as k}from"node:fs";import{cp as yn,mkdir as v,readFile as at,readdir as lt,rename as Pe,rm as he,symlink as wn,writeFile as D}from"node:fs/promises";import u from"node:path";function ue(e=null){return{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!0,error:e}}s(ue,"emptyProfileCatalogState");function de(e=null){return{skillCount:0,generatedAt:null,stale:!0,error:e}}s(de,"emptyProfileSkillCatalogState");function fe(){return{status:"ready",requirementCount:0,blockingCount:0,optionalMissingCount:0,readyCount:0,requirements:[],blockingRequirements:[]}}s(fe,"emptyProfileSetupGate");function Y(){return{changedAgents:[],newAgents:[],deletedAgents:[],changedSkills:[],changedActions:[],changedExtensions:[],setupChanges:[],envRequirementChanges:[],files:[]}}s(Y,"emptyProfileDiffSummary");function pe(e=null){return{state:e?"error":"none",message:e??"No active OpenPond profile.",agentCount:0,actionCount:0,defaultAction:null,checkFresh:!1,checkStaleReason:e??"No active profile.",localHead:null,hostedHead:null}}s(pe,"emptyProfileSummary");import{existsSync as U}from"node:fs";import{readFile as zt,stat as Jt}from"node:fs/promises";import V from"node:path";var He=".openpond/agent-manifest.json",Ne=".openpond/action-registry.json",Wt=".openpond/source-upload-metadata.json",Kt=".openpond/agent-package-origin.json";async function Be(e){return Je({agentId:"default",sourcePath:e,preferred:!0})}s(Be,"loadProfileActionCatalog");async function ze(e){if(e.length===0)return{catalog:{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!1,error:null},actionCatalog:[],sourceSetupRequirements:[]};let t=[...e.filter(l=>l.preferred),...e.filter(l=>!l.preferred)],n=await Promise.all(t.map(Je)),o=new Map,r=[];for(let l of n)for(let c of l.actionCatalog){let d=o.has(c.id)?`${c.agentId??"agent"}.${c.sourceActionId??c.id}`:c.id,g=d===c.id?c:{...c,id:d};o.set(d,g),r.push(g)}let i=Vt(n.map(l=>l.catalog.generatedAt)),a=n.map(l=>l.catalog.error).filter(Boolean);return{catalog:{actionCount:r.length,generatedAt:i,manifestPath:n.find(l=>l.catalog.manifestPath)?.catalog.manifestPath??null,registryPath:n.find(l=>l.catalog.registryPath)?.catalog.registryPath??null,stale:n.some(l=>l.catalog.stale),error:a.length>0?a.join("; "):null},actionCatalog:r,sourceSetupRequirements:n.flatMap(l=>l.sourceSetupRequirements)}}s(ze,"loadProfileActionCatalogForSources");async function Je(e){let t=e.sourcePath,n=V.join(t,He),o=V.join(t,Ne),r=V.join(t,Wt),i=V.join(t,Kt);try{let a=await X(n),l=await X(o),c=await X(r),d=w(await X(i)),g=w(w(a)?.inputSchemas),P=De(w(c)?.setupRequirements)??[],x=Xt(P),S=new Map;for(let m of[...ge(w(a)?.actionCatalog),...ge(w(l)?.actions),...ge(w(a)?.actions)]){let $=p(m.id)??p(m.name);if(!$)continue;let C=S.get($),kt=Zt({sourceRequirementsByAction:x,actionId:$,actionName:p(m.name)}),Ct=Qt(De(m.setupRequirements)??C?.setupRequirements??[],kt),Ot={id:$,agentId:e.agentId,sourcePath:t,sourceActionId:$,name:p(m.name)??C?.name??$,label:p(m.label)??C?.label??rn($),description:p(m.description)??C?.description??null,visibility:p(m.visibility)??C?.visibility??"default",inputSchema:on(m.inputSchema,g)??C?.inputSchema??null,outputSchema:We(m.outputSchema)??C?.outputSchema??null,approvalPolicy:w(m.approvalPolicy)??C?.approvalPolicy??null,artifactPolicy:w(m.artifactPolicy)??C?.artifactPolicy??null,setupRequirements:Ct,mcp:w(m.mcp)??C?.mcp??null,schedulePolicy:w(m.schedulePolicy)??C?.schedulePolicy??null,trace:Yt(w(m.trace)??C?.trace??null,d),implementation:w(m.implementation)??C?.implementation??null,invokesModel:typeof m.invokesModel=="boolean"?m.invokesModel:C?.invokesModel};S.set($,Ot)}let M=Array.from(S.values()).filter(m=>m.visibility!=="internal"&&m.visibility!=="debug"),G=[...a?[]:[He],...l?[]:[Ne]],_=await nn([n,o]);return{catalog:{actionCount:M.length,generatedAt:_,manifestPath:U(n)?n:null,registryPath:U(o)?o:null,stale:G.length>0,error:G.length>0?tn(e,G):null},actionCatalog:M,sourceSetupRequirements:P}}catch(a){return{catalog:{actionCount:0,generatedAt:null,manifestPath:U(n)?n:null,registryPath:U(o)?o:null,stale:!0,error:a instanceof Error?a.message:String(a)},actionCatalog:[],sourceSetupRequirements:[]}}}s(Je,"loadProfileActionCatalogSource");function Yt(e,t){if(!t)return e;let n=p(t.versionId),o=p(t.digest);return!n||!o?e:{...e??{},agentVersionId:n,agentPackageDigest:o,validationReceiptIds:Ue(t.validationReceiptIds),evalReceiptIds:Ue(t.evalReceiptIds)}}s(Yt,"mergeAgentPackageTrace");function Ue(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}s(Ue,"stringArray");function Vt(e){let t=0;for(let n of e){if(!n)continue;let o=Date.parse(n);Number.isFinite(o)&&(t=Math.max(t,o))}return t>0?new Date(t).toISOString():null}s(Vt,"latestIso");function Xt(e){let t=new Map;for(let n of e){let o=[p(n.actionId),p(n.sourceActionId),p(n.actionName)].filter(r=>!!r);for(let r of o){let i=t.get(r)??[];i.push(n),t.set(r,i)}}return t}s(Xt,"sourceSetupRequirementsByAction");function Zt(e){return[...e.sourceRequirementsByAction.get(e.actionId)??[],...e.actionName&&e.actionName!==e.actionId?e.sourceRequirementsByAction.get(e.actionName)??[]:[]].map(n=>({...n,source:"source_upload_metadata"}))}s(Zt,"setupRequirementsForActionSource");function Qt(e,t){if(t.length===0)return e;let n=[],o=new Set;for(let r of[...e,...t]){let i=en(r);o.has(i)||(o.add(i),n.push(r))}return n}s(Qt,"mergeSetupRequirements");function en(e){return[p(e.actionId)??p(e.sourceActionId)??p(e.actionName)??"",p(e.kind)??p(e.type)??"",p(e.name)??p(e.key)??p(e.provider)??p(e.tool)??p(e.command)??p(e.packageName)??p(e.path)??p(e.repo)??p(e.url)??p(e.id)??""].join(":")}s(en,"setupRequirementIdentity");function tn(e,t){return[`Profile agent ${e.agentId} at ${e.sourcePath} is missing SDK catalog artifact(s): ${t.join(", ")}.`,"Run `openpond profile check --kind all` after source materialization so each enabled profile agent has inspect/build artifacts."].join(" ")}s(tn,"missingSourceArtifactsMessage");async function X(e){return U(e)?JSON.parse(await zt(e,"utf8")):null}s(X,"readJsonIfExists");async function nn(e){let t=0;for(let n of e){if(!U(n))continue;let o=await Jt(n);t=Math.max(t,o.mtimeMs)}return t>0?new Date(t).toISOString():null}s(nn,"latestMtime");function w(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}s(w,"asRecord");function ge(e){return Array.isArray(e)?e.filter(t=>!!w(t)):[]}s(ge,"records");function De(e){return Array.isArray(e)?e.filter(t=>!!w(t)):null}s(De,"recordArray");function p(e){return typeof e=="string"&&e.trim()?e.trim():null}s(p,"text");function We(e){return p(e)??w(e)}s(We,"schemaValue");function on(e,t){let n=We(e);return typeof n!="string"?n:w(t?.[n])??n}s(on,"resolvedSchemaValue");function rn(e){let t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}s(rn,"titleFromActionId");import{createHash as sn}from"node:crypto";import{existsSync as Xe}from"node:fs";import{readdir as Ze,readFile as an,stat as ln}from"node:fs/promises";import q from"node:path";var me="skills",Z="SKILL.md",Ke=8e4;async function Qe(e){let t=q.join(e,me);if(!Xe(t))return{skillCatalog:Ye({stale:!1}),skills:[]};try{let n=await Ze(t,{withFileTypes:!0}),o=(await Promise.all(n.filter(i=>i.isDirectory()).map(i=>un(e,i.name)))).sort((i,a)=>i.name.localeCompare(a.name)||i.path.localeCompare(a.path));fn(o);let r=await pn(e,o);return{skillCatalog:{skillCount:o.length,generatedAt:r,stale:!1,error:null},skills:o}}catch(n){return{skillCatalog:Ye({stale:!0,error:n instanceof Error?n.message:String(n)}),skills:[]}}}s(Qe,"loadProfileSkills");function cn(e){let t=[],n=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/.exec(e);if(!n)return{name:null,description:null,body:e.trim(),messages:["SKILL.md must start with YAML frontmatter bounded by ---."]};let o=n[1]??"",r=(n[2]??"").trim(),i;try{i=Re.load(o)}catch(d){t.push(`SKILL.md frontmatter is invalid YAML: ${d instanceof Error?d.message:String(d)}`)}let a=mn(i),l=Ve(a?.name),c=Ve(a?.description);return l||t.push("Skill frontmatter must include a non-empty name."),c||t.push("Skill frontmatter must include a non-empty description."),r||t.push("Skill body must be non-empty markdown."),{name:l,description:c,body:r,messages:t}}s(cn,"parseProfileSkillMarkdown");function Ye(e={}){return{skillCount:0,generatedAt:null,stale:e.stale??!0,error:e.error??null}}s(Ye,"emptyProfileSkillCatalogState");async function un(e,t){let n=q.join(me,t,Z).replace(/\\/g,"/"),o=q.join(e,n),r=[],i=q.join(e,me,t),a=await dn(i),l="";Xe(o)?l=await an(o,"utf8"):r.push(`Missing ${Z}.`),l.length>Ke&&r.push(`Skill markdown exceeds the limit of ${Ke} characters.`);let c=cn(l);r.push(...c.messages);let d=c.name??t,g=c.description??"";return gn(d)||r.push("Skill name must be lowercase kebab-case."),d!==t&&r.push(`Skill name must match its directory name (${t}).`),{name:d,description:g,path:n,scope:"profile",enabled:r.length===0,sourcePath:e,charCount:l.length,sourceHash:Pn(l),validationStatus:r.length>0?"error":"valid",validationMessages:r,resourceFiles:a.filter(P=>P!==Z)}}s(un,"loadProfileSkillDirectory");async function dn(e){let t=[];async function n(o,r){let i=await Ze(o,{withFileTypes:!0});await Promise.all(i.map(async a=>{let l=r?`${r}/${a.name}`:a.name;a.isDirectory()?await n(q.join(o,a.name),l):a.isFile()&&t.push(l)}))}return s(n,"visit"),await n(e,""),t.sort()}s(dn,"listPackageFiles");function fn(e){let t=new Map;for(let n of e)t.set(n.name,(t.get(n.name)??0)+1);for(let n of e)(t.get(n.name)??0)<=1||(n.enabled=!1,n.validationStatus="error",n.validationMessages=[...n.validationMessages,`Duplicate skill name: ${n.name}`])}s(fn,"markDuplicateSkillNames");async function pn(e,t){let n=0;for(let o of t){let r=q.dirname(q.join(e,o.path)),i=[Z,...o.resourceFiles];for(let a of i){let l=await ln(q.join(r,a)).catch(()=>null);l?.isFile()&&(n=Math.max(n,l.mtimeMs))}}return n>0?new Date(n).toISOString():null}s(pn,"latestSkillMtime");function gn(e){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)}s(gn,"isKebabCaseSkillName");function mn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}s(mn,"asRecord");function Ve(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}s(Ve,"text");function Pn(e){return sn("sha256").update(e).digest("hex")}s(Pn,"sha256Hex");var F="openpond-profile.json",Sn="settings/profile.yaml",ct="default",E="default";function kn(e,t){let n=e?.defaultAgent??E,o=e?.enabledAgents&&e.enabledAgents.length>0?e.enabledAgents:[n];return{...e??{},path:t,defaultAgent:n,enabledAgents:o}}s(kn,"mergeProfileRepoManifestEntry");function ee(e,t,n){let o=A(e);if(e){let l=o.findIndex(d=>u.resolve(d.repoPath)===u.resolve(e.repoPath)&&d.profile===e.profile),c={source:o[l]?.source??"local",repositoryId:o[l]?.repositoryId??u.resolve(e.repoPath),repoPath:u.resolve(e.repoPath),profile:e.profile,...e.lastCheck?{lastCheck:e.lastCheck}:{},...e.lastPush?{lastPush:e.lastPush}:{}};l>=0?o[l]=c:o.push(c)}let r=o.findIndex(l=>u.resolve(l.repoPath)===u.resolve(t)&&l.profile===n),i=r>=0?o[r]:{source:"local",repositoryId:u.resolve(t),repoPath:u.resolve(t),profile:n};return r<0&&o.push(i),{repoPath:u.resolve(t),profile:n,mode:"local",profiles:o,...i.lastCheck?{lastCheck:i.lastCheck}:{},...i.lastPush?{lastPush:i.lastPush}:{}}}s(ee,"mergeActiveLocalProfileConfig");function A(e){if(!e)return[];let t=e.profiles?.map(n=>({...n}))??[];return t.some(n=>u.resolve(n.repoPath)===u.resolve(e.repoPath)&&n.profile===e.profile)||t.push({source:"local",repositoryId:u.resolve(e.repoPath),repoPath:u.resolve(e.repoPath),profile:e.profile,...e.lastCheck?{lastCheck:e.lastCheck}:{},...e.lastPush?{lastPush:e.lastPush}:{}}),t}s(A,"profileConfigEntries");var Cn=st(import.meta.url);function On(){return u.join(Oe(),"library","profiles","default-repo")}s(On,"defaultLocalProfileRepoPath");function ut(e=null){return{mode:"none",repoPath:null,activeProfile:null,sourcePath:null,manifestPath:null,agents:[],skills:[],evals:[],git:null,catalog:ue(e),skillCatalog:de(e),actionCatalog:[],sourceSetupRequirements:[],setupGate:fe(),diff:Y(),hosted:null,summary:pe(e),lastCheck:null,error:e}}s(ut,"emptyProfileState");async function qo(e={}){let t=u.resolve(e.repoPath??On()),n=ke(e.profile),o=u.join("profiles",n),r=u.join(t,o),i=e.template??"blank-agent",a=i==="blank-profile";await v(t,{recursive:!0});let l=k(u.join(t,F)),c=await T(t).catch(()=>Tn(n,o));if(a&&l&&c.profiles[n])throw new Error(`Profile "${n}" already exists in ${t}.`);c.defaultProfile=c.defaultProfile||n,c.profiles[n]=kn(c.profiles[n],o),a&&(c.profiles[n].enabledAgents=[]),a?await v(r,{recursive:!0}):await In(r,i,!!e.force),await pt(r),await vn(t,r,n,{includeDefaultAgent:!a}),await Q(t,c),await Me(t);let d=(await O()).openpondProfile;return await L({openpondProfile:ee(d,t,n)}),j()}s(qo,"initLocalProfileRepo");async function jo(e,t,n){let o=u.resolve(e),r=await T(o),i=ke(t??r.defaultProfile);Ce(r,o,i);let a=(await O()).openpondProfile,l=ee(a,o,i);return dt(l,o,i,n),await L({openpondProfile:l}),j()}s(jo,"loadLocalProfileRepo");async function Fo(e,t,n){let o=u.resolve(e),r=await T(o),i=ke(t??r.defaultProfile);Ce(r,o,i);let a=(await O()).openpondProfile,l=ee(a,o,i);return dt(l,o,i,n),a&&(l.repoPath=a.repoPath,l.profile=a.profile,l.lastCheck=a.lastCheck,l.lastPush=a.lastPush),await L({openpondProfile:l}),bn(ye({repoPath:o,profile:i,source:n?.source,repositoryId:n?.repositoryId}))}s(Fo,"registerLocalProfileRepo");function dt(e,t,n,o){o&&(e.profiles=A(e).map(r=>u.resolve(r.repoPath)===t&&r.profile===n?{...r,source:o.source,repositoryId:o.repositoryId}:r))}s(dt,"applyProfileIdentity");async function To(e,t){let n=e.trim(),o=Fn(t);if(!n)throw new Error("Agent ID is required.");let i=(await O()).openpondProfile;if(!i)throw new Error("No active local Profile.");let a=await T(i.repoPath),l=a.profiles[i.profile];if(!l)throw new Error(`Profile "${i.profile}" was not found.`);let c=l.defaultAgent??E;if(!(l.enabledAgents??[c]).includes(n))throw new Error(`Agent "${n}" was not found in Profile "${i.profile}".`);let g={...l.agentNames??{}};return o===n?delete g[n]:g[n]=o,Object.keys(g).length?l.agentNames=g:delete l.agentNames,await Q(i.repoPath,a),j()}s(To,"renameActiveProfileAgent");async function Go(e){let t=e.agentPackage;if(Gn(t),!/^[a-z0-9][a-z0-9._-]{0,190}$/.test(t.agentId))throw new Error("Agent package ID is not safe for a local Profile.");let n=await te(),o=n.state.sourcePath;await pt(o);let r=u.join(o,"agents");await v(r,{recursive:!0});let i=u.join(r,t.agentId),a=k(i);if(a&&e.overwrite!==!0)throw new Error(`Agent "${t.agentId}" already exists. Confirm replacement to install this version.`);let l=u.join(r,`.${t.agentId}.${tt()}.installing`),c=u.join(r,`.${t.agentId}.${tt()}.backup`),d=await T(n.config.repoPath),g=JSON.stringify(d),P=!1,x=!1;try{await Hn(l,t),a&&(await Pe(i,c),P=!0),await Pe(l,i),x=!0;let S=d.profiles[n.config.profile];if(!S)throw new Error(`Profile "${n.config.profile}" was not found.`);let M=new Set(S.enabledAgents??[]);M.add(t.agentId),S.enabledAgents=[...M],S.defaultAgent||(S.defaultAgent=t.agentId),S.agentNames={...S.agentNames??{},[t.agentId]:t.title},await Q(n.config.repoPath,d),P&&await he(c,{recursive:!0,force:!0})}catch(S){throw await he(l,{recursive:!0,force:!0}),x&&await he(i,{recursive:!0,force:!0}),P&&k(c)&&await Pe(c,i),JSON.stringify(d)!==g&&await Q(n.config.repoPath,JSON.parse(g)).catch(()=>{}),S}return{state:await j(),agentId:t.agentId,versionId:t.versionId,digest:t.digest}}s(Go,"installAgentPackageIntoActiveProfile");async function j(){let t=(await O()).openpondProfile;return t?z(t):ut()}s(j,"loadOpenPondProfileState");function ye(e){return{source:e.source??"local",repositoryId:e.repositoryId?.trim()||u.resolve(e.repoPath),profileId:e.profile}}s(ye,"openPondProfileRef");async function Rn(){let e=(await O()).openpondProfile;if(!e)return{lastUsed:null,profiles:[]};let t=A(e),n=await Promise.all(t.map(async o=>{let r=await z({repoPath:o.repoPath,profile:o.profile,mode:"local",...o.lastCheck?{lastCheck:o.lastCheck}:{},...o.lastPush?{lastPush:o.lastPush}:{}});return{ref:ye(o),name:o.profile,repoPath:o.repoPath,sourcePath:r.sourcePath,state:r}}));return{lastUsed:ye({repoPath:e.repoPath,profile:e.profile,source:A(e).find(o=>u.resolve(o.repoPath)===u.resolve(e.repoPath)&&o.profile===e.profile)?.source,repositoryId:A(e).find(o=>u.resolve(o.repoPath)===u.resolve(e.repoPath)&&o.profile===e.profile)?.repositoryId}),profiles:n}}s(Rn,"loadOpenPondProfileLibrary");async function bn(e){if(!e)return j();let t=(await O()).openpondProfile,n=A(t).find(o=>o.source===e.source&&o.repositoryId===e.repositoryId&&o.profile===e.profileId);return n?z({repoPath:n.repoPath,profile:n.profile,mode:"local",...n.lastCheck?{lastCheck:n.lastCheck}:{},...n.lastPush?{lastPush:n.lastPush}:{}}):ut(`Profile "${e.profileId}" is not installed on this device.`)}s(bn,"loadOpenPondProfileStateForRef");async function Ho(e){let t=(await O()).openpondProfile,n=A(t).find(o=>o.source===e.source&&o.repositoryId===e.repositoryId&&o.profile===e.profileId);if(!n)throw new Error(`Profile "${e.profileId}" is not installed on this device.`);return await L({openpondProfile:ee(t,n.repoPath,n.profile)}),j()}s(Ho,"selectOpenPondProfile");async function No(e){let t=(await O()).openpondProfile;if(!t)return{lastUsed:null,profiles:[]};let n=A(t).filter(i=>i.source!==e.source||i.repositoryId!==e.repositoryId||i.profile!==e.profileId);if(n.length===0)return await L({openpondProfile:null}),{lastUsed:null,profiles:[]};let r=u.resolve(t.repoPath)===u.resolve(A(t).find(i=>i.source===e.source&&i.repositoryId===e.repositoryId&&i.profile===e.profileId)?.repoPath??"")&&t.profile===e.profileId?n[0]:n.find(i=>u.resolve(i.repoPath)===u.resolve(t.repoPath)&&i.profile===t.profile)??n[0];return await L({openpondProfile:{repoPath:r.repoPath,profile:r.profile,mode:"local",profiles:n,...r.lastCheck?{lastCheck:r.lastCheck}:{},...r.lastPush?{lastPush:r.lastPush}:{}}}),Rn()}s(No,"removeOpenPondProfile");async function Uo(e,t){return z({mode:"local",repoPath:e,profile:t})}s(Uo,"inspectOpenPondProfileSource");async function z(e){try{let t=await T(e.repoPath),n=Ce(t,e.repoPath,e.profile),o=await xn(t,e.profile),r=mt({manifest:t,profile:e.profile,profileSourcePath:n,agents:o}),[i,a,l,c]=await Promise.all([N(e.repoPath),ze(r),Qe(n),_n(n,r)]),d=ot(e),g=qn(i,e.profile),P=K({actionCatalog:a.actionCatalog,sourceSetupRequirements:a.sourceSetupRequirements}),x=Ln({agents:o,actionCatalog:a.actionCatalog,catalog:a.catalog,diff:g,git:i,hosted:d,lastCheck:e.lastCheck??null,error:null});return{mode:"local",repoPath:e.repoPath,activeProfile:e.profile,sourcePath:n,manifestPath:u.join(e.repoPath,F),agents:o,skills:l.skills,evals:c,git:i,catalog:a.catalog,skillCatalog:l.skillCatalog,actionCatalog:a.actionCatalog,sourceSetupRequirements:a.sourceSetupRequirements,setupGate:P,diff:g,hosted:d,summary:x,lastCheck:e.lastCheck??null,error:null}}catch(t){let n=await N(e.repoPath).catch(()=>null),o=t instanceof Error?t.message:String(t);return{mode:"local",repoPath:e.repoPath,activeProfile:e.profile,sourcePath:null,manifestPath:u.join(e.repoPath,F),agents:[],skills:[],evals:[],git:n,catalog:ue(o),skillCatalog:de(o),actionCatalog:[],sourceSetupRequirements:[],setupGate:fe(),diff:Y(),hosted:ot(e),summary:pe(o),lastCheck:e.lastCheck??null,error:o}}}s(z,"loadOpenPondProfileStateForConfig");async function Do(e){return z({repoPath:u.resolve(e.repoPath),profile:e.profileId,mode:"local"})}s(Do,"loadOpenPondProfileStateFromSource");async function te(){let e=(await O()).openpondProfile;if(!e)throw new Error("No active OpenPond profile. Run `openpond init` or `openpond profile load --path <dir>`.");let t=await j();if(t.error)throw new Error(t.error);if(!t.sourcePath)throw new Error("Active OpenPond profile has no source path.");return{config:e,state:t}}s(te,"requireActiveLocalProfile");async function Bo(e){let t=await te(),n=e.command==="run"?e.args??[]:[],o=e.command==="run"?t.state.actionCatalog.find(l=>l.id===n[0]):null,r=u.resolve(e.cwd??o?.sourcePath??t.state.sourcePath),i=e.command==="run"?nt(r,e.args??[],o?.sourceActionId??null):null;if(e.command==="run"&&i){let l=i[0],c=u.resolve(t.state.sourcePath)===r?{actionCatalog:t.state.actionCatalog,sourceSetupRequirements:t.state.sourceSetupRequirements}:await Be(r);oe(l,K({actionCatalog:c.actionCatalog,sourceSetupRequirements:c.sourceSetupRequirements,actionId:l}))}let a=await ft({command:e.command,args:e.command==="run"?i??nt(r,e.args??[]):e.args,cwd:r,inherit:e.inherit,throwOnFailure:!1});if((e.command==="inspect"||e.command==="build"||e.command==="validate"||e.command==="eval")&&await Se(e.command,a.code),a.code!==0){let l=a.stderr.trim()||a.stdout.trim();throw new Error(l||`${e.command} failed with exit code ${a.code??"unknown"}`)}return a}s(Bo,"runProfileSdkCommand");async function ft(e){let t=u.resolve(e.cwd),n=Un(),o=e.command==="run"?[...n.args,e.command,...e.args??[]]:[...n.args,e.command,"--cwd",t,...e.args??[]],r=await wt(n.command,o,{cwd:t,inherit:e.inherit,timeoutMs:e.timeoutMs,maxOutputBytes:e.maxOutputBytes});if(e.throwOnFailure!==!1&&r.code!==0){let i=St(r,e.command);throw new Error(i||`${e.command} failed with exit code ${r.code??"unknown"}`)}return r}s(ft,"runAgentSdkProjectCommand");function nt(e,t,n=null){let[o,...r]=t;if(!o||o.startsWith("--"))throw new Error("run requires an action name");return[n??o,"--cwd",e,...r]}s(nt,"runCommandArgs");async function zo(e){let t=!e||e==="all"?["inspect","build","validate","eval"]:[e],n=await te(),o=await T(n.config.repoPath),r=mt({manifest:o,profile:n.config.profile,profileSourcePath:n.state.sourcePath,agents:n.state.agents});if(r.length===0){if(t.some(i=>i!=="inspect"&&i!=="build"&&i!=="validate"&&i!=="eval"))throw new Error("check kind must be one of inspect, build, validate, eval, all");await Se("validate",0);return}for(let i of t){if(i!=="inspect"&&i!=="build"&&i!=="validate"&&i!=="eval")throw new Error("check kind must be one of inspect, build, validate, eval, all");for(let a of r)await An({command:i,source:a,profileSourcePath:n.state.sourcePath,sourceCount:r.length})}}s(zo,"runProfileCheck");async function An(e){let t=e.command==="inspect"||e.command==="validate"||e.command==="eval"?["--json"]:[];if(e.sourceCount>1){let o=u.relative(e.profileSourcePath,e.source.sourcePath)||".";console.log(`
9
9
  [profile:${e.source.agentId}] ${e.command} ${o}`)}let n=await ft({command:e.command,args:t,cwd:e.source.sourcePath,inherit:!1,throwOnFailure:!1});if(n.stdout.trim()&&console.log(n.stdout.trim()),n.stderr.trim()&&console.error(n.stderr.trim()),await Se(e.command,n.code),n.code!==0){let o=St(n,e.command);throw new Error([`Profile check failed for enabled agent ${e.source.agentId} at ${e.source.sourcePath}.`,o||`${e.command} failed with exit code ${n.code??"unknown"}`].join(`
10
10
  `))}}s(An,"runProfileCheckForSource");async function Jo(e){let t=await te();if(!t.state.repoPath)throw new Error("Active OpenPond profile has no repo path.");let n=await $e(t.state.repoPath,e?.trim()||`Update OpenPond profile ${t.state.activeProfile??ct}`);return{committed:n.committed,stdout:n.stdout,stderr:n.stderr,state:await j()}}s(Jo,"commitActiveProfileChanges");async function Wo(e){let t=(await O()).openpondProfile;if(!t)return;let n=A(t).map(o=>u.resolve(o.repoPath)===u.resolve(t.repoPath)&&o.profile===t.profile?{...o,lastPush:e}:o);await L({openpondProfile:{...t,lastPush:e,profiles:n}})}s(Wo,"saveProfilePushStatus");async function Se(e,t){let n=(await O()).openpondProfile;if(!n)return;let o=await qe(n.repoPath).catch(()=>null),r={command:e,status:t===0?"passed":"failed",checkedAt:new Date().toISOString(),exitCode:t,sourceHead:o},i=A(n).map(a=>u.resolve(a.repoPath)===u.resolve(n.repoPath)&&a.profile===n.profile?{...a,lastCheck:r}:a);await L({openpondProfile:{...n,lastCheck:r,profiles:i}})}s(Se,"saveProfileCheckStatus");async function In(e,t,n){if(await v(e,{recursive:!0}),(await lt(e)).length>0&&!n)return;let r=J(),i=u.join(r,"templates",t);if(!k(i))throw new Error(`Unknown agent template "${t}".`);await yn(i,e,{recursive:!0,force:n,errorOnExist:!1}),await En(e,r)}s(In,"ensureProfileSource");async function vn(e,t,n,o={}){if(await v(u.join(e,"profiles"),{recursive:!0}),o.includeDefaultAgent===!1)return;for(let a of["agents","skills","workflows","actions","extensions","prompts","goals","evals","settings","traces"])await v(u.join(t,a),{recursive:!0});let r=u.join(t,Sn);k(r)||await D(r,["schema: openpond.profile.v1",`profile: ${n}`,"agents:",` - id: ${E}`," path: agent/agent.ts"," enabled: true",""].join(`
11
11
  `),"utf8");let i=u.join(t,"openpond.lock");k(i)||await D(i,`# OpenPond profile lockfile placeholder