openpond 0.2.23 → 0.2.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/dist/app-server.js +1 -1
  2. package/dist/chunks/actions-command-S27YU6NW.js +2 -0
  3. package/dist/chunks/{app-layer-4CK6ZEKN.js → app-layer-57323XKJ.js} +1 -1
  4. package/dist/chunks/app-server-runtime-AOSX4AH5.js +2 -0
  5. package/dist/chunks/apps-U3TXSPU6.js +2 -0
  6. package/dist/chunks/{chunk-NS3VMSTX.js → chunk-4D3JNBSP.js} +2 -2
  7. package/dist/chunks/chunk-4KDHMGKI.js +2 -0
  8. package/dist/chunks/chunk-6LY7GYNK.js +2 -0
  9. package/dist/chunks/{chunk-BZMVB3GS.js → chunk-6XF4GI35.js} +1 -1
  10. package/dist/chunks/{chunk-73KFNV3D.js → chunk-7TV2VBSD.js} +1 -1
  11. package/dist/chunks/{chunk-CXDS2LSW.js → chunk-AC2M2HO3.js} +1 -1
  12. package/dist/chunks/{chunk-XDVKDELR.js → chunk-B3LJ777T.js} +1 -1
  13. package/dist/chunks/{chunk-ZVOO7FKM.js → chunk-BSHAIAXY.js} +1 -1
  14. package/dist/chunks/{chunk-QWE3RHNY.js → chunk-C5OV4XWF.js} +1 -1
  15. package/dist/chunks/{chunk-WYHHDJEG.js → chunk-D6BBQHZM.js} +12 -12
  16. package/dist/chunks/{chunk-JS6MS2NR.js → chunk-F3VURV3Q.js} +2 -2
  17. package/dist/chunks/chunk-F4WS5QIT.js +54 -0
  18. package/dist/chunks/{chunk-V4ACXLID.js → chunk-GOQDMRUV.js} +1 -1
  19. package/dist/chunks/chunk-J3ZRHNGL.js +2 -0
  20. package/dist/chunks/{chunk-MD7IADMT.js → chunk-K5IJNSHP.js} +1 -1
  21. package/dist/chunks/{chunk-H75VJFMZ.js → chunk-KLSLHUTO.js} +1 -1
  22. package/dist/chunks/{chunk-Q76GR2JM.js → chunk-M4CJXPMH.js} +1 -1
  23. package/dist/chunks/chunk-M4VGRNP6.js +2 -0
  24. package/dist/chunks/{chunk-T3VPZRIX.js → chunk-NVVETL4F.js} +1 -1
  25. package/dist/chunks/chunk-TJNIYJUH.js +2 -0
  26. package/dist/chunks/{chunk-CTC5EYSH.js → chunk-TR37PJIQ.js} +3 -3
  27. package/dist/chunks/{chunk-V2BBMZ7I.js → chunk-WK5HTGXV.js} +1 -1
  28. package/dist/chunks/{chunk-3XUBKIBN.js → chunk-WTZYPCLS.js} +1 -1
  29. package/dist/chunks/chunk-XRV4WLI7.js +2 -0
  30. package/dist/chunks/chunk-XWPC3AN4.js +1 -0
  31. package/dist/chunks/chunk-Y2NQXJ2Q.js +5 -0
  32. package/dist/chunks/{chunk-DWROB2J6.js → chunk-YNH6AUGE.js} +1 -1
  33. package/dist/chunks/cli-WZ5H6EPA.js +2 -0
  34. package/dist/chunks/configuration-command-BASDSNVK.js +2 -0
  35. package/dist/chunks/{continual-OJYXVTIZ.js → continual-6EW2SLGL.js} +1 -1
  36. package/dist/chunks/core-commands-YQTVPPLJ.js +2 -0
  37. package/dist/chunks/desktop-test-JITAYXCK.js +3 -0
  38. package/dist/chunks/dist-5C6RYTQQ.js +2 -0
  39. package/dist/chunks/{extension-AZRG5IPK.js → extension-ZKWQ3ZPJ.js} +1 -1
  40. package/dist/chunks/{help-6IMGNP7A.js → help-SDEZHWZL.js} +1 -1
  41. package/dist/chunks/{opchat-OS7WAVZO.js → opchat-IOP37GN3.js} +1 -1
  42. package/dist/chunks/organizations-4LQEILYG.js +2 -0
  43. package/dist/chunks/{profile-A3YR3WVU.js → profile-MVLYUDLU.js} +1 -1
  44. package/dist/chunks/project-agent-DALYNEZ4.js +2 -0
  45. package/dist/chunks/sandbox-command-VHCKLKN5.js +2 -0
  46. package/dist/chunks/{sandbox-template-FK2TGQPK.js → sandbox-template-WY7XIMDK.js} +1 -1
  47. package/dist/chunks/{src-UIX7LWM7.js → src-22KEI2VU.js} +1 -1
  48. package/dist/chunks/{src-RZFKQSHW.js → src-DT7YDHH6.js} +2 -2
  49. package/dist/chunks/taskset-YPKY3HUM.js +2 -0
  50. package/dist/chunks/{teams-bot-PASMNRFS.js → teams-bot-47H7LRFD.js} +1 -1
  51. package/dist/chunks/training-7PST5HZU.js +2 -0
  52. package/dist/chunks/{workspaces-YFAAPNVP.js → workspaces-QCCYGHZG.js} +1 -1
  53. package/dist/cli.js +1 -1
  54. package/dist/index.js +1 -1
  55. package/dist/web/assets/{App-CZo3tYaG.js → App-BzNZ7ycx.js} +28 -28
  56. package/dist/web/assets/{AppDialog-18Y9aU8z.js → AppDialog-C3H3HARP.js} +1 -1
  57. package/dist/web/assets/{AppTerminalPanel-9jAU4wYe.js → AppTerminalPanel-DIXARKfe.js} +2 -2
  58. package/dist/web/assets/{AppsView-BCYnY9mm.js → AppsView-D0xPDTPJ.js} +1 -1
  59. package/dist/web/assets/{BrowserSidebar-BVf3sUAG.js → BrowserSidebar-D5eE9O30.js} +1 -1
  60. package/dist/web/assets/{CartesianChart-iai9Dz1D.js → CartesianChart-KMVbiMJX.js} +1 -1
  61. package/dist/web/assets/{CollaborationTabs-D7bZIwFC.js → CollaborationTabs-C1LTvUbK.js} +1 -1
  62. package/dist/web/assets/{CommandMenu-diFDbKQl.js → CommandMenu-C9elnZaI.js} +1 -1
  63. package/dist/web/assets/{CommunityView-DaLkwOxW.js → CommunityView-BvXxVHmL.js} +1 -1
  64. package/dist/web/assets/{ComposerCreateImproveStrip-B59nTCE7.js → ComposerCreateImproveStrip-Cwu8EaCb.js} +1 -1
  65. package/dist/web/assets/{GetStartedView-BETryURK.js → GetStartedView-BI1j30-I.js} +1 -1
  66. package/dist/web/assets/HostedModelLearningReview-Bwkg3lyV.js +1 -0
  67. package/dist/web/assets/{HostedModelLearningSettings-FCly06RA.js → HostedModelLearningSettings-DhaT1bxX.js} +1 -1
  68. package/dist/web/assets/{LabModelVersionDetailPage-9MzQj6cy.js → LabModelVersionDetailPage-CeSm-sAq.js} +1 -1
  69. package/dist/web/assets/{LabSkillSidebar-BJHO5-J9.js → LabSkillSidebar-BzGs7EC8.js} +1 -1
  70. package/dist/web/assets/{LabsRoute-6jVWrbOO.js → LabsRoute-BQi8W0-2.js} +4 -4
  71. package/dist/web/assets/{MainChatThread-DAoPK8jG.js → MainChatThread-D3KXQ4Te.js} +2 -2
  72. package/dist/web/assets/{MainPane-LDPzuZSj.js → MainPane-J15DRf-n.js} +4 -4
  73. package/dist/web/assets/{MarkdownText-B8URwlq9.js → MarkdownText-BWIVACAt.js} +1 -1
  74. package/dist/web/assets/{Messages-Byk73D9T.js → Messages-BPbo8ih9.js} +1 -1
  75. package/dist/web/assets/{NativeSkillSidebar-BodHqCCH.js → NativeSkillSidebar-BeqI4dXF.js} +1 -1
  76. package/dist/web/assets/{NewExperienceSwitcher-BkUxxlOu.js → NewExperienceSwitcher-BggrQVIi.js} +1 -1
  77. package/dist/web/assets/{NewProjectDialog-BZr2wm-4.js → NewProjectDialog-B4PTFf78.js} +1 -1
  78. package/dist/web/assets/{OutputsPage-C8ZDtD1Y.js → OutputsPage-DChjcyaP.js} +1 -1
  79. package/dist/web/assets/{ProjectsPage-CgfjGsl2.js → ProjectsPage-BdUkyg6I.js} +1 -1
  80. package/dist/web/assets/{RightChatPanelStack-DV3csVka.js → RightChatPanelStack-CLCOzLVJ.js} +1 -1
  81. package/dist/web/assets/{RightSidebarHomePanel-DvLaHLBb.js → RightSidebarHomePanel-qs2Fa4JQ.js} +1 -1
  82. package/dist/web/assets/{ScheduledWorkPage-DtzxPTAL.js → ScheduledWorkPage-DzehKDhk.js} +1 -1
  83. package/dist/web/assets/{SettingsView-C3sVxgPc.js → SettingsView-DJiJKYWW.js} +3 -3
  84. package/dist/web/assets/{TeamChatView-B-w2nrWF.js → TeamChatView-uGwanVsA.js} +1 -1
  85. package/dist/web/assets/{TerminalOverlay-_X7WVAev.js → TerminalOverlay-DJNdErEp.js} +1 -1
  86. package/dist/web/assets/{TrainingCreationPanel-DaVppW1m.js → TrainingCreationPanel-CwyKMNwt.js} +1 -1
  87. package/dist/web/assets/{TrainingDraftPanel-CVj19T6L.js → TrainingDraftPanel-Rdusv4s_.js} +1 -1
  88. package/dist/web/assets/{UsageSettingsSection-fRTHVjhG.js → UsageSettingsSection-BkRalGcP.js} +1 -1
  89. package/dist/web/assets/{WorkSidebarPanel-CGOQwdIW.js → WorkSidebarPanel-d8PB-XNy.js} +1 -1
  90. package/dist/web/assets/{WorkspaceDiffPanel-D6hbMv14.js → WorkspaceDiffPanel-DfpyLroX.js} +3 -3
  91. package/dist/web/assets/{WorkspaceEnvironmentMenu-rWj1aDI4.js → WorkspaceEnvironmentMenu-DhUUB-lq.js} +1 -1
  92. package/dist/web/assets/{WorkspaceGitDialogs-DVU5SrD-.js → WorkspaceGitDialogs-0juVLtVy.js} +1 -1
  93. package/dist/web/assets/{WorkspaceMonacoEditor-D78JPviN.js → WorkspaceMonacoEditor-Blo5esSN.js} +3 -3
  94. package/dist/web/assets/{arrow-up-right-CnaPKXjg.js → arrow-up-right-BXeo-8KJ.js} +1 -1
  95. package/dist/web/assets/{chat-file-links-D1INEr8r.js → chat-file-links-BEbA_E33.js} +1 -1
  96. package/dist/web/assets/chevron-up-Dx5rir4H.js +1 -0
  97. package/dist/web/assets/{clipboard-B8GTg8tx.js → clipboard-17OIp5F-.js} +1 -1
  98. package/dist/web/assets/{cloud-upload-BlEc_10E.js → cloud-upload-D28o8URw.js} +1 -1
  99. package/dist/web/assets/{cssMode-BiYvezMD.js → cssMode-DDPYV_bh.js} +1 -1
  100. package/dist/web/assets/{folder-open-BaNdbDD5.js → folder-open-CqBlANkk.js} +1 -1
  101. package/dist/web/assets/{folder-plus-BQhz_VxM.js → folder-plus-DkUnvZhx.js} +1 -1
  102. package/dist/web/assets/{git-commit-horizontal-wv523Ooq.js → git-commit-horizontal-BEIomQj0.js} +1 -1
  103. package/dist/web/assets/{htmlMode-BaMdOCq4.js → htmlMode-gF-t3JxJ.js} +1 -1
  104. package/dist/web/assets/{index-DP8vqolj.js → index-Dg_FWrRZ.js} +2 -2
  105. package/dist/web/assets/{info-C0Ova1D9.js → info-n9PKmODI.js} +1 -1
  106. package/dist/web/assets/{jsonMode-BTt0GByK.js → jsonMode-B5DVQ7wE.js} +1 -1
  107. package/dist/web/assets/{lspLanguageFeatures-C-1acLbv.js → lspLanguageFeatures-FK4QlUnB.js} +1 -1
  108. package/dist/web/assets/{minimize-2-CW5KYp0W.js → minimize-2--J7-Zqg1.js} +1 -1
  109. package/dist/web/assets/{monaco.contribution-DoAhyjpn.js → monaco.contribution-CM_Srh4F.js} +2 -2
  110. package/dist/web/assets/{monaco.contribution-P9b5cZU2.js → monaco.contribution-CV2W_Ydj.js} +2 -2
  111. package/dist/web/assets/{monaco.contribution-DyKzYxR3.js → monaco.contribution-DCmsluF_.js} +2 -2
  112. package/dist/web/assets/{monaco.contribution-CpiBa8rP.js → monaco.contribution-DEkLSjvo.js} +2 -2
  113. package/dist/web/assets/{play-jV1i4pfe.js → play-CT6lFZDI.js} +1 -1
  114. package/dist/web/assets/{python-BQnnGrv3.js → python-DQHHAEpa.js} +1 -1
  115. package/dist/web/assets/{refresh-cw-REnkUGNy.js → refresh-cw-Cm-4hHSn.js} +1 -1
  116. package/dist/web/assets/{save-B2WTTCI_.js → save-CwgR_oyc.js} +1 -1
  117. package/dist/web/assets/{square-CRb2lKMC.js → square-DPrPBeHW.js} +1 -1
  118. package/dist/web/assets/{toggleHighContrast-BGsGhGW4.js → toggleHighContrast-C1QZjrPj.js} +1 -1
  119. package/dist/web/assets/{tsMode-BWtSmvFs.js → tsMode-DY4Ji1ac.js} +1 -1
  120. package/dist/web/assets/{upload-B_PICaZn.js → upload-DABGNAIq.js} +1 -1
  121. package/dist/web/assets/{useLocalAgentSchedules-zmmvBnwd.js → useLocalAgentSchedules-D5P28Jej.js} +1 -1
  122. package/dist/web/assets/{wifi-off-CjKTt0zE.js → wifi-off-CJOdJJRb.js} +1 -1
  123. package/dist/web/assets/{workers-CxglqyKV.js → workers-BLjr7D_D.js} +1 -1
  124. package/dist/web/assets/{yaml-DgyPsmb2.js → yaml-eXk00scV.js} +1 -1
  125. package/dist/web/index.html +1 -1
  126. package/package.json +1 -1
  127. package/dist/chunks/actions-command-CZD7U6CC.js +0 -2
  128. package/dist/chunks/app-server-runtime-5XZWU7JL.js +0 -2
  129. package/dist/chunks/apps-NIQBGOGH.js +0 -2
  130. package/dist/chunks/chunk-3YAGJU2X.js +0 -2
  131. package/dist/chunks/chunk-G2VYRU27.js +0 -5
  132. package/dist/chunks/chunk-HZP5U2AA.js +0 -3
  133. package/dist/chunks/chunk-J3WNPOLS.js +0 -2
  134. package/dist/chunks/chunk-NNLI4OWY.js +0 -53
  135. package/dist/chunks/chunk-SS3EG6S2.js +0 -2
  136. package/dist/chunks/chunk-Y7ZYJQGZ.js +0 -2
  137. package/dist/chunks/cli-GWKOPTLS.js +0 -2
  138. package/dist/chunks/configuration-command-OAZNWOFX.js +0 -2
  139. package/dist/chunks/core-commands-VGUAOSWS.js +0 -2
  140. package/dist/chunks/desktop-test-SPTFR43A.js +0 -3
  141. package/dist/chunks/dist-UA2RQUA4.js +0 -2
  142. package/dist/chunks/organizations-QPACFCMH.js +0 -2
  143. package/dist/chunks/project-agent-5H6VCDAY.js +0 -2
  144. package/dist/chunks/sandbox-command-RKUHXCZJ.js +0 -2
  145. package/dist/chunks/taskset-PISBOILQ.js +0 -2
  146. package/dist/chunks/training-2NDOWH5S.js +0 -2
  147. package/dist/web/assets/HostedModelLearningReview-D5JtAiLZ.js +0 -1
  148. package/dist/web/assets/chevron-up-Bx5d_Wmr.js +0 -1
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{c as j,e as E,f as z,g as H,i as N,kb as O}from"./chunk-NNLI4OWY.js";import{b as i}from"./chunk-ES2ISFJC.js";import{a as k,c as I,f as A,h as d}from"./chunk-H7IWJN7L.js";import{a}from"./chunk-FTQLQJQV.js";import b from"node:path";import{AsyncLocalStorage as V}from"node:async_hooks";import{promises as M}from"node:fs";var B=new V;function pe(e,t=!1){let n=B.getStore();n&&(t&&(n.length=0),n.push(e))}a(pe,"onStartupFailure");async function fe(e,t){await O(e);let n;try{n=await H(b.join(d(e).runtime,"server-owner"),100)}catch(s){if(s instanceof I&&s.issue.code==="STORAGE_BUSY"){let o=await N(b.join(d(e).runtime,"endpoint.json"),()=>null);throw new I({code:"RUNTIME_ALREADY_RUNNING",path:e,message:"An OpenPond runtime already owns this home.",action:o?.url?`Connect to the existing runtime at ${o.url}, or stop it before starting another.`:"Stop the existing runtime before starting another with this home."})}throw s}let r=[];try{let s=await k(e,()=>B.run(r,t)),o=s.close.bind(s);r.length=0;let l;return{...s,close:a(()=>l??=(async()=>{try{await k(e,o)}finally{await M.rm(b.join(d(e).runtime,"endpoint.json"),{force:!0}),await n()}})(),"close")}}catch(s){try{for(let o of r.reverse())await Promise.resolve().then(()=>k(e,o)).catch(()=>{});await M.rm(b.join(d(e).runtime,"endpoint.json"),{force:!0})}finally{await n()}throw s}}a(fe,"ownHomeRuntime");async function me(e,t,n){await E(b.join(d(e).runtime,"endpoint.json"),JSON.stringify({schemaVersion:"openpond.runtimeEndpoint.v1",pid:process.pid,url:t,serverId:n}))}a(me,"publishRuntimeEndpoint");function ge(e){if(!e.maxContextTokens||!e.usableContextTokens)return{shouldCompact:!1,projectedTokens:e.projectedTokens,thresholdTokens:Number.MAX_SAFE_INTEGER,usableContextTokens:0,maxContextTokens:0,tokenSource:"heuristic"};let t=Math.max(.01,Math.min(1,(e.triggerPercent??85)/100)),n=Math.max(1,Math.floor(e.usableContextTokens*t));return{shouldCompact:e.projectedTokens>=n,projectedTokens:e.projectedTokens,thresholdTokens:n,usableContextTokens:e.usableContextTokens,maxContextTokens:e.maxContextTokens,tokenSource:"heuristic"}}a(ge,"agentCompactionDecision");async function be(e){await e.started();try{return await e.compact()}catch(t){throw await e.failed(t),t}}a(be,"runAgentCompaction");async function xe(e){let t=e.host.projectEvents(e.events),n=e.host.selectEvents(t,e.maxContextTokens),{summaryEvents:r,preservedEvents:s,preservedEventIds:o}=n;if(r.length===0)throw new Error("There is not enough prior context to compact.");let l=e.host.normalizeRecords(r),c=e.host.normalizeRecords(s),h=e.host.buildFileLedger(e.host.normalizeRecords(t)),u=e.host.serializeRecords(l,e.host.inputCharBudget(e.maxContextTokens));if(!u.text.trim())throw new Error("There is not enough prior context to compact.");let p=e.host.buildSummaryMessages({serializedHistory:u.text,fileLedger:h}),v=Date.now(),w=(await e.host.streamSummary({model:e.model,messages:p,signal:e.signal})).trim(),R=Date.now()-v;if(!w)throw new Error("Compaction summary was empty.");let P=e.host.estimateProjection({events:t,preservedEvents:s,summary:w}),_=e.host.createMetrics({sourceEvents:t.length,summarizedEvents:r.length,preservedEvents:s.length,sourceRecords:u.sourceRecordCount,includedRecords:u.includedRecordCount,omittedRecords:u.omittedRecordCount,preservedRecords:c.length,truncatedRecords:u.truncatedRecordCount,summaryInputTruncated:u.inputTruncated,sourceSelectionStrategy:u.selectionStrategy,summaryInputChars:u.inputChars,retainedTailTokens:n.retainedTailTokens,retainedTailBudgetTokens:n.retainedTailBudgetTokens,finalProviderContextTokens:P.inputTokensAfter,durationMs:R,fileLedgerEntries:h.length,splitTurnId:n.splitTurnId});return{summary:w,model:e.model,compactedThroughEventId:t[t.length-1]?.id??null,compactedThroughTurnId:e.host.lastTurnId(t),preservedFromEventId:s[0]?.id??null,preservedEventIds:o,preservedResourceRefs:e.host.durableResourceRefs(e.events),sourceEventCount:r.length,preservedEventCount:s.length,fileLedger:h,inputTokensBefore:P.inputTokensBefore,inputTokensAfter:P.inputTokensAfter,maxContextTokens:e.maxContextTokens,tokenSource:"heuristic",metrics:_}}a(xe,"runAgentCompactionProgram");var y="2026-09-20",ye=["initialize","initialized","runtime/capabilities","thread/start","thread/resume","thread/read","turn/start","turn/steer","task/inbox","task/queue","task/inputUpdate","turn/interrupt","approval/resolve","userInput/resolve","profile/workflows","profile/evaluations","profile/trainingSource","profile/evaluations/prepare","profile/evaluations/run","profile/evaluations/runSuite","profile/evaluations/executeCase","profile/evaluations/executeRun","profile/evaluations/compare","profile/evaluations/report","harness/inspect","harness/proposalReview","harness/review","harness/acceptEvaluationReview","harness/materializeEvaluationTaskset","harness/runEvaluationBaseline","harness/validate","harness/backgroundReview","harness/diff","harness/rollback","refiner/inspect","refiner/update","refiner/activate","refiner/rollback"],U=i.object({jsonrpc:i.literal("2.0"),id:i.union([i.string(),i.number()]),method:i.string().trim().min(1),params:i.unknown().optional()}).strict(),$=i.object({jsonrpc:i.literal("2.0"),method:i.string().trim().min(1),params:i.unknown().optional()}).strict(),G=i.object({jsonrpc:i.literal("2.0"),id:i.union([i.string(),i.number()]),result:i.unknown()}).strict(),W=i.object({jsonrpc:i.literal("2.0"),id:i.union([i.string(),i.number(),i.null()]),error:i.object({code:i.number().int(),message:i.string(),data:i.unknown().optional()}).strict()}).strict(),Se=i.union([U,$,G,W]),K=i.object({protocolVersion:i.string().trim().min(1),client:i.object({name:i.string().trim().min(1),version:i.string().trim().min(1)}).strict(),capabilities:i.record(i.string(),i.unknown()).default({})}).strict(),S=class{static{a(this,"AgentJsonRpcDispatcher")}#e;#r=null;#t=!1;constructor(t){this.#e=t}get initialized(){return this.#t}async handle(t){let n=$.safeParse(t);if(n.success&&!("id"in t)){if(n.data.method==="initialized"){if(!this.#r)throw new f(-32002,"initialize must be called first");this.#t=!0}return null}let r=U.safeParse(t);if(!r.success)return q(null,-32600,"Invalid Request",r.error.flatten());let s=r.data;try{let o=await this.#n(s.method,s.params);return{jsonrpc:"2.0",id:s.id,result:o}}catch(o){let l=o instanceof f?o:new f(-32603,o instanceof Error?o.message:String(o));return q(s.id,l.code,l.message,l.data)}}async#n(t,n){if(t==="initialize"){let r=K.parse(n);if(r.protocolVersion!==y)throw new f(-32001,"Incompatible agent protocol version",{requested:r.protocolVersion,supported:y});return this.#r=r,{protocolVersion:y,server:{name:"openpond-app-server",version:"1"},capabilities:await this.#e.capabilities()}}if(!this.#t)throw new f(-32002,"initialized notification is required");switch(t){case"runtime/capabilities":return this.#e.capabilities(n);case"thread/start":return this.#e.threadStart(n);case"thread/resume":return this.#e.threadResume(n);case"thread/read":return this.#e.threadRead(n);case"turn/start":return this.#e.turnStart(n);case"turn/steer":return this.#e.turnSteer(n);case"task/inbox":return this.#e.taskInbox(n);case"task/queue":return this.#e.taskQueue(n);case"task/inputUpdate":return this.#e.taskInputUpdate(n);case"turn/interrupt":return this.#e.turnInterrupt(n);case"approval/resolve":return this.#e.approvalResolve(n);case"userInput/resolve":return this.#e.userInputResolve(n);case"profile/workflows":return this.#e.profileWorkflows(n);case"profile/evaluations":return this.#e.profileEvaluations(n);case"profile/trainingSource":return this.#e.profileTrainingSource(n);case"profile/evaluations/prepare":return this.#e.profileEvaluationPrepare(n);case"profile/evaluations/run":return this.#e.profileEvaluationRun(n);case"profile/evaluations/runSuite":return this.#e.profileEvaluationRunSuite(n);case"profile/evaluations/executeCase":return this.#e.profileEvaluationExecuteCase(n);case"profile/evaluations/executeRun":return this.#e.profileEvaluationExecuteRun(n);case"profile/evaluations/compare":return this.#e.profileEvaluationCompare(n);case"profile/evaluations/report":return this.#e.profileEvaluationReport(n);case"harness/inspect":return this.#e.harnessInspect(n);case"harness/proposalReview":return this.#e.harnessProposalReview(n);case"harness/review":return this.#e.harnessReview(n);case"harness/acceptEvaluationReview":return this.#e.harnessAcceptEvaluationReview(n);case"harness/materializeEvaluationTaskset":return this.#e.harnessMaterializeEvaluationTaskset(n);case"harness/runEvaluationBaseline":return this.#e.harnessRunEvaluationBaseline(n);case"harness/validate":return this.#e.harnessValidate(n);case"harness/backgroundReview":return this.#e.harnessBackgroundReview(n);case"harness/diff":return this.#e.harnessDiff(n);case"harness/rollback":return this.#e.harnessRollback(n);case"refiner/inspect":return this.#e.refinerInspect(n);case"refiner/update":return this.#e.refinerUpdate(n);case"refiner/activate":return this.#e.refinerActivate(n);case"refiner/rollback":return this.#e.refinerRollback(n);default:throw new f(-32601,`Method not found: ${t}`)}}},f=class extends Error{static{a(this,"JsonRpcDispatchError")}code;data;constructor(t,n,r){super(n),this.code=t,this.data=r}};function q(e,t,n,r){return{jsonrpc:"2.0",id:e,error:{code:t,message:n,...r===void 0?{}:{data:r}}}}a(q,"jsonRpcError");import{createHash as Q}from"node:crypto";function C(e){if(e===null||typeof e=="boolean"||typeof e=="string")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new Error("Canonical JSON cannot encode a non-finite number.");return e}if(Array.isArray(e))return e.map(C);if(typeof e=="object"){let t={};for(let n of Object.keys(e).sort()){let r=e[n];r!==void 0&&(t[n]=C(r))}return t}throw new Error(`Canonical JSON cannot encode ${typeof e}.`)}a(C,"canonicalJson");function g(e){return Q("sha256").update(JSON.stringify(C(e)),"utf8").digest("hex")}a(g,"canonicalHash");var Y=i.enum(["thread.started","thread.resumed","turn.started","turn.steered","turn.interrupted","turn.completed","turn.failed","item.started","item.delta","item.completed","assistant.reasoning.delta","assistant.delta","tool.started","tool.completed","approval.requested","approval.resolved","user_input.requested","user_input.resolved","compaction.started","compaction.completed","harness.admitted","harness.refiner.queued","harness.refiner.started","harness.refiner.completed","harness.refiner.failed","diagnostic"]),X=i.object({sequence:i.number().int().nonnegative(),name:Y,source:i.enum(["runtime","provider","tool","host","refiner"]),status:i.string().trim().min(1).nullable().default(null),threadId:i.string().trim().min(1),turnId:i.string().trim().min(1).nullable().default(null),callId:i.string().trim().min(1).nullable().default(null),output:i.string().nullable().default(null),error:i.string().nullable().default(null),data:i.record(i.string(),i.unknown()).default({})}).strict();function He(e){return g(X.parse(e))}a(He,"canonicalEventHash");import{once as Z}from"node:events";import{createInterface as ee}from"node:readline";async function D(e){let t=new S(e.host),n=Promise.resolve(),r=[],s=a(u=>(n=n.then(async()=>{e.writable.write(`${JSON.stringify(u)}
2
+ import{Bb as O,c as j,e as E,f as z,g as H,i as N}from"./chunk-F4WS5QIT.js";import{b as i}from"./chunk-ES2ISFJC.js";import{a as k,c as I,f as A,h as d}from"./chunk-H7IWJN7L.js";import{a}from"./chunk-FTQLQJQV.js";import b from"node:path";import{AsyncLocalStorage as V}from"node:async_hooks";import{promises as M}from"node:fs";var B=new V;function pe(e,t=!1){let n=B.getStore();n&&(t&&(n.length=0),n.push(e))}a(pe,"onStartupFailure");async function fe(e,t){await O(e);let n;try{n=await H(b.join(d(e).runtime,"server-owner"),100)}catch(s){if(s instanceof I&&s.issue.code==="STORAGE_BUSY"){let o=await N(b.join(d(e).runtime,"endpoint.json"),()=>null);throw new I({code:"RUNTIME_ALREADY_RUNNING",path:e,message:"An OpenPond runtime already owns this home.",action:o?.url?`Connect to the existing runtime at ${o.url}, or stop it before starting another.`:"Stop the existing runtime before starting another with this home."})}throw s}let r=[];try{let s=await k(e,()=>B.run(r,t)),o=s.close.bind(s);r.length=0;let l;return{...s,close:a(()=>l??=(async()=>{try{await k(e,o)}finally{await M.rm(b.join(d(e).runtime,"endpoint.json"),{force:!0}),await n()}})(),"close")}}catch(s){try{for(let o of r.reverse())await Promise.resolve().then(()=>k(e,o)).catch(()=>{});await M.rm(b.join(d(e).runtime,"endpoint.json"),{force:!0})}finally{await n()}throw s}}a(fe,"ownHomeRuntime");async function me(e,t,n){await E(b.join(d(e).runtime,"endpoint.json"),JSON.stringify({schemaVersion:"openpond.runtimeEndpoint.v1",pid:process.pid,url:t,serverId:n}))}a(me,"publishRuntimeEndpoint");function ge(e){if(!e.maxContextTokens||!e.usableContextTokens)return{shouldCompact:!1,projectedTokens:e.projectedTokens,thresholdTokens:Number.MAX_SAFE_INTEGER,usableContextTokens:0,maxContextTokens:0,tokenSource:"heuristic"};let t=Math.max(.01,Math.min(1,(e.triggerPercent??85)/100)),n=Math.max(1,Math.floor(e.usableContextTokens*t));return{shouldCompact:e.projectedTokens>=n,projectedTokens:e.projectedTokens,thresholdTokens:n,usableContextTokens:e.usableContextTokens,maxContextTokens:e.maxContextTokens,tokenSource:"heuristic"}}a(ge,"agentCompactionDecision");async function be(e){await e.started();try{return await e.compact()}catch(t){throw await e.failed(t),t}}a(be,"runAgentCompaction");async function xe(e){let t=e.host.projectEvents(e.events),n=e.host.selectEvents(t,e.maxContextTokens),{summaryEvents:r,preservedEvents:s,preservedEventIds:o}=n;if(r.length===0)throw new Error("There is not enough prior context to compact.");let l=e.host.normalizeRecords(r),c=e.host.normalizeRecords(s),h=e.host.buildFileLedger(e.host.normalizeRecords(t)),u=e.host.serializeRecords(l,e.host.inputCharBudget(e.maxContextTokens));if(!u.text.trim())throw new Error("There is not enough prior context to compact.");let p=e.host.buildSummaryMessages({serializedHistory:u.text,fileLedger:h}),v=Date.now(),w=(await e.host.streamSummary({model:e.model,messages:p,signal:e.signal})).trim(),R=Date.now()-v;if(!w)throw new Error("Compaction summary was empty.");let P=e.host.estimateProjection({events:t,preservedEvents:s,summary:w}),_=e.host.createMetrics({sourceEvents:t.length,summarizedEvents:r.length,preservedEvents:s.length,sourceRecords:u.sourceRecordCount,includedRecords:u.includedRecordCount,omittedRecords:u.omittedRecordCount,preservedRecords:c.length,truncatedRecords:u.truncatedRecordCount,summaryInputTruncated:u.inputTruncated,sourceSelectionStrategy:u.selectionStrategy,summaryInputChars:u.inputChars,retainedTailTokens:n.retainedTailTokens,retainedTailBudgetTokens:n.retainedTailBudgetTokens,finalProviderContextTokens:P.inputTokensAfter,durationMs:R,fileLedgerEntries:h.length,splitTurnId:n.splitTurnId});return{summary:w,model:e.model,compactedThroughEventId:t[t.length-1]?.id??null,compactedThroughTurnId:e.host.lastTurnId(t),preservedFromEventId:s[0]?.id??null,preservedEventIds:o,preservedResourceRefs:e.host.durableResourceRefs(e.events),sourceEventCount:r.length,preservedEventCount:s.length,fileLedger:h,inputTokensBefore:P.inputTokensBefore,inputTokensAfter:P.inputTokensAfter,maxContextTokens:e.maxContextTokens,tokenSource:"heuristic",metrics:_}}a(xe,"runAgentCompactionProgram");var y="2026-09-20",ye=["initialize","initialized","runtime/capabilities","thread/start","thread/resume","thread/read","turn/start","turn/steer","task/inbox","task/queue","task/inputUpdate","turn/interrupt","approval/resolve","userInput/resolve","profile/workflows","profile/evaluations","profile/trainingSource","profile/evaluations/prepare","profile/evaluations/run","profile/evaluations/runSuite","profile/evaluations/executeCase","profile/evaluations/executeRun","profile/evaluations/compare","profile/evaluations/report","harness/inspect","harness/proposalReview","harness/review","harness/acceptEvaluationReview","harness/materializeEvaluationTaskset","harness/runEvaluationBaseline","harness/validate","harness/backgroundReview","harness/diff","harness/rollback","refiner/inspect","refiner/update","refiner/activate","refiner/rollback"],U=i.object({jsonrpc:i.literal("2.0"),id:i.union([i.string(),i.number()]),method:i.string().trim().min(1),params:i.unknown().optional()}).strict(),$=i.object({jsonrpc:i.literal("2.0"),method:i.string().trim().min(1),params:i.unknown().optional()}).strict(),G=i.object({jsonrpc:i.literal("2.0"),id:i.union([i.string(),i.number()]),result:i.unknown()}).strict(),W=i.object({jsonrpc:i.literal("2.0"),id:i.union([i.string(),i.number(),i.null()]),error:i.object({code:i.number().int(),message:i.string(),data:i.unknown().optional()}).strict()}).strict(),Se=i.union([U,$,G,W]),K=i.object({protocolVersion:i.string().trim().min(1),client:i.object({name:i.string().trim().min(1),version:i.string().trim().min(1)}).strict(),capabilities:i.record(i.string(),i.unknown()).default({})}).strict(),S=class{static{a(this,"AgentJsonRpcDispatcher")}#e;#r=null;#t=!1;constructor(t){this.#e=t}get initialized(){return this.#t}async handle(t){let n=$.safeParse(t);if(n.success&&!("id"in t)){if(n.data.method==="initialized"){if(!this.#r)throw new f(-32002,"initialize must be called first");this.#t=!0}return null}let r=U.safeParse(t);if(!r.success)return q(null,-32600,"Invalid Request",r.error.flatten());let s=r.data;try{let o=await this.#n(s.method,s.params);return{jsonrpc:"2.0",id:s.id,result:o}}catch(o){let l=o instanceof f?o:new f(-32603,o instanceof Error?o.message:String(o));return q(s.id,l.code,l.message,l.data)}}async#n(t,n){if(t==="initialize"){let r=K.parse(n);if(r.protocolVersion!==y)throw new f(-32001,"Incompatible agent protocol version",{requested:r.protocolVersion,supported:y});return this.#r=r,{protocolVersion:y,server:{name:"openpond-app-server",version:"1"},capabilities:await this.#e.capabilities()}}if(!this.#t)throw new f(-32002,"initialized notification is required");switch(t){case"runtime/capabilities":return this.#e.capabilities(n);case"thread/start":return this.#e.threadStart(n);case"thread/resume":return this.#e.threadResume(n);case"thread/read":return this.#e.threadRead(n);case"turn/start":return this.#e.turnStart(n);case"turn/steer":return this.#e.turnSteer(n);case"task/inbox":return this.#e.taskInbox(n);case"task/queue":return this.#e.taskQueue(n);case"task/inputUpdate":return this.#e.taskInputUpdate(n);case"turn/interrupt":return this.#e.turnInterrupt(n);case"approval/resolve":return this.#e.approvalResolve(n);case"userInput/resolve":return this.#e.userInputResolve(n);case"profile/workflows":return this.#e.profileWorkflows(n);case"profile/evaluations":return this.#e.profileEvaluations(n);case"profile/trainingSource":return this.#e.profileTrainingSource(n);case"profile/evaluations/prepare":return this.#e.profileEvaluationPrepare(n);case"profile/evaluations/run":return this.#e.profileEvaluationRun(n);case"profile/evaluations/runSuite":return this.#e.profileEvaluationRunSuite(n);case"profile/evaluations/executeCase":return this.#e.profileEvaluationExecuteCase(n);case"profile/evaluations/executeRun":return this.#e.profileEvaluationExecuteRun(n);case"profile/evaluations/compare":return this.#e.profileEvaluationCompare(n);case"profile/evaluations/report":return this.#e.profileEvaluationReport(n);case"harness/inspect":return this.#e.harnessInspect(n);case"harness/proposalReview":return this.#e.harnessProposalReview(n);case"harness/review":return this.#e.harnessReview(n);case"harness/acceptEvaluationReview":return this.#e.harnessAcceptEvaluationReview(n);case"harness/materializeEvaluationTaskset":return this.#e.harnessMaterializeEvaluationTaskset(n);case"harness/runEvaluationBaseline":return this.#e.harnessRunEvaluationBaseline(n);case"harness/validate":return this.#e.harnessValidate(n);case"harness/backgroundReview":return this.#e.harnessBackgroundReview(n);case"harness/diff":return this.#e.harnessDiff(n);case"harness/rollback":return this.#e.harnessRollback(n);case"refiner/inspect":return this.#e.refinerInspect(n);case"refiner/update":return this.#e.refinerUpdate(n);case"refiner/activate":return this.#e.refinerActivate(n);case"refiner/rollback":return this.#e.refinerRollback(n);default:throw new f(-32601,`Method not found: ${t}`)}}},f=class extends Error{static{a(this,"JsonRpcDispatchError")}code;data;constructor(t,n,r){super(n),this.code=t,this.data=r}};function q(e,t,n,r){return{jsonrpc:"2.0",id:e,error:{code:t,message:n,...r===void 0?{}:{data:r}}}}a(q,"jsonRpcError");import{createHash as Q}from"node:crypto";function C(e){if(e===null||typeof e=="boolean"||typeof e=="string")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new Error("Canonical JSON cannot encode a non-finite number.");return e}if(Array.isArray(e))return e.map(C);if(typeof e=="object"){let t={};for(let n of Object.keys(e).sort()){let r=e[n];r!==void 0&&(t[n]=C(r))}return t}throw new Error(`Canonical JSON cannot encode ${typeof e}.`)}a(C,"canonicalJson");function g(e){return Q("sha256").update(JSON.stringify(C(e)),"utf8").digest("hex")}a(g,"canonicalHash");var Y=i.enum(["thread.started","thread.resumed","turn.started","turn.steered","turn.interrupted","turn.completed","turn.failed","item.started","item.delta","item.completed","assistant.reasoning.delta","assistant.delta","tool.started","tool.completed","approval.requested","approval.resolved","user_input.requested","user_input.resolved","compaction.started","compaction.completed","harness.admitted","harness.refiner.queued","harness.refiner.started","harness.refiner.completed","harness.refiner.failed","diagnostic"]),X=i.object({sequence:i.number().int().nonnegative(),name:Y,source:i.enum(["runtime","provider","tool","host","refiner"]),status:i.string().trim().min(1).nullable().default(null),threadId:i.string().trim().min(1),turnId:i.string().trim().min(1).nullable().default(null),callId:i.string().trim().min(1).nullable().default(null),output:i.string().nullable().default(null),error:i.string().nullable().default(null),data:i.record(i.string(),i.unknown()).default({})}).strict();function He(e){return g(X.parse(e))}a(He,"canonicalEventHash");import{once as Z}from"node:events";import{createInterface as ee}from"node:readline";async function D(e){let t=new S(e.host),n=Promise.resolve(),r=[],s=a(u=>(n=n.then(async()=>{e.writable.write(`${JSON.stringify(u)}
3
3
  `)||await Z(e.writable,"drain")}),n),"write"),o=a(()=>{if(!(!t.initialized||r.length===0))for(let u of r.splice(0))s(u)},"flushPendingNotifications"),l=e.host.subscribe?.(u=>{if(!t.initialized){r.push(u);return}s(u)}),c=new Set,h=ee({input:e.readable,crlfDelay:1/0});try{for await(let u of h){if(!u.trim())continue;let p;try{p=JSON.parse(u)}catch{await s({jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}});continue}let v=(async()=>{let R=await t.handle(p);R&&await s(R),o()})(),w=p&&typeof p=="object"&&"method"in p?p.method:null;if(w==="initialize"||w==="initialized"){await v;continue}c.add(v),v.finally(()=>c.delete(v))}await Promise.all(c),await n}finally{l?.()}}a(D,"runAgentJsonlServer");var T=i.object({threadId:i.string().trim().min(1)}).passthrough(),te=i.object({session:i.unknown()}).strict(),x=T.extend({input:i.unknown()}),re=x.extend({idempotencyKey:i.string().trim().min(1).max(200)}),ne=x.extend({inputId:i.string().trim().min(1)}),ae=T.extend({reason:i.string().trim().min(1).optional()}),ie=i.object({approvalId:i.string().trim().min(1),input:i.unknown()}).strict();function L(e){let t=a(async(r,s,o)=>{let l=performance.now();e.telemetry?.({method:r,phase:"started",threadId:s,durationMs:null,errorClass:null});try{let c=await o();return e.telemetry?.({method:r,phase:"completed",threadId:s,durationMs:performance.now()-l,errorClass:null}),c}catch(c){throw e.telemetry?.({method:r,phase:"failed",threadId:s,durationMs:performance.now()-l,errorClass:c instanceof Error?c.name:"UnknownError"}),c}},"run"),n=a(async(r,s="thread/read")=>{let{threadId:o}=T.parse(r);return t(s,o,async()=>{let[l,c,h]=await Promise.all([e.readThread(o),e.listTurns(o),e.listEvents(o)]);return{thread:l,turns:c,events:h}})},"threadRead");return{capabilities:a(r=>t("runtime/capabilities",null,()=>e.capabilities(r)),"capabilities"),threadStart:a(async r=>t("thread/start",null,async()=>({thread:await e.createThread(te.parse(r).session)})),"threadStart"),threadResume:a(r=>n(r,"thread/resume"),"threadResume"),threadRead:n,turnStart:a(async r=>{let s=x.parse(r);return t("turn/start",s.threadId,async()=>({turn:await e.startTurn(s.threadId,s.input)}))},"turnStart"),turnSteer:a(async r=>{let s=x.parse(r);return t("turn/steer",s.threadId,async()=>({receipt:await e.steerTurn(s.threadId,s.input)}))},"turnSteer"),taskInbox:a(async r=>{let{threadId:s}=T.parse(r);return t("task/inbox",s,()=>e.readTaskInbox(s))},"taskInbox"),taskQueue:a(async r=>{let s=re.parse(r);return t("task/queue",s.threadId,()=>e.queueTaskInput(s.threadId,s.input,s.idempotencyKey))},"taskQueue"),taskInputUpdate:a(async r=>{let s=ne.parse(r);return t("task/inputUpdate",s.threadId,()=>e.updateTaskInput(s.threadId,s.inputId,s.input))},"taskInputUpdate"),turnInterrupt:a(async r=>{let s=ae.parse(r);return t("turn/interrupt",s.threadId,async()=>({turn:await e.interruptTurn(s.threadId,s.reason)}))},"turnInterrupt"),approvalResolve:a(async r=>{let s=ie.parse(r);return t("approval/resolve",null,async()=>({approval:await e.resolveApproval(s.approvalId,s.input)}))},"approvalResolve"),userInputResolve:a(async r=>{let s=x.parse(r);return t("userInput/resolve",s.threadId,async()=>(e.isTurnActive(s.threadId)&&await e.waitForTurnSettlement(s.threadId),{turn:await e.startTurn(s.threadId,s.input)}))},"userInputResolve"),profileWorkflows:a(()=>t("profile/workflows",null,()=>e.listProfileWorkflows()),"profileWorkflows"),profileEvaluations:a(()=>t("profile/evaluations",null,()=>e.listProfileEvaluations()),"profileEvaluations"),profileTrainingSource:a(()=>t("profile/trainingSource",null,()=>e.loadProfileTrainingSource()),"profileTrainingSource"),profileEvaluationPrepare:a(r=>t("profile/evaluations/prepare",null,()=>e.prepareProfileEvaluationRun(r)),"profileEvaluationPrepare"),profileEvaluationRun:a(r=>t("profile/evaluations/run",null,()=>e.runPreparedProfileEvaluation(r)),"profileEvaluationRun"),profileEvaluationRunSuite:a(r=>t("profile/evaluations/runSuite",null,()=>e.runProfileEvaluationSuite(r)),"profileEvaluationRunSuite"),profileEvaluationExecuteCase:a(r=>t("profile/evaluations/executeCase",null,()=>e.executeProfileEvaluationCase(r)),"profileEvaluationExecuteCase"),profileEvaluationExecuteRun:a(r=>t("profile/evaluations/executeRun",null,()=>e.executeProfileEvaluationRun(r)),"profileEvaluationExecuteRun"),profileEvaluationCompare:a(r=>t("profile/evaluations/compare",null,()=>e.compareProfileEvaluationRuns(r)),"profileEvaluationCompare"),profileEvaluationReport:a(r=>t("profile/evaluations/report",null,()=>e.buildProfileEvaluationReport(r)),"profileEvaluationReport"),harnessInspect:a(()=>t("harness/inspect",null,()=>e.inspectHarness()),"harnessInspect"),harnessProposalReview:a(r=>t("harness/proposalReview",null,()=>e.reviewHarnessProposal(r)),"harnessProposalReview"),harnessReview:a(r=>t("harness/review",null,()=>e.reviewHarness(r)),"harnessReview"),harnessAcceptEvaluationReview:a(r=>t("harness/acceptEvaluationReview",null,()=>e.acceptHarnessEvaluationReview(r)),"harnessAcceptEvaluationReview"),harnessMaterializeEvaluationTaskset:a(r=>t("harness/materializeEvaluationTaskset",null,()=>e.materializeHarnessEvaluationTaskset(r)),"harnessMaterializeEvaluationTaskset"),harnessRunEvaluationBaseline:a(r=>t("harness/runEvaluationBaseline",null,()=>e.runHarnessEvaluationBaseline(r)),"harnessRunEvaluationBaseline"),harnessValidate:a(()=>t("harness/validate",null,()=>e.validateHarness()),"harnessValidate"),harnessBackgroundReview:a(r=>t("harness/backgroundReview",null,()=>e.updateHarnessBackgroundReview(r)),"harnessBackgroundReview"),harnessDiff:a(r=>t("harness/diff",null,()=>e.diffHarness(r)),"harnessDiff"),harnessRollback:a(r=>t("harness/rollback",null,()=>e.rollbackHarness(r)),"harnessRollback"),refinerInspect:a(()=>t("refiner/inspect",null,()=>e.inspectRefiner()),"refinerInspect"),refinerUpdate:a(r=>t("refiner/update",null,()=>e.updateRefiner(r)),"refinerUpdate"),refinerActivate:a(r=>t("refiner/activate",null,()=>e.activateRefiner(r)),"refinerActivate"),refinerRollback:a(r=>t("refiner/rollback",null,()=>e.rollbackRefiner(r)),"refinerRollback"),subscribe:e.subscribeEvents&&e.eventNotification?r=>e.subscribeEvents(s=>r(e.eventNotification(s))):void 0}}a(L,"createAgentRuntimeService");var m=i.string().regex(/^[a-f0-9]{64}$/),et=i.object({harnessReleaseHash:m,instructionsHash:m,skillHashes:i.record(i.string(),m),agentAssetHashes:i.record(i.string(),m),toolCatalogHash:m,memoryRevision:i.number().int().nonnegative().nullable()}).strict(),se=i.object({protocolVersion:i.string().trim().min(1),threadId:i.string().trim().min(1),turnId:i.string().trim().min(1),harnessReleaseHash:m,toolCatalogHash:m,context:i.record(i.string(),i.unknown()),pendingInteraction:i.record(i.string(),i.unknown()).nullable(),usage:i.record(i.string(),i.unknown())}).strict();function tt(e){return g(se.parse(e))}a(tt,"checkpointHash");function rt(e){return[e.system,...e.harnessInstructions,...e.skillInstructions,...e.hostInstructions??[]].map(t=>t.trim()).filter(Boolean).join(`
4
4
 
5
5
  `)}a(rt,"materializeAgentPrompt");function st(e){let t=new Set,n=[...e].map(o=>{let l=o.name.trim();if(!l)throw new Error("Agent tool names cannot be empty.");if(t.has(l))throw new Error(`Duplicate agent tool: ${l}.`);if(t.add(l),!o.unavailableReason&&!o.executorAvailable)throw new Error(`Agent tool ${l} is declared as available without an executor.`);return{...o,name:l}}).sort((o,l)=>o.name.localeCompare(l.name)),r=n.filter(o=>!o.unavailableReason).map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema})),s=n.map(o=>({name:o.name,displayLabel:o.displayLabel??o.name,placement:o.placement,available:!o.unavailableReason,unavailableReason:o.unavailableReason??null}));return{byName:new Map(n.map(o=>[o.name,o])),tools:n,modelTools:r,capabilities:s,hash:g({modelTools:r,capabilities:s})}}a(st,"createAgentToolCatalogProjection");async function ot(e,t){let n=e.byName.get(t.name);if(!n)throw new Error(`Unknown agent tool: ${t.name}.`);if(n.unavailableReason)throw new Error(`Agent tool ${t.name} is unavailable: ${n.unavailableReason}`);if(!n.execute)throw new Error(`Agent tool ${t.name} has no executor.`);let r=n.validateArguments?n.validateArguments(t.arguments):t.arguments;return n.execute(r,t.context)}a(ot,"executeProjectedAgentTool");var F=class{static{a(this,"TaskSignals")}#e=new Map;notify(t){for(let n of[...this.#e.get(t)??[]])n()}subscribe(t,n){let r=this.#e.get(t);return r||this.#e.set(t,r=new Set),r.add(n),()=>{r.delete(n),r.size===0&&this.#e.delete(t)}}async wait(t){let n=a(()=>{},"wake"),r=0,s=a(()=>{r+=1,n()},"changed"),o=[...new Set(t.taskIds)].map(c=>this.subscribe(c,s)),l=setTimeout(s,Math.max(0,t.deadline-Date.now()));t.signal.addEventListener("abort",s);try{for(;;){t.signal.throwIfAborted();let c=r,h=await t.read();if(h!==null)return h;if(Date.now()>=t.deadline)return null;r===c&&await new Promise(u=>{n=u,(r!==c||t.signal.aborted)&&u()})}}finally{clearTimeout(l),t.signal.removeEventListener("abort",s);for(let c of o)c()}}},J=class{static{a(this,"TaskSerialExecutor")}#e=new Map;async run(t,n){let s=(this.#e.get(t)??Promise.resolve()).then(n),o=s.then(()=>{},()=>{});this.#e.set(t,o);try{return await s}finally{this.#e.get(t)===o&&this.#e.delete(t)}}};function St(e){return oe({runtime:L(e.ports),close:e.close})}a(St,"createAppServer");function oe(e){let t=!1;return{runtime:e.runtime,close:a(async()=>{t||(t=!0,await e.close?.())},"close")}}a(oe,"attachAppServer");async function Tt(e){try{await D({host:e.appServer.runtime,readable:e.readable,writable:e.writable})}finally{await e.appServer.close()}}a(Tt,"runAppServerJsonl");import{randomBytes as le}from"node:crypto";function jt(){return A()}a(jt,"appDataDir");function zt(e){return d(e).config}a(zt,"providersConfigPath");function Ht(e){return d(e).credentials}a(Ht,"providerSecretsConfigPath");function Nt(e){return d(e).key}a(Nt,"providerSecretsKeyPath");async function Ot(e){let t=d(e).token;return z(t,async()=>{let n=(await j(t))?.trim(),r=process.env.OPENPOND_APP_TOKEN||n||le(32).toString("base64url");return r!==n&&await E(t,r),{token:r,tokenFile:t}})}a(Ot,"ensureCapabilityToken");export{pe as a,fe as b,me as c,g as d,ge as e,be as f,xe as g,X as h,He as i,y as j,ye as k,se as l,tt as m,rt as n,st as o,ot as p,F as q,J as r,St as s,Tt as t,jt as u,zt as v,Ht as w,Nt as x,Ot as y};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{B as te,D as ne,E as oe,F as P,G as re,H as se,l as H,z as ee}from"./chunk-J3WNPOLS.js";import{a as T,b as y,c as w,h as Y,i as B,j as K}from"./chunk-J2S7BOZU.js";import{Da as $,Gb as M,Pa as Q,nb as F}from"./chunk-WYHHDJEG.js";import{a as l}from"./chunk-HZP5U2AA.js";import{b as a}from"./chunk-ES2ISFJC.js";import{a as d}from"./chunk-FTQLQJQV.js";function ie(r,e){return{supportsResume:!e,get:d((...t)=>r.get(...t),"get"),start:e?async()=>{throw new Error("This runtime does not support resuming a stopped guest; start fresh Work with saved outputs")}:(...t)=>r.start(...t),exec:d((t,n)=>r.exec(t,e?{...n,timeoutSeconds:Math.min(n.timeoutSeconds??30,60)}:n),"exec"),mkdir:d((...t)=>r.mkdir(...t),"mkdir"),uploadFile:d((...t)=>r.uploadFile(...t),"uploadFile"),uploadFileBase64:d((...t)=>r.uploadFileBase64(...t),"uploadFileBase64"),listFiles:d((...t)=>r.listFiles(...t),"listFiles"),downloadFileResponse:d((...t)=>r.downloadFileResponse(...t),"downloadFileResponse"),stop:d((...t)=>r.stop(...t),"stop"),delete:d((...t)=>r.delete(...t),"delete"),createWork:d(({requestId:t,repo:n,budgetUsd:o,metadata:s})=>{if(e){if(n?.trim())throw new Error("This runtime does not support repository provisioning; provide Work inputs instead");if(o!==void 0)throw new Error("Hosted spending budgets are not supported by this runtime");let p={resources:e.resources??{cpu:1,memoryGb:2,diskGb:10},...t?{requestId:t}:{}};return r.create(p)}let i=o?.trim()||"1.00";return r.create({...n?.trim()?{repo:n.trim()}:{},runtimeProfileId:"openpond-work-v1",resources:{cpu:2,memoryGb:4,diskGb:16},budget:{maxUsd:i},quotas:{maxSpendUsd:i,maxDurationSeconds:3600,idleTimeoutSeconds:900,maxCommands:200,maxOpenPorts:4},metadata:{source:"openpond-sdk-work",...s,...t?{workRequestId:t}:{}}},{async:!0})},"createWork")}}d(ie,"workSandbox");function N(r,e){let t=new URL(r);if(!["http:","https:"].includes(t.protocol)||t.username||t.password||t.search||t.hash)throw new Error(`${e} must be an HTTP(S) endpoint without embedded credentials, query or fragment`);return t.toString().replace(/\/$/,"")}d(N,"configuredEndpoint");function _(r,e){if(!r?.trim())throw new Error(`${e} is required`);return r.trim()}d(_,"configuredKey");var ke=a.object({choices:a.array(a.object({message:a.object({content:a.string().nullable().optional(),tool_calls:a.array(a.object({id:a.string().min(1),type:a.literal("function"),function:a.object({name:a.string().min(1),arguments:a.string()})})).optional()})})).min(1)});async function ae(r,e){if(!e)return K(r);let t=await fetch(`${r.apiBaseUrl}/chat/completions`,{method:"POST",headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},body:JSON.stringify({model:r.model,messages:r.messages,tools:r.tools,tool_choice:"auto",stream:!1}),signal:r.signal,redirect:"error"});if(!t.ok)throw new Error(`Configured model request failed (${t.status})`);return ke.parse(await t.json())}d(ae,"workModelTurn");var xe="openpond-chat",Re=24,Se=4e4,D=2e4,z="outputs",J="inputs/previous-outputs",ue="inputs/.openpond-context.json",Ce=100,de=100,pe=100*1024*1024,x=class{static{d(this,"OpenPondWorkClient")}#e;#n;#t;#o;#r;#s;constructor(e){this.#e=e.apiKey,this.#n=e.apiBaseUrl,this.#t=e.chatApiBaseUrl,this.#o=ie(e.sandboxes,e.sandboxConfig),this.#r=e.defaultModel??xe,this.#s=e.customModel??!1}async run(e){let t=e.prompt.trim();if(!t)throw new Error("Work prompt is required");e.signal?.throwIfAborted();let n=d(async m=>e.onEvent?.(m),"emit"),o=e.cleanup??"keep",s=We(o),i=null,p=null,f=!1,g=le(e.maxSteps,1,100,Re),c="";try{await n({type:"status",message:"Preparing sandbox"}),i=await this.#g(e),await n({type:"sandbox",sandboxId:i.id,state:i.state}),await this.#u(i.id,e.inputs??[]),p=await this.#m(i.id);let m=[{role:"system",content:ve(i.id,(e.inputs?.length??0)>0)},...(e.history??[]).map(h=>({...h})),{role:"user",content:t}];for(let h=1;h<=g;h+=1){e.signal?.throwIfAborted(),await n({type:"status",message:`Thinking \xB7 step ${h}`});let G=(await ae({apiBaseUrl:this.#t,token:this.#e,model:e.model?.trim()||this.#r,messages:m,tools:Ie,toolChoice:"auto",signal:e.signal,metadata:{source:"openpond-sdk-work",sandboxId:i.id,apiBaseUrl:this.#n,...e.metadata}},this.#s)).choices?.[0],W=G?.message?.content?.trim()??"",L=G?.message?.tool_calls??[];if(m.push({role:"assistant",content:W||null,...L.length>0?{tool_calls:L}:{}}),W&&(c=W,await n({type:"assistant",text:W})),L.length===0){let b=await this.#p(i.id,p);for(let U of b)await n({type:"output",output:U});f=!0,await this.#i(i.id,b,e,s,n);let A={sandboxId:i.id,text:c,steps:h,outputs:b,lifecycle:s};return await n({type:"done",...A}),A}for(let[b,A]of L.entries()){e.signal?.throwIfAborted();let U=await this.#h(i.id,A,b,e.timeoutSeconds,n);m.push(U)}}throw new Error(`Work did not finish within ${g} steps`)}catch(m){if(i&&p&&!f)try{let h=await this.#p(i.id,p);for(let Z of h)await n({type:"output",output:Z});await this.#i(i.id,h,e,s,n)}catch(h){ce(m,s,h)}throw ce(m,s),m}}async deleteSandbox(e){try{if((await this.#o.get(e)).state==="deleted")return;await this.#o.delete(e)}catch(t){if(t instanceof T&&t.status===404)return;throw t}}async#u(e,t){if(t.length===0)return;if(t.length>de)throw new Error(`Work inputs exceed the ${de} file limit`);if(t.reduce((i,p)=>i+Buffer.byteLength(p.contentsBase64,"base64"),0)>pe)throw new Error(`Work inputs exceed the ${pe} byte limit`);await this.#o.mkdir(e,{path:J,recursive:!0});let o=new Set,s=[];for(let[i,p]of t.entries()){let f=Ae(p,i,o),g=`${J}/${f}`;await this.#o.uploadFileBase64(e,g,p.contentsBase64),s.push({id:p.id,path:g,name:p.name,mimeType:p.mimeType??null,checksumSha256:p.checksumSha256??null,revision:p.revision??null,metadata:p.metadata??{}})}await this.#o.uploadFile(e,ue,JSON.stringify({version:1,files:s},null,2))}async#i(e,t,n,o,s){if(o.persistence.outputCount=t.length,t.length===0)o.persistence.status="not_needed";else if(n.persistOutput){o.persistence.status="running";for(let i of t){await s({type:"persistence",output:i,status:"started"});try{let p=Le(this.#o,e,i);await n.persistOutput({output:i,download:p}),o.persistence.persistedCount+=1,await s({type:"persistence",output:i,status:"succeeded"})}catch(p){let f=k(p);throw o.persistence.status="failed",o.persistence.error=f,await s({type:"persistence",output:i,status:"failed",error:f}),(n.cleanup??"keep")!=="keep"&&await this.#a(e,o,s),p}}o.persistence.status="complete"}else{if((n.cleanup??"keep")==="delete"&&!n.discardOutputs)throw o.persistence.status="failed",o.persistence.error="Deleting a Work sandbox with outputs requires persistOutput or discardOutputs: true",await this.#a(e,o,s),new Error(o.persistence.error);o.persistence.status="not_requested"}await this.#d(e,n.cleanup??"keep",o,s)}async#a(e,t,n){if(this.#o.supportsResume){await this.#d(e,"stop",t,n);return}t.cleanup.status="pending",t.cleanup.finalSandboxState="running",t.cleanup.error="Output persistence must be retried before guest deletion",await n({type:"cleanup",policy:t.cleanupPolicy,status:"pending",sandboxState:"running",error:t.cleanup.error})}async#d(e,t,n,o){if(t!=="keep"){n.cleanup.status="running",await o({type:"cleanup",policy:t,status:"started"});try{let s=t==="delete"?await this.#o.delete(e):(await this.#o.stop(e)).sandbox;n.cleanup.finalSandboxState=s.state,n.cleanup.status=t==="delete"&&s.state==="deleted"||t==="stop"&&s.state==="stopped"?"complete":"pending",await o({type:"cleanup",policy:t,status:n.cleanup.status,sandboxState:s.state})}catch(s){let i=k(s);throw n.cleanup.status="failed",n.cleanup.error=i,await o({type:"cleanup",policy:t,status:"failed",error:i}),s}}}downloadOutput(e,t){return this.#o.downloadFileResponse(e,typeof t=="string"?t:t.path)}async#m(e){return await this.#o.mkdir(e,{path:z,recursive:!0}),Te(await this.#c(e))}async#p(e,t){return(await this.#c(e)).filter(o=>t.get(o.path)!==me(o)).sort((o,s)=>o.path.localeCompare(s.path)).slice(0,Ce).map(_e)}async#c(e){return(await this.#o.listFiles(e,{path:z,recursive:!0,maxEntries:500})).files.filter(n=>n.type==="file"&&!ge(n.path).includes("/.openpond-"))}async#g(e){if(e.sandboxId){let n=await this.#o.get(e.sandboxId);if(n.state==="stopped")await this.#o.start(n.id,{async:!0});else if(n.state==="deleted"||n.state==="error")throw new Error(`Cannot resume sandbox ${n.id} in state ${n.state}`);return await this.#l(n.id,e.signal)}let t=await this.#o.createWork(e);return this.#l(t.id,e.signal)}async#l(e,t){let n=Date.now()+72e4,o=await this.#o.get(e);for(;Date.now()<n;){if(t?.throwIfAborted(),o.state==="running")return o;if(o.state==="error"||o.state==="deleted")throw new Error(`Sandbox ${o.id} entered ${o.state}${o.logs.length?`: ${o.logs.join(`
2
+ import{B as te,D as ne,E as oe,F as P,G as re,H as se,l as H,z as ee}from"./chunk-4KDHMGKI.js";import{a as T,b as y,c as w,h as Y,i as B,j as K}from"./chunk-J2S7BOZU.js";import{Da as $,Gb as M,Pa as Q,nb as F}from"./chunk-D6BBQHZM.js";import{k as l}from"./chunk-F4WS5QIT.js";import{b as a}from"./chunk-ES2ISFJC.js";import{a as d}from"./chunk-FTQLQJQV.js";function ie(r,e){return{supportsResume:!e,get:d((...t)=>r.get(...t),"get"),start:e?async()=>{throw new Error("This runtime does not support resuming a stopped guest; start fresh Work with saved outputs")}:(...t)=>r.start(...t),exec:d((t,n)=>r.exec(t,e?{...n,timeoutSeconds:Math.min(n.timeoutSeconds??30,60)}:n),"exec"),mkdir:d((...t)=>r.mkdir(...t),"mkdir"),uploadFile:d((...t)=>r.uploadFile(...t),"uploadFile"),uploadFileBase64:d((...t)=>r.uploadFileBase64(...t),"uploadFileBase64"),listFiles:d((...t)=>r.listFiles(...t),"listFiles"),downloadFileResponse:d((...t)=>r.downloadFileResponse(...t),"downloadFileResponse"),stop:d((...t)=>r.stop(...t),"stop"),delete:d((...t)=>r.delete(...t),"delete"),createWork:d(({requestId:t,repo:n,budgetUsd:o,metadata:s})=>{if(e){if(n?.trim())throw new Error("This runtime does not support repository provisioning; provide Work inputs instead");if(o!==void 0)throw new Error("Hosted spending budgets are not supported by this runtime");let p={resources:e.resources??{cpu:1,memoryGb:2,diskGb:10},...t?{requestId:t}:{}};return r.create(p)}let i=o?.trim()||"1.00";return r.create({...n?.trim()?{repo:n.trim()}:{},runtimeProfileId:"openpond-work-v1",resources:{cpu:2,memoryGb:4,diskGb:16},budget:{maxUsd:i},quotas:{maxSpendUsd:i,maxDurationSeconds:3600,idleTimeoutSeconds:900,maxCommands:200,maxOpenPorts:4},metadata:{source:"openpond-sdk-work",...s,...t?{workRequestId:t}:{}}},{async:!0})},"createWork")}}d(ie,"workSandbox");function N(r,e){let t=new URL(r);if(!["http:","https:"].includes(t.protocol)||t.username||t.password||t.search||t.hash)throw new Error(`${e} must be an HTTP(S) endpoint without embedded credentials, query or fragment`);return t.toString().replace(/\/$/,"")}d(N,"configuredEndpoint");function _(r,e){if(!r?.trim())throw new Error(`${e} is required`);return r.trim()}d(_,"configuredKey");var ke=a.object({choices:a.array(a.object({message:a.object({content:a.string().nullable().optional(),tool_calls:a.array(a.object({id:a.string().min(1),type:a.literal("function"),function:a.object({name:a.string().min(1),arguments:a.string()})})).optional()})})).min(1)});async function ae(r,e){if(!e)return K(r);let t=await fetch(`${r.apiBaseUrl}/chat/completions`,{method:"POST",headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},body:JSON.stringify({model:r.model,messages:r.messages,tools:r.tools,tool_choice:"auto",stream:!1}),signal:r.signal,redirect:"error"});if(!t.ok)throw new Error(`Configured model request failed (${t.status})`);return ke.parse(await t.json())}d(ae,"workModelTurn");var xe="openpond-chat",Re=24,Se=4e4,D=2e4,z="outputs",J="inputs/previous-outputs",ue="inputs/.openpond-context.json",Ce=100,de=100,pe=100*1024*1024,x=class{static{d(this,"OpenPondWorkClient")}#e;#n;#t;#o;#r;#s;constructor(e){this.#e=e.apiKey,this.#n=e.apiBaseUrl,this.#t=e.chatApiBaseUrl,this.#o=ie(e.sandboxes,e.sandboxConfig),this.#r=e.defaultModel??xe,this.#s=e.customModel??!1}async run(e){let t=e.prompt.trim();if(!t)throw new Error("Work prompt is required");e.signal?.throwIfAborted();let n=d(async m=>e.onEvent?.(m),"emit"),o=e.cleanup??"keep",s=We(o),i=null,p=null,f=!1,g=le(e.maxSteps,1,100,Re),c="";try{await n({type:"status",message:"Preparing sandbox"}),i=await this.#g(e),await n({type:"sandbox",sandboxId:i.id,state:i.state}),await this.#u(i.id,e.inputs??[]),p=await this.#m(i.id);let m=[{role:"system",content:ve(i.id,(e.inputs?.length??0)>0)},...(e.history??[]).map(h=>({...h})),{role:"user",content:t}];for(let h=1;h<=g;h+=1){e.signal?.throwIfAborted(),await n({type:"status",message:`Thinking \xB7 step ${h}`});let G=(await ae({apiBaseUrl:this.#t,token:this.#e,model:e.model?.trim()||this.#r,messages:m,tools:Ie,toolChoice:"auto",signal:e.signal,metadata:{source:"openpond-sdk-work",sandboxId:i.id,apiBaseUrl:this.#n,...e.metadata}},this.#s)).choices?.[0],W=G?.message?.content?.trim()??"",L=G?.message?.tool_calls??[];if(m.push({role:"assistant",content:W||null,...L.length>0?{tool_calls:L}:{}}),W&&(c=W,await n({type:"assistant",text:W})),L.length===0){let b=await this.#p(i.id,p);for(let U of b)await n({type:"output",output:U});f=!0,await this.#i(i.id,b,e,s,n);let A={sandboxId:i.id,text:c,steps:h,outputs:b,lifecycle:s};return await n({type:"done",...A}),A}for(let[b,A]of L.entries()){e.signal?.throwIfAborted();let U=await this.#h(i.id,A,b,e.timeoutSeconds,n);m.push(U)}}throw new Error(`Work did not finish within ${g} steps`)}catch(m){if(i&&p&&!f)try{let h=await this.#p(i.id,p);for(let Z of h)await n({type:"output",output:Z});await this.#i(i.id,h,e,s,n)}catch(h){ce(m,s,h)}throw ce(m,s),m}}async deleteSandbox(e){try{if((await this.#o.get(e)).state==="deleted")return;await this.#o.delete(e)}catch(t){if(t instanceof T&&t.status===404)return;throw t}}async#u(e,t){if(t.length===0)return;if(t.length>de)throw new Error(`Work inputs exceed the ${de} file limit`);if(t.reduce((i,p)=>i+Buffer.byteLength(p.contentsBase64,"base64"),0)>pe)throw new Error(`Work inputs exceed the ${pe} byte limit`);await this.#o.mkdir(e,{path:J,recursive:!0});let o=new Set,s=[];for(let[i,p]of t.entries()){let f=Ae(p,i,o),g=`${J}/${f}`;await this.#o.uploadFileBase64(e,g,p.contentsBase64),s.push({id:p.id,path:g,name:p.name,mimeType:p.mimeType??null,checksumSha256:p.checksumSha256??null,revision:p.revision??null,metadata:p.metadata??{}})}await this.#o.uploadFile(e,ue,JSON.stringify({version:1,files:s},null,2))}async#i(e,t,n,o,s){if(o.persistence.outputCount=t.length,t.length===0)o.persistence.status="not_needed";else if(n.persistOutput){o.persistence.status="running";for(let i of t){await s({type:"persistence",output:i,status:"started"});try{let p=Le(this.#o,e,i);await n.persistOutput({output:i,download:p}),o.persistence.persistedCount+=1,await s({type:"persistence",output:i,status:"succeeded"})}catch(p){let f=k(p);throw o.persistence.status="failed",o.persistence.error=f,await s({type:"persistence",output:i,status:"failed",error:f}),(n.cleanup??"keep")!=="keep"&&await this.#a(e,o,s),p}}o.persistence.status="complete"}else{if((n.cleanup??"keep")==="delete"&&!n.discardOutputs)throw o.persistence.status="failed",o.persistence.error="Deleting a Work sandbox with outputs requires persistOutput or discardOutputs: true",await this.#a(e,o,s),new Error(o.persistence.error);o.persistence.status="not_requested"}await this.#d(e,n.cleanup??"keep",o,s)}async#a(e,t,n){if(this.#o.supportsResume){await this.#d(e,"stop",t,n);return}t.cleanup.status="pending",t.cleanup.finalSandboxState="running",t.cleanup.error="Output persistence must be retried before guest deletion",await n({type:"cleanup",policy:t.cleanupPolicy,status:"pending",sandboxState:"running",error:t.cleanup.error})}async#d(e,t,n,o){if(t!=="keep"){n.cleanup.status="running",await o({type:"cleanup",policy:t,status:"started"});try{let s=t==="delete"?await this.#o.delete(e):(await this.#o.stop(e)).sandbox;n.cleanup.finalSandboxState=s.state,n.cleanup.status=t==="delete"&&s.state==="deleted"||t==="stop"&&s.state==="stopped"?"complete":"pending",await o({type:"cleanup",policy:t,status:n.cleanup.status,sandboxState:s.state})}catch(s){let i=k(s);throw n.cleanup.status="failed",n.cleanup.error=i,await o({type:"cleanup",policy:t,status:"failed",error:i}),s}}}downloadOutput(e,t){return this.#o.downloadFileResponse(e,typeof t=="string"?t:t.path)}async#m(e){return await this.#o.mkdir(e,{path:z,recursive:!0}),Te(await this.#c(e))}async#p(e,t){return(await this.#c(e)).filter(o=>t.get(o.path)!==me(o)).sort((o,s)=>o.path.localeCompare(s.path)).slice(0,Ce).map(_e)}async#c(e){return(await this.#o.listFiles(e,{path:z,recursive:!0,maxEntries:500})).files.filter(n=>n.type==="file"&&!ge(n.path).includes("/.openpond-"))}async#g(e){if(e.sandboxId){let n=await this.#o.get(e.sandboxId);if(n.state==="stopped")await this.#o.start(n.id,{async:!0});else if(n.state==="deleted"||n.state==="error")throw new Error(`Cannot resume sandbox ${n.id} in state ${n.state}`);return await this.#l(n.id,e.signal)}let t=await this.#o.createWork(e);return this.#l(t.id,e.signal)}async#l(e,t){let n=Date.now()+72e4,o=await this.#o.get(e);for(;Date.now()<n;){if(t?.throwIfAborted(),o.state==="running")return o;if(o.state==="error"||o.state==="deleted")throw new Error(`Sandbox ${o.id} entered ${o.state}${o.logs.length?`: ${o.logs.join(`
3
3
  `)}`:""}`);await Ue(2e3,t),o=await this.#o.get(e)}throw new Error(`Sandbox ${e} did not become ready before timeout`)}async#h(e,t,n,o,s){let i=t.id||`work_tool_${n}`,p=t.function?.name;if(p!=="run_command")return O(i,{error:`Unknown tool: ${p??"missing"}`});let f;try{f=JSON.parse(t.function?.arguments||"{}")}catch(c){return O(i,{error:`Invalid tool arguments: ${k(c)}`})}let g=typeof f.command=="string"?f.command.trim():"";if(!g)return O(i,{error:"command is required"});if(g.length>D){let c=`command exceeds the ${D} character limit`;return await s({type:"tool",toolCallId:i,command:g,status:"failed",output:c}),O(i,{status:"failed",error:c})}await s({type:"tool",toolCallId:i,command:g,status:"started"});try{let c=await this.#o.exec(e,{command:g,timeoutSeconds:le(o,1,900,180)}),m=Ee(c.command.output,Se),h=c.command.status==="succeeded"?"succeeded":"failed";return await s({type:"tool",toolCallId:i,command:g,status:h,output:m,exitCode:c.command.exitCode}),O(i,{status:c.command.status,exitCode:c.command.exitCode,output:m})}catch(c){if(c instanceof T)throw c;let m=k(c);return await s({type:"tool",toolCallId:i,command:g,status:"failed",output:m}),O(i,{status:"failed",error:m})}}},Ie=[{type:"function",function:{name:"run_command",description:"Run a shell command inside the persistent OpenPond sandbox. Use standard shell tools to inspect, edit, build, and test files. Commands start in the repository workspace.",parameters:{type:"object",additionalProperties:!1,properties:{command:{type:"string",minLength:1,maxLength:D,description:"Shell command to execute."}},required:["command"]}}}];function ve(r,e){return["You are OpenPond Work, a careful coding agent operating in an isolated Linux sandbox.",`The active sandbox is ${r}.`,...e?[`The authoritative saved files for this turn are staged under /workspace/${J}; their manifest is /workspace/${ue}.`,"Before revising a previous output, read its staged file and manifest. Copy the staged input into the output directory before editing it; previous output paths may not exist in this sandbox.","Preserve the actual file bytes. Never reconstruct a saved file from the conversation or claim to have preserved it without reading the staged input."]:[],"Use run_command to inspect the workspace, edit files, and validate your work.",`Place completed user-facing files in ${z}. The runtime collects new and revised files there automatically when the turn completes.`,"Do the requested work completely. Preserve existing user changes and avoid destructive commands.","Keep the user informed with concise prose, but call tools whenever verification or file changes are needed.","Before finishing, run relevant tests and summarize the concrete result."].join(`
4
4
  `)}d(ve,"systemPrompt");function We(r){return{cleanupPolicy:r,persistence:{status:"not_requested",outputCount:0,persistedCount:0},cleanup:{status:"not_requested"}}}d(We,"initialLifecycle");function Le(r,e,t){let n=null;return()=>(n??=r.downloadFileResponse(e,{path:t.path,maxBytes:Math.max(1,t.sizeBytes)}).then(o=>{let s=Buffer.byteLength(o.file.contentsBase64,"base64");if(o.file.truncated||o.file.returnedBytes!==o.file.totalSizeBytes||s!==t.sizeBytes)throw new Error(`Output download was incomplete for ${t.name}`);return o}),n)}d(Le,"lazyOutputDownload");function Ae(r,e,t){let n=r.id.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,80)||`input-${e+1}`,o=r.name.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(-120)||"file",s=`${n}-${o}`,i=s,p=1;for(;t.has(i);)p+=1,i=`${s}-${p}`;return t.add(i),i}d(Ae,"uniqueInputName");function ce(r,e,t){!r||typeof r!="object"||Object.assign(r,{workLifecycle:e,...t?{workFinalizationError:k(t)}:{}})}d(ce,"attachWorkFailure");function Te(r){return new Map(r.map(e=>[e.path,me(e)]))}d(Te,"outputSignatures");function me(r){return`${r.sizeBytes}:${r.updatedAt}`}d(me,"outputSignature");function _e(r){let e=ge(r.path).split("/").at(-1)||r.path,t=qe(e);return{path:r.path,name:e,mimeType:t,sizeBytes:r.sizeBytes,updatedAt:r.updatedAt,isBinary:r.isBinary??null,previewable:r.previewable??(t.startsWith("image/")||t==="application/pdf"||t.startsWith("text/"))}}d(_e,"workOutputFromFile");function ge(r){return r.replaceAll("\\","/")}d(ge,"normalizedOutputPath");function qe(r){let e=r.toLowerCase().match(/\.[^.]+$/)?.[0]??"";return je[e]??"application/octet-stream"}d(qe,"workOutputMimeType");var je=Object.freeze({".avif":"image/avif",".csv":"text/csv",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".gif":"image/gif",".html":"text/html",".jpeg":"image/jpeg",".jpg":"image/jpeg",".json":"application/json",".m4a":"audio/mp4",".md":"text/markdown",".mov":"video/quicktime",".mp3":"audio/mpeg",".mp4":"video/mp4",".pdf":"application/pdf",".png":"image/png",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".svg":"image/svg+xml",".tsv":"text/tab-separated-values",".txt":"text/plain",".wav":"audio/wav",".webm":"video/webm",".webp":"image/webp",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});function O(r,e){return{role:"tool",tool_call_id:r,content:JSON.stringify(e)}}d(O,"toolMessage");function le(r,e,t,n){return Number.isFinite(r)?Math.min(t,Math.max(e,Math.floor(r))):n}d(le,"boundedInteger");function Ee(r,e){return r.length<=e?r:`${r.slice(0,e)}
5
5
  \u2026 output truncated by openpond-sdk`}d(Ee,"truncate");function k(r){return r instanceof Error?r.message:String(r)}d(k,"errorMessage");function Ue(r,e){return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}let o=setTimeout(t,r);o.unref?.(),e?.addEventListener("abort",()=>{clearTimeout(o),n(e.reason)},{once:!0})})}d(Ue,"sleep");import{promises as he}from"node:fs";var R=class{static{d(this,"OpenPondProjectActionsClient")}#e;#n;constructor(e){this.#e=e.apiKey,this.#n=e.apiBaseUrl.replace(/\/+$/,"")}async list(e){let t=await y(this.#n,this.#e,q(e.projectId,"releases",e.teamId));return(await w(t,"List Project Action releases")).releases}async catalog(e){let t=await y(this.#n,this.#e,q(e.projectId,"catalog",e.teamId));return(await w(t,"Get Project Action catalog")).catalog}async publish(e){let[t,n]=await Promise.all([he.readFile(e.build.bundlePath),he.readFile(e.build.runnerPath)]),o=await y(this.#n,this.#e,q(e.projectId,"releases",e.teamId),{method:"POST",body:JSON.stringify({sourceRef:e.sourceRef,sourceCommitSha:e.sourceCommitSha,bundleBase64:t.toString("base64"),runnerBase64:n.toString("base64"),registry:e.build.registry,manifest:e.build.manifest,metadata:e.metadata})});return(await w(o,"Publish Project Actions")).release}async run(e){let t=await y(this.#n,this.#e,q(e.projectId,`actions/${encodeURIComponent(e.actionId)}`,e.teamId),{method:"POST",body:JSON.stringify({input:e.value??{},releaseId:e.releaseId,idempotencyKey:e.idempotencyKey,callerType:e.callerType??"sdk",callerId:e.callerId}),signal:e.signal,timeoutMs:9e5});return(await w(t,"Run Project Action")).invocation}};function q(r,e,t){return`/v1/project-actions/${encodeURIComponent(r)}/${e}?teamId=${encodeURIComponent(t)}`}d(q,"projectActionPath");var C=class{static{d(this,"OpenPondProfileActionsClient")}#e;#n;constructor(e){this.#e=e.apiKey,this.#n=e.apiBaseUrl.replace(/\/+$/,"")}async catalog(e){let t=S(e.teamId,"teamId"),n=new URLSearchParams({teamId:t});e.profileId?.trim()&&n.set("profileId",e.profileId.trim()),e.profileName?.trim()&&n.set("profileName",e.profileName.trim());let o=await y(this.#n,this.#e,`/v1/profile/actions?${n.toString()}`);return(await w(o,"Get Profile Action catalog")).catalog}async run(e){let t=S(e.teamId,"teamId"),n=S(e.actionKey,"actionKey"),o=S(e.idempotencyKey,"idempotencyKey"),s=S(e.catalogVersion,"catalogVersion"),i=await y(this.#n,this.#e,`/v1/profile/actions/run?${new URLSearchParams({teamId:t}).toString()}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e.profileId?.trim()?{profileId:e.profileId.trim()}:{},...e.profileName?.trim()?{profileName:e.profileName.trim()}:{},actionKey:n,value:e.value??{},conversationId:e.conversationId??null,createConversation:e.createConversation,conversationTitle:e.conversationTitle??null,idempotencyKey:o,catalogVersion:s,externalCapabilityLeases:e.externalCapabilityLeases})});return w(i,"Run Profile Action")}};function S(r,e){let t=r.trim();if(!t)throw new Error(`${e} is required`);return t}d(S,"requiredValue");import{randomUUID as fe}from"node:crypto";var I=class{static{d(this,"OpenPondWorkflowsClient")}#e;#n;constructor(e){this.#e=e.apiKey,this.#n=e.apiBaseUrl.replace(/\/+$/,"")}async list(e={}){return this.#t("","List Workflows",{signal:e.signal})}async create(e,t={}){return this.#t("","Create Workflow",{method:"POST",body:JSON.stringify({...e,clientRequestId:e.clientRequestId?.trim()||fe()}),signal:t.signal})}async update(e,t,n={}){return this.#t(`/schedules/${encodeURIComponent(V(e,"scheduleId"))}`,"Update Workflow",{method:"PATCH",body:JSON.stringify(t),signal:n.signal})}async delete(e,t={}){return this.#t(`/schedules/${encodeURIComponent(V(e,"scheduleId"))}`,"Delete Workflow",{method:"DELETE",signal:t.signal})}async runNow(e,t={},n={}){return this.#t(`/schedules/${encodeURIComponent(V(e,"scheduleId"))}/run`,"Run Workflow",{method:"POST",body:JSON.stringify({clientRequestId:t.clientRequestId?.trim()||fe()}),signal:n.signal})}async#t(e,t,n={}){let o=await y(this.#n,this.#e,`/v1/saved-work${e}`,n);return w(o,t)}};function V(r,e){let t=r.trim();if(!t)throw new Error(`${e} is required`);return t}d(V,"requiredId");var j=a.object({id:l,scope:l,sourceId:l,name:a.string().trim().min(1).max(100),keyPrefix:a.string().min(1).max(100),createdAt:a.iso.datetime(),expiresAt:a.iso.datetime(),revokedAt:a.iso.datetime().nullable()}).strict(),ye=a.string().regex(/^opk_key_[A-Za-z0-9]{16}_[A-Za-z0-9]{48}$/),E=a.discriminatedUnion("action",[a.object({action:a.literal("create"),scope:l,sourceId:l,name:a.string().trim().min(1).max(100),expiresAt:a.iso.datetime(),operationId:l,apiKey:ye}).strict(),a.object({action:a.literal("list"),scope:l,sourceId:l,afterId:l.optional(),limit:a.number().int().min(1).max(100).default(30)}).strict(),a.object({action:a.literal("revoke"),scope:l,sourceId:l,id:l}).strict()]),we=a.object({credential:j,apiKey:ye}).strict(),Pe=a.object({items:a.array(j).max(100),nextCursor:l.nullable()}).strict(),Oe=a.object({scope:l,sourceId:l}).strict(),be=a.object({scope:l,source:F,taskDefinition:F,enabled:a.boolean(),allowedSplits:a.array(Q).min(1).max(4)}).strict();var Be=a.object({batchId:a.string().trim().min(1).max(500),modelProjectId:a.string().trim().min(1).max(500)}).strict(),Ke=a.object({batchId:a.string().min(1),projectId:a.string().min(1),tasksetId:a.string().min(1),releaseId:a.string().min(1),revision:a.number().int().positive(),contentHash:a.string().regex(/^[a-f0-9]{64}$/)}).strict(),u=class extends Error{constructor(t,n,o,s){super(o);this.status=t;this.code=n;this.details=s;this.name="OpenPondLearningError"}status;code;details;static{d(this,"OpenPondLearningError")}},v=class{static{d(this,"OpenPondLearningClient")}#e;constructor(e){if(!e.apiKey.trim()||!e.scope.trim())throw new Error("Learning API key and scope are required.");let t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol)||t.username||t.password||t.search||t.hash)throw new Error("Learning base URL must be an HTTP(S) endpoint without credentials, query, or fragment.");this.#e={...e,baseUrl:t.toString().replace(/\/+$/,"")}}async command(e,t={}){ne(e);let n=oe.parse({scope:this.#e.scope,command:e}),o=se.parse(await this.#t("commands",n,t));if(o.operationId!==e.operationId)throw new u(502,"operation_identity_mismatch","Learning response did not match the submitted operation.",null);return o}submitExample(e,t={}){return this.command({action:"submit_example",operationId:e.idempotencyKey,example:e},t)}submitFeedback(e,t={}){return this.command({action:"submit_feedback",operationId:e.idempotencyKey,feedback:e},t)}async get(e,t,n,o={}){let s=P.parse({action:"get",scope:this.#e.scope,kind:e,id:t,...n===void 0?{}:{revision:n}});return H[e].parse(await this.#t("read",s,o))}async inspectEvidence(e,t={}){let n=P.parse({action:"inspect_evidence",scope:this.#e.scope,evidence:e}),o=re.parse(await this.#t("read",n,t));if(!M(o.evidence,e))throw new u(502,"evidence_identity_mismatch","Inspection did not match the requested evidence release.",null);return o}async inspectTaskQueue(e=null,t={}){let n=P.parse({action:"inspect_task_queue",scope:this.#e.scope,modelProjectId:e}),o=te.parse(await this.#t("read",n,t));if(o.modelProjectId!==e)throw new u(502,"model_identity_mismatch","Task queue did not match the requested Model.",null);return o}async inspectPolicy(e,t={}){let n=P.parse({action:"inspect_policy",scope:this.#e.scope,policy:e}),o=ee.parse(await this.#t("read",n,t));if(!M(o.policy,e))throw new u(502,"policy_identity_mismatch","Inspection did not match the requested policy release.",null);return o}async createSourceCredential(e,t={}){let n=E.parse({...e,action:"create",scope:this.#e.scope}),o=we.parse(await this.#t("credentials",n,t));if(this.#n(o.credential,e.sourceId),o.apiKey!==e.apiKey||!e.apiKey.startsWith(`${o.credential.keyPrefix}_`))throw new u(502,"credential_identity_mismatch","Credential response did not match the prepared credential.",null);return o}async listSourceCredentials(e,t={},n={}){let o=E.parse({...t,action:"list",scope:this.#e.scope,sourceId:e}),s=Pe.parse(await this.#t("credentials",o,n));if(s.items.length>(t.limit??30))throw new u(502,"credential_page_invalid","Credential response exceeded the requested page size.",null);for(let i of s.items)this.#n(i,e);return s}async revokeSourceCredential(e,t,n={}){let o=E.parse({action:"revoke",scope:this.#e.scope,sourceId:e,id:t}),s=j.parse(await this.#t("credentials",o,n));if(this.#n(s,e),s.id!==t||s.revokedAt===null)throw new u(502,"credential_revocation_mismatch","Credential revocation did not match the requested credential.",null);return s}async sourceConfiguration(e,t={}){let n=Oe.parse({scope:this.#e.scope,sourceId:e}),o=be.parse(await this.#t("source-config",n,t));if(o.scope!==this.#e.scope||o.source.id!==e)throw new u(502,"source_identity_mismatch","Source configuration did not match the requested source.",null);return o}#n(e,t){if(e.scope!==this.#e.scope||e.sourceId!==t)throw new u(502,"credential_scope_mismatch","Credential response did not match the requested source.",null)}async list(e,t={},n={}){let o=P.parse({action:"list",scope:this.#e.scope,kind:e,...t});return a.object({items:a.array(H[e]).max(100),nextCursor:a.string().nullable()}).strict().parse(await this.#t("read",o,n))}async publishBatch(e,t={}){let n=Be.parse(e),o=Ke.parse(await this.#t("publish-batch",{...n,scope:this.#e.scope},t));if(o.batchId!==n.batchId)throw new u(502,"batch_identity_mismatch","Published batch response did not match the requested batch.",null);return o}async#t(e,t,n){$(t,16777216);let o=await(this.#e.fetch??globalThis.fetch)(`${this.#e.baseUrl}/v1/learning/${e}`,{method:"POST",headers:{Authorization:`Bearer ${this.#e.apiKey}`,"Content-Type":"application/json",Accept:"application/json","X-OpenPond-Team-Id":this.#e.scope},body:JSON.stringify(t),signal:n.signal,redirect:"error"}),s=await $e(o);if(!o.ok){let i=a.object({code:a.string().optional(),error:a.string().optional()}).passthrough().safeParse(s);throw new u(o.status,i.success?i.data.code??"learning_request_failed":"learning_request_failed",i.success?i.data.error??`Learning request failed (${o.status}).`:`Learning request failed (${o.status}).`,s)}return s}};async function $e(r){let t=r.body?.getReader();if(!t)throw new u(r.status,"empty_response","Learning response was empty.",null);let n=new TextDecoder,o=0,s="";try{for(;;){let p=await t.read();if(p.done)break;if(o+=p.value.byteLength,o>16777216)throw new u(r.status,"response_too_large","Learning response exceeded 16 MiB; request a smaller page.",null);s+=n.decode(p.value,{stream:!0})}s+=n.decode();let i=JSON.parse(s);return $(i,16777216),i}finally{await t.cancel(),t.releaseLock()}}d($e,"readBoundedLearningResponse");var X=class{static{d(this,"OpenPondClient")}sandboxes;work;workflows;actions;profileActions;learning;constructor(e){let t=e.apiKey?.trim()??"";if(!t&&(!e.sandbox||!e.model))throw new Error("OpenPond API key is required when using a default sandbox or model");let n=e.sandbox?{...e.sandbox,endpoint:N(e.sandbox.endpoint,"Sandbox endpoint"),apiKey:_(e.sandbox.apiKey,"Sandbox API key")}:void 0,o=e.model?{endpoint:N(e.model.endpoint,"Model endpoint"),apiKey:_(e.model.apiKey,"Model API key"),model:_(e.model.model,"Model ID")}:void 0,s=e.baseUrl?.trim()||"https://api.openpond.ai";this.learning=i=>new v({apiKey:t,baseUrl:s,scope:i}),this.sandboxes=Y({apiKey:n?.apiKey??t,baseUrl:s,sandboxApiUrl:n?.endpoint??e.sandboxApiUrl,customEndpoint:!!n}),this.work=new x({apiKey:o?.apiKey??t,apiBaseUrl:s,chatApiBaseUrl:o?.endpoint||e.chatApiUrl?.trim()||B({apiBaseUrl:s,env:{}}),sandboxes:this.sandboxes,sandboxConfig:n,defaultModel:o?.model,customModel:!!o}),this.workflows=new I({apiKey:t,apiBaseUrl:s}),this.actions=new R({apiKey:t,apiBaseUrl:s}),this.profileActions=new C({apiKey:t,apiBaseUrl:s})}};function Jt(r){return new X(r)}d(Jt,"createOpenPondClient");export{Jt as a};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{$ as In,Aa as Fr,Ba as Vr,Ca as At,Eb as Gr,I as Lr,Va as On,b as _n,ba as An,c as It,dd as Pt,ed as Ct,fd as Tt,g as kn,gd as Un,la as Pn,ld as Ne,ma as Cn,oa as Br,ra as qr,sa as Tn,sc as Mn,t as wn,ta as jn,u as Rn,va as $r,wa as Dr,xa as Nr,ya as zr,za as En}from"./chunk-CTC5EYSH.js";import{a as Hn,b as Kr,c as Wr}from"./chunk-6MI4KKWF.js";import{b as ne,d as kt,e as wt}from"./chunk-J2S7BOZU.js";import{J as Tr,L as vn,M as jr,N as Er,bb as Ur,h as Rr,i as Ir,k as Ar,l as Pr,p as ve,q as Cr,s as Rt,t as Sn,ya as Or,z as ae,za as Mr}from"./chunk-WYHHDJEG.js";import{a as Hr}from"./chunk-6FA3GG5B.js";import{A as it,B as ur,D as dr,Ja as kr,Ka as wr,M as pr,N as gr,O as $e,P as pn,Q as De,R as st,S as Se,U as fr,Ua as yn,V as hr,Y as br,Z as xr,_ as gn,aa as yr,ba as Sr,ca as fn,da as vr,f as _t,s as dn,t as mr,ya as bn,z as ot,za as xn}from"./chunk-NNLI4OWY.js";import{a as m,b as g,c as S,e as b,f as O,p as cr,q as $}from"./chunk-HZP5U2AA.js";import{b as e}from"./chunk-ES2ISFJC.js";import{f as X,h as vt,p as hn,r as _r}from"./chunk-H7IWJN7L.js";import{a as s}from"./chunk-FTQLQJQV.js";import{createHash as Vl}from"node:crypto";import{existsSync as Qr}from"node:fs";import{readdir as Zr,readFile as eo,stat as Gl}from"node:fs/promises";import se from"node:path";var Ln="skills",jt="SKILL.md",Jr=8e4;async function Bn(t){let n=se.join(t,Ln);if(!Qr(n))return{skillCatalog:Yr({stale:!1}),skills:[]};try{let a=await Zr(n,{withFileTypes:!0}),r=(await Promise.all(a.filter(o=>o.isDirectory()).map(o=>Kl(t,o.name)))).sort((o,l)=>o.name.localeCompare(l.name)||o.path.localeCompare(l.path));Jl(r);let i=await Yl(t,r);return{skillCatalog:{skillCount:r.length,generatedAt:i,stale:!1,error:null},skills:r}}catch(a){return{skillCatalog:Yr({stale:!0,error:a instanceof Error?a.message:String(a)}),skills:[]}}}s(Bn,"loadProfileSkills");function ze(t){let n=[],a=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/.exec(t);if(!a)return{name:null,description:null,body:t.trim(),messages:["SKILL.md must start with YAML frontmatter bounded by ---."]};let r=a[1]??"",i=(a[2]??"").trim(),o;try{o=Hr.load(r)}catch(p){n.push(`SKILL.md frontmatter is invalid YAML: ${p instanceof Error?p.message:String(p)}`)}let l=Xl(o),c=Xr(l?.name),u=Xr(l?.description);return c||n.push("Skill frontmatter must include a non-empty name."),u||n.push("Skill frontmatter must include a non-empty description."),i||n.push("Skill body must be non-empty markdown."),{name:c,description:u,body:i,messages:n}}s(ze,"parseProfileSkillMarkdown");async function Rh(t){let n=t.name.trim();if(!to(n))throw new Error("Profile skill name must be lowercase kebab-case.");let r=(await Bn(t.profileSourcePath)).skills.find(c=>c.name===n);if(!r)throw new Error(`Profile skill not found: ${n}`);if(!r.enabled||r.validationStatus!=="valid"){let c=r.validationMessages.length>0?` ${r.validationMessages.join(" ")}`:"";throw new Error(`Profile skill ${n} is not valid.${c}`)}let i=se.join(t.profileSourcePath,r.path),o=await eo(i,"utf8"),l=ze(o);if(l.messages.length>0)throw new Error(`Profile skill ${n} is not valid. ${l.messages.join(" ")}`);return{name:r.name,description:r.description,body:l.body,path:r.path,sourcePath:r.sourcePath,sourceHash:r.sourceHash,charCount:r.charCount,packagePath:se.dirname(i),resourceFiles:r.resourceFiles}}s(Rh,"readProfileSkill");function Yr(t={}){return{skillCount:0,generatedAt:null,stale:t.stale??!0,error:t.error??null}}s(Yr,"emptyProfileSkillCatalogState");async function Kl(t,n){let a=se.join(Ln,n,jt).replace(/\\/g,"/"),r=se.join(t,a),i=[],o=se.join(t,Ln,n),l=await Wl(o),c="";Qr(r)?c=await eo(r,"utf8"):i.push(`Missing ${jt}.`),c.length>Jr&&i.push(`Skill markdown exceeds the limit of ${Jr} characters.`);let u=ze(c);i.push(...u.messages);let p=u.name??n,k=u.description??"";return to(p)||i.push("Skill name must be lowercase kebab-case."),p!==n&&i.push(`Skill name must match its directory name (${n}).`),{name:p,description:k,path:a,scope:"profile",enabled:i.length===0,sourcePath:t,charCount:c.length,sourceHash:Ql(c),validationStatus:i.length>0?"error":"valid",validationMessages:i,resourceFiles:l.filter(v=>v!==jt)}}s(Kl,"loadProfileSkillDirectory");async function Wl(t){let n=[];async function a(r,i){let o=await Zr(r,{withFileTypes:!0});await Promise.all(o.map(async l=>{let c=i?`${i}/${l.name}`:l.name;l.isDirectory()?await a(se.join(r,l.name),c):l.isFile()&&n.push(c)}))}return s(a,"visit"),await a(t,""),n.sort()}s(Wl,"listPackageFiles");function Jl(t){let n=new Map;for(let a of t)n.set(a.name,(n.get(a.name)??0)+1);for(let a of t)(n.get(a.name)??0)<=1||(a.enabled=!1,a.validationStatus="error",a.validationMessages=[...a.validationMessages,`Duplicate skill name: ${a.name}`])}s(Jl,"markDuplicateSkillNames");async function Yl(t,n){let a=0;for(let r of n){let i=se.dirname(se.join(t,r.path)),o=[jt,...r.resourceFiles];for(let l of o){let c=await Gl(se.join(i,l)).catch(()=>null);c?.isFile()&&(a=Math.max(a,c.mtimeMs))}}return a>0?new Date(a).toISOString():null}s(Yl,"latestSkillMtime");function to(t){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(t)}s(to,"isKebabCaseSkillName");function Xl(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}s(Xl,"asRecord");function Xr(t){if(typeof t!="string")return null;let n=t.trim();return n.length>0?n:null}s(Xr,"text");function Ql(t){return Vl("sha256").update(t).digest("hex")}s(Ql,"sha256Hex");import{createRequire as Go}from"node:module";import{createHash as $o,randomUUID as Do}from"node:crypto";import{spawn as Qc}from"node:child_process";import{existsSync as G}from"node:fs";import{cp as Zc,mkdir as me,readFile as Ko,readdir as Wo,rename as ra,rm as oa,symlink as em,writeFile as Je}from"node:fs/promises";import f from"node:path";import Zl from"node:path";var Et="default",no=["apiKey","baseUrl","apiBaseUrl","chatApiBaseUrl","token","appId","conversationId"];function _e(t,n){return Object.prototype.hasOwnProperty.call(t,n)}s(_e,"hasOwn");function ge(t){if(typeof t!="string")return null;let n=t.trim();return n.length>0?n:null}s(ge,"normalizeHandle");function N(t){if(typeof t!="string")return null;let n=t.trim();return n?n.replace(/\/$/,""):null}s(N,"normalizeBaseUrl");function co(t){let n=ge(t);if(!n)throw new Error("profile handle must be non-empty");return n}s(co,"requireHandle");function ec(t){if(typeof t!="string")throw new Error("apiKey must be a non-empty string");let n=t.trim();if(!n)throw new Error("apiKey must be a non-empty string");return n}s(ec,"requireApiKey");function lt(t,n){let a=ge(t),r=ge(n);return!!(a&&r&&a.toLowerCase()===r.toLowerCase())}s(lt,"handleEquals");function $n(t,n,a){let r=N(a);return t.findIndex(i=>lt(i.handle,n)?r?N(i.baseUrl)===r:!0:!1)}s($n,"findAccountIndex");function Ve(t){let n=ge(t.handle)??Et,a=N(t.baseUrl);return a?{handle:n,baseUrl:a}:{handle:n}}s(Ve,"selectorFromAccount");function Fe(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,a=ge(typeof n.handle=="string"?n.handle:void 0);if(!a)return null;let r=N(typeof n.baseUrl=="string"?n.baseUrl:void 0);return r?{handle:a,baseUrl:r}:{handle:a}}s(Fe,"sanitizeActiveProfile");function Dn(t){if(!t||typeof t!="object"||Array.isArray(t))return;let n=t,a=typeof n.repoPath=="string"?n.repoPath.trim():"",r=typeof n.profile=="string"&&n.profile.trim()?n.profile.trim():"default";if(!a)return;let i={repoPath:a,profile:r,mode:"local"};if(n.lastCheck&&typeof n.lastCheck=="object"&&!Array.isArray(n.lastCheck)){let o=n.lastCheck,l=o.command,c=o.status,u=o.checkedAt;(l==="inspect"||l==="build"||l==="validate"||l==="eval"||l==="run")&&(c==="passed"||c==="failed")&&typeof u=="string"&&(i.lastCheck={command:l,status:c,checkedAt:u,...typeof o.exitCode=="number"||o.exitCode===null?{exitCode:o.exitCode}:{},...typeof o.sourceHead=="string"||o.sourceHead===null?{sourceHead:o.sourceHead}:{}})}if(n.lastPush&&typeof n.lastPush=="object"&&!Array.isArray(n.lastPush)){let o=n.lastPush,l=o.status,c=o.pushedAt;(l==="pushed"||l==="failed")&&typeof c=="string"&&(i.lastPush={status:l,pushedAt:c,...typeof o.teamId=="string"||o.teamId===null?{teamId:o.teamId}:{},...typeof o.projectId=="string"||o.projectId===null?{projectId:o.projectId}:{},...typeof o.localHead=="string"||o.localHead===null?{localHead:o.localHead}:{},...typeof o.hostedHead=="string"||o.hostedHead===null?{hostedHead:o.hostedHead}:{},...typeof o.sourceRef=="string"||o.sourceRef===null?{sourceRef:o.sourceRef}:{},...o.promotionStatus==="uploaded"||o.promotionStatus==="hosted_source_materialized"||o.promotionStatus==="hosted_source_materialize_failed"||o.promotionStatus==="hosted_source_check_pending"||o.promotionStatus==="hosted_source_check_failed"||o.promotionStatus==="hosted_source_published"||o.promotionStatus==="hosted_source_publish_failed"||o.promotionStatus==="hosted_run_pending"||o.promotionStatus==="hosted_run_passed"||o.promotionStatus==="hosted_run_failed"||o.promotionStatus===null?{promotionStatus:o.promotionStatus}:{},...o.hostedRunStatus==="not_started"||o.hostedRunStatus==="running"||o.hostedRunStatus==="passed"||o.hostedRunStatus==="failed"||o.hostedRunStatus===null?{hostedRunStatus:o.hostedRunStatus}:{},...typeof o.hostedRunAgentId=="string"||o.hostedRunAgentId===null?{hostedRunAgentId:o.hostedRunAgentId}:{},...typeof o.hostedRunId=="string"||o.hostedRunId===null?{hostedRunId:o.hostedRunId}:{},...typeof o.hostedRunAt=="string"||o.hostedRunAt===null?{hostedRunAt:o.hostedRunAt}:{},...ao(o.hostedSourceMaterialization)?{hostedSourceMaterialization:ao(o.hostedSourceMaterialization)}:{},...ro(o.hostedSourceCheck)?{hostedSourceCheck:ro(o.hostedSourceCheck)}:{},...oo(o.hostedPublish)?{hostedPublish:oo(o.hostedPublish)}:{},...io(o.hostedRun)?{hostedRun:io(o.hostedRun)}:{},...typeof o.error=="string"||o.error===null?{error:o.error}:{}})}if(Array.isArray(n.profiles)){let o=n.profiles.flatMap(l=>{let c=Dn(l);if(!c)return[];let u=l,p=u.source==="github"||u.source==="openpond_git"?u.source:"local",k=typeof u.repositoryId=="string"&&u.repositoryId.trim()?u.repositoryId.trim():Zl.resolve(c.repoPath);return[{source:p,repositoryId:k,repoPath:c.repoPath,profile:c.profile,...c.lastCheck?{lastCheck:c.lastCheck}:{},...c.lastPush?{lastPush:c.lastPush}:{}}]});o.length>0&&(i.profiles=o)}return i}s(Dn,"sanitizeLocalOpenPondProfile");function ao(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,a=Ot(n.status);return a?{status:a,...A(n,"agentId"),...A(n,"runtimeAgentId"),...A(n,"projectId"),...A(n,"sourceRoot"),...A(n,"sourceRef"),...A(n,"sourceCommitSha"),...A(n,"manifestHash"),...A(n,"manifestPath"),...A(n,"manifestSyncedAt"),...so(n,"fileCount"),...so(n,"totalBytes"),...A(n,"generatedManifestPath"),...qn(n,"synthesizedOpenPondYaml"),...A(n,"uploadMetadataPath"),...F(n,"setupCommands"),...F(n,"validationCommands"),...A(n,"materializedAt"),...A(n,"error")}:null}s(ao,"sanitizeHostedMaterializationStatus");function ro(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,a=Ot(n.status);return a?{status:a,...A(n,"agentId"),...A(n,"deployPlanStatus"),...qn(n,"canRun"),...qn(n,"canDeploy"),...A(n,"sourceRef"),...A(n,"sourceCommitSha"),...A(n,"manifestHash"),...A(n,"manifestPath"),...F(n,"setupCommands"),...F(n,"validationCommands"),...F(n,"requiredChecks"),...F(n,"evalNames"),...F(n,"blockedReasons"),...F(n,"staleReasons"),...A(n,"runtimeId"),...A(n,"sandboxId"),...F(n,"traceArtifactRefs"),...F(n,"evalResultArtifactRefs"),...F(n,"validatorArtifactRefs"),...A(n,"checkedAt"),...A(n,"error")}:null}s(ro,"sanitizeHostedSourceCheckStatus");function oo(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,a=Ot(n.status);return a?{status:a,...A(n,"agentId"),...A(n,"snapshotId"),...A(n,"sourceRef"),...A(n,"sourceCommitSha"),...A(n,"manifestHash"),...A(n,"manifestPath"),...A(n,"buildStatus"),...A(n,"validationStatus"),...A(n,"evalStatus"),...A(n,"publishedAt"),...A(n,"error")}:null}s(oo,"sanitizeHostedPublishStatus");function io(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,a=Ot(n.status);return a?{status:a,...A(n,"agentId"),...A(n,"runId"),...A(n,"runtimeId"),...A(n,"sandboxId"),...A(n,"sourceRef"),...A(n,"sourceCommitSha"),...A(n,"manifestHash"),...A(n,"setupGateStatus"),...F(n,"setupRequirementRefs"),...F(n,"artifactRefs"),...F(n,"traceArtifactRefs"),...F(n,"evalArtifactRefs"),...A(n,"startedAt"),...A(n,"completedAt"),...A(n,"error")}:null}s(io,"sanitizeHostedRunSummary");function A(t,n){let a=t[n];return typeof a=="string"||a===null?{[n]:a}:{}}s(A,"nullableStringProp");function qn(t,n){let a=t[n];return typeof a=="boolean"||a===null?{[n]:a}:{}}s(qn,"nullableBooleanProp");function so(t,n){let a=t[n];return typeof a=="number"||a===null?{[n]:a}:{}}s(so,"nullableNumberProp");function F(t,n){let a=t[n];if(!Array.isArray(a))return{};let r=a.filter(i=>typeof i=="string");return{[n]:r}}s(F,"stringArrayProp");function Ot(t){return typeof t=="string"&&t.trim()?t.trim():null}s(Ot,"stringField");function mo(t,n){if(!lt(t.handle,n.handle))return!1;let a=N(n.baseUrl);return a?N(t.baseUrl)===a:!N(t.baseUrl)}s(mo,"accountMatchesSelector");function Nn(t,n,a={}){let r=N(n.baseUrl);if(r)return $n(t,n.handle,r);let i=t.findIndex(l=>mo(l,n));if(i!==-1)return i;let o=t.map((l,c)=>({account:l,index:c})).filter(({account:l})=>lt(l.handle,n.handle));if(o.length>1&&a.requireUnambiguous)throw new Error(`multiple profiles found for ${n.handle}; pass --base-url to select one`);return o[0]?.index??-1}s(Nn,"findAccountIndexForSelector");function tc(t){if(!t||typeof t!="object"||Array.isArray(t))return;let n=t,a={};return typeof n.token=="string"&&(a.token=n.token),(typeof n.appId=="string"||n.appId===null)&&(a.appId=n.appId),(typeof n.conversationId=="string"||n.conversationId===null)&&(a.conversationId=n.conversationId),Object.keys(a).length>0?a:void 0}s(tc,"sanitizeSession");function nc(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,a=ge(typeof n.handle=="string"?n.handle:void 0);if(!a)return null;let r={handle:a};typeof n.apiKey=="string"&&(r.apiKey=n.apiKey),typeof n.baseUrl=="string"&&(r.baseUrl=n.baseUrl),typeof n.apiBaseUrl=="string"&&(r.apiBaseUrl=n.apiBaseUrl),typeof n.chatApiBaseUrl=="string"&&(r.chatApiBaseUrl=n.chatApiBaseUrl),typeof n.environment=="string"&&(r.environment=n.environment);let i=tc(n.session);return i&&(r.session=i),r}s(nc,"sanitizeAccount");function ac(t){let n={};return typeof t.token=="string"&&(n.token=t.token),(typeof t.appId=="string"||t.appId===null)&&(n.appId=t.appId),(typeof t.conversationId=="string"||t.conversationId===null)&&(n.conversationId=t.conversationId),Object.keys(n).length>0?n:void 0}s(ac,"extractLegacySession");function rc(t,n){let a={handle:n};typeof t.apiKey=="string"&&(a.apiKey=t.apiKey),typeof t.baseUrl=="string"&&(a.baseUrl=t.baseUrl),typeof t.apiBaseUrl=="string"&&(a.apiBaseUrl=t.apiBaseUrl),typeof t.chatApiBaseUrl=="string"&&(a.chatApiBaseUrl=t.chatApiBaseUrl);let r=ac(t);return r&&(a.session=r),a}s(rc,"extractLegacyAccount");function uo(t){let n={};typeof t.lspEnabled=="boolean"&&(n.lspEnabled=t.lspEnabled),(t.executionMode==="local"||t.executionMode==="hosted")&&(n.executionMode=t.executionMode),(t.mode==="general"||t.mode==="builder")&&(n.mode=t.mode);let a=Dn(t.openpondProfile);a&&(n.openpondProfile=a);let r=[],i=Array.isArray(t.accounts)?t.accounts:[];for(let u of i){let p=nc(u);p&&$n(r,p.handle,p.baseUrl)===-1&&r.push(p)}if(r.length===0){let u=Fe(t.activeProfile)?.handle||Et;r.push(rc(t,u))}let o=Fe(t.activeProfile),l=o?Nn(r,o):-1,c=r[l===-1?0:l];return n.accounts=r,n.activeProfile=Ve(c),n}s(uo,"normalizeGlobalConfig");function oc(t,n,a){let r=t.accounts??[],i=N(a??process.env.OPENPOND_BASE_URL),o=ge(n);if(o)return i?{handle:o,baseUrl:i}:{handle:o};let l=ge(process.env.OPENPOND_ACCOUNT);if(l)return i?{handle:l,baseUrl:i}:{handle:l};let c=Fe(t.activeProfile);return c?i?{handle:c.handle,baseUrl:i}:c:r[0]?Ve(r[0]):{handle:Et}}s(oc,"resolveRequestedProfile");function po(t,n,a){let r=N(a);if(r){let o=$n(t,n,r);if(o!==-1)return t[o]}else{let o=t.filter(l=>lt(l.handle,n));if(o.length>1)throw new Error(`multiple profiles found for ${n}; pass --base-url to select one`);if(o.length===1)return o[0]}let i={handle:n};return r&&(i.baseUrl=r),t.push(i),i}s(po,"ensureAccount");function lo(t){t.session&&Object.keys(t.session).length===0&&delete t.session}s(lo,"cleanupAccount");function ic(t,n,a,r){let i=a===null||a===void 0&&r.undefinedDeletes;switch(n){case"apiKey":{if(i){delete t.apiKey;return}typeof a=="string"&&(t.apiKey=a);return}case"baseUrl":{if(i){delete t.baseUrl;return}typeof a=="string"&&(t.baseUrl=a);return}case"apiBaseUrl":{if(i){delete t.apiBaseUrl;return}typeof a=="string"&&(t.apiBaseUrl=a);return}case"chatApiBaseUrl":{if(i){delete t.chatApiBaseUrl;return}typeof a=="string"&&(t.chatApiBaseUrl=a);return}case"token":case"appId":case"conversationId":{if(t.session||(t.session={}),i){delete t.session[n],lo(t);return}(typeof a=="string"||a===null)&&(t.session[n]=a),lo(t);return}}}s(ic,"applyScopedKey");function sc(t,n,a){if(!no.some(u=>_e(n,u)))return!1;let i=t.accounts??[],o=Fe(n.activeProfile)??oc(t),l=N(_e(n,"baseUrl")?n.baseUrl??null:o.baseUrl??process.env.OPENPOND_BASE_URL),c=po(i,o.handle,l);for(let u of no)_e(n,u)&&ic(c,u,n[u],a);return t.accounts=i,t.activeProfile=Ve(c),!0}s(sc,"applyAccountPatch");function lc(t,n){if(_e(n,"lspEnabled")&&(typeof n.lspEnabled=="boolean"?t.lspEnabled=n.lspEnabled:n.lspEnabled===null&&delete t.lspEnabled),_e(n,"executionMode")&&(n.executionMode==="local"||n.executionMode==="hosted"?t.executionMode=n.executionMode:n.executionMode===null&&delete t.executionMode),_e(n,"mode")&&(n.mode==="general"||n.mode==="builder"?t.mode=n.mode:n.mode===null&&delete t.mode),_e(n,"activeProfile")){let a=Fe(n.activeProfile);if(a){let r=Nn(t.accounts??[],a);t.activeProfile=r===-1?a:Ve((t.accounts??[])[r])}else n.activeProfile===null&&delete t.activeProfile}if(_e(n,"openpondProfile")){let a=Dn(n.openpondProfile);a?t.openpondProfile=a:n.openpondProfile===null&&delete t.openpondProfile}}s(lc,"applyTopLevelPatch");async function Mt(t){let n=X();return await yn(n),await wr(n,a=>{let r=uo(a);return t(r),r})}s(Mt,"updateGlobalConfig");async function V(){let t=X();return await yn(t),uo(await kr(t))}s(V,"loadGlobalConfig");async function zn(){let t=await V(),n=Fe(t.activeProfile);return(t.accounts??[]).map(a=>{let r=ge(a.handle)??Et;return{handle:r,baseUrl:N(a.baseUrl),apiBaseUrl:N(a.apiBaseUrl),chatApiBaseUrl:N(a.chatApiBaseUrl),environment:a.environment?.trim()||null,isActive:!!(n&&mo({...a,handle:r},n)),hasApiKey:!!a.apiKey?.trim(),hasSessionToken:!!a.session?.token?.trim(),sessionAppId:a.session?.appId??null,sessionConversationId:a.session?.conversationId??null}})}s(zn,"listConfiguredProfiles");async function cc(t,n={}){let a=co(t),r=N(n.baseUrl),i=-1;await Mt(l=>{let c=l.accounts??[];if(i=Nn(c,r?{handle:a,baseUrl:r}:{handle:a},{requireUnambiguous:!0}),i===-1)throw new Error(`profile not found: ${a}`);l.activeProfile=Ve(c[i])});let o=await zn();return o.find(l=>l.isActive)??o[i]}s(cc,"setActiveProfile");async function mc(t){let n=co(t.handle),a=ec(t.apiKey),r=N(t.baseUrl),i=N(t.apiBaseUrl),o=N(t.chatApiBaseUrl),l={handle:n};await Mt(p=>{let k=p.accounts??[],v=po(k,n,r);v.apiKey=a,r&&(v.baseUrl=r),i?v.apiBaseUrl=i:t.apiBaseUrl===null&&delete v.apiBaseUrl,o?v.chatApiBaseUrl=o:t.chatApiBaseUrl===null&&delete v.chatApiBaseUrl,t.environment===null?delete v.environment:typeof t.environment=="string"&&t.environment.trim()&&(v.environment=t.environment.trim()),p.accounts=k,l=Ve(v),t.setActive!==!1&&(p.activeProfile=l)});let u=(await zn()).find(p=>lt(p.handle,l.handle)?r?N(p.baseUrl)===r:!0:!1);if(!u)throw new Error(`failed to save profile: ${n}`);return u}s(mc,"saveProfileApiKey");async function le(t){await Mt(n=>{lc(n,t),sc(n,t,{undefinedDeletes:!1})})}s(le,"saveGlobalConfig");function Fn(t=null){return{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!0,error:t}}s(Fn,"emptyProfileCatalogState");function Vn(t=null){return{skillCount:0,generatedAt:null,stale:!0,error:t}}s(Vn,"emptyProfileSkillCatalogState");function Gn(){return{status:"ready",requirementCount:0,blockingCount:0,optionalMissingCount:0,readyCount:0,requirements:[],blockingRequirements:[]}}s(Gn,"emptyProfileSetupGate");function Ut(){return{changedAgents:[],newAgents:[],deletedAgents:[],changedSkills:[],changedActions:[],changedExtensions:[],setupChanges:[],envRequirementChanges:[],files:[]}}s(Ut,"emptyProfileDiffSummary");function Kn(t=null){return{state:t?"error":"none",message:t??"No active OpenPond profile.",agentCount:0,actionCount:0,defaultAction:null,checkFresh:!1,checkStaleReason:t??"No active profile.",localHead:null,hostedHead:null}}s(Kn,"emptyProfileSummary");import{existsSync as Ge}from"node:fs";import{readFile as uc,stat as dc}from"node:fs/promises";import Ht from"node:path";var go=".openpond/agent-manifest.json",fo=".openpond/action-registry.json",pc=".openpond/source-upload-metadata.json",gc=".openpond/agent-package-origin.json";async function xo(t){return So({agentId:"default",sourcePath:t,preferred:!0})}s(xo,"loadProfileActionCatalog");async function yo(t){if(t.length===0)return{catalog:{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!1,error:null},actionCatalog:[],sourceSetupRequirements:[]};let n=[...t.filter(c=>c.preferred),...t.filter(c=>!c.preferred)],a=await Promise.all(n.map(So)),r=new Map,i=[];for(let c of a)for(let u of c.actionCatalog){let p=r.has(u.id)?`${u.agentId??"agent"}.${u.sourceActionId??u.id}`:u.id,k=p===u.id?u:{...u,id:p};r.set(p,k),i.push(k)}let o=hc(a.map(c=>c.catalog.generatedAt)),l=a.map(c=>c.catalog.error).filter(Boolean);return{catalog:{actionCount:i.length,generatedAt:o,manifestPath:a.find(c=>c.catalog.manifestPath)?.catalog.manifestPath??null,registryPath:a.find(c=>c.catalog.registryPath)?.catalog.registryPath??null,stale:a.some(c=>c.catalog.stale),error:l.length>0?l.join("; "):null},actionCatalog:i,sourceSetupRequirements:a.flatMap(c=>c.sourceSetupRequirements)}}s(yo,"loadProfileActionCatalogForSources");async function So(t){let n=t.sourcePath,a=Ht.join(n,go),r=Ht.join(n,fo),i=Ht.join(n,pc),o=Ht.join(n,gc);try{let l=await Lt(a),c=await Lt(r),u=await Lt(i),p=z(await Lt(o)),k=z(z(l)?.inputSchemas),v=bo(z(u)?.setupRequirements)??[],E=bc(v),H=new Map;for(let y of[...Wn(z(l)?.actionCatalog),...Wn(z(c)?.actions),...Wn(z(l)?.actions)]){let R=U(y.id)??U(y.name);if(!R)continue;let C=H.get(R),B=xc({sourceRequirementsByAction:E,actionId:R,actionName:U(y.name)}),Y=yc(bo(y.setupRequirements)??C?.setupRequirements??[],B),ye={id:R,agentId:t.agentId,sourcePath:n,sourceActionId:R,name:U(y.name)??C?.name??R,label:U(y.label)??C?.label??wc(R),description:U(y.description)??C?.description??null,visibility:U(y.visibility)??C?.visibility??"default",inputSchema:kc(y.inputSchema,k)??C?.inputSchema??null,outputSchema:vo(y.outputSchema)??C?.outputSchema??null,approvalPolicy:z(y.approvalPolicy)??C?.approvalPolicy??null,artifactPolicy:z(y.artifactPolicy)??C?.artifactPolicy??null,setupRequirements:Y,mcp:z(y.mcp)??C?.mcp??null,schedulePolicy:z(y.schedulePolicy)??C?.schedulePolicy??null,trace:fc(z(y.trace)??C?.trace??null,p),implementation:z(y.implementation)??C?.implementation??null,invokesModel:typeof y.invokesModel=="boolean"?y.invokesModel:C?.invokesModel};H.set(R,ye)}let x=Array.from(H.values()).filter(y=>y.visibility!=="internal"&&y.visibility!=="debug"),_=[...l?[]:[go],...c?[]:[fo]],w=await _c([a,r]);return{catalog:{actionCount:x.length,generatedAt:w,manifestPath:Ge(a)?a:null,registryPath:Ge(r)?r:null,stale:_.length>0,error:_.length>0?vc(t,_):null},actionCatalog:x,sourceSetupRequirements:v}}catch(l){return{catalog:{actionCount:0,generatedAt:null,manifestPath:Ge(a)?a:null,registryPath:Ge(r)?r:null,stale:!0,error:l instanceof Error?l.message:String(l)},actionCatalog:[],sourceSetupRequirements:[]}}}s(So,"loadProfileActionCatalogSource");function fc(t,n){if(!n)return t;let a=U(n.versionId),r=U(n.digest);return!a||!r?t:{...t??{},agentVersionId:a,agentPackageDigest:r,validationReceiptIds:ho(n.validationReceiptIds),evalReceiptIds:ho(n.evalReceiptIds)}}s(fc,"mergeAgentPackageTrace");function ho(t){return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.trim().length>0):[]}s(ho,"stringArray");function hc(t){let n=0;for(let a of t){if(!a)continue;let r=Date.parse(a);Number.isFinite(r)&&(n=Math.max(n,r))}return n>0?new Date(n).toISOString():null}s(hc,"latestIso");function bc(t){let n=new Map;for(let a of t){let r=[U(a.actionId),U(a.sourceActionId),U(a.actionName)].filter(i=>!!i);for(let i of r){let o=n.get(i)??[];o.push(a),n.set(i,o)}}return n}s(bc,"sourceSetupRequirementsByAction");function xc(t){return[...t.sourceRequirementsByAction.get(t.actionId)??[],...t.actionName&&t.actionName!==t.actionId?t.sourceRequirementsByAction.get(t.actionName)??[]:[]].map(a=>({...a,source:"source_upload_metadata"}))}s(xc,"setupRequirementsForActionSource");function yc(t,n){if(n.length===0)return t;let a=[],r=new Set;for(let i of[...t,...n]){let o=Sc(i);r.has(o)||(r.add(o),a.push(i))}return a}s(yc,"mergeSetupRequirements");function Sc(t){return[U(t.actionId)??U(t.sourceActionId)??U(t.actionName)??"",U(t.kind)??U(t.type)??"",U(t.name)??U(t.key)??U(t.provider)??U(t.tool)??U(t.command)??U(t.packageName)??U(t.path)??U(t.repo)??U(t.url)??U(t.id)??""].join(":")}s(Sc,"setupRequirementIdentity");function vc(t,n){return[`Profile agent ${t.agentId} at ${t.sourcePath} is missing SDK catalog artifact(s): ${n.join(", ")}.`,"Run `openpond profile check --kind all` after source materialization so each enabled profile agent has inspect/build artifacts."].join(" ")}s(vc,"missingSourceArtifactsMessage");async function Lt(t){return Ge(t)?JSON.parse(await uc(t,"utf8")):null}s(Lt,"readJsonIfExists");async function _c(t){let n=0;for(let a of t){if(!Ge(a))continue;let r=await dc(a);n=Math.max(n,r.mtimeMs)}return n>0?new Date(n).toISOString():null}s(_c,"latestMtime");function z(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}s(z,"asRecord");function Wn(t){return Array.isArray(t)?t.filter(n=>!!z(n)):[]}s(Wn,"records");function bo(t){return Array.isArray(t)?t.filter(n=>!!z(n)):null}s(bo,"recordArray");function U(t){return typeof t=="string"&&t.trim()?t.trim():null}s(U,"text");function vo(t){return U(t)??z(t)}s(vo,"schemaValue");function kc(t,n){let a=vo(t);return typeof a!="string"?a:z(n?.[a])??a}s(kc,"resolvedSchemaValue");function wc(t){let n=t.replace(/[._-]+/g," ").trim();return n?n.replace(/\b\w/g,a=>a.toUpperCase()):t}s(wc,"titleFromActionId");var Bt=class extends Error{static{s(this,"OpenPondProfileSetupRequiredError")}code="agent_source_setup_required";details;constructor(n,a){let r=a.blockingRequirements.map(i=>i.label);super(["agent_source_setup_required",`Profile action ${n} has unresolved required setup.`,r.length?`Missing setup: ${r.join(", ")}`:""].filter(Boolean).join(`
2
+ import{$ as In,Aa as Fr,Ba as Vr,Ca as At,Eb as Gr,I as Lr,Va as On,b as _n,ba as An,c as It,dd as Pt,ed as Ct,fd as Tt,g as kn,gd as Un,la as Pn,ld as Ne,ma as Cn,oa as Br,ra as qr,sa as Tn,sc as Mn,t as wn,ta as jn,u as Rn,va as $r,wa as Dr,xa as Nr,ya as zr,za as En}from"./chunk-TR37PJIQ.js";import{a as Hn,b as Kr,c as Wr}from"./chunk-6MI4KKWF.js";import{b as ne,d as kt,e as wt}from"./chunk-J2S7BOZU.js";import{J as Tr,L as vn,M as jr,N as Er,bb as Ur,h as Rr,i as Ir,k as Ar,l as Pr,p as ve,q as Cr,s as Rt,t as Sn,ya as Or,z as ae,za as Mr}from"./chunk-D6BBQHZM.js";import{a as Hr}from"./chunk-6FA3GG5B.js";import{$a as wr,A as $,J as dn,K as mr,Pa as bn,Q as ot,Qa as xn,R as it,S as ur,U as dr,_a as kr,ba as pr,ca as gr,da as $e,ea as pn,f as _t,fa as De,ga as st,ha as Se,ja as fr,jb as yn,k as m,ka as hr,l as g,m as S,na as br,o as b,oa as xr,p as O,pa as gn,ra as yr,sa as Sr,ta as fn,ua as vr,z as cr}from"./chunk-F4WS5QIT.js";import{b as e}from"./chunk-ES2ISFJC.js";import{f as X,h as vt,p as hn,r as _r}from"./chunk-H7IWJN7L.js";import{a as s}from"./chunk-FTQLQJQV.js";import{createHash as Vl}from"node:crypto";import{existsSync as Qr}from"node:fs";import{readdir as Zr,readFile as eo,stat as Gl}from"node:fs/promises";import se from"node:path";var Ln="skills",jt="SKILL.md",Jr=8e4;async function Bn(t){let n=se.join(t,Ln);if(!Qr(n))return{skillCatalog:Yr({stale:!1}),skills:[]};try{let a=await Zr(n,{withFileTypes:!0}),r=(await Promise.all(a.filter(o=>o.isDirectory()).map(o=>Kl(t,o.name)))).sort((o,l)=>o.name.localeCompare(l.name)||o.path.localeCompare(l.path));Jl(r);let i=await Yl(t,r);return{skillCatalog:{skillCount:r.length,generatedAt:i,stale:!1,error:null},skills:r}}catch(a){return{skillCatalog:Yr({stale:!0,error:a instanceof Error?a.message:String(a)}),skills:[]}}}s(Bn,"loadProfileSkills");function ze(t){let n=[],a=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/.exec(t);if(!a)return{name:null,description:null,body:t.trim(),messages:["SKILL.md must start with YAML frontmatter bounded by ---."]};let r=a[1]??"",i=(a[2]??"").trim(),o;try{o=Hr.load(r)}catch(p){n.push(`SKILL.md frontmatter is invalid YAML: ${p instanceof Error?p.message:String(p)}`)}let l=Xl(o),c=Xr(l?.name),u=Xr(l?.description);return c||n.push("Skill frontmatter must include a non-empty name."),u||n.push("Skill frontmatter must include a non-empty description."),i||n.push("Skill body must be non-empty markdown."),{name:c,description:u,body:i,messages:n}}s(ze,"parseProfileSkillMarkdown");async function Rh(t){let n=t.name.trim();if(!to(n))throw new Error("Profile skill name must be lowercase kebab-case.");let r=(await Bn(t.profileSourcePath)).skills.find(c=>c.name===n);if(!r)throw new Error(`Profile skill not found: ${n}`);if(!r.enabled||r.validationStatus!=="valid"){let c=r.validationMessages.length>0?` ${r.validationMessages.join(" ")}`:"";throw new Error(`Profile skill ${n} is not valid.${c}`)}let i=se.join(t.profileSourcePath,r.path),o=await eo(i,"utf8"),l=ze(o);if(l.messages.length>0)throw new Error(`Profile skill ${n} is not valid. ${l.messages.join(" ")}`);return{name:r.name,description:r.description,body:l.body,path:r.path,sourcePath:r.sourcePath,sourceHash:r.sourceHash,charCount:r.charCount,packagePath:se.dirname(i),resourceFiles:r.resourceFiles}}s(Rh,"readProfileSkill");function Yr(t={}){return{skillCount:0,generatedAt:null,stale:t.stale??!0,error:t.error??null}}s(Yr,"emptyProfileSkillCatalogState");async function Kl(t,n){let a=se.join(Ln,n,jt).replace(/\\/g,"/"),r=se.join(t,a),i=[],o=se.join(t,Ln,n),l=await Wl(o),c="";Qr(r)?c=await eo(r,"utf8"):i.push(`Missing ${jt}.`),c.length>Jr&&i.push(`Skill markdown exceeds the limit of ${Jr} characters.`);let u=ze(c);i.push(...u.messages);let p=u.name??n,k=u.description??"";return to(p)||i.push("Skill name must be lowercase kebab-case."),p!==n&&i.push(`Skill name must match its directory name (${n}).`),{name:p,description:k,path:a,scope:"profile",enabled:i.length===0,sourcePath:t,charCount:c.length,sourceHash:Ql(c),validationStatus:i.length>0?"error":"valid",validationMessages:i,resourceFiles:l.filter(v=>v!==jt)}}s(Kl,"loadProfileSkillDirectory");async function Wl(t){let n=[];async function a(r,i){let o=await Zr(r,{withFileTypes:!0});await Promise.all(o.map(async l=>{let c=i?`${i}/${l.name}`:l.name;l.isDirectory()?await a(se.join(r,l.name),c):l.isFile()&&n.push(c)}))}return s(a,"visit"),await a(t,""),n.sort()}s(Wl,"listPackageFiles");function Jl(t){let n=new Map;for(let a of t)n.set(a.name,(n.get(a.name)??0)+1);for(let a of t)(n.get(a.name)??0)<=1||(a.enabled=!1,a.validationStatus="error",a.validationMessages=[...a.validationMessages,`Duplicate skill name: ${a.name}`])}s(Jl,"markDuplicateSkillNames");async function Yl(t,n){let a=0;for(let r of n){let i=se.dirname(se.join(t,r.path)),o=[jt,...r.resourceFiles];for(let l of o){let c=await Gl(se.join(i,l)).catch(()=>null);c?.isFile()&&(a=Math.max(a,c.mtimeMs))}}return a>0?new Date(a).toISOString():null}s(Yl,"latestSkillMtime");function to(t){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(t)}s(to,"isKebabCaseSkillName");function Xl(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}s(Xl,"asRecord");function Xr(t){if(typeof t!="string")return null;let n=t.trim();return n.length>0?n:null}s(Xr,"text");function Ql(t){return Vl("sha256").update(t).digest("hex")}s(Ql,"sha256Hex");import{createRequire as Go}from"node:module";import{createHash as $o,randomUUID as Do}from"node:crypto";import{spawn as Qc}from"node:child_process";import{existsSync as G}from"node:fs";import{cp as Zc,mkdir as me,readFile as Ko,readdir as Wo,rename as ra,rm as oa,symlink as em,writeFile as Je}from"node:fs/promises";import f from"node:path";import Zl from"node:path";var Et="default",no=["apiKey","baseUrl","apiBaseUrl","chatApiBaseUrl","token","appId","conversationId"];function _e(t,n){return Object.prototype.hasOwnProperty.call(t,n)}s(_e,"hasOwn");function ge(t){if(typeof t!="string")return null;let n=t.trim();return n.length>0?n:null}s(ge,"normalizeHandle");function N(t){if(typeof t!="string")return null;let n=t.trim();return n?n.replace(/\/$/,""):null}s(N,"normalizeBaseUrl");function co(t){let n=ge(t);if(!n)throw new Error("profile handle must be non-empty");return n}s(co,"requireHandle");function ec(t){if(typeof t!="string")throw new Error("apiKey must be a non-empty string");let n=t.trim();if(!n)throw new Error("apiKey must be a non-empty string");return n}s(ec,"requireApiKey");function lt(t,n){let a=ge(t),r=ge(n);return!!(a&&r&&a.toLowerCase()===r.toLowerCase())}s(lt,"handleEquals");function $n(t,n,a){let r=N(a);return t.findIndex(i=>lt(i.handle,n)?r?N(i.baseUrl)===r:!0:!1)}s($n,"findAccountIndex");function Ve(t){let n=ge(t.handle)??Et,a=N(t.baseUrl);return a?{handle:n,baseUrl:a}:{handle:n}}s(Ve,"selectorFromAccount");function Fe(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,a=ge(typeof n.handle=="string"?n.handle:void 0);if(!a)return null;let r=N(typeof n.baseUrl=="string"?n.baseUrl:void 0);return r?{handle:a,baseUrl:r}:{handle:a}}s(Fe,"sanitizeActiveProfile");function Dn(t){if(!t||typeof t!="object"||Array.isArray(t))return;let n=t,a=typeof n.repoPath=="string"?n.repoPath.trim():"",r=typeof n.profile=="string"&&n.profile.trim()?n.profile.trim():"default";if(!a)return;let i={repoPath:a,profile:r,mode:"local"};if(n.lastCheck&&typeof n.lastCheck=="object"&&!Array.isArray(n.lastCheck)){let o=n.lastCheck,l=o.command,c=o.status,u=o.checkedAt;(l==="inspect"||l==="build"||l==="validate"||l==="eval"||l==="run")&&(c==="passed"||c==="failed")&&typeof u=="string"&&(i.lastCheck={command:l,status:c,checkedAt:u,...typeof o.exitCode=="number"||o.exitCode===null?{exitCode:o.exitCode}:{},...typeof o.sourceHead=="string"||o.sourceHead===null?{sourceHead:o.sourceHead}:{}})}if(n.lastPush&&typeof n.lastPush=="object"&&!Array.isArray(n.lastPush)){let o=n.lastPush,l=o.status,c=o.pushedAt;(l==="pushed"||l==="failed")&&typeof c=="string"&&(i.lastPush={status:l,pushedAt:c,...typeof o.teamId=="string"||o.teamId===null?{teamId:o.teamId}:{},...typeof o.projectId=="string"||o.projectId===null?{projectId:o.projectId}:{},...typeof o.localHead=="string"||o.localHead===null?{localHead:o.localHead}:{},...typeof o.hostedHead=="string"||o.hostedHead===null?{hostedHead:o.hostedHead}:{},...typeof o.sourceRef=="string"||o.sourceRef===null?{sourceRef:o.sourceRef}:{},...o.promotionStatus==="uploaded"||o.promotionStatus==="hosted_source_materialized"||o.promotionStatus==="hosted_source_materialize_failed"||o.promotionStatus==="hosted_source_check_pending"||o.promotionStatus==="hosted_source_check_failed"||o.promotionStatus==="hosted_source_published"||o.promotionStatus==="hosted_source_publish_failed"||o.promotionStatus==="hosted_run_pending"||o.promotionStatus==="hosted_run_passed"||o.promotionStatus==="hosted_run_failed"||o.promotionStatus===null?{promotionStatus:o.promotionStatus}:{},...o.hostedRunStatus==="not_started"||o.hostedRunStatus==="running"||o.hostedRunStatus==="passed"||o.hostedRunStatus==="failed"||o.hostedRunStatus===null?{hostedRunStatus:o.hostedRunStatus}:{},...typeof o.hostedRunAgentId=="string"||o.hostedRunAgentId===null?{hostedRunAgentId:o.hostedRunAgentId}:{},...typeof o.hostedRunId=="string"||o.hostedRunId===null?{hostedRunId:o.hostedRunId}:{},...typeof o.hostedRunAt=="string"||o.hostedRunAt===null?{hostedRunAt:o.hostedRunAt}:{},...ao(o.hostedSourceMaterialization)?{hostedSourceMaterialization:ao(o.hostedSourceMaterialization)}:{},...ro(o.hostedSourceCheck)?{hostedSourceCheck:ro(o.hostedSourceCheck)}:{},...oo(o.hostedPublish)?{hostedPublish:oo(o.hostedPublish)}:{},...io(o.hostedRun)?{hostedRun:io(o.hostedRun)}:{},...typeof o.error=="string"||o.error===null?{error:o.error}:{}})}if(Array.isArray(n.profiles)){let o=n.profiles.flatMap(l=>{let c=Dn(l);if(!c)return[];let u=l,p=u.source==="github"||u.source==="openpond_git"?u.source:"local",k=typeof u.repositoryId=="string"&&u.repositoryId.trim()?u.repositoryId.trim():Zl.resolve(c.repoPath);return[{source:p,repositoryId:k,repoPath:c.repoPath,profile:c.profile,...c.lastCheck?{lastCheck:c.lastCheck}:{},...c.lastPush?{lastPush:c.lastPush}:{}}]});o.length>0&&(i.profiles=o)}return i}s(Dn,"sanitizeLocalOpenPondProfile");function ao(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,a=Ot(n.status);return a?{status:a,...A(n,"agentId"),...A(n,"runtimeAgentId"),...A(n,"projectId"),...A(n,"sourceRoot"),...A(n,"sourceRef"),...A(n,"sourceCommitSha"),...A(n,"manifestHash"),...A(n,"manifestPath"),...A(n,"manifestSyncedAt"),...so(n,"fileCount"),...so(n,"totalBytes"),...A(n,"generatedManifestPath"),...qn(n,"synthesizedOpenPondYaml"),...A(n,"uploadMetadataPath"),...F(n,"setupCommands"),...F(n,"validationCommands"),...A(n,"materializedAt"),...A(n,"error")}:null}s(ao,"sanitizeHostedMaterializationStatus");function ro(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,a=Ot(n.status);return a?{status:a,...A(n,"agentId"),...A(n,"deployPlanStatus"),...qn(n,"canRun"),...qn(n,"canDeploy"),...A(n,"sourceRef"),...A(n,"sourceCommitSha"),...A(n,"manifestHash"),...A(n,"manifestPath"),...F(n,"setupCommands"),...F(n,"validationCommands"),...F(n,"requiredChecks"),...F(n,"evalNames"),...F(n,"blockedReasons"),...F(n,"staleReasons"),...A(n,"runtimeId"),...A(n,"sandboxId"),...F(n,"traceArtifactRefs"),...F(n,"evalResultArtifactRefs"),...F(n,"validatorArtifactRefs"),...A(n,"checkedAt"),...A(n,"error")}:null}s(ro,"sanitizeHostedSourceCheckStatus");function oo(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,a=Ot(n.status);return a?{status:a,...A(n,"agentId"),...A(n,"snapshotId"),...A(n,"sourceRef"),...A(n,"sourceCommitSha"),...A(n,"manifestHash"),...A(n,"manifestPath"),...A(n,"buildStatus"),...A(n,"validationStatus"),...A(n,"evalStatus"),...A(n,"publishedAt"),...A(n,"error")}:null}s(oo,"sanitizeHostedPublishStatus");function io(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,a=Ot(n.status);return a?{status:a,...A(n,"agentId"),...A(n,"runId"),...A(n,"runtimeId"),...A(n,"sandboxId"),...A(n,"sourceRef"),...A(n,"sourceCommitSha"),...A(n,"manifestHash"),...A(n,"setupGateStatus"),...F(n,"setupRequirementRefs"),...F(n,"artifactRefs"),...F(n,"traceArtifactRefs"),...F(n,"evalArtifactRefs"),...A(n,"startedAt"),...A(n,"completedAt"),...A(n,"error")}:null}s(io,"sanitizeHostedRunSummary");function A(t,n){let a=t[n];return typeof a=="string"||a===null?{[n]:a}:{}}s(A,"nullableStringProp");function qn(t,n){let a=t[n];return typeof a=="boolean"||a===null?{[n]:a}:{}}s(qn,"nullableBooleanProp");function so(t,n){let a=t[n];return typeof a=="number"||a===null?{[n]:a}:{}}s(so,"nullableNumberProp");function F(t,n){let a=t[n];if(!Array.isArray(a))return{};let r=a.filter(i=>typeof i=="string");return{[n]:r}}s(F,"stringArrayProp");function Ot(t){return typeof t=="string"&&t.trim()?t.trim():null}s(Ot,"stringField");function mo(t,n){if(!lt(t.handle,n.handle))return!1;let a=N(n.baseUrl);return a?N(t.baseUrl)===a:!N(t.baseUrl)}s(mo,"accountMatchesSelector");function Nn(t,n,a={}){let r=N(n.baseUrl);if(r)return $n(t,n.handle,r);let i=t.findIndex(l=>mo(l,n));if(i!==-1)return i;let o=t.map((l,c)=>({account:l,index:c})).filter(({account:l})=>lt(l.handle,n.handle));if(o.length>1&&a.requireUnambiguous)throw new Error(`multiple profiles found for ${n.handle}; pass --base-url to select one`);return o[0]?.index??-1}s(Nn,"findAccountIndexForSelector");function tc(t){if(!t||typeof t!="object"||Array.isArray(t))return;let n=t,a={};return typeof n.token=="string"&&(a.token=n.token),(typeof n.appId=="string"||n.appId===null)&&(a.appId=n.appId),(typeof n.conversationId=="string"||n.conversationId===null)&&(a.conversationId=n.conversationId),Object.keys(a).length>0?a:void 0}s(tc,"sanitizeSession");function nc(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,a=ge(typeof n.handle=="string"?n.handle:void 0);if(!a)return null;let r={handle:a};typeof n.apiKey=="string"&&(r.apiKey=n.apiKey),typeof n.baseUrl=="string"&&(r.baseUrl=n.baseUrl),typeof n.apiBaseUrl=="string"&&(r.apiBaseUrl=n.apiBaseUrl),typeof n.chatApiBaseUrl=="string"&&(r.chatApiBaseUrl=n.chatApiBaseUrl),typeof n.environment=="string"&&(r.environment=n.environment);let i=tc(n.session);return i&&(r.session=i),r}s(nc,"sanitizeAccount");function ac(t){let n={};return typeof t.token=="string"&&(n.token=t.token),(typeof t.appId=="string"||t.appId===null)&&(n.appId=t.appId),(typeof t.conversationId=="string"||t.conversationId===null)&&(n.conversationId=t.conversationId),Object.keys(n).length>0?n:void 0}s(ac,"extractLegacySession");function rc(t,n){let a={handle:n};typeof t.apiKey=="string"&&(a.apiKey=t.apiKey),typeof t.baseUrl=="string"&&(a.baseUrl=t.baseUrl),typeof t.apiBaseUrl=="string"&&(a.apiBaseUrl=t.apiBaseUrl),typeof t.chatApiBaseUrl=="string"&&(a.chatApiBaseUrl=t.chatApiBaseUrl);let r=ac(t);return r&&(a.session=r),a}s(rc,"extractLegacyAccount");function uo(t){let n={};typeof t.lspEnabled=="boolean"&&(n.lspEnabled=t.lspEnabled),(t.executionMode==="local"||t.executionMode==="hosted")&&(n.executionMode=t.executionMode),(t.mode==="general"||t.mode==="builder")&&(n.mode=t.mode);let a=Dn(t.openpondProfile);a&&(n.openpondProfile=a);let r=[],i=Array.isArray(t.accounts)?t.accounts:[];for(let u of i){let p=nc(u);p&&$n(r,p.handle,p.baseUrl)===-1&&r.push(p)}if(r.length===0){let u=Fe(t.activeProfile)?.handle||Et;r.push(rc(t,u))}let o=Fe(t.activeProfile),l=o?Nn(r,o):-1,c=r[l===-1?0:l];return n.accounts=r,n.activeProfile=Ve(c),n}s(uo,"normalizeGlobalConfig");function oc(t,n,a){let r=t.accounts??[],i=N(a??process.env.OPENPOND_BASE_URL),o=ge(n);if(o)return i?{handle:o,baseUrl:i}:{handle:o};let l=ge(process.env.OPENPOND_ACCOUNT);if(l)return i?{handle:l,baseUrl:i}:{handle:l};let c=Fe(t.activeProfile);return c?i?{handle:c.handle,baseUrl:i}:c:r[0]?Ve(r[0]):{handle:Et}}s(oc,"resolveRequestedProfile");function po(t,n,a){let r=N(a);if(r){let o=$n(t,n,r);if(o!==-1)return t[o]}else{let o=t.filter(l=>lt(l.handle,n));if(o.length>1)throw new Error(`multiple profiles found for ${n}; pass --base-url to select one`);if(o.length===1)return o[0]}let i={handle:n};return r&&(i.baseUrl=r),t.push(i),i}s(po,"ensureAccount");function lo(t){t.session&&Object.keys(t.session).length===0&&delete t.session}s(lo,"cleanupAccount");function ic(t,n,a,r){let i=a===null||a===void 0&&r.undefinedDeletes;switch(n){case"apiKey":{if(i){delete t.apiKey;return}typeof a=="string"&&(t.apiKey=a);return}case"baseUrl":{if(i){delete t.baseUrl;return}typeof a=="string"&&(t.baseUrl=a);return}case"apiBaseUrl":{if(i){delete t.apiBaseUrl;return}typeof a=="string"&&(t.apiBaseUrl=a);return}case"chatApiBaseUrl":{if(i){delete t.chatApiBaseUrl;return}typeof a=="string"&&(t.chatApiBaseUrl=a);return}case"token":case"appId":case"conversationId":{if(t.session||(t.session={}),i){delete t.session[n],lo(t);return}(typeof a=="string"||a===null)&&(t.session[n]=a),lo(t);return}}}s(ic,"applyScopedKey");function sc(t,n,a){if(!no.some(u=>_e(n,u)))return!1;let i=t.accounts??[],o=Fe(n.activeProfile)??oc(t),l=N(_e(n,"baseUrl")?n.baseUrl??null:o.baseUrl??process.env.OPENPOND_BASE_URL),c=po(i,o.handle,l);for(let u of no)_e(n,u)&&ic(c,u,n[u],a);return t.accounts=i,t.activeProfile=Ve(c),!0}s(sc,"applyAccountPatch");function lc(t,n){if(_e(n,"lspEnabled")&&(typeof n.lspEnabled=="boolean"?t.lspEnabled=n.lspEnabled:n.lspEnabled===null&&delete t.lspEnabled),_e(n,"executionMode")&&(n.executionMode==="local"||n.executionMode==="hosted"?t.executionMode=n.executionMode:n.executionMode===null&&delete t.executionMode),_e(n,"mode")&&(n.mode==="general"||n.mode==="builder"?t.mode=n.mode:n.mode===null&&delete t.mode),_e(n,"activeProfile")){let a=Fe(n.activeProfile);if(a){let r=Nn(t.accounts??[],a);t.activeProfile=r===-1?a:Ve((t.accounts??[])[r])}else n.activeProfile===null&&delete t.activeProfile}if(_e(n,"openpondProfile")){let a=Dn(n.openpondProfile);a?t.openpondProfile=a:n.openpondProfile===null&&delete t.openpondProfile}}s(lc,"applyTopLevelPatch");async function Mt(t){let n=X();return await yn(n),await wr(n,a=>{let r=uo(a);return t(r),r})}s(Mt,"updateGlobalConfig");async function V(){let t=X();return await yn(t),uo(await kr(t))}s(V,"loadGlobalConfig");async function zn(){let t=await V(),n=Fe(t.activeProfile);return(t.accounts??[]).map(a=>{let r=ge(a.handle)??Et;return{handle:r,baseUrl:N(a.baseUrl),apiBaseUrl:N(a.apiBaseUrl),chatApiBaseUrl:N(a.chatApiBaseUrl),environment:a.environment?.trim()||null,isActive:!!(n&&mo({...a,handle:r},n)),hasApiKey:!!a.apiKey?.trim(),hasSessionToken:!!a.session?.token?.trim(),sessionAppId:a.session?.appId??null,sessionConversationId:a.session?.conversationId??null}})}s(zn,"listConfiguredProfiles");async function cc(t,n={}){let a=co(t),r=N(n.baseUrl),i=-1;await Mt(l=>{let c=l.accounts??[];if(i=Nn(c,r?{handle:a,baseUrl:r}:{handle:a},{requireUnambiguous:!0}),i===-1)throw new Error(`profile not found: ${a}`);l.activeProfile=Ve(c[i])});let o=await zn();return o.find(l=>l.isActive)??o[i]}s(cc,"setActiveProfile");async function mc(t){let n=co(t.handle),a=ec(t.apiKey),r=N(t.baseUrl),i=N(t.apiBaseUrl),o=N(t.chatApiBaseUrl),l={handle:n};await Mt(p=>{let k=p.accounts??[],v=po(k,n,r);v.apiKey=a,r&&(v.baseUrl=r),i?v.apiBaseUrl=i:t.apiBaseUrl===null&&delete v.apiBaseUrl,o?v.chatApiBaseUrl=o:t.chatApiBaseUrl===null&&delete v.chatApiBaseUrl,t.environment===null?delete v.environment:typeof t.environment=="string"&&t.environment.trim()&&(v.environment=t.environment.trim()),p.accounts=k,l=Ve(v),t.setActive!==!1&&(p.activeProfile=l)});let u=(await zn()).find(p=>lt(p.handle,l.handle)?r?N(p.baseUrl)===r:!0:!1);if(!u)throw new Error(`failed to save profile: ${n}`);return u}s(mc,"saveProfileApiKey");async function le(t){await Mt(n=>{lc(n,t),sc(n,t,{undefinedDeletes:!1})})}s(le,"saveGlobalConfig");function Fn(t=null){return{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!0,error:t}}s(Fn,"emptyProfileCatalogState");function Vn(t=null){return{skillCount:0,generatedAt:null,stale:!0,error:t}}s(Vn,"emptyProfileSkillCatalogState");function Gn(){return{status:"ready",requirementCount:0,blockingCount:0,optionalMissingCount:0,readyCount:0,requirements:[],blockingRequirements:[]}}s(Gn,"emptyProfileSetupGate");function Ut(){return{changedAgents:[],newAgents:[],deletedAgents:[],changedSkills:[],changedActions:[],changedExtensions:[],setupChanges:[],envRequirementChanges:[],files:[]}}s(Ut,"emptyProfileDiffSummary");function Kn(t=null){return{state:t?"error":"none",message:t??"No active OpenPond profile.",agentCount:0,actionCount:0,defaultAction:null,checkFresh:!1,checkStaleReason:t??"No active profile.",localHead:null,hostedHead:null}}s(Kn,"emptyProfileSummary");import{existsSync as Ge}from"node:fs";import{readFile as uc,stat as dc}from"node:fs/promises";import Ht from"node:path";var go=".openpond/agent-manifest.json",fo=".openpond/action-registry.json",pc=".openpond/source-upload-metadata.json",gc=".openpond/agent-package-origin.json";async function xo(t){return So({agentId:"default",sourcePath:t,preferred:!0})}s(xo,"loadProfileActionCatalog");async function yo(t){if(t.length===0)return{catalog:{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!1,error:null},actionCatalog:[],sourceSetupRequirements:[]};let n=[...t.filter(c=>c.preferred),...t.filter(c=>!c.preferred)],a=await Promise.all(n.map(So)),r=new Map,i=[];for(let c of a)for(let u of c.actionCatalog){let p=r.has(u.id)?`${u.agentId??"agent"}.${u.sourceActionId??u.id}`:u.id,k=p===u.id?u:{...u,id:p};r.set(p,k),i.push(k)}let o=hc(a.map(c=>c.catalog.generatedAt)),l=a.map(c=>c.catalog.error).filter(Boolean);return{catalog:{actionCount:i.length,generatedAt:o,manifestPath:a.find(c=>c.catalog.manifestPath)?.catalog.manifestPath??null,registryPath:a.find(c=>c.catalog.registryPath)?.catalog.registryPath??null,stale:a.some(c=>c.catalog.stale),error:l.length>0?l.join("; "):null},actionCatalog:i,sourceSetupRequirements:a.flatMap(c=>c.sourceSetupRequirements)}}s(yo,"loadProfileActionCatalogForSources");async function So(t){let n=t.sourcePath,a=Ht.join(n,go),r=Ht.join(n,fo),i=Ht.join(n,pc),o=Ht.join(n,gc);try{let l=await Lt(a),c=await Lt(r),u=await Lt(i),p=z(await Lt(o)),k=z(z(l)?.inputSchemas),v=bo(z(u)?.setupRequirements)??[],E=bc(v),H=new Map;for(let y of[...Wn(z(l)?.actionCatalog),...Wn(z(c)?.actions),...Wn(z(l)?.actions)]){let R=U(y.id)??U(y.name);if(!R)continue;let C=H.get(R),B=xc({sourceRequirementsByAction:E,actionId:R,actionName:U(y.name)}),Y=yc(bo(y.setupRequirements)??C?.setupRequirements??[],B),ye={id:R,agentId:t.agentId,sourcePath:n,sourceActionId:R,name:U(y.name)??C?.name??R,label:U(y.label)??C?.label??wc(R),description:U(y.description)??C?.description??null,visibility:U(y.visibility)??C?.visibility??"default",inputSchema:kc(y.inputSchema,k)??C?.inputSchema??null,outputSchema:vo(y.outputSchema)??C?.outputSchema??null,approvalPolicy:z(y.approvalPolicy)??C?.approvalPolicy??null,artifactPolicy:z(y.artifactPolicy)??C?.artifactPolicy??null,setupRequirements:Y,mcp:z(y.mcp)??C?.mcp??null,schedulePolicy:z(y.schedulePolicy)??C?.schedulePolicy??null,trace:fc(z(y.trace)??C?.trace??null,p),implementation:z(y.implementation)??C?.implementation??null,invokesModel:typeof y.invokesModel=="boolean"?y.invokesModel:C?.invokesModel};H.set(R,ye)}let x=Array.from(H.values()).filter(y=>y.visibility!=="internal"&&y.visibility!=="debug"),_=[...l?[]:[go],...c?[]:[fo]],w=await _c([a,r]);return{catalog:{actionCount:x.length,generatedAt:w,manifestPath:Ge(a)?a:null,registryPath:Ge(r)?r:null,stale:_.length>0,error:_.length>0?vc(t,_):null},actionCatalog:x,sourceSetupRequirements:v}}catch(l){return{catalog:{actionCount:0,generatedAt:null,manifestPath:Ge(a)?a:null,registryPath:Ge(r)?r:null,stale:!0,error:l instanceof Error?l.message:String(l)},actionCatalog:[],sourceSetupRequirements:[]}}}s(So,"loadProfileActionCatalogSource");function fc(t,n){if(!n)return t;let a=U(n.versionId),r=U(n.digest);return!a||!r?t:{...t??{},agentVersionId:a,agentPackageDigest:r,validationReceiptIds:ho(n.validationReceiptIds),evalReceiptIds:ho(n.evalReceiptIds)}}s(fc,"mergeAgentPackageTrace");function ho(t){return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.trim().length>0):[]}s(ho,"stringArray");function hc(t){let n=0;for(let a of t){if(!a)continue;let r=Date.parse(a);Number.isFinite(r)&&(n=Math.max(n,r))}return n>0?new Date(n).toISOString():null}s(hc,"latestIso");function bc(t){let n=new Map;for(let a of t){let r=[U(a.actionId),U(a.sourceActionId),U(a.actionName)].filter(i=>!!i);for(let i of r){let o=n.get(i)??[];o.push(a),n.set(i,o)}}return n}s(bc,"sourceSetupRequirementsByAction");function xc(t){return[...t.sourceRequirementsByAction.get(t.actionId)??[],...t.actionName&&t.actionName!==t.actionId?t.sourceRequirementsByAction.get(t.actionName)??[]:[]].map(a=>({...a,source:"source_upload_metadata"}))}s(xc,"setupRequirementsForActionSource");function yc(t,n){if(n.length===0)return t;let a=[],r=new Set;for(let i of[...t,...n]){let o=Sc(i);r.has(o)||(r.add(o),a.push(i))}return a}s(yc,"mergeSetupRequirements");function Sc(t){return[U(t.actionId)??U(t.sourceActionId)??U(t.actionName)??"",U(t.kind)??U(t.type)??"",U(t.name)??U(t.key)??U(t.provider)??U(t.tool)??U(t.command)??U(t.packageName)??U(t.path)??U(t.repo)??U(t.url)??U(t.id)??""].join(":")}s(Sc,"setupRequirementIdentity");function vc(t,n){return[`Profile agent ${t.agentId} at ${t.sourcePath} is missing SDK catalog artifact(s): ${n.join(", ")}.`,"Run `openpond profile check --kind all` after source materialization so each enabled profile agent has inspect/build artifacts."].join(" ")}s(vc,"missingSourceArtifactsMessage");async function Lt(t){return Ge(t)?JSON.parse(await uc(t,"utf8")):null}s(Lt,"readJsonIfExists");async function _c(t){let n=0;for(let a of t){if(!Ge(a))continue;let r=await dc(a);n=Math.max(n,r.mtimeMs)}return n>0?new Date(n).toISOString():null}s(_c,"latestMtime");function z(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}s(z,"asRecord");function Wn(t){return Array.isArray(t)?t.filter(n=>!!z(n)):[]}s(Wn,"records");function bo(t){return Array.isArray(t)?t.filter(n=>!!z(n)):null}s(bo,"recordArray");function U(t){return typeof t=="string"&&t.trim()?t.trim():null}s(U,"text");function vo(t){return U(t)??z(t)}s(vo,"schemaValue");function kc(t,n){let a=vo(t);return typeof a!="string"?a:z(n?.[a])??a}s(kc,"resolvedSchemaValue");function wc(t){let n=t.replace(/[._-]+/g," ").trim();return n?n.replace(/\b\w/g,a=>a.toUpperCase()):t}s(wc,"titleFromActionId");var Bt=class extends Error{static{s(this,"OpenPondProfileSetupRequiredError")}code="agent_source_setup_required";details;constructor(n,a){let r=a.blockingRequirements.map(i=>i.label);super(["agent_source_setup_required",`Profile action ${n} has unresolved required setup.`,r.length?`Missing setup: ${r.join(", ")}`:""].filter(Boolean).join(`
3
3
  `)),this.name="OpenPondProfileSetupRequiredError",this.details={error:"agent_source_setup_required",actionId:n,setupGate:a,missing:r,blockingSetupRequirements:a.blockingRequirements,setupRequirements:a.requirements}}};function qt(t){let n=new Map;for(let l of t.sourceSetupRequirements??[]){let c=Ic(l);if(t.actionId&&c&&c!==t.actionId&&q(l.actionName)!==t.actionId&&q(l.sourceActionId)!==t.actionId)continue;let u=_o({record:l,source:"source_upload_metadata",actionId:c});u&&n.set(u.ref,u)}for(let l of t.actionCatalog)if(!(t.actionId&&l.id!==t.actionId&&l.name!==t.actionId))for(let c of l.setupRequirements??[]){let u=_o({record:c,source:"action_catalog",actionId:l.id});u&&n.set(u.ref,u)}let a=Array.from(n.values()),r=a.filter(l=>l.blocking),i=a.filter(l=>!l.required&&!Jn(l.status)).length,o=a.filter(l=>Jn(l.status)).length;return{status:Pc(r),requirementCount:a.length,blockingCount:r.length,optionalMissingCount:i,readyCount:o,requirements:a,blockingRequirements:r}}s(qt,"buildOpenPondProfileSetupGate");function Yn(t,n){if(n.blockingRequirements.length>0)throw new Bt(t,n)}s(Yn,"assertOpenPondProfileActionReady");function Rc(t){let n=t.actionId?`${t.actionId}: `:"",a=t.required?"required":"optional";return`${n}${t.label} (${a}, ${t.status})`}s(Rc,"formatOpenPondProfileSetupRequirement");function _o(t){let n=t.source==="action_catalog"&&q(t.record.source)==="source_upload_metadata"?"source_upload_metadata":t.source,a=q(t.record.kind)??q(t.record.type),r=q(t.record.label)??q(t.record.name)??q(t.record.key)??q(t.record.provider)??q(t.record.tool)??q(t.record.command)??q(t.record.packageName)??q(t.record.path)??q(t.record.repo)??q(t.record.url)??q(t.record.id)??a??"setup requirement",i=t.record.required!==!1,o=Ac(t.record);return{ref:[n,t.actionId??"source",a??"requirement",r].join(":"),source:n,actionId:t.actionId,kind:a,label:r,status:o,required:i,blocking:i&&!Jn(o)}}s(_o,"setupRequirementFromRecord");function Ic(t){return q(t.actionId)??q(t.sourceActionId)??q(t.actionName)}s(Ic,"setupRequirementActionId");function Ac(t){let n=q(t.status)??q(t.state);return n?n==="satisfied"||n==="connected"||n==="provided"?"ready":n:typeof t.satisfied=="boolean"?t.satisfied?"ready":"setup_required":typeof t.ready=="boolean"&&t.ready?"ready":"setup_required"}s(Ac,"setupStatus");function Pc(t){return t.length===0?"ready":t.some(n=>["blocked","unsupported","unsupported_dependency","stale"].includes(n.status))?"blocked":"setup_required"}s(Pc,"gateStatus");function Jn(t){return t==="ready"||t==="disabled"}s(Jn,"isReadyStatus");function q(t){return typeof t=="string"&&t.trim()?t.trim():null}s(q,"text");import{spawn as Cc}from"node:child_process";import{randomUUID as Tc}from"node:crypto";import{existsSync as Xn}from"node:fs";import{readFile as jc,rm as Ec,writeFile as Ro}from"node:fs/promises";import $t from"node:path";var Io=["**/node_modules/","**/.bun/","**/.env","**/.env.*","**/.openpond/traces/","**/.openpond/vendor/","**/.openpond/eval-results.json","**/.openpond/artifact-index.json","**/.openpond/source-upload-cache.json",""].join(`
4
4
  `);async function Ao(t){if(!Xn($t.join(t,".git"))){let o=await J(t,["init","-b","main"]);if(o.code!==0)throw new Error(Pe("git init",o))}let n=$t.join(t,".gitignore");if(Xn(n)?await Oc(n):await Ro(n,Io,"utf8"),await Uc(t))return;let a=await Ce(t);if(!a.dirty&&a.files.length===0)return;let r=await J(t,["add","-A"]);if(r.code!==0)throw new Error(Pe("git add",r));let i=await J(t,["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(i.code!==0&&!/nothing to commit/i.test(i.stdout+i.stderr))throw new Error(Pe("git commit",i))}s(Ao,"ensureProfileGitRepo");async function Oc(t){let n=await jc(t,"utf8").catch(()=>""),a=Io.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).filter(i=>!n.split(/\r?\n/).some(o=>o.trim()===i));if(a.length===0)return;let r=n.endsWith(`
5
5
  `)||n.length===0?"":`
@@ -0,0 +1,2 @@
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-Y2NQXJ2Q.js";import{a as fe,b as L,c as R}from"./chunk-TJNIYJUH.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-6LY7GYNK.js";import{d as y,e as ue,f as ge,g as C}from"./chunk-XRV4WLI7.js";import{a as Z,b as ee,c as te}from"./chunk-F3VURV3Q.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};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{d as F}from"./chunk-XDVKDELR.js";import{a as o}from"./chunk-FTQLQJQV.js";import{spawn as nt,spawnSync as At}from"node:child_process";import{accessSync as vt,constants as Rt,existsSync as _t,promises as Bt}from"node:fs";import et from"node:path";var rt="Git is required for OpenPond app workspaces, but macOS reports Apple Command Line Tools are not installed. OpenPond skipped /usr/bin/git to avoid opening the Xcode installer prompt. Install Command Line Tools with `xcode-select --install`, install Git from Homebrew, or put a non-Apple git binary earlier on PATH.",T;function Lt(e){try{return _t(e)?(vt(e,Rt.X_OK),!0):!1}catch{return!1}}o(Lt,"isExecutable");function Ot(){let e=(process.env.PATH??"").split(et.delimiter).map(t=>t.trim()).filter(Boolean);for(let t of e){let n=et.join(t,"git");if(!(n==="/usr/bin/git"||n==="/bin/git")&&Lt(n))return n}return null}o(Ot,"firstNonAppleGitOnPath");function it(){let e=At("/usr/bin/xcode-select",["-p"],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return e.status===0&&!!e.stdout.trim()}o(it,"appleDeveloperToolsAvailable");function Dt(e){if(e!=="git"||process.platform!=="darwin")return{command:e};if(T!==void 0)return{command:T};let t=Ot();return t?(T=t,{command:t}):it()?(T="git",{command:"git"}):{error:rt}}o(Dt,"resolveWorkspaceCommand");function u(e,t,n,r={},i){return new Promise(s=>{let a=Dt(e);if("error"in a){s({code:1,stdout:"",stderr:a.error});return}let c=nt(a.command,t,{cwd:n,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:[i===void 0?"ignore":"pipe","pipe","pipe"]}),d=[],p=[];i!==void 0&&c.stdin?.end(i),c.stdout?.on("data",h=>d.push(h)),c.stderr?.on("data",h=>p.push(h)),c.on("error",h=>{s({code:1,stdout:"",stderr:h.message})}),c.on("close",h=>{s({code:h??1,stdout:Buffer.concat(d).toString("utf8"),stderr:Buffer.concat(p).toString("utf8")})})})}o(u,"runCommand");function Gt(e){return!!(e&&e.includes(rt.slice(0,80)))}o(Gt,"isMacOSGitDeveloperToolsMissing");async function Se(e){await Bt.mkdir(e,{recursive:!0});let t=await u("git",["--version"],e);if(t.code===0)return{ok:!0,command:T??"git",version:(t.stdout||t.stderr).trim()};let n=t.stderr.trim()||t.stdout.trim()||"Git is required for OpenPond app workspaces.";return{ok:!1,error:n,installAction:process.platform==="darwin"&&Gt(n)?"macos_command_line_tools":"manual_git_install"}}o(Se,"checkWorkspaceGitAvailability");function ye(){if(process.platform!=="darwin")return{ok:!1,error:"Apple Command Line Tools installation is only available on macOS."};if(it())return{ok:!0,message:"Apple Command Line Tools already appear to be installed."};try{return nt("/usr/bin/xcode-select",["--install"],{detached:!0,stdio:"ignore"}).unref(),{ok:!0,message:"Opened the Apple Command Line Tools installer."}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}o(ye,"startMacOSCommandLineToolsInstall");import{promises as k}from"node:fs";import m from"node:path";var st=24e3,ot=8e4,It=512*1024,ct=15*1024*1024,Tt=20*1024*1024,Mt=new Set([".cache",".eggs",".git",".ipynb_checkpoints",".mypy_cache",".next",".nox",".nuxt",".openpond",".output",".parcel-cache",".pytest_cache",".pyre",".ruff_cache",".svelte-kit",".tox",".turbo",".venv","__pycache__","artifacts","build","coverage","dist","env","node_modules","out","site-packages","target","venv","volumes"]),zt=new Set([".7z",".avif",".db",".doc",".docx",".gif",".gz",".ico",".jpeg",".jpg",".mov",".mp4",".pdf",".png",".sqlite",".tar",".webp",".xls",".xlsm",".xlsx",".zip"]),$t=new Map([[".avif","image/avif"],[".gif","image/gif"],[".jpeg","image/jpeg"],[".jpg","image/jpeg"],[".png","image/png"],[".webp","image/webp"]]),Nt=new Map([[".m4v","video/x-m4v"],[".mov","video/quicktime"],[".mp4","video/mp4"],[".webm","video/webm"]]),Ht=new Set([".doc",".docx",".pdf"]);function Ut(e){return e.replace(/[^a-zA-Z0-9._-]/g,"-").slice(0,120)||"app"}o(Ut,"safeAppSegment");function N(e){if(!e)return"unknown";try{let t=new URL(e).hostname.toLowerCase();if(t==="github.com"||t.endsWith(".github.com"))return"github";if(t==="openpond.ai"||t.endsWith(".openpond.ai"))return"openpond"}catch{return"unknown"}return"local_git"}o(N,"sourceFromRemote");function $(e){return e.replace(/x-access-token:[^@]+@/g,"x-access-token:***@").replace(/Authorization:\s*Basic\s+[A-Za-z0-9+/=]+/gi,"Authorization: Basic ***")}o($,"redactRemoteUrl");async function G(e){try{return await k.access(e),!0}catch{return!1}}o(G,"pathExists");async function O(e){return await G(e)?(await u("git",["rev-parse","--git-dir"],e)).code===0:!1}o(O,"isGitRepo");function X(e){return e.length<=st?e:`${e.slice(0,st)}
2
+ import{d as F}from"./chunk-B3LJ777T.js";import{a as o}from"./chunk-FTQLQJQV.js";import{spawn as nt,spawnSync as At}from"node:child_process";import{accessSync as vt,constants as Rt,existsSync as _t,promises as Bt}from"node:fs";import et from"node:path";var rt="Git is required for OpenPond app workspaces, but macOS reports Apple Command Line Tools are not installed. OpenPond skipped /usr/bin/git to avoid opening the Xcode installer prompt. Install Command Line Tools with `xcode-select --install`, install Git from Homebrew, or put a non-Apple git binary earlier on PATH.",T;function Lt(e){try{return _t(e)?(vt(e,Rt.X_OK),!0):!1}catch{return!1}}o(Lt,"isExecutable");function Ot(){let e=(process.env.PATH??"").split(et.delimiter).map(t=>t.trim()).filter(Boolean);for(let t of e){let n=et.join(t,"git");if(!(n==="/usr/bin/git"||n==="/bin/git")&&Lt(n))return n}return null}o(Ot,"firstNonAppleGitOnPath");function it(){let e=At("/usr/bin/xcode-select",["-p"],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return e.status===0&&!!e.stdout.trim()}o(it,"appleDeveloperToolsAvailable");function Dt(e){if(e!=="git"||process.platform!=="darwin")return{command:e};if(T!==void 0)return{command:T};let t=Ot();return t?(T=t,{command:t}):it()?(T="git",{command:"git"}):{error:rt}}o(Dt,"resolveWorkspaceCommand");function u(e,t,n,r={},i){return new Promise(s=>{let a=Dt(e);if("error"in a){s({code:1,stdout:"",stderr:a.error});return}let c=nt(a.command,t,{cwd:n,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:[i===void 0?"ignore":"pipe","pipe","pipe"]}),d=[],p=[];i!==void 0&&c.stdin?.end(i),c.stdout?.on("data",h=>d.push(h)),c.stderr?.on("data",h=>p.push(h)),c.on("error",h=>{s({code:1,stdout:"",stderr:h.message})}),c.on("close",h=>{s({code:h??1,stdout:Buffer.concat(d).toString("utf8"),stderr:Buffer.concat(p).toString("utf8")})})})}o(u,"runCommand");function Gt(e){return!!(e&&e.includes(rt.slice(0,80)))}o(Gt,"isMacOSGitDeveloperToolsMissing");async function Se(e){await Bt.mkdir(e,{recursive:!0});let t=await u("git",["--version"],e);if(t.code===0)return{ok:!0,command:T??"git",version:(t.stdout||t.stderr).trim()};let n=t.stderr.trim()||t.stdout.trim()||"Git is required for OpenPond app workspaces.";return{ok:!1,error:n,installAction:process.platform==="darwin"&&Gt(n)?"macos_command_line_tools":"manual_git_install"}}o(Se,"checkWorkspaceGitAvailability");function ye(){if(process.platform!=="darwin")return{ok:!1,error:"Apple Command Line Tools installation is only available on macOS."};if(it())return{ok:!0,message:"Apple Command Line Tools already appear to be installed."};try{return nt("/usr/bin/xcode-select",["--install"],{detached:!0,stdio:"ignore"}).unref(),{ok:!0,message:"Opened the Apple Command Line Tools installer."}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}o(ye,"startMacOSCommandLineToolsInstall");import{promises as k}from"node:fs";import m from"node:path";var st=24e3,ot=8e4,It=512*1024,ct=15*1024*1024,Tt=20*1024*1024,Mt=new Set([".cache",".eggs",".git",".ipynb_checkpoints",".mypy_cache",".next",".nox",".nuxt",".openpond",".output",".parcel-cache",".pytest_cache",".pyre",".ruff_cache",".svelte-kit",".tox",".turbo",".venv","__pycache__","artifacts","build","coverage","dist","env","node_modules","out","site-packages","target","venv","volumes"]),zt=new Set([".7z",".avif",".db",".doc",".docx",".gif",".gz",".ico",".jpeg",".jpg",".mov",".mp4",".pdf",".png",".sqlite",".tar",".webp",".xls",".xlsm",".xlsx",".zip"]),$t=new Map([[".avif","image/avif"],[".gif","image/gif"],[".jpeg","image/jpeg"],[".jpg","image/jpeg"],[".png","image/png"],[".webp","image/webp"]]),Nt=new Map([[".m4v","video/x-m4v"],[".mov","video/quicktime"],[".mp4","video/mp4"],[".webm","video/webm"]]),Ht=new Set([".doc",".docx",".pdf"]);function Ut(e){return e.replace(/[^a-zA-Z0-9._-]/g,"-").slice(0,120)||"app"}o(Ut,"safeAppSegment");function N(e){if(!e)return"unknown";try{let t=new URL(e).hostname.toLowerCase();if(t==="github.com"||t.endsWith(".github.com"))return"github";if(t==="openpond.ai"||t.endsWith(".openpond.ai"))return"openpond"}catch{return"unknown"}return"local_git"}o(N,"sourceFromRemote");function $(e){return e.replace(/x-access-token:[^@]+@/g,"x-access-token:***@").replace(/Authorization:\s*Basic\s+[A-Za-z0-9+/=]+/gi,"Authorization: Basic ***")}o($,"redactRemoteUrl");async function G(e){try{return await k.access(e),!0}catch{return!1}}o(G,"pathExists");async function O(e){return await G(e)?(await u("git",["rev-parse","--git-dir"],e)).code===0:!1}o(O,"isGitRepo");function X(e){return e.length<=st?e:`${e.slice(0,st)}
3
3
 
4
4
  [diff truncated]`}o(X,"truncatePatch");function jt(e){return e.length<=ot?e:`${e.slice(0,ot)}
5
5
 
@@ -0,0 +1,2 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{i as s}from"./chunk-XRV4WLI7.js";import{a as i}from"./chunk-GLUWATL5.js";import{a as n}from"./chunk-FTQLQJQV.js";import{stdin as a,stdout as c}from"node:process";import{createInterface as l}from"node:readline/promises";var p=`${i}/settings/api-keys`;function u(e){let t=process.env.OPENPOND_API_KEY?.trim();if(t)return t;let r=e.apiKey?.trim();if(r)return r;let o=e.token?.trim();return o&&o.startsWith("opk_")?o:null}n(u,"resolveApiKey");async function P(){if(!a.isTTY||!c.isTTY)throw new Error("OpenPond API key is required in non-interactive mode. Set OPENPOND_API_KEY or run `openpond login` in a terminal.");console.log("Open the OpenPond UI to create an API key:"),console.log(p);let e=l({input:a,output:c});try{let t=(await e.question("Paste your OpenPond API key: ")).trim();if(!t)throw new Error("API key is required");return t.startsWith("opk_")||console.log("warning: API keys usually start with opk_."),t}finally{e.close()}}n(P,"promptForApiKey");async function A(e,t){let r=u(e);if(r)return r;let o=await P();return await s({apiKey:o,baseUrl:t,activeProfile:e.activeProfile}),console.log("Saved account credentials to the encrypted OpenPond credential store."),o}n(A,"ensureApiKey");export{u as a,P as b,A as c};