openpond 0.2.45 → 0.2.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/RELEASE.md +16 -13
- package/dist/app-server.d.ts +10584 -10105
- package/dist/app-server.js +1 -1
- package/dist/chunks/actions-command-DSO6YOEE.js +2 -0
- package/dist/chunks/{app-layer-MDJFV3HZ.js → app-layer-RRFI27N4.js} +1 -1
- package/dist/chunks/app-server-runtime-3KFJJUJH.js +2 -0
- package/dist/chunks/apps-NELJL377.js +2 -0
- package/dist/chunks/chunk-2SPZYBDN.js +16 -0
- package/dist/chunks/{chunk-U6SFIFDM.js → chunk-36YNUUZL.js} +136 -136
- package/dist/chunks/chunk-3HBCQNRN.js +2 -0
- package/dist/chunks/chunk-4UTBLHFC.js +2 -0
- package/dist/chunks/chunk-526PVA3V.js +2678 -0
- package/dist/chunks/{chunk-B6LYKEMU.js → chunk-6MH55NGW.js} +1 -1
- package/dist/chunks/chunk-7QEE4PBI.js +8 -0
- package/dist/chunks/{chunk-GEDEVI4Y.js → chunk-7YR6CBNU.js} +1 -1
- package/dist/chunks/{chunk-25GCTLAZ.js → chunk-A2GVVXFV.js} +1 -1
- package/dist/chunks/chunk-BM7TU6NX.js +190 -0
- package/dist/chunks/{chunk-XPB6NY7L.js → chunk-CNTGL5IX.js} +3 -3
- package/dist/chunks/{chunk-VVV5I22A.js → chunk-D7DA5G2U.js} +2 -2
- package/dist/chunks/chunk-DALJMSJG.js +33 -0
- package/dist/chunks/{chunk-4EGDKOYP.js → chunk-DLZP22WV.js} +1 -1
- package/dist/chunks/chunk-EMKZVP7Z.js +2 -0
- package/dist/chunks/{chunk-CXS3WXL3.js → chunk-F7RCOLZD.js} +1 -1
- package/dist/chunks/{chunk-FXIUKYUR.js → chunk-HA7EFTPF.js} +3 -3
- package/dist/chunks/chunk-IKWDL3RB.js +17 -0
- package/dist/chunks/{chunk-V62BHD5G.js → chunk-JDLAHVAJ.js} +1 -1
- package/dist/chunks/chunk-K6S4TY5W.js +9 -0
- package/dist/chunks/{chunk-IYRHG54Q.js → chunk-MASJQWA2.js} +1 -1
- package/dist/chunks/{chunk-B3O2GAQH.js → chunk-N3DEA6PG.js} +1 -1
- package/dist/chunks/{chunk-CR6CDOKS.js → chunk-N5QNXMIS.js} +2 -2
- package/dist/chunks/{chunk-OJVIH7J6.js → chunk-NAZ26IZL.js} +1 -1
- package/dist/chunks/chunk-NNF6KCHD.js +3 -0
- package/dist/chunks/chunk-PA7XP42P.js +2 -0
- package/dist/chunks/chunk-PJM2G7SG.js +21 -0
- package/dist/chunks/chunk-PYABBF53.js +53 -0
- package/dist/chunks/chunk-Q4H3NUVW.js +3 -0
- package/dist/chunks/chunk-QRWPEW3Z.js +24 -0
- package/dist/chunks/{chunk-Z2BYC6TP.js → chunk-QXVIIM4T.js} +1 -1
- package/dist/chunks/{chunk-DXAZUJPA.js → chunk-R3XFY7VL.js} +1 -1
- package/dist/chunks/{chunk-EG55BFQ4.js → chunk-RLZPX4YP.js} +1 -1
- package/dist/chunks/{chunk-5ZFEQLRI.js → chunk-SDEDAHV6.js} +72 -67
- package/dist/chunks/{chunk-VESOG2SS.js → chunk-T5LE6R5S.js} +1 -1
- package/dist/chunks/chunk-TGIB24K4.js +22 -0
- package/dist/chunks/chunk-TT46OISU.js +2 -0
- package/dist/chunks/{chunk-TVQE3JMI.js → chunk-UJ5EFSEC.js} +1 -1
- package/dist/chunks/{chunk-KPDWQCF6.js → chunk-WITSXYEW.js} +1 -1
- package/dist/chunks/chunk-WV2APYWG.js +2 -0
- package/dist/chunks/chunk-XBCIBAXD.js +4 -0
- package/dist/chunks/chunk-XDMUD4FW.js +5 -0
- package/dist/chunks/chunk-XM26DGML.js +3 -0
- package/dist/chunks/{chunk-J65BMG5Q.js → chunk-XON44M6V.js} +1 -1
- package/dist/chunks/{chunk-DWGB536R.js → chunk-YBVIFIXN.js} +7 -7
- package/dist/chunks/{chunk-YWX7FKLM.js → chunk-YIB3J4RC.js} +1 -1
- package/dist/chunks/chunk-YL6VFJ4P.js +2 -0
- package/dist/chunks/cli-WPAYXAJX.js +2 -0
- package/dist/chunks/{configuration-command-75ZCMZ6X.js → configuration-command-SA56RV5B.js} +1 -1
- package/dist/chunks/connected-evidence-IVSQZYIB.js +2 -0
- package/dist/chunks/{continual-WWPXK2LO.js → continual-PKK2BOTB.js} +3 -3
- package/dist/chunks/core-commands-W5IGIITV.js +2 -0
- package/dist/chunks/datasets-KSO2UG6R.js +2 -0
- package/dist/chunks/desktop-test-6HXFM7PO.js +3 -0
- package/dist/chunks/{dist-ELWB75PL.js → dist-4HV2W6V4.js} +1 -1
- package/dist/chunks/dist-VDVI7KIO.js +2 -0
- package/dist/chunks/evaluation-coordination-MOFBXRXN.js +2 -0
- package/dist/chunks/experiment-improvements-TDHM6NEA.js +2 -0
- package/dist/chunks/experiments-HFPDFD4I.js +2 -0
- package/dist/chunks/{extension-3M2CSWZB.js → extension-R373LYIB.js} +1 -1
- package/dist/chunks/{help-RLRU33WN.js → help-PEFQDDTA.js} +1 -1
- package/dist/chunks/hosted-experiment-improvement-T6Q7ASMI.js +3 -0
- package/dist/chunks/hosted-harness-runtime-2R5QRZCG.js +2 -0
- package/dist/chunks/hosted-profile-candidate-TKOY3M4S.js +3 -0
- package/dist/chunks/hosted-profile-compiler-VLBFIEWK.js +2 -0
- package/dist/chunks/hosted-profile-evaluation-control-7B3RAZU2.js +2 -0
- package/dist/chunks/hosted-profile-evaluation-inspection-3MB6MWO6.js +3 -0
- package/dist/chunks/hosted-profile-evaluation-preparation-C7WEABZ5.js +3 -0
- package/dist/chunks/human-review-HRGGACEM.js +2 -0
- package/dist/chunks/import-RSAQ44GG.js +4 -0
- package/dist/chunks/learning-FNBEIAY6.js +2 -0
- package/dist/chunks/opchat-I7ZWJ5XK.js +3 -0
- package/dist/chunks/organizations-LFCZIH7E.js +2 -0
- package/dist/chunks/{profile-DC4UEVVG.js → profile-EPIX5QVK.js} +1 -1
- package/dist/chunks/project-agent-DGOPMECP.js +2 -0
- package/dist/chunks/sandbox-command-Q5F6VUOS.js +2 -0
- package/dist/chunks/{sandbox-template-DFHWHCIQ.js → sandbox-template-7GICPIKJ.js} +1 -1
- package/dist/chunks/{src-CREVQF7M.js → src-DH5AQ4Z7.js} +5 -5
- package/dist/chunks/src-R4TSYNTK.js +329 -0
- package/dist/chunks/{taskset-TB2ICAZU.js → taskset-LUG3ZU6J.js} +1 -1
- package/dist/chunks/{teams-bot-BNBL57S5.js → teams-bot-Z6RJGHME.js} +1 -1
- package/dist/chunks/{training-FW5FOGR3.js → training-XHE6FVII.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/web/agent-sources/SOURCES.md +11 -0
- package/dist/web/agent-sources/claude-code.svg +1 -0
- package/dist/web/agent-sources/codex.svg +1 -0
- package/dist/web/agent-sources/grok-build.svg +3 -0
- package/dist/web/agent-sources/hermes.png +0 -0
- package/dist/web/agent-sources/oh-my-pi.svg +11 -0
- package/dist/web/agent-sources/openclaw.svg +54 -0
- package/dist/web/agent-sources/opencode.svg +4 -0
- package/dist/web/agent-sources/pi.svg +6 -0
- package/dist/web/assets/App-BI-uOpnP.js +234 -0
- package/dist/web/assets/App-DkH8CeoI.css +1 -0
- package/dist/web/assets/{AppDialog-Cgn_fTGR.js → AppDialog-1iGodoot.js} +1 -1
- package/dist/web/assets/{AppTerminalPanel-cNYkSvM2.js → AppTerminalPanel-udtBdWFn.js} +2 -2
- package/dist/web/assets/AppsView-BonAGiS8.css +1 -0
- package/dist/web/assets/AppsView-DhKsU4yi.js +1 -0
- package/dist/web/assets/BrowserSidebar-BnOyqIQT.js +1 -0
- package/dist/web/assets/{CartesianChart-Bg3Lm5mZ.js → CartesianChart-C24DAywn.js} +1 -1
- package/dist/web/assets/{CollaborationTabs-BIfgIy5X.js → CollaborationTabs-DgmOF5Fe.js} +1 -1
- package/dist/web/assets/{CommandMenu-D9BimyPx.js → CommandMenu-CUNGtHwS.js} +1 -1
- package/dist/web/assets/CommunityView-CE7qeJnr.js +1 -0
- package/dist/web/assets/ComposerCreateImproveStrip-BixNsg2a.js +1 -0
- package/dist/web/assets/GetStartedView-B8gCwmBX.js +1 -0
- package/dist/web/assets/HostedModelLearningReview-CitgUNfC.js +1 -0
- package/dist/web/assets/HostedModelLearningSettings-WUaqzNsa.js +1 -0
- package/dist/web/assets/LabModelVersionDetailPage-Cx0kL69J.js +1 -0
- package/dist/web/assets/LabSkillSidebar-DRggqZ1j.js +1 -0
- package/dist/web/assets/LabsRoute-BujTZhqC.js +99 -0
- package/dist/web/assets/MainChatThread-CyA_644R.js +2 -0
- package/dist/web/assets/MainPane-DOWsSew1.css +1 -0
- package/dist/web/assets/MainPane-LaEtxydD.js +19 -0
- package/dist/web/assets/{MarkdownText-De0WzrEw.js → MarkdownText-DJI5LwT0.js} +19 -19
- package/dist/web/assets/{NativeSkillSidebar-B4jtf5RO.js → NativeSkillSidebar-CkFpWxjd.js} +1 -1
- package/dist/web/assets/{NewExperienceSwitcher-Bg1DVr96.js → NewExperienceSwitcher-DXcRHHsu.js} +1 -1
- package/dist/web/assets/{NewProjectDialog-i_wvIBw-.js → NewProjectDialog-gDzX_ZIJ.js} +1 -1
- package/dist/web/assets/OutputsPage-J_k-_N82.js +1 -0
- package/dist/web/assets/{ProjectsPage-BD0eml0M.js → ProjectsPage-BsyZmvlg.js} +1 -1
- package/dist/web/assets/RightChatPanelStack-Bz8puMUB.js +1 -0
- package/dist/web/assets/{RightSidebarHomePanel-BTpU5wGh.js → RightSidebarHomePanel-DmorYb6p.js} +1 -1
- package/dist/web/assets/ScheduledWorkPage-BFDzQUyL.js +1 -0
- package/dist/web/assets/SettingsView-BB7wCdbr.js +5 -0
- package/dist/web/assets/SettingsView-BnANbPLS.css +1 -0
- package/dist/web/assets/{TeamChatView-5LjuRNd6.js → TeamChatView-CZ3b7rq2.js} +2 -2
- package/dist/web/assets/{TerminalOverlay-BCWBSotQ.js → TerminalOverlay-Ck43Qri3.js} +12 -12
- package/dist/web/assets/{TrainingCreationPanel-hvOHRVJx.js → TrainingCreationPanel-ejqPZm3g.js} +1 -1
- package/dist/web/assets/{TrainingDraftPanel-CGEHGljE.js → TrainingDraftPanel-Cy2AQxxL.js} +1 -1
- package/dist/web/assets/{UsageSettingsSection-B8nbqhag.js → UsageSettingsSection-B7nyMItm.js} +1 -1
- package/dist/web/assets/WorkSidebarPanel-BfjAc097.js +1 -0
- package/dist/web/assets/WorkspaceDiffPanel-D9hAV8l7.js +14 -0
- package/dist/web/assets/WorkspaceEnvironmentMenu-B-K9XgFB.js +32 -0
- package/dist/web/assets/{WorkspaceGitDialogs-Dyx4Rbiy.js → WorkspaceGitDialogs-BJVFx_L3.js} +1 -1
- package/dist/web/assets/{WorkspaceMonacoEditor-B1dKexHo.js → WorkspaceMonacoEditor-p-FWMXoZ.js} +3 -3
- package/dist/web/assets/{arrow-up-right-CCj7SOGp.js → arrow-up-right-CFGI2YSt.js} +1 -1
- package/dist/web/assets/chunk-UHVJOMWN-BAlur2vw.js +1 -0
- package/dist/web/assets/{clipboard-BY6ELc9Z.js → clipboard-DIIxBort.js} +1 -1
- package/dist/web/assets/{cloud-upload-BOka5EKK.js → cloud-upload-BaQFNCTp.js} +1 -1
- package/dist/web/assets/{cssMode-C34j8ti5.js → cssMode-6LOkSggB.js} +1 -1
- package/dist/web/assets/{folder-open-CX2jidFj.js → folder-open-DZSxfPtr.js} +1 -1
- package/dist/web/assets/{folder-plus-Dh2Q9LP3.js → folder-plus-21v4D_Vx.js} +1 -1
- package/dist/web/assets/{git-commit-horizontal-CfevriuT.js → git-commit-horizontal-CgGixL64.js} +1 -1
- package/dist/web/assets/{htmlMode-BORwVkZg.js → htmlMode-B5uRraNd.js} +1 -1
- package/dist/web/assets/index-DJcUXSsN.css +1 -0
- package/dist/web/assets/{index-BBjRfC--.js → index-DOMrqhcz.js} +2 -2
- package/dist/web/assets/{info-Bv3dbs3G.js → info-BGTcmow7.js} +1 -1
- package/dist/web/assets/{jsonMode-BYWtZ6AK.js → jsonMode-D3m8N4Gi.js} +1 -1
- package/dist/web/assets/{lspLanguageFeatures-CEAdFSpU.js → lspLanguageFeatures-DoyipLsB.js} +1 -1
- package/dist/web/assets/{minimize-2-MhorZwY5.js → minimize-2-B01qSko4.js} +1 -1
- package/dist/web/assets/{monaco.contribution-ZUUVx_3M.js → monaco.contribution--U8v3jpa.js} +2 -2
- package/dist/web/assets/{monaco.contribution-CN7AWJNd.js → monaco.contribution-BJyfaGX2.js} +2 -2
- package/dist/web/assets/{monaco.contribution-CDhPpbIo.js → monaco.contribution-Bc22foTx.js} +2 -2
- package/dist/web/assets/{monaco.contribution-DHA7FuJX.js → monaco.contribution-DuRhJ6zU.js} +2 -2
- package/dist/web/assets/{monitor-DLcrkfM5.js → monitor-eZP8ZTHe.js} +1 -1
- package/dist/web/assets/play-CGsWFR_B.js +1 -0
- package/dist/web/assets/{python-CXwvPmc4.js → python-BNrLZWud.js} +1 -1
- package/dist/web/assets/{save-DaN65kMq.js → save-BLgjrccP.js} +1 -1
- package/dist/web/assets/{square-zRgIUdSv.js → square-CI1qNtvE.js} +1 -1
- package/dist/web/assets/{toggleHighContrast-DWeRZFzr.js → toggleHighContrast-B_GcTCnw.js} +1 -1
- package/dist/web/assets/{tsMode-nLBhKngY.js → tsMode-CmruH_ys.js} +1 -1
- package/dist/web/assets/{upload-BfUu4Eu1.js → upload-DnlgGS2x.js} +1 -1
- package/dist/web/assets/useLocalAgentSchedules-BBhGUfK-.js +1 -0
- package/dist/web/assets/useProviderSettings-Bw-csWbH.css +1 -0
- package/dist/web/assets/useProviderSettings-DfhdkKdC.js +5 -0
- package/dist/web/assets/{useSessionTurnCache-BQMWfV8u.js → useSessionTurnCache-BwscKl5i.js} +1 -1
- package/dist/web/assets/{wifi-off-bdka5es5.js → wifi-off-Dz-4EDCc.js} +1 -1
- package/dist/web/assets/{workers-z7XHFFNs.js → workers-Bi9u46cp.js} +1 -1
- package/dist/web/assets/{yaml-BTr4i4DD.js → yaml-DVTkiRnh.js} +1 -1
- package/dist/web/index.html +2 -2
- package/docs/command-reference.md +22 -0
- package/package.json +1 -2
- package/dist/chunks/actions-command-CRDLSPFA.js +0 -2
- package/dist/chunks/app-server-runtime-PJONTCCO.js +0 -2
- package/dist/chunks/apps-MD2DKEDW.js +0 -2
- package/dist/chunks/chunk-3BJ4P5LI.js +0 -520
- package/dist/chunks/chunk-3SRIPOJQ.js +0 -2
- package/dist/chunks/chunk-65BW2QXY.js +0 -2
- package/dist/chunks/chunk-6BL2ZIAP.js +0 -184
- package/dist/chunks/chunk-6QUICEQA.js +0 -5
- package/dist/chunks/chunk-7D2WMUWK.js +0 -3
- package/dist/chunks/chunk-7KIBRK3A.js +0 -4
- package/dist/chunks/chunk-ALZRXBEC.js +0 -33
- package/dist/chunks/chunk-ELNJUG64.js +0 -17
- package/dist/chunks/chunk-H3C4ZYEA.js +0 -16
- package/dist/chunks/chunk-HUBI3RUK.js +0 -2
- package/dist/chunks/chunk-HZP5U2AA.js +0 -3
- package/dist/chunks/chunk-KOR2AZVB.js +0 -24
- package/dist/chunks/chunk-M2YXYBSP.js +0 -2
- package/dist/chunks/chunk-MTJNKRXL.js +0 -22
- package/dist/chunks/chunk-NXUCGKY2.js +0 -5
- package/dist/chunks/chunk-PDIT2QS7.js +0 -8
- package/dist/chunks/chunk-QVRNOGAU.js +0 -21
- package/dist/chunks/chunk-TNXILYI6.js +0 -2
- package/dist/chunks/chunk-V6WBSW5Q.js +0 -3
- package/dist/chunks/chunk-VFTUP5NQ.js +0 -2
- package/dist/chunks/chunk-XWLI7WJH.js +0 -2160
- package/dist/chunks/cli-BKBH6FZY.js +0 -2
- package/dist/chunks/connected-evidence-UPUVVQ6P.js +0 -2
- package/dist/chunks/core-commands-SS2GV7WU.js +0 -2
- package/dist/chunks/datasets-TCLXV34N.js +0 -2
- package/dist/chunks/desktop-test-7ZHZHUB6.js +0 -3
- package/dist/chunks/dist-VDN6E54A.js +0 -2
- package/dist/chunks/evaluation-coordination-ZX5GLMRC.js +0 -2
- package/dist/chunks/experiment-improvements-O6DCQXCX.js +0 -2
- package/dist/chunks/experiments-JOQOBQXY.js +0 -2
- package/dist/chunks/hosted-experiment-improvement-IKO677PI.js +0 -3
- package/dist/chunks/hosted-harness-runtime-H2Q2SNZT.js +0 -2
- package/dist/chunks/hosted-profile-candidate-FHHSLJNO.js +0 -3
- package/dist/chunks/hosted-profile-compiler-5B256VV3.js +0 -2
- package/dist/chunks/hosted-profile-evaluation-control-Z25TZOW4.js +0 -2
- package/dist/chunks/hosted-profile-evaluation-inspection-MFYPLTZQ.js +0 -3
- package/dist/chunks/hosted-profile-evaluation-preparation-MAB2PSCC.js +0 -3
- package/dist/chunks/human-review-6H3BW7OZ.js +0 -2
- package/dist/chunks/learning-Y6WNDVQW.js +0 -2
- package/dist/chunks/opchat-3E4FH3DC.js +0 -3
- package/dist/chunks/organizations-PRVCUPMN.js +0 -2
- package/dist/chunks/project-agent-ZX3CELKI.js +0 -2
- package/dist/chunks/sandbox-command-HHQMZK3G.js +0 -2
- package/dist/chunks/src-MAZ7OBVY.js +0 -327
- package/dist/web/assets/App-BgeSqoRS.css +0 -1
- package/dist/web/assets/App-C6EWFrLP.js +0 -227
- package/dist/web/assets/AppsView-9zpKBSLv.js +0 -1
- package/dist/web/assets/AppsView-CzbB5pXp.css +0 -1
- package/dist/web/assets/BrowserSidebar-Xo21N1ej.js +0 -1
- package/dist/web/assets/CommunityView-BoW-yLju.js +0 -1
- package/dist/web/assets/ComposerCreateImproveStrip-BIKVEgr1.js +0 -1
- package/dist/web/assets/GetStartedView-B99v4-hh.js +0 -1
- package/dist/web/assets/HostedModelLearningReview-DEScpX2Z.js +0 -1
- package/dist/web/assets/HostedModelLearningSettings-4HT5eEiL.js +0 -1
- package/dist/web/assets/LabModelVersionDetailPage-DkYdI7gr.js +0 -1
- package/dist/web/assets/LabSkillSidebar-Bp5XYipm.js +0 -1
- package/dist/web/assets/LabsRoute-VopO7n34.js +0 -105
- package/dist/web/assets/MainChatThread-3Gg0oDZT.js +0 -2
- package/dist/web/assets/MainPane-CUqMVG9-.js +0 -19
- package/dist/web/assets/OutputsPage-CZiPxLyN.js +0 -1
- package/dist/web/assets/RightChatPanelStack-CEBFPHKP.js +0 -1
- package/dist/web/assets/ScheduledWorkPage-Y6XGoh-X.js +0 -1
- package/dist/web/assets/SettingsView-C7av3zwv.css +0 -1
- package/dist/web/assets/SettingsView-Kh14f463.js +0 -9
- package/dist/web/assets/WorkSidebarPanel-B6hlPEIs.js +0 -1
- package/dist/web/assets/WorkspaceDiffPanel-q8A15-0x.js +0 -14
- package/dist/web/assets/WorkspaceEnvironmentMenu-BiFTPWtC.js +0 -32
- package/dist/web/assets/chunk-DJWHN7NU-1eQoMoKO.js +0 -1
- package/dist/web/assets/index-B9VSiz_z.css +0 -1
- package/dist/web/assets/refresh-cw-BTfIxHb3.js +0 -1
- package/dist/web/assets/useLocalAgentSchedules-BCITWhg2.js +0 -1
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
+
import{b as e}from"./chunk-ES2ISFJC.js";import{a as o}from"./chunk-FTQLQJQV.js";import{createHash as je}from"node:crypto";function $(i){if(i===null||typeof i=="boolean"||typeof i=="string")return i;if(typeof i=="number"){if(!Number.isFinite(i))throw new Error("Canonical JSON cannot encode a non-finite number.");return i}if(Array.isArray(i))return i.map($);if(typeof i=="object"){let t={};for(let r of Object.keys(i).sort()){let n=i[r];n!==void 0&&(t[r]=$(n))}return t}throw new Error(`Canonical JSON cannot encode ${typeof i}.`)}o($,"canonicalJson");function E(i){return je("sha256").update(JSON.stringify($(i)),"utf8").digest("hex")}o(E,"canonicalHash");function Ye(i){if(!i.maxContextTokens||!i.usableContextTokens)return{shouldCompact:!1,projectedTokens:i.projectedTokens,thresholdTokens:Number.MAX_SAFE_INTEGER,usableContextTokens:0,maxContextTokens:0,tokenSource:"heuristic"};let t=Math.max(.01,Math.min(1,(i.triggerPercent??85)/100)),r=Math.max(1,Math.floor(i.usableContextTokens*t));return{shouldCompact:i.projectedTokens>=r,projectedTokens:i.projectedTokens,thresholdTokens:r,usableContextTokens:i.usableContextTokens,maxContextTokens:i.maxContextTokens,tokenSource:"heuristic"}}o(Ye,"agentCompactionDecision");async function Ze(i){await i.started();try{return await i.compact()}catch(t){throw await i.failed(t),t}}o(Ze,"runAgentCompaction");async function et(i){let t=i.host.projectEvents(i.events),r=i.host.selectEvents(t,i.maxContextTokens),{summaryEvents:n,preservedEvents:s,preservedEventIds:c}=r;if(n.length===0)throw new Error("There is not enough prior context to compact.");let l=i.host.normalizeRecords(n),d=i.host.normalizeRecords(s),h=i.host.buildFileLedger(i.host.normalizeRecords(t)),m=i.host.serializeRecords(l,i.host.inputCharBudget(i.maxContextTokens));if(!m.text.trim())throw new Error("There is not enough prior context to compact.");let g=i.host.buildSummaryMessages({serializedHistory:m.text,fileLedger:h}),v=Date.now(),k=(await i.host.streamSummary({model:i.model,messages:g,signal:i.signal})).trim(),w=Date.now()-v;if(!k)throw new Error("Compaction summary was empty.");let f=i.host.estimateProjection({events:t,preservedEvents:s,summary:k}),x=i.host.createMetrics({sourceEvents:t.length,summarizedEvents:n.length,preservedEvents:s.length,sourceRecords:m.sourceRecordCount,includedRecords:m.includedRecordCount,omittedRecords:m.omittedRecordCount,preservedRecords:d.length,truncatedRecords:m.truncatedRecordCount,summaryInputTruncated:m.inputTruncated,sourceSelectionStrategy:m.selectionStrategy,summaryInputChars:m.inputChars,retainedTailTokens:r.retainedTailTokens,retainedTailBudgetTokens:r.retainedTailBudgetTokens,finalProviderContextTokens:f.inputTokensAfter,durationMs:w,fileLedgerEntries:h.length,splitTurnId:r.splitTurnId});return{summary:k,model:i.model,compactedThroughEventId:t[t.length-1]?.id??null,compactedThroughTurnId:i.host.lastTurnId(t),preservedFromEventId:s[0]?.id??null,preservedEventIds:c,preservedResourceRefs:i.host.durableResourceRefs(i.events),sourceEventCount:n.length,preservedEventCount:s.length,fileLedger:h,inputTokensBefore:f.inputTokensBefore,inputTokensAfter:f.inputTokensAfter,maxContextTokens:i.maxContextTokens,tokenSource:"heuristic",metrics:x}}o(et,"runAgentCompactionProgram");var Se=e.enum(["thread.started","thread.resumed","turn.started","turn.steered","turn.interrupted","turn.completed","turn.failed","item.started","item.delta","item.completed","assistant.reasoning.delta","assistant.delta","tool.started","tool.completed","approval.requested","approval.resolved","user_input.requested","user_input.resolved","compaction.started","compaction.completed","harness.admitted","harness.refiner.queued","harness.refiner.started","harness.refiner.completed","harness.refiner.failed","diagnostic"]),Ee=e.object({sequence:e.number().int().nonnegative(),name:Se,source:e.enum(["runtime","provider","tool","host","refiner"]),status:e.string().trim().min(1).nullable().default(null),threadId:e.string().trim().min(1),turnId:e.string().trim().min(1).nullable().default(null),callId:e.string().trim().min(1).nullable().default(null),output:e.string().nullable().default(null),error:e.string().nullable().default(null),data:e.record(e.string(),e.unknown()).default({})}).strict();function st(i){return E(Ee.parse(i))}o(st,"canonicalEventHash");var q="2026-09-20",lt=["initialize","initialized","runtime/capabilities","thread/start","thread/resume","thread/read","turn/start","turn/steer","task/inbox","task/queue","task/inputUpdate","turn/interrupt","approval/resolve","userInput/resolve","profile/workflows","profile/evaluations","profile/trainingSource","profile/evaluations/prepare","profile/evaluations/run","profile/evaluations/runSuite","profile/evaluations/executeCase","profile/evaluations/executeRun","profile/evaluations/compare","profile/evaluations/report","experiments/executeCase","experiments/cancelCase","harness/inspect","harness/proposalReview","harness/review","harness/acceptEvaluationReview","harness/materializeEvaluationTaskset","harness/runEvaluationBaseline","harness/validate","harness/backgroundReview","harness/diff","harness/rollback","refiner/inspect","refiner/update","refiner/activate","refiner/rollback"],W=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number()]),method:e.string().trim().min(1),params:e.unknown().optional()}).strict(),Q=e.object({jsonrpc:e.literal("2.0"),method:e.string().trim().min(1),params:e.unknown().optional()}).strict(),B=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number()]),result:e.unknown()}).strict(),U=e.object({jsonrpc:e.literal("2.0"),id:e.union([e.string(),e.number(),e.null()]),error:e.object({code:e.number().int(),message:e.string(),data:e.unknown().optional()}).strict()}).strict(),ut=e.union([W,Q,B,U]),_e=e.object({protocolVersion:e.string().trim().min(1),client:e.object({name:e.string().trim().min(1),version:e.string().trim().min(1)}).strict(),capabilities:e.record(e.string(),e.unknown()).default({})}).strict(),V=class{static{o(this,"AgentJsonRpcDispatcher")}#e;#t=null;#r=!1;constructor(t){this.#e=t}get initialized(){return this.#r}async handle(t){let r=Q.safeParse(t);if(r.success&&!("id"in t)){if(r.data.method==="initialized"){if(!this.#t)throw new _(-32002,"initialize must be called first");this.#r=!0}return null}let n=W.safeParse(t);if(!n.success)return K(null,-32600,"Invalid Request",n.error.flatten());let s=n.data;try{let c=await this.#n(s.method,s.params);return{jsonrpc:"2.0",id:s.id,result:c}}catch(c){let l=c instanceof _?c:new _(-32603,c instanceof Error?c.message:String(c));return K(s.id,l.code,l.message,l.data)}}async#n(t,r){if(t==="initialize"){let n=_e.parse(r);if(n.protocolVersion!==q)throw new _(-32001,"Incompatible agent protocol version",{requested:n.protocolVersion,supported:q});return this.#t=n,{protocolVersion:q,server:{name:"openpond-app-server",version:"1"},capabilities:await this.#e.capabilities()}}if(!this.#r)throw new _(-32002,"initialized notification is required");switch(t){case"runtime/capabilities":return this.#e.capabilities(r);case"thread/start":return this.#e.threadStart(r);case"thread/resume":return this.#e.threadResume(r);case"thread/read":return this.#e.threadRead(r);case"turn/start":return this.#e.turnStart(r);case"turn/steer":return this.#e.turnSteer(r);case"task/inbox":return this.#e.taskInbox(r);case"task/queue":return this.#e.taskQueue(r);case"task/inputUpdate":return this.#e.taskInputUpdate(r);case"turn/interrupt":return this.#e.turnInterrupt(r);case"approval/resolve":return this.#e.approvalResolve(r);case"userInput/resolve":return this.#e.userInputResolve(r);case"profile/workflows":return this.#e.profileWorkflows(r);case"profile/evaluations":return this.#e.profileEvaluations(r);case"profile/trainingSource":return this.#e.profileTrainingSource(r);case"profile/evaluations/prepare":return this.#e.profileEvaluationPrepare(r);case"profile/evaluations/run":return this.#e.profileEvaluationRun(r);case"experiments/executeCase":{if(!this.#e.experimentExecuteCase)throw new Error("Experiment execution is unavailable in this runtime.");return this.#e.experimentExecuteCase(r)}case"experiments/cancelCase":{if(!this.#e.experimentCancelCase)throw new Error("Experiment cancellation is unavailable in this runtime.");return this.#e.experimentCancelCase(r)}case"profile/evaluations/runSuite":return this.#e.profileEvaluationRunSuite(r);case"profile/evaluations/executeCase":return this.#e.profileEvaluationExecuteCase(r);case"profile/evaluations/executeRun":return this.#e.profileEvaluationExecuteRun(r);case"profile/evaluations/compare":return this.#e.profileEvaluationCompare(r);case"profile/evaluations/report":return this.#e.profileEvaluationReport(r);case"harness/inspect":return this.#e.harnessInspect(r);case"harness/proposalReview":return this.#e.harnessProposalReview(r);case"harness/review":return this.#e.harnessReview(r);case"harness/acceptEvaluationReview":return this.#e.harnessAcceptEvaluationReview(r);case"harness/materializeEvaluationTaskset":return this.#e.harnessMaterializeEvaluationTaskset(r);case"harness/runEvaluationBaseline":return this.#e.harnessRunEvaluationBaseline(r);case"harness/validate":return this.#e.harnessValidate(r);case"harness/backgroundReview":return this.#e.harnessBackgroundReview(r);case"harness/diff":return this.#e.harnessDiff(r);case"harness/rollback":return this.#e.harnessRollback(r);case"refiner/inspect":return this.#e.refinerInspect(r);case"refiner/update":return this.#e.refinerUpdate(r);case"refiner/activate":return this.#e.refinerActivate(r);case"refiner/rollback":return this.#e.refinerRollback(r);default:throw new _(-32601,`Method not found: ${t}`)}}},_=class extends Error{static{o(this,"JsonRpcDispatchError")}code;data;constructor(t,r,n){super(r),this.code=t,this.data=n}};function K(i,t,r,n){return{jsonrpc:"2.0",id:i,error:{code:t,message:r,...n===void 0?{}:{data:n}}}}o(K,"jsonRpcError");var X=class{static{o(this,"AgentRpcClient")}#e;#t;constructor(t){this.#e=t.request.bind(t),this.#t=t.notify.bind(t)}async initialize(t,r={}){let n=await this.#e("initialize",{protocolVersion:q,client:t,capabilities:r});return await this.#t("initialized"),n}capabilities=o((t={})=>this.#e("runtime/capabilities",t),"capabilities");threadStart=o(t=>this.#e("thread/start",t),"threadStart");threadResume=o(t=>this.#e("thread/resume",t),"threadResume");threadRead=o(t=>this.#e("thread/read",t),"threadRead");turnStart=o(t=>this.#e("turn/start",t),"turnStart");turnSteer=o(t=>this.#e("turn/steer",t),"turnSteer");taskInbox=o(t=>this.#e("task/inbox",t),"taskInbox");taskQueue=o(t=>this.#e("task/queue",t),"taskQueue");taskInputUpdate=o(t=>this.#e("task/inputUpdate",t),"taskInputUpdate");turnInterrupt=o(t=>this.#e("turn/interrupt",t),"turnInterrupt");approvalResolve=o(t=>this.#e("approval/resolve",t),"approvalResolve");userInputResolve=o(t=>this.#e("userInput/resolve",t),"userInputResolve");profileWorkflows=o(t=>this.#e("profile/workflows",t),"profileWorkflows");profileEvaluations=o(t=>this.#e("profile/evaluations",t),"profileEvaluations");profileEvaluationPrepare=o(t=>this.#e("profile/evaluations/prepare",t),"profileEvaluationPrepare");profileEvaluationRun=o(t=>this.#e("profile/evaluations/run",t),"profileEvaluationRun");profileEvaluationRunSuite=o(t=>this.#e("profile/evaluations/runSuite",t),"profileEvaluationRunSuite");profileEvaluationExecuteCase=o(t=>this.#e("profile/evaluations/executeCase",t),"profileEvaluationExecuteCase");profileEvaluationExecuteRun=o(t=>this.#e("profile/evaluations/executeRun",t),"profileEvaluationExecuteRun");profileEvaluationCompare=o(t=>this.#e("profile/evaluations/compare",t),"profileEvaluationCompare");experimentExecuteCase=o(t=>this.#e("experiments/executeCase",t),"experimentExecuteCase");experimentCancelCase=o(t=>this.#e("experiments/cancelCase",t),"experimentCancelCase");harnessInspect=o((t={})=>this.#e("harness/inspect",t),"harnessInspect");harnessProposalReview=o((t={})=>this.#e("harness/proposalReview",t),"harnessProposalReview");harnessReview=o((t={})=>this.#e("harness/review",t),"harnessReview");harnessAcceptEvaluationReview=o((t={})=>this.#e("harness/acceptEvaluationReview",t),"harnessAcceptEvaluationReview");harnessMaterializeEvaluationTaskset=o((t={})=>this.#e("harness/materializeEvaluationTaskset",t),"harnessMaterializeEvaluationTaskset");harnessRunEvaluationBaseline=o((t={})=>this.#e("harness/runEvaluationBaseline",t),"harnessRunEvaluationBaseline");harnessValidate=o((t={})=>this.#e("harness/validate",t),"harnessValidate");harnessBackgroundReview=o((t={})=>this.#e("harness/backgroundReview",t),"harnessBackgroundReview");harnessDiff=o((t={})=>this.#e("harness/diff",t),"harnessDiff");harnessRollback=o((t={})=>this.#e("harness/rollback",t),"harnessRollback");refinerInspect=o(t=>this.#e("refiner/inspect",t),"refinerInspect");refinerUpdate=o(t=>this.#e("refiner/update",t),"refinerUpdate");refinerActivate=o(t=>this.#e("refiner/activate",t),"refinerActivate");refinerRollback=o(t=>this.#e("refiner/rollback",t),"refinerRollback")};var D=e.object({caseId:e.string().trim().min(1).max(191),admissionHash:e.string().regex(/^[a-f0-9]{64}$/),definitionHash:e.string().regex(/^[a-f0-9]{64}$/),ordinal:e.number().int().nonnegative(),operation:e.enum(["create","reset","step","collect","destroy"]),value:e.record(e.string(),e.unknown()),timeoutMs:e.number().int().min(1).max(3e4)}).strict();var u=e.string().trim().min(1).max(200),O=e.string().trim().min(1).max(32e3),P=e.number().int().nonnegative(),Y=e.object({id:u,sessionId:u,senderSessionId:u.nullable(),senderKind:e.enum(["user","task","runtime"]),kind:e.enum(["steer","message","followup","queued","result"]),body:O,payload:e.record(e.string(),e.unknown()),idempotencyKey:u,replyTo:u.nullable(),expectedTurnId:u.nullable()}).strict(),Re=e.discriminatedUnion("action",[e.object({action:e.literal("resume"),expectedRevision:e.number().int().positive()}).strict(),e.object({action:e.literal("cancel"),expectedRevision:e.number().int().positive()}).strict(),e.object({action:e.literal("edit"),expectedRevision:e.number().int().positive(),body:O}).strict(),e.object({action:e.literal("steer"),expectedRevision:e.number().int().positive(),expectedTurnId:u}).strict()]),Z=e.object({id:u,sessionId:u,turnId:u,targetSessionId:u.nullable(),targetTurnId:u.nullable(),targetInputId:u.nullable(),afterSequence:P,deadline:e.string(),state:e.enum(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:e.string(),updatedAt:e.string()}).strict(),ee=e.record(e.string(),e.unknown()),Te=e.enum(["queued","running","completed","failed","cancelled","needs_resume"]),Ce=e.object({parentSessionId:u.nullable().optional(),childSessionId:u.nullable().optional(),status:e.array(Te).nullable().optional(),afterId:e.string().max(200),limit:e.number().int().min(1).max(10)}).strict(),te=e.discriminatedUnion("action",[e.object({action:e.literal("recoverTaskInboxOwners"),ownerId:u}).strict(),e.object({action:e.literal("hasTaskCompletion"),turnId:u}).strict(),e.object({action:e.literal("taskInboxSnapshot"),sessionId:u}).strict(),e.object({action:e.literal("taskInboxSnapshotInputs"),sessionId:u,afterSequence:P}).strict(),e.object({action:e.literal("declareTaskWork"),sessionId:u,turnId:u,ownerId:u,areas:e.array(O).max(100)}).strict(),e.object({action:e.literal("taskWorkAreas"),sessionId:u}).strict(),e.object({action:e.literal("admitTaskInput"),input:Y}).strict(),e.object({action:e.literal("admitTaskInputs"),inputs:e.array(Y).max(50)}).strict(),e.object({action:e.literal("rejectTaskInput"),id:u,error:O}).strict(),e.object({action:e.literal("getTaskInput"),id:u}).strict(),e.object({action:e.literal("taskInputsForSession"),sessionId:u,query:e.object({afterSequence:P.optional(),pendingOnly:e.boolean().optional(),limit:e.number().int().min(1).max(500).optional()}).strict()}).strict(),e.object({action:e.literal("mutateTaskInput"),sessionId:u,inputId:u,change:Re}).strict(),e.object({action:e.literal("openTaskInboxTurn"),sessionId:u,turnId:u,ownerId:u}).strict(),e.object({action:e.literal("renewTaskInboxTurn"),sessionId:u,turnId:u,ownerId:u}).strict(),e.object({action:e.literal("pendingTaskInputs"),sessionId:u,turnId:u,afterSequence:P}).strict(),e.object({action:e.literal("taskAssignmentInputs"),turnId:u,afterSequence:P}).strict(),e.object({action:e.literal("pauseTaskInboxTurn"),sessionId:u,turnId:u,ownerId:u}).strict(),e.object({action:e.literal("includeTaskInputs"),sessionId:u,turnId:u,ownerId:u,requestId:u}).strict(),e.object({action:e.literal("settleTaskInputRequest"),requestId:u,outcome:e.enum(["resolved","failed","replaced"])}).strict(),e.object({action:e.literal("sealTaskInboxTurn"),sessionId:u,turnId:u,ownerId:u}).strict(),e.object({action:e.literal("sealNativeTaskInboxTurn"),sessionId:u,turnId:u,ownerId:u}).strict(),e.object({action:e.literal("closeTaskInboxTurn"),sessionId:u,turnId:u,ownerId:u,outcome:e.enum(["completed","failed","interrupted"])}).strict(),e.object({action:e.literal("taskInboxPaused"),sessionId:u}).strict(),e.object({action:e.literal("reserveTaskFollowup"),sessionId:u,turnId:u,ownerId:u}).strict(),e.object({action:e.literal("taskInboxWakeTargets"),afterSessionId:e.string().max(200)}).strict(),e.object({action:e.literal("createTaskWait"),value:Z}).strict(),e.object({action:e.literal("settleTaskWait"),id:u,state:Z.shape.state}).strict(),e.object({action:e.literal("taskWaitsForSession"),sessionId:u,afterId:e.string().max(200)}).strict(),e.object({action:e.literal("commitSubagentCompletion"),value:ee,turnId:u}).strict(),e.object({action:e.literal("pendingTaskCompletions"),afterTurnId:e.string().max(200)}).strict(),e.object({action:e.literal("settleTaskCompletion"),turnId:u,inputId:u}).strict(),e.object({action:e.literal("upsertSubagentRun"),value:ee}).strict(),e.object({action:e.literal("getSubagentRun"),id:u}).strict(),e.object({action:e.literal("listSubagentRuns"),query:Ce}).strict()]);var A=e.string().trim().min(1).max(191),re=e.object({createdAt:e.string().min(1),id:A}).strict(),ne=e.enum(["trigger_decision","route_decision","refiner_outcome","proposal","targeted_validation","apply_receipt"]),ie=e.discriminatedUnion("action",[e.object({action:e.literal("active_release"),workspaceId:A}).strict(),e.object({action:e.literal("put_artifact"),workspaceId:A,kind:ne,artifact:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("artifact_page"),workspaceId:A,kind:ne,before:re.nullable(),limit:e.number().int().min(1).max(200)}).strict(),e.object({action:e.literal("pending_trigger_page"),workspaceId:A,before:re.nullable(),limit:e.number().int().min(1).max(200)}).strict()]);var b=e.string().trim().min(1).max(240),se=e.string().regex(/^[a-f0-9]{64}$/),oe=e.enum(["run_overlay","observation","trigger_decision","route_decision","proposal","targeted_validation","apply_receipt","refiner_outcome"]),ae=e.object({createdAt:e.string().datetime(),id:b}).strict(),ce=e.discriminatedUnion("action",[e.object({action:e.literal("artifact_put"),workspaceId:b,kind:oe,artifact:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("artifact_page"),workspaceId:b,kind:oe,before:ae.nullable(),limit:e.number().int().min(1).max(100)}).strict(),e.object({action:e.literal("pending_page"),workspaceId:b,before:ae.nullable(),limit:e.number().int().min(1).max(100)}).strict(),e.object({action:e.literal("workspace_get"),workspaceId:b}).strict(),e.object({action:e.literal("background_get"),workspaceId:b}).strict(),e.object({action:e.literal("overlay_get"),runId:b}).strict(),e.object({action:e.literal("overlay_freeze"),runId:b,expectedRevision:e.number().int().nonnegative(),overlay:e.record(e.string(),e.unknown()),proposal:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("memory_get"),workspaceId:b,sessionId:b,key:b}).strict(),e.object({action:e.literal("memory_page"),workspaceId:b,sessionId:b,before:e.object({updatedAt:e.string().datetime(),key:b}).strict().nullable(),limit:e.number().int().min(1).max(20),includeDeleted:e.boolean()}).strict(),e.object({action:e.literal("memory_write"),sessionId:b,input:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("release_get"),contentHash:se}).strict(),e.object({action:e.literal("release_put"),record:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("session_get"),sessionId:b}).strict(),e.object({action:e.literal("turn_get"),turnId:b}).strict(),e.object({action:e.literal("turn_page"),sessionId:b,before:e.number().int().positive().nullable(),limit:e.number().int().min(1).max(100)}).strict(),e.object({action:e.literal("event_page"),turnId:b,afterSequence:e.number().int().nonnegative(),names:e.array(b).max(40),limit:e.number().int().min(1).max(100)}).strict(),e.object({action:e.literal("event_append"),event:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("usage_put"),record:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("snapshot_restore"),turnId:b,expectedHash:se,snapshot:e.record(e.string(),e.unknown())}).strict()]);var j=e.string().trim().min(1).max(200),le=e.string().regex(/^[a-f0-9]{64}$/),qe=e.object({kind:e.enum(["structural","visual","test","user_review"]),status:e.enum(["passed","failed","not_run"]),label:e.string().trim().min(1).max(240),detail:e.string().trim().max(4e3).nullable().optional(),ref:e.string().trim().max(4096).nullable().optional()}),ue=e.object({id:j,title:e.string().trim().min(1).max(240),sourceTaskId:j,sourceTurnId:j,revision:e.number().int().positive(),createdAt:e.string().datetime(),contentType:e.string().trim().min(1).max(200),sizeBytes:e.number().int().min(1).max(1e7),sha256:le,validation:e.array(qe).max(32)}).strict(),de=e.object({sessionId:j,turnId:j,output:ue}).strict(),pe=e.object({uploadId:j,index:e.number().int().min(0).max(1024),offset:e.number().int().min(0).max(1e7),sha256:le,contentsBase64:e.string().min(1).max(131072)}).strict(),me=e.object({uploadId:j}).strict(),Pe=ue.pick({id:!0,title:!0,sourceTaskId:!0,sourceTurnId:!0,revision:!0,createdAt:!0,validation:!0}),he=e.object({sessionId:j,turnId:j,output:Pe,sandboxPath:e.string().trim().min(1).max(4096)}).strict();var z=e.string().trim().min(1).max(200),Ae=e.object({type:e.enum(["create","get","start","stop","exec","open_port","list_files","download_file","upload_file","search_files","delete_file","stat_file","mkdir","move_file","process_start","process_get","git_status","git_diff","git_export_patch","git_branch","git_commit","git_pull","git_push"]),sandboxId:z.optional(),payload:e.unknown().optional(),processId:z.optional(),failOnUnpreservedChanges:e.boolean().optional()}).strict().superRefine((i,t)=>{i.type!=="create"&&!i.sandboxId&&t.addIssue({code:"custom",message:"Sandbox identity is required."}),i.type==="create"&&i.sandboxId&&t.addIssue({code:"custom",message:"Create cannot target a sandbox identity."}),i.type==="process_get"&&!i.processId&&t.addIssue({code:"custom",message:"Process identity is required."})}),fe=e.object({action:Ae}).strict(),be=e.object({sessionId:z,turnId:z,name:z}).strict();var p=1,a=e.string().trim().min(1).max(191),R=e.number().int().min(1).max(200),Ht=e.object({teamId:a,ownerUserId:a,workspaceId:a,conversationId:a,turnId:a,attempt:e.number().int().min(1),leaseGeneration:e.number().int().min(1)}).strict(),ge=e.discriminatedUnion("operation",[e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/list"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/read"),params:e.object({fileId:a,revision:e.number().int().min(1),offset:e.number().int().min(0).max(1e7).optional(),maxChars:e.number().int().min(1).max(1e5).optional(),firstPage:e.number().int().min(1).max(1e3).optional(),pageCount:e.number().int().min(1).max(10).optional()}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("profile.externalDataset.authorize"),params:e.object({bindingHash:e.string().regex(/^[a-f0-9]{64}$/),manifestHash:e.string().regex(/^[a-f0-9]{64}$/).optional(),taskId:a.optional(),seed:e.string().min(1).max(500).optional()}).strict().refine(i=>!!i.taskId==!!i.seed,"Case authority requires both task and seed.")}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("experiment/environment"),params:D}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("experiment/policy"),params:e.object({caseId:a,admissionHash:e.string().regex(/^[a-f0-9]{64}$/),ordinal:e.number().int().nonnegative(),messages:e.array(e.record(e.string(),e.unknown())).max(2e3),tools:e.array(e.record(e.string(),e.unknown())).max(200)}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("sandbox/request"),params:fe}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("embedding/authorize"),params:be}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/begin"),params:de}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/chunk"),params:pe}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/complete"),params:me}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("output/saveSandboxFile"),params:he}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("settings/get"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/get"),params:e.object({reference:e.object({id:a,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict().nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/overlay/get"),params:e.object({runId:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/overlay/put"),params:e.object({runId:a,expectedRevision:e.number().int().min(0).nullable(),overlay:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/overlay/freezeProposal"),params:e.object({runId:a,expectedRevision:e.number().int().min(0),overlay:e.record(e.string(),e.unknown()),proposal:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/memory/get"),params:e.object({workspaceId:a,key:e.string().min(1).max(120)}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/memory/list"),params:e.object({workspaceId:a,includeDeleted:e.boolean(),before:e.object({updatedAt:e.string(),key:e.string()}).strict().nullable(),limit:R}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/memory/search"),params:e.object({workspaceId:a,query:e.string().trim().min(1).max(500),limit:e.number().int().min(1).max(20)}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/memory/write"),params:e.object({input:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/state/read"),params:e.object({workspaceId:a,kind:e.enum(["selection","workspace_settings","evaluation_review_settings","candidates","cross_run_requests"]),afterId:a.nullable(),limit:e.number().int().min(1).max(100)}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("profile-evaluations/execute"),params:e.discriminatedUnion("action",[e.object({action:e.literal("get"),kind:e.enum(["grade","receipt","run","comparison","suite"]),id:a}).strict(),e.object({action:e.literal("page"),kind:e.enum(["grade","receipt","run","comparison","suite"]),profileKey:e.string().regex(/^[a-f0-9]{64}$/),before:e.object({createdAt:e.string(),id:a}).strict().nullable(),limit:e.number().int().min(1).max(100)}).strict(),e.object({action:e.literal("put"),kind:e.enum(["grade","receipt","run","comparison","suite"]),payload:e.record(e.string(),e.unknown()),profileKey:e.string().regex(/^[a-f0-9]{64}$/).nullable(),createdAt:e.string()}).strict()])}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/workspace/transition"),params:e.discriminatedUnion("action",[e.object({action:e.literal("advance"),receiptId:a,workspaceId:a,proposal:e.record(e.string(),e.unknown()),validations:e.array(e.record(e.string(),e.unknown())).max(100),nextRelease:e.object({id:a,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),nextSourceRevision:e.string().min(1),now:e.string()}).strict(),e.object({action:e.literal("reviewedAdvance"),receiptId:a,workspaceId:a,proposal:e.record(e.string(),e.unknown()),validations:e.array(e.record(e.string(),e.unknown())).max(100),nextRelease:e.object({id:a,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),nextSourceRevision:e.string().min(1),reviewer:a,now:e.string()}).strict(),e.object({action:e.literal("rollback"),receiptId:a,workspaceId:a,expectedWorkspaceRevision:e.number().int().nonnegative(),expectedChannelRevision:e.number().int().nonnegative(),targetRelease:e.object({id:a,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),targetSourceRevision:e.string().min(1),rollbackOf:e.object({id:a,contentHash:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),now:e.string()}).strict()])}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("task-inbox/execute"),params:te}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("harness/review/execute"),params:ce}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("refiner/execute"),params:e.object({action:ie}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("create-improve/execute"),params:e.discriminatedUnion("action",[e.object({action:e.literal("get"),runId:a}).strict(),e.object({action:e.literal("page"),query:e.object({profileId:a.nullable(),targetKind:a.nullable(),targetId:a.nullable(),state:e.array(a).max(20)}).strict(),before:e.object({updatedAt:e.string(),id:a}).strict().nullable(),limit:R}).strict(),e.object({action:e.literal("put"),run:e.record(e.string(),e.unknown())}).strict(),e.object({action:e.literal("mutate"),mutation:e.record(e.string(),e.unknown()),next:e.record(e.string(),e.unknown())}).strict()])}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("approval/get"),params:e.object({approvalId:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("approval/upsert"),params:e.object({approval:e.record(e.string(),e.unknown()),expectedRevision:e.number().int().min(1).nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("usage/getByRequestId"),params:e.object({requestId:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("usage/upsert"),params:e.object({record:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("usage/page"),params:e.object({query:e.object({sessionId:a.optional(),turnId:a.optional(),provider:a.optional(),model:a.optional(),startedAtFrom:e.string().optional(),startedAtTo:e.string().optional(),visibility:e.enum(["user_facing","background","system"]).optional(),status:e.enum(["started","completed","failed","interrupted","missing"]).optional()}).strict(),before:e.object({startedAt:e.string(),requestOrdinal:e.number().int().min(0),id:a}).strict().nullable(),limit:R}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("capabilities"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("session/count"),params:e.object({}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("session/get"),params:e.object({sessionId:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("session/page"),params:e.object({afterId:a.nullable(),limit:R}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("session/put"),params:e.object({sessionId:a,expectedRevision:e.number().int().min(1).nullable(),session:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("turn/count"),params:e.object({sessionId:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("turn/wakeCount"),params:e.object({sessionId:a,key:e.enum(["messageId","fromRunId"]),value:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("turn/get"),params:e.object({turnId:a}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("turn/put"),params:e.object({sessionId:a,turnId:a,expectedRevision:e.number().int().min(1).nullable(),turn:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("turn/latest"),params:e.object({sessionId:a,status:e.enum(["in_progress","completed","failed","interrupted"]).nullable()}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("turn/page"),params:e.object({sessionId:a,beforeSortIndex:e.number().int().min(0).nullable().optional(),limit:R}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("thread/turnPage"),params:e.object({sessionId:a,beforeSortIndex:e.number().int().min(0).nullable().optional(),limit:R}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("event/append"),params:e.object({event:e.record(e.string(),e.unknown())}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("events/page"),params:e.object({sessionId:a.nullable(),afterSequence:e.number().int().min(0),beforeSequence:e.number().int().min(1).nullable().optional(),limit:R,excludeReasoningDeltas:e.boolean().optional()}).strict()}).strict(),e.object({contractVersion:e.literal(p),requestId:a,operation:e.literal("events/latestAssistantText"),params:e.object({sessionId:a}).strict()}).strict()]),Vt=e.object({contractVersion:e.literal(p),operations:e.array(e.enum(["experiment/policy","experiment/environment","sandbox/request","embedding/authorize","output/begin","output/chunk","output/complete","output/saveSandboxFile","output/list","output/read","settings/get","harness/get","harness/overlay/get","harness/overlay/put","harness/overlay/freezeProposal","harness/memory/get","harness/memory/list","harness/memory/search","harness/memory/write","harness/state/read","profile-evaluations/execute","harness/review/execute","harness/workspace/transition","task-inbox/execute","refiner/execute","create-improve/execute","approval/get","approval/upsert","usage/getByRequestId","usage/upsert","usage/page","session/count","session/get","session/page","session/put","turn/count","turn/wakeCount","turn/get","turn/put","turn/latest","turn/page","thread/turnPage","event/append","events/page","events/latestAssistantText"])).max(50),allowedTools:e.array(a).max(128),maxPageSize:R,maxRequestBytes:e.number().int().min(1).max(8388608),maxInFlight:e.number().int().min(1).max(64)}).strict();var we=class{static{o(this,"AgentHostStorageClient")}#e=new Map;#t=null;#r=1;bind(t){if(this.#t)throw new Error("Host storage client is already bound.");this.#t=t}async request(t,r=15e3){let n=ge.parse(t);if(!this.#t)throw new Error("Host storage transport is unavailable.");if(this.#e.size>=32)throw new Error("Host storage request limit exceeded.");let s=`host-storage:${this.#r++}`,c={jsonrpc:"2.0",id:s,method:"host/storage",params:n},l=n.operation==="experiment/policy"||n.operation==="experiment/environment";if(Buffer.byteLength(JSON.stringify(c))>(l?8388608:256e3))throw new Error("Host storage request is too large.");let d=new Promise((h,m)=>{let g=n.operation==="sandbox/request"||l?3e5:6e4,v=setTimeout(()=>{this.#e.delete(s),m(new Error("Host storage request timed out."))},Math.max(1,Math.min(g,r)));this.#e.set(s,{resolve:h,reject:m,timer:v,maxResponseBytes:n.operation==="experiment/environment"?16e5:1e6})});try{await this.#t(c)}catch(h){let m=this.#e.get(s);m&&(clearTimeout(m.timer),this.#e.delete(s),m.reject(h instanceof Error?h:new Error(String(h))))}return d}accept(t){let r=B.safeParse(t),n=r.success?null:U.safeParse(t),s=r.success?r.data:n?.success?n.data:null;if(!s||typeof s.id!="string"||!s.id.startsWith("host-storage:"))return!1;let c=this.#e.get(s.id);return c?(clearTimeout(c.timer),this.#e.delete(s.id),Buffer.byteLength(JSON.stringify(s))>c.maxResponseBytes?(c.reject(new Error("Host storage response is too large.")),!0):("error"in s?c.reject(new Error(`Host storage request failed: ${s.error.message}`)):c.resolve(s.result),!0)):!0}close(){this.#t=null;for(let t of this.#e.values())clearTimeout(t.timer),t.reject(new Error("Host storage transport closed."));this.#e.clear()}};import{once as ze}from"node:events";import{createInterface as He}from"node:readline";async function Ft(i){let t=null,r=Promise.resolve(),n=[],s=o(f=>(r=r.then(async()=>{i.writable.write(`${JSON.stringify(f)}
|
|
3
|
+
`)||await ze(i.writable,"drain")}),r),"write");i.hostStorageClient?.bind(f=>s(f));let c=o(()=>{if(!(!t?.initialized||n.length===0))for(let f of n.splice(0))s(f)},"flushPendingNotifications"),l,d=new Set,h=He({input:i.readable,crlfDelay:1/0}),m=[],g=!1,v=null,k=o(async f=>{let x=t;if(!x)throw new Error("Agent runtime dispatcher is unavailable.");let S=(async()=>{let G=await x.handle(f);G&&await s(G),c()})(),F=f&&typeof f=="object"&&"method"in f?f.method:null;if(F==="initialize"||F==="initialized"){await S;return}d.add(S),S.finally(()=>d.delete(S))},"dispatch"),w=(async()=>{let f=typeof i.host=="function"?await i.host():i.host;for(t=new V(f),l=f.subscribe?.(x=>{if(!t?.initialized){n.push(x);return}s(x)});m.length>0;)await k(m.shift());g=!0})().catch(f=>{v=f,h.close()});try{for await(let f of h){if(!f.trim())continue;if(Buffer.byteLength(f,"utf8")>1e6){await s({jsonrpc:"2.0",id:null,error:{code:-32600,message:"Request exceeds the JSONL size limit"}});continue}let x;try{x=JSON.parse(f)}catch{await s({jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}});continue}if(!i.hostStorageClient?.accept(x))if(g)await k(x);else if(m.length>=64){let S=x&&typeof x=="object"&&"id"in x?x.id:null;(typeof S=="string"||typeof S=="number")&&await s({jsonrpc:"2.0",id:S,error:{code:-32e3,message:"Runtime startup request limit exceeded"}})}else m.push(x)}if(await w,v)throw v;await Promise.all(d),await r}finally{i.hostStorageClient?.close(),l?.()}}o(Ft,"runAgentJsonlServer");var M=e.object({threadId:e.string().trim().min(1)}).passthrough(),Ve=M.extend({includeHistory:e.boolean().optional()}),Oe=e.object({session:e.unknown()}).strict(),H=M.extend({input:e.unknown()}),Me=H.extend({idempotencyKey:e.string().trim().min(1).max(200)}),Ne=H.extend({inputId:e.string().trim().min(1)}),Le=M.extend({reason:e.string().trim().min(1).optional()}),$e=e.object({approvalId:e.string().trim().min(1),input:e.unknown()}).strict();function tr(i){let t=o(async(n,s,c)=>{let l=performance.now();i.telemetry?.({method:n,phase:"started",threadId:s,durationMs:null,errorClass:null});try{let d=await c();return i.telemetry?.({method:n,phase:"completed",threadId:s,durationMs:performance.now()-l,errorClass:null}),d}catch(d){throw i.telemetry?.({method:n,phase:"failed",threadId:s,durationMs:performance.now()-l,errorClass:d instanceof Error?d.name:"UnknownError"}),d}},"run"),r=o(async(n,s="thread/read")=>{let{threadId:c,includeHistory:l}=Ve.parse(n);return t(s,c,async()=>{if(l===!1)return{thread:await i.readThread(c),turns:[],events:[]};let[d,h,m]=await Promise.all([i.readThread(c),i.listTurns(c),i.listEvents(c)]);return{thread:d,turns:h,events:m}})},"threadRead");return{capabilities:o(n=>t("runtime/capabilities",null,()=>i.capabilities(n)),"capabilities"),threadStart:o(async n=>t("thread/start",null,async()=>({thread:await i.createThread(Oe.parse(n).session)})),"threadStart"),threadResume:o(n=>r(n,"thread/resume"),"threadResume"),threadRead:r,turnStart:o(async n=>{let s=H.parse(n);return t("turn/start",s.threadId,async()=>({turn:await i.startTurn(s.threadId,s.input)}))},"turnStart"),turnSteer:o(async n=>{let s=H.parse(n);return t("turn/steer",s.threadId,async()=>({receipt:await i.steerTurn(s.threadId,s.input)}))},"turnSteer"),taskInbox:o(async n=>{let{threadId:s}=M.parse(n);return t("task/inbox",s,()=>i.readTaskInbox(s))},"taskInbox"),taskQueue:o(async n=>{let s=Me.parse(n);return t("task/queue",s.threadId,()=>i.queueTaskInput(s.threadId,s.input,s.idempotencyKey))},"taskQueue"),taskInputUpdate:o(async n=>{let s=Ne.parse(n);return t("task/inputUpdate",s.threadId,()=>i.updateTaskInput(s.threadId,s.inputId,s.input))},"taskInputUpdate"),turnInterrupt:o(async n=>{let s=Le.parse(n);return t("turn/interrupt",s.threadId,async()=>({turn:await i.interruptTurn(s.threadId,s.reason)}))},"turnInterrupt"),approvalResolve:o(async n=>{let s=$e.parse(n);return t("approval/resolve",null,async()=>({approval:await i.resolveApproval(s.approvalId,s.input)}))},"approvalResolve"),userInputResolve:o(async n=>{let s=H.parse(n);return t("userInput/resolve",s.threadId,async()=>(i.isTurnActive(s.threadId)&&await i.waitForTurnSettlement(s.threadId),{turn:await i.startTurn(s.threadId,s.input)}))},"userInputResolve"),profileWorkflows:o(()=>t("profile/workflows",null,()=>i.listProfileWorkflows()),"profileWorkflows"),profileEvaluations:o(n=>t("profile/evaluations",null,()=>i.listProfileEvaluations(n)),"profileEvaluations"),profileTrainingSource:o(()=>t("profile/trainingSource",null,()=>i.loadProfileTrainingSource()),"profileTrainingSource"),profileEvaluationPrepare:o(n=>t("profile/evaluations/prepare",null,()=>i.prepareProfileEvaluationRun(n)),"profileEvaluationPrepare"),profileEvaluationRun:o(n=>t("profile/evaluations/run",null,()=>i.runPreparedProfileEvaluation(n)),"profileEvaluationRun"),...i.executeExperimentCase?{experimentExecuteCase:o(n=>t("experiments/executeCase",null,()=>i.executeExperimentCase(n)),"experimentExecuteCase")}:{},...i.cancelExperimentCase?{experimentCancelCase:o(n=>t("experiments/cancelCase",null,()=>i.cancelExperimentCase(n)),"experimentCancelCase")}:{},profileEvaluationRunSuite:o(n=>t("profile/evaluations/runSuite",null,()=>i.runProfileEvaluationSuite(n)),"profileEvaluationRunSuite"),profileEvaluationExecuteCase:o(n=>t("profile/evaluations/executeCase",null,()=>i.executeProfileEvaluationCase(n)),"profileEvaluationExecuteCase"),profileEvaluationExecuteRun:o(n=>t("profile/evaluations/executeRun",null,()=>i.executeProfileEvaluationRun(n)),"profileEvaluationExecuteRun"),profileEvaluationCompare:o(n=>t("profile/evaluations/compare",null,()=>i.compareProfileEvaluationRuns(n)),"profileEvaluationCompare"),profileEvaluationReport:o(n=>t("profile/evaluations/report",null,()=>i.buildProfileEvaluationReport(n)),"profileEvaluationReport"),harnessInspect:o(()=>t("harness/inspect",null,()=>i.inspectHarness()),"harnessInspect"),harnessProposalReview:o(n=>t("harness/proposalReview",null,()=>i.reviewHarnessProposal(n)),"harnessProposalReview"),harnessReview:o(n=>t("harness/review",null,()=>i.reviewHarness(n)),"harnessReview"),harnessAcceptEvaluationReview:o(n=>t("harness/acceptEvaluationReview",null,()=>i.acceptHarnessEvaluationReview(n)),"harnessAcceptEvaluationReview"),harnessMaterializeEvaluationTaskset:o(n=>t("harness/materializeEvaluationTaskset",null,()=>i.materializeHarnessEvaluationTaskset(n)),"harnessMaterializeEvaluationTaskset"),harnessRunEvaluationBaseline:o(n=>t("harness/runEvaluationBaseline",null,()=>i.runHarnessEvaluationBaseline(n)),"harnessRunEvaluationBaseline"),harnessValidate:o(()=>t("harness/validate",null,()=>i.validateHarness()),"harnessValidate"),harnessBackgroundReview:o(n=>t("harness/backgroundReview",null,()=>i.updateHarnessBackgroundReview(n)),"harnessBackgroundReview"),harnessDiff:o(n=>t("harness/diff",null,()=>i.diffHarness(n)),"harnessDiff"),harnessRollback:o(n=>t("harness/rollback",null,()=>i.rollbackHarness(n)),"harnessRollback"),refinerInspect:o(()=>t("refiner/inspect",null,()=>i.inspectRefiner()),"refinerInspect"),refinerUpdate:o(n=>t("refiner/update",null,()=>i.updateRefiner(n)),"refinerUpdate"),refinerActivate:o(n=>t("refiner/activate",null,()=>i.activateRefiner(n)),"refinerActivate"),refinerRollback:o(n=>t("refiner/rollback",null,()=>i.rollbackRefiner(n)),"refinerRollback"),subscribe:i.subscribeEvents&&i.eventNotification?n=>i.subscribeEvents(s=>n(i.eventNotification(s))):void 0}}o(tr,"createAgentRuntimeService");var T=e.string().regex(/^[a-f0-9]{64}$/),Be=e.object({harnessReleaseHash:T,instructionsHash:T,skillHashes:e.record(e.string(),T),agentAssetHashes:e.record(e.string(),T),toolCatalogHash:T,memoryRevision:e.number().int().nonnegative().nullable()}).strict(),Ue=e.object({protocolVersion:e.string().trim().min(1),threadId:e.string().trim().min(1),turnId:e.string().trim().min(1),harnessReleaseHash:T,toolCatalogHash:T,context:e.record(e.string(),e.unknown()),pendingInteraction:e.record(e.string(),e.unknown()).nullable(),usage:e.record(e.string(),e.unknown())}).strict();function or(i){return E(Be.parse(i))}o(or,"effectiveSurfaceHash");function ar(i){return E(Ue.parse(i))}o(ar,"checkpointHash");function cr(i){return[i.system,...i.harnessInstructions,...i.skillInstructions,...i.hostInstructions??[]].map(t=>t.trim()).filter(Boolean).join(`
|
|
4
|
+
|
|
5
|
+
`)}o(cr,"materializeAgentPrompt");function mr(i){let t=new Map;for(let l of i){let d=l.name.trim();if(!d)throw new Error("Agent tool names cannot be empty.");if(t.has(d))throw new Error(`Duplicate agent tool: ${d}.`);if(!l.unavailableReason&&!l.execute)throw new Error(`Agent tool ${d} is declared as available without an executor.`);t.set(d,{...l,name:d})}let r=[...t.values()].sort((l,d)=>l.name.localeCompare(d.name)),n=r.filter(l=>!l.unavailableReason).map(l=>({name:l.name,description:l.description,inputSchema:e.toJSONSchema(l.inputSchema,{target:"draft-7",unrepresentable:"any"})})),s=r.map(l=>({name:l.name,displayLabel:l.displayLabel??l.name,placement:l.placement,available:!l.unavailableReason,unavailableReason:l.unavailableReason??null})),c=E({modelTools:n,capabilities:s});return{byName:t,tools:r,modelTools:n,capabilities:s,hash:c}}o(mr,"createAgentToolCatalog");async function hr(i,t){let r=i.byName.get(t.name);if(!r)throw new Error(`Unknown agent tool: ${t.name}.`);if(r.unavailableReason)throw new Error(`Agent tool ${t.name} is unavailable: ${r.unavailableReason}`);if(!r.execute)throw new Error(`Agent tool ${t.name} has no executor.`);return r.execute(r.inputSchema.parse(t.arguments),t.context)}o(hr,"executeAgentTool");function fr(i){let t=new Set,r=[...i].map(c=>{let l=c.name.trim();if(!l)throw new Error("Agent tool names cannot be empty.");if(t.has(l))throw new Error(`Duplicate agent tool: ${l}.`);if(t.add(l),!c.unavailableReason&&!c.executorAvailable)throw new Error(`Agent tool ${l} is declared as available without an executor.`);return{...c,name:l}}).sort((c,l)=>c.name.localeCompare(l.name)),n=r.filter(c=>!c.unavailableReason).map(c=>({name:c.name,description:c.description,inputSchema:c.inputSchema})),s=r.map(c=>({name:c.name,displayLabel:c.displayLabel??c.name,placement:c.placement,available:!c.unavailableReason,unavailableReason:c.unavailableReason??null}));return{byName:new Map(r.map(c=>[c.name,c])),tools:r,modelTools:n,capabilities:s,hash:E({modelTools:n,capabilities:s})}}o(fr,"createAgentToolCatalogProjection");async function br(i,t){let r=i.byName.get(t.name);if(!r)throw new Error(`Unknown agent tool: ${t.name}.`);if(r.unavailableReason)throw new Error(`Agent tool ${t.name} is unavailable: ${r.unavailableReason}`);if(!r.execute)throw new Error(`Agent tool ${t.name} has no executor.`);let n=r.validateArguments?r.validateArguments(t.arguments):t.arguments;return r.execute(n,t.context)}o(br,"executeProjectedAgentTool");var ve=class{static{o(this,"TaskSignals")}#e=new Map;notify(t){for(let r of[...this.#e.get(t)??[]])r()}subscribe(t,r){let n=this.#e.get(t);return n||this.#e.set(t,n=new Set),n.add(r),()=>{n.delete(r),n.size===0&&this.#e.delete(t)}}async wait(t){let r=o(()=>{},"wake"),n=0,s=o(()=>{n+=1,r()},"changed"),c=[...new Set(t.taskIds)].map(d=>this.subscribe(d,s)),l=setTimeout(s,Math.max(0,t.deadline-Date.now()));t.signal.addEventListener("abort",s);try{for(;;){t.signal.throwIfAborted();let d=n,h=await t.read();if(h!==null)return h;if(Date.now()>=t.deadline)return null;n===d&&await new Promise(m=>{r=m,(n!==d||t.signal.aborted)&&m()})}}finally{clearTimeout(l),t.signal.removeEventListener("abort",s);for(let d of c)d()}}},xe=class{static{o(this,"TaskSerialExecutor")}#e=new Map;async run(t,r){let s=(this.#e.get(t)??Promise.resolve()).then(r),c=s.then(()=>{},()=>{});this.#e.set(t,c);try{return await s}finally{this.#e.get(t)===c&&this.#e.delete(t)}}};var N=class extends Error{static{o(this,"AcpRpcError")}code;data;constructor(t,r,n){super(r),this.code=t,this.data=n,this.name="AcpRpcError"}};import{execFile as De}from"node:child_process";function y(i,t){if(i.pid){if(process.platform==="win32"){De("taskkill",["/PID",String(i.pid),"/T",...t==="SIGKILL"?["/F"]:[]],{windowsHide:!0},()=>{});return}try{process.kill(-i.pid,t)}catch(r){if(r.code!=="ESRCH")throw r}}}o(y,"signalNativeProcess");import{spawn as Je}from"node:child_process";import{StringDecoder as Fe}from"node:string_decoder";var J=8*1024*1024,L={outcome:{outcome:"cancelled"}};function C(i){return i!==null&&typeof i=="object"&&!Array.isArray(i)}o(C,"object");var Ie=class{static{o(this,"AcpClient")}options;child=null;pending=new Map;sessions=new Set;activePrompts=new Set;permissions=new Map;nextId=1;buffer="";decoder=new Fe("utf8");initialized=null;updateQueue=Promise.resolve();stopped=!1;constructor(t){this.options=t}initialize(){return this.initialized?this.initialized:(this.initialized=this.connect(),this.initialized)}async connect(){if(this.stopped)throw new Error("ACP client is closed; reconnect with a new client.");let t=Je(this.options.command,this.options.args,{cwd:this.options.cwd,env:this.options.env??process.env,stdio:["pipe","pipe","pipe"],shell:!1,detached:process.platform!=="win32"});this.child=t,t.stdout.on("data",r=>this.consume(this.decoder.write(r))),t.stderr.resume(),t.stdin.on("error",r=>this.fail(r)),t.on("error",r=>this.fail(r)),t.on("exit",(r,n)=>this.fail(new Error(`ACP agent exited (${n??r??"unknown"}).`)));try{let r=await this.request("initialize",{protocolVersion:1,clientInfo:{name:"openpond",title:"OpenPond",version:"1"},clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}});if(r.protocolVersion!==1)throw new Error(`Unsupported ACP protocol version: ${r.protocolVersion}`);return r}catch(r){throw await this.stop(),r}}async authenticate(t){let n=(await this.initialize()).authMethods?.find(s=>s.id===t);if(!n)throw new Error("The agent did not advertise this authentication method.");if(n.type==="terminal")throw new Error("Run the agent's terminal login, then reconnect.");await this.request("authenticate",{methodId:t})}async createSession(t,r=[]){await this.initialize();let n=await this.request("session/new",{cwd:t,mcpServers:r});if(typeof n.sessionId!="string"||!n.sessionId)throw new Error("Agent returned no native session identity.");return this.sessions.add(n.sessionId),n}async loadSession(t,r,n=[]){if(!(await this.initialize()).agentCapabilities?.loadSession)throw new Error("This agent does not support native session loading.");this.sessions.add(t);try{let c=await this.request("session/load",{sessionId:t,cwd:r,mcpServers:n});return await this.updateQueue,{...c,sessionId:t}}catch(c){throw this.sessions.delete(t),c}}async setModel(t,r){this.assertSession(t),await this.request("session/set_model",{sessionId:t,modelId:r})}async setMode(t,r){this.assertSession(t),await this.request("session/set_mode",{sessionId:t,modeId:r})}async setConfigOption(t,r,n){return this.assertSession(t),await this.request("session/set_config_option",{sessionId:t,configId:r,value:n})}async prompt(t,r,n){if(this.assertSession(t),n?.aborted)throw new Error("ACP prompt cancelled.");if(this.activePrompts.has(t))throw new Error("A prompt is already active for this native session.");this.activePrompts.add(t);let s,c=o(()=>{this.cancel(t),s=setTimeout(()=>{this.stop()},5e3),s.unref()},"abort");n?.addEventListener("abort",c,{once:!0});try{let l=await this.request("session/prompt",{sessionId:t,prompt:r},0);return await this.updateQueue,n?.aborted?{...l,stopReason:"cancelled"}:l}catch(l){if(n?.aborted)return{stopReason:"cancelled"};throw l}finally{s&&clearTimeout(s),n?.removeEventListener("abort",c),this.activePrompts.delete(t),this.cancelPermissions(t)}}cancel(t){this.cancelPermissions(t),this.sessions.has(t)&&this.child&&this.write({jsonrpc:"2.0",method:"session/cancel",params:{sessionId:t}})}async stop(){if(this.stopped)return;this.stopped=!0;let t=this.child;this.fail(new Error("ACP connection closed.")),!(!t||t.exitCode!==null||t.signalCode!==null)&&await new Promise(r=>{let n=setTimeout(()=>y(t,"SIGKILL"),2e3);n.unref(),t.once("exit",()=>{clearTimeout(n),r()}),y(t,"SIGTERM")})}assertSession(t){if(!this.sessions.has(t))throw new Error("Session does not belong to this ACP connection.")}request(t,r,n=this.options.requestTimeoutMs??3e4){let s=this.nextId++;return new Promise((c,l)=>{let d=n>0?setTimeout(()=>{this.pending.delete(s),l(new Error(`ACP request timed out: ${t}`))},n):void 0;d?.unref(),this.pending.set(s,{resolve:c,reject:l,timer:d});try{this.write({jsonrpc:"2.0",id:s,method:t,params:r})}catch(h){d&&clearTimeout(d),this.pending.delete(s),l(h)}})}write(t){if(!this.child||this.child.stdin.destroyed)throw new Error("ACP connection is not running.");let r=JSON.stringify(t);if(Buffer.byteLength(r)>J)throw new Error("ACP frame exceeds the size limit.");this.child.stdin.write(`${r}
|
|
6
|
+
`)}consume(t){this.buffer+=t;let r;for(;(r=this.buffer.indexOf(`
|
|
7
|
+
`))!==-1;){let n=this.buffer.slice(0,r);if(this.buffer=this.buffer.slice(r+1),!!n.trim())try{if(Buffer.byteLength(n)>J)throw new Error("ACP frame exceeds the size limit.");this.receive(JSON.parse(n))}catch{this.fail(new Error("Invalid ACP protocol frame.")),this.stop();return}}Buffer.byteLength(this.buffer)>J&&(this.fail(new Error("ACP frame exceeds the size limit.")),this.stop())}receive(t){if(!C(t)||t.jsonrpc!=="2.0")throw new Error("Invalid JSON-RPC envelope.");if(typeof t.method=="string"){if("id"in t){this.handleRequest(t);return}if(t.method==="session/update"&&C(t.params)){let{sessionId:n,update:s}=t.params;if(typeof n!="string"||!this.sessions.has(n)||!C(s))return;this.updateQueue=this.updateQueue.then(async()=>{await this.options.onUpdate?.(n,s)}),this.updateQueue.catch(c=>{this.fail(c),this.stop()})}return}if(typeof t.id!="number")return;let r=this.pending.get(t.id);r&&(this.pending.delete(t.id),r.timer&&clearTimeout(r.timer),C(t.error)?r.reject(new N(Number(t.error.code),String(t.error.message),t.error.data)):r.resolve(t.result))}async handleRequest(t){let r=t.id;if(!(typeof r!="number"&&typeof r!="string"))try{if(t.method!=="session/request_permission"){this.write({jsonrpc:"2.0",id:r,error:{code:-32601,message:"Client method not supported."}});return}let n=t.params;if(!C(n)||typeof n.sessionId!="string"||!Array.isArray(n.options)||!C(n.toolCall))throw new Error("Invalid permission request.");if(this.assertSession(n.sessionId),!this.activePrompts.has(n.sessionId)){this.write({jsonrpc:"2.0",id:r,result:L});return}let s=new AbortController,c=this.permissions.get(n.sessionId)??new Set;c.add(s),this.permissions.set(n.sessionId,c);let l=L;try{if(this.options.onPermission&&(l=await Promise.race([this.options.onPermission(n,s.signal),new Promise(d=>s.signal.addEventListener("abort",()=>d(L),{once:!0}))])),s.signal.aborted&&(l=L),l.outcome.outcome==="selected"){let d=l.outcome.optionId;if(!n.options.some(h=>C(h)&&h.optionId===d))throw new Error("Permission option was not advertised by the agent.")}}finally{c.delete(s),c.size||this.permissions.delete(n.sessionId)}this.child&&this.write({jsonrpc:"2.0",id:r,result:l})}catch{this.child&&this.write({jsonrpc:"2.0",id:r,error:{code:-32602,message:"Invalid or expired client request."}})}}cancelPermissions(t){for(let r of this.permissions.get(t)??[])r.abort();this.permissions.delete(t)}fail(t){let r=this.child,n=!!r;this.child=null,r&&(y(r,"SIGTERM"),setTimeout(()=>y(r,"SIGKILL"),2e3).unref());for(let s of this.pending.values())s.timer&&clearTimeout(s.timer),s.reject(t);this.pending.clear();for(let s of this.sessions)this.cancelPermissions(s);this.sessions.clear(),n&&this.options.onExit?.(t)}};import{spawn as Ge}from"node:child_process";import{randomUUID as ye}from"node:crypto";import{StringDecoder as Ke}from"node:string_decoder";var I=o(i=>i&&typeof i=="object"&&!Array.isArray(i)?i:{},"record"),ke=class{static{o(this,"ClaudeCliClient")}options;child=null;sessionId=null;pending=new Map;turn=null;permissions=new Set;updates=Promise.resolve();closed=!1;model="default";constructor(t){this.options=t}async initialize(){return{protocolVersion:1,agentCapabilities:{loadSession:!0,mcpCapabilities:{http:!0},promptCapabilities:{image:!0,embeddedContext:!0}},authMethods:[],agentInfo:{name:"Claude Code CLI",version:"native"}}}async authenticate(t){throw new Error("Use Claude Code's native login, then reconnect.")}async createSession(t,r=[]){return this.start(ye(),t,!1,r)}async loadSession(t,r,n=[]){return this.start(t,r,!0,n)}async start(t,r,n,s){if(this.child||this.closed)throw new Error("Claude connection already owns a session or is closed.");if(!/^[a-f0-9-]{36}$/i.test(t))throw new Error("Invalid native Claude session identity.");this.sessionId=t;let c=Object.fromEntries(s.map(m=>[String(m.name),{type:"http",url:m.url,headers:Object.fromEntries((Array.isArray(m.headers)?m.headers:[]).map(g=>{let v=I(g);return[String(v.name),String(v.value)]}))}])),l=Ge(this.options.command,["--print","--verbose","--input-format","stream-json","--output-format","stream-json","--include-partial-messages","--permission-prompt-tool","stdio",...s.length?["--mcp-config",JSON.stringify({mcpServers:c})]:[],n?"--resume":"--session-id",t],{cwd:r,env:this.options.env??process.env,stdio:["pipe","pipe","pipe"],shell:!1,detached:process.platform!=="win32"});this.child=l;let d=new Ke("utf8"),h="";l.stderr.resume(),l.stdout.on("data",m=>{h+=d.write(m);let g;for(;(g=h.indexOf(`
|
|
8
|
+
`))>=0;){let v=h.slice(0,g);if(h=h.slice(g+1),!!v.trim())try{if(Buffer.byteLength(v)>8*1024*1024)throw new Error("Oversized frame");this.receive(I(JSON.parse(v)))}catch{this.fail(new Error("Invalid Claude CLI protocol frame.")),this.stop();return}}Buffer.byteLength(h)>8*1024*1024&&(this.fail(new Error("Claude CLI frame exceeds limit.")),this.stop())}),l.on("error",m=>this.fail(m)),l.stdin.on("error",m=>this.fail(m)),l.on("exit",m=>{this.fail(new Error(`Claude CLI exited (${m??"signal"}).`)),y(l,"SIGTERM"),setTimeout(()=>y(l,"SIGKILL"),2e3).unref(),this.child=null});try{let m=await this.control({subtype:"initialize",hooks:null}),g=Array.isArray(m.models)?m.models.map(I).filter(w=>typeof w.value=="string"):[],v=g.find(w=>w.value==="default")?.description,k=typeof v=="string"?g.find(w=>w.value!=="default"&&typeof w.displayName=="string"&&(v===w.displayName||v.startsWith(`${w.displayName} \xB7`))):void 0;return{sessionId:t,models:{currentModelId:this.model,availableModels:g.map(w=>({modelId:String(w.value),name:w.value==="default"&&k?`${k.displayName} (default)`:String(w.displayName??w.value),...typeof w.description=="string"?{description:w.description}:{}}))},modes:{currentModeId:String(m.current_permission_mode??"manual"),availableModes:[{id:"manual",name:"Ask for permissions"},{id:"plan",name:"Plan"}]}}}catch(m){throw await this.stop(),m}}async setModel(t,r){this.assertSession(t),await this.control({subtype:"set_model",model:r}),this.model=r}async setMode(t,r){if(this.assertSession(t),!["manual","plan"].includes(r))throw new Error("Unsupported Claude permission mode.");await this.control({subtype:"set_permission_mode",mode:r})}async prompt(t,r,n){if(this.assertSession(t),this.turn)throw new Error("A prompt is already active for this native session.");if(n?.aborted)throw new Error("Claude turn cancelled.");let s=new Promise((d,h)=>{this.turn={resolve:d,reject:h}}),c,l=o(()=>{for(let d of this.permissions)d.abort();this.control({subtype:"interrupt"}).catch(()=>{}),c=setTimeout(()=>{this.stop()},5e3),c.unref()},"abort");n?.addEventListener("abort",l,{once:!0});try{this.write({type:"user",session_id:t,parent_tool_use_id:null,message:{role:"user",content:r.map(h=>h.type==="image"?{type:"image",source:{type:"base64",media_type:h.mimeType,data:h.data}}:h)}});let d=await s;return await this.updates,n?.aborted?{stopReason:"cancelled"}:d}catch(d){if(n?.aborted)return{stopReason:"cancelled"};throw d}finally{n?.removeEventListener("abort",l),c&&clearTimeout(c),this.turn=null;for(let d of this.permissions)d.abort();this.permissions.clear()}}assertSession(t){if(!this.child||this.sessionId!==t||this.closed)throw new Error("Session does not belong to this Claude connection.")}write(t){if(!this.child||this.child.stdin.destroyed)throw new Error("Claude connection is closed.");let r=JSON.stringify(t);if(Buffer.byteLength(r)>8*1024*1024)throw new Error("Claude input exceeds limit.");this.child.stdin.write(`${r}
|
|
9
|
+
`)}control(t){let r=ye();return new Promise((n,s)=>{let c=setTimeout(()=>{this.pending.delete(r),s(new Error(`Claude control request timed out: ${t.subtype}`))},this.options.requestTimeoutMs??3e4);c.unref(),this.pending.set(r,{resolve:n,reject:s,timer:c});try{this.write({type:"control_request",request_id:r,request:t})}catch(l){clearTimeout(c),this.pending.delete(r),s(l)}})}emit(t){if(!this.turn||!this.sessionId)return;let r=this.sessionId;this.updates=this.updates.then(async()=>{await this.options.onUpdate?.(r,t)}),this.updates.catch(n=>{this.fail(n),this.stop()})}receive(t){if(typeof t.session_id=="string"&&t.session_id!==this.sessionId){this.fail(new Error("Claude changed native session identity.")),this.stop();return}if(t.type==="control_response"){let r=I(t.response),n=String(r.request_id),s=this.pending.get(n);if(!s)return;clearTimeout(s.timer),this.pending.delete(n),r.subtype==="error"?s.reject(new Error(String(r.error??"Claude control failed."))):s.resolve(I(r.response))}else if(t.type==="control_request")this.permission(t);else if(t.type==="stream_event"){let r=I(t.event),n=I(r.delta),s=I(r.content_block);r.type==="content_block_delta"&&(n.type==="text_delta"||n.type==="thinking_delta")&&this.emit({sessionUpdate:n.type==="text_delta"?"agent_message_chunk":"agent_thought_chunk",content:{type:"text",text:n.text??n.thinking??""}}),r.type==="content_block_start"&&s.type==="tool_use"&&this.emit({sessionUpdate:"tool_call",toolCallId:s.id,title:s.name,kind:"other",status:"in_progress",rawInput:s.input})}else if(t.type==="assistant"){let r=I(t.message).content;for(let n of Array.isArray(r)?r.map(I):[])n.type==="tool_use"&&this.emit({sessionUpdate:"tool_call_update",toolCallId:n.id,title:n.name,status:"in_progress",rawInput:n.input})}else if(t.type==="user"){let r=I(t.message).content;for(let n of Array.isArray(r)?r.map(I):[])n.type==="tool_result"&&this.emit({sessionUpdate:"tool_call_update",toolCallId:n.tool_use_id,status:n.is_error?"failed":"completed",content:n.content})}else if(t.type==="result"){if(t.session_id&&t.session_id!==this.sessionId){this.fail(new Error("Claude changed native session identity."));return}this.emit({sessionUpdate:"usage_update",usage:t.usage,totalCostUsd:t.total_cost_usd}),t.is_error?this.turn?.reject(new Error(Array.isArray(t.errors)?t.errors.map(String).join("; "):"Claude turn failed.")):this.turn?.resolve({stopReason:"end_turn"})}}async permission(t){let r=I(t.request),n=String(t.request_id);if(r.subtype!=="can_use_tool"||!this.turn||!this.sessionId){this.write({type:"control_response",response:{subtype:"error",request_id:n,error:"Unsupported or inactive control request."}});return}let s=new AbortController;this.permissions.add(s);try{let c=I(r.input),l=r.tool_name==="AskUserQuestion"&&Array.isArray(c.questions)?c.questions:void 0,d=new Promise(g=>s.signal.addEventListener("abort",()=>g({outcome:{outcome:"cancelled"}}),{once:!0})),h=await Promise.race([d,this.options.onPermission?.({sessionId:this.sessionId,toolCall:{toolCallId:r.tool_use_id,title:r.title??r.tool_name,rawInput:r.input},questions:l,options:[{optionId:"allow",name:"Allow once",kind:"allow_once"},{optionId:"deny",name:"Deny",kind:"reject_once"}]},s.signal)]),m=!s.signal.aborted&&h?.outcome.outcome==="selected"&&h.outcome.optionId==="allow";this.child&&this.write({type:"control_response",response:{subtype:"success",request_id:n,response:m?{behavior:"allow",updatedInput:l?{...c,answers:h?.answers}:r.input}:{behavior:"deny",message:"Permission declined or turn cancelled."}}})}catch{this.child&&this.write({type:"control_response",response:{subtype:"success",request_id:n,response:{behavior:"deny",message:"Permission could not be resolved."}}})}finally{this.permissions.delete(s)}}fail(t){for(let r of this.pending.values())clearTimeout(r.timer),r.reject(t);this.pending.clear(),this.turn?.reject(t),this.turn=null;for(let r of this.permissions)r.abort();this.permissions.clear(),this.options.onExit?.(t)}async stop(){if(this.closed)return;this.closed=!0,this.fail(new Error("Claude connection closed."));let t=this.child;!t||t.exitCode!==null||t.signalCode!==null||(await new Promise(r=>{let n=setTimeout(()=>y(t,"SIGKILL"),2e3);n.unref(),t.once("exit",()=>{clearTimeout(n),r()}),y(t,"SIGTERM")}),this.child=null)}};export{$ as a,E as b,Ye as c,Ze as d,et as e,Se as f,Ee as g,st as h,q as i,lt as j,W as k,Q as l,B as m,U as n,ut as o,_e as p,V as q,X as r,D as s,te as t,ie as u,ce as v,ue as w,de as x,pe as y,me as z,Pe as A,he as B,Ae as C,fe as D,be as E,p as F,Ht as G,ge as H,Vt as I,we as J,Ft as K,tr as L,Be as M,Ue as N,or as O,ar as P,cr as Q,mr as R,hr as S,fr as T,br as U,ve as V,xe as W,N as X,Ie as Y,ke as Z};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{a as me,b as D,c as G,d as j,e as z,g as ye,i as T,j as we,k as S,l as he,v as B,x as F}from"./chunk-B3O2GAQH.js";import{a as re,b as L,c as R}from"./chunk-65BW2QXY.js";import{a as Z,b as ee,c as te}from"./chunk-V6WBSW5Q.js";import{b as H,c as be,d as ve,f as w,h as P,i as Re}from"./chunk-BSHAIAXY.js";import{a as M,f as v,k as X}from"./chunk-3M53YXEI.js";import{M as pe,N as ue,R as ge,V as fe,h as $,i as ie,l as ae,n as se,o as ce,p as le,q as de}from"./chunk-Z2BYC6TP.js";import{d as y,e as ne,f as oe,g as C}from"./chunk-DXAZUJPA.js";import{a as g}from"./chunk-FTQLQJQV.js";import{promises as V,existsSync as W}from"node:fs";import U from"node:path";import{stdin as $e}from"node:process";async function Ge(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=await ce(n,i,a.id);console.log(JSON.stringify(s,null,2))}g(Ge,"runTemplateStatus");async function je(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=await le(n,i,a.id);console.log(JSON.stringify(s,null,2))}g(je,"runTemplateBranches");async function ze(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=typeof e.env=="string"?e.env:typeof e.environment=="string"?e.environment:void 0,f=X(s),c=await de(n,i,a.id,{environment:f});console.log(JSON.stringify(c,null,2))}g(ze,"runTemplateUpdate");async function He(e){let o=await y(),t=w(o),r=typeof e.apiKey=="string"?e.apiKey:typeof e.key=="string"?e.key:null,n=r?r.trim():await L();if(!n)throw new Error("API key is required");n.startsWith("opk_")||console.log("warning: API keys usually start with opk_."),await C({handle:o.activeProfile?.handle||"default",apiKey:n,baseUrl:t,apiBaseUrl:o.apiBaseUrl,chatApiBaseUrl:o.chatApiBaseUrl,setActive:!0}),console.log("Saved account credentials to the encrypted OpenPond credential store.")}g(He,"runLogin");async function Fe(e,o){let t=o[0]||"list";if(t==="list"){let r=await ne();console.log(JSON.stringify({profiles:r},null,2));return}if(t==="use"){let r=o[1];if(!r)throw new Error("usage: profiles use <name> [--base-url <url>]");let n=await oe(r,{baseUrl:H(e)});console.log(JSON.stringify({profile:n},null,2));return}if(t==="save"){let r=o[1];if(!r)throw new Error("usage: profiles save <name> --api-key <key> [--base-url <url>] [--api-base-url <url>] [--chat-api-base-url <url>]");let n=typeof e.apiKey=="string"?e.apiKey:typeof e.key=="string"?e.key:null,i=n?n.trim():await L(),a=typeof e.environment=="string"?e.environment:typeof e.env=="string"?e.env:void 0,s=await C({handle:r,apiKey:i,baseUrl:H(e),apiBaseUrl:be(e),chatApiBaseUrl:ve(e),environment:a,setActive:!0});console.log(JSON.stringify({profile:s},null,2));return}throw new Error("usage: profiles <list|use|save> [args]")}g(Fe,"runProfiles");async function Ve(){let e=await y(),o=w(e),t=P(e),r=await R(e,o),n=await pe(t,r);console.log(JSON.stringify(n,null,2))}g(Ve,"runAccount");async function We(e){let o=await y(),t=P(o),r=re(o),n=await ue(t,r);console.log(JSON.stringify(n,null,2))}g(We,"runHealth");async function qe(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=typeof e.branch=="string"?String(e.branch):void 0,f=await $(n,i,a.id,{branch:s});if(!f?.id){console.log("no deployments found");return}let c=await ie(n,i,f.id),d=(c&&Array.isArray(c.toolsJson)?c.toolsJson:null)||(c&&typeof c.metadataJson=="object"&&c.metadataJson?c.metadataJson.tools:null),u=Array.isArray(d)?d:[];if(u.length===0){console.log("no tools found");return}for(let l of u){let m=l,h=m.profile||m.function,I=m.name||h?.name||"unknown",p=m.description||h?.description||"";console.log(p?`${I} - ${p}`:I)}}g(qe,"runToolList");async function Ye(e,o,t){let r=await y(),n=w(r),i=P(r),a=await R(r,n),{app:s}=await T(i,a,o),f=typeof e.branch=="string"?String(e.branch):void 0,c=await $(i,a,s.id,{branch:f});if(!c?.id)throw new Error("no deployments found");let d;if(typeof e.body=="string")try{d=JSON.parse(e.body)}catch{throw new Error("tool body must be valid JSON")}let u=typeof e.method=="string"?String(e.method).toUpperCase():"POST",l=await fe(n,a,{appId:s.id,deploymentId:c.id,toolName:t,method:u,body:d,headers:a?{"openpond-api-key":a}:void 0});if(!l.ok)throw new Error(l.error||`tool failed (${l.status})`);let m=l.data??{ok:!0};console.log(JSON.stringify(m,null,2))}g(Ye,"runToolRun");async function Qe(e,o,t){let r=await y(),n=w(r),i=P(r),a=await R(r,n),{app:s}=await T(i,a,o),f=typeof e.branch=="string"?String(e.branch):void 0,c=typeof e.deploymentId=="string"?String(e.deploymentId):void 0,d=c?{id:c}:await $(i,a,s.id,{branch:f});if(!d?.id)throw new Error("no deployments found");let u=typeof e.body=="string"?M(String(e.body),"body"):{};if(!u||typeof u!="object"||Array.isArray(u))throw new Error("body must be a JSON object");let l=typeof e.method=="string"?String(e.method).toUpperCase():"POST",m={...u,appId:s.id,deploymentId:d.id,toolName:t,method:l},h=await ge(i,a,m);console.log(JSON.stringify(h,null,2))}g(Qe,"runBacktestRun");async function Xe(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a,handle:s,repo:f}=await T(n,i,o),c=typeof e.branch=="string"?String(e.branch):void 0,d=typeof e.deploymentId=="string"?String(e.deploymentId):void 0,u=d?{id:d}:await $(n,i,a.id,{branch:c});if(!u?.id){console.log("no deployments found");return}await we({baseUrl:n,apiKey:i,deploymentId:u.id,prefix:`[${s}/${f}] `,intervalMs:e.interval?Number(e.interval):void 0,timeoutMs:e.timeout?Number(e.timeout):void 0})}g(Xe,"runDeployWatch");async function Ze(e,o){let r=((typeof e.name=="string"?e.name:null)||o.join(" ")).trim();if(!r)throw new Error("usage: repo create --name <name> [--team-id <id>] [--path <dir>] [--template <owner/repo|url>] [--template-branch <branch>] [--empty|--opentool] [--sandbox] [--token] [--auto-schedule-migration <true|false>]");let n=await y(),i=w(n),a=await R(n,i),s=P(n),f=typeof e.teamId=="string"&&e.teamId.trim()?e.teamId.trim():void 0,c=typeof e.template=="string"?e.template.trim():"";if(c&&(e.empty==="true"||e.opentool==="true"))throw new Error("choose one: --template or --empty/--opentool");if(e.empty==="true"&&e.opentool==="true")throw new Error("choose one: --empty or --opentool");let d=typeof e.description=="string"?e.description.trim():void 0,u=typeof e.templateBranch=="string"&&e.templateBranch.trim().length>0?e.templateBranch.trim():void 0,l=typeof e.env=="string"?M(e.env,"env"):void 0;if(l){if(typeof l!="object"||Array.isArray(l))throw new Error("env must be a JSON object");for(let[b,A]of Object.entries(l))if(typeof A!="string")throw new Error(`env value for ${b} must be a string`)}if(c){e.deployOnPush!==void 0&&console.warn("deploy-on-push is not used for template create (auto deploys)");let b=Re(c,i),k=(await se(s,a,[{name:r,...d?{description:d}:{},templateRepoUrl:b,...u?{templateBranch:u}:{},...l?{envVars:l}:{}}],f)).items?.[0];if(!k||k.status!=="ok"||!k.appId)throw new Error(k?.error||"Template create failed");console.log(`app_id: ${k.appId}`),k.deploymentId&&console.log(`deployment_id: ${k.deploymentId}`),k.conversationId&&console.log(`conversation_id: ${k.conversationId}`);return}let m=process.cwd(),h=typeof e.path=="string"?e.path:typeof e.dir=="string"?e.dir:null,I=h&&h.trim().length>0?h.trim():$e.isTTY?await he(m):m,p=U.resolve(I);if(W(p)){if(!(await V.stat(p)).isDirectory())throw new Error(`path is not a directory: ${p}`)}else await V.mkdir(p,{recursive:!0});let Pe=(await V.readdir(p)).filter(b=>b!==".git").length===0,x=v(e.yes)||v(e.force);if(!Pe&&!x&&!await S(`Directory is not empty (${p}). Continue?`,!1)){console.log("aborted");return}let ke=U.join(p,".git");if(!W(ke)){if(!(x?!0:await S("Initialize git repository here?",!0))){console.log("aborted");return}let A=await B("git",["init"],{cwd:p});if(A.code!==0)throw new Error(`git init failed: ${A.stderr.trim()||A.stdout.trim()||"unknown error"}`)}let K=await F(p,"origin");if(K&&!x&&!await S(`Remote "origin" already set (${K}). Replace it?`,!1)){console.log("aborted");return}let q=e.opentool==="true"?"opentool":"empty",Te=v(e.sandbox),Be=v(e.deployOnPush),N=e.autoScheduleMigration,Y=typeof N=="string"||typeof N=="boolean",Ee=Y?v(N):void 0,E=await ae(s,a,{name:r,...f?{teamId:f}:{},...d?{description:d}:{},...q?{repoInit:q}:{},...Te?{sandbox:!0}:{},...l?{envVars:l}:{},...Be?{deployOnPush:!0}:{},...Y?{autoScheduleMigration:Ee}:{}}),O=me(E);z(O);let J=v(e.token)||v(e.setRemoteToken),Oe=D(O,a),Q=J?Oe:O,_=await B("git",K?["remote","set-url","origin",Q]:["remote","add","origin",Q],{cwd:p});if(_.code!==0)throw new Error(`git remote failed: ${j(_.stderr.trim()||_.stdout.trim()||"unknown error")}`);let Ae=J?G(O):O;console.log(`app_id: ${E.appId}`),E.gitOwner&&E.gitRepo&&console.log(`repo: ${E.gitOwner}/${E.gitRepo}`),console.log(`remote: ${Ae}`),console.log('next: git add . && git commit -m "init"');let Ie=E.defaultBranch||"master";console.log(`next: openpond repo push --path ${p} --branch ${Ie}`),J||console.log(`token-remote (non-interactive): git -C ${p} remote set-url origin ${G(O)}`);try{await ye({apiBase:s,apiKey:a,forceRefresh:!0})}catch(b){console.warn("cache refresh failed",b)}}g(Ze,"runRepoCreate");async function Se(e){let o=await B("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e});if(o.code!==0)return null;let t=o.stdout.trim();return t.length>0?t:null}g(Se,"resolveGitBranch");async function et(e){let o=await y(),t=w(o),r=await R(o,t),n=typeof e.path=="string"?e.path:typeof e.dir=="string"?e.dir:null,i=U.resolve(n&&n.trim().length>0?n.trim():"."),a=U.join(i,".git");if(!W(a))throw new Error(`git repo not found at ${i} (missing .git)`);let s=await F(i,"origin");if(!s)throw new Error("origin remote not set; run `openpond repo create` first");z(s);let c=(typeof e.branch=="string"?e.branch.trim():"")||await Se(i);if(!c)throw new Error("unable to resolve git branch; pass --branch");let d;try{d=D(s,r)}catch{throw new Error("origin remote must be https for tokenized pushes")}let u=v(e.keepTokenRemote)||v(e.token)||v(e.setRemoteToken),l=s.includes("x-access-token:"),m=!u&&!l?s:null,h=process.env.GIT_TERMINAL_PROMPT;process.env.GIT_TERMINAL_PROMPT="0";try{if(!l){let p=await B("git",["remote","set-url","origin",d],{cwd:i});if(p.code!==0)throw new Error(`git remote set-url failed: ${j(p.stderr.trim()||p.stdout.trim()||"unknown error")}`)}if((await B("git",["push","-u","origin",c],{cwd:i,inherit:!0})).code!==0)throw new Error("git push failed")}finally{m&&await B("git",["remote","set-url","origin",m],{cwd:i}).catch(()=>null),h===void 0?delete process.env.GIT_TERMINAL_PROMPT:process.env.GIT_TERMINAL_PROMPT=h}}g(et,"runRepoPush");async function tt(e){if(e.length===0)throw new Error("usage: opentool <init|validate|build> [args]");let o=process.platform==="win32"?"npx.cmd":"npx";if((await B(o,["opentool",...e],{inherit:!0})).code!==0)throw new Error("opentool command failed")}g(tt,"runOpentool");async function nt(){let e="openpond",o=Z(),t=await te(e),r=`npm i -g ${e}@${t}`,n=ee(o,t);if(n===0){console.log(`${e} is up to date (${o})`);return}if(n===-1){console.log(`Update available: ${o} -> ${t}`),console.log(`Run: ${r}`);return}if(n===1){console.log(`Installed version (${o}) is newer than npm latest (${t}).`);return}if(o===t){console.log(`${e} is up to date (${o})`);return}console.log(`Installed: ${o}`),console.log(`Latest: ${t}`),console.log(`Run: ${r}`)}g(nt,"runCheckUpdate");export{Ge as a,je as b,ze as c,He as d,Fe as e,Ve as f,We as g,qe as h,Ye as i,Qe as j,Xe as k,Ze as l,Se as m,et as n,tt as o,nt as p};
|
|
2
|
+
import{a as me,b as D,c as G,d as j,e as z,g as ye,i as T,j as we,k as S,l as he,v as B,x as F}from"./chunk-N3DEA6PG.js";import{a as re,b as L,c as R}from"./chunk-PA7XP42P.js";import{b as H,c as be,d as ve,f as w,h as P,i as Re}from"./chunk-BSHAIAXY.js";import{a as Z,b as ee,c as te}from"./chunk-Q4H3NUVW.js";import{a as M,f as v,k as X}from"./chunk-3M53YXEI.js";import{M as pe,N as ue,R as ge,V as fe,h as $,i as ie,l as ae,n as se,o as ce,p as le,q as de}from"./chunk-QXVIIM4T.js";import{d as y,e as ne,f as oe,g as C}from"./chunk-R3XFY7VL.js";import{a as g}from"./chunk-FTQLQJQV.js";import{promises as V,existsSync as W}from"node:fs";import U from"node:path";import{stdin as $e}from"node:process";async function Ge(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=await ce(n,i,a.id);console.log(JSON.stringify(s,null,2))}g(Ge,"runTemplateStatus");async function je(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=await le(n,i,a.id);console.log(JSON.stringify(s,null,2))}g(je,"runTemplateBranches");async function ze(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=typeof e.env=="string"?e.env:typeof e.environment=="string"?e.environment:void 0,f=X(s),c=await de(n,i,a.id,{environment:f});console.log(JSON.stringify(c,null,2))}g(ze,"runTemplateUpdate");async function He(e){let o=await y(),t=w(o),r=typeof e.apiKey=="string"?e.apiKey:typeof e.key=="string"?e.key:null,n=r?r.trim():await L();if(!n)throw new Error("API key is required");n.startsWith("opk_")||console.log("warning: API keys usually start with opk_."),await C({handle:o.activeProfile?.handle||"default",apiKey:n,baseUrl:t,apiBaseUrl:o.apiBaseUrl,chatApiBaseUrl:o.chatApiBaseUrl,setActive:!0}),console.log("Saved account credentials to the encrypted OpenPond credential store.")}g(He,"runLogin");async function Fe(e,o){let t=o[0]||"list";if(t==="list"){let r=await ne();console.log(JSON.stringify({profiles:r},null,2));return}if(t==="use"){let r=o[1];if(!r)throw new Error("usage: profiles use <name> [--base-url <url>]");let n=await oe(r,{baseUrl:H(e)});console.log(JSON.stringify({profile:n},null,2));return}if(t==="save"){let r=o[1];if(!r)throw new Error("usage: profiles save <name> --api-key <key> [--base-url <url>] [--api-base-url <url>] [--chat-api-base-url <url>]");let n=typeof e.apiKey=="string"?e.apiKey:typeof e.key=="string"?e.key:null,i=n?n.trim():await L(),a=typeof e.environment=="string"?e.environment:typeof e.env=="string"?e.env:void 0,s=await C({handle:r,apiKey:i,baseUrl:H(e),apiBaseUrl:be(e),chatApiBaseUrl:ve(e),environment:a,setActive:!0});console.log(JSON.stringify({profile:s},null,2));return}throw new Error("usage: profiles <list|use|save> [args]")}g(Fe,"runProfiles");async function Ve(){let e=await y(),o=w(e),t=P(e),r=await R(e,o),n=await pe(t,r);console.log(JSON.stringify(n,null,2))}g(Ve,"runAccount");async function We(e){let o=await y(),t=P(o),r=re(o),n=await ue(t,r);console.log(JSON.stringify(n,null,2))}g(We,"runHealth");async function qe(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=typeof e.branch=="string"?String(e.branch):void 0,f=await $(n,i,a.id,{branch:s});if(!f?.id){console.log("no deployments found");return}let c=await ie(n,i,f.id),d=(c&&Array.isArray(c.toolsJson)?c.toolsJson:null)||(c&&typeof c.metadataJson=="object"&&c.metadataJson?c.metadataJson.tools:null),u=Array.isArray(d)?d:[];if(u.length===0){console.log("no tools found");return}for(let l of u){let m=l,h=m.profile||m.function,I=m.name||h?.name||"unknown",p=m.description||h?.description||"";console.log(p?`${I} - ${p}`:I)}}g(qe,"runToolList");async function Ye(e,o,t){let r=await y(),n=w(r),i=P(r),a=await R(r,n),{app:s}=await T(i,a,o),f=typeof e.branch=="string"?String(e.branch):void 0,c=await $(i,a,s.id,{branch:f});if(!c?.id)throw new Error("no deployments found");let d;if(typeof e.body=="string")try{d=JSON.parse(e.body)}catch{throw new Error("tool body must be valid JSON")}let u=typeof e.method=="string"?String(e.method).toUpperCase():"POST",l=await fe(n,a,{appId:s.id,deploymentId:c.id,toolName:t,method:u,body:d,headers:a?{"openpond-api-key":a}:void 0});if(!l.ok)throw new Error(l.error||`tool failed (${l.status})`);let m=l.data??{ok:!0};console.log(JSON.stringify(m,null,2))}g(Ye,"runToolRun");async function Qe(e,o,t){let r=await y(),n=w(r),i=P(r),a=await R(r,n),{app:s}=await T(i,a,o),f=typeof e.branch=="string"?String(e.branch):void 0,c=typeof e.deploymentId=="string"?String(e.deploymentId):void 0,d=c?{id:c}:await $(i,a,s.id,{branch:f});if(!d?.id)throw new Error("no deployments found");let u=typeof e.body=="string"?M(String(e.body),"body"):{};if(!u||typeof u!="object"||Array.isArray(u))throw new Error("body must be a JSON object");let l=typeof e.method=="string"?String(e.method).toUpperCase():"POST",m={...u,appId:s.id,deploymentId:d.id,toolName:t,method:l},h=await ge(i,a,m);console.log(JSON.stringify(h,null,2))}g(Qe,"runBacktestRun");async function Xe(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a,handle:s,repo:f}=await T(n,i,o),c=typeof e.branch=="string"?String(e.branch):void 0,d=typeof e.deploymentId=="string"?String(e.deploymentId):void 0,u=d?{id:d}:await $(n,i,a.id,{branch:c});if(!u?.id){console.log("no deployments found");return}await we({baseUrl:n,apiKey:i,deploymentId:u.id,prefix:`[${s}/${f}] `,intervalMs:e.interval?Number(e.interval):void 0,timeoutMs:e.timeout?Number(e.timeout):void 0})}g(Xe,"runDeployWatch");async function Ze(e,o){let r=((typeof e.name=="string"?e.name:null)||o.join(" ")).trim();if(!r)throw new Error("usage: repo create --name <name> [--team-id <id>] [--path <dir>] [--template <owner/repo|url>] [--template-branch <branch>] [--empty|--opentool] [--sandbox] [--token] [--auto-schedule-migration <true|false>]");let n=await y(),i=w(n),a=await R(n,i),s=P(n),f=typeof e.teamId=="string"&&e.teamId.trim()?e.teamId.trim():void 0,c=typeof e.template=="string"?e.template.trim():"";if(c&&(e.empty==="true"||e.opentool==="true"))throw new Error("choose one: --template or --empty/--opentool");if(e.empty==="true"&&e.opentool==="true")throw new Error("choose one: --empty or --opentool");let d=typeof e.description=="string"?e.description.trim():void 0,u=typeof e.templateBranch=="string"&&e.templateBranch.trim().length>0?e.templateBranch.trim():void 0,l=typeof e.env=="string"?M(e.env,"env"):void 0;if(l){if(typeof l!="object"||Array.isArray(l))throw new Error("env must be a JSON object");for(let[b,A]of Object.entries(l))if(typeof A!="string")throw new Error(`env value for ${b} must be a string`)}if(c){e.deployOnPush!==void 0&&console.warn("deploy-on-push is not used for template create (auto deploys)");let b=Re(c,i),k=(await se(s,a,[{name:r,...d?{description:d}:{},templateRepoUrl:b,...u?{templateBranch:u}:{},...l?{envVars:l}:{}}],f)).items?.[0];if(!k||k.status!=="ok"||!k.appId)throw new Error(k?.error||"Template create failed");console.log(`app_id: ${k.appId}`),k.deploymentId&&console.log(`deployment_id: ${k.deploymentId}`),k.conversationId&&console.log(`conversation_id: ${k.conversationId}`);return}let m=process.cwd(),h=typeof e.path=="string"?e.path:typeof e.dir=="string"?e.dir:null,I=h&&h.trim().length>0?h.trim():$e.isTTY?await he(m):m,p=U.resolve(I);if(W(p)){if(!(await V.stat(p)).isDirectory())throw new Error(`path is not a directory: ${p}`)}else await V.mkdir(p,{recursive:!0});let Pe=(await V.readdir(p)).filter(b=>b!==".git").length===0,x=v(e.yes)||v(e.force);if(!Pe&&!x&&!await S(`Directory is not empty (${p}). Continue?`,!1)){console.log("aborted");return}let ke=U.join(p,".git");if(!W(ke)){if(!(x?!0:await S("Initialize git repository here?",!0))){console.log("aborted");return}let A=await B("git",["init"],{cwd:p});if(A.code!==0)throw new Error(`git init failed: ${A.stderr.trim()||A.stdout.trim()||"unknown error"}`)}let K=await F(p,"origin");if(K&&!x&&!await S(`Remote "origin" already set (${K}). Replace it?`,!1)){console.log("aborted");return}let q=e.opentool==="true"?"opentool":"empty",Te=v(e.sandbox),Be=v(e.deployOnPush),N=e.autoScheduleMigration,Y=typeof N=="string"||typeof N=="boolean",Ee=Y?v(N):void 0,E=await ae(s,a,{name:r,...f?{teamId:f}:{},...d?{description:d}:{},...q?{repoInit:q}:{},...Te?{sandbox:!0}:{},...l?{envVars:l}:{},...Be?{deployOnPush:!0}:{},...Y?{autoScheduleMigration:Ee}:{}}),O=me(E);z(O);let J=v(e.token)||v(e.setRemoteToken),Oe=D(O,a),Q=J?Oe:O,_=await B("git",K?["remote","set-url","origin",Q]:["remote","add","origin",Q],{cwd:p});if(_.code!==0)throw new Error(`git remote failed: ${j(_.stderr.trim()||_.stdout.trim()||"unknown error")}`);let Ae=J?G(O):O;console.log(`app_id: ${E.appId}`),E.gitOwner&&E.gitRepo&&console.log(`repo: ${E.gitOwner}/${E.gitRepo}`),console.log(`remote: ${Ae}`),console.log('next: git add . && git commit -m "init"');let Ie=E.defaultBranch||"master";console.log(`next: openpond repo push --path ${p} --branch ${Ie}`),J||console.log(`token-remote (non-interactive): git -C ${p} remote set-url origin ${G(O)}`);try{await ye({apiBase:s,apiKey:a,forceRefresh:!0})}catch(b){console.warn("cache refresh failed",b)}}g(Ze,"runRepoCreate");async function Se(e){let o=await B("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e});if(o.code!==0)return null;let t=o.stdout.trim();return t.length>0?t:null}g(Se,"resolveGitBranch");async function et(e){let o=await y(),t=w(o),r=await R(o,t),n=typeof e.path=="string"?e.path:typeof e.dir=="string"?e.dir:null,i=U.resolve(n&&n.trim().length>0?n.trim():"."),a=U.join(i,".git");if(!W(a))throw new Error(`git repo not found at ${i} (missing .git)`);let s=await F(i,"origin");if(!s)throw new Error("origin remote not set; run `openpond repo create` first");z(s);let c=(typeof e.branch=="string"?e.branch.trim():"")||await Se(i);if(!c)throw new Error("unable to resolve git branch; pass --branch");let d;try{d=D(s,r)}catch{throw new Error("origin remote must be https for tokenized pushes")}let u=v(e.keepTokenRemote)||v(e.token)||v(e.setRemoteToken),l=s.includes("x-access-token:"),m=!u&&!l?s:null,h=process.env.GIT_TERMINAL_PROMPT;process.env.GIT_TERMINAL_PROMPT="0";try{if(!l){let p=await B("git",["remote","set-url","origin",d],{cwd:i});if(p.code!==0)throw new Error(`git remote set-url failed: ${j(p.stderr.trim()||p.stdout.trim()||"unknown error")}`)}if((await B("git",["push","-u","origin",c],{cwd:i,inherit:!0})).code!==0)throw new Error("git push failed")}finally{m&&await B("git",["remote","set-url","origin",m],{cwd:i}).catch(()=>null),h===void 0?delete process.env.GIT_TERMINAL_PROMPT:process.env.GIT_TERMINAL_PROMPT=h}}g(et,"runRepoPush");async function tt(e){if(e.length===0)throw new Error("usage: opentool <init|validate|build> [args]");let o=process.platform==="win32"?"npx.cmd":"npx";if((await B(o,["opentool",...e],{inherit:!0})).code!==0)throw new Error("opentool command failed")}g(tt,"runOpentool");async function nt(){let e="openpond",o=Z(),t=await te(e),r=`npm i -g ${e}@${t}`,n=ee(o,t);if(n===0){console.log(`${e} is up to date (${o})`);return}if(n===-1){console.log(`Update available: ${o} -> ${t}`),console.log(`Run: ${r}`);return}if(n===1){console.log(`Installed version (${o}) is newer than npm latest (${t}).`);return}if(o===t){console.log(`${e} is up to date (${o})`);return}console.log(`Installed: ${o}`),console.log(`Latest: ${t}`),console.log(`Run: ${r}`)}g(nt,"runCheckUpdate");export{Ge as a,je as b,ze as c,He as d,Fe as e,Ve as f,We as g,qe as h,Ye as i,Qe as j,Xe as k,Ze as l,Se as m,et as n,tt as o,nt as p};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{c as B}from"./chunk-
|
|
2
|
+
import{c as B}from"./chunk-PA7XP42P.js";import{e as D,f as k,g as K}from"./chunk-BSHAIAXY.js";import{f as w}from"./chunk-3M53YXEI.js";import{$ as N,W as y,X as L,Y as U,Z as M,_ as $,f as T,g as A,j as I,u as _}from"./chunk-QXVIIM4T.js";import{d as O}from"./chunk-R3XFY7VL.js";import{b as v}from"./chunk-GLUWATL5.js";import{h as C}from"./chunk-Z3D4C7BG.js";import{a as o}from"./chunk-FTQLQJQV.js";function ce(e){if(e.repoUrl)return e.repoUrl;if(e.gitHost&&e.gitOwner&&e.gitRepo)return`https://${e.gitHost}/${e.gitOwner}/${e.gitRepo}.git`;throw new Error("repoUrl missing from API response")}o(ce,"resolveRepoUrl");function le(e,t){let n=new URL(e),r=encodeURIComponent(t);return`${n.protocol}//x-access-token:${r}@${n.host}${n.pathname}`}o(le,"formatTokenizedRepoUrl");function fe(e){let t=new URL(e);return`${t.protocol}//x-access-token:$OPENPOND_API_KEY@${t.host}${t.pathname}`}o(fe,"formatTokenizedRepoUrlForPrint");function me(e){return e.replace(/x-access-token:[^@]+@/g,"x-access-token:***@")}o(me,"redactToken");function pe(e){let t=process.env.OPENPOND_BASE_URL;if(t)try{let n=new URL(t).hostname,r=new URL(e).hostname;n&&r&&n!==r&&(console.warn(`warning: repo host (${r}) does not match OPENPOND_BASE_URL (${n})`),console.warn("warning: verify your git host configuration matches OPENPOND_BASE_URL."))}catch{}}o(pe,"warnOnRepoHostMismatch");function W(e){let t=e.split("/").filter(Boolean);if(t.length!==2)throw new Error("expected <handle>/<repo>");return{handle:t[0],repo:t[1]}}o(W,"parseHandleRepo");function S(e){return(e||"").trim().toLowerCase()}o(S,"normalizeRepoName");async function ee(e){if(!e.forceRefresh){let n=await L({apiBase:e.apiBase,apiKey:e.apiKey,ttlMs:y});if(n)return n}let t=await I(e.apiBase,e.apiKey);return await U({apiBase:e.apiBase,apiKey:e.apiKey,apps:t}),t}o(ee,"fetchAppsWithCache");async function Re(e){if(!e.forceRefresh){let r=await M({apiBase:e.apiBase,apiKey:e.apiKey,ttlMs:y});if(r)return r}let t=await _(e.apiBase,e.apiKey),n=Array.isArray(t.tools)?t.tools:[];return await $({apiBase:e.apiBase,apiKey:e.apiKey,tools:n}),n}o(Re,"fetchToolsWithCache");async function Pe(e,t,n){let{handle:r,repo:s}=W(n),i=await ee({apiBase:e,apiKey:t}),a=S(s),d=i.find(u=>u.handle&&u.handle!==r?!1:[u.repo,u.gitRepo,u.id].map(S).includes(a));if(!d)throw new Error(`app not found for ${r}/${s}`);return{app:d,handle:r,repo:s}}o(Pe,"resolveAppTarget");async function Ee(e){let t=e.intervalMs??5e3,n=e.timeoutMs??240*1e3,r=new Set,s=Date.now();for(;Date.now()-s<n;){let a=(await T(e.baseUrl,e.apiKey,e.deploymentId)).filter(u=>!r.has(u.id));for(let u of a)r.add(u.id);for(let u of a)console.log(`${e.prefix}${u.message}`);let d=await A(e.baseUrl,e.apiKey,e.deploymentId);if(d.status==="failed"){console.log(`${e.prefix}deployment failed`);return}if(d.status==="running"||d.status==="deployed"){console.log(`${e.prefix}deployment complete`);return}await new Promise(u=>setTimeout(u,t))}console.log(`${e.prefix}deployment still in progress`)}o(Ee,"pollDeploymentLogs");import{stdin as q,stdout as H}from"node:process";import{createInterface as F}from"node:readline/promises";async function z(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8").replace(/\r?\n$/,"")}o(z,"readAllStdin");function V(e){return new Promise((t,n)=>{let r=process.stdin,s=process.stderr,i="",a=r.isRaw;function d(){r.off("data",u),r.setRawMode&&r.setRawMode(a),r.pause(),s.write(`
|
|
3
3
|
`)}o(d,"cleanup");function u(m){let f=Buffer.isBuffer(m)?m:Buffer.from(m);for(let c of f){if(c===3){d(),n(new Error("secret prompt cancelled"));return}if(c===13||c===10){d(),t(i);return}if(c===127||c===8){i.length>0&&(i=i.slice(0,-1),s.write("\b \b"));continue}i+=Buffer.from([c]).toString("utf8"),s.write("*")}}o(u,"onData"),s.write(e),r.resume(),r.setRawMode&&r.setRawMode(!0),r.on("data",u)})}o(V,"readMaskedLine");async function Ae(e,t=!1){let n=F({input:q,output:H});try{let r=t?"[Y/n]":"[y/N]",s=(await n.question(`${e} ${r} `)).trim().toLowerCase();return s?s==="y"||s==="yes":t}finally{n.close()}}o(Ae,"promptConfirm");async function Ie(e){let t=F({input:q,output:H});try{return(await t.question(`Local path (default: ${e}): `)).trim()||e}finally{t.close()}}o(Ie,"promptForPath");var X=["readonly","attempt","feature","rollout","replay","template_build","scheduled_run","patch_only","hotfix","multi_feature_batch"],j=["none","manual","auto_after_checks"],G=[...N];function te(e,t){return(process.env.OPENPOND_SANDBOX_BASE_URL||process.env.OPENPOND_API_URL||e.apiBaseUrl||K(process.env.OPENPOND_BASE_URL||e.baseUrl)||v).replace(/\/$/,"")}o(te,"resolveSandboxBaseUrl");async function We(e){let t=await ne(e),n=k(t),r=await B(t,n),s=D(e)||process.env.OPENPOND_SANDBOX_API_URL?.trim()||null,i=te(t,e);return C(s?{apiKey:r,sandboxApiUrl:s}:{apiKey:r,baseUrl:i})}o(We,"resolveSandboxClient");async function ne(e){return O()}o(ne,"loadSandboxConfig");function qe(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw new Error("workflow-mode must be a non-empty value");let t=e.trim();if(!X.includes(t))throw new Error(`workflow-mode must be one of ${X.join(", ")}`);return t}o(qe,"parseSandboxWorkflowModeOption");function He(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw new Error("runtime-promotion-policy must be a non-empty value");let t=e.trim();if(!j.includes(t))throw new Error(`runtime-promotion-policy must be one of ${j.join(", ")}`);return t}o(He,"parseSandboxRuntimePromotionPolicyOption");function Fe(e){if(typeof e!="string"||!e.trim())return;let t=e.trim();if(!G.includes(t))throw new Error(`runtime-profile-id must be one of ${G.join(", ")}`);return t}o(Fe,"parseSandboxRuntimeProfileIdOption");function re(e){let t=Y(e.envRef,"env-ref").map(({name:i,value:a})=>({name:i,secretRef:a})),n=Y(e.envLiteral,"env-literal").map(({name:i,value:a})=>{if(oe(i)&&!w(e.allowPlainSecretEnv))throw new Error(`refusing plaintext value for secret-like env ${i}; create a sandbox secret and pass --env-ref ${i}=openpond://secret/...`);return{name:i,value:a}}),r=[...t,...n],s=new Set;for(let i of r){if(s.has(i.name))throw new Error(`duplicate sandbox env var: ${i.name}`);s.add(i.name)}return r}o(re,"parseSandboxEnvOptions");function ze(e,t){let n=re(t),r=new Set(n.map(a=>a.name)),s=new Map(n.map(a=>[a.name,a]));for(let a of e.inputs.env)if(s.get(a.name)?.value!==void 0&&a.secret!==!1)throw new Error(`sandbox template env ${a.name} requires a secret ref. Pass --env-ref ${a.name}=openpond://secret/...`);let i=e.inputs.env.filter(a=>a.required&&!r.has(a.name)).map(a=>a.name);if(i.length>0)throw new Error(`missing required sandbox template env refs: ${i.join(", ")}. Pass --env-ref NAME=openpond://secret/...`);return n}o(ze,"parseSandboxTemplateEnvOptions");function Y(e,t){return typeof e!="string"?[]:e.split(",").map(n=>n.trim()).filter(Boolean).map(n=>{let r=n.indexOf("=");if(r<=0)throw new Error(`${t} entries must use NAME=value`);let s=n.slice(0,r).trim(),i=n.slice(r+1).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))throw new Error(`${t} has invalid env name: ${s}`);if(!i)throw new Error(`${t} value is required for ${s}`);return{name:s,value:i}})}o(Y,"parseSandboxEnvAssignments");function oe(e){return/(?:SECRET|TOKEN|KEY|PASSWORD|PASSWD|PRIVATE|CREDENTIAL|DATABASE_URL|DSN)/i.test(e)}o(oe,"isSecretLikeEnvName");async function Ve(e,t){if(typeof e.value=="string"||typeof e.secretValue=="string")throw new Error("sandbox secret values must be provided with --stdin or the masked prompt");if(w(e.stdin)){let s=await z();if(!s)throw new Error(`${t} read no secret value from stdin`);return s}if(!process.stdin.isTTY)throw new Error(`${t} requires --stdin when not running in a TTY`);let r=await V(`${t}: `);if(!r)throw new Error(`${t} cannot be empty`);return r}o(Ve,"readSandboxSecretValue");function Xe(e){return{id:e.id,teamId:e.teamId,name:e.name,scope:e.scope,status:e.status,secretRef:e.secretRef,currentVersion:e.currentVersion,updatedAt:e.updatedAt,lastUsedAt:e.lastUsedAt,attachedDestinations:e.attachments?.length??0}}o(Xe,"summarizeSandboxSecret");import{Buffer as b}from"node:buffer";import{spawn as Q}from"node:child_process";var ie=600*1e3,se=2*1024*1024;function R(e,t=[],n={}){return n.inherit&&n.terminateWhenStdoutIncludes!==void 0?Promise.reject(new Error("terminateWhenStdoutIncludes requires captured stdout")):n.terminateWhenStdoutIncludes===""?Promise.reject(new Error("terminateWhenStdoutIncludes must not be empty")):new Promise((r,s)=>{let i=Q(e,t,{cwd:n.cwd,env:n.env?{...process.env,...n.env}:void 0,shell:n.shell,detached:n.detached??process.platform!=="win32",stdio:n.inherit?"inherit":[n.stdin===void 0?"ignore":"pipe","pipe","pipe"]}),a=new h(J(n)),d=new h(J(n)),u=!1,m=n.timeoutMs??ie,f,c,x=null,g=!1,P=o(()=>{f&&clearTimeout(f),c&&clearTimeout(c)},"clearTimers"),E=o(l=>{x!==null||g||(x=l,u=l==="timeout",f&&(clearTimeout(f),f=void 0),Z(i.pid,"SIGTERM"),c=setTimeout(()=>{i.exitCode===null&&i.signalCode===null&&Z(i.pid,"SIGKILL")},5e3))},"requestTermination");m>0&&(f=setTimeout(()=>{E("timeout")},m)),n.inherit||(i.stdout?.on("data",l=>{a.append(l);let p=n.terminateWhenStdoutIncludes;p!==void 0&&a.text().includes(p)&&E("output")}),i.stderr?.on("data",l=>{d.append(l)})),i.on("error",l=>{P(),g=!0,s(l)}),i.on("close",(l,p)=>{g||(g=!0,P(),r({code:l,signal:p,terminationReason:x??(p?"signal":"exit"),stdout:a.text(),stderr:d.text(),timedOut:u,stdoutTruncated:a.truncated,stderrTruncated:d.truncated}))}),n.stdin!==void 0&&i.stdin?.end(n.stdin)})}o(R,"runProcessCommand");var h=class{static{o(this,"BoundedOutput")}#t=[];#n;#e=0;truncated=!1;constructor(t){this.#n=t}append(t){let n=b.isBuffer(t)?t:b.from(t),r=this.#n-this.#e;if(r<=0){n.byteLength>0&&(this.truncated=!0);return}if(n.byteLength<=r){this.#t.push(n),this.#e+=n.byteLength;return}this.#t.push(n.subarray(0,r)),this.#e+=r,this.truncated=!0}text(){let t=b.concat(this.#t,this.#e).toString("utf8");return this.truncated?`${t}
|
|
4
4
|
[truncated after ${this.#n} bytes]
|
|
5
5
|
`:t}};function J(e){let t=e.maxOutputBytes??se;return Math.max(0,Math.floor(t))}o(J,"maxOutputBytes");function Z(e,t){if(e){if(process.platform==="win32"){let n=["/PID",String(e),"/T"];t==="SIGKILL"&&n.push("/F"),Q("taskkill",n,{stdio:"ignore",windowsHide:!0}).unref();return}try{process.kill(-e,t)}catch(n){if(n.code!=="ESRCH")throw n}}}o(Z,"terminateProcessTree");async function ae(e,t,n={}){return R(e,t,{cwd:n.cwd,inherit:n.inherit,timeoutMs:n.timeoutMs,maxOutputBytes:n.maxOutputBytes,terminateWhenStdoutIncludes:n.terminateWhenStdoutIncludes})}o(ae,"runCommand");async function rt(e,t={}){let n=t.timeoutSeconds===void 0?void 0:t.timeoutSeconds*1e3;return R(e,[],{cwd:t.cwd,env:t.env,shell:!0,inherit:t.inherit,timeoutMs:n,maxOutputBytes:t.maxOutputBytes})}o(rt,"runShellCommand");async function ot(e,t){let n=await ae("git",["remote","get-url",t],{cwd:e});if(n.code!==0)return null;let r=n.stdout.trim();return r.length>0?r:null}o(ot,"getGitRemoteUrl");export{ce as a,le as b,fe as c,me as d,pe as e,S as f,ee as g,Re as h,Pe as i,Ee as j,Ae as k,Ie as l,We as m,qe as n,He as o,Fe as p,re as q,ze as r,Ve as s,Xe as t,R as u,ae as v,rt as w,ot as x};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{a as be,b as Ae,c as Ie,d as ve}from"./chunk-
|
|
2
|
+
import{a as be,b as Ae,c as Ie,d as ve}from"./chunk-JDLAHVAJ.js";import{a as Re}from"./chunk-6FA3GG5B.js";import{c as O,i as L}from"./chunk-R3XFY7VL.js";import{f as Oe}from"./chunk-H7IWJN7L.js";import{a as s}from"./chunk-FTQLQJQV.js";var W=class extends Error{static{s(this,"OpenPondProfileSetupRequiredError")}code="agent_source_setup_required";details;constructor(t,n){let o=n.blockingRequirements.map(r=>r.label);super(["agent_source_setup_required",`Profile action ${t} has unresolved required setup.`,o.length?`Missing setup: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
3
3
|
`)),this.name="OpenPondProfileSetupRequiredError",this.details={error:"agent_source_setup_required",actionId:t,setupGate:n,missing:o,blockingSetupRequirements:n.blockingRequirements,setupRequirements:n.requirements}}};function K(e){let t=new Map;for(let a of e.sourceSetupRequirements??[]){let l=bt(a);if(e.actionId&&l&&l!==e.actionId&&h(a.actionName)!==e.actionId&&h(a.sourceActionId)!==e.actionId)continue;let c=Ee({record:a,source:"source_upload_metadata",actionId:l});c&&t.set(c.ref,c)}for(let a of e.actionCatalog)if(!(e.actionId&&a.id!==e.actionId&&a.name!==e.actionId))for(let l of a.setupRequirements??[]){let c=Ee({record:l,source:"action_catalog",actionId:a.id});c&&t.set(c.ref,c)}let n=Array.from(t.values()),o=n.filter(a=>a.blocking),r=n.filter(a=>!a.required&&!ne(a.status)).length,i=n.filter(a=>ne(a.status)).length;return{status:It(o),requirementCount:n.length,blockingCount:o.length,optionalMissingCount:r,readyCount:i,requirements:n,blockingRequirements:o}}s(K,"buildOpenPondProfileSetupGate");function oe(e,t){if(t.blockingRequirements.length>0)throw new W(e,t)}s(oe,"assertOpenPondProfileActionReady");function Rt(e){let t=e.actionId?`${e.actionId}: `:"",n=e.required?"required":"optional";return`${t}${e.label} (${n}, ${e.status})`}s(Rt,"formatOpenPondProfileSetupRequirement");function Ee(e){let t=e.source==="action_catalog"&&h(e.record.source)==="source_upload_metadata"?"source_upload_metadata":e.source,n=h(e.record.kind)??h(e.record.type),o=h(e.record.label)??h(e.record.name)??h(e.record.key)??h(e.record.provider)??h(e.record.tool)??h(e.record.command)??h(e.record.packageName)??h(e.record.path)??h(e.record.repo)??h(e.record.url)??h(e.record.id)??n??"setup requirement",r=e.record.required!==!1,i=At(e.record);return{ref:[t,e.actionId??"source",n??"requirement",o].join(":"),source:t,actionId:e.actionId,kind:n,label:o,status:i,required:r,blocking:r&&!ne(i)}}s(Ee,"setupRequirementFromRecord");function bt(e){return h(e.actionId)??h(e.sourceActionId)??h(e.actionName)}s(bt,"setupRequirementActionId");function At(e){let t=h(e.status)??h(e.state);return t?t==="satisfied"||t==="connected"||t==="provided"?"ready":t:typeof e.satisfied=="boolean"?e.satisfied?"ready":"setup_required":typeof e.ready=="boolean"&&e.ready?"ready":"setup_required"}s(At,"setupStatus");function It(e){return e.length===0?"ready":e.some(t=>["blocked","unsupported","unsupported_dependency","stale"].includes(t.status))?"blocked":"setup_required"}s(It,"gateStatus");function ne(e){return e==="ready"||e==="disabled"}s(ne,"isReadyStatus");function h(e){return typeof e=="string"&&e.trim()?e.trim():null}s(h,"text");import{stat as qt}from"node:fs/promises";import se from"node:path";import{spawn as vt}from"node:child_process";import{existsSync as re}from"node:fs";import{readFile as Et,rm as Kn,writeFile as _e}from"node:fs/promises";import ie from"node:path";var Le=["**/node_modules/","**/.bun/","**/.env","**/.env.*","**/.openpond/traces/","**/.openpond/vendor/","**/.openpond/eval-results.json","**/.openpond/artifact-index.json","**/.openpond/source-upload-cache.json",""].join(`
|
|
4
4
|
`);async function Me(e){if(!re(ie.join(e,".git"))){let i=await R(e,["init","-b","main"]);if(i.code!==0)throw new Error(H("git init",i))}let t=ie.join(e,".gitignore");if(re(t)?await xt(t):await _e(t,Le,"utf8"),await _t(e))return;let n=await N(e);if(!n.dirty&&n.files.length===0)return;let o=await R(e,["add","-A"]);if(o.code!==0)throw new Error(H("git add",o));let r=await R(e,["commit","-m","Initialize OpenPond profile"],{env:{...process.env,GIT_AUTHOR_NAME:process.env.GIT_AUTHOR_NAME||"OpenPond",GIT_AUTHOR_EMAIL:process.env.GIT_AUTHOR_EMAIL||"openpond@example.invalid",GIT_COMMITTER_NAME:process.env.GIT_COMMITTER_NAME||"OpenPond",GIT_COMMITTER_EMAIL:process.env.GIT_COMMITTER_EMAIL||"openpond@example.invalid"}});if(r.code!==0&&!/nothing to commit/i.test(r.stdout+r.stderr))throw new Error(H("git commit",r))}s(Me,"ensureProfileGitRepo");async function xt(e){let t=await Et(e,"utf8").catch(()=>""),n=Le.split(/\r?\n/).map(r=>r.trim()).filter(Boolean).filter(r=>!t.split(/\r?\n/).some(i=>i.trim()===r));if(n.length===0)return;let o=t.endsWith(`
|
|
5
5
|
`)||t.length===0?"":`
|
|
6
6
|
`;await _e(e,`${t}${o}${n.join(`
|
|
7
7
|
`)}
|
|
8
|
-
`,"utf8")}s(xt,"ensureProfileGitignoreRules");async function N(e){if(!re(ie.join(e,".git")))return{isRepo:!1,branch:null,head:null,shortHead:null,dirty:!1,upstream:null,ahead:null,behind:null,remoteUrl:null,files:[],error:null};let t=await R(e,["rev-parse","--is-inside-work-tree"]);if(t.code!==0||t.stdout.trim()!=="true")return{isRepo:!1,branch:null,head:null,shortHead:null,dirty:!1,upstream:null,ahead:null,behind:null,remoteUrl:null,files:[],error:t.stderr.trim()||t.stdout.trim()||"not a Git work tree"};let[n,o,r,i,a]=await Promise.all([B(e,["branch","--show-current"]),B(e,["rev-parse","HEAD"]),R(e,["status","--porcelain=v1","-uall"]),B(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"]),B(e,["remote","get-url","origin"])]),l=r.code===0?Mt(r.stdout):[],c=i?await Lt(e):{ahead:null,behind:null},d=o||null;return{isRepo:!0,branch:n||null,head:d,shortHead:d?d.slice(0,12):null,dirty:l.length>0,upstream:i,ahead:c.ahead,behind:c.behind,remoteUrl:a,files:l,error:r.code===0?null:H("git status",r)}}s(N,"loadProfileGitState");async function $e(e,t){let n=await N(e);if(!n.isRepo)throw new Error(n.error??"Active OpenPond profile source is not a Git repo.");if(!n.dirty)return{committed:!1,stdout:"",stderr:"",state:n};let o=await R(e,["add","-A"]);if(o.code!==0)throw new Error(H("git add",o));let r=await R(e,["commit","-m",t]);if(r.code!==0)throw new Error(H("git commit",r));return{committed:!0,stdout:r.stdout,stderr:r.stderr,state:await N(e)}}s($e,"commitProfileChanges");async function qe(e){return B(e,["rev-parse","HEAD"])}s(qe,"profileGitHead");async function _t(e){return(await R(e,["rev-parse","--verify","HEAD"])).code===0}s(_t,"hasGitHead");async function Lt(e){let t=await R(e,["rev-list","--left-right","--count","@{u}...HEAD"]);if(t.code!==0)return{ahead:null,behind:null};let[n,o]=t.stdout.trim().split(/\s+/),r=n?Number.parseInt(n,10):Number.NaN,i=o?Number.parseInt(o,10):Number.NaN;return{ahead:Number.isFinite(i)?i:null,behind:Number.isFinite(r)?r:null}}s(Lt,"loadAheadBehind");async function B(e,t){let n=await R(e,t);return n.code!==0?null:n.stdout.trim()||null}s(B,"gitText");function Mt(e){return e.split(/\r?\n/).map(t=>t.trimEnd()).filter(Boolean).map(t=>{let n=t[0]??" ",o=t[1]??" ",r=`${n}${o}`.trim()||"changed",i=t.slice(3),a=i.split(" -> "),l=n===" "?null:n,c=o===" "?null:o,d=a.length===2?a[1]:i,g=a.length===2?a[0]:null;return{path:xe(d),originalPath:g?xe(g):null,indexStatus:l,worktreeStatus:c,status:r,category:$t(l,c)}})}s(Mt,"parsePorcelainStatus");function $t(e,t){return e==="?"&&t==="?"?"untracked":e==="R"||t==="R"?"renamed":e==="A"||t==="A"?"added":e==="D"||t==="D"?"deleted":e==="M"||t==="M"?"modified":"changed"}s($t,"gitChangeCategory");function xe(e){let t=e.trim();if(!t.startsWith('"')||!t.endsWith('"'))return t;try{return JSON.parse(t)}catch{return t.slice(1,-1)}}s(xe,"unquoteGitPath");function H(e,t){return t.stderr.trim()||t.stdout.trim()||`${e} failed with exit code ${t.code??"unknown"}`}s(H,"gitFailureMessage");async function R(e,t,n={}){return new Promise((o,r)=>{let i=vt("git",t,{cwd:e,env:n.env,stdio:"pipe"}),a="",l="";i.stdout?.on("data",c=>{a+=String(c)}),i.stderr?.on("data",c=>{l+=String(c)}),i.on("error",r),i.on("close",c=>{o({code:c,stdout:a,stderr:l})}),n.input!==void 0?i.stdin?.end(n.input):i.stdin?.end()})}s(R,"runGitCommand");var ae=1500,Te=8*1024*1024,le=100*1024*1024,ce=8,jt={maxFiles:ae,maxFileBytes:Te,maxTotalBytes:le,concurrency:ce},Ft={mode:"single_json_payload",chunkingSupported:!1};async function Tt(e){let t=await R(e,["ls-files","-z"]);if(t.code!==0)throw new Error(t.stderr.trim()||t.stdout.trim()||"git ls-files failed for profile source upload");let n=t.stdout.split("\0").map(c=>c.trim()).filter(Boolean).filter(c=>{let d=c.replace(/\\/g,"/");return Fe(d)&&!Gt(d)}).sort();if(n.length===0)throw new Error("No committed profile source files found to upload.");if(n.length>ae)throw new Error(`Too many profile source files to upload: ${n.length} > ${ae}`);let o=(await je(n,ce,async c=>{let d=se.resolve(e,c),g=se.relative(e,d).replace(/\\/g,"/");if(!Fe(g))throw new Error(`Profile source path escapes repo: ${c}`);let P=await qt(d);if(!P.isFile())return null;if(P.size>Te)throw new Error(`Profile source file is too large: ${c} (${P.size} bytes)`);return{path:g,absolutePath:d,size:P.size,mtimeMs:Math.trunc(P.mtimeMs),ctimeMs:Math.trunc(P.ctimeMs)}})).filter(c=>c!==null),r=0;for(let c of o)if(r+=c.size,r>le)throw new Error(`Profile source upload is too large: ${r} > ${le}`);let i=await Ae(e),a=await je(o,ce,async c=>Ie(c,i));await ve(e,a).catch(()=>{});let l=a.map(c=>c.entry);return{entries:l,fileCount:l.length,totalBytes:r,limits:jt,transport:Ft}}s(Tt,"collectProfileSourceUploadEntries");async function je(e,t,n){let o=new Array(e.length),r=0,i=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:i},async()=>{for(;r<e.length;){let a=r;r+=1,o[a]=await n(e[a],a)}})),o}s(je,"mapWithConcurrency");function Fe(e){return e.length>0&&!e.includes("\0")&&!se.isAbsolute(e)&&!e.split(/[\\/]+/).some(t=>!t||t==="."||t==="..")}s(Fe,"isSafeProfileSourcePath");function Gt(e){return e.split(/[\\/]+/).some((t,n,o)=>{let r=t.toLowerCase();if(r===".git"||r==="node_modules"||r===".bun"||r===".env"||r.startsWith(".env.")||e.replace(/\\/g,"/")===be)return!0;if(r!==".openpond")return!1;let i=o[n+1]?.toLowerCase();return i==="goals"||i==="traces"||i==="vendor"||i==="eval-results.json"||i==="artifact-index.json"})}s(Gt,"shouldSkipProfileSourcePath");function Ht(e){let t=y(e.checkResult),n=y(t?.deployPlan)??y(e.deployPlan),o=y(n?.source),r=y(n?.checks),i=y(t?.sourceCheckStatus);return{status:e.status,agentId:e.agentId,deployPlanStatus:f(n?.status),canRun:Ge(n?.canRun),canDeploy:Ge(n?.canDeploy),sourceRef:f(o?.sourceRef),sourceCommitSha:f(o?.sourceCommitSha),manifestHash:f(o?.manifestHash),manifestPath:f(o?.manifestPath),setupCommands:b(r?.setupCommands),validationCommands:b(r?.validationCommands),requiredChecks:b(r?.requiredChecks),evalNames:b(r?.evalNames),blockedReasons:b(n?.blockedReasons),staleReasons:b(n?.staleReasons),runtimeId:f(i?.latestRuntimeId),sandboxId:f(i?.latestSandboxId),traceArtifactRefs:b(i?.traceArtifactRefs),evalResultArtifactRefs:b(i?.evalResultArtifactRefs),validatorArtifactRefs:b(i?.validatorArtifactRefs),checkedAt:e.checkedAt??new Date().toISOString(),error:e.error??null}}s(Ht,"hostedSourceCheckStatusFromPayload");function Nt(e){let t=y(e.publishResult),n=y(t?.activeManifestSnapshot)??y(t?.manifestSnapshot)??y(t?.snapshot);return{status:e.status??"published",agentId:e.agentId,snapshotId:f(n?.id),sourceRef:f(n?.sourceRef),sourceCommitSha:f(n?.sourceCommitSha),manifestHash:f(n?.manifestHash),manifestPath:f(n?.manifestPath),buildStatus:f(n?.buildStatus),validationStatus:f(n?.validationStatus),evalStatus:f(n?.evalStatus),publishedAt:f(t?.publishedAt)??f(n?.publishedAt),error:e.error??null}}s(Nt,"hostedPublishStatusFromPayload");function Ut(e){let t=y(e.runResult),n=y(t?.run),o=y(n?.runtimeSource),r=y(n?.metadata),i=y(r?.sourceSummary),a=y(r?.setupGate),l=y(r?.responseSummary),c=y(r?.traceSummary),d=y(r?.evalSummary);return{status:f(n?.status)??(e.error?"failed":"running"),agentId:f(n?.agentId)??e.agentId,runId:f(n?.id),runtimeId:f(n?.runtimeId),sandboxId:f(n?.sandboxId),sourceRef:f(o?.sourceRef)??f(i?.sourceRef)??f(r?.sourceRef),sourceCommitSha:f(o?.sourceCommitSha)??f(i?.sourceCommitSha)??f(r?.hostedHead),manifestHash:f(o?.manifestHash)??f(i?.manifestHash),setupGateStatus:f(a?.status),setupRequirementRefs:Bt(a),artifactRefs:b(l?.artifactRefs),traceArtifactRefs:b(c?.artifactRefs),evalArtifactRefs:b(d?.artifactRefs),startedAt:f(n?.createdAt),completedAt:f(n?.completedAt),error:e.error??null}}s(Ut,"hostedRunSummaryFromPayload");function Dt(e){return e?.status?e.status==="succeeded"||e.status==="passed"?"passed":e.status==="failed"||e.status==="cancelled"?"failed":"running":"not_started"}s(Dt,"hostedRunStatusFromRunSummary");function Bt(e){return e?(Array.isArray(e.requirements)?e.requirements:Array.isArray(e.blockingRequirements)?e.blockingRequirements:[]).map(n=>{let o=y(n);return f(o?.ref)??f(o?.id)??f(o?.label)}).filter(n=>!!n):[]}s(Bt,"setupRequirementRefs");function y(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}s(y,"record");function f(e){return typeof e=="string"&&e.trim()?e.trim():null}s(f,"text");function Ge(e){return typeof e=="boolean"?e:null}s(Ge,"booleanValue");function b(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}s(b,"textArray");import{createRequire as st}from"node:module";import{createHash as et,randomUUID as tt}from"node:crypto";import{spawn as hn}from"node:child_process";import{existsSync as k}from"node:fs";import{cp as yn,mkdir as v,readFile as at,readdir as lt,rename as Pe,rm as he,symlink as wn,writeFile as D}from"node:fs/promises";import u from"node:path";function ue(e=null){return{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!0,error:e}}s(ue,"emptyProfileCatalogState");function de(e=null){return{skillCount:0,generatedAt:null,stale:!0,error:e}}s(de,"emptyProfileSkillCatalogState");function fe(){return{status:"ready",requirementCount:0,blockingCount:0,optionalMissingCount:0,readyCount:0,requirements:[],blockingRequirements:[]}}s(fe,"emptyProfileSetupGate");function Y(){return{changedAgents:[],newAgents:[],deletedAgents:[],changedSkills:[],changedActions:[],changedExtensions:[],setupChanges:[],envRequirementChanges:[],files:[]}}s(Y,"emptyProfileDiffSummary");function pe(e=null){return{state:e?"error":"none",message:e??"No active OpenPond profile.",agentCount:0,actionCount:0,defaultAction:null,checkFresh:!1,checkStaleReason:e??"No active profile.",localHead:null,hostedHead:null}}s(pe,"emptyProfileSummary");import{existsSync as U}from"node:fs";import{readFile as zt,stat as Jt}from"node:fs/promises";import V from"node:path";var He=".openpond/agent-manifest.json",Ne=".openpond/action-registry.json",Wt=".openpond/source-upload-metadata.json",Kt=".openpond/agent-package-origin.json";async function Be(e){return Je({agentId:"default",sourcePath:e,preferred:!0})}s(Be,"loadProfileActionCatalog");async function ze(e){if(e.length===0)return{catalog:{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!1,error:null},actionCatalog:[],sourceSetupRequirements:[]};let t=[...e.filter(l=>l.preferred),...e.filter(l=>!l.preferred)],n=await Promise.all(t.map(Je)),o=new Map,r=[];for(let l of n)for(let c of l.actionCatalog){let d=o.has(c.id)?`${c.agentId??"agent"}.${c.sourceActionId??c.id}`:c.id,g=d===c.id?c:{...c,id:d};o.set(d,g),r.push(g)}let i=Vt(n.map(l=>l.catalog.generatedAt)),a=n.map(l=>l.catalog.error).filter(Boolean);return{catalog:{actionCount:r.length,generatedAt:i,manifestPath:n.find(l=>l.catalog.manifestPath)?.catalog.manifestPath??null,registryPath:n.find(l=>l.catalog.registryPath)?.catalog.registryPath??null,stale:n.some(l=>l.catalog.stale),error:a.length>0?a.join("; "):null},actionCatalog:r,sourceSetupRequirements:n.flatMap(l=>l.sourceSetupRequirements)}}s(ze,"loadProfileActionCatalogForSources");async function Je(e){let t=e.sourcePath,n=V.join(t,He),o=V.join(t,Ne),r=V.join(t,Wt),i=V.join(t,Kt);try{let a=await X(n),l=await X(o),c=await X(r),d=w(await X(i)),g=w(w(a)?.inputSchemas),P=De(w(c)?.setupRequirements)??[],x=Xt(P),S=new Map;for(let m of[...ge(w(a)?.actionCatalog),...ge(w(l)?.actions),...ge(w(a)?.actions)]){let $=p(m.id)??p(m.name);if(!$)continue;let C=S.get($),kt=Zt({sourceRequirementsByAction:x,actionId:$,actionName:p(m.name)}),Ct=Qt(De(m.setupRequirements)??C?.setupRequirements??[],kt),Ot={id:$,agentId:e.agentId,sourcePath:t,sourceActionId:$,name:p(m.name)??C?.name??$,label:p(m.label)??C?.label??rn($),description:p(m.description)??C?.description??null,visibility:p(m.visibility)??C?.visibility??"default",inputSchema:on(m.inputSchema,g)??C?.inputSchema??null,outputSchema:We(m.outputSchema)??C?.outputSchema??null,approvalPolicy:w(m.approvalPolicy)??C?.approvalPolicy??null,artifactPolicy:w(m.artifactPolicy)??C?.artifactPolicy??null,setupRequirements:Ct,mcp:w(m.mcp)??C?.mcp??null,schedulePolicy:w(m.schedulePolicy)??C?.schedulePolicy??null,trace:Yt(w(m.trace)??C?.trace??null,d),implementation:w(m.implementation)??C?.implementation??null,invokesModel:typeof m.invokesModel=="boolean"?m.invokesModel:C?.invokesModel};S.set($,Ot)}let M=Array.from(S.values()).filter(m=>m.visibility!=="internal"&&m.visibility!=="debug"),G=[...a?[]:[He],...l?[]:[Ne]],_=await nn([n,o]);return{catalog:{actionCount:M.length,generatedAt:_,manifestPath:U(n)?n:null,registryPath:U(o)?o:null,stale:G.length>0,error:G.length>0?tn(e,G):null},actionCatalog:M,sourceSetupRequirements:P}}catch(a){return{catalog:{actionCount:0,generatedAt:null,manifestPath:U(n)?n:null,registryPath:U(o)?o:null,stale:!0,error:a instanceof Error?a.message:String(a)},actionCatalog:[],sourceSetupRequirements:[]}}}s(Je,"loadProfileActionCatalogSource");function Yt(e,t){if(!t)return e;let n=p(t.versionId),o=p(t.digest);return!n||!o?e:{...e??{},agentVersionId:n,agentPackageDigest:o,validationReceiptIds:Ue(t.validationReceiptIds),evalReceiptIds:Ue(t.evalReceiptIds)}}s(Yt,"mergeAgentPackageTrace");function Ue(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}s(Ue,"stringArray");function Vt(e){let t=0;for(let n of e){if(!n)continue;let o=Date.parse(n);Number.isFinite(o)&&(t=Math.max(t,o))}return t>0?new Date(t).toISOString():null}s(Vt,"latestIso");function Xt(e){let t=new Map;for(let n of e){let o=[p(n.actionId),p(n.sourceActionId),p(n.actionName)].filter(r=>!!r);for(let r of o){let i=t.get(r)??[];i.push(n),t.set(r,i)}}return t}s(Xt,"sourceSetupRequirementsByAction");function Zt(e){return[...e.sourceRequirementsByAction.get(e.actionId)??[],...e.actionName&&e.actionName!==e.actionId?e.sourceRequirementsByAction.get(e.actionName)??[]:[]].map(n=>({...n,source:"source_upload_metadata"}))}s(Zt,"setupRequirementsForActionSource");function Qt(e,t){if(t.length===0)return e;let n=[],o=new Set;for(let r of[...e,...t]){let i=en(r);o.has(i)||(o.add(i),n.push(r))}return n}s(Qt,"mergeSetupRequirements");function en(e){return[p(e.actionId)??p(e.sourceActionId)??p(e.actionName)??"",p(e.kind)??p(e.type)??"",p(e.name)??p(e.key)??p(e.provider)??p(e.tool)??p(e.command)??p(e.packageName)??p(e.path)??p(e.repo)??p(e.url)??p(e.id)??""].join(":")}s(en,"setupRequirementIdentity");function tn(e,t){return[`Profile agent ${e.agentId} at ${e.sourcePath} is missing SDK catalog artifact(s): ${t.join(", ")}.`,"Run `openpond profile check --kind all` after source materialization so each enabled profile agent has inspect/build artifacts."].join(" ")}s(tn,"missingSourceArtifactsMessage");async function X(e){return U(e)?JSON.parse(await zt(e,"utf8")):null}s(X,"readJsonIfExists");async function nn(e){let t=0;for(let n of e){if(!U(n))continue;let o=await Jt(n);t=Math.max(t,o.mtimeMs)}return t>0?new Date(t).toISOString():null}s(nn,"latestMtime");function w(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}s(w,"asRecord");function ge(e){return Array.isArray(e)?e.filter(t=>!!w(t)):[]}s(ge,"records");function De(e){return Array.isArray(e)?e.filter(t=>!!w(t)):null}s(De,"recordArray");function p(e){return typeof e=="string"&&e.trim()?e.trim():null}s(p,"text");function We(e){return p(e)??w(e)}s(We,"schemaValue");function on(e,t){let n=We(e);return typeof n!="string"?n:w(t?.[n])??n}s(on,"resolvedSchemaValue");function rn(e){let t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}s(rn,"titleFromActionId");import{createHash as sn}from"node:crypto";import{existsSync as Xe}from"node:fs";import{readdir as Ze,readFile as an,stat as ln}from"node:fs/promises";import q from"node:path";var me="skills",Z="SKILL.md",Ke=8e4;async function Qe(e){let t=q.join(e,me);if(!Xe(t))return{skillCatalog:Ye({stale:!1}),skills:[]};try{let n=await Ze(t,{withFileTypes:!0}),o=(await Promise.all(n.filter(i=>i.isDirectory()).map(i=>un(e,i.name)))).sort((i,a)=>i.name.localeCompare(a.name)||i.path.localeCompare(a.path));fn(o);let r=await pn(e,o);return{skillCatalog:{skillCount:o.length,generatedAt:r,stale:!1,error:null},skills:o}}catch(n){return{skillCatalog:Ye({stale:!0,error:n instanceof Error?n.message:String(n)}),skills:[]}}}s(Qe,"loadProfileSkills");function cn(e){let t=[],n=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/.exec(e);if(!n)return{name:null,description:null,body:e.trim(),messages:["SKILL.md must start with YAML frontmatter bounded by ---."]};let o=n[1]??"",r=(n[2]??"").trim(),i;try{i=Oe.load(o)}catch(d){t.push(`SKILL.md frontmatter is invalid YAML: ${d instanceof Error?d.message:String(d)}`)}let a=mn(i),l=Ve(a?.name),c=Ve(a?.description);return l||t.push("Skill frontmatter must include a non-empty name."),c||t.push("Skill frontmatter must include a non-empty description."),r||t.push("Skill body must be non-empty markdown."),{name:l,description:c,body:r,messages:t}}s(cn,"parseProfileSkillMarkdown");function Ye(e={}){return{skillCount:0,generatedAt:null,stale:e.stale??!0,error:e.error??null}}s(Ye,"emptyProfileSkillCatalogState");async function un(e,t){let n=q.join(me,t,Z).replace(/\\/g,"/"),o=q.join(e,n),r=[],i=q.join(e,me,t),a=await dn(i),l="";Xe(o)?l=await an(o,"utf8"):r.push(`Missing ${Z}.`),l.length>Ke&&r.push(`Skill markdown exceeds the limit of ${Ke} characters.`);let c=cn(l);r.push(...c.messages);let d=c.name??t,g=c.description??"";return gn(d)||r.push("Skill name must be lowercase kebab-case."),d!==t&&r.push(`Skill name must match its directory name (${t}).`),{name:d,description:g,path:n,scope:"profile",enabled:r.length===0,sourcePath:e,charCount:l.length,sourceHash:Pn(l),validationStatus:r.length>0?"error":"valid",validationMessages:r,resourceFiles:a.filter(P=>P!==Z)}}s(un,"loadProfileSkillDirectory");async function dn(e){let t=[];async function n(o,r){let i=await Ze(o,{withFileTypes:!0});await Promise.all(i.map(async a=>{let l=r?`${r}/${a.name}`:a.name;a.isDirectory()?await n(q.join(o,a.name),l):a.isFile()&&t.push(l)}))}return s(n,"visit"),await n(e,""),t.sort()}s(dn,"listPackageFiles");function fn(e){let t=new Map;for(let n of e)t.set(n.name,(t.get(n.name)??0)+1);for(let n of e)(t.get(n.name)??0)<=1||(n.enabled=!1,n.validationStatus="error",n.validationMessages=[...n.validationMessages,`Duplicate skill name: ${n.name}`])}s(fn,"markDuplicateSkillNames");async function pn(e,t){let n=0;for(let o of t){let r=q.dirname(q.join(e,o.path)),i=[Z,...o.resourceFiles];for(let a of i){let l=await ln(q.join(r,a)).catch(()=>null);l?.isFile()&&(n=Math.max(n,l.mtimeMs))}}return n>0?new Date(n).toISOString():null}s(pn,"latestSkillMtime");function gn(e){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)}s(gn,"isKebabCaseSkillName");function mn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}s(mn,"asRecord");function Ve(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}s(Ve,"text");function Pn(e){return sn("sha256").update(e).digest("hex")}s(Pn,"sha256Hex");var F="openpond-profile.json",Sn="settings/profile.yaml",ct="default",E="default";function kn(e,t){let n=e?.defaultAgent??E,o=e?.enabledAgents&&e.enabledAgents.length>0?e.enabledAgents:[n];return{...e??{},path:t,defaultAgent:n,enabledAgents:o}}s(kn,"mergeProfileRepoManifestEntry");function ee(e,t,n){let o=A(e);if(e){let l=o.findIndex(d=>u.resolve(d.repoPath)===u.resolve(e.repoPath)&&d.profile===e.profile),c={source:o[l]?.source??"local",repositoryId:o[l]?.repositoryId??u.resolve(e.repoPath),repoPath:u.resolve(e.repoPath),profile:e.profile,...e.lastCheck?{lastCheck:e.lastCheck}:{},...e.lastPush?{lastPush:e.lastPush}:{}};l>=0?o[l]=c:o.push(c)}let r=o.findIndex(l=>u.resolve(l.repoPath)===u.resolve(t)&&l.profile===n),i=r>=0?o[r]:{source:"local",repositoryId:u.resolve(t),repoPath:u.resolve(t),profile:n};return r<0&&o.push(i),{repoPath:u.resolve(t),profile:n,mode:"local",profiles:o,...i.lastCheck?{lastCheck:i.lastCheck}:{},...i.lastPush?{lastPush:i.lastPush}:{}}}s(ee,"mergeActiveLocalProfileConfig");function A(e){if(!e)return[];let t=e.profiles?.map(n=>({...n}))??[];return t.some(n=>u.resolve(n.repoPath)===u.resolve(e.repoPath)&&n.profile===e.profile)||t.push({source:"local",repositoryId:u.resolve(e.repoPath),repoPath:u.resolve(e.repoPath),profile:e.profile,...e.lastCheck?{lastCheck:e.lastCheck}:{},...e.lastPush?{lastPush:e.lastPush}:{}}),t}s(A,"profileConfigEntries");var Cn=st(import.meta.url);function On(){return u.join(Re(),"library","profiles","default-repo")}s(On,"defaultLocalProfileRepoPath");function ut(e=null){return{mode:"none",repoPath:null,activeProfile:null,sourcePath:null,manifestPath:null,agents:[],skills:[],evals:[],git:null,catalog:ue(e),skillCatalog:de(e),actionCatalog:[],sourceSetupRequirements:[],setupGate:fe(),diff:Y(),hosted:null,summary:pe(e),lastCheck:null,error:e}}s(ut,"emptyProfileState");async function qo(e={}){let t=u.resolve(e.repoPath??On()),n=ke(e.profile),o=u.join("profiles",n),r=u.join(t,o),i=e.template??"blank-agent",a=i==="blank-profile";await v(t,{recursive:!0});let l=k(u.join(t,F)),c=await T(t).catch(()=>Tn(n,o));if(a&&l&&c.profiles[n])throw new Error(`Profile "${n}" already exists in ${t}.`);c.defaultProfile=c.defaultProfile||n,c.profiles[n]=kn(c.profiles[n],o),a&&(c.profiles[n].enabledAgents=[]),a?await v(r,{recursive:!0}):await In(r,i,!!e.force),await pt(r),await vn(t,r,n,{includeDefaultAgent:!a}),await Q(t,c),await Me(t);let d=(await O()).openpondProfile;return await L({openpondProfile:ee(d,t,n)}),j()}s(qo,"initLocalProfileRepo");async function jo(e,t,n){let o=u.resolve(e),r=await T(o),i=ke(t??r.defaultProfile);Ce(r,o,i);let a=(await O()).openpondProfile,l=ee(a,o,i);return dt(l,o,i,n),await L({openpondProfile:l}),j()}s(jo,"loadLocalProfileRepo");async function Fo(e,t,n){let o=u.resolve(e),r=await T(o),i=ke(t??r.defaultProfile);Ce(r,o,i);let a=(await O()).openpondProfile,l=ee(a,o,i);return dt(l,o,i,n),a&&(l.repoPath=a.repoPath,l.profile=a.profile,l.lastCheck=a.lastCheck,l.lastPush=a.lastPush),await L({openpondProfile:l}),bn(ye({repoPath:o,profile:i,source:n?.source,repositoryId:n?.repositoryId}))}s(Fo,"registerLocalProfileRepo");function dt(e,t,n,o){o&&(e.profiles=A(e).map(r=>u.resolve(r.repoPath)===t&&r.profile===n?{...r,source:o.source,repositoryId:o.repositoryId}:r))}s(dt,"applyProfileIdentity");async function To(e,t){let n=e.trim(),o=Fn(t);if(!n)throw new Error("Agent ID is required.");let i=(await O()).openpondProfile;if(!i)throw new Error("No active local Profile.");let a=await T(i.repoPath),l=a.profiles[i.profile];if(!l)throw new Error(`Profile "${i.profile}" was not found.`);let c=l.defaultAgent??E;if(!(l.enabledAgents??[c]).includes(n))throw new Error(`Agent "${n}" was not found in Profile "${i.profile}".`);let g={...l.agentNames??{}};return o===n?delete g[n]:g[n]=o,Object.keys(g).length?l.agentNames=g:delete l.agentNames,await Q(i.repoPath,a),j()}s(To,"renameActiveProfileAgent");async function Go(e){let t=e.agentPackage;if(Gn(t),!/^[a-z0-9][a-z0-9._-]{0,190}$/.test(t.agentId))throw new Error("Agent package ID is not safe for a local Profile.");let n=await te(),o=n.state.sourcePath;await pt(o);let r=u.join(o,"agents");await v(r,{recursive:!0});let i=u.join(r,t.agentId),a=k(i);if(a&&e.overwrite!==!0)throw new Error(`Agent "${t.agentId}" already exists. Confirm replacement to install this version.`);let l=u.join(r,`.${t.agentId}.${tt()}.installing`),c=u.join(r,`.${t.agentId}.${tt()}.backup`),d=await T(n.config.repoPath),g=JSON.stringify(d),P=!1,x=!1;try{await Hn(l,t),a&&(await Pe(i,c),P=!0),await Pe(l,i),x=!0;let S=d.profiles[n.config.profile];if(!S)throw new Error(`Profile "${n.config.profile}" was not found.`);let M=new Set(S.enabledAgents??[]);M.add(t.agentId),S.enabledAgents=[...M],S.defaultAgent||(S.defaultAgent=t.agentId),S.agentNames={...S.agentNames??{},[t.agentId]:t.title},await Q(n.config.repoPath,d),P&&await he(c,{recursive:!0,force:!0})}catch(S){throw await he(l,{recursive:!0,force:!0}),x&&await he(i,{recursive:!0,force:!0}),P&&k(c)&&await Pe(c,i),JSON.stringify(d)!==g&&await Q(n.config.repoPath,JSON.parse(g)).catch(()=>{}),S}return{state:await j(),agentId:t.agentId,versionId:t.versionId,digest:t.digest}}s(Go,"installAgentPackageIntoActiveProfile");async function j(){let t=(await O()).openpondProfile;return t?z(t):ut()}s(j,"loadOpenPondProfileState");function ye(e){return{source:e.source??"local",repositoryId:e.repositoryId?.trim()||u.resolve(e.repoPath),profileId:e.profile}}s(ye,"openPondProfileRef");async function Rn(){let e=(await O()).openpondProfile;if(!e)return{lastUsed:null,profiles:[]};let t=A(e),n=await Promise.all(t.map(async o=>{let r=await z({repoPath:o.repoPath,profile:o.profile,mode:"local",...o.lastCheck?{lastCheck:o.lastCheck}:{},...o.lastPush?{lastPush:o.lastPush}:{}});return{ref:ye(o),name:o.profile,repoPath:o.repoPath,sourcePath:r.sourcePath,state:r}}));return{lastUsed:ye({repoPath:e.repoPath,profile:e.profile,source:A(e).find(o=>u.resolve(o.repoPath)===u.resolve(e.repoPath)&&o.profile===e.profile)?.source,repositoryId:A(e).find(o=>u.resolve(o.repoPath)===u.resolve(e.repoPath)&&o.profile===e.profile)?.repositoryId}),profiles:n}}s(Rn,"loadOpenPondProfileLibrary");async function bn(e){if(!e)return j();let t=(await O()).openpondProfile,n=A(t).find(o=>o.source===e.source&&o.repositoryId===e.repositoryId&&o.profile===e.profileId);return n?z({repoPath:n.repoPath,profile:n.profile,mode:"local",...n.lastCheck?{lastCheck:n.lastCheck}:{},...n.lastPush?{lastPush:n.lastPush}:{}}):ut(`Profile "${e.profileId}" is not installed on this device.`)}s(bn,"loadOpenPondProfileStateForRef");async function Ho(e){let t=(await O()).openpondProfile,n=A(t).find(o=>o.source===e.source&&o.repositoryId===e.repositoryId&&o.profile===e.profileId);if(!n)throw new Error(`Profile "${e.profileId}" is not installed on this device.`);return await L({openpondProfile:ee(t,n.repoPath,n.profile)}),j()}s(Ho,"selectOpenPondProfile");async function No(e){let t=(await O()).openpondProfile;if(!t)return{lastUsed:null,profiles:[]};let n=A(t).filter(i=>i.source!==e.source||i.repositoryId!==e.repositoryId||i.profile!==e.profileId);if(n.length===0)return await L({openpondProfile:null}),{lastUsed:null,profiles:[]};let r=u.resolve(t.repoPath)===u.resolve(A(t).find(i=>i.source===e.source&&i.repositoryId===e.repositoryId&&i.profile===e.profileId)?.repoPath??"")&&t.profile===e.profileId?n[0]:n.find(i=>u.resolve(i.repoPath)===u.resolve(t.repoPath)&&i.profile===t.profile)??n[0];return await L({openpondProfile:{repoPath:r.repoPath,profile:r.profile,mode:"local",profiles:n,...r.lastCheck?{lastCheck:r.lastCheck}:{},...r.lastPush?{lastPush:r.lastPush}:{}}}),Rn()}s(No,"removeOpenPondProfile");async function Uo(e,t){return z({mode:"local",repoPath:e,profile:t})}s(Uo,"inspectOpenPondProfileSource");async function z(e){try{let t=await T(e.repoPath),n=Ce(t,e.repoPath,e.profile),o=await xn(t,e.profile),r=mt({manifest:t,profile:e.profile,profileSourcePath:n,agents:o}),[i,a,l,c]=await Promise.all([N(e.repoPath),ze(r),Qe(n),_n(n,r)]),d=ot(e),g=qn(i,e.profile),P=K({actionCatalog:a.actionCatalog,sourceSetupRequirements:a.sourceSetupRequirements}),x=Ln({agents:o,actionCatalog:a.actionCatalog,catalog:a.catalog,diff:g,git:i,hosted:d,lastCheck:e.lastCheck??null,error:null});return{mode:"local",repoPath:e.repoPath,activeProfile:e.profile,sourcePath:n,manifestPath:u.join(e.repoPath,F),agents:o,skills:l.skills,evals:c,git:i,catalog:a.catalog,skillCatalog:l.skillCatalog,actionCatalog:a.actionCatalog,sourceSetupRequirements:a.sourceSetupRequirements,setupGate:P,diff:g,hosted:d,summary:x,lastCheck:e.lastCheck??null,error:null}}catch(t){let n=await N(e.repoPath).catch(()=>null),o=t instanceof Error?t.message:String(t);return{mode:"local",repoPath:e.repoPath,activeProfile:e.profile,sourcePath:null,manifestPath:u.join(e.repoPath,F),agents:[],skills:[],evals:[],git:n,catalog:ue(o),skillCatalog:de(o),actionCatalog:[],sourceSetupRequirements:[],setupGate:fe(),diff:Y(),hosted:ot(e),summary:pe(o),lastCheck:e.lastCheck??null,error:o}}}s(z,"loadOpenPondProfileStateForConfig");async function Do(e){return z({repoPath:u.resolve(e.repoPath),profile:e.profileId,mode:"local"})}s(Do,"loadOpenPondProfileStateFromSource");async function te(){let e=(await O()).openpondProfile;if(!e)throw new Error("No active OpenPond profile. Run `openpond init` or `openpond profile load --path <dir>`.");let t=await j();if(t.error)throw new Error(t.error);if(!t.sourcePath)throw new Error("Active OpenPond profile has no source path.");return{config:e,state:t}}s(te,"requireActiveLocalProfile");async function Bo(e){let t=await te(),n=e.command==="run"?e.args??[]:[],o=e.command==="run"?t.state.actionCatalog.find(l=>l.id===n[0]):null,r=u.resolve(e.cwd??o?.sourcePath??t.state.sourcePath),i=e.command==="run"?nt(r,e.args??[],o?.sourceActionId??null):null;if(e.command==="run"&&i){let l=i[0],c=u.resolve(t.state.sourcePath)===r?{actionCatalog:t.state.actionCatalog,sourceSetupRequirements:t.state.sourceSetupRequirements}:await Be(r);oe(l,K({actionCatalog:c.actionCatalog,sourceSetupRequirements:c.sourceSetupRequirements,actionId:l}))}let a=await ft({command:e.command,args:e.command==="run"?i??nt(r,e.args??[]):e.args,cwd:r,inherit:e.inherit,throwOnFailure:!1});if((e.command==="inspect"||e.command==="build"||e.command==="validate"||e.command==="eval")&&await Se(e.command,a.code),a.code!==0){let l=a.stderr.trim()||a.stdout.trim();throw new Error(l||`${e.command} failed with exit code ${a.code??"unknown"}`)}return a}s(Bo,"runProfileSdkCommand");async function ft(e){let t=u.resolve(e.cwd),n=Un(),o=e.command==="run"?[...n.args,e.command,...e.args??[]]:[...n.args,e.command,"--cwd",t,...e.args??[]],r=await wt(n.command,o,{cwd:t,inherit:e.inherit,timeoutMs:e.timeoutMs,maxOutputBytes:e.maxOutputBytes});if(e.throwOnFailure!==!1&&r.code!==0){let i=St(r,e.command);throw new Error(i||`${e.command} failed with exit code ${r.code??"unknown"}`)}return r}s(ft,"runAgentSdkProjectCommand");function nt(e,t,n=null){let[o,...r]=t;if(!o||o.startsWith("--"))throw new Error("run requires an action name");return[n??o,"--cwd",e,...r]}s(nt,"runCommandArgs");async function zo(e){let t=!e||e==="all"?["inspect","build","validate","eval"]:[e],n=await te(),o=await T(n.config.repoPath),r=mt({manifest:o,profile:n.config.profile,profileSourcePath:n.state.sourcePath,agents:n.state.agents});if(r.length===0){if(t.some(i=>i!=="inspect"&&i!=="build"&&i!=="validate"&&i!=="eval"))throw new Error("check kind must be one of inspect, build, validate, eval, all");await Se("validate",0);return}for(let i of t){if(i!=="inspect"&&i!=="build"&&i!=="validate"&&i!=="eval")throw new Error("check kind must be one of inspect, build, validate, eval, all");for(let a of r)await An({command:i,source:a,profileSourcePath:n.state.sourcePath,sourceCount:r.length})}}s(zo,"runProfileCheck");async function An(e){let t=e.command==="inspect"||e.command==="validate"||e.command==="eval"?["--json"]:[];if(e.sourceCount>1){let o=u.relative(e.profileSourcePath,e.source.sourcePath)||".";console.log(`
|
|
8
|
+
`,"utf8")}s(xt,"ensureProfileGitignoreRules");async function N(e){if(!re(ie.join(e,".git")))return{isRepo:!1,branch:null,head:null,shortHead:null,dirty:!1,upstream:null,ahead:null,behind:null,remoteUrl:null,files:[],error:null};let t=await R(e,["rev-parse","--is-inside-work-tree"]);if(t.code!==0||t.stdout.trim()!=="true")return{isRepo:!1,branch:null,head:null,shortHead:null,dirty:!1,upstream:null,ahead:null,behind:null,remoteUrl:null,files:[],error:t.stderr.trim()||t.stdout.trim()||"not a Git work tree"};let[n,o,r,i,a]=await Promise.all([B(e,["branch","--show-current"]),B(e,["rev-parse","HEAD"]),R(e,["status","--porcelain=v1","-uall"]),B(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"]),B(e,["remote","get-url","origin"])]),l=r.code===0?Mt(r.stdout):[],c=i?await Lt(e):{ahead:null,behind:null},d=o||null;return{isRepo:!0,branch:n||null,head:d,shortHead:d?d.slice(0,12):null,dirty:l.length>0,upstream:i,ahead:c.ahead,behind:c.behind,remoteUrl:a,files:l,error:r.code===0?null:H("git status",r)}}s(N,"loadProfileGitState");async function $e(e,t){let n=await N(e);if(!n.isRepo)throw new Error(n.error??"Active OpenPond profile source is not a Git repo.");if(!n.dirty)return{committed:!1,stdout:"",stderr:"",state:n};let o=await R(e,["add","-A"]);if(o.code!==0)throw new Error(H("git add",o));let r=await R(e,["commit","-m",t]);if(r.code!==0)throw new Error(H("git commit",r));return{committed:!0,stdout:r.stdout,stderr:r.stderr,state:await N(e)}}s($e,"commitProfileChanges");async function qe(e){return B(e,["rev-parse","HEAD"])}s(qe,"profileGitHead");async function _t(e){return(await R(e,["rev-parse","--verify","HEAD"])).code===0}s(_t,"hasGitHead");async function Lt(e){let t=await R(e,["rev-list","--left-right","--count","@{u}...HEAD"]);if(t.code!==0)return{ahead:null,behind:null};let[n,o]=t.stdout.trim().split(/\s+/),r=n?Number.parseInt(n,10):Number.NaN,i=o?Number.parseInt(o,10):Number.NaN;return{ahead:Number.isFinite(i)?i:null,behind:Number.isFinite(r)?r:null}}s(Lt,"loadAheadBehind");async function B(e,t){let n=await R(e,t);return n.code!==0?null:n.stdout.trim()||null}s(B,"gitText");function Mt(e){return e.split(/\r?\n/).map(t=>t.trimEnd()).filter(Boolean).map(t=>{let n=t[0]??" ",o=t[1]??" ",r=`${n}${o}`.trim()||"changed",i=t.slice(3),a=i.split(" -> "),l=n===" "?null:n,c=o===" "?null:o,d=a.length===2?a[1]:i,g=a.length===2?a[0]:null;return{path:xe(d),originalPath:g?xe(g):null,indexStatus:l,worktreeStatus:c,status:r,category:$t(l,c)}})}s(Mt,"parsePorcelainStatus");function $t(e,t){return e==="?"&&t==="?"?"untracked":e==="R"||t==="R"?"renamed":e==="A"||t==="A"?"added":e==="D"||t==="D"?"deleted":e==="M"||t==="M"?"modified":"changed"}s($t,"gitChangeCategory");function xe(e){let t=e.trim();if(!t.startsWith('"')||!t.endsWith('"'))return t;try{return JSON.parse(t)}catch{return t.slice(1,-1)}}s(xe,"unquoteGitPath");function H(e,t){return t.stderr.trim()||t.stdout.trim()||`${e} failed with exit code ${t.code??"unknown"}`}s(H,"gitFailureMessage");async function R(e,t,n={}){return new Promise((o,r)=>{let i=vt("git",t,{cwd:e,env:n.env,stdio:"pipe"}),a="",l="";i.stdout?.on("data",c=>{a+=String(c)}),i.stderr?.on("data",c=>{l+=String(c)}),i.on("error",r),i.on("close",c=>{o({code:c,stdout:a,stderr:l})}),n.input!==void 0?i.stdin?.end(n.input):i.stdin?.end()})}s(R,"runGitCommand");var ae=1500,Te=8*1024*1024,le=100*1024*1024,ce=8,jt={maxFiles:ae,maxFileBytes:Te,maxTotalBytes:le,concurrency:ce},Ft={mode:"single_json_payload",chunkingSupported:!1};async function Tt(e){let t=await R(e,["ls-files","-z"]);if(t.code!==0)throw new Error(t.stderr.trim()||t.stdout.trim()||"git ls-files failed for profile source upload");let n=t.stdout.split("\0").map(c=>c.trim()).filter(Boolean).filter(c=>{let d=c.replace(/\\/g,"/");return Fe(d)&&!Gt(d)}).sort();if(n.length===0)throw new Error("No committed profile source files found to upload.");if(n.length>ae)throw new Error(`Too many profile source files to upload: ${n.length} > ${ae}`);let o=(await je(n,ce,async c=>{let d=se.resolve(e,c),g=se.relative(e,d).replace(/\\/g,"/");if(!Fe(g))throw new Error(`Profile source path escapes repo: ${c}`);let P=await qt(d);if(!P.isFile())return null;if(P.size>Te)throw new Error(`Profile source file is too large: ${c} (${P.size} bytes)`);return{path:g,absolutePath:d,size:P.size,mtimeMs:Math.trunc(P.mtimeMs),ctimeMs:Math.trunc(P.ctimeMs)}})).filter(c=>c!==null),r=0;for(let c of o)if(r+=c.size,r>le)throw new Error(`Profile source upload is too large: ${r} > ${le}`);let i=await Ae(e),a=await je(o,ce,async c=>Ie(c,i));await ve(e,a).catch(()=>{});let l=a.map(c=>c.entry);return{entries:l,fileCount:l.length,totalBytes:r,limits:jt,transport:Ft}}s(Tt,"collectProfileSourceUploadEntries");async function je(e,t,n){let o=new Array(e.length),r=0,i=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:i},async()=>{for(;r<e.length;){let a=r;r+=1,o[a]=await n(e[a],a)}})),o}s(je,"mapWithConcurrency");function Fe(e){return e.length>0&&!e.includes("\0")&&!se.isAbsolute(e)&&!e.split(/[\\/]+/).some(t=>!t||t==="."||t==="..")}s(Fe,"isSafeProfileSourcePath");function Gt(e){return e.split(/[\\/]+/).some((t,n,o)=>{let r=t.toLowerCase();if(r===".git"||r==="node_modules"||r===".bun"||r===".env"||r.startsWith(".env.")||e.replace(/\\/g,"/")===be)return!0;if(r!==".openpond")return!1;let i=o[n+1]?.toLowerCase();return i==="goals"||i==="traces"||i==="vendor"||i==="eval-results.json"||i==="artifact-index.json"})}s(Gt,"shouldSkipProfileSourcePath");function Ht(e){let t=y(e.checkResult),n=y(t?.deployPlan)??y(e.deployPlan),o=y(n?.source),r=y(n?.checks),i=y(t?.sourceCheckStatus);return{status:e.status,agentId:e.agentId,deployPlanStatus:f(n?.status),canRun:Ge(n?.canRun),canDeploy:Ge(n?.canDeploy),sourceRef:f(o?.sourceRef),sourceCommitSha:f(o?.sourceCommitSha),manifestHash:f(o?.manifestHash),manifestPath:f(o?.manifestPath),setupCommands:b(r?.setupCommands),validationCommands:b(r?.validationCommands),requiredChecks:b(r?.requiredChecks),evalNames:b(r?.evalNames),blockedReasons:b(n?.blockedReasons),staleReasons:b(n?.staleReasons),runtimeId:f(i?.latestRuntimeId),sandboxId:f(i?.latestSandboxId),traceArtifactRefs:b(i?.traceArtifactRefs),evalResultArtifactRefs:b(i?.evalResultArtifactRefs),validatorArtifactRefs:b(i?.validatorArtifactRefs),checkedAt:e.checkedAt??new Date().toISOString(),error:e.error??null}}s(Ht,"hostedSourceCheckStatusFromPayload");function Nt(e){let t=y(e.publishResult),n=y(t?.activeManifestSnapshot)??y(t?.manifestSnapshot)??y(t?.snapshot);return{status:e.status??"published",agentId:e.agentId,snapshotId:f(n?.id),sourceRef:f(n?.sourceRef),sourceCommitSha:f(n?.sourceCommitSha),manifestHash:f(n?.manifestHash),manifestPath:f(n?.manifestPath),buildStatus:f(n?.buildStatus),validationStatus:f(n?.validationStatus),evalStatus:f(n?.evalStatus),publishedAt:f(t?.publishedAt)??f(n?.publishedAt),error:e.error??null}}s(Nt,"hostedPublishStatusFromPayload");function Ut(e){let t=y(e.runResult),n=y(t?.run),o=y(n?.runtimeSource),r=y(n?.metadata),i=y(r?.sourceSummary),a=y(r?.setupGate),l=y(r?.responseSummary),c=y(r?.traceSummary),d=y(r?.evalSummary);return{status:f(n?.status)??(e.error?"failed":"running"),agentId:f(n?.agentId)??e.agentId,runId:f(n?.id),runtimeId:f(n?.runtimeId),sandboxId:f(n?.sandboxId),sourceRef:f(o?.sourceRef)??f(i?.sourceRef)??f(r?.sourceRef),sourceCommitSha:f(o?.sourceCommitSha)??f(i?.sourceCommitSha)??f(r?.hostedHead),manifestHash:f(o?.manifestHash)??f(i?.manifestHash),setupGateStatus:f(a?.status),setupRequirementRefs:Bt(a),artifactRefs:b(l?.artifactRefs),traceArtifactRefs:b(c?.artifactRefs),evalArtifactRefs:b(d?.artifactRefs),startedAt:f(n?.createdAt),completedAt:f(n?.completedAt),error:e.error??null}}s(Ut,"hostedRunSummaryFromPayload");function Dt(e){return e?.status?e.status==="succeeded"||e.status==="passed"?"passed":e.status==="failed"||e.status==="cancelled"?"failed":"running":"not_started"}s(Dt,"hostedRunStatusFromRunSummary");function Bt(e){return e?(Array.isArray(e.requirements)?e.requirements:Array.isArray(e.blockingRequirements)?e.blockingRequirements:[]).map(n=>{let o=y(n);return f(o?.ref)??f(o?.id)??f(o?.label)}).filter(n=>!!n):[]}s(Bt,"setupRequirementRefs");function y(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}s(y,"record");function f(e){return typeof e=="string"&&e.trim()?e.trim():null}s(f,"text");function Ge(e){return typeof e=="boolean"?e:null}s(Ge,"booleanValue");function b(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}s(b,"textArray");import{createRequire as st}from"node:module";import{createHash as et,randomUUID as tt}from"node:crypto";import{spawn as hn}from"node:child_process";import{existsSync as k}from"node:fs";import{cp as yn,mkdir as v,readFile as at,readdir as lt,rename as Pe,rm as he,symlink as wn,writeFile as D}from"node:fs/promises";import u from"node:path";function ue(e=null){return{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!0,error:e}}s(ue,"emptyProfileCatalogState");function de(e=null){return{skillCount:0,generatedAt:null,stale:!0,error:e}}s(de,"emptyProfileSkillCatalogState");function fe(){return{status:"ready",requirementCount:0,blockingCount:0,optionalMissingCount:0,readyCount:0,requirements:[],blockingRequirements:[]}}s(fe,"emptyProfileSetupGate");function Y(){return{changedAgents:[],newAgents:[],deletedAgents:[],changedSkills:[],changedActions:[],changedExtensions:[],setupChanges:[],envRequirementChanges:[],files:[]}}s(Y,"emptyProfileDiffSummary");function pe(e=null){return{state:e?"error":"none",message:e??"No active OpenPond profile.",agentCount:0,actionCount:0,defaultAction:null,checkFresh:!1,checkStaleReason:e??"No active profile.",localHead:null,hostedHead:null}}s(pe,"emptyProfileSummary");import{existsSync as U}from"node:fs";import{readFile as zt,stat as Jt}from"node:fs/promises";import V from"node:path";var He=".openpond/agent-manifest.json",Ne=".openpond/action-registry.json",Wt=".openpond/source-upload-metadata.json",Kt=".openpond/agent-package-origin.json";async function Be(e){return Je({agentId:"default",sourcePath:e,preferred:!0})}s(Be,"loadProfileActionCatalog");async function ze(e){if(e.length===0)return{catalog:{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!1,error:null},actionCatalog:[],sourceSetupRequirements:[]};let t=[...e.filter(l=>l.preferred),...e.filter(l=>!l.preferred)],n=await Promise.all(t.map(Je)),o=new Map,r=[];for(let l of n)for(let c of l.actionCatalog){let d=o.has(c.id)?`${c.agentId??"agent"}.${c.sourceActionId??c.id}`:c.id,g=d===c.id?c:{...c,id:d};o.set(d,g),r.push(g)}let i=Vt(n.map(l=>l.catalog.generatedAt)),a=n.map(l=>l.catalog.error).filter(Boolean);return{catalog:{actionCount:r.length,generatedAt:i,manifestPath:n.find(l=>l.catalog.manifestPath)?.catalog.manifestPath??null,registryPath:n.find(l=>l.catalog.registryPath)?.catalog.registryPath??null,stale:n.some(l=>l.catalog.stale),error:a.length>0?a.join("; "):null},actionCatalog:r,sourceSetupRequirements:n.flatMap(l=>l.sourceSetupRequirements)}}s(ze,"loadProfileActionCatalogForSources");async function Je(e){let t=e.sourcePath,n=V.join(t,He),o=V.join(t,Ne),r=V.join(t,Wt),i=V.join(t,Kt);try{let a=await X(n),l=await X(o),c=await X(r),d=w(await X(i)),g=w(w(a)?.inputSchemas),P=De(w(c)?.setupRequirements)??[],x=Xt(P),S=new Map;for(let m of[...ge(w(a)?.actionCatalog),...ge(w(l)?.actions),...ge(w(a)?.actions)]){let $=p(m.id)??p(m.name);if(!$)continue;let C=S.get($),kt=Zt({sourceRequirementsByAction:x,actionId:$,actionName:p(m.name)}),Ct=Qt(De(m.setupRequirements)??C?.setupRequirements??[],kt),Ot={id:$,agentId:e.agentId,sourcePath:t,sourceActionId:$,name:p(m.name)??C?.name??$,label:p(m.label)??C?.label??rn($),description:p(m.description)??C?.description??null,visibility:p(m.visibility)??C?.visibility??"default",inputSchema:on(m.inputSchema,g)??C?.inputSchema??null,outputSchema:We(m.outputSchema)??C?.outputSchema??null,approvalPolicy:w(m.approvalPolicy)??C?.approvalPolicy??null,artifactPolicy:w(m.artifactPolicy)??C?.artifactPolicy??null,setupRequirements:Ct,mcp:w(m.mcp)??C?.mcp??null,schedulePolicy:w(m.schedulePolicy)??C?.schedulePolicy??null,trace:Yt(w(m.trace)??C?.trace??null,d),implementation:w(m.implementation)??C?.implementation??null,invokesModel:typeof m.invokesModel=="boolean"?m.invokesModel:C?.invokesModel};S.set($,Ot)}let M=Array.from(S.values()).filter(m=>m.visibility!=="internal"&&m.visibility!=="debug"),G=[...a?[]:[He],...l?[]:[Ne]],_=await nn([n,o]);return{catalog:{actionCount:M.length,generatedAt:_,manifestPath:U(n)?n:null,registryPath:U(o)?o:null,stale:G.length>0,error:G.length>0?tn(e,G):null},actionCatalog:M,sourceSetupRequirements:P}}catch(a){return{catalog:{actionCount:0,generatedAt:null,manifestPath:U(n)?n:null,registryPath:U(o)?o:null,stale:!0,error:a instanceof Error?a.message:String(a)},actionCatalog:[],sourceSetupRequirements:[]}}}s(Je,"loadProfileActionCatalogSource");function Yt(e,t){if(!t)return e;let n=p(t.versionId),o=p(t.digest);return!n||!o?e:{...e??{},agentVersionId:n,agentPackageDigest:o,validationReceiptIds:Ue(t.validationReceiptIds),evalReceiptIds:Ue(t.evalReceiptIds)}}s(Yt,"mergeAgentPackageTrace");function Ue(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}s(Ue,"stringArray");function Vt(e){let t=0;for(let n of e){if(!n)continue;let o=Date.parse(n);Number.isFinite(o)&&(t=Math.max(t,o))}return t>0?new Date(t).toISOString():null}s(Vt,"latestIso");function Xt(e){let t=new Map;for(let n of e){let o=[p(n.actionId),p(n.sourceActionId),p(n.actionName)].filter(r=>!!r);for(let r of o){let i=t.get(r)??[];i.push(n),t.set(r,i)}}return t}s(Xt,"sourceSetupRequirementsByAction");function Zt(e){return[...e.sourceRequirementsByAction.get(e.actionId)??[],...e.actionName&&e.actionName!==e.actionId?e.sourceRequirementsByAction.get(e.actionName)??[]:[]].map(n=>({...n,source:"source_upload_metadata"}))}s(Zt,"setupRequirementsForActionSource");function Qt(e,t){if(t.length===0)return e;let n=[],o=new Set;for(let r of[...e,...t]){let i=en(r);o.has(i)||(o.add(i),n.push(r))}return n}s(Qt,"mergeSetupRequirements");function en(e){return[p(e.actionId)??p(e.sourceActionId)??p(e.actionName)??"",p(e.kind)??p(e.type)??"",p(e.name)??p(e.key)??p(e.provider)??p(e.tool)??p(e.command)??p(e.packageName)??p(e.path)??p(e.repo)??p(e.url)??p(e.id)??""].join(":")}s(en,"setupRequirementIdentity");function tn(e,t){return[`Profile agent ${e.agentId} at ${e.sourcePath} is missing SDK catalog artifact(s): ${t.join(", ")}.`,"Run `openpond profile check --kind all` after source materialization so each enabled profile agent has inspect/build artifacts."].join(" ")}s(tn,"missingSourceArtifactsMessage");async function X(e){return U(e)?JSON.parse(await zt(e,"utf8")):null}s(X,"readJsonIfExists");async function nn(e){let t=0;for(let n of e){if(!U(n))continue;let o=await Jt(n);t=Math.max(t,o.mtimeMs)}return t>0?new Date(t).toISOString():null}s(nn,"latestMtime");function w(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}s(w,"asRecord");function ge(e){return Array.isArray(e)?e.filter(t=>!!w(t)):[]}s(ge,"records");function De(e){return Array.isArray(e)?e.filter(t=>!!w(t)):null}s(De,"recordArray");function p(e){return typeof e=="string"&&e.trim()?e.trim():null}s(p,"text");function We(e){return p(e)??w(e)}s(We,"schemaValue");function on(e,t){let n=We(e);return typeof n!="string"?n:w(t?.[n])??n}s(on,"resolvedSchemaValue");function rn(e){let t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}s(rn,"titleFromActionId");import{createHash as sn}from"node:crypto";import{existsSync as Xe}from"node:fs";import{readdir as Ze,readFile as an,stat as ln}from"node:fs/promises";import q from"node:path";var me="skills",Z="SKILL.md",Ke=8e4;async function Qe(e){let t=q.join(e,me);if(!Xe(t))return{skillCatalog:Ye({stale:!1}),skills:[]};try{let n=await Ze(t,{withFileTypes:!0}),o=(await Promise.all(n.filter(i=>i.isDirectory()).map(i=>un(e,i.name)))).sort((i,a)=>i.name.localeCompare(a.name)||i.path.localeCompare(a.path));fn(o);let r=await pn(e,o);return{skillCatalog:{skillCount:o.length,generatedAt:r,stale:!1,error:null},skills:o}}catch(n){return{skillCatalog:Ye({stale:!0,error:n instanceof Error?n.message:String(n)}),skills:[]}}}s(Qe,"loadProfileSkills");function cn(e){let t=[],n=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/.exec(e);if(!n)return{name:null,description:null,body:e.trim(),messages:["SKILL.md must start with YAML frontmatter bounded by ---."]};let o=n[1]??"",r=(n[2]??"").trim(),i;try{i=Re.load(o)}catch(d){t.push(`SKILL.md frontmatter is invalid YAML: ${d instanceof Error?d.message:String(d)}`)}let a=mn(i),l=Ve(a?.name),c=Ve(a?.description);return l||t.push("Skill frontmatter must include a non-empty name."),c||t.push("Skill frontmatter must include a non-empty description."),r||t.push("Skill body must be non-empty markdown."),{name:l,description:c,body:r,messages:t}}s(cn,"parseProfileSkillMarkdown");function Ye(e={}){return{skillCount:0,generatedAt:null,stale:e.stale??!0,error:e.error??null}}s(Ye,"emptyProfileSkillCatalogState");async function un(e,t){let n=q.join(me,t,Z).replace(/\\/g,"/"),o=q.join(e,n),r=[],i=q.join(e,me,t),a=await dn(i),l="";Xe(o)?l=await an(o,"utf8"):r.push(`Missing ${Z}.`),l.length>Ke&&r.push(`Skill markdown exceeds the limit of ${Ke} characters.`);let c=cn(l);r.push(...c.messages);let d=c.name??t,g=c.description??"";return gn(d)||r.push("Skill name must be lowercase kebab-case."),d!==t&&r.push(`Skill name must match its directory name (${t}).`),{name:d,description:g,path:n,scope:"profile",enabled:r.length===0,sourcePath:e,charCount:l.length,sourceHash:Pn(l),validationStatus:r.length>0?"error":"valid",validationMessages:r,resourceFiles:a.filter(P=>P!==Z)}}s(un,"loadProfileSkillDirectory");async function dn(e){let t=[];async function n(o,r){let i=await Ze(o,{withFileTypes:!0});await Promise.all(i.map(async a=>{let l=r?`${r}/${a.name}`:a.name;a.isDirectory()?await n(q.join(o,a.name),l):a.isFile()&&t.push(l)}))}return s(n,"visit"),await n(e,""),t.sort()}s(dn,"listPackageFiles");function fn(e){let t=new Map;for(let n of e)t.set(n.name,(t.get(n.name)??0)+1);for(let n of e)(t.get(n.name)??0)<=1||(n.enabled=!1,n.validationStatus="error",n.validationMessages=[...n.validationMessages,`Duplicate skill name: ${n.name}`])}s(fn,"markDuplicateSkillNames");async function pn(e,t){let n=0;for(let o of t){let r=q.dirname(q.join(e,o.path)),i=[Z,...o.resourceFiles];for(let a of i){let l=await ln(q.join(r,a)).catch(()=>null);l?.isFile()&&(n=Math.max(n,l.mtimeMs))}}return n>0?new Date(n).toISOString():null}s(pn,"latestSkillMtime");function gn(e){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)}s(gn,"isKebabCaseSkillName");function mn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}s(mn,"asRecord");function Ve(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}s(Ve,"text");function Pn(e){return sn("sha256").update(e).digest("hex")}s(Pn,"sha256Hex");var F="openpond-profile.json",Sn="settings/profile.yaml",ct="default",E="default";function kn(e,t){let n=e?.defaultAgent??E,o=e?.enabledAgents&&e.enabledAgents.length>0?e.enabledAgents:[n];return{...e??{},path:t,defaultAgent:n,enabledAgents:o}}s(kn,"mergeProfileRepoManifestEntry");function ee(e,t,n){let o=A(e);if(e){let l=o.findIndex(d=>u.resolve(d.repoPath)===u.resolve(e.repoPath)&&d.profile===e.profile),c={source:o[l]?.source??"local",repositoryId:o[l]?.repositoryId??u.resolve(e.repoPath),repoPath:u.resolve(e.repoPath),profile:e.profile,...e.lastCheck?{lastCheck:e.lastCheck}:{},...e.lastPush?{lastPush:e.lastPush}:{}};l>=0?o[l]=c:o.push(c)}let r=o.findIndex(l=>u.resolve(l.repoPath)===u.resolve(t)&&l.profile===n),i=r>=0?o[r]:{source:"local",repositoryId:u.resolve(t),repoPath:u.resolve(t),profile:n};return r<0&&o.push(i),{repoPath:u.resolve(t),profile:n,mode:"local",profiles:o,...i.lastCheck?{lastCheck:i.lastCheck}:{},...i.lastPush?{lastPush:i.lastPush}:{}}}s(ee,"mergeActiveLocalProfileConfig");function A(e){if(!e)return[];let t=e.profiles?.map(n=>({...n}))??[];return t.some(n=>u.resolve(n.repoPath)===u.resolve(e.repoPath)&&n.profile===e.profile)||t.push({source:"local",repositoryId:u.resolve(e.repoPath),repoPath:u.resolve(e.repoPath),profile:e.profile,...e.lastCheck?{lastCheck:e.lastCheck}:{},...e.lastPush?{lastPush:e.lastPush}:{}}),t}s(A,"profileConfigEntries");var Cn=st(import.meta.url);function On(){return u.join(Oe(),"library","profiles","default-repo")}s(On,"defaultLocalProfileRepoPath");function ut(e=null){return{mode:"none",repoPath:null,activeProfile:null,sourcePath:null,manifestPath:null,agents:[],skills:[],evals:[],git:null,catalog:ue(e),skillCatalog:de(e),actionCatalog:[],sourceSetupRequirements:[],setupGate:fe(),diff:Y(),hosted:null,summary:pe(e),lastCheck:null,error:e}}s(ut,"emptyProfileState");async function qo(e={}){let t=u.resolve(e.repoPath??On()),n=ke(e.profile),o=u.join("profiles",n),r=u.join(t,o),i=e.template??"blank-agent",a=i==="blank-profile";await v(t,{recursive:!0});let l=k(u.join(t,F)),c=await T(t).catch(()=>Tn(n,o));if(a&&l&&c.profiles[n])throw new Error(`Profile "${n}" already exists in ${t}.`);c.defaultProfile=c.defaultProfile||n,c.profiles[n]=kn(c.profiles[n],o),a&&(c.profiles[n].enabledAgents=[]),a?await v(r,{recursive:!0}):await In(r,i,!!e.force),await pt(r),await vn(t,r,n,{includeDefaultAgent:!a}),await Q(t,c),await Me(t);let d=(await O()).openpondProfile;return await L({openpondProfile:ee(d,t,n)}),j()}s(qo,"initLocalProfileRepo");async function jo(e,t,n){let o=u.resolve(e),r=await T(o),i=ke(t??r.defaultProfile);Ce(r,o,i);let a=(await O()).openpondProfile,l=ee(a,o,i);return dt(l,o,i,n),await L({openpondProfile:l}),j()}s(jo,"loadLocalProfileRepo");async function Fo(e,t,n){let o=u.resolve(e),r=await T(o),i=ke(t??r.defaultProfile);Ce(r,o,i);let a=(await O()).openpondProfile,l=ee(a,o,i);return dt(l,o,i,n),a&&(l.repoPath=a.repoPath,l.profile=a.profile,l.lastCheck=a.lastCheck,l.lastPush=a.lastPush),await L({openpondProfile:l}),bn(ye({repoPath:o,profile:i,source:n?.source,repositoryId:n?.repositoryId}))}s(Fo,"registerLocalProfileRepo");function dt(e,t,n,o){o&&(e.profiles=A(e).map(r=>u.resolve(r.repoPath)===t&&r.profile===n?{...r,source:o.source,repositoryId:o.repositoryId}:r))}s(dt,"applyProfileIdentity");async function To(e,t){let n=e.trim(),o=Fn(t);if(!n)throw new Error("Agent ID is required.");let i=(await O()).openpondProfile;if(!i)throw new Error("No active local Profile.");let a=await T(i.repoPath),l=a.profiles[i.profile];if(!l)throw new Error(`Profile "${i.profile}" was not found.`);let c=l.defaultAgent??E;if(!(l.enabledAgents??[c]).includes(n))throw new Error(`Agent "${n}" was not found in Profile "${i.profile}".`);let g={...l.agentNames??{}};return o===n?delete g[n]:g[n]=o,Object.keys(g).length?l.agentNames=g:delete l.agentNames,await Q(i.repoPath,a),j()}s(To,"renameActiveProfileAgent");async function Go(e){let t=e.agentPackage;if(Gn(t),!/^[a-z0-9][a-z0-9._-]{0,190}$/.test(t.agentId))throw new Error("Agent package ID is not safe for a local Profile.");let n=await te(),o=n.state.sourcePath;await pt(o);let r=u.join(o,"agents");await v(r,{recursive:!0});let i=u.join(r,t.agentId),a=k(i);if(a&&e.overwrite!==!0)throw new Error(`Agent "${t.agentId}" already exists. Confirm replacement to install this version.`);let l=u.join(r,`.${t.agentId}.${tt()}.installing`),c=u.join(r,`.${t.agentId}.${tt()}.backup`),d=await T(n.config.repoPath),g=JSON.stringify(d),P=!1,x=!1;try{await Hn(l,t),a&&(await Pe(i,c),P=!0),await Pe(l,i),x=!0;let S=d.profiles[n.config.profile];if(!S)throw new Error(`Profile "${n.config.profile}" was not found.`);let M=new Set(S.enabledAgents??[]);M.add(t.agentId),S.enabledAgents=[...M],S.defaultAgent||(S.defaultAgent=t.agentId),S.agentNames={...S.agentNames??{},[t.agentId]:t.title},await Q(n.config.repoPath,d),P&&await he(c,{recursive:!0,force:!0})}catch(S){throw await he(l,{recursive:!0,force:!0}),x&&await he(i,{recursive:!0,force:!0}),P&&k(c)&&await Pe(c,i),JSON.stringify(d)!==g&&await Q(n.config.repoPath,JSON.parse(g)).catch(()=>{}),S}return{state:await j(),agentId:t.agentId,versionId:t.versionId,digest:t.digest}}s(Go,"installAgentPackageIntoActiveProfile");async function j(){let t=(await O()).openpondProfile;return t?z(t):ut()}s(j,"loadOpenPondProfileState");function ye(e){return{source:e.source??"local",repositoryId:e.repositoryId?.trim()||u.resolve(e.repoPath),profileId:e.profile}}s(ye,"openPondProfileRef");async function Rn(){let e=(await O()).openpondProfile;if(!e)return{lastUsed:null,profiles:[]};let t=A(e),n=await Promise.all(t.map(async o=>{let r=await z({repoPath:o.repoPath,profile:o.profile,mode:"local",...o.lastCheck?{lastCheck:o.lastCheck}:{},...o.lastPush?{lastPush:o.lastPush}:{}});return{ref:ye(o),name:o.profile,repoPath:o.repoPath,sourcePath:r.sourcePath,state:r}}));return{lastUsed:ye({repoPath:e.repoPath,profile:e.profile,source:A(e).find(o=>u.resolve(o.repoPath)===u.resolve(e.repoPath)&&o.profile===e.profile)?.source,repositoryId:A(e).find(o=>u.resolve(o.repoPath)===u.resolve(e.repoPath)&&o.profile===e.profile)?.repositoryId}),profiles:n}}s(Rn,"loadOpenPondProfileLibrary");async function bn(e){if(!e)return j();let t=(await O()).openpondProfile,n=A(t).find(o=>o.source===e.source&&o.repositoryId===e.repositoryId&&o.profile===e.profileId);return n?z({repoPath:n.repoPath,profile:n.profile,mode:"local",...n.lastCheck?{lastCheck:n.lastCheck}:{},...n.lastPush?{lastPush:n.lastPush}:{}}):ut(`Profile "${e.profileId}" is not installed on this device.`)}s(bn,"loadOpenPondProfileStateForRef");async function Ho(e){let t=(await O()).openpondProfile,n=A(t).find(o=>o.source===e.source&&o.repositoryId===e.repositoryId&&o.profile===e.profileId);if(!n)throw new Error(`Profile "${e.profileId}" is not installed on this device.`);return await L({openpondProfile:ee(t,n.repoPath,n.profile)}),j()}s(Ho,"selectOpenPondProfile");async function No(e){let t=(await O()).openpondProfile;if(!t)return{lastUsed:null,profiles:[]};let n=A(t).filter(i=>i.source!==e.source||i.repositoryId!==e.repositoryId||i.profile!==e.profileId);if(n.length===0)return await L({openpondProfile:null}),{lastUsed:null,profiles:[]};let r=u.resolve(t.repoPath)===u.resolve(A(t).find(i=>i.source===e.source&&i.repositoryId===e.repositoryId&&i.profile===e.profileId)?.repoPath??"")&&t.profile===e.profileId?n[0]:n.find(i=>u.resolve(i.repoPath)===u.resolve(t.repoPath)&&i.profile===t.profile)??n[0];return await L({openpondProfile:{repoPath:r.repoPath,profile:r.profile,mode:"local",profiles:n,...r.lastCheck?{lastCheck:r.lastCheck}:{},...r.lastPush?{lastPush:r.lastPush}:{}}}),Rn()}s(No,"removeOpenPondProfile");async function Uo(e,t){return z({mode:"local",repoPath:e,profile:t})}s(Uo,"inspectOpenPondProfileSource");async function z(e){try{let t=await T(e.repoPath),n=Ce(t,e.repoPath,e.profile),o=await xn(t,e.profile),r=mt({manifest:t,profile:e.profile,profileSourcePath:n,agents:o}),[i,a,l,c]=await Promise.all([N(e.repoPath),ze(r),Qe(n),_n(n,r)]),d=ot(e),g=qn(i,e.profile),P=K({actionCatalog:a.actionCatalog,sourceSetupRequirements:a.sourceSetupRequirements}),x=Ln({agents:o,actionCatalog:a.actionCatalog,catalog:a.catalog,diff:g,git:i,hosted:d,lastCheck:e.lastCheck??null,error:null});return{mode:"local",repoPath:e.repoPath,activeProfile:e.profile,sourcePath:n,manifestPath:u.join(e.repoPath,F),agents:o,skills:l.skills,evals:c,git:i,catalog:a.catalog,skillCatalog:l.skillCatalog,actionCatalog:a.actionCatalog,sourceSetupRequirements:a.sourceSetupRequirements,setupGate:P,diff:g,hosted:d,summary:x,lastCheck:e.lastCheck??null,error:null}}catch(t){let n=await N(e.repoPath).catch(()=>null),o=t instanceof Error?t.message:String(t);return{mode:"local",repoPath:e.repoPath,activeProfile:e.profile,sourcePath:null,manifestPath:u.join(e.repoPath,F),agents:[],skills:[],evals:[],git:n,catalog:ue(o),skillCatalog:de(o),actionCatalog:[],sourceSetupRequirements:[],setupGate:fe(),diff:Y(),hosted:ot(e),summary:pe(o),lastCheck:e.lastCheck??null,error:o}}}s(z,"loadOpenPondProfileStateForConfig");async function Do(e){return z({repoPath:u.resolve(e.repoPath),profile:e.profileId,mode:"local"})}s(Do,"loadOpenPondProfileStateFromSource");async function te(){let e=(await O()).openpondProfile;if(!e)throw new Error("No active OpenPond profile. Run `openpond init` or `openpond profile load --path <dir>`.");let t=await j();if(t.error)throw new Error(t.error);if(!t.sourcePath)throw new Error("Active OpenPond profile has no source path.");return{config:e,state:t}}s(te,"requireActiveLocalProfile");async function Bo(e){let t=await te(),n=e.command==="run"?e.args??[]:[],o=e.command==="run"?t.state.actionCatalog.find(l=>l.id===n[0]):null,r=u.resolve(e.cwd??o?.sourcePath??t.state.sourcePath),i=e.command==="run"?nt(r,e.args??[],o?.sourceActionId??null):null;if(e.command==="run"&&i){let l=i[0],c=u.resolve(t.state.sourcePath)===r?{actionCatalog:t.state.actionCatalog,sourceSetupRequirements:t.state.sourceSetupRequirements}:await Be(r);oe(l,K({actionCatalog:c.actionCatalog,sourceSetupRequirements:c.sourceSetupRequirements,actionId:l}))}let a=await ft({command:e.command,args:e.command==="run"?i??nt(r,e.args??[]):e.args,cwd:r,inherit:e.inherit,throwOnFailure:!1});if((e.command==="inspect"||e.command==="build"||e.command==="validate"||e.command==="eval")&&await Se(e.command,a.code),a.code!==0){let l=a.stderr.trim()||a.stdout.trim();throw new Error(l||`${e.command} failed with exit code ${a.code??"unknown"}`)}return a}s(Bo,"runProfileSdkCommand");async function ft(e){let t=u.resolve(e.cwd),n=Un(),o=e.command==="run"?[...n.args,e.command,...e.args??[]]:[...n.args,e.command,"--cwd",t,...e.args??[]],r=await wt(n.command,o,{cwd:t,inherit:e.inherit,timeoutMs:e.timeoutMs,maxOutputBytes:e.maxOutputBytes});if(e.throwOnFailure!==!1&&r.code!==0){let i=St(r,e.command);throw new Error(i||`${e.command} failed with exit code ${r.code??"unknown"}`)}return r}s(ft,"runAgentSdkProjectCommand");function nt(e,t,n=null){let[o,...r]=t;if(!o||o.startsWith("--"))throw new Error("run requires an action name");return[n??o,"--cwd",e,...r]}s(nt,"runCommandArgs");async function zo(e){let t=!e||e==="all"?["inspect","build","validate","eval"]:[e],n=await te(),o=await T(n.config.repoPath),r=mt({manifest:o,profile:n.config.profile,profileSourcePath:n.state.sourcePath,agents:n.state.agents});if(r.length===0){if(t.some(i=>i!=="inspect"&&i!=="build"&&i!=="validate"&&i!=="eval"))throw new Error("check kind must be one of inspect, build, validate, eval, all");await Se("validate",0);return}for(let i of t){if(i!=="inspect"&&i!=="build"&&i!=="validate"&&i!=="eval")throw new Error("check kind must be one of inspect, build, validate, eval, all");for(let a of r)await An({command:i,source:a,profileSourcePath:n.state.sourcePath,sourceCount:r.length})}}s(zo,"runProfileCheck");async function An(e){let t=e.command==="inspect"||e.command==="validate"||e.command==="eval"?["--json"]:[];if(e.sourceCount>1){let o=u.relative(e.profileSourcePath,e.source.sourcePath)||".";console.log(`
|
|
9
9
|
[profile:${e.source.agentId}] ${e.command} ${o}`)}let n=await ft({command:e.command,args:t,cwd:e.source.sourcePath,inherit:!1,throwOnFailure:!1});if(n.stdout.trim()&&console.log(n.stdout.trim()),n.stderr.trim()&&console.error(n.stderr.trim()),await Se(e.command,n.code),n.code!==0){let o=St(n,e.command);throw new Error([`Profile check failed for enabled agent ${e.source.agentId} at ${e.source.sourcePath}.`,o||`${e.command} failed with exit code ${n.code??"unknown"}`].join(`
|
|
10
10
|
`))}}s(An,"runProfileCheckForSource");async function Jo(e){let t=await te();if(!t.state.repoPath)throw new Error("Active OpenPond profile has no repo path.");let n=await $e(t.state.repoPath,e?.trim()||`Update OpenPond profile ${t.state.activeProfile??ct}`);return{committed:n.committed,stdout:n.stdout,stderr:n.stderr,state:await j()}}s(Jo,"commitActiveProfileChanges");async function Wo(e){let t=(await O()).openpondProfile;if(!t)return;let n=A(t).map(o=>u.resolve(o.repoPath)===u.resolve(t.repoPath)&&o.profile===t.profile?{...o,lastPush:e}:o);await L({openpondProfile:{...t,lastPush:e,profiles:n}})}s(Wo,"saveProfilePushStatus");async function Se(e,t){let n=(await O()).openpondProfile;if(!n)return;let o=await qe(n.repoPath).catch(()=>null),r={command:e,status:t===0?"passed":"failed",checkedAt:new Date().toISOString(),exitCode:t,sourceHead:o},i=A(n).map(a=>u.resolve(a.repoPath)===u.resolve(n.repoPath)&&a.profile===n.profile?{...a,lastCheck:r}:a);await L({openpondProfile:{...n,lastCheck:r,profiles:i}})}s(Se,"saveProfileCheckStatus");async function In(e,t,n){if(await v(e,{recursive:!0}),(await lt(e)).length>0&&!n)return;let r=J(),i=u.join(r,"templates",t);if(!k(i))throw new Error(`Unknown agent template "${t}".`);await yn(i,e,{recursive:!0,force:n,errorOnExist:!1}),await En(e,r)}s(In,"ensureProfileSource");async function vn(e,t,n,o={}){if(await v(u.join(e,"profiles"),{recursive:!0}),o.includeDefaultAgent===!1)return;for(let a of["agents","skills","workflows","actions","extensions","prompts","goals","evals","settings","traces"])await v(u.join(t,a),{recursive:!0});let r=u.join(t,Sn);k(r)||await D(r,["schema: openpond.profile.v1",`profile: ${n}`,"agents:",` - id: ${E}`," path: agent/agent.ts"," enabled: true",""].join(`
|
|
11
11
|
`),"utf8");let i=u.join(t,"openpond.lock");k(i)||await D(i,`# OpenPond profile lockfile placeholder
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{
|
|
2
|
+
import{b as ie,c as se,d as ce}from"./chunk-JDLAHVAJ.js";import{h as X,k as Z}from"./chunk-EAPFMACH.js";import{a as I}from"./chunk-6FA3GG5B.js";import{n as V,o as G,u as J}from"./chunk-N3DEA6PG.js";import{c as o,d as H,e as l,f as K,h as ae,i as w}from"./chunk-3M53YXEI.js";import{a as i}from"./chunk-FTQLQJQV.js";import{existsSync as j,readFileSync as _e}from"node:fs";import{createRequire as Ie}from"node:module";import b from"node:path";function de(e){let n=b.join(e,"node_modules","openpond-agent-sdk","dist","cli.js");if(j(n))return{command:process.execPath,args:[n]};let t=b.join(e,"node_modules",".bin","openpond-agent");if(j(t))return{command:t,args:[]};let r=b.join(e,"node_modules","openpond-agent-sdk","src","cli.ts");if(j(r))return ue(b.dirname(b.dirname(r)),r);let a=De(e);return a||{command:"openpond-agent",args:[]}}i(de,"resolveLocalAgentSdkCommand");function De(e){let n=b.join(e,"package.json");if(!j(n))return null;try{let t=JSON.parse(_e(n,"utf8")),r=t.dependencies?.["openpond-agent-sdk"]??t.devDependencies?.["openpond-agent-sdk"]??t.peerDependencies?.["openpond-agent-sdk"];if(!r?.startsWith("file:"))return null;let a=b.resolve(e,r.slice(5)),d=b.join(a,"src","cli.ts");if(j(d))return ue(a,d);let s=b.join(a,"dist","cli.js");if(j(s))return{command:process.execPath,args:[s]}}catch{return null}return null}i(De,"resolveAgentSdkDependencyCli");function ue(e,n){let t=Ie(b.join(e,"package.json")).resolve("tsx/cli");return{command:process.execPath,args:[t,n]}}i(ue,"nodeTypescriptCommand");import{Buffer as A}from"node:buffer";import{existsSync as U,promises as P}from"node:fs";import m from"node:path";import{createHash as Te}from"node:crypto";import{existsSync as T,promises as M,readFileSync as ye,statSync as Me}from"node:fs";import{tmpdir as $e}from"node:os";import y from"node:path";import{gunzipSync as ze}from"node:zlib";import{existsSync as C}from"node:fs";import v from"node:path";function L(e,n){let t=n.packageManager;if(typeof t=="string"){let r=t.split("@")[0];if(r==="bun"||r==="npm"||r==="pnpm"||r==="yarn")return r}return C(v.join(e,"bun.lock"))||C(v.join(e,"bun.lockb"))?"bun":C(v.join(e,"pnpm-lock.yaml"))?"pnpm":C(v.join(e,"yarn.lock"))?"yarn":C(v.join(e,"package-lock.json"))||C(v.join(e,"npm-shrinkwrap.json"))?"npm":"unknown"}i(L,"detectAgentSdkPackageManager");function le(e){return e==="npm"?"npm install --offline":e==="pnpm"?"pnpm install --offline":e==="yarn"?"yarn install --offline":e==="bun"?"bun install --offline":"pnpm install --offline"}i(le,"agentSdkDependencyInstallCommand");function pe(e,n){return e==="pnpm"?`pnpm run ${n}`:e==="yarn"?`yarn ${n}`:e==="npm"?`npm run ${n}`:e==="bun"?`bun run ${n}`:`pnpm run ${n}`}i(pe,"agentSdkRunScriptCommand");function ge(e,n){return e==="pnpm"?`pnpm --silent run ${n}`:e==="yarn"?`yarn --silent ${n}`:e==="npm"?`npm run --silent ${n}`:e==="bun"?`bun run --silent ${n}`:`pnpm --silent run ${n}`}i(ge,"agentSdkRunJsonScriptCommand");var ke=".openpond/vendor/openpond-agent-sdk.tgz",Ue=".openpond/vendor/npm",Ne=`file:${ke}`,fe="# openpond-agent-sdk-source-upload: synthesized-openpond-yaml";async function ne(e,n,t={}){return J(e,n,{cwd:t.cwd})}i(ne,"runCommand");function Je(e){for(let n of["dependencies","devDependencies","peerDependencies"]){let t=e[n];if(!t||typeof t!="object"||Array.isArray(t))continue;let r=t["openpond-agent-sdk"];if(typeof r=="string"&&r.trim())return r.trim()}return null}i(Je,"readOpenPondAgentSdkVersionSpec");async function he(e,n){let t=Ke(e,n);if(!t)return null;let r=await M.mkdtemp(y.join($e(),"openpond-agent-sdk-pack-"));try{let a=t.kind==="package_root"?await Le(t.packageRoot,r):t.kind==="registry"?await He(t.versionSpec,r):t.tarballContents,d=await Fe({sdkPackageJson:t.packageJson,dependencyBaseDir:t.dependencyBaseDir,projectPackageJson:n,projectPath:e,tempDir:r}),s=L(e,n),c=Xe(n,d,s),u=s==="pnpm"||s==="unknown"?Ze(e,d):null,p=le(s),f={packageName:"openpond-agent-sdk",source:"uploaded_tarball",path:ke,sha256:O(a),sizeBytes:a.byteLength};return{rewrittenPackageJson:c,pnpmWorkspaceSource:u,tarballs:[{...f,contents:a},...d],dependencySetup:{required:!0,packageManager:s,installCommand:p,commands:[p],packageJsonPath:"package.json",expectedBinaryPath:"node_modules/.bin/openpond-agent",generatedArtifactDirectory:".openpond",sdkPackage:f,dependencyPackages:d.map(g=>({packageName:g.packageName,source:g.source,versionSpec:g.versionSpec,path:g.path,sha256:g.sha256,sizeBytes:g.sizeBytes}))}}}finally{await M.rm(r,{recursive:!0,force:!0})}}i(he,"buildAgentSdkMaterializedDependency");async function Le(e,n){let t=await ne("npm",["pack","--silent","--pack-destination",n,e],{cwd:e});if(t.code!==0){let a=[t.stderr.trim(),t.stdout.trim()].filter(Boolean).join(`
|
|
3
3
|
`);throw new Error(`failed to pack openpond-agent-sdk for source upload${a?`:
|
|
4
4
|
${a}`:""}`)}let r=t.stdout.trim().split(/\r?\n/).filter(Boolean).pop();if(!r)throw new Error("failed to pack openpond-agent-sdk for source upload: npm pack did not return a tarball name");return M.readFile(y.join(n,r))}i(Le,"packOpenPondAgentSdkPackageRoot");async function Fe(e){let n=D(e.sdkPackageJson.dependencies),t=D(e.projectPackageJson.dependencies),r=D(e.projectPackageJson.devDependencies);delete t["openpond-agent-sdk"],delete r["openpond-agent-sdk"];let a=[...Object.entries(n).map(([c,u])=>({packageName:c,versionSpec:u,dependencyBaseDir:e.dependencyBaseDir})),...Object.entries(t).map(([c,u])=>({packageName:c,versionSpec:u,dependencyBaseDir:e.projectPath})),...Object.entries(r).map(([c,u])=>({packageName:c,versionSpec:u,dependencyBaseDir:e.projectPath}))].sort((c,u)=>c.packageName.localeCompare(u.packageName)),d=new Set,s=[];for(;a.length>0;){let{packageName:c,versionSpec:u,dependencyBaseDir:p}=a.shift();if(d.has(c))continue;d.add(c);let f=We({packageName:c,versionSpec:u,dependencyBaseDir:p}),g=await ne("npm",["pack","--silent","--pack-destination",e.tempDir,f],{cwd:p});if(g.code!==0){let h=[g.stderr.trim(),g.stdout.trim()].filter(Boolean).join(`
|
|
5
5
|
`);throw new Error(`failed to pack openpond-agent-sdk dependency ${c}${h?`:
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
+
import{b as i}from"./chunk-ES2ISFJC.js";import{a as o}from"./chunk-FTQLQJQV.js";var E=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),j=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),A=class r{static{o(this,"Sha256State")}state=new Uint32Array(E);pending=new Uint8Array(64);pendingLength=0;byteLength=0;words=new Uint32Array(64);update(t){let n=typeof t=="string"?new TextEncoder().encode(t):t;if(!Number.isSafeInteger(this.byteLength+n.length))throw new RangeError("SHA-256 input is too large");this.byteLength+=n.length;let e=0;if(this.pendingLength){let a=Math.min(64-this.pendingLength,n.length);this.pending.set(n.subarray(0,a),this.pendingLength),this.pendingLength+=a,e+=a,this.pendingLength===64&&(this.compress(this.pending),this.pendingLength=0)}for(;e+64<=n.length;)this.compress(n.subarray(e,e+64)),e+=64;return e<n.length&&(this.pending.set(n.subarray(e)),this.pendingLength=n.length-e),this}clone(){let t=new r;return t.state.set(this.state),t.pending.set(this.pending),t.pendingLength=this.pendingLength,t.byteLength=this.byteLength,t}digestHex(){let t=this.clone(),n=new Uint8Array(t.pendingLength<56?64:128);n.set(t.pending.subarray(0,t.pendingLength)),n[t.pendingLength]=128;let e=t.byteLength*8,a=new DataView(n.buffer);return a.setUint32(n.length-8,Math.floor(e/4294967296),!1),a.setUint32(n.length-4,e>>>0,!1),t.compress(n.subarray(0,64)),n.length===128&&t.compress(n.subarray(64)),Array.from(t.state,c=>c.toString(16).padStart(8,"0")).join("")}compress(t){let n=new DataView(t.buffer,t.byteOffset,64),e=this.state,a=this.words;for(let s=0;s<16;s+=1)a[s]=n.getUint32(s*4,!1);for(let s=16;s<64;s+=1){let p=a[s-15],g=a[s-2],S=x(p,7)^x(p,18)^p>>>3,L=x(g,17)^x(g,19)^g>>>10;a[s]=a[s-16]+S+a[s-7]+L>>>0}let c=e[0],h=e[1],m=e[2],y=e[3],f=e[4],b=e[5],u=e[6],w=e[7];for(let s=0;s<64;s+=1){let p=f&b^~f&u,g=c&h^c&m^h&m,S=x(c,2)^x(c,13)^x(c,22),L=x(f,6)^x(f,11)^x(f,25),H=w+L+p+j[s]+a[s]>>>0,I=S+g>>>0;w=u,u=b,b=f,f=y+H>>>0,y=m,m=h,h=c,c=H+I>>>0}e[0]=e[0]+c>>>0,e[1]=e[1]+h>>>0,e[2]=e[2]+m>>>0,e[3]=e[3]+y>>>0,e[4]=e[4]+f>>>0,e[5]=e[5]+b>>>0,e[6]=e[6]+u>>>0,e[7]=e[7]+w>>>0}};function _(r){return new A().update(r).digestHex()}o(_,"sha256Hex");function x(r,t){return r>>>t|r<<32-t}o(x,"rotateRight");var U=2e3,T=25e7,l=i.string().trim().min(1).max(240),d=i.string().regex(/^[a-f0-9]{64}$/),k=i.string().datetime({offset:!0}),J=i.record(i.string(),i.unknown()).default({}),O=i.object({id:l,contentHash:d}).strict(),X=O.extend({revision:i.number().int().positive()}).strict(),Y=i.object({id:l,path:i.string().trim().min(1).max(U).refine(B),contentHash:d,sizeBytes:i.number().int().nonnegative().max(T),mediaType:i.string().trim().min(1).max(200),visibility:i.enum(["policy","verifier","host_private"])}).strict(),q=i.object({id:l,contentHash:d,mediaType:i.string().trim().min(1).max(200).nullable().default(null),sizeBytes:i.number().int().nonnegative().max(T).nullable().default(null)}).strict(),F=i.enum(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function v(r){return`${JSON.stringify(R(r),null,2)}
|
|
3
|
+
`}o(v,"canonicalJson");function z(r){return _(r)}o(z,"sha256");function M(r){return z(v(r))}o(M,"contentHash");function W(r,t){let{contentHash:n,...e}=r,a=M(e);if(n!==a)throw new Error(`${t} contentHash is ${n}; expected ${a}.`)}o(W,"assertContentHash");function B(r){let t=r.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}o(B,"safeRelativePath");function R(r){return Array.isArray(r)?r.map(R):!r||typeof r!="object"?r:Object.fromEntries(Object.entries(r).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,R(n)]))}o(R,"sortValue");var ee=i.object({provider:l,model:l,revision:i.string().trim().min(1).max(500).nullable().default(null),artifactHash:d.nullable().default(null),tokenizerRevision:i.string().trim().min(1).max(500).nullable().default(null),chatTemplateHash:d.nullable().default(null)}).strict(),C=["openpond","codex","claude-code","grok-build","opencode","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],N=i.enum(C),te=i.object({providerId:N,modelId:i.string().trim().min(1).max(300)});export{A as a,l as b,d as c,k as d,J as e,O as f,X as g,Y as h,q as i,F as j,v as k,z as l,M as m,W as n,ee as o,C as p,N as q,te as r};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
+
import{i}from"./chunk-R3XFY7VL.js";import{a as s}from"./chunk-GLUWATL5.js";import{a as n}from"./chunk-FTQLQJQV.js";import{stdin as a,stdout as c}from"node:process";import{createInterface as l}from"node:readline/promises";var p=`${s}/console/services/identity-access/api-keys`;function u(e){let t=process.env.OPENPOND_API_KEY?.trim();if(t)return t;let r=e.apiKey?.trim();if(r)return r;let o=e.token?.trim();return o&&o.startsWith("opk_")?o:null}n(u,"resolveApiKey");async function P(){if(!a.isTTY||!c.isTTY)throw new Error("OpenPond API key is required in non-interactive mode. Set OPENPOND_API_KEY or run `openpond login` in a terminal.");console.log("Open the OpenPond UI to create an API key:"),console.log(p);let e=l({input:a,output:c});try{let t=(await e.question("Paste your OpenPond API key: ")).trim();if(!t)throw new Error("API key is required");return t.startsWith("opk_")||console.log("warning: API keys usually start with opk_."),t}finally{e.close()}}n(P,"promptForApiKey");async function A(e,t){let r=u(e);if(r)return r;let o=await P();return await i({apiKey:o,baseUrl:t,activeProfile:e.activeProfile}),console.log("Saved account credentials to the encrypted OpenPond credential store."),o}n(A,"ensureApiKey");export{u as a,P as b,A as c};
|