openpond 0.2.46 → 0.2.47

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 (204) hide show
  1. package/dist/app-server.d.ts +96 -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-3KFJJUJH.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-JBHAU7PH.js → chunk-36YNUUZL.js} +137 -137
  9. package/dist/chunks/chunk-3HBCQNRN.js +2 -0
  10. package/dist/chunks/chunk-4UTBLHFC.js +2 -0
  11. package/dist/chunks/{chunk-FOEUDMME.js → chunk-526PVA3V.js} +86 -86
  12. package/dist/chunks/{chunk-5OGRWWEH.js → chunk-6MH55NGW.js} +1 -1
  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-HO5L2FUU.js → chunk-A2GVVXFV.js} +1 -1
  16. package/dist/chunks/{chunk-W4IL6TWB.js → chunk-BM7TU6NX.js} +115 -111
  17. package/dist/chunks/{chunk-HP2D3W2B.js → chunk-CNTGL5IX.js} +1 -1
  18. package/dist/chunks/{chunk-WWABOVRW.js → chunk-D7DA5G2U.js} +2 -2
  19. package/dist/chunks/{chunk-UWO34HP6.js → chunk-DALJMSJG.js} +2 -2
  20. package/dist/chunks/{chunk-33AO3P6X.js → chunk-DLZP22WV.js} +1 -1
  21. package/dist/chunks/{chunk-BKMGBIBT.js → chunk-EMKZVP7Z.js} +1 -1
  22. package/dist/chunks/chunk-F7RCOLZD.js +2 -0
  23. package/dist/chunks/{chunk-ZJY2L43W.js → chunk-HA7EFTPF.js} +1 -1
  24. package/dist/chunks/{chunk-HK3WGUKK.js → chunk-IKWDL3RB.js} +1 -1
  25. package/dist/chunks/{chunk-ZC57DX6D.js → chunk-JDLAHVAJ.js} +1 -1
  26. package/dist/chunks/{chunk-D6MQTNJ3.js → chunk-K6S4TY5W.js} +6 -6
  27. package/dist/chunks/{chunk-IV7F74JJ.js → chunk-MASJQWA2.js} +1 -1
  28. package/dist/chunks/{chunk-XLDW5NN3.js → chunk-N3DEA6PG.js} +1 -1
  29. package/dist/chunks/{chunk-F5DUN73H.js → chunk-N5QNXMIS.js} +1 -1
  30. package/dist/chunks/{chunk-MCRA6ZGJ.js → chunk-NAZ26IZL.js} +1 -1
  31. package/dist/chunks/chunk-NNF6KCHD.js +3 -0
  32. package/dist/chunks/{chunk-USWZ3KUC.js → chunk-PA7XP42P.js} +1 -1
  33. package/dist/chunks/{chunk-BQNK2NMB.js → chunk-PJM2G7SG.js} +1 -1
  34. package/dist/chunks/chunk-PYABBF53.js +53 -0
  35. package/dist/chunks/{chunk-TYWBEJOA.js → chunk-Q4H3NUVW.js} +2 -2
  36. package/dist/chunks/chunk-QRWPEW3Z.js +24 -0
  37. package/dist/chunks/{chunk-LZSY5IM3.js → chunk-QXVIIM4T.js} +1 -1
  38. package/dist/chunks/{chunk-6SJZXZNA.js → chunk-R3XFY7VL.js} +1 -1
  39. package/dist/chunks/{chunk-EWS7MXTM.js → chunk-RLZPX4YP.js} +1 -1
  40. package/dist/chunks/{chunk-VW7D3DRM.js → chunk-SDEDAHV6.js} +72 -67
  41. package/dist/chunks/{chunk-BUFQKDAW.js → chunk-T5LE6R5S.js} +1 -1
  42. package/dist/chunks/{chunk-L4BYPZ4U.js → chunk-TGIB24K4.js} +1 -1
  43. package/dist/chunks/{chunk-KUKOZJIR.js → chunk-TT46OISU.js} +1 -1
  44. package/dist/chunks/{chunk-6WLJWRMF.js → chunk-UJ5EFSEC.js} +1 -1
  45. package/dist/chunks/{chunk-KE5RH6JA.js → chunk-WITSXYEW.js} +1 -1
  46. package/dist/chunks/chunk-WV2APYWG.js +2 -0
  47. package/dist/chunks/chunk-XBCIBAXD.js +4 -0
  48. package/dist/chunks/chunk-XDMUD4FW.js +5 -0
  49. package/dist/chunks/{chunk-DNXKIIV7.js → chunk-XM26DGML.js} +1 -1
  50. package/dist/chunks/{chunk-4VKNBADF.js → chunk-XON44M6V.js} +1 -1
  51. package/dist/chunks/{chunk-D6E7JBBQ.js → chunk-YBVIFIXN.js} +1 -1
  52. package/dist/chunks/{chunk-OGXSE57Z.js → chunk-YIB3J4RC.js} +1 -1
  53. package/dist/chunks/{chunk-H6W55CQG.js → chunk-YL6VFJ4P.js} +1 -1
  54. package/dist/chunks/cli-WPAYXAJX.js +2 -0
  55. package/dist/chunks/{configuration-command-MVZS625X.js → configuration-command-SA56RV5B.js} +1 -1
  56. package/dist/chunks/{connected-evidence-7LHUZ2UI.js → connected-evidence-IVSQZYIB.js} +1 -1
  57. package/dist/chunks/{continual-K5JNHNQH.js → continual-PKK2BOTB.js} +1 -1
  58. package/dist/chunks/core-commands-W5IGIITV.js +2 -0
  59. package/dist/chunks/{datasets-KDN2EXHE.js → datasets-KSO2UG6R.js} +1 -1
  60. package/dist/chunks/{desktop-test-WIOEKMPR.js → desktop-test-6HXFM7PO.js} +1 -1
  61. package/dist/chunks/{dist-JBE7DPFZ.js → dist-4HV2W6V4.js} +1 -1
  62. package/dist/chunks/{dist-3MTJ7VM6.js → dist-VDVI7KIO.js} +1 -1
  63. package/dist/chunks/{evaluation-coordination-NGYHL7HG.js → evaluation-coordination-MOFBXRXN.js} +1 -1
  64. package/dist/chunks/{experiment-improvements-2M7GRGWS.js → experiment-improvements-TDHM6NEA.js} +1 -1
  65. package/dist/chunks/{experiments-B6CRZ3GI.js → experiments-HFPDFD4I.js} +1 -1
  66. package/dist/chunks/{extension-RZTMK3ON.js → extension-R373LYIB.js} +1 -1
  67. package/dist/chunks/{help-EISFHH2F.js → help-PEFQDDTA.js} +1 -1
  68. package/dist/chunks/{hosted-experiment-improvement-6CHH65DX.js → hosted-experiment-improvement-T6Q7ASMI.js} +1 -1
  69. package/dist/chunks/hosted-harness-runtime-2R5QRZCG.js +2 -0
  70. package/dist/chunks/{hosted-profile-candidate-HYEISIAC.js → hosted-profile-candidate-TKOY3M4S.js} +1 -1
  71. package/dist/chunks/hosted-profile-compiler-VLBFIEWK.js +2 -0
  72. package/dist/chunks/{hosted-profile-evaluation-control-LV6YXOG7.js → hosted-profile-evaluation-control-7B3RAZU2.js} +1 -1
  73. package/dist/chunks/{hosted-profile-evaluation-inspection-A62UYFEP.js → hosted-profile-evaluation-inspection-3MB6MWO6.js} +1 -1
  74. package/dist/chunks/{hosted-profile-evaluation-preparation-OR4OLYEX.js → hosted-profile-evaluation-preparation-C7WEABZ5.js} +1 -1
  75. package/dist/chunks/{human-review-J6JGNRBR.js → human-review-HRGGACEM.js} +1 -1
  76. package/dist/chunks/import-RSAQ44GG.js +4 -0
  77. package/dist/chunks/{learning-REL6GGNA.js → learning-FNBEIAY6.js} +1 -1
  78. package/dist/chunks/{opchat-CUZUU2WM.js → opchat-I7ZWJ5XK.js} +1 -1
  79. package/dist/chunks/{organizations-VT27V4B2.js → organizations-LFCZIH7E.js} +1 -1
  80. package/dist/chunks/{profile-N2E5ASHQ.js → profile-EPIX5QVK.js} +1 -1
  81. package/dist/chunks/{project-agent-XMXOBJSC.js → project-agent-DGOPMECP.js} +1 -1
  82. package/dist/chunks/{sandbox-command-NC665ZZ5.js → sandbox-command-Q5F6VUOS.js} +1 -1
  83. package/dist/chunks/{sandbox-template-OTP6S3RU.js → sandbox-template-7GICPIKJ.js} +1 -1
  84. package/dist/chunks/{src-WM35IF4W.js → src-DH5AQ4Z7.js} +1 -1
  85. package/dist/chunks/src-R4TSYNTK.js +329 -0
  86. package/dist/chunks/{taskset-COAPMTT3.js → taskset-LUG3ZU6J.js} +1 -1
  87. package/dist/chunks/{teams-bot-ACWJ7PJP.js → teams-bot-Z6RJGHME.js} +1 -1
  88. package/dist/chunks/{training-4JUK7YQV.js → training-XHE6FVII.js} +1 -1
  89. package/dist/cli.js +1 -1
  90. package/dist/index.js +1 -1
  91. package/dist/web/agent-sources/SOURCES.md +11 -0
  92. package/dist/web/agent-sources/claude-code.svg +1 -0
  93. package/dist/web/agent-sources/codex.svg +1 -0
  94. package/dist/web/agent-sources/grok-build.svg +3 -0
  95. package/dist/web/agent-sources/hermes.png +0 -0
  96. package/dist/web/agent-sources/oh-my-pi.svg +11 -0
  97. package/dist/web/agent-sources/openclaw.svg +54 -0
  98. package/dist/web/agent-sources/opencode.svg +4 -0
  99. package/dist/web/agent-sources/pi.svg +6 -0
  100. package/dist/web/assets/App-BI-uOpnP.js +234 -0
  101. package/dist/web/assets/App-DkH8CeoI.css +1 -0
  102. package/dist/web/assets/{AppDialog-CaxeNfsu.js → AppDialog-1iGodoot.js} +1 -1
  103. package/dist/web/assets/{AppTerminalPanel-dtK0ZPer.js → AppTerminalPanel-udtBdWFn.js} +2 -2
  104. package/dist/web/assets/AppsView-BonAGiS8.css +1 -0
  105. package/dist/web/assets/AppsView-DhKsU4yi.js +1 -0
  106. package/dist/web/assets/BrowserSidebar-BnOyqIQT.js +1 -0
  107. package/dist/web/assets/{CartesianChart-Drfk6jTn.js → CartesianChart-C24DAywn.js} +1 -1
  108. package/dist/web/assets/{CollaborationTabs-Czh2noeb.js → CollaborationTabs-DgmOF5Fe.js} +1 -1
  109. package/dist/web/assets/{CommandMenu-D-M-xomh.js → CommandMenu-CUNGtHwS.js} +1 -1
  110. package/dist/web/assets/{CommunityView-BrdxUI5Z.js → CommunityView-CE7qeJnr.js} +1 -1
  111. package/dist/web/assets/{ComposerCreateImproveStrip-CJ8nkYJf.js → ComposerCreateImproveStrip-BixNsg2a.js} +1 -1
  112. package/dist/web/assets/{GetStartedView-u7Jw7YA1.js → GetStartedView-B8gCwmBX.js} +1 -1
  113. package/dist/web/assets/{HostedModelLearningReview-D0a2nwse.js → HostedModelLearningReview-CitgUNfC.js} +1 -1
  114. package/dist/web/assets/{HostedModelLearningSettings-CQQGyjxi.js → HostedModelLearningSettings-WUaqzNsa.js} +1 -1
  115. package/dist/web/assets/{LabModelVersionDetailPage-Cxlc4sSC.js → LabModelVersionDetailPage-Cx0kL69J.js} +1 -1
  116. package/dist/web/assets/{LabSkillSidebar-BnJkDb0c.js → LabSkillSidebar-DRggqZ1j.js} +1 -1
  117. package/dist/web/assets/LabsRoute-BujTZhqC.js +99 -0
  118. package/dist/web/assets/{MainChatThread-r_TYiTnW.js → MainChatThread-CyA_644R.js} +2 -2
  119. package/dist/web/assets/MainPane-LaEtxydD.js +19 -0
  120. package/dist/web/assets/{MarkdownText-BxPHz4je.js → MarkdownText-DJI5LwT0.js} +19 -19
  121. package/dist/web/assets/{NativeSkillSidebar-CCHK6kMG.js → NativeSkillSidebar-CkFpWxjd.js} +1 -1
  122. package/dist/web/assets/{NewExperienceSwitcher-CuKWTDZj.js → NewExperienceSwitcher-DXcRHHsu.js} +1 -1
  123. package/dist/web/assets/{NewProjectDialog-CS6sw2oD.js → NewProjectDialog-gDzX_ZIJ.js} +1 -1
  124. package/dist/web/assets/{OutputsPage-JDM5bfLJ.js → OutputsPage-J_k-_N82.js} +1 -1
  125. package/dist/web/assets/{ProjectsPage-B3zTBHOA.js → ProjectsPage-BsyZmvlg.js} +1 -1
  126. package/dist/web/assets/{RightChatPanelStack-L8S3yj1u.js → RightChatPanelStack-Bz8puMUB.js} +1 -1
  127. package/dist/web/assets/{RightSidebarHomePanel-BWJQKFUp.js → RightSidebarHomePanel-DmorYb6p.js} +1 -1
  128. package/dist/web/assets/ScheduledWorkPage-BFDzQUyL.js +1 -0
  129. package/dist/web/assets/SettingsView-BB7wCdbr.js +5 -0
  130. package/dist/web/assets/SettingsView-BnANbPLS.css +1 -0
  131. package/dist/web/assets/{TeamChatView-DakXCNQE.js → TeamChatView-CZ3b7rq2.js} +2 -2
  132. package/dist/web/assets/{TerminalOverlay-DaonK5C0.js → TerminalOverlay-Ck43Qri3.js} +1 -1
  133. package/dist/web/assets/{TrainingCreationPanel-CUvSsSwp.js → TrainingCreationPanel-ejqPZm3g.js} +1 -1
  134. package/dist/web/assets/{TrainingDraftPanel-DNivtVwd.js → TrainingDraftPanel-Cy2AQxxL.js} +1 -1
  135. package/dist/web/assets/{UsageSettingsSection-rbmuoPoE.js → UsageSettingsSection-B7nyMItm.js} +1 -1
  136. package/dist/web/assets/{WorkSidebarPanel-DrYt9xzv.js → WorkSidebarPanel-BfjAc097.js} +1 -1
  137. package/dist/web/assets/{WorkspaceDiffPanel-CThoTqe4.js → WorkspaceDiffPanel-D9hAV8l7.js} +5 -5
  138. package/dist/web/assets/{WorkspaceEnvironmentMenu-DeODKxvW.js → WorkspaceEnvironmentMenu-B-K9XgFB.js} +3 -3
  139. package/dist/web/assets/{WorkspaceGitDialogs-CBarJYF-.js → WorkspaceGitDialogs-BJVFx_L3.js} +1 -1
  140. package/dist/web/assets/{WorkspaceMonacoEditor-Hmu5m_sO.js → WorkspaceMonacoEditor-p-FWMXoZ.js} +3 -3
  141. package/dist/web/assets/{arrow-up-right-BV2IHfb9.js → arrow-up-right-CFGI2YSt.js} +1 -1
  142. package/dist/web/assets/{chunk-YTGRET2L-PKzEfYnf.js → chunk-UHVJOMWN-BAlur2vw.js} +1 -1
  143. package/dist/web/assets/{clipboard-DDIvAWKp.js → clipboard-DIIxBort.js} +1 -1
  144. package/dist/web/assets/{cloud-upload-Dv6kFnfC.js → cloud-upload-BaQFNCTp.js} +1 -1
  145. package/dist/web/assets/{cssMode-BK0jFqWW.js → cssMode-6LOkSggB.js} +1 -1
  146. package/dist/web/assets/{folder-open-B9ixJQJX.js → folder-open-DZSxfPtr.js} +1 -1
  147. package/dist/web/assets/{folder-plus-DqSKvtNB.js → folder-plus-21v4D_Vx.js} +1 -1
  148. package/dist/web/assets/{git-commit-horizontal-C1lQvfxe.js → git-commit-horizontal-CgGixL64.js} +1 -1
  149. package/dist/web/assets/{htmlMode-CCV301b6.js → htmlMode-B5uRraNd.js} +1 -1
  150. package/dist/web/assets/index-DJcUXSsN.css +1 -0
  151. package/dist/web/assets/{index-DIaKfM8a.js → index-DOMrqhcz.js} +2 -2
  152. package/dist/web/assets/{info-BEvaynAD.js → info-BGTcmow7.js} +1 -1
  153. package/dist/web/assets/{jsonMode-Co4pyN4F.js → jsonMode-D3m8N4Gi.js} +1 -1
  154. package/dist/web/assets/{lspLanguageFeatures-CSU0G5da.js → lspLanguageFeatures-DoyipLsB.js} +1 -1
  155. package/dist/web/assets/{minimize-2-DT8t8wwP.js → minimize-2-B01qSko4.js} +1 -1
  156. package/dist/web/assets/{monaco.contribution-Cr0AaHCD.js → monaco.contribution--U8v3jpa.js} +2 -2
  157. package/dist/web/assets/{monaco.contribution-DSBAb_PC.js → monaco.contribution-BJyfaGX2.js} +2 -2
  158. package/dist/web/assets/{monaco.contribution-CBwGIQY1.js → monaco.contribution-Bc22foTx.js} +2 -2
  159. package/dist/web/assets/{monaco.contribution-DUZrs1D-.js → monaco.contribution-DuRhJ6zU.js} +2 -2
  160. package/dist/web/assets/{monitor-DGqnfsK9.js → monitor-eZP8ZTHe.js} +1 -1
  161. package/dist/web/assets/{play-C1XWyKh6.js → play-CGsWFR_B.js} +1 -1
  162. package/dist/web/assets/{python-Z1foxLdf.js → python-BNrLZWud.js} +1 -1
  163. package/dist/web/assets/{save-CX2kF74j.js → save-BLgjrccP.js} +1 -1
  164. package/dist/web/assets/{square-DMkXeYeV.js → square-CI1qNtvE.js} +1 -1
  165. package/dist/web/assets/{toggleHighContrast-CRMVp779.js → toggleHighContrast-B_GcTCnw.js} +1 -1
  166. package/dist/web/assets/{tsMode-Czu8YAqh.js → tsMode-CmruH_ys.js} +1 -1
  167. package/dist/web/assets/{upload-giKOPnl1.js → upload-DnlgGS2x.js} +1 -1
  168. package/dist/web/assets/useLocalAgentSchedules-BBhGUfK-.js +1 -0
  169. package/dist/web/assets/useProviderSettings-Bw-csWbH.css +1 -0
  170. package/dist/web/assets/useProviderSettings-DfhdkKdC.js +5 -0
  171. package/dist/web/assets/{useSessionTurnCache-CUYFsu_W.js → useSessionTurnCache-BwscKl5i.js} +1 -1
  172. package/dist/web/assets/{wifi-off-DbDXaV1N.js → wifi-off-Dz-4EDCc.js} +1 -1
  173. package/dist/web/assets/{workers-Cno4XklJ.js → workers-Bi9u46cp.js} +1 -1
  174. package/dist/web/assets/{yaml-C28t_C6h.js → yaml-DVTkiRnh.js} +1 -1
  175. package/dist/web/index.html +2 -2
  176. package/package.json +1 -1
  177. package/dist/chunks/app-server-runtime-FL2CHQU2.js +0 -2
  178. package/dist/chunks/chunk-5ZZM3TUN.js +0 -24
  179. package/dist/chunks/chunk-6JBWHR6T.js +0 -5
  180. package/dist/chunks/chunk-FKCWOASO.js +0 -49
  181. package/dist/chunks/chunk-ICZEOMPO.js +0 -2
  182. package/dist/chunks/chunk-JO7GRBOG.js +0 -2
  183. package/dist/chunks/chunk-M7PBDRKC.js +0 -2
  184. package/dist/chunks/chunk-P653BXMY.js +0 -3
  185. package/dist/chunks/chunk-PMZH2TKS.js +0 -4
  186. package/dist/chunks/chunk-WVNN3RB2.js +0 -2
  187. package/dist/chunks/cli-5QR7QNQJ.js +0 -2
  188. package/dist/chunks/core-commands-J2SJM5I5.js +0 -2
  189. package/dist/chunks/hosted-harness-runtime-PAYMAXH7.js +0 -2
  190. package/dist/chunks/hosted-profile-compiler-KQREWJA5.js +0 -2
  191. package/dist/chunks/import-YHSX6SBZ.js +0 -4
  192. package/dist/chunks/src-TNWF3IC5.js +0 -329
  193. package/dist/web/assets/App-CdDQ-lXE.css +0 -1
  194. package/dist/web/assets/App-D2f8_mGk.js +0 -235
  195. package/dist/web/assets/AppsView-CzbB5pXp.css +0 -1
  196. package/dist/web/assets/AppsView-DwK1UBJP.js +0 -1
  197. package/dist/web/assets/BrowserSidebar-Cj9VnkgU.js +0 -1
  198. package/dist/web/assets/LabsRoute-hHwZNbqN.js +0 -99
  199. package/dist/web/assets/MainPane-DJcd4tPk.js +0 -19
  200. package/dist/web/assets/ScheduledWorkPage-qX12p4B0.js +0 -1
  201. package/dist/web/assets/SettingsView-0KMs-r2I.js +0 -9
  202. package/dist/web/assets/SettingsView-CVsuQeCZ.css +0 -1
  203. package/dist/web/assets/index-1cMIFBxZ.css +0 -1
  204. package/dist/web/assets/useLocalAgentSchedules-BHxWmOeC.js +0 -1
@@ -1,49 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as Ie,b as W,c as x,g as ve,h as oe}from"./chunk-JO7GRBOG.js";import{l as S}from"./chunk-P653BXMY.js";import{a as u}from"./chunk-FTQLQJQV.js";var Se={codex:"Codex",claude_code:"Claude Code",hermes:"Hermes",openclaw:"OpenClaw",opencode:"OpenCode",grok_build:"Grok Build",pi:"Pi",oh_my_pi:"Oh My Pi"},T=32*1024*1024;import{homedir as bt}from"node:os";import{realpath as Ce,stat as le,readdir as It,readFile as vt}from"node:fs/promises";import{resolve as de,join as k,isAbsolute as St}from"node:path";import{opendir as gt,readFile as yt,stat as K}from"node:fs/promises";import{basename as wt,dirname as _t,join as O,resolve as ae}from"node:path";function Ne(t,e){let s=e.HERMES_HOME?.trim();if(s){let i=s.replace(/\$(\w+)|\$\{([^}]+)\}/gu,(o,a,r)=>e[a||r]??o);return ae(i==="~"?t:i.startsWith("~/")?O(t,i.slice(2)):i)}let n=e.HERMES_DATA_DIR_SUFFIX||"";return process.platform==="win32"?O(e.LOCALAPPDATA?.trim()||O(t,"AppData","Local"),`hermes${n}`):O(t,`.hermes${n}`)}u(Ne,"hermesHome");var Te=u(t=>K(t).then(e=>e.isDirectory()).catch(()=>!1),"isDirectory"),Oe=u(t=>K(t).then(e=>e.isFile()).catch(()=>!1),"isFile");async function ce(t,e){let s=[],n=await gt(t).catch(()=>null);if(!n)return s;let i=0;for await(let o of n){if(++i>100)throw new Error("More than 100 profile entries. Select the exact --source-path.");o.isDirectory()&&!o.isSymbolicLink()&&e(o.name)&&s.push(o.name)}return s.sort()}u(ce,"profileNames");async function Ae(t){if(wt(_t(t))==="profiles")return[{root:t}];let e=O(t,"profiles");try{let s=await ce(e,a=>/^[a-z0-9][a-z0-9_-]{0,63}$/u.test(a)),n=[];for(let a of s)await K(O(e,".deleted",a)).then(()=>!0).catch(()=>!1)||await Oe(O(e,a,"state.db"))&&n.push({root:O(e,a)});let i="",o=O(t,"active_profile");if(await K(o).then(a=>a.isFile()&&a.size<=1024).catch(()=>!1)&&(i=(await yt(o,"utf8")).replace(/^\uFEFF/u,"").trim().toLowerCase()),i&&i!=="default"){if(!/^[a-z0-9][a-z0-9_-]{0,63}$/u.test(i))return[{root:t,reason:"Hermes active profile is invalid. Select the exact --source-path."}];let a=n.findIndex(r=>r.root===O(e,i));a<0?n.unshift({root:O(e,i),reason:"Hermes active profile has no retained live state database. Select a profile explicitly."}):n.unshift(...n.splice(a,1))}return(await Oe(O(t,"state.db"))||!n.length)&&n.push({root:t}),n}catch(s){return[{root:t,reason:s instanceof Error?s.message:"Cannot inventory Hermes profiles. Select the exact --source-path."}]}}u(Ae,"hermesLocations");function Y(t){return/^[a-z0-9][a-z0-9._-]{0,63}$/u.test(t)&&!t.endsWith(".")&&!/^(?:con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/iu.test(t)}u(Y,"validOmpProfile");async function Re(t,e){let s=O(t,e.PI_CONFIG_DIR||".omp"),n=(e.OMP_PROFILE!==void 0?e.OMP_PROFILE:e.PI_PROFILE)?.trim();if(n&&n!=="default"&&!Y(n))return[{root:s,reason:"Oh My Pi profile is invalid. Select the exact --source-path."}];if(e.PI_CODING_AGENT_SESSION_DIR)return[{root:ae(e.PI_CODING_AGENT_SESSION_DIR)}];let i=(process.platform==="linux"||process.platform==="darwin")&&e.XDG_DATA_HOME?O(e.XDG_DATA_HOME,"omp"):void 0;async function o(a){let r=a?O(s,"profiles",a,"agent"):O(s,"agent"),l=e.PI_PROFILE?.trim(),c=l&&Y(l)?O(s,"profiles",l,"agent"):void 0,p=!a&&e.PI_CODING_AGENT_DIR&&e.PI_CODING_AGENT_DIR!==c?ae(e.PI_CODING_AGENT_DIR):void 0,d=i&&(a?O(i,"profiles",a):i);return{root:(!p||p===r)&&d&&await Te(d)?d:p||r}}if(u(o,"location"),n||e.OMP_PROFILE!==void 0||e.PI_PROFILE!==void 0||e.PI_CODING_AGENT_DIR)return[await o(n&&n!=="default"?n:void 0)];try{let a=new Set(await ce(O(s,"profiles"),Y));if(i)for(let l of await ce(O(i,"profiles"),Y))a.add(l);let r=[await o()];for(let l of[...a].sort()){let c=await o(l);await Te(O(c.root,"sessions"))&&r.push(c)}return r}catch(a){return[{root:s,reason:a instanceof Error?a.message:"Cannot inventory Oh My Pi profiles. Select the exact --source-path."}]}}u(Re,"ompLocations");async function Rs(t){let e=t.home??bt(),s=t.environment??process.env,n={codex:s.CODEX_HOME||k(e,".codex"),claude_code:s.CLAUDE_CONFIG_DIR||k(e,".claude"),hermes:Ne(e,s),openclaw:s.OPENCLAW_STATE_DIR||k(e,".openclaw"),opencode:k(s.XDG_DATA_HOME||k(e,".local/share"),"opencode"),grok_build:s.GROK_HOME||k(e,".grok"),pi:s.PI_CODING_AGENT_DIR||k(e,".pi/agent"),oh_my_pi:k(e,".omp/agent")},i=n.pi,o=!1;if(s.PI_CODING_AGENT_SESSION_DIR)n.pi=de(s.PI_CODING_AGENT_SESSION_DIR);else if(!t.locations?.pi)try{let r=k(i,"settings.json");if((await le(r)).size<=1024*1024){let l=JSON.parse(await vt(r,"utf8"));typeof l.sessionDir=="string"&&l.sessionDir.trim()&&(St(l.sessionDir)?n.pi=l.sessionDir:o=!0)}}catch{}let a=[];for(let r of Object.keys(Se)){let l=t.locations?.[r]?[{root:t.locations[r]}]:r==="hermes"?await Ae(de(n.hermes)):r==="oh_my_pi"?await Re(e,s):[{root:n[r]}];for(let c of l){let p=de(c.root),d=!1,E=!1;try{p=await Ce(p);let h=await le(p);E=h.isFile(),d=h.isDirectory()||E}catch{}if(c.reason&&(d=!1),r==="openclaw"&&d&&!E){let h=k(p,"agents"),_=await It(h,{withFileTypes:!0}).catch(()=>[]),y=[];for(let f of _.slice(0,100)){if(!f.isDirectory()||f.isSymbolicLink())continue;let m=k(h,f.name,"agent","openclaw-agent.sqlite");await le(m).then(b=>b.isFile()).catch(()=>!1)&&y.push(await Ce(m))}if(y.length){for(let f of y)a.push({source:r,root:f,machineId:t.machineId,instanceId:`native-${S([t.machineId,r,f]).slice(0,40)}`,acquisition:"sqlite",available:!0,capabilities:{history:!0,live:!0,nativeResume:!1}});continue}}if(r==="pi"&&o&&!t.locations?.pi){a.push({source:r,root:p,machineId:t.machineId,instanceId:`native-${S([t.machineId,r,p]).slice(0,40)}`,acquisition:"files",available:!1,capabilities:{history:!1,live:!1,nativeResume:!1},reason:"Pi config uses a working-directory-relative sessionDir. Select its resolved directory with --source-path."});continue}a.push({source:r,root:p,machineId:t.machineId,instanceId:`native-${S([t.machineId,r,p]).slice(0,40)}`,acquisition:E&&!/\.(?:db|sqlite)$/u.test(p)?"files":r==="hermes"||r==="opencode"||r==="openclaw"&&E?"sqlite":r==="openclaw"?"bundle":"files",available:d,capabilities:{history:d,live:d&&(r!=="openclaw"||E),nativeResume:!1},...d?{}:{reason:c.reason??"Source location is missing or unreadable. Select a custom location."}})}}return a.filter((r,l)=>a.findIndex(c=>c.instanceId===r.instanceId)===l)}u(Rs,"discoverSources");import{open as Ft,lstat as $t,readdir as Pt,readFile as Ht,realpath as Qe,stat as tt}from"node:fs/promises";import{basename as z,dirname as jt,isAbsolute as ue,join as Q,relative as Bt,resolve as qt,sep as Wt}from"node:path";import{zstdDecompressSync as Gt}from"node:zlib";function A(t,e="milliseconds"){if(typeof t!="number"&&typeof t!="string")return null;let s=new Date(typeof t=="number"&&e==="seconds"?t*1e3:t);return Number.isFinite(s.getTime())?s.toISOString():null}u(A,"connectedTimestamp");function Tt(t){return{path:t.path,contentHash:S(t.text),sizeBytes:new TextEncoder().encode(t.text).length}}u(Tt,"connectedFileIdentity");function R(t){if(t.events.length+(t.unmappedEvents?.length??0)>x.events)throw new Error("connected_event_limit");let e=t.events.map((r,l)=>({...r,sequence:l}));if(new Set(e.map(r=>r.id)).size!==e.length)throw new Error("connected_duplicate_event");let s=e.flatMap((r,l)=>r.kind==="message"&&r.role==="user"?[l]:[]);if(!s.length)throw new Error("The session has no retained user request.");if(s.length+(t.includeConversation===!1?0:1)>x.boundaries)throw new Error("connected_boundary_limit");let n=`family-${S([t.origin,...t.acquisition?[t.acquisition.sourceInstanceId]:[],t.parentSessionId??t.sessionId]).slice(0,32)}`,i=s.map((r,l)=>{let c=s[l+1]??e.length,p=e.slice(r+1,c),d=p.filter(oe).at(-1),E=p.filter(I=>I.kind==="tool_call"||I.kind==="tool_result"),h=new Set(E.filter(I=>I.kind==="tool_call").map(I=>I.callId)),_=new Set(E.filter(I=>I.kind==="tool_result").map(I=>I.callId)),y=E.some(I=>!I.callId)||[...h].some(I=>!_.has(I))||[..._].some(I=>!h.has(I)),f=[...p].reverse().find(I=>I.kind==="terminal"),m=f&&typeof f.content=="object"&&f.content!==null&&!Array.isArray(f.content)?f.content.status:null,b=e.slice(0,r+1).some(I=>I.kind==="compaction"),N=p.some(I=>I.kind==="unknown");return{id:`case-${S([t.origin,...t.acquisition?[t.acquisition.sourceInstanceId]:[],t.sessionId,t.branchId??null,e[r].id]).slice(0,40)}`,familyKey:n,projection:"turn",requestEventId:e[r].id,start:r,end:c,inputHash:S(e.slice(0,r+1)),outputHash:d?S(d.content):null,revisionHash:S(p),terminal:m==="completed"||m==="failed"||m==="cancelled"?m:"unknown",coverage:{answer:!!d,context:t.contextComplete===!1?"unknown":b?"compacted":"retained",process:E.length?y||N?"partial":"retained":N?"partial":"absent",artifacts:p.some(I=>I.kind==="artifact")?"references_only":"absent",replay:"unavailable",gaps:[...d?[]:["No recorded assistant answer."],...t.contextComplete===!1?["The source omits preceding context."]:[],...b?["Earlier context was compacted by the source."]:[],...y?["Tool call/result correlation is incomplete."]:[],...N?["Some source events have no supported process mapping."]:[],...f?[]:["No terminal receipt was recorded."],"No resettable execution environment was admitted."]}}});if(t.includeConversation!==!1){let r=i[0],l=i.at(-1),c=e.slice(r.start+1),p=c.filter(oe);i.push({...r,id:`conversation-${S([t.origin,...t.acquisition?[t.acquisition.sourceInstanceId]:[],t.sessionId,t.branchId??null]).slice(0,40)}`,projection:"conversation",end:e.length,outputHash:p.length?S(p.map(d=>d.content)):null,revisionHash:S(c),terminal:l.terminal,coverage:{...r.coverage,answer:p.length>0,process:i.some(d=>d.coverage.process==="partial")?"partial":i.some(d=>d.coverage.process==="retained")?"retained":"absent",context:i.some(d=>d.coverage.context==="unknown")?"unknown":i.some(d=>d.coverage.context==="compacted")?"compacted":"retained",artifacts:i.some(d=>d.coverage.artifacts==="references_only")?"references_only":"absent",gaps:[...new Set(i.flatMap(d=>d.coverage.gaps))].slice(0,100)}})}let o={schemaVersion:Ie,normalizerVersion:W,origin:t.origin,sessionId:t.sessionId,branchId:t.branchId??null,parentSessionId:t.parentSessionId??null,exporterVersion:t.exporterVersion??null,sourceFiles:t.files.map(Tt).sort((r,l)=>r.path.localeCompare(l.path)),...t.acquisition?{acquisition:t.acquisition}:{},events:e,unmappedEvents:(t.unmappedEvents??[]).map((r,l)=>({...r,sequence:l})),boundaries:i,warnings:t.warnings??[]},a=ve.parse({...o,contentHash:S(o)});if(new TextEncoder().encode(JSON.stringify(a)).length>x.decodedBytes)throw new Error("connected_normalized_size_limit");return a}u(R,"normalizeConnectedSession");function F(t){let e=t.text.replace(/^\uFEFF/u,"").split(/\r?\n/u);if(e.length>x.events+1)throw new Error("connected_event_limit");return e.flatMap((s,n)=>{if(!s.trim())return[];if(new TextEncoder().encode(s).length>x.lineBytes)throw new Error(`Source line ${n+1} exceeds the limit.`);let i;try{i=JSON.parse(s)}catch{throw new Error(`Invalid JSON on line ${n+1}.`)}if(!i||typeof i!="object"||Array.isArray(i))throw new Error(`Unsupported record on line ${n+1}.`);return[i]})}u(F,"connectedJsonLines");function g(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{}}u(g,"object");function w(t){return{sequence:0,occurredAt:null,role:null,callId:null,parentId:null,usage:null,...t}}u(w,"event");function v(t){return JSON.parse(JSON.stringify(t??null))}u(v,"json");function L(t,e,s="reported_invocation"){let n=g(t),i=u((...c)=>{let p=c.find(d=>typeof d=="number"&&Number.isSafeInteger(d)&&d>=0);return typeof p=="number"?p:null},"number"),o=i(n.input_tokens,n.prompt_tokens),a=i(n.output_tokens,n.completion_tokens),r=i(n.cache_read_input_tokens,n.cached_input_tokens,g(n.input_tokens_details).cached_tokens),l=i(n.total_tokens);return o===null&&a===null&&r===null&&l===null?null:{invocationId:e,inputTokens:o,outputTokens:a,cachedInputTokens:r,totalTokens:l,provenance:s}}u(L,"sourceUsage");function xe(t,e){let s=new Set(e.map(c=>g(c.params).sessionId).filter(c=>typeof c=="string"));if(s.size!==1)throw new Error("Grok Build updates must identify exactly one retained session.");let n=[],i=new Set,o=new Map,a=null,r=null,l=!0;for(let c of e){let p=g(c.params),d=g(p.update),E=g(p._meta),h=d.sessionUpdate;if(typeof E.eventId!="string"||i.has(E.eventId))throw new Error("Grok Build updates require unique native event IDs.");i.add(E.eventId);let _=E.eventId,y=A(E.agentTimestampMs??(typeof c.timestamp=="number"?c.timestamp*1e3:null)),f=g(d.content);if(h==="user_message_chunk"){if(f.type!=="text"||typeof f.text!="string")throw new Error("Grok user content type requires a qualified adapter.");!a||l?(a=w({id:_,kind:"message",role:"user",occurredAt:y,content:f.text}),n.push(a),r=null,l=!1):a.content=String(a.content)+f.text}else if(h==="agent_message_chunk"){if(f.type!=="text"||typeof f.text!="string"){n.push(w({id:_,kind:"unknown",occurredAt:y,content:v(d)}));continue}r?r.content=String(r.content)+f.text:(r=w({id:_,kind:"message",role:"assistant",occurredAt:y,content:f.text}),n.push(r))}else if(h==="tool_call"||h==="tool_call_update"){let m=typeof d.toolCallId=="string"?d.toolCallId:null;if(!m){n.push(w({id:_,kind:"unknown",occurredAt:y,content:v(d)}));continue}let b=o.get(m);b?d.rawInput!==void 0&&(b.content=v({title:d.title,input:d.rawInput})):(b=w({id:`${_}:call`,kind:"tool_call",callId:m,occurredAt:y,content:v({title:d.title,input:d.rawInput})}),o.set(m,b),n.push(b)),(d.status==="completed"||d.status==="failed")&&n.push(w({id:`${_}:result`,kind:"tool_result",role:"tool",callId:m,occurredAt:y,content:v({status:d.status,output:d.rawOutput,content:d.content})}))}else if(h==="turn_completed"){let m=g(d.usage),b=typeof d.prompt_id=="string"?d.prompt_id:_;n.push(w({id:_,kind:"terminal",occurredAt:y,content:{status:d.stop_reason==="end_turn"?"completed":d.stop_reason==="cancelled"?"cancelled":"failed"},usage:L({input_tokens:m.inputTokens,output_tokens:m.outputTokens,cached_input_tokens:m.cachedReadTokens,total_tokens:m.totalTokens},b)})),l=!0,r=null,a=null}else h!=="agent_thought_chunk"&&n.push(w({id:_,kind:"unknown",occurredAt:y,content:v(d)}))}return R({origin:"grok_build",sessionId:String([...s][0]),files:[t],events:n,contextComplete:!1,warnings:["Grok retained ACP updates omit system context and encrypted reasoning. Tool coverage reflects only logged updates."]})}u(xe,"parseGrokBuildSession");function Le(t,e,s,n){let i=e.filter(m=>m.type==="session"),o=i[0];if(i.length!==1||!o||!(s==="openclaw"?[3,4].includes(Number(o.version)):o.version===3)||typeof o.id!="string")throw new Error("Unsupported native session tree version.");let a,l=(s!=="openclaw"?e:e.map(m=>{if(m.type==="session")return m;if(m.type==="leaf"){if(typeof m.targetId!="string")throw new Error("OpenClaw leaf control does not select a retained entry.");return a=m.targetId,m}if(typeof m.id!="string")throw new Error("OpenClaw transcript entry is missing its native identity.");let b=m.parentId===void 0?a??null:m.parentId;return m.appendMode!=="side"&&(a=m.id),{...m,parentId:b}})).filter(m=>m.type!=="session"&&m.type!=="title"&&m.type!=="leaf"),c=new Map,p=new Set;for(let m of l){if(typeof m.id!="string"||c.has(m.id))throw new Error("Session tree has missing or duplicate entry identities.");c.set(m.id,m),typeof m.parentId=="string"&&p.add(m.parentId)}n??=a;let d=[...c.keys()].filter(m=>!p.has(m));if(!n&&d.length!==1)throw new Error("Select a branch leaf for this branched session.");let E=n??d[0];if(!E||!c.has(E))throw new Error("The selected session branch is unavailable.");let h=[],_=new Set,y=E;for(;y;){if(_.has(y))throw new Error("Session branch contains a cycle.");_.add(y);let m=c.get(y);if(!m)throw new Error("Session branch has a missing ancestor.");h.push(m),y=typeof m.parentId=="string"?m.parentId:null}h.reverse();let f=[];for(let m of h){let b=String(m.id),N={occurredAt:A(m.timestamp),parentId:typeof m.parentId=="string"?m.parentId:null};if(m.type==="compaction"||m.type==="branch_summary"){f.push(w({...N,id:b,kind:"compaction",content:v({summary:m.summary,firstKeptEntryId:m.firstKeptEntryId})}));continue}if(m.type!=="message")continue;let I=g(m.message),M=I.role;if(M==="toolResult"){f.push(w({...N,id:b,kind:"tool_result",role:"tool",callId:typeof I.toolCallId=="string"?I.toolCallId:null,content:v({content:I.content,isError:I.isError===!0})}));continue}if(M!=="user"&&M!=="assistant"&&M!=="system"){f.push(w({...N,id:b,kind:"unknown",content:v({role:M,content:I.content})}));continue}let be=Array.isArray(I.content)?I.content.map(g):[],re=typeof I.content=="string"?I.content:be.filter(j=>j.type==="text").map(j=>String(j.text??"")).join(`
3
- `),J=g(I.usage),ie=L({input_tokens:J.input,output_tokens:J.output,cached_input_tokens:J.cacheRead,total_tokens:J.totalTokens},b);re||M!=="assistant"?f.push(w({...N,id:b,kind:"message",role:M,content:M==="system"&&!re&&I.sections?v(I.sections):re,usage:ie})):ie&&f.push(w({...N,id:`${b}:usage`,kind:"usage",content:null,usage:ie}));for(let[j,U]of be.entries())U.type==="toolCall"?f.push(w({...N,id:`${b}:call:${j}`,kind:"tool_call",callId:typeof U.id=="string"?U.id:null,content:v({name:U.name,arguments:U.arguments})})):U.type!=="text"&&U.type!=="thinking"&&f.push(w({...N,id:`${b}:block:${j}`,kind:"unknown",content:v(U)}));M==="assistant"&&["stop","error","aborted"].includes(String(I.stopReason))&&f.push(w({...N,id:`${b}:terminal`,kind:"terminal",content:{status:I.stopReason==="stop"?"completed":I.stopReason==="aborted"?"cancelled":"failed"}}))}return R({origin:s,sessionId:o.id,branchId:null,...s==="openclaw"?{contextComplete:!1}:{},files:[t],events:f,exporterVersion:`session-v${o.version}`,warnings:["Only the selected branch is included. Private provider payloads and credential metadata are excluded."]})}u(Le,"parsePiSession");function ke(t,e){let s=g(e),n=g(s.info);if(typeof n.id!="string"||!Array.isArray(s.messages))throw new Error("OpenCode requires its native JSON session export (info and messages).");let i=[];for(let o of s.messages){let a=g(o),r=g(a.info),l=g(r.time);if(typeof r.id!="string"||r.sessionID!==n.id||!Array.isArray(a.parts))throw new Error("OpenCode message identity does not match its session.");let c=r.role;if(c!=="user"&&c!=="assistant")throw new Error("Unsupported OpenCode message role.");let p={occurredAt:A(l.created),parentId:typeof r.parentID=="string"?r.parentID:null},d=a.parts.map(g);if(d.some(f=>f.sessionID!==n.id||f.messageID!==r.id||typeof f.id!="string"))throw new Error("OpenCode part identity does not match its message.");let E=d.filter(f=>f.type==="text").map(f=>String(f.text??"")).join(`
4
- `),h=g(r.tokens),_=g(h.cache),y=L({input_tokens:h.input,output_tokens:h.output,cached_input_tokens:_.read,total_tokens:h.total},r.id);E||c==="user"?i.push(w({...p,id:r.id,kind:"message",role:c,content:E,usage:y})):y&&i.push(w({...p,id:`${r.id}:usage`,kind:"usage",content:null,usage:y}));for(let f of d){let m=String(f.id);if(f.type==="tool"){let b=g(f.state),N=typeof f.callID=="string"?f.callID:null;i.push(w({...p,id:`${m}:call`,kind:"tool_call",callId:N,content:v({name:f.tool,arguments:b.input})})),(b.status==="completed"||b.status==="error")&&i.push(w({...p,id:`${m}:result`,kind:"tool_result",role:"tool",callId:N,content:v({output:b.output,error:b.error,status:b.status})}))}else f.type==="compaction"?i.push(w({...p,id:m,kind:"compaction",content:v(f)})):["text","reasoning","step-start","step-finish"].includes(String(f.type))||i.push(w({...p,id:m,kind:"unknown",content:v(f)}))}c==="assistant"&&(r.finish==="stop"||r.error)&&i.push(w({...p,id:`${r.id}:terminal`,kind:"terminal",content:{status:r.error?"failed":"completed"}}))}return R({origin:"opencode",sessionId:n.id,parentSessionId:typeof n.parentID=="string"?n.parentID:null,exporterVersion:typeof n.version=="string"?n.version:null,files:[t],events:i,warnings:["Source-reported usage is not an OpenPond billing receipt."]})}u(ke,"parseOpenCodeSession");var pe="codex-native-authorization-v1",Ot=pe;function De(t){let e=[],s=u((o,a,r)=>{let l={policy:Ot,sourcePath:o,sourceHash:S(a),entries:r};return e.push(l),l},"omit"),n=u((o,a)=>o.replace(/<permissions instructions>[\s\S]*?<\/permissions instructions>/gu,r=>r.replace(/^## Approved command prefixes\r?\n[\s\S]*?(?=^## |<\/permissions instructions>)/gmu,l=>{let c=s(a,l,null);return`## Approved command prefixes
5
- [Native authorization rules omitted; policy ${c.policy}; source hash ${c.sourceHash}]
6
- `})),"permissionsText"),i=g(t.payload);if(t.type==="response_item"&&i.type==="message"&&["system","developer"].includes(String(i.role))){let o=typeof i.content=="string"?n(i.content,"/payload/content"):Array.isArray(i.content)?i.content.map((a,r)=>{let l=g(a);return typeof l.text=="string"?{...l,text:n(l.text,`/payload/content/${r}/text`)}:a}):i.content;return{row:{...t,payload:{...i,content:o}},omissions:e}}if(t.type==="world_state"){let o=g(i.state),a=g(o.permissions);if(Array.isArray(a.approved_command_prefixes)){let r=s("/payload/state/permissions/approved_command_prefixes",a.approved_command_prefixes,a.approved_command_prefixes.length);return{row:{...t,payload:{...i,state:{...o,permissions:{...a,approved_command_prefixes:{omitted:"native_authorization_state",...r}}}}},omissions:e}}}return{row:t,omissions:e}}u(De,"projectCodexAuthorization");function Me(t,e){let s=g(e.find(a=>a.type==="session_meta")?.payload);if(typeof s.id!="string")throw new Error("This is not a supported Codex rollout: session_meta.id is missing.");let n=[],i=null,o=0;for(let[a,r]of e.entries()){let l=De(r);o+=l.omissions.length;let c=g(l.row.payload);if(r.type==="session_meta")continue;if(r.type==="turn_context"){i=typeof c.turn_id=="string"?c.turn_id:i;continue}let d={id:typeof c.id=="string"?c.id:`codex-event-${S([a,r]).slice(0,32)}`,occurredAt:A(r.timestamp),parentId:i};if(r.type==="response_item")c.type==="message"&&["user","assistant","system","developer"].includes(String(c.role))?n.push(w({...d,kind:"message",role:c.role==="developer"?"system":c.role,content:v(c.content)})):c.type==="function_call"||c.type==="custom_tool_call"?n.push(w({...d,kind:"tool_call",callId:typeof c.call_id=="string"?c.call_id:null,content:v(c)})):c.type==="function_call_output"||c.type==="custom_tool_call_output"?n.push(w({...d,kind:"tool_result",role:"tool",callId:typeof c.call_id=="string"?c.call_id:null,content:v(c.output)})):n.push(w({...d,kind:"unknown",content:v(c)}));else if(r.type==="compacted")n.push(w({...d,kind:"compaction",content:v(c)}));else if(r.type==="event_msg"){if(["user_message","agent_message","agent_reasoning","task_started"].includes(String(c.type)))continue;if(c.type==="task_complete"||c.type==="turn_aborted")n.push(w({...d,kind:"terminal",content:{status:c.type==="task_complete"?"completed":"cancelled",source:v(c)}}));else if(c.type==="token_count"){let E=g(c.info),h=L(E.total_token_usage,`codex-cumulative:${s.id}:${a}`,"reported_cumulative");n.push(w({...d,kind:"usage",usage:h,content:v(c)}))}else n.push(w({...d,kind:"unknown",content:v(c)}))}else n.push(w({...d,kind:"unknown",content:v(l.row)}))}return R({origin:"codex",sessionId:s.id,parentSessionId:typeof s.forked_from_id=="string"?s.forked_from_id:null,exporterVersion:typeof s.cli_version=="string"?s.cli_version:null,files:[t],events:n,warnings:["Codex cumulative usage is retained as reported totals and is not summed as billed invocations.","Referenced files are unavailable unless separately admitted.",...o?[`Codex native authorization state excluded by codex-native-authorization-v1 from ${o} locations. Omission markers retain source-section hashes; sourceFiles retains original byte hashes. Other conversation evidence is unchanged and still requires privacy admission.`]:[]]})}u(Me,"parseCodexSession");function G(t){let e=t.filter(p=>(p.type==="user"||p.type==="assistant")&&typeof p.uuid=="string"),s=new Set(e.flatMap(p=>typeof p.sessionId=="string"?[p.sessionId]:[]));if(s.size!==1||!e.length)throw new Error("A supported Claude Code transcript must identify one session with UUID messages.");let n=[...s][0],i=t.filter(p=>typeof p.uuid=="string"&&p.sessionId===n),o=new Map(i.map(p=>[p.uuid,p]));if(o.size!==i.length)throw new Error("Claude Code transcript contains duplicate message UUIDs.");let a=new Set(i.flatMap(p=>typeof p.parentUuid=="string"?[p.parentUuid]:[])),r=i.filter(p=>!a.has(p.uuid));if(!r.length)throw new Error("Claude Code transcript has no selectable branch leaf.");function l(p){let d=o.get(p);if(!d)throw new Error("The selected Claude Code branch leaf is missing.");let E=[],h=new Set,_=!1;for(;d;){let y=d.uuid;if(h.has(y))throw new Error("Claude Code branch contains a parent cycle.");h.add(y),E.unshift(d);let f=d.parentUuid;if(typeof f!="string")break;d=o.get(f),d||(_=!0)}return{chain:E,missingParent:_,chainHash:S(E)}}u(l,"select");function c(){if(r.length>256)throw new Error("This transcript exceeds the 256-branch inspection limit.");return r.map(p=>{let d=l(p.uuid),E=d.chain.filter(f=>f.type==="user"||f.type==="assistant"),h=E.at(-1),_=g(h?.message).content,y=typeof _=="string"?_:Array.isArray(_)?_.flatMap(f=>typeof g(f).text=="string"?[g(f).text]:[]).join(" "):"";return{leafId:p.uuid,chainHash:d.chainHash,title:y.slice(0,180),updatedAt:A(h?.timestamp),messages:E.length}})}return u(c,"branches"),{sessionId:n,leaves:r,select:l,branches:c}}u(G,"claudeGraph");function Ue(t,e,s){let n=G(e);if(!s&&n.leaves.length!==1)throw new Error("This transcript has multiple branches. Select a branch leaf UUID before importing.");let{chain:i,missingParent:o}=n.select(s??n.leaves[0].uuid),a=[];for(let r of i){if(r.type!=="user"&&r.type!=="assistant")continue;let l=g(r.message),c=l.content,p={occurredAt:A(r.timestamp),parentId:typeof r.parentUuid=="string"?r.parentUuid:null},d=r.type==="user"?"user":"assistant",E=Array.isArray(c)?c:[{type:"text",text:c}],h=E.filter(_=>g(_).type==="text");h.length&&a.push(w({...p,id:r.uuid,kind:"message",role:d,content:v(h)})),d==="assistant"&&l.usage&&a.push(w({...p,id:`${r.uuid}:usage`,kind:"usage",content:v(l.usage),usage:L(l.usage,typeof l.id=="string"?l.id:r.uuid)}));for(let[_,y]of E.entries()){let f=g(y);if(f.type==="text"||f.type==="thinking"||f.type==="redacted_thinking")continue;let m=`${r.uuid}:${_}`;f.type==="tool_use"?a.push(w({...p,id:m,kind:"tool_call",callId:typeof f.id=="string"?f.id:null,content:v(f)})):f.type==="tool_result"?a.push(w({...p,id:m,kind:"tool_result",role:"tool",callId:typeof f.tool_use_id=="string"?f.tool_use_id:null,content:v(f)})):a.push(w({...p,id:m,kind:"unknown",content:v(f)}))}l.stop_reason==="end_turn"&&a.push(w({...p,id:`${r.uuid}:terminal`,kind:"terminal",content:{status:"completed"}}))}return e.some(r=>r.type==="system"&&r.subtype==="compact_boundary")&&a.unshift(w({id:`compaction-${S(e.filter(r=>r.subtype==="compact_boundary")).slice(0,32)}`,kind:"compaction",content:{source:"claude_compact_boundary"}})),R({origin:"claude_code",sessionId:n.sessionId,branchId:null,parentSessionId:typeof i[0]?.parentSessionId=="string"?i[0].parentSessionId:null,exporterVersion:typeof i.at(-1)?.version=="string"?i.at(-1).version:null,files:[t],events:a,contextComplete:!o,warnings:[...o?["The transcript omits an ancestor; complete context is unavailable."]:[],...i.some(r=>r.isSidechain)?["This is a subagent/sidechain transcript; parent context is not implicitly imported."]:[],"Claude Code transcript schema is internal; only the declared message shapes are normalized."]})}u(Ue,"parseClaudeSession");function Fe(t,e){let s=[];for(let[n,i]of t.entries()){let o=g(i),a=typeof o.entryId=="string"?o.entryId:typeof o.id=="string"?o.id:typeof o.id=="number"&&Number.isSafeInteger(o.id)?String(o.id):typeof o.message_id=="string"?o.message_id:`${e}-${S([n,o]).slice(0,32)}`,r={occurredAt:A(o.timestamp,e==="hermes"?"seconds":"milliseconds"),parentId:typeof o.parentId=="string"?o.parentId:null};if(o.role==="tool"){s.push(w({...r,id:a,kind:"tool_result",role:"tool",callId:typeof o.tool_call_id=="string"?o.tool_call_id:null,content:v(o.content)}));continue}if(!["user","assistant","system"].includes(String(o.role))){s.push(w({...r,id:a,kind:"unknown",content:v(o)}));continue}if(s.push(w({...r,id:a,kind:"message",role:o.role,content:v(o.content),usage:L(o.usage,a)})),Array.isArray(o.tool_calls))for(let[l,c]of o.tool_calls.entries()){let p=g(c);s.push(w({...r,id:`${a}:call:${l}`,kind:"tool_call",callId:typeof p.id=="string"?p.id:null,content:v(p)}))}(o.finish_reason==="stop"||o.stop_reason==="end_turn")&&s.push(w({...r,id:`${a}:terminal`,kind:"terminal",content:{status:"completed"}}))}return s}u(Fe,"historyEvents");function $e(t,e){let s=typeof e.id=="string"?e.id:typeof e.session_id=="string"?e.session_id:null;if(!s||!Array.isArray(e.messages))throw new Error("Hermes requires a full-session export with id or session_id and messages.");if(e.message_count!==void 0&&e.message_count!==e.messages.length)throw new Error("Hermes full-session message count differs from the retained messages.");let n=Array.isArray(e.lineage_session_ids)?e.lineage_session_ids.find(o=>typeof o=="string"&&o):null,i=Fe(e.messages,"hermes");return typeof e.system_prompt=="string"&&e.system_prompt.trim()&&i.unshift(w({id:`hermes-system-${S(e.system_prompt).slice(0,32)}`,kind:"message",role:"system",content:e.system_prompt})),R({origin:"hermes",sessionId:s,parentSessionId:typeof n=="string"?n:typeof e.parent_session_id=="string"?e.parent_session_id:null,exporterVersion:typeof e.version=="string"?e.version:null,files:[t],events:i,warnings:["Reported usage is not an OpenPond billing receipt.","Exporter redaction and missing tools/artifacts remain evidence gaps.",...e.session_id&&!e.id?["This is a Hermes session backup. Exporter version and terminal receipts may be unavailable."]:[]]})}u($e,"parseHermesEvidence");function Pe(t){let e=u(d=>{let E=t.find(h=>h.path===d);if(!E)throw new Error(`OpenClaw bundle is missing ${d}.`);return E},"read"),s=g(JSON.parse(e("manifest.json").text)),n=g(JSON.parse(e("session-branch.json").text)),i=e("events.jsonl"),o=F(i);if(s.traceSchema!=="openclaw-trajectory"||s.schemaVersion!==1||typeof s.sessionId!="string"||typeof s.traceId!="string")throw new Error("Unsupported OpenClaw trajectory manifest.");if(s.leafId!==n.leafId||s.eventCount!==o.length||o.some(d=>d.traceSchema!==s.traceSchema||d.schemaVersion!==1||d.sessionId!==s.sessionId||d.traceId!==s.traceId))throw new Error("OpenClaw bundle identity/count does not match its manifest.");if(!Array.isArray(n.entries))throw new Error("OpenClaw active branch entries are missing.");if(n.header&&g(n.header).id!==s.sessionId)throw new Error("OpenClaw branch header differs from the manifest session.");let a=new Set,r=[];for(let[d,E]of n.entries.entries()){let h=g(E);if(typeof h.id!="string"||a.has(h.id)||d>0&&h.parentId!==g(n.entries[d-1]).id)throw new Error("OpenClaw active branch is duplicate, incomplete or unordered.");a.add(h.id),h.type==="message"&&r.push({...g(h.message),entryId:h.id,parentId:h.parentId??null,timestamp:h.timestamp??g(h.message).timestamp})}if(n.entries.length&&g(n.entries.at(-1)).id!==n.leafId)throw new Error("OpenClaw branch does not reach its leaf.");let l=Fe(r,"openclaw"),c=[],p=new Set;for(let[d,E]of o.entries()){if(!Number.isSafeInteger(E.seq)||E.seq<0||p.has(E.seq)||d>0&&Number(o[d-1].seq)>=Number(E.seq))throw new Error("OpenClaw events have invalid/duplicate/unordered sequences.");p.add(E.seq),c.push(w({id:`trajectory:${s.traceId}:${E.seq}`,kind:"unknown",occurredAt:A(E.ts),content:v(E)}))}return R({origin:"openclaw",sessionId:s.sessionId,files:t,events:l,unmappedEvents:c,exporterVersion:typeof s.openclawVersion=="string"?s.openclawVersion:null,warnings:["Raw trajectory events are retained; unqualified event types are not advertised as complete process grading.",...Array.isArray(s.warnings)?s.warnings.map(d=>typeof g(d).message=="string"?String(g(d).message).slice(0,500):"The source exporter reports incomplete evidence."):[]].slice(0,100)})}u(Pe,"parseOpenClawEvidence");function kn(t){return t==="codex"?`${W}/${pe}`:W}u(kn,"agentImportNormalizerRevision");function He(t){if(!t.files.length||t.files.length>x.files)throw new Error("Choose between 1 and 100 source files.");let e=new Set,s=0;for(let r of t.files){if(r.path.length>500||r.path.startsWith("/")||r.path.includes("\\")||r.path.split("/").some(l=>!l||l==="."||l==="..")||e.has(r.path))throw new Error("Unsafe or duplicate source file path.");e.add(r.path),s+=new TextEncoder().encode(r.text).length}if(s>x.decodedBytes)throw new Error("Decoded source files exceed 64 MiB.");let n=[],i=[],o=u((r,l)=>{try{n.push(...l().map(c=>t.acquisition?R({origin:c.origin,sessionId:c.sessionId,branchId:c.branchId,parentSessionId:c.parentSessionId,exporterVersion:c.exporterVersion,files:t.files.filter(p=>c.sourceFiles.some(d=>d.path===p.path)),events:c.events,unmappedEvents:c.unmappedEvents,warnings:c.warnings,contextComplete:!c.boundaries.some(p=>p.coverage.context==="unknown"),acquisition:t.acquisition}):c))}catch(c){i.push({file:r,message:c instanceof Error?c.message:"Unsupported session."})}},"attempt");if(t.source==="openclaw"&&t.files.some(r=>r.path.endsWith("manifest.json")))o("manifest.json",()=>{let r=t.files[0].path.split("/")[0],l=!t.files.some(c=>c.path==="manifest.json")&&t.files.every(c=>c.path.startsWith(`${r}/`))?t.files.map(c=>({...c,path:c.path.slice(r.length+1)})):t.files;return[Pe(l)]});else for(let r of t.files)o(r.path,()=>{if(t.source==="opencode")return[ke(r,JSON.parse(r.text))];let l;if(t.source==="hermes"&&r.path.endsWith(".json")){let c=JSON.parse(r.text.replace(/^\uFEFF/u,""));if(!c||typeof c!="object"||Array.isArray(c))throw new Error("Hermes session backup must be one JSON object.");l=[c]}else l=F(r);if(t.source==="grok_build")return[xe(r,l)];if(t.source==="pi"||t.source==="oh_my_pi"||t.source==="openclaw")return[Le(r,l,t.source,t.branchLeafId)];if(t.source==="codex")return[Me(r,l)];if(t.source==="claude_code")return[Ue(r,l,t.branchLeafId)];if(t.source==="hermes")return l.map(c=>$e(r,c));throw new Error("Unsupported source adapter.")});if(n.length>x.sessions||n.reduce((r,l)=>r+l.events.length+l.unmappedEvents.length,0)>x.events||n.reduce((r,l)=>r+l.boundaries.length,0)>x.boundaries)throw new Error("Import exceeds the session/event/boundary limit.");let a=new Map;for(let r of n){let l=JSON.stringify([r.origin,r.sessionId,r.branchId]),c=a.get(l);if(c&&c!==r.contentHash)throw new Error("The same session has different contents in this selection. Choose one export.");a.set(l,r.contentHash)}return{schemaVersion:"openpond.agentImportPreview.v1",source:t.source,sourceHash:S({source:t.source,files:[...t.files].sort((r,l)=>r.path.localeCompare(l.path)),branchLeafId:t.branchLeafId??null}),sessions:n.filter((r,l)=>n.findIndex(c=>c.contentHash===r.contentHash)===l),issues:i}}u(He,"previewAgentImport");import{DatabaseSync as Mt}from"node:sqlite";import{join as Ut}from"node:path";import{DatabaseSync as kt}from"node:sqlite";import{zstdDecompressSync as ze}from"node:zlib";import{createHash as Dt}from"node:crypto";import{createHash as Nt}from"node:crypto";import{readFileSync as At,realpathSync as je,statSync as Rt}from"node:fs";import{basename as Ct,dirname as Be,join as qe,relative as xt,sep as We}from"node:path";import{zstdDecompressSync as Lt}from"node:zlib";function Ge(t,e,s){let n=t.prepare("SELECT generation,archive_name,archive_sha256,event_count,raw_bytes,archive_bytes,last_seq,storage,length(archive_blob) AS blob_bytes FROM session_transcript_cold_archives WHERE session_id=?").get(s);if(!n)return null;if(Number(n.archive_bytes)>T||Number(n.raw_bytes)>T||Number(n.event_count)>1e5)throw new Error("OpenClaw cold archive exceeds the retained size limit.");let i;if(n.storage==="sqlite"){if(Number(n.blob_bytes)!==Number(n.archive_bytes))throw new Error("OpenClaw cold archive size differs from its receipt.");let E=t.prepare("SELECT archive_blob FROM session_transcript_cold_archives WHERE session_id=?").get(s);if(!(E.archive_blob instanceof Uint8Array))throw new Error("OpenClaw cold archive is unavailable.");i=E.archive_blob}else if(n.storage==="file"){let E=String(n.archive_name);if(!/^[a-f0-9]{64}\.jsonl\.zst$/.test(E))throw new Error("Invalid OpenClaw cold archive name.");let h=Be(e.root),_=Ct(h)==="agent"?qe(Be(h),"sessions"):h,y=je(_),f=je(qe(_,"cold",E)),m=xt(y,f);if(m===".."||m.startsWith(`..${We}`)||m.startsWith(We))throw new Error("OpenClaw cold archive leaves the selected agent directory.");let b=Rt(f);if(!b.isFile()||b.size!==Number(n.archive_bytes))throw new Error("OpenClaw cold archive size differs from its receipt.");i=At(f)}else throw new Error("Unsupported OpenClaw cold archive storage.");if(i.length!==Number(n.archive_bytes)||Nt("sha256").update(i).digest("hex")!==n.archive_sha256)throw new Error("OpenClaw cold archive checksum differs from its receipt.");let o=Lt(i,{maxOutputLength:T}),a=new TextDecoder("utf8",{fatal:!0}).decode(o).trimEnd().split(`
7
- `),r=JSON.parse(a.shift()??"null");if(r?.kind!=="header"||r.version!==1||r.sessionId!==s||r.generation!==n.generation)throw new Error("OpenClaw cold archive identity differs from its receipt.");let l=[],c=-1,p=0;for(let E of a){let h=JSON.parse(E);if(!["event","identity","active","index","fts"].includes(h?.kind))throw new Error("Unsupported OpenClaw cold archive record.");if(h.kind==="event"){if(!Number.isSafeInteger(h.row?.seq)||h.row.seq<=c||typeof h.row.event_json!="string")throw new Error("Invalid OpenClaw cold archive event sequence.");c=h.row.seq,p+=Buffer.byteLength(h.row.event_json),l.push(h.row.event_json)}}if(l.length!==Number(n.event_count)||c!==Number(n.last_seq)||p+l.length-1!==Number(n.raw_bytes))throw new Error("OpenClaw cold archive contents differ from its receipt.");let d=JSON.parse(l[0]??"null");if(d?.type!=="session"||d.id!==s)throw new Error("OpenClaw transcript identity differs from selected session.");return{path:`${s}.jsonl`,text:l.join(`
8
- `)+`
9
- `}}u(Ge,"readOpenClawColdArchive");function Xe(t){let e=new kt(t.root,{readOnly:!0,allowExtension:!1,enableDoubleQuotedStringLiterals:!1});return e.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=1000; BEGIN"),e}u(Xe,"open");function Z(t,e){return!!t.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(e)}u(Z,"has");function Ve(t,e){let s=Xe(t);try{let n=Z(s,"session_transcript_archives")?"UNION ALL SELECT session_id AS id,created_at AS updated,archive_sha256 AS revision FROM session_transcript_archives":"",i=Z(s,"session_transcript_cold_archives")?"UNION ALL SELECT session_id AS id,archived_at AS updated,archive_sha256 AS revision FROM session_transcript_cold_archives":"",o=s.prepare(`SELECT id,MAX(updated) AS updated,MAX(revision) AS revision FROM (
10
- SELECT session_id AS id,MAX(created_at) AS updated,CAST(MAX(seq) AS TEXT) AS revision FROM transcript_events GROUP BY session_id
11
- ${n} ${i}) WHERE id > ? GROUP BY id ORDER BY id LIMIT ?`).all(e.cursor??"",e.limit+1),a=o.slice(0,e.limit).map(r=>({nativeSessionId:String(r.id),sourceInstanceId:t.instanceId,path:String(r.id),title:String(r.id),cwd:null,updatedAt:new Date(Number(r.updated)||0).toISOString()}));return{items:a,nextCursor:o.length>e.limit?a.at(-1).nativeSessionId:null}}finally{s.close()}}u(Ve,"listOpenClawSessions");function Je(t,e){let s=Xe(t);try{if(Z(s,"session_transcript_cold_archives")){let c=Ge(s,t,e);if(c)return c}if(!s.prepare("SELECT 1 FROM transcript_events WHERE session_id=? LIMIT 1").get(e)){if(!Z(s,"session_transcript_archives"))throw new Error("OpenClaw archive is unavailable.");let c=s.prepare("SELECT archive_name,length(archive_blob) AS bytes FROM session_transcript_archives WHERE session_id=? ORDER BY created_at DESC LIMIT 1").get(e);if(!c||Number(c.bytes)>T)throw new Error("OpenClaw archive is missing or exceeds the retained byte limit.");let p=s.prepare("SELECT archive_blob,archive_sha256,encoding FROM session_transcript_archives WHERE archive_name=? AND session_id=?").get(String(c.archive_name),e);if(!(p.archive_blob instanceof Uint8Array)||Dt("sha256").update(p.archive_blob).digest("hex")!==p.archive_sha256)throw new Error("OpenClaw archive checksum differs from its retained receipt.");if(p.encoding!=="zstd"&&p.encoding!=="identity")throw new Error("Unsupported OpenClaw archive encoding.");let d=p.encoding==="zstd"?ze(p.archive_blob,{maxOutputLength:T}):p.archive_blob,E=new TextDecoder("utf8",{fatal:!0}).decode(d),h=JSON.parse(E.split(`
12
- `,1)[0]);if(h.type!=="session"||h.id!==e)throw new Error("OpenClaw archive identity differs from selected session.");return{path:`${e}.jsonl`,text:E}}let i=s.prepare("SELECT COUNT(*) AS n,SUM(COALESCE(event_utf8_bytes,length(CAST(event_json AS BLOB)),0)) AS bytes FROM transcript_events WHERE session_id=?").get(e);if(Number(i.n)>1e5||Number(i.bytes)>T)throw new Error("OpenClaw transcript exceeds the retained size limit.");let o=s.prepare("SELECT seq,event_json,event_zstd,event_utf8_bytes FROM transcript_events WHERE session_id=? ORDER BY seq LIMIT 100001").all(e),a=0,r=o.map(c=>{let p;if(typeof c.event_json=="string")p=c.event_json;else{if(!(c.event_zstd instanceof Uint8Array)||Number(c.event_utf8_bytes)>T)throw new Error("Unsupported OpenClaw compressed transcript record.");let d=ze(c.event_zstd,{maxOutputLength:T});if(d.length!==Number(c.event_utf8_bytes))throw new Error("OpenClaw compressed transcript size differs from its receipt.");p=new TextDecoder("utf8",{fatal:!0}).decode(d)}if(a+=Buffer.byteLength(p),a>T)throw new Error("OpenClaw transcript exceeds retained size limit.");return p});if(!r.length)throw new Error("OpenClaw transcript is unavailable.");let l=JSON.parse(r[0]);if(l.type!=="session"||l.id!==e)throw new Error("OpenClaw transcript identity differs from selected session.");return{path:`${e}.jsonl`,text:r.join(`
13
- `)+`
14
- `}}finally{s.close()}}u(Je,"readOpenClawSession");function Ye(t){let e=t.root.endsWith(".db")?t.root:Ut(t.root,t.source==="opencode"?"opencode.db":"state.db"),s=new Mt(e,{readOnly:!0,allowExtension:!1,enableDoubleQuotedStringLiterals:!1});return s.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=1000; BEGIN"),s}u(Ye,"open");function Ke(t,e){if(t.source==="openclaw")return Ve(t,e);let s=Ye(t);try{let n=e.since?Date.parse(e.since):0,i=t.source==="opencode"?s.prepare("SELECT id,title,directory AS cwd,time_updated AS updated, time_updated || ':' || COALESCE((SELECT MAX(time_updated) FROM message WHERE session_id=session.id),0) || ':' || COALESCE((SELECT MAX(time_updated) FROM part WHERE session_id=session.id),0) || ':' || (SELECT COUNT(*) FROM part WHERE session_id=session.id) AS revision FROM session WHERE id > ? AND time_updated >= ? ORDER BY id LIMIT ?").all(e.cursor??"",n,e.limit+1):s.prepare("SELECT id,title,cwd,MAX(COALESCE(last_activity_at,0),started_at) * 1000 AS updated FROM sessions WHERE id > ? AND MAX(COALESCE(last_activity_at,0),started_at) * 1000 >= ? ORDER BY id LIMIT ?").all(e.cursor??"",n,e.limit+1),o=i.slice(0,e.limit).map(a=>({nativeSessionId:String(a.id),sourceInstanceId:t.instanceId,path:String(a.id),title:typeof a.title=="string"?a.title:String(a.id),cwd:typeof a.cwd=="string"?a.cwd:null,updatedAt:new Date(Number(a.updated)).toISOString(),storageRevision:t.source==="opencode"?String(a.revision):void 0}));return{items:o,nextCursor:i.length>e.limit?o.at(-1).nativeSessionId:null}}finally{s.close()}}u(Ke,"listDatabaseSessions");function Ze(t,e){if(t.source==="openclaw")return Je(t,e);let s=Ye(t);try{let n;if(t.source==="opencode"){let o=s.prepare("SELECT id,title,directory,parent_id,version,time_created,time_updated FROM session WHERE id = ?").get(e);if(!o)throw new Error("Native session is unavailable.");let a=s.prepare("SELECT (SELECT COALESCE(SUM(length(CAST(data AS BLOB))),0) FROM message WHERE session_id=?) + (SELECT COALESCE(SUM(length(CAST(data AS BLOB))),0) FROM part WHERE session_id=?) AS bytes").get(e,e);if(Number(a?.bytes)>T)throw new Error("Native session exceeds the retained byte limit.");let r=s.prepare("SELECT id,data FROM message WHERE session_id = ? ORDER BY time_created,id LIMIT 100001").all(e);if(r.length>1e5)throw new Error("Native session exceeds the event limit.");let l=0,c=r.map(p=>{if(l+=Buffer.byteLength(String(p.data)),l>T)throw new Error("Native session exceeds the retained byte limit.");let d=s.prepare("SELECT id,data FROM part WHERE session_id = ? AND message_id = ? ORDER BY time_created,id LIMIT 100001").all(e,String(p.id));if(d.length>1e5)throw new Error("Native parts exceed the event limit.");return{info:{...JSON.parse(String(p.data)),id:p.id,sessionID:e},parts:d.map(E=>{if(l+=Buffer.byteLength(String(E.data)),l>T)throw new Error("Native session exceeds the retained byte limit.");return{...JSON.parse(String(E.data)),id:E.id,sessionID:e,messageID:p.id}})}});n={info:{...o,parentID:o.parent_id,time:{created:o.time_created,updated:o.time_updated}},messages:c}}else{let o=s.prepare("SELECT id,title,parent_session_id,system_prompt FROM sessions WHERE id = ?").get(e);if(!o)throw new Error("Native session is unavailable.");let a=s.prepare("SELECT COALESCE(SUM(length(CAST(COALESCE(content,'') AS BLOB))+length(CAST(COALESCE(tool_calls,'') AS BLOB))),0) AS bytes FROM messages WHERE session_id=? AND active=1").get(e);if(Number(a?.bytes)>T)throw new Error("Native session exceeds the retained byte limit.");let r=s.prepare("SELECT id,role,content,tool_call_id,tool_calls,timestamp,finish_reason,compacted FROM messages WHERE session_id = ? AND active = 1 ORDER BY id LIMIT 100001").all(e);if(r.length>1e5)throw new Error("Native session exceeds the event limit.");let l=0;n={...o,messages:r.map(c=>{if(l+=Buffer.byteLength(JSON.stringify(c)),l>T)throw new Error("Native session exceeds the retained byte limit.");return{...c,tool_calls:typeof c.tool_calls=="string"?JSON.parse(c.tool_calls):null}}),message_count:r.length}}let i=JSON.stringify(n);if(Buffer.byteLength(i)>T)throw new Error("Native session exceeds the retained byte limit.");return{path:`${e}.json`,text:i}}finally{s.close()}}u(Ze,"readDatabaseSession");async function st(t,e,s=!0){let n=await Qe(t.root),i=await Qe(qt(n,e)),o=Bt(n,i);if(o.startsWith(`..${Wt}`)||o===".."||ue(o))throw new Error("History path is outside the selected source.");if(s&&(await tt(i)).size>T)throw new Error("Source file exceeds 32 MiB.");return i}u(st,"selectedPath");async function X(t,e){let s=await st(t,e),n=await Ht(s);if(n.byteLength>T)throw new Error("Source changed beyond the retained limit.");let i=s.endsWith(".zst")?Gt(n,{maxOutputLength:64*1024*1024}):n,o=new TextDecoder("utf-8",{fatal:!0}).decode(i);if(s.endsWith(".jsonl")&&o&&!o.endsWith(`
15
- `)){let a=o.lastIndexOf(`
16
- `);try{JSON.parse(o.slice(a+1))}catch{return o.slice(0,a+1)}}return o}u(X,"readSelectedFile");async function zt(t){if((await $t(t.root)).isFile())return[""];let e=t.source==="codex"?["sessions","archived_sessions"]:t.source==="grok_build"?["sessions"]:t.source==="claude_code"?["projects"]:t.source==="pi"||t.source==="oh_my_pi"?["sessions"]:[""],s=[];async function n(i,o){if(o>12)throw new Error("Selected history exceeds directory depth limit.");let a;try{a=await Pt(Q(t.root,i),{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return;throw r}for(let r of a){let l=Q(i,r.name);if(!r.isSymbolicLink()&&(r.isDirectory()?await n(l,o+1):r.isFile()&&(t.source==="openclaw"?r.name==="manifest.json":t.source==="grok_build"?r.name==="updates.jsonl":/\.jsonl(?:\.zst)?$/u.test(r.name))&&s.push(l),s.length>1e4))throw new Error("Select a narrower source directory (more than 10,000 history files).")}}u(n,"walk");for(let i of e)await n(i,0);return!s.length&&e[0]!==""&&await n("",0),s.sort()}u(zt,"pathsBelow");function et(t,e){return(e||t.root).endsWith(".json")}u(et,"sessionFileJson");async function pr(t,e={}){if(!t.available||!t.capabilities.history)throw new Error(t.reason??"Native history is unavailable.");let s=e.limit??50;if(!Number.isInteger(s)||s<1||s>100||e.since&&!Number.isFinite(Date.parse(e.since)))throw new Error("Invalid history page or date range.");if(t.acquisition==="sqlite")return Ke(t,{...e,limit:s});let n=await zt(t),i=[];for(let o of n)if(!(e.cursor&&o<=e.cursor)){try{let a=await tt(Q(t.root,o));if(e.since&&a.mtimeMs<Date.parse(e.since))continue;let r;if(t.acquisition!=="bundle"&&!et(t,o)&&t.source!=="hermes"&&!(o||t.root).endsWith(".zst")){let y=await Ft(await st(t,o,!1),"r");try{let f=Buffer.alloc(262144),m=await y.read(f,0,f.length,0),b=f.subarray(0,m.bytesRead).toString("utf8"),N=b.lastIndexOf(`
17
- `);if(r=b,!b.endsWith(`
18
- `))try{JSON.parse(b.slice(N+1))}catch{r=b.slice(0,N+1)}}finally{await y.close()}}else r=await X(t,o);let l=t.acquisition==="bundle"||et(t,o)?[g(JSON.parse(r))]:r.split(/\r?\n/u).filter(Boolean).slice(0,t.source==="claude_code"?void 0:12).map(y=>g(JSON.parse(y))),c=l.find(y=>y.type==="session"||y.type==="session_meta")??l[0]??{},p=c.type==="session_meta"?g(c.payload):t.source==="grok_build"?g(c.params):t.source==="opencode"?g(c.info):c,d=typeof p.id=="string"?p.id:typeof p.sessionId=="string"?p.sessionId:z(o).replace(/\.jsonl(?:\.zst)?$/u,""),h=(t.source==="claude_code"?l.find(y=>y.sessionId===d&&y.type==="user"&&typeof y.cwd=="string"&&ue(y.cwd)):void 0)?.cwd??p.cwd,_=d;if(t.source==="grok_build"&&o.endsWith("updates.jsonl"))try{let y=g(JSON.parse(await X(t,Q(jt(o),"summary.json")))),f=g(y.info);f.id===d&&(h=f.cwd,typeof y.generated_title=="string"&&(_=y.generated_title.slice(0,500)))}catch{}i.push({nativeSessionId:d,sourceInstanceId:t.instanceId,path:o,title:_,cwd:typeof h=="string"&&ue(h)?h:null,updatedAt:a.mtime.toISOString(),storageRevision:[a.dev,a.ino,a.size,a.mtimeMs,a.ctimeMs].join(":")})}catch(a){if(a.code==="ENOENT")continue;i.push({nativeSessionId:z(o||t.root),sourceInstanceId:t.instanceId,path:o,title:z(o||t.root),cwd:null,updatedAt:new Date(0).toISOString(),issue:a instanceof Error?a.message:"Unable to inspect native session"})}if(i.length>s)break}return{items:i.slice(0,s),nextCursor:i.length>s?i[s-1].path:null}}u(pr,"listSessions");async function ur(t,e){if(t.source!=="claude_code")return{revision:"",branches:[]};if(e.issue)throw new Error(e.issue);if(e.sourceInstanceId!==t.instanceId)throw new Error("Native session belongs to another selected source.");let s=await X(t,e.path),n=G(F({path:z(e.path),text:s}));if(n.sessionId!==e.nativeSessionId)throw new Error("Native session changed identity.");return{revision:S(s),branches:n.branches()}}u(ur,"inspectSessionBranches");async function fr(t,e,s={}){if(e.issue)throw new Error(e.issue);if(e.sourceInstanceId!==t.instanceId)throw new Error("Native session belongs to another selected source.");let n;if(t.acquisition==="sqlite")n=[Ze(t,e.nativeSessionId)];else if(t.acquisition==="bundle"){let o=e.path.slice(0,-13);n=await Promise.all(["manifest.json","events.jsonl","session-branch.json"].map(async a=>({path:a,text:await X(t,`${o}${a}`)})))}else n=[{path:z(e.path||t.root).replace(/\.zst$/u,""),text:await X(t,e.path)}];if(s.expectedBranchRevision&&!s.branchLeafId)throw new Error("Choose a branch before supplying its revision.");if(t.source==="claude_code"){let o=n[0],a=G(F(o));if(a.sessionId!==e.nativeSessionId)throw new Error("Native session changed identity.");if(s.branchAnchor){if(s.branchLeafId||s.expectedBranchRevision)throw new Error("Choose either a frozen branch snapshot or a followed branch anchor.");if(a.select(s.branchAnchor.leafId).chainHash!==s.branchAnchor.chainHash)throw new Error("The selected branch history changed. Review and select it again before syncing.");let l=a.leaves.filter(c=>a.select(c.uuid).chain.some(p=>p.uuid===s.branchAnchor.leafId));if(l.length!==1)throw new Error("The selected branch diverged. Pause this connection and choose its branch again.");s={...s,branchLeafId:l[0].uuid}}if(s.expectedBranchRevision&&S(o.text)!==s.expectedBranchRevision)throw new Error("This conversation changed. Refresh its branches and choose again.");if(s.branchLeafId){if(!a.leaves.some(r=>r.uuid===s.branchLeafId))throw new Error("The selected Claude branch is no longer a leaf. Refresh and choose again.");n=[{...o,text:a.select(s.branchLeafId).chain.map(r=>JSON.stringify(r)).join(`
19
- `)+`
20
- `}]}}else if(s.expectedBranchRevision||s.branchAnchor)throw new Error("Branch revision selection is only supported for Claude Code.");let i=He({source:t.source,files:n,acquisition:{machineId:t.machineId,sourceInstanceId:t.instanceId},...s});if(i.issues.length)throw new Error(i.issues.map(o=>o.message).join("; "));if(t.acquisition==="sqlite"&&i.sessions.some(o=>o.sessionId!==e.nativeSessionId))throw new Error("Native session changed identity.");return{files:n,preview:i,branchLeafId:s.branchLeafId}}u(fr,"readSession");import{DatabaseSync as Xt}from"node:sqlite";import{mkdir as Vt,chmod as rt}from"node:fs/promises";import{join as Jt}from"node:path";var ee={reconcileMs:3e4,heartbeatMs:1e4,staleMs:6e4,maxPending:1e4,maxBytes:1073741824,batchCases:20,batchBytes:1048576};function gr(t,e){if(e.id!==t.id||e.teamId!==t.teamId||e.projectId!==t.projectId||e.machineId!==t.source.machineId||e.sourceInstanceId!==t.source.instanceId||e.sourceRoot!==t.source.root||e.source!==t.source.source)throw new Error("The hosted destination belongs to another source or workspace.");return{taskDatasetId:e.taskDatasetId,conversationDatasetId:e.conversationDatasetId}}u(gr,"collectorDestinations");function nt(t){let e={tasks:null,conversations:null};if(!t.accountBaseUrl||!t.destinations)return e;let s;try{s=new URL(t.accountBaseUrl)}catch{return e}if(s.protocol!=="https:"&&!(s.protocol==="http:"&&["localhost","127.0.0.1"].includes(s.hostname))||s.username||s.password||s.search||s.hash||s.pathname!=="/")return e;let n=u(i=>i?`${s.origin}/console/datasets/${encodeURIComponent(i)}/tasks?project=${encodeURIComponent(t.projectId)}&connection=${encodeURIComponent(t.id)}`:null,"link");return{tasks:n(t.destinations.taskDatasetId),conversations:n(t.destinations.conversationDatasetId)}}u(nt,"collectorDestinationLinks");var te=class{static{u(this,"CollectorProgress")}database;constructor(e){this.database=e,e.exec(`
21
- CREATE TABLE IF NOT EXISTS backfills(connection_id TEXT PRIMARY KEY,discovered INTEGER NOT NULL DEFAULT 0);
22
- CREATE TABLE IF NOT EXISTS backfill_units(connection_id TEXT NOT NULL,session_key TEXT NOT NULL,state TEXT NOT NULL,error TEXT,PRIMARY KEY(connection_id,session_key));
23
- CREATE TABLE IF NOT EXISTS backfill_operations(operation_id TEXT PRIMARY KEY,connection_id TEXT NOT NULL,session_key TEXT NOT NULL,admitted INTEGER NOT NULL DEFAULT 0);
24
- `)}reset(e){for(let s of["backfill_operations","backfill_units","backfills"])this.database.prepare(`DELETE FROM ${s} WHERE connection_id=?`).run(e)}select(e,s){this.database.prepare("INSERT OR IGNORE INTO backfills(connection_id) VALUES(?)").run(e),this.database.prepare("SELECT discovered FROM backfills WHERE connection_id=?").get(e)?.discovered||this.database.prepare("INSERT OR IGNORE INTO backfill_units VALUES(?,?,'reading',NULL)").run(e,s)}tracks(e,s){let n=this.database.prepare("SELECT state FROM backfill_units WHERE connection_id=? AND session_key=?").get(e,s);return n?.state==="reading"||n?.state==="error"}queued(e,s,n){this.tracks(s,n)&&this.database.prepare("INSERT OR IGNORE INTO backfill_operations VALUES(?,?,?,0)").run(e,s,n)}retained(e,s,n){if(!this.tracks(e,s))return;let i=this.database.prepare("SELECT id FROM pending WHERE connection_id=? AND json_extract(payload,'$.sessionKey')=?").all(e,n);for(let o of i)this.queued(String(o.id),e,s)}read(e,s,n){if(!this.tracks(e,s))return;let i=this.database.prepare("SELECT COUNT(*) AS n FROM backfill_operations WHERE connection_id=? AND session_key=? AND admitted=0").get(e,s);this.database.prepare("UPDATE backfill_units SET state=?,error=NULL WHERE connection_id=? AND session_key=?").run(Number(i?.n)?"queued":n?"complete":"skipped",e,s)}failed(e,s,n){this.tracks(e,s)&&this.database.prepare("UPDATE backfill_units SET state='error',error=? WHERE connection_id=? AND session_key=?").run(n.slice(0,500),e,s)}discovered(e){this.database.prepare("INSERT INTO backfills VALUES(?,1) ON CONFLICT(connection_id) DO UPDATE SET discovered=1").run(e)}acknowledge(e){let s=this.database.prepare("SELECT connection_id,session_key FROM backfill_operations WHERE operation_id=?").get(e);if(!s)return;this.database.prepare("UPDATE backfill_operations SET admitted=1 WHERE operation_id=?").run(e);let n=this.database.prepare("SELECT COUNT(*) AS n FROM backfill_operations WHERE connection_id=? AND session_key=? AND admitted=0").get(s.connection_id,s.session_key);Number(n?.n)||this.database.prepare("UPDATE backfill_units SET state='complete' WHERE connection_id=? AND session_key=? AND state='queued'").run(s.connection_id,s.session_key)}status(e){let s=this.database.prepare("SELECT discovered FROM backfills WHERE connection_id=?").get(e),n=this.database.prepare("SELECT state,COUNT(*) AS n FROM backfill_units WHERE connection_id=? GROUP BY state").all(e),i=u(a=>Number(n.find(r=>r.state===a)?.n??0),"count"),o=n.reduce((a,r)=>a+Number(r.n),0);return{stage:s?.discovered?i("error")?"attention":i("reading")?"reading":i("queued")?"uploading":"complete":"discovering",total:o,admitted:i("complete"),skipped:i("skipped"),failed:i("error")}}};var B=class t{static{u(this,"CollectorStore")}database;progress;constructor(e){this.database=e,this.progress=new te(e)}static async open(e){await Vt(e,{recursive:!0,mode:448}),await rt(e,448);let s=Jt(e,"collector.sqlite"),n=new Xt(s);return await rt(s,384),n.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=1000;
25
- CREATE TABLE IF NOT EXISTS settings(key TEXT PRIMARY KEY,value TEXT NOT NULL);
26
- CREATE TABLE IF NOT EXISTS connections(id TEXT PRIMARY KEY,config TEXT NOT NULL,admitted INTEGER NOT NULL DEFAULT 0,error TEXT);
27
- CREATE TABLE IF NOT EXISTS admitted_boundaries(connection_id TEXT NOT NULL,boundary_id TEXT NOT NULL,PRIMARY KEY(connection_id,boundary_id));
28
- CREATE TABLE IF NOT EXISTS source_scans(connection_id TEXT NOT NULL,session_key TEXT NOT NULL,revision TEXT NOT NULL,PRIMARY KEY(connection_id,session_key));
29
- CREATE TABLE IF NOT EXISTS checkpoints(connection_id TEXT NOT NULL,session_key TEXT NOT NULL,boundary_id TEXT NOT NULL,revision TEXT NOT NULL,PRIMARY KEY(connection_id,session_key,boundary_id));
30
- CREATE TABLE IF NOT EXISTS pending(id TEXT PRIMARY KEY,connection_id TEXT NOT NULL,payload TEXT NOT NULL,bytes INTEGER NOT NULL,attempts INTEGER NOT NULL DEFAULT 0,retry_at INTEGER NOT NULL DEFAULT 0,created_at INTEGER NOT NULL);
31
- INSERT OR IGNORE INTO settings VALUES('desiredState','stopped');`),new t(n)}close(){this.database.close()}setting(e){let s=this.database.prepare("SELECT value FROM settings WHERE key=?").get(e);return typeof s?.value=="string"?s.value:null}set(e,s){this.database.prepare("INSERT INTO settings VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(e,s)}connections(){return this.database.prepare("SELECT config FROM connections ORDER BY id").all().map(e=>JSON.parse(String(e.config)))}put(e){this.database.exec("BEGIN IMMEDIATE");try{let s=this.connections().find(i=>i.id===e.id);if(s&&s.revision>e.revision){this.database.exec("COMMIT");return}let n=!!s&&(s.source.instanceId!==e.source.instanceId||s.projectId!==e.projectId||s.teamId!==e.teamId||s.apiBaseUrl!==e.apiBaseUrl||s.account!==e.account);if(n&&(e={...e,destinations:void 0}),s&&(n||s.since!==e.since)){this.progress.reset(e.id),this.database.prepare("DELETE FROM settings WHERE key=?").run(`errors:${e.id}`),this.database.prepare("DELETE FROM settings WHERE key=?").run(`syncAcknowledged:${e.id}`),e={...e,completedSyncRevision:0},this.error(e.id,null);for(let i of["source_scans","checkpoints","pending"])this.database.prepare(`DELETE FROM ${i} WHERE connection_id=?`).run(e.id);n&&(this.database.prepare("DELETE FROM admitted_boundaries WHERE connection_id=?").run(e.id),this.database.prepare("UPDATE connections SET admitted=0 WHERE id=?").run(e.id),this.database.prepare("DELETE FROM settings WHERE key=?").run(`lastAdmission:${e.id}`))}else s&&(e={...e,requestedSyncRevision:Math.max(s.requestedSyncRevision??0,e.requestedSyncRevision??0),completedSyncRevision:Math.max(s.completedSyncRevision??0,e.completedSyncRevision??0)});this.database.prepare("INSERT INTO connections(id,config) VALUES(?,?) ON CONFLICT(id) DO UPDATE SET config=excluded.config").run(e.id,JSON.stringify(e)),this.database.exec("COMMIT")}catch(s){throw this.database.exec("ROLLBACK"),s}}error(e,s){this.database.prepare("UPDATE connections SET error=? WHERE id=?").run(s?.slice(0,500)??null,e)}queued(e){return Number((e?this.database.prepare("SELECT COUNT(*) AS n FROM pending WHERE connection_id=?").get(e):this.database.prepare("SELECT COUNT(*) AS n FROM pending").get())?.n??0)}sourceChanged(e,s,n){return this.database.prepare("SELECT revision FROM source_scans WHERE connection_id=? AND session_key=?").get(e,s)?.revision!==n}scanned(e,s,n){this.database.prepare("INSERT INTO source_scans VALUES(?,?,?) ON CONFLICT(connection_id,session_key) DO UPDATE SET revision=excluded.revision").run(e,s,n)}changed(e,s,n,i){return this.database.prepare("SELECT revision FROM checkpoints WHERE connection_id=? AND session_key=? AND boundary_id=?").get(e,s,n)?.revision!==i}enqueue(e,s,n){let i=JSON.stringify(e),o=Buffer.byteLength(i);this.database.exec("BEGIN IMMEDIATE");try{let a=this.database.prepare("SELECT COUNT(*) AS count,COALESCE(SUM(bytes),0) AS bytes FROM pending").get();if(Number(a.count)>=ee.maxPending||Number(a.bytes)+o>ee.maxBytes)throw new Error("Buffer full. Restore connectivity before acquiring more history.");this.database.prepare("INSERT OR IGNORE INTO pending(id,connection_id,payload,bytes,created_at) VALUES(?,?,?,?,?)").run(e.operationId,e.connectionId,i,o,Date.now());let r=this.database.prepare("INSERT INTO checkpoints VALUES(?,?,?,?) ON CONFLICT(connection_id,session_key,boundary_id) DO UPDATE SET revision=excluded.revision");for(let l of s)r.run(e.connectionId,e.sessionKey,l.id,l.revision);n&&this.progress.queued(e.operationId,e.connectionId,n),this.database.exec("COMMIT")}catch(a){throw this.database.exec("ROLLBACK"),a}}next(e){let s=this.database.prepare("SELECT payload,attempts FROM pending WHERE connection_id=? AND retry_at <= ? ORDER BY created_at,id LIMIT 1").get(e,Date.now());return s?{entry:JSON.parse(String(s.payload)),attempts:Number(s.attempts)}:null}acknowledge(e){this.database.exec("BEGIN IMMEDIATE");try{let s=this.database.prepare("DELETE FROM pending WHERE id=?").run(e.operationId);if(Number(s.changes)>0){this.progress.acknowledge(e.operationId),this.set(`lastAdmission:${e.connectionId}`,new Date().toISOString());let n=0,i=this.database.prepare("INSERT OR IGNORE INTO admitted_boundaries VALUES(?,?)");for(let o of e.boundaryIds)n+=Number(i.run(e.connectionId,o).changes);this.database.prepare("UPDATE connections SET admitted=admitted+? WHERE id=?").run(n,e.connectionId)}this.database.exec("COMMIT")}catch(s){throw this.database.exec("ROLLBACK"),s}}retry(e,s){let n=Math.min(6e4,1e3*2**Math.min(s,6));this.database.prepare("UPDATE pending SET attempts=?,retry_at=? WHERE id=?").run(s+1,Date.now()+n+Math.floor(Math.random()*Math.max(1,n/5)),e)}status(){let e=this.setting("heartbeatAt"),s=Number(this.setting("pid"))||null,n=!1;try{s&&(process.kill(s,0),n=!0)}catch{}return{schemaVersion:1,running:n&&!!e&&Date.now()-Date.parse(e)<ee.staleMs,desiredState:this.setting("desiredState")==="running"?"running":"stopped",pid:s,heartbeatAt:e,connections:this.database.prepare("SELECT id,config,admitted,error FROM connections ORDER BY id").all().map(i=>{let o=JSON.parse(String(i.config));return{id:String(i.id),state:o.state,projectId:o.projectId,source:o.source.source,queued:this.queued(String(i.id)),admitted:Number(i.admitted),error:typeof i.error=="string"?i.error:null,backfill:this.progress.status(String(i.id)),pendingBytes:Number(this.database.prepare("SELECT COALESCE(SUM(bytes),0) AS bytes FROM pending WHERE connection_id=?").get(String(i.id))?.bytes??0),lastAdmissionAt:this.setting(`lastAdmission:${i.id}`),requestedSyncRevision:o.requestedSyncRevision??0,completedSyncRevision:o.completedSyncRevision??0,acknowledgedSyncRevision:Number(this.setting(`syncAcknowledged:${i.id}`))||0,destinationLinks:nt(o)}})}}};import{randomUUID as os}from"node:crypto";import{createHash as Yt}from"node:crypto";import{constants as P}from"node:fs";import{chmod as at,copyFile as Kt,lstat as H,mkdir as Zt,mkdtemp as Qt,open as Ee,realpath as se,rename as es,rm as ct}from"node:fs/promises";import{dirname as it,isAbsolute as ts,join as $,relative as ss,resolve as ns,sep as rs}from"node:path";var lt="appimage-runtime",is='const p=require("node:path");const u=require("node:url");const entry=p.join(process.env.APPDIR,"resources","cli","cli.js");process.argv.splice(1,0,entry);import(u.pathToFileURL(entry).href);';async function me(t){let e=ns(t);for(let n=e;;n=it(n)){let i=await H(n).catch(o=>{if(o.code==="ENOENT")return null;throw o});if(i&&(!i.isDirectory()||i.isSymbolicLink()))throw new Error("Collector runtime storage must use real directories.");if(it(n)===n)break}await Zt(e,{recursive:!0,mode:448});let s=await H(e);if(!s.isDirectory()||s.isSymbolicLink()||s.uid!==process.getuid())throw new Error("Collector runtime storage must belong to the current user.");await at(e,448)}u(me,"privateDirectory");async function he(t){let e=Yt("sha256"),s=await Ee(t,P.O_RDONLY|P.O_NOFOLLOW);try{for await(let n of s.createReadStream({autoClose:!1}))e.update(n)}finally{await s.close()}return e.digest("hex")}u(he,"digest");async function fe(t){let e=await Ee(t,P.O_RDONLY|P.O_NOFOLLOW);try{await e.sync()}finally{await e.close()}}u(fe,"sync");async function ot(t,e){let s=await H(t);if(!s.isFile()||s.isSymbolicLink()||s.uid!==process.getuid()||(s.mode&511)!==320||await he(t)!==e)throw new Error("Retained AppImage runtime failed its ownership or integrity check.")}u(ot,"verify");async function dt(t,e=process.env){if(process.platform!=="linux"||!e.APPIMAGE||!e.APPDIR)return null;let s=await se(e.APPDIR),n=await se(t.executable),i=ss(s,n);if(ts(i)||i===".."||i.startsWith(`..${rs}`))return null;let o=t.args[0];if(!o||await se(o)!==$(s,"resources","cli","cli.js"))throw new Error("AppImage collection requires its bundled CLI entrypoint.");let a=await se(e.APPIMAGE),r=await H(a);if(!r.isFile()||r.size>1024*1024*1024)throw new Error("AppImage runtime is unavailable or exceeds the retained size limit.");let l=Buffer.alloc(11),c=await Ee(a,P.O_RDONLY|P.O_NOFOLLOW);try{await c.read(l,0,l.length,0)}finally{await c.close()}if(!l.subarray(0,4).equals(Buffer.from([127,69,76,70]))||!l.subarray(8,11).equals(Buffer.from([65,73,2])))throw new Error("Collector runtime must be a type-2 AppImage.");let p=await he(a);await me(t.directory);let d=$(t.directory,lt);await me(d);let E=$(d,p),h=$(E,"openpond.AppImage"),_=await H(E).catch(y=>{if(y.code==="ENOENT")return null;throw y});if(_){if(!_.isDirectory()||_.isSymbolicLink()||_.uid!==process.getuid()||(_.mode&511)!==448)throw new Error("Retained runtime directory is not private.");await ot(h,p)}else{let y=await Qt($(d,".stage-"));try{let f=$(y,"openpond.AppImage");await Kt(a,f,P.COPYFILE_EXCL),await at(f,320);let m=await H(a);if(r.dev!==m.dev||r.ino!==m.ino||r.size!==m.size||r.mtimeMs!==m.mtimeMs||await he(f)!==p)throw new Error("AppImage changed while preparing the collector runtime; retry installation.");await fe(f),await fe(y);try{await es(y,E)}catch(b){if(!["EEXIST","ENOTEMPTY"].includes(b.code??""))throw b}await ot(h,p),await fe(d)}finally{await ct(y,{recursive:!0,force:!0})}}return{executable:h,args:["-e",is,"--",...t.args.slice(1)]}}u(dt,"retainAppImageRuntime");async function pt(t){let e=$(t,lt),s=await H(e).catch(n=>{if(n.code==="ENOENT")return null;throw n});if(s){if(await me(t),!s.isDirectory()||s.isSymbolicLink()||s.uid!==process.getuid())throw new Error("Refusing to remove unowned collector runtime storage.");await ct(e,{recursive:!0})}}u(pt,"removeAppImageRuntimes");import{execFile as as}from"node:child_process";import{promisify as cs}from"node:util";import{mkdir as ge,writeFile as ne,rm as V,rename as ls}from"node:fs/promises";import{homedir as mt}from"node:os";import{isAbsolute as ut,join as D}from"node:path";var ht=cs(as),C=u(async(t,e)=>{await ht(t,e,{timeout:15e3,maxBuffer:16384,windowsHide:!0})},"command"),q=u(t=>t.replace(/&/gu,"&amp;").replace(/</gu,"&lt;").replace(/>/gu,"&gt;").replace(/"/gu,"&quot;"),"xml"),ft=u(t=>`"${t.replace(/\\/gu,"\\\\").replace(/"/gu,'\\"').replace(/%/gu,"%%").replace(/\$/gu,"$$")}"`,"systemd");function we(t){return`openpond-import-${S(t).slice(0,16)}`}u(we,"identity");async function Gr(t,e){let s=await B.open(t);try{s.put(e)}finally{s.close()}}u(Gr,"configureCollector");async function _e(t){let e=await B.open(t);try{return e.status()}finally{e.close()}}u(_e,"collectorStatus");async function ye(t,e,s){let n=await B.open(t);try{if(e==="start"||e==="stop")n.set("desiredState",e==="start"?"running":"stopped");else if(e==="sync")n.set("syncNow","yes");else{let i=n.connections().find(o=>o.id===s);if(!i)throw new Error("Select a retained connection.");n.put({...i,state:e==="pause"?"paused":e==="resume"?"active":"disconnected"})}return n.status()}finally{n.close()}}u(ye,"controlCollector");async function zr(t){if(!ut(t.directory)||!ut(t.executable)||[t.directory,t.executable,...t.args].some(a=>/[\r\n\0]/u.test(a)))throw new Error("Collector service requires absolute paths and single-line arguments.");let e=await dt(t);e&&(t={...t,...e,environment:{...t.environment,ELECTRON_RUN_AS_NODE:"1",APPIMAGE_EXTRACT_AND_RUN:"1"}});let s=Object.entries(t.environment??{});if(s.some(([a,r])=>!["OPENPOND_HOME","ELECTRON_RUN_AS_NODE","APPIMAGE_EXTRACT_AND_RUN"].includes(a)||typeof r!="string"||/[\r\n\0]/u.test(r)))throw new Error("Unsupported service environment setting.");let n=t.home??mt(),i=we(t.directory),o=[...t.args,"import","service","run","--collector-dir",t.directory];if(process.platform==="linux"){let a=D(n,".config/systemd/user");await ge(a,{recursive:!0,mode:448}),await ds(D(a,`${i}.service`),`[Unit]
32
- Description=OpenPond conversation importer
33
- After=network-online.target
34
- [Service]
35
- Type=simple
36
- ${s.map(([r,l])=>`Environment=${ft(`${r}=${l}`)}`).join(`
37
- `)}
38
- ExecStart=${[t.executable,...o].map(ft).join(" ")}
39
- Restart=on-failure
40
- RestartSec=5
41
- UMask=0077
42
- NoNewPrivileges=true
43
- [Install]
44
- WantedBy=default.target
45
- `,{mode:384}),await C("systemctl",["--user","daemon-reload"]),await C("systemctl",["--user","enable",`${i}.service`])}else if(process.platform==="darwin"){let a=D(n,"Library/LaunchAgents");await ge(a,{recursive:!0,mode:448});let r=D(a,`${i}.plist`),l=!1;try{await C("launchctl",["print",`gui/${process.getuid()}/${i}`]),l=!0}catch{}l&&await C("launchctl",["bootout",`gui/${process.getuid()}/${i}`]),await ne(r,`<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>Label</key><string>${i}</string><key>ProgramArguments</key><array>${[t.executable,...o].map(c=>`<string>${q(c)}</string>`).join("")}</array><key>EnvironmentVariables</key><dict>${s.map(([c,p])=>`<key>${q(c)}</key><string>${q(p)}</string>`).join("")}</dict><key>RunAtLoad</key><true/><key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict><key>ThrottleInterval</key><integer>5</integer></dict></plist>`,{mode:384}),await C("launchctl",["bootstrap",`gui/${process.getuid()}`,r])}else if(process.platform==="win32"){let a=(await ht("whoami",[],{timeout:5e3,maxBuffer:1024})).stdout.trim(),r=D(t.directory,"scheduled-task.xml");await ge(t.directory,{recursive:!0});let l=u(d=>`"${d.replace(/(\\*)"/gu,'$1$1\\"').replace(/(\\+)$/u,"$1$1")}"`,"quoted"),c=D(t.directory,"start-collector.ps1"),p=u(d=>`'${d.replace(/'/gu,"''")}'`,"ps");await ne(c,`${s.map(([d,E])=>`$env:${d} = ${p(E)}`).join(`
46
- `)}
47
- & ${[t.executable,...o].map(p).join(" ")}
48
- exit $LASTEXITCODE
49
- `,{mode:384}),await ne(r,`<?xml version="1.0"?><Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><Triggers><LogonTrigger><Enabled>true</Enabled><UserId>${q(a)}</UserId></LogonTrigger></Triggers><Principals><Principal id="Owner"><UserId>${q(a)}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals><Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><ExecutionTimeLimit>PT0S</ExecutionTimeLimit><RestartOnFailure><Interval>PT1M</Interval><Count>999</Count></RestartOnFailure></Settings><Actions Context="Owner"><Exec><Command>powershell.exe</Command><Arguments>${q(["-NoProfile","-NonInteractive","-File",c].map(l).join(" "))}</Arguments></Exec></Actions></Task>`,{mode:384}),await C("schtasks",["/Create","/TN",i,"/XML",r,"/F"])}else throw new Error("This OS has no qualified per-user supervisor. Run the collector in the foreground.");return{name:i,platform:process.platform,status:await _e(t.directory)}}u(zr,"installCollectorService");async function Xr(t,e=mt()){await ye(t,"stop");let s=we(t);if(process.platform==="linux")await C("systemctl",["--user","disable","--now",`${s}.service`]),await V(D(e,".config/systemd/user",`${s}.service`),{force:!0}),await C("systemctl",["--user","daemon-reload"]);else if(process.platform==="darwin")await C("launchctl",["bootout",`gui/${process.getuid()}/${s}`]),await V(D(e,"Library/LaunchAgents",`${s}.plist`),{force:!0});else if(process.platform==="win32")await C("schtasks",["/End","/TN",s]),await C("schtasks",["/Delete","/TN",s,"/F"]),await V(D(t,"scheduled-task.xml"),{force:!0}),await V(D(t,"start-collector.ps1"),{force:!0});else throw new Error("No per-user supervisor is available.");return process.platform==="linux"&&await pt(t),_e(t)}u(Xr,"uninstallCollectorService");async function Vr(t){await ye(t,"start");let e=we(t);try{if(process.platform==="linux")await C("systemctl",["--user","restart",`${e}.service`]);else if(process.platform==="darwin")await C("launchctl",["kickstart","-k",`gui/${process.getuid()}/${e}`]);else if(process.platform==="win32")await C("schtasks",["/Run","/TN",e]);else throw new Error("No per-user supervisor is available.")}catch(s){throw await ye(t,"stop"),s}return _e(t)}u(Vr,"startCollectorService");async function ds(t,e,s){let n=`${t}.${os()}.tmp`;try{await ne(n,e,{...s,flag:"wx"}),await ls(n,t)}finally{await V(n,{force:!0})}}u(ds,"atomicServiceFile");import{homedir as ps}from"node:os";import{join as Et,resolve as us}from"node:path";import{randomUUID as fs}from"node:crypto";import{mkdir as ms,open as hs,readFile as Es}from"node:fs/promises";function gs(t=process.env.OPENPOND_HOME||Et(ps(),".openpond")){return us(t,"conversation-importer")}u(gs,"collectorDirectory");async function ti(t=gs()){await ms(t,{recursive:!0,mode:448});let e=Et(t,"machine-id");try{let n=await hs(e,"wx",384);try{await n.writeFile(fs()),await n.sync()}finally{await n.close()}}catch(n){if(n.code!=="EEXIST")throw n}let s=(await Es(e,"utf8")).trim();if(!/^[a-f0-9-]{36}$/u.test(s))throw new Error("Collector machine identity is invalid; restore its retained state.");return s}u(ti,"collectorMachineId");export{Se as a,Rs as b,kn as c,pr as d,ur as e,fr as f,ee as g,gr as h,B as i,Gr as j,_e as k,ye as l,zr as m,Xr as n,Vr as o,gs as p,ti as q};
@@ -1,2 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{g as J}from"./chunk-HO5L2FUU.js";import{$ as G,S as U,aa as F,ea as N}from"./chunk-JBHAU7PH.js";import{L as O,da as H}from"./chunk-6JBWHR6T.js";import{Ca as R,Ta as $,pc as L}from"./chunk-5ZZM3TUN.js";import{s as _,t as q,u as E}from"./chunk-JO7GRBOG.js";import{na as V,oa as P,qa as z,wa as W}from"./chunk-BQNK2NMB.js";import{Ea as j}from"./chunk-VW7D3DRM.js";import{a as g,b as h,c as b,k as M,l as s,n as B,q as A}from"./chunk-P653BXMY.js";import{b as c}from"./chunk-ES2ISFJC.js";import{a as u}from"./chunk-FTQLQJQV.js";import{promises as Y}from"node:fs";import Z from"node:path";async function ue(e){let i=e.definition.tasksetRelease,r=await J(e.store,e.harnessRelease);if(!r)throw new Error("Evaluation Profile Harness release is unavailable.");let t=await te({...e,runtime:r});if(t)return t;let a=await e.store.listTasksetRevisions(e.profileId);for(let o of a){if(i.id!==o.id&&i.id!==`taskset-release-${o.id}-r${o.revision}`)continue;let l=await ee(e.storeDir,o);if(l.taskset.id===i.id&&l.taskset.contentHash===i.contentHash)return l}throw new Error(`Released Taskset ${i.id} is unavailable in Profile ${e.profileId}.`)}u(ue,"loadLocalProfileEvaluationTaskset");async function ee(e,i){let r=i.metadata.importedPackageHash;if(typeof r=="string"){let o=await F(e,r);if(o.taskset.id!==i.id||o.taskset.revision!==i.revision)throw new Error("Imported evaluation Taskset differs from its local Profile revision.");return o}if($(i)!==i.contentHash)throw new Error("Authored evaluation Taskset differs from its immutable revision.");let t=L({taskset:i,adapterId:U(i)}),a=await N({storeDir:e,taskset:i,content:{schemaVersion:"openpond.tasksetPackage.v1",taskset:t.tasksetRelease,environment:t.environmentRelease,verifierSet:t.verifierSetRelease}});return await G(e,a),a}u(ee,"loadCandidate");async function te(e){let i=e.definition.tasksetRelease,r=e.runtime;if(r.release.harnessRelease.id!==e.harnessRelease.id||r.release.harnessRelease.contentHash!==e.harnessRelease.contentHash)throw new Error("Evaluation Taskset runtime differs from its requested release.");let t=`evals/tasksets/${i.contentHash}.json`,a=r.release.harnessRelease.files.find(o=>o.path===t);if(a){if(a.visibility!=="verifier")throw new Error("Evaluation Taskset package is not verifier-private.");let o=await Y.readFile(Z.join(r.release.bundlePath,"source",...t.split("/")));if(M(o)!==a.contentHash)throw new Error("Released evaluation Taskset package bytes differ from their source receipt.");let l=R(JSON.parse(o.toString("utf8")));if(l.taskset.id!==i.id||l.taskset.contentHash!==i.contentHash)throw new Error("Released evaluation Taskset package differs from its definition.");return l}return null}u(te,"loadReleasedProfileEvaluationTaskset");function y(e){return{id:z(e),label:"Selected Dataset evaluation",description:"Explicit sealed external Dataset evaluation recipe.",target:e.target,tasksetRelease:{id:e.dataset.id,contentHash:e.dataset.contentHash},split:e.split,taskIds:[...new Set(e.population.map(i=>i.taskId))],seeds:[...new Set(e.population.map(i=>i.seed))],criterion:e.criterion}}u(y,"externalProfileEvaluationDefinition");async function we(e){let i=e.manifest.profileEvaluation,r=i?.externalDatasetBinding?P(i.externalDatasetBinding):null;if(!r)return null;if(!e.resolveExternalDataset)throw new Error("This owner has no authorized external Dataset resolver.");let t=await e.resolveExternalDataset(r,e.selected);await t.authorize();let a=R(t.packageValue),o=await e.loadCatalog({ref:e.selected.profileRef,sourceRevision:e.selected.sourceRevision,harnessRelease:e.selected.harnessRelease});if(s(t.binding)!==s(r)||r.profileId!==e.selected.profileRef.profileId||r.declaredProfileCatalogHash!==o.catalogHash||a.contentHash!==r.packageHash||s(a.taskset)!==s(e.taskset)||r.environmentHash!==s(a.taskset.environment)||r.privateDatasetClosureHash!==s(a.files.filter(d=>d.asset.visibility!=="policy").map(d=>d.asset)))throw new Error("External Dataset admission changed its actual Profile, package or private closure.");let l=y(r),m={schemaVersion:"openpond.profileEvaluations.v1",definitions:[l],suites:[]};if(E(e.manifest,e.taskset,m),!i||i.catalogHash!==s(m)||i.definitionHash!==s(l)||s(i.target)!==s(r.target))throw new Error("External Dataset manifest changed its derived definition.");return await t.authorize(),{...t,packageValue:a,definition:l,catalog:m}}u(we,"admitProfileExternalDataset");var ae=c.object({id:g,createdAt:b,definitionId:g,externalDatasetBinding:V.optional(),profileRef:O.optional(),profileSource:c.object({sourceRevision:c.string().min(1).max(500),harnessRelease:c.object({id:g,contentHash:h}).strict()}).strict().optional(),modelRef:A,hostModelConfigurationHash:h.optional(),hostArtifactHash:h.optional(),maximumSpendUsd:c.number().positive().max(1e4).optional(),expectedManifestHash:h.optional(),hostExperiment:c.object({definition:c.object({id:g,revision:c.number().int().positive(),contentHash:h}).strict().nullable(),configurationHash:h,project:c.object({id:g,revision:c.number().int().positive(),contentHash:h,targetId:g.nullable()}).strict().optional()}).strict().optional()}).strict();function Se(e){return async(i,r)=>{let t=ae.parse(i);if(r?.requireExpectedManifestHash&&!t.expectedManifestHash)throw new Error("Profile evaluation execution requires the reviewed manifest hash.");if(t.profileSource&&!t.profileRef)throw new Error("An exact Profile source requires its accepted Profile reference.");let a=r?.selectedWorkflows??await e.selectedWorkflows(t.profileRef,t.profileSource);if(t.profileRef&&s(t.profileRef)!==s(a.profileRef))throw new Error("Profile preparation did not resolve the explicitly selected Profile.");if(t.profileSource&&(a.sourceRevision!==t.profileSource.sourceRevision||s(a.harnessRelease)!==s(t.profileSource.harnessRelease)))throw new Error("Profile preparation changed its explicitly pinned source.");let o=t.externalDatasetBinding?P(t.externalDatasetBinding):null,l=o?await(e.resolveExternalDataset?e.resolveExternalDataset(o,a):Promise.reject(new Error("This host has not qualified external Dataset Profile execution."))):null;if(l&&(await l.authorize(),s(P(l.binding))!==s(o)))throw new Error("External Dataset admission differs from the actual authorized recipe.");let m=await e.loadCatalog({ref:a.profileRef,sourceRevision:a.sourceRevision,harnessRelease:a.harnessRelease});if(o&&o.declaredProfileCatalogHash!==m.catalogHash)throw new Error("The original Profile verifier catalog changed.");let d=o?y(o):null;if(d&&t.definitionId!==d.id)throw new Error("Use the external recipe's own definition identity.");let T={schemaVersion:"openpond.profileEvaluations.v1",definitions:d?[d]:m.definitions,suites:d?[]:m.suites},p=d??m.definitions.find(n=>n.id===t.definitionId);if(!p)throw new Error(`Evaluation ${t.definitionId} is absent from the selected Profile release.`);let v=p.target,D=v.kind==="workflow"?a.workflows.find(n=>n.binding.workflowId===v.workflowId)?.binding:j.parse({schemaVersion:"openpond.profileComponentBinding.v1",profileId:a.profileRef.profileId,sourceRevision:a.sourceRevision,harnessRelease:a.harnessRelease,target:v});if(!D)throw new Error(`Evaluation workflow ${v.kind==="workflow"?v.workflowId:""} is absent from the selected Profile release.`);let k=R(l?.packageValue??await e.loadTasksetPackage(p,a.profileRef.profileId,a.harnessRelease)),f=k.taskset;if(f.id!==p.tasksetRelease.id||f.contentHash!==p.tasksetRelease.contentHash)throw new Error("Evaluation Taskset package differs from its released definition.");let S=f.environment.kind==="text"&&f.tools.length===0,K=f.environment.kind==="work"&&f.environment.entrypoint==="openpond-work-v1"&&f.tools.every(n=>["work_exec","work_save_output"].includes(n.name));if(!S&&!K)throw new Error("Profile evaluation supports text cases or Work cases with the built-in execution and output tools.");if(t.maximumSpendUsd!==void 0&&!S)throw new Error("Bounded hosted Profile evaluation currently qualifies text cases without external compute.");if(f.tasks.some(n=>n.artifactRefs.length>H.maxAttachments||n.artifactRefs.some(w=>w.visibility!=="policy"||w.mediaType!=="application/pdf"||w.sizeBytes>H.maxAttachmentBytes)))throw new Error("Profile evaluation accepts only bounded policy-visible PDF task attachments.");if(!o&&!e.privateGradingPreflight&&(f.graders.some(n=>n.kind==="model_judge"||n.kind==="custom_verifier")||f.metrics?.aggregation==="custom"))throw new Error("Profile evaluation cannot run this Taskset's model judge, custom verifier, or custom metric in the current app-server runtime.");await e.privateGradingPreflight?.(k);let I={adapterId:v.kind==="workflow"?"openpond.profile-workflow":"openpond.profile-component",placement:e.placement,runtimeVersion:"app-server-v1",capabilityReceipt:s({adapterId:v.kind==="workflow"?"openpond.profile-workflow":"openpond.profile-component",packageHash:k.contentHash,connectedAppScopes:f.policy.connectedAppScopes})},Q={...W({catalog:T,definitionId:p.id,profileId:a.profileRef.profileId,sourceRevision:a.sourceRevision,harnessRelease:a.harnessRelease,environmentHash:s({packageHash:k.contentHash,runtimeTarget:I})}),...o?{externalDatasetBinding:o}:{},...e.sourceCandidate?{sourceCandidate:e.sourceCandidate}:{}};if(o&&(o.packageHash!==k.contentHash||o.environmentHash!==s(f.environment)||o.privateDatasetClosureHash!==s(k.files.filter(n=>n.asset.visibility!=="policy").map(n=>n.asset))))throw new Error("External Dataset package/environment/private closure changed.");let X=B.parse({provider:t.modelRef.providerId,model:t.modelRef.modelId,revision:null,artifactHash:t.hostArtifactHash??null,tokenizerRevision:null,chatTemplateHash:null}),C=await e.modelConfigurationHash(t.modelRef,t),x=_({schemaVersion:"openpond.tasksetRunManifest.v1",id:t.id,tasksetRelease:p.tasksetRelease,packageHash:k.contentHash,execution:{kind:"harness",harnessRelease:a.harnessRelease},profileEvaluation:Q,policy:{kind:"model",model:X,configurationHash:C},gradingRole:"evaluation",metricPolicy:q(f),population:o?o.population.map(n=>({...n,receiptId:`evaluation-${s([t.id,n.taskId,n.seed,n.fixtureId]).slice(0,32)}`})):p.taskIds.flatMap(n=>p.seeds.map(w=>({receiptId:`evaluation-${s([t.id,n,w]).slice(0,32)}`,taskId:n,seed:w,fixtureId:null}))),runtimeTarget:I,limits:{maxTurns:128,timeoutMs:f.environment.defaultTimeoutMs,maxOutputBytes:25e7,maximumSpendUsd:t.maximumSpendUsd??null},createdAt:t.createdAt,metadata:{sourceTasksetId:f.metadata.sourceTasksetId??f.id,...a.profileRef.source==="openpond_git"?{profileRepositoryId:a.profileRef.repositoryId}:{},...t.hostExperiment?{experimentDefinition:t.hostExperiment.definition,experimentConfigurationHash:t.hostExperiment.configurationHash,...t.hostExperiment.project?{project:t.hostExperiment.project}:{}}:{}}});if(E(x,f,T),l&&await l.authorize(),t.expectedManifestHash&&x.contentHash!==t.expectedManifestHash)throw new Error("Profile evaluation setup changed since preview; prepare the run again.");return{manifest:x,taskset:f,profileRef:a.profileRef,binding:D,modelRef:t.modelRef,modelConfigurationHash:C}}}u(Se,"createProfileEvaluationRunPreparationService");export{ue as a,te as b,we as c,Se as d};
@@ -1,2 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{C as Qe,Ga as Q,Ha as nt,Ia as at,Ja as rt,Ka as st,La as it,Ma as X,R as Xe,T as Ye,V as he,W as ge,X as Re,a as N,b as le,c as We,j as de,k as Ge,l as ue,m as fe,oa as et,qa as tt,ta as ve,ua as we,v as $,y as Ze,z as pe}from"./chunk-BQNK2NMB.js";import{g as Ue}from"./chunk-VW7D3DRM.js";import{a as v,b as R,c as _,d as C,e as g,g as J,h as j,i as me,k as Ke,l as o,m as V,n as Z}from"./chunk-P653BXMY.js";import{b as t}from"./chunk-ES2ISFJC.js";import{a as m}from"./chunk-FTQLQJQV.js";var Me=t.object({adapterId:v,placement:t.enum(["local","remote","colocated","provider_native"]),runtimeVersion:t.string().trim().min(1).max(200),capabilityReceipt:R}).strict(),je=t.object({maxTurns:t.number().int().positive().max(1e5),timeoutMs:t.number().int().positive().max(864e5),maxOutputBytes:t.number().int().positive().max(25e7),maximumSpendUsd:t.number().nonnegative().nullable()}).strict(),ot=t.object({schemaVersion:t.literal("openpond.runManifest.v1"),id:v,harnessRelease:g,tasksetRelease:g,model:Z,runtimeTarget:Me,limits:je,approval:t.object({id:v,contentHash:R}).strict().nullable(),createdAt:_,metadata:C}).strict(),K=ot.extend({contentHash:R}).strict(),Pe=t.object({schemaVersion:t.literal("openpond.attemptReceipt.v1"),id:v,runManifest:g,taskId:v,seed:t.string().trim().min(1).max(500),terminal:t.boolean(),failureClass:me.nullable(),outputHash:R.nullable(),traceHash:R,artifactRefs:t.array(j).max(1e5),graderEvidenceRefs:t.array(j).max(1e4),startedAt:_,completedAt:_,latencyMs:t.number().int().nonnegative(),costUsd:t.number().nonnegative().nullable(),legacyAttemptRef:v.nullable().default(null),metadata:C}).strict(),be=Pe.extend({contentHash:R}).strict(),ct=t.object({schemaVersion:t.literal("openpond.evaluationResult.v1"),id:v,runManifest:g,harnessRelease:g,tasksetRelease:g,model:Z,receiptRefs:t.array(g).min(1).max(1e6),attemptCount:t.number().int().positive(),rewardEligibleCount:t.number().int().nonnegative(),terminalCount:t.number().int().nonnegative(),meanScore:t.number().min(0).max(1).nullable(),failureCounts:t.record(me,t.number().int().nonnegative()),authoredMetric:ue.optional(),metadata:C}).strict(),cn=ct.extend({contentHash:R}).strict(),mn=t.object({schemaVersion:t.literal("openpond.harnessCompatibility.v1"),id:v,baseHarnessRelease:g,candidateHarnessRelease:g,tasksetRelease:g,environmentHash:R,toolContractHash:R,policyHash:R,graderInterfaceHash:R,metadata:C}).strict(),ln=mn.extend({contentHash:R}).strict();function Ra(e){let n=ot.parse(e);return K.parse({...n,contentHash:o(n)})}m(Ra,"createRunManifest");function va(e){let n=Pe.parse(e);return be.parse({...n,contentHash:o(n)})}m(va,"createAttemptReceipt");function D(e){let n=be.safeParse(e);if(!n.success)return!1;let{contentHash:a,...s}=n.data;return o(Pe.parse(s))===a}m(D,"verifyAttemptReceipt");function mt(e){if(!e.receipts.length)throw new Error("An evaluation requires at least one attempt receipt.");for(let r of e.receipts){if(r.runManifest.id!==e.manifest.id||r.runManifest.contentHash!==e.manifest.contentHash)throw new Error(`Attempt receipt ${r.id} belongs to a different Run Manifest.`);if(!D(r))throw new Error(`Attempt receipt ${r.id} has an invalid content hash.`)}if(e.authoredMetric){fe(e.authoredMetric);let r=e.authoredMetric;if(r.runManifest.id!==e.manifest.id||r.runManifest.contentHash!==e.manifest.contentHash||o(r.tasksetRelease)!==o(e.manifest.tasksetRelease)||o(r.receiptRefs)!==o(e.receipts.map(({id:i,contentHash:u})=>({id:i,contentHash:u}))))throw new Error("Authored metric does not describe this evaluation's exact manifest and receipts.")}let n=e.receipts.flatMap(r=>typeof r.metadata.score=="number"&&Number.isFinite(r.metadata.score)?[r.metadata.score]:[]),a=Object.fromEntries(me.options.map(r=>[r,e.receipts.filter(i=>i.failureClass===r).length])),s=ct.parse({schemaVersion:"openpond.evaluationResult.v1",id:e.id,runManifest:{id:e.manifest.id,contentHash:e.manifest.contentHash},harnessRelease:e.manifest.harnessRelease,tasksetRelease:e.manifest.tasksetRelease,model:e.manifest.model,receiptRefs:e.receipts.map(r=>({id:r.id,contentHash:r.contentHash})),attemptCount:e.receipts.length,rewardEligibleCount:e.receipts.filter(r=>r.metadata.rewardEligible===!0&&r.failureClass!=="infrastructure_failure").length,terminalCount:e.receipts.filter(r=>r.terminal).length,meanScore:n.length?n.reduce((r,i)=>r+i,0)/n.length:null,failureCounts:a,...e.authoredMetric?{authoredMetric:e.authoredMetric}:{},metadata:e.metadata??{}});return cn.parse({...s,contentHash:o(s)})}m(mt,"aggregateEvaluationReceipts");function Te(e,n,a){if(e.tasksetRelease.contentHash!==n.tasksetRelease.contentHash)throw new Error("Evaluation runs use different Taskset Releases.");if(e.harnessRelease.contentHash===n.harnessRelease.contentHash)return;if(!a)throw new Error("Evaluation runs use different Harness Releases without a compatibility receipt.");let s=ln.parse(a);if(V(s,"Harness compatibility receipt"),s.baseHarnessRelease.contentHash!==e.harnessRelease.contentHash||s.candidateHarnessRelease.contentHash!==n.harnessRelease.contentHash||s.tasksetRelease.contentHash!==e.tasksetRelease.contentHash)throw new Error("Harness compatibility receipt does not match the compared runs.")}m(Te,"assertComparableRunManifests");var lt=t.object({schemaVersion:t.literal("openpond.humanResultView.v1"),executionId:t.string().min(1),executionHash:t.string().regex(/^[a-f0-9]{64}$/),selection:t.array($).max(1e4),coverage:t.object({pending:t.number().int().nonnegative(),submitted:t.number().int().nonnegative(),accepted:t.number().int().nonnegative(),rejected:t.number().int().nonnegative(),cancelled:t.number().int().nonnegative()}).strict(),results:t.array(t.object({review:$,decision:$.nullable(),attemptIds:t.array(t.string().min(1)).min(1).max(2),mode:t.enum(["individual","pairwise"]),origin:t.enum(["hosted_retained","recorded_evidence","owner_attested_local","native_local"]),status:t.enum(["pending","submitted","accepted","rejected","cancelled"]),grader:$,answers:t.array(Ze).max(100)}).strict()).max(1e4)}).strict(),xe=lt.extend({contentHash:t.string().regex(/^[a-f0-9]{64}$/)}).strict();function dt(e){let n=e.reviews.map(r=>{let i=pe.parse(r),{contentHash:u,...l}=i;if(o(l)!==u||!i.evidence.attempts.some(d=>d.experimentId===e.executionId))throw new N("human_result_selection_mismatch",409);return i});if(new Set(n.map(r=>r.id)).size!==n.length)throw new N("human_result_duplicate_review",422);let a=n.map(r=>{let i=r.decisions.at(-1);return{review:{id:r.id,revision:r.revision,contentHash:r.contentHash},decision:i?{id:i.id,revision:i.revision,contentHash:i.contentHash}:null,attemptIds:r.evidence.attempts.map(u=>u.attemptId),mode:r.form.mode,origin:r.evidence.attempts.some(u=>u.localSource?.kind==="owner_attested_local")?"owner_attested_local":r.evidence.attempts.some(u=>u.localSource?.kind==="native_local")?"native_local":r.evidence.attempts.some(u=>u.recordedSource)?"recorded_evidence":"hosted_retained",status:r.status==="accepted"?"accepted":r.status==="rejected"?"rejected":r.status==="cancelled"?"cancelled":r.status==="submitted"?"submitted":"pending",grader:r.evidence.grader,answers:r.status==="accepted"&&i?.outcome==="accept"?i.answers:[]}}),s={pending:0,submitted:0,accepted:0,rejected:0,cancelled:0};for(let r of a)s[r.status]++;return xe.parse(Qe(lt.parse({schemaVersion:"openpond.humanResultView.v1",executionId:e.executionId,executionHash:e.executionHash,selection:a.map(r=>r.review),coverage:s,results:a})))}m(dt,"createHumanResultView");var dn=t.discriminatedUnion("kind",[t.object({kind:t.literal("model"),model:Z,configurationHash:R}).strict(),t.object({kind:t.literal("fixture")}).strict()]),un=t.discriminatedUnion("kind",[t.object({kind:t.literal("taskset"),environmentRelease:g,verifierSetRelease:g,policyHash:R}).strict(),t.object({kind:t.literal("harness"),harnessRelease:g}).strict()]),fn=t.object({receiptId:v,taskId:v,seed:t.string().trim().min(1).max(500),fixtureId:v.nullable()}).strict(),ut=t.object({schemaVersion:t.literal("openpond.tasksetRunManifest.v1"),id:v,tasksetRelease:g,packageHash:R,execution:un,profileEvaluation:we.optional(),policy:dn,gradingRole:t.literal("evaluation"),metricPolicy:de,population:t.array(fn).min(1).max(1e5),runtimeTarget:Me,limits:je,createdAt:_,metadata:C}).strict().superRefine((e,n)=>{new Set(e.population.map(a=>a.receiptId)).size!==e.population.length&&n.addIssue({code:"custom",path:["population"],message:"Run receipt identities must be unique."}),e.population.some(a=>a.fixtureId!==null!=(e.policy.kind==="fixture"))&&n.addIssue({code:"custom",path:["population"],message:"Only fixture runs require a fixture identity for every member."}),e.profileEvaluation&&(e.execution.kind!=="harness"||e.execution.harnessRelease.id!==e.profileEvaluation.harnessRelease.id||e.execution.harnessRelease.contentHash!==e.profileEvaluation.harnessRelease.contentHash)&&n.addIssue({code:"custom",path:["profileEvaluation"],message:"Profile evaluation must execute its exact bound Harness release."})}),z=ut.safeExtend({contentHash:R});function Ta(e){let n=ut.parse(e);return z.parse({...n,contentHash:o(n)})}m(Ta,"createTasksetRunManifest");function pn(e){return e.metrics??{schemaVersion:"openpond.tasksetMetricPolicy.v1",primaryMetric:"mean_score",aggregation:"mean_score",missingReward:"exclude",customAggregator:null}}m(pn,"tasksetRunMetricPolicy");function Oe(e,n){if(z.parse(e),V(e,"Taskset run manifest"),Re(n),e.tasksetRelease.id!==n.id||e.tasksetRelease.contentHash!==n.contentHash)throw new Error("Taskset run differs from its pinned release.");if(o(e.metricPolicy)!==o(pn(n)))throw new Error("Taskset run metric differs from its pinned release.");let a=new Set(n.tasks.map(s=>s.id));if(e.population.some(s=>!a.has(s.taskId)))throw new Error("Taskset run population contains an unknown task.");if(e.execution.kind==="taskset"&&(!n.environmentRelease||!n.verifierSetRelease||o(e.execution.environmentRelease)!==o(n.environmentRelease)||o(e.execution.verifierSetRelease)!==o(n.verifierSetRelease)||e.execution.policyHash!==o(n.policy)))throw new Error("Taskset-owned execution differs from its pinned release.")}m(Oe,"assertTasksetRunRelease");function Oa(e,n,a){Oe(e,n);let s=ve.parse(a),r=e.profileEvaluation;if(!r||e.execution.kind!=="harness"||e.policy.kind!=="model")throw new Error("Profile evaluation requires fresh model execution through its bound Harness.");if(r.catalogHash!==o(s))throw new Error("Profile evaluation catalog differs from its pinned source.");let i=s.definitions.find(c=>c.id===r.definitionId);if(!i||r.definitionHash!==o(i)||o(r.target)!==o(i.target))throw new Error("Profile evaluation definition differs from its pinned source.");if(i.tasksetRelease.id!==n.id||i.tasksetRelease.contentHash!==n.contentHash)throw new Error("Profile evaluation Taskset differs from its pinned definition.");if(i.split==="train")throw new Error("Profile evaluation cannot execute training cases.");let u=new Map(n.tasks.map(c=>[c.id,c]));if(i.taskIds.some(c=>u.get(c)?.split!==i.split))throw new Error("Profile evaluation case is absent from its declared Taskset split.");if(r.externalDatasetBinding){let c=et(r.externalDatasetBinding);if(r.definitionId!==tt(c)||c.dataset.id!==n.id||c.dataset.revision!==n.revision||c.dataset.contentHash!==n.contentHash||c.packageHash!==e.packageHash||c.profileId!==r.profileId||o(c.target)!==o(r.target)||c.split!==i.split||c.environmentHash!==o(n.environment)||c.population.length!==e.population.length||c.population.some((f,p)=>o(f)!==o({taskId:e.population[p].taskId,seed:e.population[p].seed,fixtureId:e.population[p].fixtureId})))throw new Error("Profile external Dataset execution differs from its exact admitted recipe.");return}let l=new Set(i.taskIds.flatMap(c=>i.seeds.map(f=>JSON.stringify([c,f])))),d=new Set(e.population.map(({taskId:c,seed:f})=>JSON.stringify([c,f])));if(e.population.some(c=>c.fixtureId!==null)||d.size!==l.size||e.population.length!==l.size||[...d].some(c=>!l.has(c)))throw new Error("Profile evaluation population differs from its declared cases and seeds.")}m(Oa,"assertProfileEvaluationRunAdmission");function Ve(e,n){z.parse(e),V(e,"Taskset run manifest");let a=new Map(n.map(s=>[s.id,s]));if(a.size!==n.length||n.length!==e.population.length)throw new Error("Run receipts differ from the complete admitted population.");return e.population.map(s=>{let r=a.get(s.receiptId);if(!r||!D(r)||r.runManifest.id!==e.id||r.runManifest.contentHash!==e.contentHash||r.taskId!==s.taskId||r.seed!==s.seed)throw new Error("Run receipt differs from its admitted member or manifest.");if(r.metadata.gradingRole!=="evaluation")throw new Error("Taskset run requires evaluation-role evidence.");if(!r.terminal&&!["infrastructure_failure","timeout","cancelled"].includes(r.failureClass??""))throw new Error("Taskset run member has no terminal accounting outcome.");return r})}m(Ve,"orderTasksetRunReceipts");var ft=t.object({schemaVersion:t.literal("openpond.profileEvaluationComparison.v1"),id:v,tasksetRelease:g,populationHash:R,environmentHash:R,metricPolicyHash:R,limitsHash:R,members:t.array(t.object({runManifest:g,metricResultHash:R,source:we,policy:z.shape.policy,score:t.number().min(0).max(1).nullable()}).strict()).min(2).max(100),createdAt:_}).strict(),hn=ft.extend({contentHash:R}).strict();function La(e){if(e.members.length<2)throw new Error("A comparison requires at least two runs.");let n=e.members.map(({manifest:d,result:c})=>{if(z.parse(d),V(d,"Taskset run manifest"),fe(c),!d.profileEvaluation||d.execution.kind!=="harness")throw new Error("Profile comparison requires released Profile evaluation runs.");if(c.runManifest.id!==d.id||c.runManifest.contentHash!==d.contentHash||c.tasksetRelease.id!==d.tasksetRelease.id||c.tasksetRelease.contentHash!==d.tasksetRelease.contentHash||c.policyHash!==o(d.metricPolicy))throw new Error("Profile comparison metric differs from its run manifest.");return{manifest:d,result:c,source:d.profileEvaluation}}),a=n[0],s=o(a.manifest.population.map(({taskId:d,seed:c,fixtureId:f})=>({taskId:d,seed:c,fixtureId:f}))),r=o(a.manifest.metricPolicy),i=o(a.manifest.limits),u=new Set;for(let d of n){if(u.has(d.manifest.id))throw new Error("Profile comparison repeats a run.");if(u.add(d.manifest.id),d.manifest.tasksetRelease.id!==a.manifest.tasksetRelease.id||d.manifest.tasksetRelease.contentHash!==a.manifest.tasksetRelease.contentHash||o(d.manifest.population.map(({taskId:c,seed:f,fixtureId:p})=>({taskId:c,seed:f,fixtureId:p})))!==s||d.source.environmentHash!==a.source.environmentHash||o(d.manifest.metricPolicy)!==r||o(d.manifest.limits)!==i||d.manifest.runtimeTarget.adapterId!==a.manifest.runtimeTarget.adapterId||d.manifest.runtimeTarget.placement!==a.manifest.runtimeTarget.placement||d.manifest.runtimeTarget.runtimeVersion!==a.manifest.runtimeTarget.runtimeVersion)throw new Error("Profile comparison runs differ in frozen tasks, environment, grading, limits, or runtime.")}let l=ft.parse({schemaVersion:"openpond.profileEvaluationComparison.v1",id:e.id,tasksetRelease:a.manifest.tasksetRelease,populationHash:s,environmentHash:a.source.environmentHash,metricPolicyHash:r,limitsHash:i,members:n.map(({manifest:d,result:c,source:f})=>({runManifest:{id:d.id,contentHash:d.contentHash},metricResultHash:c.contentHash,source:f,policy:d.policy,score:c.value})),createdAt:e.createdAt});return hn.parse({...l,contentHash:o(l)})}m(La,"createProfileEvaluationComparison");var pt=t.object({schemaVersion:t.literal("openpond.profileEvaluationSuiteRun.v1"),id:v,suiteId:v,suiteHash:R,catalogHash:R,profileId:v,sourceRevision:t.string().trim().min(1).max(240),harnessRelease:g,members:t.array(t.object({definitionId:v,runManifest:g,runHash:R,passed:t.boolean(),score:t.number().min(0).max(1).nullable()}).strict()).min(1).max(1e3),passed:t.boolean(),createdAt:_,completedAt:_}).strict(),gn=pt.extend({contentHash:R}).strict();function Za(e){let n=ve.parse(e.catalog),a=n.suites.find(l=>l.id===e.suiteId);if(!a)throw new Error(`Profile evaluation suite ${e.suiteId} is absent from its catalog.`);if(e.members.length!==a.definitionIds.length)throw new Error("Profile evaluation suite has an incomplete run population.");let s=e.members.map((l,d)=>{let c=a.definitionIds[d],f=n.definitions.find(w=>w.id===c);if(!f||l.definitionId!==c)throw new Error("Profile evaluation suite members differ from declared definition order.");let p=z.parse(l.manifest);V(p,"Profile evaluation suite member manifest");let h=p.profileEvaluation;if(!h||p.execution.kind!=="harness"||h.definitionId!==c||h.definitionHash!==o(f)||o(h.target)!==o(f.target)||h.catalogHash!==o(n)||p.tasksetRelease.id!==f.tasksetRelease.id||p.tasksetRelease.contentHash!==f.tasksetRelease.contentHash)throw new Error("Profile evaluation suite member differs from its released definition.");return{...l,manifest:p,source:h}}),r=s[0].source,i=s[0].manifest.policy;if(i.kind!=="model")throw new Error("Profile evaluation suite requires model runs.");for(let l of s){if(l.source.profileId!==r.profileId||l.source.sourceRevision!==r.sourceRevision||l.source.harnessRelease.id!==r.harnessRelease.id||l.source.harnessRelease.contentHash!==r.harnessRelease.contentHash)throw new Error("Profile evaluation suite members use different Profile releases.");let d=l.manifest.policy;if(d.kind!=="model"||o(d)!==o(i))throw new Error("Profile evaluation suite members use different model configurations.")}let u=pt.parse({schemaVersion:"openpond.profileEvaluationSuiteRun.v1",id:e.id,suiteId:a.id,suiteHash:o(a),catalogHash:o(n),profileId:r.profileId,sourceRevision:r.sourceRevision,harnessRelease:r.harnessRelease,members:s.map(l=>({definitionId:l.definitionId,runManifest:{id:l.manifest.id,contentHash:l.manifest.contentHash},runHash:l.runHash,passed:l.passed,score:l.score})),passed:s.every(l=>l.passed),createdAt:e.createdAt,completedAt:e.completedAt});return gn.parse({...u,contentHash:o(u)})}m(Za,"createProfileEvaluationSuiteRun");var Rn="openpond.connectedEvidence.v1",vn="connected-evidence-1",Se={files:100,sourceBytes:32*1024*1024,decodedBytes:64*1024*1024,lineBytes:2*1024*1024,events:1e5,sessions:1e3,boundaries:5e3,evaluatorBytes:2*1024*1024},P=t.string().min(1).max(500),Y=t.string().regex(/^[a-f0-9]{64}$/),wn=t.string().datetime().nullable(),He=t.number().int().nonnegative().nullable(),bn=t.enum(["native_chat","native_work","codex","claude_code","hermes","openclaw","opencode","grok_build","pi","oh_my_pi"]),xn=t.object({invocationId:P,inputTokens:He,outputTokens:He,cachedInputTokens:He,totalTokens:He,provenance:t.enum(["billed_invocation","reported_invocation","reported_cumulative"])}).strict(),ht=t.object({id:P,sequence:t.number().int().nonnegative(),occurredAt:wn,kind:t.enum(["message","tool_call","tool_result","compaction","artifact","terminal","usage","unknown"]),role:t.enum(["user","assistant","system","tool"]).nullable(),callId:P.nullable(),parentId:P.nullable(),content:t.json(),usage:xn.nullable()}).strict(),Sn=t.object({id:P,familyKey:P,projection:t.enum(["turn","conversation"]),requestEventId:P,start:t.number().int().nonnegative(),end:t.number().int().positive(),inputHash:Y,outputHash:Y.nullable(),revisionHash:Y,terminal:t.enum(["completed","failed","cancelled","unknown"]),coverage:t.object({answer:t.boolean(),context:t.enum(["retained","compacted","unknown"]),process:t.enum(["retained","partial","absent"]),artifacts:t.enum(["retained","references_only","absent"]),replay:t.literal("unavailable"),gaps:t.array(t.string().max(500)).max(100)}).strict()}).strict(),tr=t.object({schemaVersion:t.literal(Rn),normalizerVersion:t.literal(vn),origin:bn,sessionId:P,branchId:P.nullable(),parentSessionId:P.nullable(),exporterVersion:t.string().max(200).nullable(),acquisition:t.object({machineId:P,sourceInstanceId:P}).strict().optional(),sourceFiles:t.array(t.object({path:P,contentHash:Y,sizeBytes:t.number().int().nonnegative()}).strict()).max(Se.files),events:t.array(ht).max(Se.events),unmappedEvents:t.array(ht).max(Se.events),boundaries:t.array(Sn).max(Se.boundaries),warnings:t.array(t.string().max(500)).max(100),contentHash:Y}).strict();function nr(e){return e.kind!=="message"||e.role!=="assistant"||e.content===null?!1:typeof e.content=="string"?e.content.trim().length>0:Array.isArray(e.content)?e.content.length>0:typeof e.content!="object"||!("text"in e.content)||typeof e.content.text=="string"&&e.content.text.trim().length>0}m(nr,"hasRecordedConnectedAnswer");async function lr(e,n){return e.signal?.throwIfAborted(),Oe(e.manifest,e.taskset),gt(e.taskset,e.source),Rt({...e,policy:e.manifest.metricPolicy,receipts:Ve(e.manifest,e.receipts)},n)}m(lr,"aggregateTasksetRunReceipts");function gt(e,n){Re(e),e.metrics?.customAggregator&&vt(e.metrics.customAggregator,n)}m(gt,"assertTasksetMetricSource");async function dr(e,n){if(gt(e.taskset,e.source),e.taskset.id!==e.manifest.tasksetRelease.id||e.taskset.contentHash!==e.manifest.tasksetRelease.contentHash)throw new Error("Metric Taskset differs from the Run Manifest's pinned release.");let a=new Set(e.taskset.tasks.map(r=>r.id));if(e.receipts.some(r=>!a.has(r.taskId)))throw new Error("Metric receipt names a task outside the pinned Taskset.");let s=e.taskset.metrics?await Rt({...e,policy:e.taskset.metrics},n):void 0;return mt({id:e.id,manifest:e.manifest,receipts:e.receipts,metadata:e.metadata,authoredMetric:s})}m(dr,"aggregateTasksetEvaluationReceipts");async function Rt(e,n){e.signal?.throwIfAborted();let a=de.parse(e.policy),s=e.manifest.schemaVersion==="openpond.tasksetRunManifest.v1"?z.parse(e.manifest):K.parse(e.manifest);if(V(s,"Metric Run Manifest"),s.schemaVersion==="openpond.tasksetRunManifest.v1"){if(o(a)!==o(s.metricPolicy))throw new Error("Metric policy differs from the admitted run.");if(Ve(s,e.receipts).some((w,A)=>w.id!==e.receipts[A]?.id))throw new Error("Metric receipts must follow the admitted population order.")}if(!e.receipts.length||e.receipts.length>1e6)throw new Error("Metric execution requires 1 to 1,000,000 attempt receipts.");let r=new Set,i=[],u=[],l=0;for(let h of e.receipts){if(e.signal?.throwIfAborted(),!D(h))throw new Error(`Metric receipt ${h.id} has an invalid content hash.`);if(h.runManifest.id!==s.id||h.runManifest.contentHash!==s.contentHash)throw new Error(`Metric receipt ${h.id} belongs to a different Run Manifest.`);if(r.has(h.id))throw new Error(`Metric receipt ${h.id} is duplicated.`);if(r.add(h.id),!h.terminal||["infrastructure_failure","timeout","cancelled"].includes(h.failureClass??""))continue;let w=h.metadata.score;if(typeof w=="number"&&(!Number.isFinite(w)||w<0||w>1))throw new Error(`Metric receipt ${h.id} has an invalid score.`);let A=h.metadata.rewardEligible===!0&&typeof w=="number"&&(a.aggregation!=="pass_rate"||typeof h.metadata.passed=="boolean");if(!A&&(l+=1,a.missingReward==="exclude"))continue;let B=a.aggregation==="weighted_mean"&&Object.hasOwn(a.taskWeights,h.taskId)?a.taskWeights[h.taskId]:void 0;if(a.aggregation==="weighted_mean"&&B===void 0)throw new Error(`Metric policy has no weight for task ${h.taskId}.`);i.push(A?a.aggregation==="pass_rate"?Number(h.metadata.passed):w:0),u.push(B??1)}let d=null,c=e.receipts.map(({id:h,contentHash:w})=>({id:h,contentHash:w})),f=i.length;if(a.customAggregator){if(vt(a.customAggregator,e.source),!n)throw new Error("Custom metrics require an isolated executor.");if(i.length){let h=await n({source:e.source,module:a.customAggregator.module,exportName:a.customAggregator.exportName,scores:i,timeoutMs:a.customAggregator.timeoutMs,signal:e.signal});if(typeof h!="number"||!Number.isFinite(h)||h<0||h>1)throw new Error("Custom metric must return a finite number between 0 and 1.");d=h}}else if(i.length){let h=u.reduce((w,A)=>w+A,0);d=i.reduce((w,A,B)=>w+A*(u[B]/h),0),d=Math.max(0,Math.min(1,d))}e.signal?.throwIfAborted();let p=Ge.parse({schemaVersion:"openpond.tasksetMetricResult.v1",runManifest:{id:s.id,contentHash:s.contentHash},tasksetRelease:s.tasksetRelease,policy:a,policyHash:o(a),receiptRefs:c,includedCount:f,missingRewardCount:l,excludedCount:c.length-f,value:d});return ue.parse({...p,contentHash:o(p)})}m(Rt,"executeTasksetMetric");function vt(e,n){if(n===void 0||new TextEncoder().encode(n).byteLength>524288||Ke(n)!==e.contentHash)throw new Error("Metric module bytes do not match the pinned content hash or exceed the source limit.")}m(vt,"assertMetricSource");function wt(e,n){let a=pe.parse(e),{contentHash:s,...r}=a,i=a.decisions.at(-1);if(s!==o(r)||s!==n.reviewHash||a.status!=="accepted"||!i||i.outcome!=="accept"||i.contentHash!==n.decisionHash)throw new N("human_accepted_revision_unavailable",409);let u=i.submissions.map(l=>{let d=a.submissions.find(c=>c.id===l.id&&c.contentHash===l.contentHash);if(!d||d.evidenceHash!==o(a.evidence)||d.formHash!==o(a.form))throw new N("human_accepted_lineage_invalid",409);return{id:d.id,revision:d.revision,contentHash:d.contentHash}});return{schemaVersion:"openpond.acceptedHumanEvidence.v1",scope:a.scope,projectId:a.projectId,review:{id:a.id,revision:a.revision,contentHash:s},sourceOrigins:a.evidence.attempts.map(l=>l.localSource?l.localSource.kind:l.recordedSource?"recorded_evidence":"hosted_retained"),decision:{id:i.id,revision:i.revision,contentHash:i.contentHash},submissions:u,evidence:a.evidence,answers:i.answers,...a.execution?.result?{execution:{id:a.execution.executionId,result:a.execution.result,configurationHash:a.execution.configurationHash}}:{},...i.taskProposalHash?{taskProposal:a.submissions.find(l=>l.taskProposal?.contentHash===i.taskProposalHash).taskProposal}:{}}}m(wt,"acceptedHumanEvidence");var _e=t.string().regex(/^[a-f0-9]{64}$/),ee=t.string().min(1).max(240),ye={feedbackKey:ee,criterionId:ee},Hn=t.discriminatedUnion("kind",[t.object({...ye,kind:t.literal("normalized_score"),minimum:t.number().finite(),maximum:t.number().finite(),passThreshold:t.number().min(0).max(1).optional()}).strict(),t.object({...ye,kind:t.literal("boolean")}).strict(),t.object({...ye,kind:t.literal("category")}).strict(),t.object({...ye,kind:t.literal("preference_score"),tieScore:t.number().min(0).max(1).nullable()}).strict()]),bt=t.object({execution:g,resultHash:_e,reviews:t.array(t.object({review:$,decision:$}).strict()).min(1).max(1e4)}).strict(),Ht=t.object({rules:t.array(Hn).min(1).max(100),baseline:bt,candidate:bt}).strict().superRefine((e,n)=>{new Set(e.rules.map(a=>a.feedbackKey)).size!==e.rules.length&&n.addIssue({code:"custom",message:"Select each Human feedback key once."})}),xt=t.object({manifest:at,result:rt}).strict(),St=t.object({id:ee,manifestHash:_e,resultHash:_e}).strict(),yt=t.object({schemaVersion:t.literal("openpond.humanComparisonProjection.v1"),teamId:ee,projectId:ee,selections:Ht,original:t.object({baseline:St,candidate:St}).strict(),humanResults:t.object({baseline:xe,candidate:xe}).strict(),baseline:xt,candidate:xt}).strict(),_t=yt.extend({contentHash:_e}).strict();function y(e){throw new N(e,409)}m(y,"fail");async function Cr(e){let n=Ht.parse(e.selections);await e.authorize();let a={baseline:X(e.baseline),candidate:X(e.candidate)},s=new Set([n.baseline.execution.id,n.candidate.execution.id]);s.size!==2&&y("human_comparison_distinct_executions_required");let r=0;async function i(f){let p=a[f],h=n[f],w=p.manifest.lineage?.execution;p.manifest.lineage?.humanProjection&&y("human_comparison_recursive_projection"),(!w||o(w)!==o(h.execution)||p.manifest.teamId!==e.teamId)&&y("human_comparison_execution_changed");let A=[],B=new Map;for(let x of h.reviews){let b=await e.readReview(x.review);(b.scope!==e.teamId||b.projectId!==e.projectId||b.kind!=="grade"||b.revision!==x.review.revision||b.id!==x.review.id)&&y("human_comparison_review_scope_changed");let T=wt(b,{reviewHash:x.review.contentHash,decisionHash:x.decision.contentHash});r+=new TextEncoder().encode(JSON.stringify({answers:T.answers,form:b.form})).byteLength,r>4194304&&y("human_comparison_projection_too_large"),o(T.decision)!==o(x.decision)&&y("human_comparison_decision_changed"),b.evidence.attempts.some(q=>!s.has(q.experimentId))&&y("human_comparison_foreign_attempt");let E=b.evidence.attempts.filter(q=>q.experimentId===w.id);E.length!==1&&y("human_comparison_attempt_ambiguous");let H=E[0],M=await e.caseIdentity(H),I=p.result.cases.find(q=>Q(q.identity)===Q(M));(!I||M.caseId!==H.taskId||!I.traceRef||I.traceRef.contentHash!==H.trace?.contentHash||I.output===null)&&y("human_comparison_receipt_changed");let O=Q(M)+":"+b.evidence.grader.id;B.has(O)&&y("human_comparison_duplicate_assessment"),B.set(O,{review:b,accepted:T,attempt:H}),A.push(b)}let Ae=dt({executionId:w.id,executionHash:w.contentHash,reviews:A});(Ae.contentHash!==h.resultHash||Ae.coverage.accepted!==A.length)&&y("human_comparison_result_changed");let Fe=new Map(n.rules.map(x=>[x.feedbackKey,x])),en=p.manifest.evaluators.map(x=>{let b=Fe.get(x.feedbackKey);if(!b)return x;let T=A.filter(H=>H.evidence.grader.id===x.release.id&&String(H.evidence.grader.revision)===String(x.release.revision)&&H.evidence.grader.contentHash===x.release.contentHash).map(H=>H.form);(!T.length||new Set(T.map(o)).size!==1)&&y("human_comparison_form_changed");let E=T[0].criteria.find(H=>H.id===b.criterionId);return E||y("human_comparison_criterion_unavailable"),(b.kind==="normalized_score"&&(E.kind!=="score"||b.minimum!==E.minimum||b.maximum!==E.maximum||b.maximum<=b.minimum)||b.kind==="boolean"&&E.kind!=="boolean"||b.kind==="category"&&E.kind!=="category"||b.kind==="preference_score"&&(E.kind!=="preference"||T[0].mode!=="pairwise"))&&y("human_comparison_rule_changed"),{...x,output:b.kind==="boolean"?"boolean":b.kind==="category"?"category":"score",categories:E.kind==="category"?E.options:[],configurationHash:o({original:x.configurationHash,rule:b,formHash:o(T[0])})}});n.rules.some(x=>!p.manifest.evaluators.some(b=>b.feedbackKey===x.feedbackKey))&&y("human_comparison_grader_unavailable");let{contentHash:tn,...nn}=p.manifest,oe={originalManifest:{id:p.manifest.id,contentHash:p.manifest.contentHash},selectionHash:o(h),rulesHash:o(n.rules)},ce=st({...nn,id:nt(oe.originalManifest,oe.selectionHash,oe.rulesHash),lineage:{...p.manifest.lineage,humanProjection:oe},evaluators:en}),an=p.result.cases.map(x=>{let b=x.feedback.map(E=>{let H=Fe.get(E.feedbackKey);if(!H)return E;let M=B.get(Q(x.identity)+":"+E.evaluator.id);(!M||M.review.evidence.grader.contentHash!==E.evaluator.contentHash)&&y("human_comparison_assessment_missing");let I=M.accepted.answers.find(q=>q.criterionId===H.criterionId),O=null;if(I&&!I.abstain&&(H.kind==="normalized_score"&&typeof I.value=="number"&&(O=(I.value-H.minimum)/(H.maximum-H.minimum)),H.kind==="boolean"&&typeof I.value=="boolean"&&(O=I.value),H.kind==="category"&&typeof I.value=="string"&&(O=I.value),H.kind==="preference_score")){let q=M.review.evidence.attempts.findIndex(Je=>Je.experimentId===w.id&&Je.attemptId===M.attempt.attemptId);O=I.value==="tie"?H.tieScore:I.value==="A"||I.value==="B"?I.value===(q===0?"A":"B")?1:0:null}return{...E,status:O===null?"unavailable":"scored",value:O,passed:O===null?null:H.kind==="boolean"?O:H.kind==="normalized_score"&&H.passThreshold!==void 0?Number(O)>=H.passThreshold:null,reasoning:I?.note??null,evidenceRefs:[{id:M.accepted.review.id,contentHash:M.accepted.review.contentHash,mediaType:"application/vnd.openpond.human-review+json",sizeBytes:null},{id:M.accepted.decision.id,contentHash:M.accepted.decision.contentHash,mediaType:"application/vnd.openpond.human-decision+json",sizeBytes:null}]}}),T=x.output!==null&&b.every(E=>E.status==="scored");return{...x,feedback:b,status:T?"completed":x.status,error:T?null:x.error}}),{contentHash:rn,...sn}=p.result,on=it({...sn,manifest:{id:ce.id,contentHash:ce.contentHash},cases:an},ce);for(let x of A){let b=await e.readReview({id:x.id,revision:x.revision,contentHash:x.contentHash});(b.contentHash!==x.contentHash||b.status!=="accepted")&&y("human_comparison_review_changed")}return await e.authorize(),{evidence:{manifest:ce,result:on},humanResult:Ae}}m(i,"lane");let u=await i("baseline"),l=await i("candidate");for(let f of[...n.baseline.reviews,...n.candidate.reviews]){let p=await e.readReview(f.review);(p.contentHash!==f.review.contentHash||p.status!=="accepted"||p.decisions.at(-1)?.contentHash!==f.decision.contentHash)&&y("human_comparison_review_changed")}await e.authorize();let d={baseline:{id:a.baseline.manifest.id,manifestHash:a.baseline.manifest.contentHash,resultHash:a.baseline.result.contentHash},candidate:{id:a.candidate.manifest.id,manifestHash:a.candidate.manifest.contentHash,resultHash:a.candidate.result.contentHash}},c=yt.parse({schemaVersion:"openpond.humanComparisonProjection.v1",teamId:e.teamId,projectId:e.projectId,selections:n,original:d,humanResults:{baseline:u.humanResult,candidate:l.humanResult},baseline:u.evidence,candidate:l.evidence});return new TextEncoder().encode(JSON.stringify(c)).byteLength>8388608&&y("human_comparison_projection_too_large"),_t.parse({...c,contentHash:o(c)})}m(Cr,"projectAcceptedHumanComparison");function Ir(e,n){let a=_t.parse(e),{contentHash:s,...r}=a;s!==o(r)&&y("human_comparison_projection_invalid");for(let i of["baseline","candidate"]){let u=X(a[i]),l=u.manifest.lineage,d=l?.humanProjection,c=a.original[i],f=a.selections[i];(!l||!d||d.originalManifest.id!==c.id||d.originalManifest.contentHash!==c.manifestHash||d.selectionHash!==o(f)||d.rulesHash!==o(a.selections.rules)||o(l.execution)!==o(f.execution)||u.manifest.teamId!==a.teamId||a.humanResults[i].contentHash!==f.resultHash)&&y("human_comparison_projection_lineage_changed");let{contentHash:p,...h}=a.humanResults[i];if((o(h)!==p||h.executionId!==f.execution.id||h.executionHash!==f.execution.contentHash||o(h.selection)!==o(f.reviews.map(w=>w.review)))&&y("human_comparison_human_result_changed"),n){let w=X(n[i]);(w.manifest.lineage?.humanProjection||w.manifest.id!==c.id||w.manifest.contentHash!==c.manifestHash||w.result.contentHash!==c.resultHash||o(w.manifest.lineage?.execution)!==o(f.execution))&&y("human_comparison_original_changed")}}return a}m(Ir,"verifyHumanComparisonProjection");var Et=t.enum(["scored","unscorable"]),ze=t.enum(["policy","environment","collector","verifier","provider","host","user","scheduler"]),yn=t.enum(["completed","policy_failure","incomplete_output","task_deadline","environment_failure","collector_failure","verifier_failure","provider_failure","host_failure","infrastructure_timeout","cancelled"]),te=t.object({schemaVersion:t.literal("openpond.environmentRelease.v1"),id:v,revision:t.number().int().positive(),contract:Xe,actionSchemaRef:J.nullable(),observationSchemaRef:J.nullable(),stateSchemaRef:J.nullable(),artifactCollection:t.object({maxArtifacts:t.number().int().positive().max(1e5),maxTotalBytes:t.number().int().positive().max(1e10)}).strict(),adapterConformanceHashes:t.record(v,R),metadata:C}).strict(),Ct=te.extend({contentHash:R}).strict(),_n=t.enum(["collected","missing","skipped","failed"]),kt=t.enum(["not_requested","passed","failed"]),kn=t.object({requiredOutputPath:t.string().trim().min(1).max(2e3).nullable(),collectedPath:t.string().trim().min(1).max(4e3).nullable(),declaredMediaType:t.string().trim().min(1).max(200).nullable(),detectedMediaType:t.string().trim().min(1).max(200).nullable(),artifact:j.nullable(),status:_n,parseStatus:kt,schemaStatus:kt,errorCode:v.nullable(),failureOwner:ze.nullable(),evidenceRefs:t.array(j).max(1e4),metadata:C}).strict(),L=t.object({schemaVersion:t.literal("openpond.artifactManifest.v1"),id:v,attemptRef:g,entries:t.array(kn).max(1e5),createdAt:_,metadata:C}).strict(),ne=L.extend({contentHash:R}).strict(),U=t.object({schemaVersion:t.literal("openpond.verifierSetRelease.v1"),id:v,revision:t.number().int().positive(),graders:t.array(Ye).min(1).max(1e3),isolation:t.object({processBoundary:t.enum(["same_process","isolated_process","container"]),networkPolicy:t.literal("none"),defaultTimeoutMs:t.number().int().positive().max(3e5)}).strict(),calibrationReceiptRefs:t.array(g).max(1e4),metadata:C}).strict(),It=U.extend({contentHash:R}).strict(),F=t.object({verifierId:v,verifierVersion:t.string().trim().min(1).max(100),status:Et,rawScore:t.number().finite().nullable(),normalizedScore:t.number().min(0).max(1).nullable(),weight:t.number().nonnegative().max(1e3),passed:t.boolean(),hardGate:t.boolean(),rewardEligible:t.boolean(),rewardContribution:t.number().min(0).max(1).nullable(),failureOwner:ze.nullable(),feedback:t.array(t.string().max(2e4)).max(1e3),visibleEvidenceRefs:t.array(j).max(1e4),privilegedEvidenceRefs:t.array(j).max(1e4),metadata:C}).strict().superRefine((e,n)=>{e.status==="scored"&&e.normalizedScore===null&&n.addIssue({code:"custom",message:"A scored component requires a normalized score.",path:["normalizedScore"]}),e.status==="unscorable"&&(e.normalizedScore!==null||e.rewardEligible)&&n.addIssue({code:"custom",message:"An unscorable component cannot contribute reward.",path:["status"]})}),At=t.object({schemaVersion:t.literal("openpond.rewardReceipt.v1"),id:v,attemptRef:g,verifierSetRef:g,artifactManifestRef:g,status:Et,reward:t.number().min(0).max(1).nullable(),learningEligible:t.boolean(),passed:t.boolean(),outcomeClass:yn,failureOwner:ze.nullable(),components:t.array(F).min(1).max(1e4),visibleEvidenceRefs:t.array(j).max(1e5),privilegedEvidenceRefs:t.array(j).max(1e5),supersedes:g.nullable(),createdAt:_,metadata:C}).strict();function Mt(e,n){e.status==="scored"&&(e.reward===null||!e.learningEligible)&&n.addIssue({code:"custom",message:"A scored receipt requires a reward and is learning-eligible.",path:["status"]}),e.status==="unscorable"&&(e.reward!==null||e.learningEligible)&&n.addIssue({code:"custom",message:"An unscorable receipt has null reward and is not learning-eligible.",path:["status"]})}m(Mt,"validateRewardReceipt");var qe=At.superRefine(Mt),Be=At.extend({contentHash:R}).strict().superRefine(Mt);function Nr(e){let n=te.parse(e);return Ct.parse({...n,contentHash:o(n)})}m(Nr,"createEnvironmentRelease");function $r(e){let n=L.parse(e);return ne.parse({...n,contentHash:o(n)})}m($r,"createArtifactManifest");function Dr(e){let n=U.parse(e);return It.parse({...n,contentHash:o(n)})}m(Dr,"createVerifierSetRelease");function Lr(e){if(ae(e.environment,te,"Environment Release"),ae(e.verifierSet,U,"Verifier Set Release"),o(e.taskset.environment)!==o(e.environment.contract))throw new Error("Environment Release does not match the Taskset execution contract.");if(o(e.taskset.graders)!==o(e.verifierSet.graders))throw new Error("Verifier Set Release does not match the Taskset graders.");let{contentHash:n,...a}=e.taskset,s=he.parse({...a,environmentRelease:{id:e.environment.id,contentHash:e.environment.contentHash},verifierSetRelease:{id:e.verifierSet.id,contentHash:e.verifierSet.contentHash}});return ge.parse({...s,contentHash:o(s)})}m(Lr,"bindTasksetExecutionReleases");function Fr(e){switch(e.failureClass){case null:return{outcomeClass:"completed",failureOwner:null};case"policy_failure":return{outcomeClass:"policy_failure",failureOwner:"policy"};case"environment_failure":return{outcomeClass:"environment_failure",failureOwner:"environment"};case"grader_failure":return{outcomeClass:"verifier_failure",failureOwner:"verifier"};case"infrastructure_failure":return{outcomeClass:"host_failure",failureOwner:"host"};case"cancelled":return{outcomeClass:"cancelled",failureOwner:"user"};case"timeout":return e.timeoutKind==="task_deadline"?{outcomeClass:"task_deadline",failureOwner:"policy"}:{outcomeClass:"infrastructure_timeout",failureOwner:"host"}}}m(Fr,"classifyAttemptOutcome");function Jr(e){if(ae(e.verifierSet,U,"Verifier Set Release"),ae(e.artifactManifest,L,"Artifact Manifest"),e.artifactManifest.attemptRef.id!==e.attemptRef.id||e.artifactManifest.attemptRef.contentHash!==e.attemptRef.contentHash)throw new Error("Artifact Manifest does not belong to the Reward Receipt Attempt.");let n=En(e.outcomeClass),a=e.components.map(p=>{let h=F.parse(p),w=n&&h.status==="scored"&&h.normalizedScore!==null&&h.rewardEligible;return F.parse({...h,rewardEligible:w,rewardContribution:w?h.normalizedScore:null})}),s=a.filter(p=>p.rewardEligible&&p.normalizedScore!==null),r=s.length>0?"scored":"unscorable",i=s.some(p=>p.hardGate&&!p.passed),u=s.reduce((p,h)=>p+h.weight,0),l=u>0?s.reduce((p,h)=>p+h.normalizedScore*h.weight,0)/u:0,d=r==="scored"?i?0:l:null,c=r==="scored"&&s.every(p=>p.passed),f=qe.parse({schemaVersion:"openpond.rewardReceipt.v1",id:e.id,attemptRef:e.attemptRef,verifierSetRef:{id:e.verifierSet.id,contentHash:e.verifierSet.contentHash},artifactManifestRef:{id:e.artifactManifest.id,contentHash:e.artifactManifest.contentHash},status:r,reward:d,learningEligible:r==="scored",passed:c,outcomeClass:e.outcomeClass,failureOwner:e.failureOwner,components:a,visibleEvidenceRefs:jt([...e.visibleEvidenceRefs??[],...a.flatMap(p=>p.visibleEvidenceRefs)]),privilegedEvidenceRefs:jt([...e.privilegedEvidenceRefs??[],...a.flatMap(p=>p.privilegedEvidenceRefs)]),supersedes:e.supersedes??null,createdAt:e.createdAt,metadata:e.metadata??{}});return Be.parse({...f,contentHash:o(f)})}m(Jr,"createRewardReceipt");function Kr(e){return Ne(e,te)}m(Kr,"verifyEnvironmentRelease");function Ur(e){return Ne(e,L)}m(Ur,"verifyArtifactManifest");function Wr(e){return Ne(e,U)}m(Wr,"verifyVerifierSetRelease");function Gr(e){let n=Be.safeParse(e);if(!n.success)return!1;let{contentHash:a,...s}=n.data;return o(qe.parse(s))===a}m(Gr,"verifyRewardReceipt");function En(e){return e==="completed"||e==="policy_failure"||e==="incomplete_output"||e==="task_deadline"}m(En,"isScorableOutcome");function jt(e){return[...new Map(e.map(n=>[`${n.id}:${n.contentHash}`,n])).values()]}m(jt,"uniqueArtifactRefs");function ae(e,n,a){let{contentHash:s,...r}=e,i=o(n.parse(r));if(s!==i)throw new Error(`${a} content hash mismatch.`)}m(ae,"verifyContentHash");function Ne(e,n){try{return ae(e,n,"Receipt"),!0}catch{return!1}}m(Ne,"hasValidContentHash");var Cn=t.enum(["calibration","training_reward","validation","frozen_eval"]),as=t.enum(["human","model","deterministic","fixture"]),In=t.enum(["production","synthetic_smoke"]),An=t.enum(["markdown","text","code","json","image"]),Mn=t.object({id:v,label:t.string().trim().min(1).max(500),instruction:t.string().trim().min(1).max(1e4),weight:t.number().nonnegative().max(1e3)}).strict(),jn=t.object({source:t.enum(["attempt_output","artifact"]),path:t.string().trim().min(1).max(2e3),renderer:An}).strict(),Pn=t.object({showTaskPrompt:t.boolean(),randomizeCandidateOrder:t.boolean(),hideModelIdentity:t.boolean(),parts:t.array(jn).min(1).max(20)}).strict().superRefine((e,n)=>{e.parts.some(a=>a.renderer==="markdown"||a.renderer==="text")||n.addIssue({code:"custom",path:["parts"],message:"A preference presentation must expose text or Markdown content."})}),Tn=t.object({strategy:t.literal("randomized_blinded_v1"),maxAssignmentsPerCandidate:t.number().int().positive().max(1e4)}).strict(),On=t.object({algorithm:t.literal("mean_pairwise_win_fraction_v1"),quorum:t.number().int().positive().max(100),rejectAllThreshold:t.number().min(.5).max(1)}).strict(),Vn=t.object({algorithm:t.literal("pairwise_win_fraction_v1"),verifierId:v,verifierVersion:t.string().trim().min(1).max(100),weight:t.number().positive().max(1e3)}).strict(),zn=t.object({minimumSamples:t.number().int().positive().max(1e5),minimumOrderAgreement:t.number().min(0).max(1),minimumTieAgreement:t.number().min(0).max(1),minimumOrderSwapAgreement:t.number().min(0).max(1)}).strict(),De=t.object({schemaVersion:t.literal("openpond.preferenceComparisonRelease.v1"),id:v,revision:t.number().int().positive(),tasksetRelease:g,candidateCount:t.number().int().min(2).max(4),resultMode:t.literal("ordered_tie_groups"),allowTies:t.boolean(),allowRejectAll:t.boolean(),presentation:Pn,rubricRef:j,criteria:t.array(Mn).max(20),assignment:Tn,aggregation:On,rewardProjection:Vn,calibration:zn,metadata:C}).strict().superRefine((e,n)=>{let a=e.criteria.map(s=>s.id);new Set(a).size!==a.length&&n.addIssue({code:"custom",path:["criteria"],message:"Preference criterion IDs must be unique."})}),Tt=De.extend({contentHash:R}).strict(),qn=t.object({id:v,contentHash:R}).strict(),Bn=t.object({tasksetRelease:g,harnessReleases:t.array(g).min(1).max(4),runManifestRefs:t.array(g).min(1).max(4),harnessCompatibilityReceiptRefs:t.array(g).max(6),environmentRelease:g,verifierSetRelease:g,toolContractHash:R,policyHash:R}).strict(),Nn=t.object({attemptRef:g,runManifestRef:g,artifactManifestRef:g,visibleArtifactIds:t.array(v).max(1e5)}).strict().superRefine((e,n)=>{new Set(e.visibleArtifactIds).size!==e.visibleArtifactIds.length&&n.addIssue({code:"custom",path:["visibleArtifactIds"],message:"Visible artifact IDs must be unique per candidate."})}),Ot=t.object({schemaVersion:t.literal("openpond.comparisonAssignment.v1"),id:v,comparisonRelease:g,taskRef:qn,lineage:Bn,candidates:t.array(Nn).min(2).max(4),presentedCandidateOrder:t.array(v).min(2).max(4),purpose:Cn,createdAt:_,metadata:C}).strict().superRefine((e,n)=>{let a=e.candidates.map(s=>s.attemptRef.id);new Set(a).size!==a.length&&n.addIssue({code:"custom",path:["candidates"],message:"An assignment cannot contain the same attempt twice."}),(new Set(e.presentedCandidateOrder).size!==e.presentedCandidateOrder.length||e.presentedCandidateOrder.length!==a.length||e.presentedCandidateOrder.some(s=>!a.includes(s)))&&n.addIssue({code:"custom",path:["presentedCandidateOrder"],message:"Presented candidate order must contain every assignment candidate exactly once."})}),Vt=Ot,zt=Ot.extend({contentHash:R}).strict().superRefine((e,n)=>{let a=e.candidates.map(s=>s.attemptRef.id);new Set(a).size!==a.length&&n.addIssue({code:"custom",path:["candidates"],message:"An assignment cannot contain the same attempt twice."})}),qt=t.array(t.array(v).min(1).max(4)).max(4),$n=t.discriminatedUnion("kind",[t.object({kind:t.enum(["human","model","deterministic"]),releaseRef:g}).strict(),t.object({kind:t.literal("fixture"),releaseRef:g,fixtureRelease:g,labelSource:t.literal("synthetic"),qualificationEligibility:t.literal("smoke_only")}).strict()]),Bt=t.object({schemaVersion:t.literal("openpond.preferenceReceipt.v1"),id:v,assignmentRef:g,reviewer:$n,order:qt,rejectAll:t.boolean(),criterionScores:t.record(v,t.record(v,t.number().finite().min(0).max(1))),feedbackArtifactRef:j.nullable(),startedAt:_,completedAt:_,metadata:C}).strict().superRefine((e,n)=>{e.rejectAll&&e.order.length!==0&&n.addIssue({code:"custom",path:["order"],message:"A reject-all preference receipt cannot contain an order."}),!e.rejectAll&&e.order.length===0&&n.addIssue({code:"custom",path:["order"],message:"A non-reject preference receipt requires an ordered result."}),Date.parse(e.completedAt)<Date.parse(e.startedAt)&&n.addIssue({code:"custom",path:["completedAt"],message:"A preference receipt cannot complete before it starts."})}),Nt=Bt,$t=Bt.extend({contentHash:R}).strict(),Dt=t.object({schemaVersion:t.literal("openpond.preferenceAggregationReceipt.v1"),id:v,assignmentRef:g,comparisonRelease:g,receiptRefs:t.array(g).min(1).max(100),order:qt,rejectAll:t.boolean(),pairwiseWinFractions:t.record(v,t.number().min(0).max(1)),quorum:t.number().int().positive().max(100),createdAt:_,metadata:C}).strict().superRefine((e,n)=>{e.rejectAll&&e.order.length!==0&&n.addIssue({code:"custom",path:["order"],message:"A reject-all aggregate cannot contain an order."})}),Dn=Dt,Ln=Dt.extend({contentHash:R}).strict(),Lt=t.object({schemaVersion:t.literal("openpond.preferenceCalibrationReport.v1"),id:v,comparisonRelease:g,automatedReviewer:g,humanReceiptRefs:t.array(g).min(1).max(1e5),modelReceiptRefs:t.array(g).min(1).max(1e5),sampleCount:t.number().int().positive().max(1e5),orderAgreement:t.number().min(0).max(1),tieAgreement:t.number().min(0).max(1),orderSwapAgreement:t.number().min(0).max(1),passed:t.boolean(),createdAt:_,metadata:C}).strict(),Ft=Lt,Jt=Lt.extend({contentHash:R}).strict();function rs(e){let n=De.parse(e);return Tt.parse({...n,contentHash:o(n)})}m(rs,"createPreferenceComparisonRelease");function Fn(e){return se(e,De,Tt)}m(Fn,"verifyPreferenceComparisonRelease");function ss(e){let n=G(e.comparisonRelease),a=sa(e.taskset);if(!k(n.tasksetRelease,S(a)))throw new Error("Preference Comparison Release does not belong to the supplied Taskset Release.");if(e.candidates.length!==n.candidateCount)throw new Error("Comparison assignment candidate count does not match the immutable comparison release.");let s=n.presentation.parts.some(f=>f.source==="artifact"),r=e.candidates.map(f=>Qn(f,a,s)),i=r[0];for(let f of r.slice(1)){if(f.attempt.taskId!==i.attempt.taskId)throw new Error("Preference comparison candidates must belong to the same Taskset task.");let p=aa(i.runManifest,f.runManifest,e.harnessCompatibilityReceipts??[]);p&&k(p.baseHarnessRelease,f.runManifest.harnessRelease)?Te(f.runManifest,i.runManifest,p):Te(i.runManifest,f.runManifest,p)}let u=a.tasks.find(f=>f.id===i.attempt.taskId);if(!u)throw new Error("Comparison candidates reference a task absent from the supplied Taskset Release.");if(!a.environmentRelease||!a.verifierSetRelease)throw new Error("Preference comparison requires a Taskset bound to immutable Environment and Verifier Set Releases.");let l=r.map(f=>f.attempt.id),d=[...e.presentedCandidateOrder??l],c=Vt.parse({schemaVersion:"openpond.comparisonAssignment.v1",id:e.id,comparisonRelease:S(n),taskRef:{id:u.id,contentHash:o({taskId:u.id,tasksetRelease:S(a)})},lineage:{tasksetRelease:S(a),harnessReleases:$e(r.map(f=>f.runManifest.harnessRelease)),runManifestRefs:$e(r.map(f=>S(f.runManifest))),harnessCompatibilityReceiptRefs:$e((e.harnessCompatibilityReceipts??[]).map(S)),environmentRelease:a.environmentRelease,verifierSetRelease:a.verifierSetRelease,toolContractHash:o(a.tools),policyHash:o(a.policy)},candidates:r.map(f=>({attemptRef:S(f.attempt),runManifestRef:S(f.runManifest),artifactManifestRef:S(f.artifactManifest),visibleArtifactIds:[...f.visibleArtifactIds]})),presentedCandidateOrder:d,purpose:e.purpose,createdAt:e.createdAt,metadata:e.metadata??{}});return zt.parse({...c,contentHash:o(c)})}m(ss,"createComparisonAssignment");function Jn(e){return se(e,Vt,zt)}m(Jn,"verifyComparisonAssignment");function Le(e,n){let a=ie(e),s=G(n);if(!k(a.comparisonRelease,S(s)))throw new Error("Comparison assignment does not reference the supplied comparison release.");if(a.candidates.length!==s.candidateCount)throw new Error("Comparison assignment does not satisfy its release candidate count.")}m(Le,"validateComparisonAssignment");function Kn(e){let n=ie(e.assignment),a=G(e.comparisonRelease);Le(n,a);let s=Nt.parse({schemaVersion:"openpond.preferenceReceipt.v1",id:e.id,assignmentRef:S(n),reviewer:e.reviewer,order:e.order.map(r=>[...r]),rejectAll:e.rejectAll,criterionScores:e.criterionScores??{},feedbackArtifactRef:e.feedbackArtifactRef??null,startedAt:e.startedAt,completedAt:e.completedAt,metadata:e.metadata??{}});return W({order:s.order,rejectAll:s.rejectAll},n,a),Xn(s.criterionScores,n,a),$t.parse({...s,contentHash:o(s)})}m(Kn,"createPreferenceReceipt");function is(e){let n=e.assignment.candidates.map(l=>l.attemptRef.id),a=Object.keys(e.ratings);if(a.length!==n.length||n.some(l=>!e.ratings[l])||a.some(l=>!n.includes(l)))throw new Error("Synthetic fixture ratings must label every assignment candidate exactly once.");let s=["love","like","reject"],r=n.every(l=>e.ratings[l]==="reject"),i=r?[]:s.map(l=>n.filter(d=>e.ratings[d]===l)).filter(l=>l.length>0),u={love:1,like:.5,reject:0};return Kn({id:e.id,assignment:e.assignment,comparisonRelease:e.comparisonRelease,reviewer:{kind:"fixture",releaseRef:e.labelerRelease,fixtureRelease:e.fixtureRelease,labelSource:"synthetic",qualificationEligibility:"smoke_only"},order:i,rejectAll:r,criterionScores:Object.fromEntries(n.map(l=>[l,Object.fromEntries(e.comparisonRelease.criteria.map(d=>[d.id,u[e.ratings[l]]]))])),startedAt:e.startedAt,completedAt:e.completedAt,metadata:e.metadata??{}})}m(is,"createSyntheticFixturePreferenceReceipt");function Un(e){return se(e,Nt,$t)}m(Un,"verifyPreferenceReceipt");function Wn(e){return se(e,Dn,Ln)}m(Wn,"verifyPreferenceAggregationReceipt");function os(e){let n=G(e.comparisonRelease);if(e.pairs.length<n.calibration.minimumSamples)throw new Error(`Preference calibration requires at least ${n.calibration.minimumSamples} human/model pairs.`);let a=e.pairs.map(c=>ta(c,n)),s=a[0].model.reviewer.releaseRef;if(a.some(c=>!k(c.model.reviewer.releaseRef,s)))throw new Error("Preference calibration requires model receipts from one immutable automated reviewer release.");let r=re(a.map(c=>Pt(c.human,c.model,c.assignment))),i=re(a.map(c=>ea(c.human,c.model,c.assignment))),u=re(a.map(c=>c.swappedModel?Pt(c.model,c.swappedModel,c.assignment):1)),l=r>=n.calibration.minimumOrderAgreement&&i>=n.calibration.minimumTieAgreement&&u>=n.calibration.minimumOrderSwapAgreement,d=Ft.parse({schemaVersion:"openpond.preferenceCalibrationReport.v1",id:e.id,comparisonRelease:S(n),automatedReviewer:s,humanReceiptRefs:a.map(c=>S(c.human)),modelReceiptRefs:a.map(c=>S(c.model)),sampleCount:a.length,orderAgreement:r,tieAgreement:i,orderSwapAgreement:u,passed:l,createdAt:e.createdAt,metadata:e.metadata??{}});return Jt.parse({...d,contentHash:o(d)})}m(os,"createPreferenceCalibrationReport");function Gn(e){return se(e,Ft,Jt)}m(Gn,"verifyPreferenceCalibrationReport");function Zn(e){let n=ie(e.assignment),a=G(e.comparisonRelease);if(Le(n,a),e.result.schemaVersion==="openpond.preferenceReceipt.v1"){let r=ke(e.result);if(!k(r.assignmentRef,S(n)))throw new Error("Preference receipt does not belong to the supplied assignment.");return W(r,n,a),Yn(r,n)}let s=ra(e.result);if(!k(s.assignmentRef,S(n))||!k(s.comparisonRelease,S(a)))throw new Error("Preference aggregate does not belong to the supplied assignment and release.");return W(s,n,a),s.rejectAll?Ut(n):s.pairwiseWinFractions}m(Zn,"projectPairwiseWinFraction");function cs(e){let n=ie(e.assignment),a=G(e.comparisonRelease),s=Zn({assignment:n,comparisonRelease:a,result:e.result}),r=new Map((e.candidates??[]).map(f=>[f.attemptRef.id,f])),i=e.result.schemaVersion==="openpond.preferenceReceipt.v1"?e.result:null,u=i?.reviewer.kind==="model",l=i?.reviewer.kind==="fixture",d=In.parse(e.rewardScope??"production"),c=l?d==="synthetic_smoke":!u||na(i,a,e.calibrationReport??null);return Object.fromEntries(n.candidates.map(f=>{let p=r.get(f.attemptRef.id),h=p?.eligible??!0,w=s[f.attemptRef.id],A=h&&c?F.parse({verifierId:a.rewardProjection.verifierId,verifierVersion:a.rewardProjection.verifierVersion,status:"scored",rawScore:w,normalizedScore:w,weight:a.rewardProjection.weight,passed:w>0,hardGate:!1,rewardEligible:!0,rewardContribution:w,failureOwner:null,feedback:[],visibleEvidenceRefs:[],privilegedEvidenceRefs:[],metadata:{comparisonAssignment:S(n),preferenceResult:S(e.result),...e.calibrationReport?{calibrationReport:S(e.calibrationReport)}:{}}}):F.parse({verifierId:a.rewardProjection.verifierId,verifierVersion:a.rewardProjection.verifierVersion,status:"unscorable",rawScore:null,normalizedScore:null,weight:a.rewardProjection.weight,passed:!1,hardGate:!1,rewardEligible:!1,rewardContribution:null,failureOwner:p?.failureOwner??"verifier",feedback:[h?l?"Synthetic fixture preference evidence is admitted only to synthetic-smoke reward scope.":"Automated preference reviewer is uncalibrated or inconsistent.":"Candidate is not eligible for comparative preference scoring."],visibleEvidenceRefs:[],privilegedEvidenceRefs:[],metadata:{comparisonAssignment:S(n),preferenceResult:S(e.result),...e.calibrationReport?{calibrationReport:S(e.calibrationReport)}:{}}});return[f.attemptRef.id,A]}))}m(cs,"createPreferenceRewardComponents");function Qn(e,n,a){let s=be.parse(e.attempt);if(!D(s))throw new Error("Comparison candidate Attempt Receipt has an invalid content hash.");let r=ne.parse(e.artifactManifest);if(!ia(r))throw new Error("Comparison candidate Artifact Manifest has an invalid content hash.");let i=K.parse(e.runManifest);if(!oa(i))throw new Error("Comparison candidate Run Manifest has an invalid content hash.");if(!k(s.runManifest,S(i)))throw new Error("Comparison candidate Attempt Receipt does not belong to its supplied Run Manifest.");if(!k(i.tasksetRelease,S(n)))throw new Error("Comparison candidate Run Manifest does not belong to the supplied Taskset Release.");if(!k(r.attemptRef,S(s)))throw new Error("Comparison candidate Artifact Manifest does not belong to its Attempt Receipt.");if(!s.terminal||s.failureClass!==null)throw new Error("Only completed, non-failed attempts can be assigned for comparative review.");let u=[...e.visibleArtifactIds],l=new Set(u),d=new Set(r.entries.filter(c=>c.status==="collected"&&c.artifact!==null).map(c=>c.artifact.id));if(a&&!u.length)throw new Error("Comparison presentation requires each candidate to expose a reviewable artifact.");if(u.some(c=>!d.has(c)))throw new Error("Comparison candidate exposes an artifact that is missing, uncollected, or unreviewable.");if(l.size!==u.length)throw new Error("Comparison candidate visible artifacts must be unique.");return{attempt:s,artifactManifest:r,runManifest:i,visibleArtifactIds:u}}m(Qn,"validateComparisonCandidate");function W(e,n,a){let s=n.candidates.map(i=>i.attemptRef.id);if(e.rejectAll){if(!a.allowRejectAll)throw new Error("This comparison release does not allow reject-all results.");if(e.order.length)throw new Error("Reject-all results cannot include ordered candidates.");return}let r=e.order.flat();if(new Set(r).size!==r.length||r.length!==s.length||r.some(i=>!s.includes(i)))throw new Error("Preference result must rank every assignment candidate exactly once.");if(!a.allowTies&&e.order.some(i=>i.length>1))throw new Error("This comparison release does not allow tied candidates.")}m(W,"validatePreferenceResult");function Xn(e,n,a){let s=new Set(n.candidates.map(i=>i.attemptRef.id)),r=new Set(a.criteria.map(i=>i.id));for(let[i,u]of Object.entries(e)){if(!s.has(i))throw new Error("Criterion scores include a candidate absent from the assignment.");for(let l of Object.keys(u))if(!r.has(l))throw new Error("Criterion scores include a criterion absent from the comparison release.")}}m(Xn,"validateCriterionScores");function Yn(e,n){if(e.rejectAll)return Ut(n);let a=n.candidates.map(r=>r.attemptRef.id),s=new Map(e.order.flatMap((r,i)=>r.map(u=>[u,i])));return Object.fromEntries(a.map(r=>{let i=s.get(r);if(i===void 0)throw new Error("Preference result is missing a comparison candidate.");let u=0;for(let l of a){if(l===r)continue;let d=s.get(l);if(d===void 0)throw new Error("Preference result is missing a comparison candidate.");u+=i<d?1:i===d?.5:0}return[r,u/(a.length-1)]}))}m(Yn,"pairwiseScoresForResult");function Pt(e,n,a){let s=a.candidates.map(i=>i.attemptRef.id),r=Kt(s);return r.length?re(r.map(([i,u])=>Ee(e,i,u)===Ee(n,i,u)?1:0)):1}m(Pt,"pairwiseAgreement");function ea(e,n,a){let s=Kt(a.candidates.map(r=>r.attemptRef.id));return s.length?re(s.map(([r,i])=>Ee(e,r,i)===0==(Ee(n,r,i)===0)?1:0)):1}m(ea,"tieAgreementScore");function Ee(e,n,a){if(e.rejectAll)return 0;let s=new Map(e.order.flatMap((u,l)=>u.map(d=>[d,l]))),r=s.get(n),i=s.get(a);if(r===void 0||i===void 0)throw new Error("Preference result does not cover all comparison candidates.");return r<i?1:r===i?0:-1}m(Ee,"pairRelation");function Kt(e){let n=[];for(let a=0;a<e.length;a+=1)for(let s=a+1;s<e.length;s+=1)n.push([e[a],e[s]]);return n}m(Kt,"pairsFor");function ta(e,n){let a=ie(e.assignment);if(Le(a,n),a.purpose==="frozen_eval")throw new Error("Frozen-evaluation comparisons cannot calibrate an automated preference reviewer.");let s=ke(e.human),r=ke(e.model);if(s.reviewer.kind!=="human"||r.reviewer.kind!=="model")throw new Error("Preference calibration requires one human and one automated model receipt per assignment.");if(!k(s.assignmentRef,S(a))||!k(r.assignmentRef,S(a)))throw new Error("Preference calibration receipts must belong to their supplied assignment.");W(s,a,n),W(r,a,n);let i=e.swappedModel?ke(e.swappedModel):null;if(i){if(i.reviewer.kind!=="model"||!k(i.assignmentRef,S(a)))throw new Error("Order-swap calibration receipts must be model receipts for the same assignment.");if(!k(i.reviewer.releaseRef,r.reviewer.releaseRef))throw new Error("Order-swap calibration must use the same immutable automated reviewer release.");W(i,a,n)}return{assignment:a,human:s,model:r,swappedModel:i}}m(ta,"validateCalibrationPair");function na(e,n,a){return!a||!Gn(a)?!1:a.passed&&k(a.comparisonRelease,S(n))&&k(a.automatedReviewer,e.reviewer.releaseRef)}m(na,"isCalibratedAutomatedReviewer");function Ut(e){return Object.fromEntries(e.candidates.map(n=>[n.attemptRef.id,0]))}m(Ut,"zeroScores");function re(e){return e.length?e.reduce((n,a)=>n+a,0)/e.length:0}m(re,"mean");function S(e){return{id:e.id,contentHash:e.contentHash}}m(S,"ref");function k(e,n){return e.id===n.id&&e.contentHash===n.contentHash}m(k,"sameRef");function $e(e){return[...new Map(e.map(n=>[`${n.id}:${n.contentHash}`,n])).values()]}m($e,"uniqueRefs");function aa(e,n,a){if(!k(e.harnessRelease,n.harnessRelease))return a.find(s=>k(s.tasksetRelease,e.tasksetRelease)&&(k(s.baseHarnessRelease,e.harnessRelease)&&k(s.candidateHarnessRelease,n.harnessRelease)||k(s.baseHarnessRelease,n.harnessRelease)&&k(s.candidateHarnessRelease,e.harnessRelease)))}m(aa,"compatibilityForRunManifests");function se(e,n,a){let s=a.safeParse(e);if(!s.success||!s.data)return!1;let{contentHash:r,...i}=s.data;try{return o(n.parse(i))===r}catch{return!1}}m(se,"verifyHashed");function G(e){if(!Fn(e))throw new Error("Preference Comparison Release has an invalid content hash.");return e}m(G,"verifyComparisonRelease");function ie(e){if(!Jn(e))throw new Error("Comparison Assignment has an invalid content hash.");return e}m(ie,"verifyAssignment");function ke(e){if(!Un(e))throw new Error("Preference Receipt has an invalid content hash.");return e}m(ke,"verifyReceipt");function ra(e){if(!Wn(e))throw new Error("Preference Aggregation Receipt has an invalid content hash.");return e}m(ra,"verifyAggregate");function sa(e){let{contentHash:n,...a}=ge.parse(e);if(o(he.parse(a))!==n)throw new Error("Taskset Release has an invalid content hash.");return e}m(sa,"verifyTasksetRelease");function ia(e){let n=ne.safeParse(e);if(!n.success)return!1;let{contentHash:a,...s}=n.data;return o(L.parse(s))===a}m(ia,"verifyArtifactManifest");function oa(e){let n=K.safeParse(e);if(!n.success)return!1;let{contentHash:a,...s}=n.data;return o(s)===a}m(oa,"verifyRunManifest");var ca=t.object({profileId:v,sourceRevision:t.string().trim().min(1).max(240),harnessRelease:g}).strict(),ma=t.object({kind:t.enum(["run","suite","comparison"]),id:v,contentHash:R}).strict(),Wt=t.object({schemaVersion:t.literal("openpond.profileEvaluationReport.v1"),id:v,createdAt:_,testedSources:t.array(ca).min(1).max(100),tasksetReleases:t.array(g).min(1).max(100),metricPolicyHashes:t.array(R).min(1).max(100),modelConfigurationHashes:t.array(R).min(1).max(100),evidence:t.array(ma).min(1).max(100),summary:t.object({totalChecks:t.number().int().nonnegative(),passedChecks:t.number().int().nonnegative(),failedChecks:t.number().int().nonnegative(),unscoredChecks:t.number().int().nonnegative(),meanScore:t.number().min(0).max(1).nullable()}).strict()}).strict().superRefine((e,n)=>{let{summary:a}=e;a.passedChecks+a.failedChecks+a.unscoredChecks!==a.totalChecks&&n.addIssue({code:"custom",path:["summary"],message:"Report check counts must add up."}),new Set(e.evidence.map(({kind:s,id:r})=>`${s}:${r}`)).size!==e.evidence.length&&n.addIssue({code:"custom",path:["evidence"],message:"Report evidence must be unique."})}),Gt=Wt.safeExtend({contentHash:R});function fs(e){let n=Wt.parse(e);return Gt.parse({...n,contentHash:o(n)})}m(fs,"createProfileEvaluationReport");function ps(e){let n=Gt.parse(e),{contentHash:a,...s}=n;if(o(s)!==a)throw new Error("Profile evaluation report content hash differs from its source bytes.");return n}m(ps,"assertProfileEvaluationReport");var la=t.string().regex(/^(0|-?[1-9][0-9]*)$/).max(20).refine(e=>{if(e.length>20||!/^(0|-?[1-9][0-9]*)$/.test(e))return!1;let n=BigInt(e);return n>=-(1n<<63n)&&n<1n<<63n},"SQL integers must fit signed 64-bit storage."),Qt=t.union([t.null(),t.string().max(262144),t.number().finite(),t.object({integer:la}).strict(),t.object({blobBase64:t.string().max(349528).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}).strict()]),Zt=t.string().min(1).max(128).refine(e=>!e.includes("\0")),da=t.object({tables:t.array(t.object({name:Zt,columns:t.array(t.object({name:Zt,type:t.enum(["INTEGER","REAL","TEXT","BLOB"])}).strict()).min(1).max(128),rows:t.array(t.array(Qt).max(128)).max(4096)}).strict()).max(64)}).strict().superRefine((e,n)=>{let a=new Set;for(let[s,r]of e.tables.entries()){let i=r.name.toLowerCase();(a.has(i)||i.startsWith("sqlite_"))&&n.addIssue({code:"custom",path:["tables",s,"name"],message:"Table names must be unique and outside SQLite's reserved namespace."}),a.add(i),new Set(r.columns.map(u=>u.name.toLowerCase())).size!==r.columns.length&&n.addIssue({code:"custom",path:["tables",s,"columns"],message:"Column names must be unique."}),r.rows.some(u=>u.length!==r.columns.length)&&n.addIssue({code:"custom",path:["tables",s,"rows"],message:"Each row must match the declared columns."})}}),Ce=t.object({schemaVersion:t.literal("openpond.sqlExecution.v1"),snapshot:da,sql:t.string().min(1).max(65536).refine(e=>!e.includes("\0")),maxRows:t.number().int().min(1).max(4096),maxResultBytes:t.number().int().min(256).max(262144)}).strict(),ws=t.discriminatedUnion("status",[t.object({status:t.literal("completed"),columns:t.array(t.string()).max(128),rows:t.array(t.array(Qt).max(128)).max(4096)}).strict(),t.object({status:t.literal("rejected"),code:t.enum(["invalid_query","multiple_statements","result_too_large","memory_limit"])}).strict()]);function bs(e){le(e,1048576);let n=Ce.parse(e);if(new TextEncoder().encode(n.sql).byteLength>65536)throw new Error("sql_source_too_large");return n}m(bs,"assertSqlExecutionRequest");var Ie=t.object({scope:t.enum(["input","initialState","state","arguments"]),path:t.array(t.string().min(1).max(256)).max(16)}).strict(),Xt={id:t.string().min(1).max(128),operation:t.enum(["step","collect"]),toolName:t.string().min(1).max(500).optional(),timeoutMs:t.number().int().min(1).max(2e4)},Yt=t.discriminatedUnion("kind",[t.object({...Xt,kind:t.literal("sqlite.v1"),sql:Ie,snapshot:Ie,maxRows:Ce.shape.maxRows,maxResultBytes:Ce.shape.maxResultBytes}).strict(),t.object({...Xt,kind:t.literal("javascript.v1"),source:Ie,cases:Ie,exportName:t.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/).max(128),maxCases:t.number().int().min(1).max(32),maxResultBytes:t.number().int().min(256).max(262144)}).strict()]).superRefine((e,n)=>{e.operation==="step"!=(e.toolName!==void 0)&&n.addIssue({code:"custom",path:["toolName"],message:"Only step services require a declared tool name."}),e.operation==="collect"&&(e.kind==="sqlite.v1"?[e.sql,e.snapshot]:[e.source,e.cases]).some(s=>s.scope==="arguments")&&n.addIssue({code:"custom",message:"Collection has no tool arguments."})});var ua=t.object({schemaVersion:t.literal("openpond.javascriptEnvironment.v1"),id:t.string().trim().min(1).max(500),revision:t.number().int().positive(),module:J.refine(e=>e.visibility==="host_private","Environment code belongs to the execution owner."),tools:t.array(Ue).min(1).max(200),maxSteps:t.number().int().min(1).max(1e3),maxStateBytes:t.number().int().min(1).max(1048576),maxObservationBytes:t.number().int().min(1).max(262144),operationTimeoutMs:t.number().int().min(1).max(3e4),executionServices:t.array(Yt).min(1).max(16).optional()}).strict().superRefine((e,n)=>{new Set(e.tools.map(s=>s.name)).size!==e.tools.length&&n.addIssue({code:"custom",path:["tools"],message:"Environment tool names must be unique."}),e.tools.forEach((s,r)=>{We(s.inputSchema).valid||n.addIssue({code:"custom",path:["tools",r,"inputSchema"],message:"Environment tools require a supported JSON schema."}),s.inputSchemaHash!==o(s.inputSchema)&&n.addIssue({code:"custom",path:["tools",r,"inputSchemaHash"],message:"Tool schema identity differs from its declared schema."})});let a=e.executionServices??[];new Set(a.map(s=>s.id)).size!==a.length&&n.addIssue({code:"custom",path:["executionServices"],message:"Execution service identities must be unique."}),a.forEach((s,r)=>{let i=e.tools.find(u=>u.name===s.toolName);s.operation==="step"&&!i&&n.addIssue({code:"custom",path:["executionServices",r,"toolName"],message:"Execution services must target a declared tool."}),s.timeoutMs>=Math.min(e.operationTimeoutMs,i?.timeoutMs??e.operationTimeoutMs)&&n.addIssue({code:"custom",path:["executionServices",r,"timeoutMs"],message:"Service budgets must leave time for the authored controller."})})}),fa=ua.safeExtend({contentHash:t.string().regex(/^[a-f0-9]{64}$/)}),As=t.enum(["create","reset","step","collect","destroy"]),Ms=t.object({state:t.record(t.string(),t.unknown()),observation:t.record(t.string(),t.unknown())}).strict();function js(e){le(e,4194304);let n=fa.parse(e),{contentHash:a,...s}=n;if(o(s)!==a)throw new Error("environment_definition_hash_mismatch");return structuredClone(n)}m(js,"assertJavaScriptEnvironmentDefinition");export{Rn as a,vn as b,Se as c,bn as d,ht as e,Sn as f,tr as g,nr as h,K as i,Pe as j,be as k,cn as l,Ra as m,va as n,D as o,mt as p,fn as q,z as r,Ta as s,pn as t,Oa as u,Ve as v,lr as w,gt as x,dr as y,xe as z,dt as A,Ht as B,_t as C,Cr as D,Ir as E,Et as F,ze as G,yn as H,Ct as I,kn as J,ne as K,It as L,F as M,Be as N,Nr as O,$r as P,Dr as Q,Lr as R,Fr as S,Jr as T,Kr as U,Ur as V,Wr as W,Gr as X,Tt as Y,zt as Z,$t as _,Jt as $,rs as aa,ss as ba,Jn as ca,Le as da,Kn as ea,is as fa,Un as ga,os as ha,cs as ia,hn as ja,La as ka,Gt as la,fs as ma,ps as na,gn as oa,Za as pa,ws as qa,bs as ra,Yt as sa,fa as ta,As as ua,Ms as va,js as wa};
@@ -1,2 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{k as H,la as R}from"./chunk-JBHAU7PH.js";import{J as I,N as C}from"./chunk-ZJY2L43W.js";import{k,l as b}from"./chunk-P653BXMY.js";import{a as h}from"./chunk-FTQLQJQV.js";import{promises as s}from"node:fs";import n from"node:path";import{execFile as O}from"node:child_process";import{promisify as A}from"node:util";var T=A(O);async function v(e,i,a={}){return(await T("git",["-C",e,...i],{encoding:"utf8",timeout:3e4,maxBuffer:8388608,env:{...process.env,...a}})).stdout.trim()}h(v,"candidateGit");async function j(e,i=I,a=!1){if(e.profileRef.source!=="local"&&!a)throw new Error("This Git adapter requires the actual installed local Profile owner; hosted adoption needs its published-source owner.");let r=await i(e.profileRef);if(r.error||r.mode!=="local"||r.activeProfile!==e.profileRef.profileId||!r.repoPath||!r.sourcePath)throw new Error("The original Profile owner is unavailable.");let l=await s.realpath(r.repoPath),p=await s.realpath(r.sourcePath),f=n.relative(l,p);if(f.startsWith("..")||n.isAbsolute(f))throw new Error("Profile source escapes its actual Git owner.");return{profile:r,repo:l,source:p,sourceRelative:f}}h(j,"originalCandidateProfile");async function Pe(e,i,a=!0){if(!/^[a-f0-9]{40}$/.test(i)||await v(e,["rev-parse","HEAD"])!==i)throw new Error("The original Profile Git revision changed.");if(a&&await v(e,["status","--porcelain","--untracked-files=all"]))throw new Error("Commit or reconcile changes in the original Profile before this operation.")}h(Pe,"assertCandidateGitHead");async function ye(e,i){let a=await j(e.state,e.loadProfile,e.allowRemoteSnapshot),r=n.join(e.storeDir,"library","harnesses","profile-candidate-staging");await s.mkdir(r,{recursive:!0,mode:448});let l=await s.mkdtemp(n.join(r,"source-"));await s.rmdir(l),await v(a.repo,["worktree","add","--detach",l,e.commit]);try{let p=await C({repoPath:l,profileId:e.state.profileRef.profileId});if(p.error||!p.sourcePath)throw new Error("The staged original Profile cannot be loaded.");return await i({root:l,profile:p,repo:a.repo,source:p.sourcePath})}finally{await v(a.repo,["worktree","remove","--force",l]).catch(()=>{}),await s.rm(l,{recursive:!0,force:!0})}}h(ye,"withCandidateProfileWorktree");function y(e){if(!e||n.isAbsolute(e)||e.includes("\\")||e.split("/").some(i=>!i||i==="."||i===".."))throw new Error("Original Profile patch path is not contained.");return e}h(y,"portable");async function ve(e){let i=e.base.manifest.metadata.profileSourceBindings;if(!Array.isArray(i))throw new Error("The original release needs compiler source bindings before candidate adoption.");let a=e.state.component.path,r=e.state.component,l=new Map(i.map(t=>{if(!t||typeof t!="object"||typeof t.releasedPath!="string"||typeof t.profileRelativePath!="string")throw new Error("Original Profile source binding is invalid.");return[y(t.releasedPath),y(t.profileRelativePath)]})),p=r.kind==="instruction"&&a==="instructions/system.md"&&e.base.manifest.metadata.profileInstructionSourcePath==="instructions/system.md"&&!l.has(a),f=l.get(a)??(p?"instructions/system.md":void 0),S=r.kind==="workflow"?`workflows/${r.workflowId}/`:r.kind==="agent"?a.split("/").slice(0,2).join("/")+"/":n.posix.dirname(a)+"/",w=f?n.posix.dirname(f)+"/":null;if(r.kind==="workflow"&&!f&&(w=S),r.kind==="agent"){let t=e.profile.agents.find(o=>a.startsWith(`agents/${o.id}/`));if(!t)throw new Error("The selected Agent original source is unavailable.");let c=y(t.path);w=((await s.lstat(n.join(e.source,c))).isDirectory()?c:n.posix.dirname(c))+"/"}let E=new Map(e.base.sourceFiles.map(t=>[t.path,t])),x=new Map(e.candidate.sourceFiles.map(t=>[t.path,t])),g=new Map;for(let t of new Set([...E.keys(),...x.keys()])){let c=E.get(t),m=x.get(t);if(c?.asset.contentHash===m?.asset.contentHash)continue;if(c&&c.asset.visibility!=="policy"||m&&m.asset.visibility!=="policy")throw new Error("A candidate cannot change protected Profile source.");let o=l.get(t)??(p&&t===a?f:void 0);if(!o&&t.startsWith(S)&&w&&(o=w+t.slice(S.length)),!o&&t==="workflows/catalog.json"&&[...l.keys()].some(P=>/^workflows\/[^/]+\/(PROMPT\.md|ACTION\.json)$/.test(P))||!o&&t==="dependency-lock/profile-import.json")continue;if(!o)throw new Error(`The selected component has no original Profile source mapping: ${t}`);if(o=y(o),o!==f&&!(r.kind!=="instruction"&&w&&o.startsWith(w)))throw new Error("Candidate patch changes a different original Profile component.");if(H(o))throw new Error("Candidate patch crosses the protected Profile evaluation closure.");let u=g.get(o),d=m?.bytes??null;if(u&&(u.before!==(c?.asset.contentHash??null)||b(u.bytes===null?null:Array.from(u.bytes))!==b(d===null?null:Array.from(d))))throw new Error("Public component aliases disagree on the original source edit.");g.set(o,{before:p&&t===a?null:c?.asset.contentHash??null,bytes:d})}for(let[t,c]of g){let m=n.join(e.source,...t.split("/")),o=n.dirname(m);for(;!await s.stat(o).catch(()=>null);)o=n.dirname(o);let u=n.relative(await s.realpath(e.source),await s.realpath(o));if(u.startsWith("..")||n.isAbsolute(u))throw new Error("Candidate patch escapes the staged Profile source.");let d=await s.lstat(m).catch(()=>null);if(d?.isSymbolicLink()||d&&!d.isFile())throw new Error("Original source patch needs a regular file.");let P=d?await s.readFile(m):null;if((P?k(P):null)!==c.before)throw new Error("Original source bytes differ from the exact candidate baseline.");c.bytes===null?await s.rm(m):(await s.mkdir(n.dirname(m),{recursive:!0}),await s.writeFile(m,c.bytes,{mode:d?.mode??384}))}return[...g.keys()]}h(ve,"applyCandidateProfileSource");function Se(e){let i=e.base.manifest.metadata.profileRepositoryId;return R({storeDir:e.storeDir,workspaceId:e.state.ownerWorkspaceId,name:e.base.manifest.name,profile:e.profile,sourceRevision:e.sourceRevision,...typeof i=="string"?{repositoryId:i}:{}})}h(Se,"compileOriginalCandidateProfile");export{v as a,j as b,Pe as c,ye as d,ve as e,Se as f};
@@ -1,3 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{b as t}from"./chunk-ES2ISFJC.js";import{a as c}from"./chunk-FTQLQJQV.js";var O=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),v=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function E(n){let a=typeof n=="string"?new TextEncoder().encode(n):n,r=Math.ceil((a.byteLength+9)/64)*64,d=new Uint8Array(r);d.set(a),d[a.byteLength]=128;let b=a.byteLength*8,A=new DataView(d.buffer);A.setUint32(r-8,Math.floor(b/4294967296),!1),A.setUint32(r-4,b>>>0,!1);let e=new Uint32Array(O),f=new Uint32Array(64);for(let u=0;u<r;u+=64){for(let o=0;o<16;o+=1)f[o]=A.getUint32(u+o*4,!1);for(let o=16;o<64;o+=1){let g=f[o-15],S=f[o-2],T=i(g,7)^i(g,18)^g>>>3,w=i(S,17)^i(S,19)^S>>>10;f[o]=f[o-16]+T+f[o-7]+w>>>0}let s=e[0],p=e[1],h=e[2],_=e[3],x=e[4],y=e[5],R=e[6],H=e[7];for(let o=0;o<64;o+=1){let g=x&y^~x&R,S=s&p^s&h^p&h,T=i(s,2)^i(s,13)^i(s,22),w=i(x,6)^i(x,11)^i(x,25),j=H+w+g+v[o]+f[o]>>>0,L=T+S>>>0;H=R,R=y,y=x,x=_+j>>>0,_=h,h=p,p=s,s=j+L>>>0}e[0]=e[0]+s>>>0,e[1]=e[1]+p>>>0,e[2]=e[2]+h>>>0,e[3]=e[3]+_>>>0,e[4]=e[4]+x>>>0,e[5]=e[5]+y>>>0,e[6]=e[6]+R>>>0,e[7]=e[7]+H>>>0}return Array.from(e,u=>u.toString(16).padStart(8,"0")).join("")}c(E,"sha256Hex");function i(n,a){return n>>>a|n<<32-a}c(i,"rotateRight");var z=2e3,U=25e7,l=t.string().trim().min(1).max(240),m=t.string().regex(/^[a-f0-9]{64}$/),Y=t.string().datetime({offset:!0}),q=t.record(t.string(),t.unknown()).default({}),M=t.object({id:l,contentHash:m}).strict(),F=M.extend({revision:t.number().int().positive()}).strict(),W=t.object({id:l,path:t.string().trim().min(1).max(z).refine(N),contentHash:m,sizeBytes:t.number().int().nonnegative().max(U),mediaType:t.string().trim().min(1).max(200),visibility:t.enum(["policy","verifier","host_private"])}).strict(),G=t.object({id:l,contentHash:m,mediaType:t.string().trim().min(1).max(200).nullable().default(null),sizeBytes:t.number().int().nonnegative().max(U).nullable().default(null)}).strict(),K=t.enum(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function B(n){return`${JSON.stringify(I(n),null,2)}
3
- `}c(B,"canonicalJson");function C(n){return E(n)}c(C,"sha256");function P(n){return C(B(n))}c(P,"contentHash");function Q(n,a){let{contentHash:r,...d}=n,b=P(d);if(r!==b)throw new Error(`${a} contentHash is ${r}; expected ${b}.`)}c(Q,"assertContentHash");function N(n){let a=n.replaceAll("\\","/");return!a||a.startsWith("/")||a.includes("\0")?!1:!a.split("/").some(r=>!r||r==="."||r==="..")}c(N,"safeRelativePath");function I(n){return Array.isArray(n)?n.map(I):!n||typeof n!="object"?n:Object.fromEntries(Object.entries(n).sort(([a],[r])=>a.localeCompare(r)).map(([a,r])=>[a,I(r)]))}c(I,"sortValue");var ae=t.object({provider:l,model:l,revision:t.string().trim().min(1).max(500).nullable().default(null),artifactHash:m.nullable().default(null),tokenizerRevision:t.string().trim().min(1).max(500).nullable().default(null),chatTemplateHash:m.nullable().default(null)}).strict(),$=["openpond","codex","claude-code","grok-build","opencode","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],k=t.enum($),oe=t.object({providerId:k,modelId:t.string().trim().min(1).max(300)});export{l as a,m as b,Y as c,q as d,M as e,F as f,W as g,G as h,K as i,B as j,C as k,P as l,Q as m,ae as n,$ as o,k as p,oe as q};