@myrialabs/clopen 0.4.44 → 0.4.46

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 (118) 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/models.test.ts +49 -0
  15. package/backend/engine/adapters/claude/models.ts +81 -562
  16. package/backend/engine/adapters/claude/stream.ts +32 -5
  17. package/backend/engine/adapters/cline/credential.ts +42 -18
  18. package/backend/engine/adapters/cline/mcp-tools.ts +26 -4
  19. package/backend/engine/adapters/cline/message-converter.ts +31 -1
  20. package/backend/engine/adapters/cline/models.test.ts +77 -0
  21. package/backend/engine/adapters/cline/models.ts +89 -3
  22. package/backend/engine/adapters/cline/presets.ts +5 -0
  23. package/backend/engine/adapters/cline/stream.ts +29 -8
  24. package/backend/engine/adapters/codex/message-converter.ts +1 -1
  25. package/backend/engine/adapters/codex/models.ts +54 -31
  26. package/backend/engine/adapters/codex/patch-rollout.test.ts +36 -1
  27. package/backend/engine/adapters/codex/patch-rollout.ts +60 -29
  28. package/backend/engine/adapters/codex/session-fork.ts +5 -0
  29. package/backend/engine/adapters/codex/stream.ts +29 -11
  30. package/backend/engine/adapters/copilot/models.test.ts +40 -0
  31. package/backend/engine/adapters/copilot/models.ts +51 -24
  32. package/backend/engine/adapters/copilot/permissions.test.ts +47 -0
  33. package/backend/engine/adapters/copilot/permissions.ts +72 -0
  34. package/backend/engine/adapters/copilot/stream.ts +83 -70
  35. package/backend/engine/adapters/cursor/stream.ts +27 -12
  36. package/backend/engine/adapters/opencode/server.ts +14 -4
  37. package/backend/engine/adapters/opencode/stream.ts +18 -3
  38. package/backend/engine/adapters/pi/credential.test.ts +83 -0
  39. package/backend/engine/adapters/pi/credential.ts +68 -12
  40. package/backend/engine/adapters/pi/environment.ts +9 -5
  41. package/backend/engine/adapters/pi/mcp.test.ts +194 -0
  42. package/backend/engine/adapters/pi/mcp.ts +88 -0
  43. package/backend/engine/adapters/pi/message-converter.ts +6 -4
  44. package/backend/engine/adapters/pi/presets.ts +10 -5
  45. package/backend/engine/adapters/pi/stream.ts +77 -41
  46. package/backend/engine/adapters/qwen/environment.ts +39 -2
  47. package/backend/engine/adapters/qwen/message-converter.test.ts +64 -0
  48. package/backend/engine/adapters/qwen/message-converter.ts +40 -23
  49. package/backend/engine/adapters/qwen/models.test.ts +25 -0
  50. package/backend/engine/adapters/qwen/models.ts +42 -5
  51. package/backend/engine/adapters/qwen/session-store.test.ts +39 -0
  52. package/backend/engine/adapters/qwen/session-store.ts +66 -0
  53. package/backend/engine/adapters/qwen/stream.ts +118 -87
  54. package/backend/engine/artifact-sync.ts +12 -5
  55. package/backend/engine/docs/adapter-contract.md +7 -4
  56. package/backend/engine/docs/lessons-learned.md +405 -62
  57. package/backend/engine/docs/quick-reference.md +2 -2
  58. package/backend/engine/docs/stack.md +17 -4
  59. package/backend/engine/docs/websocket-routes.md +5 -5
  60. package/backend/engine/install-recipes.test.ts +105 -5
  61. package/backend/engine/install-recipes.ts +102 -42
  62. package/backend/engine/install-runner.ts +56 -2
  63. package/backend/engine/stack-project.ts +71 -1
  64. package/backend/files/file-watcher.test.ts +77 -0
  65. package/backend/files/file-watcher.ts +92 -60
  66. package/backend/files/watch-ignore.test.ts +182 -0
  67. package/backend/files/watch-ignore.ts +244 -0
  68. package/backend/git/git-executor.ts +14 -4
  69. package/backend/index.ts +16 -1
  70. package/backend/instructions/service.ts +5 -3
  71. package/backend/instructions/sync.ts +10 -27
  72. package/backend/mcp/README.md +2 -2
  73. package/backend/mcp/external/config.ts +83 -23
  74. package/backend/mcp/external/project.ts +124 -0
  75. package/backend/mcp/external/proxy.ts +65 -11
  76. package/backend/mcp/index.ts +22 -9
  77. package/backend/mcp/internal/config.ts +42 -3
  78. package/backend/mcp/internal/remote-server.ts +11 -1
  79. package/backend/memory/embedding/install.ts +29 -1
  80. package/backend/skills/marketplace.ts +1 -1
  81. package/backend/snapshot/blob-store.ts +9 -5
  82. package/backend/snapshot/git-attribution.test.ts +42 -0
  83. package/backend/snapshot/git-attribution.ts +306 -0
  84. package/backend/snapshot/gitignore.test.ts +62 -0
  85. package/backend/snapshot/gitignore.ts +158 -78
  86. package/backend/snapshot/snapshot-service.test.ts +270 -0
  87. package/backend/snapshot/snapshot-service.ts +412 -136
  88. package/backend/snapshot/turn-activity.test.ts +52 -0
  89. package/backend/snapshot/turn-activity.ts +83 -0
  90. package/backend/snapshot/turn-changes.test.ts +58 -1
  91. package/backend/snapshot/turn-changes.ts +66 -0
  92. package/backend/utils/keyed-lock.test.ts +33 -0
  93. package/backend/utils/keyed-lock.ts +17 -0
  94. package/backend/utils/port-utils.test.ts +29 -0
  95. package/backend/utils/port-utils.ts +19 -0
  96. package/backend/worktrees/tree.ts +1 -1
  97. package/backend/ws/chat/composer.ts +504 -0
  98. package/backend/ws/chat/index.ts +3 -1
  99. package/backend/ws/chat/stream.ts +252 -440
  100. package/backend/ws/engine/cline/accounts.ts +26 -6
  101. package/backend/ws/engine/codex/accounts.test.ts +49 -0
  102. package/backend/ws/engine/codex/accounts.ts +17 -13
  103. package/backend/ws/engine/pi/accounts.ts +61 -6
  104. package/backend/ws/index.ts +4 -0
  105. package/backend/ws/project-artifacts/index.ts +236 -0
  106. package/backend/ws/snapshot/changes.ts +66 -31
  107. package/dist/assets/{index-DX5OwLOc.js → index-BTcR1byF.js} +1 -1
  108. package/dist/assets/{index-BWyhqUi5.js → index-CwuKQelV.js} +1 -1
  109. package/dist/assets/main-BiDNMWb3.css +1 -0
  110. package/dist/assets/main-BlhKWz2B.js +1241 -0
  111. package/dist/index.html +2 -2
  112. package/package.json +19 -15
  113. package/shared/types/stores/settings.ts +5 -0
  114. package/shared/types/unified/message.ts +2 -0
  115. package/backend/engine/adapters/pi/mcp-tools.ts +0 -131
  116. package/backend/engine/adapters/qwen/session-fork.ts +0 -109
  117. package/dist/assets/main-DOkwqXRU.js +0 -1215
  118. package/dist/assets/main-DzCY0n-j.css +0 -1
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Project MCP — servers a repository declares in `.agents/mcp.json`.
3
+ *
4
+ * They ride the same proxy as installed servers (Clopen is the upstream client,
5
+ * engines only ever see a loopback bridge URL), on a project-addressed route:
6
+ * `/mcp/proj/<projectId>/<name>`. Two things differ from installed servers:
7
+ *
8
+ * - TRUST. The file lives in the repo, so anyone who can push to it could make
9
+ * the server run a command. A server is emitted — and the bridge will only
10
+ * connect it — while the file's current sha256 matches the hash an admin
11
+ * approved (`project_mcp_trust`). Any edit makes it inert until re-approved.
12
+ * The check runs at config-build time AND again when the bridge connects, so
13
+ * a file swapped between the two is still refused.
14
+ * - PLACE. stdio servers start with the repository as their working
15
+ * directory, which is what a repo-relative `command`/`args` expects.
16
+ *
17
+ * Namespace: `project-<name>`, so tools surface as `mcp__project-<name>__<tool>`
18
+ * and never collide with an installed server of the same name.
19
+ */
20
+
21
+ import { readFileSync, statSync } from 'node:fs';
22
+ import { join } from 'path';
23
+ import { projectQueries, projectMcpTrustQueries } from '$backend/database/queries';
24
+ import { parseProjectMcpJson, hashContent } from '$backend/artifacts/project/scan';
25
+ import { PROJECT_WRITE_PATHS } from '$backend/artifacts/project/sources';
26
+ import { slugify } from '$backend/artifacts/slug';
27
+ import { debug } from '$shared/utils/logger';
28
+ import type { ResolvedExternalServer } from './types';
29
+
30
+ export interface ResolvedProjectServer extends ResolvedExternalServer {
31
+ projectId: string;
32
+ /** Repository root — the working directory for stdio servers. */
33
+ cwd: string;
34
+ }
35
+
36
+ /** Largest `.agents/mcp.json` Clopen will read. */
37
+ const MAX_BYTES = 256 * 1024;
38
+
39
+ /**
40
+ * Namespaces of project servers emitted so far. Engines report MCP tools under
41
+ * `<namespace><sep><tool>` with an SDK-specific separator, and the resolver has
42
+ * no project context — so it matches against the namespaces actually handed out.
43
+ */
44
+ const knownNamespaces = new Set<string>();
45
+
46
+ export function projectNamespace(name: string): string {
47
+ return `project-${slugify(name)}`;
48
+ }
49
+
50
+ export function knownProjectNamespaces(): string[] {
51
+ return [...knownNamespaces];
52
+ }
53
+
54
+ /** Expand `${VAR}` / `${VAR:-default}` from the server's environment, as `.mcp.json` does. */
55
+ function expand(value: string): string {
56
+ return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g, (_m, name: string, fallback?: string) =>
57
+ process.env[name] ?? fallback ?? ''
58
+ );
59
+ }
60
+
61
+ function expandRecord(record: Record<string, string>): Record<string, string> {
62
+ return Object.fromEntries(Object.entries(record).map(([k, v]) => [k, expand(v)]));
63
+ }
64
+
65
+ /** The raw file for a project, or null when absent/oversized. */
66
+ export function readProjectMcpFile(projectPath: string): string | null {
67
+ const file = join(projectPath, PROJECT_WRITE_PATHS.mcp);
68
+ try {
69
+ const info = statSync(file);
70
+ if (!info.isFile() || info.size > MAX_BYTES) return null;
71
+ return readFileSync(file, 'utf8');
72
+ } catch {
73
+ return null;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Every server in the project's `.agents/mcp.json`, but only while the file is
79
+ * the approved version. Synchronous on purpose: the per-engine MCP builders it
80
+ * feeds are synchronous, and the file is small.
81
+ */
82
+ export function getTrustedProjectServers(projectId: string | null | undefined): ResolvedProjectServer[] {
83
+ if (!projectId) return [];
84
+ const project = projectQueries.getById(projectId);
85
+ if (!project?.path) return [];
86
+ const raw = readProjectMcpFile(project.path);
87
+ if (raw == null) return [];
88
+ if (!projectMcpTrustQueries.isTrusted(projectId, hashContent(raw))) {
89
+ debug.log('mcp', `🔒 Project ${projectId}: .agents/mcp.json is not approved (or changed since) — not loading it`);
90
+ return [];
91
+ }
92
+ let parsed;
93
+ try {
94
+ parsed = parseProjectMcpJson(raw);
95
+ } catch (error) {
96
+ debug.warn('mcp', `Project ${projectId}: .agents/mcp.json is invalid:`, error);
97
+ return [];
98
+ }
99
+ return parsed.map(s => {
100
+ const namespace = projectNamespace(s.name);
101
+ knownNamespaces.add(namespace);
102
+ return {
103
+ id: 0,
104
+ slug: s.name,
105
+ namespace,
106
+ name: s.name,
107
+ transport: s.transport,
108
+ command: s.command ? expand(s.command) : null,
109
+ args: s.args.map(expand),
110
+ env: expandRecord(s.env),
111
+ url: s.url ? expand(s.url) : null,
112
+ headers: expandRecord(s.headers),
113
+ projectId,
114
+ cwd: project.path
115
+ };
116
+ });
117
+ }
118
+
119
+ /** One trusted project server by name, or a readable error. */
120
+ export function requireTrustedProjectServer(projectId: string, name: string): ResolvedProjectServer {
121
+ const server = getTrustedProjectServers(projectId).find(s => s.name === name);
122
+ if (!server) throw new Error(`Project MCP server "${name}" is not declared in an approved .agents/mcp.json`);
123
+ return server;
124
+ }
@@ -40,6 +40,7 @@ import { debug } from '$shared/utils/logger';
40
40
  import { mcpServerQueries, permissionSetQueries, profileQueries } from '$backend/database/queries';
41
41
  import type { EngineType } from '$shared/types/unified';
42
42
  import { resolveServerRow } from './config';
43
+ import { requireTrustedProjectServer, type ResolvedProjectServer } from './project';
43
44
  import { parseToolOverrides, isToolExposed } from './tools';
44
45
  // Import the PURE resolver (no `$backend/mcp` dependency) to avoid an
45
46
  // mcp → permissions/service → mcp import cycle.
@@ -54,7 +55,7 @@ const UPSTREAM_CONNECT_TIMEOUT_MS = 30_000;
54
55
  * subprocess or remote HTTP/SSE). OAuth/API-key headers come from
55
56
  * `resolveServerRow`, which injects the Clopen-managed bearer.
56
57
  */
57
- async function connectUpstream(s: ResolvedExternalServer): Promise<Client> {
58
+ async function connectUpstream(s: ResolvedExternalServer & { cwd?: string }): Promise<Client> {
58
59
  const client = new Client({ name: 'clopen-proxy', version: '1.0.0' }, { capabilities: {} });
59
60
 
60
61
  if (s.transport === 'stdio') {
@@ -65,6 +66,8 @@ async function connectUpstream(s: ResolvedExternalServer): Promise<Client> {
65
66
  command: s.command,
66
67
  args: s.args,
67
68
  env: { ...getDefaultEnvironment(), ...s.env },
69
+ // Project servers (`.agents/mcp.json`) start inside their repository.
70
+ ...(s.cwd ? { cwd: s.cwd } : {}),
68
71
  stderr: 'ignore'
69
72
  });
70
73
  await client.connect(transport, { timeout: UPSTREAM_CONNECT_TIMEOUT_MS });
@@ -185,20 +188,46 @@ export async function createExternalProxyServer(slug: string, engine?: EngineTyp
185
188
  throw new Error(`External MCP server is disabled: ${slug}`);
186
189
  }
187
190
 
188
- const resolved = resolveServerRow(row);
189
- const overrides = parseToolOverrides(row.tool_overrides);
190
- const client = await connectUpstream(resolved);
191
-
192
- // Global tool-permission policy for this engine (Settings → Permissions).
193
- // MCP tools carry no permission hook on some engines (e.g. OpenCode only gates
191
+ // Global tool-permission policy for this engine (Settings → Permissions). MCP
192
+ // tools carry no permission hook on some engines (e.g. OpenCode only gates
194
193
  // edit/bash/webfetch), so the bridge is the single reliable enforcement point
195
- // for MCP deny/allow across every engine — it filters the tool out before the
196
- // engine ever sees it. Rules are matched against the canonical engine-facing
197
- // name `mcp__<namespace>__<tool>` (the identity the Permissions UI uses).
198
- // Global scope only: the bridge has no session/project context.
194
+ // for MCP deny/allow across every engine. Global scope only: this bridge has
195
+ // no session/project context.
199
196
  const permissions = engine
200
197
  ? mergePermissions(pickEngineSet(permissionSetQueries.getGlobal(), engine), undefined)
201
198
  : null;
199
+ return buildProxyServer(resolveServerRow(row), parseToolOverrides(row.tool_overrides), engine, permissions);
200
+ }
201
+
202
+ /**
203
+ * Proxy for one server of a project's approved `.agents/mcp.json` — the
204
+ * `/mcp/proj/<projectId>/<name>` bridge. Trust is re-checked here, at connect
205
+ * time: a file edited after the engine received its config is refused rather
206
+ * than run. Project-scoped permission rules apply on top of the global ones,
207
+ * because unlike the installed-server bridge this one knows its project.
208
+ */
209
+ export async function createProjectProxyServer(projectId: string, name: string, engine?: EngineType): Promise<ExternalProxy> {
210
+ const resolved = requireTrustedProjectServer(projectId, name);
211
+ const permissions = engine
212
+ ? mergePermissions(
213
+ pickEngineSet(permissionSetQueries.getGlobal(), engine),
214
+ pickEngineSet(permissionSetQueries.getForProject(projectId), engine)
215
+ )
216
+ : null;
217
+ return buildProxyServer(resolved, {}, engine, permissions);
218
+ }
219
+
220
+ async function buildProxyServer(
221
+ resolved: ResolvedExternalServer | ResolvedProjectServer,
222
+ overrides: ReturnType<typeof parseToolOverrides>,
223
+ engine: EngineType | undefined,
224
+ permissions: ReturnType<typeof mergePermissions> | null
225
+ ): Promise<ExternalProxy> {
226
+ const slug = resolved.slug;
227
+ const client = await connectUpstream(resolved);
228
+
229
+ // Rules match the canonical engine-facing name `mcp__<namespace>__<tool>`
230
+ // (the identity the Permissions UI uses).
202
231
  const permitted = (toolName: string): boolean =>
203
232
  !permissions || isToolAllowed(permissions, `mcp__${resolved.namespace}__${toolName}`);
204
233
 
@@ -266,6 +295,31 @@ async function withUpstreamClient<T>(slug: string, fn: (client: Client) => Promi
266
295
  }
267
296
  }
268
297
 
298
+ /** Same as {@link withUpstreamClient} for a project server (trust-checked). */
299
+ async function withProjectUpstreamClient<T>(projectId: string, name: string, fn: (client: Client) => Promise<T>): Promise<T> {
300
+ const client = await connectUpstream(requireTrustedProjectServer(projectId, name));
301
+ try {
302
+ return await fn(client);
303
+ } finally {
304
+ client.close().catch(error => debug.warn('mcp', `Project MCP ${name}: error closing client:`, error));
305
+ }
306
+ }
307
+
308
+ /** Sanitized tools of a trusted project server — for the in-process engine (Cline). */
309
+ export async function listProjectServerTools(projectId: string, name: string): Promise<Tool[]> {
310
+ return withProjectUpstreamClient(projectId, name, async (client) => (await listAllToolsRaw(client)).map(sanitizeTool));
311
+ }
312
+
313
+ /** Call one tool of a trusted project server — for the in-process engine (Cline). */
314
+ export async function callProjectServerTool(projectId: string, name: string, toolName: string, args: unknown): Promise<unknown> {
315
+ return withProjectUpstreamClient(projectId, name, async (client) =>
316
+ client.request(
317
+ { method: 'tools/call', params: { name: toolName, arguments: (args ?? {}) as Record<string, unknown> } },
318
+ CompatibilityCallToolResultSchema
319
+ )
320
+ );
321
+ }
322
+
269
323
  /** List a server's sanitized tools live (unfiltered) — for the Settings tool panel. */
270
324
  export async function listExternalServerTools(slug: string): Promise<Tool[]> {
271
325
  return withUpstreamClient(slug, async (client) => (await listAllToolsRaw(client)).map(sanitizeTool));
@@ -59,7 +59,7 @@ export {
59
59
  export * from './internal/servers';
60
60
 
61
61
  // Remote MCP HTTP bridge (serves internal tools + external proxies to non-Claude engines)
62
- export { handleMcpRequest, handleExternalMcpRequest, closeMcpServer } from './internal/remote-server';
62
+ export { handleMcpRequest, handleExternalMcpRequest, handleProjectMcpRequest, closeMcpServer } from './internal/remote-server';
63
63
 
64
64
  // Project context service for MCP tool handlers
65
65
  export { projectContextService } from './internal/project-context';
@@ -75,8 +75,10 @@ export {
75
75
 
76
76
  // External catalog + types (used by the WS layer and Settings → MCP)
77
77
  export { listRegistryServers, mapRegistryServer } from './external/registry-client';
78
- export { getEnabledExternalServers, resolveServerRow, remoteNeedsOAuth, getEngineConfigsForServer } from './external/config';
79
- export { listExternalServerTools, callExternalServerTool } from './external/proxy';
78
+ export { getEnabledExternalServers, resolveServerRow, remoteNeedsOAuth, getEngineConfigsForServer, getOpenCodeProjectMcpConfig } from './external/config';
79
+ export { listExternalServerTools, callExternalServerTool, listProjectServerTools, callProjectServerTool } from './external/proxy';
80
+ export { getTrustedProjectServers, projectNamespace, readProjectMcpFile } from './external/project';
81
+ export type { ResolvedProjectServer } from './external/project';
80
82
  export { parseToolOverrides, resolveToolExposure, pruneToolOverrides, MCP_ENGINES } from './external/tools';
81
83
  export type { ToolExposure } from './external/tools';
82
84
  export { probeServer } from './external/probe';
@@ -108,11 +110,14 @@ export type { ParsedMcpServer, ParsedField, ParseResult } from './external/parse
108
110
  export async function getEnabledMcpServers(context?: McpExecutionContext, profileFilter?: Set<string>): Promise<Record<string, McpServerConfig>> {
109
111
  return {
110
112
  ...(await internal.getEnabledMcpServers(context, profileFilter)),
111
- ...external.getClaudeExternalMcpConfig(profileFilter)
113
+ ...external.getClaudeExternalMcpConfig(profileFilter, context?.projectId)
112
114
  };
113
115
  }
114
116
 
115
- /** Open Code MCP config: internal `clopen-mcp` remote bridge + external servers. */
117
+ /**
118
+ * Open Code MCP config: internal `clopen-mcp` remote bridge + external servers.
119
+ * Project servers are NOT included — see {@link getOpenCodeProjectMcpConfig}.
120
+ */
116
121
  export function getOpenCodeMcpConfig(profileFilter?: Set<string>) {
117
122
  return {
118
123
  ...internal.getOpenCodeMcpConfig(profileFilter),
@@ -124,7 +129,7 @@ export function getOpenCodeMcpConfig(profileFilter?: Set<string>) {
124
129
  export function getCodexMcpConfig(profileFilter?: Set<string>, context?: McpExecutionContext) {
125
130
  return {
126
131
  ...internal.getCodexMcpConfig(profileFilter, context),
127
- ...external.getCodexExternalMcpConfig(profileFilter)
132
+ ...external.getCodexExternalMcpConfig(profileFilter, context?.projectId)
128
133
  };
129
134
  }
130
135
 
@@ -132,7 +137,7 @@ export function getCodexMcpConfig(profileFilter?: Set<string>, context?: McpExec
132
137
  export function getCopilotMcpConfig(profileFilter?: Set<string>, context?: McpExecutionContext) {
133
138
  return {
134
139
  ...internal.getCopilotMcpConfig(profileFilter, context),
135
- ...external.getCopilotExternalMcpConfig(profileFilter)
140
+ ...external.getCopilotExternalMcpConfig(profileFilter, context?.projectId)
136
141
  };
137
142
  }
138
143
 
@@ -140,7 +145,15 @@ export function getCopilotMcpConfig(profileFilter?: Set<string>, context?: McpEx
140
145
  export function getCursorMcpConfig(profileFilter?: Set<string>, context?: McpExecutionContext) {
141
146
  return {
142
147
  ...internal.getCursorMcpConfig(profileFilter, context),
143
- ...external.getCursorExternalMcpConfig(profileFilter)
148
+ ...external.getCursorExternalMcpConfig(profileFilter, context?.projectId)
149
+ };
150
+ }
151
+
152
+ /** Pi MCP config: internal `clopen-mcp` remote bridge + external servers. */
153
+ export function getPiMcpConfig(profileFilter?: Set<string>, context?: McpExecutionContext) {
154
+ return {
155
+ ...internal.getPiMcpConfig(profileFilter, context),
156
+ ...external.getPiExternalMcpConfig(profileFilter, context?.projectId)
144
157
  };
145
158
  }
146
159
 
@@ -148,7 +161,7 @@ export function getCursorMcpConfig(profileFilter?: Set<string>, context?: McpExe
148
161
  export function getQwenMcpConfig(profileFilter?: Set<string>, context?: McpExecutionContext) {
149
162
  return {
150
163
  ...internal.getQwenMcpConfig(profileFilter, context),
151
- ...external.getQwenExternalMcpConfig(profileFilter)
164
+ ...external.getQwenExternalMcpConfig(profileFilter, context?.projectId)
152
165
  };
153
166
  }
154
167
 
@@ -10,6 +10,7 @@ import type { McpRemoteConfig } from '@opencode-ai/sdk';
10
10
  import type { MCPHTTPServerConfig } from '@github/copilot-sdk';
11
11
  import type { CLIMcpServerConfig as QwenMcpServerConfig } from '@qwen-code/sdk';
12
12
  import type { McpServerConfig as CursorMcpServerConfig } from '@cursor/sdk';
13
+ import type { McpServerConfig as PiMcpServerConfig } from '@earendil-works/pi-coding-agent';
13
14
  import type { ServerConfig, ParsedMcpToolName, ServerName } from './types';
14
15
  import type { McpExecutionContext } from '../../engine/types';
15
16
  import type { EngineType } from '$shared/types/unified';
@@ -442,7 +443,7 @@ export function resolveOpenCodeToolName(toolName: string): string | null {
442
443
  /**
443
444
  * Loopback URL of the internal `clopen-mcp` bridge, addressed to the caller.
444
445
  *
445
- * The in-process engines (Claude, Pi, Cline) bind `McpExecutionContext` around
446
+ * The in-process engines (Claude, Cline) bind `McpExecutionContext` around
446
447
  * every tool handler, so a tool call always knows which project asked. The
447
448
  * engines that reach the bridge over HTTP had no such thing: the request
448
449
  * carries no identity, so the handler fell back to "the most recently started
@@ -453,8 +454,8 @@ export function resolveOpenCodeToolName(toolName: string): string | null {
453
454
  * The query string closes that. Each config says as much as its own lifetime
454
455
  * allows, and the bridge binds whatever it is told:
455
456
  *
456
- * - `project` + `session` — the caller named outright. Copilot, Cursor and Qwen
457
- * build their config per stream, so both are true for the whole MCP session.
457
+ * - `project` + `session` — the caller named outright. Copilot, Cursor, Pi and
458
+ * Qwen build their config per stream, so both are true for the whole MCP session.
458
459
  * - `project` alone — Codex, whose client (and therefore this URL) is built
459
460
  * once per project and reused by every chat session in it.
460
461
  * - `engine` alone — Open Code, whose URL is baked into a server the pool shares
@@ -664,6 +665,44 @@ export function getCursorMcpConfig(
664
665
  };
665
666
  }
666
667
 
668
+ // ============================================================================
669
+ // Pi MCP Configuration
670
+ // ============================================================================
671
+
672
+ /**
673
+ * Get MCP configuration for the Pi engine.
674
+ *
675
+ * Pi runs in-process but connects MCP servers with its own client (the SDK's
676
+ * `createMcpExtension`), so it reaches the SAME `/mcp` bridge as the other
677
+ * engines instead of calling handlers directly. `exposure: 'direct'` declares
678
+ * the tools to the model like any other tool — Pi's default (`codemode`) would
679
+ * hide them behind a scripting tool. The bearer header also keeps Pi's own
680
+ * OAuth flow (and its `mcp-auth.json`) out of the loop; `timeout` is seconds.
681
+ */
682
+ export function getPiMcpConfig(
683
+ profileFilter?: Set<string>,
684
+ context?: McpExecutionContext
685
+ ): Record<string, PiMcpServerConfig> {
686
+ const enabledServers = activeInternalServerNames(profileFilter);
687
+ if (enabledServers.length === 0) {
688
+ return {};
689
+ }
690
+
691
+ const url = internalBridgeUrl('pi', context);
692
+
693
+ debug.log('mcp', `📦 Pi MCP: remote server at ${url}`);
694
+
695
+ return {
696
+ 'clopen-mcp': {
697
+ type: 'http',
698
+ url,
699
+ exposure: 'direct',
700
+ timeout: MCP_TOOL_CALL_TIMEOUT_MS / 1000,
701
+ headers: { Authorization: `Bearer ${getMcpServiceToken()}` },
702
+ },
703
+ };
704
+ }
705
+
667
706
  // ============================================================================
668
707
  // Qwen Code MCP Configuration
669
708
  // ============================================================================
@@ -19,7 +19,7 @@
19
19
  import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
20
20
  import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
21
21
  import { createRemoteMcpServer, type RemoteMcpCaller } from './servers/helper';
22
- import { createExternalProxyServer } from '../external/proxy';
22
+ import { createExternalProxyServer, createProjectProxyServer } from '../external/proxy';
23
23
  import { debug } from '$shared/utils/logger';
24
24
  import { authQueries } from '$backend/database/queries';
25
25
  import { hashToken } from '$backend/auth/tokens';
@@ -273,6 +273,16 @@ export async function handleExternalMcpRequest(request: Request, slug: string):
273
273
  return handleStreamable(request, `External MCP (${slug}${engine ? `, ${engine}` : ''})`, () => createExternalProxyServer(slug, engine));
274
274
  }
275
275
 
276
+ /**
277
+ * Handle a request to the per-project proxy `/mcp/proj/<projectId>/<name>` — a
278
+ * server from the project's approved `.agents/mcp.json` (see
279
+ * `backend/mcp/external/project.ts`).
280
+ */
281
+ export async function handleProjectMcpRequest(request: Request, projectId: string, name: string): Promise<Response> {
282
+ const engine = (new URL(request.url).searchParams.get('engine') as EngineType | null) ?? undefined;
283
+ return handleStreamable(request, `Project MCP (${projectId}/${name}${engine ? `, ${engine}` : ''})`, () => createProjectProxyServer(projectId, name, engine));
284
+ }
285
+
276
286
  /**
277
287
  * Close all active MCP sessions and transports.
278
288
  * Called during graceful server shutdown.
@@ -20,7 +20,7 @@
20
20
  * neighbours forever, which is far harder to notice than a failed download.
21
21
  */
22
22
 
23
- import { mkdir, rename, rm, writeFile } from 'node:fs/promises';
23
+ import { mkdir, readdir, rename, rm, writeFile } from 'node:fs/promises';
24
24
  import { join } from 'node:path';
25
25
  import { debug } from '$shared/utils/logger';
26
26
  import { embedder } from './embedder';
@@ -160,6 +160,7 @@ async function run(): Promise<boolean> {
160
160
  if (isEmbeddingArtifactInstalled()) {
161
161
  const loaded = await embedder.load();
162
162
  if (loaded) {
163
+ void pruneStaleVersions();
163
164
  clearRetry();
164
165
  setStatus({
165
166
  phase: 'installed',
@@ -233,6 +234,7 @@ async function run(): Promise<boolean> {
233
234
  embedder.unload();
234
235
  const loaded = await embedder.load();
235
236
  if (loaded) {
237
+ void pruneStaleVersions();
236
238
  clearRetry();
237
239
  setStatus({
238
240
  phase: 'installed',
@@ -250,5 +252,31 @@ async function run(): Promise<boolean> {
250
252
  return loaded;
251
253
  }
252
254
 
255
+ /**
256
+ * Remove every other version's directory — and any leftover `.partial` staging
257
+ * dir — once the current version has loaded. A version bump downloads into a
258
+ * fresh directory and nothing ever read the old one again, so it sat there for
259
+ * good. Gated on a successful load so an upgrade that fails keeps the previous
260
+ * artifact on disk.
261
+ */
262
+ async function pruneStaleVersions(): Promise<void> {
263
+ const root = getStackEmbeddingDir();
264
+ let entries: string[];
265
+ try {
266
+ entries = await readdir(root);
267
+ } catch {
268
+ return;
269
+ }
270
+ for (const entry of entries) {
271
+ if (entry === EMBEDDING_VERSION) continue;
272
+ try {
273
+ await rm(join(root, entry), { recursive: true, force: true });
274
+ debug.log('memory', `Removed superseded embedding artifact: ${entry}`);
275
+ } catch (error) {
276
+ debug.warn('memory', `Could not remove superseded embedding artifact ${entry}`, error);
277
+ }
278
+ }
279
+ }
280
+
253
281
  /** Marker so the catch can tell a bad payload from a bad connection. */
254
282
  class CorruptAssetError extends Error {}
@@ -39,7 +39,7 @@ export interface FetchedSkill {
39
39
  }
40
40
 
41
41
  const PAGE_SIZE = 30;
42
- const COMMUNITY_INDEX_URL = 'https://majiayu000.github.io/claude-skill-registry-core/search-index-lite.json';
42
+ const COMMUNITY_INDEX_URL = 'https://majiayu000.github.io/claude-skill-registry/search-index-lite.json';
43
43
 
44
44
  /**
45
45
  * A lite-index entry. The index uses full keys (`name`/`description`/`install`/
@@ -32,7 +32,7 @@ class BlobStore {
32
32
  private initialized = false;
33
33
 
34
34
  /**
35
- * Cache: filepath -> { mtimeMs, size, hash }
35
+ * Cache: absolute path -> { mtimeMs, size, hash }
36
36
  * Avoids re-reading files that haven't changed (based on mtime + size).
37
37
  */
38
38
  private fileHashCache = new Map<string, FileHashCacheEntry>();
@@ -115,22 +115,26 @@ class BlobStore {
115
115
  * If the file has changed, reads content, hashes it, stores blob, and caches.
116
116
  * Reads as Buffer to safely handle binary files (images, PDFs, etc.).
117
117
  *
118
+ * Cached by absolute path. It used to be keyed by whatever the caller passed,
119
+ * which was the project-relative path — shared by every project and every
120
+ * worktree copy, where the same file often has the same size.
121
+ *
118
122
  * @returns hash and content Buffer (content is null if cache hit and blob already exists)
119
123
  */
120
- async hashFile(filepath: string, fullPath: string): Promise<{ hash: string; content: Buffer | null; cached: boolean }> {
124
+ async hashFile(fullPath: string): Promise<{ hash: string; content: Buffer | null; cached: boolean }> {
121
125
  await this.init();
122
126
 
123
127
  const stat = await fs.stat(fullPath);
124
128
 
125
129
  // Check mtime cache
126
- const cached = this.fileHashCache.get(filepath);
130
+ const cached = this.fileHashCache.get(fullPath);
127
131
  if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
128
132
  // Verify blob still exists on disk (could have been cleaned up)
129
133
  if (await this.hasBlob(cached.hash)) {
130
134
  return { hash: cached.hash, content: null, cached: true };
131
135
  }
132
136
  // Blob was deleted — invalidate cache, fall through to re-read and re-store
133
- this.fileHashCache.delete(filepath);
137
+ this.fileHashCache.delete(fullPath);
134
138
  }
135
139
 
136
140
  // File changed or cache miss - read as Buffer (binary-safe, no encoding conversion)
@@ -141,7 +145,7 @@ class BlobStore {
141
145
  await this.storeBlob(content);
142
146
 
143
147
  // Update cache
144
- this.fileHashCache.set(filepath, {
148
+ this.fileHashCache.set(fullPath, {
145
149
  mtimeMs: stat.mtimeMs,
146
150
  size: stat.size,
147
151
  hash
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Reading the reflog for HEAD moves that rewrote the working tree.
3
+ *
4
+ * The line that matters is between a commit and everything else: a commit
5
+ * records files somebody already wrote, so treating it as git's own change
6
+ * would erase an agent's work the moment it committed it.
7
+ */
8
+
9
+ import { describe, it, expect } from 'bun:test';
10
+ import { isAuthoredCommit, parseReflog, workingTreeTransitions } from './git-attribution';
11
+
12
+ describe('isAuthoredCommit', () => {
13
+ it('knows a commit from the working tree from one that ends a merge', () => {
14
+ expect(isAuthoredCommit('commit: fix things')).toBe(true);
15
+ expect(isAuthoredCommit('commit (amend): fix things')).toBe(true);
16
+ expect(isAuthoredCommit('commit (initial): init')).toBe(true);
17
+ expect(isAuthoredCommit('commit (merge): Merge branch x')).toBe(false);
18
+ expect(isAuthoredCommit('merge origin/main: Merge made by the \'ort\' strategy.')).toBe(false);
19
+ expect(isAuthoredCommit('pull: Fast-forward')).toBe(false);
20
+ });
21
+ });
22
+
23
+ describe('workingTreeTransitions', () => {
24
+ const reflog = parseReflog([
25
+ 'c3\tHEAD@{1000}\tmerge origin/main: Fast-forward',
26
+ 'c2\tHEAD@{990}\tcommit: agent work',
27
+ 'c1\tHEAD@{500}\tcheckout: moving from a to main'
28
+ ].join('\n'));
29
+
30
+ it('parses sha, time and subject, newest first', () => {
31
+ expect(reflog[0]).toEqual({ sha: 'c3', time: 1000, subject: 'merge origin/main: Fast-forward' });
32
+ expect(reflog).toHaveLength(3);
33
+ });
34
+
35
+ it('keeps the moves inside the turn and skips commits', () => {
36
+ expect(workingTreeTransitions(reflog, 'c1', 980_000)).toEqual([{ from: 'c2', to: 'c3' }]);
37
+ });
38
+
39
+ it('finds nothing when the turn began after the last move', () => {
40
+ expect(workingTreeTransitions(reflog, 'c3', 2_000_000)).toEqual([]);
41
+ });
42
+ });