openpond 0.2.46 → 0.2.48

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 (212) hide show
  1. package/dist/app-server.d.ts +157 -1
  2. package/dist/app-server.js +1 -1
  3. package/dist/chunks/{actions-command-I3NI75P2.js → actions-command-DSO6YOEE.js} +1 -1
  4. package/dist/chunks/{app-layer-B3SMVO4B.js → app-layer-RRFI27N4.js} +1 -1
  5. package/dist/chunks/app-server-runtime-RWO4KGPU.js +2 -0
  6. package/dist/chunks/{apps-OA2VX34V.js → apps-NELJL377.js} +1 -1
  7. package/dist/chunks/{chunk-4UTIEH5H.js → chunk-2SPZYBDN.js} +1 -1
  8. package/dist/chunks/{chunk-LL4QP2IM.js → chunk-2ZJJFBIA.js} +1 -1
  9. package/dist/chunks/{chunk-HP2D3W2B.js → chunk-42GOV5ZU.js} +3 -3
  10. package/dist/chunks/{chunk-PGKEDR3S.js → chunk-5CMKGD43.js} +1 -1
  11. package/dist/chunks/{chunk-D6MQTNJ3.js → chunk-7K72KS5C.js} +6 -6
  12. package/dist/chunks/{chunk-JBHAU7PH.js → chunk-7MXZJQS7.js} +137 -137
  13. package/dist/chunks/{chunk-YSYXIJ46.js → chunk-7QEE4PBI.js} +1 -1
  14. package/dist/chunks/{chunk-F2AG46CV.js → chunk-7YR6CBNU.js} +1 -1
  15. package/dist/chunks/{chunk-UWO34HP6.js → chunk-DALJMSJG.js} +2 -2
  16. package/dist/chunks/chunk-DFM5JTS2.js +2 -0
  17. package/dist/chunks/{chunk-33AO3P6X.js → chunk-DLZP22WV.js} +1 -1
  18. package/dist/chunks/{chunk-BKMGBIBT.js → chunk-EMKZVP7Z.js} +1 -1
  19. package/dist/chunks/chunk-EPY7M5XS.js +2 -0
  20. package/dist/chunks/{chunk-ZJY2L43W.js → chunk-HA7EFTPF.js} +1 -1
  21. package/dist/chunks/{chunk-HK3WGUKK.js → chunk-IKWDL3RB.js} +1 -1
  22. package/dist/chunks/chunk-IOQUF34U.js +2 -0
  23. package/dist/chunks/chunk-JCCU3VFK.js +2 -0
  24. package/dist/chunks/{chunk-ZC57DX6D.js → chunk-JDLAHVAJ.js} +1 -1
  25. package/dist/chunks/{chunk-WWABOVRW.js → chunk-LVL4TIAO.js} +2 -2
  26. package/dist/chunks/{chunk-IV7F74JJ.js → chunk-MASJQWA2.js} +1 -1
  27. package/dist/chunks/{chunk-XLDW5NN3.js → chunk-N3DEA6PG.js} +1 -1
  28. package/dist/chunks/{chunk-F5DUN73H.js → chunk-N5QNXMIS.js} +1 -1
  29. package/dist/chunks/{chunk-MCRA6ZGJ.js → chunk-NAZ26IZL.js} +1 -1
  30. package/dist/chunks/chunk-NHJ26KXF.js +518 -0
  31. package/dist/chunks/chunk-NNF6KCHD.js +3 -0
  32. package/dist/chunks/{chunk-5OGRWWEH.js → chunk-O7VGFMDO.js} +1 -1
  33. package/dist/chunks/{chunk-USWZ3KUC.js → chunk-PA7XP42P.js} +1 -1
  34. package/dist/chunks/{chunk-BQNK2NMB.js → chunk-PJM2G7SG.js} +1 -1
  35. package/dist/chunks/chunk-PNE3IETM.js +190 -0
  36. package/dist/chunks/chunk-PYABBF53.js +53 -0
  37. package/dist/chunks/{chunk-TYWBEJOA.js → chunk-Q4H3NUVW.js} +2 -2
  38. package/dist/chunks/{chunk-HO5L2FUU.js → chunk-QJRXTIOC.js} +1 -1
  39. package/dist/chunks/chunk-QRWPEW3Z.js +24 -0
  40. package/dist/chunks/{chunk-LZSY5IM3.js → chunk-QXVIIM4T.js} +1 -1
  41. package/dist/chunks/{chunk-6SJZXZNA.js → chunk-R3XFY7VL.js} +1 -1
  42. package/dist/chunks/{chunk-EWS7MXTM.js → chunk-RLZPX4YP.js} +1 -1
  43. package/dist/chunks/{chunk-VW7D3DRM.js → chunk-SDEDAHV6.js} +72 -67
  44. package/dist/chunks/{chunk-BUFQKDAW.js → chunk-T5LE6R5S.js} +1 -1
  45. package/dist/chunks/{chunk-L4BYPZ4U.js → chunk-TGIB24K4.js} +1 -1
  46. package/dist/chunks/{chunk-D6E7JBBQ.js → chunk-TIUSKRBP.js} +4 -4
  47. package/dist/chunks/{chunk-6WLJWRMF.js → chunk-UJ5EFSEC.js} +1 -1
  48. package/dist/chunks/chunk-VOIH2BQA.js +2162 -0
  49. package/dist/chunks/{chunk-KE5RH6JA.js → chunk-WITSXYEW.js} +1 -1
  50. package/dist/chunks/chunk-WV2APYWG.js +2 -0
  51. package/dist/chunks/chunk-XBCIBAXD.js +4 -0
  52. package/dist/chunks/chunk-XDMUD4FW.js +5 -0
  53. package/dist/chunks/{chunk-DNXKIIV7.js → chunk-XM26DGML.js} +1 -1
  54. package/dist/chunks/{chunk-OGXSE57Z.js → chunk-YIB3J4RC.js} +1 -1
  55. package/dist/chunks/{chunk-H6W55CQG.js → chunk-YL6VFJ4P.js} +1 -1
  56. package/dist/chunks/cli-ZLDLOKPL.js +2 -0
  57. package/dist/chunks/{configuration-command-MVZS625X.js → configuration-command-SA56RV5B.js} +1 -1
  58. package/dist/chunks/{connected-evidence-7LHUZ2UI.js → connected-evidence-IVSQZYIB.js} +1 -1
  59. package/dist/chunks/{continual-K5JNHNQH.js → continual-PKK2BOTB.js} +1 -1
  60. package/dist/chunks/core-commands-W5IGIITV.js +2 -0
  61. package/dist/chunks/{datasets-KDN2EXHE.js → datasets-KSO2UG6R.js} +1 -1
  62. package/dist/chunks/{desktop-test-WIOEKMPR.js → desktop-test-6HXFM7PO.js} +1 -1
  63. package/dist/chunks/{dist-JBE7DPFZ.js → dist-4HV2W6V4.js} +1 -1
  64. package/dist/chunks/{dist-3MTJ7VM6.js → dist-BLBZENVB.js} +1 -1
  65. package/dist/chunks/{evaluation-coordination-NGYHL7HG.js → evaluation-coordination-MOFBXRXN.js} +1 -1
  66. package/dist/chunks/{experiment-improvements-2M7GRGWS.js → experiment-improvements-TDHM6NEA.js} +1 -1
  67. package/dist/chunks/{experiments-B6CRZ3GI.js → experiments-HFPDFD4I.js} +1 -1
  68. package/dist/chunks/{extension-RZTMK3ON.js → extension-R373LYIB.js} +1 -1
  69. package/dist/chunks/{help-EISFHH2F.js → help-PEFQDDTA.js} +1 -1
  70. package/dist/chunks/{hosted-experiment-improvement-6CHH65DX.js → hosted-experiment-improvement-MGMZWTZY.js} +1 -1
  71. package/dist/chunks/hosted-harness-runtime-FZZLWLBR.js +2 -0
  72. package/dist/chunks/{hosted-profile-candidate-HYEISIAC.js → hosted-profile-candidate-LVNKOTKJ.js} +1 -1
  73. package/dist/chunks/hosted-profile-compiler-PQFIWO5B.js +2 -0
  74. package/dist/chunks/{hosted-profile-evaluation-control-LV6YXOG7.js → hosted-profile-evaluation-control-7B3RAZU2.js} +1 -1
  75. package/dist/chunks/{hosted-profile-evaluation-inspection-A62UYFEP.js → hosted-profile-evaluation-inspection-FPCV42DD.js} +1 -1
  76. package/dist/chunks/hosted-profile-evaluation-preparation-JROREZH3.js +3 -0
  77. package/dist/chunks/{human-review-J6JGNRBR.js → human-review-HRGGACEM.js} +1 -1
  78. package/dist/chunks/import-RSAQ44GG.js +4 -0
  79. package/dist/chunks/{learning-REL6GGNA.js → learning-FNBEIAY6.js} +1 -1
  80. package/dist/chunks/{opchat-CUZUU2WM.js → opchat-I7ZWJ5XK.js} +1 -1
  81. package/dist/chunks/{organizations-VT27V4B2.js → organizations-LFCZIH7E.js} +1 -1
  82. package/dist/chunks/{profile-N2E5ASHQ.js → profile-EPIX5QVK.js} +1 -1
  83. package/dist/chunks/{project-agent-XMXOBJSC.js → project-agent-DGOPMECP.js} +1 -1
  84. package/dist/chunks/{sandbox-command-NC665ZZ5.js → sandbox-command-Q5F6VUOS.js} +1 -1
  85. package/dist/chunks/{sandbox-template-OTP6S3RU.js → sandbox-template-7GICPIKJ.js} +1 -1
  86. package/dist/chunks/{src-WM35IF4W.js → src-DH5AQ4Z7.js} +1 -1
  87. package/dist/chunks/src-GKWEQK2T.js +329 -0
  88. package/dist/chunks/{taskset-COAPMTT3.js → taskset-LUG3ZU6J.js} +1 -1
  89. package/dist/chunks/{teams-bot-ACWJ7PJP.js → teams-bot-Z6RJGHME.js} +1 -1
  90. package/dist/chunks/{training-4JUK7YQV.js → training-XHE6FVII.js} +1 -1
  91. package/dist/chunks/{workspaces-WTPFRJMS.js → workspaces-XIQNPAP7.js} +1 -1
  92. package/dist/cli.js +1 -1
  93. package/dist/index.js +1 -1
  94. package/dist/web/agent-sources/SOURCES.md +11 -0
  95. package/dist/web/agent-sources/claude-code.svg +1 -0
  96. package/dist/web/agent-sources/codex.svg +1 -0
  97. package/dist/web/agent-sources/grok-build.svg +3 -0
  98. package/dist/web/agent-sources/hermes.png +0 -0
  99. package/dist/web/agent-sources/oh-my-pi.svg +11 -0
  100. package/dist/web/agent-sources/openclaw.svg +54 -0
  101. package/dist/web/agent-sources/opencode.svg +4 -0
  102. package/dist/web/agent-sources/pi.svg +6 -0
  103. package/dist/web/assets/App-BI-uOpnP.js +234 -0
  104. package/dist/web/assets/App-DkH8CeoI.css +1 -0
  105. package/dist/web/assets/{AppDialog-CaxeNfsu.js → AppDialog-1iGodoot.js} +1 -1
  106. package/dist/web/assets/{AppTerminalPanel-dtK0ZPer.js → AppTerminalPanel-udtBdWFn.js} +2 -2
  107. package/dist/web/assets/AppsView-BonAGiS8.css +1 -0
  108. package/dist/web/assets/AppsView-DhKsU4yi.js +1 -0
  109. package/dist/web/assets/BrowserSidebar-BnOyqIQT.js +1 -0
  110. package/dist/web/assets/{CartesianChart-Drfk6jTn.js → CartesianChart-C24DAywn.js} +1 -1
  111. package/dist/web/assets/{CollaborationTabs-Czh2noeb.js → CollaborationTabs-DgmOF5Fe.js} +1 -1
  112. package/dist/web/assets/{CommandMenu-D-M-xomh.js → CommandMenu-CUNGtHwS.js} +1 -1
  113. package/dist/web/assets/{CommunityView-BrdxUI5Z.js → CommunityView-CE7qeJnr.js} +1 -1
  114. package/dist/web/assets/{ComposerCreateImproveStrip-CJ8nkYJf.js → ComposerCreateImproveStrip-BixNsg2a.js} +1 -1
  115. package/dist/web/assets/{GetStartedView-u7Jw7YA1.js → GetStartedView-B8gCwmBX.js} +1 -1
  116. package/dist/web/assets/{HostedModelLearningReview-D0a2nwse.js → HostedModelLearningReview-CitgUNfC.js} +1 -1
  117. package/dist/web/assets/{HostedModelLearningSettings-CQQGyjxi.js → HostedModelLearningSettings-WUaqzNsa.js} +1 -1
  118. package/dist/web/assets/{LabModelVersionDetailPage-Cxlc4sSC.js → LabModelVersionDetailPage-Cx0kL69J.js} +1 -1
  119. package/dist/web/assets/{LabSkillSidebar-BnJkDb0c.js → LabSkillSidebar-DRggqZ1j.js} +1 -1
  120. package/dist/web/assets/LabsRoute-BujTZhqC.js +99 -0
  121. package/dist/web/assets/{MainChatThread-r_TYiTnW.js → MainChatThread-CyA_644R.js} +2 -2
  122. package/dist/web/assets/MainPane-LaEtxydD.js +19 -0
  123. package/dist/web/assets/{MarkdownText-BxPHz4je.js → MarkdownText-DJI5LwT0.js} +19 -19
  124. package/dist/web/assets/{NativeSkillSidebar-CCHK6kMG.js → NativeSkillSidebar-CkFpWxjd.js} +1 -1
  125. package/dist/web/assets/{NewExperienceSwitcher-CuKWTDZj.js → NewExperienceSwitcher-DXcRHHsu.js} +1 -1
  126. package/dist/web/assets/{NewProjectDialog-CS6sw2oD.js → NewProjectDialog-gDzX_ZIJ.js} +1 -1
  127. package/dist/web/assets/{OutputsPage-JDM5bfLJ.js → OutputsPage-J_k-_N82.js} +1 -1
  128. package/dist/web/assets/{ProjectsPage-B3zTBHOA.js → ProjectsPage-BsyZmvlg.js} +1 -1
  129. package/dist/web/assets/{RightChatPanelStack-L8S3yj1u.js → RightChatPanelStack-Bz8puMUB.js} +1 -1
  130. package/dist/web/assets/{RightSidebarHomePanel-BWJQKFUp.js → RightSidebarHomePanel-DmorYb6p.js} +1 -1
  131. package/dist/web/assets/ScheduledWorkPage-BFDzQUyL.js +1 -0
  132. package/dist/web/assets/SettingsView-BB7wCdbr.js +5 -0
  133. package/dist/web/assets/SettingsView-BnANbPLS.css +1 -0
  134. package/dist/web/assets/{TeamChatView-DakXCNQE.js → TeamChatView-CZ3b7rq2.js} +2 -2
  135. package/dist/web/assets/{TerminalOverlay-DaonK5C0.js → TerminalOverlay-Ck43Qri3.js} +1 -1
  136. package/dist/web/assets/{TrainingCreationPanel-CUvSsSwp.js → TrainingCreationPanel-ejqPZm3g.js} +1 -1
  137. package/dist/web/assets/{TrainingDraftPanel-DNivtVwd.js → TrainingDraftPanel-Cy2AQxxL.js} +1 -1
  138. package/dist/web/assets/{UsageSettingsSection-rbmuoPoE.js → UsageSettingsSection-B7nyMItm.js} +1 -1
  139. package/dist/web/assets/{WorkSidebarPanel-DrYt9xzv.js → WorkSidebarPanel-BfjAc097.js} +1 -1
  140. package/dist/web/assets/{WorkspaceDiffPanel-CThoTqe4.js → WorkspaceDiffPanel-D9hAV8l7.js} +5 -5
  141. package/dist/web/assets/{WorkspaceEnvironmentMenu-DeODKxvW.js → WorkspaceEnvironmentMenu-B-K9XgFB.js} +3 -3
  142. package/dist/web/assets/{WorkspaceGitDialogs-CBarJYF-.js → WorkspaceGitDialogs-BJVFx_L3.js} +1 -1
  143. package/dist/web/assets/{WorkspaceMonacoEditor-Hmu5m_sO.js → WorkspaceMonacoEditor-p-FWMXoZ.js} +3 -3
  144. package/dist/web/assets/{arrow-up-right-BV2IHfb9.js → arrow-up-right-CFGI2YSt.js} +1 -1
  145. package/dist/web/assets/{chunk-YTGRET2L-PKzEfYnf.js → chunk-UHVJOMWN-BAlur2vw.js} +1 -1
  146. package/dist/web/assets/{clipboard-DDIvAWKp.js → clipboard-DIIxBort.js} +1 -1
  147. package/dist/web/assets/{cloud-upload-Dv6kFnfC.js → cloud-upload-BaQFNCTp.js} +1 -1
  148. package/dist/web/assets/{cssMode-BK0jFqWW.js → cssMode-6LOkSggB.js} +1 -1
  149. package/dist/web/assets/{folder-open-B9ixJQJX.js → folder-open-DZSxfPtr.js} +1 -1
  150. package/dist/web/assets/{folder-plus-DqSKvtNB.js → folder-plus-21v4D_Vx.js} +1 -1
  151. package/dist/web/assets/{git-commit-horizontal-C1lQvfxe.js → git-commit-horizontal-CgGixL64.js} +1 -1
  152. package/dist/web/assets/{htmlMode-CCV301b6.js → htmlMode-B5uRraNd.js} +1 -1
  153. package/dist/web/assets/index-DJcUXSsN.css +1 -0
  154. package/dist/web/assets/{index-DIaKfM8a.js → index-DOMrqhcz.js} +2 -2
  155. package/dist/web/assets/{info-BEvaynAD.js → info-BGTcmow7.js} +1 -1
  156. package/dist/web/assets/{jsonMode-Co4pyN4F.js → jsonMode-D3m8N4Gi.js} +1 -1
  157. package/dist/web/assets/{lspLanguageFeatures-CSU0G5da.js → lspLanguageFeatures-DoyipLsB.js} +1 -1
  158. package/dist/web/assets/{minimize-2-DT8t8wwP.js → minimize-2-B01qSko4.js} +1 -1
  159. package/dist/web/assets/{monaco.contribution-Cr0AaHCD.js → monaco.contribution--U8v3jpa.js} +2 -2
  160. package/dist/web/assets/{monaco.contribution-DSBAb_PC.js → monaco.contribution-BJyfaGX2.js} +2 -2
  161. package/dist/web/assets/{monaco.contribution-CBwGIQY1.js → monaco.contribution-Bc22foTx.js} +2 -2
  162. package/dist/web/assets/{monaco.contribution-DUZrs1D-.js → monaco.contribution-DuRhJ6zU.js} +2 -2
  163. package/dist/web/assets/{monitor-DGqnfsK9.js → monitor-eZP8ZTHe.js} +1 -1
  164. package/dist/web/assets/{play-C1XWyKh6.js → play-CGsWFR_B.js} +1 -1
  165. package/dist/web/assets/{python-Z1foxLdf.js → python-BNrLZWud.js} +1 -1
  166. package/dist/web/assets/{save-CX2kF74j.js → save-BLgjrccP.js} +1 -1
  167. package/dist/web/assets/{square-DMkXeYeV.js → square-CI1qNtvE.js} +1 -1
  168. package/dist/web/assets/{toggleHighContrast-CRMVp779.js → toggleHighContrast-B_GcTCnw.js} +1 -1
  169. package/dist/web/assets/{tsMode-Czu8YAqh.js → tsMode-CmruH_ys.js} +1 -1
  170. package/dist/web/assets/{upload-giKOPnl1.js → upload-DnlgGS2x.js} +1 -1
  171. package/dist/web/assets/useLocalAgentSchedules-BBhGUfK-.js +1 -0
  172. package/dist/web/assets/useProviderSettings-Bw-csWbH.css +1 -0
  173. package/dist/web/assets/useProviderSettings-DfhdkKdC.js +5 -0
  174. package/dist/web/assets/{useSessionTurnCache-CUYFsu_W.js → useSessionTurnCache-BwscKl5i.js} +1 -1
  175. package/dist/web/assets/{wifi-off-DbDXaV1N.js → wifi-off-Dz-4EDCc.js} +1 -1
  176. package/dist/web/assets/{workers-Cno4XklJ.js → workers-Bi9u46cp.js} +1 -1
  177. package/dist/web/assets/{yaml-C28t_C6h.js → yaml-DVTkiRnh.js} +1 -1
  178. package/dist/web/index.html +2 -2
  179. package/package.json +1 -1
  180. package/dist/chunks/app-server-runtime-FL2CHQU2.js +0 -2
  181. package/dist/chunks/chunk-4VKNBADF.js +0 -2
  182. package/dist/chunks/chunk-5ZZM3TUN.js +0 -24
  183. package/dist/chunks/chunk-6JBWHR6T.js +0 -5
  184. package/dist/chunks/chunk-FKCWOASO.js +0 -49
  185. package/dist/chunks/chunk-FOEUDMME.js +0 -2678
  186. package/dist/chunks/chunk-ICZEOMPO.js +0 -2
  187. package/dist/chunks/chunk-JO7GRBOG.js +0 -2
  188. package/dist/chunks/chunk-KUKOZJIR.js +0 -2
  189. package/dist/chunks/chunk-M7PBDRKC.js +0 -2
  190. package/dist/chunks/chunk-P653BXMY.js +0 -3
  191. package/dist/chunks/chunk-PMZH2TKS.js +0 -4
  192. package/dist/chunks/chunk-W4IL6TWB.js +0 -186
  193. package/dist/chunks/chunk-WVNN3RB2.js +0 -2
  194. package/dist/chunks/cli-5QR7QNQJ.js +0 -2
  195. package/dist/chunks/core-commands-J2SJM5I5.js +0 -2
  196. package/dist/chunks/hosted-harness-runtime-PAYMAXH7.js +0 -2
  197. package/dist/chunks/hosted-profile-compiler-KQREWJA5.js +0 -2
  198. package/dist/chunks/hosted-profile-evaluation-preparation-OR4OLYEX.js +0 -3
  199. package/dist/chunks/import-YHSX6SBZ.js +0 -4
  200. package/dist/chunks/src-TNWF3IC5.js +0 -329
  201. package/dist/web/assets/App-CdDQ-lXE.css +0 -1
  202. package/dist/web/assets/App-D2f8_mGk.js +0 -235
  203. package/dist/web/assets/AppsView-CzbB5pXp.css +0 -1
  204. package/dist/web/assets/AppsView-DwK1UBJP.js +0 -1
  205. package/dist/web/assets/BrowserSidebar-Cj9VnkgU.js +0 -1
  206. package/dist/web/assets/LabsRoute-hHwZNbqN.js +0 -99
  207. package/dist/web/assets/MainPane-DJcd4tPk.js +0 -19
  208. package/dist/web/assets/ScheduledWorkPage-qX12p4B0.js +0 -1
  209. package/dist/web/assets/SettingsView-0KMs-r2I.js +0 -9
  210. package/dist/web/assets/SettingsView-CVsuQeCZ.css +0 -1
  211. package/dist/web/assets/index-1cMIFBxZ.css +0 -1
  212. package/dist/web/assets/useLocalAgentSchedules-BHxWmOeC.js +0 -1
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import"./chunk-BX4J2VDU.js";import{a as se}from"./chunk-PMZH2TKS.js";import"./chunk-HK3WGUKK.js";import"./chunk-6MI4KKWF.js";import"./chunk-5ZZM3TUN.js";import"./chunk-OGXSE57Z.js";import"./chunk-JEVA7YQL.js";import"./chunk-22UARBPW.js";import{a as T,x as D}from"./chunk-F5DUN73H.js";import"./chunk-ZC57DX6D.js";import"./chunk-EAPFMACH.js";import"./chunk-6FA3GG5B.js";import{f as G}from"./chunk-3M53YXEI.js";import"./chunk-LZSY5IM3.js";import"./chunk-6SJZXZNA.js";import"./chunk-GLUWATL5.js";import"./chunk-JO7GRBOG.js";import"./chunk-BQNK2NMB.js";import"./chunk-VW7D3DRM.js";import{f as N}from"./chunk-UWO34HP6.js";import"./chunk-L4BYPZ4U.js";import"./chunk-P653BXMY.js";import"./chunk-ES2ISFJC.js";import{f as ne,h as z,p as B,r as oe}from"./chunk-H7IWJN7L.js";import{a as r}from"./chunk-FTQLQJQV.js";var u=class extends Error{static{r(this,"GithubExtensionError")}code;status;constructor(t,o){super(t),this.name="GithubExtensionError",this.code=o.code,this.status=o.status??400}};import{createHash as ce}from"node:crypto";import J from"node:path";var ie="HEAD",ae=64,de=512,le=20*1024*1024,K=5*1024*1024,me=8,Ue=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,pe=/^[A-Za-z0-9_.-]+$/,ue=new Set(["agents","assets","references","scripts"]);function Se(e={}){let t=e.fetch??fetch,o=e.githubToken?.trim()||process.env.GITHUB_TOKEN?.trim()||process.env.GH_TOKEN?.trim()||null;return{async resolve(n){let s=await qe(n,t,o);return{preview:await Te(s,t,o),files:ge(s)}},async download(n,s){await _e({resolution:n,fetchImpl:t,githubToken:o,writeFile:s})}}}r(Se,"createGithubSourceClient");function I(e){let t=e.trim(),o="",n="";if(/^(?:https?:\/\/)?github\.com\//i.test(t)){let d=new URL(t.startsWith("http")?t:`https://${t}`);if(d.hostname.toLowerCase()!=="github.com")throw j(e);let a=d.pathname.replace(/^\/+|\/+$/g,"").split("/");if(a.length!==2)throw j(e);[o="",n=""]=a}else{let a=t.replace(/^github:/i,"").replace(/^\/+|\/+$/g,"").split("/");if(a.length!==2)throw j(e);[o="",n=""]=a}if(n=n.replace(/\.git$/i,""),!pe.test(o)||!pe.test(n))throw j(e);let s=o.toLowerCase(),i=n.toLowerCase();return{id:`github:${s}/${i}`,owner:s,repo:i,repositoryUrl:`https://github.com/${s}/${i}`}}r(I,"parseGithubExtensionSource");async function qe(e,t,o){let n=I(e.source),s=e.ref?.trim()||ie,i=await H(t,o,`/repos/${n.owner}/${n.repo}`),d=s===ie?i.default_branch?.trim()||"main":s,a=await H(t,o,`/repos/${n.owner}/${n.repo}/commits/${encodeURIComponent(d)}`),b=a.sha?.trim(),f=a.commit?.tree?.sha?.trim();if(!b||!f)throw new u("GitHub returned an incomplete commit response.",{code:"github_invalid_commit",status:502});let y=await H(t,o,`/repos/${n.owner}/${n.repo}/git/trees/${f}?recursive=1`);if(y.truncated)throw new u("The GitHub repository tree is too large to install safely.",{code:"github_tree_truncated"});let w=(y.tree??[]).filter(ze),x=Le(w);if(x.length===0)throw new u("No skills found. Add SKILL.md at the repository root or use a standard agent skills directory.",{code:"extension_no_skills"});if(x.length>ae)throw new u(`Extension contains more than ${ae} skills.`,{code:"extension_too_many_skills"});Ge(x);let A=w.find(m=>m.type==="blob"&&/^readme(?:\.[^/]+)?$/i.test(m.path))??null;return{identity:n,requestedRef:s,resolvedCommit:b,tree:w,skillPackages:x,readme:A}}r(qe,"resolveSource");async function Te(e,t,o){let n=await xe(e.skillPackages,me,async a=>{let b=await Fe(e,a.entry,t,o);return je(a,b)}),s=De(n.map(a=>a.name));for(let a of n)s.has(a.name)&&(a.validationStatus="error",a.validationMessages=[...a.validationMessages,`Duplicate skill name: ${a.name}`]);let i=n.flatMap(a=>a.validationMessages.map(b=>`${a.relativePath}: ${b}`)),d=ge(e);return{...e.identity,source:"github",requestedRef:e.requestedRef,resolvedCommit:e.resolvedCommit,sourcePath:null,readmePath:e.readme?.path??null,packageHash:Ne(d),skills:n.sort((a,b)=>a.name.localeCompare(b.name)),validationStatus:i.length===0?"valid":"error",validationMessages:i}}r(Te,"buildPreview");function je(e,t){let o=T(t),n=e.root==="."?null:J.posix.basename(e.root),s=o.name??n??"invalid-skill",i=[...o.messages];Ue.test(s)||i.push("Skill name must be lowercase kebab-case."),n&&s!==n&&i.push(`Skill name must match its directory name (${n}).`);let d=e.files.filter(a=>a.path!==e.entry.path).map(a=>Be(e.root,a.path)).sort();return{name:s,description:o.description??"",relativePath:e.root==="."?"SKILL.md":`${e.root}/SKILL.md`,sourcePath:"",charCount:t.length,sourceHash:ce("sha256").update(t).digest("hex"),resourceFiles:d,validationStatus:i.length===0?"valid":"error",validationMessages:[...new Set(i)]}}r(je,"previewSkill");function Le(e){let t=[],o=e.find(a=>a.type==="blob"&&a.path==="SKILL.md");o&&t.push({root:".",entry:o});let n=e.filter(a=>a.type==="blob"&&a.path.endsWith("/SKILL.md")),s=n.filter(a=>Me(a.path)),i=s.length>0?s:n,d=new Set(i.map(a=>J.posix.dirname(a.path)));for(let a of i){let b=J.posix.dirname(a.path);[...d].some(f=>f!==b&&b.startsWith(`${f}/`))||t.push({root:b,entry:a})}return t.map(({root:a,entry:b})=>{let f=e.filter(x=>{if(x.type!=="blob")return!1;if(a!==".")return x.path.startsWith(`${a}/`);if(x.path==="SKILL.md")return!0;let A=x.path.split("/",1)[0]??"";return ue.has(A)}),y=e.find(x=>x.type!=="blob"&&x.type!=="tree"&&(a==="."?x.path==="SKILL.md"||ue.has(x.path.split("/",1)[0]??""):x.path.startsWith(`${a}/`))),w=f.find(x=>x.mode==="120000");if(y||w)throw new u(`Skill package ${a} contains a symlink or submodule.`,{code:"extension_unsafe_entry"});return{root:a,entry:b,files:f}})}r(Le,"discoverSkillPackages");function Me(e){let t=e.split("/");if(t.at(-1)!=="SKILL.md")return!1;let o=t.slice(0,-1);if(o.length<2)return!1;let n=o.lastIndexOf("skills");if(n<0||n>2)return!1;let s=o.slice(0,n),i=o.slice(n+1);if(i.length<1||i.length>2)return!1;if(n===0)return!0;let d=s[0]??"";return d.startsWith(".")||d==="agent"||d==="data"}r(Me,"isStandardAgentSkillsPath");function ge(e){let t=new Map;e.readme&&t.set(e.readme.path,e.readme);for(let o of e.skillPackages)for(let n of o.files)t.set(n.path,n);return[...t.values()].sort((o,n)=>o.path.localeCompare(n.path))}r(ge,"filesToDownload");async function _e(e){let t=0;await xe(e.resolution.files,me,async o=>{let n=await be({owner:e.resolution.preview.owner,repo:e.resolution.preview.repo,commit:e.resolution.preview.resolvedCommit,file:o,fetchImpl:e.fetchImpl,githubToken:e.githubToken});if(t+=n.byteLength,t>le)throw new u("Extension download exceeds the maximum allowed size.",{code:"extension_too_large"});await e.writeFile(o.path,n,o.mode==="100755")})}r(_e,"downloadFiles");async function Fe(e,t,o,n){let s=await be({owner:e.identity.owner,repo:e.identity.repo,commit:e.resolvedCommit,file:t,fetchImpl:o,githubToken:n});return new TextDecoder("utf-8",{fatal:!0}).decode(s)}r(Fe,"downloadText");async function be(e){let t=e.file.path.split("/").map(encodeURIComponent).join("/"),o=`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.commit}/${t}`,n=await e.fetchImpl(o,{headers:he(e.githubToken,"application/vnd.github.raw"),redirect:"follow"});if(!n.ok)throw new u(`GitHub file download failed (${n.status}): ${e.file.path}`,{code:"github_download_failed",status:n.status});let s=Number(n.headers.get("content-length"));if(Number.isFinite(s)&&s>K)throw new u(`Extension file is too large: ${e.file.path}`,{code:"extension_file_too_large"});let i=new Uint8Array(await n.arrayBuffer());if(i.byteLength>K)throw new u(`Extension file is too large: ${e.file.path}`,{code:"extension_file_too_large"});return i}r(be,"downloadBytes");async function H(e,t,o){let n=await e(`https://api.github.com${o}`,{headers:he(t,"application/vnd.github+json")});if(!n.ok){let s=await n.json().catch(()=>null),i=typeof s?.message=="string"?`: ${s.message}`:"";throw new u(`GitHub request failed (${n.status})${i}`,{code:n.status===404?"github_repository_not_found":"github_request_failed",status:n.status})}return await n.json()}r(H,"githubJson");function he(e,t){let o=new Headers({Accept:t,"User-Agent":"openpond-extension-installer","X-GitHub-Api-Version":"2022-11-28"});return e&&o.set("Authorization",`Bearer ${e}`),o}r(he,"githubHeaders");function Ge(e){let t=new Map;for(let n of e)for(let s of n.files)t.set(s.path,s);if(t.size>de)throw new u(`Extension contains more than ${de} skill files.`,{code:"extension_too_many_files"});let o=0;for(let n of t.values()){if((n.size??0)>K)throw new u(`Extension file is too large: ${n.path}`,{code:"extension_file_too_large"});o+=n.size??0}if(o>le)throw new u("Extension exceeds the maximum allowed size.",{code:"extension_too_large"})}r(Ge,"validateDownloadLimits");function ze(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.path=="string"&&!t.path.startsWith("/")&&!t.path.split("/").includes("..")&&typeof t.mode=="string"&&(t.type==="blob"||t.type==="tree"||t.type==="commit")&&typeof t.sha=="string"}r(ze,"validTreeEntry");function Ne(e){let t=ce("sha256");for(let o of e)t.update(`${o.path}\0${o.sha}\0${o.size??""}
2
+ import"./chunk-BX4J2VDU.js";import{a as se}from"./chunk-XBCIBAXD.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-YIB3J4RC.js";import"./chunk-JEVA7YQL.js";import"./chunk-22UARBPW.js";import{a as T,x as D}from"./chunk-N5QNXMIS.js";import"./chunk-JDLAHVAJ.js";import"./chunk-EAPFMACH.js";import"./chunk-6FA3GG5B.js";import{f as G}from"./chunk-3M53YXEI.js";import"./chunk-QXVIIM4T.js";import"./chunk-R3XFY7VL.js";import"./chunk-GLUWATL5.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import{f as N}from"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import{f as ne,h as z,p as B,r as oe}from"./chunk-H7IWJN7L.js";import{a as r}from"./chunk-FTQLQJQV.js";var u=class extends Error{static{r(this,"GithubExtensionError")}code;status;constructor(t,o){super(t),this.name="GithubExtensionError",this.code=o.code,this.status=o.status??400}};import{createHash as ce}from"node:crypto";import J from"node:path";var ie="HEAD",ae=64,de=512,le=20*1024*1024,K=5*1024*1024,me=8,Ue=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,pe=/^[A-Za-z0-9_.-]+$/,ue=new Set(["agents","assets","references","scripts"]);function Se(e={}){let t=e.fetch??fetch,o=e.githubToken?.trim()||process.env.GITHUB_TOKEN?.trim()||process.env.GH_TOKEN?.trim()||null;return{async resolve(n){let s=await qe(n,t,o);return{preview:await Te(s,t,o),files:ge(s)}},async download(n,s){await _e({resolution:n,fetchImpl:t,githubToken:o,writeFile:s})}}}r(Se,"createGithubSourceClient");function I(e){let t=e.trim(),o="",n="";if(/^(?:https?:\/\/)?github\.com\//i.test(t)){let d=new URL(t.startsWith("http")?t:`https://${t}`);if(d.hostname.toLowerCase()!=="github.com")throw j(e);let a=d.pathname.replace(/^\/+|\/+$/g,"").split("/");if(a.length!==2)throw j(e);[o="",n=""]=a}else{let a=t.replace(/^github:/i,"").replace(/^\/+|\/+$/g,"").split("/");if(a.length!==2)throw j(e);[o="",n=""]=a}if(n=n.replace(/\.git$/i,""),!pe.test(o)||!pe.test(n))throw j(e);let s=o.toLowerCase(),i=n.toLowerCase();return{id:`github:${s}/${i}`,owner:s,repo:i,repositoryUrl:`https://github.com/${s}/${i}`}}r(I,"parseGithubExtensionSource");async function qe(e,t,o){let n=I(e.source),s=e.ref?.trim()||ie,i=await H(t,o,`/repos/${n.owner}/${n.repo}`),d=s===ie?i.default_branch?.trim()||"main":s,a=await H(t,o,`/repos/${n.owner}/${n.repo}/commits/${encodeURIComponent(d)}`),b=a.sha?.trim(),f=a.commit?.tree?.sha?.trim();if(!b||!f)throw new u("GitHub returned an incomplete commit response.",{code:"github_invalid_commit",status:502});let y=await H(t,o,`/repos/${n.owner}/${n.repo}/git/trees/${f}?recursive=1`);if(y.truncated)throw new u("The GitHub repository tree is too large to install safely.",{code:"github_tree_truncated"});let w=(y.tree??[]).filter(ze),x=Le(w);if(x.length===0)throw new u("No skills found. Add SKILL.md at the repository root or use a standard agent skills directory.",{code:"extension_no_skills"});if(x.length>ae)throw new u(`Extension contains more than ${ae} skills.`,{code:"extension_too_many_skills"});Ge(x);let A=w.find(m=>m.type==="blob"&&/^readme(?:\.[^/]+)?$/i.test(m.path))??null;return{identity:n,requestedRef:s,resolvedCommit:b,tree:w,skillPackages:x,readme:A}}r(qe,"resolveSource");async function Te(e,t,o){let n=await xe(e.skillPackages,me,async a=>{let b=await Fe(e,a.entry,t,o);return je(a,b)}),s=De(n.map(a=>a.name));for(let a of n)s.has(a.name)&&(a.validationStatus="error",a.validationMessages=[...a.validationMessages,`Duplicate skill name: ${a.name}`]);let i=n.flatMap(a=>a.validationMessages.map(b=>`${a.relativePath}: ${b}`)),d=ge(e);return{...e.identity,source:"github",requestedRef:e.requestedRef,resolvedCommit:e.resolvedCommit,sourcePath:null,readmePath:e.readme?.path??null,packageHash:Ne(d),skills:n.sort((a,b)=>a.name.localeCompare(b.name)),validationStatus:i.length===0?"valid":"error",validationMessages:i}}r(Te,"buildPreview");function je(e,t){let o=T(t),n=e.root==="."?null:J.posix.basename(e.root),s=o.name??n??"invalid-skill",i=[...o.messages];Ue.test(s)||i.push("Skill name must be lowercase kebab-case."),n&&s!==n&&i.push(`Skill name must match its directory name (${n}).`);let d=e.files.filter(a=>a.path!==e.entry.path).map(a=>Be(e.root,a.path)).sort();return{name:s,description:o.description??"",relativePath:e.root==="."?"SKILL.md":`${e.root}/SKILL.md`,sourcePath:"",charCount:t.length,sourceHash:ce("sha256").update(t).digest("hex"),resourceFiles:d,validationStatus:i.length===0?"valid":"error",validationMessages:[...new Set(i)]}}r(je,"previewSkill");function Le(e){let t=[],o=e.find(a=>a.type==="blob"&&a.path==="SKILL.md");o&&t.push({root:".",entry:o});let n=e.filter(a=>a.type==="blob"&&a.path.endsWith("/SKILL.md")),s=n.filter(a=>Me(a.path)),i=s.length>0?s:n,d=new Set(i.map(a=>J.posix.dirname(a.path)));for(let a of i){let b=J.posix.dirname(a.path);[...d].some(f=>f!==b&&b.startsWith(`${f}/`))||t.push({root:b,entry:a})}return t.map(({root:a,entry:b})=>{let f=e.filter(x=>{if(x.type!=="blob")return!1;if(a!==".")return x.path.startsWith(`${a}/`);if(x.path==="SKILL.md")return!0;let A=x.path.split("/",1)[0]??"";return ue.has(A)}),y=e.find(x=>x.type!=="blob"&&x.type!=="tree"&&(a==="."?x.path==="SKILL.md"||ue.has(x.path.split("/",1)[0]??""):x.path.startsWith(`${a}/`))),w=f.find(x=>x.mode==="120000");if(y||w)throw new u(`Skill package ${a} contains a symlink or submodule.`,{code:"extension_unsafe_entry"});return{root:a,entry:b,files:f}})}r(Le,"discoverSkillPackages");function Me(e){let t=e.split("/");if(t.at(-1)!=="SKILL.md")return!1;let o=t.slice(0,-1);if(o.length<2)return!1;let n=o.lastIndexOf("skills");if(n<0||n>2)return!1;let s=o.slice(0,n),i=o.slice(n+1);if(i.length<1||i.length>2)return!1;if(n===0)return!0;let d=s[0]??"";return d.startsWith(".")||d==="agent"||d==="data"}r(Me,"isStandardAgentSkillsPath");function ge(e){let t=new Map;e.readme&&t.set(e.readme.path,e.readme);for(let o of e.skillPackages)for(let n of o.files)t.set(n.path,n);return[...t.values()].sort((o,n)=>o.path.localeCompare(n.path))}r(ge,"filesToDownload");async function _e(e){let t=0;await xe(e.resolution.files,me,async o=>{let n=await be({owner:e.resolution.preview.owner,repo:e.resolution.preview.repo,commit:e.resolution.preview.resolvedCommit,file:o,fetchImpl:e.fetchImpl,githubToken:e.githubToken});if(t+=n.byteLength,t>le)throw new u("Extension download exceeds the maximum allowed size.",{code:"extension_too_large"});await e.writeFile(o.path,n,o.mode==="100755")})}r(_e,"downloadFiles");async function Fe(e,t,o,n){let s=await be({owner:e.identity.owner,repo:e.identity.repo,commit:e.resolvedCommit,file:t,fetchImpl:o,githubToken:n});return new TextDecoder("utf-8",{fatal:!0}).decode(s)}r(Fe,"downloadText");async function be(e){let t=e.file.path.split("/").map(encodeURIComponent).join("/"),o=`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.commit}/${t}`,n=await e.fetchImpl(o,{headers:he(e.githubToken,"application/vnd.github.raw"),redirect:"follow"});if(!n.ok)throw new u(`GitHub file download failed (${n.status}): ${e.file.path}`,{code:"github_download_failed",status:n.status});let s=Number(n.headers.get("content-length"));if(Number.isFinite(s)&&s>K)throw new u(`Extension file is too large: ${e.file.path}`,{code:"extension_file_too_large"});let i=new Uint8Array(await n.arrayBuffer());if(i.byteLength>K)throw new u(`Extension file is too large: ${e.file.path}`,{code:"extension_file_too_large"});return i}r(be,"downloadBytes");async function H(e,t,o){let n=await e(`https://api.github.com${o}`,{headers:he(t,"application/vnd.github+json")});if(!n.ok){let s=await n.json().catch(()=>null),i=typeof s?.message=="string"?`: ${s.message}`:"";throw new u(`GitHub request failed (${n.status})${i}`,{code:n.status===404?"github_repository_not_found":"github_request_failed",status:n.status})}return await n.json()}r(H,"githubJson");function he(e,t){let o=new Headers({Accept:t,"User-Agent":"openpond-extension-installer","X-GitHub-Api-Version":"2022-11-28"});return e&&o.set("Authorization",`Bearer ${e}`),o}r(he,"githubHeaders");function Ge(e){let t=new Map;for(let n of e)for(let s of n.files)t.set(s.path,s);if(t.size>de)throw new u(`Extension contains more than ${de} skill files.`,{code:"extension_too_many_files"});let o=0;for(let n of t.values()){if((n.size??0)>K)throw new u(`Extension file is too large: ${n.path}`,{code:"extension_file_too_large"});o+=n.size??0}if(o>le)throw new u("Extension exceeds the maximum allowed size.",{code:"extension_too_large"})}r(Ge,"validateDownloadLimits");function ze(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.path=="string"&&!t.path.startsWith("/")&&!t.path.split("/").includes("..")&&typeof t.mode=="string"&&(t.type==="blob"||t.type==="tree"||t.type==="commit")&&typeof t.sha=="string"}r(ze,"validTreeEntry");function Ne(e){let t=ce("sha256");for(let o of e)t.update(`${o.path}\0${o.sha}\0${o.size??""}
3
3
  `);return t.digest("hex")}r(Ne,"hashTree");function Be(e,t){return e==="."?t:t.slice(e.length+1)}r(Be,"relativeSkillPath");function De(e){let t=new Set,o=new Set;for(let n of e)t.has(n)&&o.add(n),t.add(n);return o}r(De,"duplicateValues");async function xe(e,t,o){let n=new Array(e.length),s=0;async function i(){for(;s<e.length;){let d=s;s+=1,n[d]=await o(e[d])}}return r(i,"worker"),await Promise.all(Array.from({length:Math.min(t,e.length)},i)),n}r(xe,"mapConcurrent");function j(e){return new u(`Invalid GitHub extension source: ${e}. Use owner/repo or https://github.com/owner/repo.`,{code:"github_invalid_source"})}r(j,"invalidSource");import{createHash as He,randomUUID as we}from"node:crypto";import{existsSync as v}from"node:fs";import{mkdir as W,readFile as Je,rename as k,rm as E,stat as Ke,writeFile as Re}from"node:fs/promises";import g from"node:path";var M=1,We=15e3;function Oe(e={}){let t=g.resolve(e.home??e.rootPath??ne()),o=g.resolve(e.rootPath??g.join(t,"library","extensions")),n=z(t).database,s=Se({fetch:e.fetch,githubToken:e.githubToken}),i=e.now??(()=>new Date);async function d(){try{let m=await O(t),p=await Promise.all(m.extensions.map(S=>V(o,S)));return Ze(p,await C(e.reservedSkillNames)),{rootPath:o,registryPath:n,extensions:p.sort(Q),error:null}}catch(m){return{rootPath:o,registryPath:n,extensions:[],error:m instanceof Error?m.message:String(m)}}}r(d,"list");async function a(m){let p=await s.resolve(m),S=await O(t),c=S.extensions.find(l=>l.id===p.preview.id)??null;return U(p.preview,S.extensions.filter(l=>l.id!==c?.id),await C(e.reservedSkillNames)),p.preview}r(a,"preview");async function b(m){let p=I(m.source);return Y(o,p.id,async()=>{let S=await O(t);if(S.extensions.some(h=>h.id===p.id))throw new u(`${p.owner}/${p.repo} is already installed.`,{code:"extension_already_installed",status:409});let c=await s.resolve(m);Ie(c.preview),U(c.preview,S.extensions,await C(e.reservedSkillNames));let l=i().toISOString(),R=await fe({rootPath:o,resolution:c,installedAt:l,updatedAt:l,github:s});try{let h=await C(e.reservedSkillNames);return await X(t,i,P=>({...P,extensions:Xe(P,R,h)})),await Pe(o,R.id),R}catch(h){throw await ye(o,R.id),h}})}r(b,"add");async function f(m){let p=I(m.source);return Y(o,p.id,async()=>{let S=await O(t),c=L(S,p.id),l=await s.resolve({source:c.repositoryUrl,ref:m.ref?.trim()||c.requestedRef});if(Ie(l.preview),U(l.preview,S.extensions.filter(h=>h.id!==c.id),await C(e.reservedSkillNames)),c.resolvedCommit===l.preview.resolvedCommit&&c.packageHash===l.preview.packageHash&&c.requestedRef===l.preview.requestedRef)return V(o,c);let R=await fe({rootPath:o,resolution:l,installedAt:c.installedAt,updatedAt:i().toISOString(),github:s});try{let h=await C(e.reservedSkillNames);return await X(t,i,P=>({...P,extensions:Ye(P,R,h)})),await Pe(o,R.id),R}catch(h){throw await ye(o,R.id),h}})}r(f,"update");async function y(){let m=await d();if(m.error)throw new u(m.error,{code:"extension_registry_error"});let p={updated:[],unchanged:[],failed:[]};for(let S of m.extensions)try{let c=await f({source:S.repositoryUrl,ref:S.requestedRef});c.resolvedCommit===S.resolvedCommit&&c.packageHash===S.packageHash?p.unchanged.push(c):p.updated.push(c)}catch(c){p.failed.push({id:S.id,error:c instanceof Error?c.message:String(c)})}return p}r(y,"updateAll");async function w(m){let p=I(m),S=await O(t);return V(o,L(S,p.id))}r(w,"inspect");async function x(m){let p=I(m);return Y(o,p.id,async()=>{let S=await O(t),c=L(S,p.id),l=q(o,p.owner,p.repo),R=`${l}.${we()}.remove`;v(l)&&await k(l,R);try{return await X(t,i,h=>({...h,extensions:h.extensions.filter(P=>P.id!==c.id)})),await E(R,{recursive:!0,force:!0}),c}catch(h){throw v(R)&&!v(l)&&await k(R,l),h}})}r(x,"remove");async function A(m){let p=m.trim();if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(p))throw new u("Extension skill name must be lowercase kebab-case.",{code:"extension_skill_invalid_name"});let S=await d();if(S.error)throw new u(S.error,{code:"extension_registry_error"});let c=S.extensions.flatMap(te=>te.skills.filter(F=>F.name===p).map(F=>({extension:te,skill:F})));if(c.length===0)throw new u(`Extension skill not found: ${p}`,{code:"extension_skill_not_found",status:404});if(c.length>1)throw new u(`Extension skill name is ambiguous: ${p}`,{code:"extension_skill_conflict",status:409});let l=c[0];if(l.extension.validationStatus!=="valid"||l.skill.validationStatus!=="valid")throw new u(`Extension skill ${p} is not valid.`,{code:"extension_skill_invalid"});let R=$e(l.extension.sourcePath,l.skill.relativePath),h=await Je(R,"utf8"),P=He("sha256").update(h).digest("hex");if(P!==l.skill.sourceHash)throw new u(`Extension skill ${p} changed on disk. Update or reinstall its extension before using it.`,{code:"extension_skill_modified"});let $=T(h);if($.messages.length>0||$.name!==p||!$.description)throw new u(`Extension skill ${p} is not valid. ${$.messages.join(" ")}`.trim(),{code:"extension_skill_invalid"});return{name:p,description:$.description,body:$.body,path:l.skill.relativePath,sourcePath:l.extension.sourcePath,sourceHash:P,charCount:h.length,packagePath:g.dirname(R),resourceFiles:l.skill.resourceFiles}}return r(A,"readSkill"),{rootPath:o,registryPath:n,list:d,preview:a,add:b,update:f,updateAll:y,inspect:w,remove:x,readSkill:A}}r(Oe,"createGithubExtensionManager");async function fe(e){let t=e.resolution.preview,o=q(e.rootPath,t.owner,t.repo),n=`${o}.${we()}.install`,s=Z(e.rootPath,t.id),i=g.join(n,"current");await E(n,{recursive:!0,force:!0}),await E(s,{recursive:!0,force:!0}),await W(i,{recursive:!0,mode:448});try{await e.github.download(e.resolution,async(a,b,f)=>{let y=$e(i,a);await W(g.dirname(y),{recursive:!0,mode:448}),await Re(y,b,{mode:f?448:384})});let d=Ve(t,o,e.installedAt,e.updatedAt);return await Re(g.join(n,"extension.json"),`${JSON.stringify(d,null,2)}
4
4
  `,{mode:384}),await W(g.dirname(o),{recursive:!0,mode:448}),v(o)&&await k(o,s),await k(n,o),d}catch(d){throw await E(n,{recursive:!0,force:!0}),v(s)&&!v(o)&&await k(s,o),d}}r(fe,"materializeExtension");function Ve(e,t,o,n){let s=g.join(t,"current");return{...e,sourcePath:s,readmePath:e.readmePath?g.join(s,e.readmePath):null,installedAt:o,updatedAt:n,skills:e.skills.map(i=>({...i,sourcePath:g.join(s,i.relativePath)}))}}r(Ve,"installedExtension");async function Pe(e,t){await E(Z(e,t),{recursive:!0,force:!0})}r(Pe,"finalizeMaterialization");async function ye(e,t){let o=I(t.replace(/^github:/,"")),n=q(e,o.owner,o.repo),s=Z(e,t);await E(n,{recursive:!0,force:!0}),v(s)&&await k(s,n)}r(ye,"rollbackMaterialization");async function V(e,t){let o=q(e,t.owner,t.repo),n=g.join(o,"current"),s=(await Ke(g.join(o,"extension.json")).catch(()=>null))?.isFile()??!1,i=t.validationMessages.filter(d=>d!=="Installed files are missing.");return s||i.push("Installed files are missing."),{...t,sourcePath:n,readmePath:t.readmePath?g.join(n,g.basename(t.readmePath)):null,skills:t.skills.map(d=>({...d,sourcePath:g.join(n,d.relativePath)})),validationStatus:i.length===0?"valid":"error",validationMessages:i}}r(V,"hydrateExtension");function Ie(e){if(e.validationStatus!=="valid")throw new u(`Extension contains invalid skills: ${e.validationMessages.join(" ")}`,{code:"extension_invalid"})}r(Ie,"assertInstallable");function U(e,t,o){let n=new Map;for(let i of o)n.set(i,"a shipped OpenPond skill");for(let i of t)for(let d of i.skills)n.set(d.name,i.id);let s=e.skills.map(i=>({name:i.name,owner:n.get(i.name)})).filter(i=>!!i.owner);if(s.length!==0)throw new u(`Skill name conflict: ${s.map(i=>`${i.name} (${i.owner})`).join(", ")}.`,{code:"extension_skill_conflict",status:409})}r(U,"assertSkillNamesAvailable");function Xe(e,t,o){if(e.extensions.some(n=>n.id===t.id))throw new u(`${t.owner}/${t.repo} is already installed.`,{code:"extension_already_installed",status:409});return U(t,e.extensions,o),[...e.extensions,t].sort(Q)}r(Xe,"appendInstalledExtension");function Ye(e,t,o){return L(e,t.id),U(t,e.extensions.filter(n=>n.id!==t.id),o),e.extensions.map(n=>n.id===t.id?t:n).sort(Q)}r(Ye,"replaceInstalledExtension");function Ze(e,t){let o=new Map;for(let n of t)o.set(n,"built-in");for(let n of e)for(let s of n.skills){let i=o.get(s.name);if(!i){o.set(s.name,n.id);continue}let d=`Skill name conflicts with ${i}: ${s.name}`;s.validationStatus="error",s.validationMessages=[...new Set([...s.validationMessages,d])],n.validationStatus="error",n.validationMessages=[...new Set([...n.validationMessages,d])]}}r(Ze,"markInstalledSkillConflicts");async function C(e){let t=typeof e=="function"?await e():e??[];return[...new Set(t.map(o=>o.trim()).filter(Boolean))]}r(C,"reservedSkillNames");function L(e,t){let o=e.extensions.find(n=>n.id===t);if(o)return o;throw new u(`${t.replace(/^github:/,"")} is not installed.`,{code:"extension_not_installed",status:404})}r(L,"requireInstalled");async function O(e){let t=B(e,"extension_installations","registry")?.value;if(!t)return et();if(t.schemaVersion!==M||!Array.isArray(t.extensions)||!t.extensions.every(ve))throw new Error("Extension registry has an unsupported format.");return Qe(t)}r(O,"readRegistry");async function X(e,t,o){await N(g.join(z(e).runtime,"extension-registry"),async()=>{let n=B(e,"extension_installations","registry"),s=o(await O(e));oe(e,"extension_installations","registry",{...s,schemaVersion:M,updatedAt:t().toISOString()},n?.revision??null)})}r(X,"writeRegistry");function Qe(e){return{schemaVersion:M,updatedAt:typeof e?.updatedAt=="string"?e.updatedAt:null,extensions:Array.isArray(e?.extensions)?e.extensions.filter(ve):[]}}r(Qe,"normalizeRegistry");function et(){return{schemaVersion:M,updatedAt:null,extensions:[]}}r(et,"emptyRegistry");function ve(e){if(!e||typeof e!="object")return!1;let t=e;return t.source==="github"&&typeof t.id=="string"&&typeof t.owner=="string"&&typeof t.repo=="string"&&typeof t.repositoryUrl=="string"&&typeof t.requestedRef=="string"&&typeof t.resolvedCommit=="string"&&Array.isArray(t.skills)}r(ve,"isStoredExtension");function $e(e,t){if(g.isAbsolute(t)||t.split(/[\\/]/).includes(".."))throw new u(`Unsafe extension path: ${t}`,{code:"extension_unsafe_path"});let o=g.resolve(e,...t.split("/")),n=`${g.resolve(e)}${g.sep}`;if(!o.startsWith(n))throw new u(`Unsafe extension path: ${t}`,{code:"extension_unsafe_path"});return o}r($e,"safeDestination");function q(e,t,o){return g.join(e,"github",t,o)}r(q,"extensionDirectory");function Z(e,t){let o=I(t.replace(/^github:/,""));return`${q(e,o.owner,o.repo)}.previous`}r(Z,"backupDirectory");async function Y(e,t,o){let n=t.replace(/[^a-z0-9.-]+/gi,"-");return N(g.join(e,".locks",n),o,We)}r(Y,"withExtensionLock");function Q(e,t){return e.id.localeCompare(t.id)}r(Q,"extensionSort");async function Ln(e,t,o=Oe({reservedSkillNames:r(async()=>{let n=await D();return[...se,...n.skills.map(s=>s.name)]},"reservedSkillNames")})){let n=t[0]?.toLowerCase()||"list",s=G(e.json);if(n==="list"){let i=await o.list();if(i.error)throw new Error(i.error);tt(i.extensions,s);return}if(n==="add"||n==="preview"){let d={source:_(t[1],n),ref:Ce(e.ref)},a=n==="preview"?await o.preview(d):await o.add(d);ee(a,s,n==="preview"?"Preview":"Installed");return}if(n==="inspect"){ee(await o.inspect(_(t[1],n)),s,"Installed");return}if(n==="update"){if(G(e.all)){let a=await o.updateAll();if(s)console.log(JSON.stringify(a,null,2));else{console.log(`Updated ${a.updated.length}; unchanged ${a.unchanged.length}; failed ${a.failed.length}.`);for(let b of a.failed)console.log(`- ${b.id}: ${b.error}`)}a.failed.length>0&&(process.exitCode=1);return}let i=_(t[1],n),d=await o.update({source:i,ref:Ce(e.ref)});ee(d,s,"Updated");return}if(n==="remove"){let i=await o.remove(_(t[1],n));console.log(s?JSON.stringify({removed:i},null,2):`Removed ${i.owner}/${i.repo} and ${i.skills.length} skill(s).`);return}throw new Error("usage: openpond extension <add|preview|list|inspect|update|remove> [owner/repo] [--ref <ref>] [--all] [--json]")}r(Ln,"runOpenPondExtensionCommand");function ee(e,t,o){if(t){console.log(JSON.stringify(e,null,2));return}console.log(`${o} ${e.owner}/${e.repo}@${e.resolvedCommit.slice(0,12)} (${e.requestedRef}).`);for(let n of e.skills){let s=n.resourceFiles.length>0?`, ${n.resourceFiles.length} resource(s)`:"";console.log(`- ${n.name}${s}: ${n.description}`)}}r(ee,"printExtension");function tt(e,t){if(t){console.log(JSON.stringify({extensions:e},null,2));return}if(e.length===0){console.log("No third-party extensions installed.");return}console.log(`Third-party extensions (${e.length}):`);for(let o of e)console.log(`- ${o.owner}/${o.repo}@${o.resolvedCommit.slice(0,12)} \xB7 ${o.skills.length} skill(s) \xB7 ${o.validationStatus}`)}r(tt,"printExtensionList");function _(e,t){let o=e?.trim();if(o)return o;throw new Error(`usage: openpond extension ${t} <owner/repo>`)}r(_,"requiredSource");function Ce(e){return typeof e=="string"&&e.trim()?e.trim():void 0}r(Ce,"optionText");export{Ln as runOpenPondExtensionCommand};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{d as r,f as i,k as p}from"./chunk-TYWBEJOA.js";import"./chunk-3M53YXEI.js";import{a as t}from"./chunk-FTQLQJQV.js";function d(){console.log(m())}t(d,"printHelp");function m(){let n=["OpenPond CLI","","Usage:"," openpond [--no-open] [--hostname HOST] [--port PORT]"," openpond <command> [options] [-- passthrough...]"," openpond --version","","Commands:"];for(let o of i()){let s=o.aliases?.length?` (aliases: ${o.aliases.join(", ")})`:"";n.push(` ${o.usage}${s}`);for(let e of o.usages??[])n.push(` ${e}`)}n.push("","Global options:");for(let[o,s]of Object.entries(r).sort(([e],[a])=>e.localeCompare(a))){let e=o.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`);n.push(s==="boolean"?` --${e}`:` --${e} <${s}>`)}return n.push("","Run `openpond <command> --help` for the selected command schema.","Arguments after `--` are passed through without option parsing."),n.join(`
2
+ import{d as r,f as i,k as p}from"./chunk-Q4H3NUVW.js";import"./chunk-3M53YXEI.js";import{a as t}from"./chunk-FTQLQJQV.js";function d(){console.log(m())}t(d,"printHelp");function m(){let n=["OpenPond CLI","","Usage:"," openpond [--no-open] [--hostname HOST] [--port PORT]"," openpond <command> [options] [-- passthrough...]"," openpond --version","","Commands:"];for(let o of i()){let s=o.aliases?.length?` (aliases: ${o.aliases.join(", ")})`:"";n.push(` ${o.usage}${s}`);for(let e of o.usages??[])n.push(` ${e}`)}n.push("","Global options:");for(let[o,s]of Object.entries(r).sort(([e],[a])=>e.localeCompare(a))){let e=o.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`);n.push(s==="boolean"?` --${e}`:` --${e} <${s}>`)}return n.push("","Run `openpond <command> --help` for the selected command schema.","Arguments after `--` are passed through without option parsing."),n.join(`
3
3
  `)}t(m,"formatCliHelp");function l(){return["# OpenPond CLI command reference","","<!-- Generated by `pnpm --dir apps/cli docs:commands`; do not edit by hand. -->","","Parsing, aliases, command help, and this reference use the same authoritative registry.","",...i().map(o=>`## ${o.name}
4
4
 
5
5
  \`\`\`text
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as Ie,b as ye,c as Re,d as He,e as Ee,f as Pe,h as B,i as Ae,j as je}from"./chunk-D6E7JBBQ.js";import{e as Ce,f as U}from"./chunk-M7PBDRKC.js";import{X as be,Xa as Se,Y as ke,hb as xe,jb as Te,n as we,o as ve,ob as G,pb as De,qb as ze}from"./chunk-FOEUDMME.js";import"./chunk-BKMGBIBT.js";import"./chunk-33AO3P6X.js";import{b as ge}from"./chunk-4VKNBADF.js";import{a as z}from"./chunk-BUFQKDAW.js";import"./chunk-HO5L2FUU.js";import{h as me,ka as fe,oa as D,pa as he}from"./chunk-JBHAU7PH.js";import"./chunk-F2AG46CV.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-LL4QP2IM.js";import"./chunk-PGKEDR3S.js";import{M as W}from"./chunk-ZJY2L43W.js";import"./chunk-L3KS6MOV.js";import"./chunk-YSYXIJ46.js";import{Da as de,Ea as ce,M as C,N as $,a as se,lc as pe}from"./chunk-6JBWHR6T.js";import{aa as le,ga as V,ia as ue}from"./chunk-HK3WGUKK.js";import"./chunk-6MI4KKWF.js";import{Ca as ie,za as ae}from"./chunk-5ZZM3TUN.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import{B as re,C as oe,E as ne}from"./chunk-JO7GRBOG.js";import{Ma as M}from"./chunk-BQNK2NMB.js";import{K as Y,O as ee,ra as te}from"./chunk-VW7D3DRM.js";import"./chunk-UWO34HP6.js";import"./chunk-L4BYPZ4U.js";import{k as J,l as R,q as X}from"./chunk-P653BXMY.js";import{b as e}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as i}from"./chunk-FTQLQJQV.js";import{promises as $e}from"node:fs";import Ue from"node:path";import Le from"node:http";var Q=e.object({socketPath:e.string().min(1).max(1e3),capability:e.string().regex(/^[a-f0-9]{64}$/),jobId:e.string().min(1),pinHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),Ne=e.object({jobId:e.string().min(1),pinHash:e.string().regex(/^[a-f0-9]{64}$/),requestId:e.string().min(1).max(500),model:X,reasoningEffort:e.enum(["off","low","medium","high","xhigh","max","none"]).nullable(),messages:e.array(e.unknown()).min(1).max(1e3),tools:e.array(e.unknown()).max(100),toolChoice:e.unknown(),maxOutputTokens:e.number().int().positive().max(131072),temperature:e.number().finite().optional(),topP:e.number().finite().optional(),seed:e.number().int().optional()}).strict(),Je=e.discriminatedUnion("kind",[e.object({kind:e.literal("chat_completions_reasoning"),reasoningContent:e.string()}).strict(),e.object({kind:e.literal("responses_reasoning_items"),items:e.array(e.record(e.string(),e.unknown()))}).strict()]),Ve=e.object({id:e.string().optional(),type:e.string(),function:e.object({name:e.string().optional(),arguments:e.string().optional()}).passthrough().optional()}).passthrough(),Ge=e.object({text:e.string().optional(),usage:e.unknown().optional(),costUsd:e.number().finite().nonnegative().optional(),continuation:Je.optional(),toolCalls:e.array(Ve).optional()}).strict();function qe(s,r){let t=Q.parse(s);async function n(u,v,I=r){I.throwIfAborted();let x=Buffer.from(JSON.stringify({action:u,jobId:t.jobId,pinHash:t.pinHash,value:v}));if(x.length>8*1024*1024)throw new Error("Hosted advanced request exceeds its private byte limit.");return new Promise((y,h)=>{let l=Le.request({socketPath:t.socketPath,path:"/",method:"POST",headers:{authorization:`Bearer ${t.capability}`,"content-type":"application/json","content-length":x.length},signal:I},H=>{let E=[],P=0;H.on("data",w=>{if(P+=w.length,P>8388608){H.destroy(new Error("Hosted advanced response exceeds its private byte limit."));return}E.push(w)}),H.on("error",h),H.on("end",()=>{try{let w=JSON.parse(Buffer.concat(E).toString("utf8"));if(H.statusCode!==200)throw new Error(typeof w?.error=="string"?w.error:"The actual hosted advanced owner refused this operation.");y(w)}catch(w){h(w)}})});l.on("error",h),l.end(x)})}i(n,"call");let d=i(async function*(u){let v=Ne.parse({jobId:t.jobId,pinHash:t.pinHash,requestId:u.requestId,model:u.model,reasoningEffort:u.reasoningEffort,messages:u.messages,tools:u.tools,toolChoice:u.toolChoice,maxOutputTokens:u.maxOutputTokens??4096,...u.temperature===void 0?{}:{temperature:u.temperature},...u.topP===void 0?{}:{topP:u.topP},...u.seed===void 0?{}:{seed:u.seed}}),I=e.object({deltas:e.array(Ge).max(1e5)}).strict().parse(await n("model",v,AbortSignal.any([r,u.signal])));for(let x of I.deltas)yield x},"stream");return{stream:d,text:i(async u=>{let v="";for await(let I of d({...u,reasoningEffort:u.reasoningEffort??null,tools:[],toolChoice:"none"}))I.text&&(v+=I.text),I.usage!==void 0&&u.onUsage?.(I.usage,I.costUsd);return v},"text"),authorize:i(async()=>{await n("authorize",{})},"authorize"),ceiling:i(async(u,v,I)=>e.object({configurationHash:e.string().regex(/^[a-f0-9]{64}$/),maximumChargeUsd:e.number().finite().positive()}).strict().parse(await n("ceiling",{modelId:u,pricing:v,maximumOutputTokens:I})),"ceiling"),compute:i((u,v=!1)=>n("compute",u,v?AbortSignal.timeout(6e4):r),"compute"),checkpoint:i(u=>n("checkpoint",u),"checkpoint")}}i(qe,"createHostedAdvancedModelBridge");import Qe from"node:path";var Me=e.string().regex(/^[a-f0-9]{64}$/),Ke=e.object({taskId:e.string().min(1),caseHash:Me,session:C,turn:$,events:e.array(se).max(1e4),traceHash:Me,output:e.string().nullable()}).strict(),K=e.object({packageValue:ae,contexts:e.array(Ke).max(1e4)}).strict();async function _e(s){let r=V(s.pin),t=K.parse(s.privateSource),n=ie(t.packageValue),d=M(e.object({manifest:e.unknown(),result:e.unknown()}).parse(s.evidence));async function m(){if(await s.authorize(),r.actorId!==s.actor.actorId||r.teamId!==s.actor.teamId||r.profileRef.source!=="openpond_git"||r.profileRef.repositoryId!==s.source.repositoryId||r.profileRef.profileId!==s.source.profileId||r.sourceRevision!==s.source.sourceRevision)throw new Error("The actual hosted advanced source owner changed.")}if(i(m,"authorize"),await m(),d.manifest.teamId!==r.teamId||d.result.status!=="completed"||d.manifest.id!==r.evidence.id||d.result.contentHash!==r.evidence.contentHash||R(d.manifest.dataset)!==R(r.externalDatasetBinding.dataset))throw new Error("The exact completed hosted advanced evidence changed.");if(n.contentHash!==r.externalDatasetBinding.packageHash||n.contentHash!==r.adaptationDatasetBinding.packageHash||n.environment.contentHash!==r.environmentPolicy.environmentHash||n.environment.contract.networkPolicy!=="none")throw new Error("The hosted advanced environment/package is not the exact reviewed closed-network release.");if(n.taskset.tools.some(l=>l.name==="web_search"||l.name==="web_fetch"))throw new Error("Live external tools require their own qualified frozen-observation and budget owner.");if(n.verifierSet.graders.some(l=>l.kind==="human"||l.kind==="model_judge"&&l.calibrationStatus!=="passed"))throw new Error("Advanced hosted evaluation needs executable, qualified independent graders.");let u=r.adaptationTaskIds.map(l=>n.taskset.tasks.find(H=>H.id===l)),v=r.holdoutTaskIds.map(l=>n.taskset.tasks.find(H=>H.id===l)),I=new Set(u.map(l=>l?.clusterKey));if(u.some(l=>!l||l.split!==r.adaptationSplit)||v.some(l=>!l||l.split!==r.holdoutSplit||I.has(l.clusterKey)))throw new Error("Hosted adaptation/holdout membership or independent families changed.");let x=await s.store.getHarnessReleaseRecord(r.baselineRelease.contentHash);if(!x||x.harnessRelease.id!==r.baselineRelease.id||s.workspace.currentChannel.release?.contentHash!==r.baselineRelease.contentHash)throw new Error("The exact hosted source baseline is unavailable.");let y=await D({workspaceId:typeof x.agentSnapshot.metadata.workspaceId=="string"?x.agentSnapshot.metadata.workspaceId:x.workspaceId,sourceDir:Qe.join(x.bundlePath,"source")});if(z(y).protectedClosureHash!==r.privateClosureHash)throw new Error("The protected hosted Profile closure changed.");let h={packageValue:n,authorize:m};return{read:i(async l=>{if(V(l).contentHash!==r.contentHash)throw new Error("The actual hosted advanced admission changed.");return await m(),h},"read"),evidence:i(async()=>(await m(),d),"evidence"),authorize:i(async()=>m(),"authorize"),reviewContext:i(async(l,H)=>{await m();let E=t.contexts.filter(p=>p.taskId===H),P=d.result.cases.find(p=>p.identity.caseId===H);if(E.length!==1||!P||P.status!=="completed")throw new Error("The actual retained hosted review case is unavailable.");let w=E[0];if(w.caseHash!==R(P)||w.session.cloudTeamId!==r.teamId||w.turn.sessionId!==w.session.id||w.turn.status==="in_progress"||w.events.some(p=>p.sessionId!==w.session.id||p.turnId!==w.turn.id))throw new Error("The actual hosted review session/turn/trace binding changed.");return await m(),{...w,case:{output:w.output}}},"reviewContext")}}i(_e,"createHostedAdvancedRefinerSource");import{randomUUID as Ze}from"node:crypto";function Oe(s){async function r(n){let d=await s.store.getSession(n);if(!d||d.cloudTeamId!==s.teamId||d.metadata?.hostedAdvancedTurnId!==s.hostedTurnId||d.metadata?.parentModelRunId!==s.modelRunId)throw new Error("The actual hosted advanced case owner changed.");return d}i(r,"read");async function t(n,d,m){let u=await r(n),v=e.object({action:e.string()}).passthrough().parse(d).action;return ce.parse(await s.bridge.compute({session:u,payload:d,turnId:m??null},v==="sandbox_stop"||v==="sandbox_receipts"))}return i(t,"tool"),{createSession:i(async n=>{await s.bridge.authorize();let d=C.partial().parse(n),m=new Date().toISOString();if(d.metadata?.parentModelRunId!==s.modelRunId)throw new Error("The foreground case belongs to another actual advanced Run.");let u=C.parse({...d,id:`hosted-advanced-case-${Ze()}`,provider:"openpond",currentProfile:s.profileRef,cloudTeamId:s.teamId,cwd:null,codexThreadId:null,appId:null,appName:null,createdAt:m,updatedAt:m,status:"active",pinned:!1,archived:!1,order:0,hiddenFromDefaultSidebar:!0,title:d.title??"Advanced hosted evaluation case",metadata:{...d.metadata,source:"hosted-advanced-evaluation",hostedAdvancedTurnId:s.hostedTurnId,actorId:s.actorId,workspaceTarget:"hosted",benchmarkRuntime:"hosted_managed_work"}});return await s.store.insertSessionAtFront(u),await s.bridge.authorize(),u},"createSession"),getSession:r,runtimeEventsForSession:i(n=>s.store.runtimeEventsForSession(n),"runtimeEventsForSession"),executeWorkspaceTool:i((n,d,m)=>t(n,d,m?.turnId),"executeWorkspaceTool"),settleCostEvidence:i((n,d)=>t(n,{action:"sandbox_receipts",args:{}},d?.turnId),"settleCostEvidence")}}i(Oe,"createHostedAdvancedWorkRuntime");var Xe=e.string().regex(/^[a-f0-9]{64}$/),Be=e.object({version:e.string().min(1),source:e.string().min(1),effectiveAt:e.string().min(1),inputUsdPerMillionTokens:e.number().finite().nonnegative(),cachedInputUsdPerMillionTokens:e.number().finite().nonnegative(),outputUsdPerMillionTokens:e.number().finite().nonnegative()}).strict(),Z=e.object({operation:e.enum(["prepare_run","start","read","resume","cancel"]),request:ue,configuration:e.object({id:e.string().min(1),profileId:e.string().min(1),etag:Xe}).strict(),refinerRelease:Y,privateSource:K,upstream:e.object({modelId:e.string().min(1),revision:e.string().min(1),pricing:Be}).strict(),judgeModels:e.array(e.object({modelId:e.string().min(1),revision:e.string().min(1),pricing:Be}).strict()).max(50),bridge:Q.optional(),hostedTurnId:e.string().min(1).optional()}).strict();async function Fe(s){let r=Z.parse(s.request),t=r.request.pin;if(r.request.model.providerId!=="openpond"||r.request.model.modelId!==r.upstream.modelId||r.configuration.id!==r.request.modelId||r.configuration.profileId!==t.profileRef.profileId||r.request.profileId!==t.profileRef.profileId||r.refinerRelease.id!==t.refinerRelease.id||r.refinerRelease.contentHash!==t.refinerRelease.contentHash)throw new Error("The actual hosted advanced configuration/model/Refiner admission changed.");let n=`advanced-refiner-${R([t.actorId,t.teamId,t.operationId,t.contentHash,r.request.model,[r.request.seed],1]).slice(0,40)}`;if((r.operation==="start"||r.operation==="resume")&&(!r.bridge||!r.hostedTurnId))throw new Error("The actual hosted advanced execution grant is unavailable.");let m=r.bridge?qe(r.bridge,s.signal):null;if(r.bridge&&(r.bridge.jobId!==n||r.bridge.pinHash!==t.contentHash))throw new Error("The hosted model bridge belongs to another actual Run.");let u=i(async()=>{s.signal.throwIfAborted(),await s.authorize(),m&&await m.authorize()},"authorize"),v=await _e({...s,pin:t,privateSource:r.privateSource,authorize:u}),I=we(ve(s.storeDir));await I.persistRelease(r.refinerRelease),await I.writeSource(ee(r.refinerRelease.profile)),I.binding()?.release.contentHash!==t.refinerRelease.contentHash&&await I.transition(r.refinerRelease,{operation:"activate",bindingChanged:!0,actor:s.actor.actorId,reason:"Pin the actual hosted evaluation fork to its admitted immutable Refiner release.",authoringSkillHash:null});let y=ke({storeDir:s.storeDir,authorize:i(async()=>u(),"authorize"),packageForPin:i(async()=>r.privateSource.packageValue,"packageForPin"),prepareModel:i(async(c,f,k)=>{if(!m)throw new Error("The actual hosted model ceiling owner is unavailable.");return m.ceiling(c,k,f)},"prepareModel")}),h=i(async function*(c){let f=be(),k=[r.upstream,...r.judgeModels].find(q=>q.modelId===c.model.modelId);if(!m||!f||!k)throw new Error("The actual hosted model and durable shared budget are unavailable.");let{signal:T,...j}=c,O=c.maxOutputTokens??4096,L=await f.call(c.requestId,j,k.pricing,O,async()=>{let q=[],F=null;for await(let N of m.stream({...c,signal:AbortSignal.any([T,f.signal])}))q.push(N),N.costUsd!==void 0&&(F=(F??0)+N.costUsd);return{value:q,costUsd:F}});for(let q of L)yield q},"stream"),l=i(async c=>{let f="";for await(let k of h({...c,reasoningEffort:c.reasoningEffort??null,tools:[],toolChoice:"none"}))k.text&&(f+=k.text),k.usage!==void 0&&c.onUsage?.(k.usage,k.costUsd);return f},"text"),H=Ie({store:s.store,storeDir:s.storeDir}),E=await H.projectSelected({profileId:t.profileRef.profileId,package:r.privateSource.packageValue,adaptationSplit:t.adaptationSplit,holdoutSplit:t.holdoutSplit}),P=i(async c=>{let f=C.partial().parse(c),k=new Date().toISOString(),T=C.parse({...f,id:`hosted-review-${R([n,f.metadata]).slice(0,40)}`,cloudTeamId:t.teamId,currentProfile:t.profileRef,appId:null,appName:null,cwd:null,codexThreadId:null,title:f.title??"Hosted Refiner review",provider:"openpond",createdAt:k,updatedAt:k,status:"active",pinned:!1,archived:!1,order:0,metadata:{...f.metadata,hostedAdvancedTurnId:r.hostedTurnId??null,actorId:t.actorId,source:"hosted-advanced-evaluation"}});return await s.store.insertSessionAtFront(T),T},"createSession"),w=m&&r.hostedTurnId?Oe({store:s.store,bridge:m,teamId:t.teamId,actorId:t.actorId,hostedTurnId:r.hostedTurnId,modelRunId:n,profileRef:t.profileRef}):void 0,p=Se({store:s.store,storeDir:s.storeDir,modelJudge:ye({store:s.store,modelText:l}),modelText:l,modelStream:h,workRuntime:w,resolveTasksetRelease:i(c=>H.releaseForTaskset(c),"resolveTasksetRelease")}),a={store:s.store,storeDir:s.storeDir,evaluation:p,benchmarkTasksets:H,loadProfileState:i(async()=>s.profile,"loadProfileState"),resolveEvaluationProject:i(async(c,f)=>{if(await u(),c!==r.configuration.id||f!==r.configuration.profileId)throw new Error("The actual hosted evaluation configuration changed.");return{id:c,profileId:f}},"resolveEvaluationProject"),resolveUpstreamModel:i(async()=>({providerId:"openpond",modelId:r.upstream.modelId,revision:r.upstream.revision,pricing:r.upstream.pricing}),"resolveUpstreamModel"),advancedBoundary:y,refinerStream:i(async function*(c){if(!c.requestId)throw new Error("A hosted Refiner call needs its actual retained ID.");yield*h({model:c.model,reasoningEffort:"low",messages:c.messages,tools:[],toolChoice:"none",requestId:c.requestId,maxOutputTokens:4096,signal:c.signal,hostedTokenPricing:c.pricing})},"refinerStream")},o=Re({...a,reviewQuality:He({source:v,boundary:y,benchmark:a,createSession:P})}),g={advancedEvaluation:t,selectedTaskset:{id:E.id,revision:E.revision,contentHash:E.contentHash},modelId:r.request.modelId,profileId:r.request.profileId,model:r.request.model,reasoningEffort:r.request.reasoningEffort,seeds:[r.request.seed],repetitions:1,maximumSpendUsd:t.maximumCostUsd},b,S=i(()=>{o.cancel(n)},"stop");s.signal.addEventListener("abort",S,{once:!0});try{if(r.operation==="prepare_run")return o.prepare(g);let c=await s.store.getModelRun(n);if(!c||c.evaluation?.benchmarkId!=="harness-refiner"||c.evaluation.advancedEvaluation?.contentHash!==t.contentHash)throw new Error("The original hosted advanced Run is unavailable.");if(r.operation==="read")return c;if(r.operation==="cancel")return o.cancel(n);if(m){let T=!1;b=setInterval(()=>{T||(T=!0,s.store.getModelRun(n).then(j=>j?m.checkpoint(j):void 0).catch(()=>S()).finally(()=>{T=!1}))},2e3)}r.operation==="start"?await o.start(g):await o.resume(n);let f=await o.wait(n);if(!f)throw new Error("The actual hosted advanced engine did not retain its Run.");let k=pe.parse(f);return m&&await m.checkpoint(k),k}finally{b&&clearInterval(b),s.signal.removeEventListener("abort",S),await o.close(),await y.close()}}i(Fe,"runHostedAdvancedRefinerOwner");import{promises as _}from"node:fs";import A from"node:path";var Ye=e.object({actor:e.object({actorId:e.string().min(1),teamId:e.string().min(1)}).strict(),storeDir:e.string().min(1),source:e.object({repoPath:e.string().min(1),repositoryId:e.string().min(1),profileId:e.string().min(1),sourceRevision:e.string().regex(/^[a-f0-9]{40,64}$/),filesHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),evidence:e.object({manifest:e.unknown(),result:e.unknown()}).strict(),operation:e.enum(["advanced","describe","command","queue","cancelQueued","bind","finish","beginTesting","cancelTesting","failTesting","comparison","beginAdoption","export","source","tool","toolCatalog"]),advanced:Z.optional(),command:le.optional(),candidateId:e.string().optional(),revision:e.number().int().positive().optional(),actualSession:C.optional(),actualTurn:$.optional(),recipe:e.unknown().optional(),baseline:e.object({manifest:e.unknown(),result:e.unknown()}).strict().optional(),candidate:e.object({manifest:e.unknown(),result:e.unknown()}).strict().optional(),humanProjection:oe.optional(),humanSelections:re.optional(),adoptionReadback:e.unknown().optional(),failure:e.object({message:e.string().max(2e3),cancelled:e.boolean()}).strict().optional(),tool:e.object({name:e.string(),args:e.record(e.string(),e.unknown()),callId:e.string()}).strict().optional(),agentRuntime:e.object({source:e.string(),cliRelativePath:e.string()}).strict().optional(),queued:e.object({sessionId:e.string(),turnId:e.string(),createdAt:e.string().datetime()}).strict().optional()}).strict();async function We(s,r=new AbortController().signal){r.throwIfAborted();let t=Ye.parse(s),{actor:n,source:d}=t;if(!A.isAbsolute(t.storeDir)||!A.isAbsolute(d.repoPath))throw new Error("Hosted candidate owner requires contained absolute private paths.");let m=M(t.evidence),u=[t.baseline,t.candidate].filter(l=>l!==void 0).map(l=>M(l));if(m.manifest.teamId!==n.teamId)throw new Error("Hosted candidate evidence belongs to another team.");if(await B(d.repoPath)!==d.filesHash)throw new Error("The admitted hosted Profile source bytes changed.");let v=`hosted-improve-source-${R([n,d.repositoryId,d.profileId,d.sourceRevision]).slice(0,40)}`,I=A.join(t.storeDir,"library","profile-experiment-origins",v);if(await _.mkdir(A.dirname(I),{recursive:!0,mode:448}),await _.stat(I).catch(()=>null)||await _.cp(d.repoPath,I,{recursive:!0,errorOnExist:!0,force:!1}),await B(I)!==d.filesHash)throw new Error("The private accepted Profile cache changed.");let x=await W(I,d.profileId);if(x.error||!x.sourcePath)throw new Error("The accepted hosted Profile does not compile.");let y=new xe(t.storeDir),h;try{let l=await y.getHarnessWorkspace(v);l||(l=(await fe({store:y,storeDir:t.storeDir,id:v,ownerId:n.actorId,name:d.profileId,profile:x,sourceRevision:d.sourceRevision,repositoryId:d.repositoryId,selectionEligible:!1,originMetadata:{profileExperimentOrigin:{schemaVersion:"openpond.profileExperimentOrigin.v1",...n,sourceRevision:d.sourceRevision,sourcePath:I,sourceFilesHash:d.filesHash},hostedImprovementOwner:!0}})).workspace);let H={source:"openpond_git",repositoryId:d.repositoryId,profileId:d.profileId},E=i(async()=>{if(r.throwIfAborted(),await B(I)!==d.filesHash||await B(d.repoPath)!==d.filesHash)throw new Error("Accepted source changed during private candidate I/O.")},"authorizer");if(t.operation==="advanced"){if(!t.advanced)throw new Error("Missing actual hosted advanced owner command.");return Fe({store:y,storeDir:t.storeDir,actor:n,profile:x,workspace:l,source:d,evidence:m,request:t.advanced,authorize:E,signal:r})}let P=i(()=>{if(!t.adoptionReadback)throw new Error("Actual hosted Git owner has not returned its sealed adoption receipt.");return e.object({receipt:e.object({id:e.string(),contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),activeRelease:e.object({id:e.string(),contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),testedCandidateRelease:e.object({id:e.string(),contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),executableSourceHash:e.string().regex(/^[a-f0-9]{64}$/),protectedClosureHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict().parse(t.adoptionReadback)},"readback");h=Ee({store:y,storeDir:t.storeDir,projectHumanComparison:i(async()=>{if(await E(),!t.humanProjection)throw new Error("The current private Human comparison owner is unavailable.");return ne(t.humanProjection)},"projectHumanComparison"),authorizeOwner:i(async(a,o,g,b,S)=>{if(R(a)!==R(n)||R(g)!==R(H)||o.id!==v)throw new Error("Hosted candidate source owner changed.");if(S.requireCurrentBase&&(o.currentChannel.release?.contentHash!==l.currentChannel.release?.contentHash||d.sourceRevision!==o.metadata.profileExperimentOrigin.sourceRevision))throw new Error("Hosted candidate accepted revision changed.");await E()},"authorizeOwner"),loadEvidence:i(async(a,o)=>{if(R(a)!==R(n))throw new Error("Hosted candidate evidence actor changed.");let g=[m,...u].find(b=>b.manifest.id===o.id&&b.result.contentHash===o.contentHash&&b.manifest.teamId===n.teamId);if(!g)throw new Error("Hosted candidate exact retained evidence changed.");return await E(),g},"loadEvidence"),freezeProfile:i(async(a,o,g)=>{let b=await y.getHarnessReleaseRecord(o.baseRelease.contentHash);if(!b)throw new Error("Hosted source baseline is missing.");let S=await D({workspaceId:typeof b.agentSnapshot.metadata.workspaceId=="string"?b.agentSnapshot.metadata.workspaceId:b.workspaceId,sourceDir:A.join(b.bundlePath,"source")}),c=await D({workspaceId:typeof g.release.agentSnapshot.metadata.workspaceId=="string"?g.release.agentSnapshot.metadata.workspaceId:g.release.workspaceId,sourceDir:A.join(g.release.bundlePath,"source")});return Ae({store:y,storeDir:t.storeDir,state:o},async f=>{await Ce({...f,state:o,base:S,candidate:c});let k=await W(f.root,o.profileRef.profileId),T=await U({storeDir:t.storeDir,state:o,profile:k,sourceRevision:g.profileSourceRevision,base:S}),j=z(T);if(j.protectedClosureHash!==z(S).protectedClosureHash)throw new Error("Hosted source candidate changed protected evaluation closure.");let O=A.join(t.storeDir,"library","profile-candidate-archives",o.id,j.contentHash);await _.mkdir(A.dirname(O),{recursive:!0,mode:448}),await _.stat(O).catch(()=>null)||await _.cp(f.root,O,{recursive:!0,errorOnExist:!0,force:!1});let L=await W(O,o.profileRef.profileId);if((await U({storeDir:t.storeDir,state:o,profile:L,sourceRevision:g.profileSourceRevision,base:S})).harnessRelease.contentHash!==T.harnessRelease.contentHash)throw new Error("Hosted frozen Profile archive readback differs.");let F=await he({storeDir:t.storeDir,workspaceId:g.release.workspaceId,compiled:T,createdAt:g.release.createdAt});return await E(),{...g,release:F,executableIdentity:j}})},"freezeProfile"),adopt:i(async()=>P(),"adopt"),readAdoption:i(async()=>t.adoptionReadback?P():null,"readAdoption"),rollback:i(async()=>P(),"rollback")});let w=Pe({store:y,improvements:h,actorId:i(async()=>n.actorId,"actorId"),teamId:i(async()=>n.teamId,"teamId"),loadProfile:i(async a=>{if(R(a)!==R(H))throw new Error("Candidate requested another source owner.");return x},"loadProfile"),agentRuntime:t.agentRuntime,operationSignal:r,loadAgentRuntime:De({storeDir:t.storeDir,loadArchive:ze({storeDir:t.storeDir})})});if(t.operation==="describe"){await E();let a=l.currentChannel.release,o=a?await y.getHarnessReleaseRecord(a.contentHash):null;if(!a||!o||o.workspaceId!==l.id||o.harnessRelease.id!==a.id||o.harnessRelease.contentHash!==a.contentHash||l.ownerScope.kind!=="personal"||l.ownerScope.id!==n.actorId)throw new Error("Hosted source release is unavailable to its admitted owner.");let g=await D({workspaceId:typeof o.agentSnapshot.metadata.workspaceId=="string"?o.agentSnapshot.metadata.workspaceId:v,sourceDir:A.join(o.bundlePath,"source")});if(g.harnessRelease.contentHash!==o.harnessRelease.contentHash)throw new Error("Hosted source compiler readback changed.");let b=await ge({runtime:{release:o},ref:H,sourceRevision:d.sourceRevision,harnessRelease:a}),S=i(c=>{let f=g.sourceFiles.find(k=>k.path===c)?.bytes;return f?JSON.parse(Buffer.from(f).toString("utf8")):null},"readJson");return await E(),{workspaceId:v,ownerRevision:l.revision,profileRef:H,baseRelease:l.currentChannel.release,profileSourceRevision:d.sourceRevision,manifest:g.manifest,executable:z(g),catalogHash:b.catalogHash,workflows:S("workflows/catalog.json"),actions:S("workflows/actions.json")}}if(t.operation==="command"){let a=t.command;if(!a)throw new Error("Missing canonical Improve command.");if(a.operation==="start")return h.start(n,a.request);if(a.operation==="list")return h.list(n,a.limit,a.cursor);if(!("id"in a))throw new Error("Discover exact hosted source choices through the authenticated host.");let o=await h.read(n,a.id);if(a.operation==="read")return o;if(a.operation==="instructions"){let g=await h.partition(n,o.id),b=await me(g.sourceRoot,o.component.path),S=await _.readFile(b);if(S.length>25e4)throw new Error("Instruction editor size limit exceeded.");let c=S.toString("utf8");if(o.component.kind==="workflow"){let f=JSON.parse(c).workflows?.find(k=>k.id===o.component.workflowId);if(f?.invocation?.kind!=="instructions")throw new Error("Use Work to author this executable Workflow.");c=f.invocation.instructions}return{candidateId:o.id,candidateRevision:o.revision,path:o.component.path,text:c,textHash:J(c),contentHash:J(S)}}if(a.operation==="humanComparisonOptions")throw new Error("Read the actual paired sources through their current hosted Experiment owner.");if(!("revision"in a)||o.revision!==a.revision)throw new Error("Candidate revision changed.");if(a.operation==="edit")return h.edit(n,o.id,o.revision,a.expectedFileHash,a.text);if(a.operation==="mode")return h.setMode(n,o.id,o.revision,a.mode);if(a.operation==="freeze")return h.freeze(n,o.id,o.revision);if(a.operation==="useCandidate")return h.useCandidate(n,o.id,o.revision);if(a.operation==="rollback")return h.rollback(n,o.id,o.revision);if(a.operation==="discard")return h.discard(n,o.id,o.revision);throw new Error("Hosted Work/test lifecycle requires the actual host turn/run admission.")}if(!t.candidateId)throw new Error("Missing actual hosted candidate ID.");let p=await h.read(n,t.candidateId);if(t.operation==="beginAdoption")return h.beginAdoption(n,p.id,t.revision);if(t.operation==="export")return je(y,p,"hosted_execution");if(t.operation==="source"){if(!p.frozen||p.status!=="frozen"&&p.status!=="testing"&&p.status!=="ready_for_review"&&p.status!=="adopting")throw new Error("Only the exact frozen source can enter hosted preparation.");let a=await y.getHarnessReleaseRecord(p.frozen.release.contentHash);if(!a||a.harnessRelease.id!==p.frozen.release.id)throw new Error("Frozen hosted source is unavailable.");let o=await D({workspaceId:typeof a.agentSnapshot.metadata.workspaceId=="string"?a.agentSnapshot.metadata.workspaceId:a.workspaceId,sourceDir:A.join(a.bundlePath,"source")}),g=z(o);if(o.harnessRelease.contentHash!==p.frozen.release.contentHash||g.contentHash!==p.frozen.executableSourceHash||g.protectedClosureHash!==p.frozen.protectedClosureHash)throw new Error("Frozen hosted executable changed.");let b=A.join(t.storeDir,"library","profile-candidate-archives",p.id,g.contentHash),S=await W(b,p.profileRef.profileId);if(S.error||!S.sourcePath)throw new Error("Frozen actual Profile archive is unavailable.");let c=await y.getHarnessReleaseRecord(p.baseRelease.contentHash);if(!c)throw new Error("Frozen baseline is unavailable.");let f=await D({workspaceId:typeof c.agentSnapshot.metadata.workspaceId=="string"?c.agentSnapshot.metadata.workspaceId:c.workspaceId,sourceDir:A.join(c.bundlePath,"source")}),k=await U({storeDir:t.storeDir,state:p,profile:S,sourceRevision:p.frozen.profileSourceRevision,base:f});if(k.harnessRelease.contentHash!==p.frozen.release.contentHash||z(k).contentHash!==g.contentHash)throw new Error("Actual frozen Profile archive differs from its compiled release.");return{state:p,profileSource:{repoPath:b,profileId:p.profileRef.profileId,sourceRevision:p.frozen.profileSourceRevision,repositoryId:p.profileRef.repositoryId,filesHash:await B(b)},sourcePackage:te({agentSnapshot:o.agentSnapshot,harnessRelease:o.harnessRelease,files:new Map(o.sourceFiles.map(T=>[T.path,T.bytes]))})}}if(t.operation==="comparison"){if(!t.baseline||!t.candidate)throw new Error("Missing actual hosted paired evidence.");return h.completeComparison(n,p.id,t.revision,M(t.baseline),M(t.candidate),t.humanSelections)}if(t.operation==="beginTesting")return h.beginTesting(n,p.id,t.revision,t.recipe);if(t.operation==="failTesting"){if(!t.failure)throw new Error("Missing actual hosted test failure.");return h.failTesting(n,p.id,t.revision,t.failure.message,t.failure.cancelled)}if(t.operation==="cancelTesting")return h.cancelTesting(n,p.id,t.revision);if(t.operation==="queue"){if(!t.queued)throw new Error("Missing actual hosted queue admission.");return h.queueAuthoringTurn(n,p.id,t.revision,t.queued.sessionId,t.queued.turnId,t.queued.createdAt)}if(t.operation==="cancelQueued")return h.cancelQueuedAuthoring(n,p.id,t.revision);if(t.operation==="bind"||t.operation==="finish"||t.operation==="tool"||t.operation==="toolCatalog"){if(!t.actualSession||!t.actualTurn||t.actualTurn.sessionId!==t.actualSession.id||t.actualSession.cloudTeamId!==n.teamId||R(t.actualSession.currentProfile)!==R(H))throw new Error("Actual hosted candidate Work binding changed.");let a=t.actualSession,o=t.actualTurn,g=await y.getSession(a.id);if(!g)await y.insertSessionAtFront(a);else if(R({...g,updatedAt:a.updatedAt,status:a.status})!==R(a))throw new Error("Retained hosted candidate session changed.");let b=await y.getTurn(o.id);if(!b)await y.insertTurn(o);else{if(b.sessionId!==o.sessionId||R(b.metadata.refinementCandidate)!==R(o.metadata.refinementCandidate)||b.prompt!==o.prompt)throw new Error("Actual hosted candidate turn identity changed.");await y.updateTurn(o.id,()=>o)}if(t.operation==="bind")return h.bindAuthoringTurn(n,p.id,t.revision,a.id,o.id);if(t.operation==="finish")return h.finishAuthoring(n,p.id,t.revision);if(t.operation==="toolCatalog")return await w.candidateAuthoringForTurn(a.id,o.id),[...G({loadProfileState:i(async()=>x,"loadProfileState"),resolveCandidateProfile:w.resolveCandidateProfile,executeCandidateAgentCommand:w.executeCandidateAgentCommand}),...Te(async()=>{throw new Error("Hosted file tools require a bound private call.")}),{name:"exec_command",description:"Run a bounded command confined to the selected public candidate component.",parameters:{type:"object",additionalProperties:!1,properties:{command:{type:"string",minLength:1,maxLength:2e4},cwd:{type:"string"}},required:["command"]}},{name:"view_image",description:"Inspect an image inside the candidate public source tree.",parameters:{type:"object",additionalProperties:!1,properties:{path:{type:"string"}},required:["path"]}}].map(({name:c,description:f,parameters:k})=>({name:c,description:f,parameters:k}));if(!t.tool)throw new Error("Missing candidate tool call.");await w.authorizeCandidateTool({sessionId:a.id,turnId:o.id,name:t.tool.name});let S={session:a,turnId:o.id,args:t.tool.args,callId:t.tool.callId,signal:r,workspaceDiffBaseline:null,turnPermissions:{approvalPolicy:"never",sandbox:"workspace-write",codexPermissionMode:"default"},provider:a.provider,model:o.modelRef?.modelId??a.modelRef?.modelId??"",mentionedApps:[],userPrompt:o.prompt,turnMetadata:o.metadata};if(t.tool.name==="get_profile"||t.tool.name.startsWith("agent_")||t.tool.name==="ask_user"){let c=G({loadProfileState:i(async()=>x,"loadProfileState"),resolveCandidateProfile:w.resolveCandidateProfile,executeCandidateAgentCommand:w.executeCandidateAgentCommand}).find(f=>f.name===t.tool.name);if(!c)throw new Error("Candidate authoring tool is unavailable.");return c.execute(S)}if(t.tool.name==="view_image")return w.executeCandidateImage(S);if(t.tool.name==="exec_command")return w.executeCandidateCommand(S,{session:a,turnId:o.id,command:e.string().min(1).max(2e4).parse(t.tool.args.command),cwd:typeof t.tool.args.cwd=="string"?t.tool.args.cwd:null,signal:S.signal,source:"model_tool"});if(["list_files","read_files","search_files","workspace_status","write_file","write_files","edit_file","delete_file"].includes(t.tool.name))return w.executeCandidateWorkspaceTool({session:a,turnId:o.id,request:de.parse({action:t.tool.name,args:t.tool.args,source:"chat_action"})});throw new Error("This hosted tool has no confined candidate transport.")}throw new Error("Unknown private hosted Improve operation.")}finally{await h?.close(),await y.close()}}i(We,"runHostedExperimentImprovementOwner");async function wr(s){if(s.length!==1||s[0].length>16e3||!/^[A-Za-z0-9_-]+$/.test(s[0]))throw new Error("Hosted Improve IPC argument is invalid.");let r=e.object({directory:e.string(),file:e.string().regex(/^[A-Za-z0-9_-]+\.json$/)}).strict().parse(JSON.parse(Buffer.from(s[0],"base64url").toString("utf8")));if(!Ue.isAbsolute(r.directory))throw new Error("Hosted Improve IPC requires an absolute private directory.");let t=Ue.join(r.directory,r.file),n=await $e.lstat(t);if(!n.isFile()||n.isSymbolicLink()||n.size>32*1024*1024)throw new Error("Hosted Improve private request exceeds its byte/type limit.");let d=new AbortController,m=i(()=>d.abort(new Error("The actual hosted owner stopped this private operation.")),"stop");process.once("SIGTERM",m),process.once("SIGINT",m);try{let u=await We(JSON.parse(await $e.readFile(t,"utf8")),d.signal),v=Buffer.from(JSON.stringify(u));if(v.length>32*1024*1024)throw new Error("Hosted Improve private response exceeds its byte limit.");process.stdout.write(`${v.toString("utf8")}
2
+ import{a as Ie,b as ye,c as Re,d as He,e as Ee,f as Pe,h as B,i as Ae,j as je}from"./chunk-TIUSKRBP.js";import{e as Ce,f as U}from"./chunk-IOQUF34U.js";import{V as be,Va as Se,W as ke,hb as xe,jb as Te,n as we,nb as G,o as ve,ob as De,pb as ze}from"./chunk-NHJ26KXF.js";import"./chunk-EMKZVP7Z.js";import"./chunk-DLZP22WV.js";import{k as ge}from"./chunk-VOIH2BQA.js";import{a as z}from"./chunk-T5LE6R5S.js";import"./chunk-QJRXTIOC.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import{h as me,ma as fe,qa as D,ra as he}from"./chunk-7MXZJQS7.js";import"./chunk-7YR6CBNU.js";import"./chunk-2ZJJFBIA.js";import"./chunk-5CMKGD43.js";import{M as W}from"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import{Da as de,Ea as ce,M as C,N as $,a as se,lc as pe}from"./chunk-XDMUD4FW.js";import{aa as le,ga as V,ia as ue}from"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import{Ca as ie,za as ae}from"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import{B as re,C as oe,E as ne}from"./chunk-WV2APYWG.js";import{Ma as M}from"./chunk-PJM2G7SG.js";import{L as Y,P as ee,sa as te}from"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import{l as J,m as R,r as X}from"./chunk-NNF6KCHD.js";import{b as e}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as i}from"./chunk-FTQLQJQV.js";import{promises as $e}from"node:fs";import Ue from"node:path";import Le from"node:http";var Q=e.object({socketPath:e.string().min(1).max(1e3),capability:e.string().regex(/^[a-f0-9]{64}$/),jobId:e.string().min(1),pinHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),Ne=e.object({jobId:e.string().min(1),pinHash:e.string().regex(/^[a-f0-9]{64}$/),requestId:e.string().min(1).max(500),model:X,reasoningEffort:e.enum(["off","low","medium","high","xhigh","max","none"]).nullable(),messages:e.array(e.unknown()).min(1).max(1e3),tools:e.array(e.unknown()).max(100),toolChoice:e.unknown(),maxOutputTokens:e.number().int().positive().max(131072),temperature:e.number().finite().optional(),topP:e.number().finite().optional(),seed:e.number().int().optional()}).strict(),Je=e.discriminatedUnion("kind",[e.object({kind:e.literal("chat_completions_reasoning"),reasoningContent:e.string()}).strict(),e.object({kind:e.literal("responses_reasoning_items"),items:e.array(e.record(e.string(),e.unknown()))}).strict()]),Ve=e.object({id:e.string().optional(),type:e.string(),function:e.object({name:e.string().optional(),arguments:e.string().optional()}).passthrough().optional()}).passthrough(),Ge=e.object({text:e.string().optional(),usage:e.unknown().optional(),costUsd:e.number().finite().nonnegative().optional(),continuation:Je.optional(),toolCalls:e.array(Ve).optional()}).strict();function qe(s,r){let t=Q.parse(s);async function n(u,v,I=r){I.throwIfAborted();let x=Buffer.from(JSON.stringify({action:u,jobId:t.jobId,pinHash:t.pinHash,value:v}));if(x.length>8*1024*1024)throw new Error("Hosted advanced request exceeds its private byte limit.");return new Promise((y,h)=>{let l=Le.request({socketPath:t.socketPath,path:"/",method:"POST",headers:{authorization:`Bearer ${t.capability}`,"content-type":"application/json","content-length":x.length},signal:I},H=>{let E=[],P=0;H.on("data",w=>{if(P+=w.length,P>8388608){H.destroy(new Error("Hosted advanced response exceeds its private byte limit."));return}E.push(w)}),H.on("error",h),H.on("end",()=>{try{let w=JSON.parse(Buffer.concat(E).toString("utf8"));if(H.statusCode!==200)throw new Error(typeof w?.error=="string"?w.error:"The actual hosted advanced owner refused this operation.");y(w)}catch(w){h(w)}})});l.on("error",h),l.end(x)})}i(n,"call");let d=i(async function*(u){let v=Ne.parse({jobId:t.jobId,pinHash:t.pinHash,requestId:u.requestId,model:u.model,reasoningEffort:u.reasoningEffort,messages:u.messages,tools:u.tools,toolChoice:u.toolChoice,maxOutputTokens:u.maxOutputTokens??4096,...u.temperature===void 0?{}:{temperature:u.temperature},...u.topP===void 0?{}:{topP:u.topP},...u.seed===void 0?{}:{seed:u.seed}}),I=e.object({deltas:e.array(Ge).max(1e5)}).strict().parse(await n("model",v,AbortSignal.any([r,u.signal])));for(let x of I.deltas)yield x},"stream");return{stream:d,text:i(async u=>{let v="";for await(let I of d({...u,reasoningEffort:u.reasoningEffort??null,tools:[],toolChoice:"none"}))I.text&&(v+=I.text),I.usage!==void 0&&u.onUsage?.(I.usage,I.costUsd);return v},"text"),authorize:i(async()=>{await n("authorize",{})},"authorize"),ceiling:i(async(u,v,I)=>e.object({configurationHash:e.string().regex(/^[a-f0-9]{64}$/),maximumChargeUsd:e.number().finite().positive()}).strict().parse(await n("ceiling",{modelId:u,pricing:v,maximumOutputTokens:I})),"ceiling"),compute:i((u,v=!1)=>n("compute",u,v?AbortSignal.timeout(6e4):r),"compute"),checkpoint:i(u=>n("checkpoint",u),"checkpoint")}}i(qe,"createHostedAdvancedModelBridge");import Qe from"node:path";var Me=e.string().regex(/^[a-f0-9]{64}$/),Ke=e.object({taskId:e.string().min(1),caseHash:Me,session:C,turn:$,events:e.array(se).max(1e4),traceHash:Me,output:e.string().nullable()}).strict(),K=e.object({packageValue:ae,contexts:e.array(Ke).max(1e4)}).strict();async function _e(s){let r=V(s.pin),t=K.parse(s.privateSource),n=ie(t.packageValue),d=M(e.object({manifest:e.unknown(),result:e.unknown()}).parse(s.evidence));async function m(){if(await s.authorize(),r.actorId!==s.actor.actorId||r.teamId!==s.actor.teamId||r.profileRef.source!=="openpond_git"||r.profileRef.repositoryId!==s.source.repositoryId||r.profileRef.profileId!==s.source.profileId||r.sourceRevision!==s.source.sourceRevision)throw new Error("The actual hosted advanced source owner changed.")}if(i(m,"authorize"),await m(),d.manifest.teamId!==r.teamId||d.result.status!=="completed"||d.manifest.id!==r.evidence.id||d.result.contentHash!==r.evidence.contentHash||R(d.manifest.dataset)!==R(r.externalDatasetBinding.dataset))throw new Error("The exact completed hosted advanced evidence changed.");if(n.contentHash!==r.externalDatasetBinding.packageHash||n.contentHash!==r.adaptationDatasetBinding.packageHash||n.environment.contentHash!==r.environmentPolicy.environmentHash||n.environment.contract.networkPolicy!=="none")throw new Error("The hosted advanced environment/package is not the exact reviewed closed-network release.");if(n.taskset.tools.some(l=>l.name==="web_search"||l.name==="web_fetch"))throw new Error("Live external tools require their own qualified frozen-observation and budget owner.");if(n.verifierSet.graders.some(l=>l.kind==="human"||l.kind==="model_judge"&&l.calibrationStatus!=="passed"))throw new Error("Advanced hosted evaluation needs executable, qualified independent graders.");let u=r.adaptationTaskIds.map(l=>n.taskset.tasks.find(H=>H.id===l)),v=r.holdoutTaskIds.map(l=>n.taskset.tasks.find(H=>H.id===l)),I=new Set(u.map(l=>l?.clusterKey));if(u.some(l=>!l||l.split!==r.adaptationSplit)||v.some(l=>!l||l.split!==r.holdoutSplit||I.has(l.clusterKey)))throw new Error("Hosted adaptation/holdout membership or independent families changed.");let x=await s.store.getHarnessReleaseRecord(r.baselineRelease.contentHash);if(!x||x.harnessRelease.id!==r.baselineRelease.id||s.workspace.currentChannel.release?.contentHash!==r.baselineRelease.contentHash)throw new Error("The exact hosted source baseline is unavailable.");let y=await D({workspaceId:typeof x.agentSnapshot.metadata.workspaceId=="string"?x.agentSnapshot.metadata.workspaceId:x.workspaceId,sourceDir:Qe.join(x.bundlePath,"source")});if(z(y).protectedClosureHash!==r.privateClosureHash)throw new Error("The protected hosted Profile closure changed.");let h={packageValue:n,authorize:m};return{read:i(async l=>{if(V(l).contentHash!==r.contentHash)throw new Error("The actual hosted advanced admission changed.");return await m(),h},"read"),evidence:i(async()=>(await m(),d),"evidence"),authorize:i(async()=>m(),"authorize"),reviewContext:i(async(l,H)=>{await m();let E=t.contexts.filter(p=>p.taskId===H),P=d.result.cases.find(p=>p.identity.caseId===H);if(E.length!==1||!P||P.status!=="completed")throw new Error("The actual retained hosted review case is unavailable.");let w=E[0];if(w.caseHash!==R(P)||w.session.cloudTeamId!==r.teamId||w.turn.sessionId!==w.session.id||w.turn.status==="in_progress"||w.events.some(p=>p.sessionId!==w.session.id||p.turnId!==w.turn.id))throw new Error("The actual hosted review session/turn/trace binding changed.");return await m(),{...w,case:{output:w.output}}},"reviewContext")}}i(_e,"createHostedAdvancedRefinerSource");import{randomUUID as Ze}from"node:crypto";function Oe(s){async function r(n){let d=await s.store.getSession(n);if(!d||d.cloudTeamId!==s.teamId||d.metadata?.hostedAdvancedTurnId!==s.hostedTurnId||d.metadata?.parentModelRunId!==s.modelRunId)throw new Error("The actual hosted advanced case owner changed.");return d}i(r,"read");async function t(n,d,m){let u=await r(n),v=e.object({action:e.string()}).passthrough().parse(d).action;return ce.parse(await s.bridge.compute({session:u,payload:d,turnId:m??null},v==="sandbox_stop"||v==="sandbox_receipts"))}return i(t,"tool"),{createSession:i(async n=>{await s.bridge.authorize();let d=C.partial().parse(n),m=new Date().toISOString();if(d.metadata?.parentModelRunId!==s.modelRunId)throw new Error("The foreground case belongs to another actual advanced Run.");let u=C.parse({...d,id:`hosted-advanced-case-${Ze()}`,provider:"openpond",currentProfile:s.profileRef,cloudTeamId:s.teamId,cwd:null,codexThreadId:null,appId:null,appName:null,createdAt:m,updatedAt:m,status:"active",pinned:!1,archived:!1,order:0,hiddenFromDefaultSidebar:!0,title:d.title??"Advanced hosted evaluation case",metadata:{...d.metadata,source:"hosted-advanced-evaluation",hostedAdvancedTurnId:s.hostedTurnId,actorId:s.actorId,workspaceTarget:"hosted",benchmarkRuntime:"hosted_managed_work"}});return await s.store.insertSessionAtFront(u),await s.bridge.authorize(),u},"createSession"),getSession:r,runtimeEventsForSession:i(n=>s.store.runtimeEventsForSession(n),"runtimeEventsForSession"),executeWorkspaceTool:i((n,d,m)=>t(n,d,m?.turnId),"executeWorkspaceTool"),settleCostEvidence:i((n,d)=>t(n,{action:"sandbox_receipts",args:{}},d?.turnId),"settleCostEvidence")}}i(Oe,"createHostedAdvancedWorkRuntime");var Xe=e.string().regex(/^[a-f0-9]{64}$/),Be=e.object({version:e.string().min(1),source:e.string().min(1),effectiveAt:e.string().min(1),inputUsdPerMillionTokens:e.number().finite().nonnegative(),cachedInputUsdPerMillionTokens:e.number().finite().nonnegative(),outputUsdPerMillionTokens:e.number().finite().nonnegative()}).strict(),Z=e.object({operation:e.enum(["prepare_run","start","read","resume","cancel"]),request:ue,configuration:e.object({id:e.string().min(1),profileId:e.string().min(1),etag:Xe}).strict(),refinerRelease:Y,privateSource:K,upstream:e.object({modelId:e.string().min(1),revision:e.string().min(1),pricing:Be}).strict(),judgeModels:e.array(e.object({modelId:e.string().min(1),revision:e.string().min(1),pricing:Be}).strict()).max(50),bridge:Q.optional(),hostedTurnId:e.string().min(1).optional()}).strict();async function Fe(s){let r=Z.parse(s.request),t=r.request.pin;if(r.request.model.providerId!=="openpond"||r.request.model.modelId!==r.upstream.modelId||r.configuration.id!==r.request.modelId||r.configuration.profileId!==t.profileRef.profileId||r.request.profileId!==t.profileRef.profileId||r.refinerRelease.id!==t.refinerRelease.id||r.refinerRelease.contentHash!==t.refinerRelease.contentHash)throw new Error("The actual hosted advanced configuration/model/Refiner admission changed.");let n=`advanced-refiner-${R([t.actorId,t.teamId,t.operationId,t.contentHash,r.request.model,[r.request.seed],1]).slice(0,40)}`;if((r.operation==="start"||r.operation==="resume")&&(!r.bridge||!r.hostedTurnId))throw new Error("The actual hosted advanced execution grant is unavailable.");let m=r.bridge?qe(r.bridge,s.signal):null;if(r.bridge&&(r.bridge.jobId!==n||r.bridge.pinHash!==t.contentHash))throw new Error("The hosted model bridge belongs to another actual Run.");let u=i(async()=>{s.signal.throwIfAborted(),await s.authorize(),m&&await m.authorize()},"authorize"),v=await _e({...s,pin:t,privateSource:r.privateSource,authorize:u}),I=we(ve(s.storeDir));await I.persistRelease(r.refinerRelease),await I.writeSource(ee(r.refinerRelease.profile)),I.binding()?.release.contentHash!==t.refinerRelease.contentHash&&await I.transition(r.refinerRelease,{operation:"activate",bindingChanged:!0,actor:s.actor.actorId,reason:"Pin the actual hosted evaluation fork to its admitted immutable Refiner release.",authoringSkillHash:null});let y=ke({storeDir:s.storeDir,authorize:i(async()=>u(),"authorize"),packageForPin:i(async()=>r.privateSource.packageValue,"packageForPin"),prepareModel:i(async(c,f,k)=>{if(!m)throw new Error("The actual hosted model ceiling owner is unavailable.");return m.ceiling(c,k,f)},"prepareModel")}),h=i(async function*(c){let f=be(),k=[r.upstream,...r.judgeModels].find(q=>q.modelId===c.model.modelId);if(!m||!f||!k)throw new Error("The actual hosted model and durable shared budget are unavailable.");let{signal:T,...j}=c,O=c.maxOutputTokens??4096,L=await f.call(c.requestId,j,k.pricing,O,async()=>{let q=[],F=null;for await(let N of m.stream({...c,signal:AbortSignal.any([T,f.signal])}))q.push(N),N.costUsd!==void 0&&(F=(F??0)+N.costUsd);return{value:q,costUsd:F}});for(let q of L)yield q},"stream"),l=i(async c=>{let f="";for await(let k of h({...c,reasoningEffort:c.reasoningEffort??null,tools:[],toolChoice:"none"}))k.text&&(f+=k.text),k.usage!==void 0&&c.onUsage?.(k.usage,k.costUsd);return f},"text"),H=Ie({store:s.store,storeDir:s.storeDir}),E=await H.projectSelected({profileId:t.profileRef.profileId,package:r.privateSource.packageValue,adaptationSplit:t.adaptationSplit,holdoutSplit:t.holdoutSplit}),P=i(async c=>{let f=C.partial().parse(c),k=new Date().toISOString(),T=C.parse({...f,id:`hosted-review-${R([n,f.metadata]).slice(0,40)}`,cloudTeamId:t.teamId,currentProfile:t.profileRef,appId:null,appName:null,cwd:null,codexThreadId:null,title:f.title??"Hosted Refiner review",provider:"openpond",createdAt:k,updatedAt:k,status:"active",pinned:!1,archived:!1,order:0,metadata:{...f.metadata,hostedAdvancedTurnId:r.hostedTurnId??null,actorId:t.actorId,source:"hosted-advanced-evaluation"}});return await s.store.insertSessionAtFront(T),T},"createSession"),w=m&&r.hostedTurnId?Oe({store:s.store,bridge:m,teamId:t.teamId,actorId:t.actorId,hostedTurnId:r.hostedTurnId,modelRunId:n,profileRef:t.profileRef}):void 0,p=Se({store:s.store,storeDir:s.storeDir,modelJudge:ye({store:s.store,modelText:l}),modelText:l,modelStream:h,workRuntime:w,resolveTasksetRelease:i(c=>H.releaseForTaskset(c),"resolveTasksetRelease")}),a={store:s.store,storeDir:s.storeDir,evaluation:p,benchmarkTasksets:H,loadProfileState:i(async()=>s.profile,"loadProfileState"),resolveEvaluationProject:i(async(c,f)=>{if(await u(),c!==r.configuration.id||f!==r.configuration.profileId)throw new Error("The actual hosted evaluation configuration changed.");return{id:c,profileId:f}},"resolveEvaluationProject"),resolveUpstreamModel:i(async()=>({providerId:"openpond",modelId:r.upstream.modelId,revision:r.upstream.revision,pricing:r.upstream.pricing}),"resolveUpstreamModel"),advancedBoundary:y,refinerStream:i(async function*(c){if(!c.requestId)throw new Error("A hosted Refiner call needs its actual retained ID.");yield*h({model:c.model,reasoningEffort:"low",messages:c.messages,tools:[],toolChoice:"none",requestId:c.requestId,maxOutputTokens:4096,signal:c.signal,hostedTokenPricing:c.pricing})},"refinerStream")},o=Re({...a,reviewQuality:He({source:v,boundary:y,benchmark:a,createSession:P})}),g={advancedEvaluation:t,selectedTaskset:{id:E.id,revision:E.revision,contentHash:E.contentHash},modelId:r.request.modelId,profileId:r.request.profileId,model:r.request.model,reasoningEffort:r.request.reasoningEffort,seeds:[r.request.seed],repetitions:1,maximumSpendUsd:t.maximumCostUsd},b,S=i(()=>{o.cancel(n)},"stop");s.signal.addEventListener("abort",S,{once:!0});try{if(r.operation==="prepare_run")return o.prepare(g);let c=await s.store.getModelRun(n);if(!c||c.evaluation?.benchmarkId!=="harness-refiner"||c.evaluation.advancedEvaluation?.contentHash!==t.contentHash)throw new Error("The original hosted advanced Run is unavailable.");if(r.operation==="read")return c;if(r.operation==="cancel")return o.cancel(n);if(m){let T=!1;b=setInterval(()=>{T||(T=!0,s.store.getModelRun(n).then(j=>j?m.checkpoint(j):void 0).catch(()=>S()).finally(()=>{T=!1}))},2e3)}r.operation==="start"?await o.start(g):await o.resume(n);let f=await o.wait(n);if(!f)throw new Error("The actual hosted advanced engine did not retain its Run.");let k=pe.parse(f);return m&&await m.checkpoint(k),k}finally{b&&clearInterval(b),s.signal.removeEventListener("abort",S),await o.close(),await y.close()}}i(Fe,"runHostedAdvancedRefinerOwner");import{promises as _}from"node:fs";import A from"node:path";var Ye=e.object({actor:e.object({actorId:e.string().min(1),teamId:e.string().min(1)}).strict(),storeDir:e.string().min(1),source:e.object({repoPath:e.string().min(1),repositoryId:e.string().min(1),profileId:e.string().min(1),sourceRevision:e.string().regex(/^[a-f0-9]{40,64}$/),filesHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),evidence:e.object({manifest:e.unknown(),result:e.unknown()}).strict(),operation:e.enum(["advanced","describe","command","queue","cancelQueued","bind","finish","beginTesting","cancelTesting","failTesting","comparison","beginAdoption","export","source","tool","toolCatalog"]),advanced:Z.optional(),command:le.optional(),candidateId:e.string().optional(),revision:e.number().int().positive().optional(),actualSession:C.optional(),actualTurn:$.optional(),recipe:e.unknown().optional(),baseline:e.object({manifest:e.unknown(),result:e.unknown()}).strict().optional(),candidate:e.object({manifest:e.unknown(),result:e.unknown()}).strict().optional(),humanProjection:oe.optional(),humanSelections:re.optional(),adoptionReadback:e.unknown().optional(),failure:e.object({message:e.string().max(2e3),cancelled:e.boolean()}).strict().optional(),tool:e.object({name:e.string(),args:e.record(e.string(),e.unknown()),callId:e.string()}).strict().optional(),agentRuntime:e.object({source:e.string(),cliRelativePath:e.string()}).strict().optional(),queued:e.object({sessionId:e.string(),turnId:e.string(),createdAt:e.string().datetime()}).strict().optional()}).strict();async function We(s,r=new AbortController().signal){r.throwIfAborted();let t=Ye.parse(s),{actor:n,source:d}=t;if(!A.isAbsolute(t.storeDir)||!A.isAbsolute(d.repoPath))throw new Error("Hosted candidate owner requires contained absolute private paths.");let m=M(t.evidence),u=[t.baseline,t.candidate].filter(l=>l!==void 0).map(l=>M(l));if(m.manifest.teamId!==n.teamId)throw new Error("Hosted candidate evidence belongs to another team.");if(await B(d.repoPath)!==d.filesHash)throw new Error("The admitted hosted Profile source bytes changed.");let v=`hosted-improve-source-${R([n,d.repositoryId,d.profileId,d.sourceRevision]).slice(0,40)}`,I=A.join(t.storeDir,"library","profile-experiment-origins",v);if(await _.mkdir(A.dirname(I),{recursive:!0,mode:448}),await _.stat(I).catch(()=>null)||await _.cp(d.repoPath,I,{recursive:!0,errorOnExist:!0,force:!1}),await B(I)!==d.filesHash)throw new Error("The private accepted Profile cache changed.");let x=await W(I,d.profileId);if(x.error||!x.sourcePath)throw new Error("The accepted hosted Profile does not compile.");let y=new xe(t.storeDir),h;try{let l=await y.getHarnessWorkspace(v);l||(l=(await fe({store:y,storeDir:t.storeDir,id:v,ownerId:n.actorId,name:d.profileId,profile:x,sourceRevision:d.sourceRevision,repositoryId:d.repositoryId,selectionEligible:!1,originMetadata:{profileExperimentOrigin:{schemaVersion:"openpond.profileExperimentOrigin.v1",...n,sourceRevision:d.sourceRevision,sourcePath:I,sourceFilesHash:d.filesHash},hostedImprovementOwner:!0}})).workspace);let H={source:"openpond_git",repositoryId:d.repositoryId,profileId:d.profileId},E=i(async()=>{if(r.throwIfAborted(),await B(I)!==d.filesHash||await B(d.repoPath)!==d.filesHash)throw new Error("Accepted source changed during private candidate I/O.")},"authorizer");if(t.operation==="advanced"){if(!t.advanced)throw new Error("Missing actual hosted advanced owner command.");return Fe({store:y,storeDir:t.storeDir,actor:n,profile:x,workspace:l,source:d,evidence:m,request:t.advanced,authorize:E,signal:r})}let P=i(()=>{if(!t.adoptionReadback)throw new Error("Actual hosted Git owner has not returned its sealed adoption receipt.");return e.object({receipt:e.object({id:e.string(),contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),activeRelease:e.object({id:e.string(),contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),testedCandidateRelease:e.object({id:e.string(),contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),executableSourceHash:e.string().regex(/^[a-f0-9]{64}$/),protectedClosureHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict().parse(t.adoptionReadback)},"readback");h=Ee({store:y,storeDir:t.storeDir,projectHumanComparison:i(async()=>{if(await E(),!t.humanProjection)throw new Error("The current private Human comparison owner is unavailable.");return ne(t.humanProjection)},"projectHumanComparison"),authorizeOwner:i(async(a,o,g,b,S)=>{if(R(a)!==R(n)||R(g)!==R(H)||o.id!==v)throw new Error("Hosted candidate source owner changed.");if(S.requireCurrentBase&&(o.currentChannel.release?.contentHash!==l.currentChannel.release?.contentHash||d.sourceRevision!==o.metadata.profileExperimentOrigin.sourceRevision))throw new Error("Hosted candidate accepted revision changed.");await E()},"authorizeOwner"),loadEvidence:i(async(a,o)=>{if(R(a)!==R(n))throw new Error("Hosted candidate evidence actor changed.");let g=[m,...u].find(b=>b.manifest.id===o.id&&b.result.contentHash===o.contentHash&&b.manifest.teamId===n.teamId);if(!g)throw new Error("Hosted candidate exact retained evidence changed.");return await E(),g},"loadEvidence"),freezeProfile:i(async(a,o,g)=>{let b=await y.getHarnessReleaseRecord(o.baseRelease.contentHash);if(!b)throw new Error("Hosted source baseline is missing.");let S=await D({workspaceId:typeof b.agentSnapshot.metadata.workspaceId=="string"?b.agentSnapshot.metadata.workspaceId:b.workspaceId,sourceDir:A.join(b.bundlePath,"source")}),c=await D({workspaceId:typeof g.release.agentSnapshot.metadata.workspaceId=="string"?g.release.agentSnapshot.metadata.workspaceId:g.release.workspaceId,sourceDir:A.join(g.release.bundlePath,"source")});return Ae({store:y,storeDir:t.storeDir,state:o},async f=>{await Ce({...f,state:o,base:S,candidate:c});let k=await W(f.root,o.profileRef.profileId),T=await U({storeDir:t.storeDir,state:o,profile:k,sourceRevision:g.profileSourceRevision,base:S}),j=z(T);if(j.protectedClosureHash!==z(S).protectedClosureHash)throw new Error("Hosted source candidate changed protected evaluation closure.");let O=A.join(t.storeDir,"library","profile-candidate-archives",o.id,j.contentHash);await _.mkdir(A.dirname(O),{recursive:!0,mode:448}),await _.stat(O).catch(()=>null)||await _.cp(f.root,O,{recursive:!0,errorOnExist:!0,force:!1});let L=await W(O,o.profileRef.profileId);if((await U({storeDir:t.storeDir,state:o,profile:L,sourceRevision:g.profileSourceRevision,base:S})).harnessRelease.contentHash!==T.harnessRelease.contentHash)throw new Error("Hosted frozen Profile archive readback differs.");let F=await he({storeDir:t.storeDir,workspaceId:g.release.workspaceId,compiled:T,createdAt:g.release.createdAt});return await E(),{...g,release:F,executableIdentity:j}})},"freezeProfile"),adopt:i(async()=>P(),"adopt"),readAdoption:i(async()=>t.adoptionReadback?P():null,"readAdoption"),rollback:i(async()=>P(),"rollback")});let w=Pe({store:y,improvements:h,actorId:i(async()=>n.actorId,"actorId"),teamId:i(async()=>n.teamId,"teamId"),loadProfile:i(async a=>{if(R(a)!==R(H))throw new Error("Candidate requested another source owner.");return x},"loadProfile"),agentRuntime:t.agentRuntime,operationSignal:r,loadAgentRuntime:De({storeDir:t.storeDir,loadArchive:ze({storeDir:t.storeDir})})});if(t.operation==="describe"){await E();let a=l.currentChannel.release,o=a?await y.getHarnessReleaseRecord(a.contentHash):null;if(!a||!o||o.workspaceId!==l.id||o.harnessRelease.id!==a.id||o.harnessRelease.contentHash!==a.contentHash||l.ownerScope.kind!=="personal"||l.ownerScope.id!==n.actorId)throw new Error("Hosted source release is unavailable to its admitted owner.");let g=await D({workspaceId:typeof o.agentSnapshot.metadata.workspaceId=="string"?o.agentSnapshot.metadata.workspaceId:v,sourceDir:A.join(o.bundlePath,"source")});if(g.harnessRelease.contentHash!==o.harnessRelease.contentHash)throw new Error("Hosted source compiler readback changed.");let b=await ge({runtime:{release:o},ref:H,sourceRevision:d.sourceRevision,harnessRelease:a}),S=i(c=>{let f=g.sourceFiles.find(k=>k.path===c)?.bytes;return f?JSON.parse(Buffer.from(f).toString("utf8")):null},"readJson");return await E(),{workspaceId:v,ownerRevision:l.revision,profileRef:H,baseRelease:l.currentChannel.release,profileSourceRevision:d.sourceRevision,manifest:g.manifest,executable:z(g),catalogHash:b.catalogHash,workflows:S("workflows/catalog.json"),actions:S("workflows/actions.json")}}if(t.operation==="command"){let a=t.command;if(!a)throw new Error("Missing canonical Improve command.");if(a.operation==="start")return h.start(n,a.request);if(a.operation==="list")return h.list(n,a.limit,a.cursor);if(!("id"in a))throw new Error("Discover exact hosted source choices through the authenticated host.");let o=await h.read(n,a.id);if(a.operation==="read")return o;if(a.operation==="instructions"){let g=await h.partition(n,o.id),b=await me(g.sourceRoot,o.component.path),S=await _.readFile(b);if(S.length>25e4)throw new Error("Instruction editor size limit exceeded.");let c=S.toString("utf8");if(o.component.kind==="workflow"){let f=JSON.parse(c).workflows?.find(k=>k.id===o.component.workflowId);if(f?.invocation?.kind!=="instructions")throw new Error("Use Work to author this executable Workflow.");c=f.invocation.instructions}return{candidateId:o.id,candidateRevision:o.revision,path:o.component.path,text:c,textHash:J(c),contentHash:J(S)}}if(a.operation==="humanComparisonOptions")throw new Error("Read the actual paired sources through their current hosted Experiment owner.");if(!("revision"in a)||o.revision!==a.revision)throw new Error("Candidate revision changed.");if(a.operation==="edit")return h.edit(n,o.id,o.revision,a.expectedFileHash,a.text);if(a.operation==="mode")return h.setMode(n,o.id,o.revision,a.mode);if(a.operation==="freeze")return h.freeze(n,o.id,o.revision);if(a.operation==="useCandidate")return h.useCandidate(n,o.id,o.revision);if(a.operation==="rollback")return h.rollback(n,o.id,o.revision);if(a.operation==="discard")return h.discard(n,o.id,o.revision);throw new Error("Hosted Work/test lifecycle requires the actual host turn/run admission.")}if(!t.candidateId)throw new Error("Missing actual hosted candidate ID.");let p=await h.read(n,t.candidateId);if(t.operation==="beginAdoption")return h.beginAdoption(n,p.id,t.revision);if(t.operation==="export")return je(y,p,"hosted_execution");if(t.operation==="source"){if(!p.frozen||p.status!=="frozen"&&p.status!=="testing"&&p.status!=="ready_for_review"&&p.status!=="adopting")throw new Error("Only the exact frozen source can enter hosted preparation.");let a=await y.getHarnessReleaseRecord(p.frozen.release.contentHash);if(!a||a.harnessRelease.id!==p.frozen.release.id)throw new Error("Frozen hosted source is unavailable.");let o=await D({workspaceId:typeof a.agentSnapshot.metadata.workspaceId=="string"?a.agentSnapshot.metadata.workspaceId:a.workspaceId,sourceDir:A.join(a.bundlePath,"source")}),g=z(o);if(o.harnessRelease.contentHash!==p.frozen.release.contentHash||g.contentHash!==p.frozen.executableSourceHash||g.protectedClosureHash!==p.frozen.protectedClosureHash)throw new Error("Frozen hosted executable changed.");let b=A.join(t.storeDir,"library","profile-candidate-archives",p.id,g.contentHash),S=await W(b,p.profileRef.profileId);if(S.error||!S.sourcePath)throw new Error("Frozen actual Profile archive is unavailable.");let c=await y.getHarnessReleaseRecord(p.baseRelease.contentHash);if(!c)throw new Error("Frozen baseline is unavailable.");let f=await D({workspaceId:typeof c.agentSnapshot.metadata.workspaceId=="string"?c.agentSnapshot.metadata.workspaceId:c.workspaceId,sourceDir:A.join(c.bundlePath,"source")}),k=await U({storeDir:t.storeDir,state:p,profile:S,sourceRevision:p.frozen.profileSourceRevision,base:f});if(k.harnessRelease.contentHash!==p.frozen.release.contentHash||z(k).contentHash!==g.contentHash)throw new Error("Actual frozen Profile archive differs from its compiled release.");return{state:p,profileSource:{repoPath:b,profileId:p.profileRef.profileId,sourceRevision:p.frozen.profileSourceRevision,repositoryId:p.profileRef.repositoryId,filesHash:await B(b)},sourcePackage:te({agentSnapshot:o.agentSnapshot,harnessRelease:o.harnessRelease,files:new Map(o.sourceFiles.map(T=>[T.path,T.bytes]))})}}if(t.operation==="comparison"){if(!t.baseline||!t.candidate)throw new Error("Missing actual hosted paired evidence.");return h.completeComparison(n,p.id,t.revision,M(t.baseline),M(t.candidate),t.humanSelections)}if(t.operation==="beginTesting")return h.beginTesting(n,p.id,t.revision,t.recipe);if(t.operation==="failTesting"){if(!t.failure)throw new Error("Missing actual hosted test failure.");return h.failTesting(n,p.id,t.revision,t.failure.message,t.failure.cancelled)}if(t.operation==="cancelTesting")return h.cancelTesting(n,p.id,t.revision);if(t.operation==="queue"){if(!t.queued)throw new Error("Missing actual hosted queue admission.");return h.queueAuthoringTurn(n,p.id,t.revision,t.queued.sessionId,t.queued.turnId,t.queued.createdAt)}if(t.operation==="cancelQueued")return h.cancelQueuedAuthoring(n,p.id,t.revision);if(t.operation==="bind"||t.operation==="finish"||t.operation==="tool"||t.operation==="toolCatalog"){if(!t.actualSession||!t.actualTurn||t.actualTurn.sessionId!==t.actualSession.id||t.actualSession.cloudTeamId!==n.teamId||R(t.actualSession.currentProfile)!==R(H))throw new Error("Actual hosted candidate Work binding changed.");let a=t.actualSession,o=t.actualTurn,g=await y.getSession(a.id);if(!g)await y.insertSessionAtFront(a);else if(R({...g,updatedAt:a.updatedAt,status:a.status})!==R(a))throw new Error("Retained hosted candidate session changed.");let b=await y.getTurn(o.id);if(!b)await y.insertTurn(o);else{if(b.sessionId!==o.sessionId||R(b.metadata.refinementCandidate)!==R(o.metadata.refinementCandidate)||b.prompt!==o.prompt)throw new Error("Actual hosted candidate turn identity changed.");await y.updateTurn(o.id,()=>o)}if(t.operation==="bind")return h.bindAuthoringTurn(n,p.id,t.revision,a.id,o.id);if(t.operation==="finish")return h.finishAuthoring(n,p.id,t.revision);if(t.operation==="toolCatalog")return await w.candidateAuthoringForTurn(a.id,o.id),[...G({loadProfileState:i(async()=>x,"loadProfileState"),resolveCandidateProfile:w.resolveCandidateProfile,executeCandidateAgentCommand:w.executeCandidateAgentCommand}),...Te(async()=>{throw new Error("Hosted file tools require a bound private call.")}),{name:"exec_command",description:"Run a bounded command confined to the selected public candidate component.",parameters:{type:"object",additionalProperties:!1,properties:{command:{type:"string",minLength:1,maxLength:2e4},cwd:{type:"string"}},required:["command"]}},{name:"view_image",description:"Inspect an image inside the candidate public source tree.",parameters:{type:"object",additionalProperties:!1,properties:{path:{type:"string"}},required:["path"]}}].map(({name:c,description:f,parameters:k})=>({name:c,description:f,parameters:k}));if(!t.tool)throw new Error("Missing candidate tool call.");await w.authorizeCandidateTool({sessionId:a.id,turnId:o.id,name:t.tool.name});let S={session:a,turnId:o.id,args:t.tool.args,callId:t.tool.callId,signal:r,workspaceDiffBaseline:null,turnPermissions:{approvalPolicy:"never",sandbox:"workspace-write",codexPermissionMode:"default"},provider:a.provider,model:o.modelRef?.modelId??a.modelRef?.modelId??"",mentionedApps:[],userPrompt:o.prompt,turnMetadata:o.metadata};if(t.tool.name==="get_profile"||t.tool.name.startsWith("agent_")||t.tool.name==="ask_user"){let c=G({loadProfileState:i(async()=>x,"loadProfileState"),resolveCandidateProfile:w.resolveCandidateProfile,executeCandidateAgentCommand:w.executeCandidateAgentCommand}).find(f=>f.name===t.tool.name);if(!c)throw new Error("Candidate authoring tool is unavailable.");return c.execute(S)}if(t.tool.name==="view_image")return w.executeCandidateImage(S);if(t.tool.name==="exec_command")return w.executeCandidateCommand(S,{session:a,turnId:o.id,command:e.string().min(1).max(2e4).parse(t.tool.args.command),cwd:typeof t.tool.args.cwd=="string"?t.tool.args.cwd:null,signal:S.signal,source:"model_tool"});if(["list_files","read_files","search_files","workspace_status","write_file","write_files","edit_file","delete_file"].includes(t.tool.name))return w.executeCandidateWorkspaceTool({session:a,turnId:o.id,request:de.parse({action:t.tool.name,args:t.tool.args,source:"chat_action"})});throw new Error("This hosted tool has no confined candidate transport.")}throw new Error("Unknown private hosted Improve operation.")}finally{await h?.close(),await y.close()}}i(We,"runHostedExperimentImprovementOwner");async function wr(s){if(s.length!==1||s[0].length>16e3||!/^[A-Za-z0-9_-]+$/.test(s[0]))throw new Error("Hosted Improve IPC argument is invalid.");let r=e.object({directory:e.string(),file:e.string().regex(/^[A-Za-z0-9_-]+\.json$/)}).strict().parse(JSON.parse(Buffer.from(s[0],"base64url").toString("utf8")));if(!Ue.isAbsolute(r.directory))throw new Error("Hosted Improve IPC requires an absolute private directory.");let t=Ue.join(r.directory,r.file),n=await $e.lstat(t);if(!n.isFile()||n.isSymbolicLink()||n.size>32*1024*1024)throw new Error("Hosted Improve private request exceeds its byte/type limit.");let d=new AbortController,m=i(()=>d.abort(new Error("The actual hosted owner stopped this private operation.")),"stop");process.once("SIGTERM",m),process.once("SIGINT",m);try{let u=await We(JSON.parse(await $e.readFile(t,"utf8")),d.signal),v=Buffer.from(JSON.stringify(u));if(v.length>32*1024*1024)throw new Error("Hosted Improve private response exceeds its byte limit.");process.stdout.write(`${v.toString("utf8")}
3
3
  `)}finally{process.removeListener("SIGTERM",m),process.removeListener("SIGINT",m)}}i(wr,"runHostedExperimentImprovementCli");export{wr as runHostedExperimentImprovementCli};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{b as a,c as b}from"./chunk-O7VGFMDO.js";import"./chunk-QJRXTIOC.js";import"./chunk-7K72KS5C.js";import"./chunk-7MXZJQS7.js";import"./chunk-7YR6CBNU.js";import"./chunk-5CMKGD43.js";import"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import"./chunk-XDMUD4FW.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as loadHostedHarnessRuntime,b as loadHostedHarnessRuntimeForSession};
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a,e as F}from"./chunk-M7PBDRKC.js";import{a as O}from"./chunk-BKMGBIBT.js";import{a as h}from"./chunk-BUFQKDAW.js";import{la as I,oa as D,pa as M}from"./chunk-JBHAU7PH.js";import"./chunk-F2AG46CV.js";import"./chunk-PGKEDR3S.js";import{N as w}from"./chunk-ZJY2L43W.js";import"./chunk-L3KS6MOV.js";import"./chunk-YSYXIJ46.js";import{od as A}from"./chunk-6JBWHR6T.js";import"./chunk-HK3WGUKK.js";import"./chunk-6MI4KKWF.js";import"./chunk-5ZZM3TUN.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import"./chunk-JO7GRBOG.js";import"./chunk-BQNK2NMB.js";import{ta as R}from"./chunk-VW7D3DRM.js";import"./chunk-UWO34HP6.js";import"./chunk-L4BYPZ4U.js";import{j as C,k as v}from"./chunk-P653BXMY.js";import{b as c}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as f}from"./chunk-FTQLQJQV.js";import{promises as m}from"node:fs";import n from"node:path";var $=c.object({action:c.enum(["stage","readback","rollback"]),repoPath:c.string(),outputDir:c.string(),exportFile:c.string(),commit:c.string().regex(/^[a-f0-9]{40}$/).optional(),expectedExecutableSourceHash:c.string().regex(/^[a-f0-9]{64}$/).optional()}).strict();async function z(l){let e=$.parse(l);if(!n.isAbsolute(e.repoPath)||!n.isAbsolute(e.outputDir)||!/^[a-zA-Z0-9_-]+\.json$/.test(e.exportFile))throw new Error("Hosted candidate private IPC is not contained.");let g=n.join(e.outputDir,e.exportFile),H=await m.lstat(g);if(!H.isFile()||H.isSymbolicLink()||H.size>8*1024*1024)throw new Error("Hosted candidate export exceeds its private IPC bound.");let t=O(JSON.parse(await m.readFile(g,"utf8"))),u=await w({repoPath:e.repoPath,profileId:t.profileRef.profileId});if(u.error||!u.sourcePath)throw new Error("Actual hosted Profile source is unavailable.");if(e.action!=="readback"){let o=!1;try{await a(e.repoPath,["symbolic-ref","-q","HEAD"]),o=!0}catch{}if(o||await a(e.repoPath,["rev-parse","HEAD"])!==(e.action==="rollback"?e.commit:t.expectedCommit)||await a(e.repoPath,["status","--porcelain","--untracked-files=all"]))throw new Error("Candidate staging requires a clean detached exact original source worktree.")}let x=f(async o=>I({storeDir:e.outputDir,workspaceId:t.compiler.workspaceId,name:t.compiler.name,profile:await w({repoPath:e.repoPath,profileId:t.profileRef.profileId}),sourceRevision:o,repositoryId:t.compiler.repositoryId}),"compile");if(e.action==="readback"){if(!e.commit||await a(e.repoPath,["rev-parse","HEAD"])!==e.commit)throw new Error("Hosted Profile readback is not the committed source.");let o=await x(e.commit),i=h(o);if(i.profileGitHead!==e.commit||i.contentHash!==(e.expectedExecutableSourceHash??t.executableSourceHash)||i.protectedClosureHash!==t.protectedClosureHash)throw new Error("Hosted active executable differs from the actual tested candidate.");let s=await M({storeDir:e.outputDir,workspaceId:t.compiler.workspaceId,compiled:o,createdAt:t.createdAt});return{commit:e.commit,activeRelease:{id:s.harnessRelease.id,contentHash:s.harnessRelease.contentHash},executableSourceHash:i.contentHash,protectedClosureHash:i.protectedClosureHash}}if(e.action==="rollback"){if(!e.commit)throw new Error("Rollback requires the exact accepted commit.");await a(e.repoPath,["-c","core.hooksPath=/dev/null","revert","--no-commit",e.commit])}let p=await x(t.expectedCommit);if(p.harnessRelease.contentHash!==t.baseRelease.contentHash||p.harnessRelease.id!==t.baseRelease.id)throw new Error("Hosted original source differs from the owner-attested baseline release.");if(e.action==="stage"){let o=Buffer.from(t.sourceManifest.base64,"base64");if(o.toString("base64")!==t.sourceManifest.base64||o.length!==t.sourceManifest.sizeBytes||v(o)!==t.sourceManifest.contentHash)throw new Error("Candidate source manifest byte identity differs.");let i=A.parse(JSON.parse(o.toString("utf8"))),s=n.join(e.outputDir,"candidate-source");await m.mkdir(s,{recursive:!0}),await m.writeFile(n.join(s,"harness.json"),C(i));let _=R(t.policySource),j=new Map(p.sourceFiles.filter(r=>r.asset.visibility!=="policy").map(r=>[r.path,r]));for(let r of i.files){let k=r.visibility==="policy"?_.get(r.path):j.get(r.path)?.bytes;if(!k)throw new Error("The hosted source cannot hydrate the exact protected candidate closure.");let y=n.join(s,r.path);if(n.relative(s,y).startsWith(".."))throw new Error("Candidate release path escapes private staging.");await m.mkdir(n.dirname(y),{recursive:!0}),await m.writeFile(y,k)}let P=await D({workspaceId:t.compiler.workspaceId,sourceDir:s}),S=h(P);if(P.harnessRelease.contentHash!==t.policySource.harnessRelease.contentHash||S.contentHash!==t.executableSourceHash||S.protectedClosureHash!==t.protectedClosureHash)throw new Error("Owner-attested candidate differs from independently compiled hosted source.");await F({source:u.sourcePath,state:{component:t.component},base:p,candidate:P,profile:u})}await a(e.repoPath,["add","--all"]),await a(e.repoPath,["-c","core.hooksPath=/dev/null","-c","commit.gpgSign=false","commit","-m",`${e.action==="rollback"?"Roll back":"Adopt"} owner-tested candidate ${t.candidateId}`],{GIT_AUTHOR_NAME:"OpenPond",GIT_AUTHOR_EMAIL:"profile-candidate@openpond.local",GIT_COMMITTER_NAME:"OpenPond",GIT_COMMITTER_EMAIL:"profile-candidate@openpond.local"});let E=await a(e.repoPath,["rev-parse","HEAD"]),T=await w({repoPath:e.repoPath,profileId:t.profileRef.profileId}),b=await I({storeDir:e.outputDir,workspaceId:t.compiler.workspaceId,name:t.compiler.name,profile:T,sourceRevision:E,repositoryId:t.compiler.repositoryId}),d=h(b);if(e.action==="stage"&&(d.contentHash!==t.executableSourceHash||d.protectedClosureHash!==t.protectedClosureHash)||e.action==="rollback"&&(d.contentHash!==h(p).contentHash||d.protectedClosureHash!==h(p).protectedClosureHash))throw new Error("Staged actual source differs from its exact tested executable graph.");return{commit:E,activeRelease:{id:b.harnessRelease.id,contentHash:b.harnessRelease.contentHash},executableSourceHash:d.contentHash,protectedClosureHash:d.protectedClosureHash}}f(z,"hostedProfileCandidate");async function Q(l){if(l.length!==1||l[0].length>16e3||!/^[a-zA-Z0-9_-]+$/.test(l[0]))throw new Error("Hosted candidate IPC argument is invalid.");process.stdout.write(`${JSON.stringify(await z(JSON.parse(Buffer.from(l[0],"base64url").toString("utf8"))))}
2
+ import{a,e as F}from"./chunk-IOQUF34U.js";import{a as O}from"./chunk-EMKZVP7Z.js";import{a as h}from"./chunk-T5LE6R5S.js";import{na as I,qa as D,ra as M}from"./chunk-7MXZJQS7.js";import"./chunk-7YR6CBNU.js";import"./chunk-5CMKGD43.js";import{N as w}from"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import{od as A}from"./chunk-XDMUD4FW.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import{ua as R}from"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import{k as C,l as v}from"./chunk-NNF6KCHD.js";import{b as c}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as f}from"./chunk-FTQLQJQV.js";import{promises as m}from"node:fs";import n from"node:path";var $=c.object({action:c.enum(["stage","readback","rollback"]),repoPath:c.string(),outputDir:c.string(),exportFile:c.string(),commit:c.string().regex(/^[a-f0-9]{40}$/).optional(),expectedExecutableSourceHash:c.string().regex(/^[a-f0-9]{64}$/).optional()}).strict();async function z(l){let e=$.parse(l);if(!n.isAbsolute(e.repoPath)||!n.isAbsolute(e.outputDir)||!/^[a-zA-Z0-9_-]+\.json$/.test(e.exportFile))throw new Error("Hosted candidate private IPC is not contained.");let g=n.join(e.outputDir,e.exportFile),H=await m.lstat(g);if(!H.isFile()||H.isSymbolicLink()||H.size>8*1024*1024)throw new Error("Hosted candidate export exceeds its private IPC bound.");let t=O(JSON.parse(await m.readFile(g,"utf8"))),u=await w({repoPath:e.repoPath,profileId:t.profileRef.profileId});if(u.error||!u.sourcePath)throw new Error("Actual hosted Profile source is unavailable.");if(e.action!=="readback"){let o=!1;try{await a(e.repoPath,["symbolic-ref","-q","HEAD"]),o=!0}catch{}if(o||await a(e.repoPath,["rev-parse","HEAD"])!==(e.action==="rollback"?e.commit:t.expectedCommit)||await a(e.repoPath,["status","--porcelain","--untracked-files=all"]))throw new Error("Candidate staging requires a clean detached exact original source worktree.")}let x=f(async o=>I({storeDir:e.outputDir,workspaceId:t.compiler.workspaceId,name:t.compiler.name,profile:await w({repoPath:e.repoPath,profileId:t.profileRef.profileId}),sourceRevision:o,repositoryId:t.compiler.repositoryId}),"compile");if(e.action==="readback"){if(!e.commit||await a(e.repoPath,["rev-parse","HEAD"])!==e.commit)throw new Error("Hosted Profile readback is not the committed source.");let o=await x(e.commit),i=h(o);if(i.profileGitHead!==e.commit||i.contentHash!==(e.expectedExecutableSourceHash??t.executableSourceHash)||i.protectedClosureHash!==t.protectedClosureHash)throw new Error("Hosted active executable differs from the actual tested candidate.");let s=await M({storeDir:e.outputDir,workspaceId:t.compiler.workspaceId,compiled:o,createdAt:t.createdAt});return{commit:e.commit,activeRelease:{id:s.harnessRelease.id,contentHash:s.harnessRelease.contentHash},executableSourceHash:i.contentHash,protectedClosureHash:i.protectedClosureHash}}if(e.action==="rollback"){if(!e.commit)throw new Error("Rollback requires the exact accepted commit.");await a(e.repoPath,["-c","core.hooksPath=/dev/null","revert","--no-commit",e.commit])}let p=await x(t.expectedCommit);if(p.harnessRelease.contentHash!==t.baseRelease.contentHash||p.harnessRelease.id!==t.baseRelease.id)throw new Error("Hosted original source differs from the owner-attested baseline release.");if(e.action==="stage"){let o=Buffer.from(t.sourceManifest.base64,"base64");if(o.toString("base64")!==t.sourceManifest.base64||o.length!==t.sourceManifest.sizeBytes||v(o)!==t.sourceManifest.contentHash)throw new Error("Candidate source manifest byte identity differs.");let i=A.parse(JSON.parse(o.toString("utf8"))),s=n.join(e.outputDir,"candidate-source");await m.mkdir(s,{recursive:!0}),await m.writeFile(n.join(s,"harness.json"),C(i));let _=R(t.policySource),j=new Map(p.sourceFiles.filter(r=>r.asset.visibility!=="policy").map(r=>[r.path,r]));for(let r of i.files){let k=r.visibility==="policy"?_.get(r.path):j.get(r.path)?.bytes;if(!k)throw new Error("The hosted source cannot hydrate the exact protected candidate closure.");let y=n.join(s,r.path);if(n.relative(s,y).startsWith(".."))throw new Error("Candidate release path escapes private staging.");await m.mkdir(n.dirname(y),{recursive:!0}),await m.writeFile(y,k)}let P=await D({workspaceId:t.compiler.workspaceId,sourceDir:s}),S=h(P);if(P.harnessRelease.contentHash!==t.policySource.harnessRelease.contentHash||S.contentHash!==t.executableSourceHash||S.protectedClosureHash!==t.protectedClosureHash)throw new Error("Owner-attested candidate differs from independently compiled hosted source.");await F({source:u.sourcePath,state:{component:t.component},base:p,candidate:P,profile:u})}await a(e.repoPath,["add","--all"]),await a(e.repoPath,["-c","core.hooksPath=/dev/null","-c","commit.gpgSign=false","commit","-m",`${e.action==="rollback"?"Roll back":"Adopt"} owner-tested candidate ${t.candidateId}`],{GIT_AUTHOR_NAME:"OpenPond",GIT_AUTHOR_EMAIL:"profile-candidate@openpond.local",GIT_COMMITTER_NAME:"OpenPond",GIT_COMMITTER_EMAIL:"profile-candidate@openpond.local"});let E=await a(e.repoPath,["rev-parse","HEAD"]),T=await w({repoPath:e.repoPath,profileId:t.profileRef.profileId}),b=await I({storeDir:e.outputDir,workspaceId:t.compiler.workspaceId,name:t.compiler.name,profile:T,sourceRevision:E,repositoryId:t.compiler.repositoryId}),d=h(b);if(e.action==="stage"&&(d.contentHash!==t.executableSourceHash||d.protectedClosureHash!==t.protectedClosureHash)||e.action==="rollback"&&(d.contentHash!==h(p).contentHash||d.protectedClosureHash!==h(p).protectedClosureHash))throw new Error("Staged actual source differs from its exact tested executable graph.");return{commit:E,activeRelease:{id:b.harnessRelease.id,contentHash:b.harnessRelease.contentHash},executableSourceHash:d.contentHash,protectedClosureHash:d.protectedClosureHash}}f(z,"hostedProfileCandidate");async function Q(l){if(l.length!==1||l[0].length>16e3||!/^[a-zA-Z0-9_-]+$/.test(l[0]))throw new Error("Hosted candidate IPC argument is invalid.");process.stdout.write(`${JSON.stringify(await z(JSON.parse(Buffer.from(l[0],"base64url").toString("utf8"))))}
3
3
  `)}f(Q,"runHostedProfileCandidateCli");export{z as hostedProfileCandidate,Q as runHostedProfileCandidateCli};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{a,b,c,d}from"./chunk-LVL4TIAO.js";import"./chunk-7MXZJQS7.js";import"./chunk-7YR6CBNU.js";import"./chunk-5CMKGD43.js";import"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import"./chunk-XDMUD4FW.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as compileHostedProfileRelease,b as runHostedProfileCompilerCli,c as runHostedProfileEvaluationCli,d as runHostedProfileInspectionCli};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as m,b as c}from"./chunk-DNXKIIV7.js";import{a as l}from"./chunk-F2AG46CV.js";import{L as f}from"./chunk-6JBWHR6T.js";import"./chunk-HK3WGUKK.js";import"./chunk-6MI4KKWF.js";import"./chunk-5ZZM3TUN.js";import"./chunk-6FA3GG5B.js";import{ja as s,oa as u}from"./chunk-JO7GRBOG.js";import"./chunk-BQNK2NMB.js";import"./chunk-VW7D3DRM.js";import"./chunk-L4BYPZ4U.js";import{m as t}from"./chunk-P653BXMY.js";import{b as n}from"./chunk-ES2ISFJC.js";import{a as i}from"./chunk-FTQLQJQV.js";var v=n.object({profileRef:f,sourceRevision:n.string().min(1),action:n.enum(["compare","report"]),request:n.unknown(),runs:n.array(l).max(1e4),comparisons:n.array(s).max(1e4),suiteRuns:n.array(u).max(1e4)}).strict();async function h(p){let o=v.parse(p);for(let e of[...o.runs,...o.comparisons,...o.suiteRuns])t(e,"Hosted evaluation evidence");let a={getProfileEvaluationRun:i(async e=>o.runs.find(r=>r.manifest.id===e)??null,"getProfileEvaluationRun"),getProfileEvaluationComparison:i(async e=>o.comparisons.find(r=>r.id===e)??null,"getProfileEvaluationComparison"),getProfileEvaluationSuiteRun:i(async e=>o.suiteRuns.find(r=>r.id===e)??null,"getProfileEvaluationSuiteRun"),saveProfileEvaluationComparison:i(async(e,r)=>r,"saveProfileEvaluationComparison")};return o.action==="compare"?m({store:a,selectedProfile:i(async()=>({ref:o.profileRef,sourceRevision:o.sourceRevision}),"selectedProfile")})(o.request):c({store:a,profileRef:o.profileRef,request:o.request})}i(h,"controlHostedProfileEvaluation");export{h as controlHostedProfileEvaluation};
2
+ import{a as m,b as c}from"./chunk-XM26DGML.js";import{a as l}from"./chunk-7YR6CBNU.js";import{L as f}from"./chunk-XDMUD4FW.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import{ja as s,oa as u}from"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-TGIB24K4.js";import{n as t}from"./chunk-NNF6KCHD.js";import{b as n}from"./chunk-ES2ISFJC.js";import{a as i}from"./chunk-FTQLQJQV.js";var v=n.object({profileRef:f,sourceRevision:n.string().min(1),action:n.enum(["compare","report"]),request:n.unknown(),runs:n.array(l).max(1e4),comparisons:n.array(s).max(1e4),suiteRuns:n.array(u).max(1e4)}).strict();async function h(p){let o=v.parse(p);for(let e of[...o.runs,...o.comparisons,...o.suiteRuns])t(e,"Hosted evaluation evidence");let a={getProfileEvaluationRun:i(async e=>o.runs.find(r=>r.manifest.id===e)??null,"getProfileEvaluationRun"),getProfileEvaluationComparison:i(async e=>o.comparisons.find(r=>r.id===e)??null,"getProfileEvaluationComparison"),getProfileEvaluationSuiteRun:i(async e=>o.suiteRuns.find(r=>r.id===e)??null,"getProfileEvaluationSuiteRun"),saveProfileEvaluationComparison:i(async(e,r)=>r,"saveProfileEvaluationComparison")};return o.action==="compare"?m({store:a,selectedProfile:i(async()=>({ref:o.profileRef,sourceRevision:o.sourceRevision}),"selectedProfile")})(o.request):c({store:a,profileRef:o.profileRef,request:o.request})}i(h,"controlHostedProfileEvaluation");export{h as controlHostedProfileEvaluation};
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{c as R,d as P}from"./chunk-WVNN3RB2.js";import{a as E}from"./chunk-F2AG46CV.js";import{L as v,M as S,N as w,Y as y,a as h}from"./chunk-6JBWHR6T.js";import"./chunk-HK3WGUKK.js";import"./chunk-6MI4KKWF.js";import"./chunk-5ZZM3TUN.js";import"./chunk-6FA3GG5B.js";import{k as g}from"./chunk-JO7GRBOG.js";import{h as m}from"./chunk-BQNK2NMB.js";import"./chunk-VW7D3DRM.js";import"./chunk-L4BYPZ4U.js";import"./chunk-P653BXMY.js";import{b as s}from"./chunk-ES2ISFJC.js";import{a as n}from"./chunk-FTQLQJQV.js";var I=s.object({profileRef:v,inspection:R,run:E.nullable(),receipts:s.array(g).max(1e4),grades:s.array(m).max(1e4),sessions:s.array(S).max(1e4),turns:s.array(w).max(1e4),events:s.array(h).max(1e4),usage:s.array(y).max(1e4)}).strict();async function x(c){let t=I.parse(c),o=n((e,i)=>{let f=new Map;for(let p of e){let d=i(p);if(f.has(d))throw new Error("Hosted evaluation inspection has duplicate evidence identities.");f.set(d,p)}return f},"map"),r=o(t.receipts,e=>e.id),u=o(t.grades,e=>e.contentHash),l=o(t.sessions,e=>e.id),a=o(t.turns,e=>e.id);return P({profileRef:t.profileRef,...t.inspection,store:{getProfileEvaluationRun:n(async e=>t.run?.manifest.id===e?t.run:null,"getProfileEvaluationRun"),getProfileEvaluationReceipt:n(async e=>r.get(e)??null,"getProfileEvaluationReceipt"),getProfileEvaluationGrade:n(async e=>u.get(e)??null,"getProfileEvaluationGrade"),getSession:n(async e=>l.get(e)??null,"getSession"),getTurn:n(async e=>a.get(e)??null,"getTurn"),runtimeEventsForTurn:n(async e=>t.events.filter(i=>i.turnId===e),"runtimeEventsForTurn"),listModelUsageRecords:n(async e=>t.usage.filter(i=>(!e?.sessionId||i.sessionId===e.sessionId)&&(!e?.turnId||i.turnId===e.turnId)),"listModelUsageRecords")}})}n(x,"inspectHostedProfileEvaluation");async function B(c){if(c.length!==0)throw new Error("Hosted evaluation inspection uses bounded standard input.");let t=[],o=0;for await(let l of process.stdin){let a=Buffer.from(l);if(o+=a.length,o>32*1024*1024)throw new Error("Hosted evaluation inspection input is too large.");t.push(a)}let r=JSON.parse(Buffer.concat(t).toString("utf8")),u=r.action==="compare"||r.action==="report"?await(await import("./hosted-profile-evaluation-control-LV6YXOG7.js")).controlHostedProfileEvaluation(r):await x(r);process.stdout.write(`${JSON.stringify(u)}
2
+ import{c as R,d as P}from"./chunk-EPY7M5XS.js";import{a as E}from"./chunk-7YR6CBNU.js";import{L as v,M as S,N as w,Y as y,a as h}from"./chunk-XDMUD4FW.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import{k as g}from"./chunk-WV2APYWG.js";import{h as m}from"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import{b as s}from"./chunk-ES2ISFJC.js";import{a as n}from"./chunk-FTQLQJQV.js";var I=s.object({profileRef:v,inspection:R,run:E.nullable(),receipts:s.array(g).max(1e4),grades:s.array(m).max(1e4),sessions:s.array(S).max(1e4),turns:s.array(w).max(1e4),events:s.array(h).max(1e4),usage:s.array(y).max(1e4)}).strict();async function x(c){let t=I.parse(c),o=n((e,i)=>{let f=new Map;for(let p of e){let d=i(p);if(f.has(d))throw new Error("Hosted evaluation inspection has duplicate evidence identities.");f.set(d,p)}return f},"map"),r=o(t.receipts,e=>e.id),u=o(t.grades,e=>e.contentHash),l=o(t.sessions,e=>e.id),a=o(t.turns,e=>e.id);return P({profileRef:t.profileRef,...t.inspection,store:{getProfileEvaluationRun:n(async e=>t.run?.manifest.id===e?t.run:null,"getProfileEvaluationRun"),getProfileEvaluationReceipt:n(async e=>r.get(e)??null,"getProfileEvaluationReceipt"),getProfileEvaluationGrade:n(async e=>u.get(e)??null,"getProfileEvaluationGrade"),getSession:n(async e=>l.get(e)??null,"getSession"),getTurn:n(async e=>a.get(e)??null,"getTurn"),runtimeEventsForTurn:n(async e=>t.events.filter(i=>i.turnId===e),"runtimeEventsForTurn"),listModelUsageRecords:n(async e=>t.usage.filter(i=>(!e?.sessionId||i.sessionId===e.sessionId)&&(!e?.turnId||i.turnId===e.turnId)),"listModelUsageRecords")}})}n(x,"inspectHostedProfileEvaluation");async function B(c){if(c.length!==0)throw new Error("Hosted evaluation inspection uses bounded standard input.");let t=[],o=0;for await(let l of process.stdin){let a=Buffer.from(l);if(o+=a.length,o>32*1024*1024)throw new Error("Hosted evaluation inspection input is too large.");t.push(a)}let r=JSON.parse(Buffer.concat(t).toString("utf8")),u=r.action==="compare"||r.action==="report"?await(await import("./hosted-profile-evaluation-control-7B3RAZU2.js")).controlHostedProfileEvaluation(r):await x(r);process.stdout.write(`${JSON.stringify(u)}
3
3
  `)}n(B,"runHostedProfileInspectionCli");export{x as inspectHostedProfileEvaluation,B as runHostedProfileInspectionCli};
@@ -0,0 +1,3 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{a as V}from"./chunk-LVL4TIAO.js";import{c as E,f as j,h as D}from"./chunk-DFM5JTS2.js";import{k as x}from"./chunk-VOIH2BQA.js";import{a as b}from"./chunk-T5LE6R5S.js";import"./chunk-QJRXTIOC.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-7K72KS5C.js";import{ha as I,qa as C}from"./chunk-7MXZJQS7.js";import"./chunk-7YR6CBNU.js";import"./chunk-5CMKGD43.js";import"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import"./chunk-XDMUD4FW.js";import{ta as m}from"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import{Ca as S}from"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import{ma as H}from"./chunk-PJM2G7SG.js";import{Ga as y,j as P,m as R}from"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import{m as d}from"./chunk-NNF6KCHD.js";import{b as e}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as s}from"./chunk-FTQLQJQV.js";import{readFile as h,realpath as z,lstat as A}from"node:fs/promises";import l from"node:path";var B=e.object({compile:e.object({repoPath:e.string(),profileId:e.string(),repositoryId:e.string(),sourceRevision:e.string(),workspaceId:e.string(),outputDir:e.string()}).strict(),externalDatasetPackage:e.string().regex(/^external-dataset-[a-f0-9-]+\.json$/).optional(),sourceCandidate:H.optional(),action:e.enum(["catalog","prepare"]),request:e.unknown().optional()}).strict();async function G(t){let o=await V(t.compile);if(t.sourceCandidate){let a=await C({workspaceId:typeof o.agentSnapshot.metadata.workspaceId=="string"?o.agentSnapshot.metadata.workspaceId:o.workspaceId,sourceDir:l.join(o.bundlePath,"source")});if(d(t.sourceCandidate.harnessRelease)!==d({id:o.harnessRelease.id,contentHash:o.harnessRelease.contentHash})||b(a).protectedClosureHash!==t.sourceCandidate.protectedClosureHash)throw new Error("Private candidate source differs from its actual frozen compiled release.")}let g={release:I.parse({schemaVersion:"openpond.localHarnessReleaseRecord.v1",workspaceId:o.workspaceId,sourceRevision:o.sourceRevision,agentSnapshot:P.parse(o.agentSnapshot),harnessRelease:R.parse(o.harnessRelease),bundlePath:o.bundlePath,createdAt:new Date().toISOString()})},p={source:"openpond_git",profileId:t.compile.profileId,repositoryId:t.compile.repositoryId},f=t.compile.sourceRevision,c={id:o.harnessRelease.id,contentHash:o.harnessRelease.contentHash},w=s(async a=>x({...a,runtime:g}),"loadCatalog"),q=await w({ref:p,sourceRevision:f,harnessRelease:c}),k=l.join(o.bundlePath,"source"),v=o.harnessRelease.files.some(a=>a.path==="workflows/catalog.json")?await(async()=>{let a=y({agentSnapshot:o.agentSnapshot,harnessRelease:o.harnessRelease,catalogBytes:await h(l.join(k,"workflows/catalog.json")),actionBytes:await h(l.join(k,"workflows/actions.json"))});return a.catalog.workflows.map(r=>({workflow:r,binding:{schemaVersion:"openpond.profileWorkflowBinding.v1",profileId:p.profileId,sourceRevision:f,harnessRelease:c,catalogHash:a.catalogHash,workflowId:r.id}}))})():[],T={profileRef:p,sourceRevision:f,harnessRelease:c,workflows:v};if(t.action==="catalog")return{...q,workflows:v};let u=t.externalDatasetPackage?await(async()=>{let a=await z(t.compile.outputDir),r=l.join(a,t.externalDatasetPackage),i=await A(r);if(!i.isFile()||i.isSymbolicLink()||i.size>32*1024*1024||await z(r)!==r)throw new Error("External Dataset cache is outside its bounded verifier storage.");let n=e.object({packageValue:e.unknown(),graders:e.array(e.object({id:e.string(),version:e.string(),contentHash:e.string(),feedbackKey:e.string(),release:e.object({id:e.string(),revision:e.union([e.string(),e.number()]),contentHash:e.string()}).strict().nullable()}).strict()).max(100)}).strict().parse(JSON.parse(await h(r,"utf8")));return{packageValue:S(n.packageValue),graders:n.graders}})():null;return D({privateGradingPreflight:s(a=>E(a,!1),"privateGradingPreflight"),sourceCandidate:t.sourceCandidate,resolveExternalDataset:u?async a=>{let r=m({binding:a,...u}),i=d(o.harnessRelease.files.filter(n=>n.visibility!=="policy").map(n=>({path:n.path,asset:n})));if(a.protectedProfileClosureHash!==i)throw new Error("The selected Profile's protected evaluator closure changed.");return{binding:a,packageValue:r,authorize:s(async()=>{m({binding:a,...u})},"authorize")}}:void 0,loadCatalog:w,selectedWorkflows:s(async()=>T,"selectedWorkflows"),placement:"remote",loadTasksetPackage:s(async a=>{let r=await j({runtime:g,definition:a,harnessRelease:c});if(!r)throw new Error("Hosted evaluation Taskset is absent from its published Profile release.");return r},"loadTasksetPackage"),modelConfigurationHash:s(async(a,r)=>{if(a.providerId!=="openpond"||!r.hostModelConfigurationHash)throw new Error("Hosted evaluation preparation requires a trusted model configuration receipt.");return r.hostModelConfigurationHash},"modelConfigurationHash")})(t.request)}s(G,"prepareHostedProfileEvaluation");async function ae(t){if(t.length!==1||t[0].length>48e3||!/^[A-Za-z0-9_-]+$/.test(t[0]))throw new Error("Hosted Profile evaluation preparation argument is invalid.");let o=B.parse(JSON.parse(Buffer.from(t[0],"base64url").toString("utf8")));process.stdout.write(`${JSON.stringify(await G(o))}
3
+ `)}s(ae,"runHostedProfileEvaluationCli");export{G as prepareHostedProfileEvaluation,ae as runHostedProfileEvaluationCli};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as E,c as S}from"./chunk-NPOHW5OU.js";import"./chunk-XLDW5NN3.js";import{c as I}from"./chunk-USWZ3KUC.js";import{c as x,f as y}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-EWS7MXTM.js";import"./chunk-TYWBEJOA.js";import{c as n}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import{u as R}from"./chunk-4UTIEH5H.js";import"./chunk-LZSY5IM3.js";import{d as g}from"./chunk-6SJZXZNA.js";import{b}from"./chunk-GLUWATL5.js";import"./chunk-H6W55CQG.js";import"./chunk-Z3D4C7BG.js";import{z as v}from"./chunk-JO7GRBOG.js";import{E as w,F as f,O as p,P as h}from"./chunk-BQNK2NMB.js";import"./chunk-VW7D3DRM.js";import"./chunk-UWO34HP6.js";import"./chunk-L4BYPZ4U.js";import{l as u}from"./chunk-P653BXMY.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as m}from"./chunk-FTQLQJQV.js";import{readFile as A,stat as L}from"node:fs/promises";async function C(r,l){let[o,a]=l,i=n(r,"team"),q=r.local===!0||r.local==="true";if(!i||!o||l.length>2)throw new Error("usage: human-review <read|inbox|inspect|results|request> [id] --team <id> [--input-file <path>] [--local --server-url <loopback-origin>]");let t;if(o==="request"){let e=n(r,"inputFile");if(a||!e||(await L(e)).size>1048576)throw new Error("Request requires a bounded --input-file with exact scoped pins, revision and stable operationId for mutations.");if(t=p.parse(JSON.parse(await A(e,"utf8"))),t.scope!==i)throw new Error("Input belongs to another workspace.")}else if(o==="inbox"){if(a)throw new Error("Inbox does not accept an assignment id.");t=p.parse({endpoint:"inbox",scope:i,view:n(r,"view")||"mine",status:n(r,"status")||"active",limit:Number(n(r,"limit")||100),...n(r,"project")?{projectId:n(r,"project")}:{},...n(r,"afterId")?{afterId:n(r,"afterId")}:{}})}else{if(!a)throw new Error(`${o} requires an exact assignment or execution id.`);t=p.parse(o==="read"?{endpoint:"get",scope:i,id:a,...n(r,"revision")?{revision:Number(n(r,"revision"))}:{}}:o==="inspect"?{endpoint:"inspect",scope:i,id:a,...n(r,"slot")?{slot:Number(n(r,"slot"))}:{},...n(r,"afterId")?{afterId:n(r,"afterId")}:{}}:o==="results"?{endpoint:"results",scope:i,executionId:a}:{endpoint:o,scope:i,id:a})}let s;if(q){let e=new URL(n(r,"serverUrl")||E);if(e.protocol!=="http:"||!["localhost","127.0.0.1","[::1]"].includes(e.hostname)||e.username||e.password||e.search||e.hash||e.pathname!=="/")throw new Error("Local Human review requires an HTTP loopback server origin.");let c=await S(e.origin),d=await c(new URL("/v1/human-review?location=local",e),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),redirect:"error",signal:AbortSignal.timeout(3e4)}),H=await U(d);if(s=JSON.parse(H),!d.ok)throw new Error(typeof s.error=="string"?s.error:`Local Human request failed (${d.status}).`)}else{let e=await g();s=await new R({scope:i,apiKey:await I(e,y(e)),baseUrl:x(r)??e.apiBaseUrl??b}).request(t,AbortSignal.timeout(3e4))}if(t.endpoint==="get"||t.endpoint==="command"){let e=w.parse(s),c=t.endpoint==="get"?t.id:t.command.id;if(e.id!==c||e.scope!==i)throw new Error("Review response differs from the requested identity.")}if(t.endpoint==="inbox"&&f.parse(s).items.some(c=>c.scope!==i||t.projectId&&c.projectId!==t.projectId))throw new Error("Inbox response differs from the requested scope.");if(t.endpoint==="inspect"&&h.parse(s).some(e=>e.reviewId!==t.id))throw new Error("Inspection response differs from the selected assignment.");if(t.endpoint==="results"){let e=v.parse(s),{contentHash:c,...d}=e;if(e.executionId!==t.executionId||u(d)!==c||t.selection!==void 0&&u(e.selection)!==u(t.selection))throw new Error("Result response differs from the selected execution or retained review revisions.")}console.log(JSON.stringify(s,null,2))}m(C,"runHumanReviewCommand");async function U(r){let l=r.body?.getReader();if(!l)throw new Error("Review response is unavailable.");let o=[],a=0;try{for(;;){let i=await l.read();if(i.done)break;if(a+=i.value.byteLength,a>8388608)throw new Error("Review response exceeds its bounded transport.");o.push(i.value)}}finally{await l.cancel(),l.releaseLock()}return Buffer.concat(o).toString("utf8")}m(U,"boundedResponse");export{C as runHumanReviewCommand};
2
+ import{a as E,c as S}from"./chunk-NPOHW5OU.js";import"./chunk-N3DEA6PG.js";import{c as I}from"./chunk-PA7XP42P.js";import{c as x,f as y}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-RLZPX4YP.js";import"./chunk-Q4H3NUVW.js";import{c as n}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import{u as R}from"./chunk-2SPZYBDN.js";import"./chunk-QXVIIM4T.js";import{d as g}from"./chunk-R3XFY7VL.js";import{b}from"./chunk-GLUWATL5.js";import"./chunk-YL6VFJ4P.js";import"./chunk-Z3D4C7BG.js";import{z as v}from"./chunk-WV2APYWG.js";import{E as w,F as f,O as p,P as h}from"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import{m as u}from"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as m}from"./chunk-FTQLQJQV.js";import{readFile as A,stat as L}from"node:fs/promises";async function C(r,l){let[o,a]=l,i=n(r,"team"),q=r.local===!0||r.local==="true";if(!i||!o||l.length>2)throw new Error("usage: human-review <read|inbox|inspect|results|request> [id] --team <id> [--input-file <path>] [--local --server-url <loopback-origin>]");let t;if(o==="request"){let e=n(r,"inputFile");if(a||!e||(await L(e)).size>1048576)throw new Error("Request requires a bounded --input-file with exact scoped pins, revision and stable operationId for mutations.");if(t=p.parse(JSON.parse(await A(e,"utf8"))),t.scope!==i)throw new Error("Input belongs to another workspace.")}else if(o==="inbox"){if(a)throw new Error("Inbox does not accept an assignment id.");t=p.parse({endpoint:"inbox",scope:i,view:n(r,"view")||"mine",status:n(r,"status")||"active",limit:Number(n(r,"limit")||100),...n(r,"project")?{projectId:n(r,"project")}:{},...n(r,"afterId")?{afterId:n(r,"afterId")}:{}})}else{if(!a)throw new Error(`${o} requires an exact assignment or execution id.`);t=p.parse(o==="read"?{endpoint:"get",scope:i,id:a,...n(r,"revision")?{revision:Number(n(r,"revision"))}:{}}:o==="inspect"?{endpoint:"inspect",scope:i,id:a,...n(r,"slot")?{slot:Number(n(r,"slot"))}:{},...n(r,"afterId")?{afterId:n(r,"afterId")}:{}}:o==="results"?{endpoint:"results",scope:i,executionId:a}:{endpoint:o,scope:i,id:a})}let s;if(q){let e=new URL(n(r,"serverUrl")||E);if(e.protocol!=="http:"||!["localhost","127.0.0.1","[::1]"].includes(e.hostname)||e.username||e.password||e.search||e.hash||e.pathname!=="/")throw new Error("Local Human review requires an HTTP loopback server origin.");let c=await S(e.origin),d=await c(new URL("/v1/human-review?location=local",e),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),redirect:"error",signal:AbortSignal.timeout(3e4)}),H=await U(d);if(s=JSON.parse(H),!d.ok)throw new Error(typeof s.error=="string"?s.error:`Local Human request failed (${d.status}).`)}else{let e=await g();s=await new R({scope:i,apiKey:await I(e,y(e)),baseUrl:x(r)??e.apiBaseUrl??b}).request(t,AbortSignal.timeout(3e4))}if(t.endpoint==="get"||t.endpoint==="command"){let e=w.parse(s),c=t.endpoint==="get"?t.id:t.command.id;if(e.id!==c||e.scope!==i)throw new Error("Review response differs from the requested identity.")}if(t.endpoint==="inbox"&&f.parse(s).items.some(c=>c.scope!==i||t.projectId&&c.projectId!==t.projectId))throw new Error("Inbox response differs from the requested scope.");if(t.endpoint==="inspect"&&h.parse(s).some(e=>e.reviewId!==t.id))throw new Error("Inspection response differs from the selected assignment.");if(t.endpoint==="results"){let e=v.parse(s),{contentHash:c,...d}=e;if(e.executionId!==t.executionId||u(d)!==c||t.selection!==void 0&&u(e.selection)!==u(t.selection))throw new Error("Result response differs from the selected execution or retained review revisions.")}console.log(JSON.stringify(s,null,2))}m(C,"runHumanReviewCommand");async function U(r){let l=r.body?.getReader();if(!l)throw new Error("Review response is unavailable.");let o=[],a=0;try{for(;;){let i=await l.read();if(i.done)break;if(a+=i.value.byteLength,a>8388608)throw new Error("Review response exceeds its bounded transport.");o.push(i.value)}}finally{await l.cancel(),l.releaseLock()}return Buffer.concat(o).toString("utf8")}m(U,"boundedResponse");export{C as runHumanReviewCommand};
@@ -0,0 +1,4 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{a as D,b as ce,c as de,d as le,e as M,f as X,g as J,h as L,i as Z,j as B,k as z,l as P,m as ee,n as te,o as ue,p as se,q as pe,r as G}from"./chunk-PYABBF53.js";import{k as W}from"./chunk-N3DEA6PG.js";import{a as we}from"./chunk-PA7XP42P.js";import{c as ve,f as ye}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-RLZPX4YP.js";import"./chunk-Q4H3NUVW.js";import{c as E,f as H}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import{p as fe,q as me,r as F}from"./chunk-2SPZYBDN.js";import"./chunk-QXVIIM4T.js";import{d as Y,g as he}from"./chunk-R3XFY7VL.js";import{b as ge}from"./chunk-GLUWATL5.js";import"./chunk-YL6VFJ4P.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import{l as ae,m as T}from"./chunk-NNF6KCHD.js";import{b as I}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as p}from"./chunk-FTQLQJQV.js";import{createInterface as qe}from"node:readline/promises";import{resolve as Ue}from"node:path";import{watch as Pe}from"node:fs";import{randomUUID as je}from"node:crypto";var Me=["source","admission","control","heartbeat"],j=class{static{p(this,"CollectorErrors")}store;constructor(e){this.store=e}read(e){let o=this.store.setting(`errors:${e}`);if(o)return JSON.parse(o);let s=this.store.database.prepare("SELECT error FROM backfill_units WHERE connection_id=? AND state='error' AND error IS NOT NULL ORDER BY session_key LIMIT 1").get(e);return typeof s?.error=="string"?{source:s.error}:{}}message(e,o){let s=this.read(e);return Me.filter(r=>r!==o).map(r=>s[r]).find(Boolean)??null}source(e){return this.read(e).source??null}set(e,o,s){let r=this.read(e);s?r[o]=s.slice(0,500):delete r[o],this.store.set(`errors:${e}`,JSON.stringify(r)),this.store.error(e,this.message(e))}};var Le=I.object({leafId:I.string().min(1).max(200),chainHash:I.string().regex(/^[a-f0-9]{64}$/),sourceInstanceId:I.string().min(1)}).strict(),Se=p((t,e)=>`branch:${JSON.stringify([t,e])}`,"key");function be(t,e,o){let s=t.setting(Se(e,o));if(!s)return;let r=Le.parse(JSON.parse(s));return t.connections().find(g=>g.id===e)?.source.instanceId===r.sourceInstanceId?{leafId:r.leafId,chainHash:r.chainHash}:void 0}p(be,"collectorBranchAnchor");async function Ie(t,e){if(t.source!=="claude_code")throw new Error("Branch selection is currently supported for Claude Code.");let o,s=[];do{let r=await M(t,{cursor:o,limit:100});s.push(...r.items.filter(a=>a.nativeSessionId===e)),o=r.nextCursor??void 0}while(o);if(s.length!==1)throw new Error("Select exactly one native session in this connection's source location.");return s[0]}p(Ie,"findSession");async function Re(t,e,o){let s=await B.open(t);try{let r=s.connections().find(g=>g.id===e);if(!r)throw new Error("Select a connection from openpond import status.");let a=await Ie(r.source,o);return{session:a,...await X(r.source,a)}}finally{s.close()}}p(Re,"inspectCollectorBranches");async function Ce(t,e,o,s){let r=await B.open(t);try{let a=r.connections().find(u=>u.id===e);if(!a||a.state!=="paused")throw new Error(`Pause this connection first: openpond import pause ${e}`);let g=await Ie(a.source,o),c=await X(a.source,g),l=c.branches.find(u=>u.leafId===s.leafId);if(c.revision!==s.revision||!l)throw new Error("This conversation changed. Refresh its branches and choose again.");await J(a.source,g,{branchLeafId:s.leafId,expectedBranchRevision:s.revision}),r.database.exec("BEGIN IMMEDIATE");try{let u=r.connections().find(S=>S.id===e);if(!u||u.state!=="paused"||u.revision!==a.revision||u.source.instanceId!==a.source.instanceId)throw new Error("Connection changed during branch selection. Refresh and try again.");r.set(Se(e,o),JSON.stringify({leafId:l.leafId,chainHash:l.chainHash,sourceInstanceId:a.source.instanceId}));for(let S of["source_scans","checkpoints","pending"])r.database.prepare(`DELETE FROM ${S} WHERE connection_id=?`).run(e);let v=new j(r);v.set(e,"source",v.source(e)),r.progress.reset(e),v.set(e,"admission",null),r.database.exec("COMMIT")}catch(u){throw r.database.exec("ROLLBACK"),u}return{connectionId:e,nativeSessionId:o,leafId:l.leafId,state:"paused"}}finally{r.close()}}p(Ce,"selectCollectorBranch");var V=class{static{p(this,"CollectorSyncRequests")}store;acquisitions=new Map;constructor(e){this.store=e}observe(e,o){let s=o.requestedSyncRevision??e.requestedSyncRevision??0,r=o.completedSyncRevision??0;if(!Number.isSafeInteger(s)||s<0||s>o.revision||!Number.isSafeInteger(r)||r<0||r>s)throw new Error("Invalid remote sync acknowledgement.");let a=this.confirmed(e.id);return r>a&&this.store.set(`syncAcknowledged:${e.id}`,String(r)),{requestedSyncRevision:Math.max(e.requestedSyncRevision??0,s),completedSyncRevision:Math.max(e.completedSyncRevision??0,r)}}needsAcquisition(e){let o=e.requestedSyncRevision??0;if(o<=(e.completedSyncRevision??0))return!1;let s=this.acquisitions.get(e.id);return s?.controlRevision!==e.revision||s.requestedSyncRevision!==o}acquired(e,o){this.acquisitions.set(e,o)}complete(e,o){let s=this.acquisitions.get(e.id),r=e.requestedSyncRevision??0;if(e.state!=="active"||this.store.setting("desiredState")!=="running"||this.store.queued(e.id)||o||!s?.succeeded||s.controlRevision!==e.revision||s.requestedSyncRevision!==r||r<=(e.completedSyncRevision??0))return e;let a={...e,completedSyncRevision:r};return this.store.put(a),a}confirmed(e){return Number(this.store.setting(`syncAcknowledged:${e}`))||0}needsAcknowledgement(e){return(e.completedSyncRevision??0)>this.confirmed(e.id)}};async function Ee(t){let e=await B.open(t.directory),o=je();e.database.exec("BEGIN IMMEDIATE");try{let i=e.setting("owner");if(i){let f=JSON.parse(i),h=!0;try{process.kill(f.pid,0)}catch(n){h=n.code!=="ESRCH"}if(h)throw new Error("The collector already has a live owner.")}e.set("owner",JSON.stringify({pid:process.pid,nonce:o})),e.database.exec("COMMIT")}catch(i){throw e.database.exec("ROLLBACK"),e.close(),i}if(e.setting("desiredState")!=="running"){e.set("owner",""),e.close();return}e.set("pid",String(process.pid));let s=!0,r=0,a=0,g=new Map,c=new j(e),l=new V(e),u=new Map;function v(i){return e.connections().find(f=>f.id===i.id)??i}p(v,"retained");function S(i){let f=e.queued(i.id),h=c.message(i.id,"heartbeat");return{pendingOperations:f,error:h,completedSyncRevision:!f&&!h?i.completedSyncRevision??0:0}}p(S,"heartbeatInput");function d(i,f){let h=v(i);if(h.state==="disconnected"||f.revision<h.revision)return h;let n=l.observe(h,f);f.revision>h.revision&&c.set(h.id,"control",null);let m={...h,...n,...f.revision>h.revision?{revision:f.revision,state:f.state}:{},...f.destinations?{destinations:f.destinations}:{}};return e.put(m),m}p(d,"applyRemote");function R(i,f,h){let n=f instanceof Error?f.message:"Collection failed.";c.set(i.id,h,n);let m=f&&typeof f=="object"&&"status"in f?Number(f.status):0,C=v(i);C.state!=="disconnected"&&[400,401,403].includes(m)&&e.put({...C,state:m===400?"paused":"disconnected"})}p(R,"recordFailure");async function N(i){let f=i.revision,h=i.requestedSyncRevision??0,n,m=[];do{if(Date.now()-a>=L.heartbeatMs){a=Date.now(),e.set("heartbeatAt",new Date().toISOString());for(let w of e.connections())if(w.state!=="disconnected")try{let x=await t.transport.heartbeat(w,S(w));d(w,x),c.set(w.id,"heartbeat",null)}catch(x){R(w,x,"heartbeat")}}if(i=e.connections().find(w=>w.id===i.id)??i,i.state!=="active"||t.signal.aborted||e.setting("desiredState")!=="running")return;let C=await M(i.source,{since:i.since??void 0,cursor:n,limit:50});for(let w of C.items){let x=JSON.stringify([w.path,w.nativeSessionId]),O=w.storageRevision?T([w.storageRevision,de(i.source.source)]):null;if(e.progress.select(i.id,x),t.signal.aborted||e.setting("desiredState")!=="running"||e.connections().find(y=>y.id===i.id)?.state!=="active")return;try{if(O&&!e.sourceChanged(i.id,x,O)&&!e.progress.tracks(i.id,x))continue;let{files:y,preview:b,branchLeafId:k}=await J(i.source,w,{branchAnchor:be(e,i.id,w.nativeSessionId)}),$=!1;for(let q of b.sessions){let _=JSON.stringify([i.source.instanceId,q.sessionId,q.branchId]);e.progress.retained(i.id,x,_);let ne=q.boundaries.filter(A=>A.projection==="turn"&&A.terminal!=="unknown"&&(!i.since||Date.parse(q.events[A.start].occurredAt??w.updatedAt)>=Date.parse(i.since)));$||=ne.length>0;let ie=ne.filter(A=>e.changed(i.id,_,A.id,T([A.inputHash,A.revisionHash])));for(let A=0;A<ie.length;A+=L.batchCases){let Q=ie.slice(A,A+L.batchCases),De=`sync-${T([i.id,_,Q.map(U=>[U.id,U.inputHash,U.revisionHash])]).slice(0,48)}`;e.enqueue({operationId:De,connectionId:i.id,sessionKey:_,contentHash:q.contentHash,files:y,boundaryIds:Q.map(U=>U.id),...k?{branchLeafId:k}:{}},Q.map(U=>({id:U.id,revision:T([U.inputHash,U.revisionHash])})),x)}}e.progress.read(i.id,x,$),O&&e.scanned(i.id,x,O)}catch(y){if(y instanceof le){e.progress.read(i.id,x,!1),O&&e.scanned(i.id,x,O);continue}e.progress.failed(i.id,x,y instanceof Error?y.message:"Unable to read session"),m.push(`${w.nativeSessionId}: ${y instanceof Error?y.message:"Unable to read session"}`)}}n=C.nextCursor??void 0}while(n);e.progress.discovered(i.id),u.set(i.id,f),l.acquired(i.id,{controlRevision:f,requestedSyncRevision:h,succeeded:m.length===0}),c.set(i.id,"source",m.length?`${m.length} session(s) need attention. ${m[0]}`:null)}p(N,"acquire");try{for(;!t.signal.aborted&&e.setting("desiredState")==="running";){let i=e.connections();e.set("heartbeatAt",new Date().toISOString());for(let n of i)if(n.state!=="disconnected"&&!g.has(n.source.root))try{let m=Pe(n.source.root,{recursive:n.source.acquisition!=="sqlite"},()=>{s=!0});m.on("error",()=>{s=!0}),g.set(n.source.root,m)}catch{}let f=Date.now()-a>=L.heartbeatMs;f&&(a=Date.now());let h=s||Date.now()-r>=L.reconcileMs||e.setting("syncNow")==="yes";h&&(s=!1,r=Date.now(),e.set("syncNow","no"));for(let n of i){if(n=v(n),n.state==="disconnected")continue;let m="heartbeat";try{if(f){let w=await t.transport.heartbeat(n,S(n));n=d(n,w),c.set(n.id,"heartbeat",null)}if(n.state!=="active"){u.delete(n.id);continue}if(m="source",(h||u.get(n.id)!==n.revision||l.needsAcquisition(n))&&await N(n),n=e.connections().find(w=>w.id===n.id)??n,n.state!=="active"||t.signal.aborted||e.setting("desiredState")!=="running")continue;m="admission";let C=e.next(n.id);if(C)try{await t.transport.admit(n,C.entry),e.acknowledge(C.entry),c.set(n.id,"admission",null)}catch(w){throw e.retry(C.entry.operationId,C.attempts),w}if(n=v(n),t.signal.aborted||e.setting("desiredState")!=="running"||n.state!=="active")continue;if(n=l.complete(n,c.message(n.id,"heartbeat")),l.needsAcknowledgement(n)&&S(n).completedSyncRevision){m="heartbeat";let w=await t.transport.heartbeat(n,S(n));n=d(n,w),c.set(n.id,"heartbeat",null)}if(!t.signal.aborted&&e.setting("desiredState")==="running"&&n.state==="active"&&!n.keepSyncing&&u.get(n.id)===n.revision&&e.queued(n.id)===0&&e.progress.status(n.id).stage==="complete"&&!c.source(n.id)&&l.confirmed(n.id)>=(n.requestedSyncRevision??0)){if(m="control",!t.transport.pause)throw new Error("This transport cannot acknowledge completion of a one-time import.");let w=await t.transport.pause(n);d(n,w),c.set(n.id,"control",null)}}catch(C){R(n,C,m)}}await new Promise(n=>{let m=p(()=>{clearTimeout(C),t.signal.removeEventListener("abort",m),n()},"done"),C=setTimeout(m,1e3);t.signal.addEventListener("abort",m,{once:!0})})}}finally{for(let f of g.values())f.close();JSON.parse(e.setting("owner")||"{}").nonce===o&&(e.set("pid",""),e.set("heartbeatAt",""),e.set("owner","")),e.close()}}p(Ee,"runCollector");import{createHash as Ne,generateKeyPairSync as Ke,createPublicKey as _e,diffieHellman as Je,createDecipheriv as ze}from"node:crypto";import{spawn as Ge}from"node:child_process";var xe=p(t=>Ne("sha256").update(t).digest("hex"),"hash"),Fe=I.object({publicKey:I.string().max(200),iv:I.string().max(100),tag:I.string().max(100),ciphertext:I.string().max(1e4)}).strict();async function re(t,e,o){let s=await fetch(`${t}${e}`,{method:"POST",redirect:"error",signal:AbortSignal.timeout(15e3),headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),r=await s.text();if(r.length>16384)throw new Error("Authorization response exceeded its limit.");if(!s.ok)throw Object.assign(new Error(`Browser sign-in failed (${s.status}).`),{status:s.status});return JSON.parse(r)}p(re,"post");function Ye(t){let e=process.platform==="darwin"?"open":process.platform==="win32"?"rundll32":"xdg-open",o=process.platform==="win32"?["url.dll,FileProtocolHandler",t]:[t],s=Ge(e,o,{stdio:"ignore",detached:!0});s.on("error",()=>{}),s.unref()}p(Ye,"openBrowser");async function Oe(t,e){let o=await Y(),s=ve(e)||o.apiBaseUrl||ge,r=E(e,"baseUrl")||(new URL(s).hostname==="staging-api.openpond.ai"?"https://staging.openpond.ai":ye(o)),a=new URL(r),g=new URL(s);for(let d of[a,g])if(d.protocol!=="https:"&&!(d.protocol==="http:"&&["localhost","127.0.0.1"].includes(d.hostname))||d.username||d.password||d.search||d.hash)throw new Error("Sign-in requires a clean HTTPS origin or local development origin.");let c=`import-${xe([a.origin,t.machineId,t.instanceId].join(":")).slice(0,24)}`,l=Ke("x25519"),u=l.publicKey.export({format:"der",type:"spki"}).toString("base64"),v=I.object({deviceCode:I.string(),userCode:I.string(),expiresAt:I.string().datetime(),intervalSeconds:I.number().min(2).max(10)}).strict().parse(await re(a.origin,"/api/cli/import/device",{publicKey:u,machineId:t.machineId,sourceInstanceId:t.instanceId,sourceLabel:D[t.source],sourceRoot:t.root,...E(e,"team")?{requestedTeamId:E(e,"team")}:{}})),S=`${a.origin}/console/connections/authorize?code=${encodeURIComponent(v.userCode)}`;for(console.log(`OpenPond sign-in code: ${v.userCode}
3
+ ${S}`),Ye(S);Date.now()<Date.parse(v.expiresAt);){await new Promise(m=>setTimeout(m,v.intervalSeconds*1e3));let d;try{d=await re(a.origin,"/api/cli/import/token",{deviceCode:v.deviceCode})}catch(m){if(Number(m.status)===429)continue;throw m}let R=I.object({state:I.enum(["pending","approved","denied","consumed"]),envelope:Fe.nullable().optional()}).strict().parse(d);if(R.state==="denied"||R.state==="consumed")throw new Error("Browser sign-in was declined or already consumed. Start the connection again.");if(R.state!=="approved"||!R.envelope)continue;let N=R.envelope,i=_e({key:Buffer.from(N.publicKey,"base64"),format:"der",type:"spki"});if(i.asymmetricKeyType!=="x25519")throw new Error("Invalid sign-in encryption key.");let f=Ne("sha256").update(Je({privateKey:l.privateKey,publicKey:i})).digest(),h=ze("aes-256-gcm",f,Buffer.from(N.iv,"base64"));h.setAAD(Buffer.from(xe(v.deviceCode))),h.setAuthTag(Buffer.from(N.tag,"base64"));let n=I.object({apiKey:I.string().min(1),teamId:I.string().min(1),expiresAt:I.string().datetime()}).strict().parse(JSON.parse(Buffer.concat([h.update(Buffer.from(N.ciphertext,"base64")),h.final()]).toString("utf8")));if(E(e,"team")&&n.teamId!==E(e,"team"))throw new Error("Browser approved a different workspace.");return await he({handle:c,apiKey:n.apiKey,baseUrl:a.origin,apiBaseUrl:g.origin,setActive:!1}),await re(a.origin,"/api/cli/import/token",{deviceCode:v.deviceCode,acknowledge:!0}),{apiKey:n.apiKey,teamId:n.teamId,baseUrl:g.origin,account:c,accountBaseUrl:a.origin}}throw new Error("Browser sign-in expired. Start the connection again.")}p(Oe,"authorizeImporter");async function K(t){let e=await Y({account:t.account,baseUrl:t.accountBaseUrl}),o=t.account?e.apiKey:we(e);if(!o)throw Object.assign(new Error("This source is disconnected. Reconnect it with OpenPond Importer to authorize collection."),{status:401});let s={apiKey:o,baseUrl:t.apiBaseUrl,teamId:t.teamId};return{evidence:new me(s),sync:new F(s)}}p(K,"collectorClients");var ke={async pause(t){let{sync:e}=await K(t),o=await e.control({id:t.id,expectedRevision:t.revision,action:"pause"});return{revision:o.revision,state:o.state,destinations:Z(t,o),requestedSyncRevision:o.requestedSyncRevision,completedSyncRevision:o.completedSyncRevision}},async heartbeat(t,e){let{sync:o}=await K(t),s=await o.heartbeat({id:t.id,expectedRevision:t.revision,...e});return{revision:s.revision,state:s.state,destinations:Z(t,s),requestedSyncRevision:s.requestedSyncRevision,completedSyncRevision:s.completedSyncRevision}},async admit(t,e){let{evidence:o,sync:s}=await K(t),r=AbortSignal.timeout(6e4),a=Buffer.from(JSON.stringify(e.files.map(d=>({path:d.path,encoding:"utf8",base64:Buffer.from(d.text).toString("base64")})))),g={hash:ae(a),parts:Math.ceil(a.length/2e5)};for(let d=0;d<g.parts;d++)await o.uploadPart({...g,index:d,base64:a.subarray(d*2e5,(d+1)*2e5).toString("base64")},r);let c={upload:g,source:t.source.source,...e.branchLeafId?{branchLeafId:e.branchLeafId}:{},destination:{kind:"existing",projectId:t.projectId},acquisition:{machineId:t.source.machineId,sourceInstanceId:t.source.instanceId}},l=await o.preview(c,r);if(l.issues.length)throw Object.assign(new Error("Source schema was rejected; inspect the connection before resuming."),{status:400});let u=l.sessions.find(d=>d.sessionHash===e.contentHash);if(!u||e.boundaryIds.some(d=>!u.boundaries.some(R=>R.id===d&&R.projection==="turn"&&R.terminal!=="unknown")))throw Object.assign(new Error("Server preview differs from the retained source boundaries."),{status:400});let v={...c,operationId:e.operationId,previewHash:l.previewHash,selection:[{sessionHash:u.sessionHash,boundaryIds:e.boundaryIds}]},S=fe.parse(await s.commit({connectionId:t.id,expectedRevision:t.revision,request:v},r));if(S.state!=="completed"||S.operationId!==e.operationId||S.requestHash!==T(v)||S.projectId!==t.projectId)throw new Error("Admission did not acknowledge this retained operation.")}};import{emitKeypressEvents as We}from"node:readline";async function Ae(t){console.log("Ctrl+C closes this view and keeps syncing. Ctrl+D pauses this connection.");let e=new AbortController,o=p(()=>e.abort(),"detach"),s=!1,r=process.stdin.isRaw,a=p((c,l)=>{l?.ctrl&&(l.name==="c"&&o(),l.name==="d"&&!s&&(s=!0,t.pause().then(o).catch(u=>{console.error(`
4
+ Unable to pause: ${u instanceof Error?u.message:"connection update failed"}`),s=!1})))},"keypress");We(process.stdin),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("keypress",a),process.stdin.once("end",o),process.once("SIGINT",o);let g=0;try{for(;!e.signal.aborted;){let c=await P(t.directory),l=c.connections.find(f=>f.id===t.connectionId);if(!l)break;let u=l.backfill,v=u.admitted+u.skipped,S=u.total?v/u.total:u.stage==="complete"?1:0,d=Math.max(0,Math.min(20,Math.floor(S*20))),R=u.stage==="discovering"?`${["|","/","-","\\"][g++%4]} Discovering conversations (${u.total} found)`:`[${"=".repeat(d)}${" ".repeat(20-d)}] ${v}/${u.total} conversations`,N=c.running?l.state!=="active"?l.state:u.stage==="complete"?t.keepSyncing?"Watching for new conversations":"Import complete":u.stage:"Service offline",i=`${R} ${l.admitted} tasks admitted ${u.skipped} skipped ${u.failed} need attention ${l.queued} queued ${l.error||N}${l.lastAdmissionAt?` Last sync ${l.lastAdmissionAt}`:""}`;if(process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(i),!t.keepSyncing&&l.state==="paused"&&l.queued===0)break;await new Promise(f=>{let h=p(()=>{clearTimeout(n),e.signal.removeEventListener("abort",h),f()},"done"),n=setTimeout(h,1e3);e.signal.addEventListener("abort",h,{once:!0})})}}finally{process.stdin.off("keypress",a),process.stdin.off("end",o),process.off("SIGINT",o),process.stdin.setRawMode(r??!1),process.stdin.pause(),console.log()}}p(Ae,"monitorImport");async function oe(t,e){let o=await B.open(t),s;try{s=o.connections().find(r=>r.id===e)}finally{o.close()}if(!s)throw new Error("Select a retained connection from openpond import status.");if(s.source.machineId!==await G(t))throw new Error("This connection belongs to another machine. Use explicit Connect setup.");if(!s.accountBaseUrl)throw new Error("The original sign-in destination is unavailable. Use explicit Connect setup.");return s}p(oe,"retainedReconnect");function Te(t,e){if(!e?.available||!e.capabilities.history||e.source!==t.source.source||e.machineId!==t.source.machineId||e.instanceId!==t.source.instanceId||e.root!==t.source.root)throw new Error("The retained source is unavailable or its identity changed. Restore its original location or use explicit Connect setup.")}p(Te,"assertReconnectSource");async function $e(t,e){let o=await oe(t,e.id),s=p(r=>({...r,destinations:void 0,requestedSyncRevision:r.requestedSyncRevision??0,completedSyncRevision:r.completedSyncRevision??0}),"scope");if(T(s(o))!==T(s(e)))throw new Error("The connection changed during sign-in. Reconnect again after reviewing its current scope.")}p($e,"assertReconnectUnchanged");import{createInterface as Ve}from"node:readline/promises";async function Be(t,e,o,s){let r=E(s,"session");if(!o||!r)throw new Error("Use openpond import branches <connection-id> --session <native-session-id>.");let a=await Re(t,o,r);if(e==="branches"){console.log(JSON.stringify(a,null,2));return}let g=process.stdin.isTTY&&process.stdout.isTTY&&!H(s.json),c=E(s,"leaf"),l=E(s,"revision");if(!c&&g){a.branches.forEach((S,d)=>console.log(`${d+1}. ${S.title||S.leafId} (${S.messages} messages; ${S.updatedAt||"date unavailable"})`));let v=Ve({input:process.stdin,output:process.stdout});try{c=a.branches[Number(await v.question("Choose the branch to sync: "))-1]?.leafId??"",l=a.revision}finally{v.close()}}if(!c||!l)throw new Error("Supply --leaf and --revision from import branches, or choose interactively. No branch was selected.");if(!a.branches.some(v=>v.leafId===c)||l!==a.revision)throw new Error("Branch selection is stale or invalid. Run import branches again.");if(!H(s.yes)&&(!g||!await W("Sync only this branch and its unambiguous future continuation for this conversation? Other branches stay excluded.",!1)))throw new Error("Branch selection was not approved.");let u=await Ce(t,o,r,{leafId:c,revision:l});console.log(JSON.stringify({...u,next:`openpond import resume ${o}`},null,2))}p(Be,"runImporterBranchCommand");async function is(t,e){let[o="connect",s]=e,r=Ue(E(t,"collectorDir")||pe()),a=H(t.json),g=p(y=>console.log(JSON.stringify(y,null,2)),"print");if(o==="branches"||o==="branch"){await Be(r,o,s,t);return}if(o==="service"){if(s==="status"){g(await P(r));return}if(s==="stop"){g(await ee(r,"stop"));return}if(s==="uninstall"){g(await ue(r));return}if(s==="install"){g(await te({directory:r,executable:process.execPath,args:[process.argv[1]],environment:He()}));return}if(s==="start"){g(await se(r));return}if(s==="run"){let y=new AbortController,b=p(()=>y.abort(),"stop");process.once("SIGTERM",b),process.once("SIGINT",b);try{await Ee({directory:r,transport:ke,signal:y.signal})}finally{process.off("SIGTERM",b),process.off("SIGINT",b)}return}throw new Error("usage: openpond import service <install|start|stop|status|run|uninstall>")}if(o==="status"){g(await P(r));return}if(o==="sync"){g(await ee(r,"sync"));return}if(["pause","resume","disconnect"].includes(o)){let y=await B.open(r),b;try{b=y.connections().find(q=>q.id===s)}finally{y.close()}if(!b)throw new Error("Select a connection id from openpond import status.");let{sync:k}=await K(b),$=await k.control({id:b.id,expectedRevision:b.revision,action:o});await z(r,{...b,revision:$.revision,state:$.state}),g($);return}let c=o==="reconnect"?await oe(r,s):null;c&&(t={...t,source:c.source.source,sourcePath:c.source.root,project:c.projectId,connection:c.id,team:c.teamId,apiBaseUrl:c.apiBaseUrl,baseUrl:c.accountBaseUrl,once:!c.keepSyncing});let l=E(t,"source");if(l&&!(l in D))throw new Error("Choose a supported native source name.");let u=await G(r),v=await ce({machineId:u,...l&&E(t,"sourcePath")?{locations:{[l]:Ue(E(t,"sourcePath"))}}:{}});if(o==="discover"){g(v);return}if(o!=="connect"&&o!=="reconnect")throw new Error("usage: openpond import <connect|reconnect|discover|status|sync|pause|resume|disconnect|branches|branch|service>");let S=v.filter(y=>y.source===l),d=S.length===1?S[0]:void 0,R=process.stdin.isTTY&&process.stdout.isTTY&&!a;if(c&&Te(c,d),!d&&R){let y=S.length>1?S:v.filter(k=>k.available);y.forEach((k,$)=>console.log(`${$+1}. ${D[k.source]} ${k.root}${k.capabilities.history?"":` (${k.reason})`}`));let b=qe({input:process.stdin,output:process.stdout});try{d=y[Number(await b.question("Choose a source: "))-1]}finally{b.close()}}if(!d?.capabilities.history)throw new Error(d?.reason??(S.length>1?"Multiple source instances found. Select the exact --source-path or use interactive setup.":"Select --source and optionally --source-path."));let N=E(t,"range")||"week";if(!c&&R&&!t.range){let y=qe({input:process.stdin,output:process.stdout});try{N=(await y.question("History: day, week, or all [week]: ")).trim()||"week"}finally{y.close()}}if(!["day","week","all"].includes(N))throw new Error("--range must be day, week or all.");let i=c?c.since:N==="all"?null:new Date(Date.now()-(N==="day"?1:7)*864e5).toISOString(),f=await M(d,{since:i??void 0,limit:100});a||console.log(`Found ${f.items.length}${f.nextCursor?"+":""} sessions in ${d.root}. History: ${c?i?`since ${i}`:"all":N}.`);let h=!H(t.once),n=E(t,"project");if(!H(t.yes)&&(!R||!await W(`Sync this source to ${n||"your personal Imported conversations Project"} and ${h?"keep syncing":"import once"}?`,!0)))throw new Error("Connection was not approved. No history was uploaded.");let m=await Oe(d,t),C=new F(m),w=E(t,"connection")||`sync-${T([m.baseUrl,m.teamId,d.instanceId,n||"default"]).slice(0,40)}`;c&&await $e(r,c);let x=(await C.list()).items.find(y=>y.id===w),O=await C.register({id:w,source:d.source,machineId:u,sourceInstanceId:d.instanceId,sourceLabel:D[d.source],sourceRoot:d.root,destination:n?{kind:"existing",projectId:n}:{kind:"new",name:"Imported conversations"},since:i,keepSyncing:h,expectedRevision:x?.revision??0});await z(r,{id:O.id,teamId:m.teamId,apiBaseUrl:m.baseUrl,account:m.account,accountBaseUrl:m.accountBaseUrl,source:d,projectId:O.projectId,revision:O.revision,requestedSyncRevision:O.requestedSyncRevision,completedSyncRevision:O.completedSyncRevision,since:i,keepSyncing:h,state:O.state}),await te({directory:r,executable:process.execPath,args:[process.argv[1]],environment:He()}),await se(r),g({connection:O,service:await P(r)}),R&&!H(t.detach)&&await Ae({directory:r,connectionId:w,keepSyncing:h,async pause(){let y=await B.open(r),b;try{b=y.connections().find(q=>q.id===w)}finally{y.close()}if(!b)throw new Error("The connection is unavailable.");let{sync:k}=await K(b),$=await k.control({id:b.id,expectedRevision:b.revision,action:"pause"});await z(r,{...b,revision:$.revision,state:$.state})}})}p(is,"runImportCommand");function He(){return{...process.env.OPENPOND_HOME?{OPENPOND_HOME:process.env.OPENPOND_HOME}:{},...process.env.ELECTRON_RUN_AS_NODE==="1"?{ELECTRON_RUN_AS_NODE:"1"}:{}}}p(He,"collectorEnvironment");export{is as runImportCommand};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{$a as s,$b as sa,$c as sb,Ab as T,Ac as Ta,Ad as Tb,Bb as U,Bc as Ua,Bd as Ub,Cb as V,Cc as Va,Cd as Vb,Db as W,Dc as Wa,Dd as Wb,Eb as X,Ec as Xa,Ed as Xb,Fb as Y,Fc as Ya,Fd as Yb,Gb as Z,Gc as Za,Gd as Zb,Hb as _,Hc as _a,Hd as _b,Ib as $,Ic as $a,Id as $b,Jb as aa,Jc as ab,Jd as ac,Kb as ba,Kc as bb,Kd as bc,Lb as ca,Lc as cb,Ld as cc,Mb as da,Mc as db,Md as dc,Nb as ea,Nc as eb,Nd as ec,Oa as f,Ob as fa,Oc as fb,Od as fc,Pa as g,Pb as ga,Pc as gb,Pd as gc,Qa as h,Qb as ha,Qc as hb,Qd as hc,Ra as i,Rb as ia,Rc as ib,Rd as ic,Sa as j,Sb as ja,Sc as jb,Sd as jc,Ta as k,Tb as ka,Tc as kb,Td as kc,Ua as l,Ub as la,Uc as lb,Ud as lc,Va as m,Vb as ma,Vc as mb,Vd as mc,Wa as n,Wb as na,Wc as nb,Wd as nc,Xa as o,Xb as oa,Xc as ob,Ya as p,Yb as pa,Yc as pb,Za as q,Zb as qa,Zc as qb,_a as r,_b as ra,_c as rb,a,ab as t,ac as ta,ad as tb,bb as u,bc as ua,bd as ub,cb as v,cc as va,cd as vb,db as w,dc as wa,dd as wb,eb as x,ec as xa,ed as xb,fb as y,fc as ya,fd as yb,gb as z,gc as za,gd as zb,hb as A,hc as Aa,hd as Ab,ia as b,ib as B,ic as Ba,id as Bb,ja as c,jb as C,jc as Ca,jd as Cb,ka as d,kb as D,kc as Da,kd as Db,la as e,lb as E,lc as Ea,ld as Eb,mb as F,mc as Fa,md as Fb,nb as G,nc as Ga,nd as Gb,ob as H,oc as Ha,od as Hb,pb as I,pc as Ia,pd as Ib,qb as J,qc as Ja,qd as Jb,rb as K,rc as Ka,rd as Kb,sb as L,sc as La,sd as Lb,tb as M,tc as Ma,td as Mb,ub as N,uc as Na,ud as Nb,vb as O,vc as Oa,vd as Ob,wb as P,wc as Pa,wd as Pb,xb as Q,xc as Qa,xd as Qb,yb as R,yc as Ra,yd as Rb,zb as S,zc as Sa,zd as Sb}from"./chunk-BQNK2NMB.js";import"./chunk-VW7D3DRM.js";import"./chunk-P653BXMY.js";import"./chunk-ES2ISFJC.js";import"./chunk-FTQLQJQV.js";export{fc as AcceptanceAttemptSchema,Zb as AcceptanceCheckSchema,dc as AcceptanceGroupManifestContentSchema,ec as AcceptanceGroupManifestSchema,gc as AcceptanceGroupSnapshotContentSchema,hc as AcceptanceGroupSnapshotSchema,bc as AcceptanceMeasurementSchema,_b as AcceptancePlanContentSchema,$b as AcceptancePlanSchema,Da as ApplyTaskCorrectionCommandSchema,Ka as ArchiveAuthoringDraftCommandSchema,oa as AuthoringDraftContentSchema,qa as AuthoringDraftFinalizationSchema,na as AuthoringDraftInputSchema,pa as AuthoringDraftSchema,ma as AuthoringTargetKindSchema,g as BoundJudgeResponseSchema,Qa as CancelLearningIterationCommandSchema,Pa as CancelLearningIterationReservationCommandSchema,Ma as CancelRewardCheckCommandSchema,Ia as CancelTaskGradeCommandSchema,la as CombinedRewardAuthoringFieldsSchema,Ya as DEFAULT_REWARD_VERIFIER_SOURCE,ya as ImportTaskIntakeCommandSchema,i as JudgeCallReservationSchema,J as LearningAcceptedParentSchema,Wb as LearningCandidateDecisionObservationSchema,ea as LearningChainSchema,Ab as LearningCommandRequestSchema,Sa as LearningCommandSchema,lb as LearningConflictError,ga as LearningConsumptionSchema,a as LearningDomainError,fa as LearningEligibilityCountsSchema,Ua as LearningIterationDispatchSchema,Va as LearningIterationObservationSchema,ha as LearningIterationReservationSchema,L as LearningIterationSchema,K as LearningIterationStatusSchema,Ta as LearningIterationSubmissionSchema,da as LearningIterationTriggerSchema,o as LearningJsonObjectSchema,q as LearningJsonPointerSchema,Db as LearningOperationResultSchema,H as LearningPolicyContentSchema,tb as LearningPolicyInspectionResultSchema,I as LearningPolicySchema,Bb as LearningReadRequestSchema,kb as LearningResourceKindSchema,N as LearningResourceSchema,u as LearningReviewOriginSchema,p as LearningRevisionRefSchema,Xa as LearningScheduleFireSchema,Wa as LearningScheduleSchema,v as LearningSourceContentSchema,w as LearningSourceSchema,xb as LearningTaskQueueInspectionSchema,b as LearningTextAssetContentSchema,c as LearningTextAssetSchema,Ob as MAX_REWARD_CALIBRATION_CLOSURE_BYTES,l as NightlyScheduleSchema,Na as PublishCheckedRewardCommandSchema,za as PublishLearningResourceCommandSchema,Aa as PublishLearningResourcesCommandSchema,La as QueueRewardCheckCommandSchema,Fa as QueueTaskGradeCommandSchema,Oa as ReserveLearningIterationCommandSchema,Ea as ResolveTaskFeedbackCommandSchema,Ra as RetryLearningIterationDispatchCommandSchema,Ga as ReviewTaskEvidenceCommandSchema,ja as RewardAuthoringFieldsSchema,Pb as RewardCalibrationClosureSchema,eb as RewardCheckRunSchema,cb as RewardCheckRuntimeSchema,ia as RewardFixtureAuthoringFieldsSchema,db as RewardFixtureCheckResultSchema,bb as RewardFixtureSchema,Ja as SaveAuthoringDraftCommandSchema,Ha as SealTaskBatchCommandSchema,Ba as SubmitTaskExampleCommandSchema,Ca as SubmitTaskFeedbackCommandSchema,ra as TASK_INTAKE_LIMITS,D as TaskAdmissionDecisionContentSchema,E as TaskAdmissionDecisionSchema,F as TaskBatchContentSchema,aa as TaskBatchPackageMetadataSchema,G as TaskBatchSchema,r as TaskDefinitionContentSchema,s as TaskDefinitionSchema,y as TaskEvidenceContentSchema,Cb as TaskEvidenceInspectionResultSchema,z as TaskEvidenceSchema,x as TaskExampleSubmissionSchema,C as TaskFeedbackSchema,B as TaskFeedbackSubmissionSchema,ka as TaskFormatAuthoringFieldsSchema,M as TaskGradeRunSchema,ta as TaskIntakeFileSchema,sa as TaskIntakeFormatSchema,va as TaskIntakePreviewSchema,ua as TaskIntakeRecordSchema,A as TaskRatingSchema,t as TaskSourceMappingSchema,f as TrainingHandoffOriginSchema,nc as acceptanceGroupVerdict,mc as assertAcceptanceBaselineReuse,kc as assertAcceptanceGroupSnapshot,lc as assertAcceptanceGroupUpdate,Y as assertAdmissionDecision,Z as assertGradeIdentity,R as assertLearningContentHash,zb as assertLearningRequestJson,wb as assertRewardCalibration,ab as authoringNumber,n as coalesceNightlyOccurrences,Za as compileRewardAuthoring,gb as compileRewardCheck,fb as compileRewardFixtures,ba as compileTaskBatch,ic as createAcceptanceGroupManifest,jc as createAcceptanceGroupSnapshot,ac as createAcceptancePlan,h as createBoundModelJudgeRunner,k as createBudgetedJudgeExecutor,Nb as createBudgetedRewardFixtureExecutor,Hb as createBuiltinTaskGradeExecutor,Mb as createIsolatedRewardFixtureExecutor,Vb as createLearningIterationWorker,Yb as createLearningScheduleWorker,Gb as createLearningService,d as createLearningTextAsset,Rb as createRewardCalibrationClosure,Kb as createRewardCheckJudgeBudgetStore,Ub as createRewardCheckWorker,Lb as createTaskGradeJudgeBudgetStore,Ib as createTaskGradeWorker,Eb as decodeTaskIntakeText,cc as evaluateAcceptancePlan,hb as executeRewardFixture,Sb as exportRewardCalibrationClosure,ub as inspectLearningPolicy,yb as inspectLearningTaskQueue,S as inspectTaskEvidence,xa as intakeDate,wa as intakeId,j as judgeCommittedSpend,ob as learningEvidenceId,pb as learningOperationId,O as learningRef,jb as learningResourceSchemas,rb as learningScheduleId,U as mapTaskSourceRecord,ib as matchRewardFixture,m as nextNightlyOccurrence,$a as parseRewardAuthoringObject,Fb as previewTaskIntake,vb as qualifyRewardCheck,V as readTaskJsonPointer,Xb as reconcileLearningCandidateDecision,nb as requireLearningRelease,mb as requireLearningResource,qb as resolveLearningTrainingParent,_a as rewardAuthoringFields,Tb as rewardCalibrationClosureAsset,Jb as rewardFixtureFromRating,P as sameLearningRef,Q as sealLearningContent,$ as sealTaskBatch,sb as synchronizeLearningSchedule,X as taskAttemptEvidence,ca as taskBatchPackageMetadata,_ as taskFamilyReservations,W as taskRecordFromEvidence,T as validateSourceSubmission,e as verifyLearningTextAsset,Qb as verifyRewardCalibrationClosure};
2
+ import{$a as s,$b as sa,$c as sb,Ab as T,Ac as Ta,Ad as Tb,Bb as U,Bc as Ua,Bd as Ub,Cb as V,Cc as Va,Cd as Vb,Db as W,Dc as Wa,Dd as Wb,Eb as X,Ec as Xa,Ed as Xb,Fb as Y,Fc as Ya,Fd as Yb,Gb as Z,Gc as Za,Gd as Zb,Hb as _,Hc as _a,Hd as _b,Ib as $,Ic as $a,Id as $b,Jb as aa,Jc as ab,Jd as ac,Kb as ba,Kc as bb,Kd as bc,Lb as ca,Lc as cb,Ld as cc,Mb as da,Mc as db,Md as dc,Nb as ea,Nc as eb,Nd as ec,Oa as f,Ob as fa,Oc as fb,Od as fc,Pa as g,Pb as ga,Pc as gb,Pd as gc,Qa as h,Qb as ha,Qc as hb,Qd as hc,Ra as i,Rb as ia,Rc as ib,Rd as ic,Sa as j,Sb as ja,Sc as jb,Sd as jc,Ta as k,Tb as ka,Tc as kb,Td as kc,Ua as l,Ub as la,Uc as lb,Ud as lc,Va as m,Vb as ma,Vc as mb,Vd as mc,Wa as n,Wb as na,Wc as nb,Wd as nc,Xa as o,Xb as oa,Xc as ob,Ya as p,Yb as pa,Yc as pb,Za as q,Zb as qa,Zc as qb,_a as r,_b as ra,_c as rb,a,ab as t,ac as ta,ad as tb,bb as u,bc as ua,bd as ub,cb as v,cc as va,cd as vb,db as w,dc as wa,dd as wb,eb as x,ec as xa,ed as xb,fb as y,fc as ya,fd as yb,gb as z,gc as za,gd as zb,hb as A,hc as Aa,hd as Ab,ia as b,ib as B,ic as Ba,id as Bb,ja as c,jb as C,jc as Ca,jd as Cb,ka as d,kb as D,kc as Da,kd as Db,la as e,lb as E,lc as Ea,ld as Eb,mb as F,mc as Fa,md as Fb,nb as G,nc as Ga,nd as Gb,ob as H,oc as Ha,od as Hb,pb as I,pc as Ia,pd as Ib,qb as J,qc as Ja,qd as Jb,rb as K,rc as Ka,rd as Kb,sb as L,sc as La,sd as Lb,tb as M,tc as Ma,td as Mb,ub as N,uc as Na,ud as Nb,vb as O,vc as Oa,vd as Ob,wb as P,wc as Pa,wd as Pb,xb as Q,xc as Qa,xd as Qb,yb as R,yc as Ra,yd as Rb,zb as S,zc as Sa,zd as Sb}from"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-FTQLQJQV.js";export{fc as AcceptanceAttemptSchema,Zb as AcceptanceCheckSchema,dc as AcceptanceGroupManifestContentSchema,ec as AcceptanceGroupManifestSchema,gc as AcceptanceGroupSnapshotContentSchema,hc as AcceptanceGroupSnapshotSchema,bc as AcceptanceMeasurementSchema,_b as AcceptancePlanContentSchema,$b as AcceptancePlanSchema,Da as ApplyTaskCorrectionCommandSchema,Ka as ArchiveAuthoringDraftCommandSchema,oa as AuthoringDraftContentSchema,qa as AuthoringDraftFinalizationSchema,na as AuthoringDraftInputSchema,pa as AuthoringDraftSchema,ma as AuthoringTargetKindSchema,g as BoundJudgeResponseSchema,Qa as CancelLearningIterationCommandSchema,Pa as CancelLearningIterationReservationCommandSchema,Ma as CancelRewardCheckCommandSchema,Ia as CancelTaskGradeCommandSchema,la as CombinedRewardAuthoringFieldsSchema,Ya as DEFAULT_REWARD_VERIFIER_SOURCE,ya as ImportTaskIntakeCommandSchema,i as JudgeCallReservationSchema,J as LearningAcceptedParentSchema,Wb as LearningCandidateDecisionObservationSchema,ea as LearningChainSchema,Ab as LearningCommandRequestSchema,Sa as LearningCommandSchema,lb as LearningConflictError,ga as LearningConsumptionSchema,a as LearningDomainError,fa as LearningEligibilityCountsSchema,Ua as LearningIterationDispatchSchema,Va as LearningIterationObservationSchema,ha as LearningIterationReservationSchema,L as LearningIterationSchema,K as LearningIterationStatusSchema,Ta as LearningIterationSubmissionSchema,da as LearningIterationTriggerSchema,o as LearningJsonObjectSchema,q as LearningJsonPointerSchema,Db as LearningOperationResultSchema,H as LearningPolicyContentSchema,tb as LearningPolicyInspectionResultSchema,I as LearningPolicySchema,Bb as LearningReadRequestSchema,kb as LearningResourceKindSchema,N as LearningResourceSchema,u as LearningReviewOriginSchema,p as LearningRevisionRefSchema,Xa as LearningScheduleFireSchema,Wa as LearningScheduleSchema,v as LearningSourceContentSchema,w as LearningSourceSchema,xb as LearningTaskQueueInspectionSchema,b as LearningTextAssetContentSchema,c as LearningTextAssetSchema,Ob as MAX_REWARD_CALIBRATION_CLOSURE_BYTES,l as NightlyScheduleSchema,Na as PublishCheckedRewardCommandSchema,za as PublishLearningResourceCommandSchema,Aa as PublishLearningResourcesCommandSchema,La as QueueRewardCheckCommandSchema,Fa as QueueTaskGradeCommandSchema,Oa as ReserveLearningIterationCommandSchema,Ea as ResolveTaskFeedbackCommandSchema,Ra as RetryLearningIterationDispatchCommandSchema,Ga as ReviewTaskEvidenceCommandSchema,ja as RewardAuthoringFieldsSchema,Pb as RewardCalibrationClosureSchema,eb as RewardCheckRunSchema,cb as RewardCheckRuntimeSchema,ia as RewardFixtureAuthoringFieldsSchema,db as RewardFixtureCheckResultSchema,bb as RewardFixtureSchema,Ja as SaveAuthoringDraftCommandSchema,Ha as SealTaskBatchCommandSchema,Ba as SubmitTaskExampleCommandSchema,Ca as SubmitTaskFeedbackCommandSchema,ra as TASK_INTAKE_LIMITS,D as TaskAdmissionDecisionContentSchema,E as TaskAdmissionDecisionSchema,F as TaskBatchContentSchema,aa as TaskBatchPackageMetadataSchema,G as TaskBatchSchema,r as TaskDefinitionContentSchema,s as TaskDefinitionSchema,y as TaskEvidenceContentSchema,Cb as TaskEvidenceInspectionResultSchema,z as TaskEvidenceSchema,x as TaskExampleSubmissionSchema,C as TaskFeedbackSchema,B as TaskFeedbackSubmissionSchema,ka as TaskFormatAuthoringFieldsSchema,M as TaskGradeRunSchema,ta as TaskIntakeFileSchema,sa as TaskIntakeFormatSchema,va as TaskIntakePreviewSchema,ua as TaskIntakeRecordSchema,A as TaskRatingSchema,t as TaskSourceMappingSchema,f as TrainingHandoffOriginSchema,nc as acceptanceGroupVerdict,mc as assertAcceptanceBaselineReuse,kc as assertAcceptanceGroupSnapshot,lc as assertAcceptanceGroupUpdate,Y as assertAdmissionDecision,Z as assertGradeIdentity,R as assertLearningContentHash,zb as assertLearningRequestJson,wb as assertRewardCalibration,ab as authoringNumber,n as coalesceNightlyOccurrences,Za as compileRewardAuthoring,gb as compileRewardCheck,fb as compileRewardFixtures,ba as compileTaskBatch,ic as createAcceptanceGroupManifest,jc as createAcceptanceGroupSnapshot,ac as createAcceptancePlan,h as createBoundModelJudgeRunner,k as createBudgetedJudgeExecutor,Nb as createBudgetedRewardFixtureExecutor,Hb as createBuiltinTaskGradeExecutor,Mb as createIsolatedRewardFixtureExecutor,Vb as createLearningIterationWorker,Yb as createLearningScheduleWorker,Gb as createLearningService,d as createLearningTextAsset,Rb as createRewardCalibrationClosure,Kb as createRewardCheckJudgeBudgetStore,Ub as createRewardCheckWorker,Lb as createTaskGradeJudgeBudgetStore,Ib as createTaskGradeWorker,Eb as decodeTaskIntakeText,cc as evaluateAcceptancePlan,hb as executeRewardFixture,Sb as exportRewardCalibrationClosure,ub as inspectLearningPolicy,yb as inspectLearningTaskQueue,S as inspectTaskEvidence,xa as intakeDate,wa as intakeId,j as judgeCommittedSpend,ob as learningEvidenceId,pb as learningOperationId,O as learningRef,jb as learningResourceSchemas,rb as learningScheduleId,U as mapTaskSourceRecord,ib as matchRewardFixture,m as nextNightlyOccurrence,$a as parseRewardAuthoringObject,Fb as previewTaskIntake,vb as qualifyRewardCheck,V as readTaskJsonPointer,Xb as reconcileLearningCandidateDecision,nb as requireLearningRelease,mb as requireLearningResource,qb as resolveLearningTrainingParent,_a as rewardAuthoringFields,Tb as rewardCalibrationClosureAsset,Jb as rewardFixtureFromRating,P as sameLearningRef,Q as sealLearningContent,$ as sealTaskBatch,sb as synchronizeLearningSchedule,X as taskAttemptEvidence,ca as taskBatchPackageMetadata,_ as taskFamilyReservations,W as taskRecordFromEvidence,T as validateSourceSubmission,e as verifyLearningTextAsset,Qb as verifyRewardCalibrationClosure};
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import"./chunk-PMZH2TKS.js";import"./chunk-HK3WGUKK.js";import"./chunk-6MI4KKWF.js";import"./chunk-5ZZM3TUN.js";import{a as u,c as A,d as x,i as v,j as S,k as R}from"./chunk-JEVA7YQL.js";import"./chunk-6FA3GG5B.js";import"./chunk-XLDW5NN3.js";import{c as B}from"./chunk-USWZ3KUC.js";import{c as U,d as C,f as O}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-EWS7MXTM.js";import"./chunk-TYWBEJOA.js";import{f as m}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import"./chunk-4UTIEH5H.js";import"./chunk-LZSY5IM3.js";import{d as k}from"./chunk-6SJZXZNA.js";import"./chunk-GLUWATL5.js";import"./chunk-H6W55CQG.js";import"./chunk-Z3D4C7BG.js";import"./chunk-JO7GRBOG.js";import"./chunk-BQNK2NMB.js";import"./chunk-VW7D3DRM.js";import"./chunk-UWO34HP6.js";import{L as y}from"./chunk-L4BYPZ4U.js";import"./chunk-P653BXMY.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as i}from"./chunk-FTQLQJQV.js";import{randomUUID as b}from"node:crypto";async function G(r,t){let e=t[0]||"smoke",n=await k(),l=await B(n,O(n)),c=P(n,r);if(e==="provider-catalog"||e==="providers-catalog"||e==="catalog"){let a=await E({apiBaseUrl:c,token:l});console.log(JSON.stringify(a,null,2));return}if(e==="models"||e==="model-list"){let a=await A({apiBaseUrl:c,token:l});console.log(JSON.stringify(a,null,2));return}if(e==="model"||e==="model-get"){let a=t[1]||o(r,"model");if(!a)throw new Error("usage: opchat model <model>");let p=await x({apiBaseUrl:c,token:l,model:a});console.log(JSON.stringify(p,null,2));return}if(e==="chat"){let a=o(r,"model")||"openpond-chat",p=o(r,"effort"),f=p?y.parse(p):void 0,d=o(r,"message")||o(r,"prompt")||"Reply with a short confirmation from OpChat.";if(!m(r.stream)){let s=await v({apiBaseUrl:c,token:l,model:a,reasoningEffort:f,messages:[{role:"user",content:d}]});console.log(JSON.stringify(s,null,2));return}let g="",h=null,w=null;for await(let s of S({apiBaseUrl:c,token:l,model:a,reasoningEffort:f,messages:[{role:"user",content:d}]}))s.type==="text_delta"?(g+=s.text,process.stdout.write(s.text)):s.type==="finish"?h=s.finishReason:s.type==="usage"&&(w=s.usage);process.stdout.write(`
2
+ import"./chunk-XBCIBAXD.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import{a as u,c as A,d as x,i as v,j as S,k as R}from"./chunk-JEVA7YQL.js";import"./chunk-6FA3GG5B.js";import"./chunk-N3DEA6PG.js";import{c as B}from"./chunk-PA7XP42P.js";import{c as U,d as C,f as O}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-RLZPX4YP.js";import"./chunk-Q4H3NUVW.js";import{f as m}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import"./chunk-2SPZYBDN.js";import"./chunk-QXVIIM4T.js";import{d as k}from"./chunk-R3XFY7VL.js";import"./chunk-GLUWATL5.js";import"./chunk-YL6VFJ4P.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import{L as y}from"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as i}from"./chunk-FTQLQJQV.js";import{randomUUID as b}from"node:crypto";async function G(r,t){let e=t[0]||"smoke",n=await k(),l=await B(n,O(n)),c=P(n,r);if(e==="provider-catalog"||e==="providers-catalog"||e==="catalog"){let a=await E({apiBaseUrl:c,token:l});console.log(JSON.stringify(a,null,2));return}if(e==="models"||e==="model-list"){let a=await A({apiBaseUrl:c,token:l});console.log(JSON.stringify(a,null,2));return}if(e==="model"||e==="model-get"){let a=t[1]||o(r,"model");if(!a)throw new Error("usage: opchat model <model>");let p=await x({apiBaseUrl:c,token:l,model:a});console.log(JSON.stringify(p,null,2));return}if(e==="chat"){let a=o(r,"model")||"openpond-chat",p=o(r,"effort"),f=p?y.parse(p):void 0,d=o(r,"message")||o(r,"prompt")||"Reply with a short confirmation from OpChat.";if(!m(r.stream)){let s=await v({apiBaseUrl:c,token:l,model:a,reasoningEffort:f,messages:[{role:"user",content:d}]});console.log(JSON.stringify(s,null,2));return}let g="",h=null,w=null;for await(let s of S({apiBaseUrl:c,token:l,model:a,reasoningEffort:f,messages:[{role:"user",content:d}]}))s.type==="text_delta"?(g+=s.text,process.stdout.write(s.text)):s.type==="finish"?h=s.finishReason:s.type==="usage"&&(w=s.usage);process.stdout.write(`
3
3
  `),console.log(JSON.stringify({finishReason:h,usage:w,text:g},null,2));return}if(e==="smoke"){let a=await R({apiBaseUrl:c,token:l,defaultModel:o(r,"model")||void 0,compatibilityModel:o(r,"compatibilityModel")||o(r,"compatModel")||void 0,skipStream:m(r.skipStream),skipTool:m(r.skipTool),log:i(p=>console.log(p),"log")});m(r.json)&&console.log(JSON.stringify(a,null,2));return}throw new Error("usage: opchat <provider-catalog|models|model|chat|smoke> [--opchat-api-base-url <url>] [chat --model <id> --effort <off|low|medium|high|xhigh|max>]")}i(G,"runOpChatCommand");async function E(r){let t=r.apiBaseUrl.trim().replace(/\/+$/,"");if(!t)throw new Error("OpChat API base URL is required.");let e=r.token.trim();if(!e)throw new Error("OpenPond API key is required.");let n=await fetch(`${t}/provider-catalog`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json","Content-Type":"application/json","x-openpond-client":"openpond-cli","x-openpond-request-id":b()}});if(!n.ok)throw new Error(`Hosted provider catalog failed: ${n.status} ${await T(n)}`);return n.json()}i(E,"getOpChatProviderCatalog");async function T(r){let t=await r.text().catch(()=>"");if(!t)return r.statusText||`HTTP ${r.status}`;try{let e=JSON.parse(t);if(typeof e.message=="string")return e.message;if(typeof e.error=="string")return e.error;if(e.error&&typeof e.error=="object"&&!Array.isArray(e.error)){let n=e.error;return[n.code,n.message].filter(Boolean).join(": ")||t}return t}catch{return t}}i(T,"readResponseError");function P(r,t){let e=o(t,"opchatApiBaseUrl")||o(t,"opchatApiBaseurl")||o(t,"opChatApiBaseUrl")||o(t,"opChatApiBaseurl")||o(t,"opchatApiUrl")||o(t,"opChatApiUrl");return e?u({opChatApiBaseUrl:e}):u({apiBaseUrl:U(t)||r.apiBaseUrl,chatApiBaseUrl:C(t)||r.chatApiBaseUrl})}i(P,"resolveOpChatCliBaseUrl");function o(r,t){let e=r[t];return typeof e=="string"?e.trim():""}i(o,"optionString");export{G as runOpChatCommand};