openpond 0.2.37 → 0.2.38
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/dist/app-server.js +1 -1
- package/dist/chunks/actions-command-MHWHPQ66.js +2 -0
- package/dist/chunks/{app-layer-BDAKS3DG.js → app-layer-JZTMHORT.js} +1 -1
- package/dist/chunks/app-server-runtime-PDT6BJD2.js +2 -0
- package/dist/chunks/apps-U5GIOD6W.js +2 -0
- package/dist/chunks/{chunk-DXOOJFFU.js → chunk-25OT6IYM.js} +2 -2
- package/dist/chunks/chunk-3HQEEZPO.js +2 -0
- package/dist/chunks/{chunk-YQPECTJ2.js → chunk-562Q5UVS.js} +2 -2
- package/dist/chunks/chunk-7BGT6Q2D.js +8 -0
- package/dist/chunks/{chunk-6EAQL7YX.js → chunk-AOBTILU5.js} +1 -1
- package/dist/chunks/{chunk-3YA2CD22.js → chunk-DDHUSA3I.js} +1 -1
- package/dist/chunks/{chunk-XLVFY2BA.js → chunk-FKVP26MC.js} +1 -1
- package/dist/chunks/{chunk-5YUITAUN.js → chunk-FUFIZ37W.js} +2 -2
- package/dist/chunks/chunk-GIPSOLAY.js +2 -0
- package/dist/chunks/{chunk-I6DQSOSF.js → chunk-GKRTXVNT.js} +1 -1
- package/dist/chunks/{chunk-SL7XLTIT.js → chunk-GOHJHZVA.js} +204 -204
- package/dist/chunks/{chunk-3I5BMVJI.js → chunk-IKM6ICPY.js} +1 -1
- package/dist/chunks/{chunk-4R4KM6LL.js → chunk-J4S7AVGF.js} +1 -1
- package/dist/chunks/chunk-JUX77H6K.js +13 -0
- package/dist/chunks/chunk-KNEMKYHY.js +2 -0
- package/dist/chunks/chunk-MRGA6BKG.js +19 -0
- package/dist/chunks/{chunk-FQOVC2GR.js → chunk-OCWH4BV7.js} +135 -141
- package/dist/chunks/chunk-P5CFBE6Z.js +3 -0
- package/dist/chunks/chunk-Q3X5WOVH.js +4 -0
- package/dist/chunks/{chunk-L6NNQUAT.js → chunk-QK2GLRCY.js} +1 -1
- package/dist/chunks/chunk-RELOOVWW.js +2 -0
- package/dist/chunks/chunk-SBBXUZWL.js +5 -0
- package/dist/chunks/{chunk-UJLZRM2M.js → chunk-SHCKK3SU.js} +1 -1
- package/dist/chunks/chunk-SHCRE7B2.js +2 -0
- package/dist/chunks/{chunk-3N4GQL6I.js → chunk-T7Y5OYO2.js} +1 -1
- package/dist/chunks/chunk-TZNKOKQJ.js +5 -0
- package/dist/chunks/{chunk-Z3RBK6LN.js → chunk-V5BC6QT2.js} +1 -1
- package/dist/chunks/{chunk-DG4DIFF4.js → chunk-WCZRDULE.js} +7 -7
- package/dist/chunks/chunk-XHJUP7M4.js +23 -0
- package/dist/chunks/{chunk-OO7JG7KM.js → chunk-ZCDOE3EO.js} +3 -3
- package/dist/chunks/{chunk-S4RSY6CR.js → chunk-ZCFX6HQO.js} +1 -1
- package/dist/chunks/{chunk-KCFVJDIV.js → chunk-ZPGTGQJT.js} +1 -1
- package/dist/chunks/cli-OP4EDGZN.js +2 -0
- package/dist/chunks/{configuration-command-URDRLDNY.js → configuration-command-RPNYWBKK.js} +1 -1
- package/dist/chunks/{continual-6EW2SLGL.js → continual-MHMPLLUZ.js} +3 -3
- package/dist/chunks/core-commands-WFTASSGL.js +2 -0
- package/dist/chunks/datasets-V7E4I5N3.js +13 -0
- package/dist/chunks/desktop-test-NZAZVXLK.js +3 -0
- package/dist/chunks/dist-4OUZANXR.js +2 -0
- package/dist/chunks/experiments-7UBJCQAQ.js +2 -0
- package/dist/chunks/{extension-DG2XISC6.js → extension-OQ7CFD4Q.js} +1 -1
- package/dist/chunks/{help-ZLJV3ZVW.js → help-4BB2A5JC.js} +1 -1
- package/dist/chunks/hosted-harness-runtime-6TE37GBH.js +2 -0
- package/dist/chunks/hosted-profile-compiler-7ZWCIHPA.js +3 -0
- package/dist/chunks/opchat-QVB4UIZR.js +3 -0
- package/dist/chunks/organizations-MUKXB6MX.js +2 -0
- package/dist/chunks/{profile-LMRN5QMQ.js → profile-LZYR4CMX.js} +1 -1
- package/dist/chunks/project-agent-FHNWIH2D.js +2 -0
- package/dist/chunks/sandbox-command-GJN3HSJQ.js +2 -0
- package/dist/chunks/{sandbox-template-LN5OQ55F.js → sandbox-template-6RLQYNTY.js} +1 -1
- package/dist/chunks/{src-LRJO4THC.js → src-2NVS6PNZ.js} +112 -112
- package/dist/chunks/{src-A5KEQW52.js → src-PASASTIA.js} +5 -5
- package/dist/chunks/{taskset-YPKY3HUM.js → taskset-BZYQT65N.js} +1 -1
- package/dist/chunks/{teams-bot-RY5M6AOW.js → teams-bot-UQB636V3.js} +1 -1
- package/dist/chunks/training-7PST5HZU.js +1 -1
- package/dist/chunks/{workspaces-KZ6ZJXXY.js → workspaces-2KYAFRX4.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/web/assets/{App-BRZg56AC.js → App-BL1D_PLh.js} +9 -9
- package/dist/web/assets/{AppDialog-BR9UjEFe.js → AppDialog-CmPsGOzE.js} +1 -1
- package/dist/web/assets/{AppTerminalPanel-DNXVV6S_.js → AppTerminalPanel-0_Ewf4wJ.js} +2 -2
- package/dist/web/assets/{AppsView-DhaB7uT7.js → AppsView-Ddn9R2I-.js} +1 -1
- package/dist/web/assets/{BrowserSidebar-zecj1P2T.js → BrowserSidebar-j2Yyiaz-.js} +1 -1
- package/dist/web/assets/{CartesianChart-DRhWC0XA.js → CartesianChart-BWAkc0mY.js} +1 -1
- package/dist/web/assets/{CollaborationTabs-BzNNwOcD.js → CollaborationTabs-SVc7oX8N.js} +1 -1
- package/dist/web/assets/{CommandMenu-C7HuXmgN.js → CommandMenu-CcX5ypdX.js} +1 -1
- package/dist/web/assets/{CommunityView-C4HfU5ky.js → CommunityView-B7W1C8KG.js} +1 -1
- package/dist/web/assets/{ComposerCreateImproveStrip-CG8YZxWB.js → ComposerCreateImproveStrip-BBKdrbNP.js} +1 -1
- package/dist/web/assets/{GetStartedView-ZxtcgU5X.js → GetStartedView-BXuTBT4U.js} +1 -1
- package/dist/web/assets/HostedModelLearningReview-C3oAdyoF.js +1 -0
- package/dist/web/assets/{HostedModelLearningSettings-BKM_1-LZ.js → HostedModelLearningSettings-9e5z5eRf.js} +1 -1
- package/dist/web/assets/{LabModelVersionDetailPage-CklKwV_e.js → LabModelVersionDetailPage-CctGBUae.js} +1 -1
- package/dist/web/assets/{LabSkillSidebar-Cq_axOXr.js → LabSkillSidebar-Cl8Sdiqc.js} +1 -1
- package/dist/web/assets/{LabsRoute-BPGkQnKq.js → LabsRoute-di9O0XV1.js} +4 -4
- package/dist/web/assets/{MainChatThread-DvllW6Ej.js → MainChatThread-BaEeNsrh.js} +2 -2
- package/dist/web/assets/{MainPane-BaUIvio6.js → MainPane-Dw90VsN-.js} +4 -4
- package/dist/web/assets/{MarkdownText-DP7Hjp4L.js → MarkdownText-CGGUFrZe.js} +1 -1
- package/dist/web/assets/{NativeSkillSidebar-BSSKKH-y.js → NativeSkillSidebar-2mgh6WV4.js} +1 -1
- package/dist/web/assets/{NewExperienceSwitcher-cWw4m_pU.js → NewExperienceSwitcher-DMTe3jS9.js} +1 -1
- package/dist/web/assets/{NewProjectDialog-BMzXEHsC.js → NewProjectDialog-D6pvuCoo.js} +1 -1
- package/dist/web/assets/{OutputsPage-CGWtgJ_j.js → OutputsPage-DMeIKxzN.js} +1 -1
- package/dist/web/assets/{ProjectsPage-C00Wt3oR.js → ProjectsPage-V5oXwB-5.js} +1 -1
- package/dist/web/assets/{RightChatPanelStack-0D_jpeAm.js → RightChatPanelStack-B0y2XNdm.js} +1 -1
- package/dist/web/assets/{RightSidebarHomePanel-BgHpI97K.js → RightSidebarHomePanel-BksZR71F.js} +1 -1
- package/dist/web/assets/{ScheduledWorkPage-C-P_Jv04.js → ScheduledWorkPage-BRcVebWV.js} +1 -1
- package/dist/web/assets/{SettingsView-BJDvzvtZ.js → SettingsView-CtI170q1.js} +3 -3
- package/dist/web/assets/{TeamChatView-BdUQNXvx.js → TeamChatView-DWGM8eXj.js} +1 -1
- package/dist/web/assets/{TerminalOverlay-85H1eqcg.js → TerminalOverlay-DLSmAkbQ.js} +1 -1
- package/dist/web/assets/{TrainingCreationPanel-Bdx2BJzb.js → TrainingCreationPanel-C6e6zhC8.js} +1 -1
- package/dist/web/assets/{TrainingDraftPanel-TcvqZfYS.js → TrainingDraftPanel-Q1GXOAlQ.js} +1 -1
- package/dist/web/assets/{UsageSettingsSection-Dm8bsNIT.js → UsageSettingsSection-UET2vS1c.js} +1 -1
- package/dist/web/assets/{WorkSidebarPanel-C9bKi4NH.js → WorkSidebarPanel-DMsXId2s.js} +1 -1
- package/dist/web/assets/{WorkspaceDiffPanel-CFzHklbv.js → WorkspaceDiffPanel-B_eZE-bq.js} +3 -3
- package/dist/web/assets/{WorkspaceEnvironmentMenu-_e6IkhGw.js → WorkspaceEnvironmentMenu-C848cDBP.js} +1 -1
- package/dist/web/assets/{WorkspaceGitDialogs-BglcR8S9.js → WorkspaceGitDialogs-CSnIC26s.js} +1 -1
- package/dist/web/assets/{WorkspaceMonacoEditor-BuipCT-i.js → WorkspaceMonacoEditor-C5dvv9s_.js} +3 -3
- package/dist/web/assets/{arrow-up-right-jN0p0koy.js → arrow-up-right-CsvQameJ.js} +1 -1
- package/dist/web/assets/{clipboard-Bat4as9H.js → clipboard-fZsv7_ot.js} +1 -1
- package/dist/web/assets/{cloud-upload-CFs0F_2n.js → cloud-upload-CUXNsLn2.js} +1 -1
- package/dist/web/assets/{cssMode-Cg4Jey3B.js → cssMode-1tbsSShK.js} +1 -1
- package/dist/web/assets/{folder-open-BqInWH_9.js → folder-open-Da8t5AtB.js} +1 -1
- package/dist/web/assets/{folder-plus-BSA6I7ld.js → folder-plus-X7B8dzc3.js} +1 -1
- package/dist/web/assets/{git-commit-horizontal-CLDqrpDQ.js → git-commit-horizontal-CajQIfK5.js} +1 -1
- package/dist/web/assets/{htmlMode-DHHN3vwk.js → htmlMode-qapgENKW.js} +1 -1
- package/dist/web/assets/{index-VtbQYCWA.js → index-DUQK09vA.js} +2 -2
- package/dist/web/assets/{info-BSebzpyp.js → info-BYfs9_PT.js} +1 -1
- package/dist/web/assets/{jsonMode-mvqMGlEK.js → jsonMode-DYPkWxLK.js} +1 -1
- package/dist/web/assets/{lspLanguageFeatures-Bw_QMGcP.js → lspLanguageFeatures-Cbcp__rz.js} +1 -1
- package/dist/web/assets/{minimize-2-CaHjbHpF.js → minimize-2-Dp7tWjno.js} +1 -1
- package/dist/web/assets/{monaco.contribution-DubQum0F.js → monaco.contribution-COP3_DCK.js} +2 -2
- package/dist/web/assets/{monaco.contribution-KrPDFXc4.js → monaco.contribution-CcL6YtdZ.js} +2 -2
- package/dist/web/assets/{monaco.contribution-CBkwYqsg.js → monaco.contribution-DApKEq_e.js} +2 -2
- package/dist/web/assets/{monaco.contribution-CiXEi4Ka.js → monaco.contribution-cIq6c5M4.js} +2 -2
- package/dist/web/assets/{monitor-DwOfVMY6.js → monitor-nP1D5S_1.js} +1 -1
- package/dist/web/assets/{python-BPnA89YS.js → python-DXYfRGSs.js} +1 -1
- package/dist/web/assets/{refresh-cw-DO-hUyTn.js → refresh-cw-D_9Q01ox.js} +1 -1
- package/dist/web/assets/{save-C7WFI7Mn.js → save-BxG7d5Nm.js} +1 -1
- package/dist/web/assets/{square-DiLQ59tw.js → square--Ua9DQPL.js} +1 -1
- package/dist/web/assets/{toggleHighContrast-BWFPIQBM.js → toggleHighContrast-CqAtkn5E.js} +1 -1
- package/dist/web/assets/{tsMode-CWxqU0x6.js → tsMode-BCdfa4wT.js} +1 -1
- package/dist/web/assets/{upload-vUnuWYGk.js → upload-BkYSJcbc.js} +1 -1
- package/dist/web/assets/{useLocalAgentSchedules-BFbGmflA.js → useLocalAgentSchedules-CGlPbPZr.js} +1 -1
- package/dist/web/assets/{useSessionTurnCache-C0zgYrCB.js → useSessionTurnCache-DtNQyWXl.js} +1 -1
- package/dist/web/assets/{wifi-off-DbNO6u3Z.js → wifi-off-DF8YmlRa.js} +1 -1
- package/dist/web/assets/{workers-4I09fePv.js → workers-BUHY0ojx.js} +1 -1
- package/dist/web/assets/{yaml-DpHYonDY.js → yaml-CtBzXx8s.js} +1 -1
- package/dist/web/index.html +1 -1
- package/docs/command-reference.md +35 -0
- package/package.json +3 -1
- package/dist/chunks/actions-command-GNQREIDD.js +0 -2
- package/dist/chunks/app-server-runtime-D74FFS27.js +0 -2
- package/dist/chunks/apps-2SUP5JZE.js +0 -2
- package/dist/chunks/chunk-2O5UZOYL.js +0 -13
- package/dist/chunks/chunk-3LG4G5JR.js +0 -3
- package/dist/chunks/chunk-BLXEK5F7.js +0 -26
- package/dist/chunks/chunk-DAOLQUAK.js +0 -19
- package/dist/chunks/chunk-EIB7GHIQ.js +0 -4
- package/dist/chunks/chunk-FFEI7IRU.js +0 -2
- package/dist/chunks/chunk-FOW3LI6G.js +0 -2
- package/dist/chunks/chunk-IYROEHYB.js +0 -2
- package/dist/chunks/chunk-TZ6N7WFI.js +0 -5
- package/dist/chunks/chunk-XISNUB62.js +0 -2
- package/dist/chunks/cli-A2P56J7R.js +0 -2
- package/dist/chunks/core-commands-CMAAUKPQ.js +0 -2
- package/dist/chunks/desktop-test-5PKGG6H6.js +0 -3
- package/dist/chunks/dist-CEKBK32A.js +0 -2
- package/dist/chunks/hosted-harness-runtime-ABEMAABI.js +0 -2
- package/dist/chunks/hosted-profile-compiler-CSLJT75T.js +0 -3
- package/dist/chunks/opchat-IMGIFM4W.js +0 -3
- package/dist/chunks/organizations-G3UOHURO.js +0 -2
- package/dist/chunks/project-agent-DTAVYEB6.js +0 -2
- package/dist/chunks/sandbox-command-YO6RR5SD.js +0 -2
- package/dist/web/assets/HostedModelLearningReview-BhGIhvoc.js +0 -1
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
+
import{a as Et,b as Pe}from"./chunk-L3KS6MOV.js";import{x as bt}from"./chunk-MRGA6BKG.js";import{b as j,d as ye,e as we}from"./chunk-MJC26GOX.js";import{$ as ge,Ja as Ct,Ka as vt,Ua as De,ya as Ne,za as je}from"./chunk-QK2GLRCY.js";import{f as L,h as me,p as Le,r as It}from"./chunk-H7IWJN7L.js";import{a}from"./chunk-FTQLQJQV.js";import{createRequire as Po}from"node:module";import{createHash as po,randomUUID as ho}from"node:crypto";import{spawn as Pr}from"node:child_process";import{existsSync as U}from"node:fs";import{cp as Sr,mkdir as F,readFile as So,readdir as Ao,rename as at,rm as it,symlink as Ar,writeFile as ie}from"node:fs/promises";import d from"node:path";import Sn from"node:path";var Se="default",Rt=["apiKey","baseUrl","apiBaseUrl","chatApiBaseUrl","token","appId","conversationId"];function W(e,t){return Object.prototype.hasOwnProperty.call(e,t)}a(W,"hasOwn");function z(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}a(z,"normalizeHandle");function _(e){if(typeof e!="string")return null;let t=e.trim();return t?t.replace(/\/$/,""):null}a(_,"normalizeBaseUrl");function Bt(e){let t=z(e);if(!t)throw new Error("profile handle must be non-empty");return t}a(Bt,"requireHandle");function An(e){if(typeof e!="string")throw new Error("apiKey must be a non-empty string");let t=e.trim();if(!t)throw new Error("apiKey must be a non-empty string");return t}a(An,"requireApiKey");function de(e,t){let o=z(e),n=z(t);return!!(o&&n&&o.toLowerCase()===n.toLowerCase())}a(de,"handleEquals");function qe(e,t,o){let n=_(o);return e.findIndex(r=>de(r.handle,t)?n?_(r.baseUrl)===n:!0:!1)}a(qe,"findAccountIndex");function ne(e){let t=z(e.handle)??Se,o=_(e.baseUrl);return o?{handle:t,baseUrl:o}:{handle:t}}a(ne,"selectorFromAccount");function oe(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,o=z(typeof t.handle=="string"?t.handle:void 0);if(!o)return null;let n=_(typeof t.baseUrl=="string"?t.baseUrl:void 0);return n?{handle:o,baseUrl:n}:{handle:o}}a(oe,"sanitizeActiveProfile");function Fe(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,o=typeof t.repoPath=="string"?t.repoPath.trim():"",n=typeof t.profile=="string"&&t.profile.trim()?t.profile.trim():"default";if(!o)return;let r={repoPath:o,profile:n,mode:"local"};if(t.lastCheck&&typeof t.lastCheck=="object"&&!Array.isArray(t.lastCheck)){let s=t.lastCheck,i=s.command,c=s.status,l=s.checkedAt;(i==="inspect"||i==="build"||i==="validate"||i==="eval"||i==="run")&&(c==="passed"||c==="failed")&&typeof l=="string"&&(r.lastCheck={command:i,status:c,checkedAt:l,...typeof s.exitCode=="number"||s.exitCode===null?{exitCode:s.exitCode}:{},...typeof s.sourceHead=="string"||s.sourceHead===null?{sourceHead:s.sourceHead}:{}})}if(t.lastPush&&typeof t.lastPush=="object"&&!Array.isArray(t.lastPush)){let s=t.lastPush,i=s.status,c=s.pushedAt;(i==="pushed"||i==="failed")&&typeof c=="string"&&(r.lastPush={status:i,pushedAt:c,...typeof s.teamId=="string"||s.teamId===null?{teamId:s.teamId}:{},...typeof s.projectId=="string"||s.projectId===null?{projectId:s.projectId}:{},...typeof s.localHead=="string"||s.localHead===null?{localHead:s.localHead}:{},...typeof s.hostedHead=="string"||s.hostedHead===null?{hostedHead:s.hostedHead}:{},...typeof s.sourceRef=="string"||s.sourceRef===null?{sourceRef:s.sourceRef}:{},...s.promotionStatus==="uploaded"||s.promotionStatus==="hosted_source_materialized"||s.promotionStatus==="hosted_source_materialize_failed"||s.promotionStatus==="hosted_source_check_pending"||s.promotionStatus==="hosted_source_check_failed"||s.promotionStatus==="hosted_source_published"||s.promotionStatus==="hosted_source_publish_failed"||s.promotionStatus==="hosted_run_pending"||s.promotionStatus==="hosted_run_passed"||s.promotionStatus==="hosted_run_failed"||s.promotionStatus===null?{promotionStatus:s.promotionStatus}:{},...s.hostedRunStatus==="not_started"||s.hostedRunStatus==="running"||s.hostedRunStatus==="passed"||s.hostedRunStatus==="failed"||s.hostedRunStatus===null?{hostedRunStatus:s.hostedRunStatus}:{},...typeof s.hostedRunAgentId=="string"||s.hostedRunAgentId===null?{hostedRunAgentId:s.hostedRunAgentId}:{},...typeof s.hostedRunId=="string"||s.hostedRunId===null?{hostedRunId:s.hostedRunId}:{},...typeof s.hostedRunAt=="string"||s.hostedRunAt===null?{hostedRunAt:s.hostedRunAt}:{},..._t(s.hostedSourceMaterialization)?{hostedSourceMaterialization:_t(s.hostedSourceMaterialization)}:{},...$t(s.hostedSourceCheck)?{hostedSourceCheck:$t(s.hostedSourceCheck)}:{},...Ot(s.hostedPublish)?{hostedPublish:Ot(s.hostedPublish)}:{},...Tt(s.hostedRun)?{hostedRun:Tt(s.hostedRun)}:{},...typeof s.error=="string"||s.error===null?{error:s.error}:{}})}if(Array.isArray(t.profiles)){let s=t.profiles.flatMap(i=>{let c=Fe(i);if(!c)return[];let l=i,u=l.source==="github"||l.source==="openpond_git"?l.source:"local",p=typeof l.repositoryId=="string"&&l.repositoryId.trim()?l.repositoryId.trim():Sn.resolve(c.repoPath);return[{source:u,repositoryId:p,repoPath:c.repoPath,profile:c.profile,...c.lastCheck?{lastCheck:c.lastCheck}:{},...c.lastPush?{lastPush:c.lastPush}:{}}]});s.length>0&&(r.profiles=s)}return r}a(Fe,"sanitizeLocalOpenPondProfile");function _t(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,o=Ae(t.status);return o?{status:o,...m(t,"agentId"),...m(t,"runtimeAgentId"),...m(t,"projectId"),...m(t,"sourceRoot"),...m(t,"sourceRef"),...m(t,"sourceCommitSha"),...m(t,"manifestHash"),...m(t,"manifestPath"),...m(t,"manifestSyncedAt"),...Ut(t,"fileCount"),...Ut(t,"totalBytes"),...m(t,"generatedManifestPath"),...He(t,"synthesizedOpenPondYaml"),...m(t,"uploadMetadataPath"),...O(t,"setupCommands"),...O(t,"validationCommands"),...m(t,"materializedAt"),...m(t,"error")}:null}a(_t,"sanitizeHostedMaterializationStatus");function $t(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,o=Ae(t.status);return o?{status:o,...m(t,"agentId"),...m(t,"deployPlanStatus"),...He(t,"canRun"),...He(t,"canDeploy"),...m(t,"sourceRef"),...m(t,"sourceCommitSha"),...m(t,"manifestHash"),...m(t,"manifestPath"),...O(t,"setupCommands"),...O(t,"validationCommands"),...O(t,"requiredChecks"),...O(t,"evalNames"),...O(t,"blockedReasons"),...O(t,"staleReasons"),...m(t,"runtimeId"),...m(t,"sandboxId"),...O(t,"traceArtifactRefs"),...O(t,"evalResultArtifactRefs"),...O(t,"validatorArtifactRefs"),...m(t,"checkedAt"),...m(t,"error")}:null}a($t,"sanitizeHostedSourceCheckStatus");function Ot(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,o=Ae(t.status);return o?{status:o,...m(t,"agentId"),...m(t,"snapshotId"),...m(t,"sourceRef"),...m(t,"sourceCommitSha"),...m(t,"manifestHash"),...m(t,"manifestPath"),...m(t,"buildStatus"),...m(t,"validationStatus"),...m(t,"evalStatus"),...m(t,"publishedAt"),...m(t,"error")}:null}a(Ot,"sanitizeHostedPublishStatus");function Tt(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,o=Ae(t.status);return o?{status:o,...m(t,"agentId"),...m(t,"runId"),...m(t,"runtimeId"),...m(t,"sandboxId"),...m(t,"sourceRef"),...m(t,"sourceCommitSha"),...m(t,"manifestHash"),...m(t,"setupGateStatus"),...O(t,"setupRequirementRefs"),...O(t,"artifactRefs"),...O(t,"traceArtifactRefs"),...O(t,"evalArtifactRefs"),...m(t,"startedAt"),...m(t,"completedAt"),...m(t,"error")}:null}a(Tt,"sanitizeHostedRunSummary");function m(e,t){let o=e[t];return typeof o=="string"||o===null?{[t]:o}:{}}a(m,"nullableStringProp");function He(e,t){let o=e[t];return typeof o=="boolean"||o===null?{[t]:o}:{}}a(He,"nullableBooleanProp");function Ut(e,t){let o=e[t];return typeof o=="number"||o===null?{[t]:o}:{}}a(Ut,"nullableNumberProp");function O(e,t){let o=e[t];if(!Array.isArray(o))return{};let n=o.filter(r=>typeof r=="string");return{[t]:n}}a(O,"stringArrayProp");function Ae(e){return typeof e=="string"&&e.trim()?e.trim():null}a(Ae,"stringField");function Lt(e,t){if(!de(e.handle,t.handle))return!1;let o=_(t.baseUrl);return o?_(e.baseUrl)===o:!_(e.baseUrl)}a(Lt,"accountMatchesSelector");function Ge(e,t,o={}){let n=_(t.baseUrl);if(n)return qe(e,t.handle,n);let r=e.findIndex(i=>Lt(i,t));if(r!==-1)return r;let s=e.map((i,c)=>({account:i,index:c})).filter(({account:i})=>de(i.handle,t.handle));if(s.length>1&&o.requireUnambiguous)throw new Error(`multiple profiles found for ${t.handle}; pass --base-url to select one`);return s[0]?.index??-1}a(Ge,"findAccountIndexForSelector");function xn(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,o={};return typeof t.token=="string"&&(o.token=t.token),(typeof t.appId=="string"||t.appId===null)&&(o.appId=t.appId),(typeof t.conversationId=="string"||t.conversationId===null)&&(o.conversationId=t.conversationId),Object.keys(o).length>0?o:void 0}a(xn,"sanitizeSession");function kn(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,o=z(typeof t.handle=="string"?t.handle:void 0);if(!o)return null;let n={handle:o};typeof t.apiKey=="string"&&(n.apiKey=t.apiKey),typeof t.baseUrl=="string"&&(n.baseUrl=t.baseUrl),typeof t.apiBaseUrl=="string"&&(n.apiBaseUrl=t.apiBaseUrl),typeof t.chatApiBaseUrl=="string"&&(n.chatApiBaseUrl=t.chatApiBaseUrl),typeof t.environment=="string"&&(n.environment=t.environment);let r=xn(t.session);return r&&(n.session=r),n}a(kn,"sanitizeAccount");function bn(e){let t={};return typeof e.token=="string"&&(t.token=e.token),(typeof e.appId=="string"||e.appId===null)&&(t.appId=e.appId),(typeof e.conversationId=="string"||e.conversationId===null)&&(t.conversationId=e.conversationId),Object.keys(t).length>0?t:void 0}a(bn,"extractLegacySession");function In(e,t){let o={handle:t};typeof e.apiKey=="string"&&(o.apiKey=e.apiKey),typeof e.baseUrl=="string"&&(o.baseUrl=e.baseUrl),typeof e.apiBaseUrl=="string"&&(o.apiBaseUrl=e.apiBaseUrl),typeof e.chatApiBaseUrl=="string"&&(o.chatApiBaseUrl=e.chatApiBaseUrl);let n=bn(e);return n&&(o.session=n),o}a(In,"extractLegacyAccount");function Nt(e){let t={};typeof e.lspEnabled=="boolean"&&(t.lspEnabled=e.lspEnabled),(e.executionMode==="local"||e.executionMode==="hosted")&&(t.executionMode=e.executionMode),(e.mode==="general"||e.mode==="builder")&&(t.mode=e.mode);let o=Fe(e.openpondProfile);o&&(t.openpondProfile=o);let n=[],r=Array.isArray(e.accounts)?e.accounts:[];for(let l of r){let u=kn(l);u&&qe(n,u.handle,u.baseUrl)===-1&&n.push(u)}if(n.length===0){let l=oe(e.activeProfile)?.handle||Se;n.push(In(e,l))}let s=oe(e.activeProfile),i=s?Ge(n,s):-1,c=n[i===-1?0:i];return t.accounts=n,t.activeProfile=ne(c),t}a(Nt,"normalizeGlobalConfig");function Cn(e,t,o){let n=e.accounts??[],r=_(o??process.env.OPENPOND_BASE_URL),s=z(t);if(s)return r?{handle:s,baseUrl:r}:{handle:s};let i=z(process.env.OPENPOND_ACCOUNT);if(i)return r?{handle:i,baseUrl:r}:{handle:i};let c=oe(e.activeProfile);return c?r?{handle:c.handle,baseUrl:r}:c:n[0]?ne(n[0]):{handle:Se}}a(Cn,"resolveRequestedProfile");function jt(e,t,o){let n=_(o);if(n){let s=qe(e,t,n);if(s!==-1)return e[s]}else{let s=e.filter(i=>de(i.handle,t));if(s.length>1)throw new Error(`multiple profiles found for ${t}; pass --base-url to select one`);if(s.length===1)return s[0]}let r={handle:t};return n&&(r.baseUrl=n),e.push(r),r}a(jt,"ensureAccount");function Mt(e){e.session&&Object.keys(e.session).length===0&&delete e.session}a(Mt,"cleanupAccount");function vn(e,t,o,n){let r=o===null||o===void 0&&n.undefinedDeletes;switch(t){case"apiKey":{if(r){delete e.apiKey;return}typeof o=="string"&&(e.apiKey=o);return}case"baseUrl":{if(r){delete e.baseUrl;return}typeof o=="string"&&(e.baseUrl=o);return}case"apiBaseUrl":{if(r){delete e.apiBaseUrl;return}typeof o=="string"&&(e.apiBaseUrl=o);return}case"chatApiBaseUrl":{if(r){delete e.chatApiBaseUrl;return}typeof o=="string"&&(e.chatApiBaseUrl=o);return}case"token":case"appId":case"conversationId":{if(e.session||(e.session={}),r){delete e.session[t],Mt(e);return}(typeof o=="string"||o===null)&&(e.session[t]=o),Mt(e);return}}}a(vn,"applyScopedKey");function En(e,t,o){if(!Rt.some(l=>W(t,l)))return!1;let r=e.accounts??[],s=oe(t.activeProfile)??Cn(e),i=_(W(t,"baseUrl")?t.baseUrl??null:s.baseUrl??process.env.OPENPOND_BASE_URL),c=jt(r,s.handle,i);for(let l of Rt)W(t,l)&&vn(c,l,t[l],o);return e.accounts=r,e.activeProfile=ne(c),!0}a(En,"applyAccountPatch");function Rn(e,t){if(W(t,"lspEnabled")&&(typeof t.lspEnabled=="boolean"?e.lspEnabled=t.lspEnabled:t.lspEnabled===null&&delete e.lspEnabled),W(t,"executionMode")&&(t.executionMode==="local"||t.executionMode==="hosted"?e.executionMode=t.executionMode:t.executionMode===null&&delete e.executionMode),W(t,"mode")&&(t.mode==="general"||t.mode==="builder"?e.mode=t.mode:t.mode===null&&delete e.mode),W(t,"activeProfile")){let o=oe(t.activeProfile);if(o){let n=Ge(e.accounts??[],o);e.activeProfile=n===-1?o:ne((e.accounts??[])[n])}else t.activeProfile===null&&delete e.activeProfile}if(W(t,"openpondProfile")){let o=Fe(t.openpondProfile);o?e.openpondProfile=o:t.openpondProfile===null&&delete e.openpondProfile}}a(Rn,"applyTopLevelPatch");async function xe(e){let t=L();return await De(t),await vt(t,o=>{let n=Nt(o);return e(n),n})}a(xe,"updateGlobalConfig");async function T(){let e=L();return await De(e),Nt(await Ct(e))}a(T,"loadGlobalConfig");async function ze(){let e=await T(),t=oe(e.activeProfile);return(e.accounts??[]).map(o=>{let n=z(o.handle)??Se;return{handle:n,baseUrl:_(o.baseUrl),apiBaseUrl:_(o.apiBaseUrl),chatApiBaseUrl:_(o.chatApiBaseUrl),environment:o.environment?.trim()||null,isActive:!!(t&&Lt({...o,handle:n},t)),hasApiKey:!!o.apiKey?.trim(),hasSessionToken:!!o.session?.token?.trim(),sessionAppId:o.session?.appId??null,sessionConversationId:o.session?.conversationId??null}})}a(ze,"listConfiguredProfiles");async function _n(e,t={}){let o=Bt(e),n=_(t.baseUrl),r=-1;await xe(i=>{let c=i.accounts??[];if(r=Ge(c,n?{handle:o,baseUrl:n}:{handle:o},{requireUnambiguous:!0}),r===-1)throw new Error(`profile not found: ${o}`);i.activeProfile=ne(c[r])});let s=await ze();return s.find(i=>i.isActive)??s[r]}a(_n,"setActiveProfile");async function $n(e){let t=Bt(e.handle),o=An(e.apiKey),n=_(e.baseUrl),r=_(e.apiBaseUrl),s=_(e.chatApiBaseUrl),i={handle:t};await xe(u=>{let p=u.accounts??[],h=jt(p,t,n);h.apiKey=o,n&&(h.baseUrl=n),r?h.apiBaseUrl=r:e.apiBaseUrl===null&&delete h.apiBaseUrl,s?h.chatApiBaseUrl=s:e.chatApiBaseUrl===null&&delete h.chatApiBaseUrl,e.environment===null?delete h.environment:typeof e.environment=="string"&&e.environment.trim()&&(h.environment=e.environment.trim()),u.accounts=p,i=ne(h),e.setActive!==!1&&(u.activeProfile=i)});let l=(await ze()).find(u=>de(u.handle,i.handle)?n?_(u.baseUrl)===n:!0:!1);if(!l)throw new Error(`failed to save profile: ${t}`);return l}a($n,"saveProfileApiKey");async function H(e){await xe(t=>{Rn(t,e),En(t,e,{undefinedDeletes:!1})})}a(H,"saveGlobalConfig");function Je(e=null){return{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!0,error:e}}a(Je,"emptyProfileCatalogState");function Ke(e=null){return{skillCount:0,generatedAt:null,stale:!0,error:e}}a(Ke,"emptyProfileSkillCatalogState");function We(){return{status:"ready",requirementCount:0,blockingCount:0,optionalMissingCount:0,readyCount:0,requirements:[],blockingRequirements:[]}}a(We,"emptyProfileSetupGate");function ke(){return{changedAgents:[],newAgents:[],deletedAgents:[],changedSkills:[],changedActions:[],changedExtensions:[],setupChanges:[],envRequirementChanges:[],files:[]}}a(ke,"emptyProfileDiffSummary");function Ve(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}}a(Ve,"emptyProfileSummary");import{existsSync as re}from"node:fs";import{readFile as On,stat as Tn}from"node:fs/promises";import be from"node:path";var Dt=".openpond/agent-manifest.json",Ht=".openpond/action-registry.json",Un=".openpond/source-upload-metadata.json",Mn=".openpond/agent-package-origin.json";async function Gt(e){return Jt({agentId:"default",sourcePath:e,preferred:!0})}a(Gt,"loadProfileActionCatalog");async function zt(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(c=>c.preferred),...e.filter(c=>!c.preferred)],o=await Promise.all(t.map(Jt)),n=new Map,r=[];for(let c of o)for(let l of c.actionCatalog){let u=n.has(l.id)?`${l.agentId??"agent"}.${l.sourceActionId??l.id}`:l.id,p=u===l.id?l:{...l,id:u};n.set(u,p),r.push(p)}let s=Ln(o.map(c=>c.catalog.generatedAt)),i=o.map(c=>c.catalog.error).filter(Boolean);return{catalog:{actionCount:r.length,generatedAt:s,manifestPath:o.find(c=>c.catalog.manifestPath)?.catalog.manifestPath??null,registryPath:o.find(c=>c.catalog.registryPath)?.catalog.registryPath??null,stale:o.some(c=>c.catalog.stale),error:i.length>0?i.join("; "):null},actionCatalog:r,sourceSetupRequirements:o.flatMap(c=>c.sourceSetupRequirements)}}a(zt,"loadProfileActionCatalogForSources");async function Jt(e){let t=e.sourcePath,o=be.join(t,Dt),n=be.join(t,Ht),r=be.join(t,Un),s=be.join(t,Mn);try{let i=await Ie(o),c=await Ie(n),l=await Ie(r),u=$(await Ie(s)),p=$($(i)?.inputSchemas),h=Ft($(l)?.setupRequirements)??[],k=Nn(h),C=new Map;for(let f of[...Ye($(i)?.actionCatalog),...Ye($(c)?.actions),...Ye($(i)?.actions)]){let y=b(f.id)??b(f.name);if(!y)continue;let x=C.get(y),v=jn({sourceRequirementsByAction:k,actionId:y,actionName:b(f.name)}),B=Dn(Ft(f.setupRequirements)??x?.setupRequirements??[],v),K={id:y,agentId:e.agentId,sourcePath:t,sourceActionId:y,name:b(f.name)??x?.name??y,label:b(f.label)??x?.label??zn(y),description:b(f.description)??x?.description??null,visibility:b(f.visibility)??x?.visibility??"default",inputSchema:Gn(f.inputSchema,p)??x?.inputSchema??null,outputSchema:Kt(f.outputSchema)??x?.outputSchema??null,approvalPolicy:$(f.approvalPolicy)??x?.approvalPolicy??null,artifactPolicy:$(f.artifactPolicy)??x?.artifactPolicy??null,setupRequirements:B,mcp:$(f.mcp)??x?.mcp??null,schedulePolicy:$(f.schedulePolicy)??x?.schedulePolicy??null,trace:Bn($(f.trace)??x?.trace??null,u),implementation:$(f.implementation)??x?.implementation??null,invokesModel:typeof f.invokesModel=="boolean"?f.invokesModel:x?.invokesModel};C.set(y,K)}let P=Array.from(C.values()).filter(f=>f.visibility!=="internal"&&f.visibility!=="debug"),g=[...i?[]:[Dt],...c?[]:[Ht]],S=await Fn([o,n]);return{catalog:{actionCount:P.length,generatedAt:S,manifestPath:re(o)?o:null,registryPath:re(n)?n:null,stale:g.length>0,error:g.length>0?qn(e,g):null},actionCatalog:P,sourceSetupRequirements:h}}catch(i){return{catalog:{actionCount:0,generatedAt:null,manifestPath:re(o)?o:null,registryPath:re(n)?n:null,stale:!0,error:i instanceof Error?i.message:String(i)},actionCatalog:[],sourceSetupRequirements:[]}}}a(Jt,"loadProfileActionCatalogSource");function Bn(e,t){if(!t)return e;let o=b(t.versionId),n=b(t.digest);return!o||!n?e:{...e??{},agentVersionId:o,agentPackageDigest:n,validationReceiptIds:qt(t.validationReceiptIds),evalReceiptIds:qt(t.evalReceiptIds)}}a(Bn,"mergeAgentPackageTrace");function qt(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}a(qt,"stringArray");function Ln(e){let t=0;for(let o of e){if(!o)continue;let n=Date.parse(o);Number.isFinite(n)&&(t=Math.max(t,n))}return t>0?new Date(t).toISOString():null}a(Ln,"latestIso");function Nn(e){let t=new Map;for(let o of e){let n=[b(o.actionId),b(o.sourceActionId),b(o.actionName)].filter(r=>!!r);for(let r of n){let s=t.get(r)??[];s.push(o),t.set(r,s)}}return t}a(Nn,"sourceSetupRequirementsByAction");function jn(e){return[...e.sourceRequirementsByAction.get(e.actionId)??[],...e.actionName&&e.actionName!==e.actionId?e.sourceRequirementsByAction.get(e.actionName)??[]:[]].map(o=>({...o,source:"source_upload_metadata"}))}a(jn,"setupRequirementsForActionSource");function Dn(e,t){if(t.length===0)return e;let o=[],n=new Set;for(let r of[...e,...t]){let s=Hn(r);n.has(s)||(n.add(s),o.push(r))}return o}a(Dn,"mergeSetupRequirements");function Hn(e){return[b(e.actionId)??b(e.sourceActionId)??b(e.actionName)??"",b(e.kind)??b(e.type)??"",b(e.name)??b(e.key)??b(e.provider)??b(e.tool)??b(e.command)??b(e.packageName)??b(e.path)??b(e.repo)??b(e.url)??b(e.id)??""].join(":")}a(Hn,"setupRequirementIdentity");function qn(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(" ")}a(qn,"missingSourceArtifactsMessage");async function Ie(e){return re(e)?JSON.parse(await On(e,"utf8")):null}a(Ie,"readJsonIfExists");async function Fn(e){let t=0;for(let o of e){if(!re(o))continue;let n=await Tn(o);t=Math.max(t,n.mtimeMs)}return t>0?new Date(t).toISOString():null}a(Fn,"latestMtime");function $(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}a($,"asRecord");function Ye(e){return Array.isArray(e)?e.filter(t=>!!$(t)):[]}a(Ye,"records");function Ft(e){return Array.isArray(e)?e.filter(t=>!!$(t)):null}a(Ft,"recordArray");function b(e){return typeof e=="string"&&e.trim()?e.trim():null}a(b,"text");function Kt(e){return b(e)??$(e)}a(Kt,"schemaValue");function Gn(e,t){let o=Kt(e);return typeof o!="string"?o:$(t?.[o])??o}a(Gn,"resolvedSchemaValue");function zn(e){let t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,o=>o.toUpperCase()):e}a(zn,"titleFromActionId");var Ce=class extends Error{static{a(this,"OpenPondProfileSetupRequiredError")}code="agent_source_setup_required";details;constructor(t,o){let n=o.blockingRequirements.map(r=>r.label);super(["agent_source_setup_required",`Profile action ${t} has unresolved required setup.`,n.length?`Missing setup: ${n.join(", ")}`:""].filter(Boolean).join(`
|
|
3
|
+
`)),this.name="OpenPondProfileSetupRequiredError",this.details={error:"agent_source_setup_required",actionId:t,setupGate:o,missing:n,blockingSetupRequirements:o.blockingRequirements,setupRequirements:o.requirements}}};function ve(e){let t=new Map;for(let i of e.sourceSetupRequirements??[]){let c=Kn(i);if(e.actionId&&c&&c!==e.actionId&&E(i.actionName)!==e.actionId&&E(i.sourceActionId)!==e.actionId)continue;let l=Wt({record:i,source:"source_upload_metadata",actionId:c});l&&t.set(l.ref,l)}for(let i of e.actionCatalog)if(!(e.actionId&&i.id!==e.actionId&&i.name!==e.actionId))for(let c of i.setupRequirements??[]){let l=Wt({record:c,source:"action_catalog",actionId:i.id});l&&t.set(l.ref,l)}let o=Array.from(t.values()),n=o.filter(i=>i.blocking),r=o.filter(i=>!i.required&&!Xe(i.status)).length,s=o.filter(i=>Xe(i.status)).length;return{status:Vn(n),requirementCount:o.length,blockingCount:n.length,optionalMissingCount:r,readyCount:s,requirements:o,blockingRequirements:n}}a(ve,"buildOpenPondProfileSetupGate");function Ze(e,t){if(t.blockingRequirements.length>0)throw new Ce(e,t)}a(Ze,"assertOpenPondProfileActionReady");function Jn(e){let t=e.actionId?`${e.actionId}: `:"",o=e.required?"required":"optional";return`${t}${e.label} (${o}, ${e.status})`}a(Jn,"formatOpenPondProfileSetupRequirement");function Wt(e){let t=e.source==="action_catalog"&&E(e.record.source)==="source_upload_metadata"?"source_upload_metadata":e.source,o=E(e.record.kind)??E(e.record.type),n=E(e.record.label)??E(e.record.name)??E(e.record.key)??E(e.record.provider)??E(e.record.tool)??E(e.record.command)??E(e.record.packageName)??E(e.record.path)??E(e.record.repo)??E(e.record.url)??E(e.record.id)??o??"setup requirement",r=e.record.required!==!1,s=Wn(e.record);return{ref:[t,e.actionId??"source",o??"requirement",n].join(":"),source:t,actionId:e.actionId,kind:o,label:n,status:s,required:r,blocking:r&&!Xe(s)}}a(Wt,"setupRequirementFromRecord");function Kn(e){return E(e.actionId)??E(e.sourceActionId)??E(e.actionName)}a(Kn,"setupRequirementActionId");function Wn(e){let t=E(e.status)??E(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"}a(Wn,"setupStatus");function Vn(e){return e.length===0?"ready":e.some(t=>["blocked","unsupported","unsupported_dependency","stale"].includes(t.status))?"blocked":"setup_required"}a(Vn,"gateStatus");function Xe(e){return e==="ready"||e==="disabled"}a(Xe,"isReadyStatus");function E(e){return typeof e=="string"&&e.trim()?e.trim():null}a(E,"text");import{spawn as Yn}from"node:child_process";import{randomUUID as Xn}from"node:crypto";import{existsSync as Qe}from"node:fs";import{readFile as Zn,rm as Qn,writeFile as Xt}from"node:fs/promises";import Ee from"node:path";var Zt=["**/node_modules/","**/.bun/","**/.env","**/.env.*","**/.openpond/traces/","**/.openpond/vendor/","**/.openpond/eval-results.json","**/.openpond/artifact-index.json","**/.openpond/source-upload-cache.json",""].join(`
|
|
4
|
+
`);async function Qt(e){if(!Qe(Ee.join(e,".git"))){let s=await M(e,["init","-b","main"]);if(s.code!==0)throw new Error(Y("git init",s))}let t=Ee.join(e,".gitignore");if(Qe(t)?await er(t):await Xt(t,Zt,"utf8"),await or(e))return;let o=await X(e);if(!o.dirty&&o.files.length===0)return;let n=await M(e,["add","-A"]);if(n.code!==0)throw new Error(Y("git add",n));let r=await M(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(Y("git commit",r))}a(Qt,"ensureProfileGitRepo");async function er(e){let t=await Zn(e,"utf8").catch(()=>""),o=Zt.split(/\r?\n/).map(r=>r.trim()).filter(Boolean).filter(r=>!t.split(/\r?\n/).some(s=>s.trim()===r));if(o.length===0)return;let n=t.endsWith(`
|
|
5
|
+
`)||t.length===0?"":`
|
|
6
|
+
`;await Xt(e,`${t}${n}${o.join(`
|
|
7
|
+
`)}
|
|
8
|
+
`,"utf8")}a(er,"ensureProfileGitignoreRules");async function X(e){if(!Qe(Ee.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 M(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[o,n,r,s,i]=await Promise.all([ae(e,["branch","--show-current"]),ae(e,["rev-parse","HEAD"]),M(e,["status","--porcelain=v1","-uall"]),ae(e,["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"]),ae(e,["remote","get-url","origin"])]),c=r.code===0?rr(r.stdout):[],l=s?await nr(e):{ahead:null,behind:null},u=n||null;return{isRepo:!0,branch:o||null,head:u,shortHead:u?u.slice(0,12):null,dirty:c.length>0,upstream:s,ahead:l.ahead,behind:l.behind,remoteUrl:i,files:c,error:r.code===0?null:Y("git status",r)}}a(X,"loadProfileGitState");async function eo(e,t){let o=await X(e);if(!o.isRepo)throw new Error(o.error??"Active OpenPond profile source is not a Git repo.");if(!o.dirty)return{committed:!1,stdout:"",stderr:"",state:o};let n=await M(e,["add","-A"]);if(n.code!==0)throw new Error(Y("git add",n));let r=await M(e,["commit","-m",t]);if(r.code!==0)throw new Error(Y("git commit",r));return{committed:!0,stdout:r.stdout,stderr:r.stderr,state:await X(e)}}a(eo,"commitProfileChanges");async function to(e){return ae(e,["rev-parse","HEAD"])}a(to,"profileGitHead");async function Ca(e){let t=await X(e.repoPath);if(!t.isRepo)throw new Error(t.error??"Active OpenPond profile source is not a Git repo.");let o=e.baseCommit??t.head;if(!o)throw new Error("A Profile benchmark requires an admitted Git commit.");let r=`refs/openpond/benchmarks/${tr(e.runId)}`,s=await ae(e.repoPath,["rev-parse","--verify",r]);if(s)return{ref:r,commit:s,baseCommit:o,paths:e.files.map(u=>Vt(u.path)).sort()};let i=e.files.map(u=>({...u,path:Vt(u.path)})).sort((u,p)=>u.path.localeCompare(p.path));if(!i.length)throw new Error("A Profile benchmark commit requires at least one file.");if(new Set(i.map(u=>u.path)).size!==i.length)throw new Error("A Profile benchmark commit cannot contain duplicate paths.");let c=Ee.join(e.repoPath,".git",`openpond-benchmark-index-${Xn()}`),l={...process.env,GIT_INDEX_FILE:c,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"};try{await se(e.repoPath,["read-tree",o],"git read-tree",{env:l});for(let h of i){let k=await se(e.repoPath,["hash-object","-w","--stdin"],`git hash-object ${h.path}`,{env:l,input:h.contents});await se(e.repoPath,["update-index","--add","--cacheinfo",`100644,${k.stdout.trim()},${h.path}`],`git update-index ${h.path}`,{env:l})}let u=await se(e.repoPath,["write-tree"],"git write-tree",{env:l}),p=await se(e.repoPath,["commit-tree",u.stdout.trim(),"-p",o,"-m",e.message??`Preserve OpenPond benchmark ${e.runId}`],"git commit-tree",{env:l});return await se(e.repoPath,["update-ref",r,p.stdout.trim()],"git update-ref",{env:l}),{ref:r,commit:p.stdout.trim(),baseCommit:o,paths:i.map(h=>h.path)}}finally{await Qn(c,{force:!0}).catch(()=>{})}}a(Ca,"commitProfileBenchmarkRef");function tr(e){let t=e.trim().replace(/[^A-Za-z0-9._-]+/g,"-");if(!t||t==="."||t==="..")throw new Error("Benchmark run id cannot form a safe Git ref.");return t}a(tr,"safeGitSegment");function Vt(e){let t=e.trim().replaceAll("\\","/");if(!t||t.startsWith("/")||t.split("/").some(o=>!o||o==="."||o==="..")||t.includes("\0"))throw new Error(`Unsafe benchmark Git path: ${e}`);return t}a(Vt,"safeGitPath");async function or(e){return(await M(e,["rev-parse","--verify","HEAD"])).code===0}a(or,"hasGitHead");async function nr(e){let t=await M(e,["rev-list","--left-right","--count","@{u}...HEAD"]);if(t.code!==0)return{ahead:null,behind:null};let[o,n]=t.stdout.trim().split(/\s+/),r=o?Number.parseInt(o,10):Number.NaN,s=n?Number.parseInt(n,10):Number.NaN;return{ahead:Number.isFinite(s)?s:null,behind:Number.isFinite(r)?r:null}}a(nr,"loadAheadBehind");async function ae(e,t){let o=await M(e,t);return o.code!==0?null:o.stdout.trim()||null}a(ae,"gitText");function rr(e){return e.split(/\r?\n/).map(t=>t.trimEnd()).filter(Boolean).map(t=>{let o=t[0]??" ",n=t[1]??" ",r=`${o}${n}`.trim()||"changed",s=t.slice(3),i=s.split(" -> "),c=o===" "?null:o,l=n===" "?null:n,u=i.length===2?i[1]:s,p=i.length===2?i[0]:null;return{path:Yt(u),originalPath:p?Yt(p):null,indexStatus:c,worktreeStatus:l,status:r,category:sr(c,l)}})}a(rr,"parsePorcelainStatus");function sr(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"}a(sr,"gitChangeCategory");function Yt(e){let t=e.trim();if(!t.startsWith('"')||!t.endsWith('"'))return t;try{return JSON.parse(t)}catch{return t.slice(1,-1)}}a(Yt,"unquoteGitPath");function Y(e,t){return t.stderr.trim()||t.stdout.trim()||`${e} failed with exit code ${t.code??"unknown"}`}a(Y,"gitFailureMessage");async function M(e,t,o={}){return new Promise((n,r)=>{let s=Yn("git",t,{cwd:e,env:o.env,stdio:"pipe"}),i="",c="";s.stdout?.on("data",l=>{i+=String(l)}),s.stderr?.on("data",l=>{c+=String(l)}),s.on("error",r),s.on("close",l=>{n({code:l,stdout:i,stderr:c})}),o.input!==void 0?s.stdin?.end(o.input):s.stdin?.end()})}a(M,"runGitCommand");async function se(e,t,o,n={}){let r=await M(e,t,n);if(r.code!==0)throw new Error(Y(o,r));return r}a(se,"requireGitSuccess");import{stat as lr}from"node:fs/promises";import ot from"node:path";import{createHash as et}from"node:crypto";import{readFile as ar}from"node:fs/promises";import ir from"node:path";var oo=".openpond/source-upload-cache.json",no="openpond.source-upload-cache.v1";async function ro(e){try{let o=(await Ne(L(),"source-upload.v1",io(e)))?.payload;if(!o)return new Map;if(o.schema!==no||!o.entries)return new Map;let n=new Map;for(let[r,s]of Object.entries(o.entries))!cr(s)||r!==tt(s)||n.set(r,s);return n}catch{return new Map}}a(ro,"readSourceUploadCache");async function so(e,t){let o=await ar(e.absolutePath),n=et("sha256").update(o).digest("hex"),r=tt({...e,sha256:n}),s=t.get(r);return s&&s.sha256===n&&et("sha256").update(Buffer.from(s.contentsBase64,"base64")).digest("hex")===n?{file:e,entry:{path:e.path,type:"file",contentsBase64:s.contentsBase64},sha256:s.sha256}:{file:e,entry:{path:e.path,type:"file",contentsBase64:o.toString("base64")},sha256:n}}a(so,"materializeSourceUploadFile");async function ao(e,t){let o={};for(let n of t){let r={path:n.file.path,size:n.file.size,mtimeMs:n.file.mtimeMs,ctimeMs:n.file.ctimeMs,sha256:n.sha256,contentsBase64:n.entry.contentsBase64};o[tt(r)]=r}await je(L(),"source-upload.v1",io(e),{schema:no,generatedAt:new Date().toISOString(),entries:o})}a(ao,"writeSourceUploadCache");function tt(e){return`${e.path}\0${e.sha256}`}a(tt,"cacheKeyForFile");function cr(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.path=="string"&&typeof t.size=="number"&&typeof t.mtimeMs=="number"&&typeof t.ctimeMs=="number"&&typeof t.sha256=="string"&&typeof t.contentsBase64=="string"}a(cr,"isCacheEntry");function io(e){return et("sha256").update(ir.resolve(e)).digest("hex")}a(io,"sourceScope");var nt=1500,uo=8*1024*1024,rt=100*1024*1024,st=8,ur={maxFiles:nt,maxFileBytes:uo,maxTotalBytes:rt,concurrency:st},dr={mode:"single_json_payload",chunkingSupported:!1};async function fr(e){let t=await M(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 o=t.stdout.split("\0").map(l=>l.trim()).filter(Boolean).filter(l=>{let u=l.replace(/\\/g,"/");return lo(u)&&!pr(u)}).sort();if(o.length===0)throw new Error("No committed profile source files found to upload.");if(o.length>nt)throw new Error(`Too many profile source files to upload: ${o.length} > ${nt}`);let n=(await co(o,st,async l=>{let u=ot.resolve(e,l),p=ot.relative(e,u).replace(/\\/g,"/");if(!lo(p))throw new Error(`Profile source path escapes repo: ${l}`);let h=await lr(u);if(!h.isFile())return null;if(h.size>uo)throw new Error(`Profile source file is too large: ${l} (${h.size} bytes)`);return{path:p,absolutePath:u,size:h.size,mtimeMs:Math.trunc(h.mtimeMs),ctimeMs:Math.trunc(h.ctimeMs)}})).filter(l=>l!==null),r=0;for(let l of n)if(r+=l.size,r>rt)throw new Error(`Profile source upload is too large: ${r} > ${rt}`);let s=await ro(e),i=await co(n,st,async l=>so(l,s));await ao(e,i).catch(()=>{});let c=i.map(l=>l.entry);return{entries:c,fileCount:c.length,totalBytes:r,limits:ur,transport:dr}}a(fr,"collectProfileSourceUploadEntries");async function co(e,t,o){let n=new Array(e.length),r=0,s=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:s},async()=>{for(;r<e.length;){let i=r;r+=1,n[i]=await o(e[i],i)}})),n}a(co,"mapWithConcurrency");function lo(e){return e.length>0&&!e.includes("\0")&&!ot.isAbsolute(e)&&!e.split(/[\\/]+/).some(t=>!t||t==="."||t==="..")}a(lo,"isSafeProfileSourcePath");function pr(e){return e.split(/[\\/]+/).some((t,o,n)=>{let r=t.toLowerCase();if(r===".git"||r==="node_modules"||r===".bun"||r===".env"||r.startsWith(".env.")||e.replace(/\\/g,"/")===oo)return!0;if(r!==".openpond")return!1;let s=n[o+1]?.toLowerCase();return s==="goals"||s==="traces"||s==="vendor"||s==="eval-results.json"||s==="artifact-index.json"})}a(pr,"shouldSkipProfileSourcePath");function hr(e){let t=R(e.checkResult),o=R(t?.deployPlan)??R(e.deployPlan),n=R(o?.source),r=R(o?.checks),s=R(t?.sourceCheckStatus);return{status:e.status,agentId:e.agentId,deployPlanStatus:w(o?.status),canRun:fo(o?.canRun),canDeploy:fo(o?.canDeploy),sourceRef:w(n?.sourceRef),sourceCommitSha:w(n?.sourceCommitSha),manifestHash:w(n?.manifestHash),manifestPath:w(n?.manifestPath),setupCommands:N(r?.setupCommands),validationCommands:N(r?.validationCommands),requiredChecks:N(r?.requiredChecks),evalNames:N(r?.evalNames),blockedReasons:N(o?.blockedReasons),staleReasons:N(o?.staleReasons),runtimeId:w(s?.latestRuntimeId),sandboxId:w(s?.latestSandboxId),traceArtifactRefs:N(s?.traceArtifactRefs),evalResultArtifactRefs:N(s?.evalResultArtifactRefs),validatorArtifactRefs:N(s?.validatorArtifactRefs),checkedAt:e.checkedAt??new Date().toISOString(),error:e.error??null}}a(hr,"hostedSourceCheckStatusFromPayload");function mr(e){let t=R(e.publishResult),o=R(t?.activeManifestSnapshot)??R(t?.manifestSnapshot)??R(t?.snapshot);return{status:e.status??"published",agentId:e.agentId,snapshotId:w(o?.id),sourceRef:w(o?.sourceRef),sourceCommitSha:w(o?.sourceCommitSha),manifestHash:w(o?.manifestHash),manifestPath:w(o?.manifestPath),buildStatus:w(o?.buildStatus),validationStatus:w(o?.validationStatus),evalStatus:w(o?.evalStatus),publishedAt:w(t?.publishedAt)??w(o?.publishedAt),error:e.error??null}}a(mr,"hostedPublishStatusFromPayload");function gr(e){let t=R(e.runResult),o=R(t?.run),n=R(o?.runtimeSource),r=R(o?.metadata),s=R(r?.sourceSummary),i=R(r?.setupGate),c=R(r?.responseSummary),l=R(r?.traceSummary),u=R(r?.evalSummary);return{status:w(o?.status)??(e.error?"failed":"running"),agentId:w(o?.agentId)??e.agentId,runId:w(o?.id),runtimeId:w(o?.runtimeId),sandboxId:w(o?.sandboxId),sourceRef:w(n?.sourceRef)??w(s?.sourceRef)??w(r?.sourceRef),sourceCommitSha:w(n?.sourceCommitSha)??w(s?.sourceCommitSha)??w(r?.hostedHead),manifestHash:w(n?.manifestHash)??w(s?.manifestHash),setupGateStatus:w(i?.status),setupRequirementRefs:wr(i),artifactRefs:N(c?.artifactRefs),traceArtifactRefs:N(l?.artifactRefs),evalArtifactRefs:N(u?.artifactRefs),startedAt:w(o?.createdAt),completedAt:w(o?.completedAt),error:e.error??null}}a(gr,"hostedRunSummaryFromPayload");function yr(e){return e?.status?e.status==="succeeded"||e.status==="passed"?"passed":e.status==="failed"||e.status==="cancelled"?"failed":"running":"not_started"}a(yr,"hostedRunStatusFromRunSummary");function wr(e){return e?(Array.isArray(e.requirements)?e.requirements:Array.isArray(e.blockingRequirements)?e.blockingRequirements:[]).map(o=>{let n=R(o);return w(n?.ref)??w(n?.id)??w(n?.label)}).filter(o=>!!o):[]}a(wr,"setupRequirementRefs");function R(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}a(R,"record");function w(e){return typeof e=="string"&&e.trim()?e.trim():null}a(w,"text");function fo(e){return typeof e=="boolean"?e:null}a(fo,"booleanValue");function N(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}a(N,"textArray");var Z="openpond-profile.json",xr="settings/profile.yaml",xo="default",G="default";function kr(e,t){let o=e?.defaultAgent??G,n=e?.enabledAgents&&e.enabledAgents.length>0?e.enabledAgents:[o];return{...e??{},path:t,defaultAgent:o,enabledAgents:n}}a(kr,"mergeProfileRepoManifestEntry");function _e(e,t,o){let n=D(e);if(e){let c=n.findIndex(u=>d.resolve(u.repoPath)===d.resolve(e.repoPath)&&u.profile===e.profile),l={source:n[c]?.source??"local",repositoryId:n[c]?.repositoryId??d.resolve(e.repoPath),repoPath:d.resolve(e.repoPath),profile:e.profile,...e.lastCheck?{lastCheck:e.lastCheck}:{},...e.lastPush?{lastPush:e.lastPush}:{}};c>=0?n[c]=l:n.push(l)}let r=n.findIndex(c=>d.resolve(c.repoPath)===d.resolve(t)&&c.profile===o),s=r>=0?n[r]:{source:"local",repositoryId:d.resolve(t),repoPath:d.resolve(t),profile:o};return r<0&&n.push(s),{repoPath:d.resolve(t),profile:o,mode:"local",profiles:n,...s.lastCheck?{lastCheck:s.lastCheck}:{},...s.lastPush?{lastPush:s.lastPush}:{}}}a(_e,"mergeActiveLocalProfileConfig");function D(e){if(!e)return[];let t=e.profiles?.map(o=>({...o}))??[];return t.some(o=>d.resolve(o.repoPath)===d.resolve(e.repoPath)&&o.profile===e.profile)||t.push({source:"local",repositoryId:d.resolve(e.repoPath),repoPath:d.resolve(e.repoPath),profile:e.profile,...e.lastCheck?{lastCheck:e.lastCheck}:{},...e.lastPush?{lastPush:e.lastPush}:{}}),t}a(D,"profileConfigEntries");var br=Po(import.meta.url);function Ir(){return d.join(L(),"library","profiles","default-repo")}a(Ir,"defaultLocalProfileRepoPath");function ko(e=null){return{mode:"none",repoPath:null,activeProfile:null,sourcePath:null,manifestPath:null,agents:[],skills:[],evals:[],git:null,catalog:Je(e),skillCatalog:Ke(e),actionCatalog:[],sourceSetupRequirements:[],setupGate:We(),diff:ke(),hosted:null,summary:Ve(e),lastCheck:null,error:e}}a(ko,"emptyProfileState");async function ni(e={}){let t=d.resolve(e.repoPath??Ir()),o=dt(e.profile),n=d.join("profiles",o),r=d.join(t,n),s=e.template??"blank-agent",i=s==="blank-profile";await F(t,{recursive:!0});let c=U(d.join(t,Z)),l=await Q(t).catch(()=>Dr(o,n));if(i&&c&&l.profiles[o])throw new Error(`Profile "${o}" already exists in ${t}.`);l.defaultProfile=l.defaultProfile||o,l.profiles[o]=kr(l.profiles[o],n),i&&(l.profiles[o].enabledAgents=[]),i?await F(r,{recursive:!0}):await Rr(r,s,!!e.force),await Co(r),await _r(t,r,o,{includeDefaultAgent:!i}),await Re(t,l),await Qt(t);let u=(await T()).openpondProfile;return await H({openpondProfile:_e(u,t,o)}),J()}a(ni,"initLocalProfileRepo");async function ri(e,t,o){let n=d.resolve(e),r=await Q(n),s=dt(t??r.defaultProfile);ft(r,n,s);let i=(await T()).openpondProfile,c=_e(i,n,s);return bo(c,n,s,o),await H({openpondProfile:c}),J()}a(ri,"loadLocalProfileRepo");async function si(e,t,o){let n=d.resolve(e),r=await Q(n),s=dt(t??r.defaultProfile);ft(r,n,s);let i=(await T()).openpondProfile,c=_e(i,n,s);return bo(c,n,s,o),i&&(c.repoPath=i.repoPath,c.profile=i.profile,c.lastCheck=i.lastCheck,c.lastPush=i.lastPush),await H({openpondProfile:c}),vr(ct({repoPath:n,profile:s,source:o?.source,repositoryId:o?.repositoryId}))}a(si,"registerLocalProfileRepo");function bo(e,t,o,n){n&&(e.profiles=D(e).map(r=>d.resolve(r.repoPath)===t&&r.profile===o?{...r,source:n.source,repositoryId:n.repositoryId}:r))}a(bo,"applyProfileIdentity");async function ai(e,t){let o=e.trim(),n=jr(t);if(!o)throw new Error("Agent ID is required.");let s=(await T()).openpondProfile;if(!s)throw new Error("No active local Profile.");let i=await Q(s.repoPath),c=i.profiles[s.profile];if(!c)throw new Error(`Profile "${s.profile}" was not found.`);let l=c.defaultAgent??G;if(!(c.enabledAgents??[l]).includes(o))throw new Error(`Agent "${o}" was not found in Profile "${s.profile}".`);let p={...c.agentNames??{}};return n===o?delete p[o]:p[o]=n,Object.keys(p).length?c.agentNames=p:delete c.agentNames,await Re(s.repoPath,i),J()}a(ai,"renameActiveProfileAgent");async function ii(e){let t=e.agentPackage;if(Hr(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 o=await Oe(),n=o.state.sourcePath;await Co(n);let r=d.join(n,"agents");await F(r,{recursive:!0});let s=d.join(r,t.agentId),i=U(s);if(i&&e.overwrite!==!0)throw new Error(`Agent "${t.agentId}" already exists. Confirm replacement to install this version.`);let c=d.join(r,`.${t.agentId}.${ho()}.installing`),l=d.join(r,`.${t.agentId}.${ho()}.backup`),u=await Q(o.config.repoPath),p=JSON.stringify(u),h=!1,k=!1;try{await qr(c,t),i&&(await at(s,l),h=!0),await at(c,s),k=!0;let C=u.profiles[o.config.profile];if(!C)throw new Error(`Profile "${o.config.profile}" was not found.`);let P=new Set(C.enabledAgents??[]);P.add(t.agentId),C.enabledAgents=[...P],C.defaultAgent||(C.defaultAgent=t.agentId),C.agentNames={...C.agentNames??{},[t.agentId]:t.title},await Re(o.config.repoPath,u),h&&await it(l,{recursive:!0,force:!0})}catch(C){throw await it(c,{recursive:!0,force:!0}),k&&await it(s,{recursive:!0,force:!0}),h&&U(l)&&await at(l,s),JSON.stringify(u)!==p&&await Re(o.config.repoPath,JSON.parse(p)).catch(()=>{}),C}return{state:await J(),agentId:t.agentId,versionId:t.versionId,digest:t.digest}}a(ii,"installAgentPackageIntoActiveProfile");async function J(){let t=(await T()).openpondProfile;return t?$e(t):ko()}a(J,"loadOpenPondProfileState");function ct(e){return{source:e.source??"local",repositoryId:e.repositoryId?.trim()||d.resolve(e.repoPath),profileId:e.profile}}a(ct,"openPondProfileRef");async function Cr(){let e=(await T()).openpondProfile;if(!e)return{lastUsed:null,profiles:[]};let t=D(e),o=await Promise.all(t.map(async n=>{let r=await $e({repoPath:n.repoPath,profile:n.profile,mode:"local",...n.lastCheck?{lastCheck:n.lastCheck}:{},...n.lastPush?{lastPush:n.lastPush}:{}});return{ref:ct(n),name:n.profile,repoPath:n.repoPath,sourcePath:r.sourcePath,state:r}}));return{lastUsed:ct({repoPath:e.repoPath,profile:e.profile,source:D(e).find(n=>d.resolve(n.repoPath)===d.resolve(e.repoPath)&&n.profile===e.profile)?.source,repositoryId:D(e).find(n=>d.resolve(n.repoPath)===d.resolve(e.repoPath)&&n.profile===e.profile)?.repositoryId}),profiles:o}}a(Cr,"loadOpenPondProfileLibrary");async function vr(e){if(!e)return J();let t=(await T()).openpondProfile,o=D(t).find(n=>n.source===e.source&&n.repositoryId===e.repositoryId&&n.profile===e.profileId);return o?$e({repoPath:o.repoPath,profile:o.profile,mode:"local",...o.lastCheck?{lastCheck:o.lastCheck}:{},...o.lastPush?{lastPush:o.lastPush}:{}}):ko(`Profile "${e.profileId}" is not installed on this device.`)}a(vr,"loadOpenPondProfileStateForRef");async function ci(e){let t=(await T()).openpondProfile,o=D(t).find(n=>n.source===e.source&&n.repositoryId===e.repositoryId&&n.profile===e.profileId);if(!o)throw new Error(`Profile "${e.profileId}" is not installed on this device.`);return await H({openpondProfile:_e(t,o.repoPath,o.profile)}),J()}a(ci,"selectOpenPondProfile");async function li(e){let t=(await T()).openpondProfile;if(!t)return{lastUsed:null,profiles:[]};let o=D(t).filter(s=>s.source!==e.source||s.repositoryId!==e.repositoryId||s.profile!==e.profileId);if(o.length===0)return await H({openpondProfile:null}),{lastUsed:null,profiles:[]};let r=d.resolve(t.repoPath)===d.resolve(D(t).find(s=>s.source===e.source&&s.repositoryId===e.repositoryId&&s.profile===e.profileId)?.repoPath??"")&&t.profile===e.profileId?o[0]:o.find(s=>d.resolve(s.repoPath)===d.resolve(t.repoPath)&&s.profile===t.profile)??o[0];return await H({openpondProfile:{repoPath:r.repoPath,profile:r.profile,mode:"local",profiles:o,...r.lastCheck?{lastCheck:r.lastCheck}:{},...r.lastPush?{lastPush:r.lastPush}:{}}}),Cr()}a(li,"removeOpenPondProfile");async function $e(e){try{let t=await Q(e.repoPath),o=ft(t,e.repoPath,e.profile),n=await Or(t,e.profile),r=Eo({manifest:t,profile:e.profile,profileSourcePath:o,agents:n}),[s,i,c,l]=await Promise.all([X(e.repoPath),zt(r),Et(o),Tr(o,r)]),u=go(e),p=Lr(s,e.profile),h=ve({actionCatalog:i.actionCatalog,sourceSetupRequirements:i.sourceSetupRequirements}),k=Ur({agents:n,actionCatalog:i.actionCatalog,catalog:i.catalog,diff:p,git:s,hosted:u,lastCheck:e.lastCheck??null,error:null});return{mode:"local",repoPath:e.repoPath,activeProfile:e.profile,sourcePath:o,manifestPath:d.join(e.repoPath,Z),agents:n,skills:c.skills,evals:l,git:s,catalog:i.catalog,skillCatalog:c.skillCatalog,actionCatalog:i.actionCatalog,sourceSetupRequirements:i.sourceSetupRequirements,setupGate:h,diff:p,hosted:u,summary:k,lastCheck:e.lastCheck??null,error:null}}catch(t){let o=await X(e.repoPath).catch(()=>null),n=t instanceof Error?t.message:String(t);return{mode:"local",repoPath:e.repoPath,activeProfile:e.profile,sourcePath:null,manifestPath:d.join(e.repoPath,Z),agents:[],skills:[],evals:[],git:o,catalog:Je(n),skillCatalog:Ke(n),actionCatalog:[],sourceSetupRequirements:[],setupGate:We(),diff:ke(),hosted:go(e),summary:Ve(n),lastCheck:e.lastCheck??null,error:n}}}a($e,"loadOpenPondProfileStateForConfig");async function ui(e){return $e({repoPath:d.resolve(e.repoPath),profile:e.profileId,mode:"local"})}a(ui,"loadOpenPondProfileStateFromSource");async function Oe(){let e=(await T()).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}}a(Oe,"requireActiveLocalProfile");async function di(e){let t=await Oe(),o=e.command==="run"?e.args??[]:[],n=e.command==="run"?t.state.actionCatalog.find(c=>c.id===o[0]):null,r=d.resolve(e.cwd??n?.sourcePath??t.state.sourcePath),s=e.command==="run"?mo(r,e.args??[],n?.sourceActionId??null):null;if(e.command==="run"&&s){let c=s[0],l=d.resolve(t.state.sourcePath)===r?{actionCatalog:t.state.actionCatalog,sourceSetupRequirements:t.state.sourceSetupRequirements}:await Gt(r);Ze(c,ve({actionCatalog:l.actionCatalog,sourceSetupRequirements:l.sourceSetupRequirements,actionId:c}))}let i=await Io({command:e.command,args:e.command==="run"?s??mo(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 ut(e.command,i.code),i.code!==0){let c=i.stderr.trim()||i.stdout.trim();throw new Error(c||`${e.command} failed with exit code ${i.code??"unknown"}`)}return i}a(di,"runProfileSdkCommand");async function Io(e){let t=d.resolve(e.cwd),o=Gr(),n=e.command==="run"?[...o.args,e.command,...e.args??[]]:[...o.args,e.command,"--cwd",t,...e.args??[]],r=await Oo(o.command,n,{cwd:t,inherit:e.inherit,timeoutMs:e.timeoutMs,maxOutputBytes:e.maxOutputBytes});if(e.throwOnFailure!==!1&&r.code!==0){let s=To(r,e.command);throw new Error(s||`${e.command} failed with exit code ${r.code??"unknown"}`)}return r}a(Io,"runAgentSdkProjectCommand");function mo(e,t,o=null){let[n,...r]=t;if(!n||n.startsWith("--"))throw new Error("run requires an action name");return[o??n,"--cwd",e,...r]}a(mo,"runCommandArgs");async function fi(e){let t=!e||e==="all"?["inspect","build","validate","eval"]:[e],o=await Oe(),n=await Q(o.config.repoPath),r=Eo({manifest:n,profile:o.config.profile,profileSourcePath:o.state.sourcePath,agents:o.state.agents});if(r.length===0){if(t.some(s=>s!=="inspect"&&s!=="build"&&s!=="validate"&&s!=="eval"))throw new Error("check kind must be one of inspect, build, validate, eval, all");await ut("validate",0);return}for(let s of t){if(s!=="inspect"&&s!=="build"&&s!=="validate"&&s!=="eval")throw new Error("check kind must be one of inspect, build, validate, eval, all");for(let i of r)await Er({command:s,source:i,profileSourcePath:o.state.sourcePath,sourceCount:r.length})}}a(fi,"runProfileCheck");async function Er(e){let t=e.command==="inspect"||e.command==="validate"||e.command==="eval"?["--json"]:[];if(e.sourceCount>1){let n=d.relative(e.profileSourcePath,e.source.sourcePath)||".";console.log(`
|
|
9
|
+
[profile:${e.source.agentId}] ${e.command} ${n}`)}let o=await Io({command:e.command,args:t,cwd:e.source.sourcePath,inherit:!1,throwOnFailure:!1});if(o.stdout.trim()&&console.log(o.stdout.trim()),o.stderr.trim()&&console.error(o.stderr.trim()),await ut(e.command,o.code),o.code!==0){let n=To(o,e.command);throw new Error([`Profile check failed for enabled agent ${e.source.agentId} at ${e.source.sourcePath}.`,n||`${e.command} failed with exit code ${o.code??"unknown"}`].join(`
|
|
10
|
+
`))}}a(Er,"runProfileCheckForSource");async function pi(e){let t=await Oe();if(!t.state.repoPath)throw new Error("Active OpenPond profile has no repo path.");let o=await eo(t.state.repoPath,e?.trim()||`Update OpenPond profile ${t.state.activeProfile??xo}`);return{committed:o.committed,stdout:o.stdout,stderr:o.stderr,state:await J()}}a(pi,"commitActiveProfileChanges");async function hi(e){let t=(await T()).openpondProfile;if(!t)return;let o=D(t).map(n=>d.resolve(n.repoPath)===d.resolve(t.repoPath)&&n.profile===t.profile?{...n,lastPush:e}:n);await H({openpondProfile:{...t,lastPush:e,profiles:o}})}a(hi,"saveProfilePushStatus");async function ut(e,t){let o=(await T()).openpondProfile;if(!o)return;let n=await to(o.repoPath).catch(()=>null),r={command:e,status:t===0?"passed":"failed",checkedAt:new Date().toISOString(),exitCode:t,sourceHead:n},s=D(o).map(i=>d.resolve(i.repoPath)===d.resolve(o.repoPath)&&i.profile===o.profile?{...i,lastCheck:r}:i);await H({openpondProfile:{...o,lastCheck:r,profiles:s}})}a(ut,"saveProfileCheckStatus");async function Rr(e,t,o){if(await F(e,{recursive:!0}),(await Ao(e)).length>0&&!o)return;let r=fe(),s=d.join(r,"templates",t);if(!U(s))throw new Error(`Unknown agent template "${t}".`);await Sr(s,e,{recursive:!0,force:o,errorOnExist:!1}),await $r(e,r)}a(Rr,"ensureProfileSource");async function _r(e,t,o,n={}){if(await F(d.join(e,"profiles"),{recursive:!0}),n.includeDefaultAgent===!1)return;for(let i of["agents","skills","workflows","actions","extensions","prompts","goals","evals","settings","traces"])await F(d.join(t,i),{recursive:!0});let r=d.join(t,xr);U(r)||await ie(r,["schema: openpond.profile.v1",`profile: ${o}`,"agents:",` - id: ${G}`," path: agent/agent.ts"," enabled: true",""].join(`
|
|
11
|
+
`),"utf8");let s=d.join(t,"openpond.lock");U(s)||await ie(s,`# OpenPond profile lockfile placeholder
|
|
12
|
+
`,"utf8")}a(_r,"ensureProfileScaffoldFiles");async function $r(e,t){let o=d.join(e,"package.json"),n=await So(o,"utf8"),r=JSON.parse(n);r.dependencies={...r.dependencies??{},"openpond-agent-sdk":`file:${t}`},await ie(o,`${JSON.stringify(r,null,2)}
|
|
13
|
+
`,"utf8")}a($r,"rewriteTemplateSdkDependency");async function Co(e){if(!U(d.join(e,"package.json")))return;let t=fe();await vo(t);let o=d.join(e,"node_modules"),n=d.join(o,"openpond-agent-sdk");await F(o,{recursive:!0}),U(n)||await Ar(t,n,"dir")}a(Co,"ensureProfileDependencies");async function vo(e){if(U(d.join(e,"dist","cli.js"))&&U(d.join(e,"dist","primitives","index.js")))return;let t=d.join(e,"scripts","build.ts");if(!U(t))throw new Error(`Resolved openpond-agent-sdk at ${e}, but built SDK files are missing.`);let o=await Oo(process.execPath,[$o(e),t],{cwd:e});if(o.code!==0){let n=o.stderr.trim()||o.stdout.trim();throw new Error(n||`openpond-agent-sdk build failed with exit code ${o.code??"unknown"}`)}}a(vo,"ensureAgentSdkBuilt");async function Or(e,t){let o=e.profiles[t];if(!o)return[];let n=o.defaultAgent??G,r=new Set(o.enabledAgents??[n]);return Array.from(r).map(s=>({id:s,name:o.agentNames?.[s]?.trim()||s,path:s===G?"agent/agent.ts":`agents/${s}`,enabled:!0}))}a(Or,"listProfileAgents");function Eo(e){let t=e.manifest.profiles[e.profile]?.defaultAgent??G;return e.agents.map(o=>({agentId:o.id,sourcePath:o.id===G?e.profileSourcePath:d.join(e.profileSourcePath,"agents",o.id),preferred:o.id===t}))}a(Eo,"profileCatalogSources");async function Tr(e,t){let o=new Map,n=[{root:d.join(e,"evals"),agentId:null},...t.flatMap(r=>[{root:d.join(r.sourcePath,"agent","evals"),agentId:r.agentId},{root:d.join(r.sourcePath,"evals"),agentId:r.agentId}])];for(let r of n)for(let s of await Ro(r.root)){let i=d.relative(e,s).split(d.sep).join("/");o.has(i)||o.set(i,{id:i,name:d.basename(s).replace(/\.eval\.[^.]+$/i,"").replace(/\.[^.]+$/i,""),path:i,agentId:r.agentId,sourcePath:s})}return[...o.values()].sort((r,s)=>r.name.localeCompare(s.name)||r.path.localeCompare(s.path))}a(Tr,"loadProfileEvals");async function Ro(e){if(!U(e))return[];let t=[];for(let o of await Ao(e,{withFileTypes:!0})){let n=d.join(e,o.name);o.isDirectory()?t.push(...await Ro(n)):o.isFile()&&/\.eval\.(?:[cm]?[jt]sx?)$/i.test(o.name)&&t.push(n)}return t}a(Ro,"listEvalSourceFiles");function go(e){let t=e.lastPush;return t?{teamId:t.teamId??null,projectId:t.projectId??null,sourceRef:t.sourceRef??null,sourceCommitSha:t.hostedHead??null,lastPushedAt:t.pushedAt,lastPushedLocalHead:t.localHead??null,lastPushedHostedHead:t.hostedHead??null,promotionStatus:t.promotionStatus??null,hostedRunStatus:t.hostedRunStatus??null,hostedRunAgentId:t.hostedRunAgentId??null,hostedRunId:t.hostedRunId??null,hostedRunAt:t.hostedRunAt??null,hostedSourceMaterialization:t.hostedSourceMaterialization??null,hostedSourceCheck:t.hostedSourceCheck??null,hostedPublish:t.hostedPublish??null,hostedRun:t.hostedRun??null}:null}a(go,"hostedBindingFromConfig");function Ur(e){let t=e.actionCatalog.find(r=>r.id==="chat")?.id??e.actionCatalog.find(r=>r.name==="chat")?.id??e.actionCatalog.find(r=>r.id.endsWith(".chat"))?.id??null,o=!!(!e.catalog.stale&&!e.git.dirty&&e.git.head&&(e.agents.length===0||e.lastCheck?.status==="passed"&&e.lastCheck.sourceHead===e.git.head)),n=e.agents.length===0&&!e.catalog.stale&&!e.git.dirty?null:Mr({catalog:e.catalog,git:e.git,lastCheck:e.lastCheck});return e.error?{state:"error",message:e.error,agentCount:e.agents.length,actionCount:e.actionCatalog.length,defaultAction:t,checkFresh:o,checkStaleReason:n,localHead:e.git.head,hostedHead:e.hosted?.sourceCommitSha??null}:e.git.isRepo?e.git.head?e.git.dirty?{state:"dirty",message:Br(e.diff),agentCount:e.agents.length,actionCount:e.actionCatalog.length,defaultAction:t,checkFresh:o,checkStaleReason:n,localHead:e.git.head,hostedHead:e.hosted?.sourceCommitSha??null}:{state:"ready",message:e.catalog.stale?"Profile source is clean; action catalog needs inspect/build.":"Profile source is clean.",agentCount:e.agents.length,actionCount:e.actionCatalog.length,defaultAction:t,checkFresh:o,checkStaleReason:n,localHead:e.git.head,hostedHead:e.hosted?.sourceCommitSha??null}:{state:"pending_commit",message:"Profile source is ready for its first commit.",agentCount:e.agents.length,actionCount:e.actionCatalog.length,defaultAction:t,checkFresh:!1,checkStaleReason:"Profile source has no committed head.",localHead:null,hostedHead:e.hosted?.sourceCommitSha??null}:{state:"error",message:"Profile source is not Git-backed.",agentCount:e.agents.length,actionCount:e.actionCatalog.length,defaultAction:t,checkFresh:!1,checkStaleReason:"Profile source is not Git-backed.",localHead:null,hostedHead:e.hosted?.sourceCommitSha??null}}a(Ur,"summarizeProfileState");function Mr(e){return e.catalog.error?`Catalog error: ${e.catalog.error}`:e.catalog.stale?"Action catalog artifacts are missing or stale.":e.lastCheck?e.lastCheck.status!=="passed"?`Last ${e.lastCheck.command} check failed.`:e.lastCheck.sourceHead?e.git.head&&e.lastCheck.sourceHead!==e.git.head?"Profile source changed since the last check.":e.git.dirty?"Profile has uncommitted source changes.":null:"Last check did not record a source head.":"Profile checks have not run."}a(Mr,"profileCheckStaleReason");function Br(e){let t=[];return e.changedAgents.length>0&&t.push(`${e.changedAgents.length} changed agent(s)`),e.newAgents.length>0&&t.push(`${e.newAgents.length} new agent(s)`),e.deletedAgents.length>0&&t.push(`${e.deletedAgents.length} deleted agent(s)`),e.changedSkills.length>0&&t.push(`${e.changedSkills.length} changed skill(s)`),e.changedActions.length>0&&t.push(`${e.changedActions.length} changed action(s)`),e.changedExtensions.length>0&&t.push(`${e.changedExtensions.length} changed extension(s)`),e.setupChanges.length>0&&t.push(`${e.setupChanges.length} setup change(s)`),e.envRequirementChanges.length>0&&t.push(`${e.envRequirementChanges.length} env requirement change(s)`),t.length>0?`Profile has ${t.join(", ")}.`:"Profile has uncommitted source changes."}a(Br,"profileDirtyMessage");function Lr(e,t){let o=ke();o.files=e.files;let n=`profiles/${t}/`;for(let r of e.files){let s=r.path.replace(/\\/g,"/");if(s===Z||s===".gitignore"){q(o.setupChanges,s);continue}if(!s.startsWith(n))continue;let i=s.slice(n.length);Nr(o,r,i)}return o}a(Lr,"summarizeProfileDiff");function Nr(e,t,o){let n=o.split("/")[0]??"";if(n==="agent")yo(e,G,t.category);else if(n==="agents"){let r=o.split("/")[1];r&&yo(e,r,t.category)}else n==="skills"?q(e.changedSkills,o.split("/")[1]??o):n==="actions"?q(e.changedActions,o.split("/")[1]??o):n==="extensions"?q(e.changedExtensions,o.split("/")[1]??o):(n==="settings"||o==="package.json"||o==="openpond.yaml"||o==="openpond.lock")&&q(e.setupChanges,o);o.toLowerCase().includes("env")&&q(e.envRequirementChanges,o),o.startsWith(".openpond/")&&q(e.changedActions,"catalog")}a(Nr,"classifyProfileFileChange");function yo(e,t,o){if(o==="added"||o==="untracked"){q(e.newAgents,t);return}if(o==="deleted"){q(e.deletedAgents,t);return}q(e.changedAgents,t)}a(yo,"addAgentChange");function q(e,t){!t||e.includes(t)||e.push(t)}a(q,"addUnique");function dt(e){let t=e?.trim();if(!t)return xo;if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new Error("profile name may only contain letters, numbers, dots, underscores, and hyphens");return t}a(dt,"normalizeProfileName");function jr(e){let t=e.trim().replace(/\s+/g," ");if(!t)throw new Error("Agent name is required.");if(t.length>80)throw new Error("Agent name must be 80 characters or fewer.");if(/[\u0000-\u001f\u007f]/.test(t))throw new Error("Agent name cannot contain control characters.");return t}a(jr,"normalizeAgentDisplayName");function Dr(e,t){return{schema:"openpond.profileRepo.v1",defaultProfile:e,profiles:{[e]:{path:t,defaultAgent:G,enabledAgents:[G]}}}}a(Dr,"defaultProfileManifest");async function Q(e){let t=d.join(e,Z),o=await So(t,"utf8"),n=JSON.parse(o);if(n.schema!=="openpond.profileRepo.v1"||!n.profiles||typeof n.profiles!="object")throw new Error(`${t} is not an OpenPond profile repo manifest.`);return n}a(Q,"readProfileManifest");async function Re(e,t){await ie(d.join(e,Z),`${JSON.stringify(t,null,2)}
|
|
14
|
+
`,"utf8")}a(Re,"writeProfileManifest");function ft(e,t,o){let n=e.profiles[o];if(!n)throw new Error(`Profile "${o}" was not found in ${d.join(t,Z)}.`);let r=d.resolve(t,n.path);if(!U(r))throw new Error(`Profile source path does not exist: ${r}`);return r}a(ft,"profileSourcePath");function Hr(e){let t=0,o=new Set;for(let c of e.source.files){let l=_o(c.path);if(o.has(l))throw new Error(`Agent package contains duplicate source path ${l}.`);o.add(l);let u=Buffer.from(c.contentsBase64,"base64");if(u.byteLength!==c.sizeBytes||po("sha256").update(u).digest("hex")!==c.sha256)throw new Error(`Agent package source checksum failed for ${l}.`);t+=u.byteLength}if(t!==e.source.totalSizeBytes)throw new Error("Agent package source size does not match its manifest.");let{digest:n,versionId:r,...s}=e,i=po("sha256").update(Fr(s)).digest("hex");if(i!==e.digest||e.versionId!==`agent-${i.slice(0,20)}`)throw new Error("Agent package content digest does not match its version.")}a(Hr,"verifyAgentPackageIntegrity");async function qr(e,t){await F(e,{recursive:!0,mode:448});for(let n of t.source.files){let r=_o(n.path),s=d.resolve(e,r);if(!s.startsWith(`${d.resolve(e)}${d.sep}`))throw new Error("Agent package source path escapes its install root.");await F(d.dirname(s),{recursive:!0,mode:448});let i=Buffer.from(n.contentsBase64,"base64");if(r==="package.json"){let c=JSON.parse(i.toString("utf8"));c.dependencies={...c.dependencies??{},"openpond-agent-sdk":`file:${fe()}`},i=Buffer.from(`${JSON.stringify(c,null,2)}
|
|
15
|
+
`,"utf8")}await ie(s,i,{mode:384,flag:"wx"})}let o=d.join(e,".openpond","agent-package-origin.json");await F(d.dirname(o),{recursive:!0,mode:448}),await ie(o,`${JSON.stringify({schema:"openpond.agent-package-origin.v1",agentId:t.agentId,versionId:t.versionId,digest:t.digest,validationReceiptIds:t.receipts.filter(n=>n.kind==="sdk_validation").map(n=>n.id),evalReceiptIds:t.receipts.filter(n=>n.kind==="sdk_eval").map(n=>n.id)},null,2)}
|
|
16
|
+
`,{mode:384,flag:"wx"})}a(qr,"materializeAgentPackage");function _o(e){let t=e.trim().replaceAll("\\","/"),o=d.posix.normalize(t);if(!o||o==="."||o===".."||o.startsWith("/")||o.startsWith("../")||o.split("/").some(n=>n===".."))throw new Error(`Agent package contains an invalid source path: ${e}.`);return o}a(_o,"normalizeAgentPackagePath");function Fr(e){return JSON.stringify(lt(e))}a(Fr,"stableAgentPackageJson");function lt(e){return Array.isArray(e)?e.map(lt):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[o])=>t.localeCompare(o)).map(([t,o])=>[t,lt(o)]))}a(lt,"sortAgentPackageJson");function fe(){let e=br.resolve("openpond-agent-sdk/package.json");return d.dirname(e)}a(fe,"resolveAgentSdkRoot");async function mi(){let e=fe();return await vo(e),e}a(mi,"prepareAgentSdkRuntimePackage");function Gr(){let e=fe(),t=d.join(e,"dist","cli.js");if(U(t))return{command:process.execPath,args:[t]};let o=d.join(e,"src","cli.ts");if(U(o))return{command:process.execPath,args:[$o(e),o]};throw new Error(`openpond-agent CLI was not found under ${e}`)}a(Gr,"resolveAgentSdkCliLaunch");function $o(e){return Po(d.join(e,"package.json")).resolve("tsx/cli")}a($o,"resolveTsxCli");async function Oo(e,t,o={}){return new Promise((n,r)=>{let s=Pr(e,t,{cwd:o.cwd,stdio:o.inherit?"inherit":"pipe"}),i="",c="",l=!1,u=!1,p=!1,h=o.timeoutMs??600*1e3,k=o.maxOutputBytes??2*1024*1024,C=h>0?setTimeout(()=>{p=!0,s.kill("SIGTERM")},h):null,P=h>0?setTimeout(()=>{p&&s.exitCode===null&&s.kill("SIGKILL")},h+5e3):null;o.inherit||(s.stdout?.on("data",S=>{let f=wo(i,String(S),k,l);i=f.text,l=f.truncated}),s.stderr?.on("data",S=>{let f=wo(c,String(S),k,u);c=f.text,u=f.truncated}));let g=a(()=>{C&&clearTimeout(C),P&&clearTimeout(P)},"clearTimers");s.on("error",S=>{g(),r(S)}),s.on("close",S=>{g(),n({code:S,stdout:i,stderr:c,timedOut:p,stdoutTruncated:l,stderrTruncated:u})})})}a(Oo,"spawnCommand");function wo(e,t,o,n){if(n)return{text:e,truncated:!0};let r=`${e}${t}`;return Buffer.byteLength(r,"utf8")<=o?{text:r,truncated:!1}:{text:`${Buffer.from(r).subarray(0,Math.max(0,o)).toString("utf8")}
|
|
17
|
+
[truncated after ${o} bytes]
|
|
18
|
+
`,truncated:!0}}a(wo,"appendBoundedOutput");function To(e,t){let o=e.stderr.trim()||e.stdout.trim(),n=[e.timedOut?`${t} timed out`:"",e.stdoutTruncated?"stdout truncated":"",e.stderrTruncated?"stderr truncated":""].filter(Boolean);return[o,...n].filter(Boolean).join(`
|
|
19
|
+
`)}a(To,"commandFailureDetail");var vi=new URL(we).hostname,Ei=new URL(ye).hostname;async function Ho(e,t,o){let n=new URLSearchParams;o?.handle&&n.set("handle",o.handle),typeof o?.limit=="number"&&Number.isFinite(o.limit)&&n.set("limit",String(Math.max(1,Math.floor(o.limit)))),typeof o?.offset=="number"&&Number.isFinite(o.offset)&&n.set("offset",String(Math.max(0,Math.floor(o.offset)))),typeof o?.includeScheduled=="boolean"&&n.set("includeScheduled",o.includeScheduled?"true":"false");let r=n.toString(),s=await j(e,t,`/apps/list${r?`?${r}`:""}`,{method:"GET"});if(!s.ok){let c=await s.text().catch(()=>"");throw new Error(`Apps list failed: ${s.status} ${c}`)}let i=await s.json().catch(()=>({}));return Array.isArray(i.apps)?i.apps:[]}a(Ho,"listApps");async function qo(e,t,o){let n=await j(e,t,"/apps/repo/create",{method:"POST",body:JSON.stringify(o)});if(!n.ok){let r=await n.text().catch(()=>"");throw new Error(`Repo create failed: ${n.status} ${r}`)}return await n.json()}a(qo,"createRepo");async function Ri(e,t,o,n){let r=await j(e,t,`/apps/${encodeURIComponent(o)}/code-visibility`,{method:"PATCH",body:JSON.stringify({codeVisibility:n})});if(!r.ok){let s=await r.text().catch(()=>"");throw new Error(`Code visibility update failed: ${r.status} ${s}`)}return await r.json()}a(Ri,"updateAppCodeVisibility");async function Fo(e,t,o){let n=await j(e,t,`/v4/apps/${o}/environment`,{method:"GET"});if(!n.ok){let r=await n.text().catch(()=>"");throw new Error(`Environment get failed: ${n.status} ${r}`)}return await n.json()}a(Fo,"getAppEnvironment");async function Go(e,t){let o=await j(e,t,"/v1/account",{method:"GET"});if(!o.ok){let n=await o.text().catch(()=>"");throw new Error(`Account lookup failed: ${o.status} ${n}`)}return await o.json()}a(Go,"getOpenPondAccount");var zo=3600*1e3;async function Uc(e,t,o,n={}){let r=await(n.apiFetch??j)(e,t,n.path??bt,{method:"POST",signal:n.signal,body:JSON.stringify(o)}),s=await r.json().catch(()=>({})),i=r.status!==404&&r.status!==405&&r.status!==501;return r.ok?{ok:typeof s.ok=="boolean"?s.ok:!0,status:r.status,endpointAvailable:i,output:Yo(s),data:Xo(s)}:{ok:!1,status:r.status,endpointAvailable:i,output:Yo(s)??(i?`Connected app tool call failed with status ${r.status}.`:`Connected app tool-call endpoint is not available (${r.status}).`),data:Xo(s)}}a(Uc,"executeConnectedAppToolCall");function Yo(e){return typeof e.output=="string"&&e.output.trim()?e.output.trim():typeof e.message=="string"&&e.message.trim()?e.message.trim():typeof e.error=="string"&&e.error.trim()?e.error.trim():null}a(Yo,"responsePayloadMessage");function Xo(e){return"data"in e?e.data:"result"in e?e.result:null}a(Xo,"responsePayloadData");var A=class extends Error{static{a(this,"GithubExtensionError")}code;status;constructor(t,o){super(t),this.name="GithubExtensionError",this.code=o.code,this.status=o.status??400}};import{createHash as nn}from"node:crypto";import ht from"node:path";var Zo="HEAD",Qo=64,en=512,rn=20*1024*1024,mt=5*1024*1024,sn=8,vs=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,tn=/^[A-Za-z0-9_.-]+$/,on=new Set(["agents","assets","references","scripts"]);function an(e={}){let t=e.fetch??fetch,o=e.githubToken?.trim()||process.env.GITHUB_TOKEN?.trim()||process.env.GH_TOKEN?.trim()||null;return{async resolve(n){let r=await Es(n,t,o);return{preview:await Rs(r,t,o),files:cn(r)}},async download(n,r){await Ts({resolution:n,fetchImpl:t,githubToken:o,writeFile:r})}}}a(an,"createGithubSourceClient");function V(e){let t=e.trim(),o="",n="";if(/^(?:https?:\/\/)?github\.com\//i.test(t)){let i=new URL(t.startsWith("http")?t:`https://${t}`);if(i.hostname.toLowerCase()!=="github.com")throw Te(e);let c=i.pathname.replace(/^\/+|\/+$/g,"").split("/");if(c.length!==2)throw Te(e);[o="",n=""]=c}else{let c=t.replace(/^github:/i,"").replace(/^\/+|\/+$/g,"").split("/");if(c.length!==2)throw Te(e);[o="",n=""]=c}if(n=n.replace(/\.git$/i,""),!tn.test(o)||!tn.test(n))throw Te(e);let r=o.toLowerCase(),s=n.toLowerCase();return{id:`github:${r}/${s}`,owner:r,repo:s,repositoryUrl:`https://github.com/${r}/${s}`}}a(V,"parseGithubExtensionSource");async function Es(e,t,o){let n=V(e.source),r=e.ref?.trim()||Zo,s=await pt(t,o,`/repos/${n.owner}/${n.repo}`),i=r===Zo?s.default_branch?.trim()||"main":r,c=await pt(t,o,`/repos/${n.owner}/${n.repo}/commits/${encodeURIComponent(i)}`),l=c.sha?.trim(),u=c.commit?.tree?.sha?.trim();if(!l||!u)throw new A("GitHub returned an incomplete commit response.",{code:"github_invalid_commit",status:502});let p=await pt(t,o,`/repos/${n.owner}/${n.repo}/git/trees/${u}?recursive=1`);if(p.truncated)throw new A("The GitHub repository tree is too large to install safely.",{code:"github_tree_truncated"});let h=(p.tree??[]).filter(Bs),k=$s(h);if(k.length===0)throw new A("No skills found. Add SKILL.md at the repository root or use a standard agent skills directory.",{code:"extension_no_skills"});if(k.length>Qo)throw new A(`Extension contains more than ${Qo} skills.`,{code:"extension_too_many_skills"});Ms(k);let C=h.find(P=>P.type==="blob"&&/^readme(?:\.[^/]+)?$/i.test(P.path))??null;return{identity:n,requestedRef:r,resolvedCommit:l,tree:h,skillPackages:k,readme:C}}a(Es,"resolveSource");async function Rs(e,t,o){let n=await dn(e.skillPackages,sn,async c=>{let l=await Us(e,c.entry,t,o);return _s(c,l)}),r=js(n.map(c=>c.name));for(let c of n)r.has(c.name)&&(c.validationStatus="error",c.validationMessages=[...c.validationMessages,`Duplicate skill name: ${c.name}`]);let s=n.flatMap(c=>c.validationMessages.map(l=>`${c.relativePath}: ${l}`)),i=cn(e);return{...e.identity,source:"github",requestedRef:e.requestedRef,resolvedCommit:e.resolvedCommit,sourcePath:null,readmePath:e.readme?.path??null,packageHash:Ls(i),skills:n.sort((c,l)=>c.name.localeCompare(l.name)),validationStatus:s.length===0?"valid":"error",validationMessages:s}}a(Rs,"buildPreview");function _s(e,t){let o=Pe(t),n=e.root==="."?null:ht.posix.basename(e.root),r=o.name??n??"invalid-skill",s=[...o.messages];vs.test(r)||s.push("Skill name must be lowercase kebab-case."),n&&r!==n&&s.push(`Skill name must match its directory name (${n}).`);let i=e.files.filter(c=>c.path!==e.entry.path).map(c=>Ns(e.root,c.path)).sort();return{name:r,description:o.description??"",relativePath:e.root==="."?"SKILL.md":`${e.root}/SKILL.md`,sourcePath:"",charCount:t.length,sourceHash:nn("sha256").update(t).digest("hex"),resourceFiles:i,validationStatus:s.length===0?"valid":"error",validationMessages:[...new Set(s)]}}a(_s,"previewSkill");function $s(e){let t=[],o=e.find(c=>c.type==="blob"&&c.path==="SKILL.md");o&&t.push({root:".",entry:o});let n=e.filter(c=>c.type==="blob"&&c.path.endsWith("/SKILL.md")),r=n.filter(c=>Os(c.path)),s=r.length>0?r:n,i=new Set(s.map(c=>ht.posix.dirname(c.path)));for(let c of s){let l=ht.posix.dirname(c.path);[...i].some(u=>u!==l&&l.startsWith(`${u}/`))||t.push({root:l,entry:c})}return t.map(({root:c,entry:l})=>{let u=e.filter(k=>{if(k.type!=="blob")return!1;if(c!==".")return k.path.startsWith(`${c}/`);if(k.path==="SKILL.md")return!0;let C=k.path.split("/",1)[0]??"";return on.has(C)}),p=e.find(k=>k.type!=="blob"&&k.type!=="tree"&&(c==="."?k.path==="SKILL.md"||on.has(k.path.split("/",1)[0]??""):k.path.startsWith(`${c}/`))),h=u.find(k=>k.mode==="120000");if(p||h)throw new A(`Skill package ${c} contains a symlink or submodule.`,{code:"extension_unsafe_entry"});return{root:c,entry:l,files:u}})}a($s,"discoverSkillPackages");function Os(e){let t=e.split("/");if(t.at(-1)!=="SKILL.md")return!1;let o=t.slice(0,-1);if(o.length<2)return!1;let n=o.lastIndexOf("skills");if(n<0||n>2)return!1;let r=o.slice(0,n),s=o.slice(n+1);if(s.length<1||s.length>2)return!1;if(n===0)return!0;let i=r[0]??"";return i.startsWith(".")||i==="agent"||i==="data"}a(Os,"isStandardAgentSkillsPath");function cn(e){let t=new Map;e.readme&&t.set(e.readme.path,e.readme);for(let o of e.skillPackages)for(let n of o.files)t.set(n.path,n);return[...t.values()].sort((o,n)=>o.path.localeCompare(n.path))}a(cn,"filesToDownload");async function Ts(e){let t=0;await dn(e.resolution.files,sn,async o=>{let n=await ln({owner:e.resolution.preview.owner,repo:e.resolution.preview.repo,commit:e.resolution.preview.resolvedCommit,file:o,fetchImpl:e.fetchImpl,githubToken:e.githubToken});if(t+=n.byteLength,t>rn)throw new A("Extension download exceeds the maximum allowed size.",{code:"extension_too_large"});await e.writeFile(o.path,n,o.mode==="100755")})}a(Ts,"downloadFiles");async function Us(e,t,o,n){let r=await ln({owner:e.identity.owner,repo:e.identity.repo,commit:e.resolvedCommit,file:t,fetchImpl:o,githubToken:n});return new TextDecoder("utf-8",{fatal:!0}).decode(r)}a(Us,"downloadText");async function ln(e){let t=e.file.path.split("/").map(encodeURIComponent).join("/"),o=`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.commit}/${t}`,n=await e.fetchImpl(o,{headers:un(e.githubToken,"application/vnd.github.raw"),redirect:"follow"});if(!n.ok)throw new A(`GitHub file download failed (${n.status}): ${e.file.path}`,{code:"github_download_failed",status:n.status});let r=Number(n.headers.get("content-length"));if(Number.isFinite(r)&&r>mt)throw new A(`Extension file is too large: ${e.file.path}`,{code:"extension_file_too_large"});let s=new Uint8Array(await n.arrayBuffer());if(s.byteLength>mt)throw new A(`Extension file is too large: ${e.file.path}`,{code:"extension_file_too_large"});return s}a(ln,"downloadBytes");async function pt(e,t,o){let n=await e(`https://api.github.com${o}`,{headers:un(t,"application/vnd.github+json")});if(!n.ok){let r=await n.json().catch(()=>null),s=typeof r?.message=="string"?`: ${r.message}`:"";throw new A(`GitHub request failed (${n.status})${s}`,{code:n.status===404?"github_repository_not_found":"github_request_failed",status:n.status})}return await n.json()}a(pt,"githubJson");function un(e,t){let o=new Headers({Accept:t,"User-Agent":"openpond-extension-installer","X-GitHub-Api-Version":"2022-11-28"});return e&&o.set("Authorization",`Bearer ${e}`),o}a(un,"githubHeaders");function Ms(e){let t=new Map;for(let n of e)for(let r of n.files)t.set(r.path,r);if(t.size>en)throw new A(`Extension contains more than ${en} skill files.`,{code:"extension_too_many_files"});let o=0;for(let n of t.values()){if((n.size??0)>mt)throw new A(`Extension file is too large: ${n.path}`,{code:"extension_file_too_large"});o+=n.size??0}if(o>rn)throw new A("Extension exceeds the maximum allowed size.",{code:"extension_too_large"})}a(Ms,"validateDownloadLimits");function Bs(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.path=="string"&&!t.path.startsWith("/")&&!t.path.split("/").includes("..")&&typeof t.mode=="string"&&(t.type==="blob"||t.type==="tree"||t.type==="commit")&&typeof t.sha=="string"}a(Bs,"validTreeEntry");function Ls(e){let t=nn("sha256");for(let o of e)t.update(`${o.path}\0${o.sha}\0${o.size??""}
|
|
20
|
+
`);return t.digest("hex")}a(Ls,"hashTree");function Ns(e,t){return e==="."?t:t.slice(e.length+1)}a(Ns,"relativeSkillPath");function js(e){let t=new Set,o=new Set;for(let n of e)t.has(n)&&o.add(n),t.add(n);return o}a(js,"duplicateValues");async function dn(e,t,o){let n=new Array(e.length),r=0;async function s(){for(;r<e.length;){let i=r;r+=1,n[i]=await o(e[i])}}return a(s,"worker"),await Promise.all(Array.from({length:Math.min(t,e.length)},s)),n}a(dn,"mapConcurrent");function Te(e){return new A(`Invalid GitHub extension source: ${e}. Use owner/repo or https://github.com/owner/repo.`,{code:"github_invalid_source"})}a(Te,"invalidSource");import{createHash as Ds,randomUUID as yn}from"node:crypto";import{existsSync as te}from"node:fs";import{mkdir as gt,readFile as Hs,rename as le,rm as ue,stat as qs,writeFile as fn}from"node:fs/promises";import I from"node:path";var Me=1,Fs=15e3;function el(e={}){let t=I.resolve(e.home??e.rootPath??L()),o=I.resolve(e.rootPath??I.join(t,"library","extensions")),n=me(t).database,r=an({fetch:e.fetch,githubToken:e.githubToken}),s=e.now??(()=>new Date);async function i(){try{let P=await ee(t),g=await Promise.all(P.extensions.map(S=>yt(o,S)));return Ks(g,await ce(e.reservedSkillNames)),{rootPath:o,registryPath:n,extensions:g.sort(At),error:null}}catch(P){return{rootPath:o,registryPath:n,extensions:[],error:P instanceof Error?P.message:String(P)}}}a(i,"list");async function c(P){let g=await r.resolve(P),S=await ee(t),f=S.extensions.find(y=>y.id===g.preview.id)??null;return pe(g.preview,S.extensions.filter(y=>y.id!==f?.id),await ce(e.reservedSkillNames)),g.preview}a(c,"preview");async function l(P){let g=V(P.source);return Pt(o,g.id,async()=>{let S=await ee(t);if(S.extensions.some(v=>v.id===g.id))throw new A(`${g.owner}/${g.repo} is already installed.`,{code:"extension_already_installed",status:409});let f=await r.resolve(P);gn(f.preview),pe(f.preview,S.extensions,await ce(e.reservedSkillNames));let y=s().toISOString(),x=await pn({rootPath:o,resolution:f,installedAt:y,updatedAt:y,github:r});try{let v=await ce(e.reservedSkillNames);return await wt(t,s,B=>({...B,extensions:zs(B,x,v)})),await hn(o,x.id),x}catch(v){throw await mn(o,x.id),v}})}a(l,"add");async function u(P){let g=V(P.source);return Pt(o,g.id,async()=>{let S=await ee(t),f=Ue(S,g.id),y=await r.resolve({source:f.repositoryUrl,ref:P.ref?.trim()||f.requestedRef});if(gn(y.preview),pe(y.preview,S.extensions.filter(v=>v.id!==f.id),await ce(e.reservedSkillNames)),f.resolvedCommit===y.preview.resolvedCommit&&f.packageHash===y.preview.packageHash&&f.requestedRef===y.preview.requestedRef)return yt(o,f);let x=await pn({rootPath:o,resolution:y,installedAt:f.installedAt,updatedAt:s().toISOString(),github:r});try{let v=await ce(e.reservedSkillNames);return await wt(t,s,B=>({...B,extensions:Js(B,x,v)})),await hn(o,x.id),x}catch(v){throw await mn(o,x.id),v}})}a(u,"update");async function p(){let P=await i();if(P.error)throw new A(P.error,{code:"extension_registry_error"});let g={updated:[],unchanged:[],failed:[]};for(let S of P.extensions)try{let f=await u({source:S.repositoryUrl,ref:S.requestedRef});f.resolvedCommit===S.resolvedCommit&&f.packageHash===S.packageHash?g.unchanged.push(f):g.updated.push(f)}catch(f){g.failed.push({id:S.id,error:f instanceof Error?f.message:String(f)})}return g}a(p,"updateAll");async function h(P){let g=V(P),S=await ee(t);return yt(o,Ue(S,g.id))}a(h,"inspect");async function k(P){let g=V(P);return Pt(o,g.id,async()=>{let S=await ee(t),f=Ue(S,g.id),y=he(o,g.owner,g.repo),x=`${y}.${yn()}.remove`;te(y)&&await le(y,x);try{return await wt(t,s,v=>({...v,extensions:v.extensions.filter(B=>B.id!==f.id)})),await ue(x,{recursive:!0,force:!0}),f}catch(v){throw te(x)&&!te(y)&&await le(x,y),v}})}a(k,"remove");async function C(P){let g=P.trim();if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(g))throw new A("Extension skill name must be lowercase kebab-case.",{code:"extension_skill_invalid_name"});let S=await i();if(S.error)throw new A(S.error,{code:"extension_registry_error"});let f=S.extensions.flatMap(kt=>kt.skills.filter(Be=>Be.name===g).map(Be=>({extension:kt,skill:Be})));if(f.length===0)throw new A(`Extension skill not found: ${g}`,{code:"extension_skill_not_found",status:404});if(f.length>1)throw new A(`Extension skill name is ambiguous: ${g}`,{code:"extension_skill_conflict",status:409});let y=f[0];if(y.extension.validationStatus!=="valid"||y.skill.validationStatus!=="valid")throw new A(`Extension skill ${g} is not valid.`,{code:"extension_skill_invalid"});let x=Pn(y.extension.sourcePath,y.skill.relativePath),v=await Hs(x,"utf8"),B=Ds("sha256").update(v).digest("hex");if(B!==y.skill.sourceHash)throw new A(`Extension skill ${g} changed on disk. Update or reinstall its extension before using it.`,{code:"extension_skill_modified"});let K=Pe(v);if(K.messages.length>0||K.name!==g||!K.description)throw new A(`Extension skill ${g} is not valid. ${K.messages.join(" ")}`.trim(),{code:"extension_skill_invalid"});return{name:g,description:K.description,body:K.body,path:y.skill.relativePath,sourcePath:y.extension.sourcePath,sourceHash:B,charCount:v.length,packagePath:I.dirname(x),resourceFiles:y.skill.resourceFiles}}return a(C,"readSkill"),{rootPath:o,registryPath:n,list:i,preview:c,add:l,update:u,updateAll:p,inspect:h,remove:k,readSkill:C}}a(el,"createGithubExtensionManager");async function pn(e){let t=e.resolution.preview,o=he(e.rootPath,t.owner,t.repo),n=`${o}.${yn()}.install`,r=St(e.rootPath,t.id),s=I.join(n,"current");await ue(n,{recursive:!0,force:!0}),await ue(r,{recursive:!0,force:!0}),await gt(s,{recursive:!0,mode:448});try{await e.github.download(e.resolution,async(c,l,u)=>{let p=Pn(s,c);await gt(I.dirname(p),{recursive:!0,mode:448}),await fn(p,l,{mode:u?448:384})});let i=Gs(t,o,e.installedAt,e.updatedAt);return await fn(I.join(n,"extension.json"),`${JSON.stringify(i,null,2)}
|
|
21
|
+
`,{mode:384}),await gt(I.dirname(o),{recursive:!0,mode:448}),te(o)&&await le(o,r),await le(n,o),i}catch(i){throw await ue(n,{recursive:!0,force:!0}),te(r)&&!te(o)&&await le(r,o),i}}a(pn,"materializeExtension");function Gs(e,t,o,n){let r=I.join(t,"current");return{...e,sourcePath:r,readmePath:e.readmePath?I.join(r,e.readmePath):null,installedAt:o,updatedAt:n,skills:e.skills.map(s=>({...s,sourcePath:I.join(r,s.relativePath)}))}}a(Gs,"installedExtension");async function hn(e,t){await ue(St(e,t),{recursive:!0,force:!0})}a(hn,"finalizeMaterialization");async function mn(e,t){let o=V(t.replace(/^github:/,"")),n=he(e,o.owner,o.repo),r=St(e,t);await ue(n,{recursive:!0,force:!0}),te(r)&&await le(r,n)}a(mn,"rollbackMaterialization");async function yt(e,t){let o=he(e,t.owner,t.repo),n=I.join(o,"current"),r=(await qs(I.join(o,"extension.json")).catch(()=>null))?.isFile()??!1,s=t.validationMessages.filter(i=>i!=="Installed files are missing.");return r||s.push("Installed files are missing."),{...t,sourcePath:n,readmePath:t.readmePath?I.join(n,I.basename(t.readmePath)):null,skills:t.skills.map(i=>({...i,sourcePath:I.join(n,i.relativePath)})),validationStatus:s.length===0?"valid":"error",validationMessages:s}}a(yt,"hydrateExtension");function gn(e){if(e.validationStatus!=="valid")throw new A(`Extension contains invalid skills: ${e.validationMessages.join(" ")}`,{code:"extension_invalid"})}a(gn,"assertInstallable");function pe(e,t,o){let n=new Map;for(let s of o)n.set(s,"a shipped OpenPond skill");for(let s of t)for(let i of s.skills)n.set(i.name,s.id);let r=e.skills.map(s=>({name:s.name,owner:n.get(s.name)})).filter(s=>!!s.owner);if(r.length!==0)throw new A(`Skill name conflict: ${r.map(s=>`${s.name} (${s.owner})`).join(", ")}.`,{code:"extension_skill_conflict",status:409})}a(pe,"assertSkillNamesAvailable");function zs(e,t,o){if(e.extensions.some(n=>n.id===t.id))throw new A(`${t.owner}/${t.repo} is already installed.`,{code:"extension_already_installed",status:409});return pe(t,e.extensions,o),[...e.extensions,t].sort(At)}a(zs,"appendInstalledExtension");function Js(e,t,o){return Ue(e,t.id),pe(t,e.extensions.filter(n=>n.id!==t.id),o),e.extensions.map(n=>n.id===t.id?t:n).sort(At)}a(Js,"replaceInstalledExtension");function Ks(e,t){let o=new Map;for(let n of t)o.set(n,"built-in");for(let n of e)for(let r of n.skills){let s=o.get(r.name);if(!s){o.set(r.name,n.id);continue}let i=`Skill name conflicts with ${s}: ${r.name}`;r.validationStatus="error",r.validationMessages=[...new Set([...r.validationMessages,i])],n.validationStatus="error",n.validationMessages=[...new Set([...n.validationMessages,i])]}}a(Ks,"markInstalledSkillConflicts");async function ce(e){let t=typeof e=="function"?await e():e??[];return[...new Set(t.map(o=>o.trim()).filter(Boolean))]}a(ce,"reservedSkillNames");function Ue(e,t){let o=e.extensions.find(n=>n.id===t);if(o)return o;throw new A(`${t.replace(/^github:/,"")} is not installed.`,{code:"extension_not_installed",status:404})}a(Ue,"requireInstalled");async function ee(e){let t=Le(e,"extension_installations","registry")?.value;if(!t)return Vs();if(t.schemaVersion!==Me||!Array.isArray(t.extensions)||!t.extensions.every(wn))throw new Error("Extension registry has an unsupported format.");return Ws(t)}a(ee,"readRegistry");async function wt(e,t,o){await ge(I.join(me(e).runtime,"extension-registry"),async()=>{let n=Le(e,"extension_installations","registry"),r=o(await ee(e));It(e,"extension_installations","registry",{...r,schemaVersion:Me,updatedAt:t().toISOString()},n?.revision??null)})}a(wt,"writeRegistry");function Ws(e){return{schemaVersion:Me,updatedAt:typeof e?.updatedAt=="string"?e.updatedAt:null,extensions:Array.isArray(e?.extensions)?e.extensions.filter(wn):[]}}a(Ws,"normalizeRegistry");function Vs(){return{schemaVersion:Me,updatedAt:null,extensions:[]}}a(Vs,"emptyRegistry");function wn(e){if(!e||typeof e!="object")return!1;let t=e;return t.source==="github"&&typeof t.id=="string"&&typeof t.owner=="string"&&typeof t.repo=="string"&&typeof t.repositoryUrl=="string"&&typeof t.requestedRef=="string"&&typeof t.resolvedCommit=="string"&&Array.isArray(t.skills)}a(wn,"isStoredExtension");function Pn(e,t){if(I.isAbsolute(t)||t.split(/[\\/]/).includes(".."))throw new A(`Unsafe extension path: ${t}`,{code:"extension_unsafe_path"});let o=I.resolve(e,...t.split("/")),n=`${I.resolve(e)}${I.sep}`;if(!o.startsWith(n))throw new A(`Unsafe extension path: ${t}`,{code:"extension_unsafe_path"});return o}a(Pn,"safeDestination");function he(e,t,o){return I.join(e,"github",t,o)}a(he,"extensionDirectory");function St(e,t){let o=V(t.replace(/^github:/,""));return`${he(e,o.owner,o.repo)}.previous`}a(St,"backupDirectory");async function Pt(e,t,o){let n=t.replace(/[^a-z0-9.-]+/gi,"-");return ge(I.join(e,".locks",n),o,Fs)}a(Pt,"withExtensionLock");function At(e,t){return e.id.localeCompare(t.id)}a(At,"extensionSort");import{createHash as Ys,randomUUID as Xs}from"node:crypto";function cl(e){let t=e.explicitKey?.trim();if(t)return t;let o=e.sourceHead?.trim()||"unknown-source",n=e.targetProjectId?.trim()||"no-target-project",r=Zs(e.input).slice(0,16),s=`profile-push-run:${e.localHead}:${o}:${e.runtimeAgentId}:${n}:${r}`;return e.retry?`${s}:retry:${(e.randomId??Xs)()}`:s}a(cl,"buildHostedRunIdempotencyKey");function Zs(e){return Ys("sha256").update(xt(e)).digest("hex")}a(Zs,"hashStableJson");function xt(e){return e===void 0?"undefined":e===null||typeof e!="object"?JSON.stringify(e)??"null":Array.isArray(e)?`[${e.map(t=>xt(t)).join(",")}]`:`{${Object.entries(e).sort(([t],[o])=>t.localeCompare(o)).map(([t,o])=>`${JSON.stringify(t)}:${xt(o)}`).join(",")}}`}a(xt,"stableJsonStringify");async function fl(e,t){let o=Qs(e);if(!o)return null;let n=await t.loadProfileState();return o==="help"?ea(n):ta(n)}a(fl,"runProfileSkillCommand");function Qs(e){let t=/^\/skill(?:\s+([\s\S]*))?$/i.exec(e.trim());if(!t)return null;let o=t[1]?.trim().toLowerCase()??"";return!o||o==="list"?"list":o==="help"?"help":null}a(Qs,"readOnlyProfileSkillAction");function ea(e){return{handled:!0,action:"help",profile:e,message:["Profile skills support:","- /skill list","- /skill create <what the skill should help with>","- /skill create <skill-name>: <what the skill should help with>","- /skill create --name <skill-name> <what the skill should help with>","- /skill edit <skill-name> <change request>","","Create and edit run as normal model turns with the bundled OpenPond Skill Authoring skill. Skills may include SKILL.md plus focused scripts, references, and assets. Use an Agent when the workflow needs code, actions, durable runtime behavior, setup, or Evals."].join(`
|
|
22
|
+
`)}}a(ea,"profileSkillHelp");function ta(e){let t=e.skills.slice().sort((n,r)=>n.name.localeCompare(r.name));return{handled:!0,action:"list",message:t.length===0?"No profile skills found in the active profile.":[`Profile skills (${t.length}):`,...t.map(n=>{let r=n.validationStatus==="valid"?"valid":`invalid: ${n.validationMessages.join("; ")}`;return`- ${n.name} (${r}) ${n.path}`})].join(`
|
|
23
|
+
`),skills:t,profile:e}}a(ta,"listProfileSkills");export{Ho as a,qo as b,Ri as c,Fo as d,Go as e,xe as f,T as g,ze as h,_n as i,$n as j,Uc as k,A as l,el as m,cl as n,ve as o,Jn as p,Ca as q,ro as r,so as s,ao as t,fr as u,hr as v,mr as w,gr as x,yr as y,Ir as z,ko as A,ni as B,ri as C,si as D,ai as E,ii as F,J as G,ct as H,Cr as I,vr as J,ci as K,li as L,ui as M,di as N,Io as O,fi as P,pi as Q,hi as R,mi as S,fl as T};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{b as Re,c as Ie,e as X,j as Ee,k as ke,l as Oe,m as Ae}from"./chunk-
|
|
2
|
+
import{b as Re,c as Ie,e as X,j as Ee,k as ke,l as Oe,m as Ae}from"./chunk-KNEMKYHY.js";import{i as Pe,o as xe,q as Ce}from"./chunk-25OT6IYM.js";import{E as v,I as Te}from"./chunk-PKBU37CH.js";import{a as K,b as Se,h as ye}from"./chunk-V5BC6QT2.js";import{Cd as O,Fd as j,Gd as re,I as k,J as te,M as N,N as H,a as F}from"./chunk-SBBXUZWL.js";import{$a as L,Ra as me,Sa as ge,Ua as Y,X as oe,Xa as he,Y as ie,_a as fe,db as ve,fb as we,gb as be,ja as ae,la as ue,ma as le,na as ce,oa as pe,qa as de,v as _}from"./chunk-QK2GLRCY.js";import{b as o}from"./chunk-ES2ISFJC.js";import{c as ne,d as q,f as se,h as M}from"./chunk-H7IWJN7L.js";import{a as u}from"./chunk-FTQLQJQV.js";import{promises as Q}from"node:fs";import it from"node:os";import at from"node:path";import{createServer as ut}from"node:http";import{randomBytes as lt}from"node:crypto";var Qe=o.discriminatedUnion("op",[o.strictObject({op:o.literal("set"),path:o.array(o.string().min(1)).min(1),value:o.unknown()}),o.strictObject({op:o.literal("unset"),path:o.array(o.string().min(1)).min(1)})]),et=o.discriminatedUnion("action",[o.strictObject({action:o.literal("patch"),expectedRevision:o.string(),operations:o.array(Qe).max(100)}),o.strictObject({action:o.literal("replace"),expectedRevision:o.string(),text:o.string().max(1048576)}),o.strictObject({action:o.literal("validate"),text:o.string().max(1048576)}),o.strictObject({action:o.literal("restore"),expectedRevision:o.string(),revision:o.string()}),o.strictObject({action:o.literal("trust"),root:o.string(),accountId:o.string(),trusted:o.boolean()}),o.strictObject({action:o.literal("client-state"),owner:o.string(),patch:ve,importOnly:o.boolean().optional()})]);function _e(n){let e=null;async function t(s,i){let a=M(n).config,l=null,c=null,p=null;try{l=await ie(a),p=await L(n,{projectRoot:s,accountId:i}),s||(e=p)}catch(b){c=q(b,a)}let h=p??(s?null:e);return{path:a,text:l,rawRevision:oe(l),issue:c,effective:h,usingLastValid:!p&&!!h,applies:"next_turn",recoverableRevisions:await ue(n),clientState:c?null:await we(n)}}u(t,"status");async function r(s){let i=et.parse(s);return i.action==="validate"?{valid:!0,document:ae(i.text,M(n).config)}:(i.action==="patch"&&await de(n,i.expectedRevision,i.operations),i.action==="replace"&&await le(n,i.expectedRevision,i.text),i.action==="restore"&&await ce(n,i.revision,i.expectedRevision),i.action==="trust"&&await fe(n,i.root,i.accountId,i.trusted),i.action==="client-state"?be(n,i.owner,i.patch,i.importOnly):t())}return u(r,"mutate"),{status:t,mutate:r,schema:pe}}u(_e,"createConfigurationPayloads");import{Buffer as He}from"node:buffer";var V={"Access-Control-Allow-Headers":"authorization, content-type, x-openpond-team-id","Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS"},tt=25*1024*1024,B=class extends Error{constructor(t,r,s){super(s);this.status=t;this.code=r;this.name="HttpBodyError"}status;code;static{u(this,"HttpBodyError")}};function Ue(n,e,t={}){for(let[s,i]of Object.entries(V))e.setHeader(s,i);let r=qe(n.headers.origin);return r?(e.setHeader("Vary",ot(e.getHeader("Vary"))),rt(r,t)?(e.setHeader("Access-Control-Allow-Origin",r),{allowed:!0,origin:r}):{allowed:!1,origin:r}):{allowed:!0,origin:null}}u(Ue,"applyCorsHeaders");function rt(n,e={}){if(n==="null")return!0;let t=Me(n);return t?st(t)?!0:new Set((e.allowedOrigins??[]).map(s=>s?Me(s):null).filter(s=>!!s)).has(t):!1}u(rt,"isAllowedCorsOrigin");function I(n,e,t){n.writeHead(e,{"Content-Type":"application/json",...V}),n.end(JSON.stringify(t))}u(I,"sendJson");function Ft(n,e,t){n.writeHead(e,{"Content-Type":"text/plain; charset=utf-8",...V}),n.end(t)}u(Ft,"sendText");function jt(n,e,t,r){n.writeHead(e,{"Content-Type":r,"Content-Length":String(t.byteLength),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff",...V}),n.end(t)}u(jt,"sendBinary");async function Z(n,e={}){let t=e.maxBytes??tt,r=qe(n.headers["content-type"]),s=[],i=0;for await(let l of n){let c=He.from(l);if(i+=c.byteLength,i>t)throw new B(413,"request_body_too_large",`JSON request body exceeds ${t} bytes.`);s.push(c)}let a=He.concat(s).toString("utf8").trim();if(!a)return{};if(!nt(r))throw new B(415,"unsupported_media_type","JSON request body requires Content-Type: application/json.");try{return JSON.parse(a)}catch{throw new B(400,"invalid_json","Request body is not valid JSON.")}}u(Z,"readJson");function Ne(n,e,t){let r=n.headers.authorization;return(typeof r=="string"&&r.startsWith("Bearer ")?r.slice(7):null)===t}u(Ne,"hasAuth");function qe(n){return Array.isArray(n)?n[0]??null:n??null}u(qe,"headerValue");function nt(n){if(!n)return!1;let e=n.split(";")[0]?.trim().toLowerCase();return e==="application/json"||!!e?.endsWith("+json")}u(nt,"isJsonContentType");function Me(n){try{let e=new URL(n);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}u(Me,"normalizeOrigin");function st(n){let e=new URL(n);return e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="::1"||e.hostname==="[::1]"}u(st,"isLoopbackOrigin");function ot(n){let t=(Array.isArray(n)?n.join(", "):n?String(n):"").split(",").map(r=>r.trim()).filter(Boolean);return t.some(r=>r.toLowerCase()==="origin")||t.push("Origin"),t.join(", ")}u(ot,"appendVaryOrigin");function Be(n){return`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>OpenPond recovery</title>
|
|
3
3
|
<style nonce="${n}">body{font:16px system-ui;background:#171819;color:#eee;max-width:850px;margin:6vh auto;padding:24px}textarea{box-sizing:border-box;width:100%;min-height:280px;background:#222;color:#eee;padding:14px;border:1px solid #777;border-radius:8px;font:14px monospace}button,input,select{font:inherit;margin:6px;padding:8px}pre{white-space:pre-wrap}code{overflow-wrap:anywhere}button{cursor:pointer}p{line-height:1.5}</style>
|
|
4
4
|
<h1>OpenPond needs a storage repair</h1><p id="issue" role="alert">Loading recovery details\u2026</p><p><code id="file"></code></p>
|
|
5
5
|
<p id="action"></p><p>Migration backups and the source installation remain available. Execution services are stopped while recovery is open.</p>
|
|
@@ -20,7 +20,7 @@ for(const [id,action] of [['preview','preview'],['migrate','migrate'],['restart'
|
|
|
20
20
|
el('diagnostics').onclick=()=>{if(!state)return;const blob=new Blob([JSON.stringify({issue:state.issue,migration:state.migration,config:{path:state.config.path,rawRevision:state.config.rawRevision,issue:state.config.issue}},null,2)],{type:'application/json'});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='openpond-recovery-diagnostics.json';a.click();URL.revokeObjectURL(a.href)};
|
|
21
21
|
el('retry').onclick=async()=>{try{await request('/v1/recovery',{action:'retry'});message('Starting OpenPond\u2026');const timer=setInterval(async()=>{try{const h=await(await fetch('/health')).json();if(!h.recovery){clearInterval(timer);const next=new URLSearchParams(location.hash.slice(1)).get('returnTo');if(next){const u=new URL(next);if(['localhost','127.0.0.1','[::1]'].includes(u.hostname)){location.replace(u.toString());return}}location.reload();}}catch{}},500)}catch(e){message(e)}};
|
|
22
22
|
(async()=>{const params=new URLSearchParams(location.hash.slice(1));token=params.get('openpondToken')||'';if(!token&&window.openpond?.getConnection)token=(await window.openpond.getConnection()).token;if(!token){message('Open the authenticated recovery URL from the launcher.');return}await load()})().catch(message);
|
|
23
|
-
</script></html>`}u(Be,"startupRecoveryPage");var ct=o.strictObject({action:o.enum(["preview","migrate","restart","retry"]),sourceAppHome:o.string().optional(),sourceConfig:o.string().optional(),resolutions:pe.optional()});function De(n){return n instanceof te&&/^(PRIVATE_STORAGE_|UNSAFE_STORAGE_|INVALID_CONFIG|CONFIG_|MIGRATION_|SOURCE_CHANGED_|CREDENTIAL_|UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|INVALID_ACCOUNT_|MISSING_INSTRUCTION_|INVALID_PROFILE_|DATABASE_RECOVERY_)/.test(n.issue.code)}u(De,"isRecoverableStartupError");async function Fe(n,e,t){let r=/^(UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|UNSAFE_STORAGE_|PRIVATE_STORAGE_)/.test(t.issue.code),s=r?await Q.mkdtemp(at.join(it.tmpdir(),"openpond-recovery-")):n;return Re(s,async()=>{let{token:i,tokenFile:a}=await Ee(s),l=_e(n),c=t.issue,p,h=new Promise(f=>{p=f}),b=ut((f,g)=>{(async()=>{let S=new URL(f.url??"/","http://127.0.0.1");if(!Ue(f,g).allowed){I(g,403,{error:"Origin not allowed"});return}if(f.method==="OPTIONS"){I(g,204,{});return}if(f.method==="GET"&&S.pathname==="/health"){I(g,200,{ok:!0,server:"openpond-app-server",version:Se,recovery:!0});return}if(f.method==="GET"&&S.pathname==="/"){let w=lt(18).toString("base64");g.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":`default-src 'none'; script-src 'nonce-${w}'; style-src 'nonce-${w}'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'`}),g.end(Be(w));return}if(!Ne(f,S,i)){I(g,401,{error:"Unauthorized"});return}let P=!r;if(f.method==="GET"&&S.pathname==="/v1/recovery"){I(g,200,{issue:c,configEditable:P,config:r?{path:_(n).config,text:null,rawRevision:"unavailable",issue:c,recoverableRevisions:[]}:await l.status(),migration:await de(n).catch(w=>({issue:N(w,n)}))});return}if(f.method==="POST"&&S.pathname==="/v1/configuration"&&P){I(g,200,await l.mutate(await Z(f)));return}if(f.method==="POST"&&S.pathname==="/v1/recovery"){let w=ct.parse(await Z(f));if(r&&w.action!=="retry"&&w.action!=="preview")throw t;if(w.action==="restart"){I(g,200,await me(n));return}if(w.action==="preview"||w.action==="migrate"){I(g,200,await Y(n,{sourceAppHome:w.sourceAppHome,sourceConfig:w.sourceConfig,resolutions:w.resolutions,dryRun:w.action==="preview"}));return}await Y(n),await F(n),I(g,200,{ready:!0}),p();return}I(g,503,{error:`${c.message} ${c.action}`,issue:c,recovery:!0})})().catch(S=>{c=N(S,n),I(g,422,{error:`${c.message} ${c.action}`,issue:c})})});await new Promise((f,g)=>{b.once("error",g),b.listen(e,"127.0.0.1",()=>{b.off("error",g),f()})});let x=b.address().port,A=`http://127.0.0.1:${x}`;return await Ie(s,A,"startup-recovery"),{url:A,port:x,token:i,tokenFile:a,storePath:_(n).database,repaired:h,close:u(async()=>{b.closeIdleConnections(),await new Promise((f,g)=>b.close(S=>S?g(S):f())),r&&await Q.rm(s,{recursive:!0,force:!0})},"close")}}).catch(async i=>{throw r&&await Q.rm(s,{recursive:!0,force:!0}),i})}u(Fe,"startRecoveryServer");import{createHash as Ct}from"node:crypto";import{createHash as pt,randomUUID as je}from"node:crypto";var dt=o.object({updatedAt:o.string(),id:o.string().min(1)}).strict(),mt=o.object({entries:o.array(k).max(200),nextBefore:dt.nullable()}).strict(),gt=o.object({run:k,replayed:o.boolean()}).strict(),$=class{constructor(e){this.client=e}client;static{u(this,"HostedCreateImproveStorage")}async getCreateImproveRun(e){let t=await this.client.request({contractVersion:v,requestId:je(),operation:"create-improve/execute",params:{action:"get",runId:e}});return t===null?null:k.parse(t)}async listCreateImproveRuns(e={}){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit??250))),r=Array.isArray(e.state)?[...e.state]:e.state?[e.state]:[],s=[],i=null;for(;s.length<t;){let a=mt.parse(await this.client.request({contractVersion:v,requestId:je(),operation:"create-improve/execute",params:{action:"page",query:{profileId:e.profileId??null,targetKind:e.targetKind??null,targetId:e.targetId??null,state:r},before:i,limit:Math.min(50,t-s.length)}}));if(e.conversationId&&a.entries.some(l=>l.scope.conversationId!==e.conversationId))throw new Error("Hosted Create/Improve page crossed its conversation scope.");if(s.push(...a.entries),!a.nextBefore)break;if(a.entries.length===0||i&&(a.nextBefore.updatedAt>i.updatedAt||a.nextBefore.updatedAt===i.updatedAt&&a.nextBefore.id>=i.id))throw new Error("Hosted Create/Improve cursor did not advance.");i=a.nextBefore}return s}async upsertCreateImproveRun(e){let t=k.parse(e),r=`create-improve:${pt("sha256").update(JSON.stringify(t)).digest("hex")}`,s=await this.client.request({contractVersion:v,requestId:r,operation:"create-improve/execute",params:{action:"put",run:t}});return k.parse(o.object({run:o.unknown()}).strict().parse(s).run)}async mutateCreateImproveRun(e,t){let r=we.parse(e),s=await this.getCreateImproveRun(r.runId);if(!s)throw new Error(`Create/Improve run not found: ${r.runId}`);if(s.appliedActionIds.includes(r.actionId))return{run:s,replayed:!0};if(s.revision!==r.expectedRevision)throw new Error(`Create/Improve run changed from revision ${r.expectedRevision} to ${s.revision}. Refresh and try again.`);let i=k.parse(t(s));if(i.id!==s.id||i.revision!==s.revision+1||!i.appliedActionIds.includes(r.actionId))throw new Error("Create/Improve mutation must preserve identity, advance one revision and record its action.");return gt.parse(await this.client.request({contractVersion:v,requestId:r.actionId,operation:"create-improve/execute",params:{action:"mutate",mutation:r,next:i}}))}};import{randomUUID as ft}from"node:crypto";async function D(n,e){let t=n;for(;;)try{return await e(t)}catch(r){if(!ht(r)||t<=1)throw r;t=Math.max(1,Math.floor(t/2))}}u(D,"hostedBoundedPage");function ht(n){return n instanceof Error?n.message==="Host storage response is too large."||n.message==="Host storage request failed: host_storage_response_too_large":!1}u(ht,"isOversizeResponse");var vt=o.object({entries:o.array(o.object({sequence:o.number().int().positive(),event:j})).max(200),totalMatchingEvents:o.number().int().nonnegative(),remainingMatchingEvents:o.number().int().nonnegative()}).strict(),W=class{constructor(e){this.client=e}client;static{u(this,"HostedRuntimeEventStorage")}async runtimeEventsForSession(e,t={}){let r=t.limit==null?1e4:Math.max(0,Math.trunc(t.limit));if(r===0)return[];let s=Math.min(r,1e4),i=[],a=Math.max(0,t.afterSequence??0),l=0,c=t.names?new Set(t.names):null;for(;i.length<=s;){let p=await this.runtimeEventPageRows({sessionId:e,afterSequence:a,beforeSequence:null,limit:Math.min(200,s+1-i.length),excludeReasoningDeltas:t.excludeReasoningDeltas});for(let h of p.entries){if(h.sequence<=a)throw new Error("Host event cursor did not advance.");if(a=h.sequence,l+=1,l>1e4)throw new Error("Hosted runtime event scan exceeds 10,000 rows; use a narrower query.");(!c||c.has(h.event.name))&&i.push(h.event)}if(p.entries.length===0||p.remainingMatchingEvents<=p.entries.length)break}if(i.length>s||t.limit==null&&r===1e4&&i.length===s)throw new Error("Hosted runtime event read exceeds 10,000 rows; use a bounded cursor query.");return i}async persistedRuntimeEventsForSession(e,t={}){return this.runtimeEventsForSession(e,t)}async appendRuntimeEvent(e){let t=j.parse(e),r=await this.client.request({contractVersion:v,requestId:t.id,operation:"event/append",params:{event:t}});return o.object({event:j}).strict().parse(r).event}async runtimeEventPageRows(e){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit))),r=Math.max(0,Math.trunc(e.afterSequence)),s=e.beforeSequence,i=[],a=0,l=0;for(;i.length<t;){let c=Math.min(200,t-i.length),p=await D(c,async h=>vt.parse(await this.client.request({contractVersion:v,requestId:`event-page:${ft()}`,operation:"events/page",params:{sessionId:e.sessionId,afterSequence:r,beforeSequence:s,limit:h,...e.excludeReasoningDeltas?{excludeReasoningDeltas:!0}:{}}})));if(i.length===0&&(a=p.totalMatchingEvents,l=p.remainingMatchingEvents),i=s===null?[...i,...p.entries]:[...p.entries,...i],p.entries.length===0||p.remainingMatchingEvents<=p.entries.length)break;if(s===null){let h=p.entries.at(-1).sequence;if(h<=r)throw new Error("Host event cursor did not advance.");r=h}else{let h=p.entries[0].sequence;if(h>=s)throw new Error("Host event cursor did not advance.");s=h}}return{entries:i,totalMatchingEvents:a,remainingMatchingEvents:l}}};import{randomUUID as y}from"node:crypto";var Le=o.object({revision:o.number().int().min(1),session:q}).strict(),Ve=o.object({revision:o.number().int().min(1),turn:M}).strict(),wt=o.object({sessions:o.array(q).max(200),nextAfterId:o.string().min(1).nullable()}).strict(),bt=o.object({turns:o.array(M).max(200),nextBeforeSortIndex:o.number().int().nonnegative().nullable()}).strict(),G=class{constructor(e){this.client=e}client;static{u(this,"HostedSessionStorage")}async count(){let e=await this.client.request({contractVersion:v,requestId:y(),operation:"session/count",params:{}});return o.object({count:o.number().int().nonnegative()}).strict().parse(e).count}async get(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"session/get",params:{sessionId:e}});return t===null?null:Le.parse(t)}async sessionCount(){return this.count()}async sessionShells(){let e=[],t=null;do{let r=await D(Math.min(10,1001-e.length),async s=>wt.parse(await this.client.request({contractVersion:v,requestId:y(),operation:"session/page",params:{afterId:t,limit:s}})));if(e.push(...r.sessions),e.length>1e3)throw new Error("Hosted session list exceeds 1,000 rows; use a scoped page query.");if(r.nextAfterId!==null&&(r.sessions.length===0||t!==null&&r.nextAfterId<=t))throw new Error("Host session cursor did not advance.");t=r.nextAfterId}while(t!==null);return e}async getSession(e){return(await this.get(e))?.session??null}async insertSessionAtFront(e){await this.put({session:e,expectedRevision:null,requestId:y()})}async updateSession(e,t){let r=await this.get(e);if(!r)return null;let s=q.parse(t(r.session));if(s.id!==e)throw new Error("A session update cannot change its identity.");return(await this.put({session:s,expectedRevision:r.revision,requestId:y()})).session}async put(e){let t=q.parse(e.session);return Le.parse(await this.client.request({contractVersion:v,requestId:e.requestId,operation:"session/put",params:{sessionId:t.id,expectedRevision:e.expectedRevision,session:t}}))}async readTurn(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/get",params:{turnId:e}});return t===null?null:Ve.parse(t)}async getTurn(e){return(await this.readTurn(e))?.turn??null}async turnsForSession(e,t=50){let r=Math.max(1,Math.min(1e3,Math.trunc(t))),s=[],i=null;for(;s.length<r;){let a=await D(Math.min(200,r-s.length),async l=>bt.parse(await this.client.request({contractVersion:v,requestId:y(),operation:"turn/page",params:{sessionId:e,beforeSortIndex:i,limit:l}})));if(s.push(...a.turns),a.nextBeforeSortIndex===null)break;if(i!==null&&a.nextBeforeSortIndex>=i)throw new Error("Host turn cursor did not advance.");i=a.nextBeforeSortIndex}return s}async countTurnsForSession(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/count",params:{sessionId:e}});return o.object({count:o.number().int().nonnegative()}).strict().parse(t).count}async hasSubagentParentWakeTurn(e,t){return await this.wakeCount(e,"messageId",t)>0}async countSubagentParentWakeTurns(e,t){return this.wakeCount(e,"fromRunId",t)}async latestAssistantTextForSession(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"events/latestAssistantText",params:{sessionId:e}});return o.object({text:o.string().nullable()}).strict().parse(t).text}async wakeCount(e,t,r){let s=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/wakeCount",params:{sessionId:e,key:t,value:r}});return o.object({count:o.number().int().nonnegative()}).strict().parse(s).count}async latestTurnForSession(e,t){let r=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/latest",params:{sessionId:e,status:t??null}});return r===null?null:M.parse(r)}async latestPersistedTurnForSession(e,t){return this.latestTurnForSession(e,t)}async insertTurn(e){await this.putTurn({turn:e,expectedRevision:null,requestId:y()})}async updateTurn(e,t){let r=await this.readTurn(e);if(!r)return null;let s=M.parse(t(r.turn));if(s.id!==e||s.sessionId!==r.turn.sessionId)throw new Error("A turn update cannot change its identity.");return(await this.putTurn({turn:s,expectedRevision:r.revision,requestId:y()})).turn}async putTurn(e){let t=M.parse(e.turn);return Ve.parse(await this.client.request({contractVersion:v,requestId:e.requestId,operation:"turn/put",params:{sessionId:t.sessionId,turnId:t.id,expectedRevision:e.expectedRevision,turn:t}}))}};import{createHash as St,randomUUID as yt}from"node:crypto";var C=o.object({ok:o.literal(!0)}).strict(),J=o.array(O),Rt=o.array(o.string()),It=o.object({turnId:o.string(),run:H}).strict(),Tt=o.object({inputs:o.array(O).max(10),hasMore:o.boolean()}).strict(),Pt=o.object({items:o.array(L).max(10),hasMore:o.boolean()}).strict(),xt=o.object({items:o.array(o.string()).max(200),hasMore:o.boolean()}).strict();function z(n,e){return`inbox:${n}:${St("sha256").update(JSON.stringify(e)).digest("hex")}`}u(z,"retryKey");var U=class{constructor(e){this.client=e}client;static{u(this,"HostedTaskInboxStorage")}async call(e,t,r=yt()){let s=await this.client.request({contractVersion:v,requestId:r,operation:"task-inbox/execute",params:e});return t.parse(s)}async inputPages(e,t=Number.MAX_SAFE_INTEGER){let r=[],s=0;for(;r.length<t;){let i=await this.call(e(s),Tt);for(let a of i.inputs){if(a.sequence<=s)throw new Error("Host task input cursor did not advance.");if(s=a.sequence,r.push(a),r.length>=t)break}if(!i.hasMore)return r;if(i.inputs.length===0)throw new Error("Host task input page made no progress.")}return r}async recoverTaskInboxOwners(e){return this.call({action:"recoverTaskInboxOwners",ownerId:e},o.array(o.object({sessionId:o.string(),turnId:o.string()}).strict()))}async hasTaskCompletion(e){return this.call({action:"hasTaskCompletion",turnId:e},o.boolean())}async taskInboxSnapshot(e){let t=await this.call({action:"taskInboxSnapshot",sessionId:e},be),[r,s]=await Promise.all([this.inputPages(i=>({action:"taskInboxSnapshotInputs",sessionId:e,afterSequence:i})),this.taskWaitsForSession(e)]);return{...t,inputs:r,waits:s}}async declareTaskWork(e,t,r,s){await this.call({action:"declareTaskWork",sessionId:e,turnId:t,ownerId:r,areas:s},C)}async taskWorkAreas(e){return this.call({action:"taskWorkAreas",sessionId:e},Rt)}async admitTaskInput(e){return this.call({action:"admitTaskInput",input:e},O)}async admitTaskInputs(e){return this.call({action:"admitTaskInputs",inputs:e},J)}async rejectTaskInput(e,t){await this.call({action:"rejectTaskInput",id:e,error:t},C)}async getTaskInput(e){return this.call({action:"getTaskInput",id:e},O.nullable())}async taskInputsForSession(e,t={}){let r=Math.max(1,Math.min(500,t.limit??128)),s=[],i=t.afterSequence??0;for(;s.length<r;){let a=Math.min(10,r-s.length),l=await this.call({action:"taskInputsForSession",sessionId:e,query:{afterSequence:i,pendingOnly:t.pendingOnly,limit:a}},J);if(!l.length)break;for(let c of l){if(c.sequence<=i)throw new Error("Host task input cursor did not advance.");i=c.sequence,s.push(c)}if(l.length<a)break}return s}async mutateTaskInput(e,t,r){return this.call({action:"mutateTaskInput",sessionId:e,inputId:t,change:r},O,z("mutate",{sessionId:e,inputId:t,change:r}))}async openTaskInboxTurn(e,t,r){await this.call({action:"openTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C,z("open",{sessionId:e,turnId:t,ownerId:r}))}async renewTaskInboxTurn(e,t,r){await this.call({action:"renewTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C)}async pendingTaskInputs(e,t){return this.inputPages(r=>({action:"pendingTaskInputs",sessionId:e,turnId:t,afterSequence:r}))}async taskAssignmentInputs(e){return this.inputPages(t=>({action:"taskAssignmentInputs",turnId:e,afterSequence:t}))}async pauseTaskInboxTurn(e,t,r){await this.call({action:"pauseTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C)}async includeTaskInputs(e,t,r,s){return this.call({action:"includeTaskInputs",sessionId:e,turnId:t,ownerId:r,requestId:s},J,z("include",{sessionId:e,turnId:t,ownerId:r,requestId:s}))}async settleTaskInputRequest(e,t){await this.call({action:"settleTaskInputRequest",requestId:e,outcome:t},C)}async sealTaskInboxTurn(e,t,r){return this.call({action:"sealTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},o.boolean())}async sealNativeTaskInboxTurn(e,t,r){return this.call({action:"sealNativeTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},J)}async closeTaskInboxTurn(e,t,r,s){await this.call({action:"closeTaskInboxTurn",sessionId:e,turnId:t,ownerId:r,outcome:s},C)}async taskInboxPaused(e){return this.call({action:"taskInboxPaused",sessionId:e},o.boolean())}async reserveTaskFollowup(e,t,r){return this.call({action:"reserveTaskFollowup",sessionId:e,turnId:t,ownerId:r},O.nullable(),z("reserve",{sessionId:e,turnId:t,ownerId:r}))}async taskInboxWakeTargets(){let e=[],t="";for(;;){let r=await this.call({action:"taskInboxWakeTargets",afterSessionId:t},xt);for(let s of r.items){if(s<=t)throw new Error("Host task wake cursor did not advance.");t=s,e.push(s)}if(!r.hasMore)return e;if(!r.items.length)throw new Error("Host task wake page made no progress.")}}async createTaskWait(e){return this.call({action:"createTaskWait",value:e},L)}async settleTaskWait(e,t){return this.call({action:"settleTaskWait",id:e,state:t},L)}async taskWaitsForSession(e){let t=[],r="";for(;;){let s=await this.call({action:"taskWaitsForSession",sessionId:e,afterId:r},Pt);for(let i of s.items){if(i.id<=r)throw new Error("Host task wait cursor did not advance.");r=i.id,t.push(i)}if(!s.hasMore)return t;if(!s.items.length)throw new Error("Host task wait page made no progress.")}}async commitSubagentCompletion(e,t){await this.call({action:"commitSubagentCompletion",value:e,turnId:t},C)}async pendingTaskCompletions(e=""){let t=[],r=e;for(;t.length<100;){let s=await this.call({action:"pendingTaskCompletions",afterTurnId:r},o.array(It).max(10));for(let i of s){if(i.turnId<=r)throw new Error("Host task completion cursor did not advance.");r=i.turnId,t.push(i)}if(s.length<10)break}return t}async settleTaskCompletion(e,t){await this.call({action:"settleTaskCompletion",turnId:e,inputId:t},C)}async upsertSubagentRun(e){return this.call({action:"upsertSubagentRun",value:H.parse(e)},H)}async getSubagentRun(e){return this.call({action:"getSubagentRun",id:e},H.nullable())}async listSubagentRuns(e={}){let r=[],s="",i=e.status?Array.isArray(e.status)?[...e.status]:[e.status]:null;for(;;){let a=await this.call({action:"listSubagentRuns",query:{parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,status:i,afterId:s,limit:10}},o.array(H).max(10));for(let l of a){if(l.id<=s)throw new Error("Host subagent run cursor did not advance.");if(s=l.id,r.push(l),r.length>1e3)throw new Error("Hosted subagent run list exceeds 1,000 rows; use a narrower session or status query.")}if(a.length<10)break}return r.sort((a,l)=>(l.updatedAt??l.createdAt).localeCompare(a.updatedAt??a.createdAt)),e.limit===void 0?r:r.slice(0,Math.max(1,Math.min(1e3,e.limit)))}async listActiveSubagentRuns(e={}){return this.listSubagentRuns({...e,status:e.status??["queued","running","needs_resume"]})}};var ee=class extends U{static{u(this,"HostedTurnRepository")}sessions;events;approvals;usage;createImprove;constructor(e){super(e),this.sessions=new G(e),this.events=new W(e),this.approvals=new ke(e),this.usage=new Oe(e),this.createImprove=new $(e)}sessionShells(){return this.sessions.sessionShells()}sessionCount(){return this.sessions.sessionCount()}getSession(e){return this.sessions.getSession(e)}insertSessionAtFront(e){return this.sessions.insertSessionAtFront(e)}updateSession(e,t){return this.sessions.updateSession(e,t)}getTurn(e){return this.sessions.getTurn(e)}insertTurn(e){return this.sessions.insertTurn(e)}updateTurn(e,t){return this.sessions.updateTurn(e,t)}latestTurnForSession(e,t){return this.sessions.latestTurnForSession(e,t)}latestPersistedTurnForSession(e,t){return this.sessions.latestPersistedTurnForSession(e,t)}turnsForSession(e,t){return this.sessions.turnsForSession(e,t)}countTurnsForSession(e){return this.sessions.countTurnsForSession(e)}hasSubagentParentWakeTurn(e,t){return this.sessions.hasSubagentParentWakeTurn(e,t)}countSubagentParentWakeTurns(e,t){return this.sessions.countSubagentParentWakeTurns(e,t)}latestAssistantTextForSession(e){return this.sessions.latestAssistantTextForSession(e)}appendRuntimeEvent(e){return this.events.appendRuntimeEvent(e)}runtimeEventsForSession(e,t){return this.events.runtimeEventsForSession(e,t)}persistedRuntimeEventsForSession(e,t){return this.events.persistedRuntimeEventsForSession(e,t)}runtimeEventPageRows(e){return this.events.runtimeEventPageRows(e)}getApproval(e){return this.approvals.getApproval(e)}async upsertApproval(e){let t=await this.approvals.readApproval(e.id);t&&JSON.stringify(t.approval)===JSON.stringify(e)||await this.approvals.putApproval({approval:e,expectedRevision:t?.revision??null,requestId:`approval:${Ct("sha256").update(JSON.stringify({approval:e,revision:t?.revision??null})).digest("hex")}`})}upsertModelUsageRecord(e){return this.usage.upsertModelUsageRecord(e)}listModelUsageRecords(e){return this.usage.listModelUsageRecords(e)}getCreateImproveRun(e){return this.createImprove.getCreateImproveRun(e)}listCreateImproveRuns(e){return this.createImprove.listCreateImproveRuns(e)}upsertCreateImproveRun(e){return this.createImprove.upsertCreateImproveRun(e)}mutateCreateImproveRun(e,t){return this.createImprove.mutateCreateImproveRun(e,t)}};function $e(n){return new ee(n)}u($e,"createHostedRuntimeCoreStorage");function We(n=process.env){let e=n.OPENPOND_API_KEY?.trim(),t=n.OPENPOND_OPCHAT_API_URL?.trim(),r=n.OPENPOND_HOSTED_MODEL_ID?.trim();if(!e||!t||!r)throw new Error("Hosted model stream requires a host credential, API URL, and admitted model.");let s=new URL(t);if(s.protocol!=="https:"||s.username||s.password||s.search||s.hash)throw new Error("Hosted model stream API URL is invalid.");return u(async function*(a){if(a.model!==r)throw new Error("Hosted model selection changed outside host admission.");yield*Pe({...a,apiBaseUrl:s.toString(),token:e,model:r})},"streamHostedModel")}u(We,"createHostedModelStreamFromEnvironment");import{existsSync as Et}from"node:fs";import T from"node:path";import{fileURLToPath as kt}from"node:url";var Ge=T.dirname(kt(import.meta.url));function R(n,e,t){let r=n[e+1];if(!r||r.startsWith("--"))throw new Error(`${t} requires a value.`);return r}u(R,"requireValue");function Je(n,e){let t=Number.parseInt(n,10);if(!Number.isFinite(t)||t<0||t>65535)throw new Error(`${e} must be a port from 0 to 65535.`);return t}u(Je,"parsePort");function Ke(n){let e="serve",t=K,r=17874,s=null,i=!1,a=!1,l=null,c,p,h=null,b=null,x=null,A=null,f,g="sqlite_bundle",S=0,P=n[0];if(P&&!P.startsWith("-")){if(P==="serve"||P==="server")e="serve";else if(P==="app-server")e="app-server";else if(P==="web")e="web";else{if(P==="help")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:a,storeDir:l,runtimeStorage:g,help:!0};throw new Error(`Unknown command: ${P}`)}S=1}for(let m=S;m<n.length;m+=1){let d=n[m];if(d==="--help"||d==="-h")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:a,storeDir:l,runtimeStorage:g,help:!0};if(d==="--listen"){let E=ye(R(n,m,d));t=E.host,r=Je(String(E.port),d),m+=1}else if(d==="--hostname"||d==="--host")t=R(n,m,d),m+=1;else if(d==="--port")r=Je(R(n,m,d),d),m+=1;else if(d==="--web-root")s=T.resolve(R(n,m,d)),m+=1;else if(d==="--source-browser-state")p=T.resolve(R(n,m,d)),m+=1;else{if(d==="--store-dir")throw new Error("--store-dir has been replaced by --home. Use --home <directory> or OPENPOND_HOME.");if(d==="--home")l=T.resolve(R(n,m,d)),m+=1;else if(d==="--hosted-cache-home")c=T.resolve(R(n,m,d)),m+=1;else if(d==="--runtime-storage"){if(R(n,m,d)!=="hosted-postgres")throw new Error("Unsupported app-server runtime storage.");g="hosted_postgres",m+=1}else if(d==="--profile-source-root")h=T.resolve(R(n,m,d)),m+=1;else if(d==="--profile-repository-id")b=R(n,m,d),m+=1;else if(d==="--profile-id")x=R(n,m,d),m+=1;else if(d==="--profile-revision")A=R(n,m,d),m+=1;else if(d==="--hosted-profile-release"){if(f)throw new Error("Duplicate hosted Profile release descriptor.");let E=R(n,m,d);if(E.length>16e3||!/^[A-Za-z0-9_-]+$/.test(E))throw new Error("Invalid hosted Profile release descriptor.");try{f=Ae.parse(JSON.parse(Buffer.from(E,"base64url").toString("utf8")))}catch{throw new Error("Invalid hosted Profile release descriptor.")}m+=1}else if(d==="--open-browser")i=!0;else if(d==="--print-access-url")a=!0;else throw new Error(`Unknown option: ${d}`)}}if(i&&a)throw new Error("--open-browser and --print-access-url cannot be used together.");if(e!=="web"&&(i||a))throw new Error("Browser options are only available in web mode.");let w=[h,b,x,A].filter(Boolean).length;if(w&&(w!==4||e!=="app-server"))throw new Error("Profile source flags require app-server mode and --profile-source-root, --profile-repository-id, --profile-id, and --profile-revision together.");if(g==="hosted_postgres"&&(e!=="app-server"||l||w))throw new Error("Hosted Postgres app-server cannot use --home or local Profile source flags.");if(f&&g!=="hosted_postgres")throw new Error("Hosted Profile release requires hosted Postgres app-server mode.");if(c&&g!=="hosted_postgres")throw new Error("Hosted cache home requires hosted Postgres mode.");return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:a,storeDir:l,runtimeStorage:g,sourceBrowserState:p,...w?{profileSource:{repoPath:h,repositoryId:b,profileId:x,sourceRevision:A}}:{},...f?{admittedProfileRelease:f}:{},...c?{hostedCacheHome:c}:{},help:!1}}u(Ke,"parseCliArgs");function Ot(){return[process.env.OPENPOND_WEB_ROOT,T.resolve(process.cwd(),"apps/web/dist"),T.resolve(Ge,"../../web/dist"),T.resolve(process.cwd(),"web"),T.resolve(Ge,"../web")].filter(n=>!!n)}u(Ot,"defaultWebRootCandidates");function At(n){let e=n?[n]:Ot();for(let t of e){let r=T.resolve(t);if(Et(T.join(r,"index.html")))return r}return null}u(At,"resolveWebRoot");function _t(n){let e=n==="0.0.0.0"||n==="::"?"127.0.0.1":n;return e.includes(":")&&!e.startsWith("[")?`[${e}]`:e}u(_t,"formatHostForUrl");function Ht(n){return`http://${_t(n.status.host)}:${n.status.port}`}u(Ht,"browserBaseUrl");function Mt(n,e){let t=new URL(n),r=new URLSearchParams;return r.set("openpondServerUrl",n),r.set("openpondToken",e),t.hash=r.toString(),t.toString()}u(Mt,"tokenizedWebUrl");async function ze(n,e=Ce){let t=Mt(n.baseUrl,n.token);if(n.printAccessUrl)return{stdout:[`OpenPond access URL: ${t}`],stderr:[]};if(!n.openBrowser)return{stdout:[`OpenPond web UI: ${n.baseUrl}`],stderr:[]};let r=await e(t);return r.opened?{stdout:[`Opened OpenPond in your browser: ${n.baseUrl}`],stderr:[]}:{stdout:[`OpenPond access URL: ${t}`],stderr:[`Could not open the system browser: ${r.error}`]}}u(ze,"resolveWebLaunchMessages");function Xe(){console.log(`Usage:
|
|
23
|
+
</script></html>`}u(Be,"startupRecoveryPage");var ct=o.strictObject({action:o.enum(["preview","migrate","restart","retry"]),sourceAppHome:o.string().optional(),sourceConfig:o.string().optional(),resolutions:me.optional()});function De(n){return n instanceof ne&&/^(PRIVATE_STORAGE_|UNSAFE_STORAGE_|INVALID_CONFIG|CONFIG_|MIGRATION_|SOURCE_CHANGED_|CREDENTIAL_|UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|INVALID_ACCOUNT_|MISSING_INSTRUCTION_|INVALID_PROFILE_|DATABASE_RECOVERY_)/.test(n.issue.code)}u(De,"isRecoverableStartupError");async function Fe(n,e,t){let r=/^(UNSUPPORTED_STORAGE_|INVALID_MIGRATION_|UNSAFE_STORAGE_|PRIVATE_STORAGE_)/.test(t.issue.code),s=r?await Q.mkdtemp(at.join(it.tmpdir(),"openpond-recovery-")):n;return Re(s,async()=>{let{token:i,tokenFile:a}=await Ee(s),l=_e(n),c=t.issue,p,h=new Promise(f=>{p=f}),b=ut((f,g)=>{(async()=>{let S=new URL(f.url??"/","http://127.0.0.1");if(!Ue(f,g).allowed){I(g,403,{error:"Origin not allowed"});return}if(f.method==="OPTIONS"){I(g,204,{});return}if(f.method==="GET"&&S.pathname==="/health"){I(g,200,{ok:!0,server:"openpond-app-server",version:Se,recovery:!0});return}if(f.method==="GET"&&S.pathname==="/"){let w=lt(18).toString("base64");g.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":`default-src 'none'; script-src 'nonce-${w}'; style-src 'nonce-${w}'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'`}),g.end(Be(w));return}if(!Ne(f,S,i)){I(g,401,{error:"Unauthorized"});return}let P=!r;if(f.method==="GET"&&S.pathname==="/v1/recovery"){I(g,200,{issue:c,configEditable:P,config:r?{path:M(n).config,text:null,rawRevision:"unavailable",issue:c,recoverableRevisions:[]}:await l.status(),migration:await ge(n).catch(w=>({issue:q(w,n)}))});return}if(f.method==="POST"&&S.pathname==="/v1/configuration"&&P){I(g,200,await l.mutate(await Z(f)));return}if(f.method==="POST"&&S.pathname==="/v1/recovery"){let w=ct.parse(await Z(f));if(r&&w.action!=="retry"&&w.action!=="preview")throw t;if(w.action==="restart"){I(g,200,await he(n));return}if(w.action==="preview"||w.action==="migrate"){I(g,200,await Y(n,{sourceAppHome:w.sourceAppHome,sourceConfig:w.sourceConfig,resolutions:w.resolutions,dryRun:w.action==="preview"}));return}await Y(n),await L(n),I(g,200,{ready:!0}),p();return}I(g,503,{error:`${c.message} ${c.action}`,issue:c,recovery:!0})})().catch(S=>{c=q(S,n),I(g,422,{error:`${c.message} ${c.action}`,issue:c})})});await new Promise((f,g)=>{b.once("error",g),b.listen(e,"127.0.0.1",()=>{b.off("error",g),f()})});let x=b.address().port,A=`http://127.0.0.1:${x}`;return await Ie(s,A,"startup-recovery"),{url:A,port:x,token:i,tokenFile:a,storePath:M(n).database,repaired:h,close:u(async()=>{b.closeIdleConnections(),await new Promise((f,g)=>b.close(S=>S?g(S):f())),r&&await Q.rm(s,{recursive:!0,force:!0})},"close")}}).catch(async i=>{throw r&&await Q.rm(s,{recursive:!0,force:!0}),i})}u(Fe,"startRecoveryServer");import{createHash as Ct}from"node:crypto";import{createHash as pt,randomUUID as je}from"node:crypto";var dt=o.object({updatedAt:o.string(),id:o.string().min(1)}).strict(),mt=o.object({entries:o.array(k).max(200),nextBefore:dt.nullable()}).strict(),gt=o.object({run:k,replayed:o.boolean()}).strict(),$=class{constructor(e){this.client=e}client;static{u(this,"HostedCreateImproveStorage")}async getCreateImproveRun(e){let t=await this.client.request({contractVersion:v,requestId:je(),operation:"create-improve/execute",params:{action:"get",runId:e}});return t===null?null:k.parse(t)}async listCreateImproveRuns(e={}){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit??250))),r=Array.isArray(e.state)?[...e.state]:e.state?[e.state]:[],s=[],i=null;for(;s.length<t;){let a=mt.parse(await this.client.request({contractVersion:v,requestId:je(),operation:"create-improve/execute",params:{action:"page",query:{profileId:e.profileId??null,targetKind:e.targetKind??null,targetId:e.targetId??null,state:r},before:i,limit:Math.min(50,t-s.length)}}));if(e.conversationId&&a.entries.some(l=>l.scope.conversationId!==e.conversationId))throw new Error("Hosted Create/Improve page crossed its conversation scope.");if(s.push(...a.entries),!a.nextBefore)break;if(a.entries.length===0||i&&(a.nextBefore.updatedAt>i.updatedAt||a.nextBefore.updatedAt===i.updatedAt&&a.nextBefore.id>=i.id))throw new Error("Hosted Create/Improve cursor did not advance.");i=a.nextBefore}return s}async upsertCreateImproveRun(e){let t=k.parse(e),r=`create-improve:${pt("sha256").update(JSON.stringify(t)).digest("hex")}`,s=await this.client.request({contractVersion:v,requestId:r,operation:"create-improve/execute",params:{action:"put",run:t}});return k.parse(o.object({run:o.unknown()}).strict().parse(s).run)}async mutateCreateImproveRun(e,t){let r=te.parse(e),s=await this.getCreateImproveRun(r.runId);if(!s)throw new Error(`Create/Improve run not found: ${r.runId}`);if(s.appliedActionIds.includes(r.actionId))return{run:s,replayed:!0};if(s.revision!==r.expectedRevision)throw new Error(`Create/Improve run changed from revision ${r.expectedRevision} to ${s.revision}. Refresh and try again.`);let i=k.parse(t(s));if(i.id!==s.id||i.revision!==s.revision+1||!i.appliedActionIds.includes(r.actionId))throw new Error("Create/Improve mutation must preserve identity, advance one revision and record its action.");return gt.parse(await this.client.request({contractVersion:v,requestId:r.actionId,operation:"create-improve/execute",params:{action:"mutate",mutation:r,next:i}}))}};import{randomUUID as ft}from"node:crypto";async function D(n,e){let t=n;for(;;)try{return await e(t)}catch(r){if(!ht(r)||t<=1)throw r;t=Math.max(1,Math.floor(t/2))}}u(D,"hostedBoundedPage");function ht(n){return n instanceof Error?n.message==="Host storage response is too large."||n.message==="Host storage request failed: host_storage_response_too_large":!1}u(ht,"isOversizeResponse");var vt=o.object({entries:o.array(o.object({sequence:o.number().int().positive(),event:F})).max(200),totalMatchingEvents:o.number().int().nonnegative(),remainingMatchingEvents:o.number().int().nonnegative()}).strict(),W=class{constructor(e){this.client=e}client;static{u(this,"HostedRuntimeEventStorage")}async runtimeEventsForSession(e,t={}){let r=t.limit==null?1e4:Math.max(0,Math.trunc(t.limit));if(r===0)return[];let s=Math.min(r,1e4),i=[],a=Math.max(0,t.afterSequence??0),l=0,c=t.names?new Set(t.names):null;for(;i.length<=s;){let p=await this.runtimeEventPageRows({sessionId:e,afterSequence:a,beforeSequence:null,limit:Math.min(200,s+1-i.length),excludeReasoningDeltas:t.excludeReasoningDeltas});for(let h of p.entries){if(h.sequence<=a)throw new Error("Host event cursor did not advance.");if(a=h.sequence,l+=1,l>1e4)throw new Error("Hosted runtime event scan exceeds 10,000 rows; use a narrower query.");(!c||c.has(h.event.name))&&i.push(h.event)}if(p.entries.length===0||p.remainingMatchingEvents<=p.entries.length)break}if(i.length>s||t.limit==null&&r===1e4&&i.length===s)throw new Error("Hosted runtime event read exceeds 10,000 rows; use a bounded cursor query.");return i}async persistedRuntimeEventsForSession(e,t={}){return this.runtimeEventsForSession(e,t)}async appendRuntimeEvent(e){let t=F.parse(e),r=await this.client.request({contractVersion:v,requestId:t.id,operation:"event/append",params:{event:t}});return o.object({event:F}).strict().parse(r).event}async runtimeEventPageRows(e){let t=Math.max(1,Math.min(1e3,Math.trunc(e.limit))),r=Math.max(0,Math.trunc(e.afterSequence)),s=e.beforeSequence,i=[],a=0,l=0;for(;i.length<t;){let c=Math.min(200,t-i.length),p=await D(c,async h=>vt.parse(await this.client.request({contractVersion:v,requestId:`event-page:${ft()}`,operation:"events/page",params:{sessionId:e.sessionId,afterSequence:r,beforeSequence:s,limit:h,...e.excludeReasoningDeltas?{excludeReasoningDeltas:!0}:{}}})));if(i.length===0&&(a=p.totalMatchingEvents,l=p.remainingMatchingEvents),i=s===null?[...i,...p.entries]:[...p.entries,...i],p.entries.length===0||p.remainingMatchingEvents<=p.entries.length)break;if(s===null){let h=p.entries.at(-1).sequence;if(h<=r)throw new Error("Host event cursor did not advance.");r=h}else{let h=p.entries[0].sequence;if(h>=s)throw new Error("Host event cursor did not advance.");s=h}}return{entries:i,totalMatchingEvents:a,remainingMatchingEvents:l}}};import{randomUUID as y}from"node:crypto";var Le=o.object({revision:o.number().int().min(1),session:N}).strict(),Ve=o.object({revision:o.number().int().min(1),turn:H}).strict(),wt=o.object({sessions:o.array(N).max(200),nextAfterId:o.string().min(1).nullable()}).strict(),bt=o.object({turns:o.array(H).max(200),nextBeforeSortIndex:o.number().int().nonnegative().nullable()}).strict(),G=class{constructor(e){this.client=e}client;static{u(this,"HostedSessionStorage")}async count(){let e=await this.client.request({contractVersion:v,requestId:y(),operation:"session/count",params:{}});return o.object({count:o.number().int().nonnegative()}).strict().parse(e).count}async get(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"session/get",params:{sessionId:e}});return t===null?null:Le.parse(t)}async sessionCount(){return this.count()}async sessionShells(){let e=[],t=null;do{let r=await D(Math.min(10,1001-e.length),async s=>wt.parse(await this.client.request({contractVersion:v,requestId:y(),operation:"session/page",params:{afterId:t,limit:s}})));if(e.push(...r.sessions),e.length>1e3)throw new Error("Hosted session list exceeds 1,000 rows; use a scoped page query.");if(r.nextAfterId!==null&&(r.sessions.length===0||t!==null&&r.nextAfterId<=t))throw new Error("Host session cursor did not advance.");t=r.nextAfterId}while(t!==null);return e}async getSession(e){return(await this.get(e))?.session??null}async insertSessionAtFront(e){await this.put({session:e,expectedRevision:null,requestId:y()})}async updateSession(e,t){let r=await this.get(e);if(!r)return null;let s=N.parse(t(r.session));if(s.id!==e)throw new Error("A session update cannot change its identity.");return(await this.put({session:s,expectedRevision:r.revision,requestId:y()})).session}async put(e){let t=N.parse(e.session);return Le.parse(await this.client.request({contractVersion:v,requestId:e.requestId,operation:"session/put",params:{sessionId:t.id,expectedRevision:e.expectedRevision,session:t}}))}async readTurn(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/get",params:{turnId:e}});return t===null?null:Ve.parse(t)}async getTurn(e){return(await this.readTurn(e))?.turn??null}async turnsForSession(e,t=50){let r=Math.max(1,Math.min(1e3,Math.trunc(t))),s=[],i=null;for(;s.length<r;){let a=await D(Math.min(200,r-s.length),async l=>bt.parse(await this.client.request({contractVersion:v,requestId:y(),operation:"turn/page",params:{sessionId:e,beforeSortIndex:i,limit:l}})));if(s.push(...a.turns),a.nextBeforeSortIndex===null)break;if(i!==null&&a.nextBeforeSortIndex>=i)throw new Error("Host turn cursor did not advance.");i=a.nextBeforeSortIndex}return s}async countTurnsForSession(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/count",params:{sessionId:e}});return o.object({count:o.number().int().nonnegative()}).strict().parse(t).count}async hasSubagentParentWakeTurn(e,t){return await this.wakeCount(e,"messageId",t)>0}async countSubagentParentWakeTurns(e,t){return this.wakeCount(e,"fromRunId",t)}async latestAssistantTextForSession(e){let t=await this.client.request({contractVersion:v,requestId:y(),operation:"events/latestAssistantText",params:{sessionId:e}});return o.object({text:o.string().nullable()}).strict().parse(t).text}async wakeCount(e,t,r){let s=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/wakeCount",params:{sessionId:e,key:t,value:r}});return o.object({count:o.number().int().nonnegative()}).strict().parse(s).count}async latestTurnForSession(e,t){let r=await this.client.request({contractVersion:v,requestId:y(),operation:"turn/latest",params:{sessionId:e,status:t??null}});return r===null?null:H.parse(r)}async latestPersistedTurnForSession(e,t){return this.latestTurnForSession(e,t)}async insertTurn(e){await this.putTurn({turn:e,expectedRevision:null,requestId:y()})}async updateTurn(e,t){let r=await this.readTurn(e);if(!r)return null;let s=H.parse(t(r.turn));if(s.id!==e||s.sessionId!==r.turn.sessionId)throw new Error("A turn update cannot change its identity.");return(await this.putTurn({turn:s,expectedRevision:r.revision,requestId:y()})).turn}async putTurn(e){let t=H.parse(e.turn);return Ve.parse(await this.client.request({contractVersion:v,requestId:e.requestId,operation:"turn/put",params:{sessionId:t.sessionId,turnId:t.id,expectedRevision:e.expectedRevision,turn:t}}))}};import{createHash as St,randomUUID as yt}from"node:crypto";var C=o.object({ok:o.literal(!0)}).strict(),J=o.array(O),Rt=o.array(o.string()),It=o.object({turnId:o.string(),run:_}).strict(),Tt=o.object({inputs:o.array(O).max(10),hasMore:o.boolean()}).strict(),Pt=o.object({items:o.array(j).max(10),hasMore:o.boolean()}).strict(),xt=o.object({items:o.array(o.string()).max(200),hasMore:o.boolean()}).strict();function z(n,e){return`inbox:${n}:${St("sha256").update(JSON.stringify(e)).digest("hex")}`}u(z,"retryKey");var U=class{constructor(e){this.client=e}client;static{u(this,"HostedTaskInboxStorage")}async call(e,t,r=yt()){let s=await this.client.request({contractVersion:v,requestId:r,operation:"task-inbox/execute",params:e});return t.parse(s)}async inputPages(e,t=Number.MAX_SAFE_INTEGER){let r=[],s=0;for(;r.length<t;){let i=await this.call(e(s),Tt);for(let a of i.inputs){if(a.sequence<=s)throw new Error("Host task input cursor did not advance.");if(s=a.sequence,r.push(a),r.length>=t)break}if(!i.hasMore)return r;if(i.inputs.length===0)throw new Error("Host task input page made no progress.")}return r}async recoverTaskInboxOwners(e){return this.call({action:"recoverTaskInboxOwners",ownerId:e},o.array(o.object({sessionId:o.string(),turnId:o.string()}).strict()))}async hasTaskCompletion(e){return this.call({action:"hasTaskCompletion",turnId:e},o.boolean())}async taskInboxSnapshot(e){let t=await this.call({action:"taskInboxSnapshot",sessionId:e},re),[r,s]=await Promise.all([this.inputPages(i=>({action:"taskInboxSnapshotInputs",sessionId:e,afterSequence:i})),this.taskWaitsForSession(e)]);return{...t,inputs:r,waits:s}}async declareTaskWork(e,t,r,s){await this.call({action:"declareTaskWork",sessionId:e,turnId:t,ownerId:r,areas:s},C)}async taskWorkAreas(e){return this.call({action:"taskWorkAreas",sessionId:e},Rt)}async admitTaskInput(e){return this.call({action:"admitTaskInput",input:e},O)}async admitTaskInputs(e){return this.call({action:"admitTaskInputs",inputs:e},J)}async rejectTaskInput(e,t){await this.call({action:"rejectTaskInput",id:e,error:t},C)}async getTaskInput(e){return this.call({action:"getTaskInput",id:e},O.nullable())}async taskInputsForSession(e,t={}){let r=Math.max(1,Math.min(500,t.limit??128)),s=[],i=t.afterSequence??0;for(;s.length<r;){let a=Math.min(10,r-s.length),l=await this.call({action:"taskInputsForSession",sessionId:e,query:{afterSequence:i,pendingOnly:t.pendingOnly,limit:a}},J);if(!l.length)break;for(let c of l){if(c.sequence<=i)throw new Error("Host task input cursor did not advance.");i=c.sequence,s.push(c)}if(l.length<a)break}return s}async mutateTaskInput(e,t,r){return this.call({action:"mutateTaskInput",sessionId:e,inputId:t,change:r},O,z("mutate",{sessionId:e,inputId:t,change:r}))}async openTaskInboxTurn(e,t,r){await this.call({action:"openTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C,z("open",{sessionId:e,turnId:t,ownerId:r}))}async renewTaskInboxTurn(e,t,r){await this.call({action:"renewTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C)}async pendingTaskInputs(e,t){return this.inputPages(r=>({action:"pendingTaskInputs",sessionId:e,turnId:t,afterSequence:r}))}async taskAssignmentInputs(e){return this.inputPages(t=>({action:"taskAssignmentInputs",turnId:e,afterSequence:t}))}async pauseTaskInboxTurn(e,t,r){await this.call({action:"pauseTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},C)}async includeTaskInputs(e,t,r,s){return this.call({action:"includeTaskInputs",sessionId:e,turnId:t,ownerId:r,requestId:s},J,z("include",{sessionId:e,turnId:t,ownerId:r,requestId:s}))}async settleTaskInputRequest(e,t){await this.call({action:"settleTaskInputRequest",requestId:e,outcome:t},C)}async sealTaskInboxTurn(e,t,r){return this.call({action:"sealTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},o.boolean())}async sealNativeTaskInboxTurn(e,t,r){return this.call({action:"sealNativeTaskInboxTurn",sessionId:e,turnId:t,ownerId:r},J)}async closeTaskInboxTurn(e,t,r,s){await this.call({action:"closeTaskInboxTurn",sessionId:e,turnId:t,ownerId:r,outcome:s},C)}async taskInboxPaused(e){return this.call({action:"taskInboxPaused",sessionId:e},o.boolean())}async reserveTaskFollowup(e,t,r){return this.call({action:"reserveTaskFollowup",sessionId:e,turnId:t,ownerId:r},O.nullable(),z("reserve",{sessionId:e,turnId:t,ownerId:r}))}async taskInboxWakeTargets(){let e=[],t="";for(;;){let r=await this.call({action:"taskInboxWakeTargets",afterSessionId:t},xt);for(let s of r.items){if(s<=t)throw new Error("Host task wake cursor did not advance.");t=s,e.push(s)}if(!r.hasMore)return e;if(!r.items.length)throw new Error("Host task wake page made no progress.")}}async createTaskWait(e){return this.call({action:"createTaskWait",value:e},j)}async settleTaskWait(e,t){return this.call({action:"settleTaskWait",id:e,state:t},j)}async taskWaitsForSession(e){let t=[],r="";for(;;){let s=await this.call({action:"taskWaitsForSession",sessionId:e,afterId:r},Pt);for(let i of s.items){if(i.id<=r)throw new Error("Host task wait cursor did not advance.");r=i.id,t.push(i)}if(!s.hasMore)return t;if(!s.items.length)throw new Error("Host task wait page made no progress.")}}async commitSubagentCompletion(e,t){await this.call({action:"commitSubagentCompletion",value:e,turnId:t},C)}async pendingTaskCompletions(e=""){let t=[],r=e;for(;t.length<100;){let s=await this.call({action:"pendingTaskCompletions",afterTurnId:r},o.array(It).max(10));for(let i of s){if(i.turnId<=r)throw new Error("Host task completion cursor did not advance.");r=i.turnId,t.push(i)}if(s.length<10)break}return t}async settleTaskCompletion(e,t){await this.call({action:"settleTaskCompletion",turnId:e,inputId:t},C)}async upsertSubagentRun(e){return this.call({action:"upsertSubagentRun",value:_.parse(e)},_)}async getSubagentRun(e){return this.call({action:"getSubagentRun",id:e},_.nullable())}async listSubagentRuns(e={}){let r=[],s="",i=e.status?Array.isArray(e.status)?[...e.status]:[e.status]:null;for(;;){let a=await this.call({action:"listSubagentRuns",query:{parentSessionId:e.parentSessionId,childSessionId:e.childSessionId,status:i,afterId:s,limit:10}},o.array(_).max(10));for(let l of a){if(l.id<=s)throw new Error("Host subagent run cursor did not advance.");if(s=l.id,r.push(l),r.length>1e3)throw new Error("Hosted subagent run list exceeds 1,000 rows; use a narrower session or status query.")}if(a.length<10)break}return r.sort((a,l)=>(l.updatedAt??l.createdAt).localeCompare(a.updatedAt??a.createdAt)),e.limit===void 0?r:r.slice(0,Math.max(1,Math.min(1e3,e.limit)))}async listActiveSubagentRuns(e={}){return this.listSubagentRuns({...e,status:e.status??["queued","running","needs_resume"]})}};var ee=class extends U{static{u(this,"HostedTurnRepository")}sessions;events;approvals;usage;createImprove;constructor(e){super(e),this.sessions=new G(e),this.events=new W(e),this.approvals=new ke(e),this.usage=new Oe(e),this.createImprove=new $(e)}sessionShells(){return this.sessions.sessionShells()}sessionCount(){return this.sessions.sessionCount()}getSession(e){return this.sessions.getSession(e)}insertSessionAtFront(e){return this.sessions.insertSessionAtFront(e)}updateSession(e,t){return this.sessions.updateSession(e,t)}getTurn(e){return this.sessions.getTurn(e)}insertTurn(e){return this.sessions.insertTurn(e)}updateTurn(e,t){return this.sessions.updateTurn(e,t)}latestTurnForSession(e,t){return this.sessions.latestTurnForSession(e,t)}latestPersistedTurnForSession(e,t){return this.sessions.latestPersistedTurnForSession(e,t)}turnsForSession(e,t){return this.sessions.turnsForSession(e,t)}countTurnsForSession(e){return this.sessions.countTurnsForSession(e)}hasSubagentParentWakeTurn(e,t){return this.sessions.hasSubagentParentWakeTurn(e,t)}countSubagentParentWakeTurns(e,t){return this.sessions.countSubagentParentWakeTurns(e,t)}latestAssistantTextForSession(e){return this.sessions.latestAssistantTextForSession(e)}appendRuntimeEvent(e){return this.events.appendRuntimeEvent(e)}runtimeEventsForSession(e,t){return this.events.runtimeEventsForSession(e,t)}persistedRuntimeEventsForSession(e,t){return this.events.persistedRuntimeEventsForSession(e,t)}runtimeEventPageRows(e){return this.events.runtimeEventPageRows(e)}getApproval(e){return this.approvals.getApproval(e)}async upsertApproval(e){let t=await this.approvals.readApproval(e.id);t&&JSON.stringify(t.approval)===JSON.stringify(e)||await this.approvals.putApproval({approval:e,expectedRevision:t?.revision??null,requestId:`approval:${Ct("sha256").update(JSON.stringify({approval:e,revision:t?.revision??null})).digest("hex")}`})}upsertModelUsageRecord(e){return this.usage.upsertModelUsageRecord(e)}listModelUsageRecords(e){return this.usage.listModelUsageRecords(e)}getCreateImproveRun(e){return this.createImprove.getCreateImproveRun(e)}listCreateImproveRuns(e){return this.createImprove.listCreateImproveRuns(e)}upsertCreateImproveRun(e){return this.createImprove.upsertCreateImproveRun(e)}mutateCreateImproveRun(e,t){return this.createImprove.mutateCreateImproveRun(e,t)}};function $e(n){return new ee(n)}u($e,"createHostedRuntimeCoreStorage");function We(n=process.env){let e=n.OPENPOND_API_KEY?.trim(),t=n.OPENPOND_OPCHAT_API_URL?.trim(),r=n.OPENPOND_HOSTED_MODEL_ID?.trim();if(!e||!t||!r)throw new Error("Hosted model stream requires a host credential, API URL, and admitted model.");let s=new URL(t);if(s.protocol!=="https:"||s.username||s.password||s.search||s.hash)throw new Error("Hosted model stream API URL is invalid.");return u(async function*(a){if(a.model!==r)throw new Error("Hosted model selection changed outside host admission.");yield*Pe({...a,apiBaseUrl:s.toString(),token:e,model:r})},"streamHostedModel")}u(We,"createHostedModelStreamFromEnvironment");import{existsSync as Et}from"node:fs";import T from"node:path";import{fileURLToPath as kt}from"node:url";var Ge=T.dirname(kt(import.meta.url));function R(n,e,t){let r=n[e+1];if(!r||r.startsWith("--"))throw new Error(`${t} requires a value.`);return r}u(R,"requireValue");function Je(n,e){let t=Number.parseInt(n,10);if(!Number.isFinite(t)||t<0||t>65535)throw new Error(`${e} must be a port from 0 to 65535.`);return t}u(Je,"parsePort");function Ke(n){let e="serve",t=K,r=17874,s=null,i=!1,a=!1,l=null,c,p,h=null,b=null,x=null,A=null,f,g="sqlite_bundle",S=0,P=n[0];if(P&&!P.startsWith("-")){if(P==="serve"||P==="server")e="serve";else if(P==="app-server")e="app-server";else if(P==="web")e="web";else{if(P==="help")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:a,storeDir:l,runtimeStorage:g,help:!0};throw new Error(`Unknown command: ${P}`)}S=1}for(let m=S;m<n.length;m+=1){let d=n[m];if(d==="--help"||d==="-h")return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:a,storeDir:l,runtimeStorage:g,help:!0};if(d==="--listen"){let E=ye(R(n,m,d));t=E.host,r=Je(String(E.port),d),m+=1}else if(d==="--hostname"||d==="--host")t=R(n,m,d),m+=1;else if(d==="--port")r=Je(R(n,m,d),d),m+=1;else if(d==="--web-root")s=T.resolve(R(n,m,d)),m+=1;else if(d==="--source-browser-state")p=T.resolve(R(n,m,d)),m+=1;else{if(d==="--store-dir")throw new Error("--store-dir has been replaced by --home. Use --home <directory> or OPENPOND_HOME.");if(d==="--home")l=T.resolve(R(n,m,d)),m+=1;else if(d==="--hosted-cache-home")c=T.resolve(R(n,m,d)),m+=1;else if(d==="--runtime-storage"){if(R(n,m,d)!=="hosted-postgres")throw new Error("Unsupported app-server runtime storage.");g="hosted_postgres",m+=1}else if(d==="--profile-source-root")h=T.resolve(R(n,m,d)),m+=1;else if(d==="--profile-repository-id")b=R(n,m,d),m+=1;else if(d==="--profile-id")x=R(n,m,d),m+=1;else if(d==="--profile-revision")A=R(n,m,d),m+=1;else if(d==="--hosted-profile-release"){if(f)throw new Error("Duplicate hosted Profile release descriptor.");let E=R(n,m,d);if(E.length>16e3||!/^[A-Za-z0-9_-]+$/.test(E))throw new Error("Invalid hosted Profile release descriptor.");try{f=Ae.parse(JSON.parse(Buffer.from(E,"base64url").toString("utf8")))}catch{throw new Error("Invalid hosted Profile release descriptor.")}m+=1}else if(d==="--open-browser")i=!0;else if(d==="--print-access-url")a=!0;else throw new Error(`Unknown option: ${d}`)}}if(i&&a)throw new Error("--open-browser and --print-access-url cannot be used together.");if(e!=="web"&&(i||a))throw new Error("Browser options are only available in web mode.");let w=[h,b,x,A].filter(Boolean).length;if(w&&(w!==4||e!=="app-server"))throw new Error("Profile source flags require app-server mode and --profile-source-root, --profile-repository-id, --profile-id, and --profile-revision together.");if(g==="hosted_postgres"&&(e!=="app-server"||l||w))throw new Error("Hosted Postgres app-server cannot use --home or local Profile source flags.");if(f&&g!=="hosted_postgres")throw new Error("Hosted Profile release requires hosted Postgres app-server mode.");if(c&&g!=="hosted_postgres")throw new Error("Hosted cache home requires hosted Postgres mode.");return{mode:e,host:t,port:r,webRoot:s,openBrowser:i,printAccessUrl:a,storeDir:l,runtimeStorage:g,sourceBrowserState:p,...w?{profileSource:{repoPath:h,repositoryId:b,profileId:x,sourceRevision:A}}:{},...f?{admittedProfileRelease:f}:{},...c?{hostedCacheHome:c}:{},help:!1}}u(Ke,"parseCliArgs");function Ot(){return[process.env.OPENPOND_WEB_ROOT,T.resolve(process.cwd(),"apps/web/dist"),T.resolve(Ge,"../../web/dist"),T.resolve(process.cwd(),"web"),T.resolve(Ge,"../web")].filter(n=>!!n)}u(Ot,"defaultWebRootCandidates");function At(n){let e=n?[n]:Ot();for(let t of e){let r=T.resolve(t);if(Et(T.join(r,"index.html")))return r}return null}u(At,"resolveWebRoot");function _t(n){let e=n==="0.0.0.0"||n==="::"?"127.0.0.1":n;return e.includes(":")&&!e.startsWith("[")?`[${e}]`:e}u(_t,"formatHostForUrl");function Ht(n){return`http://${_t(n.status.host)}:${n.status.port}`}u(Ht,"browserBaseUrl");function Mt(n,e){let t=new URL(n),r=new URLSearchParams;return r.set("openpondServerUrl",n),r.set("openpondToken",e),t.hash=r.toString(),t.toString()}u(Mt,"tokenizedWebUrl");async function ze(n,e=Ce){let t=Mt(n.baseUrl,n.token);if(n.printAccessUrl)return{stdout:[`OpenPond access URL: ${t}`],stderr:[]};if(!n.openBrowser)return{stdout:[`OpenPond web UI: ${n.baseUrl}`],stderr:[]};let r=await e(t);return r.opened?{stdout:[`Opened OpenPond in your browser: ${n.baseUrl}`],stderr:[]}:{stdout:[`OpenPond access URL: ${t}`],stderr:[`Could not open the system browser: ${r.error}`]}}u(ze,"resolveWebLaunchMessages");function Xe(){console.log(`Usage:
|
|
24
24
|
openpond-app-server serve [--hostname HOST] [--port PORT]
|
|
25
25
|
openpond-app-server app-server [--home DIR]
|
|
26
26
|
openpond-app-server web [--hostname HOST] [--port PORT] [--web-root DIR]
|
|
@@ -39,4 +39,4 @@ Options:
|
|
|
39
39
|
--profile-revision REV Accepted immutable source revision
|
|
40
40
|
--open-browser Open the authenticated web URL in the system browser
|
|
41
41
|
--print-access-url Print the authenticated URL instead of opening it
|
|
42
|
-
`)}u(Xe,"printHelp");async function an(n){let e=Ke(process.argv.slice(2));if(e.help){Xe();return}let t=e.mode==="web"?At(e.webRoot):null;if(e.mode==="web"&&!t)throw new Error("Could not find a built OpenPond web UI. Run `pnpm build:web` or pass --web-root.");if(e.mode==="app-server"){await Ze(n.createOpenPondAppServer,e.storeDir,e.profileSource,e.runtimeStorage,e.admittedProfileRelease,e.hostedCacheHome);return}e.storeDir&&(process.env.OPENPOND_HOME=e.storeDir);let r,s=e.port;for(;;)try{r=await n.createOpenPondServer({host:e.host,port:s,webRoot:t,sourceBrowserState:e.sourceBrowserState,...e.storeDir?{storeDir:e.storeDir}:{},httpEnabled:!0});break}catch(c){if(!De(c))throw c;let p=await Fe(
|
|
42
|
+
`)}u(Xe,"printHelp");async function an(n){let e=Ke(process.argv.slice(2));if(e.help){Xe();return}let t=e.mode==="web"?At(e.webRoot):null;if(e.mode==="web"&&!t)throw new Error("Could not find a built OpenPond web UI. Run `pnpm build:web` or pass --web-root.");if(e.mode==="app-server"){await Ze(n.createOpenPondAppServer,e.storeDir,e.profileSource,e.runtimeStorage,e.admittedProfileRelease,e.hostedCacheHome);return}e.storeDir&&(process.env.OPENPOND_HOME=e.storeDir);let r,s=e.port;for(;;)try{r=await n.createOpenPondServer({host:e.host,port:s,webRoot:t,sourceBrowserState:e.sourceBrowserState,...e.storeDir?{storeDir:e.storeDir}:{},httpEnabled:!0});break}catch(c){if(!De(c))throw c;let p=await Fe(se({home:e.storeDir??void 0}),s,c);s=p.port,console.log(`OPENPOND_APP_SERVER_READY ${JSON.stringify({mode:"recovery",url:p.url,tokenFile:p.tokenFile,storePath:p.storePath})}`),console.error(`${c.issue.code}: ${c.issue.message} ${c.issue.action}`);let h=await ze({baseUrl:p.url,openBrowser:e.openBrowser,printAccessUrl:e.printAccessUrl,token:p.token});for(let x of h.stdout)console.log(x);for(let x of h.stderr)console.error(x);let b=u(()=>{p.close().finally(()=>process.exit(0))},"close");process.once("SIGINT",b),process.once("SIGTERM",b);try{await p.repaired}finally{process.off("SIGINT",b),process.off("SIGTERM",b),await p.close()}}let i=e.mode==="web"?Ht(r):null;if(console.log(`OPENPOND_APP_SERVER_READY ${JSON.stringify({mode:e.mode,url:r.url,webUrl:null,webRoot:t,tokenFile:r.tokenFile,storePath:r.storePath,runtime:xe()})}`),i){let c=await ze({baseUrl:i,openBrowser:e.openBrowser,printAccessUrl:e.printAccessUrl,token:r.token});for(let p of c.stderr)console.error(p);for(let p of c.stdout)console.log(p)}else console.log(`OpenPond API server: ${r.url}`);let a=!1,l=u(async()=>{a||(a=!0,await r.close(),process.exit(0))},"shutdown");process.on("SIGINT",()=>{l()}),process.on("SIGTERM",()=>{l()}),await new Promise(()=>{})}u(an,"runOpenPondServerCli");async function un(n){let e=process.argv.slice(2),t=Ke(!e[0]||e[0].startsWith("-")?["app-server",...e]:e);if(t.help){Xe();return}if(t.mode!=="app-server")throw new Error("The app-server entrypoint only accepts the app-server command.");await Ze(n,t.storeDir,t.profileSource,t.runtimeStorage,t.admittedProfileRelease,t.hostedCacheHome)}u(un,"runOpenPondAppServerCli");async function Ze(n,e,t,r="sqlite_bundle",s,i){let a=new Te;if(r==="hosted_postgres"){if(e||t)throw new Error("Hosted Postgres app-server cannot use local storage sources.");await X({appServer:u(()=>n({...i?{storeDir:i}:{},hostStorageClient:a,runtimeStorage:{kind:"hosted_postgres",client:a,core:$e(a),inbox:new U(a),...s?{admittedProfileRelease:s}:{}},streamOpenPondHostedChatTurn:We()}),"appServer"),readable:process.stdin,writable:process.stdout,hostStorageClient:a});return}e&&(process.env.OPENPOND_HOME=e);let l=await n({...e?{storeDir:e}:{},...t?{profileSource:t}:{},hostStorageClient:a});await X({appServer:l,readable:process.stdin,writable:process.stdout,hostStorageClient:a})}u(Ze,"runAgentServer");export{_e as a,B as b,Ue as c,I as d,Ft as e,jt as f,Z as g,Ne as h,ze as i,an as j,un as k};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{n as z,o as V,p as G,q}from"./chunk-
|
|
2
|
+
import{n as z,o as V,p as G,q}from"./chunk-FUFIZ37W.js";import{a as A,f as v,g as k,h as p,i as f}from"./chunk-3M53YXEI.js";import{a}from"./chunk-FTQLQJQV.js";import{Buffer as Y}from"node:buffer";import{readdirSync as H,readFileSync as Q,statSync as F}from"node:fs";import b from"node:path";var K=500,Z=8*1024*1024,W=8*1024*1024;async function me(e,t){if(!t.sandboxRuntime&&!t.runtimeId)return{sandbox:await X(e,await e.create(t.sandbox,{async:!0}))};let n=t.runtimeId?void 0:await e.createSandboxRuntime(t.sandboxRuntime),r=t.runtimeId??n.id,o=await e.createSandboxRuntimeSandbox(r,t.sandbox);return{sandbox:await X(e,o.sandbox),runtime:o.runtime??n}}a(me,"createSandboxFromPlan");async function X(e,t){if(t.state==="running"||t.state==="stopped")return t;if(t.state==="error")throw new Error(`sandbox create failed: ${t.id}
|
|
3
3
|
${t.logs.join(`
|
|
4
4
|
`)}`);let n=12*6e4,r=3e3,o=Date.now()+n,i=t;for(;Date.now()<o;){if(await new Promise(s=>setTimeout(s,r)),i=await e.get(t.id),i.state==="running"||i.state==="stopped")return i;if(i.state==="error")throw new Error(`sandbox create failed: ${i.id}
|
|
5
5
|
${i.logs.join(`
|
|
@@ -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-5YUITAUN.js";import{a as fe,b as L,c as R}from"./chunk-FFEI7IRU.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{M as ce,N as le,R as de,V as pe,h as $,i as ne,l as oe,n as re,o as ie,p as ae,q as se}from"./chunk-UJLZRM2M.js";import{d as y,e as ue,f as ge,g as C}from"./chunk-6EAQL7YX.js";import{a as Z,b as ee,c as te}from"./chunk-3LG4G5JR.js";import{a as M,f as v,k as X}from"./chunk-3M53YXEI.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 ie(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 ae(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 se(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 ue();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 ge(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 ce(t,r);console.log(JSON.stringify(n,null,2))}g(Ve,"runAccount");async function We(e){let o=await y(),t=P(o),r=fe(o),n=await le(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 ne(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 pe(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 de(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 re(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 oe(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-FUFIZ37W.js";import{a as re,b as L,c as R}from"./chunk-3HQEEZPO.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-P5CFBE6Z.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-SHCKK3SU.js";import{d as y,e as ne,f as oe,g as C}from"./chunk-AOBTILU5.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};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
+
import{i as a,j as b,k as c}from"./chunk-ZCDOE3EO.js";import"./chunk-KNEMKYHY.js";import"./chunk-25OT6IYM.js";import"./chunk-GKRTXVNT.js";import"./chunk-OCWH4BV7.js";import"./chunk-PKBU37CH.js";import"./chunk-V5BC6QT2.js";import"./chunk-XHJUP7M4.js";import"./chunk-7BGT6Q2D.js";import"./chunk-SBBXUZWL.js";import"./chunk-L3KS6MOV.js";import"./chunk-SHCRE7B2.js";import"./chunk-MRGA6BKG.js";import"./chunk-6MI4KKWF.js";import"./chunk-WCZRDULE.js";import"./chunk-GIPSOLAY.js";import"./chunk-MJC26GOX.js";import"./chunk-JUX77H6K.js";import"./chunk-QUNRWDVO.js";import"./chunk-6FA3GG5B.js";import"./chunk-SDO4FC4Q.js";import"./chunk-IR3YJWPW.js";import"./chunk-QK2GLRCY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import"./chunk-H7IWJN7L.js";import"./chunk-FTQLQJQV.js";export{a as resolveWebLaunchMessages,c as runOpenPondAppServerCli,b as runOpenPondServerCli};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
|
|
2
|
-
import{a as f}from"./chunk-
|
|
2
|
+
import{a as f}from"./chunk-FKVP26MC.js";import"./chunk-P5CFBE6Z.js";import"./chunk-3M53YXEI.js";import{$a as I,Ba as J,Qa as N,Ra as q,Ua as k,Wa as A,X as d,Xa as B,Y as w,_ as b,_a as H,hb as E,ib as M,ja as C,jb as T,la as m,ma as j,na as x,oa as F,pa as v,qa as P}from"./chunk-QK2GLRCY.js";import"./chunk-HZP5U2AA.js";import"./chunk-ES2ISFJC.js";import{d as O,f as S,h as g}from"./chunk-H7IWJN7L.js";import{a as l}from"./chunk-FTQLQJQV.js";import R from"node:path";import{readFile as p}from"node:fs/promises";var n=l((t,s)=>typeof t[s]=="string"?t[s]:void 0,"stringOption");function a(t){console.log(JSON.stringify(t,null,2))}l(a,"print");function U(t,s){let i=n(t,"keyPath");if(i){let r=JSON.parse(i);if(Array.isArray(r)&&r.length&&r.every(c=>typeof c=="string"&&c.length))return r;throw new f("--key-path must be a JSON array of key segments.")}if(!s)throw new f("Specify a setting key, or --key-path for keys containing dots.");return s.split(".")}l(U,"keyPath");async function G(t,s){let i=S({home:n(t,"home")}),r=s[0]??"get",c=g(i).config;if(r==="path"){console.log(c);return}if(r==="export"){let e=await T(i),o=n(t,"file");o?(await b(R.resolve(o),JSON.stringify(e,null,2),{privateParent:!1}),a({path:R.resolve(o),requiresRebinding:e.requiresRebinding})):a(e);return}if(r==="backup"||r==="restore"){let e=n(t,"file"),o=n(t,"keyFile");if(!e||!o)throw new f(`config ${r} requires --file <encrypted-backup> and --key-file <separate-32-byte-key-file>.`);let u=await p(o),y=u.length===32?u:Buffer.from(u.toString("utf8").trim(),"base64");try{a(r==="backup"?await E(i,e,y):await M(e,i,y))}finally{y.fill(0),u.fill(0)}return}if(r==="collect-orphans"){a(await N(i));return}if(r==="schema"){a(F());return}if(r==="migrate"){let e=n(t,"resolutionFile"),o=e?q.parse(JSON.parse(await p(e,"utf8"))):void 0;a(await k(i,{resolutions:o,sourceAppHome:n(t,"sourceAppHome"),sourceConfig:n(t,"sourceConfig"),sourceBrowserState:n(t,"sourceBrowserState"),dryRun:t.dryRun===!0||t.dryRun==="true"}));return}if(r==="recover"){let e=n(t,"revision");a(e?await x(i,e,n(t,"expectedRevision")??d(await w(c))):await A(i));return}if(r==="restart-migration"){a(await B(i));return}if(r==="effective"){a(await I(i,{projectRoot:n(t,"projectRoot"),accountId:n(t,"accountId")}));return}if(r==="trust"||r==="untrust"){let e=n(t,"projectRoot")??s[1];if(!e)throw new f("Specify the canonical project root with --project-root.");await H(i,e,n(t,"accountId")??"local",r==="trust"),a({root:e,trusted:r==="trust"});return}if(r==="revisions"){a(await m(i));return}if(r==="validate"){let e=n(t,"file")??c;C(await p(e,"utf8"),e,t.project===!0||t.project==="true"?"project":"user"),a({valid:!0,path:e});return}if(r==="replace"){let e=n(t,"file");if(!e)throw new f("config replace requires --file <validated-toml-file>.");a(await j(i,n(t,"expectedRevision")??d(await w(c)),await p(e,"utf8")));return}if(r==="doctor"){let e=await w(c),o=null;try{await v(i)}catch(u){o=O(u,c)}a({home:i,path:c,rawRevision:d(e),issue:o,recoverableRevisions:await m(i),migration:await w(R.join(g(i).runtime,"migration.json"))!==null}),o&&(process.exitCode=1);return}if(await k(i),r==="clear-cache"){await J(i),a({cleared:!0,path:g(i).cache});return}let h=await v(i);if(r==="get"){if(!s[1]&&!t.keyPath){a(h);return}let e=h.document;for(let o of U(t,s[1]))e=e&&typeof e=="object"?e[o]:void 0;a(e??null);return}if(r==="set"||r==="unset"){let e=U(t,s[1]),o;if(r==="set"){let u=n(t,"value")??s[2];if(u===void 0)throw new f("config set requires a value. Use JSON for arrays, tables, numbers and booleans.");try{o=JSON.parse(u)}catch{o=u}}a(await P(i,n(t,"expectedRevision")??h.rawRevision,[r==="set"?{op:"set",path:e,value:o}:{op:"unset",path:e}]));return}throw new f(`Unknown config command: ${r}`)}l(G,"runConfigurationCommand");export{G as runConfigurationCommand};
|