@siteboon/claude-code-ui 1.12.0 → 1.13.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.
@@ -0,0 +1,387 @@
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
+
207
+ try {
208
+ // Initialize Codex SDK
209
+ codex = new Codex();
210
+
211
+ // Thread options with sandbox and approval settings
212
+ const threadOptions = {
213
+ workingDirectory,
214
+ skipGitRepoCheck: true,
215
+ sandboxMode,
216
+ approvalPolicy
217
+ };
218
+
219
+ // Start or resume thread
220
+ if (sessionId) {
221
+ thread = codex.resumeThread(sessionId, threadOptions);
222
+ } else {
223
+ thread = codex.startThread(threadOptions);
224
+ }
225
+
226
+ // Get the thread ID
227
+ currentSessionId = thread.id || sessionId || `codex-${Date.now()}`;
228
+
229
+ // Track the session
230
+ activeCodexSessions.set(currentSessionId, {
231
+ thread,
232
+ codex,
233
+ status: 'running',
234
+ startedAt: new Date().toISOString()
235
+ });
236
+
237
+ // Send session created event
238
+ sendMessage(ws, {
239
+ type: 'session-created',
240
+ sessionId: currentSessionId,
241
+ provider: 'codex'
242
+ });
243
+
244
+ // Execute with streaming
245
+ const streamedTurn = await thread.runStreamed(command);
246
+
247
+ for await (const event of streamedTurn.events) {
248
+ // Check if session was aborted
249
+ const session = activeCodexSessions.get(currentSessionId);
250
+ if (!session || session.status === 'aborted') {
251
+ break;
252
+ }
253
+
254
+ if (event.type === 'item.started' || event.type === 'item.updated') {
255
+ continue;
256
+ }
257
+
258
+ const transformed = transformCodexEvent(event);
259
+
260
+ sendMessage(ws, {
261
+ type: 'codex-response',
262
+ data: transformed,
263
+ sessionId: currentSessionId
264
+ });
265
+
266
+ // Extract and send token usage if available (normalized to match Claude format)
267
+ if (event.type === 'turn.completed' && event.usage) {
268
+ const totalTokens = (event.usage.input_tokens || 0) + (event.usage.output_tokens || 0);
269
+ sendMessage(ws, {
270
+ type: 'token-budget',
271
+ data: {
272
+ used: totalTokens,
273
+ total: 200000 // Default context window for Codex models
274
+ }
275
+ });
276
+ }
277
+ }
278
+
279
+ // Send completion event
280
+ sendMessage(ws, {
281
+ type: 'codex-complete',
282
+ sessionId: currentSessionId
283
+ });
284
+
285
+ } catch (error) {
286
+ console.error('[Codex] Error:', error);
287
+
288
+ sendMessage(ws, {
289
+ type: 'codex-error',
290
+ error: error.message,
291
+ sessionId: currentSessionId
292
+ });
293
+
294
+ } finally {
295
+ // Update session status
296
+ if (currentSessionId) {
297
+ const session = activeCodexSessions.get(currentSessionId);
298
+ if (session) {
299
+ session.status = 'completed';
300
+ }
301
+ }
302
+ }
303
+ }
304
+
305
+ /**
306
+ * Abort an active Codex session
307
+ * @param {string} sessionId - Session ID to abort
308
+ * @returns {boolean} - Whether abort was successful
309
+ */
310
+ export function abortCodexSession(sessionId) {
311
+ const session = activeCodexSessions.get(sessionId);
312
+
313
+ if (!session) {
314
+ return false;
315
+ }
316
+
317
+ session.status = 'aborted';
318
+
319
+ // The SDK doesn't have a direct abort method, but marking status
320
+ // will cause the streaming loop to exit
321
+
322
+ return true;
323
+ }
324
+
325
+ /**
326
+ * Check if a session is active
327
+ * @param {string} sessionId - Session ID to check
328
+ * @returns {boolean} - Whether session is active
329
+ */
330
+ export function isCodexSessionActive(sessionId) {
331
+ const session = activeCodexSessions.get(sessionId);
332
+ return session?.status === 'running';
333
+ }
334
+
335
+ /**
336
+ * Get all active sessions
337
+ * @returns {Array} - Array of active session info
338
+ */
339
+ export function getActiveCodexSessions() {
340
+ const sessions = [];
341
+
342
+ for (const [id, session] of activeCodexSessions.entries()) {
343
+ if (session.status === 'running') {
344
+ sessions.push({
345
+ id,
346
+ status: session.status,
347
+ startedAt: session.startedAt
348
+ });
349
+ }
350
+ }
351
+
352
+ return sessions;
353
+ }
354
+
355
+ /**
356
+ * Helper to send message via WebSocket or writer
357
+ * @param {WebSocket|object} ws - WebSocket or response writer
358
+ * @param {object} data - Data to send
359
+ */
360
+ function sendMessage(ws, data) {
361
+ try {
362
+ if (typeof ws.send === 'function') {
363
+ // WebSocket
364
+ ws.send(JSON.stringify(data));
365
+ } else if (typeof ws.write === 'function') {
366
+ // SSE writer (for agent API)
367
+ ws.write(`data: ${JSON.stringify(data)}\n\n`);
368
+ }
369
+ } catch (error) {
370
+ console.error('[Codex] Error sending message:', error);
371
+ }
372
+ }
373
+
374
+ // Clean up old completed sessions periodically
375
+ setInterval(() => {
376
+ const now = Date.now();
377
+ const maxAge = 30 * 60 * 1000; // 30 minutes
378
+
379
+ for (const [id, session] of activeCodexSessions.entries()) {
380
+ if (session.status !== 'running') {
381
+ const startedAt = new Date(session.startedAt).getTime();
382
+ if (now - startedAt > maxAge) {
383
+ activeCodexSessions.delete(id);
384
+ }
385
+ }
386
+ }
387
+ }, 5 * 60 * 1000); // Every 5 minutes