openpond 0.2.51 → 0.2.53

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 (142) hide show
  1. package/dist/app-server.d.ts +1 -0
  2. package/dist/app-server.js +1 -1
  3. package/dist/chunks/{app-layer-RRFI27N4.js → app-layer-I7MZYVLL.js} +1 -1
  4. package/dist/chunks/{app-server-runtime-4YKIZB22.js → app-server-runtime-KZP2LB5X.js} +1 -1
  5. package/dist/chunks/{apps-NELJL377.js → apps-TM74FFQB.js} +1 -1
  6. package/dist/chunks/{chunk-OC6UWKBL.js → chunk-3LX6RU3C.js} +2 -2
  7. package/dist/chunks/{chunk-7YR6CBNU.js → chunk-4SHKI3BH.js} +1 -1
  8. package/dist/chunks/{chunk-7MXZJQS7.js → chunk-4TZHH5FC.js} +1 -1
  9. package/dist/chunks/{chunk-ZCWHVLJ4.js → chunk-5TNDPNS3.js} +1 -1
  10. package/dist/chunks/{chunk-42GOV5ZU.js → chunk-6JAN4RMN.js} +1 -1
  11. package/dist/chunks/{chunk-OE2VF6KU.js → chunk-6VF3Q6QJ.js} +1 -1
  12. package/dist/chunks/chunk-7ZG3IT7C.js +9 -0
  13. package/dist/chunks/{chunk-EPY7M5XS.js → chunk-AFUDIT36.js} +1 -1
  14. package/dist/chunks/{chunk-Q4H3NUVW.js → chunk-AH22RHPS.js} +2 -2
  15. package/dist/chunks/{chunk-DLZP22WV.js → chunk-FPUUZQUP.js} +1 -1
  16. package/dist/chunks/{chunk-O7VGFMDO.js → chunk-GCOUYYHG.js} +1 -1
  17. package/dist/chunks/{chunk-MASJQWA2.js → chunk-GXSTZBM6.js} +1 -1
  18. package/dist/chunks/{chunk-IOQUF34U.js → chunk-H2VT22JK.js} +1 -1
  19. package/dist/chunks/{chunk-TBNBCOW7.js → chunk-NHFGEVVH.js} +1 -1
  20. package/dist/chunks/{chunk-JCCU3VFK.js → chunk-PQHTZ5CP.js} +1 -1
  21. package/dist/chunks/{chunk-QJRXTIOC.js → chunk-USKE34VR.js} +1 -1
  22. package/dist/chunks/{chunk-2ZJJFBIA.js → chunk-USMZT5FZ.js} +12 -12
  23. package/dist/chunks/{chunk-KXEG7HCG.js → chunk-XGE2XI6M.js} +115 -114
  24. package/dist/chunks/{chunk-UBFRWC6I.js → chunk-YD55Z5H3.js} +1 -1
  25. package/dist/chunks/{chunk-RLZPX4YP.js → chunk-YJ4PNAST.js} +1 -1
  26. package/dist/chunks/{cli-ZLDLOKPL.js → cli-JVB345H2.js} +1 -1
  27. package/dist/chunks/{configuration-command-SA56RV5B.js → configuration-command-MATM4XR5.js} +1 -1
  28. package/dist/chunks/{connected-evidence-IVSQZYIB.js → connected-evidence-YDPGNHLP.js} +1 -1
  29. package/dist/chunks/{core-commands-W5IGIITV.js → core-commands-MTV4EKXY.js} +1 -1
  30. package/dist/chunks/{datasets-KSO2UG6R.js → datasets-CP3IT47T.js} +1 -1
  31. package/dist/chunks/{desktop-test-6HXFM7PO.js → desktop-test-IAZC5MAH.js} +1 -1
  32. package/dist/chunks/{dist-BLBZENVB.js → dist-SAABJU5F.js} +1 -1
  33. package/dist/chunks/{evaluation-coordination-MOFBXRXN.js → evaluation-coordination-EPHLZXYM.js} +1 -1
  34. package/dist/chunks/{experiment-improvements-TDHM6NEA.js → experiment-improvements-6JTOPA74.js} +1 -1
  35. package/dist/chunks/{experiments-HFPDFD4I.js → experiments-XHPFGECH.js} +1 -1
  36. package/dist/chunks/{extension-R373LYIB.js → extension-GX7DLW2X.js} +1 -1
  37. package/dist/chunks/{help-PEFQDDTA.js → help-WLKSACLZ.js} +1 -1
  38. package/dist/chunks/{hosted-experiment-improvement-NTYYSPQX.js → hosted-experiment-improvement-HAB3UE6A.js} +1 -1
  39. package/dist/chunks/{hosted-harness-runtime-FZZLWLBR.js → hosted-harness-runtime-YM23QNDK.js} +1 -1
  40. package/dist/chunks/{hosted-profile-candidate-LVNKOTKJ.js → hosted-profile-candidate-EOBGKQAS.js} +1 -1
  41. package/dist/chunks/{hosted-profile-compiler-JODGZCA7.js → hosted-profile-compiler-OZAOZ2ES.js} +1 -1
  42. package/dist/chunks/{hosted-profile-evaluation-control-7B3RAZU2.js → hosted-profile-evaluation-control-RJ6XJZCS.js} +1 -1
  43. package/dist/chunks/{hosted-profile-evaluation-inspection-FPCV42DD.js → hosted-profile-evaluation-inspection-SJIDXPHI.js} +1 -1
  44. package/dist/chunks/{hosted-profile-evaluation-preparation-F2SPAEKK.js → hosted-profile-evaluation-preparation-26EI5LJR.js} +1 -1
  45. package/dist/chunks/{human-review-HRGGACEM.js → human-review-AAVMISBF.js} +1 -1
  46. package/dist/chunks/{import-RSAQ44GG.js → import-V3HUGRHR.js} +1 -1
  47. package/dist/chunks/{opchat-I7ZWJ5XK.js → opchat-QK43DXTY.js} +1 -1
  48. package/dist/chunks/{organizations-LFCZIH7E.js → organizations-SRPAWKC7.js} +1 -1
  49. package/dist/chunks/{profile-EPIX5QVK.js → profile-C6CQNVYE.js} +1 -1
  50. package/dist/chunks/{project-agent-DGOPMECP.js → project-agent-GZV5HNYI.js} +1 -1
  51. package/dist/chunks/{sandbox-command-Q5F6VUOS.js → sandbox-command-4TJXQTKT.js} +1 -1
  52. package/dist/chunks/{sandbox-template-7GICPIKJ.js → sandbox-template-BBGGPJMI.js} +1 -1
  53. package/dist/chunks/{src-DH5AQ4Z7.js → src-CR6UZYTX.js} +1 -1
  54. package/dist/chunks/src-P3VYLFLI.js +329 -0
  55. package/dist/chunks/{teams-bot-Z6RJGHME.js → teams-bot-7I4BAUVO.js} +1 -1
  56. package/dist/chunks/{workspaces-XIQNPAP7.js → workspaces-MFZ3OO6O.js} +1 -1
  57. package/dist/cli.js +1 -1
  58. package/dist/web/assets/App-CO2F717V.css +1 -0
  59. package/dist/web/assets/App-CuhaCsfb.js +235 -0
  60. package/dist/web/assets/{AppDialog-1iGodoot.js → AppDialog-BdusXgU0.js} +1 -1
  61. package/dist/web/assets/{AppTerminalPanel-udtBdWFn.js → AppTerminalPanel-C4uRpnBz.js} +2 -2
  62. package/dist/web/assets/{AppsView-DhKsU4yi.js → AppsView-BS1czXUP.js} +1 -1
  63. package/dist/web/assets/{BrowserSidebar-BnOyqIQT.js → BrowserSidebar-Bl7V6YO2.js} +1 -1
  64. package/dist/web/assets/{CartesianChart-C24DAywn.js → CartesianChart-BstFbsdn.js} +1 -1
  65. package/dist/web/assets/{CollaborationTabs-DgmOF5Fe.js → CollaborationTabs-B8YAf0c1.js} +1 -1
  66. package/dist/web/assets/{CommandMenu-CUNGtHwS.js → CommandMenu-DZct7zUJ.js} +1 -1
  67. package/dist/web/assets/{CommunityView-CE7qeJnr.js → CommunityView-CR0-W-uG.js} +1 -1
  68. package/dist/web/assets/{ComposerCreateImproveStrip-BixNsg2a.js → ComposerCreateImproveStrip-DR-Qo7b4.js} +1 -1
  69. package/dist/web/assets/{GetStartedView-B8gCwmBX.js → GetStartedView-xqQoMMei.js} +1 -1
  70. package/dist/web/assets/HostedModelLearningReview-CHxxf_Lu.js +1 -0
  71. package/dist/web/assets/{HostedModelLearningSettings-WUaqzNsa.js → HostedModelLearningSettings-De3i9wF4.js} +1 -1
  72. package/dist/web/assets/{LabModelVersionDetailPage-Cx0kL69J.js → LabModelVersionDetailPage-DAY1MmqP.js} +1 -1
  73. package/dist/web/assets/{LabSkillSidebar-DRggqZ1j.js → LabSkillSidebar-DLnIgnry.js} +1 -1
  74. package/dist/web/assets/{LabsRoute-BujTZhqC.js → LabsRoute-CXJRJMhr.js} +4 -4
  75. package/dist/web/assets/{MainChatThread-CyA_644R.js → MainChatThread-BwAla81W.js} +2 -2
  76. package/dist/web/assets/MainPane-CakOBCHw.js +19 -0
  77. package/dist/web/assets/{MarkdownText-DJI5LwT0.js → MarkdownText-gJMuefaJ.js} +21 -21
  78. package/dist/web/assets/{NativeSkillSidebar-CkFpWxjd.js → NativeSkillSidebar-Dlxb8iOC.js} +1 -1
  79. package/dist/web/assets/{NewExperienceSwitcher-DXcRHHsu.js → NewExperienceSwitcher-DM-cqJ-K.js} +1 -1
  80. package/dist/web/assets/{NewProjectDialog-gDzX_ZIJ.js → NewProjectDialog-Cu1q75gq.js} +1 -1
  81. package/dist/web/assets/{OutputsPage-J_k-_N82.js → OutputsPage-DiXMkasl.js} +1 -1
  82. package/dist/web/assets/{ProjectsPage-BsyZmvlg.js → ProjectsPage-DqiBHiCB.js} +1 -1
  83. package/dist/web/assets/{RightChatPanelStack-Bz8puMUB.js → RightChatPanelStack-VaOOmxwd.js} +1 -1
  84. package/dist/web/assets/{RightSidebarHomePanel-DmorYb6p.js → RightSidebarHomePanel-CeSFJM5s.js} +1 -1
  85. package/dist/web/assets/{ScheduledWorkPage-BFDzQUyL.js → ScheduledWorkPage-D1jRQxFs.js} +1 -1
  86. package/dist/web/assets/{SettingsView-BB7wCdbr.js → SettingsView-RA9OXgcu.js} +3 -3
  87. package/dist/web/assets/{TeamChatView-CZ3b7rq2.js → TeamChatView-DM0adMtj.js} +1 -1
  88. package/dist/web/assets/{TerminalOverlay-Ck43Qri3.js → TerminalOverlay-CFlH51DD.js} +1 -1
  89. package/dist/web/assets/{TrainingCreationPanel-ejqPZm3g.js → TrainingCreationPanel-CgIBVGha.js} +1 -1
  90. package/dist/web/assets/{TrainingDraftPanel-Cy2AQxxL.js → TrainingDraftPanel-Bbo3RRie.js} +1 -1
  91. package/dist/web/assets/{UsageSettingsSection-B7nyMItm.js → UsageSettingsSection-CSRjJUSa.js} +1 -1
  92. package/dist/web/assets/{WorkSidebarPanel-BfjAc097.js → WorkSidebarPanel-DwlEMEoG.js} +1 -1
  93. package/dist/web/assets/WorkspaceDiffPanel-pGVezNMw.js +14 -0
  94. package/dist/web/assets/{WorkspaceEnvironmentMenu-B-K9XgFB.js → WorkspaceEnvironmentMenu-Byjngd9V.js} +1 -1
  95. package/dist/web/assets/{WorkspaceGitDialogs-BJVFx_L3.js → WorkspaceGitDialogs-Dgmg-6XG.js} +1 -1
  96. package/dist/web/assets/{WorkspaceMonacoEditor-p-FWMXoZ.js → WorkspaceMonacoEditor-BR4qxMgU.js} +3 -3
  97. package/dist/web/assets/{arrow-up-right-CFGI2YSt.js → arrow-up-right-H0pvnH2s.js} +1 -1
  98. package/dist/web/assets/{chunk-UHVJOMWN-BAlur2vw.js → chunk-UHVJOMWN-BqXRe639.js} +1 -1
  99. package/dist/web/assets/{clipboard-DIIxBort.js → clipboard-BZzZ82Bk.js} +1 -1
  100. package/dist/web/assets/{cloud-upload-BaQFNCTp.js → cloud-upload-CJPYPVl8.js} +1 -1
  101. package/dist/web/assets/{cssMode-6LOkSggB.js → cssMode-WC4Rg1l-.js} +1 -1
  102. package/dist/web/assets/{folder-open-DZSxfPtr.js → folder-open-sLZJxLQy.js} +1 -1
  103. package/dist/web/assets/{folder-plus-21v4D_Vx.js → folder-plus-C84wrpt_.js} +1 -1
  104. package/dist/web/assets/{git-commit-horizontal-CgGixL64.js → git-commit-horizontal-Cotm7KEC.js} +1 -1
  105. package/dist/web/assets/{htmlMode-B5uRraNd.js → htmlMode-C6oZGeaB.js} +1 -1
  106. package/dist/web/assets/{index-DOMrqhcz.js → index-BxWTVKtn.js} +2 -2
  107. package/dist/web/assets/index-dSmk3FLJ.css +1 -0
  108. package/dist/web/assets/{info-BGTcmow7.js → info-Dc81lEfw.js} +1 -1
  109. package/dist/web/assets/{jsonMode-D3m8N4Gi.js → jsonMode-BET4LQIn.js} +1 -1
  110. package/dist/web/assets/{lspLanguageFeatures-DoyipLsB.js → lspLanguageFeatures-BPxA_-Kg.js} +1 -1
  111. package/dist/web/assets/{minimize-2-B01qSko4.js → minimize-2-Bs7MVN3C.js} +1 -1
  112. package/dist/web/assets/{monaco.contribution-Bc22foTx.js → monaco.contribution-7AUuf2NS.js} +2 -2
  113. package/dist/web/assets/{monaco.contribution-BJyfaGX2.js → monaco.contribution-BH6kkO4b.js} +2 -2
  114. package/dist/web/assets/{monaco.contribution-DuRhJ6zU.js → monaco.contribution-DFzEyaHi.js} +2 -2
  115. package/dist/web/assets/{monaco.contribution--U8v3jpa.js → monaco.contribution-DXzyQfVi.js} +2 -2
  116. package/dist/web/assets/{monitor-eZP8ZTHe.js → monitor-DXL019Wf.js} +1 -1
  117. package/dist/web/assets/{play-CGsWFR_B.js → play-CXkxUZeU.js} +1 -1
  118. package/dist/web/assets/{python-BNrLZWud.js → python-PzBkTjWx.js} +1 -1
  119. package/dist/web/assets/{save-BLgjrccP.js → save-DpezrtH2.js} +1 -1
  120. package/dist/web/assets/{square-CI1qNtvE.js → square-oy7f5Ce6.js} +1 -1
  121. package/dist/web/assets/{toggleHighContrast-B_GcTCnw.js → toggleHighContrast-Cto-fOXm.js} +1 -1
  122. package/dist/web/assets/{tsMode-CmruH_ys.js → tsMode-BYA4LNc6.js} +1 -1
  123. package/dist/web/assets/{upload-DnlgGS2x.js → upload-C5YFNgtS.js} +1 -1
  124. package/dist/web/assets/{useLocalAgentSchedules-BBhGUfK-.js → useLocalAgentSchedules-CnyTsqlf.js} +1 -1
  125. package/dist/web/assets/useProviderSettings-B_KeQjE5.js +5 -0
  126. package/dist/web/assets/{useSessionTurnCache-BwscKl5i.js → useSessionTurnCache-DICuJSJW.js} +1 -1
  127. package/dist/web/assets/{wifi-off-Dz-4EDCc.js → wifi-off-nzHj7JXp.js} +1 -1
  128. package/dist/web/assets/{workers-Bi9u46cp.js → workers-Dboaw6f_.js} +1 -1
  129. package/dist/web/assets/{yaml-DVTkiRnh.js → yaml-uuY5JmO8.js} +1 -1
  130. package/dist/web/index.html +2 -2
  131. package/package.json +1 -1
  132. package/dist/chunks/chunk-7K72KS5C.js +0 -9
  133. package/dist/chunks/src-STK4YHBI.js +0 -329
  134. package/dist/web/assets/App-BI-uOpnP.js +0 -234
  135. package/dist/web/assets/App-DkH8CeoI.css +0 -1
  136. package/dist/web/assets/HostedModelLearningReview-CitgUNfC.js +0 -1
  137. package/dist/web/assets/MainPane-LaEtxydD.js +0 -19
  138. package/dist/web/assets/WorkspaceDiffPanel-D9hAV8l7.js +0 -14
  139. package/dist/web/assets/index-DJcUXSsN.css +0 -1
  140. package/dist/web/assets/useProviderSettings-DfhdkKdC.js +0 -5
  141. /package/dist/chunks/{chunk-XDMUD4FW.js → chunk-2JO2KWT3.js} +0 -0
  142. /package/dist/chunks/{chunk-XBCIBAXD.js → chunk-GS2NKNKG.js} +0 -0
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{b as a,c as b}from"./chunk-O7VGFMDO.js";import"./chunk-QJRXTIOC.js";import"./chunk-7K72KS5C.js";import"./chunk-7MXZJQS7.js";import"./chunk-7YR6CBNU.js";import"./chunk-5CMKGD43.js";import"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import"./chunk-XDMUD4FW.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as loadHostedHarnessRuntime,b as loadHostedHarnessRuntimeForSession};
2
+ import{b as a,c as b}from"./chunk-GCOUYYHG.js";import"./chunk-USKE34VR.js";import"./chunk-7ZG3IT7C.js";import"./chunk-4TZHH5FC.js";import"./chunk-4SHKI3BH.js";import"./chunk-5CMKGD43.js";import"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import"./chunk-2JO2KWT3.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as loadHostedHarnessRuntime,b as loadHostedHarnessRuntimeForSession};
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a,e as F}from"./chunk-IOQUF34U.js";import{a as O}from"./chunk-EMKZVP7Z.js";import{a as h}from"./chunk-T5LE6R5S.js";import{na as I,qa as D,ra as M}from"./chunk-7MXZJQS7.js";import"./chunk-7YR6CBNU.js";import"./chunk-5CMKGD43.js";import{N as w}from"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import{od as A}from"./chunk-XDMUD4FW.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import{ua as R}from"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import{k as C,l as v}from"./chunk-NNF6KCHD.js";import{b as c}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as f}from"./chunk-FTQLQJQV.js";import{promises as m}from"node:fs";import n from"node:path";var $=c.object({action:c.enum(["stage","readback","rollback"]),repoPath:c.string(),outputDir:c.string(),exportFile:c.string(),commit:c.string().regex(/^[a-f0-9]{40}$/).optional(),expectedExecutableSourceHash:c.string().regex(/^[a-f0-9]{64}$/).optional()}).strict();async function z(l){let e=$.parse(l);if(!n.isAbsolute(e.repoPath)||!n.isAbsolute(e.outputDir)||!/^[a-zA-Z0-9_-]+\.json$/.test(e.exportFile))throw new Error("Hosted candidate private IPC is not contained.");let g=n.join(e.outputDir,e.exportFile),H=await m.lstat(g);if(!H.isFile()||H.isSymbolicLink()||H.size>8*1024*1024)throw new Error("Hosted candidate export exceeds its private IPC bound.");let t=O(JSON.parse(await m.readFile(g,"utf8"))),u=await w({repoPath:e.repoPath,profileId:t.profileRef.profileId});if(u.error||!u.sourcePath)throw new Error("Actual hosted Profile source is unavailable.");if(e.action!=="readback"){let o=!1;try{await a(e.repoPath,["symbolic-ref","-q","HEAD"]),o=!0}catch{}if(o||await a(e.repoPath,["rev-parse","HEAD"])!==(e.action==="rollback"?e.commit:t.expectedCommit)||await a(e.repoPath,["status","--porcelain","--untracked-files=all"]))throw new Error("Candidate staging requires a clean detached exact original source worktree.")}let x=f(async o=>I({storeDir:e.outputDir,workspaceId:t.compiler.workspaceId,name:t.compiler.name,profile:await w({repoPath:e.repoPath,profileId:t.profileRef.profileId}),sourceRevision:o,repositoryId:t.compiler.repositoryId}),"compile");if(e.action==="readback"){if(!e.commit||await a(e.repoPath,["rev-parse","HEAD"])!==e.commit)throw new Error("Hosted Profile readback is not the committed source.");let o=await x(e.commit),i=h(o);if(i.profileGitHead!==e.commit||i.contentHash!==(e.expectedExecutableSourceHash??t.executableSourceHash)||i.protectedClosureHash!==t.protectedClosureHash)throw new Error("Hosted active executable differs from the actual tested candidate.");let s=await M({storeDir:e.outputDir,workspaceId:t.compiler.workspaceId,compiled:o,createdAt:t.createdAt});return{commit:e.commit,activeRelease:{id:s.harnessRelease.id,contentHash:s.harnessRelease.contentHash},executableSourceHash:i.contentHash,protectedClosureHash:i.protectedClosureHash}}if(e.action==="rollback"){if(!e.commit)throw new Error("Rollback requires the exact accepted commit.");await a(e.repoPath,["-c","core.hooksPath=/dev/null","revert","--no-commit",e.commit])}let p=await x(t.expectedCommit);if(p.harnessRelease.contentHash!==t.baseRelease.contentHash||p.harnessRelease.id!==t.baseRelease.id)throw new Error("Hosted original source differs from the owner-attested baseline release.");if(e.action==="stage"){let o=Buffer.from(t.sourceManifest.base64,"base64");if(o.toString("base64")!==t.sourceManifest.base64||o.length!==t.sourceManifest.sizeBytes||v(o)!==t.sourceManifest.contentHash)throw new Error("Candidate source manifest byte identity differs.");let i=A.parse(JSON.parse(o.toString("utf8"))),s=n.join(e.outputDir,"candidate-source");await m.mkdir(s,{recursive:!0}),await m.writeFile(n.join(s,"harness.json"),C(i));let _=R(t.policySource),j=new Map(p.sourceFiles.filter(r=>r.asset.visibility!=="policy").map(r=>[r.path,r]));for(let r of i.files){let k=r.visibility==="policy"?_.get(r.path):j.get(r.path)?.bytes;if(!k)throw new Error("The hosted source cannot hydrate the exact protected candidate closure.");let y=n.join(s,r.path);if(n.relative(s,y).startsWith(".."))throw new Error("Candidate release path escapes private staging.");await m.mkdir(n.dirname(y),{recursive:!0}),await m.writeFile(y,k)}let P=await D({workspaceId:t.compiler.workspaceId,sourceDir:s}),S=h(P);if(P.harnessRelease.contentHash!==t.policySource.harnessRelease.contentHash||S.contentHash!==t.executableSourceHash||S.protectedClosureHash!==t.protectedClosureHash)throw new Error("Owner-attested candidate differs from independently compiled hosted source.");await F({source:u.sourcePath,state:{component:t.component},base:p,candidate:P,profile:u})}await a(e.repoPath,["add","--all"]),await a(e.repoPath,["-c","core.hooksPath=/dev/null","-c","commit.gpgSign=false","commit","-m",`${e.action==="rollback"?"Roll back":"Adopt"} owner-tested candidate ${t.candidateId}`],{GIT_AUTHOR_NAME:"OpenPond",GIT_AUTHOR_EMAIL:"profile-candidate@openpond.local",GIT_COMMITTER_NAME:"OpenPond",GIT_COMMITTER_EMAIL:"profile-candidate@openpond.local"});let E=await a(e.repoPath,["rev-parse","HEAD"]),T=await w({repoPath:e.repoPath,profileId:t.profileRef.profileId}),b=await I({storeDir:e.outputDir,workspaceId:t.compiler.workspaceId,name:t.compiler.name,profile:T,sourceRevision:E,repositoryId:t.compiler.repositoryId}),d=h(b);if(e.action==="stage"&&(d.contentHash!==t.executableSourceHash||d.protectedClosureHash!==t.protectedClosureHash)||e.action==="rollback"&&(d.contentHash!==h(p).contentHash||d.protectedClosureHash!==h(p).protectedClosureHash))throw new Error("Staged actual source differs from its exact tested executable graph.");return{commit:E,activeRelease:{id:b.harnessRelease.id,contentHash:b.harnessRelease.contentHash},executableSourceHash:d.contentHash,protectedClosureHash:d.protectedClosureHash}}f(z,"hostedProfileCandidate");async function Q(l){if(l.length!==1||l[0].length>16e3||!/^[a-zA-Z0-9_-]+$/.test(l[0]))throw new Error("Hosted candidate IPC argument is invalid.");process.stdout.write(`${JSON.stringify(await z(JSON.parse(Buffer.from(l[0],"base64url").toString("utf8"))))}
2
+ import{a,e as F}from"./chunk-H2VT22JK.js";import{a as O}from"./chunk-EMKZVP7Z.js";import{a as h}from"./chunk-T5LE6R5S.js";import{na as I,qa as D,ra as M}from"./chunk-4TZHH5FC.js";import"./chunk-4SHKI3BH.js";import"./chunk-5CMKGD43.js";import{N as w}from"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import{od as A}from"./chunk-2JO2KWT3.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import{ua as R}from"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import{k as C,l as v}from"./chunk-NNF6KCHD.js";import{b as c}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as f}from"./chunk-FTQLQJQV.js";import{promises as m}from"node:fs";import n from"node:path";var $=c.object({action:c.enum(["stage","readback","rollback"]),repoPath:c.string(),outputDir:c.string(),exportFile:c.string(),commit:c.string().regex(/^[a-f0-9]{40}$/).optional(),expectedExecutableSourceHash:c.string().regex(/^[a-f0-9]{64}$/).optional()}).strict();async function z(l){let e=$.parse(l);if(!n.isAbsolute(e.repoPath)||!n.isAbsolute(e.outputDir)||!/^[a-zA-Z0-9_-]+\.json$/.test(e.exportFile))throw new Error("Hosted candidate private IPC is not contained.");let g=n.join(e.outputDir,e.exportFile),H=await m.lstat(g);if(!H.isFile()||H.isSymbolicLink()||H.size>8*1024*1024)throw new Error("Hosted candidate export exceeds its private IPC bound.");let t=O(JSON.parse(await m.readFile(g,"utf8"))),u=await w({repoPath:e.repoPath,profileId:t.profileRef.profileId});if(u.error||!u.sourcePath)throw new Error("Actual hosted Profile source is unavailable.");if(e.action!=="readback"){let o=!1;try{await a(e.repoPath,["symbolic-ref","-q","HEAD"]),o=!0}catch{}if(o||await a(e.repoPath,["rev-parse","HEAD"])!==(e.action==="rollback"?e.commit:t.expectedCommit)||await a(e.repoPath,["status","--porcelain","--untracked-files=all"]))throw new Error("Candidate staging requires a clean detached exact original source worktree.")}let x=f(async o=>I({storeDir:e.outputDir,workspaceId:t.compiler.workspaceId,name:t.compiler.name,profile:await w({repoPath:e.repoPath,profileId:t.profileRef.profileId}),sourceRevision:o,repositoryId:t.compiler.repositoryId}),"compile");if(e.action==="readback"){if(!e.commit||await a(e.repoPath,["rev-parse","HEAD"])!==e.commit)throw new Error("Hosted Profile readback is not the committed source.");let o=await x(e.commit),i=h(o);if(i.profileGitHead!==e.commit||i.contentHash!==(e.expectedExecutableSourceHash??t.executableSourceHash)||i.protectedClosureHash!==t.protectedClosureHash)throw new Error("Hosted active executable differs from the actual tested candidate.");let s=await M({storeDir:e.outputDir,workspaceId:t.compiler.workspaceId,compiled:o,createdAt:t.createdAt});return{commit:e.commit,activeRelease:{id:s.harnessRelease.id,contentHash:s.harnessRelease.contentHash},executableSourceHash:i.contentHash,protectedClosureHash:i.protectedClosureHash}}if(e.action==="rollback"){if(!e.commit)throw new Error("Rollback requires the exact accepted commit.");await a(e.repoPath,["-c","core.hooksPath=/dev/null","revert","--no-commit",e.commit])}let p=await x(t.expectedCommit);if(p.harnessRelease.contentHash!==t.baseRelease.contentHash||p.harnessRelease.id!==t.baseRelease.id)throw new Error("Hosted original source differs from the owner-attested baseline release.");if(e.action==="stage"){let o=Buffer.from(t.sourceManifest.base64,"base64");if(o.toString("base64")!==t.sourceManifest.base64||o.length!==t.sourceManifest.sizeBytes||v(o)!==t.sourceManifest.contentHash)throw new Error("Candidate source manifest byte identity differs.");let i=A.parse(JSON.parse(o.toString("utf8"))),s=n.join(e.outputDir,"candidate-source");await m.mkdir(s,{recursive:!0}),await m.writeFile(n.join(s,"harness.json"),C(i));let _=R(t.policySource),j=new Map(p.sourceFiles.filter(r=>r.asset.visibility!=="policy").map(r=>[r.path,r]));for(let r of i.files){let k=r.visibility==="policy"?_.get(r.path):j.get(r.path)?.bytes;if(!k)throw new Error("The hosted source cannot hydrate the exact protected candidate closure.");let y=n.join(s,r.path);if(n.relative(s,y).startsWith(".."))throw new Error("Candidate release path escapes private staging.");await m.mkdir(n.dirname(y),{recursive:!0}),await m.writeFile(y,k)}let P=await D({workspaceId:t.compiler.workspaceId,sourceDir:s}),S=h(P);if(P.harnessRelease.contentHash!==t.policySource.harnessRelease.contentHash||S.contentHash!==t.executableSourceHash||S.protectedClosureHash!==t.protectedClosureHash)throw new Error("Owner-attested candidate differs from independently compiled hosted source.");await F({source:u.sourcePath,state:{component:t.component},base:p,candidate:P,profile:u})}await a(e.repoPath,["add","--all"]),await a(e.repoPath,["-c","core.hooksPath=/dev/null","-c","commit.gpgSign=false","commit","-m",`${e.action==="rollback"?"Roll back":"Adopt"} owner-tested candidate ${t.candidateId}`],{GIT_AUTHOR_NAME:"OpenPond",GIT_AUTHOR_EMAIL:"profile-candidate@openpond.local",GIT_COMMITTER_NAME:"OpenPond",GIT_COMMITTER_EMAIL:"profile-candidate@openpond.local"});let E=await a(e.repoPath,["rev-parse","HEAD"]),T=await w({repoPath:e.repoPath,profileId:t.profileRef.profileId}),b=await I({storeDir:e.outputDir,workspaceId:t.compiler.workspaceId,name:t.compiler.name,profile:T,sourceRevision:E,repositoryId:t.compiler.repositoryId}),d=h(b);if(e.action==="stage"&&(d.contentHash!==t.executableSourceHash||d.protectedClosureHash!==t.protectedClosureHash)||e.action==="rollback"&&(d.contentHash!==h(p).contentHash||d.protectedClosureHash!==h(p).protectedClosureHash))throw new Error("Staged actual source differs from its exact tested executable graph.");return{commit:E,activeRelease:{id:b.harnessRelease.id,contentHash:b.harnessRelease.contentHash},executableSourceHash:d.contentHash,protectedClosureHash:d.protectedClosureHash}}f(z,"hostedProfileCandidate");async function Q(l){if(l.length!==1||l[0].length>16e3||!/^[a-zA-Z0-9_-]+$/.test(l[0]))throw new Error("Hosted candidate IPC argument is invalid.");process.stdout.write(`${JSON.stringify(await z(JSON.parse(Buffer.from(l[0],"base64url").toString("utf8"))))}
3
3
  `)}f(Q,"runHostedProfileCandidateCli");export{z as hostedProfileCandidate,Q as runHostedProfileCandidateCli};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a,b,c,d}from"./chunk-OC6UWKBL.js";import"./chunk-7MXZJQS7.js";import"./chunk-7YR6CBNU.js";import"./chunk-5CMKGD43.js";import"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import"./chunk-XDMUD4FW.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as compileHostedProfileRelease,b as runHostedProfileCompilerCli,c as runHostedProfileEvaluationCli,d as runHostedProfileInspectionCli};
2
+ import{a,b,c,d}from"./chunk-3LX6RU3C.js";import"./chunk-4TZHH5FC.js";import"./chunk-4SHKI3BH.js";import"./chunk-5CMKGD43.js";import"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import"./chunk-2JO2KWT3.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as compileHostedProfileRelease,b as runHostedProfileCompilerCli,c as runHostedProfileEvaluationCli,d as runHostedProfileInspectionCli};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as m,b as c}from"./chunk-XM26DGML.js";import{a as l}from"./chunk-7YR6CBNU.js";import{L as f}from"./chunk-XDMUD4FW.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import{ja as s,oa as u}from"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-TGIB24K4.js";import{n as t}from"./chunk-NNF6KCHD.js";import{b as n}from"./chunk-ES2ISFJC.js";import{a as i}from"./chunk-FTQLQJQV.js";var v=n.object({profileRef:f,sourceRevision:n.string().min(1),action:n.enum(["compare","report"]),request:n.unknown(),runs:n.array(l).max(1e4),comparisons:n.array(s).max(1e4),suiteRuns:n.array(u).max(1e4)}).strict();async function h(p){let o=v.parse(p);for(let e of[...o.runs,...o.comparisons,...o.suiteRuns])t(e,"Hosted evaluation evidence");let a={getProfileEvaluationRun:i(async e=>o.runs.find(r=>r.manifest.id===e)??null,"getProfileEvaluationRun"),getProfileEvaluationComparison:i(async e=>o.comparisons.find(r=>r.id===e)??null,"getProfileEvaluationComparison"),getProfileEvaluationSuiteRun:i(async e=>o.suiteRuns.find(r=>r.id===e)??null,"getProfileEvaluationSuiteRun"),saveProfileEvaluationComparison:i(async(e,r)=>r,"saveProfileEvaluationComparison")};return o.action==="compare"?m({store:a,selectedProfile:i(async()=>({ref:o.profileRef,sourceRevision:o.sourceRevision}),"selectedProfile")})(o.request):c({store:a,profileRef:o.profileRef,request:o.request})}i(h,"controlHostedProfileEvaluation");export{h as controlHostedProfileEvaluation};
2
+ import{a as m,b as c}from"./chunk-XM26DGML.js";import{a as l}from"./chunk-4SHKI3BH.js";import{L as f}from"./chunk-2JO2KWT3.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import{ja as s,oa as u}from"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-TGIB24K4.js";import{n as t}from"./chunk-NNF6KCHD.js";import{b as n}from"./chunk-ES2ISFJC.js";import{a as i}from"./chunk-FTQLQJQV.js";var v=n.object({profileRef:f,sourceRevision:n.string().min(1),action:n.enum(["compare","report"]),request:n.unknown(),runs:n.array(l).max(1e4),comparisons:n.array(s).max(1e4),suiteRuns:n.array(u).max(1e4)}).strict();async function h(p){let o=v.parse(p);for(let e of[...o.runs,...o.comparisons,...o.suiteRuns])t(e,"Hosted evaluation evidence");let a={getProfileEvaluationRun:i(async e=>o.runs.find(r=>r.manifest.id===e)??null,"getProfileEvaluationRun"),getProfileEvaluationComparison:i(async e=>o.comparisons.find(r=>r.id===e)??null,"getProfileEvaluationComparison"),getProfileEvaluationSuiteRun:i(async e=>o.suiteRuns.find(r=>r.id===e)??null,"getProfileEvaluationSuiteRun"),saveProfileEvaluationComparison:i(async(e,r)=>r,"saveProfileEvaluationComparison")};return o.action==="compare"?m({store:a,selectedProfile:i(async()=>({ref:o.profileRef,sourceRevision:o.sourceRevision}),"selectedProfile")})(o.request):c({store:a,profileRef:o.profileRef,request:o.request})}i(h,"controlHostedProfileEvaluation");export{h as controlHostedProfileEvaluation};
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{c as R,d as P}from"./chunk-EPY7M5XS.js";import{a as E}from"./chunk-7YR6CBNU.js";import{L as v,M as S,N as w,Y as y,a as h}from"./chunk-XDMUD4FW.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import{k as g}from"./chunk-WV2APYWG.js";import{h as m}from"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import{b as s}from"./chunk-ES2ISFJC.js";import{a as n}from"./chunk-FTQLQJQV.js";var I=s.object({profileRef:v,inspection:R,run:E.nullable(),receipts:s.array(g).max(1e4),grades:s.array(m).max(1e4),sessions:s.array(S).max(1e4),turns:s.array(w).max(1e4),events:s.array(h).max(1e4),usage:s.array(y).max(1e4)}).strict();async function x(c){let t=I.parse(c),o=n((e,i)=>{let f=new Map;for(let p of e){let d=i(p);if(f.has(d))throw new Error("Hosted evaluation inspection has duplicate evidence identities.");f.set(d,p)}return f},"map"),r=o(t.receipts,e=>e.id),u=o(t.grades,e=>e.contentHash),l=o(t.sessions,e=>e.id),a=o(t.turns,e=>e.id);return P({profileRef:t.profileRef,...t.inspection,store:{getProfileEvaluationRun:n(async e=>t.run?.manifest.id===e?t.run:null,"getProfileEvaluationRun"),getProfileEvaluationReceipt:n(async e=>r.get(e)??null,"getProfileEvaluationReceipt"),getProfileEvaluationGrade:n(async e=>u.get(e)??null,"getProfileEvaluationGrade"),getSession:n(async e=>l.get(e)??null,"getSession"),getTurn:n(async e=>a.get(e)??null,"getTurn"),runtimeEventsForTurn:n(async e=>t.events.filter(i=>i.turnId===e),"runtimeEventsForTurn"),listModelUsageRecords:n(async e=>t.usage.filter(i=>(!e?.sessionId||i.sessionId===e.sessionId)&&(!e?.turnId||i.turnId===e.turnId)),"listModelUsageRecords")}})}n(x,"inspectHostedProfileEvaluation");async function B(c){if(c.length!==0)throw new Error("Hosted evaluation inspection uses bounded standard input.");let t=[],o=0;for await(let l of process.stdin){let a=Buffer.from(l);if(o+=a.length,o>32*1024*1024)throw new Error("Hosted evaluation inspection input is too large.");t.push(a)}let r=JSON.parse(Buffer.concat(t).toString("utf8")),u=r.action==="compare"||r.action==="report"?await(await import("./hosted-profile-evaluation-control-7B3RAZU2.js")).controlHostedProfileEvaluation(r):await x(r);process.stdout.write(`${JSON.stringify(u)}
2
+ import{c as R,d as P}from"./chunk-AFUDIT36.js";import{a as E}from"./chunk-4SHKI3BH.js";import{L as v,M as S,N as w,Y as y,a as h}from"./chunk-2JO2KWT3.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import{k as g}from"./chunk-WV2APYWG.js";import{h as m}from"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import{b as s}from"./chunk-ES2ISFJC.js";import{a as n}from"./chunk-FTQLQJQV.js";var I=s.object({profileRef:v,inspection:R,run:E.nullable(),receipts:s.array(g).max(1e4),grades:s.array(m).max(1e4),sessions:s.array(S).max(1e4),turns:s.array(w).max(1e4),events:s.array(h).max(1e4),usage:s.array(y).max(1e4)}).strict();async function x(c){let t=I.parse(c),o=n((e,i)=>{let f=new Map;for(let p of e){let d=i(p);if(f.has(d))throw new Error("Hosted evaluation inspection has duplicate evidence identities.");f.set(d,p)}return f},"map"),r=o(t.receipts,e=>e.id),u=o(t.grades,e=>e.contentHash),l=o(t.sessions,e=>e.id),a=o(t.turns,e=>e.id);return P({profileRef:t.profileRef,...t.inspection,store:{getProfileEvaluationRun:n(async e=>t.run?.manifest.id===e?t.run:null,"getProfileEvaluationRun"),getProfileEvaluationReceipt:n(async e=>r.get(e)??null,"getProfileEvaluationReceipt"),getProfileEvaluationGrade:n(async e=>u.get(e)??null,"getProfileEvaluationGrade"),getSession:n(async e=>l.get(e)??null,"getSession"),getTurn:n(async e=>a.get(e)??null,"getTurn"),runtimeEventsForTurn:n(async e=>t.events.filter(i=>i.turnId===e),"runtimeEventsForTurn"),listModelUsageRecords:n(async e=>t.usage.filter(i=>(!e?.sessionId||i.sessionId===e.sessionId)&&(!e?.turnId||i.turnId===e.turnId)),"listModelUsageRecords")}})}n(x,"inspectHostedProfileEvaluation");async function B(c){if(c.length!==0)throw new Error("Hosted evaluation inspection uses bounded standard input.");let t=[],o=0;for await(let l of process.stdin){let a=Buffer.from(l);if(o+=a.length,o>32*1024*1024)throw new Error("Hosted evaluation inspection input is too large.");t.push(a)}let r=JSON.parse(Buffer.concat(t).toString("utf8")),u=r.action==="compare"||r.action==="report"?await(await import("./hosted-profile-evaluation-control-RJ6XJZCS.js")).controlHostedProfileEvaluation(r):await x(r);process.stdout.write(`${JSON.stringify(u)}
3
3
  `)}n(B,"runHostedProfileInspectionCli");export{x as inspectHostedProfileEvaluation,B as runHostedProfileInspectionCli};
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as V}from"./chunk-OC6UWKBL.js";import{c as I,f as j,h as D}from"./chunk-ZCWHVLJ4.js";import{k as x}from"./chunk-OE2VF6KU.js";import{a as E}from"./chunk-T5LE6R5S.js";import"./chunk-QJRXTIOC.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-7K72KS5C.js";import{ha as b,qa as C}from"./chunk-7MXZJQS7.js";import"./chunk-7YR6CBNU.js";import"./chunk-5CMKGD43.js";import"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import"./chunk-XDMUD4FW.js";import{ta as m}from"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import{Ca as S}from"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import{ma as H}from"./chunk-PJM2G7SG.js";import{Ga as y,j as P,m as R}from"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import{m as d}from"./chunk-NNF6KCHD.js";import{b as e}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as s}from"./chunk-FTQLQJQV.js";import{readFile as h,realpath as z,lstat as T}from"node:fs/promises";import l from"node:path";var B=e.object({compile:e.object({repoPath:e.string(),profileId:e.string(),repositoryId:e.string(),sourceRevision:e.string(),workspaceId:e.string(),outputDir:e.string()}).strict(),externalDatasetPackage:e.string().regex(/^external-dataset-[a-f0-9-]+\.json$/).optional(),sourceCandidate:H.optional(),action:e.enum(["catalog","prepare"]),request:e.unknown().optional()}).strict();async function G(t){let o=await V(t.compile);if(t.sourceCandidate){let a=await C({workspaceId:typeof o.agentSnapshot.metadata.workspaceId=="string"?o.agentSnapshot.metadata.workspaceId:o.workspaceId,sourceDir:l.join(o.bundlePath,"source")});if(d(t.sourceCandidate.harnessRelease)!==d({id:o.harnessRelease.id,contentHash:o.harnessRelease.contentHash})||E(a).protectedClosureHash!==t.sourceCandidate.protectedClosureHash)throw new Error("Private candidate source differs from its actual frozen compiled release.")}let g={release:b.parse({schemaVersion:"openpond.localHarnessReleaseRecord.v1",workspaceId:o.workspaceId,sourceRevision:o.sourceRevision,agentSnapshot:P.parse(o.agentSnapshot),harnessRelease:R.parse(o.harnessRelease),bundlePath:o.bundlePath,createdAt:new Date().toISOString()})},p={source:"openpond_git",profileId:t.compile.profileId,repositoryId:t.compile.repositoryId},f=t.compile.sourceRevision,c={id:o.harnessRelease.id,contentHash:o.harnessRelease.contentHash},w=s(async a=>x({...a,runtime:g}),"loadCatalog"),q=await w({ref:p,sourceRevision:f,harnessRelease:c}),k=l.join(o.bundlePath,"source"),v=o.harnessRelease.files.some(a=>a.path==="workflows/catalog.json")?await(async()=>{let a=y({agentSnapshot:o.agentSnapshot,harnessRelease:o.harnessRelease,catalogBytes:await h(l.join(k,"workflows/catalog.json")),actionBytes:await h(l.join(k,"workflows/actions.json"))});return a.catalog.workflows.map(r=>({workflow:r,binding:{schemaVersion:"openpond.profileWorkflowBinding.v1",profileId:p.profileId,sourceRevision:f,harnessRelease:c,catalogHash:a.catalogHash,workflowId:r.id}}))})():[],A={profileRef:p,sourceRevision:f,harnessRelease:c,workflows:v};if(t.action==="catalog")return{...q,workflows:v};let u=t.externalDatasetPackage?await(async()=>{let a=await z(t.compile.outputDir),r=l.join(a,t.externalDatasetPackage),i=await T(r);if(!i.isFile()||i.isSymbolicLink()||i.size>32*1024*1024||await z(r)!==r)throw new Error("External Dataset cache is outside its bounded verifier storage.");let n=e.object({packageValue:e.unknown(),graders:e.array(e.object({id:e.string(),version:e.string(),contentHash:e.string(),feedbackKey:e.string(),release:e.object({id:e.string(),revision:e.union([e.string(),e.number()]),contentHash:e.string()}).strict().nullable()}).strict()).max(100)}).strict().parse(JSON.parse(await h(r,"utf8")));return{packageValue:S(n.packageValue),graders:n.graders}})():null;return D({privateGradingPreflight:s(a=>I(a,!1),"privateGradingPreflight"),sourceCandidate:t.sourceCandidate,resolveExternalDataset:u?async a=>{let r=m({binding:a,...u}),i=d(o.harnessRelease.files.filter(n=>n.visibility!=="policy").map(n=>({path:n.path,asset:n})));if(a.protectedProfileClosureHash!==i)throw new Error("The selected Profile's protected evaluator closure changed.");return{binding:a,packageValue:r,authorize:s(async()=>{m({binding:a,...u})},"authorize")}}:void 0,loadCatalog:w,selectedWorkflows:s(async()=>A,"selectedWorkflows"),placement:"remote",boundedWorkComputeAvailable:!0,loadTasksetPackage:s(async a=>{let r=await j({runtime:g,definition:a,harnessRelease:c});if(!r)throw new Error("Hosted evaluation Taskset is absent from its published Profile release.");return r},"loadTasksetPackage"),modelConfigurationHash:s(async(a,r)=>{if(a.providerId!=="openpond"||!r.hostModelConfigurationHash)throw new Error("Hosted evaluation preparation requires a trusted model configuration receipt.");return r.hostModelConfigurationHash},"modelConfigurationHash")})(t.request)}s(G,"prepareHostedProfileEvaluation");async function ae(t){if(t.length!==1||t[0].length>48e3||!/^[A-Za-z0-9_-]+$/.test(t[0]))throw new Error("Hosted Profile evaluation preparation argument is invalid.");let o=B.parse(JSON.parse(Buffer.from(t[0],"base64url").toString("utf8")));process.stdout.write(`${JSON.stringify(await G(o))}
2
+ import{a as V}from"./chunk-3LX6RU3C.js";import{c as I,f as j,h as D}from"./chunk-5TNDPNS3.js";import{k as x}from"./chunk-6VF3Q6QJ.js";import{a as E}from"./chunk-T5LE6R5S.js";import"./chunk-USKE34VR.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-7ZG3IT7C.js";import{ha as b,qa as C}from"./chunk-4TZHH5FC.js";import"./chunk-4SHKI3BH.js";import"./chunk-5CMKGD43.js";import"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-7QEE4PBI.js";import"./chunk-2JO2KWT3.js";import{ta as m}from"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import{Ca as S}from"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import{ma as H}from"./chunk-PJM2G7SG.js";import{Ga as y,j as P,m as R}from"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import{m as d}from"./chunk-NNF6KCHD.js";import{b as e}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as s}from"./chunk-FTQLQJQV.js";import{readFile as h,realpath as z,lstat as T}from"node:fs/promises";import l from"node:path";var B=e.object({compile:e.object({repoPath:e.string(),profileId:e.string(),repositoryId:e.string(),sourceRevision:e.string(),workspaceId:e.string(),outputDir:e.string()}).strict(),externalDatasetPackage:e.string().regex(/^external-dataset-[a-f0-9-]+\.json$/).optional(),sourceCandidate:H.optional(),action:e.enum(["catalog","prepare"]),request:e.unknown().optional()}).strict();async function G(t){let o=await V(t.compile);if(t.sourceCandidate){let a=await C({workspaceId:typeof o.agentSnapshot.metadata.workspaceId=="string"?o.agentSnapshot.metadata.workspaceId:o.workspaceId,sourceDir:l.join(o.bundlePath,"source")});if(d(t.sourceCandidate.harnessRelease)!==d({id:o.harnessRelease.id,contentHash:o.harnessRelease.contentHash})||E(a).protectedClosureHash!==t.sourceCandidate.protectedClosureHash)throw new Error("Private candidate source differs from its actual frozen compiled release.")}let g={release:b.parse({schemaVersion:"openpond.localHarnessReleaseRecord.v1",workspaceId:o.workspaceId,sourceRevision:o.sourceRevision,agentSnapshot:P.parse(o.agentSnapshot),harnessRelease:R.parse(o.harnessRelease),bundlePath:o.bundlePath,createdAt:new Date().toISOString()})},p={source:"openpond_git",profileId:t.compile.profileId,repositoryId:t.compile.repositoryId},f=t.compile.sourceRevision,c={id:o.harnessRelease.id,contentHash:o.harnessRelease.contentHash},w=s(async a=>x({...a,runtime:g}),"loadCatalog"),q=await w({ref:p,sourceRevision:f,harnessRelease:c}),k=l.join(o.bundlePath,"source"),v=o.harnessRelease.files.some(a=>a.path==="workflows/catalog.json")?await(async()=>{let a=y({agentSnapshot:o.agentSnapshot,harnessRelease:o.harnessRelease,catalogBytes:await h(l.join(k,"workflows/catalog.json")),actionBytes:await h(l.join(k,"workflows/actions.json"))});return a.catalog.workflows.map(r=>({workflow:r,binding:{schemaVersion:"openpond.profileWorkflowBinding.v1",profileId:p.profileId,sourceRevision:f,harnessRelease:c,catalogHash:a.catalogHash,workflowId:r.id}}))})():[],A={profileRef:p,sourceRevision:f,harnessRelease:c,workflows:v};if(t.action==="catalog")return{...q,workflows:v};let u=t.externalDatasetPackage?await(async()=>{let a=await z(t.compile.outputDir),r=l.join(a,t.externalDatasetPackage),i=await T(r);if(!i.isFile()||i.isSymbolicLink()||i.size>32*1024*1024||await z(r)!==r)throw new Error("External Dataset cache is outside its bounded verifier storage.");let n=e.object({packageValue:e.unknown(),graders:e.array(e.object({id:e.string(),version:e.string(),contentHash:e.string(),feedbackKey:e.string(),release:e.object({id:e.string(),revision:e.union([e.string(),e.number()]),contentHash:e.string()}).strict().nullable()}).strict()).max(100)}).strict().parse(JSON.parse(await h(r,"utf8")));return{packageValue:S(n.packageValue),graders:n.graders}})():null;return D({privateGradingPreflight:s(a=>I(a,!1),"privateGradingPreflight"),sourceCandidate:t.sourceCandidate,resolveExternalDataset:u?async a=>{let r=m({binding:a,...u}),i=d(o.harnessRelease.files.filter(n=>n.visibility!=="policy").map(n=>({path:n.path,asset:n})));if(a.protectedProfileClosureHash!==i)throw new Error("The selected Profile's protected evaluator closure changed.");return{binding:a,packageValue:r,authorize:s(async()=>{m({binding:a,...u})},"authorize")}}:void 0,loadCatalog:w,selectedWorkflows:s(async()=>A,"selectedWorkflows"),placement:"remote",boundedWorkComputeAvailable:!0,loadTasksetPackage:s(async a=>{let r=await j({runtime:g,definition:a,harnessRelease:c});if(!r)throw new Error("Hosted evaluation Taskset is absent from its published Profile release.");return r},"loadTasksetPackage"),modelConfigurationHash:s(async(a,r)=>{if(a.providerId!=="openpond"||!r.hostModelConfigurationHash)throw new Error("Hosted evaluation preparation requires a trusted model configuration receipt.");return r.hostModelConfigurationHash},"modelConfigurationHash")})(t.request)}s(G,"prepareHostedProfileEvaluation");async function ae(t){if(t.length!==1||t[0].length>48e3||!/^[A-Za-z0-9_-]+$/.test(t[0]))throw new Error("Hosted Profile evaluation preparation argument is invalid.");let o=B.parse(JSON.parse(Buffer.from(t[0],"base64url").toString("utf8")));process.stdout.write(`${JSON.stringify(await G(o))}
3
3
  `)}s(ae,"runHostedProfileEvaluationCli");export{G as prepareHostedProfileEvaluation,ae as runHostedProfileEvaluationCli};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as E,c as S}from"./chunk-NPOHW5OU.js";import"./chunk-N3DEA6PG.js";import{c as I}from"./chunk-PA7XP42P.js";import{c as x,f as y}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-RLZPX4YP.js";import"./chunk-Q4H3NUVW.js";import{c as n}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import{u as R}from"./chunk-2SPZYBDN.js";import"./chunk-QXVIIM4T.js";import{d as g}from"./chunk-R3XFY7VL.js";import{b}from"./chunk-GLUWATL5.js";import"./chunk-YL6VFJ4P.js";import"./chunk-Z3D4C7BG.js";import{z as v}from"./chunk-WV2APYWG.js";import{E as w,F as f,O as p,P as h}from"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import{m as u}from"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as m}from"./chunk-FTQLQJQV.js";import{readFile as A,stat as L}from"node:fs/promises";async function C(r,l){let[o,a]=l,i=n(r,"team"),q=r.local===!0||r.local==="true";if(!i||!o||l.length>2)throw new Error("usage: human-review <read|inbox|inspect|results|request> [id] --team <id> [--input-file <path>] [--local --server-url <loopback-origin>]");let t;if(o==="request"){let e=n(r,"inputFile");if(a||!e||(await L(e)).size>1048576)throw new Error("Request requires a bounded --input-file with exact scoped pins, revision and stable operationId for mutations.");if(t=p.parse(JSON.parse(await A(e,"utf8"))),t.scope!==i)throw new Error("Input belongs to another workspace.")}else if(o==="inbox"){if(a)throw new Error("Inbox does not accept an assignment id.");t=p.parse({endpoint:"inbox",scope:i,view:n(r,"view")||"mine",status:n(r,"status")||"active",limit:Number(n(r,"limit")||100),...n(r,"project")?{projectId:n(r,"project")}:{},...n(r,"afterId")?{afterId:n(r,"afterId")}:{}})}else{if(!a)throw new Error(`${o} requires an exact assignment or execution id.`);t=p.parse(o==="read"?{endpoint:"get",scope:i,id:a,...n(r,"revision")?{revision:Number(n(r,"revision"))}:{}}:o==="inspect"?{endpoint:"inspect",scope:i,id:a,...n(r,"slot")?{slot:Number(n(r,"slot"))}:{},...n(r,"afterId")?{afterId:n(r,"afterId")}:{}}:o==="results"?{endpoint:"results",scope:i,executionId:a}:{endpoint:o,scope:i,id:a})}let s;if(q){let e=new URL(n(r,"serverUrl")||E);if(e.protocol!=="http:"||!["localhost","127.0.0.1","[::1]"].includes(e.hostname)||e.username||e.password||e.search||e.hash||e.pathname!=="/")throw new Error("Local Human review requires an HTTP loopback server origin.");let c=await S(e.origin),d=await c(new URL("/v1/human-review?location=local",e),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),redirect:"error",signal:AbortSignal.timeout(3e4)}),H=await U(d);if(s=JSON.parse(H),!d.ok)throw new Error(typeof s.error=="string"?s.error:`Local Human request failed (${d.status}).`)}else{let e=await g();s=await new R({scope:i,apiKey:await I(e,y(e)),baseUrl:x(r)??e.apiBaseUrl??b}).request(t,AbortSignal.timeout(3e4))}if(t.endpoint==="get"||t.endpoint==="command"){let e=w.parse(s),c=t.endpoint==="get"?t.id:t.command.id;if(e.id!==c||e.scope!==i)throw new Error("Review response differs from the requested identity.")}if(t.endpoint==="inbox"&&f.parse(s).items.some(c=>c.scope!==i||t.projectId&&c.projectId!==t.projectId))throw new Error("Inbox response differs from the requested scope.");if(t.endpoint==="inspect"&&h.parse(s).some(e=>e.reviewId!==t.id))throw new Error("Inspection response differs from the selected assignment.");if(t.endpoint==="results"){let e=v.parse(s),{contentHash:c,...d}=e;if(e.executionId!==t.executionId||u(d)!==c||t.selection!==void 0&&u(e.selection)!==u(t.selection))throw new Error("Result response differs from the selected execution or retained review revisions.")}console.log(JSON.stringify(s,null,2))}m(C,"runHumanReviewCommand");async function U(r){let l=r.body?.getReader();if(!l)throw new Error("Review response is unavailable.");let o=[],a=0;try{for(;;){let i=await l.read();if(i.done)break;if(a+=i.value.byteLength,a>8388608)throw new Error("Review response exceeds its bounded transport.");o.push(i.value)}}finally{await l.cancel(),l.releaseLock()}return Buffer.concat(o).toString("utf8")}m(U,"boundedResponse");export{C as runHumanReviewCommand};
2
+ import{a as E,c as S}from"./chunk-NPOHW5OU.js";import"./chunk-N3DEA6PG.js";import{c as I}from"./chunk-PA7XP42P.js";import{c as x,f as y}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-YJ4PNAST.js";import"./chunk-AH22RHPS.js";import{c as n}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import{u as R}from"./chunk-2SPZYBDN.js";import"./chunk-QXVIIM4T.js";import{d as g}from"./chunk-R3XFY7VL.js";import{b}from"./chunk-GLUWATL5.js";import"./chunk-YL6VFJ4P.js";import"./chunk-Z3D4C7BG.js";import{z as v}from"./chunk-WV2APYWG.js";import{E as w,F as f,O as p,P as h}from"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import{m as u}from"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as m}from"./chunk-FTQLQJQV.js";import{readFile as A,stat as L}from"node:fs/promises";async function C(r,l){let[o,a]=l,i=n(r,"team"),q=r.local===!0||r.local==="true";if(!i||!o||l.length>2)throw new Error("usage: human-review <read|inbox|inspect|results|request> [id] --team <id> [--input-file <path>] [--local --server-url <loopback-origin>]");let t;if(o==="request"){let e=n(r,"inputFile");if(a||!e||(await L(e)).size>1048576)throw new Error("Request requires a bounded --input-file with exact scoped pins, revision and stable operationId for mutations.");if(t=p.parse(JSON.parse(await A(e,"utf8"))),t.scope!==i)throw new Error("Input belongs to another workspace.")}else if(o==="inbox"){if(a)throw new Error("Inbox does not accept an assignment id.");t=p.parse({endpoint:"inbox",scope:i,view:n(r,"view")||"mine",status:n(r,"status")||"active",limit:Number(n(r,"limit")||100),...n(r,"project")?{projectId:n(r,"project")}:{},...n(r,"afterId")?{afterId:n(r,"afterId")}:{}})}else{if(!a)throw new Error(`${o} requires an exact assignment or execution id.`);t=p.parse(o==="read"?{endpoint:"get",scope:i,id:a,...n(r,"revision")?{revision:Number(n(r,"revision"))}:{}}:o==="inspect"?{endpoint:"inspect",scope:i,id:a,...n(r,"slot")?{slot:Number(n(r,"slot"))}:{},...n(r,"afterId")?{afterId:n(r,"afterId")}:{}}:o==="results"?{endpoint:"results",scope:i,executionId:a}:{endpoint:o,scope:i,id:a})}let s;if(q){let e=new URL(n(r,"serverUrl")||E);if(e.protocol!=="http:"||!["localhost","127.0.0.1","[::1]"].includes(e.hostname)||e.username||e.password||e.search||e.hash||e.pathname!=="/")throw new Error("Local Human review requires an HTTP loopback server origin.");let c=await S(e.origin),d=await c(new URL("/v1/human-review?location=local",e),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),redirect:"error",signal:AbortSignal.timeout(3e4)}),H=await U(d);if(s=JSON.parse(H),!d.ok)throw new Error(typeof s.error=="string"?s.error:`Local Human request failed (${d.status}).`)}else{let e=await g();s=await new R({scope:i,apiKey:await I(e,y(e)),baseUrl:x(r)??e.apiBaseUrl??b}).request(t,AbortSignal.timeout(3e4))}if(t.endpoint==="get"||t.endpoint==="command"){let e=w.parse(s),c=t.endpoint==="get"?t.id:t.command.id;if(e.id!==c||e.scope!==i)throw new Error("Review response differs from the requested identity.")}if(t.endpoint==="inbox"&&f.parse(s).items.some(c=>c.scope!==i||t.projectId&&c.projectId!==t.projectId))throw new Error("Inbox response differs from the requested scope.");if(t.endpoint==="inspect"&&h.parse(s).some(e=>e.reviewId!==t.id))throw new Error("Inspection response differs from the selected assignment.");if(t.endpoint==="results"){let e=v.parse(s),{contentHash:c,...d}=e;if(e.executionId!==t.executionId||u(d)!==c||t.selection!==void 0&&u(e.selection)!==u(t.selection))throw new Error("Result response differs from the selected execution or retained review revisions.")}console.log(JSON.stringify(s,null,2))}m(C,"runHumanReviewCommand");async function U(r){let l=r.body?.getReader();if(!l)throw new Error("Review response is unavailable.");let o=[],a=0;try{for(;;){let i=await l.read();if(i.done)break;if(a+=i.value.byteLength,a>8388608)throw new Error("Review response exceeds its bounded transport.");o.push(i.value)}}finally{await l.cancel(),l.releaseLock()}return Buffer.concat(o).toString("utf8")}m(U,"boundedResponse");export{C as runHumanReviewCommand};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as D,b as ce,c as de,d as le,e as M,f as X,g as J,h as L,i as Z,j as B,k as z,l as P,m as ee,n as te,o as ue,p as se,q as pe,r as G}from"./chunk-PYABBF53.js";import{k as W}from"./chunk-N3DEA6PG.js";import{a as we}from"./chunk-PA7XP42P.js";import{c as ve,f as ye}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-RLZPX4YP.js";import"./chunk-Q4H3NUVW.js";import{c as E,f as H}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import{p as fe,q as me,r as F}from"./chunk-2SPZYBDN.js";import"./chunk-QXVIIM4T.js";import{d as Y,g as he}from"./chunk-R3XFY7VL.js";import{b as ge}from"./chunk-GLUWATL5.js";import"./chunk-YL6VFJ4P.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import{l as ae,m as T}from"./chunk-NNF6KCHD.js";import{b as I}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as p}from"./chunk-FTQLQJQV.js";import{createInterface as qe}from"node:readline/promises";import{resolve as Ue}from"node:path";import{watch as Pe}from"node:fs";import{randomUUID as je}from"node:crypto";var Me=["source","admission","control","heartbeat"],j=class{static{p(this,"CollectorErrors")}store;constructor(e){this.store=e}read(e){let o=this.store.setting(`errors:${e}`);if(o)return JSON.parse(o);let s=this.store.database.prepare("SELECT error FROM backfill_units WHERE connection_id=? AND state='error' AND error IS NOT NULL ORDER BY session_key LIMIT 1").get(e);return typeof s?.error=="string"?{source:s.error}:{}}message(e,o){let s=this.read(e);return Me.filter(r=>r!==o).map(r=>s[r]).find(Boolean)??null}source(e){return this.read(e).source??null}set(e,o,s){let r=this.read(e);s?r[o]=s.slice(0,500):delete r[o],this.store.set(`errors:${e}`,JSON.stringify(r)),this.store.error(e,this.message(e))}};var Le=I.object({leafId:I.string().min(1).max(200),chainHash:I.string().regex(/^[a-f0-9]{64}$/),sourceInstanceId:I.string().min(1)}).strict(),Se=p((t,e)=>`branch:${JSON.stringify([t,e])}`,"key");function be(t,e,o){let s=t.setting(Se(e,o));if(!s)return;let r=Le.parse(JSON.parse(s));return t.connections().find(g=>g.id===e)?.source.instanceId===r.sourceInstanceId?{leafId:r.leafId,chainHash:r.chainHash}:void 0}p(be,"collectorBranchAnchor");async function Ie(t,e){if(t.source!=="claude_code")throw new Error("Branch selection is currently supported for Claude Code.");let o,s=[];do{let r=await M(t,{cursor:o,limit:100});s.push(...r.items.filter(a=>a.nativeSessionId===e)),o=r.nextCursor??void 0}while(o);if(s.length!==1)throw new Error("Select exactly one native session in this connection's source location.");return s[0]}p(Ie,"findSession");async function Re(t,e,o){let s=await B.open(t);try{let r=s.connections().find(g=>g.id===e);if(!r)throw new Error("Select a connection from openpond import status.");let a=await Ie(r.source,o);return{session:a,...await X(r.source,a)}}finally{s.close()}}p(Re,"inspectCollectorBranches");async function Ce(t,e,o,s){let r=await B.open(t);try{let a=r.connections().find(u=>u.id===e);if(!a||a.state!=="paused")throw new Error(`Pause this connection first: openpond import pause ${e}`);let g=await Ie(a.source,o),c=await X(a.source,g),l=c.branches.find(u=>u.leafId===s.leafId);if(c.revision!==s.revision||!l)throw new Error("This conversation changed. Refresh its branches and choose again.");await J(a.source,g,{branchLeafId:s.leafId,expectedBranchRevision:s.revision}),r.database.exec("BEGIN IMMEDIATE");try{let u=r.connections().find(S=>S.id===e);if(!u||u.state!=="paused"||u.revision!==a.revision||u.source.instanceId!==a.source.instanceId)throw new Error("Connection changed during branch selection. Refresh and try again.");r.set(Se(e,o),JSON.stringify({leafId:l.leafId,chainHash:l.chainHash,sourceInstanceId:a.source.instanceId}));for(let S of["source_scans","checkpoints","pending"])r.database.prepare(`DELETE FROM ${S} WHERE connection_id=?`).run(e);let v=new j(r);v.set(e,"source",v.source(e)),r.progress.reset(e),v.set(e,"admission",null),r.database.exec("COMMIT")}catch(u){throw r.database.exec("ROLLBACK"),u}return{connectionId:e,nativeSessionId:o,leafId:l.leafId,state:"paused"}}finally{r.close()}}p(Ce,"selectCollectorBranch");var V=class{static{p(this,"CollectorSyncRequests")}store;acquisitions=new Map;constructor(e){this.store=e}observe(e,o){let s=o.requestedSyncRevision??e.requestedSyncRevision??0,r=o.completedSyncRevision??0;if(!Number.isSafeInteger(s)||s<0||s>o.revision||!Number.isSafeInteger(r)||r<0||r>s)throw new Error("Invalid remote sync acknowledgement.");let a=this.confirmed(e.id);return r>a&&this.store.set(`syncAcknowledged:${e.id}`,String(r)),{requestedSyncRevision:Math.max(e.requestedSyncRevision??0,s),completedSyncRevision:Math.max(e.completedSyncRevision??0,r)}}needsAcquisition(e){let o=e.requestedSyncRevision??0;if(o<=(e.completedSyncRevision??0))return!1;let s=this.acquisitions.get(e.id);return s?.controlRevision!==e.revision||s.requestedSyncRevision!==o}acquired(e,o){this.acquisitions.set(e,o)}complete(e,o){let s=this.acquisitions.get(e.id),r=e.requestedSyncRevision??0;if(e.state!=="active"||this.store.setting("desiredState")!=="running"||this.store.queued(e.id)||o||!s?.succeeded||s.controlRevision!==e.revision||s.requestedSyncRevision!==r||r<=(e.completedSyncRevision??0))return e;let a={...e,completedSyncRevision:r};return this.store.put(a),a}confirmed(e){return Number(this.store.setting(`syncAcknowledged:${e}`))||0}needsAcknowledgement(e){return(e.completedSyncRevision??0)>this.confirmed(e.id)}};async function Ee(t){let e=await B.open(t.directory),o=je();e.database.exec("BEGIN IMMEDIATE");try{let i=e.setting("owner");if(i){let f=JSON.parse(i),h=!0;try{process.kill(f.pid,0)}catch(n){h=n.code!=="ESRCH"}if(h)throw new Error("The collector already has a live owner.")}e.set("owner",JSON.stringify({pid:process.pid,nonce:o})),e.database.exec("COMMIT")}catch(i){throw e.database.exec("ROLLBACK"),e.close(),i}if(e.setting("desiredState")!=="running"){e.set("owner",""),e.close();return}e.set("pid",String(process.pid));let s=!0,r=0,a=0,g=new Map,c=new j(e),l=new V(e),u=new Map;function v(i){return e.connections().find(f=>f.id===i.id)??i}p(v,"retained");function S(i){let f=e.queued(i.id),h=c.message(i.id,"heartbeat");return{pendingOperations:f,error:h,completedSyncRevision:!f&&!h?i.completedSyncRevision??0:0}}p(S,"heartbeatInput");function d(i,f){let h=v(i);if(h.state==="disconnected"||f.revision<h.revision)return h;let n=l.observe(h,f);f.revision>h.revision&&c.set(h.id,"control",null);let m={...h,...n,...f.revision>h.revision?{revision:f.revision,state:f.state}:{},...f.destinations?{destinations:f.destinations}:{}};return e.put(m),m}p(d,"applyRemote");function R(i,f,h){let n=f instanceof Error?f.message:"Collection failed.";c.set(i.id,h,n);let m=f&&typeof f=="object"&&"status"in f?Number(f.status):0,C=v(i);C.state!=="disconnected"&&[400,401,403].includes(m)&&e.put({...C,state:m===400?"paused":"disconnected"})}p(R,"recordFailure");async function N(i){let f=i.revision,h=i.requestedSyncRevision??0,n,m=[];do{if(Date.now()-a>=L.heartbeatMs){a=Date.now(),e.set("heartbeatAt",new Date().toISOString());for(let w of e.connections())if(w.state!=="disconnected")try{let x=await t.transport.heartbeat(w,S(w));d(w,x),c.set(w.id,"heartbeat",null)}catch(x){R(w,x,"heartbeat")}}if(i=e.connections().find(w=>w.id===i.id)??i,i.state!=="active"||t.signal.aborted||e.setting("desiredState")!=="running")return;let C=await M(i.source,{since:i.since??void 0,cursor:n,limit:50});for(let w of C.items){let x=JSON.stringify([w.path,w.nativeSessionId]),O=w.storageRevision?T([w.storageRevision,de(i.source.source)]):null;if(e.progress.select(i.id,x),t.signal.aborted||e.setting("desiredState")!=="running"||e.connections().find(y=>y.id===i.id)?.state!=="active")return;try{if(O&&!e.sourceChanged(i.id,x,O)&&!e.progress.tracks(i.id,x))continue;let{files:y,preview:b,branchLeafId:k}=await J(i.source,w,{branchAnchor:be(e,i.id,w.nativeSessionId)}),$=!1;for(let q of b.sessions){let _=JSON.stringify([i.source.instanceId,q.sessionId,q.branchId]);e.progress.retained(i.id,x,_);let ne=q.boundaries.filter(A=>A.projection==="turn"&&A.terminal!=="unknown"&&(!i.since||Date.parse(q.events[A.start].occurredAt??w.updatedAt)>=Date.parse(i.since)));$||=ne.length>0;let ie=ne.filter(A=>e.changed(i.id,_,A.id,T([A.inputHash,A.revisionHash])));for(let A=0;A<ie.length;A+=L.batchCases){let Q=ie.slice(A,A+L.batchCases),De=`sync-${T([i.id,_,Q.map(U=>[U.id,U.inputHash,U.revisionHash])]).slice(0,48)}`;e.enqueue({operationId:De,connectionId:i.id,sessionKey:_,contentHash:q.contentHash,files:y,boundaryIds:Q.map(U=>U.id),...k?{branchLeafId:k}:{}},Q.map(U=>({id:U.id,revision:T([U.inputHash,U.revisionHash])})),x)}}e.progress.read(i.id,x,$),O&&e.scanned(i.id,x,O)}catch(y){if(y instanceof le){e.progress.read(i.id,x,!1),O&&e.scanned(i.id,x,O);continue}e.progress.failed(i.id,x,y instanceof Error?y.message:"Unable to read session"),m.push(`${w.nativeSessionId}: ${y instanceof Error?y.message:"Unable to read session"}`)}}n=C.nextCursor??void 0}while(n);e.progress.discovered(i.id),u.set(i.id,f),l.acquired(i.id,{controlRevision:f,requestedSyncRevision:h,succeeded:m.length===0}),c.set(i.id,"source",m.length?`${m.length} session(s) need attention. ${m[0]}`:null)}p(N,"acquire");try{for(;!t.signal.aborted&&e.setting("desiredState")==="running";){let i=e.connections();e.set("heartbeatAt",new Date().toISOString());for(let n of i)if(n.state!=="disconnected"&&!g.has(n.source.root))try{let m=Pe(n.source.root,{recursive:n.source.acquisition!=="sqlite"},()=>{s=!0});m.on("error",()=>{s=!0}),g.set(n.source.root,m)}catch{}let f=Date.now()-a>=L.heartbeatMs;f&&(a=Date.now());let h=s||Date.now()-r>=L.reconcileMs||e.setting("syncNow")==="yes";h&&(s=!1,r=Date.now(),e.set("syncNow","no"));for(let n of i){if(n=v(n),n.state==="disconnected")continue;let m="heartbeat";try{if(f){let w=await t.transport.heartbeat(n,S(n));n=d(n,w),c.set(n.id,"heartbeat",null)}if(n.state!=="active"){u.delete(n.id);continue}if(m="source",(h||u.get(n.id)!==n.revision||l.needsAcquisition(n))&&await N(n),n=e.connections().find(w=>w.id===n.id)??n,n.state!=="active"||t.signal.aborted||e.setting("desiredState")!=="running")continue;m="admission";let C=e.next(n.id);if(C)try{await t.transport.admit(n,C.entry),e.acknowledge(C.entry),c.set(n.id,"admission",null)}catch(w){throw e.retry(C.entry.operationId,C.attempts),w}if(n=v(n),t.signal.aborted||e.setting("desiredState")!=="running"||n.state!=="active")continue;if(n=l.complete(n,c.message(n.id,"heartbeat")),l.needsAcknowledgement(n)&&S(n).completedSyncRevision){m="heartbeat";let w=await t.transport.heartbeat(n,S(n));n=d(n,w),c.set(n.id,"heartbeat",null)}if(!t.signal.aborted&&e.setting("desiredState")==="running"&&n.state==="active"&&!n.keepSyncing&&u.get(n.id)===n.revision&&e.queued(n.id)===0&&e.progress.status(n.id).stage==="complete"&&!c.source(n.id)&&l.confirmed(n.id)>=(n.requestedSyncRevision??0)){if(m="control",!t.transport.pause)throw new Error("This transport cannot acknowledge completion of a one-time import.");let w=await t.transport.pause(n);d(n,w),c.set(n.id,"control",null)}}catch(C){R(n,C,m)}}await new Promise(n=>{let m=p(()=>{clearTimeout(C),t.signal.removeEventListener("abort",m),n()},"done"),C=setTimeout(m,1e3);t.signal.addEventListener("abort",m,{once:!0})})}}finally{for(let f of g.values())f.close();JSON.parse(e.setting("owner")||"{}").nonce===o&&(e.set("pid",""),e.set("heartbeatAt",""),e.set("owner","")),e.close()}}p(Ee,"runCollector");import{createHash as Ne,generateKeyPairSync as Ke,createPublicKey as _e,diffieHellman as Je,createDecipheriv as ze}from"node:crypto";import{spawn as Ge}from"node:child_process";var xe=p(t=>Ne("sha256").update(t).digest("hex"),"hash"),Fe=I.object({publicKey:I.string().max(200),iv:I.string().max(100),tag:I.string().max(100),ciphertext:I.string().max(1e4)}).strict();async function re(t,e,o){let s=await fetch(`${t}${e}`,{method:"POST",redirect:"error",signal:AbortSignal.timeout(15e3),headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),r=await s.text();if(r.length>16384)throw new Error("Authorization response exceeded its limit.");if(!s.ok)throw Object.assign(new Error(`Browser sign-in failed (${s.status}).`),{status:s.status});return JSON.parse(r)}p(re,"post");function Ye(t){let e=process.platform==="darwin"?"open":process.platform==="win32"?"rundll32":"xdg-open",o=process.platform==="win32"?["url.dll,FileProtocolHandler",t]:[t],s=Ge(e,o,{stdio:"ignore",detached:!0});s.on("error",()=>{}),s.unref()}p(Ye,"openBrowser");async function Oe(t,e){let o=await Y(),s=ve(e)||o.apiBaseUrl||ge,r=E(e,"baseUrl")||(new URL(s).hostname==="staging-api.openpond.ai"?"https://staging.openpond.ai":ye(o)),a=new URL(r),g=new URL(s);for(let d of[a,g])if(d.protocol!=="https:"&&!(d.protocol==="http:"&&["localhost","127.0.0.1"].includes(d.hostname))||d.username||d.password||d.search||d.hash)throw new Error("Sign-in requires a clean HTTPS origin or local development origin.");let c=`import-${xe([a.origin,t.machineId,t.instanceId].join(":")).slice(0,24)}`,l=Ke("x25519"),u=l.publicKey.export({format:"der",type:"spki"}).toString("base64"),v=I.object({deviceCode:I.string(),userCode:I.string(),expiresAt:I.string().datetime(),intervalSeconds:I.number().min(2).max(10)}).strict().parse(await re(a.origin,"/api/cli/import/device",{publicKey:u,machineId:t.machineId,sourceInstanceId:t.instanceId,sourceLabel:D[t.source],sourceRoot:t.root,...E(e,"team")?{requestedTeamId:E(e,"team")}:{}})),S=`${a.origin}/console/connections/authorize?code=${encodeURIComponent(v.userCode)}`;for(console.log(`OpenPond sign-in code: ${v.userCode}
2
+ import{a as D,b as ce,c as de,d as le,e as M,f as X,g as J,h as L,i as Z,j as B,k as z,l as P,m as ee,n as te,o as ue,p as se,q as pe,r as G}from"./chunk-PYABBF53.js";import{k as W}from"./chunk-N3DEA6PG.js";import{a as we}from"./chunk-PA7XP42P.js";import{c as ve,f as ye}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-YJ4PNAST.js";import"./chunk-AH22RHPS.js";import{c as E,f as H}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import{p as fe,q as me,r as F}from"./chunk-2SPZYBDN.js";import"./chunk-QXVIIM4T.js";import{d as Y,g as he}from"./chunk-R3XFY7VL.js";import{b as ge}from"./chunk-GLUWATL5.js";import"./chunk-YL6VFJ4P.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import{l as ae,m as T}from"./chunk-NNF6KCHD.js";import{b as I}from"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as p}from"./chunk-FTQLQJQV.js";import{createInterface as qe}from"node:readline/promises";import{resolve as Ue}from"node:path";import{watch as Pe}from"node:fs";import{randomUUID as je}from"node:crypto";var Me=["source","admission","control","heartbeat"],j=class{static{p(this,"CollectorErrors")}store;constructor(e){this.store=e}read(e){let o=this.store.setting(`errors:${e}`);if(o)return JSON.parse(o);let s=this.store.database.prepare("SELECT error FROM backfill_units WHERE connection_id=? AND state='error' AND error IS NOT NULL ORDER BY session_key LIMIT 1").get(e);return typeof s?.error=="string"?{source:s.error}:{}}message(e,o){let s=this.read(e);return Me.filter(r=>r!==o).map(r=>s[r]).find(Boolean)??null}source(e){return this.read(e).source??null}set(e,o,s){let r=this.read(e);s?r[o]=s.slice(0,500):delete r[o],this.store.set(`errors:${e}`,JSON.stringify(r)),this.store.error(e,this.message(e))}};var Le=I.object({leafId:I.string().min(1).max(200),chainHash:I.string().regex(/^[a-f0-9]{64}$/),sourceInstanceId:I.string().min(1)}).strict(),Se=p((t,e)=>`branch:${JSON.stringify([t,e])}`,"key");function be(t,e,o){let s=t.setting(Se(e,o));if(!s)return;let r=Le.parse(JSON.parse(s));return t.connections().find(g=>g.id===e)?.source.instanceId===r.sourceInstanceId?{leafId:r.leafId,chainHash:r.chainHash}:void 0}p(be,"collectorBranchAnchor");async function Ie(t,e){if(t.source!=="claude_code")throw new Error("Branch selection is currently supported for Claude Code.");let o,s=[];do{let r=await M(t,{cursor:o,limit:100});s.push(...r.items.filter(a=>a.nativeSessionId===e)),o=r.nextCursor??void 0}while(o);if(s.length!==1)throw new Error("Select exactly one native session in this connection's source location.");return s[0]}p(Ie,"findSession");async function Re(t,e,o){let s=await B.open(t);try{let r=s.connections().find(g=>g.id===e);if(!r)throw new Error("Select a connection from openpond import status.");let a=await Ie(r.source,o);return{session:a,...await X(r.source,a)}}finally{s.close()}}p(Re,"inspectCollectorBranches");async function Ce(t,e,o,s){let r=await B.open(t);try{let a=r.connections().find(u=>u.id===e);if(!a||a.state!=="paused")throw new Error(`Pause this connection first: openpond import pause ${e}`);let g=await Ie(a.source,o),c=await X(a.source,g),l=c.branches.find(u=>u.leafId===s.leafId);if(c.revision!==s.revision||!l)throw new Error("This conversation changed. Refresh its branches and choose again.");await J(a.source,g,{branchLeafId:s.leafId,expectedBranchRevision:s.revision}),r.database.exec("BEGIN IMMEDIATE");try{let u=r.connections().find(S=>S.id===e);if(!u||u.state!=="paused"||u.revision!==a.revision||u.source.instanceId!==a.source.instanceId)throw new Error("Connection changed during branch selection. Refresh and try again.");r.set(Se(e,o),JSON.stringify({leafId:l.leafId,chainHash:l.chainHash,sourceInstanceId:a.source.instanceId}));for(let S of["source_scans","checkpoints","pending"])r.database.prepare(`DELETE FROM ${S} WHERE connection_id=?`).run(e);let v=new j(r);v.set(e,"source",v.source(e)),r.progress.reset(e),v.set(e,"admission",null),r.database.exec("COMMIT")}catch(u){throw r.database.exec("ROLLBACK"),u}return{connectionId:e,nativeSessionId:o,leafId:l.leafId,state:"paused"}}finally{r.close()}}p(Ce,"selectCollectorBranch");var V=class{static{p(this,"CollectorSyncRequests")}store;acquisitions=new Map;constructor(e){this.store=e}observe(e,o){let s=o.requestedSyncRevision??e.requestedSyncRevision??0,r=o.completedSyncRevision??0;if(!Number.isSafeInteger(s)||s<0||s>o.revision||!Number.isSafeInteger(r)||r<0||r>s)throw new Error("Invalid remote sync acknowledgement.");let a=this.confirmed(e.id);return r>a&&this.store.set(`syncAcknowledged:${e.id}`,String(r)),{requestedSyncRevision:Math.max(e.requestedSyncRevision??0,s),completedSyncRevision:Math.max(e.completedSyncRevision??0,r)}}needsAcquisition(e){let o=e.requestedSyncRevision??0;if(o<=(e.completedSyncRevision??0))return!1;let s=this.acquisitions.get(e.id);return s?.controlRevision!==e.revision||s.requestedSyncRevision!==o}acquired(e,o){this.acquisitions.set(e,o)}complete(e,o){let s=this.acquisitions.get(e.id),r=e.requestedSyncRevision??0;if(e.state!=="active"||this.store.setting("desiredState")!=="running"||this.store.queued(e.id)||o||!s?.succeeded||s.controlRevision!==e.revision||s.requestedSyncRevision!==r||r<=(e.completedSyncRevision??0))return e;let a={...e,completedSyncRevision:r};return this.store.put(a),a}confirmed(e){return Number(this.store.setting(`syncAcknowledged:${e}`))||0}needsAcknowledgement(e){return(e.completedSyncRevision??0)>this.confirmed(e.id)}};async function Ee(t){let e=await B.open(t.directory),o=je();e.database.exec("BEGIN IMMEDIATE");try{let i=e.setting("owner");if(i){let f=JSON.parse(i),h=!0;try{process.kill(f.pid,0)}catch(n){h=n.code!=="ESRCH"}if(h)throw new Error("The collector already has a live owner.")}e.set("owner",JSON.stringify({pid:process.pid,nonce:o})),e.database.exec("COMMIT")}catch(i){throw e.database.exec("ROLLBACK"),e.close(),i}if(e.setting("desiredState")!=="running"){e.set("owner",""),e.close();return}e.set("pid",String(process.pid));let s=!0,r=0,a=0,g=new Map,c=new j(e),l=new V(e),u=new Map;function v(i){return e.connections().find(f=>f.id===i.id)??i}p(v,"retained");function S(i){let f=e.queued(i.id),h=c.message(i.id,"heartbeat");return{pendingOperations:f,error:h,completedSyncRevision:!f&&!h?i.completedSyncRevision??0:0}}p(S,"heartbeatInput");function d(i,f){let h=v(i);if(h.state==="disconnected"||f.revision<h.revision)return h;let n=l.observe(h,f);f.revision>h.revision&&c.set(h.id,"control",null);let m={...h,...n,...f.revision>h.revision?{revision:f.revision,state:f.state}:{},...f.destinations?{destinations:f.destinations}:{}};return e.put(m),m}p(d,"applyRemote");function R(i,f,h){let n=f instanceof Error?f.message:"Collection failed.";c.set(i.id,h,n);let m=f&&typeof f=="object"&&"status"in f?Number(f.status):0,C=v(i);C.state!=="disconnected"&&[400,401,403].includes(m)&&e.put({...C,state:m===400?"paused":"disconnected"})}p(R,"recordFailure");async function N(i){let f=i.revision,h=i.requestedSyncRevision??0,n,m=[];do{if(Date.now()-a>=L.heartbeatMs){a=Date.now(),e.set("heartbeatAt",new Date().toISOString());for(let w of e.connections())if(w.state!=="disconnected")try{let x=await t.transport.heartbeat(w,S(w));d(w,x),c.set(w.id,"heartbeat",null)}catch(x){R(w,x,"heartbeat")}}if(i=e.connections().find(w=>w.id===i.id)??i,i.state!=="active"||t.signal.aborted||e.setting("desiredState")!=="running")return;let C=await M(i.source,{since:i.since??void 0,cursor:n,limit:50});for(let w of C.items){let x=JSON.stringify([w.path,w.nativeSessionId]),O=w.storageRevision?T([w.storageRevision,de(i.source.source)]):null;if(e.progress.select(i.id,x),t.signal.aborted||e.setting("desiredState")!=="running"||e.connections().find(y=>y.id===i.id)?.state!=="active")return;try{if(O&&!e.sourceChanged(i.id,x,O)&&!e.progress.tracks(i.id,x))continue;let{files:y,preview:b,branchLeafId:k}=await J(i.source,w,{branchAnchor:be(e,i.id,w.nativeSessionId)}),$=!1;for(let q of b.sessions){let _=JSON.stringify([i.source.instanceId,q.sessionId,q.branchId]);e.progress.retained(i.id,x,_);let ne=q.boundaries.filter(A=>A.projection==="turn"&&A.terminal!=="unknown"&&(!i.since||Date.parse(q.events[A.start].occurredAt??w.updatedAt)>=Date.parse(i.since)));$||=ne.length>0;let ie=ne.filter(A=>e.changed(i.id,_,A.id,T([A.inputHash,A.revisionHash])));for(let A=0;A<ie.length;A+=L.batchCases){let Q=ie.slice(A,A+L.batchCases),De=`sync-${T([i.id,_,Q.map(U=>[U.id,U.inputHash,U.revisionHash])]).slice(0,48)}`;e.enqueue({operationId:De,connectionId:i.id,sessionKey:_,contentHash:q.contentHash,files:y,boundaryIds:Q.map(U=>U.id),...k?{branchLeafId:k}:{}},Q.map(U=>({id:U.id,revision:T([U.inputHash,U.revisionHash])})),x)}}e.progress.read(i.id,x,$),O&&e.scanned(i.id,x,O)}catch(y){if(y instanceof le){e.progress.read(i.id,x,!1),O&&e.scanned(i.id,x,O);continue}e.progress.failed(i.id,x,y instanceof Error?y.message:"Unable to read session"),m.push(`${w.nativeSessionId}: ${y instanceof Error?y.message:"Unable to read session"}`)}}n=C.nextCursor??void 0}while(n);e.progress.discovered(i.id),u.set(i.id,f),l.acquired(i.id,{controlRevision:f,requestedSyncRevision:h,succeeded:m.length===0}),c.set(i.id,"source",m.length?`${m.length} session(s) need attention. ${m[0]}`:null)}p(N,"acquire");try{for(;!t.signal.aborted&&e.setting("desiredState")==="running";){let i=e.connections();e.set("heartbeatAt",new Date().toISOString());for(let n of i)if(n.state!=="disconnected"&&!g.has(n.source.root))try{let m=Pe(n.source.root,{recursive:n.source.acquisition!=="sqlite"},()=>{s=!0});m.on("error",()=>{s=!0}),g.set(n.source.root,m)}catch{}let f=Date.now()-a>=L.heartbeatMs;f&&(a=Date.now());let h=s||Date.now()-r>=L.reconcileMs||e.setting("syncNow")==="yes";h&&(s=!1,r=Date.now(),e.set("syncNow","no"));for(let n of i){if(n=v(n),n.state==="disconnected")continue;let m="heartbeat";try{if(f){let w=await t.transport.heartbeat(n,S(n));n=d(n,w),c.set(n.id,"heartbeat",null)}if(n.state!=="active"){u.delete(n.id);continue}if(m="source",(h||u.get(n.id)!==n.revision||l.needsAcquisition(n))&&await N(n),n=e.connections().find(w=>w.id===n.id)??n,n.state!=="active"||t.signal.aborted||e.setting("desiredState")!=="running")continue;m="admission";let C=e.next(n.id);if(C)try{await t.transport.admit(n,C.entry),e.acknowledge(C.entry),c.set(n.id,"admission",null)}catch(w){throw e.retry(C.entry.operationId,C.attempts),w}if(n=v(n),t.signal.aborted||e.setting("desiredState")!=="running"||n.state!=="active")continue;if(n=l.complete(n,c.message(n.id,"heartbeat")),l.needsAcknowledgement(n)&&S(n).completedSyncRevision){m="heartbeat";let w=await t.transport.heartbeat(n,S(n));n=d(n,w),c.set(n.id,"heartbeat",null)}if(!t.signal.aborted&&e.setting("desiredState")==="running"&&n.state==="active"&&!n.keepSyncing&&u.get(n.id)===n.revision&&e.queued(n.id)===0&&e.progress.status(n.id).stage==="complete"&&!c.source(n.id)&&l.confirmed(n.id)>=(n.requestedSyncRevision??0)){if(m="control",!t.transport.pause)throw new Error("This transport cannot acknowledge completion of a one-time import.");let w=await t.transport.pause(n);d(n,w),c.set(n.id,"control",null)}}catch(C){R(n,C,m)}}await new Promise(n=>{let m=p(()=>{clearTimeout(C),t.signal.removeEventListener("abort",m),n()},"done"),C=setTimeout(m,1e3);t.signal.addEventListener("abort",m,{once:!0})})}}finally{for(let f of g.values())f.close();JSON.parse(e.setting("owner")||"{}").nonce===o&&(e.set("pid",""),e.set("heartbeatAt",""),e.set("owner","")),e.close()}}p(Ee,"runCollector");import{createHash as Ne,generateKeyPairSync as Ke,createPublicKey as _e,diffieHellman as Je,createDecipheriv as ze}from"node:crypto";import{spawn as Ge}from"node:child_process";var xe=p(t=>Ne("sha256").update(t).digest("hex"),"hash"),Fe=I.object({publicKey:I.string().max(200),iv:I.string().max(100),tag:I.string().max(100),ciphertext:I.string().max(1e4)}).strict();async function re(t,e,o){let s=await fetch(`${t}${e}`,{method:"POST",redirect:"error",signal:AbortSignal.timeout(15e3),headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),r=await s.text();if(r.length>16384)throw new Error("Authorization response exceeded its limit.");if(!s.ok)throw Object.assign(new Error(`Browser sign-in failed (${s.status}).`),{status:s.status});return JSON.parse(r)}p(re,"post");function Ye(t){let e=process.platform==="darwin"?"open":process.platform==="win32"?"rundll32":"xdg-open",o=process.platform==="win32"?["url.dll,FileProtocolHandler",t]:[t],s=Ge(e,o,{stdio:"ignore",detached:!0});s.on("error",()=>{}),s.unref()}p(Ye,"openBrowser");async function Oe(t,e){let o=await Y(),s=ve(e)||o.apiBaseUrl||ge,r=E(e,"baseUrl")||(new URL(s).hostname==="staging-api.openpond.ai"?"https://staging.openpond.ai":ye(o)),a=new URL(r),g=new URL(s);for(let d of[a,g])if(d.protocol!=="https:"&&!(d.protocol==="http:"&&["localhost","127.0.0.1"].includes(d.hostname))||d.username||d.password||d.search||d.hash)throw new Error("Sign-in requires a clean HTTPS origin or local development origin.");let c=`import-${xe([a.origin,t.machineId,t.instanceId].join(":")).slice(0,24)}`,l=Ke("x25519"),u=l.publicKey.export({format:"der",type:"spki"}).toString("base64"),v=I.object({deviceCode:I.string(),userCode:I.string(),expiresAt:I.string().datetime(),intervalSeconds:I.number().min(2).max(10)}).strict().parse(await re(a.origin,"/api/cli/import/device",{publicKey:u,machineId:t.machineId,sourceInstanceId:t.instanceId,sourceLabel:D[t.source],sourceRoot:t.root,...E(e,"team")?{requestedTeamId:E(e,"team")}:{}})),S=`${a.origin}/console/connections/authorize?code=${encodeURIComponent(v.userCode)}`;for(console.log(`OpenPond sign-in code: ${v.userCode}
3
3
  ${S}`),Ye(S);Date.now()<Date.parse(v.expiresAt);){await new Promise(m=>setTimeout(m,v.intervalSeconds*1e3));let d;try{d=await re(a.origin,"/api/cli/import/token",{deviceCode:v.deviceCode})}catch(m){if(Number(m.status)===429)continue;throw m}let R=I.object({state:I.enum(["pending","approved","denied","consumed"]),envelope:Fe.nullable().optional()}).strict().parse(d);if(R.state==="denied"||R.state==="consumed")throw new Error("Browser sign-in was declined or already consumed. Start the connection again.");if(R.state!=="approved"||!R.envelope)continue;let N=R.envelope,i=_e({key:Buffer.from(N.publicKey,"base64"),format:"der",type:"spki"});if(i.asymmetricKeyType!=="x25519")throw new Error("Invalid sign-in encryption key.");let f=Ne("sha256").update(Je({privateKey:l.privateKey,publicKey:i})).digest(),h=ze("aes-256-gcm",f,Buffer.from(N.iv,"base64"));h.setAAD(Buffer.from(xe(v.deviceCode))),h.setAuthTag(Buffer.from(N.tag,"base64"));let n=I.object({apiKey:I.string().min(1),teamId:I.string().min(1),expiresAt:I.string().datetime()}).strict().parse(JSON.parse(Buffer.concat([h.update(Buffer.from(N.ciphertext,"base64")),h.final()]).toString("utf8")));if(E(e,"team")&&n.teamId!==E(e,"team"))throw new Error("Browser approved a different workspace.");return await he({handle:c,apiKey:n.apiKey,baseUrl:a.origin,apiBaseUrl:g.origin,setActive:!1}),await re(a.origin,"/api/cli/import/token",{deviceCode:v.deviceCode,acknowledge:!0}),{apiKey:n.apiKey,teamId:n.teamId,baseUrl:g.origin,account:c,accountBaseUrl:a.origin}}throw new Error("Browser sign-in expired. Start the connection again.")}p(Oe,"authorizeImporter");async function K(t){let e=await Y({account:t.account,baseUrl:t.accountBaseUrl}),o=t.account?e.apiKey:we(e);if(!o)throw Object.assign(new Error("This source is disconnected. Reconnect it with OpenPond Importer to authorize collection."),{status:401});let s={apiKey:o,baseUrl:t.apiBaseUrl,teamId:t.teamId};return{evidence:new me(s),sync:new F(s)}}p(K,"collectorClients");var ke={async pause(t){let{sync:e}=await K(t),o=await e.control({id:t.id,expectedRevision:t.revision,action:"pause"});return{revision:o.revision,state:o.state,destinations:Z(t,o),requestedSyncRevision:o.requestedSyncRevision,completedSyncRevision:o.completedSyncRevision}},async heartbeat(t,e){let{sync:o}=await K(t),s=await o.heartbeat({id:t.id,expectedRevision:t.revision,...e});return{revision:s.revision,state:s.state,destinations:Z(t,s),requestedSyncRevision:s.requestedSyncRevision,completedSyncRevision:s.completedSyncRevision}},async admit(t,e){let{evidence:o,sync:s}=await K(t),r=AbortSignal.timeout(6e4),a=Buffer.from(JSON.stringify(e.files.map(d=>({path:d.path,encoding:"utf8",base64:Buffer.from(d.text).toString("base64")})))),g={hash:ae(a),parts:Math.ceil(a.length/2e5)};for(let d=0;d<g.parts;d++)await o.uploadPart({...g,index:d,base64:a.subarray(d*2e5,(d+1)*2e5).toString("base64")},r);let c={upload:g,source:t.source.source,...e.branchLeafId?{branchLeafId:e.branchLeafId}:{},destination:{kind:"existing",projectId:t.projectId},acquisition:{machineId:t.source.machineId,sourceInstanceId:t.source.instanceId}},l=await o.preview(c,r);if(l.issues.length)throw Object.assign(new Error("Source schema was rejected; inspect the connection before resuming."),{status:400});let u=l.sessions.find(d=>d.sessionHash===e.contentHash);if(!u||e.boundaryIds.some(d=>!u.boundaries.some(R=>R.id===d&&R.projection==="turn"&&R.terminal!=="unknown")))throw Object.assign(new Error("Server preview differs from the retained source boundaries."),{status:400});let v={...c,operationId:e.operationId,previewHash:l.previewHash,selection:[{sessionHash:u.sessionHash,boundaryIds:e.boundaryIds}]},S=fe.parse(await s.commit({connectionId:t.id,expectedRevision:t.revision,request:v},r));if(S.state!=="completed"||S.operationId!==e.operationId||S.requestHash!==T(v)||S.projectId!==t.projectId)throw new Error("Admission did not acknowledge this retained operation.")}};import{emitKeypressEvents as We}from"node:readline";async function Ae(t){console.log("Ctrl+C closes this view and keeps syncing. Ctrl+D pauses this connection.");let e=new AbortController,o=p(()=>e.abort(),"detach"),s=!1,r=process.stdin.isRaw,a=p((c,l)=>{l?.ctrl&&(l.name==="c"&&o(),l.name==="d"&&!s&&(s=!0,t.pause().then(o).catch(u=>{console.error(`
4
4
  Unable to pause: ${u instanceof Error?u.message:"connection update failed"}`),s=!1})))},"keypress");We(process.stdin),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("keypress",a),process.stdin.once("end",o),process.once("SIGINT",o);let g=0;try{for(;!e.signal.aborted;){let c=await P(t.directory),l=c.connections.find(f=>f.id===t.connectionId);if(!l)break;let u=l.backfill,v=u.admitted+u.skipped,S=u.total?v/u.total:u.stage==="complete"?1:0,d=Math.max(0,Math.min(20,Math.floor(S*20))),R=u.stage==="discovering"?`${["|","/","-","\\"][g++%4]} Discovering conversations (${u.total} found)`:`[${"=".repeat(d)}${" ".repeat(20-d)}] ${v}/${u.total} conversations`,N=c.running?l.state!=="active"?l.state:u.stage==="complete"?t.keepSyncing?"Watching for new conversations":"Import complete":u.stage:"Service offline",i=`${R} ${l.admitted} tasks admitted ${u.skipped} skipped ${u.failed} need attention ${l.queued} queued ${l.error||N}${l.lastAdmissionAt?` Last sync ${l.lastAdmissionAt}`:""}`;if(process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(i),!t.keepSyncing&&l.state==="paused"&&l.queued===0)break;await new Promise(f=>{let h=p(()=>{clearTimeout(n),e.signal.removeEventListener("abort",h),f()},"done"),n=setTimeout(h,1e3);e.signal.addEventListener("abort",h,{once:!0})})}}finally{process.stdin.off("keypress",a),process.stdin.off("end",o),process.off("SIGINT",o),process.stdin.setRawMode(r??!1),process.stdin.pause(),console.log()}}p(Ae,"monitorImport");async function oe(t,e){let o=await B.open(t),s;try{s=o.connections().find(r=>r.id===e)}finally{o.close()}if(!s)throw new Error("Select a retained connection from openpond import status.");if(s.source.machineId!==await G(t))throw new Error("This connection belongs to another machine. Use explicit Connect setup.");if(!s.accountBaseUrl)throw new Error("The original sign-in destination is unavailable. Use explicit Connect setup.");return s}p(oe,"retainedReconnect");function Te(t,e){if(!e?.available||!e.capabilities.history||e.source!==t.source.source||e.machineId!==t.source.machineId||e.instanceId!==t.source.instanceId||e.root!==t.source.root)throw new Error("The retained source is unavailable or its identity changed. Restore its original location or use explicit Connect setup.")}p(Te,"assertReconnectSource");async function $e(t,e){let o=await oe(t,e.id),s=p(r=>({...r,destinations:void 0,requestedSyncRevision:r.requestedSyncRevision??0,completedSyncRevision:r.completedSyncRevision??0}),"scope");if(T(s(o))!==T(s(e)))throw new Error("The connection changed during sign-in. Reconnect again after reviewing its current scope.")}p($e,"assertReconnectUnchanged");import{createInterface as Ve}from"node:readline/promises";async function Be(t,e,o,s){let r=E(s,"session");if(!o||!r)throw new Error("Use openpond import branches <connection-id> --session <native-session-id>.");let a=await Re(t,o,r);if(e==="branches"){console.log(JSON.stringify(a,null,2));return}let g=process.stdin.isTTY&&process.stdout.isTTY&&!H(s.json),c=E(s,"leaf"),l=E(s,"revision");if(!c&&g){a.branches.forEach((S,d)=>console.log(`${d+1}. ${S.title||S.leafId} (${S.messages} messages; ${S.updatedAt||"date unavailable"})`));let v=Ve({input:process.stdin,output:process.stdout});try{c=a.branches[Number(await v.question("Choose the branch to sync: "))-1]?.leafId??"",l=a.revision}finally{v.close()}}if(!c||!l)throw new Error("Supply --leaf and --revision from import branches, or choose interactively. No branch was selected.");if(!a.branches.some(v=>v.leafId===c)||l!==a.revision)throw new Error("Branch selection is stale or invalid. Run import branches again.");if(!H(s.yes)&&(!g||!await W("Sync only this branch and its unambiguous future continuation for this conversation? Other branches stay excluded.",!1)))throw new Error("Branch selection was not approved.");let u=await Ce(t,o,r,{leafId:c,revision:l});console.log(JSON.stringify({...u,next:`openpond import resume ${o}`},null,2))}p(Be,"runImporterBranchCommand");async function is(t,e){let[o="connect",s]=e,r=Ue(E(t,"collectorDir")||pe()),a=H(t.json),g=p(y=>console.log(JSON.stringify(y,null,2)),"print");if(o==="branches"||o==="branch"){await Be(r,o,s,t);return}if(o==="service"){if(s==="status"){g(await P(r));return}if(s==="stop"){g(await ee(r,"stop"));return}if(s==="uninstall"){g(await ue(r));return}if(s==="install"){g(await te({directory:r,executable:process.execPath,args:[process.argv[1]],environment:He()}));return}if(s==="start"){g(await se(r));return}if(s==="run"){let y=new AbortController,b=p(()=>y.abort(),"stop");process.once("SIGTERM",b),process.once("SIGINT",b);try{await Ee({directory:r,transport:ke,signal:y.signal})}finally{process.off("SIGTERM",b),process.off("SIGINT",b)}return}throw new Error("usage: openpond import service <install|start|stop|status|run|uninstall>")}if(o==="status"){g(await P(r));return}if(o==="sync"){g(await ee(r,"sync"));return}if(["pause","resume","disconnect"].includes(o)){let y=await B.open(r),b;try{b=y.connections().find(q=>q.id===s)}finally{y.close()}if(!b)throw new Error("Select a connection id from openpond import status.");let{sync:k}=await K(b),$=await k.control({id:b.id,expectedRevision:b.revision,action:o});await z(r,{...b,revision:$.revision,state:$.state}),g($);return}let c=o==="reconnect"?await oe(r,s):null;c&&(t={...t,source:c.source.source,sourcePath:c.source.root,project:c.projectId,connection:c.id,team:c.teamId,apiBaseUrl:c.apiBaseUrl,baseUrl:c.accountBaseUrl,once:!c.keepSyncing});let l=E(t,"source");if(l&&!(l in D))throw new Error("Choose a supported native source name.");let u=await G(r),v=await ce({machineId:u,...l&&E(t,"sourcePath")?{locations:{[l]:Ue(E(t,"sourcePath"))}}:{}});if(o==="discover"){g(v);return}if(o!=="connect"&&o!=="reconnect")throw new Error("usage: openpond import <connect|reconnect|discover|status|sync|pause|resume|disconnect|branches|branch|service>");let S=v.filter(y=>y.source===l),d=S.length===1?S[0]:void 0,R=process.stdin.isTTY&&process.stdout.isTTY&&!a;if(c&&Te(c,d),!d&&R){let y=S.length>1?S:v.filter(k=>k.available);y.forEach((k,$)=>console.log(`${$+1}. ${D[k.source]} ${k.root}${k.capabilities.history?"":` (${k.reason})`}`));let b=qe({input:process.stdin,output:process.stdout});try{d=y[Number(await b.question("Choose a source: "))-1]}finally{b.close()}}if(!d?.capabilities.history)throw new Error(d?.reason??(S.length>1?"Multiple source instances found. Select the exact --source-path or use interactive setup.":"Select --source and optionally --source-path."));let N=E(t,"range")||"week";if(!c&&R&&!t.range){let y=qe({input:process.stdin,output:process.stdout});try{N=(await y.question("History: day, week, or all [week]: ")).trim()||"week"}finally{y.close()}}if(!["day","week","all"].includes(N))throw new Error("--range must be day, week or all.");let i=c?c.since:N==="all"?null:new Date(Date.now()-(N==="day"?1:7)*864e5).toISOString(),f=await M(d,{since:i??void 0,limit:100});a||console.log(`Found ${f.items.length}${f.nextCursor?"+":""} sessions in ${d.root}. History: ${c?i?`since ${i}`:"all":N}.`);let h=!H(t.once),n=E(t,"project");if(!H(t.yes)&&(!R||!await W(`Sync this source to ${n||"your personal Imported conversations Project"} and ${h?"keep syncing":"import once"}?`,!0)))throw new Error("Connection was not approved. No history was uploaded.");let m=await Oe(d,t),C=new F(m),w=E(t,"connection")||`sync-${T([m.baseUrl,m.teamId,d.instanceId,n||"default"]).slice(0,40)}`;c&&await $e(r,c);let x=(await C.list()).items.find(y=>y.id===w),O=await C.register({id:w,source:d.source,machineId:u,sourceInstanceId:d.instanceId,sourceLabel:D[d.source],sourceRoot:d.root,destination:n?{kind:"existing",projectId:n}:{kind:"new",name:"Imported conversations"},since:i,keepSyncing:h,expectedRevision:x?.revision??0});await z(r,{id:O.id,teamId:m.teamId,apiBaseUrl:m.baseUrl,account:m.account,accountBaseUrl:m.accountBaseUrl,source:d,projectId:O.projectId,revision:O.revision,requestedSyncRevision:O.requestedSyncRevision,completedSyncRevision:O.completedSyncRevision,since:i,keepSyncing:h,state:O.state}),await te({directory:r,executable:process.execPath,args:[process.argv[1]],environment:He()}),await se(r),g({connection:O,service:await P(r)}),R&&!H(t.detach)&&await Ae({directory:r,connectionId:w,keepSyncing:h,async pause(){let y=await B.open(r),b;try{b=y.connections().find(q=>q.id===w)}finally{y.close()}if(!b)throw new Error("The connection is unavailable.");let{sync:k}=await K(b),$=await k.control({id:b.id,expectedRevision:b.revision,action:"pause"});await z(r,{...b,revision:$.revision,state:$.state})}})}p(is,"runImportCommand");function He(){return{...process.env.OPENPOND_HOME?{OPENPOND_HOME:process.env.OPENPOND_HOME}:{},...process.env.ELECTRON_RUN_AS_NODE==="1"?{ELECTRON_RUN_AS_NODE:"1"}:{}}}p(He,"collectorEnvironment");export{is as runImportCommand};
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import"./chunk-XBCIBAXD.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import{a as u,c as A,d as x,i as v,j as S,k as R}from"./chunk-JEVA7YQL.js";import"./chunk-6FA3GG5B.js";import"./chunk-N3DEA6PG.js";import{c as B}from"./chunk-PA7XP42P.js";import{c as U,d as C,f as O}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-RLZPX4YP.js";import"./chunk-Q4H3NUVW.js";import{f as m}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import"./chunk-2SPZYBDN.js";import"./chunk-QXVIIM4T.js";import{d as k}from"./chunk-R3XFY7VL.js";import"./chunk-GLUWATL5.js";import"./chunk-YL6VFJ4P.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import{L as y}from"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as i}from"./chunk-FTQLQJQV.js";import{randomUUID as b}from"node:crypto";async function G(r,t){let e=t[0]||"smoke",n=await k(),l=await B(n,O(n)),c=P(n,r);if(e==="provider-catalog"||e==="providers-catalog"||e==="catalog"){let a=await E({apiBaseUrl:c,token:l});console.log(JSON.stringify(a,null,2));return}if(e==="models"||e==="model-list"){let a=await A({apiBaseUrl:c,token:l});console.log(JSON.stringify(a,null,2));return}if(e==="model"||e==="model-get"){let a=t[1]||o(r,"model");if(!a)throw new Error("usage: opchat model <model>");let p=await x({apiBaseUrl:c,token:l,model:a});console.log(JSON.stringify(p,null,2));return}if(e==="chat"){let a=o(r,"model")||"openpond-chat",p=o(r,"effort"),f=p?y.parse(p):void 0,d=o(r,"message")||o(r,"prompt")||"Reply with a short confirmation from OpChat.";if(!m(r.stream)){let s=await v({apiBaseUrl:c,token:l,model:a,reasoningEffort:f,messages:[{role:"user",content:d}]});console.log(JSON.stringify(s,null,2));return}let g="",h=null,w=null;for await(let s of S({apiBaseUrl:c,token:l,model:a,reasoningEffort:f,messages:[{role:"user",content:d}]}))s.type==="text_delta"?(g+=s.text,process.stdout.write(s.text)):s.type==="finish"?h=s.finishReason:s.type==="usage"&&(w=s.usage);process.stdout.write(`
2
+ import"./chunk-GS2NKNKG.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import{a as u,c as A,d as x,i as v,j as S,k as R}from"./chunk-JEVA7YQL.js";import"./chunk-6FA3GG5B.js";import"./chunk-N3DEA6PG.js";import{c as B}from"./chunk-PA7XP42P.js";import{c as U,d as C,f as O}from"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-YJ4PNAST.js";import"./chunk-AH22RHPS.js";import{f as m}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import"./chunk-2SPZYBDN.js";import"./chunk-QXVIIM4T.js";import{d as k}from"./chunk-R3XFY7VL.js";import"./chunk-GLUWATL5.js";import"./chunk-YL6VFJ4P.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import{L as y}from"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as i}from"./chunk-FTQLQJQV.js";import{randomUUID as b}from"node:crypto";async function G(r,t){let e=t[0]||"smoke",n=await k(),l=await B(n,O(n)),c=P(n,r);if(e==="provider-catalog"||e==="providers-catalog"||e==="catalog"){let a=await E({apiBaseUrl:c,token:l});console.log(JSON.stringify(a,null,2));return}if(e==="models"||e==="model-list"){let a=await A({apiBaseUrl:c,token:l});console.log(JSON.stringify(a,null,2));return}if(e==="model"||e==="model-get"){let a=t[1]||o(r,"model");if(!a)throw new Error("usage: opchat model <model>");let p=await x({apiBaseUrl:c,token:l,model:a});console.log(JSON.stringify(p,null,2));return}if(e==="chat"){let a=o(r,"model")||"openpond-chat",p=o(r,"effort"),f=p?y.parse(p):void 0,d=o(r,"message")||o(r,"prompt")||"Reply with a short confirmation from OpChat.";if(!m(r.stream)){let s=await v({apiBaseUrl:c,token:l,model:a,reasoningEffort:f,messages:[{role:"user",content:d}]});console.log(JSON.stringify(s,null,2));return}let g="",h=null,w=null;for await(let s of S({apiBaseUrl:c,token:l,model:a,reasoningEffort:f,messages:[{role:"user",content:d}]}))s.type==="text_delta"?(g+=s.text,process.stdout.write(s.text)):s.type==="finish"?h=s.finishReason:s.type==="usage"&&(w=s.usage);process.stdout.write(`
3
3
  `),console.log(JSON.stringify({finishReason:h,usage:w,text:g},null,2));return}if(e==="smoke"){let a=await R({apiBaseUrl:c,token:l,defaultModel:o(r,"model")||void 0,compatibilityModel:o(r,"compatibilityModel")||o(r,"compatModel")||void 0,skipStream:m(r.skipStream),skipTool:m(r.skipTool),log:i(p=>console.log(p),"log")});m(r.json)&&console.log(JSON.stringify(a,null,2));return}throw new Error("usage: opchat <provider-catalog|models|model|chat|smoke> [--opchat-api-base-url <url>] [chat --model <id> --effort <off|low|medium|high|xhigh|max>]")}i(G,"runOpChatCommand");async function E(r){let t=r.apiBaseUrl.trim().replace(/\/+$/,"");if(!t)throw new Error("OpChat API base URL is required.");let e=r.token.trim();if(!e)throw new Error("OpenPond API key is required.");let n=await fetch(`${t}/provider-catalog`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json","Content-Type":"application/json","x-openpond-client":"openpond-cli","x-openpond-request-id":b()}});if(!n.ok)throw new Error(`Hosted provider catalog failed: ${n.status} ${await T(n)}`);return n.json()}i(E,"getOpChatProviderCatalog");async function T(r){let t=await r.text().catch(()=>"");if(!t)return r.statusText||`HTTP ${r.status}`;try{let e=JSON.parse(t);if(typeof e.message=="string")return e.message;if(typeof e.error=="string")return e.error;if(e.error&&typeof e.error=="object"&&!Array.isArray(e.error)){let n=e.error;return[n.code,n.message].filter(Boolean).join(": ")||t}return t}catch{return t}}i(T,"readResponseError");function P(r,t){let e=o(t,"opchatApiBaseUrl")||o(t,"opchatApiBaseurl")||o(t,"opChatApiBaseUrl")||o(t,"opChatApiBaseurl")||o(t,"opchatApiUrl")||o(t,"opChatApiUrl");return e?u({opChatApiBaseUrl:e}):u({apiBaseUrl:U(t)||r.apiBaseUrl,chatApiBaseUrl:C(t)||r.chatApiBaseUrl})}i(P,"resolveOpChatCliBaseUrl");function o(r,t){let e=r[t];return typeof e=="string"?e.trim():""}i(o,"optionString");export{G as runOpChatCommand};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-XDMUD4FW.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import{m as B}from"./chunk-N3DEA6PG.js";import"./chunk-PA7XP42P.js";import"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-RLZPX4YP.js";import"./chunk-Q4H3NUVW.js";import{a as E,f as b,h as k,i as _}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import"./chunk-2SPZYBDN.js";import"./chunk-QXVIIM4T.js";import"./chunk-R3XFY7VL.js";import"./chunk-GLUWATL5.js";import"./chunk-YL6VFJ4P.js";import{d as x,e as C}from"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as o}from"./chunk-FTQLQJQV.js";import{createHash as ie,randomBytes as ae}from"node:crypto";import{createServer as le}from"node:http";var Se=new URL(C).hostname,Ee=new URL(x).hostname,_e=`${C}/opchat/v1`;import{spawn as se}from"node:child_process";function M(e,t=process.platform){return t==="darwin"?{command:"open",args:[e]}:t==="win32"?{command:"rundll32.exe",args:["url.dll,FileProtocolHandler",e]}:{command:"xdg-open",args:[e]}}o(M,"resolveSystemBrowserCommand");async function S(e,t={}){let n=t.command??M(e),s=t.handoffTimeoutMs??1500;return new Promise(u=>{let r=!1,i=null,c=o(a=>{r||(r=!0,i&&clearTimeout(i),u(a))},"finish"),p=se(n.command,n.args,{detached:!1,shell:!1,stdio:"ignore",windowsHide:!0});p.once("error",a=>{let l=a.code;c({opened:!1,error:l?`browser launcher ${n.command} failed (${l})`:`browser launcher ${n.command} failed`})}),p.once("close",(a,l)=>{if(a===0){c({opened:!0});return}let d=l?`signal ${l}`:`code ${a??"unknown"}`;c({opened:!1,error:`browser launcher ${n.command} exited with ${d}`})}),i=setTimeout(()=>{p.unref(),c({opened:!0})},s),i.unref()})}o(S,"openUrlWithSystemBrowser");function ce(e){return[e.slug,`team=${e.teamId}`,`role=${e.role}`,`status=${e.status}`,e.displayName].join(" ")}o(ce,"formatOrganizationLine");function ue(e){return[e.email??e.userId,`user=${e.userId}`,`role=${e.role}`,e.createdAt].join(" ")}o(ue,"formatOrganizationMemberLine");function de(e){return e?[e.slug,`team=${e.teamId}`,`status=${e.status}`,`tools=${e.toolset.join(",")||"-"}`,e.resourceUrl].join(" "):"no mcp server configured"}o(de,"formatOrganizationMcpServerLine");var pe=["estimate.read","estimate.write","estimate.execute","artifacts.read","artifacts.write"];function O(e){let t=e.trim().replace(/\/$/,"");if(!t)throw new Error("MCP resource URL must be non-empty");return new URL(t).toString().replace(/\/$/,"")}o(O,"normalizeMcpResourceUrl");function N(e,t){let n=typeof t.resourceUrl=="string"&&t.resourceUrl.trim()?t.resourceUrl.trim():typeof t.url=="string"&&t.url.trim()?t.url.trim():"";if(n)return O(n);if(!e?.resourceUrl)throw new Error("organization does not have an MCP server; run organizations mcp-generate first");return O(e.resourceUrl)}o(N,"resolveMcpProbeResourceUrl");function D(e,t){let n=typeof t.origin=="string"&&t.origin.trim()?t.origin.trim():"";return n?O(n):new URL(e).origin}o(D,"resolveMcpProbeOrigin");function $(e=32){return ae(e).toString("base64url")}o($,"randomOauthToken");function me(e){return ie("sha256").update(e).digest("base64url")}o(me,"buildMcpOauthPkceChallenge");function fe(e){let t=typeof e.scope=="string"&&e.scope.trim()?e.scope:typeof e.scopes=="string"&&e.scopes.trim()?e.scopes:"";if(!t)return[...pe];let n=t.split(/[,\s]+/g).map(s=>s.trim()).filter(Boolean);if(n.length===0)throw new Error("scope must include at least one OAuth scope");return n}o(fe,"parseMcpOAuthScopes");function ge(e){let t=typeof e.clientId=="string"&&e.clientId.trim()?e.clientId.trim():"openpond-code-mcp-proof";if(t==="true")throw new Error("client-id must be a non-empty value");return t}o(ge,"resolveMcpOAuthClientId");function he(e){let t=k(e.timeoutSeconds,"timeout-seconds")??k(e.timeout,"timeout")??180;if(t<=0)throw new Error("timeout must be greater than zero");return t*1e3}o(he,"resolveMcpOAuthTimeoutMs");function ye(e){let t=k(e.callbackPort,"callback-port")??0;if(t<0||t>65535)throw new Error("callback-port must be between 0 and 65535");return t}o(ye,"resolveMcpOAuthCallbackPort");function j(e){return new Promise((t,n)=>{e.close(s=>{s?n(s):t()})})}o(j,"closeServer");async function Pe(e){let t=!1,n=null,s=null,u=null,r=new Promise((a,l)=>{s=a,u=l}),i=o((a,l,d,m,f)=>{if(t){a.writeHead(204).end();return}t=!0,a.writeHead(l,{"cache-control":"no-store","content-type":"text/html; charset=utf-8"}),a.end(d),n&&clearTimeout(n),m?s?.(m):u?.(f??new Error("oauth_callback_failed"))},"settle"),c=le((a,l)=>{let d=a.headers.host??"127.0.0.1",m=new URL(a.url??"/",`http://${d}`);if(m.pathname!=="/callback"){l.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),l.end("Not found");return}let f=m.searchParams.get("state")??"",g=m.searchParams.get("error")??"",P=m.searchParams.get("code")??"";if(f!==e.expectedState){i(l,400,"<!doctype html><title>OpenPond OAuth failed</title><p>State mismatch. Return to the terminal and retry.</p>",void 0,new Error("oauth_state_mismatch"));return}if(g){i(l,400,"<!doctype html><title>OpenPond OAuth denied</title><p>Authorization was not completed. Return to the terminal.</p>",void 0,new Error(`oauth_authorization_failed:${g}`));return}if(!P){i(l,400,"<!doctype html><title>OpenPond OAuth failed</title><p>Missing authorization code. Return to the terminal and retry.</p>",void 0,new Error("oauth_code_missing"));return}i(l,200,"<!doctype html><title>OpenPond OAuth complete</title><p>Authorization complete. You can return to the terminal.</p>",{code:P,state:f})});await new Promise((a,l)=>{let d=o(f=>{c.off("listening",m),l(f)},"onError"),m=o(()=>{c.off("error",d),a()},"onListening");c.once("error",d),c.once("listening",m),c.listen(e.port,"127.0.0.1")});let p=c.address();if(!p||typeof p.port!="number")throw await j(c),new Error("oauth_callback_listener_failed");return n=setTimeout(()=>{t||(t=!0,u?.(new Error("oauth_callback_timeout")))},e.timeoutMs),{close:o(async()=>{n&&clearTimeout(n),await j(c).catch(()=>{})},"close"),redirectUri:`http://127.0.0.1:${p.port}/callback`,waitForCallback:o(()=>r,"waitForCallback")}}o(Pe,"startMcpOAuthCallbackListener");function we(e){S(e)}o(we,"openUrlWithSystemBrowser");function Ae(e){let t=new URL(e.authorizationEndpoint);return t.searchParams.set("response_type","code"),t.searchParams.set("client_id",e.clientId),t.searchParams.set("redirect_uri",e.redirectUri),t.searchParams.set("code_challenge",e.codeChallenge),t.searchParams.set("code_challenge_method","S256"),t.searchParams.set("resource",e.resourceUrl),t.searchParams.set("scope",e.scopes.join(" ")),t.searchParams.set("state",e.state),t.toString()}o(Ae,"buildMcpOAuthAuthorizeUrl");async function Oe(e){let t=new URLSearchParams;t.set("grant_type","authorization_code"),t.set("client_id",e.clientId),t.set("redirect_uri",e.redirectUri),t.set("code",e.code),t.set("code_verifier",e.codeVerifier);let n=await fetch(`${e.origin}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:t}),s=await J(n);if(!n.ok)throw new Error(`oauth_token_exchange_failed:${n.status}:${JSON.stringify(s)}`);if(!s||typeof s!="object"||Array.isArray(s))throw new Error("oauth_token_exchange_invalid_response");let u=s;if(typeof u.access_token!="string"||!u.access_token.trim())throw new Error("oauth_token_exchange_missing_access_token");return{access_token:u.access_token,...typeof u.expires_in=="number"?{expires_in:u.expires_in}:{},...typeof u.refresh_token=="string"?{refresh_token:u.refresh_token}:{},...typeof u.scope=="string"?{scope:u.scope}:{},...typeof u.token_type=="string"?{token_type:u.token_type}:{}}}o(Oe,"exchangeMcpOAuthAuthorizationCode");async function J(e){let t=await e.text().catch(()=>"");if(!t)return null;let n=t.trim();if((e.headers.get("content-type")??"").toLowerCase().includes("application/json")||n.startsWith("{")||n.startsWith("["))try{return JSON.parse(n)}catch{return t}return t}o(J,"readMcpProbeBody");async function U(e,t={}){let n=await fetch(e,t);return{url:e,status:n.status,ok:n.ok,headers:{contentType:n.headers.get("content-type"),location:n.headers.get("location"),wwwAuthenticate:n.headers.get("www-authenticate")},body:await J(n)}}o(U,"fetchMcpProbe");function be(e,t,n){return n?{jsonrpc:"2.0",id:e,method:t,params:n}:{jsonrpc:"2.0",id:e,method:t}}o(be,"buildMcpJsonRpcRequest");function F(e){let t=typeof e.arguments=="string"&&e.arguments.trim()?e.arguments:typeof e.args=="string"&&e.args.trim()?e.args:"";if(!t)return{};let n=E(t,"arguments");if(!n||typeof n!="object"||Array.isArray(n))throw new Error("arguments must be a JSON object");return n}o(F,"parseMcpToolArguments");async function R(e){let t={"content-type":"application/json"};return e.accessToken&&(t.authorization=`Bearer ${e.accessToken}`),U(e.resourceUrl,{method:"POST",headers:t,body:JSON.stringify(be(e.id,e.method,e.params))})}o(R,"postMcpJsonRpcProbe");async function q(e){let t=O(e.resourceUrl),n=O(e.origin),s=`${t}/.well-known/oauth-protected-resource`,u=`${n}/.well-known/oauth-authorization-server`,[r,i,c,p,a,l,d]=await Promise.all([U(s),U(u),U(t),R({resourceUrl:t,id:1,method:"initialize"}),R({resourceUrl:t,id:2,method:"tools/list"}),R({resourceUrl:t,id:3,method:"tools/call",params:{name:e.toolName,arguments:e.toolArguments}}),e.accessToken?R({resourceUrl:t,id:4,method:"tools/call",params:{name:e.toolName,arguments:e.toolArguments},accessToken:e.accessToken}):Promise.resolve(null)]);return{resourceUrl:t,origin:n,protectedResource:r,authorizationServer:i,directGetChallenge:c,initialize:p,toolsList:a,unauthenticatedToolCall:l,...d?{authenticatedToolCall:d}:{}}}o(q,"probeOrganizationMcp");function ke(e){let t=typeof e=="string"?e.trim():"";if(t==="owner"||t==="admin"||t==="member")return t;throw new Error("role must be owner, admin, or member")}o(ke,"parseOrganizationRole");function xe(e){let t=typeof e.displayName=="string"&&e.displayName.trim()?e.displayName.trim():typeof e.name=="string"&&e.name.trim()?e.name.trim():"";if(!t)throw new Error("usage: organizations create --name <name> [--slug <slug>]");return{displayName:t,...typeof e.slug=="string"&&e.slug.trim()?{slug:e.slug.trim()}:{},...typeof e.primaryContactEmail=="string"&&e.primaryContactEmail.trim()?{primaryContactEmail:e.primaryContactEmail.trim()}:{},...typeof e.customDomain=="string"&&e.customDomain.trim()?{customDomain:e.customDomain.trim()}:{}}}o(xe,"buildOrganizationCreateInput");function Ce(e){let t={},n=typeof e.displayName=="string"&&e.displayName.trim()?e.displayName.trim():typeof e.name=="string"&&e.name.trim()?e.name.trim():"";if(n&&(t.displayName=n),typeof e.slug=="string"&&e.slug.trim()&&(t.slug=e.slug.trim()),typeof e.primaryContactEmail=="string"&&(t.primaryContactEmail=e.primaryContactEmail.trim()||null),typeof e.customDomain=="string"&&(t.customDomain=e.customDomain.trim()||null),typeof e.status=="string"&&e.status.trim()){let s=e.status.trim();if(s!=="active"&&s!=="disabled"&&s!=="archived")throw new Error("status must be active, disabled, or archived");t.status=s}if(Object.keys(t).length===0)throw new Error("organizations update requires at least one changed field");return t}o(Ce,"buildOrganizationUpdateInput");function Re(e){let t=typeof e.email=="string"?e.email.trim():"";if(!t)throw new Error("usage: organizations member-upsert <slug> --email <email> --role <role>");return{email:t,role:ke(e.role)}}o(Re,"buildOrganizationMemberInput");function Ue(e){return{...typeof e.origin=="string"&&e.origin.trim()?{origin:e.origin.trim()}:{},...typeof e.toolset=="string"&&e.toolset.trim()?{toolset:_(e.toolset)}:{}}}o(Ue,"buildOrganizationMcpGenerateInput");async function yo(e,t){let n=t[0]||"list",s=await B(e),u=b(e.json);if(n==="list"){let r=await s.listOrganizations();if(u){console.log(JSON.stringify({organizations:r},null,2));return}if(r.length===0){console.log("no organizations found");return}for(let i of r)console.log(ce(i));return}if(n==="create"){let r=await s.createOrganization(xe(e));console.log(JSON.stringify({organization:r},null,2));return}if(n==="get"){let r=t[1];if(!r)throw new Error("usage: organizations get <slug>");let i=await s.getOrganization(r);console.log(JSON.stringify({organization:i},null,2));return}if(n==="update"){let r=t[1];if(!r)throw new Error("usage: organizations update <slug> [--name <name>]");let i=await s.updateOrganization(r,Ce(e));console.log(JSON.stringify({organization:i},null,2));return}if(n==="members"||n==="member-list"){let r=t[1];if(!r)throw new Error("usage: organizations members <slug>");let i=await s.listOrganizationMembers(r);if(u){console.log(JSON.stringify({members:i},null,2));return}if(i.length===0){console.log("no organization members found");return}for(let c of i)console.log(ue(c));return}if(n==="member-upsert"||n==="member-add"){let r=t[1];if(!r)throw new Error("usage: organizations member-upsert <slug> --email <email> --role <role>");let i=await s.upsertOrganizationMember(r,Re(e));console.log(JSON.stringify({member:i},null,2));return}if(n==="mcp-get"||n==="mcp-server"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-get <slug>");let i=await s.getOrganizationMcpServer(r);if(u){console.log(JSON.stringify({mcpServer:i},null,2));return}console.log(de(i));return}if(n==="mcp-generate"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-generate <slug> [--origin <url>]");let i=await s.generateOrganizationMcpServer(r,Ue(e));console.log(JSON.stringify({mcpServer:i},null,2));return}if(n==="mcp-probe"||n==="mcp-inspect"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-probe <slug> [--origin <url>] [--tool <name>] [--arguments <json>] [--access-token <token>]");let i=await s.getOrganizationMcpServer(r),c=N(i,e),p=D(c,e),a=typeof e.tool=="string"&&e.tool.trim()?e.tool.trim():typeof e.toolName=="string"&&e.toolName.trim()?e.toolName.trim():"estimate_search_history",l=F(e),d=typeof e.accessToken=="string"&&e.accessToken.trim()?e.accessToken.trim():"",m=await q({resourceUrl:c,origin:p,toolName:a,toolArguments:l,...d?{accessToken:d}:{}});console.log(JSON.stringify({mcpServer:i,probe:m},null,2));return}if(n==="mcp-authorize"||n==="mcp-oauth"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-authorize <slug> [--origin <url>] [--scope <csv|space>] [--tool <name>] [--arguments <json>] [--open]");let i=await s.getOrganizationMcpServer(r),c=N(i,e),p=D(c,e),a=ge(e),l=fe(e),d=$(18),m=$(48),f=me(m),g=await Pe({expectedState:d,port:ye(e),timeoutMs:he(e)}),P=Ae({authorizationEndpoint:`${p}/oauth/authorize`,clientId:a,codeChallenge:f,redirectUri:g.redirectUri,resourceUrl:c,scopes:l,state:d});if(console.error("Open this URL to authorize the organization MCP connection:"),console.error(P),console.error(`Waiting for OAuth callback on ${g.redirectUri}`),b(e.open))try{we(P)}catch(w){console.error(`Unable to open a browser automatically: ${w instanceof Error?w.message:String(w)}`)}try{let w=await g.waitForCallback(),h=await Oe({clientId:a,code:w.code,codeVerifier:m,origin:p,redirectUri:g.redirectUri}),K=typeof e.tool=="string"&&e.tool.trim()?e.tool.trim():typeof e.toolName=="string"&&e.toolName.trim()?e.toolName.trim():"estimate_search_history",G=F(e),W=await q({accessToken:h.access_token,origin:p,resourceUrl:c,toolArguments:G,toolName:K}),V=b(e.printToken);console.log(JSON.stringify({mcpServer:i,oauth:{accessTokenReceived:!0,clientId:a,expiresIn:h.expires_in??null,refreshTokenReceived:!!h.refresh_token,scope:h.scope??l.join(" "),tokenType:h.token_type??"Bearer",...V?{accessToken:h.access_token,refreshToken:h.refresh_token??null}:{}},probe:W},null,2))}finally{await g.close()}return}if(n==="mcp-rotate"||n==="mcp-disable"||n==="mcp-enable"){let r=t[1];if(!r)throw new Error(`usage: organizations ${n} <slug>`);let i=n==="mcp-rotate"?await s.rotateOrganizationMcpServer(r):n==="mcp-disable"?await s.disableOrganizationMcpServer(r):await s.enableOrganizationMcpServer(r);console.log(JSON.stringify({mcpServer:i},null,2));return}throw new Error("usage: organizations <list|create|get|update|members|member-upsert|mcp-get|mcp-generate|mcp-probe|mcp-authorize|mcp-rotate|mcp-disable|mcp-enable> [args]")}o(yo,"runOrganizationsCommand");export{pe as DEFAULT_MCP_AUTHORIZE_SCOPES,be as buildMcpJsonRpcRequest,Ae as buildMcpOAuthAuthorizeUrl,me as buildMcpOauthPkceChallenge,xe as buildOrganizationCreateInput,Ue as buildOrganizationMcpGenerateInput,Re as buildOrganizationMemberInput,Ce as buildOrganizationUpdateInput,j as closeServer,Oe as exchangeMcpOAuthAuthorizationCode,U as fetchMcpProbe,ce as formatOrganizationLine,de as formatOrganizationMcpServerLine,ue as formatOrganizationMemberLine,O as normalizeMcpResourceUrl,we as openUrlWithSystemBrowser,fe as parseMcpOAuthScopes,F as parseMcpToolArguments,ke as parseOrganizationRole,R as postMcpJsonRpcProbe,q as probeOrganizationMcp,$ as randomOauthToken,J as readMcpProbeBody,ye as resolveMcpOAuthCallbackPort,ge as resolveMcpOAuthClientId,he as resolveMcpOAuthTimeoutMs,D as resolveMcpProbeOrigin,N as resolveMcpProbeResourceUrl,yo as runOrganizationsCommand,Pe as startMcpOAuthCallbackListener};
2
+ import"./chunk-HA7EFTPF.js";import"./chunk-L3KS6MOV.js";import"./chunk-2JO2KWT3.js";import"./chunk-IKWDL3RB.js";import"./chunk-6MI4KKWF.js";import"./chunk-QRWPEW3Z.js";import"./chunk-6FA3GG5B.js";import{m as B}from"./chunk-N3DEA6PG.js";import"./chunk-PA7XP42P.js";import"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-YJ4PNAST.js";import"./chunk-AH22RHPS.js";import{a as E,f as b,h as k,i as _}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import"./chunk-2SPZYBDN.js";import"./chunk-QXVIIM4T.js";import"./chunk-R3XFY7VL.js";import"./chunk-GLUWATL5.js";import"./chunk-YL6VFJ4P.js";import{d as x,e as C}from"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as o}from"./chunk-FTQLQJQV.js";import{createHash as ie,randomBytes as ae}from"node:crypto";import{createServer as le}from"node:http";var Se=new URL(C).hostname,Ee=new URL(x).hostname,_e=`${C}/opchat/v1`;import{spawn as se}from"node:child_process";function M(e,t=process.platform){return t==="darwin"?{command:"open",args:[e]}:t==="win32"?{command:"rundll32.exe",args:["url.dll,FileProtocolHandler",e]}:{command:"xdg-open",args:[e]}}o(M,"resolveSystemBrowserCommand");async function S(e,t={}){let n=t.command??M(e),s=t.handoffTimeoutMs??1500;return new Promise(u=>{let r=!1,i=null,c=o(a=>{r||(r=!0,i&&clearTimeout(i),u(a))},"finish"),p=se(n.command,n.args,{detached:!1,shell:!1,stdio:"ignore",windowsHide:!0});p.once("error",a=>{let l=a.code;c({opened:!1,error:l?`browser launcher ${n.command} failed (${l})`:`browser launcher ${n.command} failed`})}),p.once("close",(a,l)=>{if(a===0){c({opened:!0});return}let d=l?`signal ${l}`:`code ${a??"unknown"}`;c({opened:!1,error:`browser launcher ${n.command} exited with ${d}`})}),i=setTimeout(()=>{p.unref(),c({opened:!0})},s),i.unref()})}o(S,"openUrlWithSystemBrowser");function ce(e){return[e.slug,`team=${e.teamId}`,`role=${e.role}`,`status=${e.status}`,e.displayName].join(" ")}o(ce,"formatOrganizationLine");function ue(e){return[e.email??e.userId,`user=${e.userId}`,`role=${e.role}`,e.createdAt].join(" ")}o(ue,"formatOrganizationMemberLine");function de(e){return e?[e.slug,`team=${e.teamId}`,`status=${e.status}`,`tools=${e.toolset.join(",")||"-"}`,e.resourceUrl].join(" "):"no mcp server configured"}o(de,"formatOrganizationMcpServerLine");var pe=["estimate.read","estimate.write","estimate.execute","artifacts.read","artifacts.write"];function O(e){let t=e.trim().replace(/\/$/,"");if(!t)throw new Error("MCP resource URL must be non-empty");return new URL(t).toString().replace(/\/$/,"")}o(O,"normalizeMcpResourceUrl");function N(e,t){let n=typeof t.resourceUrl=="string"&&t.resourceUrl.trim()?t.resourceUrl.trim():typeof t.url=="string"&&t.url.trim()?t.url.trim():"";if(n)return O(n);if(!e?.resourceUrl)throw new Error("organization does not have an MCP server; run organizations mcp-generate first");return O(e.resourceUrl)}o(N,"resolveMcpProbeResourceUrl");function D(e,t){let n=typeof t.origin=="string"&&t.origin.trim()?t.origin.trim():"";return n?O(n):new URL(e).origin}o(D,"resolveMcpProbeOrigin");function $(e=32){return ae(e).toString("base64url")}o($,"randomOauthToken");function me(e){return ie("sha256").update(e).digest("base64url")}o(me,"buildMcpOauthPkceChallenge");function fe(e){let t=typeof e.scope=="string"&&e.scope.trim()?e.scope:typeof e.scopes=="string"&&e.scopes.trim()?e.scopes:"";if(!t)return[...pe];let n=t.split(/[,\s]+/g).map(s=>s.trim()).filter(Boolean);if(n.length===0)throw new Error("scope must include at least one OAuth scope");return n}o(fe,"parseMcpOAuthScopes");function ge(e){let t=typeof e.clientId=="string"&&e.clientId.trim()?e.clientId.trim():"openpond-code-mcp-proof";if(t==="true")throw new Error("client-id must be a non-empty value");return t}o(ge,"resolveMcpOAuthClientId");function he(e){let t=k(e.timeoutSeconds,"timeout-seconds")??k(e.timeout,"timeout")??180;if(t<=0)throw new Error("timeout must be greater than zero");return t*1e3}o(he,"resolveMcpOAuthTimeoutMs");function ye(e){let t=k(e.callbackPort,"callback-port")??0;if(t<0||t>65535)throw new Error("callback-port must be between 0 and 65535");return t}o(ye,"resolveMcpOAuthCallbackPort");function j(e){return new Promise((t,n)=>{e.close(s=>{s?n(s):t()})})}o(j,"closeServer");async function Pe(e){let t=!1,n=null,s=null,u=null,r=new Promise((a,l)=>{s=a,u=l}),i=o((a,l,d,m,f)=>{if(t){a.writeHead(204).end();return}t=!0,a.writeHead(l,{"cache-control":"no-store","content-type":"text/html; charset=utf-8"}),a.end(d),n&&clearTimeout(n),m?s?.(m):u?.(f??new Error("oauth_callback_failed"))},"settle"),c=le((a,l)=>{let d=a.headers.host??"127.0.0.1",m=new URL(a.url??"/",`http://${d}`);if(m.pathname!=="/callback"){l.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),l.end("Not found");return}let f=m.searchParams.get("state")??"",g=m.searchParams.get("error")??"",P=m.searchParams.get("code")??"";if(f!==e.expectedState){i(l,400,"<!doctype html><title>OpenPond OAuth failed</title><p>State mismatch. Return to the terminal and retry.</p>",void 0,new Error("oauth_state_mismatch"));return}if(g){i(l,400,"<!doctype html><title>OpenPond OAuth denied</title><p>Authorization was not completed. Return to the terminal.</p>",void 0,new Error(`oauth_authorization_failed:${g}`));return}if(!P){i(l,400,"<!doctype html><title>OpenPond OAuth failed</title><p>Missing authorization code. Return to the terminal and retry.</p>",void 0,new Error("oauth_code_missing"));return}i(l,200,"<!doctype html><title>OpenPond OAuth complete</title><p>Authorization complete. You can return to the terminal.</p>",{code:P,state:f})});await new Promise((a,l)=>{let d=o(f=>{c.off("listening",m),l(f)},"onError"),m=o(()=>{c.off("error",d),a()},"onListening");c.once("error",d),c.once("listening",m),c.listen(e.port,"127.0.0.1")});let p=c.address();if(!p||typeof p.port!="number")throw await j(c),new Error("oauth_callback_listener_failed");return n=setTimeout(()=>{t||(t=!0,u?.(new Error("oauth_callback_timeout")))},e.timeoutMs),{close:o(async()=>{n&&clearTimeout(n),await j(c).catch(()=>{})},"close"),redirectUri:`http://127.0.0.1:${p.port}/callback`,waitForCallback:o(()=>r,"waitForCallback")}}o(Pe,"startMcpOAuthCallbackListener");function we(e){S(e)}o(we,"openUrlWithSystemBrowser");function Ae(e){let t=new URL(e.authorizationEndpoint);return t.searchParams.set("response_type","code"),t.searchParams.set("client_id",e.clientId),t.searchParams.set("redirect_uri",e.redirectUri),t.searchParams.set("code_challenge",e.codeChallenge),t.searchParams.set("code_challenge_method","S256"),t.searchParams.set("resource",e.resourceUrl),t.searchParams.set("scope",e.scopes.join(" ")),t.searchParams.set("state",e.state),t.toString()}o(Ae,"buildMcpOAuthAuthorizeUrl");async function Oe(e){let t=new URLSearchParams;t.set("grant_type","authorization_code"),t.set("client_id",e.clientId),t.set("redirect_uri",e.redirectUri),t.set("code",e.code),t.set("code_verifier",e.codeVerifier);let n=await fetch(`${e.origin}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:t}),s=await J(n);if(!n.ok)throw new Error(`oauth_token_exchange_failed:${n.status}:${JSON.stringify(s)}`);if(!s||typeof s!="object"||Array.isArray(s))throw new Error("oauth_token_exchange_invalid_response");let u=s;if(typeof u.access_token!="string"||!u.access_token.trim())throw new Error("oauth_token_exchange_missing_access_token");return{access_token:u.access_token,...typeof u.expires_in=="number"?{expires_in:u.expires_in}:{},...typeof u.refresh_token=="string"?{refresh_token:u.refresh_token}:{},...typeof u.scope=="string"?{scope:u.scope}:{},...typeof u.token_type=="string"?{token_type:u.token_type}:{}}}o(Oe,"exchangeMcpOAuthAuthorizationCode");async function J(e){let t=await e.text().catch(()=>"");if(!t)return null;let n=t.trim();if((e.headers.get("content-type")??"").toLowerCase().includes("application/json")||n.startsWith("{")||n.startsWith("["))try{return JSON.parse(n)}catch{return t}return t}o(J,"readMcpProbeBody");async function U(e,t={}){let n=await fetch(e,t);return{url:e,status:n.status,ok:n.ok,headers:{contentType:n.headers.get("content-type"),location:n.headers.get("location"),wwwAuthenticate:n.headers.get("www-authenticate")},body:await J(n)}}o(U,"fetchMcpProbe");function be(e,t,n){return n?{jsonrpc:"2.0",id:e,method:t,params:n}:{jsonrpc:"2.0",id:e,method:t}}o(be,"buildMcpJsonRpcRequest");function F(e){let t=typeof e.arguments=="string"&&e.arguments.trim()?e.arguments:typeof e.args=="string"&&e.args.trim()?e.args:"";if(!t)return{};let n=E(t,"arguments");if(!n||typeof n!="object"||Array.isArray(n))throw new Error("arguments must be a JSON object");return n}o(F,"parseMcpToolArguments");async function R(e){let t={"content-type":"application/json"};return e.accessToken&&(t.authorization=`Bearer ${e.accessToken}`),U(e.resourceUrl,{method:"POST",headers:t,body:JSON.stringify(be(e.id,e.method,e.params))})}o(R,"postMcpJsonRpcProbe");async function q(e){let t=O(e.resourceUrl),n=O(e.origin),s=`${t}/.well-known/oauth-protected-resource`,u=`${n}/.well-known/oauth-authorization-server`,[r,i,c,p,a,l,d]=await Promise.all([U(s),U(u),U(t),R({resourceUrl:t,id:1,method:"initialize"}),R({resourceUrl:t,id:2,method:"tools/list"}),R({resourceUrl:t,id:3,method:"tools/call",params:{name:e.toolName,arguments:e.toolArguments}}),e.accessToken?R({resourceUrl:t,id:4,method:"tools/call",params:{name:e.toolName,arguments:e.toolArguments},accessToken:e.accessToken}):Promise.resolve(null)]);return{resourceUrl:t,origin:n,protectedResource:r,authorizationServer:i,directGetChallenge:c,initialize:p,toolsList:a,unauthenticatedToolCall:l,...d?{authenticatedToolCall:d}:{}}}o(q,"probeOrganizationMcp");function ke(e){let t=typeof e=="string"?e.trim():"";if(t==="owner"||t==="admin"||t==="member")return t;throw new Error("role must be owner, admin, or member")}o(ke,"parseOrganizationRole");function xe(e){let t=typeof e.displayName=="string"&&e.displayName.trim()?e.displayName.trim():typeof e.name=="string"&&e.name.trim()?e.name.trim():"";if(!t)throw new Error("usage: organizations create --name <name> [--slug <slug>]");return{displayName:t,...typeof e.slug=="string"&&e.slug.trim()?{slug:e.slug.trim()}:{},...typeof e.primaryContactEmail=="string"&&e.primaryContactEmail.trim()?{primaryContactEmail:e.primaryContactEmail.trim()}:{},...typeof e.customDomain=="string"&&e.customDomain.trim()?{customDomain:e.customDomain.trim()}:{}}}o(xe,"buildOrganizationCreateInput");function Ce(e){let t={},n=typeof e.displayName=="string"&&e.displayName.trim()?e.displayName.trim():typeof e.name=="string"&&e.name.trim()?e.name.trim():"";if(n&&(t.displayName=n),typeof e.slug=="string"&&e.slug.trim()&&(t.slug=e.slug.trim()),typeof e.primaryContactEmail=="string"&&(t.primaryContactEmail=e.primaryContactEmail.trim()||null),typeof e.customDomain=="string"&&(t.customDomain=e.customDomain.trim()||null),typeof e.status=="string"&&e.status.trim()){let s=e.status.trim();if(s!=="active"&&s!=="disabled"&&s!=="archived")throw new Error("status must be active, disabled, or archived");t.status=s}if(Object.keys(t).length===0)throw new Error("organizations update requires at least one changed field");return t}o(Ce,"buildOrganizationUpdateInput");function Re(e){let t=typeof e.email=="string"?e.email.trim():"";if(!t)throw new Error("usage: organizations member-upsert <slug> --email <email> --role <role>");return{email:t,role:ke(e.role)}}o(Re,"buildOrganizationMemberInput");function Ue(e){return{...typeof e.origin=="string"&&e.origin.trim()?{origin:e.origin.trim()}:{},...typeof e.toolset=="string"&&e.toolset.trim()?{toolset:_(e.toolset)}:{}}}o(Ue,"buildOrganizationMcpGenerateInput");async function yo(e,t){let n=t[0]||"list",s=await B(e),u=b(e.json);if(n==="list"){let r=await s.listOrganizations();if(u){console.log(JSON.stringify({organizations:r},null,2));return}if(r.length===0){console.log("no organizations found");return}for(let i of r)console.log(ce(i));return}if(n==="create"){let r=await s.createOrganization(xe(e));console.log(JSON.stringify({organization:r},null,2));return}if(n==="get"){let r=t[1];if(!r)throw new Error("usage: organizations get <slug>");let i=await s.getOrganization(r);console.log(JSON.stringify({organization:i},null,2));return}if(n==="update"){let r=t[1];if(!r)throw new Error("usage: organizations update <slug> [--name <name>]");let i=await s.updateOrganization(r,Ce(e));console.log(JSON.stringify({organization:i},null,2));return}if(n==="members"||n==="member-list"){let r=t[1];if(!r)throw new Error("usage: organizations members <slug>");let i=await s.listOrganizationMembers(r);if(u){console.log(JSON.stringify({members:i},null,2));return}if(i.length===0){console.log("no organization members found");return}for(let c of i)console.log(ue(c));return}if(n==="member-upsert"||n==="member-add"){let r=t[1];if(!r)throw new Error("usage: organizations member-upsert <slug> --email <email> --role <role>");let i=await s.upsertOrganizationMember(r,Re(e));console.log(JSON.stringify({member:i},null,2));return}if(n==="mcp-get"||n==="mcp-server"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-get <slug>");let i=await s.getOrganizationMcpServer(r);if(u){console.log(JSON.stringify({mcpServer:i},null,2));return}console.log(de(i));return}if(n==="mcp-generate"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-generate <slug> [--origin <url>]");let i=await s.generateOrganizationMcpServer(r,Ue(e));console.log(JSON.stringify({mcpServer:i},null,2));return}if(n==="mcp-probe"||n==="mcp-inspect"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-probe <slug> [--origin <url>] [--tool <name>] [--arguments <json>] [--access-token <token>]");let i=await s.getOrganizationMcpServer(r),c=N(i,e),p=D(c,e),a=typeof e.tool=="string"&&e.tool.trim()?e.tool.trim():typeof e.toolName=="string"&&e.toolName.trim()?e.toolName.trim():"estimate_search_history",l=F(e),d=typeof e.accessToken=="string"&&e.accessToken.trim()?e.accessToken.trim():"",m=await q({resourceUrl:c,origin:p,toolName:a,toolArguments:l,...d?{accessToken:d}:{}});console.log(JSON.stringify({mcpServer:i,probe:m},null,2));return}if(n==="mcp-authorize"||n==="mcp-oauth"){let r=t[1];if(!r)throw new Error("usage: organizations mcp-authorize <slug> [--origin <url>] [--scope <csv|space>] [--tool <name>] [--arguments <json>] [--open]");let i=await s.getOrganizationMcpServer(r),c=N(i,e),p=D(c,e),a=ge(e),l=fe(e),d=$(18),m=$(48),f=me(m),g=await Pe({expectedState:d,port:ye(e),timeoutMs:he(e)}),P=Ae({authorizationEndpoint:`${p}/oauth/authorize`,clientId:a,codeChallenge:f,redirectUri:g.redirectUri,resourceUrl:c,scopes:l,state:d});if(console.error("Open this URL to authorize the organization MCP connection:"),console.error(P),console.error(`Waiting for OAuth callback on ${g.redirectUri}`),b(e.open))try{we(P)}catch(w){console.error(`Unable to open a browser automatically: ${w instanceof Error?w.message:String(w)}`)}try{let w=await g.waitForCallback(),h=await Oe({clientId:a,code:w.code,codeVerifier:m,origin:p,redirectUri:g.redirectUri}),K=typeof e.tool=="string"&&e.tool.trim()?e.tool.trim():typeof e.toolName=="string"&&e.toolName.trim()?e.toolName.trim():"estimate_search_history",G=F(e),W=await q({accessToken:h.access_token,origin:p,resourceUrl:c,toolArguments:G,toolName:K}),V=b(e.printToken);console.log(JSON.stringify({mcpServer:i,oauth:{accessTokenReceived:!0,clientId:a,expiresIn:h.expires_in??null,refreshTokenReceived:!!h.refresh_token,scope:h.scope??l.join(" "),tokenType:h.token_type??"Bearer",...V?{accessToken:h.access_token,refreshToken:h.refresh_token??null}:{}},probe:W},null,2))}finally{await g.close()}return}if(n==="mcp-rotate"||n==="mcp-disable"||n==="mcp-enable"){let r=t[1];if(!r)throw new Error(`usage: organizations ${n} <slug>`);let i=n==="mcp-rotate"?await s.rotateOrganizationMcpServer(r):n==="mcp-disable"?await s.disableOrganizationMcpServer(r):await s.enableOrganizationMcpServer(r);console.log(JSON.stringify({mcpServer:i},null,2));return}throw new Error("usage: organizations <list|create|get|update|members|member-upsert|mcp-get|mcp-generate|mcp-probe|mcp-authorize|mcp-rotate|mcp-disable|mcp-enable> [args]")}o(yo,"runOrganizationsCommand");export{pe as DEFAULT_MCP_AUTHORIZE_SCOPES,be as buildMcpJsonRpcRequest,Ae as buildMcpOAuthAuthorizeUrl,me as buildMcpOauthPkceChallenge,xe as buildOrganizationCreateInput,Ue as buildOrganizationMcpGenerateInput,Re as buildOrganizationMemberInput,Ce as buildOrganizationUpdateInput,j as closeServer,Oe as exchangeMcpOAuthAuthorizationCode,U as fetchMcpProbe,ce as formatOrganizationLine,de as formatOrganizationMcpServerLine,ue as formatOrganizationMemberLine,O as normalizeMcpResourceUrl,we as openUrlWithSystemBrowser,fe as parseMcpOAuthScopes,F as parseMcpToolArguments,ke as parseOrganizationRole,R as postMcpJsonRpcProbe,q as probeOrganizationMcp,$ as randomOauthToken,J as readMcpProbeBody,ye as resolveMcpOAuthCallbackPort,ge as resolveMcpOAuthClientId,he as resolveMcpOAuthTimeoutMs,D as resolveMcpProbeOrigin,N as resolveMcpProbeResourceUrl,yo as runOrganizationsCommand,Pe as startMcpOAuthCallbackListener};
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{i as ye,j as K,k as W,r as $e,s as Ce}from"./chunk-NAZ26IZL.js";import{a as Ie}from"./chunk-BX4J2VDU.js";import{a as ue}from"./chunk-L3KS6MOV.js";import{Ca as de}from"./chunk-QRWPEW3Z.js";import"./chunk-X37KMV27.js";import{G as we,I as Pe,J as ke,K as C,e as Q,f as fe,g as X,h as he,i as ge,j as me,q as ee,s as pe,t as Se,x as N}from"./chunk-N5QNXMIS.js";import"./chunk-JDLAHVAJ.js";import"./chunk-EAPFMACH.js";import"./chunk-6FA3GG5B.js";import{m as G}from"./chunk-N3DEA6PG.js";import"./chunk-PA7XP42P.js";import"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-RLZPX4YP.js";import"./chunk-Q4H3NUVW.js";import{c as f,d as B,f as S}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import"./chunk-2SPZYBDN.js";import"./chunk-QXVIIM4T.js";import"./chunk-R3XFY7VL.js";import"./chunk-GLUWATL5.js";import"./chunk-YL6VFJ4P.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import{ra as ie,sa as le,va as ce}from"./chunk-PJM2G7SG.js";import{Da as se,Ma as ae}from"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as i}from"./chunk-FTQLQJQV.js";import{readFile as Ue}from"node:fs/promises";import L from"node:path";import{promises as j}from"node:fs";import b from"node:path";async function oe(e,t){let o=b.join(e,t),n=await j.lstat(o).catch(l=>{if(l.code==="ENOENT")return null;throw l});if(!n)return[];if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`Profile source directory is not a regular directory: ${t}`);let a=[];for(let l of await j.readdir(o,{withFileTypes:!0})){let h=b.join(o,l.name),d=b.relative(e,h).split(b.sep).join("/");if(l.isSymbolicLink())throw new Error(`Profile source contains a symlink: ${d}`);if(l.isDirectory())a.push(...await oe(e,d));else if(l.isFile())a.push(d);else throw new Error(`Profile source contains a non-regular file: ${d}`)}return a.sort()}i(oe,"sourceFiles");async function Re(e,t=new Set){let{skills:o,skillCatalog:n}=await ue(e);if(n.error)throw new Error(`Profile Skills: ${n.error}`);for(let s of o)if(s.validationStatus!=="valid")throw new Error(`Profile Skill ${s.name}: ${s.validationMessages.join(" ")}`);let a=new Set(o.map(s=>s.path)),l=[...await oe(e,"workflows"),...await oe(e,"evals")].sort(),h=l.filter(s=>s.startsWith("workflows/")),d=h.some(s=>/^workflows\/[^/]+\/(PROMPT\.md|ACTION\.json)$/.test(s)),u=h.includes("workflows/catalog.json");if(d&&u)throw new Error("Workflow packages and legacy workflows/catalog.json cannot coexist.");let y=d?ae({files:new Map(await Promise.all(h.map(async s=>[s,await j.readFile(b.join(e,s),"utf8")]))),skillPaths:a,actionIds:t}).catalog:u?se({catalog:JSON.parse(await j.readFile(b.join(e,"workflows/catalog.json"),"utf8")),sourcePaths:a,actionIds:t}):{workflows:[]},$=new Set(y.workflows.map(s=>s.id)),R=l.filter(s=>/^workflows\/[^/]+\/evals\/[^/]+\.json$/.test(s)||/^evals\/definitions\/[^/]+\.json$/.test(s)),w=l.filter(s=>/^evals\/suites\/[^/]+\.json$/.test(s));if(l.includes("evals/catalog.json")&&(R.length||w.length))throw new Error("Evaluation packages and legacy evals/catalog.json cannot coexist.");let v=await Promise.all(R.map(async s=>{let r=ie.parse(JSON.parse(await j.readFile(b.join(e,s),"utf8"))),m=/^workflows\/([^/]+)\/evals\//.exec(s)?.[1];if(m&&(r.target.kind!=="workflow"||r.target.workflowId!==m))throw new Error(`Evaluation ${r.id} must target its containing Workflow ${m}.`);return r})),x=await Promise.all(w.map(async s=>le.parse(JSON.parse(await j.readFile(b.join(e,s),"utf8"))))),_=l.includes("evals/catalog.json")?JSON.parse(await j.readFile(b.join(e,"evals/catalog.json"),"utf8")):{schemaVersion:"openpond.profileEvaluations.v1",definitions:v,suites:x},P=ce({catalog:_,workflowIds:$,skillPaths:a,actionIds:t}).catalog,g=l.filter(s=>/^evals\/tasksets\/[^/]+\.json$/.test(s)),O=new Map;for(let s of g){let r=de(JSON.parse(await j.readFile(b.join(e,s),"utf8"))).taskset;if(s!==`evals/tasksets/${r.contentHash}.json`)throw new Error(`Frozen Taskset file name differs from its content hash: ${s}.`);O.set(r.contentHash,r)}for(let s of P.definitions){let r=s.tasksetRelease.contentHash,m=`evals/tasksets/${r}.json`,H=O.get(r);if(!H)throw new Error(`Evaluation ${s.id} is missing Taskset ${m}.`);if(H.id!==s.tasksetRelease.id||H.contentHash!==r)throw new Error(`Evaluation ${s.id} references a different frozen Taskset.`);let E=new Set(H.tasks.filter(k=>k.split===s.split).map(k=>k.id));for(let k of s.taskIds)if(!E.has(k))throw new Error(`Evaluation ${s.id} references missing Taskset case ${k} in split ${s.split}.`)}return{workflows:y.workflows.length,skills:o.length,evaluations:P.definitions.length,tasksets:O.size}}i(Re,"checkLocalProfileSource");import te from"node:path";async function je(e){if(!e.state.sourcePath)throw new Error("Active OpenPond profile is missing a source path.");let t=e.state.agents.find(s=>s.id===e.agentId);if(!t)throw new Error(`Profile agent not found for hosted materialization: ${e.agentId}`);if(!t.enabled)throw new Error(`Profile agent is disabled: ${e.agentId}`);let o=Me(e.state.sourcePath,t.path),n=await ye(o),a=await K(o,n.entries),l=W(n,a.entries),h=await ze({client:e.client,teamId:e.teamId,projectId:e.projectId??null,profileProjectId:e.profileProjectId,profileName:e.profileName,agentId:e.agentId,localHead:e.localHead,hostedHead:e.hostedHead}),d=await e.client.projects.uploadSource(h.id,{teamId:e.teamId,entries:l.entries,branch:e.sourceRef,commitMessage:`Materialize OpenPond profile agent ${e.agentId}`}),u=await e.client.projects.sync(d.id,{teamId:e.teamId}),y=be(u)??be(d),$=ve(u)??ve(d)??e.sourceRef,R=`openpond-profile-agent:${e.profileProjectId}:${e.profileName}:${e.agentId}`,w=(await e.client.agents.list({teamId:e.teamId})).find(s=>s.externalId===R),v=await e.client.agents.upsert({teamId:e.teamId,projectId:u.id,name:t.name||e.agentId,slug:xe(e.profileName,e.agentId),selectedEntrypoint:Ne(e.state,e.agentId),triggerType:"manual",runtimeSource:{mode:"latest_source",...$?{sourceRef:$}:{},...y?{sourceCommitSha:y}:{}},metadata:{...w?.metadata??{},source:"openpond_profile_agent_materialization",profileProjectId:e.profileProjectId,profileName:e.profileName,profileAgentId:e.agentId,profileSourcePath:t.path,localHead:e.localHead,hostedHead:e.hostedHead},externalId:R}),x=A(a.uploadMetadata),_=A(x?.commands),P=A(x?.dependencySetup),g=_e(P?.commands),O=[I(_?.validate),I(_?.eval)].filter(s=>!!s);return{status:"uploaded",agentId:e.agentId,runtimeAgentId:v.id,projectId:u.id,sourceRoot:o,sourceRef:$,sourceCommitSha:y??null,manifestHash:u.sandboxManifestHash??null,manifestPath:u.sandboxManifestPath??null,manifestSyncedAt:u.sandboxManifestSyncedAt??null,fileCount:l.fileCount,totalBytes:l.totalBytes,generatedManifestPath:a.generatedManifestPath,synthesizedOpenPondYaml:a.synthesizedOpenPondYaml,uploadMetadataPath:a.uploadMetadataPath,setupCommands:g,validationCommands:O,materializedAt:new Date().toISOString()}}i(je,"materializeHostedProfileAgentSource");async function ze(e){if(e.projectId)try{return await e.client.projects.get(e.projectId,{teamId:e.teamId})}catch{}return e.client.projects.upsert({teamId:e.teamId,name:`OpenPond profile ${e.profileName} ${e.agentId}`,sourceType:"manual",externalId:`openpond-profile:${e.profileProjectId}:${e.profileName}:${e.agentId}`,description:`Materialized OpenPond profile agent ${e.agentId} for hosted Team execution.`,metadata:{source:"openpond_profile_agent_materialization",profileProjectId:e.profileProjectId,profileName:e.profileName,profileAgentId:e.agentId,localHead:e.localHead,hostedHead:e.hostedHead}})}i(ze,"getOrCreateHostedSourceProject");function Me(e,t){let o=t.replace(/\\/g,"/"),n=te.resolve(e,o),a=te.relative(e,n);if(a.startsWith("..")||te.isAbsolute(a))throw new Error(`Profile agent path escapes profile source: ${t}`);return o==="agent/agent.ts"||o.endsWith("/agent.ts")?e:n}i(Me,"resolveProfileAgentSourceRoot");function Ne(e,t){let o=e.actionCatalog.find(n=>n.agentId===t&&(n.sourceActionId==="chat"||n.name==="chat"))??e.actionCatalog.find(n=>n.agentId===t);return{scope:"action",name:typeof o?.sourceActionId=="string"&&o.sourceActionId||typeof o?.name=="string"&&o.name||"chat"}}i(Ne,"hostedEntrypointForProfileAgent");function xe(e,t){return`openpond-profile-${e}-${t}`.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"openpond-profile-agent"}i(xe,"hostedRuntimeAgentSlug");function be(e){let t=A(e),o=A(t?.sourceConfig),n=A(t?.metadata);return I(o?.sourceCommitSha)??I(o?.commitSha)??I(o?.remoteSha)??I(n?.projectSourceUploadCommitSha)??I(n?.sourceCommitSha)??I(t?.templateRemoteSha)}i(be,"sandboxProjectSourceCommitSha");function ve(e){let t=A(e),o=A(t?.sourceConfig);return I(o?.sourceRef)??I(o?.branch)??I(t?.gitBranch)??I(t?.defaultBranch)}i(ve,"sandboxProjectSourceRef");function A(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}i(A,"record");function I(e){return typeof e=="string"&&e.trim()?e.trim():null}i(I,"text");function _e(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}i(_e,"stringArray");async function bo(e){let t=await pe({repoPath:f(e,"path")||ee(),profile:f(e,"profile")||"default",template:f(e,"template")||"blank-agent",force:S(e.force)});if(S(e.json)){console.log(JSON.stringify(t,null,2));return}console.log(`Initialized OpenPond profile ${t.activeProfile} at ${t.repoPath}`),console.log(`Profile source: ${t.sourcePath}`)}i(bo,"runOpenPondInitCommand");async function vo(e,t){let o=t[0]??"current";if(o==="load"){let n=f(e,"path")||t[1];if(!n)throw new Error("usage: openpond profile load --path <dir> [--profile <name>]");let a=await Se(n,f(e,"profile")||void 0);if(S(e.json)){console.log(JSON.stringify(a,null,2));return}console.log(`Loaded OpenPond profile ${a.activeProfile} from ${a.repoPath}`);return}if(o==="current"||o==="status"){let n=await N();if(S(e.json)){console.log(JSON.stringify(n,null,2));return}ne(n);return}if(o==="diff"){let n=await N();if(S(e.json)){console.log(JSON.stringify({diff:n.diff,profile:n},null,2));return}Qe(n);return}if(o==="catalog"){let n=await N();if(S(e.json)){console.log(JSON.stringify({catalog:n.catalog,actions:n.actionCatalog,profile:n},null,2));return}Xe(n);return}if(o==="commit"){await Fe(e,t.slice(1));return}if(o==="push"){await Le(e);return}if(o==="check"){let n=f(e,"kind")||t[1]||"all";if(!["all","inspect","build","validate","eval"].includes(n))throw new Error("check kind must be one of inspect, build, validate, eval, all");if(n==="all"||n==="validate"){let a=await N();if(!a.sourcePath)throw new Error("No active Profile source to validate.");let l=await Re(a.sourcePath,new Set(a.actionCatalog.map(h=>h.id)));console.log(`Profile source valid: ${l.workflows} Workflows, ${l.skills} Skills, ${l.evaluations} evaluations, ${l.tasksets} frozen Tasksets.`)}await Pe(n);return}if(o==="ensure-hosted"){await Oe(e);return}if(o==="hosted"){let n=t[1]??"status";if(n==="ensure"){await Oe(e);return}if(n==="status"||n==="current"){await Ye(e);return}throw new Error("usage: openpond profile hosted [status|ensure] --team-id <id> [--json]")}if(o==="agents"){if((t[1]??"list")!=="list")throw new Error("usage: openpond profile agents list [--json]");await Ze(e,["list"]);return}throw new Error("usage: openpond profile <status|diff|catalog|commit|push|load|check|agents|hosted|ensure-hosted> [args]")}i(vo,"runOpenPondProfileCommand");async function Fe(e,t){let o=f(e,"message")||f(e,"commitMessage")||t.join(" ").trim()||void 0,n=await ke(o);if(S(e.json)){console.log(JSON.stringify(n,null,2));return}if(!n.committed){console.log("No profile changes to commit."),ne(n.state);return}console.log("Committed OpenPond profile changes."),n.stdout.trim()&&console.log(n.stdout.trim()),ne(n.state)}i(Fe,"runProfileCommitCommand");async function Le(e){let t=B(e,"usage: openpond profile push"),o=await N();if(o.error)throw new Error(o.error);if(!o.repoPath||!o.sourcePath||!o.manifestPath)throw new Error("No active OpenPond profile. Run `openpond init`.");if(!o.git?.isRepo)throw new Error("Active OpenPond profile source is not Git-backed. Run `openpond init` or reload a Git-backed profile.");if(!o.git.head)throw new Error("Profile source must have a committed Git head before push. Run `openpond profile commit` first.");if(o.git.dirty)throw new Error("Profile source has uncommitted changes. Run `openpond profile commit` before push.");let n=await G(e),a=S(e.ensureHosted)?await n.profile.ensureHosted({teamId:t}):await n.profile.get({teamId:t});if(!a)throw new Error("No hosted OpenPond profile repo found. Run `openpond profile ensure-hosted --team-id <id>` first, or pass `--ensure-hosted` to push.");let l=S(e.force),h=a.sourceUpload?.sourceCommitSha??null,d=o.hosted?.sourceCommitSha??null;if(d&&h!==d&&!l)throw new Error(["Hosted profile source changed since the last local push.",`Last pushed hosted head: ${d}`,`Current hosted head: ${h??"none"}`,"Inspect hosted changes before pushing, or rerun with --force to overwrite explicitly."].join(`
2
+ import{i as ye,j as K,k as W,r as $e,s as Ce}from"./chunk-NAZ26IZL.js";import{a as Ie}from"./chunk-BX4J2VDU.js";import{a as ue}from"./chunk-L3KS6MOV.js";import{Ca as de}from"./chunk-QRWPEW3Z.js";import"./chunk-X37KMV27.js";import{G as we,I as Pe,J as ke,K as C,e as Q,f as fe,g as X,h as he,i as ge,j as me,q as ee,s as pe,t as Se,x as N}from"./chunk-N5QNXMIS.js";import"./chunk-JDLAHVAJ.js";import"./chunk-EAPFMACH.js";import"./chunk-6FA3GG5B.js";import{m as G}from"./chunk-N3DEA6PG.js";import"./chunk-PA7XP42P.js";import"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-YJ4PNAST.js";import"./chunk-AH22RHPS.js";import{c as f,d as B,f as S}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import"./chunk-2SPZYBDN.js";import"./chunk-QXVIIM4T.js";import"./chunk-R3XFY7VL.js";import"./chunk-GLUWATL5.js";import"./chunk-YL6VFJ4P.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import{ra as ie,sa as le,va as ce}from"./chunk-PJM2G7SG.js";import{Da as se,Ma as ae}from"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as i}from"./chunk-FTQLQJQV.js";import{readFile as Ue}from"node:fs/promises";import L from"node:path";import{promises as j}from"node:fs";import b from"node:path";async function oe(e,t){let o=b.join(e,t),n=await j.lstat(o).catch(l=>{if(l.code==="ENOENT")return null;throw l});if(!n)return[];if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`Profile source directory is not a regular directory: ${t}`);let a=[];for(let l of await j.readdir(o,{withFileTypes:!0})){let h=b.join(o,l.name),d=b.relative(e,h).split(b.sep).join("/");if(l.isSymbolicLink())throw new Error(`Profile source contains a symlink: ${d}`);if(l.isDirectory())a.push(...await oe(e,d));else if(l.isFile())a.push(d);else throw new Error(`Profile source contains a non-regular file: ${d}`)}return a.sort()}i(oe,"sourceFiles");async function Re(e,t=new Set){let{skills:o,skillCatalog:n}=await ue(e);if(n.error)throw new Error(`Profile Skills: ${n.error}`);for(let s of o)if(s.validationStatus!=="valid")throw new Error(`Profile Skill ${s.name}: ${s.validationMessages.join(" ")}`);let a=new Set(o.map(s=>s.path)),l=[...await oe(e,"workflows"),...await oe(e,"evals")].sort(),h=l.filter(s=>s.startsWith("workflows/")),d=h.some(s=>/^workflows\/[^/]+\/(PROMPT\.md|ACTION\.json)$/.test(s)),u=h.includes("workflows/catalog.json");if(d&&u)throw new Error("Workflow packages and legacy workflows/catalog.json cannot coexist.");let y=d?ae({files:new Map(await Promise.all(h.map(async s=>[s,await j.readFile(b.join(e,s),"utf8")]))),skillPaths:a,actionIds:t}).catalog:u?se({catalog:JSON.parse(await j.readFile(b.join(e,"workflows/catalog.json"),"utf8")),sourcePaths:a,actionIds:t}):{workflows:[]},$=new Set(y.workflows.map(s=>s.id)),R=l.filter(s=>/^workflows\/[^/]+\/evals\/[^/]+\.json$/.test(s)||/^evals\/definitions\/[^/]+\.json$/.test(s)),w=l.filter(s=>/^evals\/suites\/[^/]+\.json$/.test(s));if(l.includes("evals/catalog.json")&&(R.length||w.length))throw new Error("Evaluation packages and legacy evals/catalog.json cannot coexist.");let v=await Promise.all(R.map(async s=>{let r=ie.parse(JSON.parse(await j.readFile(b.join(e,s),"utf8"))),m=/^workflows\/([^/]+)\/evals\//.exec(s)?.[1];if(m&&(r.target.kind!=="workflow"||r.target.workflowId!==m))throw new Error(`Evaluation ${r.id} must target its containing Workflow ${m}.`);return r})),x=await Promise.all(w.map(async s=>le.parse(JSON.parse(await j.readFile(b.join(e,s),"utf8"))))),_=l.includes("evals/catalog.json")?JSON.parse(await j.readFile(b.join(e,"evals/catalog.json"),"utf8")):{schemaVersion:"openpond.profileEvaluations.v1",definitions:v,suites:x},P=ce({catalog:_,workflowIds:$,skillPaths:a,actionIds:t}).catalog,g=l.filter(s=>/^evals\/tasksets\/[^/]+\.json$/.test(s)),O=new Map;for(let s of g){let r=de(JSON.parse(await j.readFile(b.join(e,s),"utf8"))).taskset;if(s!==`evals/tasksets/${r.contentHash}.json`)throw new Error(`Frozen Taskset file name differs from its content hash: ${s}.`);O.set(r.contentHash,r)}for(let s of P.definitions){let r=s.tasksetRelease.contentHash,m=`evals/tasksets/${r}.json`,H=O.get(r);if(!H)throw new Error(`Evaluation ${s.id} is missing Taskset ${m}.`);if(H.id!==s.tasksetRelease.id||H.contentHash!==r)throw new Error(`Evaluation ${s.id} references a different frozen Taskset.`);let E=new Set(H.tasks.filter(k=>k.split===s.split).map(k=>k.id));for(let k of s.taskIds)if(!E.has(k))throw new Error(`Evaluation ${s.id} references missing Taskset case ${k} in split ${s.split}.`)}return{workflows:y.workflows.length,skills:o.length,evaluations:P.definitions.length,tasksets:O.size}}i(Re,"checkLocalProfileSource");import te from"node:path";async function je(e){if(!e.state.sourcePath)throw new Error("Active OpenPond profile is missing a source path.");let t=e.state.agents.find(s=>s.id===e.agentId);if(!t)throw new Error(`Profile agent not found for hosted materialization: ${e.agentId}`);if(!t.enabled)throw new Error(`Profile agent is disabled: ${e.agentId}`);let o=Me(e.state.sourcePath,t.path),n=await ye(o),a=await K(o,n.entries),l=W(n,a.entries),h=await ze({client:e.client,teamId:e.teamId,projectId:e.projectId??null,profileProjectId:e.profileProjectId,profileName:e.profileName,agentId:e.agentId,localHead:e.localHead,hostedHead:e.hostedHead}),d=await e.client.projects.uploadSource(h.id,{teamId:e.teamId,entries:l.entries,branch:e.sourceRef,commitMessage:`Materialize OpenPond profile agent ${e.agentId}`}),u=await e.client.projects.sync(d.id,{teamId:e.teamId}),y=be(u)??be(d),$=ve(u)??ve(d)??e.sourceRef,R=`openpond-profile-agent:${e.profileProjectId}:${e.profileName}:${e.agentId}`,w=(await e.client.agents.list({teamId:e.teamId})).find(s=>s.externalId===R),v=await e.client.agents.upsert({teamId:e.teamId,projectId:u.id,name:t.name||e.agentId,slug:xe(e.profileName,e.agentId),selectedEntrypoint:Ne(e.state,e.agentId),triggerType:"manual",runtimeSource:{mode:"latest_source",...$?{sourceRef:$}:{},...y?{sourceCommitSha:y}:{}},metadata:{...w?.metadata??{},source:"openpond_profile_agent_materialization",profileProjectId:e.profileProjectId,profileName:e.profileName,profileAgentId:e.agentId,profileSourcePath:t.path,localHead:e.localHead,hostedHead:e.hostedHead},externalId:R}),x=A(a.uploadMetadata),_=A(x?.commands),P=A(x?.dependencySetup),g=_e(P?.commands),O=[I(_?.validate),I(_?.eval)].filter(s=>!!s);return{status:"uploaded",agentId:e.agentId,runtimeAgentId:v.id,projectId:u.id,sourceRoot:o,sourceRef:$,sourceCommitSha:y??null,manifestHash:u.sandboxManifestHash??null,manifestPath:u.sandboxManifestPath??null,manifestSyncedAt:u.sandboxManifestSyncedAt??null,fileCount:l.fileCount,totalBytes:l.totalBytes,generatedManifestPath:a.generatedManifestPath,synthesizedOpenPondYaml:a.synthesizedOpenPondYaml,uploadMetadataPath:a.uploadMetadataPath,setupCommands:g,validationCommands:O,materializedAt:new Date().toISOString()}}i(je,"materializeHostedProfileAgentSource");async function ze(e){if(e.projectId)try{return await e.client.projects.get(e.projectId,{teamId:e.teamId})}catch{}return e.client.projects.upsert({teamId:e.teamId,name:`OpenPond profile ${e.profileName} ${e.agentId}`,sourceType:"manual",externalId:`openpond-profile:${e.profileProjectId}:${e.profileName}:${e.agentId}`,description:`Materialized OpenPond profile agent ${e.agentId} for hosted Team execution.`,metadata:{source:"openpond_profile_agent_materialization",profileProjectId:e.profileProjectId,profileName:e.profileName,profileAgentId:e.agentId,localHead:e.localHead,hostedHead:e.hostedHead}})}i(ze,"getOrCreateHostedSourceProject");function Me(e,t){let o=t.replace(/\\/g,"/"),n=te.resolve(e,o),a=te.relative(e,n);if(a.startsWith("..")||te.isAbsolute(a))throw new Error(`Profile agent path escapes profile source: ${t}`);return o==="agent/agent.ts"||o.endsWith("/agent.ts")?e:n}i(Me,"resolveProfileAgentSourceRoot");function Ne(e,t){let o=e.actionCatalog.find(n=>n.agentId===t&&(n.sourceActionId==="chat"||n.name==="chat"))??e.actionCatalog.find(n=>n.agentId===t);return{scope:"action",name:typeof o?.sourceActionId=="string"&&o.sourceActionId||typeof o?.name=="string"&&o.name||"chat"}}i(Ne,"hostedEntrypointForProfileAgent");function xe(e,t){return`openpond-profile-${e}-${t}`.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"openpond-profile-agent"}i(xe,"hostedRuntimeAgentSlug");function be(e){let t=A(e),o=A(t?.sourceConfig),n=A(t?.metadata);return I(o?.sourceCommitSha)??I(o?.commitSha)??I(o?.remoteSha)??I(n?.projectSourceUploadCommitSha)??I(n?.sourceCommitSha)??I(t?.templateRemoteSha)}i(be,"sandboxProjectSourceCommitSha");function ve(e){let t=A(e),o=A(t?.sourceConfig);return I(o?.sourceRef)??I(o?.branch)??I(t?.gitBranch)??I(t?.defaultBranch)}i(ve,"sandboxProjectSourceRef");function A(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}i(A,"record");function I(e){return typeof e=="string"&&e.trim()?e.trim():null}i(I,"text");function _e(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}i(_e,"stringArray");async function bo(e){let t=await pe({repoPath:f(e,"path")||ee(),profile:f(e,"profile")||"default",template:f(e,"template")||"blank-agent",force:S(e.force)});if(S(e.json)){console.log(JSON.stringify(t,null,2));return}console.log(`Initialized OpenPond profile ${t.activeProfile} at ${t.repoPath}`),console.log(`Profile source: ${t.sourcePath}`)}i(bo,"runOpenPondInitCommand");async function vo(e,t){let o=t[0]??"current";if(o==="load"){let n=f(e,"path")||t[1];if(!n)throw new Error("usage: openpond profile load --path <dir> [--profile <name>]");let a=await Se(n,f(e,"profile")||void 0);if(S(e.json)){console.log(JSON.stringify(a,null,2));return}console.log(`Loaded OpenPond profile ${a.activeProfile} from ${a.repoPath}`);return}if(o==="current"||o==="status"){let n=await N();if(S(e.json)){console.log(JSON.stringify(n,null,2));return}ne(n);return}if(o==="diff"){let n=await N();if(S(e.json)){console.log(JSON.stringify({diff:n.diff,profile:n},null,2));return}Qe(n);return}if(o==="catalog"){let n=await N();if(S(e.json)){console.log(JSON.stringify({catalog:n.catalog,actions:n.actionCatalog,profile:n},null,2));return}Xe(n);return}if(o==="commit"){await Fe(e,t.slice(1));return}if(o==="push"){await Le(e);return}if(o==="check"){let n=f(e,"kind")||t[1]||"all";if(!["all","inspect","build","validate","eval"].includes(n))throw new Error("check kind must be one of inspect, build, validate, eval, all");if(n==="all"||n==="validate"){let a=await N();if(!a.sourcePath)throw new Error("No active Profile source to validate.");let l=await Re(a.sourcePath,new Set(a.actionCatalog.map(h=>h.id)));console.log(`Profile source valid: ${l.workflows} Workflows, ${l.skills} Skills, ${l.evaluations} evaluations, ${l.tasksets} frozen Tasksets.`)}await Pe(n);return}if(o==="ensure-hosted"){await Oe(e);return}if(o==="hosted"){let n=t[1]??"status";if(n==="ensure"){await Oe(e);return}if(n==="status"||n==="current"){await Ye(e);return}throw new Error("usage: openpond profile hosted [status|ensure] --team-id <id> [--json]")}if(o==="agents"){if((t[1]??"list")!=="list")throw new Error("usage: openpond profile agents list [--json]");await Ze(e,["list"]);return}throw new Error("usage: openpond profile <status|diff|catalog|commit|push|load|check|agents|hosted|ensure-hosted> [args]")}i(vo,"runOpenPondProfileCommand");async function Fe(e,t){let o=f(e,"message")||f(e,"commitMessage")||t.join(" ").trim()||void 0,n=await ke(o);if(S(e.json)){console.log(JSON.stringify(n,null,2));return}if(!n.committed){console.log("No profile changes to commit."),ne(n.state);return}console.log("Committed OpenPond profile changes."),n.stdout.trim()&&console.log(n.stdout.trim()),ne(n.state)}i(Fe,"runProfileCommitCommand");async function Le(e){let t=B(e,"usage: openpond profile push"),o=await N();if(o.error)throw new Error(o.error);if(!o.repoPath||!o.sourcePath||!o.manifestPath)throw new Error("No active OpenPond profile. Run `openpond init`.");if(!o.git?.isRepo)throw new Error("Active OpenPond profile source is not Git-backed. Run `openpond init` or reload a Git-backed profile.");if(!o.git.head)throw new Error("Profile source must have a committed Git head before push. Run `openpond profile commit` first.");if(o.git.dirty)throw new Error("Profile source has uncommitted changes. Run `openpond profile commit` before push.");let n=await G(e),a=S(e.ensureHosted)?await n.profile.ensureHosted({teamId:t}):await n.profile.get({teamId:t});if(!a)throw new Error("No hosted OpenPond profile repo found. Run `openpond profile ensure-hosted --team-id <id>` first, or pass `--ensure-hosted` to push.");let l=S(e.force),h=a.sourceUpload?.sourceCommitSha??null,d=o.hosted?.sourceCommitSha??null;if(d&&h!==d&&!l)throw new Error(["Hosted profile source changed since the last local push.",`Last pushed hosted head: ${d}`,`Current hosted head: ${h??"none"}`,"Inspect hosted changes before pushing, or rerun with --force to overwrite explicitly."].join(`
3
3
  `));let u=f(e,"hostedSourceAgentId"),y=S(e.hostedSourceChecks),$=S(e.publishHostedSource),R=f(e,"hostedRunAgentId"),w=u||(y||$?R:null),v=JSON.parse(await Ue(o.manifestPath,"utf8")),x=qe(v),_=v.profiles[o.activeProfile??v.defaultProfile]?.path??"profiles/default",P=await De({state:o,hostedSourceAgentId:w}),g=await n.profile.push({teamId:t,entries:P.entries,branch:o.git.branch??"main",commitMessage:f(e,"commitMessage")||f(e,"message")||`Push OpenPond profile ${o.activeProfile??"default"} at ${o.git.shortHead??o.git.head}`,expectedSourceCommitSha:h,localHeadSha:o.git.head,manifest:x,sourcePath:_,agents:o.agents.map(c=>({id:c.id,path:c.path,enabled:c.enabled}))}),O=new Date().toISOString(),s=o.hosted?.lastPushedLocalHead===o.git.head&&o.hosted?.sourceCommitSha===g.sourceUpload.sourceCommitSha,r={status:"pushed",promotionStatus:s?o.hosted?.promotionStatus??"uploaded":"uploaded",hostedRunStatus:s?o.hosted?.hostedRunStatus??"not_started":"not_started",pushedAt:O,teamId:t,projectId:g.profile.project.id,localHead:o.git.head,hostedHead:g.sourceUpload.sourceCommitSha,sourceRef:g.sourceUpload.sourceRef,hostedRunAgentId:s?o.hosted?.hostedRunAgentId??null:null,hostedRunId:s?o.hosted?.hostedRunId??null:null,hostedRunAt:s?o.hosted?.hostedRunAt??null:null,hostedSourceMaterialization:s?o.hosted?.hostedSourceMaterialization??null:null,hostedSourceCheck:s?o.hosted?.hostedSourceCheck??null:null,hostedPublish:s?o.hosted?.hostedPublish??null:null,hostedRun:s?o.hosted?.hostedRun??null:null};await C(r);let m=w??Be(o,R),H=Ce(e.hostedSourceDispatch,"hosted-source-dispatch")??"coding_core",E=null,k=null,Z=null;if(w&&(y||$||u))try{let c=await je({client:n,teamId:t,profileProjectId:g.profile.project.id,profileName:o.activeProfile??v.defaultProfile,state:o,agentId:w,sourceRef:g.sourceUpload.sourceRef??o.git.branch??"main",localHead:o.git.head,hostedHead:g.sourceUpload.sourceCommitSha,projectId:f(e,"hostedSourceProjectId")||(o.hosted?.hostedSourceMaterialization?.agentId===w?o.hosted.hostedSourceMaterialization.projectId:null)});r={...r,promotionStatus:"hosted_source_materialized",hostedSourceMaterialization:c},m=c.runtimeAgentId??w,await C(r)}catch(c){let p=c instanceof Error?c.message:String(c);throw r={...r,promotionStatus:"hosted_source_materialize_failed",hostedSourceMaterialization:{status:"failed",agentId:w,projectId:f(e,"hostedSourceProjectId")??null,error:p},error:p},await C(r),new Error(`Hosted source materialization failed after push: ${p}`)}if(y||$){if(!w)throw new Error("--hosted-source-agent-id or --hosted-run-agent-id is required for hosted source checks or publish.");if(!m)throw new Error("Unable to resolve the hosted runtime agent for source checks.");try{if(E=await n.agents.sourceDeployPlan(m,{teamId:t}),y){let c=r.hostedSourceMaterialization?.sourceRef??g.sourceUpload.sourceRef,p=r.hostedSourceMaterialization?.sourceCommitSha??g.sourceUpload.sourceCommitSha;if(k=await n.agents.requestSourceChecks(m,{teamId:t,...c?{sourceRef:c}:{},...p?{baseSha:p}:{},checkKind:$e(f(e,"hostedCheckKind")||f(e,"checkKind"))??"all",dispatch:H,metadata:{source:"openpond_profile_push_checks",localHead:o.git.head,hostedHead:g.sourceUpload.sourceCommitSha,materializedProjectId:r.hostedSourceMaterialization?.projectId??null,materializedSourceCommitSha:r.hostedSourceMaterialization?.sourceCommitSha??null,sourceRef:c,dispatch:H}}),k.dispatchResult?.status==="failed")throw new Error(k.dispatchResult.error??"hosted_source_check_dispatch_failed");if(k.dispatchResult?.status==="completed"){let D=Y(k.sourceCheckStatus);Ke(D)&&(await Ge({client:n,teamId:t,runtimeAgentId:m,sourceRef:c,sourceCommitSha:p,validatedAt:new Date().toISOString()}),E=await n.agents.sourceDeployPlan(m,{teamId:t}))}}r={...r,promotionStatus:y?"hosted_source_check_pending":r.promotionStatus,hostedSourceCheck:X({agentId:m,status:y?"requested":"deploy_plan_ready",deployPlan:E,checkResult:k})},await C(r)}catch(c){let p=c instanceof Error?c.message:String(c);throw r={...r,promotionStatus:"hosted_source_check_failed",hostedSourceCheck:X({agentId:m,status:"failed",deployPlan:E,checkedAt:new Date().toISOString(),error:p}),error:p},await C(r),new Error(`Hosted source check failed after push: ${p}`)}}if($){if(!w)throw new Error("--hosted-source-agent-id or --hosted-run-agent-id is required for hosted source publish.");if(!m)throw new Error("Unable to resolve the hosted runtime agent for source publish.");try{let c=f(e,"expectedManifestHash")||r.hostedSourceCheck?.manifestHash||E?.source.manifestHash||void 0;Z=await n.agents.publishSource(m,{teamId:t,...c?{expectedManifestHash:c}:{},...r.hostedSourceMaterialization?.sourceCommitSha??g.sourceUpload.sourceCommitSha?{expectedSourceCommitSha:r.hostedSourceMaterialization?.sourceCommitSha??g.sourceUpload.sourceCommitSha}:{}}),r={...r,promotionStatus:"hosted_source_published",hostedPublish:he({agentId:m,publishResult:Z})},await C(r)}catch(c){let p=c instanceof Error?c.message:String(c);throw r={...r,promotionStatus:"hosted_source_publish_failed",hostedPublish:{status:"failed",agentId:m,error:p},error:p},await C(r),new Error(`Hosted source publish failed after push: ${p}`)}}let z=null;if(R){let c=m||R,p=new Date().toISOString(),D=oo(e,"hostedRunInput")??{prompt:"hello",channel:"openpond_chat"},J=f(e,"hostedRunConversationId")||f(e,"conversationId"),U=f(e,"hostedRunTargetProjectId"),re=Ie({explicitKey:f(e,"hostedRunIdempotencyKey"),retry:S(e.hostedRunRetry),localHead:o.git.head,sourceHead:r.hostedSourceMaterialization?.sourceCommitSha??g.sourceUpload.sourceCommitSha,runtimeAgentId:c,targetProjectId:U,input:D});await C({...r,promotionStatus:"hosted_run_pending",hostedRunStatus:"running",hostedRunAgentId:c,hostedRunAt:p});try{z=await n.agents.run(c,{teamId:t,...J?{conversationId:J}:{},...U?{targetProjectId:U}:{},...U?{targetProject:{id:U}}:{},idempotencyKey:re,input:D,metadata:{source:"openpond_profile_push_run",...J?{conversationId:J}:{},targetProjectId:U||null,localHead:o.git.head,hostedHead:g.sourceUpload.sourceCommitSha,hostedRunIdempotencyKey:re,hostedRunRetry:S(e.hostedRunRetry),materializedProjectId:r.hostedSourceMaterialization?.projectId??null,materializedSourceCommitSha:r.hostedSourceMaterialization?.sourceCommitSha??null,sourceRef:r.hostedSourceMaterialization?.sourceRef??g.sourceUpload.sourceRef,publishedSnapshotId:r.hostedPublish?.snapshotId??null,manifestHash:r.hostedPublish?.manifestHash??r.hostedSourceCheck?.manifestHash??null},runtimeSourcePolicy:$?{requirePublishedSnapshot:!0,source:"diagnostic"}:{allowLatestSource:!0,source:"diagnostic"}});let F=ge({agentId:c,runResult:z}),M=me(F);await C({...r,promotionStatus:M==="passed"?"hosted_run_passed":M==="failed"?"hosted_run_failed":"hosted_run_pending",hostedRunStatus:M,hostedRunAgentId:c,hostedRunId:z.run.id,hostedRunAt:z.run.createdAt??p,hostedRun:F})}catch(F){let M=F instanceof Error?F.message:String(F);throw await C({...r,promotionStatus:"hosted_run_failed",hostedRunStatus:"failed",hostedRunAgentId:c,hostedRunAt:new Date().toISOString(),hostedRun:{status:"failed",agentId:c,error:M},error:M}),new Error(`Hosted invocation failed to start after push: ${M}`)}}if(S(e.json)){console.log(JSON.stringify({...g,uploaded:Te(P),hostedSourceMaterialization:r.hostedSourceMaterialization??null,hostedSourceChecks:k,hostedSourcePublish:Z,hostedRun:z},null,2));return}console.log(`Pushed OpenPond profile ${o.activeProfile??"default"} to hosted profile repo.`),console.log(`Project id: ${g.profile.project.id}`),console.log(`Local head: ${o.git.head}`),console.log(`Hosted source commit: ${g.sourceUpload.sourceCommitSha??"unknown"}`),console.log(`Uploaded ${P.fileCount} file(s), ${P.totalBytes} byte(s) via ${P.transport.mode} (limits: ${P.limits.maxFiles} files, ${P.limits.maxFileBytes} bytes/file, ${P.limits.maxTotalBytes} bytes total).`),console.log(z?`Hosted invocation: running ${z.run.id}`:"Hosted invocation: not started"),r.hostedSourceMaterialization&&console.log(`Hosted materialized: ${r.hostedSourceMaterialization.status}`+(r.hostedSourceMaterialization.projectId?` ${r.hostedSourceMaterialization.projectId}`:"")+(r.hostedSourceMaterialization.sourceCommitSha?` ${r.hostedSourceMaterialization.sourceCommitSha}`:"")),r.hostedSourceCheck&&console.log(`Hosted source checks: ${r.hostedSourceCheck.status}`),r.hostedPublish&&console.log(`Hosted publish: ${r.hostedPublish.status}`+(r.hostedPublish.snapshotId?` ${r.hostedPublish.snapshotId}`:"")),console.log(`Uploaded files: ${P.fileCount}`)}i(Le,"runProfilePushCommand");function Te(e){return{fileCount:e.fileCount,totalBytes:e.totalBytes,limits:e.limits,transport:e.transport}}i(Te,"summarizeProfileSourceUpload");function qe(e){return{...e,profiles:Object.fromEntries(Object.entries(e.profiles).map(([t,o])=>[t,{path:o.path,defaultAgent:o.defaultAgent??"default",enabledAgents:o.enabledAgents??[]}]))}}i(qe,"normalizeHostedProfileManifest");async function De(e){let t=e.state.repoPath;if(!t)throw new Error("Active OpenPond profile is missing a repository path.");let o=await fe(t);if(!e.hostedSourceAgentId)return o;if(!e.state.sourcePath)throw new Error("Active OpenPond profile is missing a source path.");let n=e.state.agents.find(d=>d.id===e.hostedSourceAgentId);if(!n)throw new Error(`Profile agent not found for hosted source upload: ${e.hostedSourceAgentId}`);let a=Je(e.state.sourcePath,n.path),l=L.relative(t,a).replace(/\\/g,"/");if(l.startsWith("..")||L.isAbsolute(l))throw new Error(`Profile agent path escapes profile repo: ${n.path}`);let h=await K(a,[]);return h.entries.length===0?o:W(o,h.entries.map(d=>({...d,path:l?`${l}/${d.path}`:d.path})))}i(De,"collectProfileSourceUploadForPush");function Je(e,t){let o=t.replace(/\\/g,"/"),n=L.resolve(e,o),a=L.relative(e,n);if(a.startsWith("..")||L.isAbsolute(a))throw new Error(`Profile agent path escapes profile source: ${t}`);return o==="agent/agent.ts"||o.endsWith("/agent.ts")?e:n}i(Je,"resolveProfileAgentSourceRoot");function Y(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}i(Y,"record");function T(e){return typeof e=="string"&&e.trim()?e.trim():null}i(T,"text");function Be(e,t){if(!t)return null;let o=e.hosted?.hostedSourceMaterialization;return o?.agentId===t&&o.runtimeAgentId?o.runtimeAgentId:t}i(Be,"resolveHostedRuntimeAgentIdForRun");async function Ge(e){!e.sourceRef||!e.sourceCommitSha||await e.client.agents.update(e.runtimeAgentId,{teamId:e.teamId,runtimeSource:{mode:"latest_source",sourceRef:e.sourceRef,sourceCommitSha:e.sourceCommitSha,buildStatus:"succeeded",validationStatus:"passed",validatedAt:e.validatedAt}})}i(Ge,"bindValidatedHostedRuntimeSource");function Ke(e){if(!e)return!1;let t=T(e.finalResultState)?.toLowerCase();if(t&&t!=="completed"&&!He(t))return!1;let o=Array.isArray(e.checkRuns)?e.checkRuns.map(Y).filter(u=>!!u):[];if(o.some(We))return!1;let n=o.some(u=>V(u).includes("build")&&q(u)),a=q(Y(e.validation))||o.some(u=>V(u).includes("validate")&&q(u)),l=Y(e.eval),d=!((T(e.requestedCheckKind)??"all")==="all"||(T(e.requestedCheckKind)??"")==="eval"||!!l||o.some(u=>V(u).includes("eval")))||q(l)||o.some(u=>V(u).includes("eval")&&q(u));return n&&a&&d}i(Ke,"sourceCheckStatusPassed");function V(e){return(T(e.command)??"").toLowerCase()}i(V,"checkRunCommand");function We(e){let t=e.passed;if(typeof t=="boolean")return!t;let o=e.exitCode;if(typeof o=="number"&&o!==0)return!0;let n=T(e.status)?.toLowerCase();return!!(n&&Ve(n))}i(We,"checkRunFailed");function q(e){if(!e)return!1;if(typeof e.passed=="boolean")return e.passed;let t=Ae(e.failed)??Ae(e.failedCount);if(t!==null&&t>0)return!1;let o=e.exitCode;if(typeof o=="number")return o===0;let n=T(e.status)?.toLowerCase();return!!(n&&He(n))}i(q,"checkEvidencePassed");function Ae(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()){let t=Number(e);return Number.isFinite(t)?t:null}return null}i(Ae,"numericEvidence");function He(e){return e==="passed"||e==="succeeded"||e==="success"}i(He,"passingStatus");function Ve(e){return e==="failed"||e==="failure"||e==="cancelled"}i(Ve,"failingStatus");async function Ye(e){let t=B(e,"usage: openpond profile hosted status"),n=await(await G(e)).profile.get({teamId:t});if(S(e.json)){console.log(JSON.stringify({profile:n},null,2));return}if(!n){console.log("No hosted OpenPond profile repo found."),console.log("Run `openpond profile ensure-hosted --team-id <id>` to create one.");return}Ee(n)}i(Ye,"runHostedProfileStatusCommand");async function Oe(e){let t=B(e,"usage: openpond profile ensure-hosted"),n=await(await G(e)).profile.ensureHosted({teamId:t});if(S(e.json)){console.log(JSON.stringify({profile:n},null,2));return}Ee(n)}i(Oe,"runHostedProfileEnsureCommand");async function Ze(e,t){if((t[0]??"list")!=="list")throw new Error("usage: openpond agents list [--json]");let n=await N();if(n.error)throw new Error(n.error);if(S(e.json)){console.log(JSON.stringify({agents:n.agents,profile:n},null,2));return}if(n.mode==="none"){console.log("No active OpenPond profile. Run `openpond init`.");return}if(n.agents.length===0){console.log(`No agents found in ${n.activeProfile}.`);return}for(let a of n.agents)console.log(`${a.id} ${a.enabled?"enabled":"disabled"} ${a.path}`)}i(Ze,"runOpenPondAgentsCommand");async function jo(e,t,o){let n=f(t,"cwd"),a=[...o,...eo(t,new Set(["cwd","account","profile","handle","baseUrl"]))];await we({command:e,cwd:n?L.resolve(n):void 0,args:a,inherit:!0})}i(jo,"runOpenPondProfileSdkAlias");function ne(e){if(e.mode==="none"){console.log("No active OpenPond profile."),console.log(`Default location: ${ee()}`);return}if(console.log(`Mode: ${e.mode}`),console.log(`Repo: ${e.repoPath}`),console.log(`Profile: ${e.activeProfile}`),console.log(`Source: ${e.sourcePath??"missing"}`),console.log(`State: ${e.summary.message}`),e.git&&(console.log(`Git: ${e.git.branch??"detached"} ${e.git.shortHead??"no-head"}${e.git.dirty?" dirty":" clean"}`),e.git.upstream&&console.log(`Upstream: ${e.git.upstream} ahead ${e.git.ahead??"?"} behind ${e.git.behind??"?"}`)),(e.hosted?.projectId||e.hosted?.sourceCommitSha)&&(console.log(`Hosted: ${e.hosted.projectId??"unbound"} ${e.hosted.sourceCommitSha??"no-source-head"}`),e.hosted.hostedSourceMaterialization&&console.log(`Hosted materialized: ${e.hosted.hostedSourceMaterialization.status}`+(e.hosted.hostedSourceMaterialization.agentId?` ${e.hosted.hostedSourceMaterialization.agentId}`:"")+(e.hosted.hostedSourceMaterialization.sourceCommitSha?` ${e.hosted.hostedSourceMaterialization.sourceCommitSha}`:"")),e.hosted.hostedSourceCheck&&console.log(`Hosted checks: ${e.hosted.hostedSourceCheck.status}`+(e.hosted.hostedSourceCheck.sandboxId?` sandbox ${e.hosted.hostedSourceCheck.sandboxId}`:"")),e.hosted.hostedPublish&&console.log(`Hosted publish: ${e.hosted.hostedPublish.status}`+(e.hosted.hostedPublish.snapshotId?` ${e.hosted.hostedPublish.snapshotId}`:"")),e.hosted.hostedRun&&console.log(`Hosted run: ${e.hosted.hostedRun.status}`+(e.hosted.hostedRun.runId?` ${e.hosted.hostedRun.runId}`:"")+(e.hosted.hostedRun.runtimeId?` runtime ${e.hosted.hostedRun.runtimeId}`:""))),console.log(`Catalog: ${e.catalog.actionCount} action(s)${e.catalog.stale?" stale":""}`),console.log(`Setup gate: ${e.setupGate.status} (${e.setupGate.blockingCount} blocking, ${e.setupGate.optionalMissingCount} optional missing)`),e.summary.defaultAction&&console.log(`Default action: ${e.summary.defaultAction}`),e.setupGate.blockingRequirements.length>0){console.log("Blocking setup:");for(let t of e.setupGate.blockingRequirements.slice(0,10))console.log(` ${Q(t)}`);e.setupGate.blockingRequirements.length>10&&console.log(` ... ${e.setupGate.blockingRequirements.length-10} more`)}if(!e.summary.checkFresh&&e.summary.checkStaleReason?console.log(`Checks: stale - ${e.summary.checkStaleReason}`):e.summary.checkFresh&&console.log("Checks: fresh"),e.lastCheck&&console.log(`Last check: ${e.lastCheck.command} ${e.lastCheck.status} at ${e.lastCheck.checkedAt}`),e.error&&console.log(`Error: ${e.error}`),e.agents.length>0){console.log("Agents:");for(let t of e.agents)console.log(` ${t.id} (${t.enabled?"enabled":"disabled"}) ${t.path}`)}if(e.skills.length>0){console.log("Skills:");for(let t of e.skills){let o=t.validationStatus==="valid"?"valid":t.validationStatus;console.log(` ${t.name} (${o}) ${t.path}`)}}}i(ne,"printProfileState");function Qe(e){if(e.mode==="none"){console.log("No active OpenPond profile.");return}console.log(`Profile: ${e.activeProfile}`),console.log(`State: ${e.summary.message}`);let t=[["Changed agents",e.diff.changedAgents],["New agents",e.diff.newAgents],["Deleted agents",e.diff.deletedAgents],["Changed skills",e.diff.changedSkills],["Changed actions",e.diff.changedActions],["Changed extensions",e.diff.changedExtensions],["Setup changes",e.diff.setupChanges],["Env requirement changes",e.diff.envRequirementChanges]];for(let[o,n]of t)n.length!==0&&console.log(`${o}: ${n.join(", ")}`);if(e.diff.files.length===0){console.log("No source changes.");return}console.log("Files:");for(let o of e.diff.files)console.log(` ${o.status.padEnd(2)} ${o.path}`)}i(Qe,"printProfileDiff");function Xe(e){if(e.mode==="none"){console.log("No active OpenPond profile.");return}if(console.log(`Profile: ${e.activeProfile}`),console.log(`Catalog: ${e.catalog.actionCount} action(s)${e.catalog.stale?" stale":""}`),console.log(`Setup gate: ${e.setupGate.status} (${e.setupGate.blockingCount} blocking, ${e.setupGate.optionalMissingCount} optional missing)`),e.catalog.generatedAt&&console.log(`Generated at: ${e.catalog.generatedAt}`),e.catalog.error&&console.log(`Catalog error: ${e.catalog.error}`),e.actionCatalog.length===0){console.log("No catalog actions found. Run `openpond inspect` or `openpond build`.");return}for(let o of e.actionCatalog){let n=o.label??o.name??o.id,a=o.visibility??"default",l=e.setupGate.blockingRequirements.filter(d=>d.actionId===o.id),h=l.length?`setup_required:${l.map(d=>d.label).join(",")}`:"setup_ready";console.log(`${o.id} ${a} ${h} ${n}`)}let t=e.setupGate.blockingRequirements.filter(o=>o.actionId===null);if(t.length>0){console.log("Source setup blockers:");for(let o of t)console.log(` ${Q(o)}`)}}i(Xe,"printProfileCatalog");function Ee(e){if(console.log(`Hosted profile repo: ${e.project.name}`),console.log(`Project id: ${e.project.id}`),console.log(`Role: ${e.project.role??"profile"}`),console.log(`Default profile: ${e.defaultProfile}`),console.log(`Source path: ${e.sourcePath}`),console.log(`Seed status: ${e.seedStatus}`),e.sourceUpload?.sourceRef&&console.log(`Source ref: ${e.sourceUpload.sourceRef}`),e.sourceUpload?.sourceCommitSha&&console.log(`Source commit: ${e.sourceUpload.sourceCommitSha}`),e.seededAt&&console.log(`Seeded at: ${e.seededAt}`),e.agents.length>0){console.log("Agents:");for(let t of e.agents)console.log(` ${t.id} (${t.enabled?"enabled":"disabled"}) ${t.path}`)}}i(Ee,"printHostedProfileSummary");function eo(e,t){let o=[],n=new Set(["force","json"]);for(let[a,l]of Object.entries(e)){if(t.has(a))continue;let h=`--${a.replace(/[A-Z]/g,d=>`-${d.toLowerCase()}`)}`;if(l===!0||n.has(a)&&l==="true")o.push(h);else{if(n.has(a)&&l==="false")continue;typeof l=="string"&&o.push(h,l)}}return o}i(eo,"optionArgs");function oo(e,t){let o=f(e,t);if(!o)return null;let n=JSON.parse(o);if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`--${t} must be a JSON object`);return n}i(oo,"parseJsonObjectOption");export{De as collectProfileSourceUploadForPush,Ze as runOpenPondAgentsCommand,bo as runOpenPondInitCommand,vo as runOpenPondProfileCommand,jo as runOpenPondProfileSdkAlias};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{a as b,b as Y,c as F,d as H,e as W,f as z,g as X,h as E,i as y,j as v,k as C,l as Z,m as ee,n as A,o as te,p as _,q as j,r as re,s as ne,t as x,u as M,v as R,w as J,x as N,y as U,z as T}from"./chunk-NAZ26IZL.js";import"./chunk-JDLAHVAJ.js";import"./chunk-EAPFMACH.js";import"./chunk-6FA3GG5B.js";import{m as h,n as I,v as P}from"./chunk-N3DEA6PG.js";import"./chunk-PA7XP42P.js";import"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-RLZPX4YP.js";import"./chunk-Q4H3NUVW.js";import{c as u,d,e as w,f as S}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import"./chunk-2SPZYBDN.js";import"./chunk-QXVIIM4T.js";import"./chunk-R3XFY7VL.js";import"./chunk-GLUWATL5.js";import"./chunk-YL6VFJ4P.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as g}from"./chunk-FTQLQJQV.js";function k(e){let o=e.gitRepo?`${e.gitOwner??"_"}/${e.gitRepo}`:e.internalRepoPath??e.templateRepoUrl??e.normalizedSourceIdentity;return[e.id,e.status,e.sourceType,e.name,o].join(" ")}g(k,"formatProjectLine");function L(e){let o=e.selectedEntrypoint.name?`${e.selectedEntrypoint.scope}:${e.selectedEntrypoint.name}`:e.selectedEntrypoint.scope,i=e.runtimeSource?[e.runtimeSource.mode,e.runtimeSource.publishedSnapshotName??e.runtimeSource.publishedSnapshotId??e.runtimeSource.sourceRef].filter(a=>!!a).join(":"):"latest_source";return[e.id,e.status,e.triggerType,e.defaultWorkflowMode,i,o,e.name].join(" ")}g(L,"formatAgentLine");async function B(e,o,i){let a=i[1]?.trim(),t=i[2]?.trim(),n="usage: agent source <deploy-plan|checks|manifest-snapshots|setup|publish> <agent-id> --team-id <id>",r=d(o,n);if(!a||!t)throw new Error(n);if(a==="deploy-plan"){let s=await e.agents.sourceDeployPlan(t,{teamId:r});console.log(JSON.stringify({deployPlan:s},null,2));return}if(a==="manifest-snapshots"){let s=await e.agents.manifestSnapshots(t,{teamId:r,limit:x(o.limit)});console.log(JSON.stringify({manifestSnapshots:s},null,2));return}if(a==="checks"){let s=await e.agents.requestSourceChecks(t,M(r,o));console.log(JSON.stringify(s,null,2));return}if(a==="setup"){let s=typeof o.provider=="string"?o.provider.trim():"",l=typeof o.allowedActions=="string"?o.allowedActions.split(",").map(c=>c.trim()).filter(Boolean):[];if(!s||l.length===0)throw new Error(`${n}; setup requires --provider and --allowed-actions`);let p=await e.agents.configureSourceSetup(t,{teamId:r,integrationBindings:[{provider:s,mode:"connected",connectionMode:"member_connection",grantPolicy:"read_only",allowedActions:l,enabled:!0}]});console.log(JSON.stringify(p,null,2));return}if(a==="publish"){let s=await e.agents.publishSource(t,R(r,o));console.log(JSON.stringify(s,null,2));return}throw new Error(n)}g(B,"runAgentSourceWorkflow");import G from"node:path";var Q=new Set(["inspect","build","validate","eval","traces"]);function $(e,o){return Q.has(e)?!0:e==="run"&&!u(o,"teamId")}g($,"shouldDelegateLocalAgentSdkCommand");async function q(e,o){let i=o[0]||"inspect",a=G.resolve(u(e,"cwd")||u(e,"path")||"."),t=[i,...o.slice(1),"--cwd",a];S(e.json)&&t.push("--json"),D(t,e,"input","input"),D(t,e,"inputFile","input-file");let n=b(a),r=await P(n.command,[...n.args,...t],{cwd:a,inherit:!0});r.code!==0&&(process.exitCode=r.code??1)}g(q,"runLocalAgentSdkCommand");function D(e,o,i,a){let t=u(o,i);t&&e.push(`--${a}`,t)}g(D,"appendForwardedOption");async function Oe(e,o){let i=o[0]||"list";if($(i,e)){await q(e,o);return}let a=await h(e);if(i==="list"){let t=d(e,"usage: agent list"),n=await a.agents.list({teamId:t});if(S(e.json)){console.log(JSON.stringify({agents:n},null,2));return}if(n.length===0){console.log("no sandbox agents found");return}for(let r of n)console.log(L(r));return}if(i==="create"||i==="upsert"){let t=await a.agents.upsert(U(e));console.log(JSON.stringify({agent:t},null,2));return}if(i==="get"){let t=o[1]?.trim(),n=d(e,"usage: agent get <agentId>");if(!t)throw new Error("usage: agent get <agentId> --team-id <id>");let r=await a.agents.get(t,{teamId:n});console.log(JSON.stringify({agent:r},null,2));return}if(i==="run"){let t=o[1]?.trim(),n=d(e,"usage: agent run <agentId>");if(!t)throw new Error("usage: agent run <agentId> --team-id <id>");let r=u(e,"idempotencyKey"),s=u(e,"conversationId"),l=u(e,"targetProjectId"),p=A(e.triggerType),c=I(e.workflowMode),m=w(e,"input","input"),f=w(e,"metadata","metadata"),O=j(e),K=await a.agents.run(t,{teamId:n,...s?{conversationId:s}:{},...r?{idempotencyKey:r}:{},...l?{targetProjectId:l}:{},...l?{targetProject:{id:l}}:{},...p?{triggerType:p}:{},...c?{workflowMode:c}:{},...m?{input:m}:{},...f?{metadata:f}:{},...O?{runtimeSourcePolicy:O}:{}});console.log(JSON.stringify(K,null,2));return}if(i==="bind-runtime-source"||i==="bind-source"){let t=o[1]?.trim(),n=d(e,"usage: agent bind-source <agentId>");if(!t)throw new Error("usage: agent bind-source <agentId> --team-id <id> --source-mode latest_source|published_snapshot|auto");let r=_(e);if(!r?.mode)throw new Error("usage: agent bind-source <agentId> --team-id <id> --source-mode latest_source|published_snapshot|auto");let s=await a.agents.update(t,{teamId:n,runtimeSource:r});console.log(JSON.stringify({agent:s,agentSource:s.runtimeSource},null,2));return}if(i==="run-test"){let t=o[1]?.trim(),n=d(e,"usage: agent run-test <agentId>");if(!t)throw new Error("usage: agent run-test <agentId> --team-id <id>");let r=u(e,"idempotencyKey"),s=u(e,"conversationId"),l=u(e,"targetProjectId"),p=w(e,"input","input"),c=w(e,"metadata","metadata"),m=I(e.workflowMode),f=await a.agents.run(t,{teamId:n,...s?{conversationId:s}:{},...r?{idempotencyKey:r}:{},...l?{targetProjectId:l}:{},...l?{targetProject:{id:l}}:{},...m?{workflowMode:m}:{},...p?{input:p}:{},metadata:{...c??{},source:"agent_run_test"},runtimeSourcePolicy:j(e,"diagnostic")});console.log(JSON.stringify({resolvedRuntimeSource:f.run.runtimeSource,agent:f.agent,run:f.run,sandbox:f.sandbox??null},null,2));return}if(i==="source"){await B(a,e,o);return}if(i==="update"){let t=o[1]?.trim(),n=d(e,"usage: agent update <agentId>");if(!t)throw new Error("usage: agent update <agentId> --team-id <id>");let r=await a.agents.update(t,T(n,e));console.log(JSON.stringify({agent:r},null,2));return}if(i==="archive"){let t=o[1]?.trim(),n=d(e,"usage: agent archive <agentId>");if(!t)throw new Error("usage: agent archive <agentId> --team-id <id>");let r=await a.agents.archive(t,{teamId:n});console.log(JSON.stringify({agent:r},null,2));return}throw new Error("usage: agent <inspect|build|validate|eval|traces|list|create|upsert|get|update|run|run-test|bind-source|source|edit|archive> [--team-id <id>] [--project-id <id>] [--name <name>]")}g(Oe,"runAgentCommand");import V from"node:path";async function xe(e,o){let i=o[0]||"list",a=await h(e);if(i==="list"){let t=d(e,"usage: project list"),n=await a.projects.list({teamId:t});if(S(e.json)){console.log(JSON.stringify({projects:n},null,2));return}if(n.length===0){console.log("no sandbox projects found");return}for(let r of n)console.log(k(r));return}if(i==="create"||i==="upsert"){let t=await a.projects.upsert(J(e));console.log(JSON.stringify({project:t},null,2));return}if(i==="get"){let t=o[1]?.trim(),n=d(e,"usage: project get <projectId>");if(!t)throw new Error("usage: project get <projectId> --team-id <id>");let r=await a.projects.get(t,{teamId:n});console.log(JSON.stringify({project:r},null,2));return}if(i==="update"){let t=o[1]?.trim(),n=d(e,"usage: project update <projectId>");if(!t)throw new Error("usage: project update <projectId> --team-id <id>");let r=await a.projects.update(t,N(n,e));console.log(JSON.stringify({project:r},null,2));return}if(i==="sync"){let t=o[1]?.trim(),n=d(e,"usage: project sync <projectId>");if(!t)throw new Error("usage: project sync <projectId> --team-id <id>");let r=await a.projects.sync(t,{teamId:n});console.log(JSON.stringify({project:r},null,2));return}if(i==="source-upload"||i==="upload-source"){let t=o[1]?.trim(),n=d(e,"usage: project source-upload <projectId>");if(!t)throw new Error("usage: project source-upload <projectId> --team-id <id> [--path <dir>]");let r=V.resolve(u(e,"path")||"."),s=await E(r,e),l=u(e,"commitMessage")||u(e,"commit-message")||"Upload OpenPond project source",p=await y(r),c=await v(r,p.entries),m=C(p,c.entries),f=await a.projects.uploadSource(t,{teamId:n,entries:m.entries,...s?{branch:s}:{},commitMessage:l});console.log(JSON.stringify({project:f,uploaded:{path:r,branch:s,fileCount:m.fileCount,totalBytes:m.totalBytes,limits:m.limits,transport:m.transport,...c.generatedManifestPath?{agentSdk:{generatedManifestPath:c.generatedManifestPath,generatedEntryCount:c.entries.length,synthesizedOpenPondYaml:c.synthesizedOpenPondYaml,uploadMetadataPath:c.uploadMetadataPath,uploadMetadataHash:c.uploadMetadataHash,commands:c.uploadMetadata?.commands,dependencySetup:c.uploadMetadata?.dependencySetup,packageManager:c.uploadMetadata?.packageManager,sourceTreeMode:c.uploadMetadata?.sourceTreeMode,artifactHashes:c.uploadMetadata?.artifactHashes}}:{}}},null,2));return}if(i==="archive"){let t=o[1]?.trim(),n=d(e,"usage: project archive <projectId>");if(!t)throw new Error("usage: project archive <projectId> --team-id <id>");let r=await a.projects.archive(t,{teamId:n});console.log(JSON.stringify({project:r},null,2));return}throw new Error("usage: project <list|create|upsert|get|update|sync|source-upload|archive> [--team-id <id>] [--name <name>]")}g(xe,"runProjectCommand");export{W as PROJECT_SOURCE_UPLOAD_CONCURRENCY,z as PROJECT_SOURCE_UPLOAD_LIMITS,H as PROJECT_SOURCE_UPLOAD_MAX_BYTES,Y as PROJECT_SOURCE_UPLOAD_MAX_FILES,F as PROJECT_SOURCE_UPLOAD_MAX_FILE_BYTES,X as PROJECT_SOURCE_UPLOAD_TRANSPORT,M as buildAgentSourceChecksInput,_ as buildAgentSourceConfig,j as buildAgentSourcePolicy,R as buildAgentSourcePublishInput,T as buildAgentUpdateInput,U as buildAgentUpsertInput,N as buildProjectUpdateInput,J as buildProjectUpsertInput,y as collectProjectSourceUploadEntries,L as formatAgentLine,k as formatProjectLine,ee as parseAgentEntrypointScope,ne as parseAgentSourceCheckDispatch,re as parseAgentSourceCheckKind,te as parseAgentSourceMode,A as parseAgentTriggerType,x as parsePositiveLimit,Z as parseProjectSourceType,b as resolveLocalAgentSdkCommand,Oe as runAgentCommand,B as runAgentSourceWorkflow,xe as runProjectCommand};
2
+ import{a as b,b as Y,c as F,d as H,e as W,f as z,g as X,h as E,i as y,j as v,k as C,l as Z,m as ee,n as A,o as te,p as _,q as j,r as re,s as ne,t as x,u as M,v as R,w as J,x as N,y as U,z as T}from"./chunk-NAZ26IZL.js";import"./chunk-JDLAHVAJ.js";import"./chunk-EAPFMACH.js";import"./chunk-6FA3GG5B.js";import{m as h,n as I,v as P}from"./chunk-N3DEA6PG.js";import"./chunk-PA7XP42P.js";import"./chunk-BSHAIAXY.js";import"./chunk-XWPC3AN4.js";import"./chunk-YJ4PNAST.js";import"./chunk-AH22RHPS.js";import{c as u,d,e as w,f as S}from"./chunk-3M53YXEI.js";import"./chunk-OGPHXXCD.js";import"./chunk-2SPZYBDN.js";import"./chunk-QXVIIM4T.js";import"./chunk-R3XFY7VL.js";import"./chunk-GLUWATL5.js";import"./chunk-YL6VFJ4P.js";import"./chunk-Z3D4C7BG.js";import"./chunk-WV2APYWG.js";import"./chunk-PJM2G7SG.js";import"./chunk-SDEDAHV6.js";import"./chunk-DALJMSJG.js";import"./chunk-TGIB24K4.js";import"./chunk-NNF6KCHD.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import{a as g}from"./chunk-FTQLQJQV.js";function k(e){let o=e.gitRepo?`${e.gitOwner??"_"}/${e.gitRepo}`:e.internalRepoPath??e.templateRepoUrl??e.normalizedSourceIdentity;return[e.id,e.status,e.sourceType,e.name,o].join(" ")}g(k,"formatProjectLine");function L(e){let o=e.selectedEntrypoint.name?`${e.selectedEntrypoint.scope}:${e.selectedEntrypoint.name}`:e.selectedEntrypoint.scope,i=e.runtimeSource?[e.runtimeSource.mode,e.runtimeSource.publishedSnapshotName??e.runtimeSource.publishedSnapshotId??e.runtimeSource.sourceRef].filter(a=>!!a).join(":"):"latest_source";return[e.id,e.status,e.triggerType,e.defaultWorkflowMode,i,o,e.name].join(" ")}g(L,"formatAgentLine");async function B(e,o,i){let a=i[1]?.trim(),t=i[2]?.trim(),n="usage: agent source <deploy-plan|checks|manifest-snapshots|setup|publish> <agent-id> --team-id <id>",r=d(o,n);if(!a||!t)throw new Error(n);if(a==="deploy-plan"){let s=await e.agents.sourceDeployPlan(t,{teamId:r});console.log(JSON.stringify({deployPlan:s},null,2));return}if(a==="manifest-snapshots"){let s=await e.agents.manifestSnapshots(t,{teamId:r,limit:x(o.limit)});console.log(JSON.stringify({manifestSnapshots:s},null,2));return}if(a==="checks"){let s=await e.agents.requestSourceChecks(t,M(r,o));console.log(JSON.stringify(s,null,2));return}if(a==="setup"){let s=typeof o.provider=="string"?o.provider.trim():"",l=typeof o.allowedActions=="string"?o.allowedActions.split(",").map(c=>c.trim()).filter(Boolean):[];if(!s||l.length===0)throw new Error(`${n}; setup requires --provider and --allowed-actions`);let p=await e.agents.configureSourceSetup(t,{teamId:r,integrationBindings:[{provider:s,mode:"connected",connectionMode:"member_connection",grantPolicy:"read_only",allowedActions:l,enabled:!0}]});console.log(JSON.stringify(p,null,2));return}if(a==="publish"){let s=await e.agents.publishSource(t,R(r,o));console.log(JSON.stringify(s,null,2));return}throw new Error(n)}g(B,"runAgentSourceWorkflow");import G from"node:path";var Q=new Set(["inspect","build","validate","eval","traces"]);function $(e,o){return Q.has(e)?!0:e==="run"&&!u(o,"teamId")}g($,"shouldDelegateLocalAgentSdkCommand");async function q(e,o){let i=o[0]||"inspect",a=G.resolve(u(e,"cwd")||u(e,"path")||"."),t=[i,...o.slice(1),"--cwd",a];S(e.json)&&t.push("--json"),D(t,e,"input","input"),D(t,e,"inputFile","input-file");let n=b(a),r=await P(n.command,[...n.args,...t],{cwd:a,inherit:!0});r.code!==0&&(process.exitCode=r.code??1)}g(q,"runLocalAgentSdkCommand");function D(e,o,i,a){let t=u(o,i);t&&e.push(`--${a}`,t)}g(D,"appendForwardedOption");async function Oe(e,o){let i=o[0]||"list";if($(i,e)){await q(e,o);return}let a=await h(e);if(i==="list"){let t=d(e,"usage: agent list"),n=await a.agents.list({teamId:t});if(S(e.json)){console.log(JSON.stringify({agents:n},null,2));return}if(n.length===0){console.log("no sandbox agents found");return}for(let r of n)console.log(L(r));return}if(i==="create"||i==="upsert"){let t=await a.agents.upsert(U(e));console.log(JSON.stringify({agent:t},null,2));return}if(i==="get"){let t=o[1]?.trim(),n=d(e,"usage: agent get <agentId>");if(!t)throw new Error("usage: agent get <agentId> --team-id <id>");let r=await a.agents.get(t,{teamId:n});console.log(JSON.stringify({agent:r},null,2));return}if(i==="run"){let t=o[1]?.trim(),n=d(e,"usage: agent run <agentId>");if(!t)throw new Error("usage: agent run <agentId> --team-id <id>");let r=u(e,"idempotencyKey"),s=u(e,"conversationId"),l=u(e,"targetProjectId"),p=A(e.triggerType),c=I(e.workflowMode),m=w(e,"input","input"),f=w(e,"metadata","metadata"),O=j(e),K=await a.agents.run(t,{teamId:n,...s?{conversationId:s}:{},...r?{idempotencyKey:r}:{},...l?{targetProjectId:l}:{},...l?{targetProject:{id:l}}:{},...p?{triggerType:p}:{},...c?{workflowMode:c}:{},...m?{input:m}:{},...f?{metadata:f}:{},...O?{runtimeSourcePolicy:O}:{}});console.log(JSON.stringify(K,null,2));return}if(i==="bind-runtime-source"||i==="bind-source"){let t=o[1]?.trim(),n=d(e,"usage: agent bind-source <agentId>");if(!t)throw new Error("usage: agent bind-source <agentId> --team-id <id> --source-mode latest_source|published_snapshot|auto");let r=_(e);if(!r?.mode)throw new Error("usage: agent bind-source <agentId> --team-id <id> --source-mode latest_source|published_snapshot|auto");let s=await a.agents.update(t,{teamId:n,runtimeSource:r});console.log(JSON.stringify({agent:s,agentSource:s.runtimeSource},null,2));return}if(i==="run-test"){let t=o[1]?.trim(),n=d(e,"usage: agent run-test <agentId>");if(!t)throw new Error("usage: agent run-test <agentId> --team-id <id>");let r=u(e,"idempotencyKey"),s=u(e,"conversationId"),l=u(e,"targetProjectId"),p=w(e,"input","input"),c=w(e,"metadata","metadata"),m=I(e.workflowMode),f=await a.agents.run(t,{teamId:n,...s?{conversationId:s}:{},...r?{idempotencyKey:r}:{},...l?{targetProjectId:l}:{},...l?{targetProject:{id:l}}:{},...m?{workflowMode:m}:{},...p?{input:p}:{},metadata:{...c??{},source:"agent_run_test"},runtimeSourcePolicy:j(e,"diagnostic")});console.log(JSON.stringify({resolvedRuntimeSource:f.run.runtimeSource,agent:f.agent,run:f.run,sandbox:f.sandbox??null},null,2));return}if(i==="source"){await B(a,e,o);return}if(i==="update"){let t=o[1]?.trim(),n=d(e,"usage: agent update <agentId>");if(!t)throw new Error("usage: agent update <agentId> --team-id <id>");let r=await a.agents.update(t,T(n,e));console.log(JSON.stringify({agent:r},null,2));return}if(i==="archive"){let t=o[1]?.trim(),n=d(e,"usage: agent archive <agentId>");if(!t)throw new Error("usage: agent archive <agentId> --team-id <id>");let r=await a.agents.archive(t,{teamId:n});console.log(JSON.stringify({agent:r},null,2));return}throw new Error("usage: agent <inspect|build|validate|eval|traces|list|create|upsert|get|update|run|run-test|bind-source|source|edit|archive> [--team-id <id>] [--project-id <id>] [--name <name>]")}g(Oe,"runAgentCommand");import V from"node:path";async function xe(e,o){let i=o[0]||"list",a=await h(e);if(i==="list"){let t=d(e,"usage: project list"),n=await a.projects.list({teamId:t});if(S(e.json)){console.log(JSON.stringify({projects:n},null,2));return}if(n.length===0){console.log("no sandbox projects found");return}for(let r of n)console.log(k(r));return}if(i==="create"||i==="upsert"){let t=await a.projects.upsert(J(e));console.log(JSON.stringify({project:t},null,2));return}if(i==="get"){let t=o[1]?.trim(),n=d(e,"usage: project get <projectId>");if(!t)throw new Error("usage: project get <projectId> --team-id <id>");let r=await a.projects.get(t,{teamId:n});console.log(JSON.stringify({project:r},null,2));return}if(i==="update"){let t=o[1]?.trim(),n=d(e,"usage: project update <projectId>");if(!t)throw new Error("usage: project update <projectId> --team-id <id>");let r=await a.projects.update(t,N(n,e));console.log(JSON.stringify({project:r},null,2));return}if(i==="sync"){let t=o[1]?.trim(),n=d(e,"usage: project sync <projectId>");if(!t)throw new Error("usage: project sync <projectId> --team-id <id>");let r=await a.projects.sync(t,{teamId:n});console.log(JSON.stringify({project:r},null,2));return}if(i==="source-upload"||i==="upload-source"){let t=o[1]?.trim(),n=d(e,"usage: project source-upload <projectId>");if(!t)throw new Error("usage: project source-upload <projectId> --team-id <id> [--path <dir>]");let r=V.resolve(u(e,"path")||"."),s=await E(r,e),l=u(e,"commitMessage")||u(e,"commit-message")||"Upload OpenPond project source",p=await y(r),c=await v(r,p.entries),m=C(p,c.entries),f=await a.projects.uploadSource(t,{teamId:n,entries:m.entries,...s?{branch:s}:{},commitMessage:l});console.log(JSON.stringify({project:f,uploaded:{path:r,branch:s,fileCount:m.fileCount,totalBytes:m.totalBytes,limits:m.limits,transport:m.transport,...c.generatedManifestPath?{agentSdk:{generatedManifestPath:c.generatedManifestPath,generatedEntryCount:c.entries.length,synthesizedOpenPondYaml:c.synthesizedOpenPondYaml,uploadMetadataPath:c.uploadMetadataPath,uploadMetadataHash:c.uploadMetadataHash,commands:c.uploadMetadata?.commands,dependencySetup:c.uploadMetadata?.dependencySetup,packageManager:c.uploadMetadata?.packageManager,sourceTreeMode:c.uploadMetadata?.sourceTreeMode,artifactHashes:c.uploadMetadata?.artifactHashes}}:{}}},null,2));return}if(i==="archive"){let t=o[1]?.trim(),n=d(e,"usage: project archive <projectId>");if(!t)throw new Error("usage: project archive <projectId> --team-id <id>");let r=await a.projects.archive(t,{teamId:n});console.log(JSON.stringify({project:r},null,2));return}throw new Error("usage: project <list|create|upsert|get|update|sync|source-upload|archive> [--team-id <id>] [--name <name>]")}g(xe,"runProjectCommand");export{W as PROJECT_SOURCE_UPLOAD_CONCURRENCY,z as PROJECT_SOURCE_UPLOAD_LIMITS,H as PROJECT_SOURCE_UPLOAD_MAX_BYTES,Y as PROJECT_SOURCE_UPLOAD_MAX_FILES,F as PROJECT_SOURCE_UPLOAD_MAX_FILE_BYTES,X as PROJECT_SOURCE_UPLOAD_TRANSPORT,M as buildAgentSourceChecksInput,_ as buildAgentSourceConfig,j as buildAgentSourcePolicy,R as buildAgentSourcePublishInput,T as buildAgentUpdateInput,U as buildAgentUpsertInput,N as buildProjectUpdateInput,J as buildProjectUpsertInput,y as collectProjectSourceUploadEntries,L as formatAgentLine,k as formatProjectLine,ee as parseAgentEntrypointScope,ne as parseAgentSourceCheckDispatch,re as parseAgentSourceCheckKind,te as parseAgentSourceMode,A as parseAgentTriggerType,x as parsePositiveLimit,Z as parseProjectSourceType,b as resolveLocalAgentSdkCommand,Oe as runAgentCommand,B as runAgentSourceWorkflow,xe as runProjectCommand};