@myrialabs/clopen 0.4.43 → 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 (72) 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 +26 -8
  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/message-converter.ts +6 -2
  15. package/backend/engine/adapters/claude/stream.ts +36 -8
  16. package/backend/engine/adapters/cline/mcp-tools.ts +26 -4
  17. package/backend/engine/adapters/cline/stream.ts +20 -6
  18. package/backend/engine/adapters/codex/stream.ts +21 -4
  19. package/backend/engine/adapters/copilot/stream.ts +6 -3
  20. package/backend/engine/adapters/cursor/stream.ts +19 -8
  21. package/backend/engine/adapters/opencode/server.ts +14 -4
  22. package/backend/engine/adapters/opencode/stream.ts +18 -3
  23. package/backend/engine/adapters/pi/mcp-tools.ts +26 -4
  24. package/backend/engine/adapters/pi/stream.ts +35 -3
  25. package/backend/engine/adapters/qwen/message-converter.ts +2 -2
  26. package/backend/engine/adapters/qwen/stream.ts +8 -0
  27. package/backend/engine/artifact-sync.ts +12 -5
  28. package/backend/engine/docs/lessons-learned.md +118 -0
  29. package/backend/files/file-watcher.test.ts +77 -0
  30. package/backend/files/file-watcher.ts +92 -60
  31. package/backend/files/watch-ignore.test.ts +182 -0
  32. package/backend/files/watch-ignore.ts +244 -0
  33. package/backend/git/git-executor.ts +14 -4
  34. package/backend/index.ts +11 -1
  35. package/backend/instructions/service.ts +5 -3
  36. package/backend/instructions/sync.ts +10 -27
  37. package/backend/mcp/external/config.ts +65 -23
  38. package/backend/mcp/external/project.ts +124 -0
  39. package/backend/mcp/external/proxy.ts +65 -11
  40. package/backend/mcp/index.ts +14 -9
  41. package/backend/mcp/internal/remote-server.ts +11 -1
  42. package/backend/skills/marketplace.ts +1 -1
  43. package/backend/snapshot/blob-store.ts +9 -5
  44. package/backend/snapshot/git-attribution.test.ts +42 -0
  45. package/backend/snapshot/git-attribution.ts +306 -0
  46. package/backend/snapshot/gitignore.test.ts +62 -0
  47. package/backend/snapshot/gitignore.ts +158 -78
  48. package/backend/snapshot/snapshot-service.test.ts +270 -0
  49. package/backend/snapshot/snapshot-service.ts +412 -136
  50. package/backend/snapshot/turn-activity.test.ts +52 -0
  51. package/backend/snapshot/turn-activity.ts +83 -0
  52. package/backend/snapshot/turn-changes.test.ts +58 -1
  53. package/backend/snapshot/turn-changes.ts +66 -0
  54. package/backend/worktrees/tree.ts +1 -1
  55. package/backend/ws/chat/composer.ts +504 -0
  56. package/backend/ws/chat/index.ts +3 -1
  57. package/backend/ws/chat/stream.ts +252 -440
  58. package/backend/ws/index.ts +4 -0
  59. package/backend/ws/project-artifacts/index.ts +236 -0
  60. package/backend/ws/snapshot/changes.ts +66 -31
  61. package/dist/assets/{index-BeUKiRiY.js → index-Am-rJRxA.js} +1 -1
  62. package/dist/assets/{index-B6u8cait.js → index-D-Ad1N96.js} +1 -1
  63. package/dist/assets/main--PLCDxSy.css +1 -0
  64. package/dist/assets/main-DelPm2Xt.js +1239 -0
  65. package/dist/index.html +2 -2
  66. package/package.json +5 -5
  67. package/shared/types/stores/settings.ts +5 -0
  68. package/shared/types/unified/index.ts +2 -0
  69. package/shared/types/unified/message.ts +2 -0
  70. package/shared/types/unified/stream.ts +38 -1
  71. package/dist/assets/main-CMRXlv2f.js +0 -1215
  72. 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',
@@ -23,6 +23,7 @@ import type {
23
23
  SuccessResultEvent,
24
24
  ErrorResultEvent,
25
25
  SystemInitEvent,
26
+ McpServerStatus,
26
27
  RateLimitEvent,
27
28
  RateLimitType,
28
29
  NotificationEvent,
@@ -556,12 +557,15 @@ class StreamManager extends EventEmitter {
556
557
  // engine initialization. It MUST finish before the engine can write any files
557
558
  // (awaited just before streamQuery below) — otherwise early writes would be
558
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.
559
562
  let baselineInitPromise: Promise<void> | null = null;
560
- if (requestData.projectPath && requestData.chatSessionId) {
561
- baselineInitPromise = snapshotService.initializeSessionBaseline(
563
+ if (requestData.projectPath && requestData.projectId && requestData.chatSessionId) {
564
+ baselineInitPromise = snapshotService.beginTurn(
562
565
  requestData.projectPath,
566
+ requestData.projectId,
563
567
  requestData.chatSessionId
564
- ).catch(err => debug.error('snapshot', 'Failed to initialize session baseline:', err));
568
+ ).catch(err => debug.error('snapshot', 'Failed to begin snapshot turn:', err));
565
569
  }
566
570
 
567
571
  try {
@@ -906,6 +910,12 @@ class StreamManager extends EventEmitter {
906
910
  break;
907
911
  }
908
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
+
909
919
  // ── Route by type discriminant ──────────────────────────────
910
920
 
911
921
  // Extract session ID from first event that has one
@@ -928,14 +938,14 @@ class StreamManager extends EventEmitter {
928
938
  // Suppress the toast for "soft" statuses: `pending` (still
929
939
  // connecting) and `needs-auth` (server expects OAuth/credentials
930
940
  // configured in Settings → MCP). These are not errors — a scary
931
- // toast for them is confusing. (Status is the raw SDK string,
932
- // wider than the EngineOutput union, hence the cast.)
933
- const SOFT_STATUSES = new Set(['pending', 'needs-auth']);
941
+ // toast for them is confusing. `pending` is the common case since
942
+ // claude-agent-sdk 0.3.282 connects MCP servers in the background.
943
+ const SOFT_STATUSES = new Set<McpServerStatus['status']>(['pending', 'needs-auth']);
934
944
  const failedServers = initEvent.mcpServers.filter(
935
- s => s.status !== 'connected' && !SOFT_STATUSES.has(s.status as string)
945
+ s => s.status !== 'connected' && !SOFT_STATUSES.has(s.status)
936
946
  );
937
947
  initEvent.mcpServers
938
- .filter(s => SOFT_STATUSES.has(s.status as string))
948
+ .filter(s => SOFT_STATUSES.has(s.status))
939
949
  .forEach(s => debug.log('mcp', `MCP server "${s.name}" not ready (${s.status}) — suppressing toast`));
940
950
  failedServers.forEach(server => {
941
951
  debug.warn('mcp', `MCP server connection failed: ${server.name} (${server.status})`);
@@ -1397,6 +1407,10 @@ class StreamManager extends EventEmitter {
1397
1407
  deletedPaths: delta?.deleted ?? []
1398
1408
  });
1399
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);
1400
1414
  }
1401
1415
  }
1402
1416
  }
@@ -1945,6 +1959,10 @@ class StreamManager extends EventEmitter {
1945
1959
  * Used when a session is deleted to remove green/amber status indicators.
1946
1960
  */
1947
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
+
1948
1966
  const streamsToCancel: string[] = [];
1949
1967
  const streamsToClean: string[] = [];
1950
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
+ };
@@ -44,7 +44,7 @@ import type {
44
44
  TokenUsage,
45
45
  StopReason,
46
46
  } from '$shared/types/unified';
47
- import { toCanonicalToolName } from '$shared/types/unified';
47
+ import { toCanonicalToolName, toMcpServerStatus } from '$shared/types/unified';
48
48
 
49
49
  // ============================================================
50
50
  // Helper Mappers
@@ -390,9 +390,13 @@ export function convertSystemInit(msg: SDKSystemMessage): SystemInitEvent {
390
390
  model: msg.model || '',
391
391
  engine: 'claude-code',
392
392
  tools: msg.tools || [],
393
+ // `mcp_servers[].status` is a bare `string` on this payload, so it is
394
+ // narrowed, not cast: the cast this used to do named three states the CLI
395
+ // never emits and erased `pending`/`needs-auth`, the two that decide
396
+ // whether stream-manager raises a toast.
393
397
  mcpServers: (msg.mcp_servers || []).map(s => ({
394
398
  name: s.name || '',
395
- status: (s.status as 'connected' | 'disconnected' | 'error') || 'disconnected',
399
+ status: toMcpServerStatus(s.status),
396
400
  })),
397
401
  };
398
402
  }
@@ -4,13 +4,15 @@
4
4
  * Wraps the @anthropic-ai/claude-agent-sdk into the AIEngine interface.
5
5
  * SDK messages are converted to EngineOutput by ./message-converter.ts.
6
6
  *
7
- * Currently uses v1 query() API because v2 (unstable_v2_createSession) is
8
- * @alpha and lacks critical options required by Clopen:
9
- * - cwd (multi-project working directory)
10
- * - mcpServers, systemPrompt, settingSources
11
- * - forkSession, maxTurns, abortController, includePartialMessages
12
- * - outputFormat (needed by generateStructured)
13
- * When v2 SDKSessionOptions gains these, migrate streamQuery() to v2.
7
+ * query() is the only session entry point. The alternative this comment used to
8
+ * weigh — the @alpha v2 API (unstable_v2_createSession / unstable_v2_prompt) —
9
+ * was removed upstream in 0.3.142, before the version Clopen pins, so there is
10
+ * no migration pending. prewarm() (0.3.284, @alpha) parks a spare process to
11
+ * take start-up cost off the first message, but everything Clopen varies per
12
+ * stream is frozen at prewarm time — mcpServers (whose tool handlers are bound
13
+ * to the project), hooks, canUseTool, env (git identity) — so a spare is only
14
+ * reusable within one (project × profile × account × identity) and holds
15
+ * 230-260 MB while parked. Not adopted; see docs/lessons-learned.md §10.25.
14
16
  */
15
17
 
16
18
  import { loadEngineSdk } from '$backend/engine/sdk-loader';
@@ -34,6 +36,7 @@ import { emptyGenerationError } from '../../structured-helpers';
34
36
  import { getEnabledMcpServers, getAllowedMcpTools } from '../../../mcp';
35
37
  import { syncSkills } from '$backend/skills';
36
38
  import { syncEngineArtifacts } from '$backend/engine/artifact-sync';
39
+ import { resolveProjectBridge, ensureClaudeProjectPlugin, buildProjectPromptContext } from '$backend/artifacts/project';
37
40
  import { artifactFilter } from '$backend/profiles';
38
41
  import { resolvePermissionsFromDb, isToolAllowed, hasAnyRestriction, syncPermissions } from '$backend/permissions';
39
42
  import type { AIEngine, EngineQueryOptions } from '../../types';
@@ -179,6 +182,25 @@ export class ClaudeCodeEngine implements AIEngine {
179
182
  // equivalent — the PreToolUse hook below is the authoritative enforcement.
180
183
  await syncPermissions('claude');
181
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
+
182
204
  // Resolve the effective permission policy once per stream. Enforcement
183
205
  // lives in the PreToolUse hook, NOT in canUseTool: under
184
206
  // permissionMode 'bypassPermissions' the CLI auto-approves a tool call
@@ -227,8 +249,14 @@ export class ClaudeCodeEngine implements AIEngine {
227
249
  allowDangerouslySkipPermissions: true,
228
250
  cwd: resolvedProjectPath,
229
251
  env: getEngineEnv(accountId, options.gitIdentityEnv),
230
- systemPrompt: { type: "preset", preset: "claude_code" },
252
+ systemPrompt: projectInstructions
253
+ ? { type: "preset", preset: "claude_code", append: projectInstructions }
254
+ : { type: "preset", preset: "claude_code" },
231
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 }),
232
260
  forkSession: true,
233
261
  // Reasoning level → thinking/effort (see thinkingConfig above). Adaptive
234
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 ?? {};