upfynai-code 2.9.1 → 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,403 @@
1
+ /**
2
+ * OpenAI Codex SDK Integration
3
+ * =============================
4
+ *
5
+ * This module provides integration with the OpenAI Codex SDK for non-interactive
6
+ * chat sessions. It mirrors the pattern used in claude-sdk.js for consistency.
7
+ *
8
+ * ## Usage
9
+ *
10
+ * - queryCodex(command, options, ws) - Execute a prompt with streaming via WebSocket
11
+ * - abortCodexSession(sessionId) - Cancel an active session
12
+ * - isCodexSessionActive(sessionId) - Check if a session is running
13
+ * - getActiveCodexSessions() - List all active sessions
14
+ */
15
+
16
+ import { Codex } from '@openai/codex-sdk';
17
+
18
+ // Track active sessions
19
+ const activeCodexSessions = new Map();
20
+
21
+ /**
22
+ * Transform Codex SDK event to WebSocket message format
23
+ * @param {object} event - SDK event
24
+ * @returns {object} - Transformed event for WebSocket
25
+ */
26
+ function transformCodexEvent(event) {
27
+ // Map SDK event types to a consistent format
28
+ switch (event.type) {
29
+ case 'item.started':
30
+ case 'item.updated':
31
+ case 'item.completed':
32
+ const item = event.item;
33
+ if (!item) {
34
+ return { type: event.type, item: null };
35
+ }
36
+
37
+ // Transform based on item type
38
+ switch (item.type) {
39
+ case 'agent_message':
40
+ return {
41
+ type: 'item',
42
+ itemType: 'agent_message',
43
+ message: {
44
+ role: 'assistant',
45
+ content: item.text
46
+ }
47
+ };
48
+
49
+ case 'reasoning':
50
+ return {
51
+ type: 'item',
52
+ itemType: 'reasoning',
53
+ message: {
54
+ role: 'assistant',
55
+ content: item.text,
56
+ isReasoning: true
57
+ }
58
+ };
59
+
60
+ case 'command_execution':
61
+ return {
62
+ type: 'item',
63
+ itemType: 'command_execution',
64
+ command: item.command,
65
+ output: item.aggregated_output,
66
+ exitCode: item.exit_code,
67
+ status: item.status
68
+ };
69
+
70
+ case 'file_change':
71
+ return {
72
+ type: 'item',
73
+ itemType: 'file_change',
74
+ changes: item.changes,
75
+ status: item.status
76
+ };
77
+
78
+ case 'mcp_tool_call':
79
+ return {
80
+ type: 'item',
81
+ itemType: 'mcp_tool_call',
82
+ server: item.server,
83
+ tool: item.tool,
84
+ arguments: item.arguments,
85
+ result: item.result,
86
+ error: item.error,
87
+ status: item.status
88
+ };
89
+
90
+ case 'web_search':
91
+ return {
92
+ type: 'item',
93
+ itemType: 'web_search',
94
+ query: item.query
95
+ };
96
+
97
+ case 'todo_list':
98
+ return {
99
+ type: 'item',
100
+ itemType: 'todo_list',
101
+ items: item.items
102
+ };
103
+
104
+ case 'error':
105
+ return {
106
+ type: 'item',
107
+ itemType: 'error',
108
+ message: {
109
+ role: 'error',
110
+ content: item.message
111
+ }
112
+ };
113
+
114
+ default:
115
+ return {
116
+ type: 'item',
117
+ itemType: item.type,
118
+ item: item
119
+ };
120
+ }
121
+
122
+ case 'turn.started':
123
+ return {
124
+ type: 'turn_started'
125
+ };
126
+
127
+ case 'turn.completed':
128
+ return {
129
+ type: 'turn_complete',
130
+ usage: event.usage
131
+ };
132
+
133
+ case 'turn.failed':
134
+ return {
135
+ type: 'turn_failed',
136
+ error: event.error
137
+ };
138
+
139
+ case 'thread.started':
140
+ return {
141
+ type: 'thread_started',
142
+ threadId: event.id
143
+ };
144
+
145
+ case 'error':
146
+ return {
147
+ type: 'error',
148
+ message: event.message
149
+ };
150
+
151
+ default:
152
+ return {
153
+ type: event.type,
154
+ data: event
155
+ };
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Map permission mode to Codex SDK options
161
+ * @param {string} permissionMode - 'default', 'acceptEdits', or 'bypassPermissions'
162
+ * @returns {object} - { sandboxMode, approvalPolicy }
163
+ */
164
+ function mapPermissionModeToCodexOptions(permissionMode) {
165
+ switch (permissionMode) {
166
+ case 'acceptEdits':
167
+ return {
168
+ sandboxMode: 'workspace-write',
169
+ approvalPolicy: 'never'
170
+ };
171
+ case 'bypassPermissions':
172
+ return {
173
+ sandboxMode: 'danger-full-access',
174
+ approvalPolicy: 'never'
175
+ };
176
+ case 'default':
177
+ default:
178
+ return {
179
+ sandboxMode: 'workspace-write',
180
+ approvalPolicy: 'untrusted'
181
+ };
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Execute a Codex query with streaming
187
+ * @param {string} command - The prompt to send
188
+ * @param {object} options - Options including cwd, sessionId, model, permissionMode
189
+ * @param {WebSocket|object} ws - WebSocket connection or response writer
190
+ */
191
+ export async function queryCodex(command, options = {}, ws) {
192
+ const {
193
+ sessionId,
194
+ cwd,
195
+ projectPath,
196
+ model,
197
+ permissionMode = 'default'
198
+ } = options;
199
+
200
+ const workingDirectory = cwd || projectPath || process.cwd();
201
+ const { sandboxMode, approvalPolicy } = mapPermissionModeToCodexOptions(permissionMode);
202
+
203
+ let codex;
204
+ let thread;
205
+ let currentSessionId = sessionId;
206
+ const abortController = new AbortController();
207
+
208
+ try {
209
+ // Initialize Codex SDK
210
+ codex = new Codex();
211
+
212
+ // Thread options with sandbox and approval settings
213
+ const threadOptions = {
214
+ workingDirectory,
215
+ skipGitRepoCheck: true,
216
+ sandboxMode,
217
+ approvalPolicy,
218
+ model
219
+ };
220
+
221
+ // Start or resume thread
222
+ if (sessionId) {
223
+ thread = codex.resumeThread(sessionId, threadOptions);
224
+ } else {
225
+ thread = codex.startThread(threadOptions);
226
+ }
227
+
228
+ // Get the thread ID
229
+ currentSessionId = thread.id || sessionId || `codex-${Date.now()}`;
230
+
231
+ // Track the session
232
+ activeCodexSessions.set(currentSessionId, {
233
+ thread,
234
+ codex,
235
+ status: 'running',
236
+ abortController,
237
+ startedAt: new Date().toISOString()
238
+ });
239
+
240
+ // Send session created event
241
+ sendMessage(ws, {
242
+ type: 'session-created',
243
+ sessionId: currentSessionId,
244
+ provider: 'codex'
245
+ });
246
+
247
+ // Execute with streaming
248
+ const streamedTurn = await thread.runStreamed(command, {
249
+ signal: abortController.signal
250
+ });
251
+
252
+ for await (const event of streamedTurn.events) {
253
+ // Check if session was aborted
254
+ const session = activeCodexSessions.get(currentSessionId);
255
+ if (!session || session.status === 'aborted') {
256
+ break;
257
+ }
258
+
259
+ if (event.type === 'item.started' || event.type === 'item.updated') {
260
+ continue;
261
+ }
262
+
263
+ const transformed = transformCodexEvent(event);
264
+
265
+ sendMessage(ws, {
266
+ type: 'codex-response',
267
+ data: transformed,
268
+ sessionId: currentSessionId
269
+ });
270
+
271
+ // Extract and send token usage if available (normalized to match Claude format)
272
+ if (event.type === 'turn.completed' && event.usage) {
273
+ const totalTokens = (event.usage.input_tokens || 0) + (event.usage.output_tokens || 0);
274
+ sendMessage(ws, {
275
+ type: 'token-budget',
276
+ data: {
277
+ used: totalTokens,
278
+ total: 200000 // Default context window for Codex models
279
+ },
280
+ sessionId: currentSessionId
281
+ });
282
+ }
283
+ }
284
+
285
+ // Send completion event
286
+ sendMessage(ws, {
287
+ type: 'codex-complete',
288
+ sessionId: currentSessionId,
289
+ actualSessionId: thread.id
290
+ });
291
+
292
+ } catch (error) {
293
+ const session = currentSessionId ? activeCodexSessions.get(currentSessionId) : null;
294
+ const wasAborted =
295
+ session?.status === 'aborted' ||
296
+ error?.name === 'AbortError' ||
297
+ String(error?.message || '').toLowerCase().includes('aborted');
298
+
299
+ if (!wasAborted) {
300
+ console.error('[Codex] Error:', error);
301
+ sendMessage(ws, {
302
+ type: 'codex-error',
303
+ error: error.message,
304
+ sessionId: currentSessionId
305
+ });
306
+ }
307
+
308
+ } finally {
309
+ // Update session status
310
+ if (currentSessionId) {
311
+ const session = activeCodexSessions.get(currentSessionId);
312
+ if (session) {
313
+ session.status = session.status === 'aborted' ? 'aborted' : 'completed';
314
+ }
315
+ }
316
+ }
317
+ }
318
+
319
+ /**
320
+ * Abort an active Codex session
321
+ * @param {string} sessionId - Session ID to abort
322
+ * @returns {boolean} - Whether abort was successful
323
+ */
324
+ export function abortCodexSession(sessionId) {
325
+ const session = activeCodexSessions.get(sessionId);
326
+
327
+ if (!session) {
328
+ return false;
329
+ }
330
+
331
+ session.status = 'aborted';
332
+ try {
333
+ session.abortController?.abort();
334
+ } catch (error) {
335
+ console.warn(`[Codex] Failed to abort session ${sessionId}:`, error);
336
+ }
337
+
338
+ return true;
339
+ }
340
+
341
+ /**
342
+ * Check if a session is active
343
+ * @param {string} sessionId - Session ID to check
344
+ * @returns {boolean} - Whether session is active
345
+ */
346
+ export function isCodexSessionActive(sessionId) {
347
+ const session = activeCodexSessions.get(sessionId);
348
+ return session?.status === 'running';
349
+ }
350
+
351
+ /**
352
+ * Get all active sessions
353
+ * @returns {Array} - Array of active session info
354
+ */
355
+ export function getActiveCodexSessions() {
356
+ const sessions = [];
357
+
358
+ for (const [id, session] of activeCodexSessions.entries()) {
359
+ if (session.status === 'running') {
360
+ sessions.push({
361
+ id,
362
+ status: session.status,
363
+ startedAt: session.startedAt
364
+ });
365
+ }
366
+ }
367
+
368
+ return sessions;
369
+ }
370
+
371
+ /**
372
+ * Helper to send message via WebSocket or writer
373
+ * @param {WebSocket|object} ws - WebSocket or response writer
374
+ * @param {object} data - Data to send
375
+ */
376
+ function sendMessage(ws, data) {
377
+ try {
378
+ if (ws.isSSEStreamWriter || ws.isWebSocketWriter) {
379
+ // Writer handles stringification (SSEStreamWriter or WebSocketWriter)
380
+ ws.send(data);
381
+ } else if (typeof ws.send === 'function') {
382
+ // Raw WebSocket - stringify here
383
+ ws.send(JSON.stringify(data));
384
+ }
385
+ } catch (error) {
386
+ console.error('[Codex] Error sending message:', error);
387
+ }
388
+ }
389
+
390
+ // Clean up old completed sessions periodically
391
+ setInterval(() => {
392
+ const now = Date.now();
393
+ const maxAge = 30 * 60 * 1000; // 30 minutes
394
+
395
+ for (const [id, session] of activeCodexSessions.entries()) {
396
+ if (session.status !== 'running') {
397
+ const startedAt = new Date(session.startedAt).getTime();
398
+ if (now - startedAt > maxAge) {
399
+ activeCodexSessions.delete(id);
400
+ }
401
+ }
402
+ }
403
+ }, 5 * 60 * 1000); // Every 5 minutes
@@ -0,0 +1,137 @@
1
+ /**
2
+ * OpenRouter Integration
3
+ *
4
+ * Lightweight wrapper for OpenRouter API, which provides access to
5
+ * hundreds of AI models (GPT-4, Claude, Gemini, Llama, Mistral, etc.)
6
+ * through a single API key and endpoint.
7
+ *
8
+ * Users provide their own OpenRouter API key via BYOK settings.
9
+ */
10
+
11
+ const OPENROUTER_BASE_URL = 'https://openrouter.ai/api/v1';
12
+
13
+ // Popular models available on OpenRouter
14
+ export const OPENROUTER_MODELS = {
15
+ OPTIONS: [
16
+ { value: 'anthropic/claude-sonnet-4', label: 'Claude Sonnet 4' },
17
+ { value: 'anthropic/claude-opus-4', label: 'Claude Opus 4' },
18
+ { value: 'openai/gpt-4o', label: 'GPT-4o' },
19
+ { value: 'openai/o3', label: 'O3' },
20
+ { value: 'google/gemini-2.5-pro', label: 'Gemini 2.5 Pro' },
21
+ { value: 'meta-llama/llama-4-maverick', label: 'Llama 4 Maverick' },
22
+ { value: 'mistralai/mistral-large', label: 'Mistral Large' },
23
+ { value: 'deepseek/deepseek-r1', label: 'DeepSeek R1' },
24
+ ],
25
+ DEFAULT: 'anthropic/claude-sonnet-4',
26
+ };
27
+
28
+ /**
29
+ * Query OpenRouter API with streaming support
30
+ * @param {string} message - User message
31
+ * @param {Object} options - { model, apiKey, systemPrompt }
32
+ * @param {Object} writer - WebSocketWriter or SSEStreamWriter
33
+ */
34
+ export async function queryOpenRouter(message, options = {}, writer) {
35
+ const {
36
+ model = OPENROUTER_MODELS.DEFAULT,
37
+ apiKey,
38
+ systemPrompt,
39
+ sessionId,
40
+ } = options;
41
+
42
+ if (!apiKey) {
43
+ writer.send({
44
+ type: 'error',
45
+ error: 'OpenRouter API key required. Add your key in Settings > AI Providers.',
46
+ });
47
+ return;
48
+ }
49
+
50
+ // Generate session ID
51
+ const sid = sessionId || `or-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
52
+ writer.send({ type: 'session-created', sessionId: sid });
53
+
54
+ const messages = [];
55
+ if (systemPrompt) {
56
+ messages.push({ role: 'system', content: systemPrompt });
57
+ }
58
+ messages.push({ role: 'user', content: message });
59
+
60
+ try {
61
+ const response = await fetch(`${OPENROUTER_BASE_URL}/chat/completions`, {
62
+ method: 'POST',
63
+ headers: {
64
+ 'Authorization': `Bearer ${apiKey}`,
65
+ 'Content-Type': 'application/json',
66
+ 'HTTP-Referer': 'https://cli.upfyn.com',
67
+ 'X-Title': 'Upfyn-Code',
68
+ },
69
+ body: JSON.stringify({
70
+ model,
71
+ messages,
72
+ stream: true,
73
+ }),
74
+ });
75
+
76
+ if (!response.ok) {
77
+ const errBody = await response.text();
78
+ let errMsg = `OpenRouter API error (${response.status})`;
79
+ try {
80
+ const parsed = JSON.parse(errBody);
81
+ errMsg = parsed.error?.message || errMsg;
82
+ } catch {}
83
+ writer.send({ type: 'error', error: errMsg, sessionId: sid });
84
+ return;
85
+ }
86
+
87
+ // Stream SSE response
88
+ const reader = response.body.getReader();
89
+ const decoder = new TextDecoder();
90
+ let buffer = '';
91
+ let fullContent = '';
92
+
93
+ while (true) {
94
+ const { done, value } = await reader.read();
95
+ if (done) break;
96
+
97
+ buffer += decoder.decode(value, { stream: true });
98
+ const lines = buffer.split('\n');
99
+ buffer = lines.pop() || '';
100
+
101
+ for (const line of lines) {
102
+ if (!line.startsWith('data: ')) continue;
103
+ const data = line.slice(6).trim();
104
+ if (data === '[DONE]') break;
105
+
106
+ try {
107
+ const parsed = JSON.parse(data);
108
+ const delta = parsed.choices?.[0]?.delta?.content;
109
+ if (delta) {
110
+ fullContent += delta;
111
+ writer.send({
112
+ type: 'assistant',
113
+ content: delta,
114
+ sessionId: sid,
115
+ });
116
+ }
117
+ } catch {}
118
+ }
119
+ }
120
+
121
+ // Send completion
122
+ writer.send({
123
+ type: 'result',
124
+ subtype: 'success',
125
+ sessionId: sid,
126
+ content: fullContent,
127
+ model,
128
+ provider: 'openrouter',
129
+ });
130
+ } catch (error) {
131
+ writer.send({
132
+ type: 'error',
133
+ error: `OpenRouter request failed: ${error.message}`,
134
+ sessionId: sid,
135
+ });
136
+ }
137
+ }