upfynai-code 3.0.4 → 3.2.0

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 (258) hide show
  1. package/README.md +69 -92
  2. package/bin/cli.js +191 -0
  3. package/dist/client/assets/AppContent-M14Au3SB.js +542 -0
  4. package/{client/dist/assets/BrowserPanel-0TLEl-IC.js → dist/client/assets/BrowserPanel-TFKm2NDJ.js} +2 -2
  5. package/dist/client/assets/DashboardPanel-C88HjsCh.js +1 -0
  6. package/dist/client/assets/FileTree-DvO1xnDE.js +1 -0
  7. package/{client/dist/assets/GitPanel-C_xFM-N2.js → dist/client/assets/GitPanel-D-slVlyy.js} +2 -2
  8. package/dist/client/assets/LoginModal-Chi4SYcr.js +21 -0
  9. package/{client/dist/assets/MarkdownPreview-CESjI261.js → dist/client/assets/MarkdownPreview-CuIix2u9.js} +1 -1
  10. package/dist/client/assets/MermaidBlock-Dq9uFv82.js +2 -0
  11. package/dist/client/assets/Onboarding-QYXx24dX.js +1 -0
  12. package/{client/dist/assets/PreviewPanel-CqCa92Tf.js → dist/client/assets/PreviewPanel-Dd8q-jo0.js} +1 -1
  13. package/dist/client/assets/SetupForm-CrspaUva.js +1 -0
  14. package/dist/client/assets/WorkflowsPanel-DIlYAdhB.js +1 -0
  15. package/dist/client/assets/index-CnNNzw9A.css +1 -0
  16. package/{client/dist/assets/index-HaY-3pK1.js → dist/client/assets/index-rUkK9FDP.js} +26 -26
  17. package/{client/dist/assets/vendor-codemirror-D2ALgpaX.js → dist/client/assets/vendor-codemirror-jc6nyJQg.js} +1 -1
  18. package/{client/dist/assets/vendor-diff-DNQpbhrT.js → dist/client/assets/vendor-diff-THJmAcEI.js} +1 -1
  19. package/{client/dist/assets/vendor-icons-GyYE35HP.js → dist/client/assets/vendor-icons-CfjIpdrD.js} +145 -155
  20. package/{client/dist/assets/vendor-markdown-CimbIo6Y.js → dist/client/assets/vendor-markdown-Cdm6NEGf.js} +1 -1
  21. package/dist/client/assets/vendor-mermaid-DTPaBx-U.js +2559 -0
  22. package/{client/dist/assets/vendor-react-96lCPsRK.js → dist/client/assets/vendor-react-wFkb6mSf.js} +1 -1
  23. package/{client/dist/assets/vendor-syntax-LS_Nt30I.js → dist/client/assets/vendor-syntax-C_UZR7tc.js} +1 -1
  24. package/dist/client/favicon.png +0 -0
  25. package/dist/client/icons/icon-128x128.png +0 -0
  26. package/dist/client/icons/icon-144x144.png +0 -0
  27. package/dist/client/icons/icon-152x152.png +0 -0
  28. package/dist/client/icons/icon-192x192.png +0 -0
  29. package/dist/client/icons/icon-384x384.png +0 -0
  30. package/dist/client/icons/icon-512x512.png +0 -0
  31. package/dist/client/icons/icon-72x72.png +0 -0
  32. package/dist/client/icons/icon-96x96.png +0 -0
  33. package/{client/dist → dist/client}/index.html +37 -36
  34. package/dist/client/logo-128.png +0 -0
  35. package/dist/client/logo-256.png +0 -0
  36. package/dist/client/logo-32.png +0 -0
  37. package/dist/client/logo-512.png +0 -0
  38. package/dist/client/logo-64.png +0 -0
  39. package/dist/client/logo.png +0 -0
  40. package/{client/dist → dist/client}/manifest.json +12 -12
  41. package/{client/dist → dist/client}/mcp-docs.html +1 -1
  42. package/{client/dist → dist/client}/sw.js +2 -2
  43. package/package.json +56 -105
  44. package/scripts/postinstall.js +9 -0
  45. package/scripts/prepublish.js +77 -0
  46. package/src/animation.js +228 -0
  47. package/src/auth.js +142 -0
  48. package/src/config.js +40 -0
  49. package/src/connect.js +416 -0
  50. package/src/launch.js +81 -0
  51. package/src/mcp.js +57 -0
  52. package/src/permissions.js +140 -0
  53. package/src/persistent-shell.js +261 -0
  54. package/src/server.js +54 -0
  55. package/client/dist/assets/AppContent-CwrTP6TW.js +0 -545
  56. package/client/dist/assets/CanvasFullScreen-D1GWQsGL.js +0 -1
  57. package/client/dist/assets/CanvasWorkspace-D7ORj358.js +0 -163
  58. package/client/dist/assets/DashboardPanel-BV7ybUDe.js +0 -1
  59. package/client/dist/assets/FileTree-5qfhBqdE.js +0 -1
  60. package/client/dist/assets/LoginModal-CImJHRjX.js +0 -13
  61. package/client/dist/assets/MermaidBlock-BFM21cwe.js +0 -2
  62. package/client/dist/assets/Onboarding-B3cteLu2.js +0 -1
  63. package/client/dist/assets/SetupForm-P6dsYgHO.js +0 -1
  64. package/client/dist/assets/WorkflowsPanel-CBoN80kc.js +0 -1
  65. package/client/dist/assets/index-46kkVu2i.css +0 -1
  66. package/client/dist/assets/pdf-CE_K4jFx.js +0 -12
  67. package/client/dist/assets/vendor-canvas-BZV40eAE.css +0 -1
  68. package/client/dist/assets/vendor-canvas-DvHJ_Pn2.js +0 -49
  69. package/client/dist/assets/vendor-mermaid-DucWyDEe.js +0 -2556
  70. package/client/dist/favicon.png +0 -0
  71. package/client/dist/icons/icon-128x128.png +0 -0
  72. package/client/dist/icons/icon-144x144.png +0 -0
  73. package/client/dist/icons/icon-152x152.png +0 -0
  74. package/client/dist/icons/icon-192x192.png +0 -0
  75. package/client/dist/icons/icon-384x384.png +0 -0
  76. package/client/dist/icons/icon-512x512.png +0 -0
  77. package/client/dist/icons/icon-72x72.png +0 -0
  78. package/client/dist/icons/icon-96x96.png +0 -0
  79. package/client/dist/logo-128.png +0 -0
  80. package/client/dist/logo-256.png +0 -0
  81. package/client/dist/logo-32.png +0 -0
  82. package/client/dist/logo-512.png +0 -0
  83. package/client/dist/logo-64.png +0 -0
  84. package/commands/upfynai-connect.md +0 -59
  85. package/commands/upfynai-disconnect.md +0 -31
  86. package/commands/upfynai-doctor.md +0 -99
  87. package/commands/upfynai-export.md +0 -49
  88. package/commands/upfynai-local.md +0 -82
  89. package/commands/upfynai-status.md +0 -75
  90. package/commands/upfynai-stop.md +0 -49
  91. package/commands/upfynai-uninstall.md +0 -58
  92. package/commands/upfynai.md +0 -69
  93. package/scripts/build-client.js +0 -17
  94. package/scripts/fix-node-pty.js +0 -67
  95. package/scripts/install-commands.js +0 -78
  96. package/server/agent-loop.js +0 -242
  97. package/server/auto-compact.js +0 -99
  98. package/server/browser.js +0 -131
  99. package/server/claude-sdk.js +0 -797
  100. package/server/cli-ui.js +0 -798
  101. package/server/cli.js +0 -751
  102. package/server/constants/config.js +0 -31
  103. package/server/cursor-cli.js +0 -270
  104. package/server/database/auth.db +0 -0
  105. package/server/database/db.js +0 -1547
  106. package/server/database/init.sql +0 -70
  107. package/server/index.js +0 -3813
  108. package/server/load-env.js +0 -26
  109. package/server/mcp-server.js +0 -621
  110. package/server/middleware/auth.js +0 -184
  111. package/server/middleware/relayHelpers.js +0 -44
  112. package/server/middleware/sandboxRouter.js +0 -174
  113. package/server/openai-codex.js +0 -403
  114. package/server/openrouter.js +0 -137
  115. package/server/projects.js +0 -1807
  116. package/server/provider-factory.js +0 -174
  117. package/server/relay-client.js +0 -390
  118. package/server/routes/agent.js +0 -1234
  119. package/server/routes/auth.js +0 -559
  120. package/server/routes/browser.js +0 -419
  121. package/server/routes/canvas.js +0 -53
  122. package/server/routes/cli-auth.js +0 -263
  123. package/server/routes/codex.js +0 -396
  124. package/server/routes/commands.js +0 -707
  125. package/server/routes/composio.js +0 -176
  126. package/server/routes/cursor.js +0 -770
  127. package/server/routes/dashboard.js +0 -295
  128. package/server/routes/git.js +0 -1208
  129. package/server/routes/keys.js +0 -34
  130. package/server/routes/mcp-utils.js +0 -48
  131. package/server/routes/mcp.js +0 -661
  132. package/server/routes/payments.js +0 -227
  133. package/server/routes/projects.js +0 -754
  134. package/server/routes/sessions.js +0 -146
  135. package/server/routes/settings.js +0 -261
  136. package/server/routes/taskmaster.js +0 -1928
  137. package/server/routes/user.js +0 -106
  138. package/server/routes/vapi-chat.js +0 -624
  139. package/server/routes/voice.js +0 -235
  140. package/server/routes/webhooks.js +0 -166
  141. package/server/routes/workflows.js +0 -312
  142. package/server/sandbox.js +0 -120
  143. package/server/services/browser-ai.js +0 -154
  144. package/server/services/composio.js +0 -204
  145. package/server/services/sessionRegistry.js +0 -139
  146. package/server/services/whisperService.js +0 -84
  147. package/server/services/workflowScheduler.js +0 -211
  148. package/server/tests/relay-flow.test.js +0 -570
  149. package/server/tests/sessions.test.js +0 -259
  150. package/server/utils/commandParser.js +0 -303
  151. package/server/utils/email.js +0 -66
  152. package/server/utils/gitConfig.js +0 -24
  153. package/server/utils/mcp-detector.js +0 -198
  154. package/server/utils/taskmaster-websocket.js +0 -129
  155. package/shared/integrationCatalog.d.ts +0 -12
  156. package/shared/integrationCatalog.js +0 -172
  157. package/shared/modelConstants.js +0 -96
  158. /package/{shared → dist}/agents/claude.js +0 -0
  159. /package/{shared → dist}/agents/codex.js +0 -0
  160. /package/{shared → dist}/agents/cursor.js +0 -0
  161. /package/{shared → dist}/agents/detect.js +0 -0
  162. /package/{shared → dist}/agents/exec.js +0 -0
  163. /package/{shared → dist}/agents/files.js +0 -0
  164. /package/{shared → dist}/agents/git.js +0 -0
  165. /package/{shared → dist}/agents/gitagent.js +0 -0
  166. /package/{shared → dist}/agents/index.js +0 -0
  167. /package/{shared → dist}/agents/shell.js +0 -0
  168. /package/{shared → dist}/agents/utils.js +0 -0
  169. /package/{client/dist → dist/client}/api-docs.html +0 -0
  170. /package/{client/dist → dist/client}/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  171. /package/{client/dist → dist/client}/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  172. /package/{client/dist → dist/client}/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  173. /package/{client/dist → dist/client}/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  174. /package/{client/dist → dist/client}/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  175. /package/{client/dist → dist/client}/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  176. /package/{client/dist → dist/client}/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  177. /package/{client/dist → dist/client}/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  178. /package/{client/dist → dist/client}/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  179. /package/{client/dist → dist/client}/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  180. /package/{client/dist → dist/client}/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  181. /package/{client/dist → dist/client}/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  182. /package/{client/dist → dist/client}/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  183. /package/{client/dist → dist/client}/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  184. /package/{client/dist → dist/client}/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  185. /package/{client/dist → dist/client}/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  186. /package/{client/dist → dist/client}/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  187. /package/{client/dist → dist/client}/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  188. /package/{client/dist → dist/client}/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  189. /package/{client/dist → dist/client}/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  190. /package/{client/dist → dist/client}/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  191. /package/{client/dist → dist/client}/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  192. /package/{client/dist → dist/client}/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  193. /package/{client/dist → dist/client}/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  194. /package/{client/dist → dist/client}/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  195. /package/{client/dist → dist/client}/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  196. /package/{client/dist → dist/client}/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  197. /package/{client/dist → dist/client}/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  198. /package/{client/dist → dist/client}/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  199. /package/{client/dist → dist/client}/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  200. /package/{client/dist → dist/client}/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  201. /package/{client/dist → dist/client}/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  202. /package/{client/dist → dist/client}/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  203. /package/{client/dist → dist/client}/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  204. /package/{client/dist → dist/client}/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  205. /package/{client/dist → dist/client}/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  206. /package/{client/dist → dist/client}/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  207. /package/{client/dist → dist/client}/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  208. /package/{client/dist → dist/client}/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  209. /package/{client/dist → dist/client}/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  210. /package/{client/dist → dist/client}/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  211. /package/{client/dist → dist/client}/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  212. /package/{client/dist → dist/client}/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  213. /package/{client/dist → dist/client}/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  214. /package/{client/dist → dist/client}/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  215. /package/{client/dist → dist/client}/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  216. /package/{client/dist → dist/client}/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  217. /package/{client/dist → dist/client}/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  218. /package/{client/dist → dist/client}/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  219. /package/{client/dist → dist/client}/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  220. /package/{client/dist → dist/client}/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  221. /package/{client/dist → dist/client}/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  222. /package/{client/dist → dist/client}/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  223. /package/{client/dist → dist/client}/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  224. /package/{client/dist → dist/client}/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  225. /package/{client/dist → dist/client}/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  226. /package/{client/dist → dist/client}/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  227. /package/{client/dist → dist/client}/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  228. /package/{client/dist → dist/client}/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  229. /package/{client/dist → dist/client}/assets/vendor-i18n-DCFGyhQR.js +0 -0
  230. /package/{client/dist → dist/client}/assets/vendor-xterm-CZq1hqo1.js +0 -0
  231. /package/{client/dist → dist/client}/assets/vendor-xterm-qxJ8_QYu.css +0 -0
  232. /package/{client/dist → dist/client}/clear-cache.html +0 -0
  233. /package/{client/dist → dist/client}/convert-icons.md +0 -0
  234. /package/{client/dist → dist/client}/favicon.svg +0 -0
  235. /package/{client/dist → dist/client}/generate-icons.js +0 -0
  236. /package/{client/dist → dist/client}/icons/claude-ai-icon.svg +0 -0
  237. /package/{client/dist → dist/client}/icons/codex-white.svg +0 -0
  238. /package/{client/dist → dist/client}/icons/codex.svg +0 -0
  239. /package/{client/dist → dist/client}/icons/cursor-white.svg +0 -0
  240. /package/{client/dist → dist/client}/icons/cursor.svg +0 -0
  241. /package/{client/dist → dist/client}/icons/icon-128x128.svg +0 -0
  242. /package/{client/dist → dist/client}/icons/icon-144x144.svg +0 -0
  243. /package/{client/dist → dist/client}/icons/icon-152x152.svg +0 -0
  244. /package/{client/dist → dist/client}/icons/icon-192x192.svg +0 -0
  245. /package/{client/dist → dist/client}/icons/icon-384x384.svg +0 -0
  246. /package/{client/dist → dist/client}/icons/icon-512x512.svg +0 -0
  247. /package/{client/dist → dist/client}/icons/icon-72x72.svg +0 -0
  248. /package/{client/dist → dist/client}/icons/icon-96x96.svg +0 -0
  249. /package/{client/dist → dist/client}/icons/icon-template.svg +0 -0
  250. /package/{client/dist → dist/client}/logo.svg +0 -0
  251. /package/{client/dist → dist/client}/offline.html +0 -0
  252. /package/{client/dist → dist/client}/screenshots/cli-selection.png +0 -0
  253. /package/{client/dist → dist/client}/screenshots/desktop-main.png +0 -0
  254. /package/{client/dist → dist/client}/screenshots/mobile-chat.png +0 -0
  255. /package/{client/dist → dist/client}/screenshots/tools-modal.png +0 -0
  256. /package/{shared → dist}/gitagent/index.js +0 -0
  257. /package/{shared → dist}/gitagent/parser.js +0 -0
  258. /package/{shared → dist}/gitagent/prompt-builder.js +0 -0
@@ -1,174 +0,0 @@
1
- /**
2
- * Multi-Provider Factory
3
- * Ported from opencode-ai/opencode internal/llm/provider/provider.go
4
- *
5
- * Unified interface for all AI providers. Most providers reuse the
6
- * OpenAI-compatible client with different base URLs (opencode pattern).
7
- * Only Anthropic and Google need native SDKs.
8
- *
9
- * This factory abstracts provider differences so the caller only
10
- * needs to call streamChat(messages, options) regardless of provider.
11
- */
12
-
13
- // OpenAI-compatible endpoints (opencode pattern: one client, many providers)
14
- const OPENAI_COMPATIBLE_PROVIDERS = {
15
- openrouter: {
16
- baseUrl: 'https://openrouter.ai/api/v1',
17
- keyEnv: 'OPENROUTER_API_KEY',
18
- extraHeaders: (model) => ({
19
- 'HTTP-Referer': 'https://cli.upfyn.com',
20
- 'X-Title': 'Upfyn-Code',
21
- }),
22
- },
23
- groq: {
24
- baseUrl: 'https://api.groq.com/openai/v1',
25
- keyEnv: 'GROQ_API_KEY',
26
- },
27
- deepseek: {
28
- baseUrl: 'https://api.deepseek.com/v1',
29
- keyEnv: 'DEEPSEEK_API_KEY',
30
- },
31
- xai: {
32
- baseUrl: 'https://api.x.ai/v1',
33
- keyEnv: 'XAI_API_KEY',
34
- },
35
- openai: {
36
- baseUrl: 'https://api.openai.com/v1',
37
- keyEnv: 'OPENAI_API_KEY',
38
- },
39
- };
40
-
41
- // Cost per 1M tokens (opencode pattern: models.go cost tables)
42
- const MODEL_COSTS = {
43
- 'anthropic/claude-sonnet-4': { input: 3.0, output: 15.0 },
44
- 'anthropic/claude-opus-4': { input: 15.0, output: 75.0 },
45
- 'openai/gpt-4o': { input: 2.5, output: 10.0 },
46
- 'openai/gpt-4o-mini': { input: 0.15, output: 0.6 },
47
- 'openai/o3': { input: 10.0, output: 40.0 },
48
- 'google/gemini-2.5-pro': { input: 1.25, output: 10.0 },
49
- 'deepseek/deepseek-r1': { input: 0.55, output: 2.19 },
50
- 'meta-llama/llama-4-maverick': { input: 0.5, output: 0.7 },
51
- };
52
-
53
- /**
54
- * Detect which provider to use based on model name.
55
- * @param {string} model - Model name (e.g., 'anthropic/claude-sonnet-4')
56
- * @returns {string} Provider name
57
- */
58
- export function detectProvider(model) {
59
- if (!model) return 'openrouter';
60
- if (model.startsWith('anthropic/')) return 'openrouter'; // route through OpenRouter for BYOK
61
- if (model.startsWith('openai/')) return 'openrouter';
62
- if (model.startsWith('google/')) return 'openrouter';
63
- if (model.startsWith('meta-llama/')) return 'openrouter';
64
- if (model.startsWith('deepseek/')) return 'openrouter';
65
- if (model.startsWith('mistralai/')) return 'openrouter';
66
- // Direct provider keys
67
- if (model.startsWith('gpt-')) return 'openai';
68
- if (model.startsWith('claude-')) return 'anthropic';
69
- return 'openrouter';
70
- }
71
-
72
- /**
73
- * Create a streaming chat request to any provider.
74
- * Uses the OpenAI-compatible API for most providers (opencode pattern).
75
- *
76
- * @param {string} model - Model name
77
- * @param {Array} messages - Array of { role, content }
78
- * @param {object} options - { apiKey, temperature, maxTokens }
79
- * @returns {AsyncGenerator} Yields { type, content, usage } events
80
- */
81
- export async function* streamChat(model, messages, options = {}) {
82
- const provider = detectProvider(model);
83
- const config = OPENAI_COMPATIBLE_PROVIDERS[provider];
84
-
85
- if (!config) {
86
- throw new Error(`Unsupported provider: ${provider}`);
87
- }
88
-
89
- const apiKey = options.apiKey || process.env[config.keyEnv];
90
- if (!apiKey) {
91
- throw new Error(`API key required for ${provider}. Set ${config.keyEnv} or provide via BYOK settings.`);
92
- }
93
-
94
- const headers = {
95
- 'Content-Type': 'application/json',
96
- 'Authorization': `Bearer ${apiKey}`,
97
- ...(config.extraHeaders ? config.extraHeaders(model) : {}),
98
- };
99
-
100
- const body = {
101
- model,
102
- messages,
103
- stream: true,
104
- ...(options.temperature !== undefined && { temperature: options.temperature }),
105
- ...(options.maxTokens && { max_tokens: options.maxTokens }),
106
- };
107
-
108
- const response = await fetch(`${config.baseUrl}/chat/completions`, {
109
- method: 'POST',
110
- headers,
111
- body: JSON.stringify(body),
112
- });
113
-
114
- if (!response.ok) {
115
- const errorText = await response.text();
116
- throw new Error(`${provider} API error (${response.status}): ${errorText}`);
117
- }
118
-
119
- // Parse SSE stream
120
- const reader = response.body.getReader();
121
- const decoder = new TextDecoder();
122
- let buffer = '';
123
-
124
- while (true) {
125
- const { done, value } = await reader.read();
126
- if (done) break;
127
-
128
- buffer += decoder.decode(value, { stream: true });
129
- const lines = buffer.split('\n');
130
- buffer = lines.pop();
131
-
132
- for (const line of lines) {
133
- if (!line.startsWith('data: ')) continue;
134
- const data = line.slice(6).trim();
135
- if (data === '[DONE]') {
136
- yield { type: 'complete' };
137
- return;
138
- }
139
-
140
- try {
141
- const parsed = JSON.parse(data);
142
- const delta = parsed.choices?.[0]?.delta;
143
-
144
- if (delta?.content) {
145
- yield { type: 'content_delta', content: delta.content };
146
- }
147
-
148
- // Usage info (if provided at the end)
149
- if (parsed.usage) {
150
- yield {
151
- type: 'usage',
152
- promptTokens: parsed.usage.prompt_tokens || 0,
153
- completionTokens: parsed.usage.completion_tokens || 0,
154
- };
155
- }
156
- } catch {
157
- // Skip malformed SSE chunks
158
- }
159
- }
160
- }
161
- }
162
-
163
- /**
164
- * Calculate cost for a request.
165
- * @param {string} model - Model name
166
- * @param {number} promptTokens
167
- * @param {number} completionTokens
168
- * @returns {number} Cost in cents
169
- */
170
- export function calculateCost(model, promptTokens, completionTokens) {
171
- const costs = MODEL_COSTS[model];
172
- if (!costs) return 0;
173
- return (promptTokens / 1_000_000 * costs.input + completionTokens / 1_000_000 * costs.output) * 100;
174
- }
@@ -1,390 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Upfyn-Code Relay Client
4
- *
5
- * Connects your local machine to the hosted Upfyn-Code server.
6
- * Bridges Claude CLI, terminal, filesystem, and git to the web UI.
7
- *
8
- * Usage:
9
- * upfynai-code connect --server https://upfynai.thinqmesh.com --key upfyn_xxx
10
- * upfynai-code connect (uses saved config from ~/.upfynai/config.json)
11
- */
12
-
13
- import WebSocket from 'ws';
14
- import os from 'os';
15
- import fs from 'fs';
16
- import path from 'path';
17
- import { execSync } from 'child_process';
18
- import {
19
- c,
20
- showConnectStartup,
21
- showConnectionBanner,
22
- logRelayEvent,
23
- createSpinner,
24
- } from './cli-ui.js';
25
- import { executeAction, isStreamingAction } from '../shared/agents/index.js';
26
-
27
- // Load package.json for version
28
- import { fileURLToPath } from 'url';
29
- const __filename_rc = fileURLToPath(import.meta.url);
30
- const __dirname_rc = path.dirname(__filename_rc);
31
- let VERSION = '0.0.0';
32
- try {
33
- const pkg = JSON.parse(fs.readFileSync(path.join(__dirname_rc, '../package.json'), 'utf8'));
34
- VERSION = pkg.version;
35
- } catch { /* ignore */ }
36
-
37
- const CONFIG_DIR = path.join(os.homedir(), '.upfynai');
38
- const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
39
- const CLOUD_SERVER = 'https://upfynai-code-production.up.railway.app';
40
-
41
- /** Mask internal server URL for display */
42
- function displayUrl(url) {
43
- if (!url || url === CLOUD_SERVER) return 'Upfyn Cloud (cli.upfyn.com)';
44
- try { return new URL(url).host; } catch { return url; }
45
- }
46
-
47
- function loadConfig() {
48
- try {
49
- if (fs.existsSync(CONFIG_FILE)) {
50
- return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
51
- }
52
- } catch (e) { /* ignore */ }
53
- return {};
54
- }
55
-
56
- function saveConfig(config) {
57
- if (!fs.existsSync(CONFIG_DIR)) {
58
- fs.mkdirSync(CONFIG_DIR, { recursive: true });
59
- }
60
- fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
61
- }
62
-
63
- /**
64
- * Resolve a binary name to its full path, checking PATH first then local node_modules/.bin
65
- */
66
- function resolveBinary(name) {
67
- const isWindows = process.platform === 'win32';
68
- try {
69
- const result = execSync(`${isWindows ? 'where' : 'which'} ${name}`, { stdio: 'pipe', timeout: 5000 }).toString().trim();
70
- return result.split('\n')[0].trim();
71
- } catch {
72
- const localPath = path.join(__dirname_rc, '../node_modules/.bin', name + (isWindows ? '.cmd' : ''));
73
- if (fs.existsSync(localPath)) return localPath;
74
- return name;
75
- }
76
- }
77
-
78
- /**
79
- * Detect which AI CLI agents are installed on this machine.
80
- * Used for initial agent-capabilities report (separate from the shared detect agent
81
- * which returns a different format via relay-response).
82
- */
83
- function detectInstalledAgents() {
84
- const isWindows = process.platform === 'win32';
85
- const whichCmd = isWindows ? 'where' : 'which';
86
- const localBinDir = path.join(__dirname_rc, '../node_modules/.bin');
87
-
88
- const agentDefs = [
89
- { name: 'claude', binary: 'claude', label: 'Claude Code' },
90
- { name: 'codex', binary: 'codex', label: 'OpenAI Codex' },
91
- { name: 'cursor', binary: 'cursor-agent', label: 'Cursor Agent' },
92
- ];
93
-
94
- const detected = {};
95
- for (const agent of agentDefs) {
96
- try {
97
- const result = execSync(`${whichCmd} ${agent.binary}`, { stdio: 'pipe', timeout: 5000 }).toString().trim();
98
- detected[agent.name] = { installed: true, path: result.split('\n')[0].trim(), label: agent.label };
99
- } catch {
100
- const localPath = path.join(localBinDir, agent.binary + (isWindows ? '.cmd' : ''));
101
- if (fs.existsSync(localPath)) {
102
- detected[agent.name] = { installed: true, path: localPath, label: agent.label };
103
- } else {
104
- detected[agent.name] = { installed: false, label: agent.label };
105
- }
106
- }
107
- }
108
- return detected;
109
- }
110
-
111
- /**
112
- * Build execution context for shared agents.
113
- */
114
- function buildAgentContext(requestId, ws) {
115
- return {
116
- requestId,
117
- streamMode: 'simple',
118
- resolveBinary,
119
- localBinDir: path.join(__dirname_rc, '../node_modules/.bin'),
120
- stream: (data) => {
121
- ws.send(JSON.stringify({ type: 'relay-stream', requestId, data }));
122
- },
123
- };
124
- }
125
-
126
- /**
127
- * Handle incoming relay commands from the server.
128
- * Delegates to shared agent modules.
129
- */
130
- async function handleRelayCommand(data, ws) {
131
- const { requestId, action } = data;
132
-
133
- try {
134
- const ctx = buildAgentContext(requestId, ws);
135
-
136
- if (isStreamingAction(action)) {
137
- logRelayEvent('>', `${action}: ${(data.command || '').slice(0, 60)}...`, 'cyan');
138
- const result = await executeAction(action, data, ctx);
139
- ws.send(JSON.stringify({ type: 'relay-complete', requestId, exitCode: result.exitCode }));
140
- } else {
141
- if (action === 'shell-command') logRelayEvent('$', `Shell: ${(data.command || '').slice(0, 50)}`, 'dim');
142
- else if (action === 'file-read') logRelayEvent('R', `Read: ${data.filePath}`, 'dim');
143
- else if (action === 'file-write') logRelayEvent('W', `Write: ${data.filePath}`, 'dim');
144
- else if (action === 'git-operation') logRelayEvent('G', `Git: ${data.gitCommand}`, 'dim');
145
- else if (action === 'exec') logRelayEvent('$', `Exec: ${(data.command || '').slice(0, 50)}`, 'dim');
146
-
147
- const result = await executeAction(action, data, ctx);
148
- ws.send(JSON.stringify({ type: 'relay-response', requestId, data: result }));
149
- }
150
- } catch (err) {
151
- ws.send(JSON.stringify({ type: 'relay-response', requestId, error: err.message }));
152
- }
153
- }
154
-
155
- /**
156
- * Create WebSocket connection with optional API key in handshake
157
- */
158
- function createRelayConnection(wsUrl, config = {}) {
159
- const headers = {};
160
- if (config.anthropicApiKey) headers['x-anthropic-api-key'] = config.anthropicApiKey;
161
- headers['x-upfyn-version'] = VERSION;
162
- headers['x-upfyn-machine'] = os.hostname();
163
- headers['x-upfyn-platform'] = process.platform;
164
- headers['x-upfyn-cwd'] = process.cwd();
165
- return new WebSocket(wsUrl, { headers });
166
- }
167
-
168
- /**
169
- * Main connect function (interactive — with animation and logging)
170
- */
171
- export async function connectToServer(options = {}) {
172
- const config = loadConfig();
173
- const serverUrl = options.server || config.server || CLOUD_SERVER;
174
- const relayKey = options.key || config.relayKey;
175
-
176
- if (!relayKey) {
177
- console.log('');
178
- console.log(` ${c.red('FAIL')} No relay key provided.`);
179
- console.log('');
180
- console.log(` ${c.gray('Get your relay token from the web UI:')}`);
181
- console.log(` ${c.dim('1.')} Sign in at ${c.cyan('https://cli.upfyn.com')}`);
182
- console.log(` ${c.dim('2.')} Click ${c.bright('Connect')} button`);
183
- console.log(` ${c.dim('3.')} Copy the command and run it here`);
184
- console.log('');
185
- console.log(` ${c.gray('Or run:')} ${c.bright('uc connect --server <url> --key upfyn_your_token')}`);
186
- console.log('');
187
- process.exit(1);
188
- }
189
-
190
- saveConfig({ ...config, server: serverUrl, relayKey });
191
-
192
- await showConnectStartup(displayUrl(serverUrl), os.hostname(), os.userInfo().username, VERSION);
193
-
194
- const wsUrl = serverUrl.replace(/^http/, 'ws') + '/relay?token=' + encodeURIComponent(relayKey);
195
-
196
- const spinner = createSpinner('Connecting to server...');
197
- spinner.start();
198
-
199
- let reconnectAttempts = 0;
200
- const MAX_RECONNECT = 10;
201
- let lastPongTime = Date.now();
202
-
203
- function connect() {
204
- const ws = createRelayConnection(wsUrl, config);
205
- lastPongTime = Date.now();
206
-
207
- ws.on('open', () => {
208
- reconnectAttempts = 0;
209
- lastPongTime = Date.now();
210
- });
211
-
212
- ws.on('message', (rawMessage) => {
213
- try {
214
- const data = JSON.parse(rawMessage);
215
-
216
- if (data.type === 'relay-connected') {
217
- spinner.stop('Connected!');
218
- const nameMatch = data.message?.match(/Connected as (.+?)\./);
219
- const username = nameMatch ? nameMatch[1] : 'Unknown';
220
- showConnectionBanner(username, displayUrl(serverUrl));
221
-
222
- const agents = detectInstalledAgents();
223
- const installed = Object.entries(agents)
224
- .filter(([, info]) => info.installed)
225
- .map(([name, info]) => info.label);
226
- const missing = Object.entries(agents)
227
- .filter(([, info]) => !info.installed)
228
- .map(([name, info]) => info.label);
229
-
230
- if (installed.length > 0) logRelayEvent('+', `Agents found: ${installed.join(', ')}`, 'green');
231
- if (missing.length > 0) logRelayEvent('~', `Not found: ${missing.join(', ')} (install to enable)`, 'yellow');
232
-
233
- ws.send(JSON.stringify({
234
- type: 'agent-capabilities',
235
- agents,
236
- machine: { hostname: os.hostname(), platform: process.platform, cwd: process.cwd() },
237
- }));
238
-
239
- logRelayEvent('*', 'Relay active -- waiting for commands...', 'green');
240
- return;
241
- }
242
-
243
- if (data.type === 'relay-command') {
244
- handleRelayCommand(data, ws);
245
- return;
246
- }
247
-
248
- if (data.type === 'pong' || data.type === 'server-ping') {
249
- lastPongTime = Date.now();
250
- if (data.type === 'server-ping') ws.send(JSON.stringify({ type: 'ping' }));
251
- return;
252
- }
253
-
254
- if (data.type === 'error') {
255
- spinner.fail(`Server error: ${data.error}`);
256
- return;
257
- }
258
- } catch (e) {
259
- logRelayEvent('!', `Parse error: ${e.message}`, 'red');
260
- }
261
- });
262
-
263
- ws.on('close', (code) => {
264
- if (code === 1000) {
265
- logRelayEvent('-', 'Disconnected gracefully.', 'dim');
266
- process.exit(0);
267
- }
268
- reconnectAttempts++;
269
- if (reconnectAttempts <= MAX_RECONNECT) {
270
- const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
271
- logRelayEvent('~', `Connection lost. Reconnecting in ${delay / 1000}s... (${reconnectAttempts}/${MAX_RECONNECT})`, 'yellow');
272
- setTimeout(connect, delay);
273
- } else {
274
- logRelayEvent('X', 'Max reconnection attempts reached. Exiting.', 'red');
275
- process.exit(1);
276
- }
277
- });
278
-
279
- ws.on('error', (err) => {
280
- if (err.code === 'ECONNREFUSED') {
281
- spinner.fail(`Cannot reach ${displayUrl(serverUrl)}. Is the server running?`);
282
- } else if (err.message?.includes('401') || err.message?.includes('Unauthorized')) {
283
- spinner.fail('Authentication failed (401). Your relay token may be invalid or expired.');
284
- logRelayEvent('!', 'Get a new token from Settings > Keys & Connect at: https://cli.upfyn.com', 'yellow');
285
- logRelayEvent('!', 'Then run: uc connect --key <new_token>', 'yellow');
286
- } else if (err.message?.includes('403') || err.message?.includes('Forbidden')) {
287
- spinner.fail('Access forbidden (403). Your account may be inactive or subscription expired.');
288
- } else if (err.message?.includes('504') || err.message?.includes('timeout')) {
289
- spinner.fail('Server auth timed out. The server may be overloaded — retrying...');
290
- } else if (err.code === 'ENOTFOUND' || err.code === 'EAI_AGAIN') {
291
- spinner.fail('DNS resolution failed. Check your internet connection.');
292
- } else {
293
- logRelayEvent('!', `WebSocket error: ${err.message || err.code || 'unknown'}`, 'red');
294
- }
295
- });
296
-
297
- const heartbeat = setInterval(() => {
298
- if (ws.readyState !== 1) { clearInterval(heartbeat); return; }
299
- if (Date.now() - lastPongTime > 75000) {
300
- clearInterval(heartbeat);
301
- logRelayEvent('!', 'No heartbeat response — connection stale, reconnecting...', 'yellow');
302
- ws.terminate();
303
- return;
304
- }
305
- ws.send(JSON.stringify({ type: 'ping' }));
306
- }, 30000);
307
-
308
- ws.on('close', () => clearInterval(heartbeat));
309
- ws.on('error', () => clearInterval(heartbeat));
310
- }
311
-
312
- connect();
313
-
314
- process.on('SIGINT', () => {
315
- console.log('');
316
- logRelayEvent('-', 'Disconnecting...', 'dim');
317
- process.exit(0);
318
- });
319
- }
320
-
321
- /**
322
- * Background connect function (silent — used when uc launches Claude Code)
323
- */
324
- export function connectToServerBackground(options = {}) {
325
- const config = loadConfig();
326
- const serverUrl = options.server || config.server;
327
- const relayKey = options.key || config.relayKey;
328
-
329
- if (!serverUrl || !relayKey) return;
330
-
331
- const wsUrl = serverUrl.replace(/^http/, 'ws') + '/relay?token=' + encodeURIComponent(relayKey);
332
-
333
- let reconnectAttempts = 0;
334
- const MAX_RECONNECT = 5;
335
- let lastPongTime = Date.now();
336
-
337
- function connect() {
338
- const ws = createRelayConnection(wsUrl, config);
339
- lastPongTime = Date.now();
340
-
341
- ws.on('message', (rawMessage) => {
342
- try {
343
- const data = JSON.parse(rawMessage);
344
- if (data.type === 'relay-connected') {
345
- // Detect installed agents and report to server (same as interactive connect)
346
- const agents = detectInstalledAgents();
347
- ws.send(JSON.stringify({
348
- type: 'agent-capabilities',
349
- agents,
350
- machine: { hostname: os.hostname(), platform: process.platform, cwd: process.cwd() },
351
- }));
352
- return;
353
- }
354
- if (data.type === 'pong' || data.type === 'server-ping') {
355
- lastPongTime = Date.now();
356
- if (data.type === 'server-ping') ws.send(JSON.stringify({ type: 'ping' }));
357
- return;
358
- }
359
- if (data.type === 'relay-command') {
360
- handleRelayCommand(data, ws);
361
- }
362
- } catch { /* ignore */ }
363
- });
364
-
365
- ws.on('open', () => {
366
- reconnectAttempts = 0;
367
- lastPongTime = Date.now();
368
- });
369
-
370
- ws.on('close', (code) => {
371
- clearInterval(heartbeat);
372
- if (code === 1000) return;
373
- reconnectAttempts++;
374
- if (reconnectAttempts <= MAX_RECONNECT) {
375
- const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
376
- setTimeout(connect, delay);
377
- }
378
- });
379
-
380
- ws.on('error', () => { clearInterval(heartbeat); });
381
-
382
- const heartbeat = setInterval(() => {
383
- if (ws.readyState !== 1) { clearInterval(heartbeat); return; }
384
- if (Date.now() - lastPongTime > 75000) { clearInterval(heartbeat); ws.terminate(); return; }
385
- ws.send(JSON.stringify({ type: 'ping' }));
386
- }, 30000);
387
- }
388
-
389
- connect();
390
- }