upfynai-code 2.9.0 → 2.9.2

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 (229) hide show
  1. package/README.md +91 -66
  2. package/client/dist/api-docs.html +838 -0
  3. package/client/dist/assets/AppContent-BXZDeSIC.js +545 -0
  4. package/client/dist/assets/CanvasFullScreen-mnpCnLZ9.js +1 -0
  5. package/client/dist/assets/CanvasWorkspace-4CqmjAVQ.js +163 -0
  6. package/client/dist/assets/DashboardPanel-zFIFlw56.js +1 -0
  7. package/client/dist/assets/FileTree-B0c_GaB3.js +1 -0
  8. package/client/dist/assets/GitPanel-DUP4zVU4.js +2 -0
  9. package/client/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  10. package/client/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  11. package/client/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  12. package/client/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  13. package/client/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  14. package/client/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  15. package/client/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  16. package/client/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  17. package/client/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  18. package/client/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  19. package/client/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  20. package/client/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  21. package/client/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  22. package/client/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  23. package/client/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  24. package/client/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  25. package/client/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  26. package/client/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  27. package/client/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  28. package/client/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  29. package/client/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  30. package/client/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  31. package/client/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  32. package/client/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  33. package/client/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  34. package/client/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  35. package/client/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  36. package/client/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  37. package/client/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  38. package/client/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  39. package/client/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  40. package/client/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  41. package/client/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  42. package/client/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  43. package/client/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  44. package/client/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  45. package/client/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  46. package/client/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  47. package/client/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  48. package/client/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  49. package/client/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  50. package/client/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  51. package/client/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  52. package/client/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  53. package/client/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  54. package/client/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  55. package/client/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  56. package/client/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  57. package/client/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  58. package/client/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  59. package/client/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  60. package/client/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  61. package/client/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  62. package/client/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  63. package/client/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  64. package/client/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  65. package/client/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  66. package/client/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  67. package/client/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  68. package/client/dist/assets/LoginModal-BRycfsyD.js +13 -0
  69. package/client/dist/assets/MarkdownPreview-DHmk3qzu.js +1 -0
  70. package/client/dist/assets/MermaidBlock-BuBc_G-F.js +2 -0
  71. package/client/dist/assets/Onboarding-BcnaZZ0o.js +1 -0
  72. package/client/dist/assets/PreviewPanel-CqCa92Tf.js +32 -0
  73. package/client/dist/assets/SetupForm-S0g6u5yT.js +1 -0
  74. package/client/dist/assets/WorkflowsPanel-CouH9JDO.js +1 -0
  75. package/client/dist/assets/index-BFuqS0tY.css +1 -0
  76. package/client/dist/assets/index-CNDcVl2g.js +68 -0
  77. package/client/dist/assets/pdf-CE_K4jFx.js +12 -0
  78. package/client/dist/assets/vendor-canvas-BZV40eAE.css +1 -0
  79. package/client/dist/assets/vendor-canvas-D39yWul6.js +49 -0
  80. package/client/dist/assets/vendor-codemirror-CbtmxxaB.js +35 -0
  81. package/client/dist/assets/vendor-diff-DNQpbhrT.js +69 -0
  82. package/client/dist/assets/vendor-i18n-DCFGyhQR.js +1 -0
  83. package/client/dist/assets/vendor-icons-BaD0x9SL.js +711 -0
  84. package/client/dist/assets/vendor-markdown-CimbIo6Y.js +296 -0
  85. package/client/dist/assets/vendor-mermaid-CH7SGc99.js +2556 -0
  86. package/client/dist/assets/vendor-react-96lCPsRK.js +67 -0
  87. package/client/dist/assets/vendor-syntax-DuHI9Ok6.js +16 -0
  88. package/client/dist/assets/vendor-xterm-CZq1hqo1.js +66 -0
  89. package/client/dist/assets/vendor-xterm-qxJ8_QYu.css +32 -0
  90. package/client/dist/clear-cache.html +85 -0
  91. package/client/dist/convert-icons.md +53 -0
  92. package/client/dist/favicon.png +0 -0
  93. package/client/dist/favicon.svg +5 -0
  94. package/client/dist/generate-icons.js +49 -0
  95. package/client/dist/icons/claude-ai-icon.svg +1 -0
  96. package/client/dist/icons/codex-white.svg +3 -0
  97. package/client/dist/icons/codex.svg +3 -0
  98. package/client/dist/icons/cursor-white.svg +12 -0
  99. package/client/dist/icons/cursor.svg +1 -0
  100. package/client/dist/icons/icon-128x128.png +0 -0
  101. package/client/dist/icons/icon-128x128.svg +5 -0
  102. package/client/dist/icons/icon-144x144.png +0 -0
  103. package/client/dist/icons/icon-144x144.svg +5 -0
  104. package/client/dist/icons/icon-152x152.png +0 -0
  105. package/client/dist/icons/icon-152x152.svg +5 -0
  106. package/client/dist/icons/icon-192x192.png +0 -0
  107. package/client/dist/icons/icon-192x192.svg +5 -0
  108. package/client/dist/icons/icon-384x384.png +0 -0
  109. package/client/dist/icons/icon-384x384.svg +5 -0
  110. package/client/dist/icons/icon-512x512.png +0 -0
  111. package/client/dist/icons/icon-512x512.svg +5 -0
  112. package/client/dist/icons/icon-72x72.png +0 -0
  113. package/client/dist/icons/icon-72x72.svg +5 -0
  114. package/client/dist/icons/icon-96x96.png +0 -0
  115. package/client/dist/icons/icon-96x96.svg +5 -0
  116. package/client/dist/icons/icon-template.svg +5 -0
  117. package/client/dist/index.html +119 -0
  118. package/client/dist/logo-128.png +0 -0
  119. package/client/dist/logo-256.png +0 -0
  120. package/client/dist/logo-32.png +0 -0
  121. package/client/dist/logo-512.png +0 -0
  122. package/client/dist/logo-64.png +0 -0
  123. package/client/dist/logo.svg +14 -0
  124. package/client/dist/manifest.json +61 -0
  125. package/client/dist/mcp-docs.html +108 -0
  126. package/client/dist/offline.html +84 -0
  127. package/client/dist/screenshots/cli-selection.png +0 -0
  128. package/client/dist/screenshots/desktop-main.png +0 -0
  129. package/client/dist/screenshots/mobile-chat.png +0 -0
  130. package/client/dist/screenshots/tools-modal.png +0 -0
  131. package/client/dist/sw.js +82 -0
  132. package/commands/upfynai-connect.md +59 -0
  133. package/commands/upfynai-disconnect.md +31 -0
  134. package/commands/upfynai-doctor.md +99 -0
  135. package/commands/upfynai-export.md +49 -0
  136. package/commands/upfynai-local.md +82 -0
  137. package/commands/upfynai-status.md +75 -0
  138. package/commands/upfynai-stop.md +49 -0
  139. package/commands/upfynai-uninstall.md +58 -0
  140. package/commands/upfynai.md +69 -0
  141. package/package.json +143 -82
  142. package/scripts/build-client.js +17 -0
  143. package/scripts/fix-node-pty.js +67 -0
  144. package/scripts/install-commands.js +78 -0
  145. package/server/agent-loop.js +242 -0
  146. package/server/auto-compact.js +99 -0
  147. package/server/claude-sdk.js +797 -0
  148. package/server/cli-ui.js +785 -0
  149. package/server/cli.js +596 -0
  150. package/server/constants/config.js +31 -0
  151. package/server/cursor-cli.js +270 -0
  152. package/server/database/auth.db +0 -0
  153. package/server/database/db.js +1391 -0
  154. package/server/database/init.sql +70 -0
  155. package/server/index.js +3799 -0
  156. package/server/load-env.js +26 -0
  157. package/server/mcp-server.js +621 -0
  158. package/server/middleware/auth.js +176 -0
  159. package/server/middleware/relayHelpers.js +44 -0
  160. package/server/middleware/sandboxRouter.js +174 -0
  161. package/server/openai-codex.js +403 -0
  162. package/server/openrouter.js +137 -0
  163. package/server/projects.js +1807 -0
  164. package/server/provider-factory.js +174 -0
  165. package/server/relay-client.js +379 -0
  166. package/server/routes/agent.js +1226 -0
  167. package/server/routes/auth.js +554 -0
  168. package/server/routes/canvas.js +53 -0
  169. package/server/routes/cli-auth.js +263 -0
  170. package/server/routes/codex.js +396 -0
  171. package/server/routes/commands.js +707 -0
  172. package/server/routes/composio.js +176 -0
  173. package/server/routes/cursor.js +770 -0
  174. package/server/routes/dashboard.js +295 -0
  175. package/server/routes/git.js +1208 -0
  176. package/server/routes/keys.js +34 -0
  177. package/server/routes/mcp-utils.js +48 -0
  178. package/server/routes/mcp.js +661 -0
  179. package/server/routes/payments.js +227 -0
  180. package/server/routes/projects.js +655 -0
  181. package/server/routes/sessions.js +146 -0
  182. package/server/routes/settings.js +261 -0
  183. package/server/routes/taskmaster.js +1928 -0
  184. package/server/routes/user.js +106 -0
  185. package/server/routes/vapi-chat.js +624 -0
  186. package/server/routes/voice.js +235 -0
  187. package/server/routes/webhooks.js +166 -0
  188. package/server/routes/workflows.js +312 -0
  189. package/server/sandbox.js +120 -0
  190. package/server/services/composio.js +204 -0
  191. package/server/services/sessionRegistry.js +139 -0
  192. package/server/services/whisperService.js +84 -0
  193. package/server/services/workflowScheduler.js +206 -0
  194. package/server/tests/relay-flow.test.js +570 -0
  195. package/server/tests/sessions.test.js +259 -0
  196. package/server/utils/commandParser.js +303 -0
  197. package/server/utils/email.js +61 -0
  198. package/server/utils/gitConfig.js +24 -0
  199. package/server/utils/mcp-detector.js +198 -0
  200. package/server/utils/taskmaster-websocket.js +129 -0
  201. package/shared/integrationCatalog.d.ts +12 -0
  202. package/shared/integrationCatalog.js +172 -0
  203. package/shared/modelConstants.js +96 -0
  204. package/bin/cli.js +0 -97
  205. package/dist/agents/claude.js +0 -229
  206. package/dist/agents/codex.js +0 -48
  207. package/dist/agents/cursor.js +0 -48
  208. package/dist/agents/detect.js +0 -51
  209. package/dist/agents/exec.js +0 -31
  210. package/dist/agents/files.js +0 -105
  211. package/dist/agents/git.js +0 -18
  212. package/dist/agents/gitagent.js +0 -67
  213. package/dist/agents/index.js +0 -88
  214. package/dist/agents/shell.js +0 -38
  215. package/dist/agents/utils.js +0 -136
  216. package/scripts/postinstall.js +0 -9
  217. package/scripts/prepublish.js +0 -58
  218. package/src/animation.js +0 -228
  219. package/src/auth.js +0 -122
  220. package/src/config.js +0 -40
  221. package/src/connect.js +0 -416
  222. package/src/launch.js +0 -78
  223. package/src/mcp.js +0 -57
  224. package/src/permissions.js +0 -140
  225. package/src/persistent-shell.js +0 -261
  226. package/src/server.js +0 -54
  227. /package/{dist → shared}/gitagent/index.js +0 -0
  228. /package/{dist → shared}/gitagent/parser.js +0 -0
  229. /package/{dist → shared}/gitagent/prompt-builder.js +0 -0
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Unified Session Registry
3
+ * Wraps per-provider session maps into a single interface for session management.
4
+ */
5
+
6
+ import { getActiveClaudeSDKSessions, abortClaudeSDKSession, isClaudeSDKSessionActive } from '../claude-sdk.js';
7
+ import { getActiveCursorSessions, abortCursorSession, isCursorSessionActive } from '../cursor-cli.js';
8
+ import { getActiveCodexSessions, abortCodexSession, isCodexSessionActive } from '../openai-codex.js';
9
+
10
+ /**
11
+ * Get all active sessions across all providers for a user.
12
+ * Note: current provider maps are global (not per-user), so we return all.
13
+ * When relay-based sessions are added, userId will be used to filter.
14
+ * @returns {Array<{ sessionId, provider, startTime, status, isProcessing }>}
15
+ */
16
+ export function getAllActiveSessions() {
17
+ const sessions = [];
18
+
19
+ // Claude SDK sessions — returns array of session IDs
20
+ const claudeIds = getActiveClaudeSDKSessions();
21
+ for (const id of claudeIds) {
22
+ sessions.push({
23
+ sessionId: id,
24
+ provider: 'claude',
25
+ status: isClaudeSDKSessionActive(id) ? 'active' : 'idle',
26
+ });
27
+ }
28
+
29
+ // Cursor sessions — returns array of session IDs
30
+ const cursorIds = getActiveCursorSessions();
31
+ for (const id of cursorIds) {
32
+ sessions.push({
33
+ sessionId: id,
34
+ provider: 'cursor',
35
+ status: isCursorSessionActive(id) ? 'active' : 'idle',
36
+ });
37
+ }
38
+
39
+ // Codex sessions — returns array of { id, status, startedAt }
40
+ const codexSessions = getActiveCodexSessions();
41
+ for (const s of codexSessions) {
42
+ sessions.push({
43
+ sessionId: s.id,
44
+ provider: 'codex',
45
+ status: s.status === 'running' ? 'active' : s.status,
46
+ startedAt: s.startedAt,
47
+ });
48
+ }
49
+
50
+ return sessions;
51
+ }
52
+
53
+ /**
54
+ * Check if a session is active across any provider.
55
+ * @param {string} sessionId
56
+ * @returns {{ active: boolean, provider: string|null }}
57
+ */
58
+ export function checkSessionStatus(sessionId) {
59
+ if (isClaudeSDKSessionActive(sessionId)) return { active: true, provider: 'claude' };
60
+ if (isCursorSessionActive(sessionId)) return { active: true, provider: 'cursor' };
61
+ if (isCodexSessionActive(sessionId)) return { active: true, provider: 'codex' };
62
+ return { active: false, provider: null };
63
+ }
64
+
65
+ /**
66
+ * Abort a session by ID, auto-detecting or using specified provider.
67
+ * @param {string} sessionId
68
+ * @param {string} [provider] - Optional: 'claude', 'cursor', 'codex'
69
+ * @returns {Promise<{ aborted: boolean, provider: string|null }>}
70
+ */
71
+ export async function abortSession(sessionId, provider) {
72
+ // If provider specified, abort directly
73
+ if (provider) {
74
+ const result = await abortByProvider(sessionId, provider);
75
+ return { aborted: result, provider: result ? provider : null };
76
+ }
77
+
78
+ // Auto-detect provider
79
+ if (isClaudeSDKSessionActive(sessionId)) {
80
+ const result = await abortClaudeSDKSession(sessionId);
81
+ return { aborted: result, provider: 'claude' };
82
+ }
83
+ if (isCursorSessionActive(sessionId)) {
84
+ const result = abortCursorSession(sessionId);
85
+ return { aborted: result, provider: 'cursor' };
86
+ }
87
+ if (isCodexSessionActive(sessionId)) {
88
+ const result = abortCodexSession(sessionId);
89
+ return { aborted: result, provider: 'codex' };
90
+ }
91
+
92
+ return { aborted: false, provider: null };
93
+ }
94
+
95
+ /**
96
+ * Abort all active sessions.
97
+ * @returns {Promise<Array<{ sessionId, provider, aborted }>>}
98
+ */
99
+ export async function abortAllSessions() {
100
+ const all = getAllActiveSessions();
101
+ const results = [];
102
+
103
+ for (const s of all) {
104
+ const { aborted } = await abortSession(s.sessionId, s.provider);
105
+ results.push({ sessionId: s.sessionId, provider: s.provider, aborted });
106
+ }
107
+
108
+ return results;
109
+ }
110
+
111
+ /**
112
+ * Get session stats summary.
113
+ * @returns {{ total, byProvider: { claude, cursor, codex }, active }}
114
+ */
115
+ export function getSessionStats() {
116
+ const sessions = getAllActiveSessions();
117
+ const byProvider = { claude: 0, cursor: 0, codex: 0 };
118
+
119
+ for (const s of sessions) {
120
+ byProvider[s.provider] = (byProvider[s.provider] || 0) + 1;
121
+ }
122
+
123
+ return {
124
+ total: sessions.length,
125
+ active: sessions.filter(s => s.status === 'active').length,
126
+ byProvider,
127
+ };
128
+ }
129
+
130
+ // -- Internal --
131
+
132
+ async function abortByProvider(sessionId, provider) {
133
+ switch (provider) {
134
+ case 'claude': return abortClaudeSDKSession(sessionId);
135
+ case 'cursor': return abortCursorSession(sessionId);
136
+ case 'codex': return abortCodexSession(sessionId);
137
+ default: return false;
138
+ }
139
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Local Whisper STT service using nodejs-whisper.
3
+ * Used as a fallback when no OpenAI API key is configured (local mode).
4
+ * Requires ffmpeg to be installed on the system.
5
+ */
6
+
7
+ let whisperAvailable = null; // null = unchecked, true/false
8
+ let modelReady = false;
9
+
10
+ /**
11
+ * Check if nodejs-whisper and ffmpeg are available.
12
+ */
13
+ async function isWhisperAvailable() {
14
+ if (whisperAvailable !== null) return whisperAvailable;
15
+
16
+ try {
17
+ // Check if nodejs-whisper can be imported
18
+ await import('nodejs-whisper');
19
+
20
+ // Check if ffmpeg is available
21
+ const { execSync } = await import('child_process');
22
+ execSync('ffmpeg -version', { stdio: 'pipe', timeout: 5000 });
23
+
24
+ whisperAvailable = true;
25
+ } catch {
26
+ whisperAvailable = false;
27
+ }
28
+
29
+ return whisperAvailable;
30
+ }
31
+
32
+ /**
33
+ * Ensure the whisper model is downloaded.
34
+ * Downloads the tiny.en model (~75MB) on first use.
35
+ */
36
+ async function ensureWhisperModel() {
37
+ if (modelReady) return true;
38
+
39
+ const available = await isWhisperAvailable();
40
+ if (!available) return false;
41
+
42
+ try {
43
+ const { nodeWhisper } = await import('nodejs-whisper');
44
+ // Attempt to download model if not present
45
+ await nodeWhisper.downloadModel('tiny.en');
46
+ modelReady = true;
47
+ return true;
48
+ } catch (err) {
49
+ console.warn('[WhisperService] Failed to download model:', err.message);
50
+ return false;
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Transcribe audio using local nodejs-whisper.
56
+ * @param {string} audioFilePath - Path to the audio file (WAV, MP3, etc.)
57
+ * @returns {Promise<string|null>} Transcribed text, or null if failed
58
+ */
59
+ async function transcribeLocal(audioFilePath) {
60
+ const ready = await ensureWhisperModel();
61
+ if (!ready) return null;
62
+
63
+ try {
64
+ const { nodeWhisper } = await import('nodejs-whisper');
65
+ const result = await nodeWhisper(audioFilePath, {
66
+ modelName: 'tiny.en',
67
+ autoDownloadModelName: 'tiny.en',
68
+ whisperOptions: {
69
+ outputInText: true,
70
+ language: 'en',
71
+ }
72
+ });
73
+
74
+ // nodejs-whisper returns array of segments or text
75
+ if (typeof result === 'string') return result.trim();
76
+ if (Array.isArray(result)) return result.map(s => s.speech || s.text || '').join(' ').trim();
77
+ return null;
78
+ } catch (err) {
79
+ console.error('[WhisperService] Transcription error:', err.message);
80
+ return null;
81
+ }
82
+ }
83
+
84
+ export { isWhisperAvailable, ensureWhisperModel, transcribeLocal };
@@ -0,0 +1,206 @@
1
+ import cron from 'node-cron';
2
+ import { workflowDb, webhookDb } from '../database/db.js';
3
+ import * as composioService from './composio.js';
4
+
5
+ const activeJobs = new Map(); // workflowId -> cron task
6
+
7
+ /**
8
+ * Execute a single workflow's steps (same logic as the /run endpoint).
9
+ * Returns { success, results, error }
10
+ */
11
+ async function executeWorkflow(workflow) {
12
+ const steps = typeof workflow.steps === 'string' ? JSON.parse(workflow.steps) : workflow.steps;
13
+ if (!steps.length) return { success: false, error: 'No steps' };
14
+
15
+ const run = await workflowDb.createRun(workflow.id, workflow.user_id, steps.length);
16
+ const results = [];
17
+ let lastOutput = null;
18
+
19
+ for (let i = 0; i < steps.length; i++) {
20
+ const step = steps[i];
21
+ try {
22
+ let stepResult;
23
+
24
+ if (step.type === 'webhook') {
25
+ const webhookId = step.config?.webhookId;
26
+ if (!webhookId) throw new Error('No webhook configured');
27
+
28
+ const webhook = await webhookDb.getById(Number(webhookId), workflow.user_id);
29
+ if (!webhook) throw new Error('Webhook not found');
30
+
31
+ let parsedHeaders = {};
32
+ try { parsedHeaders = JSON.parse(webhook.headers || '{}'); } catch { /* ignore */ }
33
+
34
+ const controller = new AbortController();
35
+ const timeout = setTimeout(() => controller.abort(), 15000);
36
+
37
+ const fetchOptions = {
38
+ method: webhook.method,
39
+ headers: {
40
+ 'Content-Type': 'application/json',
41
+ 'User-Agent': 'UpfynAI-Scheduler/1.0',
42
+ ...parsedHeaders
43
+ },
44
+ signal: controller.signal
45
+ };
46
+
47
+ if (['POST', 'PUT', 'PATCH'].includes(webhook.method)) {
48
+ const payload = {
49
+ workflow_id: workflow.id,
50
+ workflow_name: workflow.name,
51
+ step_index: i,
52
+ step_label: step.label,
53
+ previous_output: lastOutput,
54
+ scheduled: true,
55
+ timestamp: new Date().toISOString()
56
+ };
57
+ if (step.config?.payloadTemplate) {
58
+ try { Object.assign(payload, JSON.parse(step.config.payloadTemplate)); } catch { /* ignore */ }
59
+ }
60
+ fetchOptions.body = JSON.stringify(payload);
61
+ }
62
+
63
+ const response = await fetch(webhook.url, fetchOptions);
64
+ clearTimeout(timeout);
65
+
66
+ const contentType = response.headers.get('content-type') || '';
67
+ let body;
68
+ if (contentType.includes('application/json')) {
69
+ body = await response.json();
70
+ } else {
71
+ body = await response.text();
72
+ if (body.length > 5000) body = body.slice(0, 5000) + '...';
73
+ }
74
+
75
+ await webhookDb.updateLastTriggered(webhook.id);
76
+ stepResult = { status: response.status, body };
77
+ lastOutput = body;
78
+
79
+ } else if (step.type === 'ai-prompt') {
80
+ stepResult = { type: 'ai-prompt', prompt: step.config?.prompt || '', note: 'Scheduled AI prompts require active session' };
81
+ lastOutput = step.config?.prompt;
82
+
83
+ } else if (step.type === 'delay') {
84
+ const seconds = Math.min(step.config?.seconds || 1, 30);
85
+ await new Promise(resolve => setTimeout(resolve, seconds * 1000));
86
+ stepResult = { delayed: seconds };
87
+
88
+ } else if (step.type === 'integration') {
89
+ const toolSlug = step.config?.toolSlug;
90
+ if (!toolSlug) throw new Error('No tool configured for integration step');
91
+ if (!(await composioService.isAvailable())) throw new Error('Composio not configured');
92
+
93
+ // Interpolate {{prev.field}} templates from lastOutput
94
+ let args = { ...(step.config?.arguments || {}) };
95
+ if (lastOutput && typeof lastOutput === 'object') {
96
+ for (const [key, val] of Object.entries(args)) {
97
+ if (typeof val === 'string' && val.includes('{{prev.')) {
98
+ args[key] = val.replace(/\{\{prev\.(\w+)\}\}/g, (_, field) =>
99
+ lastOutput[field] !== undefined ? String(lastOutput[field]) : ''
100
+ );
101
+ }
102
+ }
103
+ }
104
+
105
+ const result = await composioService.executeTool(workflow.user_id, toolSlug, args);
106
+ if (!result.success) throw new Error(result.error || 'Integration execution failed');
107
+ stepResult = { toolSlug, ...result };
108
+ lastOutput = result.data || result;
109
+
110
+ } else {
111
+ stepResult = { type: step.type, note: 'Unknown step type' };
112
+ }
113
+
114
+ results.push({ step: i, label: step.label, type: step.type, success: true, result: stepResult });
115
+ await workflowDb.updateRun(run.id, { status: 'running', stepsCompleted: i + 1 });
116
+
117
+ } catch (stepError) {
118
+ results.push({ step: i, label: step.label, type: step.type, success: false, error: stepError.message });
119
+ await workflowDb.updateRun(run.id, { status: 'failed', stepsCompleted: i, error: `Step ${i + 1} (${step.label}): ${stepError.message}` });
120
+ await workflowDb.updateLastRun(workflow.id);
121
+ return { success: false, run_id: run.id, results, error: `Step ${i + 1} failed: ${stepError.message}` };
122
+ }
123
+ }
124
+
125
+ await workflowDb.updateRun(run.id, { status: 'completed', stepsCompleted: steps.length, result: results });
126
+ await workflowDb.updateLastRun(workflow.id);
127
+ return { success: true, run_id: run.id, results };
128
+ }
129
+
130
+ /**
131
+ * Schedule a single workflow's cron job.
132
+ */
133
+ function scheduleWorkflow(workflow) {
134
+ const id = workflow.id;
135
+
136
+ // Stop existing job if any
137
+ if (activeJobs.has(id)) {
138
+ activeJobs.get(id).stop();
139
+ activeJobs.delete(id);
140
+ }
141
+
142
+ if (!workflow.schedule || !workflow.schedule_enabled) return;
143
+
144
+ // Validate cron expression
145
+ if (!cron.validate(workflow.schedule)) {
146
+ console.warn(`[Scheduler] Invalid cron for workflow ${id}: ${workflow.schedule}`);
147
+ return;
148
+ }
149
+
150
+ const task = cron.schedule(workflow.schedule, async () => {
151
+ try {
152
+ await executeWorkflow(workflow);
153
+ } catch {
154
+ // workflow execution error
155
+ }
156
+ }, {
157
+ timezone: workflow.schedule_timezone || 'UTC'
158
+ });
159
+
160
+ activeJobs.set(id, task);
161
+ }
162
+
163
+ /**
164
+ * Load all scheduled workflows from DB and start their cron jobs.
165
+ * Call this once at server startup.
166
+ */
167
+ async function initScheduler() {
168
+ try {
169
+ const workflows = await workflowDb.getScheduled();
170
+ for (const wf of workflows) {
171
+ scheduleWorkflow(wf);
172
+ }
173
+ } catch (err) {
174
+ // scheduler init error — silenced
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Re-sync a specific workflow's schedule (call after create/update).
180
+ */
181
+ async function refreshWorkflowSchedule(workflowId, userId) {
182
+ try {
183
+ const wf = await workflowDb.getById(workflowId, userId);
184
+ if (wf) {
185
+ scheduleWorkflow(wf);
186
+ } else {
187
+ // Workflow deleted — stop its job
188
+ if (activeJobs.has(workflowId)) {
189
+ activeJobs.get(workflowId).stop();
190
+ activeJobs.delete(workflowId);
191
+ }
192
+ }
193
+ } catch { /* ignore */ }
194
+ }
195
+
196
+ /**
197
+ * Stop a workflow's cron job.
198
+ */
199
+ function stopWorkflowSchedule(workflowId) {
200
+ if (activeJobs.has(workflowId)) {
201
+ activeJobs.get(workflowId).stop();
202
+ activeJobs.delete(workflowId);
203
+ }
204
+ }
205
+
206
+ export { initScheduler, refreshWorkflowSchedule, stopWorkflowSchedule, executeWorkflow };