@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,105 @@
1
+ /**
2
+ * Codex Engine model catalog.
3
+ *
4
+ * Static catalog — sourced from https://developers.openai.com/codex/models.md
5
+ * and pruned to the IDs the Codex CLI actually accepts via `--model`. Models
6
+ * tagged with `requiresAuthMode` are filtered by the chat-input account
7
+ * picker so the user can't pick a ChatGPT-only model while signed in with an
8
+ * API key account (and vice versa). Update when OpenAI ships a new
9
+ * generation.
10
+ */
11
+
12
+ import type { EngineModel } from '$shared/types/unified';
13
+
14
+ export const CODEX_MODELS: EngineModel[] = [
15
+ {
16
+ engine: {
17
+ type: 'codex',
18
+ provider: 'openai',
19
+ model: { id: 'gpt-5.4', name: 'GPT-5.4' },
20
+ account: { id: 0, name: '' },
21
+ },
22
+ limit: { input: 200_000, output: 128_000 },
23
+ modalities: {
24
+ input: { text: true, image: true, audio: false, video: false, pdf: false },
25
+ output: { text: true, image: false, audio: false, video: false, pdf: false },
26
+ },
27
+ capabilities: { reasoning: true, tools: true, structuredOutput: true },
28
+ cost: { input: 0, output: 0 },
29
+ },
30
+ {
31
+ engine: {
32
+ type: 'codex',
33
+ provider: 'openai',
34
+ model: { id: 'gpt-5.4-mini', name: 'GPT-5.4 mini' },
35
+ account: { id: 0, name: '' },
36
+ },
37
+ limit: { input: 200_000, output: 128_000 },
38
+ modalities: {
39
+ input: { text: true, image: true, audio: false, video: false, pdf: false },
40
+ output: { text: true, image: false, audio: false, video: false, pdf: false },
41
+ },
42
+ capabilities: { reasoning: true, tools: true, structuredOutput: true },
43
+ cost: { input: 0, output: 0 },
44
+ },
45
+ {
46
+ engine: {
47
+ type: 'codex',
48
+ provider: 'openai',
49
+ model: { id: 'gpt-5.3-codex', name: 'GPT-5.3 Codex' },
50
+ account: { id: 0, name: '' },
51
+ },
52
+ limit: { input: 200_000, output: 128_000 },
53
+ modalities: {
54
+ input: { text: true, image: true, audio: false, video: false, pdf: false },
55
+ output: { text: true, image: false, audio: false, video: false, pdf: false },
56
+ },
57
+ capabilities: { reasoning: true, tools: true, structuredOutput: true },
58
+ cost: { input: 0, output: 0 },
59
+ },
60
+ {
61
+ engine: {
62
+ type: 'codex',
63
+ provider: 'openai',
64
+ model: { id: 'gpt-5.2', name: 'GPT-5.2' },
65
+ account: { id: 0, name: '' },
66
+ },
67
+ limit: { input: 200_000, output: 128_000 },
68
+ modalities: {
69
+ input: { text: true, image: true, audio: false, video: false, pdf: false },
70
+ output: { text: true, image: false, audio: false, video: false, pdf: false },
71
+ },
72
+ capabilities: { reasoning: true, tools: true, structuredOutput: true },
73
+ cost: { input: 0, output: 0 },
74
+ },
75
+ {
76
+ engine: {
77
+ type: 'codex',
78
+ provider: 'openai',
79
+ model: { id: 'gpt-5.5', name: 'GPT-5.5 (ChatGPT only)' },
80
+ account: { id: 0, name: '' },
81
+ },
82
+ limit: { input: 200_000, output: 128_000 },
83
+ modalities: {
84
+ input: { text: true, image: true, audio: false, video: false, pdf: false },
85
+ output: { text: true, image: false, audio: false, video: false, pdf: false },
86
+ },
87
+ capabilities: { reasoning: true, tools: true, structuredOutput: true, requiresAuthMode: 'chatgpt' },
88
+ cost: { input: 0, output: 0 },
89
+ },
90
+ {
91
+ engine: {
92
+ type: 'codex',
93
+ provider: 'openai',
94
+ model: { id: 'gpt-5.3-codex-spark', name: 'GPT-5.3 Codex Spark (ChatGPT Pro)' },
95
+ account: { id: 0, name: '' },
96
+ },
97
+ limit: { input: 200_000, output: 128_000 },
98
+ modalities: {
99
+ input: { text: true, image: false, audio: false, video: false, pdf: false },
100
+ output: { text: true, image: false, audio: false, video: false, pdf: false },
101
+ },
102
+ capabilities: { reasoning: false, tools: true, structuredOutput: false, requiresAuthMode: 'chatgpt' },
103
+ cost: { input: 0, output: 0 },
104
+ },
105
+ ];
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Codex rollout-file apply_patch extraction (workaround).
3
+ *
4
+ * The Codex SDK's typed `FileChangeItem` event only exposes `path` + `kind`
5
+ * for each change — it does NOT carry the actual old/new file contents that
6
+ * the model produced. So when we map an `update` change to a unified `Edit`
7
+ * tool block in `message-converter.ts`, the `oldString` and `newString`
8
+ * fields would always be empty.
9
+ *
10
+ * The Codex CLI does write the full unified-diff patch to the rollout JSONL
11
+ * at `~/.codex/sessions/YYYY/MM/DD/rollout-*-<thread_id>.jsonl` as a
12
+ * `custom_tool_call` with `name: "apply_patch"`. Each `apply_patch.input`
13
+ * contains an envelope-format patch like:
14
+ *
15
+ * *** Begin Patch
16
+ * *** Update File: <abs path>
17
+ * @@
18
+ * -old line
19
+ * +new line
20
+ * *** End Patch
21
+ *
22
+ * We read the rollout, parse every `apply_patch` envelope, and look up the
23
+ * latest one whose update-paths match the live `FileChangeItem` so the Edit
24
+ * block can be filled with real diff content.
25
+ *
26
+ * TODO(codex-sdk): once `@openai/codex-sdk` exposes per-change content on
27
+ * `FileUpdateChange` natively (e.g. `oldText`/`newText`), delete this file
28
+ * and read directly from the SDK event in `buildFileChangePair`.
29
+ *
30
+ * Until then, this helper depends on an undocumented internal CLI file
31
+ * format. If the format shifts between releases, the adapter degrades
32
+ * gracefully to empty `oldString`/`newString` (no worse than before).
33
+ */
34
+ import fs from 'node:fs';
35
+ import { debug } from '$shared/utils/logger';
36
+ import { findRolloutFile } from './usage-rollout';
37
+
38
+ export interface FilePatch {
39
+ oldString: string;
40
+ newString: string;
41
+ }
42
+
43
+ /**
44
+ * Parse one `apply_patch` envelope into a per-file map of old/new strings.
45
+ *
46
+ * Multiple hunks per file are concatenated (all `-`/context lines into
47
+ * `oldString`, all `+`/context lines into `newString`) so the rendered Edit
48
+ * block shows every change the model made — even though the unified `Edit`
49
+ * type only carries a single before/after pair.
50
+ *
51
+ * Only `*** Update File:` sections are returned. `Add` and `Delete`
52
+ * sections are ignored — those map to `Write`/`Bash` blocks elsewhere and
53
+ * don't need diff content.
54
+ */
55
+ export function parseApplyPatch(input: string): Map<string, FilePatch> {
56
+ const result = new Map<string, FilePatch>();
57
+ const lines = input.split('\n');
58
+
59
+ let currentPath: string | null = null;
60
+ let isUpdate = false;
61
+ const oldBuf: string[] = [];
62
+ const newBuf: string[] = [];
63
+
64
+ const flush = () => {
65
+ if (currentPath && isUpdate && (oldBuf.length || newBuf.length)) {
66
+ result.set(currentPath, {
67
+ oldString: oldBuf.join('\n'),
68
+ newString: newBuf.join('\n'),
69
+ });
70
+ }
71
+ currentPath = null;
72
+ isUpdate = false;
73
+ oldBuf.length = 0;
74
+ newBuf.length = 0;
75
+ };
76
+
77
+ for (const line of lines) {
78
+ if (line.startsWith('*** Begin Patch') || line.startsWith('*** End Patch')) {
79
+ if (line.startsWith('*** End Patch')) flush();
80
+ continue;
81
+ }
82
+ if (line.startsWith('*** Update File: ')) {
83
+ flush();
84
+ currentPath = line.slice('*** Update File: '.length).trim();
85
+ isUpdate = true;
86
+ continue;
87
+ }
88
+ if (line.startsWith('*** Add File: ') || line.startsWith('*** Delete File: ')) {
89
+ flush();
90
+ continue;
91
+ }
92
+ if (!isUpdate) continue;
93
+ if (line.startsWith('@@')) continue;
94
+ if (line.startsWith('-')) {
95
+ oldBuf.push(line.slice(1));
96
+ } else if (line.startsWith('+')) {
97
+ newBuf.push(line.slice(1));
98
+ } else {
99
+ // Context line. The CLI sometimes prefixes with a leading space,
100
+ // sometimes leaves it bare — strip one leading space if present.
101
+ const ctx = line.startsWith(' ') ? line.slice(1) : line;
102
+ oldBuf.push(ctx);
103
+ newBuf.push(ctx);
104
+ }
105
+ }
106
+ flush();
107
+ return result;
108
+ }
109
+
110
+ /**
111
+ * Read every `apply_patch` `custom_tool_call` from the rollout file in
112
+ * chronological (file) order. Each entry maps update-path → diff content.
113
+ *
114
+ * Returns an empty array if the rollout file isn't found or the read
115
+ * fails — callers should fall back to leaving `oldString`/`newString`
116
+ * empty.
117
+ */
118
+ export function readApplyPatchesFromRollout(threadId: string): Array<Map<string, FilePatch>> {
119
+ const file = findRolloutFile(threadId);
120
+ if (!file) return [];
121
+
122
+ const patches: Array<Map<string, FilePatch>> = [];
123
+ try {
124
+ const content = fs.readFileSync(file, 'utf-8');
125
+ const lines = content.split('\n');
126
+ for (const line of lines) {
127
+ if (!line || !line.includes('"apply_patch"')) continue;
128
+ try {
129
+ const parsed = JSON.parse(line);
130
+ const payload = parsed?.payload;
131
+ if (
132
+ payload?.type === 'custom_tool_call'
133
+ && payload.name === 'apply_patch'
134
+ && typeof payload.input === 'string'
135
+ ) {
136
+ patches.push(parseApplyPatch(payload.input));
137
+ }
138
+ } catch { /* malformed line — skip */ }
139
+ }
140
+ } catch (err) {
141
+ debug.warn('engine', `Codex patch-rollout: failed to read ${file}:`, err);
142
+ return [];
143
+ }
144
+ return patches;
145
+ }
146
+
147
+ /**
148
+ * Pick the patch from `patches` (rollout-order) that best matches the set
149
+ * of update-paths in the current `FileChangeItem`. Walks from the end of
150
+ * the list (most recent first) so the newest matching `apply_patch`
151
+ * always wins — that's the one whose SDK `file_change` event we just
152
+ * received.
153
+ *
154
+ * "Match" = the patch's update-path set is a superset of `wantedPaths`.
155
+ * Returns `null` if no patch matches.
156
+ */
157
+ export function findMatchingPatch(
158
+ patches: Array<Map<string, FilePatch>>,
159
+ wantedPaths: string[],
160
+ ): Map<string, FilePatch> | null {
161
+ if (wantedPaths.length === 0) return null;
162
+ for (let i = patches.length - 1; i >= 0; i--) {
163
+ const candidate = patches[i];
164
+ if (!candidate) continue;
165
+ const ok = wantedPaths.every(p => candidate.has(p));
166
+ if (ok) return candidate;
167
+ }
168
+ return null;
169
+ }
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Codex Session Fork (workaround)
3
+ *
4
+ * The Codex SDK does not yet expose a native `forkSession()` API. To support
5
+ * Clopen's multi-branch checkpoints feature — which lets the user replay an
6
+ * earlier point in the conversation as a sibling branch — we copy the
7
+ * on-disk rollout file to a fresh thread id and patch the embedded id.
8
+ *
9
+ * On-disk layout (`~/.codex/sessions/`):
10
+ *
11
+ * ~/.codex/sessions/<YYYY>/<MM>/<DD>/rollout-<TIMESTAMP>-<thread_id>.jsonl
12
+ *
13
+ * Each thread is a SINGLE JSONL file inside a date-tree, NOT a directory.
14
+ * The first line is `session_meta` whose `payload.id` is the thread_id.
15
+ * The Codex CLI's `resume <id>` walks this tree and matches the file
16
+ * whose name ends with `-<id>.jsonl`.
17
+ *
18
+ * Earlier versions of this helper assumed a directory layout
19
+ * (`~/.codex/sessions/<thread_id>/`) and so `sessionStateExists()` always
20
+ * returned false — the fork block was silently skipped and resume reused
21
+ * the source thread id, breaking multi-branch checkpoints (README §9.10
22
+ * sharp edge: "reusing the same id across turns is the symptom that
23
+ * forking is gated or skipped").
24
+ *
25
+ * TODO: when @openai/codex-sdk gains a native `forkSession()` (or
26
+ * `Codex.forkThread()`), delete this helper and switch
27
+ * `CodexEngine.streamQuery` to use the SDK API directly. The migration is
28
+ * one line — the same pattern Claude (`forkSession: true`) and OpenCode
29
+ * (`client.session.fork()`) already use.
30
+ *
31
+ * Cross-account note: `~/.codex/sessions/` is shared across ChatGPT
32
+ * accounts. A session forked under account A is readable by account B if
33
+ * accounts swap. That matches running the Codex CLI manually with two
34
+ * ChatGPT accounts; we don't add isolation on top.
35
+ */
36
+
37
+ import fs from 'node:fs';
38
+ import path from 'node:path';
39
+ import { getCodexHomeDir } from './credential';
40
+ import { debug } from '$shared/utils/logger';
41
+
42
+ const SESSION_DIR_NAME = 'sessions';
43
+
44
+ function getSessionsRoot(): string {
45
+ return path.join(getCodexHomeDir(), SESSION_DIR_NAME);
46
+ }
47
+
48
+ /**
49
+ * Walk the date-tree under `~/.codex/sessions/` and return the rollout
50
+ * file whose name ends with `-<threadId>.jsonl`. Returns null when no
51
+ * matching file is found (likely a thread that was deleted, never
52
+ * persisted, or belongs to a different `CODEX_HOME`).
53
+ *
54
+ * The walk is bounded: Codex organises rollouts by date so the search
55
+ * space is at most O(years × months × days) directories. We don't index
56
+ * because thread ids are UUIDs — collisions are not a concern.
57
+ */
58
+ function findRolloutFile(threadId: string): string | null {
59
+ const root = getSessionsRoot();
60
+ if (!fs.existsSync(root)) return null;
61
+
62
+ const suffix = `-${threadId}.jsonl`;
63
+ const stack: string[] = [root];
64
+ while (stack.length > 0) {
65
+ const dir = stack.pop()!;
66
+ let entries: fs.Dirent[];
67
+ try {
68
+ entries = fs.readdirSync(dir, { withFileTypes: true });
69
+ } catch {
70
+ continue;
71
+ }
72
+ for (const entry of entries) {
73
+ const full = path.join(dir, entry.name);
74
+ if (entry.isDirectory()) {
75
+ stack.push(full);
76
+ continue;
77
+ }
78
+ if (entry.isFile() && entry.name.endsWith(suffix)) {
79
+ return full;
80
+ }
81
+ }
82
+ }
83
+ return null;
84
+ }
85
+
86
+ /**
87
+ * Format `Date` as `YYYY-MM-DDTHH-MM-SS` (matches Codex's filename
88
+ * timestamp — colons in ISO are replaced with dashes so the path is
89
+ * filesystem-safe on every OS).
90
+ */
91
+ function formatRolloutTimestamp(date: Date): string {
92
+ const iso = date.toISOString(); // 2026-05-03T22:46:00.000Z
93
+ return iso.slice(0, 19).replace(/:/g, '-'); // 2026-05-03T22-46-00
94
+ }
95
+
96
+ /**
97
+ * Build the destination path for a fork: place it in the *current* day's
98
+ * dated subdirectory, NOT the source's day. Codex's CLI doesn't care
99
+ * which dated dir holds the rollout — it walks the whole tree on resume —
100
+ * and stamping forks with the current date keeps "recent activity"
101
+ * semantics intact for any tooling that orders by directory mtime.
102
+ */
103
+ function buildForkPath(forkThreadId: string, now: Date = new Date()): string {
104
+ const yyyy = now.getUTCFullYear().toString().padStart(4, '0');
105
+ const mm = (now.getUTCMonth() + 1).toString().padStart(2, '0');
106
+ const dd = now.getUTCDate().toString().padStart(2, '0');
107
+ const dir = path.join(getSessionsRoot(), yyyy, mm, dd);
108
+ const filename = `rollout-${formatRolloutTimestamp(now)}-${forkThreadId}.jsonl`;
109
+ return path.join(dir, filename);
110
+ }
111
+
112
+ export function sessionStateExists(threadId: string): boolean {
113
+ return findRolloutFile(threadId) !== null;
114
+ }
115
+
116
+ /**
117
+ * Copy `sourceThreadId`'s rollout file to a new file keyed by
118
+ * `forkThreadId` and patch the embedded thread id. Returns true on
119
+ * success, false if the source file is missing (caller falls back to a
120
+ * fresh thread).
121
+ *
122
+ * The destination is removed first if it already exists so a re-fork
123
+ * from the same source produces a clean copy.
124
+ */
125
+ export function forkCodexSessionState(sourceThreadId: string, forkThreadId: string): boolean {
126
+ const srcPath = findRolloutFile(sourceThreadId);
127
+ if (!srcPath) {
128
+ debug.warn('engine', `Codex fork: rollout for thread ${sourceThreadId} not found under ${getSessionsRoot()}`);
129
+ return false;
130
+ }
131
+
132
+ const dstPath = buildForkPath(forkThreadId);
133
+ const dstDir = path.dirname(dstPath);
134
+ fs.mkdirSync(dstDir, { recursive: true });
135
+
136
+ if (fs.existsSync(dstPath)) {
137
+ fs.rmSync(dstPath, { force: true });
138
+ }
139
+
140
+ // UUIDs don't collide with unrelated content, so a blanket
141
+ // search-and-replace on the source thread id is safe and avoids
142
+ // parsing the (undocumented) JSONL schema line-by-line.
143
+ const content = fs.readFileSync(srcPath, 'utf-8');
144
+ const patched = content.split(sourceThreadId).join(forkThreadId);
145
+ fs.writeFileSync(dstPath, patched);
146
+
147
+ debug.log('engine', `Codex fork: ${sourceThreadId} → ${forkThreadId} (${dstPath})`);
148
+ return true;
149
+ }