@myrialabs/clopen 0.4.32 → 0.4.34

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 (102) hide show
  1. package/backend/auth/permissions.ts +3 -0
  2. package/backend/auth/rate-limiter.test.ts +115 -0
  3. package/backend/auth/rate-limiter.ts +25 -12
  4. package/backend/chat/stream-manager.ts +4 -1
  5. package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
  6. package/backend/database/migrations/index.ts +7 -0
  7. package/backend/database/queries/db-client-connection-queries.ts +7 -2
  8. package/backend/database/queries/file-audit-log-queries.ts +1 -0
  9. package/backend/database/queries/index.ts +3 -0
  10. package/backend/database/queries/ssh-connection-queries.ts +244 -0
  11. package/backend/database/queries/ssh-known-host-queries.ts +67 -0
  12. package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
  13. package/backend/db-client/connection-manager.ts +21 -1
  14. package/backend/engine/adapters/codex/message-converter.ts +18 -12
  15. package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
  16. package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
  17. package/backend/engine/adapters/codex/stream.ts +33 -4
  18. package/backend/engine/adapters/copilot/stream.ts +1 -1
  19. package/backend/engine/adapters/cursor/stream.ts +1 -1
  20. package/backend/engine/adapters/qwen/stream.ts +1 -1
  21. package/backend/engine/docs/adapter-contract.md +7 -0
  22. package/backend/files/file-watcher.ts +283 -51
  23. package/backend/files/git-events.test.ts +110 -0
  24. package/backend/git/git-dirs.test.ts +132 -0
  25. package/backend/git/git-dirs.ts +0 -0
  26. package/backend/git/nested-repos.test.ts +108 -5
  27. package/backend/git/nested-repos.ts +103 -18
  28. package/backend/http/audio.ts +5 -32
  29. package/backend/http/bearer-auth.ts +47 -0
  30. package/backend/http/files-download.test.ts +146 -0
  31. package/backend/http/files-download.ts +109 -0
  32. package/backend/http/files-upload.ts +3 -29
  33. package/backend/http/ssh-sftp.ts +133 -0
  34. package/backend/index.ts +25 -2
  35. package/backend/mcp/README.md +34 -6
  36. package/backend/mcp/index.ts +8 -8
  37. package/backend/mcp/internal/config.ts +69 -19
  38. package/backend/mcp/internal/project-context.test.ts +40 -0
  39. package/backend/mcp/internal/project-context.ts +80 -7
  40. package/backend/mcp/internal/remote-server.test.ts +17 -2
  41. package/backend/mcp/internal/remote-server.ts +36 -3
  42. package/backend/mcp/internal/servers/helper.ts +48 -18
  43. package/backend/middleware/security.test.ts +95 -0
  44. package/backend/middleware/security.ts +114 -0
  45. package/backend/ports/attribute.test.ts +231 -0
  46. package/backend/ports/attribute.ts +444 -0
  47. package/backend/ports/kill.ts +203 -0
  48. package/backend/ports/monitor.ts +365 -0
  49. package/backend/ports/processes.test.ts +98 -0
  50. package/backend/ports/processes.ts +374 -0
  51. package/backend/ports/registry.ts +165 -0
  52. package/backend/ports/runner.ts +195 -0
  53. package/backend/ports/scan-host.ts +260 -0
  54. package/backend/ports/scan.test.ts +341 -0
  55. package/backend/ports/scan.ts +687 -0
  56. package/backend/ports/ssh-lineage.ts +318 -0
  57. package/backend/preview/browser/browser-video-capture.ts +51 -4
  58. package/backend/ssh/client-pool.ts +196 -0
  59. package/backend/ssh/connect.ts +375 -0
  60. package/backend/ssh/disk-usage.test.ts +134 -0
  61. package/backend/ssh/disk-usage.ts +214 -0
  62. package/backend/ssh/forwards.ts +340 -0
  63. package/backend/ssh/health.ts +141 -0
  64. package/backend/ssh/known-hosts.ts +96 -0
  65. package/backend/ssh/pty-backend.ts +215 -0
  66. package/backend/ssh/ptykit.ts +66 -0
  67. package/backend/ssh/sftp.test.ts +242 -0
  68. package/backend/ssh/sftp.ts +967 -0
  69. package/backend/ssh/socks5.test.ts +167 -0
  70. package/backend/ssh/socks5.ts +164 -0
  71. package/backend/ssh/tunnel.ts +87 -0
  72. package/backend/ws/auth/device.ts +1 -1
  73. package/backend/ws/auth/login.ts +8 -4
  74. package/backend/ws/db-client/connections.ts +1 -0
  75. package/backend/ws/files/watch.ts +5 -1
  76. package/backend/ws/index.ts +6 -0
  77. package/backend/ws/ports/index.ts +19 -0
  78. package/backend/ws/ports/kill.ts +80 -0
  79. package/backend/ws/ports/list.ts +60 -0
  80. package/backend/ws/ssh/access.ts +31 -0
  81. package/backend/ws/ssh/connections.ts +224 -0
  82. package/backend/ws/ssh/forwards.ts +109 -0
  83. package/backend/ws/ssh/index.ts +18 -0
  84. package/backend/ws/ssh/sftp.ts +259 -0
  85. package/backend/ws/ssh/tunnel.ts +93 -0
  86. package/dist/assets/{index-hu17G6tX.js → index-gGTMFUa8.js} +1 -1
  87. package/dist/assets/{index-DSvGoxp2.js → index-vW2RpdHu.js} +1 -1
  88. package/dist/assets/main-CYCMEbXB.css +1 -0
  89. package/dist/assets/{main-BccclZsC.js → main-ZCojSzvW.js} +506 -477
  90. package/dist/index.html +2 -2
  91. package/package.json +1 -1
  92. package/shared/types/database/schema.ts +49 -0
  93. package/shared/types/db-client/connection.ts +6 -0
  94. package/shared/types/ports/index.ts +5 -0
  95. package/shared/types/ports/port.ts +192 -0
  96. package/shared/types/ssh/connection.ts +80 -0
  97. package/shared/types/ssh/forward.ts +46 -0
  98. package/shared/types/ssh/index.ts +8 -0
  99. package/shared/types/ssh/known-host.ts +19 -0
  100. package/shared/types/ssh/sftp.ts +141 -0
  101. package/shared/utils/logger.ts +2 -0
  102. package/dist/assets/main-Ciuw0wF0.css +0 -1
@@ -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
  }
@@ -86,6 +86,24 @@ export class CodexEngine implements AIEngine {
86
86
  * `'*'` = unfiltered (no profile constraint). `null` = not initialized.
87
87
  */
88
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;
89
107
 
90
108
  get isInitialized(): boolean {
91
109
  return this._isInitialized;
@@ -101,6 +119,8 @@ export class CodexEngine implements AIEngine {
101
119
  return;
102
120
  }
103
121
 
122
+ const projectId = this.pendingProjectId;
123
+
104
124
  const account = accountId != null
105
125
  ? engineQueries.getAccount(accountId)
106
126
  : engineQueries.getActiveAccountForEngine('codex');
@@ -122,7 +142,7 @@ export class CodexEngine implements AIEngine {
122
142
  // inside the stack dir) over an older copy on the user's PATH — the SDK
123
143
  // would otherwise be pinned while the process it spawns drifts.
124
144
  const codexCli = await resolveEngineCli('codex');
125
- const mcpConfig = getCodexMcpConfig(mcpProfileFilter);
145
+ const mcpConfig = getCodexMcpConfig(mcpProfileFilter, projectId ? { projectId } : undefined);
126
146
 
127
147
  // Codex SDK takes config at construction. We pass `show_raw_agent_reasoning`
128
148
  // (so the SDK forwards reasoning text events) and forward the Clopen MCP
@@ -149,8 +169,9 @@ export class CodexEngine implements AIEngine {
149
169
  });
150
170
  this.currentAccountId = account.id;
151
171
  this.currentMcpFilterKey = mcpKey;
172
+ this.currentProjectId = projectId;
152
173
  this._isInitialized = true;
153
- 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'})`);
154
175
  }
155
176
 
156
177
  async dispose(): Promise<void> {
@@ -158,6 +179,7 @@ export class CodexEngine implements AIEngine {
158
179
  this.codex = null;
159
180
  this.currentAccountId = null;
160
181
  this.currentMcpFilterKey = null;
182
+ this.currentProjectId = null;
161
183
  this._isInitialized = false;
162
184
  debug.log('engine', 'Codex engine disposed');
163
185
  }
@@ -191,10 +213,17 @@ export class CodexEngine implements AIEngine {
191
213
  const mcpKey = mcpProfileFilter ? [...mcpProfileFilter].sort().join(',') : '*';
192
214
  const accountChanged = this._isInitialized && accountId != null && accountId !== this.currentAccountId;
193
215
  const mcpChanged = this._isInitialized && mcpKey !== this.currentMcpFilterKey;
194
- if (accountChanged || mcpChanged) {
195
- 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})`);
196
224
  await this.dispose();
197
225
  }
226
+ this.pendingProjectId = streamProjectId;
198
227
  if (!this._isInitialized || !this.codex) {
199
228
  await this.initialize(accountId, mcpProfileFilter);
200
229
  }
@@ -339,7 +339,7 @@ export class CopilotEngine implements AIEngine {
339
339
  const { approveAll } = await loadEngineSdk<typeof import('@github/copilot-sdk')>('copilot', '@github/copilot-sdk');
340
340
 
341
341
  try {
342
- const mcpConfig = getCopilotMcpConfig(mcpProfileFilter);
342
+ const mcpConfig = getCopilotMcpConfig(mcpProfileFilter, options.mcpContext);
343
343
 
344
344
  const baseConfig: ResumeSessionConfig = {
345
345
  onPermissionRequest: (request, invocation) =>
@@ -192,7 +192,7 @@ export class CursorEngine implements AIEngine {
192
192
  },
193
193
  });
194
194
  const customTools: Record<string, SDKCustomTool> = { AskUserQuestion: askTool };
195
- const mcpServers = getCursorMcpConfig(mcpProfileFilter);
195
+ const mcpServers = getCursorMcpConfig(mcpProfileFilter, options.mcpContext);
196
196
  const agents = await this.buildAgents();
197
197
 
198
198
  const { Agent } = await loadEngineSdk<typeof import('@cursor/sdk')>('cursor', '@cursor/sdk');
@@ -162,7 +162,7 @@ export class QwenEngine implements AIEngine {
162
162
  // Refresh the synthetic skills preamble in the Qwen memory file.
163
163
  await syncSkills('qwen', profileId);
164
164
  await syncEngineArtifacts('qwen', profileId);
165
- const mcpConfig = getQwenMcpConfig(mcpProfileFilter);
165
+ const mcpConfig = getQwenMcpConfig(mcpProfileFilter, options.mcpContext);
166
166
 
167
167
  // Resolve the permission policy once per stream; canUseTool enforces it
168
168
  // (Qwen otherwise auto-allows everything). Tool names arrive snake_cased.
@@ -190,6 +190,13 @@ interface EngineQueryOptions {
190
190
  **cannot** write into project B. Always forward it: see `claude/stream.ts`
191
191
  calling `getEnabledMcpServers(options.mcpContext)`.
192
192
 
193
+ Engines that reach MCP over the HTTP bridge instead of in-process forward the
194
+ same context to their config builder — `getCodexMcpConfig(filter, mcpContext)`
195
+ and friends — which writes it into the bridge URL for `handleMcpRequest` to bind.
196
+ Skipping it does not fail loudly: the handler falls back to the most recently
197
+ started stream, so tool calls land in whichever project the user most recently
198
+ prompted in. See `backend/mcp/README.md` → "Who is calling".
199
+
193
200
  `reasoningEffort` is an **opaque, native-per-engine token** — there is no
194
201
  cross-engine normalization. The adapter that produced the level in
195
202
  `models.ts` is the one that consumes it in `stream.ts`; every other layer