@myrialabs/clopen 0.4.44 → 0.4.45

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 (67) hide show
  1. package/backend/artifacts/project/bridge.ts +218 -0
  2. package/backend/artifacts/project/edit.ts +243 -0
  3. package/backend/artifacts/project/index.ts +38 -0
  4. package/backend/artifacts/project/project.test.ts +181 -0
  5. package/backend/artifacts/project/scan.ts +368 -0
  6. package/backend/artifacts/project/sources.ts +100 -0
  7. package/backend/artifacts/sync.ts +1 -1
  8. package/backend/auth/permissions.ts +15 -0
  9. package/backend/chat/stream-manager.ts +20 -3
  10. package/backend/database/migrations/083_create_project_mcp_trust.ts +32 -0
  11. package/backend/database/migrations/index.ts +7 -0
  12. package/backend/database/queries/index.ts +2 -0
  13. package/backend/database/queries/project-mcp-trust-queries.ts +43 -0
  14. package/backend/engine/adapters/claude/stream.ts +27 -1
  15. package/backend/engine/adapters/cline/mcp-tools.ts +26 -4
  16. package/backend/engine/adapters/cline/stream.ts +20 -6
  17. package/backend/engine/adapters/codex/stream.ts +21 -4
  18. package/backend/engine/adapters/copilot/stream.ts +6 -3
  19. package/backend/engine/adapters/cursor/stream.ts +19 -8
  20. package/backend/engine/adapters/opencode/server.ts +14 -4
  21. package/backend/engine/adapters/opencode/stream.ts +18 -3
  22. package/backend/engine/adapters/pi/mcp-tools.ts +26 -4
  23. package/backend/engine/adapters/pi/stream.ts +35 -3
  24. package/backend/engine/adapters/qwen/stream.ts +8 -0
  25. package/backend/engine/artifact-sync.ts +12 -5
  26. package/backend/files/file-watcher.test.ts +77 -0
  27. package/backend/files/file-watcher.ts +92 -60
  28. package/backend/files/watch-ignore.test.ts +182 -0
  29. package/backend/files/watch-ignore.ts +244 -0
  30. package/backend/git/git-executor.ts +14 -4
  31. package/backend/index.ts +11 -1
  32. package/backend/instructions/service.ts +5 -3
  33. package/backend/instructions/sync.ts +10 -27
  34. package/backend/mcp/external/config.ts +65 -23
  35. package/backend/mcp/external/project.ts +124 -0
  36. package/backend/mcp/external/proxy.ts +65 -11
  37. package/backend/mcp/index.ts +14 -9
  38. package/backend/mcp/internal/remote-server.ts +11 -1
  39. package/backend/skills/marketplace.ts +1 -1
  40. package/backend/snapshot/blob-store.ts +9 -5
  41. package/backend/snapshot/git-attribution.test.ts +42 -0
  42. package/backend/snapshot/git-attribution.ts +306 -0
  43. package/backend/snapshot/gitignore.test.ts +62 -0
  44. package/backend/snapshot/gitignore.ts +158 -78
  45. package/backend/snapshot/snapshot-service.test.ts +270 -0
  46. package/backend/snapshot/snapshot-service.ts +412 -136
  47. package/backend/snapshot/turn-activity.test.ts +52 -0
  48. package/backend/snapshot/turn-activity.ts +83 -0
  49. package/backend/snapshot/turn-changes.test.ts +58 -1
  50. package/backend/snapshot/turn-changes.ts +66 -0
  51. package/backend/worktrees/tree.ts +1 -1
  52. package/backend/ws/chat/composer.ts +504 -0
  53. package/backend/ws/chat/index.ts +3 -1
  54. package/backend/ws/chat/stream.ts +252 -440
  55. package/backend/ws/index.ts +4 -0
  56. package/backend/ws/project-artifacts/index.ts +236 -0
  57. package/backend/ws/snapshot/changes.ts +66 -31
  58. package/dist/assets/{index-BWyhqUi5.js → index-Am-rJRxA.js} +1 -1
  59. package/dist/assets/{index-DX5OwLOc.js → index-D-Ad1N96.js} +1 -1
  60. package/dist/assets/main--PLCDxSy.css +1 -0
  61. package/dist/assets/main-DelPm2Xt.js +1239 -0
  62. package/dist/index.html +2 -2
  63. package/package.json +1 -1
  64. package/shared/types/stores/settings.ts +5 -0
  65. package/shared/types/unified/message.ts +2 -0
  66. package/dist/assets/main-DOkwqXRU.js +0 -1215
  67. package/dist/assets/main-DzCY0n-j.css +0 -1
@@ -259,6 +259,21 @@ export const ADMIN_ONLY_ROUTES = new Set([
259
259
  'instructions:save-global',
260
260
  'instructions:get-project',
261
261
  'instructions:save-project',
262
+ // Project artifacts — reads and in-place edits of a repository's `.agents/`,
263
+ // `AGENTS.md` block and `.agents/mcp.json` (whose approval lets Clopen start
264
+ // the processes it declares). Same shared-store rationale; admin-only.
265
+ 'project-artifacts:scan',
266
+ 'project-artifacts:read',
267
+ 'project-artifacts:save-skill',
268
+ 'project-artifacts:delete-skill',
269
+ 'project-artifacts:save-subagent',
270
+ 'project-artifacts:delete-subagent',
271
+ 'project-artifacts:copy-to-agents',
272
+ 'project-artifacts:get-agents-md',
273
+ 'project-artifacts:save-agents-md',
274
+ 'project-artifacts:get-mcp',
275
+ 'project-artifacts:save-mcp',
276
+ 'project-artifacts:approve-mcp',
262
277
  // Permissions — per-engine tool allow/deny applied to every engine/project;
263
278
  // same shared-store rationale as Skills/MCP, admin-only surface.
264
279
  'permissions:list',
@@ -557,12 +557,15 @@ class StreamManager extends EventEmitter {
557
557
  // engine initialization. It MUST finish before the engine can write any files
558
558
  // (awaited just before streamQuery below) — otherwise early writes would be
559
559
  // folded into the baseline and silently dropped from this turn's checkpoint.
560
+ // Re-taken every turn (see SnapshotService.beginTurn): a baseline carried
561
+ // over from the previous turn charged every idle-time change to this one.
560
562
  let baselineInitPromise: Promise<void> | null = null;
561
- if (requestData.projectPath && requestData.chatSessionId) {
562
- baselineInitPromise = snapshotService.initializeSessionBaseline(
563
+ if (requestData.projectPath && requestData.projectId && requestData.chatSessionId) {
564
+ baselineInitPromise = snapshotService.beginTurn(
563
565
  requestData.projectPath,
566
+ requestData.projectId,
564
567
  requestData.chatSessionId
565
- ).catch(err => debug.error('snapshot', 'Failed to initialize session baseline:', err));
568
+ ).catch(err => debug.error('snapshot', 'Failed to begin snapshot turn:', err));
566
569
  }
567
570
 
568
571
  try {
@@ -907,6 +910,12 @@ class StreamManager extends EventEmitter {
907
910
  break;
908
911
  }
909
912
 
913
+ // Every output, not only tool calls: the gap before a call is when an
914
+ // engine that reports commands after the fact actually ran them. This
915
+ // is how a snapshot tells this chat's writes from another chat's in
916
+ // the same folder, for any tool (see snapshot/turn-activity.ts).
917
+ if (chatSessionId) snapshotService.observeEngineOutput(chatSessionId, output);
918
+
910
919
  // ── Route by type discriminant ──────────────────────────────
911
920
 
912
921
  // Extract session ID from first event that has one
@@ -1398,6 +1407,10 @@ class StreamManager extends EventEmitter {
1398
1407
  deletedPaths: delta?.deleted ?? []
1399
1408
  });
1400
1409
  });
1410
+ } else if (chatSessionId) {
1411
+ // No user message was saved, so there is nothing to capture against —
1412
+ // but the turn was opened and must not stay "running".
1413
+ void snapshotService.endTurn(chatSessionId);
1401
1414
  }
1402
1415
  }
1403
1416
  }
@@ -1946,6 +1959,10 @@ class StreamManager extends EventEmitter {
1946
1959
  * Used when a session is deleted to remove green/amber status indicators.
1947
1960
  */
1948
1961
  async cleanupSessionStreams(chatSessionId: string): Promise<void> {
1962
+ // Session-scoped state held elsewhere (e.g. the composer's drafts and
1963
+ // message queue) is released through this event.
1964
+ this.emit('session:cleanup', chatSessionId);
1965
+
1949
1966
  const streamsToCancel: string[] = [];
1950
1967
  const streamsToClean: string[] = [];
1951
1968
 
@@ -0,0 +1,32 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create project_mcp_trust for admin approval of a repository\'s .agents/mcp.json';
5
+
6
+ /**
7
+ * A repository's `.agents/mcp.json` can start arbitrary processes, and in a
8
+ * multi-user instance anyone who can push to the repo could otherwise make
9
+ * Clopen run a command on the server. So project MCP servers stay inert until
10
+ * an admin approves them.
11
+ *
12
+ * The approval is bound to the file's sha256, not to the project: any edit to
13
+ * the file — including one arriving through `git pull` — produces a new hash and
14
+ * the servers go inert again until someone re-approves the new content. One row
15
+ * per project; approving a new version replaces the old one.
16
+ */
17
+ export const up = (db: DatabaseConnection): void => {
18
+ debug.log('migration', '📋 Creating project_mcp_trust table...');
19
+ db.exec(`
20
+ CREATE TABLE IF NOT EXISTS project_mcp_trust (
21
+ project_id TEXT PRIMARY KEY REFERENCES projects(id) ON DELETE CASCADE,
22
+ file_hash TEXT NOT NULL,
23
+ approved_by TEXT,
24
+ approved_at TEXT NOT NULL DEFAULT (datetime('now'))
25
+ )
26
+ `);
27
+ debug.log('migration', '✅ project_mcp_trust table created');
28
+ };
29
+
30
+ export const down = (db: DatabaseConnection): void => {
31
+ db.exec('DROP TABLE IF EXISTS project_mcp_trust');
32
+ };
@@ -81,6 +81,7 @@ import * as migration079 from './079_merge_commands_into_skills';
81
81
  import * as migration080 from './080_create_file_shares';
82
82
  import * as migration081 from './081_create_push_subscriptions';
83
83
  import * as migration082 from './082_create_git_identities';
84
+ import * as migration083 from './083_create_project_mcp_trust';
84
85
 
85
86
  // Export all migrations in order
86
87
  export const migrations = [
@@ -575,6 +576,12 @@ export const migrations = [
575
576
  description: migration082.description,
576
577
  up: migration082.up,
577
578
  down: migration082.down
579
+ },
580
+ {
581
+ id: '083',
582
+ description: migration083.description,
583
+ up: migration083.up,
584
+ down: migration083.down
578
585
  }
579
586
  ];
580
587
 
@@ -26,6 +26,8 @@ export { subagentQueries } from './subagent-queries';
26
26
  export type { SubagentRow, SubagentInput, SubagentSource } from './subagent-queries';
27
27
  export { instructionQueries } from './instruction-queries';
28
28
  export type { InstructionRow, InstructionScope } from './instruction-queries';
29
+ export { projectMcpTrustQueries } from './project-mcp-trust-queries';
30
+ export type { ProjectMcpTrustRow } from './project-mcp-trust-queries';
29
31
  export { permissionSetQueries } from './permission-set-queries';
30
32
  export type { PermissionSet, PermissionScope } from './permission-set-queries';
31
33
  export { graphQueries, deriveDigest, entityKeyFor, DIGEST_VERSION } from './graph-queries';
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Project MCP trust — which version of a repository's `.agents/mcp.json` an
3
+ * admin approved. Approval is keyed by the file's sha256 (see migration 083), so
4
+ * a changed file is simply "not the approved one" until re-approved.
5
+ */
6
+
7
+ import { getDatabase } from '../index';
8
+
9
+ export interface ProjectMcpTrustRow {
10
+ project_id: string;
11
+ file_hash: string;
12
+ approved_by: string | null;
13
+ approved_at: string;
14
+ }
15
+
16
+ export const projectMcpTrustQueries = {
17
+ get(projectId: string): ProjectMcpTrustRow | null {
18
+ return getDatabase()
19
+ .prepare('SELECT * FROM project_mcp_trust WHERE project_id = ?')
20
+ .get(projectId) as ProjectMcpTrustRow | null;
21
+ },
22
+
23
+ isTrusted(projectId: string, fileHash: string): boolean {
24
+ return this.get(projectId)?.file_hash === fileHash;
25
+ },
26
+
27
+ approve(projectId: string, fileHash: string, approvedBy: string | null): void {
28
+ getDatabase()
29
+ .prepare(`
30
+ INSERT INTO project_mcp_trust (project_id, file_hash, approved_by, approved_at)
31
+ VALUES (?, ?, ?, datetime('now'))
32
+ ON CONFLICT(project_id) DO UPDATE SET
33
+ file_hash = excluded.file_hash,
34
+ approved_by = excluded.approved_by,
35
+ approved_at = excluded.approved_at
36
+ `)
37
+ .run(projectId, fileHash, approvedBy);
38
+ },
39
+
40
+ revoke(projectId: string): void {
41
+ getDatabase().prepare('DELETE FROM project_mcp_trust WHERE project_id = ?').run(projectId);
42
+ }
43
+ };
@@ -36,6 +36,7 @@ import { emptyGenerationError } from '../../structured-helpers';
36
36
  import { getEnabledMcpServers, getAllowedMcpTools } from '../../../mcp';
37
37
  import { syncSkills } from '$backend/skills';
38
38
  import { syncEngineArtifacts } from '$backend/engine/artifact-sync';
39
+ import { resolveProjectBridge, ensureClaudeProjectPlugin, buildProjectPromptContext } from '$backend/artifacts/project';
39
40
  import { artifactFilter } from '$backend/profiles';
40
41
  import { resolvePermissionsFromDb, isToolAllowed, hasAnyRestriction, syncPermissions } from '$backend/permissions';
41
42
  import type { AIEngine, EngineQueryOptions } from '../../types';
@@ -181,6 +182,25 @@ export class ClaudeCodeEngine implements AIEngine {
181
182
  // equivalent — the PreToolUse hook below is the authoritative enforcement.
182
183
  await syncPermissions('claude');
183
184
 
185
+ // The repository's own artifacts Claude doesn't read natively (it reads
186
+ // `.claude/*` and CLAUDE.md itself via settingSources). All three ride
187
+ // per-query options, so nothing is written into the repo or into the
188
+ // isolated config dir another session shares:
189
+ // - skills (e.g. `.agents/skills`) → a Clopen-owned local plugin;
190
+ // - subagents (e.g. `.agents/agents`) → the SDK `agents` option;
191
+ // - AGENTS.md + the Clopen-only project block → the appended system prompt.
192
+ const projectBridge = await resolveProjectBridge('claude', resolvedProjectPath, options.mcpContext?.projectId);
193
+ const projectPlugin = await ensureClaudeProjectPlugin(projectBridge);
194
+ const projectInstructions = buildProjectPromptContext(projectBridge, { instructions: true });
195
+ const projectAgents = projectBridge.subagents.length > 0
196
+ ? Object.fromEntries(projectBridge.subagents.map(sub => [sub.slug, {
197
+ description: sub.description || sub.name,
198
+ prompt: sub.prompt,
199
+ ...(sub.tools && { tools: sub.tools }),
200
+ ...(sub.model && { model: sub.model })
201
+ }]))
202
+ : undefined;
203
+
184
204
  // Resolve the effective permission policy once per stream. Enforcement
185
205
  // lives in the PreToolUse hook, NOT in canUseTool: under
186
206
  // permissionMode 'bypassPermissions' the CLI auto-approves a tool call
@@ -229,8 +249,14 @@ export class ClaudeCodeEngine implements AIEngine {
229
249
  allowDangerouslySkipPermissions: true,
230
250
  cwd: resolvedProjectPath,
231
251
  env: getEngineEnv(accountId, options.gitIdentityEnv),
232
- systemPrompt: { type: "preset", preset: "claude_code" },
252
+ systemPrompt: projectInstructions
253
+ ? { type: "preset", preset: "claude_code", append: projectInstructions }
254
+ : { type: "preset", preset: "claude_code" },
233
255
  settingSources: ["user", "project", "local"],
256
+ // The plugin carries skills only; its MCP discovery is off because
257
+ // project MCP servers come through Clopen's trust-gated bridge.
258
+ ...(projectPlugin && { plugins: [{ type: 'local' as const, path: projectPlugin, skipMcpDiscovery: true }] }),
259
+ ...(projectAgents && { agents: projectAgents }),
234
260
  forkSession: true,
235
261
  // Reasoning level → thinking/effort (see thinkingConfig above). Adaptive
236
262
  // thinking with summarized display keeps Opus 4.6+ emitting visible
@@ -25,6 +25,9 @@ import {
25
25
  getEnabledExternalServers,
26
26
  listExternalServerTools,
27
27
  callExternalServerTool,
28
+ getTrustedProjectServers,
29
+ listProjectServerTools,
30
+ callProjectServerTool,
28
31
  projectContextService,
29
32
  serverMetadata,
30
33
  } from '../../../mcp';
@@ -92,12 +95,31 @@ export async function buildClineMcpTools(
92
95
  }
93
96
 
94
97
  // ── External servers (proxied upstream) ──
95
- for (const server of getEnabledExternalServers(profileFilter)) {
98
+ // Installed servers (profile-filtered) plus the project's approved
99
+ // `.agents/mcp.json` servers, which never shadow an installed namespace.
100
+ const upstreams: { label: string; namespace: string; list: () => ReturnType<typeof listExternalServerTools>; call: (tool: string, args: unknown) => Promise<unknown> }[] =
101
+ getEnabledExternalServers(profileFilter).map(s => ({
102
+ label: s.slug,
103
+ namespace: s.namespace,
104
+ list: () => listExternalServerTools(s.slug),
105
+ call: (tool: string, args: unknown) => callExternalServerTool(s.slug, tool, args)
106
+ }));
107
+ const taken = new Set(upstreams.map(u => u.namespace));
108
+ for (const s of getTrustedProjectServers(context?.projectId)) {
109
+ if (taken.has(s.namespace)) continue;
110
+ upstreams.push({
111
+ label: s.namespace,
112
+ namespace: s.namespace,
113
+ list: () => listProjectServerTools(s.projectId, s.name),
114
+ call: (tool: string, args: unknown) => callProjectServerTool(s.projectId, s.name, tool, args)
115
+ });
116
+ }
117
+ for (const server of upstreams) {
96
118
  let externalTools;
97
119
  try {
98
- externalTools = await listExternalServerTools(server.slug);
120
+ externalTools = await server.list();
99
121
  } catch (error) {
100
- debug.warn('mcp', `Cline MCP bridge: could not list tools for "${server.slug}" (skipping):`, error);
122
+ debug.warn('mcp', `Cline MCP bridge: could not list tools for "${server.label}" (skipping):`, error);
101
123
  continue;
102
124
  }
103
125
  for (const tool of externalTools) {
@@ -108,7 +130,7 @@ export async function buildClineMcpTools(
108
130
  description: `${tool.description ?? tool.name}${schemaText}`,
109
131
  inputSchema: OPEN_PARAMS,
110
132
  async execute(params: unknown) {
111
- const result = (await callExternalServerTool(server.slug, tool.name, params ?? {})) as { content?: unknown } | undefined;
133
+ const result = (await server.call(tool.name, params ?? {})) as { content?: unknown } | undefined;
112
134
  return toResultText(result?.content);
113
135
  },
114
136
  }) as AgentTool);
@@ -31,6 +31,7 @@ import { debug } from '$shared/utils/logger';
31
31
  import { engineQueries } from '$backend/database/queries/engine-queries';
32
32
  import { syncSkills } from '$backend/skills';
33
33
  import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
34
+ import { resolveProjectBridge, type ProjectBridge } from '$backend/artifacts/project';
34
35
  import { artifactFilter } from '$backend/profiles';
35
36
  import { resolvePermissionsFromDb, isToolAllowed } from '$backend/permissions';
36
37
  import { buildJsonPrompt, extractJson, emptyGenerationError } from '../../structured-helpers';
@@ -133,7 +134,7 @@ export class ClineEngine implements AIEngine {
133
134
  return fetchClineModels();
134
135
  }
135
136
 
136
- private async buildSystemPrompt(cwd: string, providerId: string, profileId?: number): Promise<string> {
137
+ private async buildSystemPrompt(cwd: string, providerId: string, profileId?: number, project?: ProjectBridge): Promise<string> {
137
138
  const { getClineDefaultSystemPrompt } = await loadEngineSdk<typeof import('@cline/sdk')>('cline', '@cline/sdk');
138
139
  let base: string;
139
140
  try {
@@ -141,7 +142,7 @@ export class ClineEngine implements AIEngine {
141
142
  } catch {
142
143
  base = 'You are Cline, a highly skilled software engineer. Use the available tools to complete the user\'s coding task.';
143
144
  }
144
- const artifacts = buildArtifactsPromptContext('cline', profileId);
145
+ const artifacts = buildArtifactsPromptContext('cline', profileId, project);
145
146
  return artifacts ? `${base}\n\n${artifacts}` : base;
146
147
  }
147
148
 
@@ -168,6 +169,9 @@ export class ClineEngine implements AIEngine {
168
169
  const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
169
170
  await syncSkills('cline', profileId);
170
171
  await syncEngineArtifacts('cline', profileId);
172
+ // Cline (stateless Agent) reads nothing from the repo, so every project
173
+ // artifact — skills, subagents, AGENTS.md — reaches it through Clopen.
174
+ const projectBridge = await resolveProjectBridge('cline', resolvedProjectPath, options.mcpContext?.projectId);
171
175
 
172
176
  // ── Permissions → toolPolicies (denied builtins are hidden from the model) ──
173
177
  const permissions = resolvePermissionsFromDb('cline', options.mcpContext?.projectId, profileId);
@@ -201,13 +205,23 @@ export class ClineEngine implements AIEngine {
201
205
  // "Available Subagents" preamble alone can't be invoked. Expose an `Agent`
202
206
  // tool that actually spawns a bounded sub-`Agent` with the chosen subagent's
203
207
  // system prompt and returns its final text. ──
204
- const subagents: SubagentInfo[] = subagentQueries.getEnabled().map(s => ({ slug: s.slug, name: s.name, description: s.description }));
208
+ // Project subagents join the same tool; an installed subagent wins a slug clash.
209
+ const installedSubagents = subagentQueries.getEnabled();
210
+ const installedSlugs = new Set(installedSubagents.map(s => s.slug));
211
+ const projectSubagents = new Map(projectBridge.subagents.filter(s => !installedSlugs.has(s.slug)).map(s => [s.slug, s]));
212
+ const subagents: SubagentInfo[] = [
213
+ ...installedSubagents.map(s => ({ slug: s.slug, name: s.name, description: s.description })),
214
+ ...[...projectSubagents.values()].map(s => ({ slug: s.slug, name: s.name, description: s.description })),
215
+ ];
205
216
  if (subagents.length > 0) {
206
217
  const agentTool = await createAgentDispatchTool({
207
218
  subagents,
208
219
  run: async (subagent, subPrompt, toolCallId, signal) => {
209
- const md = (await readSubagentMd(subagent.slug)) ?? '';
210
- const instructions = stripFrontmatter(md) || `You are the ${subagent.name} subagent. ${subagent.description}`;
220
+ const projectSubagent = projectSubagents.get(subagent.slug);
221
+ const md = projectSubagent ? '' : ((await readSubagentMd(subagent.slug)) ?? '');
222
+ const instructions = projectSubagent?.prompt
223
+ || stripFrontmatter(md)
224
+ || `You are the ${subagent.name} subagent. ${subagent.description}`;
211
225
  // APPEND the subagent instructions to Cline's base coding prompt (a
212
226
  // bare instruction strips the tool-use scaffolding). The sub-Agent gets
213
227
  // the permission-filtered builtins ONLY — no AskUserQuestion, no MCP,
@@ -281,7 +295,7 @@ export class ClineEngine implements AIEngine {
281
295
  const priorMessages = resume ? this.sessions.get(resume) : undefined;
282
296
  const sessionId = crypto.randomUUID();
283
297
 
284
- const systemPrompt = await this.buildSystemPrompt(resolvedProjectPath, provider, profileId);
298
+ const systemPrompt = await this.buildSystemPrompt(resolvedProjectPath, provider, profileId, projectBridge);
285
299
  const agent = new Agent({
286
300
  providerId: provider,
287
301
  modelId,
@@ -28,11 +28,12 @@ import { engineQueries } from '$backend/database/queries/engine-queries';
28
28
  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
- import { getCodexMcpConfig } from '../../../mcp';
31
+ import { getCodexMcpConfig, getTrustedProjectServers } from '../../../mcp';
32
32
  import { EngineRuns } from '../run-registry';
33
33
  import { artifactFilter } from '$backend/profiles';
34
34
  import { syncSkills } from '$backend/skills';
35
35
  import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
36
+ import { resolveProjectBridge } from '$backend/artifacts/project';
36
37
  import { CODEX_MODELS, resolveCodexEffort } from './models';
37
38
  import { debug } from '$shared/utils/logger';
38
39
  import { handleStreamError, buildTurnError } from './error-handler';
@@ -135,8 +136,20 @@ export class CodexEngine implements AIEngine {
135
136
  return this.runs.isActive;
136
137
  }
137
138
 
139
+ /**
140
+ * Identity of the MCP set baked into the client: the Profile's connector
141
+ * filter plus the project's approved `.agents/mcp.json` servers. Approving,
142
+ * revoking or editing that file changes the key, so the next turn rebuilds
143
+ * the client instead of serving a stale server list.
144
+ */
145
+ private mcpKeyFor(mcpProfileFilter: Set<string> | undefined, projectId: string | null): string {
146
+ const filterKey = mcpProfileFilter ? [...mcpProfileFilter].sort().join(',') : '*';
147
+ const projectKey = getTrustedProjectServers(projectId).map(s => s.namespace).sort().join(',');
148
+ return `${filterKey}|${projectKey}`;
149
+ }
150
+
138
151
  async initialize(accountId?: number, mcpProfileFilter?: Set<string>): Promise<void> {
139
- const mcpKey = mcpProfileFilter ? [...mcpProfileFilter].sort().join(',') : '*';
152
+ const mcpKey = this.mcpKeyFor(mcpProfileFilter, this.pendingProjectId);
140
153
  if (this._isInitialized && (accountId == null || accountId === this.currentAccountId) && mcpKey === this.currentMcpFilterKey) {
141
154
  return;
142
155
  }
@@ -234,7 +247,7 @@ export class CodexEngine implements AIEngine {
234
247
  // Qwen/Copilot do per stream); `undefined` = unfiltered → no change for the
235
248
  // common no-profile path.
236
249
  const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
237
- const mcpKey = mcpProfileFilter ? [...mcpProfileFilter].sort().join(',') : '*';
250
+ const mcpKey = this.mcpKeyFor(mcpProfileFilter, options.mcpContext?.projectId ?? null);
238
251
  const accountChanged = this._isInitialized && accountId != null && accountId !== this.currentAccountId;
239
252
  const mcpChanged = this._isInitialized && mcpKey !== this.currentMcpFilterKey;
240
253
  // A client built without a project (the bare `initialize()` the engine
@@ -319,7 +332,11 @@ export class CodexEngine implements AIEngine {
319
332
  // Prompt-scoped engine: advertise the profile-scoped Skills/Commands/
320
333
  // Subagents PER-SESSION via the prompt (not the shared global AGENTS.md /
321
334
  // persistent client) so the active Profile scopes them correctly.
322
- const artifactsContext = buildArtifactsPromptContext('codex', profileId);
335
+ // Codex reads AGENTS.md and `.agents/skills` itself; anything else the
336
+ // repo carries (e.g. `.claude/skills`, the Clopen-only project block)
337
+ // rides the same per-turn prompt context.
338
+ const projectBridge = await resolveProjectBridge('codex', resolvedProjectPath, options.mcpContext?.projectId);
339
+ const artifactsContext = buildArtifactsPromptContext('codex', profileId, projectBridge);
323
340
  const input = await buildCodexInput(prompt, artifactsContext || undefined);
324
341
  const { events } = await thread.runStreamed(input, {
325
342
  signal: controller.signal,
@@ -28,6 +28,7 @@ import { EngineRuns } from '../run-registry';
28
28
  import { artifactFilter } from '$backend/profiles';
29
29
  import { syncSkills } from '$backend/skills';
30
30
  import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
31
+ import { resolveProjectBridge } from '$backend/artifacts/project';
31
32
  import { resolvePermissionsFromDb, isToolAllowed, type ResolvedPermissions } from '$backend/permissions';
32
33
  import { handleStreamError, buildSessionError } from './error-handler';
33
34
  import { fetchCopilotModels } from './models';
@@ -279,13 +280,15 @@ export class CopilotEngine implements AIEngine {
279
280
  // the authoritative per-session signal (synthetic commands/subagents are
280
281
  // stripped from the global file; the native skill mirror still loads the
281
282
  // filtered folders).
282
- const artifactsContext = buildArtifactsPromptContext('copilot', profileId);
283
+ const resolvedProjectPath = resolveOsPath(projectPath);
284
+ // Copilot reads `.github/*`, `.agents/skills`, `.claude/skills` and
285
+ // AGENTS.md itself; the rest of the repo's artifacts join the preamble.
286
+ const projectBridge = await resolveProjectBridge('copilot', resolvedProjectPath, options.mcpContext?.projectId);
287
+ const artifactsContext = buildArtifactsPromptContext('copilot', profileId, projectBridge);
283
288
 
284
289
  // Resolve the permission policy once per stream; onPermissionRequest below
285
290
  // enforces it (Copilot otherwise approves every tool via approveAll).
286
291
  const permissions = resolvePermissionsFromDb('copilot', options.mcpContext?.projectId, profileId);
287
-
288
- const resolvedProjectPath = resolveOsPath(projectPath);
289
292
  const state = createStreamConverterState('', modelId);
290
293
 
291
294
  // Buffered queue between async event handler and the for-await consumer.
@@ -30,6 +30,7 @@ import { debug } from '$shared/utils/logger';
30
30
  import { engineQueries } from '$backend/database/queries/engine-queries';
31
31
  import { syncSkills } from '$backend/skills';
32
32
  import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
33
+ import { resolveProjectBridge, type ProjectBridge } from '$backend/artifacts/project';
33
34
  import { artifactFilter } from '$backend/profiles';
34
35
  import { resolvePermissionsFromDb, excludedBuiltinTools } from '$backend/permissions';
35
36
  import { getCursorMcpConfig } from '../../../mcp';
@@ -138,17 +139,24 @@ export class CursorEngine implements AIEngine {
138
139
  return fetchCursorModels();
139
140
  }
140
141
 
141
- /** Build the `agents` config from Clopen's enabled subagents (Cursor-native). */
142
- private async buildAgents(): Promise<Record<string, AgentDefinition> | undefined> {
143
- const subagents = subagentQueries.getEnabled();
144
- if (subagents.length === 0) return undefined;
142
+ /**
143
+ * Build the `agents` config from Clopen's enabled subagents plus the
144
+ * repository's own (Cursor-native). Clopen runs Cursor with its project
145
+ * setting source off, so repo subagents only arrive this way; an installed
146
+ * subagent wins a slug clash.
147
+ */
148
+ private async buildAgents(project: ProjectBridge): Promise<Record<string, AgentDefinition> | undefined> {
145
149
  const agents: Record<string, AgentDefinition> = {};
146
- for (const s of subagents) {
150
+ for (const s of subagentQueries.getEnabled()) {
147
151
  const md = (await readSubagentMd(s.slug)) ?? '';
148
152
  const prompt = stripFrontmatter(md) || `You are the ${s.name} subagent. ${s.description}`;
149
153
  agents[s.slug] = { description: s.description || s.name, prompt, model: 'inherit' };
150
154
  }
151
- return agents;
155
+ for (const s of project.subagents) {
156
+ if (agents[s.slug]) continue;
157
+ agents[s.slug] = { description: s.description || s.name, prompt: s.prompt, model: 'inherit' };
158
+ }
159
+ return Object.keys(agents).length > 0 ? agents : undefined;
152
160
  }
153
161
 
154
162
  async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
@@ -177,6 +185,9 @@ export class CursorEngine implements AIEngine {
177
185
  const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
178
186
  await syncSkills('cursor', profileId);
179
187
  await syncEngineArtifacts('cursor', profileId);
188
+ // Cursor's own repo scan is gated on `settingSources`, which Clopen leaves
189
+ // off — so every project artifact reaches it through Clopen.
190
+ const projectBridge = await resolveProjectBridge('cursor', resolvedProjectPath, options.mcpContext?.projectId);
180
191
 
181
192
  // ── Permissions → disallowedTools ──
182
193
  // Cursor exposes no per-call permission hook, but `AgentOptions` takes a
@@ -208,7 +219,7 @@ export class CursorEngine implements AIEngine {
208
219
  });
209
220
  const customTools: Record<string, SDKCustomTool> = { AskUserQuestion: askTool };
210
221
  const mcpServers = getCursorMcpConfig(mcpProfileFilter, options.mcpContext);
211
- const agents = await this.buildAgents();
222
+ const agents = await this.buildAgents(projectBridge);
212
223
 
213
224
  const { Agent } = await loadEngineSdk<typeof import('@cursor/sdk')>('cursor', '@cursor/sdk');
214
225
  const store = await getCursorStore(projectPath);
@@ -269,7 +280,7 @@ export class CursorEngine implements AIEngine {
269
280
  // and nothing else. It is rebuilt per turn on purpose: the active Profile can
270
281
  // change mid-session, and a stale advertisement is worse than a repeated one.
271
282
  const promptText = prompt.content.filter(b => b.type === 'text').map(b => (b.type === 'text' ? b.text : '')).join('\n');
272
- const artifacts = buildArtifactsPromptContext('cursor', profileId);
283
+ const artifacts = buildArtifactsPromptContext('cursor', profileId, projectBridge);
273
284
  const text = artifacts ? `${artifacts}\n\n${promptText}` : promptText;
274
285
  const images: SDKImage[] = [];
275
286
  for (const b of prompt.content) {
@@ -70,7 +70,7 @@ import { readdir, readFile, rename, stat } from 'fs/promises';
70
70
  import { createServer } from 'node:net';
71
71
  import type { OpencodeClient } from '@opencode-ai/sdk';
72
72
  import type { Subprocess } from 'bun';
73
- import { getOpenCodeMcpConfig, getEnabledServerNames, getEnabledToolsForServer } from '../../../mcp';
73
+ import { getOpenCodeMcpConfig, getOpenCodeProjectMcpConfig, getEnabledServerNames, getEnabledToolsForServer } from '../../../mcp';
74
74
  import { engineQueries, settingsQueries } from '../../../database/queries';
75
75
  import { generateOpenCodeProviderConfig, parseCredentialMap } from './config';
76
76
  import type { OpenCodeInlineAgent } from '$backend/subagents';
@@ -155,6 +155,13 @@ export interface ServerConfigSpec {
155
155
  * every turn and the signature does not move, so no extra server is spawned.
156
156
  */
157
157
  gitIdentityEnv?: Record<string, string>;
158
+ /**
159
+ * Project whose approved `.agents/mcp.json` servers join the MCP set. Folded
160
+ * in at assembly time (not in the per-scope cache), so it changes the process
161
+ * signature but not the data dir — a project without such a file resolves to
162
+ * the same server as before.
163
+ */
164
+ projectId?: string | null;
158
165
  }
159
166
 
160
167
  /** Everything needed to spawn a server, plus the key derived from it. */
@@ -643,10 +650,13 @@ async function resolveConfig(spec: ServerConfigSpec, scopeKey: string): Promise<
643
650
  function assembleConfigContent(
644
651
  cached: CachedConfig,
645
652
  enabledProviders: string[],
646
- inlineAgents?: Record<string, OpenCodeInlineAgent>
653
+ inlineAgents?: Record<string, OpenCodeInlineAgent>,
654
+ projectMcp: Record<string, unknown> = {}
647
655
  ): string {
648
656
  const mergedConfig: Record<string, unknown> = {};
649
- if (Object.keys(cached.mcpConfig).length > 0) mergedConfig.mcp = cached.mcpConfig;
657
+ // Project servers never shadow an installed server of the same namespace.
658
+ const mcp = { ...projectMcp, ...cached.mcpConfig };
659
+ if (Object.keys(mcp).length > 0) mergedConfig.mcp = mcp;
650
660
  if (enabledProviders.length > 0) mergedConfig.enabled_providers = enabledProviders;
651
661
  if (inlineAgents && Object.keys(inlineAgents).length > 0) mergedConfig.agent = inlineAgents;
652
662
  if (Object.keys(cached.providerSection).length > 0) mergedConfig.provider = cached.providerSection;
@@ -666,7 +676,7 @@ async function resolvePlan(spec: ServerConfigSpec): Promise<SpawnPlan> {
666
676
  // Cheap and DB-derived, so it is resolved per call rather than cached — the
667
677
  // models.dev catalog it reads lives in `settings`, which bumps no revision.
668
678
  const providerConfig = generateOpenCodeProviderConfig();
669
- const configContent = assembleConfigContent(config, providerConfig.enabledProviders, spec.inlineAgents);
679
+ const configContent = assembleConfigContent(config, providerConfig.enabledProviders, spec.inlineAgents, getOpenCodeProjectMcpConfig(spec.projectId));
670
680
  // Sorted so the key order the builder happens to emit is not mistaken for a
671
681
  // different identity.
672
682
  const gitIdentityEnv = spec.gitIdentityEnv ?? {};
@@ -45,6 +45,8 @@ import {
45
45
  import { ensureClient, acquireServer, releaseServer, getDefaultServer, type ServerInstance } from './server';
46
46
  import { syncSkills } from '$backend/skills';
47
47
  import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
48
+ import { resolveProjectBridge } from '$backend/artifacts/project';
49
+ import { resolveOsPath } from '$backend/utils/paths';
48
50
  import { artifactFilter } from '$backend/profiles';
49
51
  import { buildOpenCodeInlineAgents } from '$backend/subagents';
50
52
  import { getOpenCodeProfileDisabledToolIds } from '$backend/mcp';
@@ -221,7 +223,20 @@ export class OpenCodeEngine implements AIEngine {
221
223
  // server, different Profiles get isolated servers, concurrently.
222
224
  const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
223
225
  const subagentFilter = artifactFilter(profileId, 'subagent') ?? undefined;
224
- const inlineAgents = await buildOpenCodeInlineAgents(profileId);
226
+ // Repository artifacts Open Code doesn't read natively (it reads
227
+ // `.opencode/*`, `.agents/skills`, `.claude/skills` and AGENTS.md itself).
228
+ // Project subagents join the inline agents (an installed one wins a slug
229
+ // clash); the approved `.agents/mcp.json` joins MCP via `projectId`.
230
+ const projectBridge = await resolveProjectBridge('opencode', resolveOsPath(projectPath), options.mcpContext?.projectId);
231
+ const inlineAgents = {
232
+ ...Object.fromEntries(projectBridge.subagents.map(sub => [sub.slug, {
233
+ description: sub.description || sub.name,
234
+ mode: 'subagent' as const,
235
+ prompt: sub.prompt,
236
+ ...(sub.model ? { model: sub.model } : {})
237
+ }])),
238
+ ...(await buildOpenCodeInlineAgents(profileId))
239
+ };
225
240
  // The pool derives the key from the config it is about to spawn with, so a
226
241
  // changed connector set, provider, credential or subagent prompt routes this
227
242
  // stream to a server built from it — while any server still serving another
@@ -229,7 +244,7 @@ export class OpenCodeEngine implements AIEngine {
229
244
  // stream id is what makes that safe: a held server is never reaped.
230
245
  const holderId = options.mcpContext?.streamId;
231
246
  const server = await acquireServer(
232
- { mcpProfileFilter, subagentFilter, inlineAgents, gitIdentityEnv: options.gitIdentityEnv },
247
+ { mcpProfileFilter, subagentFilter, inlineAgents, gitIdentityEnv: options.gitIdentityEnv, projectId: options.mcpContext?.projectId ?? null },
233
248
  holderId
234
249
  );
235
250
  run.server = server;
@@ -253,7 +268,7 @@ export class OpenCodeEngine implements AIEngine {
253
268
  // so advertise the profile-scoped set PER-SESSION by prepending it as a
254
269
  // leading context part each turn (authoritative for synthetic skills;
255
270
  // advisory on top of the native command/agent dirs).
256
- const artifactsContext = buildArtifactsPromptContext('opencode', profileId);
271
+ const artifactsContext = buildArtifactsPromptContext('opencode', profileId, projectBridge);
257
272
  if (artifactsContext) {
258
273
  promptParts.unshift({ type: 'text', text: artifactsContext });
259
274
  }