openpond 0.1.1 → 0.2.1

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 (225) hide show
  1. package/README.md +4 -4
  2. package/dist/cache.d.ts +7 -10
  3. package/dist/chunks/actions-command-QP3NMDK4.js +2 -0
  4. package/dist/chunks/app-layer-N7VFRVJ2.js +3 -0
  5. package/dist/chunks/app-server-runtime-OCLPUI7F.js +2 -0
  6. package/dist/chunks/apps-AMG75TI4.js +2 -0
  7. package/dist/chunks/chunk-22UARBPW.js +3 -0
  8. package/dist/chunks/chunk-3A7HZJNE.js +1 -0
  9. package/dist/chunks/chunk-3M53YXEI.js +2 -0
  10. package/dist/chunks/chunk-3NDRIQTI.js +2 -0
  11. package/dist/chunks/chunk-5BBVEWG3.js +2 -0
  12. package/dist/chunks/chunk-5O7ZVCMV.js +6 -0
  13. package/dist/chunks/chunk-6FA3GG5B.js +33 -0
  14. package/dist/chunks/chunk-6MI4KKWF.js +2 -0
  15. package/dist/chunks/chunk-BBG546O6.js +6 -0
  16. package/dist/chunks/chunk-BX4J2VDU.js +2 -0
  17. package/dist/chunks/chunk-BZMVB3GS.js +2 -0
  18. package/dist/chunks/chunk-C5LOZSVS.js +2 -0
  19. package/dist/chunks/chunk-CWQWV2T3.js +2 -0
  20. package/dist/chunks/chunk-DUA3QP6Y.js +19 -0
  21. package/dist/chunks/chunk-EAPFMACH.js +10 -0
  22. package/dist/chunks/chunk-ES2ISFJC.js +66 -0
  23. package/dist/chunks/chunk-F65NIZLM.js +2199 -0
  24. package/dist/chunks/chunk-FGJ5LFPL.js +5 -0
  25. package/dist/chunks/chunk-FTQLQJQV.js +2 -0
  26. package/dist/chunks/chunk-FY7OQ5RK.js +24 -0
  27. package/dist/chunks/chunk-FYCJSUFV.js +53 -0
  28. package/dist/chunks/chunk-GLUWATL5.js +2 -0
  29. package/dist/chunks/chunk-H7IWJN7L.js +17 -0
  30. package/dist/chunks/chunk-HZP5U2AA.js +3 -0
  31. package/dist/chunks/chunk-I5K74TOH.js +3 -0
  32. package/dist/chunks/chunk-IR3YJWPW.js +7 -0
  33. package/dist/chunks/chunk-KU7QOHFT.js +2872 -0
  34. package/dist/chunks/chunk-KV553EWX.js +16 -0
  35. package/dist/chunks/chunk-MGN6GLNZ.js +2 -0
  36. package/dist/chunks/chunk-OG5Q6NXK.js +28 -0
  37. package/dist/chunks/chunk-OGPHXXCD.js +1 -0
  38. package/dist/chunks/chunk-PI36UHRA.js +18 -0
  39. package/dist/chunks/chunk-RWSAGQTP.js +2 -0
  40. package/dist/chunks/chunk-SAE4OIPC.js +2 -0
  41. package/dist/chunks/chunk-SDO4FC4Q.js +2 -0
  42. package/dist/chunks/chunk-UKUVMXOW.js +12 -0
  43. package/dist/chunks/chunk-VCLCFK3O.js +36 -0
  44. package/dist/chunks/chunk-VYUMTRB3.js +5 -0
  45. package/dist/chunks/chunk-X37KMV27.js +1 -0
  46. package/dist/chunks/chunk-XDHAGACI.js +3 -0
  47. package/dist/chunks/chunk-XEOEKFG6.js +71 -0
  48. package/dist/chunks/chunk-ZF7TEGY5.js +5 -0
  49. package/dist/chunks/chunk-ZVOO7FKM.js +2 -0
  50. package/dist/chunks/cli-M2FG7SSI.js +2 -0
  51. package/dist/chunks/configuration-command-XBKBIZBO.js +2 -0
  52. package/dist/chunks/continual-D75WA7E7.js +7 -0
  53. package/dist/chunks/core-commands-LUZVWXQR.js +2 -0
  54. package/dist/chunks/database-X2CUV732.js +2 -0
  55. package/dist/chunks/desktop-test-KGC4JVJ7.js +3 -0
  56. package/dist/chunks/dist-NKLXFA37.js +2 -0
  57. package/dist/chunks/extension-NQ7N5LEY.js +5 -0
  58. package/dist/chunks/help-MWK66XZK.js +8 -0
  59. package/dist/chunks/module-ES6BEMUI-ZVL3F6NW.js +2 -0
  60. package/dist/chunks/module-asyncify-2EFITU5U-R7TVXNAE.js +2 -0
  61. package/dist/chunks/opchat-XJZA3QKZ.js +3 -0
  62. package/dist/chunks/organizations-UECDFEYE.js +2 -0
  63. package/dist/chunks/profile-KUMIZURM.js +3 -0
  64. package/dist/chunks/project-agent-NILMJHLV.js +2 -0
  65. package/dist/chunks/sandbox-command-QHH65OSE.js +2 -0
  66. package/dist/chunks/sandbox-template-N7I63PNU.js +10 -0
  67. package/dist/chunks/src-724HF43W.js +82 -0
  68. package/dist/chunks/src-VTKTTKQO.js +319 -0
  69. package/dist/chunks/taskset-PISBOILQ.js +2 -0
  70. package/dist/chunks/teams-bot-UV4RU53M.js +3 -0
  71. package/dist/chunks/training-2NDOWH5S.js +2 -0
  72. package/dist/chunks/workspaces-XXT4KUD3.js +2 -0
  73. package/dist/cli.js +3 -101
  74. package/dist/client.d.ts +1 -1
  75. package/dist/config.d.ts +1 -0
  76. package/dist/index.js +1 -26305
  77. package/dist/private-json-file.d.ts +1 -2
  78. package/dist/sandbox-template/manifest.js +1 -18380
  79. package/dist/web/assets/App-DxecRQUL.js +176 -0
  80. package/dist/web/assets/AppDialog-B65Eo3gp.js +1 -0
  81. package/dist/web/assets/AppTerminalPanel-B2EKQM7W.js +2 -0
  82. package/dist/web/assets/{AppsView-Ck_OzQWf.js → AppsView-BBoVe7s2.js} +1 -1
  83. package/dist/web/assets/{BrowserSidebar-CqciX8aL.js → BrowserSidebar-CSM1atSJ.js} +1 -1
  84. package/dist/web/assets/{CartesianChart-Y0lsL4vC.js → CartesianChart-CJKfXiEG.js} +1 -1
  85. package/dist/web/assets/{CollaborationTabs-BOb9PjvS.js → CollaborationTabs-BMZamWFC.js} +1 -1
  86. package/dist/web/assets/{CommandMenu-Co6JnmTu.js → CommandMenu-B3U1z2eo.js} +1 -1
  87. package/dist/web/assets/{CommunityView-BbTSeL7h.js → CommunityView-CTyRUcfy.js} +1 -1
  88. package/dist/web/assets/{ComposerCreateImproveStrip-BGzCWVFp.js → ComposerCreateImproveStrip-D7usvRtK.js} +1 -1
  89. package/dist/web/assets/GetStartedView-Ibu7oKWJ.js +1 -0
  90. package/dist/web/assets/HostedModelLearningReview-qnzIkT70.js +1 -0
  91. package/dist/web/assets/HostedModelLearningSettings--PKjpYsy.js +1 -0
  92. package/dist/web/assets/LabModelVersionDetailPage-s9uUN6fV.js +1 -0
  93. package/dist/web/assets/{LabSkillSidebar-C5oS6UmH.js → LabSkillSidebar-BKYseMiJ.js} +1 -1
  94. package/dist/web/assets/LabsRoute-C1FWCoYb.css +1 -0
  95. package/dist/web/assets/LabsRoute-DoRs0K6v.js +32 -0
  96. package/dist/web/assets/MainChatThread-DvuyMcMB.js +2 -0
  97. package/dist/web/assets/MainPane-BWwcxgHD.js +8 -0
  98. package/dist/web/assets/{MarkdownText-DqJarmTh.js → MarkdownText-D8XC5UT_.js} +1 -1
  99. package/dist/web/assets/{Messages-BaT7HOzB.js → Messages-e4A8JUjD.js} +6 -6
  100. package/dist/web/assets/{NativeSkillSidebar-DXp8snN5.js → NativeSkillSidebar-D2Joh8XB.js} +1 -1
  101. package/dist/web/assets/{NewExperienceSwitcher-CLHuGUN5.js → NewExperienceSwitcher-CzGebt2E.js} +1 -1
  102. package/dist/web/assets/{NewProjectDialog-CzpHCAaC.js → NewProjectDialog-CdMTSxUE.js} +1 -1
  103. package/dist/web/assets/{OutputsPage-DIzx-Ge6.js → OutputsPage-m7cSb8dW.js} +1 -1
  104. package/dist/web/assets/{ProjectsPage-DojwrhOy.js → ProjectsPage-C9mz8W1g.js} +1 -1
  105. package/dist/web/assets/RightChatPanelStack-B4LEqKEj.js +1 -0
  106. package/dist/web/assets/{RightSidebarHomePanel-DTzfuEX3.js → RightSidebarHomePanel-DOeUsH7h.js} +1 -1
  107. package/dist/web/assets/ScheduledWorkPage-UXZSSWgA.js +1 -0
  108. package/dist/web/assets/SettingsView-CAH0vreE.css +1 -0
  109. package/dist/web/assets/SettingsView-CQm1ai73.js +9 -0
  110. package/dist/web/assets/TeamChatView-C4haojB7.js +3 -0
  111. package/dist/web/assets/{TerminalOverlay-DnNVrCtu.js → TerminalOverlay-p2GZsuyQ.js} +3 -3
  112. package/dist/web/assets/{TrainingCreationPanel-CDwwyucO.js → TrainingCreationPanel-BYJSlO8X.js} +1 -1
  113. package/dist/web/assets/{TrainingDraftPanel-BijDnV_0.js → TrainingDraftPanel-DR5KlayH.js} +1 -1
  114. package/dist/web/assets/{UsageSettingsSection-Y5BFAu1p.js → UsageSettingsSection-BQToNXE4.js} +5 -5
  115. package/dist/web/assets/{WorkSidebarPanel-CkJlvZKm.js → WorkSidebarPanel--EeytWeg.js} +1 -1
  116. package/dist/web/assets/WorkspaceDiffPanel-BrovSYhn.js +14 -0
  117. package/dist/web/assets/{WorkspaceEnvironmentMenu-D8knAy1q.js → WorkspaceEnvironmentMenu-l-keRgvj.js} +3 -3
  118. package/dist/web/assets/{WorkspaceGitDialogs-_LHTrvh6.js → WorkspaceGitDialogs-aicWzaZu.js} +1 -1
  119. package/dist/web/assets/{WorkspaceMonacoEditor-B2B7OM_L.js → WorkspaceMonacoEditor-CO_E74jM.js} +36 -36
  120. package/dist/web/assets/{arrow-up-right-4nAzMtjW.js → arrow-up-right-rwPXNfVn.js} +1 -1
  121. package/dist/web/assets/chat-file-links-B3jDstSC.js +1 -0
  122. package/dist/web/assets/chevron-up-D089nvYQ.js +1 -0
  123. package/dist/web/assets/{clipboard-BzjUoZFo.js → clipboard-DwEExyU4.js} +1 -1
  124. package/dist/web/assets/{cloud-upload-CsrrwS-b.js → cloud-upload-D2he0-vQ.js} +1 -1
  125. package/dist/web/assets/{cssMode-CIbSSHKJ.js → cssMode-DS4k0NcI.js} +1 -1
  126. package/dist/web/assets/{folder-open-vRTuLzpS.js → folder-open-CAOLduKD.js} +1 -1
  127. package/dist/web/assets/{folder-plus-hyqwgUnx.js → folder-plus-D56MrxVT.js} +1 -1
  128. package/dist/web/assets/{git-commit-horizontal-CaxKfeYa.js → git-commit-horizontal-CeNM0oKJ.js} +1 -1
  129. package/dist/web/assets/{htmlMode-C3MGQGam.js → htmlMode-Xkni5erh.js} +1 -1
  130. package/dist/web/assets/{index-ByQIHpc9.css → index-BGMzUaup.css} +1 -1
  131. package/dist/web/assets/{index-Dvq7bpBG.js → index-KwyAyscP.js} +1 -1
  132. package/dist/web/assets/{info-aYWeE1Iw.js → info-CcrBaEE_.js} +1 -1
  133. package/dist/web/assets/{jsonMode-CpD6UkT7.js → jsonMode-C4YPbQB7.js} +1 -1
  134. package/dist/web/assets/{lspLanguageFeatures-DpcK8ZI6.js → lspLanguageFeatures-CF5oMTz6.js} +1 -1
  135. package/dist/web/assets/{minimize-2-DeYg7XqB.js → minimize-2-DzHQnInk.js} +1 -1
  136. package/dist/web/assets/{monaco.contribution-CrrdDQgP.js → monaco.contribution-0EN4mGCC.js} +2 -2
  137. package/dist/web/assets/{monaco.contribution-JWFq0HzV.js → monaco.contribution-B4qcTP0w.js} +2 -2
  138. package/dist/web/assets/{monaco.contribution-BDTM0ZJq.js → monaco.contribution-CJK_NrBm.js} +2 -2
  139. package/dist/web/assets/{monaco.contribution-C-_ekTxy.js → monaco.contribution-CkPGKNd-.js} +2 -2
  140. package/dist/web/assets/{play-BqgRTddV.js → play-p3-AMTPL.js} +1 -1
  141. package/dist/web/assets/{python-B67wope9.js → python-B0kpTxAZ.js} +1 -1
  142. package/dist/web/assets/{refresh-cw-DwMA_2On.js → refresh-cw-_jbTIzzr.js} +1 -1
  143. package/dist/web/assets/{save-B0BKh5oQ.js → save-Cy6hEotx.js} +1 -1
  144. package/dist/web/assets/{square-LY3oz82L.js → square-DKQkcrOH.js} +1 -1
  145. package/dist/web/assets/{toggleHighContrast-B2jka5B1.js → toggleHighContrast-Bnk1VVVq.js} +1 -1
  146. package/dist/web/assets/{tsMode-1MUwluYD.js → tsMode-BDrSVy7V.js} +1 -1
  147. package/dist/web/assets/{upload-bSKSkFVa.js → upload-COn0my_O.js} +1 -1
  148. package/dist/web/assets/{useLocalAgentSchedules--jnnM4Fz.js → useLocalAgentSchedules-iZNB4Oee.js} +1 -1
  149. package/dist/web/assets/{wifi-off-DA34iPmr.js → wifi-off-Cqt-ZLXY.js} +1 -1
  150. package/dist/web/assets/{workers-CczIcRcl.js → workers-hu0Ym93h.js} +1 -1
  151. package/dist/web/assets/{yaml-DwEGoHA9.js → yaml-D-JLDGL6.js} +1 -1
  152. package/dist/web/index.html +2 -2
  153. package/docs/command-reference.md +28 -2
  154. package/package.json +10 -7
  155. package/dist/chunks/actions-command-6N5XWMR6.js +0 -185
  156. package/dist/chunks/app-layer-XEYHFJHI.js +0 -214
  157. package/dist/chunks/app-server-runtime-FJM2EQPH.js +0 -21
  158. package/dist/chunks/apps-GSXUDK6V.js +0 -427
  159. package/dist/chunks/chunk-2JABRRNR.js +0 -183
  160. package/dist/chunks/chunk-47EIAYI7.js +0 -2162
  161. package/dist/chunks/chunk-4L3ZJS2T.js +0 -1207
  162. package/dist/chunks/chunk-5TKZBMQM.js +0 -731
  163. package/dist/chunks/chunk-6G6MDZLM.js +0 -14509
  164. package/dist/chunks/chunk-BVY5JYM6.js +0 -512
  165. package/dist/chunks/chunk-C5TKGE5Y.js +0 -1275
  166. package/dist/chunks/chunk-CNTM26OW.js +0 -602
  167. package/dist/chunks/chunk-D7BO5Y5J.js +0 -1531
  168. package/dist/chunks/chunk-DJL4TJYG.js +0 -70
  169. package/dist/chunks/chunk-DLQQIWN2.js +0 -648
  170. package/dist/chunks/chunk-DNXBJZAU.js +0 -630
  171. package/dist/chunks/chunk-EFET7LB7.js +0 -1331
  172. package/dist/chunks/chunk-FQS2QL5F.js +0 -14522
  173. package/dist/chunks/chunk-HFPUR4CQ.js +0 -669
  174. package/dist/chunks/chunk-J3YDKJFD.js +0 -88
  175. package/dist/chunks/chunk-J7PYGDRY.js +0 -634
  176. package/dist/chunks/chunk-JTHL5XJ2.js +0 -1838
  177. package/dist/chunks/chunk-KSRWKXRB.js +0 -12
  178. package/dist/chunks/chunk-KWDOAJJI.js +0 -238
  179. package/dist/chunks/chunk-MUMPWI4O.js +0 -92
  180. package/dist/chunks/chunk-N3TGCM7J.js +0 -1135
  181. package/dist/chunks/chunk-NTK22KJD.js +0 -10707
  182. package/dist/chunks/chunk-O6B6YCMI.js +0 -57688
  183. package/dist/chunks/chunk-R3C3MNSI.js +0 -140
  184. package/dist/chunks/chunk-SMNFI2FU.js +0 -113
  185. package/dist/chunks/chunk-UACZUFIA.js +0 -47
  186. package/dist/chunks/chunk-W5GKHH77.js +0 -168
  187. package/dist/chunks/chunk-WBAZFKC7.js +0 -1643
  188. package/dist/chunks/chunk-X7ZG4TSW.js +0 -3063
  189. package/dist/chunks/chunk-YVCYVDNP.js +0 -746
  190. package/dist/chunks/cli-6PFRZ2WV.js +0 -21
  191. package/dist/chunks/continual-FYDKLCO7.js +0 -803
  192. package/dist/chunks/core-commands-MAN3CSJQ.js +0 -48
  193. package/dist/chunks/desktop-test-OE5SST2W.js +0 -146
  194. package/dist/chunks/extension-J3CIEDP4.js +0 -10041
  195. package/dist/chunks/help-JNGJJFU5.js +0 -67
  196. package/dist/chunks/opchat-6HEQJFLL.js +0 -167
  197. package/dist/chunks/organizations-MWAPNOCK.js +0 -804
  198. package/dist/chunks/profile-P7HMONTZ.js +0 -1134
  199. package/dist/chunks/project-agent-2RAK7GAZ.js +0 -514
  200. package/dist/chunks/sandbox-command-G22CPFNK.js +0 -1659
  201. package/dist/chunks/sandbox-template-S4WRUWJ6.js +0 -1653
  202. package/dist/chunks/src-BKBZ7WLO.js +0 -3624
  203. package/dist/chunks/src-RTGN2O4H.js +0 -65745
  204. package/dist/chunks/taskset-BMI7KOWP.js +0 -66
  205. package/dist/chunks/teams-bot-5VBYEN7M.js +0 -144
  206. package/dist/chunks/training-UPVSGDTB.js +0 -17
  207. package/dist/chunks/workspaces-IJQPWX3H.js +0 -99
  208. package/dist/web/assets/App-BOkhmdHu.js +0 -173
  209. package/dist/web/assets/AppDialog-BCjKFUBn.js +0 -1
  210. package/dist/web/assets/AppTerminalPanel-DRU8GIfy.js +0 -2
  211. package/dist/web/assets/GetStartedView-jEogFjxP.js +0 -1
  212. package/dist/web/assets/LabModelVersionDetailPage-CrudId_1.js +0 -1
  213. package/dist/web/assets/LabsRoute-9v8qwEBc.js +0 -2
  214. package/dist/web/assets/LabsRoute-CGFgymTX.css +0 -1
  215. package/dist/web/assets/MainChatThread-VtMpAxlP.js +0 -2
  216. package/dist/web/assets/MainPane-BbknUzp3.js +0 -8
  217. package/dist/web/assets/RightChatPanelStack-CIE5bgmO.js +0 -1
  218. package/dist/web/assets/ScheduledWorkPage-DdbcQGSv.js +0 -1
  219. package/dist/web/assets/SettingsView-CC5GXaE1.css +0 -1
  220. package/dist/web/assets/SettingsView-QT_OLmDh.js +0 -6
  221. package/dist/web/assets/TeamChatView-C4-nG1tC.js +0 -3
  222. package/dist/web/assets/WorkspaceDiffPanel-CBgzmBk8.js +0 -14
  223. package/dist/web/assets/chat-file-links-Bned0MT7.js +0 -1
  224. package/dist/web/assets/chevron-up-DK7ejCfk.js +0 -1
  225. package/dist/web/assets/index-66-ohHD5.js +0 -1
@@ -1,1331 +0,0 @@
1
- import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
- import {
3
- DEFAULT_OPENPOND_CHAT_MODEL,
4
- ProviderCatalogSchema,
5
- SandboxAppActionRegistrySchema,
6
- createRepo,
7
- getAppEnvironment,
8
- getOpenPondAccount,
9
- listApps,
10
- listConfiguredProfiles,
11
- loadGlobalConfig,
12
- saveConfig,
13
- saveProfileApiKey,
14
- setActiveProfile
15
- } from "./chunk-6G6MDZLM.js";
16
- import {
17
- DEFAULT_OPENPOND_API_BASE_URL,
18
- DEFAULT_OPENPOND_WEB_BASE_URL
19
- } from "./chunk-JTHL5XJ2.js";
20
-
21
- // ../../packages/runtime/dist/chat.js
22
- import { randomUUID } from "node:crypto";
23
-
24
- // ../../packages/runtime/dist/urls.js
25
- var DEFAULT_OPENPOND_API_HOST = new URL(DEFAULT_OPENPOND_API_BASE_URL).hostname;
26
- var DEFAULT_OPENPOND_WEB_HOST = new URL(DEFAULT_OPENPOND_WEB_BASE_URL).hostname;
27
- var DEFAULT_OPENPOND_OPCHAT_API_BASE_URL = `${DEFAULT_OPENPOND_API_BASE_URL}/opchat/v1`;
28
- function normalizeBaseUrl(value) {
29
- if (!value)
30
- return null;
31
- const trimmed = value.trim();
32
- return trimmed ? trimmed.replace(/\/+$/, "") : null;
33
- }
34
- function mapUiBaseToApiBase(baseUrl) {
35
- const trimmed = normalizeBaseUrl(baseUrl);
36
- if (!trimmed)
37
- return null;
38
- try {
39
- const url = new URL(trimmed);
40
- const host = url.hostname.toLowerCase();
41
- if (host === DEFAULT_OPENPOND_API_HOST)
42
- return DEFAULT_OPENPOND_API_BASE_URL;
43
- if (host === DEFAULT_OPENPOND_WEB_HOST || host === "openpond.live" || host === "www.openpond.live") {
44
- return DEFAULT_OPENPOND_API_BASE_URL;
45
- }
46
- if (host.startsWith("api."))
47
- return trimmed;
48
- } catch {
49
- return null;
50
- }
51
- return null;
52
- }
53
- function resolvePublicApiBaseUrl(account, config) {
54
- const envBase = normalizeBaseUrl(process.env.OPENPOND_API_URL);
55
- if (envBase)
56
- return envBase;
57
- const accountApiBase = normalizeBaseUrl(account?.apiBaseUrl);
58
- if (accountApiBase)
59
- return accountApiBase;
60
- const configApiBase = normalizeBaseUrl(config.apiBaseUrl);
61
- if (configApiBase)
62
- return configApiBase;
63
- const mappedEnvBase = mapUiBaseToApiBase(process.env.OPENPOND_BASE_URL);
64
- if (mappedEnvBase)
65
- return mappedEnvBase;
66
- const mappedConfigBase = mapUiBaseToApiBase(account?.baseUrl || config.baseUrl);
67
- return mappedConfigBase ?? DEFAULT_OPENPOND_API_BASE_URL;
68
- }
69
- function resolveHostedChatApiBaseUrl(account, config, publicApiBaseUrl) {
70
- return resolveOpChatApiBaseUrl(account, config, publicApiBaseUrl);
71
- }
72
- function resolveOpChatApiBaseUrl(account, config, publicApiBaseUrl) {
73
- const runtimeEnv = typeof process !== "undefined" ? process.env : {};
74
- return normalizeOpChatApiBaseUrl(runtimeEnv.OPENPOND_OPCHAT_API_URL) ?? normalizeOpChatApiBaseUrl(account?.chatApiBaseUrl ?? config.chatApiBaseUrl) ?? normalizeOpChatApiBaseUrl(runtimeEnv.OPENPOND_CHAT_API_URL) ?? opChatBaseFromPublicApiBase(publicApiBaseUrl);
75
- }
76
- function normalizeOpChatApiBaseUrl(value) {
77
- const normalized = normalizeBaseUrl(value);
78
- if (!normalized)
79
- return null;
80
- try {
81
- const url = new URL(normalized);
82
- const segments = url.pathname.split("/").filter(Boolean);
83
- const opChatIndex = segments.findIndex((segment) => segment.toLowerCase() === "opchat");
84
- if (opChatIndex >= 0) {
85
- url.pathname = `/${[...segments.slice(0, opChatIndex + 1), "v1"].join("/")}`;
86
- url.search = "";
87
- url.hash = "";
88
- return normalizeBaseUrl(url.toString()) ?? null;
89
- }
90
- const v1Index = segments.findIndex((segment) => segment.toLowerCase() === "v1");
91
- if (v1Index >= 0) {
92
- url.pathname = "/opchat/v1";
93
- url.search = "";
94
- url.hash = "";
95
- return normalizeBaseUrl(url.toString()) ?? null;
96
- }
97
- url.pathname = `${url.pathname.replace(/\/+$/, "")}/opchat/v1`.replace(/\/{2,}/g, "/");
98
- url.search = "";
99
- url.hash = "";
100
- return normalizeBaseUrl(url.toString()) ?? null;
101
- } catch {
102
- return null;
103
- }
104
- }
105
- function opChatBaseFromPublicApiBase(publicApiBaseUrl) {
106
- return normalizeOpChatApiBaseUrl(publicApiBaseUrl) ?? DEFAULT_OPENPOND_OPCHAT_API_BASE_URL;
107
- }
108
- function deriveEnvironment(fallback) {
109
- if (fallback?.trim())
110
- return fallback.trim();
111
- return "production";
112
- }
113
-
114
- // ../../packages/runtime/dist/selectors.js
115
- function accountToken(account, env = process.env) {
116
- const candidates = [
117
- account?.apiKey,
118
- account?.session?.token,
119
- account?.token,
120
- env.OPENPOND_API_KEY
121
- ];
122
- for (const value of candidates) {
123
- const trimmed = typeof value === "string" ? value.trim() : "";
124
- if (trimmed)
125
- return trimmed;
126
- }
127
- return null;
128
- }
129
- function handleEquals(left, right) {
130
- return Boolean(left && right && left.toLowerCase() === right.toLowerCase());
131
- }
132
- function baseUrlEquals(left, right) {
133
- return normalizeBaseUrl(left) === normalizeBaseUrl(right);
134
- }
135
- function profileKey(handle, baseUrl) {
136
- const normalizedHandle = handle?.trim().toLowerCase() || "";
137
- return `${normalizedHandle}|${normalizeBaseUrl(baseUrl) ?? "default"}`;
138
- }
139
- function selectorBaseUrl(selector) {
140
- return normalizeBaseUrl(selector?.baseUrl);
141
- }
142
- function selectorFromAccount(account) {
143
- const baseUrl = normalizeBaseUrl(account.baseUrl);
144
- return baseUrl ? { handle: account.handle, baseUrl } : { handle: account.handle };
145
- }
146
- function normalizeActiveProfile(value) {
147
- const handle = typeof value?.handle === "string" ? value.handle.trim() : "";
148
- if (!handle)
149
- return null;
150
- const baseUrl = normalizeBaseUrl(value?.baseUrl);
151
- return baseUrl ? { handle, baseUrl } : { handle };
152
- }
153
- function accountMatchesSelector(account, selector) {
154
- if (!handleEquals(account.handle, selector.handle))
155
- return false;
156
- const baseUrl = selectorBaseUrl(selector);
157
- if (baseUrl)
158
- return baseUrlEquals(account.baseUrl, baseUrl);
159
- return !normalizeBaseUrl(account.baseUrl);
160
- }
161
- function profileMatchesSelector(profile, selector) {
162
- if (!handleEquals(profile.handle, selector.handle))
163
- return false;
164
- const baseUrl = selectorBaseUrl(selector);
165
- if (baseUrl)
166
- return baseUrlEquals(profile.baseUrl, baseUrl);
167
- return !normalizeBaseUrl(profile.baseUrl);
168
- }
169
- function findActiveAccount(config, requestedHandle, requestedBaseUrl) {
170
- const accounts = Array.isArray(config.accounts) ? config.accounts : [];
171
- const requestedProfile = requestedHandle || process.env.OPENPOND_ACCOUNT ? normalizeActiveProfile({
172
- handle: requestedHandle || process.env.OPENPOND_ACCOUNT || "",
173
- baseUrl: requestedBaseUrl ?? process.env.OPENPOND_BASE_URL ?? null
174
- }) : normalizeActiveProfile(config.activeProfile);
175
- if (requestedProfile) {
176
- const exact = accounts.find((account) => accountMatchesSelector(account, requestedProfile));
177
- if (exact)
178
- return exact;
179
- const sameHandle = accounts.filter((account) => handleEquals(account.handle, requestedProfile.handle));
180
- if (sameHandle.length === 1)
181
- return sameHandle[0] ?? null;
182
- return null;
183
- }
184
- if (accounts[0])
185
- return accounts[0];
186
- return null;
187
- }
188
- function fallbackProfilesFromConfig(config) {
189
- const accounts = Array.isArray(config.accounts) ? config.accounts : [];
190
- const activeProfile = normalizeActiveProfile(config.activeProfile) ?? (accounts[0] ? selectorFromAccount(accounts[0]) : null);
191
- return normalizeProfiles(accounts.map((account) => ({
192
- handle: account.handle,
193
- baseUrl: normalizeBaseUrl(account.baseUrl),
194
- apiBaseUrl: normalizeBaseUrl(account.apiBaseUrl),
195
- chatApiBaseUrl: normalizeBaseUrl(account.chatApiBaseUrl),
196
- environment: deriveEnvironment(account.environment),
197
- isActive: activeProfile ? accountMatchesSelector(account, activeProfile) : false,
198
- hasApiKey: Boolean(account.apiKey?.trim()),
199
- hasSessionToken: Boolean(account.session?.token?.trim() || account.token?.trim()),
200
- sessionAppId: account.session?.appId ?? null,
201
- sessionConversationId: account.session?.conversationId ?? null
202
- })));
203
- }
204
- function normalizeProfiles(profiles) {
205
- const result = /* @__PURE__ */ new Map();
206
- for (const profile of profiles) {
207
- const normalizedBaseUrl = normalizeBaseUrl(profile.baseUrl);
208
- const key = `${profile.handle.toLowerCase()}|${normalizedBaseUrl ?? "default"}`;
209
- const normalized = {
210
- ...profile,
211
- baseUrl: normalizedBaseUrl,
212
- apiBaseUrl: normalizeBaseUrl(profile.apiBaseUrl),
213
- chatApiBaseUrl: normalizeBaseUrl(profile.chatApiBaseUrl),
214
- environment: deriveEnvironment(profile.environment),
215
- isActive: profile.isActive
216
- };
217
- const current = result.get(key);
218
- if (!current || normalized.isActive && !current.isActive || normalized.hasApiKey && !current.hasApiKey) {
219
- result.set(key, normalized);
220
- }
221
- }
222
- return Array.from(result.values());
223
- }
224
- function profileAuthHealth(profile) {
225
- return profile.hasApiKey || profile.hasSessionToken ? "signed_in" : "signed_out";
226
- }
227
-
228
- // ../../packages/runtime/dist/account-state.js
229
- function normalizeHealth(health, apiBaseUrl) {
230
- if (!health)
231
- return null;
232
- return {
233
- reachable: health.reachable,
234
- authenticated: health.authenticated,
235
- apiBase: health.apiBase || apiBaseUrl,
236
- latencyMs: health.latencyMs,
237
- status: health.status,
238
- service: health.service,
239
- checkedAt: health.checkedAt,
240
- error: health.error ?? null
241
- };
242
- }
243
- function normalizeProfile(response) {
244
- const account = response?.account;
245
- if (!account)
246
- return null;
247
- return {
248
- id: account.id ?? null,
249
- email: account.email ?? null,
250
- name: account.name ?? null,
251
- handle: account.handle ?? null,
252
- image: account.image ?? null,
253
- timezone: account.timezone ?? null,
254
- isAdmin: account.isAdmin ?? null,
255
- isVerified: account.isVerified ?? null,
256
- dailyAgentAppId: account.dailyAgentAppId ?? null,
257
- dailyAgentDeploymentId: account.dailyAgentDeploymentId ?? null,
258
- credits: account.credits ?? null
259
- };
260
- }
261
- function normalizeProducts(products) {
262
- return (products ?? []).map((product) => ({
263
- ...product,
264
- id: product.id || product.userProductId || product.openPondProductId || product.name,
265
- name: product.name,
266
- type: product.type,
267
- status: product.status,
268
- isActive: product.isActive ?? null,
269
- price: product.price ?? null,
270
- currency: product.currency ?? null,
271
- credits: product.credits ?? null
272
- }));
273
- }
274
- function isEmptyDefaultProfile(profile) {
275
- return profile.handle.trim().toLowerCase() === "default" && !normalizeBaseUrl(profile.baseUrl) && !profile.hasApiKey && !profile.hasSessionToken;
276
- }
277
- function toAccountState(input) {
278
- const { config, profiles, account, token, apiBaseUrl, accountResponse, accountProfiles, health, authFailed, error } = input;
279
- const chatApiBaseUrl = resolveHostedChatApiBaseUrl(account, config, apiBaseUrl);
280
- const profile = normalizeProfile(accountResponse ?? null);
281
- const configActiveProfile = normalizeActiveProfile(config.activeProfile);
282
- const accountSelector = account ? selectorFromAccount(account) : null;
283
- const activeSelector = accountSelector ?? configActiveProfile;
284
- const displayHandle = profile?.handle || account?.handle || activeSelector?.handle || null;
285
- const activeProfileRow = (activeSelector ? profiles.find((candidate) => profileMatchesSelector(candidate, activeSelector)) : null) ?? profiles.find((candidate) => candidate.isActive) ?? null;
286
- const healthState = authFailed ? "auth_error" : token ? "signed_in" : "signed_out";
287
- const label = profile?.name || profile?.handle || profile?.email || displayHandle || "Signed out";
288
- const baseUrl = normalizeBaseUrl(activeProfileRow?.baseUrl || account?.baseUrl || DEFAULT_OPENPOND_WEB_BASE_URL);
289
- const environment = deriveEnvironment(activeProfileRow?.environment || account?.environment);
290
- const activeProfile = normalizeActiveProfile(activeSelector) ?? (displayHandle ? normalizeActiveProfile({ handle: displayHandle, baseUrl: activeProfileRow?.baseUrl ?? account?.baseUrl }) : null);
291
- const profileRows = profiles.length > 0 ? profiles : displayHandle ? [
292
- {
293
- handle: displayHandle,
294
- baseUrl: selectorBaseUrl(activeProfile) ?? normalizeBaseUrl(account?.baseUrl),
295
- apiBaseUrl,
296
- chatApiBaseUrl,
297
- environment,
298
- isActive: true,
299
- hasApiKey: Boolean(token),
300
- hasSessionToken: false,
301
- sessionAppId: null,
302
- sessionConversationId: null
303
- }
304
- ] : [];
305
- const visibleProfileRows = profileRows.filter((candidate) => !isEmptyDefaultProfile(candidate));
306
- return {
307
- state: healthState,
308
- activeProfile,
309
- label,
310
- email: profile?.email ?? null,
311
- avatarUrl: profile?.image ?? null,
312
- environment,
313
- baseUrl,
314
- apiBaseUrl,
315
- chatApiBaseUrl,
316
- creditsLabel: profile?.credits ?? null,
317
- profile,
318
- products: normalizeProducts(accountResponse?.products),
319
- apiHealth: normalizeHealth(health ?? null, apiBaseUrl),
320
- accounts: visibleProfileRows.map((candidate) => {
321
- const candidateBaseUrl = normalizeBaseUrl(candidate.baseUrl);
322
- const profileLookup = accountProfiles?.[profileKey(candidate.handle, candidateBaseUrl)] ?? null;
323
- const candidateProfile = normalizeProfile(profileLookup?.response ?? null);
324
- return {
325
- handle: candidate.handle,
326
- baseUrl: candidateBaseUrl,
327
- apiBaseUrl: normalizeBaseUrl(candidate.apiBaseUrl),
328
- chatApiBaseUrl: normalizeBaseUrl(candidate.chatApiBaseUrl),
329
- environment: deriveEnvironment(candidate.environment),
330
- isActive: activeProfile ? profileMatchesSelector(candidate, activeProfile) : false,
331
- authHealth: profileLookup?.authFailed ? "auth_error" : profileAuthHealth(candidate),
332
- displayLabel: candidateProfile?.name || candidateProfile?.handle || candidateProfile?.email || candidate.handle,
333
- email: candidateProfile?.email ?? null,
334
- avatarUrl: candidateProfile?.image ?? null
335
- };
336
- }),
337
- error: error ?? health?.error ?? null
338
- };
339
- }
340
-
341
- // ../../packages/runtime/dist/config.js
342
- import { readFileSync } from "node:fs";
343
- import { homedir } from "node:os";
344
- import { join } from "node:path";
345
- function readRawOpenPondConfig() {
346
- try {
347
- const raw = JSON.parse(readFileSync(join(homedir(), ".openpond", "config.json"), "utf8"));
348
- return raw && typeof raw === "object" ? raw : {};
349
- } catch {
350
- return {};
351
- }
352
- }
353
- function mergeRawApiBaseConfig(config) {
354
- const raw = readRawOpenPondConfig();
355
- const rawAccounts = Array.isArray(raw.accounts) ? raw.accounts : [];
356
- const accounts = Array.isArray(config.accounts) ? config.accounts : [];
357
- return {
358
- ...config,
359
- activeProfile: config.activeProfile ?? raw.activeProfile,
360
- apiBaseUrl: config.apiBaseUrl ?? raw.apiBaseUrl,
361
- chatApiBaseUrl: config.chatApiBaseUrl ?? raw.chatApiBaseUrl,
362
- accounts: accounts.map((account) => {
363
- const rawAccount = rawAccounts.find((candidate) => handleEquals(candidate.handle, account.handle) && baseUrlEquals(candidate.baseUrl, account.baseUrl)) ?? rawAccounts.find((candidate) => handleEquals(candidate.handle, account.handle));
364
- return {
365
- ...account,
366
- ...typeof rawAccount?.apiBaseUrl === "string" && rawAccount.apiBaseUrl.trim() ? { apiBaseUrl: rawAccount.apiBaseUrl } : {},
367
- ...typeof rawAccount?.chatApiBaseUrl === "string" && rawAccount.chatApiBaseUrl.trim() ? { chatApiBaseUrl: rawAccount.chatApiBaseUrl } : {}
368
- };
369
- })
370
- };
371
- }
372
-
373
- // ../../packages/runtime/dist/account-context.js
374
- async function loadProfiles(config) {
375
- try {
376
- return normalizeProfiles(await listConfiguredProfiles());
377
- } catch {
378
- return fallbackProfilesFromConfig(config);
379
- }
380
- }
381
- async function loadOpenPondAccountContext(requestedHandle, requestedBaseUrl) {
382
- const config = mergeRawApiBaseConfig(await loadGlobalConfig().catch(() => ({})));
383
- const profiles = await loadProfiles(config);
384
- const account = findActiveAccount(config, requestedHandle, requestedBaseUrl);
385
- const token = accountToken(account);
386
- const apiBaseUrl = resolvePublicApiBaseUrl(account, config);
387
- const chatApiBaseUrl = resolveHostedChatApiBaseUrl(account, config, apiBaseUrl);
388
- return {
389
- config,
390
- profiles,
391
- account,
392
- token,
393
- apiBaseUrl,
394
- chatApiBaseUrl,
395
- accountState: toAccountState({ config, profiles, account, token, apiBaseUrl })
396
- };
397
- }
398
- async function switchOpenPondAccount(input) {
399
- const baseUrl = normalizeBaseUrl(input.baseUrl);
400
- await setActiveProfile(input.handle, {
401
- baseUrl
402
- });
403
- return loadOpenPondAccountContext(input.handle, baseUrl);
404
- }
405
-
406
- // ../../packages/runtime/dist/errors.js
407
- function errorMessage(error) {
408
- return error instanceof Error ? error.message : String(error);
409
- }
410
-
411
- // ../../packages/runtime/dist/chat.js
412
- var PROVIDER_CATALOG_FETCH_TIMEOUT_MS = 15e3;
413
- function displayNameForHostedModel(id) {
414
- if (id === DEFAULT_OPENPOND_CHAT_MODEL)
415
- return "OpenPond Chat";
416
- if (id === "deepseek-v4-flash")
417
- return "DeepSeek V4 Flash";
418
- return id.replace(/[-_/]+/g, " ");
419
- }
420
- function normalizeHostedModel(model) {
421
- const id = typeof model.id === "string" ? model.id : null;
422
- if (!id)
423
- return null;
424
- return {
425
- id,
426
- displayName: displayNameForHostedModel(id),
427
- ownedBy: typeof model.owned_by === "string" ? model.owned_by : null,
428
- streaming: true,
429
- raw: model
430
- };
431
- }
432
- async function loadOpenPondHostedModels() {
433
- const context = await loadOpenPondAccountContext();
434
- if (!context.token) {
435
- return {
436
- models: [],
437
- error: "No OpenPond API key or session token is configured."
438
- };
439
- }
440
- try {
441
- const result = await listOpChatModels({
442
- apiBaseUrl: context.chatApiBaseUrl,
443
- token: context.token
444
- });
445
- const models = result.data.map((model) => normalizeHostedModel(model)).filter((value) => Boolean(value));
446
- return {
447
- models,
448
- error: null
449
- };
450
- } catch (error) {
451
- return {
452
- models: [],
453
- error: errorMessage(error)
454
- };
455
- }
456
- }
457
- async function loadOpenPondProviderCatalog() {
458
- const context = await loadOpenPondAccountContext();
459
- if (!context.token) {
460
- return {
461
- catalog: null,
462
- error: "No OpenPond API key or session token is configured."
463
- };
464
- }
465
- const controller = new AbortController();
466
- const timeout = setTimeout(() => {
467
- controller.abort(new Error("OpenPond provider catalog request timed out."));
468
- }, PROVIDER_CATALOG_FETCH_TIMEOUT_MS);
469
- try {
470
- const catalog = await listOpChatProviderCatalog({
471
- apiBaseUrl: context.chatApiBaseUrl,
472
- token: context.token,
473
- signal: controller.signal
474
- });
475
- return {
476
- catalog,
477
- error: null
478
- };
479
- } catch (error) {
480
- return {
481
- catalog: null,
482
- error: errorMessage(error)
483
- };
484
- } finally {
485
- clearTimeout(timeout);
486
- }
487
- }
488
- async function* streamOpenPondHostedChatTurn(input) {
489
- const context = await loadOpenPondAccountContext();
490
- if (!context.token) {
491
- throw new Error("OpenPond is signed out. Add an account in Settings before using OpenPond Chat.");
492
- }
493
- yield* streamOpChatChatCompletion({
494
- apiBaseUrl: context.chatApiBaseUrl,
495
- token: context.token,
496
- model: input.model || DEFAULT_OPENPOND_CHAT_MODEL,
497
- messages: input.messages,
498
- tools: input.tools,
499
- toolChoice: input.toolChoice,
500
- requestId: input.requestId,
501
- reasoningEffort: input.reasoningEffort,
502
- maxTokens: input.maxTokens,
503
- temperature: input.temperature,
504
- topP: input.topP,
505
- signal: input.signal
506
- });
507
- }
508
- async function listOpChatModels(options) {
509
- const requestUrl = opChatEndpointUrl(options.apiBaseUrl, "models");
510
- const response = await fetch(requestUrl, {
511
- method: "GET",
512
- headers: opChatHeaders(options.token, "application/json"),
513
- signal: options.signal
514
- });
515
- if (!response.ok) {
516
- throw new Error(`OpenPond OpChat model list failed: ${response.status} ${await readOpChatError(response)}`);
517
- }
518
- return await response.json();
519
- }
520
- async function listOpChatProviderCatalog(options) {
521
- const requestUrl = opChatEndpointUrl(options.apiBaseUrl, "provider-catalog");
522
- const response = await fetch(requestUrl, {
523
- method: "GET",
524
- headers: opChatHeaders(options.token, "application/json"),
525
- signal: options.signal
526
- });
527
- if (!response.ok) {
528
- throw new Error(`OpenPond OpChat provider catalog failed: ${response.status} ${await readOpChatError(response)}`);
529
- }
530
- return ProviderCatalogSchema.parse(await response.json());
531
- }
532
- async function* streamOpChatChatCompletion(options) {
533
- const requestUrl = opChatEndpointUrl(options.apiBaseUrl, "chat/completions");
534
- const response = await fetch(requestUrl, {
535
- method: "POST",
536
- headers: opChatHeaders(options.token, "text/event-stream", options.requestId),
537
- body: JSON.stringify(buildOpChatBody(options, true)),
538
- signal: options.signal
539
- });
540
- if (!response.ok) {
541
- throw new Error(`OpenPond OpChat request failed: ${response.status} ${await readOpChatError(response)}`);
542
- }
543
- if (!response.body) {
544
- throw new Error("OpenPond OpChat request failed: streaming response body is missing.");
545
- }
546
- const toolCalls = /* @__PURE__ */ new Map();
547
- let sawDone = false;
548
- let finishReason = null;
549
- let lastPayload = {};
550
- let accumulatedReasoning = "";
551
- let usage = null;
552
- const responseHeaderUsage = cacheUsageFromResponseHeaders(response.headers);
553
- const reader = response.body.getReader();
554
- const decoder = new TextDecoder();
555
- let buffer = "";
556
- let dataLines = [];
557
- const consumeEvent = () => {
558
- if (dataLines.length === 0)
559
- return [];
560
- const data = dataLines.join("\n");
561
- dataLines = [];
562
- if (data === "[DONE]") {
563
- sawDone = true;
564
- return [];
565
- }
566
- let payload;
567
- try {
568
- payload = JSON.parse(data);
569
- } catch {
570
- throw new Error("OpenPond OpChat request failed: malformed streaming event.");
571
- }
572
- if (payload && typeof payload === "object" && "error" in payload) {
573
- throw new Error(`OpenPond OpChat request failed: ${errorMessageFromPayload(payload)}`);
574
- }
575
- lastPayload = payload;
576
- const record = payload && typeof payload === "object" ? payload : {};
577
- const choices = Array.isArray(record.choices) ? record.choices : [];
578
- const choice = choices[0] && typeof choices[0] === "object" ? choices[0] : {};
579
- const delta = choice.delta && typeof choice.delta === "object" ? choice.delta : {};
580
- const deltas = [];
581
- const reasoningChunk = streamTextValue(delta.reasoning_content);
582
- if (reasoningChunk) {
583
- accumulatedReasoning += reasoningChunk;
584
- deltas.push({ type: "reasoning_delta", text: reasoningChunk, raw: payload });
585
- }
586
- const textChunk = streamTextValue(delta.content);
587
- if (textChunk) {
588
- deltas.push({ type: "text_delta", text: textChunk, raw: payload });
589
- }
590
- mergeOpChatToolCallDeltas(toolCalls, delta.tool_calls);
591
- finishReason = stringValue(choice.finish_reason) ?? finishReason;
592
- usage = parseUsage(payload) ?? usage;
593
- return deltas;
594
- };
595
- const consumeLine = (line) => {
596
- const normalized = line.endsWith("\r") ? line.slice(0, -1) : line;
597
- if (!normalized) {
598
- return consumeEvent();
599
- }
600
- if (normalized.startsWith(":"))
601
- return [];
602
- if (normalized.startsWith("data:")) {
603
- dataLines.push(normalized.slice("data:".length).trimStart());
604
- }
605
- return [];
606
- };
607
- try {
608
- while (true) {
609
- const result = await reader.read();
610
- if (result.done)
611
- break;
612
- buffer += decoder.decode(result.value, { stream: true });
613
- const lines = buffer.split("\n");
614
- buffer = lines.pop() ?? "";
615
- for (const line of lines) {
616
- for (const delta of consumeLine(line))
617
- yield delta;
618
- }
619
- }
620
- buffer += decoder.decode();
621
- if (buffer) {
622
- for (const delta of consumeLine(buffer))
623
- yield delta;
624
- }
625
- for (const delta of consumeEvent())
626
- yield delta;
627
- } finally {
628
- reader.releaseLock();
629
- }
630
- if (!sawDone) {
631
- throw new Error("OpenPond OpChat request failed: stream ended before [DONE].");
632
- }
633
- const completedToolCalls = completedOpChatToolCalls(toolCalls);
634
- if (completedToolCalls.length > 0) {
635
- yield { type: "tool_call_delta", toolCalls: completedToolCalls, raw: lastPayload };
636
- }
637
- if (completedToolCalls.length > 0 && accumulatedReasoning) {
638
- yield {
639
- type: "continuation",
640
- continuation: {
641
- kind: "chat_completions_reasoning",
642
- reasoningContent: accumulatedReasoning
643
- },
644
- raw: lastPayload
645
- };
646
- }
647
- const completedUsage = usageWithResponseHeaderCache(usage, responseHeaderUsage);
648
- if (completedUsage)
649
- yield { type: "usage", usage: completedUsage, raw: lastPayload };
650
- yield { type: "finish", finishReason, raw: lastPayload };
651
- }
652
- function cacheUsageFromResponseHeaders(headers) {
653
- const promptTokens = firstHeaderTokenCount(headers, [
654
- "fireworks-prompt-tokens",
655
- "prompt-tokens"
656
- ]);
657
- const cachedPromptTokens = firstHeaderTokenCount(headers, [
658
- "fireworks-cached-prompt-tokens",
659
- "cached-prompt-tokens"
660
- ]);
661
- if (cachedPromptTokens === null)
662
- return null;
663
- return {
664
- ...promptTokens === null ? {} : { prompt_tokens: promptTokens },
665
- cached_input_tokens: cachedPromptTokens,
666
- cache_telemetry_source: "provider_response_headers"
667
- };
668
- }
669
- function firstHeaderTokenCount(headers, names) {
670
- for (const name of names) {
671
- const value = headers.get(name);
672
- if (value === null || !/^\d+$/.test(value.trim()))
673
- continue;
674
- const parsed = Number(value);
675
- if (Number.isSafeInteger(parsed) && parsed >= 0)
676
- return parsed;
677
- }
678
- return null;
679
- }
680
- function usageWithResponseHeaderCache(usage, responseHeaderUsage) {
681
- if (!responseHeaderUsage || usageHasCacheTelemetry(usage))
682
- return usage;
683
- const merged = {
684
- ...usage ?? {},
685
- cached_input_tokens: responseHeaderUsage.cached_input_tokens,
686
- cache_telemetry_source: "provider_response_headers"
687
- };
688
- if (usageTokenCount(usage?.prompt_tokens) === null && responseHeaderUsage.prompt_tokens !== void 0) {
689
- merged.prompt_tokens = responseHeaderUsage.prompt_tokens;
690
- }
691
- return merged;
692
- }
693
- function usageHasCacheTelemetry(usage) {
694
- if (!usage)
695
- return false;
696
- if (usageTokenCount(usage.cached_input_tokens) !== null || usageTokenCount(usage.cache_read_input_tokens) !== null || usageTokenCount(usage.cache_creation_input_tokens) !== null || usageTokenCount(usage.prompt_cache_hit_tokens) !== null || usageTokenCount(usage.prompt_cache_miss_tokens) !== null)
697
- return true;
698
- return usageTokenCount(usage.prompt_tokens_details?.cached_tokens) !== null || usageTokenCount(usage.input_tokens_details?.cached_tokens) !== null;
699
- }
700
- function usageTokenCount(value) {
701
- if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0)
702
- return value;
703
- if (typeof value !== "string" || !/^\d+$/.test(value.trim()))
704
- return null;
705
- const parsed = Number(value);
706
- return Number.isSafeInteger(parsed) ? parsed : null;
707
- }
708
- function mergeOpChatToolCallDeltas(calls, value) {
709
- if (!Array.isArray(value))
710
- return;
711
- value.forEach((item, position) => {
712
- if (!item || typeof item !== "object")
713
- return;
714
- const record = item;
715
- const index = typeof record.index === "number" && Number.isInteger(record.index) ? record.index : position;
716
- const current = calls.get(index) ?? { arguments: "" };
717
- if (typeof record.id === "string")
718
- current.id = record.id;
719
- const fn = record.function && typeof record.function === "object" ? record.function : {};
720
- if (typeof fn.name === "string") {
721
- current.name = `${current.name ?? ""}${fn.name}`;
722
- }
723
- if (typeof fn.arguments === "string") {
724
- current.arguments += fn.arguments;
725
- }
726
- calls.set(index, current);
727
- });
728
- }
729
- function completedOpChatToolCalls(calls) {
730
- return [...calls.entries()].sort(([left], [right]) => left - right).flatMap(([, call]) => call.id && call.name ? [{
731
- id: call.id,
732
- type: "function",
733
- function: {
734
- name: call.name,
735
- arguments: call.arguments
736
- }
737
- }] : []);
738
- }
739
- function buildOpChatBody(options, stream) {
740
- const body = {
741
- model: options.model,
742
- messages: options.messages.map(opChatMessage),
743
- stream
744
- };
745
- if (options.tools) {
746
- body.tools = options.tools;
747
- }
748
- if (options.toolChoice !== void 0) {
749
- body.tool_choice = options.toolChoice;
750
- }
751
- if (typeof options.maxTokens === "number") {
752
- body.max_tokens = options.maxTokens;
753
- }
754
- if (typeof options.temperature === "number") {
755
- body.temperature = options.temperature;
756
- }
757
- if (typeof options.topP === "number") {
758
- body.top_p = options.topP;
759
- }
760
- Object.assign(body, opChatReasoningFields(options.reasoningEffort));
761
- return body;
762
- }
763
- function opChatReasoningFields(effort) {
764
- if (!effort)
765
- return {};
766
- if (effort === "low") {
767
- return { thinking: { type: "disabled" } };
768
- }
769
- return {
770
- thinking: { type: "enabled" },
771
- reasoning_effort: effort === "xhigh" ? "max" : "high"
772
- };
773
- }
774
- function opChatMessage(message) {
775
- const { continuation, images, ...projected } = message;
776
- const content = images?.length ? [
777
- ...typeof message.content === "string" && message.content.trim() ? [{ type: "text", text: message.content }] : [],
778
- ...images.map((image) => ({
779
- type: "image_url",
780
- image_url: {
781
- url: image.url,
782
- ...image.detail ? { detail: image.detail } : {}
783
- }
784
- }))
785
- ] : message.content;
786
- if (message.role === "assistant" && continuation?.kind === "chat_completions_reasoning") {
787
- return {
788
- ...projected,
789
- ...content !== void 0 ? { content } : {},
790
- reasoning_content: continuation.reasoningContent
791
- };
792
- }
793
- return { ...projected, ...content !== void 0 ? { content } : {} };
794
- }
795
- function opChatEndpointUrl(apiBaseUrl, path) {
796
- const normalized = apiBaseUrl.trim().replace(/\/+$/, "");
797
- if (!normalized)
798
- throw new Error("OpenPond OpChat API base URL is required.");
799
- return `${normalized}/${path}`;
800
- }
801
- function opChatHeaders(token, accept, requestId) {
802
- const trimmed = token.trim();
803
- if (!trimmed)
804
- throw new Error("OpenPond API key is required for OpChat.");
805
- const headers = new Headers();
806
- headers.set("Authorization", `Bearer ${trimmed}`);
807
- headers.set("Content-Type", "application/json");
808
- headers.set("Accept", accept);
809
- headers.set("x-openpond-client", "openpond-app");
810
- headers.set("x-openpond-request-id", requestId || randomUUID());
811
- return headers;
812
- }
813
- async function readOpChatError(response) {
814
- const text = await response.text().catch(() => "");
815
- if (!text)
816
- return response.statusText || `HTTP ${response.status}`;
817
- try {
818
- return errorMessageFromPayload(JSON.parse(text));
819
- } catch {
820
- return text;
821
- }
822
- }
823
- function errorMessageFromPayload(payload) {
824
- if (!payload || typeof payload !== "object")
825
- return String(payload || "unknown_error");
826
- const record = payload;
827
- const error = record.error;
828
- if (error && typeof error === "object") {
829
- const errorRecord = error;
830
- return [
831
- stringValue(errorRecord.code),
832
- stringValue(errorRecord.type),
833
- stringValue(errorRecord.message)
834
- ].filter(Boolean).join(": ");
835
- }
836
- return [stringValue(record.error), stringValue(record.message)].filter(Boolean).join(": ") || JSON.stringify(payload);
837
- }
838
- function parseUsage(raw) {
839
- if (!raw || typeof raw !== "object")
840
- return null;
841
- const usage = raw.usage;
842
- if (!usage || typeof usage !== "object")
843
- return null;
844
- return usage;
845
- }
846
- function stringValue(value) {
847
- return typeof value === "string" && value.trim() ? value : null;
848
- }
849
- function streamTextValue(value) {
850
- return typeof value === "string" && value.length > 0 ? value : null;
851
- }
852
-
853
- // ../../packages/runtime/dist/version.js
854
- import { readFileSync as readFileSync2 } from "node:fs";
855
- var bundledRuntimeVersion;
856
- function getBundledRuntimeVersion() {
857
- if (bundledRuntimeVersion !== void 0)
858
- return bundledRuntimeVersion ?? "openpond-code bundled";
859
- try {
860
- const packageJsonUrl = new URL("../package.json", import.meta.resolve("openpond"));
861
- const packageJson = JSON.parse(readFileSync2(packageJsonUrl, "utf8"));
862
- bundledRuntimeVersion = typeof packageJson.version === "string" ? `openpond-code@${packageJson.version}` : null;
863
- } catch {
864
- bundledRuntimeVersion = null;
865
- }
866
- return bundledRuntimeVersion ?? "openpond-code bundled";
867
- }
868
-
869
- // ../../packages/runtime/dist/system-browser.js
870
- import { spawn } from "node:child_process";
871
- function resolveSystemBrowserCommand(url, platform = process.platform) {
872
- if (platform === "darwin")
873
- return { command: "open", args: [url] };
874
- if (platform === "win32") {
875
- return {
876
- command: "rundll32.exe",
877
- args: ["url.dll,FileProtocolHandler", url]
878
- };
879
- }
880
- return { command: "xdg-open", args: [url] };
881
- }
882
- async function openUrlWithSystemBrowser(url, options = {}) {
883
- const browser = options.command ?? resolveSystemBrowserCommand(url);
884
- const handoffTimeoutMs = options.handoffTimeoutMs ?? 1500;
885
- return new Promise((resolve) => {
886
- let settled = false;
887
- let timer = null;
888
- const finish = (result) => {
889
- if (settled)
890
- return;
891
- settled = true;
892
- if (timer)
893
- clearTimeout(timer);
894
- resolve(result);
895
- };
896
- const child = spawn(browser.command, browser.args, {
897
- detached: false,
898
- shell: false,
899
- stdio: "ignore",
900
- windowsHide: true
901
- });
902
- child.once("error", (error) => {
903
- const code = error.code;
904
- finish({
905
- opened: false,
906
- error: code ? `browser launcher ${browser.command} failed (${code})` : `browser launcher ${browser.command} failed`
907
- });
908
- });
909
- child.once("close", (code, signal) => {
910
- if (code === 0) {
911
- finish({ opened: true });
912
- return;
913
- }
914
- const detail = signal ? `signal ${signal}` : `code ${code ?? "unknown"}`;
915
- finish({ opened: false, error: `browser launcher ${browser.command} exited with ${detail}` });
916
- });
917
- timer = setTimeout(() => {
918
- child.unref();
919
- finish({ opened: true });
920
- }, handoffTimeoutMs);
921
- timer.unref();
922
- });
923
- }
924
-
925
- // ../../packages/runtime/dist/apps.js
926
- function normalizeApp(input) {
927
- if (!input || typeof input !== "object")
928
- return null;
929
- const item = input;
930
- const id = typeof item.id === "string" ? item.id : null;
931
- const name = typeof item.name === "string" ? item.name : id;
932
- if (!id || !name)
933
- return null;
934
- const deployment = item.latestDeployment && typeof item.latestDeployment === "object" ? item.latestDeployment : null;
935
- const registryResult = SandboxAppActionRegistrySchema.safeParse(item.sandboxActionRegistry);
936
- return {
937
- id,
938
- name,
939
- description: typeof item.description === "string" ? item.description : null,
940
- visibility: typeof item.visibility === "string" ? item.visibility : null,
941
- gitOwner: typeof item.gitOwner === "string" ? item.gitOwner : null,
942
- gitRepo: typeof item.gitRepo === "string" ? item.gitRepo : null,
943
- gitHost: typeof item.gitHost === "string" ? item.gitHost : null,
944
- defaultBranch: typeof item.defaultBranch === "string" ? item.defaultBranch : null,
945
- sandbox: item.sandbox === true,
946
- sandboxActionRegistry: registryResult.success ? registryResult.data : null,
947
- sandboxManifestHash: typeof item.sandboxManifestHash === "string" ? item.sandboxManifestHash : null,
948
- sandboxManifestPath: typeof item.sandboxManifestPath === "string" ? item.sandboxManifestPath : null,
949
- sandboxManifestSyncedAt: typeof item.sandboxManifestSyncedAt === "string" ? item.sandboxManifestSyncedAt : item.sandboxManifestSyncedAt instanceof Date ? item.sandboxManifestSyncedAt.toISOString() : null,
950
- sandboxManifestError: typeof item.sandboxManifestError === "string" ? item.sandboxManifestError : null,
951
- updatedAt: typeof item.updatedAt === "string" ? item.updatedAt : null,
952
- latestDeployment: deployment ? {
953
- id: typeof deployment.id === "string" ? deployment.id : void 0,
954
- status: typeof deployment.status === "string" ? deployment.status : void 0,
955
- deploymentDomain: typeof deployment.deploymentDomain === "string" ? deployment.deploymentDomain : null,
956
- createdAt: typeof deployment.createdAt === "string" ? deployment.createdAt : void 0,
957
- isProduction: typeof deployment.isProduction === "boolean" ? deployment.isProduction : null,
958
- gitBranch: typeof deployment.gitBranch === "string" ? deployment.gitBranch : null
959
- } : null,
960
- scheduleSummary: normalizeScheduleSummary(item.scheduleSummary)
961
- };
962
- }
963
- function normalizeDateString(value) {
964
- if (typeof value === "string")
965
- return value;
966
- if (value instanceof Date)
967
- return value.toISOString();
968
- return null;
969
- }
970
- function normalizeSchedule(input) {
971
- if (!input || typeof input !== "object")
972
- return null;
973
- const item = input;
974
- const id = typeof item.id === "string" ? item.id : null;
975
- const name = typeof item.name === "string" ? item.name : id;
976
- const deploymentId = typeof item.deploymentId === "string" ? item.deploymentId : null;
977
- if (!id || !name || !deploymentId)
978
- return null;
979
- return {
980
- id,
981
- name,
982
- description: typeof item.description === "string" ? item.description : null,
983
- scheduleType: typeof item.scheduleType === "string" ? item.scheduleType : "cron",
984
- scheduleExpression: typeof item.scheduleExpression === "string" ? item.scheduleExpression : "",
985
- enabled: Boolean(item.enabled),
986
- rawEnabled: typeof item.rawEnabled === "boolean" ? item.rawEnabled : void 0,
987
- syncStatus: typeof item.syncStatus === "string" ? item.syncStatus : null,
988
- syncError: typeof item.syncError === "string" ? item.syncError : null,
989
- startAt: normalizeDateString(item.startAt),
990
- endAt: normalizeDateString(item.endAt),
991
- maxRuns: typeof item.maxRuns === "number" ? item.maxRuns : null,
992
- executionCount: typeof item.executionCount === "number" ? item.executionCount : null,
993
- lifecycleStatus: typeof item.lifecycleStatus === "string" ? item.lifecycleStatus : null,
994
- lifecycleReason: typeof item.lifecycleReason === "string" ? item.lifecycleReason : null,
995
- lastExecutionAt: normalizeDateString(item.lastExecutionAt),
996
- lastExecutionStatus: typeof item.lastExecutionStatus === "string" ? item.lastExecutionStatus : null,
997
- lastRunNowAt: normalizeDateString(item.lastRunNowAt),
998
- lastRunNowStatus: typeof item.lastRunNowStatus === "string" ? item.lastRunNowStatus : null,
999
- updatedAt: normalizeDateString(item.updatedAt) ?? (/* @__PURE__ */ new Date()).toISOString(),
1000
- deploymentId,
1001
- isProduction: typeof item.isProduction === "boolean" ? item.isProduction : void 0,
1002
- payload: item.payload
1003
- };
1004
- }
1005
- function normalizeScheduleSummary(input) {
1006
- if (!input || typeof input !== "object")
1007
- return null;
1008
- const item = input;
1009
- const schedules = Array.isArray(item.schedules) ? item.schedules.map(normalizeSchedule).filter((value) => Boolean(value)) : [];
1010
- const total = typeof item.total === "number" ? item.total : schedules.length;
1011
- const active = typeof item.active === "number" ? item.active : schedules.filter((schedule) => schedule.enabled).length;
1012
- const paused = typeof item.paused === "number" ? item.paused : Math.max(0, total - active);
1013
- return {
1014
- total,
1015
- active,
1016
- paused,
1017
- enabled: typeof item.enabled === "number" ? item.enabled : active,
1018
- disabled: typeof item.disabled === "number" ? item.disabled : paused,
1019
- nextRunAt: normalizeDateString(item.nextRunAt),
1020
- lastRunAt: normalizeDateString(item.lastRunAt),
1021
- schedules,
1022
- truncated: typeof item.truncated === "boolean" ? item.truncated : void 0
1023
- };
1024
- }
1025
- async function loadAccountProfileLookups(context) {
1026
- const accounts = Array.isArray(context.config.accounts) ? context.config.accounts : [];
1027
- const entries = await Promise.all(accounts.map(async (account) => {
1028
- const key = profileKey(account.handle, account.baseUrl);
1029
- const token = accountToken(account);
1030
- if (!token) {
1031
- return [
1032
- key,
1033
- { response: null, authFailed: false, error: null }
1034
- ];
1035
- }
1036
- try {
1037
- return [
1038
- key,
1039
- {
1040
- response: await getOpenPondAccount(resolvePublicApiBaseUrl(account, context.config), token),
1041
- authFailed: false,
1042
- error: null
1043
- }
1044
- ];
1045
- } catch (error) {
1046
- return [
1047
- key,
1048
- {
1049
- response: null,
1050
- authFailed: true,
1051
- error: errorMessage(error)
1052
- }
1053
- ];
1054
- }
1055
- }));
1056
- return Object.fromEntries(entries);
1057
- }
1058
- async function loadOpenPondAccountStateForContext(context) {
1059
- const accountProfiles = await loadAccountProfileLookups(context);
1060
- const activeLookup = context.account ? accountProfiles[profileKey(context.account.handle, context.account.baseUrl)] ?? null : null;
1061
- const accountResponse = activeLookup?.response ?? null;
1062
- const authError = context.token && activeLookup?.authFailed ? activeLookup.error || "OpenPond account authentication failed." : null;
1063
- return {
1064
- account: toAccountState({
1065
- ...context,
1066
- accountResponse,
1067
- accountProfiles,
1068
- authFailed: Boolean(authError),
1069
- error: authError
1070
- })
1071
- };
1072
- }
1073
- async function loadOpenPondAccountState() {
1074
- return loadOpenPondAccountStateForContext(await loadOpenPondAccountContext());
1075
- }
1076
- async function loadOpenPondApps(options = {}) {
1077
- const context = await loadOpenPondAccountContext();
1078
- const accountPromise = loadOpenPondAccountStateForContext(context);
1079
- if (!context.token) {
1080
- return {
1081
- ...await accountPromise,
1082
- apps: [],
1083
- error: "No OpenPond API key or session token is configured."
1084
- };
1085
- }
1086
- const [accountResult, appsResult] = await Promise.allSettled([
1087
- accountPromise,
1088
- listApps(context.apiBaseUrl, context.token, {
1089
- handle: context.account?.handle,
1090
- limit: options.limit ?? 20,
1091
- offset: options.offset ?? 0,
1092
- includeScheduled: options.includeScheduled ?? true
1093
- })
1094
- ]);
1095
- if (accountResult.status === "rejected")
1096
- throw accountResult.reason;
1097
- return {
1098
- account: accountResult.value.account,
1099
- apps: appsResult.status === "fulfilled" ? appsResult.value.map(normalizeApp).filter((value) => Boolean(value)) : [],
1100
- error: appsResult.status === "rejected" ? errorMessage(appsResult.reason) : null
1101
- };
1102
- }
1103
- async function createOpenPondRepoApp(input) {
1104
- const context = await loadOpenPondAccountContext();
1105
- if (!context.token) {
1106
- throw new Error("No OpenPond API key or session token is configured.");
1107
- }
1108
- return {
1109
- account: context,
1110
- response: await createRepo(context.apiBaseUrl, context.token, input)
1111
- };
1112
- }
1113
-
1114
- // ../../packages/runtime/dist/save-account.js
1115
- import { createHash } from "node:crypto";
1116
- function fallbackHandleForApiKey(apiKey) {
1117
- const digest = createHash("sha256").update(apiKey).digest("hex").slice(0, 8);
1118
- return `account-${digest}`;
1119
- }
1120
- function normalizeDerivedHandle(value) {
1121
- const trimmed = value?.trim();
1122
- if (!trimmed)
1123
- return null;
1124
- return trimmed.replace(/^@/, "");
1125
- }
1126
- async function deriveHandleForApiKey(input, apiBaseUrl) {
1127
- const explicit = normalizeDerivedHandle(input.handle);
1128
- if (explicit)
1129
- return explicit;
1130
- try {
1131
- const response = await getOpenPondAccount(apiBaseUrl, input.apiKey);
1132
- const account = response.account;
1133
- const fromProfile = normalizeDerivedHandle(account.handle) ?? normalizeDerivedHandle(account.email?.split("@")[0]) ?? normalizeDerivedHandle(account.id);
1134
- if (fromProfile)
1135
- return fromProfile;
1136
- } catch {
1137
- }
1138
- return fallbackHandleForApiKey(input.apiKey);
1139
- }
1140
- async function saveOpenPondAccount(input) {
1141
- const baseUrl = input.baseUrl ?? DEFAULT_OPENPOND_WEB_BASE_URL;
1142
- const apiBaseUrl = normalizeBaseUrl(input.apiBaseUrl) ?? mapUiBaseToApiBase(baseUrl) ?? DEFAULT_OPENPOND_API_BASE_URL;
1143
- const chatApiBaseUrl = normalizeBaseUrl(input.chatApiBaseUrl);
1144
- const handle = await deriveHandleForApiKey(input, apiBaseUrl);
1145
- await saveProfileApiKey({
1146
- handle,
1147
- apiKey: input.apiKey,
1148
- baseUrl,
1149
- apiBaseUrl,
1150
- chatApiBaseUrl,
1151
- environment: input.environment ?? "production",
1152
- setActive: input.setActive
1153
- });
1154
- return loadOpenPondAccountContext(handle, baseUrl);
1155
- }
1156
-
1157
- // ../../packages/runtime/dist/remove-account.js
1158
- function findAccountIndex(accounts, handle, baseUrl) {
1159
- const normalizedBaseUrl = normalizeBaseUrl(baseUrl);
1160
- const exactIndex = accounts.findIndex((account) => handleEquals(account.handle, handle) && baseUrlEquals(account.baseUrl, normalizedBaseUrl));
1161
- if (exactIndex !== -1)
1162
- return exactIndex;
1163
- const matchingIndexes = accounts.map((account, index) => ({ account, index })).filter(({ account }) => handleEquals(account.handle, handle));
1164
- if (matchingIndexes.length === 1)
1165
- return matchingIndexes[0].index;
1166
- if (matchingIndexes.length > 1) {
1167
- throw new Error(`Multiple OpenPond accounts match ${handle}; select one with its base URL.`);
1168
- }
1169
- return -1;
1170
- }
1171
- async function removeOpenPondAccount(input) {
1172
- const handle = input.handle.trim();
1173
- if (!handle)
1174
- throw new Error("OpenPond account handle is required.");
1175
- const config = await loadGlobalConfig();
1176
- const accounts = (config.accounts ?? []).map((account2) => ({ ...account2 }));
1177
- const index = findAccountIndex(accounts, handle, input.baseUrl);
1178
- if (index === -1)
1179
- throw new Error(`OpenPond account not found: ${handle}`);
1180
- const account = accounts[index];
1181
- const activeProfile = normalizeActiveProfile(config.activeProfile);
1182
- if (activeProfile && accountMatchesSelector(account, activeProfile)) {
1183
- throw new Error("Switch to another OpenPond account before removing the active account.");
1184
- }
1185
- accounts.splice(index, 1);
1186
- await saveConfig({ ...config, accounts });
1187
- return loadOpenPondAccountContext();
1188
- }
1189
-
1190
- // ../../packages/runtime/dist/sign-out-account.js
1191
- async function signOutOpenPondAccount() {
1192
- const config = await loadGlobalConfig();
1193
- const activeProfile = normalizeActiveProfile(config.activeProfile);
1194
- const accounts = (config.accounts ?? []).map((account) => ({ ...account }));
1195
- const activeIndex = activeProfile ? accounts.findIndex((account) => accountMatchesSelector(account, activeProfile)) : 0;
1196
- if (activeIndex < 0 || !accounts[activeIndex]) {
1197
- throw new Error("No active OpenPond account to log out.");
1198
- }
1199
- const signedOutAccount = { ...accounts[activeIndex] };
1200
- delete signedOutAccount.apiKey;
1201
- delete signedOutAccount.session;
1202
- accounts[activeIndex] = signedOutAccount;
1203
- await saveConfig({ ...config, accounts });
1204
- return loadOpenPondAccountContext(signedOutAccount.handle, signedOutAccount.baseUrl);
1205
- }
1206
-
1207
- // ../../packages/runtime/dist/update-account-config.js
1208
- function findAccountIndex2(accounts, handle, currentBaseUrl) {
1209
- const normalizedCurrentBaseUrl = normalizeBaseUrl(currentBaseUrl);
1210
- const exactIndex = accounts.findIndex((account) => handleEquals(account.handle, handle) && baseUrlEquals(account.baseUrl, normalizedCurrentBaseUrl));
1211
- if (exactIndex !== -1)
1212
- return exactIndex;
1213
- const sameHandle = accounts.map((account, index) => ({ account, index })).filter(({ account }) => handleEquals(account.handle, handle));
1214
- if (sameHandle.length === 1)
1215
- return sameHandle[0].index;
1216
- if (sameHandle.length > 1) {
1217
- throw new Error(`Multiple OpenPond accounts match ${handle}; select one with its current base URL.`);
1218
- }
1219
- return -1;
1220
- }
1221
- function applyOptionalUrl(account, key, value) {
1222
- if (value === void 0)
1223
- return;
1224
- const normalized = normalizeBaseUrl(value);
1225
- if (normalized) {
1226
- account[key] = normalized;
1227
- return;
1228
- }
1229
- if (value === null || value.trim() === "")
1230
- delete account[key];
1231
- }
1232
- async function updateOpenPondAccountConfig(input) {
1233
- const handle = input.handle.trim();
1234
- if (!handle)
1235
- throw new Error("OpenPond account handle is required.");
1236
- const config = await loadGlobalConfig();
1237
- const accounts = (config.accounts ?? []).map((account) => ({ ...account }));
1238
- const index = findAccountIndex2(accounts, handle, input.currentBaseUrl);
1239
- if (index === -1)
1240
- throw new Error(`OpenPond account not found: ${handle}`);
1241
- const previousAccount = accounts[index];
1242
- const nextAccount = { ...previousAccount };
1243
- applyOptionalUrl(nextAccount, "baseUrl", input.baseUrl);
1244
- applyOptionalUrl(nextAccount, "apiBaseUrl", input.apiBaseUrl);
1245
- applyOptionalUrl(nextAccount, "chatApiBaseUrl", input.chatApiBaseUrl);
1246
- if (input.environment === null) {
1247
- delete nextAccount.environment;
1248
- } else if (typeof input.environment === "string" && input.environment.trim()) {
1249
- nextAccount.environment = input.environment.trim();
1250
- }
1251
- const duplicateIndex = accounts.findIndex((account, candidateIndex) => candidateIndex !== index && handleEquals(account.handle, nextAccount.handle) && baseUrlEquals(account.baseUrl, nextAccount.baseUrl));
1252
- if (duplicateIndex !== -1) {
1253
- throw new Error("Another OpenPond account already uses that handle and base URL.");
1254
- }
1255
- const activeProfile = normalizeActiveProfile(config.activeProfile);
1256
- const wasActive = Boolean(activeProfile && accountMatchesSelector(previousAccount, activeProfile));
1257
- accounts[index] = nextAccount;
1258
- await saveConfig({
1259
- ...config,
1260
- accounts,
1261
- activeProfile: input.setActive || wasActive ? selectorFromAccount(nextAccount) : config.activeProfile
1262
- });
1263
- return loadOpenPondAccountContext(nextAccount.handle, nextAccount.baseUrl);
1264
- }
1265
-
1266
- // ../../packages/runtime/dist/actions.js
1267
- async function getOpenPondAppEnvironment(input) {
1268
- const context = await loadOpenPondAccountContext();
1269
- if (!context.token) {
1270
- throw new Error("OpenPond is signed out. Add an account before reading app config.");
1271
- }
1272
- return getAppEnvironment(context.apiBaseUrl, context.token, input.appId);
1273
- }
1274
-
1275
- // ../../packages/runtime/dist/ready-line-parser.js
1276
- function createReadyLineParser(prefix, onReady) {
1277
- let buffer = "";
1278
- const processLine = (line) => {
1279
- if (!line.startsWith(prefix))
1280
- return;
1281
- onReady(JSON.parse(line.slice(prefix.length)));
1282
- };
1283
- return {
1284
- push(chunk) {
1285
- buffer += chunk;
1286
- while (true) {
1287
- const lineEnd = nextLineEnd(buffer);
1288
- if (lineEnd < 0)
1289
- return;
1290
- const line = buffer.slice(0, lineEnd).replace(/\r$/, "");
1291
- const newlineLength = buffer[lineEnd] === "\r" && buffer[lineEnd + 1] === "\n" ? 2 : 1;
1292
- buffer = buffer.slice(lineEnd + newlineLength);
1293
- processLine(line);
1294
- }
1295
- },
1296
- flush() {
1297
- const line = buffer.trimEnd();
1298
- buffer = "";
1299
- if (line)
1300
- processLine(line);
1301
- }
1302
- };
1303
- }
1304
- function nextLineEnd(value) {
1305
- const lf = value.indexOf("\n");
1306
- const cr = value.indexOf("\r");
1307
- if (lf < 0)
1308
- return cr;
1309
- if (cr < 0)
1310
- return lf;
1311
- return Math.min(lf, cr);
1312
- }
1313
-
1314
- export {
1315
- loadOpenPondAccountContext,
1316
- switchOpenPondAccount,
1317
- loadOpenPondAccountState,
1318
- loadOpenPondApps,
1319
- createOpenPondRepoApp,
1320
- loadOpenPondHostedModels,
1321
- loadOpenPondProviderCatalog,
1322
- streamOpenPondHostedChatTurn,
1323
- saveOpenPondAccount,
1324
- removeOpenPondAccount,
1325
- signOutOpenPondAccount,
1326
- updateOpenPondAccountConfig,
1327
- getOpenPondAppEnvironment,
1328
- getBundledRuntimeVersion,
1329
- createReadyLineParser,
1330
- openUrlWithSystemBrowser
1331
- };