@myrialabs/clopen 0.4.31 → 0.4.33

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 (114) hide show
  1. package/backend/auth/permissions.test.ts +0 -1
  2. package/backend/auth/permissions.ts +0 -4
  3. package/backend/chat/stream-manager.ts +31 -12
  4. package/backend/database/migrations/068_create_engine_config_revision.test.ts +121 -0
  5. package/backend/database/migrations/068_create_engine_config_revision.ts +117 -0
  6. package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
  7. package/backend/database/migrations/index.ts +14 -0
  8. package/backend/database/queries/db-client-connection-queries.ts +7 -2
  9. package/backend/database/queries/file-audit-log-queries.ts +1 -0
  10. package/backend/database/queries/index.ts +3 -0
  11. package/backend/database/queries/ssh-connection-queries.ts +244 -0
  12. package/backend/database/queries/ssh-known-host-queries.ts +67 -0
  13. package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
  14. package/backend/db-client/connection-manager.ts +8 -1
  15. package/backend/engine/README.md +16 -0
  16. package/backend/engine/adapters/claude/stream.ts +89 -49
  17. package/backend/engine/adapters/cline/stream.ts +62 -24
  18. package/backend/engine/adapters/codex/message-converter.ts +18 -12
  19. package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
  20. package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
  21. package/backend/engine/adapters/codex/stream.ts +78 -22
  22. package/backend/engine/adapters/copilot/stream.ts +97 -53
  23. package/backend/engine/adapters/cursor/stream.ts +75 -35
  24. package/backend/engine/adapters/opencode/server.ts +511 -134
  25. package/backend/engine/adapters/opencode/stream.ts +131 -79
  26. package/backend/engine/adapters/pi/stream.ts +63 -24
  27. package/backend/engine/adapters/qwen/stream.ts +92 -59
  28. package/backend/engine/adapters/run-registry.test.ts +75 -0
  29. package/backend/engine/adapters/run-registry.ts +63 -0
  30. package/backend/engine/config-revision.ts +150 -0
  31. package/backend/engine/docs/adapter-contract.md +47 -9
  32. package/backend/engine/docs/adding-an-engine.md +8 -0
  33. package/backend/engine/docs/frontend-and-chat.md +39 -0
  34. package/backend/engine/docs/lessons-learned.md +70 -0
  35. package/backend/engine/docs/quick-reference.md +3 -1
  36. package/backend/engine/hot-reload.ts +99 -0
  37. package/backend/engine/index.ts +96 -24
  38. package/backend/engine/types.ts +17 -5
  39. package/backend/files/file-watcher.ts +283 -51
  40. package/backend/files/git-events.test.ts +110 -0
  41. package/backend/git/git-dirs.test.ts +132 -0
  42. package/backend/git/git-dirs.ts +0 -0
  43. package/backend/git/git-executor.ts +22 -3
  44. package/backend/git/git-service.ts +1 -1
  45. package/backend/git/nested-repos.test.ts +224 -0
  46. package/backend/git/nested-repos.ts +386 -0
  47. package/backend/http/audio.ts +5 -32
  48. package/backend/http/bearer-auth.ts +47 -0
  49. package/backend/http/files-download.test.ts +146 -0
  50. package/backend/http/files-download.ts +109 -0
  51. package/backend/http/files-upload.ts +3 -29
  52. package/backend/http/ssh-sftp.ts +133 -0
  53. package/backend/index.ts +23 -2
  54. package/backend/mcp/README.md +34 -6
  55. package/backend/mcp/index.ts +8 -8
  56. package/backend/mcp/internal/config.ts +69 -19
  57. package/backend/mcp/internal/project-context.test.ts +40 -0
  58. package/backend/mcp/internal/project-context.ts +80 -7
  59. package/backend/mcp/internal/remote-server.test.ts +17 -2
  60. package/backend/mcp/internal/remote-server.ts +36 -3
  61. package/backend/mcp/internal/servers/helper.ts +48 -18
  62. package/backend/preview/browser/browser-video-capture.ts +51 -4
  63. package/backend/snapshot/gitignore.ts +10 -174
  64. package/backend/ssh/client-pool.ts +196 -0
  65. package/backend/ssh/connect.ts +375 -0
  66. package/backend/ssh/disk-usage.test.ts +134 -0
  67. package/backend/ssh/disk-usage.ts +214 -0
  68. package/backend/ssh/forwards.ts +309 -0
  69. package/backend/ssh/health.ts +141 -0
  70. package/backend/ssh/known-hosts.ts +96 -0
  71. package/backend/ssh/pty-backend.ts +215 -0
  72. package/backend/ssh/ptykit.ts +66 -0
  73. package/backend/ssh/sftp.test.ts +242 -0
  74. package/backend/ssh/sftp.ts +967 -0
  75. package/backend/ssh/socks5.test.ts +167 -0
  76. package/backend/ssh/socks5.ts +164 -0
  77. package/backend/ssh/tunnel.ts +87 -0
  78. package/backend/ws/chat/stream.ts +24 -0
  79. package/backend/ws/db-client/connections.ts +1 -0
  80. package/backend/ws/engine/codex/accounts.ts +0 -12
  81. package/backend/ws/engine/copilot/accounts.ts +0 -10
  82. package/backend/ws/engine/cursor/accounts.ts +0 -10
  83. package/backend/ws/engine/index.ts +17 -2
  84. package/backend/ws/engine/opencode/providers.ts +0 -52
  85. package/backend/ws/files/read.ts +1 -1
  86. package/backend/ws/files/watch.ts +5 -1
  87. package/backend/ws/git/conflict.ts +1 -1
  88. package/backend/ws/git/diff.ts +1 -1
  89. package/backend/ws/git/staging.ts +1 -1
  90. package/backend/ws/git/status.ts +1 -1
  91. package/backend/ws/index.ts +4 -0
  92. package/backend/ws/ssh/access.ts +31 -0
  93. package/backend/ws/ssh/connections.ts +224 -0
  94. package/backend/ws/ssh/forwards.ts +109 -0
  95. package/backend/ws/ssh/index.ts +18 -0
  96. package/backend/ws/ssh/sftp.ts +259 -0
  97. package/backend/ws/ssh/tunnel.ts +93 -0
  98. package/dist/assets/{index-DYwQ5bP8.js → index-BF4buYmI.js} +1 -1
  99. package/dist/assets/{index-DUc5T21e.js → index-BW0DA8NV.js} +1 -1
  100. package/dist/assets/main-BbwWLJRN.js +1057 -0
  101. package/dist/assets/main-CCvRMXlP.css +1 -0
  102. package/dist/index.html +2 -2
  103. package/package.json +1 -1
  104. package/shared/types/database/schema.ts +49 -0
  105. package/shared/types/db-client/connection.ts +6 -0
  106. package/shared/types/ssh/connection.ts +80 -0
  107. package/shared/types/ssh/forward.ts +46 -0
  108. package/shared/types/ssh/index.ts +8 -0
  109. package/shared/types/ssh/known-host.ts +19 -0
  110. package/shared/types/ssh/sftp.ts +141 -0
  111. package/shared/utils/logger.ts +1 -0
  112. package/backend/ws/engine/restart.ts +0 -54
  113. package/dist/assets/main-VgdjTBLR.css +0 -1
  114. package/dist/assets/main-r0iv2PDz.js +0 -1044
@@ -1,169 +1,180 @@
1
1
  /**
2
- * Codex rollout-file apply_patch extraction (workaround).
2
+ * Codex rollout-file file-change extraction (workaround).
3
3
  *
4
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.
5
+ * for each change — it does NOT carry the actual file contents the model
6
+ * produced. So when we map an `update` change to a unified `Edit` tool block
7
+ * and an `add` change to a `Write` block in `message-converter.ts`, the
8
+ * `oldString` / `newString` / `content` fields would always be empty.
9
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:
10
+ * The Codex CLI does write the real contents to the rollout JSONL at
11
+ * `<codex-home>/sessions/YYYY/MM/DD/rollout-*-<thread_id>.jsonl` as a
12
+ * `patch_apply_end` event, emitted just before the SDK's `file_change` item:
14
13
  *
15
- * *** Begin Patch
16
- * *** Update File: <abs path>
17
- * @@
18
- * -old line
19
- * +new line
20
- * *** End Patch
14
+ * {"type":"event_msg","payload":{"type":"patch_apply_end","success":true,
15
+ * "changes":{
16
+ * "/abs/path.css": {"type":"update","unified_diff":"@@ -1,3 +1,3 @@\n …"},
17
+ * "/abs/new.md": {"type":"add","content":"# New file\n…"}
18
+ * }}}
21
19
  *
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.
20
+ * We read the rollout, collect every `patch_apply_end`, and look up the
21
+ * latest one whose change-paths match the live `FileChangeItem` so the Edit
22
+ * and Write blocks can be filled with the real content.
25
23
  *
26
24
  * 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`.
25
+ * `FileUpdateChange` natively (e.g. `unifiedDiff`/`content`), delete this
26
+ * file and read directly from the SDK event in `buildFileChangePair`.
29
27
  *
30
28
  * Until then, this helper depends on an undocumented internal CLI file
31
29
  * format. If the format shifts between releases, the adapter degrades
32
- * gracefully to empty `oldString`/`newString` (no worse than before).
30
+ * gracefully to empty content (no worse than before).
33
31
  */
34
32
  import fs from 'node:fs';
35
33
  import { debug } from '$shared/utils/logger';
36
34
  import { findRolloutFile } from './usage-rollout';
37
35
 
38
- export interface FilePatch {
36
+ /** Content recovered from the rollout for a single changed file. */
37
+ export interface FileChangeContent {
38
+ kind: 'add' | 'update' | 'delete';
39
+ /** `update` only: the pre-edit text (context + removed lines). */
39
40
  oldString: string;
41
+ /** `update` only: the post-edit text (context + added lines). */
40
42
  newString: string;
43
+ /** `add` only: the full contents of the newly created file. */
44
+ content: string;
41
45
  }
42
46
 
47
+ /** One `patch_apply_end` event: absolute file path → recovered content. */
48
+ export type FileChangeSet = Map<string, FileChangeContent>;
49
+
43
50
  /**
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.
51
+ * Shape of `payload.changes[path]` in a `patch_apply_end` rollout event.
52
+ * Undocumented CLI-internal format — every field is treated as optional.
54
53
  */
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[] = [];
54
+ interface RolloutFileChange {
55
+ type?: string;
56
+ unified_diff?: string;
57
+ content?: string;
58
+ move_path?: string | null;
59
+ }
63
60
 
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
- };
61
+ /**
62
+ * Reconstruct before/after text from a unified diff.
63
+ *
64
+ * Multiple hunks are concatenated (all `-`/context lines into `oldString`,
65
+ * all `+`/context lines into `newString`) so the rendered Edit block shows
66
+ * every change the model made in that file — even though the unified `Edit`
67
+ * type only carries a single before/after pair. Non-adjacent hunks therefore
68
+ * render as if they were contiguous; that is a deliberate trade-off of the
69
+ * single-pair `Edit` shape, not a parsing bug.
70
+ */
71
+ export function parseUnifiedDiff(unifiedDiff: string): { oldString: string; newString: string } {
72
+ const oldLines: string[] = [];
73
+ const newLines: string[] = [];
74
+ let insideHunk = false;
76
75
 
77
- for (const line of lines) {
78
- if (line.startsWith('*** Begin Patch') || line.startsWith('*** End Patch')) {
79
- if (line.startsWith('*** End Patch')) flush();
76
+ for (const line of unifiedDiff.split('\n')) {
77
+ if (line.startsWith('@@')) {
78
+ insideHunk = true;
80
79
  continue;
81
80
  }
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;
81
+ // `---` / `+++` / `diff --git` only count as file headers before the
82
+ // first hunk. Inside a hunk they are real content (a removed line whose
83
+ // text is `--`, for instance), so they must not be filtered there.
84
+ if (!insideHunk) continue;
85
+ // "" is a diff annotation, not content.
86
+ if (line.startsWith('\\')) continue;
87
+
94
88
  if (line.startsWith('-')) {
95
- oldBuf.push(line.slice(1));
89
+ oldLines.push(line.slice(1));
96
90
  } else if (line.startsWith('+')) {
97
- newBuf.push(line.slice(1));
91
+ newLines.push(line.slice(1));
98
92
  } 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);
93
+ // Context line — carried by both sides. The CLI prefixes it with a
94
+ // single space; blank context lines arrive as an empty string.
95
+ const contextLine = line.startsWith(' ') ? line.slice(1) : line;
96
+ oldLines.push(contextLine);
97
+ newLines.push(contextLine);
104
98
  }
105
99
  }
106
- flush();
107
- return result;
100
+
101
+ return { oldString: oldLines.join('\n'), newString: newLines.join('\n') };
102
+ }
103
+
104
+ /** Normalize one `payload.changes` entry into our recovered-content shape. */
105
+ function toFileChangeContent(change: RolloutFileChange): FileChangeContent | null {
106
+ if (change.type === 'add') {
107
+ return { kind: 'add', oldString: '', newString: '', content: change.content ?? '' };
108
+ }
109
+ if (change.type === 'delete') {
110
+ return { kind: 'delete', oldString: '', newString: '', content: '' };
111
+ }
112
+ if (change.type === 'update') {
113
+ const { oldString, newString } = parseUnifiedDiff(change.unified_diff ?? '');
114
+ return { kind: 'update', oldString, newString, content: '' };
115
+ }
116
+ return null;
108
117
  }
109
118
 
110
119
  /**
111
- * Read every `apply_patch` `custom_tool_call` from the rollout file in
112
- * chronological (file) order. Each entry maps update-path → diff content.
120
+ * Read every `patch_apply_end` event from the rollout file in chronological
121
+ * (file) order. Each entry maps an absolute path → recovered content.
113
122
  *
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.
123
+ * Returns an empty array if the rollout file isn't found or the read fails —
124
+ * callers should fall back to leaving the content fields empty.
117
125
  */
118
- export function readApplyPatchesFromRollout(threadId: string): Array<Map<string, FilePatch>> {
126
+ export function readFileChangeSetsFromRollout(threadId: string): FileChangeSet[] {
119
127
  const file = findRolloutFile(threadId);
120
128
  if (!file) return [];
121
129
 
122
- const patches: Array<Map<string, FilePatch>> = [];
130
+ const changeSets: FileChangeSet[] = [];
123
131
  try {
124
132
  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;
133
+ for (const line of content.split('\n')) {
134
+ if (!line || !line.includes('"patch_apply_end"')) continue;
128
135
  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));
136
+ const payload = JSON.parse(line)?.payload;
137
+ if (payload?.type !== 'patch_apply_end' || !payload.changes) continue;
138
+ const changeSet: FileChangeSet = new Map();
139
+ for (const [path, raw] of Object.entries(payload.changes as Record<string, RolloutFileChange>)) {
140
+ const recovered = toFileChangeContent(raw ?? {});
141
+ if (recovered) changeSet.set(path, recovered);
137
142
  }
143
+ if (changeSet.size > 0) changeSets.push(changeSet);
138
144
  } catch { /* malformed line — skip */ }
139
145
  }
140
146
  } catch (err) {
141
147
  debug.warn('engine', `Codex patch-rollout: failed to read ${file}:`, err);
142
148
  return [];
143
149
  }
144
- return patches;
150
+ return changeSets;
145
151
  }
146
152
 
147
153
  /**
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.
154
+ * Pick the change set that best matches the paths in the current
155
+ * `FileChangeItem`. Walks from the end of the list (most recent first) so the
156
+ * newest matching `patch_apply_end` wins — that's the one whose SDK
157
+ * `file_change` event we just received.
158
+ *
159
+ * Reading the rollout fresh on every `file_change` keeps this correct when a
160
+ * turn patches the same paths twice: at the time the first item arrives the
161
+ * second patch has not been written yet, so "newest" is still the first one.
162
+ *
163
+ * A resumed thread replays the previous rollout history into the same file,
164
+ * so older matches for the same paths are expected and deliberately skipped.
153
165
  *
154
- * "Match" = the patch's update-path set is a superset of `wantedPaths`.
155
- * Returns `null` if no patch matches.
166
+ * "Match" = the change set covers every path in `wantedPaths`.
167
+ * Returns `null` if nothing matches.
156
168
  */
157
- export function findMatchingPatch(
158
- patches: Array<Map<string, FilePatch>>,
169
+ export function findMatchingFileChangeSet(
170
+ changeSets: FileChangeSet[],
159
171
  wantedPaths: string[],
160
- ): Map<string, FilePatch> | null {
172
+ ): FileChangeSet | null {
161
173
  if (wantedPaths.length === 0) return null;
162
- for (let i = patches.length - 1; i >= 0; i--) {
163
- const candidate = patches[i];
174
+ for (let index = changeSets.length - 1; index >= 0; index--) {
175
+ const candidate = changeSets[index];
164
176
  if (!candidate) continue;
165
- const ok = wantedPaths.every(p => candidate.has(p));
166
- if (ok) return candidate;
177
+ if (wantedPaths.every(path => candidate.has(path))) return candidate;
167
178
  }
168
179
  return null;
169
180
  }
@@ -29,6 +29,7 @@ import { resolveOsPath } from '$backend/utils/paths';
29
29
  import { resolveEngineCli } from '$backend/engine/engine-cli';
30
30
  import { getCleanSpawnEnv } from '$backend/utils/index.js';
31
31
  import { getCodexMcpConfig } from '../../../mcp';
32
+ import { EngineRuns } from '../run-registry';
32
33
  import { artifactFilter } from '$backend/profiles';
33
34
  import { syncSkills } from '$backend/skills';
34
35
  import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
@@ -56,13 +57,26 @@ import path from 'node:path';
56
57
  import os from 'node:os';
57
58
  import fs from 'node:fs';
58
59
 
60
+ /** One stream in flight on this instance. */
61
+ interface CodexRun {
62
+ /** Identity of the run — the controller the caller passed to streamQuery. */
63
+ controller: AbortController;
64
+ thread: Thread | null;
65
+ }
66
+
59
67
  export class CodexEngine implements AIEngine {
60
68
  readonly name = 'codex' as const;
61
69
 
62
70
  private _isInitialized = false;
63
71
  private codex: Codex | null = null;
64
- private activeThread: Thread | null = null;
65
- private activeController: AbortController | null = null;
72
+ /**
73
+ * Every stream in flight, keyed by the AbortController its caller passed to
74
+ * streamQuery. One instance serves all chat sessions of a project, so the
75
+ * thread and controller of a stream belong to the run, not the instance — a
76
+ * field would hold only the most recent one and cancelling any chat would
77
+ * abort another chat's turn.
78
+ */
79
+ private runs = new EngineRuns<CodexRun>();
66
80
  /** Account ID currently baked into `this.codex`. Same trade-off as Copilot. */
67
81
  private currentAccountId: number | null = null;
68
82
  /**
@@ -72,13 +86,31 @@ export class CodexEngine implements AIEngine {
72
86
  * `'*'` = unfiltered (no profile constraint). `null` = not initialized.
73
87
  */
74
88
  private currentMcpFilterKey: string | null = null;
89
+ /**
90
+ * Project baked into `this.codex`'s MCP bridge URL.
91
+ *
92
+ * Codex takes its MCP set at construction, so the URL — and with it the
93
+ * identity the bridge binds tool calls to — is fixed for the life of the
94
+ * client. An instance serves exactly one project (see the per-project engine
95
+ * cache in `backend/engine/index.ts`), so the project is a safe thing to bake;
96
+ * the chat session is not, because the same client serves all of them.
97
+ * `null` = built without a project, which a later stream re-initialises.
98
+ */
99
+ private currentProjectId: string | null = null;
100
+ /**
101
+ * Project for the client `initialize()` is about to build. Carried in a field
102
+ * rather than an argument because `initialize` is part of the `AIEngine`
103
+ * interface and adding a parameter to the implementation would stop it
104
+ * satisfying that type.
105
+ */
106
+ private pendingProjectId: string | null = null;
75
107
 
76
108
  get isInitialized(): boolean {
77
109
  return this._isInitialized;
78
110
  }
79
111
 
80
112
  get isActive(): boolean {
81
- return this.activeController !== null;
113
+ return this.runs.isActive;
82
114
  }
83
115
 
84
116
  async initialize(accountId?: number, mcpProfileFilter?: Set<string>): Promise<void> {
@@ -87,6 +119,8 @@ export class CodexEngine implements AIEngine {
87
119
  return;
88
120
  }
89
121
 
122
+ const projectId = this.pendingProjectId;
123
+
90
124
  const account = accountId != null
91
125
  ? engineQueries.getAccount(accountId)
92
126
  : engineQueries.getActiveAccountForEngine('codex');
@@ -108,7 +142,7 @@ export class CodexEngine implements AIEngine {
108
142
  // inside the stack dir) over an older copy on the user's PATH — the SDK
109
143
  // would otherwise be pinned while the process it spawns drifts.
110
144
  const codexCli = await resolveEngineCli('codex');
111
- const mcpConfig = getCodexMcpConfig(mcpProfileFilter);
145
+ const mcpConfig = getCodexMcpConfig(mcpProfileFilter, projectId ? { projectId } : undefined);
112
146
 
113
147
  // Codex SDK takes config at construction. We pass `show_raw_agent_reasoning`
114
148
  // (so the SDK forwards reasoning text events) and forward the Clopen MCP
@@ -135,15 +169,17 @@ export class CodexEngine implements AIEngine {
135
169
  });
136
170
  this.currentAccountId = account.id;
137
171
  this.currentMcpFilterKey = mcpKey;
172
+ this.currentProjectId = projectId;
138
173
  this._isInitialized = true;
139
- debug.log('engine', `Codex engine initialized (account ${account.id}, mode=${credential.kind}, mcpFilter=${mcpKey})`);
174
+ debug.log('engine', `Codex engine initialized (account ${account.id}, mode=${credential.kind}, mcpFilter=${mcpKey}, project=${projectId ?? 'none'})`);
140
175
  }
141
176
 
142
177
  async dispose(): Promise<void> {
143
- await this.cancel();
178
+ await this.stopRuns(this.runs.all());
144
179
  this.codex = null;
145
180
  this.currentAccountId = null;
146
181
  this.currentMcpFilterKey = null;
182
+ this.currentProjectId = null;
147
183
  this._isInitialized = false;
148
184
  debug.log('engine', 'Codex engine disposed');
149
185
  }
@@ -177,10 +213,17 @@ export class CodexEngine implements AIEngine {
177
213
  const mcpKey = mcpProfileFilter ? [...mcpProfileFilter].sort().join(',') : '*';
178
214
  const accountChanged = this._isInitialized && accountId != null && accountId !== this.currentAccountId;
179
215
  const mcpChanged = this._isInitialized && mcpKey !== this.currentMcpFilterKey;
180
- if (accountChanged || mcpChanged) {
181
- debug.log('engine', `Codex re-initialising (accountChanged=${accountChanged}, mcpChanged=${mcpChanged})`);
216
+ // A client built without a project (the bare `initialize()` the engine
217
+ // registry does) addresses the bridge anonymously, and its tool calls fall
218
+ // back to whichever stream started last — the way an agent in one project
219
+ // ended up opening tabs in another.
220
+ const streamProjectId = options.mcpContext?.projectId ?? null;
221
+ const projectChanged = this._isInitialized && streamProjectId !== null && streamProjectId !== this.currentProjectId;
222
+ if (accountChanged || mcpChanged || projectChanged) {
223
+ debug.log('engine', `Codex re-initialising (accountChanged=${accountChanged}, mcpChanged=${mcpChanged}, projectChanged=${projectChanged})`);
182
224
  await this.dispose();
183
225
  }
226
+ this.pendingProjectId = streamProjectId;
184
227
  if (!this._isInitialized || !this.codex) {
185
228
  await this.initialize(accountId, mcpProfileFilter);
186
229
  }
@@ -197,7 +240,9 @@ export class CodexEngine implements AIEngine {
197
240
  applyAccountAuth(activeAccount);
198
241
  }
199
242
 
200
- this.activeController = abortController || new AbortController();
243
+ const controller = abortController || new AbortController();
244
+ const run: CodexRun = { controller, thread: null };
245
+ this.runs.add(run);
201
246
 
202
247
  const resolvedProjectPath = resolveOsPath(projectPath);
203
248
  const state = createCodexState('', modelId);
@@ -237,7 +282,7 @@ export class CodexEngine implements AIEngine {
237
282
  thread = this.codex.startThread(threadOptions);
238
283
  }
239
284
 
240
- this.activeThread = thread;
285
+ run.thread = thread;
241
286
 
242
287
  // Prompt-scoped engine: advertise the profile-scoped Skills/Commands/
243
288
  // Subagents PER-SESSION via the prompt (not the shared global AGENTS.md /
@@ -245,11 +290,11 @@ export class CodexEngine implements AIEngine {
245
290
  const artifactsContext = buildArtifactsPromptContext(profileId);
246
291
  const input = await buildCodexInput(prompt, artifactsContext || undefined);
247
292
  const { events } = await thread.runStreamed(input, {
248
- signal: this.activeController.signal,
293
+ signal: controller.signal,
249
294
  });
250
295
 
251
296
  for await (const event of events) {
252
- if (this.activeController.signal.aborted) break;
297
+ if (controller.signal.aborted) break;
253
298
 
254
299
  switch (event.type) {
255
300
  case 'thread.started':
@@ -284,7 +329,7 @@ export class CodexEngine implements AIEngine {
284
329
  }
285
330
  }
286
331
 
287
- yield buildResultEvent(state, this.activeController.signal.aborted);
332
+ yield buildResultEvent(state, controller.signal.aborted);
288
333
  } catch (error) {
289
334
  handleStreamError(error);
290
335
  } finally {
@@ -295,23 +340,34 @@ export class CodexEngine implements AIEngine {
295
340
  } catch (snapshotErr) {
296
341
  debug.warn('engine', 'Codex: post-stream auth.json snapshot failed (non-fatal):', snapshotErr);
297
342
  }
298
- this.activeThread = null;
299
- this.activeController = null;
343
+ // Retire THIS run only — another chat session of the same project may
344
+ // still be streaming on this instance.
345
+ this.runs.remove(run);
300
346
  }
301
347
  }
302
348
 
303
- async cancel(): Promise<void> {
349
+ /**
350
+ * Cancel the run whose AbortController is `owner`, and only that run.
351
+ */
352
+ async cancel(owner: AbortController): Promise<void> {
353
+ await this.stopRuns(this.runs.select(owner));
354
+ }
355
+
356
+ /**
357
+ * Tear down the given runs. `cancel` passes the one run it was asked to
358
+ * stop; `dispose` passes them all. Nothing else may reach this.
359
+ */
360
+ private async stopRuns(targets: CodexRun[]): Promise<void> {
304
361
  // Abort the local controller so the for-await loop exits even if the
305
362
  // SDK's signal propagation hangs.
306
- if (this.activeController && !this.activeController.signal.aborted) {
307
- this.activeController.abort();
363
+ for (const run of targets) {
364
+ if (!run.controller.signal.aborted) run.controller.abort();
365
+ this.runs.remove(run);
308
366
  }
309
- this.activeController = null;
310
- this.activeThread = null;
311
367
  }
312
368
 
313
- async interrupt(): Promise<void> {
314
- await this.cancel();
369
+ async interrupt(owner: AbortController): Promise<void> {
370
+ await this.stopRuns(this.runs.select(owner));
315
371
  }
316
372
 
317
373
  /**