@myrialabs/clopen 0.3.8 → 0.3.10

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 (146) hide show
  1. package/README.md +22 -19
  2. package/backend/auth/auth-service.ts +56 -1
  3. package/backend/auth/permissions.ts +66 -2
  4. package/backend/auth/session-cleanup.ts +58 -0
  5. package/backend/chat/stream-manager.ts +143 -13
  6. package/backend/database/migrations/032_seed_copilot_provider.ts +19 -0
  7. package/backend/database/migrations/033_seed_codex_provider.ts +19 -0
  8. package/backend/database/migrations/034_seed_qwen_provider.ts +119 -0
  9. package/backend/database/migrations/035_add_owner_to_db_client_connections.ts +34 -0
  10. package/backend/database/migrations/index.ts +29 -1
  11. package/backend/database/queries/db-client-connection-queries.ts +160 -54
  12. package/backend/database/queries/engine-queries.ts +12 -0
  13. package/backend/database/queries/project-queries.ts +10 -5
  14. package/backend/db-client/connection-manager.ts +9 -3
  15. package/backend/engine/README.md +1702 -0
  16. package/backend/engine/adapters/claude/models.ts +141 -0
  17. package/backend/engine/adapters/claude/stream.ts +1 -1
  18. package/backend/engine/adapters/codex/credential.ts +179 -0
  19. package/backend/engine/adapters/codex/error-handler.ts +65 -0
  20. package/backend/engine/adapters/codex/index.ts +1 -0
  21. package/backend/engine/adapters/codex/message-converter.ts +646 -0
  22. package/backend/engine/adapters/codex/models.ts +105 -0
  23. package/backend/engine/adapters/codex/patch-rollout.ts +169 -0
  24. package/backend/engine/adapters/codex/session-fork.ts +149 -0
  25. package/backend/engine/adapters/codex/stream.ts +310 -0
  26. package/backend/engine/adapters/codex/usage-rollout.ts +145 -0
  27. package/backend/engine/adapters/copilot/error-handler.ts +94 -0
  28. package/backend/engine/adapters/copilot/index.ts +1 -0
  29. package/backend/engine/adapters/copilot/message-converter.ts +973 -0
  30. package/backend/engine/adapters/copilot/models.ts +92 -0
  31. package/backend/engine/adapters/copilot/session-fork.ts +111 -0
  32. package/backend/engine/adapters/copilot/stream.ts +570 -0
  33. package/backend/engine/adapters/opencode/config.ts +56 -104
  34. package/backend/engine/adapters/opencode/error-handler.ts +71 -0
  35. package/backend/engine/adapters/opencode/models.ts +79 -0
  36. package/backend/engine/adapters/opencode/presets.ts +91 -0
  37. package/backend/engine/adapters/opencode/stream.ts +8 -114
  38. package/backend/engine/adapters/qwen/credential.ts +78 -0
  39. package/backend/engine/adapters/qwen/environment.ts +84 -0
  40. package/backend/engine/adapters/qwen/error-handler.ts +71 -0
  41. package/backend/engine/adapters/qwen/index.ts +1 -0
  42. package/backend/engine/adapters/qwen/message-converter.ts +1055 -0
  43. package/backend/engine/adapters/qwen/models.ts +81 -0
  44. package/backend/engine/adapters/qwen/presets.ts +51 -0
  45. package/backend/engine/adapters/qwen/session-fork.ts +97 -0
  46. package/backend/engine/adapters/qwen/stream.ts +379 -0
  47. package/backend/engine/index.ts +35 -0
  48. package/backend/engine/install-recipes.ts +80 -1
  49. package/backend/engine/install-runner.ts +4 -0
  50. package/backend/files/path-browsing.ts +20 -0
  51. package/backend/git/git-service.ts +81 -11
  52. package/backend/git/git-spawn-validation.test.ts +75 -0
  53. package/backend/git/git-spawn-validation.ts +77 -0
  54. package/backend/index.ts +5 -0
  55. package/backend/mcp/README.md +84 -14
  56. package/backend/mcp/config.ts +218 -17
  57. package/backend/mcp/index.ts +2 -0
  58. package/backend/mcp/project-context.ts +55 -0
  59. package/backend/mcp/servers/browser-automation/actions.ts +6 -1
  60. package/backend/mcp/servers/helper.ts +13 -0
  61. package/backend/middleware/error-handler.ts +16 -2
  62. package/backend/preview/browser/browser-preview-service.ts +4 -4
  63. package/backend/preview/browser/browser-tab-manager.ts +23 -3
  64. package/backend/snapshot/gitignore.ts +4 -9
  65. package/backend/tunnel/cloudflared/binary.ts +2 -2
  66. package/backend/tunnel/global-tunnel-manager.ts +9 -3
  67. package/backend/utils/ws.ts +5 -1
  68. package/backend/ws/README.md +128 -3
  69. package/backend/ws/access.ts +56 -0
  70. package/backend/ws/auth/index.ts +14 -0
  71. package/backend/ws/auth/login.ts +3 -0
  72. package/backend/ws/auth/users.ts +61 -1
  73. package/backend/ws/chat/stream.ts +139 -22
  74. package/backend/ws/db-client/access.ts +19 -0
  75. package/backend/ws/db-client/connections.ts +31 -17
  76. package/backend/ws/db-client/io.ts +7 -9
  77. package/backend/ws/db-client/query.ts +86 -32
  78. package/backend/ws/db-client/schema.ts +9 -4
  79. package/backend/ws/db-client/structure.ts +22 -10
  80. package/backend/ws/engine/access.ts +39 -0
  81. package/backend/ws/engine/claude/accounts.ts +15 -10
  82. package/backend/ws/engine/codex/accounts.ts +516 -0
  83. package/backend/ws/engine/codex/index.ts +14 -0
  84. package/backend/ws/engine/codex/status.ts +87 -0
  85. package/backend/ws/engine/copilot/accounts.ts +122 -0
  86. package/backend/ws/engine/copilot/index.ts +13 -0
  87. package/backend/ws/engine/copilot/status.ts +54 -0
  88. package/backend/ws/engine/index.ts +7 -1
  89. package/backend/ws/engine/opencode/providers.ts +1 -1
  90. package/backend/ws/engine/qwen/accounts.ts +137 -0
  91. package/backend/ws/engine/qwen/index.ts +15 -0
  92. package/backend/ws/engine/qwen/presets.ts +40 -0
  93. package/backend/ws/engine/qwen/status.ts +54 -0
  94. package/backend/ws/files/path-access.ts +101 -0
  95. package/backend/ws/files/read.ts +26 -11
  96. package/backend/ws/files/search.ts +10 -6
  97. package/backend/ws/files/state.ts +3 -0
  98. package/backend/ws/files/watch.ts +7 -1
  99. package/backend/ws/files/write.ts +109 -15
  100. package/backend/ws/git/branch.ts +13 -19
  101. package/backend/ws/git/commit-message.ts +3 -4
  102. package/backend/ws/git/commit.ts +5 -7
  103. package/backend/ws/git/conflict.ts +7 -10
  104. package/backend/ws/git/diff.ts +7 -10
  105. package/backend/ws/git/log.ts +3 -4
  106. package/backend/ws/git/remote.ts +30 -43
  107. package/backend/ws/git/staging.ts +13 -19
  108. package/backend/ws/git/status.ts +7 -11
  109. package/backend/ws/messages/crud.ts +7 -13
  110. package/backend/ws/preview/access.ts +45 -0
  111. package/backend/ws/preview/browser/cleanup.ts +3 -11
  112. package/backend/ws/preview/browser/console.ts +7 -42
  113. package/backend/ws/preview/browser/interact.ts +2 -6
  114. package/backend/ws/preview/browser/native-ui.ts +5 -18
  115. package/backend/ws/preview/browser/stats.ts +2 -12
  116. package/backend/ws/preview/browser/tab-info.ts +4 -20
  117. package/backend/ws/preview/browser/tab.ts +4 -27
  118. package/backend/ws/preview/browser/webcodecs.ts +6 -47
  119. package/backend/ws/projects/crud.ts +15 -16
  120. package/backend/ws/projects/status.ts +5 -1
  121. package/backend/ws/sessions/crud.ts +31 -36
  122. package/backend/ws/settings/crud.ts +13 -13
  123. package/backend/ws/snapshot/restore.ts +5 -2
  124. package/backend/ws/snapshot/timeline.ts +3 -1
  125. package/backend/ws/system-tools/access.ts +28 -0
  126. package/backend/ws/system-tools/install.ts +13 -4
  127. package/backend/ws/system-tools/status.ts +5 -2
  128. package/backend/ws/terminal/access.ts +56 -0
  129. package/backend/ws/terminal/persistence.ts +13 -7
  130. package/backend/ws/terminal/session.ts +35 -14
  131. package/backend/ws/terminal/stream.ts +4 -1
  132. package/dist/assets/{index-DqAGCTFT.js → index-C1afGwHY.js} +2 -2
  133. package/dist/assets/main-CZb3Y_Z_.js +315 -0
  134. package/dist/assets/main-Cn8cX2DY.css +1 -0
  135. package/dist/index.html +2 -2
  136. package/package.json +5 -1
  137. package/shared/constants/engines.ts +45 -140
  138. package/shared/types/database/schema.ts +1 -0
  139. package/shared/types/unified/common.ts +1 -1
  140. package/shared/types/unified/engine.ts +29 -1
  141. package/shared/types/unified/index.ts +2 -0
  142. package/shared/types/unified/message.ts +1 -1
  143. package/shared/types/unified/tool.ts +17 -2
  144. package/shared/utils/ws-server.ts +14 -0
  145. package/dist/assets/main-DsED0rLr.js +0 -304
  146. package/dist/assets/main-eWY9R8g9.css +0 -1
@@ -0,0 +1,516 @@
1
+ /**
2
+ * OpenAI Codex Account Management Handlers
3
+ *
4
+ * Codex supports TWO auth modes (per backend/engine/README.md §9.13):
5
+ *
6
+ * 1. **API key** — paste-token flow, identical to Copilot's. The `apiKey`
7
+ * is wrapped as `{kind:"api_key", apiKey}` and stored in
8
+ * `engine_accounts.credential`. No filesystem mutation.
9
+ *
10
+ * 2. **ChatGPT browser OAuth** — spawn `codex login` inside a PTY (so the
11
+ * CLI thinks it's interactive and emits its banner + URL prompt),
12
+ * scrape stdout for the `https://auth.openai.com/...` URL, surface it
13
+ * to the UI. The CLI writes `~/.codex/auth.json` after the user
14
+ * finishes OAuth in the browser. We snapshot the file content into
15
+ * `engine_accounts.credential` as `{kind:"chatgpt", authJson:<file>}`.
16
+ *
17
+ * Headless fallback: `codex login --device-auth` produces a device code
18
+ * printed to stdout that the user enters at openai.com/auth/device.
19
+ *
20
+ * Switching between accounts:
21
+ * - chatgpt → write the stored `authJson` blob back to `~/.codex/auth.json`
22
+ * (atomic replace) so the next `codex exec` subprocess picks it up.
23
+ * - api_key → no filesystem mutation; the engine adapter passes `apiKey` to
24
+ * `new Codex({ apiKey })`.
25
+ *
26
+ * Concurrency: a backend-wide mutex serializes ChatGPT login flows because
27
+ * `codex login` writes to the shared `~/.codex/auth.json` — two concurrent
28
+ * logins would clobber each other.
29
+ *
30
+ * Why a PTY (bun-pty) instead of Bun.spawn pipes?
31
+ * The Codex CLI suppresses its sign-in banner (URL / device-code prompt)
32
+ * when stdout is not a TTY — running it under a pipe yields zero output,
33
+ * leaving the UI stuck on "Waiting for browser sign-in…". A real PTY
34
+ * makes the CLI behave as if a human were watching, so the prompt text
35
+ * reaches us and we can scrape it.
36
+ */
37
+
38
+ import { t } from 'elysia';
39
+ import { spawn } from 'bun-pty';
40
+ import { createRouter } from '$shared/utils/ws-server';
41
+ import { ws } from '$backend/utils/ws';
42
+ import { engineQueries } from '../../../database/queries';
43
+ import { disposeAllProjectEnginesByType } from '../../../engine';
44
+ import {
45
+ authModeOf,
46
+ applyAccountAuth,
47
+ readAuthJson,
48
+ serializeCodexCredential,
49
+ } from '../../../engine/adapters/codex/credential';
50
+ import { resolveBinaryWithRefresh } from '../../../utils/cli';
51
+ import { getCleanSpawnEnv } from '../../../utils/env';
52
+ import { debug } from '$shared/utils/logger';
53
+ import { requireSetupSessionAccess } from '../access';
54
+
55
+ // ─────────────────────────────────────────────────────────────────────────────
56
+ // ANSI helpers — Codex emits coloured output and cursor moves; we strip them
57
+ // before pattern-matching but stream the raw bytes (with ANSI) to the UI's
58
+ // xterm.js so the user sees the CLI exactly as it would render in a real
59
+ // terminal.
60
+ // ─────────────────────────────────────────────────────────────────────────────
61
+
62
+ function stripAnsi(str: string): string {
63
+ return str
64
+ .replace(/\x1B\[\d+;\d+[Hf]/g, '\n')
65
+ .replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, '');
66
+ }
67
+
68
+ // ─────────────────────────────────────────────────────────────────────────────
69
+ // Engine cleanup helper — called after any account mutation that might affect
70
+ // the active account so the next stream re-reads the credential from DB.
71
+ // ─────────────────────────────────────────────────────────────────────────────
72
+
73
+ async function disposeCodexEngines(): Promise<void> {
74
+ try {
75
+ await disposeAllProjectEnginesByType('codex');
76
+ } catch {
77
+ /* engine may not be initialised — ignore */
78
+ }
79
+ }
80
+
81
+ // ─────────────────────────────────────────────────────────────────────────────
82
+ // ChatGPT login PTY management
83
+ // ─────────────────────────────────────────────────────────────────────────────
84
+
85
+ interface CodexLoginProcess {
86
+ pty: ReturnType<typeof spawn>;
87
+ buffer: string;
88
+ urlEmitted: boolean;
89
+ completed: boolean;
90
+ cancelled: boolean;
91
+ disposed: boolean;
92
+ userId: string;
93
+ accountName: string;
94
+ deviceAuth: boolean;
95
+ timer: ReturnType<typeof setTimeout>;
96
+ }
97
+
98
+ const setupProcesses = new Map<string, CodexLoginProcess>();
99
+ const userSetups = new Map<string, string>();
100
+
101
+ const SETUP_TIMEOUT_MS = 15 * 60 * 1000; // 15 minutes — matches device-code expiry window
102
+
103
+ /**
104
+ * Backend-wide mutex protecting `codex login` so two simultaneous calls don't
105
+ * clobber `~/.codex/auth.json`. Implemented as a chained Promise — every new
106
+ * login waits for the previous one to settle before spawning.
107
+ */
108
+ let codexLoginChain: Promise<void> = Promise.resolve();
109
+ function serializeCodexLogin<T>(work: () => Promise<T>): Promise<T> {
110
+ const next = codexLoginChain.then(() => work());
111
+ codexLoginChain = next.then(() => undefined, () => undefined);
112
+ return next;
113
+ }
114
+
115
+ function cleanupSetup(setupId: string): void {
116
+ const entry = setupProcesses.get(setupId);
117
+ if (!entry || entry.disposed) return;
118
+ entry.disposed = true;
119
+ clearTimeout(entry.timer);
120
+ if (!entry.completed) {
121
+ try { entry.pty.kill(); } catch { /* already dead */ }
122
+ }
123
+ userSetups.delete(entry.userId);
124
+ setupProcesses.delete(setupId);
125
+ }
126
+
127
+ function extractAuthUrl(buffer: string): string | null {
128
+ // Browser-OAuth flow URL printed by `codex login` (no --device-auth).
129
+ const match = buffer.match(/https:\/\/auth\.openai\.com\/oauth\/authorize\?[^\s]+/);
130
+ return match ? match[0] : null;
131
+ }
132
+
133
+ function extractDeviceCode(buffer: string): { code: string; verificationUrl: string } | null {
134
+ // `codex login --device-auth` (v0.120+) prints a multi-line block:
135
+ // 1. Open this link in your browser and sign in to your account
136
+ // https://auth.openai.com/codex/device
137
+ //
138
+ // 2. Enter this one-time code (expires in 15 minutes)
139
+ // 6XUJ-L2VE1
140
+ //
141
+ // The code lives on its own line, indented. The URL is any
142
+ // auth.openai.com path containing "device".
143
+ const urlMatch = buffer.match(/https:\/\/[^\s]*openai\.com\/[^\s]*device[^\s]*/i);
144
+ if (!urlMatch) return null;
145
+
146
+ // Codes seen so far are 4–5 alphanum chars, dash, 4–5 alphanum chars
147
+ // (e.g. "6XUJ-L2VE1"). Match on its own line so we don't pick up
148
+ // stray dashes from the banner.
149
+ const codeMatch = buffer.match(/(?:^|\n)\s*([A-Z0-9]{3,8}-[A-Z0-9]{3,8})\s*(?:\r?\n|$)/);
150
+ if (!codeMatch) return null;
151
+
152
+ return { code: codeMatch[1], verificationUrl: urlMatch[0] };
153
+ }
154
+
155
+ function isLoginSuccess(buffer: string): boolean {
156
+ return /Successfully logged in/i.test(buffer);
157
+ }
158
+
159
+ function persistChatGptLoginResult(accountName: string): { ok: true; accountId: number } | { ok: false; error: string } {
160
+ const provider = engineQueries.getProviderBySlug('codex', 'openai');
161
+ if (!provider) return { ok: false, error: 'OpenAI Codex provider not found in DB' };
162
+
163
+ const authJson = readAuthJson();
164
+ if (authJson === null) {
165
+ return { ok: false, error: 'Codex CLI reported success but ~/.codex/auth.json was not found' };
166
+ }
167
+
168
+ const credential = serializeCodexCredential({ kind: 'chatgpt', authJson });
169
+ const account = engineQueries.createAccount(provider.id, accountName, credential);
170
+ return { ok: true, accountId: account.id };
171
+ }
172
+
173
+ // ─────────────────────────────────────────────────────────────────────────────
174
+ // Handlers
175
+ // ─────────────────────────────────────────────────────────────────────────────
176
+
177
+ export const codexAccountsHandler = createRouter()
178
+
179
+ .http('engine:codex-accounts-list', {
180
+ data: t.Object({}),
181
+ response: t.Object({
182
+ accounts: t.Array(t.Object({
183
+ id: t.Number(),
184
+ name: t.String(),
185
+ isActive: t.Boolean(),
186
+ authMode: t.Union([t.Literal('api_key'), t.Literal('chatgpt'), t.Null()]),
187
+ createdAt: t.String()
188
+ }))
189
+ })
190
+ }, async () => {
191
+ const provider = engineQueries.getProviderBySlug('codex', 'openai');
192
+ if (!provider) return { accounts: [] };
193
+ const accounts = engineQueries.getAccountsByProvider(provider.id);
194
+ return {
195
+ accounts: accounts.map(a => ({
196
+ id: a.id,
197
+ name: a.name,
198
+ isActive: a.is_active === 1,
199
+ authMode: authModeOf(a),
200
+ createdAt: a.created_at
201
+ }))
202
+ };
203
+ })
204
+
205
+ // ─── API-key flow (paste-token) ───
206
+ .http('engine:codex-accounts-add-api-key', {
207
+ data: t.Object({
208
+ name: t.String({ minLength: 1 }),
209
+ apiKey: t.String({ minLength: 1 })
210
+ }),
211
+ response: t.Object({
212
+ account: t.Object({
213
+ id: t.Number(),
214
+ name: t.String(),
215
+ isActive: t.Boolean(),
216
+ authMode: t.Union([t.Literal('api_key'), t.Literal('chatgpt'), t.Null()]),
217
+ createdAt: t.String()
218
+ })
219
+ })
220
+ }, async ({ data }) => {
221
+ const provider = engineQueries.getProviderBySlug('codex', 'openai');
222
+ if (!provider) {
223
+ throw new Error('OpenAI Codex provider not found in database');
224
+ }
225
+
226
+ const credential = serializeCodexCredential({ kind: 'api_key', apiKey: data.apiKey.trim() });
227
+ const account = engineQueries.createAccount(provider.id, data.name.trim(), credential);
228
+
229
+ if (account.is_active === 1) {
230
+ await disposeCodexEngines();
231
+ }
232
+
233
+ return {
234
+ account: {
235
+ id: account.id,
236
+ name: account.name,
237
+ isActive: account.is_active === 1,
238
+ authMode: authModeOf(account),
239
+ createdAt: account.created_at
240
+ }
241
+ };
242
+ })
243
+
244
+ .http('engine:codex-accounts-switch', {
245
+ data: t.Object({ id: t.Number() }),
246
+ response: t.Object({ success: t.Boolean() })
247
+ }, async ({ data }) => {
248
+ const account = engineQueries.getAccount(data.id);
249
+ if (!account) throw new Error('Account not found');
250
+
251
+ engineQueries.switchAccount(data.id);
252
+
253
+ // For ChatGPT-mode accounts, swap `~/.codex/auth.json` immediately so
254
+ // the next `codex exec` (which may run before the engine's
255
+ // stream-start hook fires) reads the right credential.
256
+ applyAccountAuth(account);
257
+
258
+ await disposeCodexEngines();
259
+ return { success: true };
260
+ })
261
+
262
+ .http('engine:codex-accounts-delete', {
263
+ data: t.Object({ id: t.Number() }),
264
+ response: t.Object({ success: t.Boolean() })
265
+ }, async ({ data }) => {
266
+ const active = engineQueries.getActiveAccountForEngine('codex');
267
+ engineQueries.deleteAccount(data.id);
268
+
269
+ if (active?.id === data.id) {
270
+ // The new active account (auto-promoted by deleteAccount) needs its
271
+ // auth applied so the next stream uses the correct credential.
272
+ const newActive = engineQueries.getActiveAccountForEngine('codex');
273
+ if (newActive) applyAccountAuth(newActive);
274
+ await disposeCodexEngines();
275
+ }
276
+ return { success: true };
277
+ })
278
+
279
+ .http('engine:codex-accounts-rename', {
280
+ data: t.Object({ id: t.Number(), name: t.String({ minLength: 1 }) }),
281
+ response: t.Object({ success: t.Boolean() })
282
+ }, async ({ data }) => {
283
+ engineQueries.renameAccount(data.id, data.name.trim());
284
+ return { success: true };
285
+ })
286
+
287
+ // ─── ChatGPT browser OAuth flow ───
288
+ //
289
+ // Spawn `codex login` in a PTY (the CLI silently no-ops when stdout
290
+ // isn't a TTY), scan stdout for the URL/device-code prompt, surface it
291
+ // to the UI, then on success snapshot ~/.codex/auth.json into
292
+ // engine_accounts.credential.
293
+ .on('engine:codex-account-setup-start', {
294
+ data: t.Object({
295
+ name: t.String({ minLength: 1 }),
296
+ deviceAuth: t.Optional(t.Boolean())
297
+ })
298
+ }, async ({ data, conn }) => {
299
+ const userId = ws.getUserId(conn);
300
+ const setupId = crypto.randomUUID();
301
+
302
+ debug.log('engine', `[${setupId}] Starting codex login PTY (deviceAuth=${!!data.deviceAuth})`);
303
+
304
+ // Cancel any existing setup for this user — only one login at a time.
305
+ const existing = userSetups.get(userId);
306
+ if (existing) cleanupSetup(existing);
307
+
308
+ const codexCmd = await resolveBinaryWithRefresh('codex');
309
+ if (!codexCmd) {
310
+ ws.emit.user(userId, 'engine:codex-account-setup-error', {
311
+ setupId,
312
+ message: 'Codex CLI not found on PATH. Install it via Settings → System Tools.'
313
+ });
314
+ return;
315
+ }
316
+
317
+ // Serialize across all in-flight Codex logins so we don't clobber
318
+ // ~/.codex/auth.json. Each setup waits for the previous to settle.
319
+ await serializeCodexLogin(async () => {
320
+ const args = data.deviceAuth ? ['login', '--device-auth'] : ['login'];
321
+
322
+ // Clean env + force a non-interactive browser fallback so the CLI
323
+ // prints the URL instead of trying to open a browser on the
324
+ // server. (`BROWSER=false` is honoured by most OS open helpers.)
325
+ const ptyEnv = getCleanSpawnEnv();
326
+ ptyEnv['BROWSER'] = 'false';
327
+
328
+ let pty: ReturnType<typeof spawn>;
329
+ try {
330
+ pty = spawn(codexCmd, args, {
331
+ name: 'xterm-256color',
332
+ cols: 1000,
333
+ rows: 30,
334
+ cwd: process.cwd(),
335
+ env: ptyEnv,
336
+ });
337
+ } catch (err) {
338
+ ws.emit.user(userId, 'engine:codex-account-setup-error', {
339
+ setupId,
340
+ message: `Failed to start codex login: ${err instanceof Error ? err.message : String(err)}`
341
+ });
342
+ return;
343
+ }
344
+
345
+ const timer = setTimeout(() => {
346
+ ws.emit.user(userId, 'engine:codex-account-setup-error', {
347
+ setupId,
348
+ message: 'Codex login timed out after 15 minutes'
349
+ });
350
+ cleanupSetup(setupId);
351
+ }, SETUP_TIMEOUT_MS);
352
+
353
+ const entry: CodexLoginProcess = {
354
+ pty,
355
+ buffer: '',
356
+ urlEmitted: false,
357
+ completed: false,
358
+ cancelled: false,
359
+ disposed: false,
360
+ userId,
361
+ accountName: data.name.trim(),
362
+ deviceAuth: !!data.deviceAuth,
363
+ timer,
364
+ };
365
+ setupProcesses.set(setupId, entry);
366
+ userSetups.set(userId, setupId);
367
+
368
+ // ── Single onData listener — matches the Claude Code pattern ──
369
+ pty.onData((chunk: string) => {
370
+ if (entry.disposed || entry.completed) return;
371
+ entry.buffer += chunk;
372
+
373
+ // Stream raw PTY bytes to the UI's xterm.js (handles ANSI).
374
+ ws.emit.user(userId, 'engine:codex-account-setup-stream-data', {
375
+ setupId,
376
+ data: chunk,
377
+ });
378
+
379
+ const clean = stripAnsi(entry.buffer);
380
+
381
+ if (!entry.deviceAuth && !entry.urlEmitted) {
382
+ const url = extractAuthUrl(clean);
383
+ if (url) {
384
+ entry.urlEmitted = true;
385
+ debug.log('engine', `[${setupId}] Auth URL captured`);
386
+ ws.emit.user(userId, 'engine:codex-account-setup-url', {
387
+ setupId,
388
+ authUrl: url,
389
+ });
390
+ }
391
+ }
392
+
393
+ if (entry.deviceAuth && !entry.urlEmitted) {
394
+ const device = extractDeviceCode(clean);
395
+ if (device) {
396
+ entry.urlEmitted = true;
397
+ debug.log('engine', `[${setupId}] Device code captured: ${device.code}`);
398
+ ws.emit.user(userId, 'engine:codex-account-setup-device-code', {
399
+ setupId,
400
+ code: device.code,
401
+ verificationUrl: device.verificationUrl,
402
+ });
403
+ }
404
+ }
405
+
406
+ if (isLoginSuccess(clean) && !entry.completed) {
407
+ entry.completed = true;
408
+ debug.log('engine', `[${setupId}] Codex login success — persisting auth.json`);
409
+ const result = persistChatGptLoginResult(entry.accountName);
410
+ if (result.ok) {
411
+ disposeCodexEngines().finally(() => {
412
+ ws.emit.user(userId, 'engine:codex-account-setup-complete', {
413
+ setupId,
414
+ accountId: result.accountId,
415
+ });
416
+ });
417
+ } else {
418
+ ws.emit.user(userId, 'engine:codex-account-setup-error', {
419
+ setupId,
420
+ message: result.error,
421
+ });
422
+ }
423
+ try { entry.pty.kill(); } catch { /* ignore */ }
424
+ cleanupSetup(setupId);
425
+ }
426
+ });
427
+
428
+ pty.onExit(({ exitCode }) => {
429
+ if (entry.disposed || entry.cancelled) return;
430
+ if (entry.completed) return;
431
+
432
+ const clean = stripAnsi(entry.buffer);
433
+
434
+ // Last-chance success check — sometimes the success line lands
435
+ // in the final chunk right before exit.
436
+ if (isLoginSuccess(clean)) {
437
+ entry.completed = true;
438
+ const result = persistChatGptLoginResult(entry.accountName);
439
+ if (result.ok) {
440
+ disposeCodexEngines().finally(() => {
441
+ ws.emit.user(userId, 'engine:codex-account-setup-complete', {
442
+ setupId,
443
+ accountId: result.accountId,
444
+ });
445
+ });
446
+ } else {
447
+ ws.emit.user(userId, 'engine:codex-account-setup-error', {
448
+ setupId,
449
+ message: result.error,
450
+ });
451
+ }
452
+ } else {
453
+ ws.emit.user(userId, 'engine:codex-account-setup-error', {
454
+ setupId,
455
+ message: exitCode === 0
456
+ ? 'Codex login exited without confirming success'
457
+ : `Codex login exited with code ${exitCode}`,
458
+ });
459
+ }
460
+ cleanupSetup(setupId);
461
+ });
462
+ });
463
+ })
464
+
465
+ .on('engine:codex-account-setup-cancel', {
466
+ data: t.Object({ setupId: t.String() })
467
+ }, async ({ data, conn }) => {
468
+ let entry: CodexLoginProcess;
469
+ try {
470
+ entry = requireSetupSessionAccess(conn, data.setupId, setupProcesses);
471
+ } catch {
472
+ return;
473
+ }
474
+ entry.cancelled = true;
475
+ cleanupSetup(data.setupId);
476
+ })
477
+
478
+ // Restart all Codex engine instances. Use after changing the active
479
+ // account so subsequent models:list / chat calls re-initialise with the
480
+ // right credential. (The auth-blob swap on accounts-switch already
481
+ // handles the on-disk file; this just drops cached engine instances.)
482
+ .http('engine:codex-restart', {
483
+ data: t.Object({}),
484
+ response: t.Object({ success: t.Boolean() })
485
+ }, async () => {
486
+ await disposeCodexEngines();
487
+ return { success: true };
488
+ })
489
+
490
+ // ─── Server → client events ───
491
+
492
+ .emit('engine:codex-account-setup-url', t.Object({
493
+ setupId: t.String(),
494
+ authUrl: t.String()
495
+ }))
496
+
497
+ .emit('engine:codex-account-setup-device-code', t.Object({
498
+ setupId: t.String(),
499
+ code: t.String(),
500
+ verificationUrl: t.String()
501
+ }))
502
+
503
+ .emit('engine:codex-account-setup-complete', t.Object({
504
+ setupId: t.String(),
505
+ accountId: t.Number()
506
+ }))
507
+
508
+ .emit('engine:codex-account-setup-error', t.Object({
509
+ setupId: t.String(),
510
+ message: t.String()
511
+ }))
512
+
513
+ .emit('engine:codex-account-setup-stream-data', t.Object({
514
+ setupId: t.String(),
515
+ data: t.String()
516
+ }));
@@ -0,0 +1,14 @@
1
+ /**
2
+ * OpenAI Codex Engine Router
3
+ *
4
+ * Combines status detection and account management handlers (incl. dual auth
5
+ * flow — API key + ChatGPT browser OAuth + device-auth fallback).
6
+ */
7
+
8
+ import { createRouter } from '$shared/utils/ws-server';
9
+ import { codexStatusHandler } from './status';
10
+ import { codexAccountsHandler } from './accounts';
11
+
12
+ export const codexEngineRouter = createRouter()
13
+ .merge(codexStatusHandler)
14
+ .merge(codexAccountsHandler);
@@ -0,0 +1,87 @@
1
+ /**
2
+ * OpenAI Codex Engine Status Handler
3
+ *
4
+ * Reports SDK availability + active account state. Codex differs from
5
+ * Copilot in that the SDK does NOT bundle a CLI internally — the CLI must
6
+ * be installed on PATH (System Tools → Codex CLI). `installed` reflects
7
+ * whether the `codex` binary resolves on the host's PATH.
8
+ */
9
+
10
+ import { t } from 'elysia';
11
+ import { createRouter } from '$shared/utils/ws-server';
12
+ import { engineQueries } from '../../../database/queries';
13
+ import { resolveBinaryWithRefresh } from '../../../utils/cli';
14
+ import { getBackendOS } from '../../../utils/os';
15
+ import { debug } from '$shared/utils/logger';
16
+
17
+ function readSdkVersion(): string | null {
18
+ try {
19
+ const path = require.resolve('@openai/codex-sdk/package.json');
20
+ const pkg = require(path) as { version?: string };
21
+ return pkg.version ?? null;
22
+ } catch {
23
+ return null;
24
+ }
25
+ }
26
+
27
+ async function readCliVersion(): Promise<string | null> {
28
+ const bin = await resolveBinaryWithRefresh('codex');
29
+ if (!bin) return null;
30
+ try {
31
+ const proc = Bun.spawn([bin, '--version'], { stdout: 'pipe', stderr: 'pipe' });
32
+ const exitCode = await proc.exited;
33
+ if (exitCode !== 0) return null;
34
+ const stdout = await new Response(proc.stdout).text();
35
+ const first = stdout.trim().split('\n')[0]?.trim() ?? '';
36
+ return first || null;
37
+ } catch {
38
+ return null;
39
+ }
40
+ }
41
+
42
+ export const codexStatusHandler = createRouter()
43
+ .http('engine:codex-status', {
44
+ data: t.Object({}),
45
+ response: t.Object({
46
+ installed: t.Boolean(),
47
+ version: t.Union([t.String(), t.Null()]),
48
+ sdkVersion: t.Union([t.String(), t.Null()]),
49
+ activeAccount: t.Union([
50
+ t.Object({
51
+ id: t.Number(),
52
+ name: t.String(),
53
+ authMode: t.Union([t.Literal('api_key'), t.Literal('chatgpt'), t.Null()])
54
+ }),
55
+ t.Null()
56
+ ]),
57
+ accountsCount: t.Number(),
58
+ backendOS: t.Union([t.Literal('windows'), t.Literal('macos'), t.Literal('linux')])
59
+ })
60
+ }, async () => {
61
+ debug.log('engine', 'Checking Codex status...');
62
+
63
+ const provider = engineQueries.getProviderBySlug('codex', 'openai');
64
+ const accounts = provider ? engineQueries.getAccountsByProvider(provider.id) : [];
65
+ const activeAccount = engineQueries.getActiveAccountForEngine('codex');
66
+
67
+ const cliVersion = await readCliVersion();
68
+
69
+ // authMode parsing — defer the import to avoid initializing fs paths in
70
+ // the status hot path; only matters when an active account exists.
71
+ let authMode: 'api_key' | 'chatgpt' | null = null;
72
+ if (activeAccount) {
73
+ const { authModeOf } = await import('../../../engine/adapters/codex/credential');
74
+ authMode = authModeOf(activeAccount);
75
+ }
76
+
77
+ return {
78
+ installed: cliVersion !== null,
79
+ version: cliVersion,
80
+ sdkVersion: readSdkVersion(),
81
+ activeAccount: activeAccount
82
+ ? { id: activeAccount.id, name: activeAccount.name, authMode }
83
+ : null,
84
+ accountsCount: accounts.length,
85
+ backendOS: getBackendOS()
86
+ };
87
+ });