openpond 0.2.15 → 0.2.17

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 (110) hide show
  1. package/dist/app-server.d.ts +2 -0
  2. package/dist/app-server.js +1 -1
  3. package/dist/chunks/{app-layer-SSLVAUNI.js → app-layer-CFIW5CWC.js} +1 -1
  4. package/dist/chunks/{app-server-runtime-QUC4HPQU.js → app-server-runtime-Q7NJ6PXF.js} +1 -1
  5. package/dist/chunks/{apps-JEKTEGSW.js → apps-67PSSK6Q.js} +1 -1
  6. package/dist/chunks/{chunk-YNXFXNQM.js → chunk-BE35DIOI.js} +1 -1
  7. package/dist/chunks/{chunk-4E5ETWKU.js → chunk-CULWDNK3.js} +334 -332
  8. package/dist/chunks/{chunk-ZYG2PXY2.js → chunk-G54T4IWQ.js} +1 -1
  9. package/dist/chunks/{chunk-7I73OREC.js → chunk-GHKJKXDF.js} +1 -1
  10. package/dist/chunks/{chunk-K4ZKAHLG.js → chunk-MACBJI6D.js} +1 -1
  11. package/dist/chunks/{chunk-UOQHYTCK.js → chunk-N3KS3AJK.js} +1 -1
  12. package/dist/chunks/{chunk-FHBQ6OWG.js → chunk-PRA6LX2G.js} +1 -1
  13. package/dist/chunks/{chunk-VRXXKDF2.js → chunk-Q7QAKAGF.js} +1 -1
  14. package/dist/chunks/chunk-RB7BWSFJ.js +5 -0
  15. package/dist/chunks/{chunk-JTQDNX2J.js → chunk-SKKAWYCQ.js} +1 -1
  16. package/dist/chunks/{chunk-QLZ67Y6C.js → chunk-VL3RGI55.js} +2 -2
  17. package/dist/chunks/{cli-7YSRAC4Y.js → cli-BCBRWI2M.js} +1 -1
  18. package/dist/chunks/{configuration-command-DH4ZZUKL.js → configuration-command-D66B4TXT.js} +1 -1
  19. package/dist/chunks/{core-commands-TUUSA6WB.js → core-commands-D6OHIVUG.js} +1 -1
  20. package/dist/chunks/{desktop-test-S3RME4QT.js → desktop-test-RBRWSLEM.js} +1 -1
  21. package/dist/chunks/{extension-D64BYPFY.js → extension-MP3XCX56.js} +1 -1
  22. package/dist/chunks/{help-AOVE3SSY.js → help-XVBIPQHN.js} +1 -1
  23. package/dist/chunks/{opchat-KC2FL5TT.js → opchat-NYSALH7B.js} +1 -1
  24. package/dist/chunks/{organizations-AAES2P7W.js → organizations-ZCQX3SY3.js} +1 -1
  25. package/dist/chunks/{profile-FRYWK2IE.js → profile-PFR6PWNE.js} +1 -1
  26. package/dist/chunks/{project-agent-WPW6DWK7.js → project-agent-KSMTTZYC.js} +1 -1
  27. package/dist/chunks/{sandbox-command-ZHKJZ3FJ.js → sandbox-command-MVBSIKB6.js} +1 -1
  28. package/dist/chunks/{sandbox-template-SPVQIMG5.js → sandbox-template-2OWCTKBP.js} +1 -1
  29. package/dist/chunks/{src-LYFCDA5G.js → src-7TTHR4DL.js} +1 -1
  30. package/dist/chunks/{src-AADCZ2JW.js → src-ITECV3AD.js} +105 -105
  31. package/dist/chunks/{teams-bot-LD3QORJI.js → teams-bot-IUE3CWSW.js} +1 -1
  32. package/dist/chunks/{workspaces-P2WNCMXC.js → workspaces-WI56RXUN.js} +1 -1
  33. package/dist/cli.js +1 -1
  34. package/dist/web/assets/{App-kwt-UxX_.js → App-DQfdLgyV.js} +3 -3
  35. package/dist/web/assets/{AppDialog-LXQo_7oW.js → AppDialog-BnldMLvF.js} +1 -1
  36. package/dist/web/assets/{AppTerminalPanel-CUqrUrkA.js → AppTerminalPanel-DR5SeX9y.js} +2 -2
  37. package/dist/web/assets/{AppsView-5J2RX301.js → AppsView-Bu_XEgkd.js} +1 -1
  38. package/dist/web/assets/{BrowserSidebar-mZ8RjUOr.js → BrowserSidebar-BdKPWbN8.js} +1 -1
  39. package/dist/web/assets/{CartesianChart-7x3SO8Hj.js → CartesianChart-CSkLcF_5.js} +1 -1
  40. package/dist/web/assets/{CollaborationTabs-ByC9WJqu.js → CollaborationTabs-C9cRq5ob.js} +1 -1
  41. package/dist/web/assets/{CommandMenu-CqDb2Kb2.js → CommandMenu-Deqzk3u9.js} +1 -1
  42. package/dist/web/assets/{CommunityView-BmxYkWqC.js → CommunityView-B5dKYacH.js} +1 -1
  43. package/dist/web/assets/{ComposerCreateImproveStrip-2Tyj9KOQ.js → ComposerCreateImproveStrip-5LPlQFN4.js} +1 -1
  44. package/dist/web/assets/{GetStartedView-1WYkmevY.js → GetStartedView-DmuGykfx.js} +1 -1
  45. package/dist/web/assets/HostedModelLearningReview-BRPSFNza.js +1 -0
  46. package/dist/web/assets/{HostedModelLearningSettings-Brza5hSD.js → HostedModelLearningSettings-BsdX-CkH.js} +1 -1
  47. package/dist/web/assets/{LabModelVersionDetailPage-C4WtQKER.js → LabModelVersionDetailPage-BUO5cpDh.js} +1 -1
  48. package/dist/web/assets/{LabSkillSidebar-D3g6E0Ap.js → LabSkillSidebar-mTpdM-G8.js} +1 -1
  49. package/dist/web/assets/{LabsRoute-BO0yEsCR.js → LabsRoute-BhfxBg5_.js} +4 -4
  50. package/dist/web/assets/{MainChatThread-CKPR_rY0.js → MainChatThread-BAxA18lN.js} +2 -2
  51. package/dist/web/assets/{MainPane-B8mDzSqi.js → MainPane-Dv5USGqR.js} +4 -4
  52. package/dist/web/assets/{MarkdownText-D6_UI4Ly.js → MarkdownText-DWGLUbdE.js} +1 -1
  53. package/dist/web/assets/{Messages-DptbENmQ.js → Messages-CuhCtaya.js} +1 -1
  54. package/dist/web/assets/{NativeSkillSidebar-CF1NTAR6.js → NativeSkillSidebar-B8OMVpPT.js} +1 -1
  55. package/dist/web/assets/{NewExperienceSwitcher-CwlpLsXW.js → NewExperienceSwitcher-kIKV8_Wd.js} +1 -1
  56. package/dist/web/assets/{NewProjectDialog-Ls4K9a5S.js → NewProjectDialog-B-7dHoT6.js} +1 -1
  57. package/dist/web/assets/{OutputsPage-ClNuidPW.js → OutputsPage-C4DRT8pF.js} +1 -1
  58. package/dist/web/assets/{ProjectsPage-Sj83NsdP.js → ProjectsPage-CLjW6Kc3.js} +1 -1
  59. package/dist/web/assets/{RightChatPanelStack-m5-cI0NL.js → RightChatPanelStack-C4-4VLb-.js} +1 -1
  60. package/dist/web/assets/{RightSidebarHomePanel-B--t--OJ.js → RightSidebarHomePanel-CVbfOg2p.js} +1 -1
  61. package/dist/web/assets/{ScheduledWorkPage-JVfMtGMs.js → ScheduledWorkPage-CWzwbOOZ.js} +1 -1
  62. package/dist/web/assets/SettingsView-BIwO8elm.js +9 -0
  63. package/dist/web/assets/{SettingsView-B9Tn0_zX.css → SettingsView-BaWWvIJW.css} +1 -1
  64. package/dist/web/assets/{TeamChatView-D8ilbncz.js → TeamChatView-miR9w_53.js} +1 -1
  65. package/dist/web/assets/{TerminalOverlay-A6nSxm5C.js → TerminalOverlay-BOmx_hJX.js} +1 -1
  66. package/dist/web/assets/{TrainingCreationPanel-CwpnBbuN.js → TrainingCreationPanel-DSRejaYV.js} +1 -1
  67. package/dist/web/assets/{TrainingDraftPanel-B_Gh_0yq.js → TrainingDraftPanel-XBH6Uh0_.js} +1 -1
  68. package/dist/web/assets/{UsageSettingsSection-qTX3k9-f.js → UsageSettingsSection-DROtDdak.js} +1 -1
  69. package/dist/web/assets/{WorkSidebarPanel-B-fDRRRs.js → WorkSidebarPanel-CHwObGs6.js} +1 -1
  70. package/dist/web/assets/{WorkspaceDiffPanel-CfvvifJg.js → WorkspaceDiffPanel-BoB_1R8w.js} +3 -3
  71. package/dist/web/assets/{WorkspaceEnvironmentMenu-BL6WHWLO.js → WorkspaceEnvironmentMenu-Dvqy2NJP.js} +1 -1
  72. package/dist/web/assets/{WorkspaceGitDialogs-pyZQJL_2.js → WorkspaceGitDialogs-BC45mifk.js} +1 -1
  73. package/dist/web/assets/{WorkspaceMonacoEditor-C2cNf0UO.js → WorkspaceMonacoEditor-cDO3Elh0.js} +3 -3
  74. package/dist/web/assets/{arrow-up-right-BQv8RCGD.js → arrow-up-right-Dv3nebbh.js} +1 -1
  75. package/dist/web/assets/{chat-file-links-C3erG0P2.js → chat-file-links-DQYtkwit.js} +1 -1
  76. package/dist/web/assets/chevron-up-BUOpWd2a.js +1 -0
  77. package/dist/web/assets/{clipboard-BSPYX7yq.js → clipboard-CnNPmg50.js} +1 -1
  78. package/dist/web/assets/{cloud-upload-CJVhhG6P.js → cloud-upload-DisZOwXE.js} +1 -1
  79. package/dist/web/assets/{cssMode-RCJXPUO-.js → cssMode-Bd8sFlb5.js} +1 -1
  80. package/dist/web/assets/{folder-open-2a5riVSG.js → folder-open-D0PIN0Cj.js} +1 -1
  81. package/dist/web/assets/{folder-plus-DuVvIFve.js → folder-plus-DTNZNwa9.js} +1 -1
  82. package/dist/web/assets/{git-commit-horizontal-BifoV1dR.js → git-commit-horizontal-C0QdA7uv.js} +1 -1
  83. package/dist/web/assets/{htmlMode-DnEOXzjT.js → htmlMode-Cu-nKV7Z.js} +1 -1
  84. package/dist/web/assets/{index-B5RqBp_p.js → index-De4k_YMo.js} +2 -2
  85. package/dist/web/assets/{info-BWvLCbJ2.js → info-B-n_omgE.js} +1 -1
  86. package/dist/web/assets/{jsonMode-DQfml7E4.js → jsonMode-B377iBCv.js} +1 -1
  87. package/dist/web/assets/{lspLanguageFeatures-WKs-7xHz.js → lspLanguageFeatures-BBHfVtV0.js} +1 -1
  88. package/dist/web/assets/{minimize-2-C-_iqAbt.js → minimize-2-C6JQGKgk.js} +1 -1
  89. package/dist/web/assets/{monaco.contribution-B5y78DUP.js → monaco.contribution-B0l6Oe3a.js} +2 -2
  90. package/dist/web/assets/{monaco.contribution-DCekL-SI.js → monaco.contribution-BDLeUQLG.js} +2 -2
  91. package/dist/web/assets/{monaco.contribution-Qc1u700n.js → monaco.contribution-CCSCAu65.js} +2 -2
  92. package/dist/web/assets/{monaco.contribution-B29c98Aa.js → monaco.contribution-CIq6sYw4.js} +2 -2
  93. package/dist/web/assets/{play-DsP3gpGK.js → play-B5O4Hz_W.js} +1 -1
  94. package/dist/web/assets/{python-CJ1QdM8L.js → python-BQkq0gZA.js} +1 -1
  95. package/dist/web/assets/{refresh-cw-DaASy_i0.js → refresh-cw-D2E-pp4H.js} +1 -1
  96. package/dist/web/assets/{save-BBQ7L8VS.js → save-CPNNuWwp.js} +1 -1
  97. package/dist/web/assets/{square-DTl9YrMp.js → square-DUgXVoF0.js} +1 -1
  98. package/dist/web/assets/{toggleHighContrast-D-DNRZ-D.js → toggleHighContrast-BbQBtO9I.js} +1 -1
  99. package/dist/web/assets/{tsMode-CmWbxnjM.js → tsMode-CsVhouTE.js} +1 -1
  100. package/dist/web/assets/{upload-juEp2zRQ.js → upload-t7xHt3GY.js} +1 -1
  101. package/dist/web/assets/{useLocalAgentSchedules-DF_bIseW.js → useLocalAgentSchedules-D4lJelHt.js} +1 -1
  102. package/dist/web/assets/{wifi-off-DrkIaS1O.js → wifi-off-B_QPKtA-.js} +1 -1
  103. package/dist/web/assets/{workers-LygfviY3.js → workers-p7TrE4Qa.js} +1 -1
  104. package/dist/web/assets/{yaml-BIpimtDQ.js → yaml-C8adeAyH.js} +1 -1
  105. package/dist/web/index.html +1 -1
  106. package/package.json +1 -1
  107. package/dist/chunks/chunk-6C2EXO4H.js +0 -5
  108. package/dist/web/assets/HostedModelLearningReview-DHahsQJH.js +0 -1
  109. package/dist/web/assets/SettingsView-B7FnZ-b0.js +0 -9
  110. package/dist/web/assets/chevron-up-D9MMQKU3.js +0 -1
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{b as Q,c as Z,t as ee,y as oe}from"./chunk-6C2EXO4H.js";import{a as T,b as X,h as K}from"./chunk-YNXFXNQM.js";import{n as te,p as re}from"./chunk-UOQHYTCK.js";import{$a as E,Ra as V,Sa as J,Ua as I,Xa as F,_a as W,b as L,c as B,db as z,fb as q,gb as Y,ja as D,la as H,ma as M,na as $,oa as j,qa as G}from"./chunk-NNLI4OWY.js";import{b as i}from"./chunk-ES2ISFJC.js";import{c as N,d as C,f as k,h as R}from"./chunk-H7IWJN7L.js";import{a as s}from"./chunk-FTQLQJQV.js";import{promises as U}from"node:fs";import Ee from"node:os";import Ae from"node:path";import{createServer as Ie}from"node:http";import{randomBytes as Te}from"node:crypto";var be=i.discriminatedUnion("op",[i.strictObject({op:i.literal("set"),path:i.array(i.string().min(1)).min(1),value:i.unknown()}),i.strictObject({op:i.literal("unset"),path:i.array(i.string().min(1)).min(1)})]),Oe=i.discriminatedUnion("action",[i.strictObject({action:i.literal("patch"),expectedRevision:i.string(),operations:i.array(be).max(100)}),i.strictObject({action:i.literal("replace"),expectedRevision:i.string(),text:i.string().max(1048576)}),i.strictObject({action:i.literal("validate"),text:i.string().max(1048576)}),i.strictObject({action:i.literal("restore"),expectedRevision:i.string(),revision:i.string()}),i.strictObject({action:i.literal("trust"),root:i.string(),accountId:i.string(),trusted:i.boolean()}),i.strictObject({action:i.literal("client-state"),owner:i.string(),patch:z,importOnly:i.boolean().optional()})]);function ne(e){let t=null;async function r(l,n){let g=R(e).config,w=null,p=null,d=null;try{w=await B(g),d=await E(e,{projectRoot:l,accountId:n}),l||(t=d)}catch(v){p=C(v,g)}let y=d??(l?null:t);return{path:g,text:w,rawRevision:L(w),issue:p,effective:y,usingLastValid:!d&&!!y,applies:"next_turn",recoverableRevisions:await H(e),clientState:p?null:await q(e)}}s(r,"status");async function o(l){let n=Oe.parse(l);return n.action==="validate"?{valid:!0,document:D(n.text,R(e).config)}:(n.action==="patch"&&await G(e,n.expectedRevision,n.operations),n.action==="replace"&&await M(e,n.expectedRevision,n.text),n.action==="restore"&&await $(e,n.revision,n.expectedRevision),n.action==="trust"&&await W(e,n.root,n.accountId,n.trusted),n.action==="client-state"?Y(e,n.owner,n.patch,n.importOnly):r())}return s(o,"mutate"),{status:r,mutate:o,schema:j}}s(ne,"createConfigurationPayloads");import{Buffer as ie}from"node:buffer";var A={"Access-Control-Allow-Headers":"authorization, content-type, x-openpond-team-id","Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS"},Se=25*1024*1024,x=class extends Error{constructor(r,o,l){super(l);this.status=r;this.code=o;this.name="HttpBodyError"}status;code;static{s(this,"HttpBodyError")}};function ae(e,t,r={}){for(let[l,n]of Object.entries(A))t.setHeader(l,n);let o=ce(e.headers.origin);return o?(t.setHeader("Vary",xe(t.getHeader("Vary"))),Re(o,r)?(t.setHeader("Access-Control-Allow-Origin",o),{allowed:!0,origin:o}):{allowed:!1,origin:o}):{allowed:!0,origin:null}}s(ae,"applyCorsHeaders");function Re(e,t={}){if(e==="null")return!0;let r=se(e);return r?Ce(r)?!0:new Set((t.allowedOrigins??[]).map(l=>l?se(l):null).filter(l=>!!l)).has(r):!1}s(Re,"isAllowedCorsOrigin");function h(e,t,r){e.writeHead(t,{"Content-Type":"application/json",...A}),e.end(JSON.stringify(r))}s(h,"sendJson");function Je(e,t,r){e.writeHead(t,{"Content-Type":"text/plain; charset=utf-8",...A}),e.end(r)}s(Je,"sendText");function Fe(e,t,r,o){e.writeHead(t,{"Content-Type":o,"Content-Length":String(r.byteLength),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff",...A}),e.end(r)}s(Fe,"sendBinary");async function _(e,t={}){let r=t.maxBytes??Se,o=ce(e.headers["content-type"]),l=[],n=0;for await(let w of e){let p=ie.from(w);if(n+=p.byteLength,n>r)throw new x(413,"request_body_too_large",`JSON request body exceeds ${r} bytes.`);l.push(p)}let g=ie.concat(l).toString("utf8").trim();if(!g)return{};if(!Pe(o))throw new x(415,"unsupported_media_type","JSON request body requires Content-Type: application/json.");try{return JSON.parse(g)}catch{throw new x(400,"invalid_json","Request body is not valid JSON.")}}s(_,"readJson");function le(e,t,r){let o=e.headers.authorization;return(typeof o=="string"&&o.startsWith("Bearer ")?o.slice(7):null)===r}s(le,"hasAuth");function ce(e){return Array.isArray(e)?e[0]??null:e??null}s(ce,"headerValue");function Pe(e){if(!e)return!1;let t=e.split(";")[0]?.trim().toLowerCase();return t==="application/json"||!!t?.endsWith("+json")}s(Pe,"isJsonContentType");function se(e){try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.origin}catch{return null}}s(se,"normalizeOrigin");function Ce(e){let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="::1"||t.hostname==="[::1]"}s(Ce,"isLoopbackOrigin");function xe(e){let r=(Array.isArray(e)?e.join(", "):e?String(e):"").split(",").map(o=>o.trim()).filter(Boolean);return r.some(o=>o.toLowerCase()==="origin")||r.push("Origin"),r.join(", ")}s(xe,"appendVaryOrigin");function pe(e){return`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>OpenPond recovery</title>
2
+ import{b as Q,c as Z,t as ee,y as oe}from"./chunk-RB7BWSFJ.js";import{a as T,b as X,h as K}from"./chunk-BE35DIOI.js";import{n as te,p as re}from"./chunk-N3KS3AJK.js";import{$a as E,Ra as V,Sa as J,Ua as I,Xa as F,_a as W,b as L,c as B,db as z,fb as q,gb as Y,ja as D,la as H,ma as M,na as $,oa as j,qa as G}from"./chunk-NNLI4OWY.js";import{b as i}from"./chunk-ES2ISFJC.js";import{c as N,d as C,f as k,h as R}from"./chunk-H7IWJN7L.js";import{a as s}from"./chunk-FTQLQJQV.js";import{promises as U}from"node:fs";import Ee from"node:os";import Ae from"node:path";import{createServer as Ie}from"node:http";import{randomBytes as Te}from"node:crypto";var be=i.discriminatedUnion("op",[i.strictObject({op:i.literal("set"),path:i.array(i.string().min(1)).min(1),value:i.unknown()}),i.strictObject({op:i.literal("unset"),path:i.array(i.string().min(1)).min(1)})]),Oe=i.discriminatedUnion("action",[i.strictObject({action:i.literal("patch"),expectedRevision:i.string(),operations:i.array(be).max(100)}),i.strictObject({action:i.literal("replace"),expectedRevision:i.string(),text:i.string().max(1048576)}),i.strictObject({action:i.literal("validate"),text:i.string().max(1048576)}),i.strictObject({action:i.literal("restore"),expectedRevision:i.string(),revision:i.string()}),i.strictObject({action:i.literal("trust"),root:i.string(),accountId:i.string(),trusted:i.boolean()}),i.strictObject({action:i.literal("client-state"),owner:i.string(),patch:z,importOnly:i.boolean().optional()})]);function ne(e){let t=null;async function r(l,n){let g=R(e).config,w=null,p=null,d=null;try{w=await B(g),d=await E(e,{projectRoot:l,accountId:n}),l||(t=d)}catch(v){p=C(v,g)}let y=d??(l?null:t);return{path:g,text:w,rawRevision:L(w),issue:p,effective:y,usingLastValid:!d&&!!y,applies:"next_turn",recoverableRevisions:await H(e),clientState:p?null:await q(e)}}s(r,"status");async function o(l){let n=Oe.parse(l);return n.action==="validate"?{valid:!0,document:D(n.text,R(e).config)}:(n.action==="patch"&&await G(e,n.expectedRevision,n.operations),n.action==="replace"&&await M(e,n.expectedRevision,n.text),n.action==="restore"&&await $(e,n.revision,n.expectedRevision),n.action==="trust"&&await W(e,n.root,n.accountId,n.trusted),n.action==="client-state"?Y(e,n.owner,n.patch,n.importOnly):r())}return s(o,"mutate"),{status:r,mutate:o,schema:j}}s(ne,"createConfigurationPayloads");import{Buffer as ie}from"node:buffer";var A={"Access-Control-Allow-Headers":"authorization, content-type, x-openpond-team-id","Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS"},Se=25*1024*1024,x=class extends Error{constructor(r,o,l){super(l);this.status=r;this.code=o;this.name="HttpBodyError"}status;code;static{s(this,"HttpBodyError")}};function ae(e,t,r={}){for(let[l,n]of Object.entries(A))t.setHeader(l,n);let o=ce(e.headers.origin);return o?(t.setHeader("Vary",xe(t.getHeader("Vary"))),Re(o,r)?(t.setHeader("Access-Control-Allow-Origin",o),{allowed:!0,origin:o}):{allowed:!1,origin:o}):{allowed:!0,origin:null}}s(ae,"applyCorsHeaders");function Re(e,t={}){if(e==="null")return!0;let r=se(e);return r?Ce(r)?!0:new Set((t.allowedOrigins??[]).map(l=>l?se(l):null).filter(l=>!!l)).has(r):!1}s(Re,"isAllowedCorsOrigin");function h(e,t,r){e.writeHead(t,{"Content-Type":"application/json",...A}),e.end(JSON.stringify(r))}s(h,"sendJson");function Je(e,t,r){e.writeHead(t,{"Content-Type":"text/plain; charset=utf-8",...A}),e.end(r)}s(Je,"sendText");function Fe(e,t,r,o){e.writeHead(t,{"Content-Type":o,"Content-Length":String(r.byteLength),"Cache-Control":"no-store","X-Content-Type-Options":"nosniff",...A}),e.end(r)}s(Fe,"sendBinary");async function _(e,t={}){let r=t.maxBytes??Se,o=ce(e.headers["content-type"]),l=[],n=0;for await(let w of e){let p=ie.from(w);if(n+=p.byteLength,n>r)throw new x(413,"request_body_too_large",`JSON request body exceeds ${r} bytes.`);l.push(p)}let g=ie.concat(l).toString("utf8").trim();if(!g)return{};if(!Pe(o))throw new x(415,"unsupported_media_type","JSON request body requires Content-Type: application/json.");try{return JSON.parse(g)}catch{throw new x(400,"invalid_json","Request body is not valid JSON.")}}s(_,"readJson");function le(e,t,r){let o=e.headers.authorization;return(typeof o=="string"&&o.startsWith("Bearer ")?o.slice(7):null)===r}s(le,"hasAuth");function ce(e){return Array.isArray(e)?e[0]??null:e??null}s(ce,"headerValue");function Pe(e){if(!e)return!1;let t=e.split(";")[0]?.trim().toLowerCase();return t==="application/json"||!!t?.endsWith("+json")}s(Pe,"isJsonContentType");function se(e){try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.origin}catch{return null}}s(se,"normalizeOrigin");function Ce(e){let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="::1"||t.hostname==="[::1]"}s(Ce,"isLoopbackOrigin");function xe(e){let r=(Array.isArray(e)?e.join(", "):e?String(e):"").split(",").map(o=>o.trim()).filter(Boolean);return r.some(o=>o.toLowerCase()==="origin")||r.push("Origin"),r.join(", ")}s(xe,"appendVaryOrigin");function pe(e){return`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>OpenPond recovery</title>
3
3
  <style nonce="${e}">body{font:16px system-ui;background:#171819;color:#eee;max-width:850px;margin:6vh auto;padding:24px}textarea{box-sizing:border-box;width:100%;min-height:280px;background:#222;color:#eee;padding:14px;border:1px solid #777;border-radius:8px;font:14px monospace}button,input,select{font:inherit;margin:6px;padding:8px}pre{white-space:pre-wrap}code{overflow-wrap:anywhere}button{cursor:pointer}p{line-height:1.5}</style>
4
4
  <h1>OpenPond needs a storage repair</h1><p id="issue" role="alert">Loading recovery details\u2026</p><p><code id="file"></code></p>
5
5
  <p id="action"></p><p>Migration backups and the source installation remain available. Execution services are stopped while recovery is open.</p>
@@ -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-YNXFXNQM.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-BE35DIOI.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
 
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{A as F,a as fe,b as L,c as R,d as me,e as D,f as G,g as j,h as z,j as ye,l as T,m as we,n as S,o as he,y as B}from"./chunk-G2VYRU27.js";import{b as H,c as be,d as ve,f as w,h as P,i as Re}from"./chunk-ZVOO7FKM.js";import{$ as ge,M as ce,N as le,R as de,V as pe,Z as y,_ as ue,aa as C,h as $,i as ne,l as oe,n as re,o as ie,p as ae,q as se}from"./chunk-SS3EG6S2.js";import{a as Z,b as ee,c as te}from"./chunk-QLZ67Y6C.js";import{a as M,f as v,k as X}from"./chunk-3M53YXEI.js";import{a as g}from"./chunk-FTQLQJQV.js";import{promises as V,existsSync as W}from"node:fs";import U from"node:path";import{stdin as $e}from"node:process";async function Ge(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=await ie(n,i,a.id);console.log(JSON.stringify(s,null,2))}g(Ge,"runTemplateStatus");async function je(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=await ae(n,i,a.id);console.log(JSON.stringify(s,null,2))}g(je,"runTemplateBranches");async function ze(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=typeof e.env=="string"?e.env:typeof e.environment=="string"?e.environment:void 0,f=X(s),c=await se(n,i,a.id,{environment:f});console.log(JSON.stringify(c,null,2))}g(ze,"runTemplateUpdate");async function He(e){let o=await y(),t=w(o),r=typeof e.apiKey=="string"?e.apiKey:typeof e.key=="string"?e.key:null,n=r?r.trim():await L();if(!n)throw new Error("API key is required");n.startsWith("opk_")||console.log("warning: API keys usually start with opk_."),await C({handle:o.activeProfile?.handle||"default",apiKey:n,baseUrl:t,apiBaseUrl:o.apiBaseUrl,chatApiBaseUrl:o.chatApiBaseUrl,setActive:!0}),console.log("Saved account credentials to the encrypted OpenPond credential store.")}g(He,"runLogin");async function Fe(e,o){let t=o[0]||"list";if(t==="list"){let r=await ue();console.log(JSON.stringify({profiles:r},null,2));return}if(t==="use"){let r=o[1];if(!r)throw new Error("usage: profiles use <name> [--base-url <url>]");let n=await ge(r,{baseUrl:H(e)});console.log(JSON.stringify({profile:n},null,2));return}if(t==="save"){let r=o[1];if(!r)throw new Error("usage: profiles save <name> --api-key <key> [--base-url <url>] [--api-base-url <url>] [--chat-api-base-url <url>]");let n=typeof e.apiKey=="string"?e.apiKey:typeof e.key=="string"?e.key:null,i=n?n.trim():await L(),a=typeof e.environment=="string"?e.environment:typeof e.env=="string"?e.env:void 0,s=await C({handle:r,apiKey:i,baseUrl:H(e),apiBaseUrl:be(e),chatApiBaseUrl:ve(e),environment:a,setActive:!0});console.log(JSON.stringify({profile:s},null,2));return}throw new Error("usage: profiles <list|use|save> [args]")}g(Fe,"runProfiles");async function Ve(){let e=await y(),o=w(e),t=P(e),r=await R(e,o),n=await ce(t,r);console.log(JSON.stringify(n,null,2))}g(Ve,"runAccount");async function We(e){let o=await y(),t=P(o),r=fe(o),n=await le(t,r);console.log(JSON.stringify(n,null,2))}g(We,"runHealth");async function qe(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a}=await T(n,i,o),s=typeof e.branch=="string"?String(e.branch):void 0,f=await $(n,i,a.id,{branch:s});if(!f?.id){console.log("no deployments found");return}let c=await ne(n,i,f.id),d=(c&&Array.isArray(c.toolsJson)?c.toolsJson:null)||(c&&typeof c.metadataJson=="object"&&c.metadataJson?c.metadataJson.tools:null),u=Array.isArray(d)?d:[];if(u.length===0){console.log("no tools found");return}for(let l of u){let m=l,h=m.profile||m.function,I=m.name||h?.name||"unknown",p=m.description||h?.description||"";console.log(p?`${I} - ${p}`:I)}}g(qe,"runToolList");async function Ye(e,o,t){let r=await y(),n=w(r),i=P(r),a=await R(r,n),{app:s}=await T(i,a,o),f=typeof e.branch=="string"?String(e.branch):void 0,c=await $(i,a,s.id,{branch:f});if(!c?.id)throw new Error("no deployments found");let d;if(typeof e.body=="string")try{d=JSON.parse(e.body)}catch{throw new Error("tool body must be valid JSON")}let u=typeof e.method=="string"?String(e.method).toUpperCase():"POST",l=await pe(n,a,{appId:s.id,deploymentId:c.id,toolName:t,method:u,body:d,headers:a?{"openpond-api-key":a}:void 0});if(!l.ok)throw new Error(l.error||`tool failed (${l.status})`);let m=l.data??{ok:!0};console.log(JSON.stringify(m,null,2))}g(Ye,"runToolRun");async function Qe(e,o,t){let r=await y(),n=w(r),i=P(r),a=await R(r,n),{app:s}=await T(i,a,o),f=typeof e.branch=="string"?String(e.branch):void 0,c=typeof e.deploymentId=="string"?String(e.deploymentId):void 0,d=c?{id:c}:await $(i,a,s.id,{branch:f});if(!d?.id)throw new Error("no deployments found");let u=typeof e.body=="string"?M(String(e.body),"body"):{};if(!u||typeof u!="object"||Array.isArray(u))throw new Error("body must be a JSON object");let l=typeof e.method=="string"?String(e.method).toUpperCase():"POST",m={...u,appId:s.id,deploymentId:d.id,toolName:t,method:l},h=await de(i,a,m);console.log(JSON.stringify(h,null,2))}g(Qe,"runBacktestRun");async function Xe(e,o){let t=await y(),r=w(t),n=P(t),i=await R(t,r),{app:a,handle:s,repo:f}=await T(n,i,o),c=typeof e.branch=="string"?String(e.branch):void 0,d=typeof e.deploymentId=="string"?String(e.deploymentId):void 0,u=d?{id:d}:await $(n,i,a.id,{branch:c});if(!u?.id){console.log("no deployments found");return}await we({baseUrl:n,apiKey:i,deploymentId:u.id,prefix:`[${s}/${f}] `,intervalMs:e.interval?Number(e.interval):void 0,timeoutMs:e.timeout?Number(e.timeout):void 0})}g(Xe,"runDeployWatch");async function Ze(e,o){let r=((typeof e.name=="string"?e.name:null)||o.join(" ")).trim();if(!r)throw new Error("usage: repo create --name <name> [--team-id <id>] [--path <dir>] [--template <owner/repo|url>] [--template-branch <branch>] [--empty|--opentool] [--sandbox] [--token] [--auto-schedule-migration <true|false>]");let n=await y(),i=w(n),a=await R(n,i),s=P(n),f=typeof e.teamId=="string"&&e.teamId.trim()?e.teamId.trim():void 0,c=typeof e.template=="string"?e.template.trim():"";if(c&&(e.empty==="true"||e.opentool==="true"))throw new Error("choose one: --template or --empty/--opentool");if(e.empty==="true"&&e.opentool==="true")throw new Error("choose one: --empty or --opentool");let d=typeof e.description=="string"?e.description.trim():void 0,u=typeof e.templateBranch=="string"&&e.templateBranch.trim().length>0?e.templateBranch.trim():void 0,l=typeof e.env=="string"?M(e.env,"env"):void 0;if(l){if(typeof l!="object"||Array.isArray(l))throw new Error("env must be a JSON object");for(let[b,A]of Object.entries(l))if(typeof A!="string")throw new Error(`env value for ${b} must be a string`)}if(c){e.deployOnPush!==void 0&&console.warn("deploy-on-push is not used for template create (auto deploys)");let b=Re(c,i),k=(await re(s,a,[{name:r,...d?{description:d}:{},templateRepoUrl:b,...u?{templateBranch:u}:{},...l?{envVars:l}:{}}],f)).items?.[0];if(!k||k.status!=="ok"||!k.appId)throw new Error(k?.error||"Template create failed");console.log(`app_id: ${k.appId}`),k.deploymentId&&console.log(`deployment_id: ${k.deploymentId}`),k.conversationId&&console.log(`conversation_id: ${k.conversationId}`);return}let m=process.cwd(),h=typeof e.path=="string"?e.path:typeof e.dir=="string"?e.dir:null,I=h&&h.trim().length>0?h.trim():$e.isTTY?await he(m):m,p=U.resolve(I);if(W(p)){if(!(await V.stat(p)).isDirectory())throw new Error(`path is not a directory: ${p}`)}else await V.mkdir(p,{recursive:!0});let Pe=(await V.readdir(p)).filter(b=>b!==".git").length===0,x=v(e.yes)||v(e.force);if(!Pe&&!x&&!await S(`Directory is not empty (${p}). Continue?`,!1)){console.log("aborted");return}let ke=U.join(p,".git");if(!W(ke)){if(!(x?!0:await S("Initialize git repository here?",!0))){console.log("aborted");return}let A=await B("git",["init"],{cwd:p});if(A.code!==0)throw new Error(`git init failed: ${A.stderr.trim()||A.stdout.trim()||"unknown error"}`)}let K=await F(p,"origin");if(K&&!x&&!await S(`Remote "origin" already set (${K}). Replace it?`,!1)){console.log("aborted");return}let q=e.opentool==="true"?"opentool":"empty",Te=v(e.sandbox),Be=v(e.deployOnPush),N=e.autoScheduleMigration,Y=typeof N=="string"||typeof N=="boolean",Ee=Y?v(N):void 0,E=await oe(s,a,{name:r,...f?{teamId:f}:{},...d?{description:d}:{},...q?{repoInit:q}:{},...Te?{sandbox:!0}:{},...l?{envVars:l}:{},...Be?{deployOnPush:!0}:{},...Y?{autoScheduleMigration:Ee}:{}}),O=me(E);z(O);let J=v(e.token)||v(e.setRemoteToken),Oe=D(O,a),Q=J?Oe:O,_=await B("git",K?["remote","set-url","origin",Q]:["remote","add","origin",Q],{cwd:p});if(_.code!==0)throw new Error(`git remote failed: ${j(_.stderr.trim()||_.stdout.trim()||"unknown error")}`);let Ae=J?G(O):O;console.log(`app_id: ${E.appId}`),E.gitOwner&&E.gitRepo&&console.log(`repo: ${E.gitOwner}/${E.gitRepo}`),console.log(`remote: ${Ae}`),console.log('next: git add . && git commit -m "init"');let Ie=E.defaultBranch||"master";console.log(`next: openpond repo push --path ${p} --branch ${Ie}`),J||console.log(`token-remote (non-interactive): git -C ${p} remote set-url origin ${G(O)}`);try{await ye({apiBase:s,apiKey:a,forceRefresh:!0})}catch(b){console.warn("cache refresh failed",b)}}g(Ze,"runRepoCreate");async function Se(e){let o=await B("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e});if(o.code!==0)return null;let t=o.stdout.trim();return t.length>0?t:null}g(Se,"resolveGitBranch");async function et(e){let o=await y(),t=w(o),r=await R(o,t),n=typeof e.path=="string"?e.path:typeof e.dir=="string"?e.dir:null,i=U.resolve(n&&n.trim().length>0?n.trim():"."),a=U.join(i,".git");if(!W(a))throw new Error(`git repo not found at ${i} (missing .git)`);let s=await F(i,"origin");if(!s)throw new Error("origin remote not set; run `openpond repo create` first");z(s);let c=(typeof e.branch=="string"?e.branch.trim():"")||await Se(i);if(!c)throw new Error("unable to resolve git branch; pass --branch");let d;try{d=D(s,r)}catch{throw new Error("origin remote must be https for tokenized pushes")}let u=v(e.keepTokenRemote)||v(e.token)||v(e.setRemoteToken),l=s.includes("x-access-token:"),m=!u&&!l?s:null,h=process.env.GIT_TERMINAL_PROMPT;process.env.GIT_TERMINAL_PROMPT="0";try{if(!l){let p=await B("git",["remote","set-url","origin",d],{cwd:i});if(p.code!==0)throw new Error(`git remote set-url failed: ${j(p.stderr.trim()||p.stdout.trim()||"unknown error")}`)}if((await B("git",["push","-u","origin",c],{cwd:i,inherit:!0})).code!==0)throw new Error("git push failed")}finally{m&&await B("git",["remote","set-url","origin",m],{cwd:i}).catch(()=>null),h===void 0?delete process.env.GIT_TERMINAL_PROMPT:process.env.GIT_TERMINAL_PROMPT=h}}g(et,"runRepoPush");async function tt(e){if(e.length===0)throw new Error("usage: opentool <init|validate|build> [args]");let o=process.platform==="win32"?"npx.cmd":"npx";if((await B(o,["opentool",...e],{inherit:!0})).code!==0)throw new Error("opentool command failed")}g(tt,"runOpentool");async function nt(){let e="openpond",o=Z(),t=await te(e),r=`npm i -g ${e}@${t}`,n=ee(o,t);if(n===0){console.log(`${e} is up to date (${o})`);return}if(n===-1){console.log(`Update available: ${o} -> ${t}`),console.log(`Run: ${r}`);return}if(n===1){console.log(`Installed version (${o}) is newer than npm latest (${t}).`);return}if(o===t){console.log(`${e} is up to date (${o})`);return}console.log(`Installed: ${o}`),console.log(`Latest: ${t}`),console.log(`Run: ${r}`)}g(nt,"runCheckUpdate");export{Ge as a,je as b,ze as c,He as d,Fe as e,Ve as f,We as g,qe as h,Ye as i,Qe as j,Xe as k,Ze as l,Se as m,et as n,tt as o,nt as p};
2
+ import{A as F,a as fe,b as L,c as R,d as me,e as D,f as G,g as j,h as z,j as ye,l as T,m as we,n as S,o as he,y as B}from"./chunk-G2VYRU27.js";import{b as H,c as be,d as ve,f as w,h as P,i as Re}from"./chunk-ZVOO7FKM.js";import{$ as ge,M as ce,N as le,R as de,V as pe,Z as y,_ as ue,aa as C,h as $,i as ne,l as oe,n as re,o as ie,p as ae,q as se}from"./chunk-SS3EG6S2.js";import{a as Z,b as ee,c as te}from"./chunk-VL3RGI55.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{Y as ge,a as ue,b as de,d as pe,e as K,f as N,g as fe,h as me,i as he,j as ye}from"./chunk-FHBQ6OWG.js";import{d as R,e as U}from"./chunk-J2S7BOZU.js";import{K as ne,q as ce}from"./chunk-NNLI4OWY.js";import{a}from"./chunk-FTQLQJQV.js";import{randomUUID as He}from"node:crypto";var _e=new URL(U).hostname,Se=new URL(R).hostname,Ce=`${U}/opchat/v1`;function l(e){if(!e)return null;let n=e.trim();return n?n.replace(/\/+$/,""):null}a(l,"normalizeBaseUrl");function V(e){let n=l(e);if(!n)return null;try{let o=new URL(n).hostname.toLowerCase();if(o===_e)return U;if(o===Se||o==="openpond.live"||o==="www.openpond.live")return U;if(o.startsWith("api."))return n}catch{return null}return null}a(V,"mapUiBaseToApiBase");function G(e,n){let t=l(process.env.OPENPOND_API_URL);if(t)return t;let o=l(e?.apiBaseUrl);if(o)return o;let r=l(n.apiBaseUrl);if(r)return r;let s=V(process.env.OPENPOND_BASE_URL);return s||(V(e?.baseUrl||n.baseUrl)??U)}a(G,"resolvePublicApiBaseUrl");function J(e,n,t){return Ie(e,n,t)}a(J,"resolveHostedChatApiBaseUrl");function Ie(e,n,t){let o=typeof process<"u"?process.env:{};return W(o.OPENPOND_OPCHAT_API_URL)??W(e?.chatApiBaseUrl??n.chatApiBaseUrl)??W(o.OPENPOND_CHAT_API_URL)??Re(t)}a(Ie,"resolveOpChatApiBaseUrl");function W(e){let n=l(e);if(!n)return null;try{let t=new URL(n),o=t.pathname.split("/").filter(Boolean),r=o.findIndex(i=>i.toLowerCase()==="opchat");return r>=0?(t.pathname=`/${[...o.slice(0,r+1),"v1"].join("/")}`,t.search="",t.hash="",l(t.toString())??null):o.findIndex(i=>i.toLowerCase()==="v1")>=0?(t.pathname="/opchat/v1",t.search="",t.hash="",l(t.toString())??null):(t.pathname=`${t.pathname.replace(/\/+$/,"")}/opchat/v1`.replace(/\/{2,}/g,"/"),t.search="",t.hash="",l(t.toString())??null)}catch{return null}}a(W,"normalizeOpChatApiBaseUrl");function Re(e){return W(e)??Ce}a(Re,"opChatBaseFromPublicApiBase");function T(e){return e?.trim()?e.trim():"production"}a(T,"deriveEnvironment");function Y(e,n=process.env){let t=[e?.apiKey,e?.session?.token,e?.token,n.OPENPOND_API_KEY];for(let o of t){let r=typeof o=="string"?o.trim():"";if(r)return r}return null}a(Y,"accountToken");function P(e,n){return!!(e&&n&&e.toLowerCase()===n.toLowerCase())}a(P,"handleEquals");function v(e,n){return l(e)===l(n)}a(v,"baseUrlEquals");function z(e,n){return`${e?.trim().toLowerCase()||""}|${l(n)??"default"}`}a(z,"profileKey");function Q(e){return l(e?.baseUrl)}a(Q,"selectorBaseUrl");function F(e){let n=l(e.baseUrl);return n?{handle:e.handle,baseUrl:n}:{handle:e.handle}}a(F,"selectorFromAccount");function g(e){let n=typeof e?.handle=="string"?e.handle.trim():"";if(!n)return null;let t=l(e?.baseUrl);return t?{handle:n,baseUrl:t}:{handle:n}}a(g,"normalizeActiveProfile");function k(e,n){if(!P(e.handle,n.handle))return!1;let t=Q(n);return t?v(e.baseUrl,t):!l(e.baseUrl)}a(k,"accountMatchesSelector");function te(e,n){if(!P(e.handle,n.handle))return!1;let t=Q(n);return t?v(e.baseUrl,t):!l(e.baseUrl)}a(te,"profileMatchesSelector");function Ae(e,n,t){let o=Array.isArray(e.accounts)?e.accounts:[],r=n||process.env.OPENPOND_ACCOUNT?g({handle:n||process.env.OPENPOND_ACCOUNT||"",baseUrl:t??process.env.OPENPOND_BASE_URL??null}):g(e.activeProfile);if(r){let s=o.find(c=>k(c,r));if(s)return s;let i=o.filter(c=>P(c.handle,r.handle));return i.length===1?i[0]??null:null}return o[0]?o[0]:null}a(Ae,"findActiveAccount");function Pe(e){let n=Array.isArray(e.accounts)?e.accounts:[],t=g(e.activeProfile)??(n[0]?F(n[0]):null);return oe(n.map(o=>({handle:o.handle,baseUrl:l(o.baseUrl),apiBaseUrl:l(o.apiBaseUrl),chatApiBaseUrl:l(o.chatApiBaseUrl),environment:T(o.environment),isActive:t?k(o,t):!1,hasApiKey:!!o.apiKey?.trim(),hasSessionToken:!!(o.session?.token?.trim()||o.token?.trim()),sessionAppId:o.session?.appId??null,sessionConversationId:o.session?.conversationId??null})))}a(Pe,"fallbackProfilesFromConfig");function oe(e){let n=new Map;for(let t of e){let o=l(t.baseUrl),r=`${t.handle.toLowerCase()}|${o??"default"}`,s={...t,baseUrl:o,apiBaseUrl:l(t.apiBaseUrl),chatApiBaseUrl:l(t.chatApiBaseUrl),environment:T(t.environment),isActive:t.isActive},i=n.get(r);(!i||s.isActive&&!i.isActive||s.hasApiKey&&!i.hasApiKey)&&n.set(r,s)}return Array.from(n.values())}a(oe,"normalizeProfiles");function we(e){return e.hasApiKey||e.hasSessionToken?"signed_in":"signed_out"}a(we,"profileAuthHealth");function Ne(e,n){return e?{reachable:e.reachable,authenticated:e.authenticated,apiBase:e.apiBase||n,latencyMs:e.latencyMs,status:e.status,service:e.service,checkedAt:e.checkedAt,error:e.error??null}:null}a(Ne,"normalizeHealth");function Oe(e){let n=e?.account;return n?{id:n.id??null,email:n.email??null,name:n.name??null,handle:n.handle??null,image:n.image??null,timezone:n.timezone??null,isAdmin:n.isAdmin??null,isVerified:n.isVerified??null,dailyAgentAppId:n.dailyAgentAppId??null,dailyAgentDeploymentId:n.dailyAgentDeploymentId??null,credits:n.credits??null}:null}a(Oe,"normalizeProfile");function Te(e){return(e??[]).map(n=>({...n,id:n.id||n.userProductId||n.openPondProductId||n.name,name:n.name,type:n.type,status:n.status,isActive:n.isActive??null,price:n.price??null,currency:n.currency??null,credits:n.credits??null}))}a(Te,"normalizeProducts");function Le(e){return e.handle.trim().toLowerCase()==="default"&&!l(e.baseUrl)&&!e.hasApiKey&&!e.hasSessionToken}a(Le,"isEmptyDefaultProfile");function X(e){let{config:n,profiles:t,account:o,token:r,apiBaseUrl:s,accountResponse:i,accountProfiles:c,health:y,authFailed:A,error:f}=e,w=J(o,n,s),m=Oe(i??null),S=g(n.activeProfile),E=(o?F(o):null)??S,O=m?.handle||o?.handle||E?.handle||null,C=(E?t.find(p=>te(p,E)):null)??t.find(p=>p.isActive)??null,h=A?"auth_error":r?"signed_in":"signed_out",u=m?.name||m?.handle||m?.email||O||"Signed out",I=l(C?.baseUrl||o?.baseUrl||R),b=T(C?.environment||o?.environment),x=g(E)??(O?g({handle:O,baseUrl:C?.baseUrl??o?.baseUrl}):null),$=(t.length>0?t:O?[{handle:O,baseUrl:Q(x)??l(o?.baseUrl),apiBaseUrl:s,chatApiBaseUrl:w,environment:b,isActive:!0,hasApiKey:!!r,hasSessionToken:!1,sessionAppId:null,sessionConversationId:null}]:[]).filter(p=>!Le(p));return{state:h,activeProfile:x,label:u,email:m?.email??null,avatarUrl:m?.image??null,environment:b,baseUrl:I,apiBaseUrl:s,chatApiBaseUrl:w,creditsLabel:m?.credits??null,profile:m,products:Te(i?.products),apiHealth:Ne(y??null,s),accounts:$.map(p=>{let H=l(p.baseUrl),le=c?.[z(p.handle,H)]??null,M=Oe(le?.response??null);return{handle:p.handle,baseUrl:H,apiBaseUrl:l(p.apiBaseUrl),chatApiBaseUrl:l(p.chatApiBaseUrl),environment:T(p.environment),isActive:x?te(p,x):!1,authHealth:le?.authFailed?"auth_error":we(p),displayLabel:M?.name||M?.handle||M?.email||p.handle,email:M?.email??null,avatarUrl:M?.image??null}}),error:f??y?.error??null}}a(X,"toAccountState");async function De(e){try{return oe(await me())}catch{return Pe(e)}}a(De,"loadProfiles");async function d(e,n){let t=await fe(),o=await De(t),r=Ae(t,e,n),s=Y(r),i=G(r,t),c=J(r,t,i);return{config:t,profiles:o,account:r,token:s,apiBaseUrl:i,chatApiBaseUrl:c,accountState:X({config:t,profiles:o,account:r,token:s,apiBaseUrl:i})}}a(d,"loadOpenPondAccountContext");async function $e(e){let n=l(e.baseUrl);return await he(e.handle,{baseUrl:n}),d(e.handle,n)}a($e,"switchOpenPondAccount");function L(e){return e instanceof Error?e.message:String(e)}a(L,"errorMessage");var Me=15e3;function ze(e){return e===ne?"OpenPond Chat":e==="deepseek-v4-flash"?"DeepSeek V4 Flash":e.replace(/[-_/]+/g," ")}a(ze,"displayNameForHostedModel");function Fe(e){let n=typeof e.id=="string"?e.id:null;return n?{id:n,displayName:ze(n),ownedBy:typeof e.owned_by=="string"?e.owned_by:null,streaming:!0,raw:e}:null}a(Fe,"normalizeHostedModel");async function je(){let e=await d();if(!e.token)return{models:[],error:"No OpenPond API key or session token is configured."};try{return{models:(await We({apiBaseUrl:e.chatApiBaseUrl,token:e.token})).data.map(o=>Fe(o)).filter(o=>!!o),error:null}}catch(n){return{models:[],error:L(n)}}}a(je,"loadOpenPondHostedModels");async function qe(){let e=await d();if(!e.token)return{catalog:null,error:"No OpenPond API key or session token is configured."};let n=new AbortController,t=setTimeout(()=>{n.abort(new Error("OpenPond provider catalog request timed out."))},Me);try{return{catalog:await Ue({apiBaseUrl:e.chatApiBaseUrl,token:e.token,signal:n.signal}),error:null}}catch(o){return{catalog:null,error:L(o)}}finally{clearTimeout(t)}}a(qe,"loadOpenPondProviderCatalog");async function*Ke(e){let n=await d();if(!n.token)throw new Error("OpenPond is signed out. Add an account in Settings before using OpenPond Chat.");yield*Ve({apiBaseUrl:n.chatApiBaseUrl,token:n.token,model:e.model||ne,messages:e.messages,tools:e.tools,toolChoice:e.toolChoice,requestId:e.requestId,reasoningEffort:e.reasoningEffort,maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,signal:e.signal})}a(Ke,"streamOpenPondHostedChatTurn");async function We(e){let n=re(e.apiBaseUrl,"models"),t=await fetch(n,{method:"GET",headers:ae(e.token,"application/json"),signal:e.signal});if(!t.ok)throw new Error(`OpenPond OpChat model list failed: ${t.status} ${await se(t)}`);return await t.json()}a(We,"listOpChatModels");async function Ue(e){let n=re(e.apiBaseUrl,"provider-catalog"),t=await fetch(n,{method:"GET",headers:ae(e.token,"application/json"),signal:e.signal});if(!t.ok)throw new Error(`OpenPond OpChat provider catalog failed: ${t.status} ${await se(t)}`);return ce.parse(await t.json())}a(Ue,"listOpChatProviderCatalog");async function*Ve(e){let n=re(e.apiBaseUrl,"chat/completions"),t=await fetch(n,{method:"POST",headers:ae(e.token,"text/event-stream",e.requestId),body:JSON.stringify(Ze(e,!0)),signal:e.signal});if(!t.ok)throw new Error(`OpenPond OpChat request failed: ${t.status} ${await se(t)}`);if(!t.body)throw new Error("OpenPond OpChat request failed: streaming response body is missing.");let o=new Map,r=!1,s=null,i={},c="",y=null,A=Ge(t.headers),f=t.body.getReader(),w=new TextDecoder,m="",S=[],ee=a(()=>{if(S.length===0)return[];let h=S.join(`
2
+ import{Y as ge,a as ue,b as de,d as pe,e as K,f as N,g as fe,h as me,i as he,j as ye}from"./chunk-PRA6LX2G.js";import{d as R,e as U}from"./chunk-J2S7BOZU.js";import{K as ne,q as ce}from"./chunk-NNLI4OWY.js";import{a}from"./chunk-FTQLQJQV.js";import{randomUUID as He}from"node:crypto";var _e=new URL(U).hostname,Se=new URL(R).hostname,Ce=`${U}/opchat/v1`;function l(e){if(!e)return null;let n=e.trim();return n?n.replace(/\/+$/,""):null}a(l,"normalizeBaseUrl");function V(e){let n=l(e);if(!n)return null;try{let o=new URL(n).hostname.toLowerCase();if(o===_e)return U;if(o===Se||o==="openpond.live"||o==="www.openpond.live")return U;if(o.startsWith("api."))return n}catch{return null}return null}a(V,"mapUiBaseToApiBase");function G(e,n){let t=l(process.env.OPENPOND_API_URL);if(t)return t;let o=l(e?.apiBaseUrl);if(o)return o;let r=l(n.apiBaseUrl);if(r)return r;let s=V(process.env.OPENPOND_BASE_URL);return s||(V(e?.baseUrl||n.baseUrl)??U)}a(G,"resolvePublicApiBaseUrl");function J(e,n,t){return Ie(e,n,t)}a(J,"resolveHostedChatApiBaseUrl");function Ie(e,n,t){let o=typeof process<"u"?process.env:{};return W(o.OPENPOND_OPCHAT_API_URL)??W(e?.chatApiBaseUrl??n.chatApiBaseUrl)??W(o.OPENPOND_CHAT_API_URL)??Re(t)}a(Ie,"resolveOpChatApiBaseUrl");function W(e){let n=l(e);if(!n)return null;try{let t=new URL(n),o=t.pathname.split("/").filter(Boolean),r=o.findIndex(i=>i.toLowerCase()==="opchat");return r>=0?(t.pathname=`/${[...o.slice(0,r+1),"v1"].join("/")}`,t.search="",t.hash="",l(t.toString())??null):o.findIndex(i=>i.toLowerCase()==="v1")>=0?(t.pathname="/opchat/v1",t.search="",t.hash="",l(t.toString())??null):(t.pathname=`${t.pathname.replace(/\/+$/,"")}/opchat/v1`.replace(/\/{2,}/g,"/"),t.search="",t.hash="",l(t.toString())??null)}catch{return null}}a(W,"normalizeOpChatApiBaseUrl");function Re(e){return W(e)??Ce}a(Re,"opChatBaseFromPublicApiBase");function T(e){return e?.trim()?e.trim():"production"}a(T,"deriveEnvironment");function Y(e,n=process.env){let t=[e?.apiKey,e?.session?.token,e?.token,n.OPENPOND_API_KEY];for(let o of t){let r=typeof o=="string"?o.trim():"";if(r)return r}return null}a(Y,"accountToken");function P(e,n){return!!(e&&n&&e.toLowerCase()===n.toLowerCase())}a(P,"handleEquals");function v(e,n){return l(e)===l(n)}a(v,"baseUrlEquals");function z(e,n){return`${e?.trim().toLowerCase()||""}|${l(n)??"default"}`}a(z,"profileKey");function Q(e){return l(e?.baseUrl)}a(Q,"selectorBaseUrl");function F(e){let n=l(e.baseUrl);return n?{handle:e.handle,baseUrl:n}:{handle:e.handle}}a(F,"selectorFromAccount");function g(e){let n=typeof e?.handle=="string"?e.handle.trim():"";if(!n)return null;let t=l(e?.baseUrl);return t?{handle:n,baseUrl:t}:{handle:n}}a(g,"normalizeActiveProfile");function k(e,n){if(!P(e.handle,n.handle))return!1;let t=Q(n);return t?v(e.baseUrl,t):!l(e.baseUrl)}a(k,"accountMatchesSelector");function te(e,n){if(!P(e.handle,n.handle))return!1;let t=Q(n);return t?v(e.baseUrl,t):!l(e.baseUrl)}a(te,"profileMatchesSelector");function Ae(e,n,t){let o=Array.isArray(e.accounts)?e.accounts:[],r=n||process.env.OPENPOND_ACCOUNT?g({handle:n||process.env.OPENPOND_ACCOUNT||"",baseUrl:t??process.env.OPENPOND_BASE_URL??null}):g(e.activeProfile);if(r){let s=o.find(c=>k(c,r));if(s)return s;let i=o.filter(c=>P(c.handle,r.handle));return i.length===1?i[0]??null:null}return o[0]?o[0]:null}a(Ae,"findActiveAccount");function Pe(e){let n=Array.isArray(e.accounts)?e.accounts:[],t=g(e.activeProfile)??(n[0]?F(n[0]):null);return oe(n.map(o=>({handle:o.handle,baseUrl:l(o.baseUrl),apiBaseUrl:l(o.apiBaseUrl),chatApiBaseUrl:l(o.chatApiBaseUrl),environment:T(o.environment),isActive:t?k(o,t):!1,hasApiKey:!!o.apiKey?.trim(),hasSessionToken:!!(o.session?.token?.trim()||o.token?.trim()),sessionAppId:o.session?.appId??null,sessionConversationId:o.session?.conversationId??null})))}a(Pe,"fallbackProfilesFromConfig");function oe(e){let n=new Map;for(let t of e){let o=l(t.baseUrl),r=`${t.handle.toLowerCase()}|${o??"default"}`,s={...t,baseUrl:o,apiBaseUrl:l(t.apiBaseUrl),chatApiBaseUrl:l(t.chatApiBaseUrl),environment:T(t.environment),isActive:t.isActive},i=n.get(r);(!i||s.isActive&&!i.isActive||s.hasApiKey&&!i.hasApiKey)&&n.set(r,s)}return Array.from(n.values())}a(oe,"normalizeProfiles");function we(e){return e.hasApiKey||e.hasSessionToken?"signed_in":"signed_out"}a(we,"profileAuthHealth");function Ne(e,n){return e?{reachable:e.reachable,authenticated:e.authenticated,apiBase:e.apiBase||n,latencyMs:e.latencyMs,status:e.status,service:e.service,checkedAt:e.checkedAt,error:e.error??null}:null}a(Ne,"normalizeHealth");function Oe(e){let n=e?.account;return n?{id:n.id??null,email:n.email??null,name:n.name??null,handle:n.handle??null,image:n.image??null,timezone:n.timezone??null,isAdmin:n.isAdmin??null,isVerified:n.isVerified??null,dailyAgentAppId:n.dailyAgentAppId??null,dailyAgentDeploymentId:n.dailyAgentDeploymentId??null,credits:n.credits??null}:null}a(Oe,"normalizeProfile");function Te(e){return(e??[]).map(n=>({...n,id:n.id||n.userProductId||n.openPondProductId||n.name,name:n.name,type:n.type,status:n.status,isActive:n.isActive??null,price:n.price??null,currency:n.currency??null,credits:n.credits??null}))}a(Te,"normalizeProducts");function Le(e){return e.handle.trim().toLowerCase()==="default"&&!l(e.baseUrl)&&!e.hasApiKey&&!e.hasSessionToken}a(Le,"isEmptyDefaultProfile");function X(e){let{config:n,profiles:t,account:o,token:r,apiBaseUrl:s,accountResponse:i,accountProfiles:c,health:y,authFailed:A,error:f}=e,w=J(o,n,s),m=Oe(i??null),S=g(n.activeProfile),E=(o?F(o):null)??S,O=m?.handle||o?.handle||E?.handle||null,C=(E?t.find(p=>te(p,E)):null)??t.find(p=>p.isActive)??null,h=A?"auth_error":r?"signed_in":"signed_out",u=m?.name||m?.handle||m?.email||O||"Signed out",I=l(C?.baseUrl||o?.baseUrl||R),b=T(C?.environment||o?.environment),x=g(E)??(O?g({handle:O,baseUrl:C?.baseUrl??o?.baseUrl}):null),$=(t.length>0?t:O?[{handle:O,baseUrl:Q(x)??l(o?.baseUrl),apiBaseUrl:s,chatApiBaseUrl:w,environment:b,isActive:!0,hasApiKey:!!r,hasSessionToken:!1,sessionAppId:null,sessionConversationId:null}]:[]).filter(p=>!Le(p));return{state:h,activeProfile:x,label:u,email:m?.email??null,avatarUrl:m?.image??null,environment:b,baseUrl:I,apiBaseUrl:s,chatApiBaseUrl:w,creditsLabel:m?.credits??null,profile:m,products:Te(i?.products),apiHealth:Ne(y??null,s),accounts:$.map(p=>{let H=l(p.baseUrl),le=c?.[z(p.handle,H)]??null,M=Oe(le?.response??null);return{handle:p.handle,baseUrl:H,apiBaseUrl:l(p.apiBaseUrl),chatApiBaseUrl:l(p.chatApiBaseUrl),environment:T(p.environment),isActive:x?te(p,x):!1,authHealth:le?.authFailed?"auth_error":we(p),displayLabel:M?.name||M?.handle||M?.email||p.handle,email:M?.email??null,avatarUrl:M?.image??null}}),error:f??y?.error??null}}a(X,"toAccountState");async function De(e){try{return oe(await me())}catch{return Pe(e)}}a(De,"loadProfiles");async function d(e,n){let t=await fe(),o=await De(t),r=Ae(t,e,n),s=Y(r),i=G(r,t),c=J(r,t,i);return{config:t,profiles:o,account:r,token:s,apiBaseUrl:i,chatApiBaseUrl:c,accountState:X({config:t,profiles:o,account:r,token:s,apiBaseUrl:i})}}a(d,"loadOpenPondAccountContext");async function $e(e){let n=l(e.baseUrl);return await he(e.handle,{baseUrl:n}),d(e.handle,n)}a($e,"switchOpenPondAccount");function L(e){return e instanceof Error?e.message:String(e)}a(L,"errorMessage");var Me=15e3;function ze(e){return e===ne?"OpenPond Chat":e==="deepseek-v4-flash"?"DeepSeek V4 Flash":e.replace(/[-_/]+/g," ")}a(ze,"displayNameForHostedModel");function Fe(e){let n=typeof e.id=="string"?e.id:null;return n?{id:n,displayName:ze(n),ownedBy:typeof e.owned_by=="string"?e.owned_by:null,streaming:!0,raw:e}:null}a(Fe,"normalizeHostedModel");async function je(){let e=await d();if(!e.token)return{models:[],error:"No OpenPond API key or session token is configured."};try{return{models:(await We({apiBaseUrl:e.chatApiBaseUrl,token:e.token})).data.map(o=>Fe(o)).filter(o=>!!o),error:null}}catch(n){return{models:[],error:L(n)}}}a(je,"loadOpenPondHostedModels");async function qe(){let e=await d();if(!e.token)return{catalog:null,error:"No OpenPond API key or session token is configured."};let n=new AbortController,t=setTimeout(()=>{n.abort(new Error("OpenPond provider catalog request timed out."))},Me);try{return{catalog:await Ue({apiBaseUrl:e.chatApiBaseUrl,token:e.token,signal:n.signal}),error:null}}catch(o){return{catalog:null,error:L(o)}}finally{clearTimeout(t)}}a(qe,"loadOpenPondProviderCatalog");async function*Ke(e){let n=await d();if(!n.token)throw new Error("OpenPond is signed out. Add an account in Settings before using OpenPond Chat.");yield*Ve({apiBaseUrl:n.chatApiBaseUrl,token:n.token,model:e.model||ne,messages:e.messages,tools:e.tools,toolChoice:e.toolChoice,requestId:e.requestId,reasoningEffort:e.reasoningEffort,maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,signal:e.signal})}a(Ke,"streamOpenPondHostedChatTurn");async function We(e){let n=re(e.apiBaseUrl,"models"),t=await fetch(n,{method:"GET",headers:ae(e.token,"application/json"),signal:e.signal});if(!t.ok)throw new Error(`OpenPond OpChat model list failed: ${t.status} ${await se(t)}`);return await t.json()}a(We,"listOpChatModels");async function Ue(e){let n=re(e.apiBaseUrl,"provider-catalog"),t=await fetch(n,{method:"GET",headers:ae(e.token,"application/json"),signal:e.signal});if(!t.ok)throw new Error(`OpenPond OpChat provider catalog failed: ${t.status} ${await se(t)}`);return ce.parse(await t.json())}a(Ue,"listOpChatProviderCatalog");async function*Ve(e){let n=re(e.apiBaseUrl,"chat/completions"),t=await fetch(n,{method:"POST",headers:ae(e.token,"text/event-stream",e.requestId),body:JSON.stringify(Ze(e,!0)),signal:e.signal});if(!t.ok)throw new Error(`OpenPond OpChat request failed: ${t.status} ${await se(t)}`);if(!t.body)throw new Error("OpenPond OpChat request failed: streaming response body is missing.");let o=new Map,r=!1,s=null,i={},c="",y=null,A=Ge(t.headers),f=t.body.getReader(),w=new TextDecoder,m="",S=[],ee=a(()=>{if(S.length===0)return[];let h=S.join(`
3
3
  `);if(S=[],h==="[DONE]")return r=!0,[];let u;try{u=JSON.parse(h)}catch{throw new Error("OpenPond OpChat request failed: malformed streaming event.")}if(u&&typeof u=="object"&&"error"in u)throw new Error(`OpenPond OpChat request failed: ${ke(u)}`);i=u;let I=u&&typeof u=="object"?u:{},b=Array.isArray(I.choices)?I.choices:[],x=b[0]&&typeof b[0]=="object"?b[0]:{},q=x.delta&&typeof x.delta=="object"?x.delta:{},$=[],p=be(q.reasoning_content);p&&(c+=p,$.push({type:"reasoning_delta",text:p,raw:u}));let H=be(q.content);return H&&$.push({type:"text_delta",text:H,raw:u}),Qe(o,q.tool_calls),s=D(x.finish_reason)??s,y=tn(u)??y,$},"consumeEvent"),E=a(h=>{let u=h.endsWith("\r")?h.slice(0,-1):h;return u?u.startsWith(":")?[]:(u.startsWith("data:")&&S.push(u.slice(5).trimStart()),[]):ee()},"consumeLine");try{for(;;){let h=await f.read();if(h.done)break;m+=w.decode(h.value,{stream:!0});let u=m.split(`
4
4
  `);m=u.pop()??"";for(let I of u)for(let b of E(I))yield b}if(m+=w.decode(),m)for(let h of E(m))yield h;for(let h of ee())yield h}finally{f.releaseLock()}if(!r)throw new Error("OpenPond OpChat request failed: stream ended before [DONE].");let O=Xe(o);O.length>0&&(yield{type:"tool_call_delta",toolCalls:O,raw:i}),O.length>0&&c&&(yield{type:"continuation",continuation:{kind:"chat_completions_reasoning",reasoningContent:c},raw:i});let C=Je(y,A);C&&(yield{type:"usage",usage:C,raw:i}),yield{type:"finish",finishReason:s,raw:i}}a(Ve,"streamOpChatChatCompletion");function Ge(e){let n=xe(e,["fireworks-prompt-tokens","prompt-tokens"]),t=xe(e,["fireworks-cached-prompt-tokens","cached-prompt-tokens"]);return t===null?null:{...n===null?{}:{prompt_tokens:n},cached_input_tokens:t,cache_telemetry_source:"provider_response_headers"}}a(Ge,"cacheUsageFromResponseHeaders");function xe(e,n){for(let t of n){let o=e.get(t);if(o===null||!/^\d+$/.test(o.trim()))continue;let r=Number(o);if(Number.isSafeInteger(r)&&r>=0)return r}return null}a(xe,"firstHeaderTokenCount");function Je(e,n){if(!n||Ye(e))return e;let t={...e??{},cached_input_tokens:n.cached_input_tokens,cache_telemetry_source:"provider_response_headers"};return B(e?.prompt_tokens)===null&&n.prompt_tokens!==void 0&&(t.prompt_tokens=n.prompt_tokens),t}a(Je,"usageWithResponseHeaderCache");function Ye(e){return e?B(e.cached_input_tokens)!==null||B(e.cache_read_input_tokens)!==null||B(e.cache_creation_input_tokens)!==null||B(e.prompt_cache_hit_tokens)!==null||B(e.prompt_cache_miss_tokens)!==null?!0:B(e.prompt_tokens_details?.cached_tokens)!==null||B(e.input_tokens_details?.cached_tokens)!==null:!1}a(Ye,"usageHasCacheTelemetry");function B(e){if(typeof e=="number"&&Number.isSafeInteger(e)&&e>=0)return e;if(typeof e!="string"||!/^\d+$/.test(e.trim()))return null;let n=Number(e);return Number.isSafeInteger(n)?n:null}a(B,"usageTokenCount");function Qe(e,n){Array.isArray(n)&&n.forEach((t,o)=>{if(!t||typeof t!="object")return;let r=t,s=typeof r.index=="number"&&Number.isInteger(r.index)?r.index:o,i=e.get(s)??{arguments:""};typeof r.id=="string"&&(i.id=r.id);let c=r.function&&typeof r.function=="object"?r.function:{};typeof c.name=="string"&&(i.name=`${i.name??""}${c.name}`),typeof c.arguments=="string"&&(i.arguments+=c.arguments),e.set(s,i)})}a(Qe,"mergeOpChatToolCallDeltas");function Xe(e){return[...e.entries()].sort(([n],[t])=>n-t).flatMap(([,n])=>n.id&&n.name?[{id:n.id,type:"function",function:{name:n.name,arguments:n.arguments}}]:[])}a(Xe,"completedOpChatToolCalls");function Ze(e,n){let t={model:e.model,messages:e.messages.map(nn),stream:n};return e.tools&&(t.tools=e.tools),e.toolChoice!==void 0&&(t.tool_choice=e.toolChoice),typeof e.maxTokens=="number"&&(t.max_tokens=e.maxTokens),typeof e.temperature=="number"&&(t.temperature=e.temperature),typeof e.topP=="number"&&(t.top_p=e.topP),Object.assign(t,en(e.reasoningEffort)),t}a(Ze,"buildOpChatBody");function en(e){return e?e==="low"?{thinking:{type:"disabled"}}:{thinking:{type:"enabled"},reasoning_effort:e==="xhigh"?"max":"high"}:{}}a(en,"opChatReasoningFields");function nn(e){let{continuation:n,images:t,...o}=e,r=t?.length?[...typeof e.content=="string"&&e.content.trim()?[{type:"text",text:e.content}]:[],...t.map(s=>({type:"image_url",image_url:{url:s.url,...s.detail?{detail:s.detail}:{}}}))]:e.content;return e.role==="assistant"&&n?.kind==="chat_completions_reasoning"?{...o,...r!==void 0?{content:r}:{},reasoning_content:n.reasoningContent}:{...o,...r!==void 0?{content:r}:{}}}a(nn,"opChatMessage");function re(e,n){let t=e.trim().replace(/\/+$/,"");if(!t)throw new Error("OpenPond OpChat API base URL is required.");return`${t}/${n}`}a(re,"opChatEndpointUrl");function ae(e,n,t){let o=e.trim();if(!o)throw new Error("OpenPond API key is required for OpChat.");let r=new Headers;return r.set("Authorization",`Bearer ${o}`),r.set("Content-Type","application/json"),r.set("Accept",n),r.set("x-openpond-client","openpond-app"),r.set("x-openpond-request-id",t||He()),r}a(ae,"opChatHeaders");async function se(e){let n=await e.text().catch(()=>"");if(!n)return e.statusText||`HTTP ${e.status}`;try{return ke(JSON.parse(n))}catch{return n}}a(se,"readOpChatError");function ke(e){if(!e||typeof e!="object")return String(e||"unknown_error");let n=e,t=n.error;if(t&&typeof t=="object"){let o=t;return[D(o.code),D(o.type),D(o.message)].filter(Boolean).join(": ")}return[D(n.error),D(n.message)].filter(Boolean).join(": ")||JSON.stringify(e)}a(ke,"errorMessageFromPayload");function tn(e){if(!e||typeof e!="object")return null;let n=e.usage;return!n||typeof n!="object"?null:n}a(tn,"parseUsage");function D(e){return typeof e=="string"&&e.trim()?e:null}a(D,"stringValue");function be(e){return typeof e=="string"&&e.length>0?e:null}a(be,"streamTextValue");import{readFileSync as on}from"node:fs";var j;function rn(){if(j!==void 0)return j??"openpond-code bundled";try{let e=new URL("../package.json",import.meta.resolve("openpond")),n=JSON.parse(on(e,"utf8"));j=typeof n.version=="string"?`openpond-code@${n.version}`:null}catch{j=null}return j??"openpond-code bundled"}a(rn,"getBundledRuntimeVersion");import{spawn as an}from"node:child_process";function Be(e,n=process.platform){return n==="darwin"?{command:"open",args:[e]}:n==="win32"?{command:"rundll32.exe",args:["url.dll,FileProtocolHandler",e]}:{command:"xdg-open",args:[e]}}a(Be,"resolveSystemBrowserCommand");async function sn(e,n={}){let t=n.command??Be(e),o=n.handoffTimeoutMs??1500;return new Promise(r=>{let s=!1,i=null,c=a(A=>{s||(s=!0,i&&clearTimeout(i),r(A))},"finish"),y=an(t.command,t.args,{detached:!1,shell:!1,stdio:"ignore",windowsHide:!0});y.once("error",A=>{let f=A.code;c({opened:!1,error:f?`browser launcher ${t.command} failed (${f})`:`browser launcher ${t.command} failed`})}),y.once("close",(A,f)=>{if(A===0){c({opened:!0});return}let w=f?`signal ${f}`:`code ${A??"unknown"}`;c({opened:!1,error:`browser launcher ${t.command} exited with ${w}`})}),i=setTimeout(()=>{y.unref(),c({opened:!0})},o),i.unref()})}a(sn,"openUrlWithSystemBrowser");function ln(e){if(!e||typeof e!="object")return null;let n=e,t=typeof n.id=="string"?n.id:null,o=typeof n.name=="string"?n.name:t;if(!t||!o)return null;let r=n.latestDeployment&&typeof n.latestDeployment=="object"?n.latestDeployment:null,s=ge.safeParse(n.sandboxActionRegistry);return{id:t,name:o,description:typeof n.description=="string"?n.description:null,visibility:typeof n.visibility=="string"?n.visibility:null,gitOwner:typeof n.gitOwner=="string"?n.gitOwner:null,gitRepo:typeof n.gitRepo=="string"?n.gitRepo:null,gitHost:typeof n.gitHost=="string"?n.gitHost:null,defaultBranch:typeof n.defaultBranch=="string"?n.defaultBranch:null,sandbox:n.sandbox===!0,sandboxActionRegistry:s.success?s.data:null,sandboxManifestHash:typeof n.sandboxManifestHash=="string"?n.sandboxManifestHash:null,sandboxManifestPath:typeof n.sandboxManifestPath=="string"?n.sandboxManifestPath:null,sandboxManifestSyncedAt:typeof n.sandboxManifestSyncedAt=="string"?n.sandboxManifestSyncedAt:n.sandboxManifestSyncedAt instanceof Date?n.sandboxManifestSyncedAt.toISOString():null,sandboxManifestError:typeof n.sandboxManifestError=="string"?n.sandboxManifestError:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null,latestDeployment:r?{id:typeof r.id=="string"?r.id:void 0,status:typeof r.status=="string"?r.status:void 0,deploymentDomain:typeof r.deploymentDomain=="string"?r.deploymentDomain:null,createdAt:typeof r.createdAt=="string"?r.createdAt:void 0,isProduction:typeof r.isProduction=="boolean"?r.isProduction:null,gitBranch:typeof r.gitBranch=="string"?r.gitBranch:null}:null,scheduleSummary:un(n.scheduleSummary)}}a(ln,"normalizeApp");function _(e){return typeof e=="string"?e:e instanceof Date?e.toISOString():null}a(_,"normalizeDateString");function cn(e){if(!e||typeof e!="object")return null;let n=e,t=typeof n.id=="string"?n.id:null,o=typeof n.name=="string"?n.name:t,r=typeof n.deploymentId=="string"?n.deploymentId:null;return!t||!o||!r?null:{id:t,name:o,description:typeof n.description=="string"?n.description:null,scheduleType:typeof n.scheduleType=="string"?n.scheduleType:"cron",scheduleExpression:typeof n.scheduleExpression=="string"?n.scheduleExpression:"",enabled:!!n.enabled,rawEnabled:typeof n.rawEnabled=="boolean"?n.rawEnabled:void 0,syncStatus:typeof n.syncStatus=="string"?n.syncStatus:null,syncError:typeof n.syncError=="string"?n.syncError:null,startAt:_(n.startAt),endAt:_(n.endAt),maxRuns:typeof n.maxRuns=="number"?n.maxRuns:null,executionCount:typeof n.executionCount=="number"?n.executionCount:null,lifecycleStatus:typeof n.lifecycleStatus=="string"?n.lifecycleStatus:null,lifecycleReason:typeof n.lifecycleReason=="string"?n.lifecycleReason:null,lastExecutionAt:_(n.lastExecutionAt),lastExecutionStatus:typeof n.lastExecutionStatus=="string"?n.lastExecutionStatus:null,lastRunNowAt:_(n.lastRunNowAt),lastRunNowStatus:typeof n.lastRunNowStatus=="string"?n.lastRunNowStatus:null,updatedAt:_(n.updatedAt)??new Date().toISOString(),deploymentId:r,isProduction:typeof n.isProduction=="boolean"?n.isProduction:void 0,payload:n.payload}}a(cn,"normalizeSchedule");function un(e){if(!e||typeof e!="object")return null;let n=e,t=Array.isArray(n.schedules)?n.schedules.map(cn).filter(i=>!!i):[],o=typeof n.total=="number"?n.total:t.length,r=typeof n.active=="number"?n.active:t.filter(i=>i.enabled).length,s=typeof n.paused=="number"?n.paused:Math.max(0,o-r);return{total:o,active:r,paused:s,enabled:typeof n.enabled=="number"?n.enabled:r,disabled:typeof n.disabled=="number"?n.disabled:s,nextRunAt:_(n.nextRunAt),lastRunAt:_(n.lastRunAt),schedules:t,truncated:typeof n.truncated=="boolean"?n.truncated:void 0}}a(un,"normalizeScheduleSummary");async function dn(e){let n=Array.isArray(e.config.accounts)?e.config.accounts:[],t=await Promise.all(n.map(async o=>{let r=z(o.handle,o.baseUrl),s=Y(o);if(!s)return[r,{response:null,authFailed:!1,error:null}];try{return[r,{response:await K(G(o,e.config),s),authFailed:!1,error:null}]}catch(i){return[r,{response:null,authFailed:!0,error:L(i)}]}}));return Object.fromEntries(t)}a(dn,"loadAccountProfileLookups");async function Ee(e){let n=await dn(e),t=e.account?n[z(e.account.handle,e.account.baseUrl)]??null:null,o=t?.response??null,r=e.token&&t?.authFailed?t.error||"OpenPond account authentication failed.":null;return{account:X({...e,accountResponse:o,accountProfiles:n,authFailed:!!r,error:r})}}a(Ee,"loadOpenPondAccountStateForContext");async function pn(){return Ee(await d())}a(pn,"loadOpenPondAccountState");async function ve(e={}){let n=await d(),t=Ee(n);if(!n.token)return{...await t,apps:[],error:"No OpenPond API key or session token is configured."};let[o,r]=await Promise.allSettled([t,ue(n.apiBaseUrl,n.token,{handle:n.account?.handle,limit:e.limit??20,offset:e.offset??0,includeScheduled:e.includeScheduled??!0})]);if(o.status==="rejected")throw o.reason;return{account:o.value.account,apps:r.status==="fulfilled"?r.value.map(ln).filter(s=>!!s):[],error:r.status==="rejected"?L(r.reason):null}}a(ve,"loadOpenPondApps");async function fn(e){let n=await d();if(!n.token)throw new Error("No OpenPond API key or session token is configured.");return{account:n,response:await de(n.apiBaseUrl,n.token,e)}}a(fn,"createOpenPondRepoApp");import{createHash as mn}from"node:crypto";function hn(e){return`account-${mn("sha256").update(e).digest("hex").slice(0,8)}`}a(hn,"fallbackHandleForApiKey");function Z(e){let n=e?.trim();return n?n.replace(/^@/,""):null}a(Z,"normalizeDerivedHandle");async function yn(e,n){let t=Z(e.handle);if(t)return t;try{let r=(await K(n,e.apiKey)).account,s=Z(r.handle)??Z(r.email?.split("@")[0])??Z(r.id);if(s)return s}catch{}return hn(e.apiKey)}a(yn,"deriveHandleForApiKey");async function gn(e){let n=e.baseUrl??R,t=l(e.apiBaseUrl)??V(n)??U,o=l(e.chatApiBaseUrl),r=await yn(e,t);return await ye({handle:r,apiKey:e.apiKey,baseUrl:n,apiBaseUrl:t,chatApiBaseUrl:o,environment:e.environment??"production",setActive:e.setActive}),d(r,n)}a(gn,"saveOpenPondAccount");function An(e,n,t){let o=l(t),r=e.findIndex(i=>P(i.handle,n)&&v(i.baseUrl,o));if(r!==-1)return r;let s=e.map((i,c)=>({account:i,index:c})).filter(({account:i})=>P(i.handle,n));if(s.length===1)return s[0].index;if(s.length>1)throw new Error(`Multiple OpenPond accounts match ${n}; select one with its base URL.`);return-1}a(An,"findAccountIndex");async function Pn(e){let n=e.handle.trim();if(!n)throw new Error("OpenPond account handle is required.");return await N(t=>{let o=(t.accounts??[]).map(c=>({...c})),r=An(o,n,e.baseUrl);if(r===-1)throw new Error(`OpenPond account not found: ${n}`);let s=o[r],i=g(t.activeProfile);if(i&&k(s,i))throw new Error("Switch to another OpenPond account before removing the active account.");o.splice(r,1),t.accounts=o}),d()}a(Pn,"removeOpenPondAccount");async function wn(){let e;return await N(n=>{let t=g(n.activeProfile),o=(n.accounts??[]).map(s=>({...s})),r=t?o.findIndex(s=>k(s,t)):0;if(r<0||!o[r])throw new Error("No active OpenPond account to log out.");e={...o[r]},delete e.apiKey,delete e.session,o[r]=e,n.accounts=o}),d(e.handle,e.baseUrl)}a(wn,"signOutOpenPondAccount");function On(e,n,t){let o=l(t),r=e.findIndex(i=>P(i.handle,n)&&v(i.baseUrl,o));if(r!==-1)return r;let s=e.map((i,c)=>({account:i,index:c})).filter(({account:i})=>P(i.handle,n));if(s.length===1)return s[0].index;if(s.length>1)throw new Error(`Multiple OpenPond accounts match ${n}; select one with its current base URL.`);return-1}a(On,"findAccountIndex");function ie(e,n,t){if(t===void 0)return;let o=l(t);if(o){e[n]=o;return}(t===null||t.trim()==="")&&delete e[n]}a(ie,"applyOptionalUrl");async function xn(e){let n=e.handle.trim();if(!n)throw new Error("OpenPond account handle is required.");let t;return await N(o=>{let r=(o.accounts??[]).map(f=>({...f})),s=On(r,n,e.currentBaseUrl);if(s===-1)throw new Error(`OpenPond account not found: ${n}`);let i=r[s];if(t={...i},ie(t,"baseUrl",e.baseUrl),ie(t,"apiBaseUrl",e.apiBaseUrl),ie(t,"chatApiBaseUrl",e.chatApiBaseUrl),e.environment===null?delete t.environment:typeof e.environment=="string"&&e.environment.trim()&&(t.environment=e.environment.trim()),r.findIndex((f,w)=>w!==s&&P(f.handle,t.handle)&&v(f.baseUrl,t.baseUrl))!==-1)throw new Error("Another OpenPond account already uses that handle and base URL.");let y=g(o.activeProfile),A=!!(y&&k(i,y));r[s]=t,o.accounts=r,o.activeProfile=e.setActive||A?F(t):o.activeProfile}),d(t.handle,t.baseUrl)}a(xn,"updateOpenPondAccountConfig");async function bn(e){let n=await d();if(!n.token)throw new Error("OpenPond is signed out. Add an account before reading app config.");return pe(n.apiBaseUrl,n.token,e.appId)}a(bn,"getOpenPondAppEnvironment");function Un(e,n){let t="",o=a(r=>{r.startsWith(e)&&n(JSON.parse(r.slice(e.length)))},"processLine");return{push(r){for(t+=r;;){let s=kn(t);if(s<0)return;let i=t.slice(0,s).replace(/\r$/,""),c=t[s]==="\r"&&t[s+1]===`
5
5
  `?2:1;t=t.slice(s+c),o(i)}},flush(){let r=t.trimEnd();t="",r&&o(r)}}}a(Un,"createReadyLineParser");function kn(e){let n=e.indexOf(`
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import{Aa as Vr,Ba as At,Db as Gr,I as Lr,Ua as On,_ as In,aa as An,b as _n,c as It,cd as Pt,dd as Ct,ed as Tt,fd as Un,g as kn,ka as Pn,kd as Ne,la as Cn,na as Br,qa as qr,ra as Tn,rc as Mn,sa as jn,t as wn,u as Rn,ua as $r,va as Dr,wa as Nr,xa as zr,ya as En,za as Fr}from"./chunk-VRXXKDF2.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,ab 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,xa as Or,ya as Mr,z as ae}from"./chunk-A2PIGBPD.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-Q7QAKAGF.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,ab 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,xa as Or,ya as Mr,z as ae}from"./chunk-A2PIGBPD.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(`
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?"":`