@myrialabs/clopen 0.3.7 → 0.3.9

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 (149) hide show
  1. package/backend/auth/permissions.ts +41 -2
  2. package/backend/chat/stream-manager.ts +71 -0
  3. package/backend/database/migrations/030_add_files_panel_state_to_user_projects.ts +34 -0
  4. package/backend/database/migrations/031_create_db_client_tables.ts +74 -0
  5. package/backend/database/migrations/032_seed_copilot_provider.ts +19 -0
  6. package/backend/database/migrations/033_seed_codex_provider.ts +19 -0
  7. package/backend/database/migrations/034_seed_qwen_provider.ts +119 -0
  8. package/backend/database/migrations/035_add_owner_to_db_client_connections.ts +34 -0
  9. package/backend/database/migrations/index.ts +43 -1
  10. package/backend/database/queries/db-client-connection-queries.ts +343 -0
  11. package/backend/database/queries/db-client-query-history-queries.ts +113 -0
  12. package/backend/database/queries/engine-queries.ts +12 -0
  13. package/backend/database/queries/index.ts +3 -1
  14. package/backend/database/queries/project-queries.ts +28 -0
  15. package/backend/db-client/connection-manager.ts +257 -0
  16. package/backend/db-client/drivers/bun-sql-helpers.ts +41 -0
  17. package/backend/db-client/drivers/mongodb.ts +358 -0
  18. package/backend/db-client/drivers/mysql.ts +385 -0
  19. package/backend/db-client/drivers/postgres.ts +446 -0
  20. package/backend/db-client/drivers/redis.ts +267 -0
  21. package/backend/db-client/drivers/sql-builders.ts +215 -0
  22. package/backend/db-client/drivers/sqlite.ts +346 -0
  23. package/backend/db-client/drivers/types.ts +92 -0
  24. package/backend/db-client/query-executor.ts +126 -0
  25. package/backend/db-client/ssh-tunnel.ts +122 -0
  26. package/backend/engine/README.md +1702 -0
  27. package/backend/engine/adapters/claude/models.ts +141 -0
  28. package/backend/engine/adapters/claude/stream.ts +1 -1
  29. package/backend/engine/adapters/codex/credential.ts +179 -0
  30. package/backend/engine/adapters/codex/error-handler.ts +65 -0
  31. package/backend/engine/adapters/codex/index.ts +1 -0
  32. package/backend/engine/adapters/codex/message-converter.ts +646 -0
  33. package/backend/engine/adapters/codex/models.ts +105 -0
  34. package/backend/engine/adapters/codex/patch-rollout.ts +169 -0
  35. package/backend/engine/adapters/codex/session-fork.ts +149 -0
  36. package/backend/engine/adapters/codex/stream.ts +310 -0
  37. package/backend/engine/adapters/codex/usage-rollout.ts +145 -0
  38. package/backend/engine/adapters/copilot/error-handler.ts +94 -0
  39. package/backend/engine/adapters/copilot/index.ts +1 -0
  40. package/backend/engine/adapters/copilot/message-converter.ts +973 -0
  41. package/backend/engine/adapters/copilot/models.ts +92 -0
  42. package/backend/engine/adapters/copilot/session-fork.ts +111 -0
  43. package/backend/engine/adapters/copilot/stream.ts +573 -0
  44. package/backend/engine/adapters/opencode/config.ts +56 -104
  45. package/backend/engine/adapters/opencode/error-handler.ts +71 -0
  46. package/backend/engine/adapters/opencode/models.ts +79 -0
  47. package/backend/engine/adapters/opencode/presets.ts +91 -0
  48. package/backend/engine/adapters/opencode/stream.ts +5 -115
  49. package/backend/engine/adapters/qwen/credential.ts +78 -0
  50. package/backend/engine/adapters/qwen/environment.ts +84 -0
  51. package/backend/engine/adapters/qwen/error-handler.ts +71 -0
  52. package/backend/engine/adapters/qwen/index.ts +1 -0
  53. package/backend/engine/adapters/qwen/message-converter.ts +1055 -0
  54. package/backend/engine/adapters/qwen/models.ts +81 -0
  55. package/backend/engine/adapters/qwen/presets.ts +51 -0
  56. package/backend/engine/adapters/qwen/session-fork.ts +97 -0
  57. package/backend/engine/adapters/qwen/stream.ts +380 -0
  58. package/backend/engine/index.ts +35 -0
  59. package/backend/engine/install-recipes.ts +80 -1
  60. package/backend/engine/install-runner.ts +4 -0
  61. package/backend/git/git-service.ts +12 -0
  62. package/backend/mcp/README.md +84 -14
  63. package/backend/mcp/config.ts +218 -17
  64. package/backend/mcp/index.ts +2 -0
  65. package/backend/mcp/project-context.ts +55 -0
  66. package/backend/mcp/servers/browser-automation/actions.ts +6 -1
  67. package/backend/mcp/servers/helper.ts +13 -0
  68. package/backend/middleware/error-handler.ts +16 -2
  69. package/backend/preview/browser/browser-preview-service.ts +4 -4
  70. package/backend/preview/browser/scripts/video-stream.ts +9 -3
  71. package/backend/ws/README.md +128 -3
  72. package/backend/ws/access.ts +56 -0
  73. package/backend/ws/chat/stream.ts +36 -12
  74. package/backend/ws/db-client/access.ts +19 -0
  75. package/backend/ws/db-client/connections.ts +194 -0
  76. package/backend/ws/db-client/index.ts +17 -0
  77. package/backend/ws/db-client/io.ts +456 -0
  78. package/backend/ws/db-client/query.ts +214 -0
  79. package/backend/ws/db-client/schema.ts +81 -0
  80. package/backend/ws/db-client/structure.ts +230 -0
  81. package/backend/ws/engine/access.ts +39 -0
  82. package/backend/ws/engine/claude/accounts.ts +15 -10
  83. package/backend/ws/engine/codex/accounts.ts +516 -0
  84. package/backend/ws/engine/codex/index.ts +14 -0
  85. package/backend/ws/engine/codex/status.ts +87 -0
  86. package/backend/ws/engine/copilot/accounts.ts +122 -0
  87. package/backend/ws/engine/copilot/index.ts +13 -0
  88. package/backend/ws/engine/copilot/status.ts +54 -0
  89. package/backend/ws/engine/index.ts +7 -1
  90. package/backend/ws/engine/opencode/providers.ts +1 -1
  91. package/backend/ws/engine/qwen/accounts.ts +137 -0
  92. package/backend/ws/engine/qwen/index.ts +15 -0
  93. package/backend/ws/engine/qwen/presets.ts +40 -0
  94. package/backend/ws/engine/qwen/status.ts +54 -0
  95. package/backend/ws/files/index.ts +5 -1
  96. package/backend/ws/files/read.ts +34 -0
  97. package/backend/ws/files/state.ts +42 -0
  98. package/backend/ws/files/watch.ts +7 -1
  99. package/backend/ws/git/branch.ts +13 -19
  100. package/backend/ws/git/commit-message.ts +3 -4
  101. package/backend/ws/git/commit.ts +5 -7
  102. package/backend/ws/git/conflict.ts +7 -10
  103. package/backend/ws/git/diff.ts +7 -10
  104. package/backend/ws/git/log.ts +3 -4
  105. package/backend/ws/git/remote.ts +30 -43
  106. package/backend/ws/git/staging.ts +13 -19
  107. package/backend/ws/git/status.ts +7 -11
  108. package/backend/ws/index.ts +5 -1
  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 +5 -40
  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 +4 -10
  120. package/backend/ws/projects/status.ts +2 -0
  121. package/backend/ws/sessions/crud.ts +22 -33
  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 +12 -6
  130. package/backend/ws/terminal/session.ts +35 -14
  131. package/backend/ws/terminal/stream.ts +4 -1
  132. package/dist/assets/{index-C86jwBxR.js → index-D8V2wj9B.js} +2 -2
  133. package/dist/assets/{main-DhLx8wD1.js → main-C9nYVmnw.js} +222 -195
  134. package/dist/assets/main-hspyFOoK.css +1 -0
  135. package/dist/index.html +2 -2
  136. package/package.json +7 -1
  137. package/shared/constants/engines.ts +45 -140
  138. package/shared/types/database/schema.ts +49 -1
  139. package/shared/types/db-client/connection.ts +60 -0
  140. package/shared/types/db-client/index.ts +6 -0
  141. package/shared/types/db-client/query.ts +77 -0
  142. package/shared/types/unified/common.ts +1 -1
  143. package/shared/types/unified/engine.ts +29 -1
  144. package/shared/types/unified/index.ts +2 -0
  145. package/shared/types/unified/message.ts +1 -1
  146. package/shared/types/unified/tool.ts +17 -2
  147. package/shared/utils/logger.ts +1 -0
  148. package/shared/utils/ws-server.ts +14 -0
  149. package/dist/assets/main-jTnmAoXS.css +0 -1
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Codex Engine Adapter
3
+ *
4
+ * Wraps `@openai/codex-sdk` into the AIEngine interface. The SDK manages a
5
+ * subprocess (`codex exec`) per turn — we only own the per-project `Codex`
6
+ * instance, the `Thread` lifecycle, and an `AbortController` for cancellation.
7
+ *
8
+ * Auth: dual mode (API key + ChatGPT browser OAuth). See ./auth.ts and
9
+ * backend/engine/README.md §9.13 for the auth-blob swap pattern.
10
+ *
11
+ * MCP: reuses the existing remote MCP HTTP server at /mcp via
12
+ * getCodexMcpConfig() in backend/mcp/config.ts. No new MCP infrastructure.
13
+ *
14
+ * TODO(codex-sdk): AskUserQuestion is currently UNSUPPORTED for Codex. The
15
+ * upstream `@openai/codex-sdk` exposes no callback hook (no `canUseTool`
16
+ * equivalent, no permission/elicitation events on the stream). Once the SDK
17
+ * surfaces a native interactive-question primitive, implement
18
+ * `resolveUserAnswer` on this adapter and route `chat:ask-user-answer` from
19
+ * `backend/ws/chat/stream.ts` to it — same pattern as Claude/OpenCode.
20
+ */
21
+
22
+ import { Codex, type Thread, type ThreadOptions, type Input as CodexInput } from '@openai/codex-sdk';
23
+ import type { EngineOutput, EngineModel } from '$shared/types/unified';
24
+ import type { AIEngine, EngineQueryOptions } from '../../types';
25
+ import { engineQueries } from '$backend/database/queries/engine-queries';
26
+ import { resolveOsPath } from '$backend/utils/paths';
27
+ import { resolveBinary } from '$backend/utils/cli';
28
+ import { getCodexMcpConfig } from '../../../mcp/config';
29
+ import { CODEX_MODELS } from './models';
30
+ import { debug } from '$shared/utils/logger';
31
+ import { handleStreamError, buildTurnError } from './error-handler';
32
+ import {
33
+ createCodexState,
34
+ convertThreadStarted,
35
+ convertTurnStarted,
36
+ convertItemStarted,
37
+ convertItemUpdated,
38
+ convertItemCompleted,
39
+ convertTurnCompleted,
40
+ buildResultEvent,
41
+ } from './message-converter';
42
+ import {
43
+ parseCodexCredential,
44
+ applyAccountAuth,
45
+ snapshotAuthJsonToActiveAccount,
46
+ } from './credential';
47
+ import { forkCodexSessionState, sessionStateExists } from './session-fork';
48
+ import path from 'node:path';
49
+ import os from 'node:os';
50
+ import fs from 'node:fs';
51
+
52
+ export class CodexEngine implements AIEngine {
53
+ readonly name = 'codex' as const;
54
+
55
+ private _isInitialized = false;
56
+ private codex: Codex | null = null;
57
+ private activeThread: Thread | null = null;
58
+ private activeController: AbortController | null = null;
59
+ /** Account ID currently baked into `this.codex`. Same trade-off as Copilot. */
60
+ private currentAccountId: number | null = null;
61
+
62
+ get isInitialized(): boolean {
63
+ return this._isInitialized;
64
+ }
65
+
66
+ get isActive(): boolean {
67
+ return this.activeController !== null;
68
+ }
69
+
70
+ async initialize(accountId?: number): Promise<void> {
71
+ if (this._isInitialized && (accountId == null || accountId === this.currentAccountId)) {
72
+ return;
73
+ }
74
+
75
+ const account = accountId != null
76
+ ? engineQueries.getAccount(accountId)
77
+ : engineQueries.getActiveAccountForEngine('codex');
78
+ if (!account) {
79
+ throw new Error('No active Codex account. Add an OpenAI API key or sign in with ChatGPT in Settings → Engines → Codex.');
80
+ }
81
+
82
+ const credential = parseCodexCredential(account.credential);
83
+ if (!credential) {
84
+ throw new Error(`Codex account "${account.name}" has an invalid credential. Re-add it in Settings → Engines.`);
85
+ }
86
+
87
+ // For ChatGPT mode, ensure ~/.codex/auth.json reflects this account
88
+ // before we construct the SDK client. For API-key mode the apiKey
89
+ // option is passed directly; no filesystem mutation.
90
+ applyAccountAuth(account);
91
+
92
+ const codexBinary = resolveBinary('codex');
93
+ const mcpConfig = getCodexMcpConfig();
94
+
95
+ // Codex SDK takes config at construction. We pass `show_raw_agent_reasoning`
96
+ // (so the SDK forwards reasoning text events), enable network access in the
97
+ // workspace-write sandbox (matches Claude/Copilot trust model — see plan §7),
98
+ // and forward the Clopen MCP HTTP endpoint to the spawned subprocess.
99
+ this.codex = new Codex({
100
+ apiKey: credential.kind === 'api_key' ? credential.apiKey : undefined,
101
+ ...(codexBinary ? { codexPathOverride: codexBinary } : {}),
102
+ config: {
103
+ show_raw_agent_reasoning: true,
104
+ sandbox_workspace_write: { network_access: true },
105
+ ...(Object.keys(mcpConfig).length > 0 ? { mcp_servers: mcpConfig } : {}),
106
+ },
107
+ });
108
+ this.currentAccountId = account.id;
109
+ this._isInitialized = true;
110
+ debug.log('engine', `Codex engine initialized (account ${account.id}, mode=${credential.kind})`);
111
+ }
112
+
113
+ async dispose(): Promise<void> {
114
+ await this.cancel();
115
+ this.codex = null;
116
+ this.currentAccountId = null;
117
+ this._isInitialized = false;
118
+ debug.log('engine', 'Codex engine disposed');
119
+ }
120
+
121
+ async getAvailableModels(): Promise<EngineModel[]> {
122
+ // Static catalog — no CLI call needed (plan §4.7).
123
+ return CODEX_MODELS;
124
+ }
125
+
126
+ async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
127
+ const { projectPath, prompt, resume, modelId, abortController, accountId } = options;
128
+
129
+ // Per-stream account override — same shape as Copilot. The SDK takes
130
+ // the apiKey at construction time, so an account switch requires
131
+ // re-creating the Codex client.
132
+ if (this._isInitialized && accountId != null && accountId !== this.currentAccountId) {
133
+ debug.log('engine', `Codex account switch ${this.currentAccountId} → ${accountId}; re-initialising`);
134
+ await this.dispose();
135
+ }
136
+ if (!this._isInitialized || !this.codex) {
137
+ await this.initialize(accountId);
138
+ }
139
+ if (!this.codex) {
140
+ throw new Error('Codex client unavailable.');
141
+ }
142
+
143
+ // Refresh auth.json for the active account every turn (cheap idempotent
144
+ // op — only writes when the file content drifts from the stored blob).
145
+ const activeAccount = accountId != null
146
+ ? engineQueries.getAccount(accountId)
147
+ : engineQueries.getActiveAccountForEngine('codex');
148
+ if (activeAccount) {
149
+ applyAccountAuth(activeAccount);
150
+ }
151
+
152
+ this.activeController = abortController || new AbortController();
153
+
154
+ const resolvedProjectPath = resolveOsPath(projectPath);
155
+ const state = createCodexState('', modelId);
156
+
157
+ const threadOptions: ThreadOptions = {
158
+ model: modelId,
159
+ workingDirectory: resolvedProjectPath,
160
+ skipGitRepoCheck: true,
161
+ sandboxMode: 'workspace-write',
162
+ approvalPolicy: 'never',
163
+ modelReasoningEffort: 'medium',
164
+ networkAccessEnabled: true,
165
+ webSearchMode: 'cached',
166
+ webSearchEnabled: true,
167
+ };
168
+
169
+ try {
170
+ let thread: Thread;
171
+
172
+ if (resume) {
173
+ // Fork-by-copy on EVERY resume — same semantics as Copilot
174
+ // (README §9.10 sharp edge: never gate on options.forkSession).
175
+ let resumeId = resume;
176
+ if (sessionStateExists(resume)) {
177
+ const forkId = crypto.randomUUID();
178
+ if (forkCodexSessionState(resume, forkId)) {
179
+ resumeId = forkId;
180
+ }
181
+ }
182
+ try {
183
+ thread = this.codex.resumeThread(resumeId, threadOptions);
184
+ debug.log('engine', `Codex resumed thread: ${resumeId}${resumeId === resume ? '' : ` (forked from ${resume})`}`);
185
+ } catch (error) {
186
+ debug.warn('engine', `Failed to resume Codex thread ${resumeId}, starting fresh:`, error);
187
+ thread = this.codex.startThread(threadOptions);
188
+ }
189
+ } else {
190
+ thread = this.codex.startThread(threadOptions);
191
+ }
192
+
193
+ this.activeThread = thread;
194
+
195
+ const input = await buildCodexInput(prompt);
196
+ const { events } = await thread.runStreamed(input, {
197
+ signal: this.activeController.signal,
198
+ });
199
+
200
+ for await (const event of events) {
201
+ if (this.activeController.signal.aborted) break;
202
+
203
+ switch (event.type) {
204
+ case 'thread.started':
205
+ yield* convertThreadStarted(event, state);
206
+ break;
207
+
208
+ case 'turn.started':
209
+ yield* convertTurnStarted(state);
210
+ break;
211
+
212
+ case 'item.started':
213
+ yield* convertItemStarted(event, state);
214
+ break;
215
+
216
+ case 'item.updated':
217
+ yield* convertItemUpdated(event, state);
218
+ break;
219
+
220
+ case 'item.completed':
221
+ yield* convertItemCompleted(event, state);
222
+ break;
223
+
224
+ case 'turn.completed':
225
+ yield* convertTurnCompleted(event, state);
226
+ break;
227
+
228
+ case 'turn.failed':
229
+ throw buildTurnError(event.error);
230
+
231
+ case 'error':
232
+ throw new Error(event.message || 'Unknown Codex error');
233
+ }
234
+ }
235
+
236
+ yield buildResultEvent(state, this.activeController.signal.aborted);
237
+ } catch (error) {
238
+ handleStreamError(error);
239
+ } finally {
240
+ // Snapshot the (possibly token-refreshed) auth.json back to DB so
241
+ // refreshes survive across account switches (README §9.13 step 4).
242
+ try {
243
+ snapshotAuthJsonToActiveAccount();
244
+ } catch (snapshotErr) {
245
+ debug.warn('engine', 'Codex: post-stream auth.json snapshot failed (non-fatal):', snapshotErr);
246
+ }
247
+ this.activeThread = null;
248
+ this.activeController = null;
249
+ }
250
+ }
251
+
252
+ async cancel(): Promise<void> {
253
+ // Abort the local controller so the for-await loop exits even if the
254
+ // SDK's signal propagation hangs.
255
+ if (this.activeController && !this.activeController.signal.aborted) {
256
+ this.activeController.abort();
257
+ }
258
+ this.activeController = null;
259
+ this.activeThread = null;
260
+ }
261
+
262
+ async interrupt(): Promise<void> {
263
+ await this.cancel();
264
+ }
265
+ }
266
+
267
+ // ============================================================================
268
+ // Helpers
269
+ // ============================================================================
270
+
271
+ async function buildCodexInput(prompt: EngineQueryOptions['prompt']): Promise<CodexInput> {
272
+ const items: Array<{ type: 'text'; text: string } | { type: 'local_image'; path: string }> = [];
273
+
274
+ for (const block of prompt.content) {
275
+ if (block.type === 'text') {
276
+ items.push({ type: 'text', text: block.text });
277
+ } else if (block.type === 'image') {
278
+ // Codex's SDK accepts local_image paths only — write the image
279
+ // bytes to a tmp file, then pass the path.
280
+ const tmpPath = await writeImageToTemp(block.data, block.mediaType);
281
+ if (tmpPath) {
282
+ items.push({ type: 'local_image', path: tmpPath });
283
+ }
284
+ }
285
+ // Document blocks (PDF) — Codex SDK has no document input. Skipped.
286
+ }
287
+
288
+ if (items.length === 0) {
289
+ return '';
290
+ }
291
+ if (items.length === 1 && items[0].type === 'text') {
292
+ return items[0].text;
293
+ }
294
+ return items;
295
+ }
296
+
297
+ async function writeImageToTemp(base64: string, mediaType: string): Promise<string | null> {
298
+ try {
299
+ const ext = mediaType.split('/')[1]?.split('+')[0] || 'png';
300
+ const tmpDir = path.join(os.tmpdir(), 'clopen-codex');
301
+ if (!fs.existsSync(tmpDir)) fs.mkdirSync(tmpDir, { recursive: true });
302
+ const tmpPath = path.join(tmpDir, `${crypto.randomUUID()}.${ext}`);
303
+ const buffer = Buffer.from(base64, 'base64');
304
+ fs.writeFileSync(tmpPath, buffer);
305
+ return tmpPath;
306
+ } catch (err) {
307
+ debug.warn('engine', 'Codex: failed to write image attachment:', err);
308
+ return null;
309
+ }
310
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Codex rollout-file usage extraction (workaround).
3
+ *
4
+ * The Codex CLI's `--experimental-json` `turn.completed.usage` is the SUM of
5
+ * `input_tokens` across every internal API call within a turn — useful for
6
+ * cost accounting but wrong for context-window display. A turn that makes 5
7
+ * tool-calling round-trips reports 5× the actual prompt size, so the UI's
8
+ * "% of context" indicator overcounts dramatically (we saw ~117k displayed
9
+ * when the real per-call load was ~20k).
10
+ *
11
+ * The CLI also writes a richer `event_msg` / `token_count` payload to the
12
+ * rollout JSONL at `~/.codex/sessions/YYYY/MM/DD/rollout-*-<thread_id>.jsonl`,
13
+ * which contains both `total_token_usage` (cumulative — what the SDK forwards)
14
+ * AND `last_token_usage` (the real per-call load). We read the rollout's last
15
+ * `token_count` event after each turn and use `last_token_usage` instead.
16
+ *
17
+ * TODO(codex-sdk): delete this entire helper once `@openai/codex-sdk` exposes
18
+ * per-call usage natively (e.g. `turn.completed.lastUsage` or a dedicated
19
+ * `token_count` event in the SDK's typed `ThreadEvent` union). When that
20
+ * lands:
21
+ * 1. Switch `convertTurnCompleted` in ./message-converter.ts back to
22
+ * reading the SDK's per-call field directly — no filesystem access.
23
+ * 2. Remove the `import { readLastTokenUsageFromRollout } from './usage-rollout'`
24
+ * line from message-converter.ts.
25
+ * 3. Delete this file.
26
+ *
27
+ * Until then, this helper is a private contract with an undocumented internal
28
+ * file format. Codex CLI may rename fields, change the directory layout, or
29
+ * stop writing rollout files between releases — keep the fallback to
30
+ * `event.usage` in `convertTurnCompleted` so the adapter degrades gracefully.
31
+ */
32
+ import fs from 'node:fs';
33
+ import path from 'node:path';
34
+ import type { Usage } from '@openai/codex-sdk';
35
+ import { getCodexHomeDir } from './credential';
36
+ import { debug } from '$shared/utils/logger';
37
+
38
+ const SESSIONS_DIR_NAME = 'sessions';
39
+
40
+ /**
41
+ * Locate the rollout file for `threadId`.
42
+ *
43
+ * Layout: `<codex-home>/sessions/YYYY/MM/DD/rollout-YYYY-MM-DDTHH-mm-ss-<thread_id>.jsonl`.
44
+ * We can't predict the timestamp prefix, so we walk year/month/day directories
45
+ * looking for a filename ending in `<thread_id>.jsonl`. Returns the freshest
46
+ * match by mtime (forks/restarts can create multiple).
47
+ */
48
+ export function findRolloutFile(threadId: string): string | null {
49
+ if (!threadId) return null;
50
+ const sessionsRoot = path.join(getCodexHomeDir(), SESSIONS_DIR_NAME);
51
+ const suffix = `${threadId}.jsonl`;
52
+ let best: { file: string; mtimeMs: number } | null = null;
53
+
54
+ let years: string[] = [];
55
+ try {
56
+ years = fs.readdirSync(sessionsRoot);
57
+ } catch {
58
+ return null;
59
+ }
60
+
61
+ for (const year of years) {
62
+ const yearDir = path.join(sessionsRoot, year);
63
+ let months: string[] = [];
64
+ try { months = fs.readdirSync(yearDir); } catch { continue; }
65
+ for (const month of months) {
66
+ const monthDir = path.join(yearDir, month);
67
+ let days: string[] = [];
68
+ try { days = fs.readdirSync(monthDir); } catch { continue; }
69
+ for (const day of days) {
70
+ const dayDir = path.join(monthDir, day);
71
+ let entries: string[] = [];
72
+ try { entries = fs.readdirSync(dayDir); } catch { continue; }
73
+ for (const entry of entries) {
74
+ if (!entry.endsWith(suffix)) continue;
75
+ const full = path.join(dayDir, entry);
76
+ try {
77
+ const stat = fs.statSync(full);
78
+ if (!best || stat.mtimeMs > best.mtimeMs) {
79
+ best = { file: full, mtimeMs: stat.mtimeMs };
80
+ }
81
+ } catch { /* ignore */ }
82
+ }
83
+ }
84
+ }
85
+ }
86
+
87
+ return best?.file ?? null;
88
+ }
89
+
90
+ interface RolloutTokenInfo {
91
+ last_token_usage?: {
92
+ input_tokens?: number;
93
+ cached_input_tokens?: number;
94
+ output_tokens?: number;
95
+ reasoning_output_tokens?: number;
96
+ };
97
+ model_context_window?: number;
98
+ }
99
+
100
+ /**
101
+ * Read the rollout file and return the most recent `token_count` event's
102
+ * `last_token_usage`. Returns null if the file or event is missing.
103
+ *
104
+ * Scans from the end of the file (one chunk at a time) so we don't load the
105
+ * full transcript into memory just to find the last entry.
106
+ */
107
+ export function readLastTokenUsageFromRollout(threadId: string): Usage | null {
108
+ const file = findRolloutFile(threadId);
109
+ if (!file) return null;
110
+
111
+ let info: RolloutTokenInfo | null = null;
112
+ try {
113
+ // Rollout files are JSONL with one event per line. Reading the whole
114
+ // file and walking lines in reverse is the simplest reliable way to
115
+ // find the last `token_count` event — these files are typically
116
+ // well under a few MB.
117
+ const content = fs.readFileSync(file, 'utf-8');
118
+ const lines = content.split('\n');
119
+ for (let i = lines.length - 1; i >= 0; i--) {
120
+ const line = lines[i];
121
+ if (!line || !line.includes('"token_count"')) continue;
122
+ try {
123
+ const parsed = JSON.parse(line);
124
+ const payload = parsed?.payload;
125
+ if (payload?.type === 'token_count' && payload.info) {
126
+ info = payload.info as RolloutTokenInfo;
127
+ break;
128
+ }
129
+ } catch { /* malformed line — keep scanning */ }
130
+ }
131
+ } catch (err) {
132
+ debug.warn('engine', `Codex usage-rollout: failed to read ${file}:`, err);
133
+ return null;
134
+ }
135
+
136
+ const last = info?.last_token_usage;
137
+ if (!last) return null;
138
+
139
+ return {
140
+ input_tokens: last.input_tokens ?? 0,
141
+ cached_input_tokens: last.cached_input_tokens ?? 0,
142
+ output_tokens: last.output_tokens ?? 0,
143
+ reasoning_output_tokens: last.reasoning_output_tokens ?? 0,
144
+ };
145
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Copilot SDK error handler.
3
+ *
4
+ * Mirrors the Claude error-handler pattern:
5
+ * - Swallow abort errors (returned during cancellation, not rethrown).
6
+ * - Map well-known Copilot error categories to user-facing messages.
7
+ * - Otherwise, enrich the message with status code / providerCallId / url.
8
+ */
9
+
10
+ import type { SessionEvent } from '@github/copilot-sdk';
11
+
12
+ type ErrorData = Extract<SessionEvent, { type: 'session.error' }>['data'];
13
+
14
+ export function handleStreamError(error: unknown): void {
15
+ if (!(error instanceof Error)) {
16
+ throw error;
17
+ }
18
+
19
+ if (
20
+ error.name === 'AbortError'
21
+ || error.message.includes('aborted')
22
+ || error.message.includes('abort')
23
+ || error.message === 'Operation aborted'
24
+ ) {
25
+ return;
26
+ }
27
+
28
+ if (error.message.includes('ENOENT') || error.message.includes('spawn copilot')) {
29
+ throw new Error('GitHub Copilot CLI not found. Reinstall @github/copilot-sdk so the bundled CLI is available.');
30
+ }
31
+
32
+ if (error.message.includes('Copilot Requests')) {
33
+ throw new Error('Your GitHub PAT is missing the "Copilot Requests" permission. Regenerate it at github.com/settings/personal-access-tokens/new and enable Copilot Requests under Account permissions.');
34
+ }
35
+
36
+ if (error.message.includes('GITHUB_TOKEN') || error.message.includes('not authenticated')) {
37
+ throw new Error('GitHub Copilot is not authenticated. Add a Personal Access Token with the "Copilot Requests" permission in Settings.');
38
+ }
39
+
40
+ throw new Error(extractDetailedError(error));
41
+ }
42
+
43
+ /**
44
+ * Build a Copilot-flavoured error from a `session.error` ErrorData payload.
45
+ * Returns an Error with errorType + statusCode + url enrichment.
46
+ */
47
+ export function buildSessionError(data: ErrorData): Error {
48
+ let message = data.message?.trim() || 'Unknown Copilot error';
49
+
50
+ switch (data.errorType) {
51
+ case 'authentication':
52
+ message = `Authentication failed: ${message}`;
53
+ break;
54
+ case 'authorization':
55
+ message = `Authorization denied: ${message}`;
56
+ break;
57
+ case 'quota':
58
+ message = `Copilot quota exceeded: ${message}`;
59
+ break;
60
+ case 'rate_limit':
61
+ message = `Copilot rate limit reached: ${message}`;
62
+ break;
63
+ case 'context_limit':
64
+ message = `Context limit exceeded: ${message}`;
65
+ break;
66
+ }
67
+
68
+ if (data.statusCode && !message.includes(String(data.statusCode))) {
69
+ message += ` (status ${data.statusCode})`;
70
+ }
71
+ if (data.providerCallId) {
72
+ message += ` [requestId: ${data.providerCallId}]`;
73
+ }
74
+ if (data.url) {
75
+ message += ` — ${data.url}`;
76
+ }
77
+
78
+ return new Error(message);
79
+ }
80
+
81
+ function extractDetailedError(error: Error): string {
82
+ const err = error as Record<string, any>;
83
+ let message = (err.message || '').replace(/^Error:\s*/, '');
84
+ if (!message) {
85
+ message = err.name && err.name !== 'Error' ? String(err.name) : 'Unknown error';
86
+ }
87
+ if (err.status && !message.includes(String(err.status))) {
88
+ message += ` (status ${err.status})`;
89
+ }
90
+ if (err.code && !message.includes(String(err.code))) {
91
+ message += ` [${err.code}]`;
92
+ }
93
+ return message || error.message || 'Unknown error';
94
+ }
@@ -0,0 +1 @@
1
+ export { CopilotEngine } from './stream';