@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,244 @@
1
+ /**
2
+ * What the file watcher ignores.
3
+ *
4
+ * The rule of thumb: ignore what a tool writes and nobody edits by hand —
5
+ * dependency stores, build output, caches, VCS internals — because it is large
6
+ * (on Linux every watched directory costs an inotify handle) and noisy (a build
7
+ * would reload the explorer hundreds of times). Everything else is watched,
8
+ * dot-directories included: `.agents/`, `.claude/`, `.github/` and `.vscode/`
9
+ * hold files people and agents edit, and ignoring every dot path left the
10
+ * explorer stale until a reload.
11
+ *
12
+ * A bare list of names cannot get there on its own: names match at any depth,
13
+ * so a common one (`bin`, `target`, `out`, `Library`) would hide real source in
14
+ * some other ecosystem — Clopen's own `bin/` is source. So there are three
15
+ * layers, and a directory is ignored when any of them matches:
16
+ *
17
+ * 1. Names that mean "generated" wherever they appear ({@link IGNORED_DIRS}).
18
+ * 2. Ambiguous names, ignored only next to the manifest of the ecosystem that
19
+ * generates them ({@link MARKED_OUTPUT_DIRS}): `target/` beside
20
+ * `Cargo.toml`, `bin/` beside a `.csproj`.
21
+ * 3. Directories that describe themselves, whatever they are called
22
+ * ({@link SIGNATURE_ENTRIES}): the cross-tool `CACHEDIR.TAG` standard, and
23
+ * Python / conda environments.
24
+ *
25
+ * `.gitignore` is deliberately NOT a source. People commonly ignore folders
26
+ * they edit every day — `.claude/`, `.vscode/`, `.agents/`, local config — and
27
+ * pruning by it would bring back exactly the stale-explorer bug this fixes.
28
+ */
29
+
30
+ import { readdir } from 'node:fs/promises';
31
+ import { basename, dirname, join, sep } from 'node:path';
32
+
33
+ /** Layer 1: names that are machine-written wherever they appear. */
34
+ const IGNORED_DIRS = new Set([
35
+ // Version control internals
36
+ '.git', '.hg', '.svn', '.jj', '.bzr',
37
+ // JavaScript / TypeScript
38
+ 'node_modules', 'bower_components', 'jspm_packages', '.pnpm-store', '.yarn',
39
+ 'dist', 'build', 'coverage', '.nyc_output',
40
+ '.next', '.nuxt', '.output', '.svelte-kit', '.angular', '.astro', '.expo',
41
+ '.react-router', '.vinxi', '.nitro', '.vite', '.parcel-cache', '.turbo', '.nx',
42
+ '.docusaurus', '.vercel', '.netlify', '.wrangler', '.serverless', '.sass-cache',
43
+ // Python
44
+ '__pycache__', '__pypackages__', '.venv', '.tox', '.nox', '.eggs', '.pytest_cache',
45
+ '.mypy_cache', '.ruff_cache', '.pytype', '.pyre', '.hypothesis', 'htmlcov',
46
+ '.ipynb_checkpoints', '.pdm-build',
47
+ // JVM / Android / native
48
+ '.gradle', '.kotlin', '.cxx', '.externalNativeBuild',
49
+ // Apple
50
+ 'DerivedData', '.build', '.swiftpm', 'xcuserdata',
51
+ // Dart / Flutter
52
+ '.dart_tool', '.pub-cache',
53
+ // Haskell, OCaml, Elm, Zig, Nim
54
+ '.stack-work', 'dist-newstyle', '_opam', '_esy', 'elm-stuff',
55
+ '.zig-cache', 'zig-cache', 'zig-out', 'nimcache',
56
+ // Game engines, R
57
+ '.godot', '.Rproj.user',
58
+ // Monorepo build systems
59
+ 'buck-out', '.pants.d',
60
+ // Infrastructure
61
+ '.terraform', '.terragrunt-cache', '.aws-sam',
62
+ // Editors and IDEs (state churn, not settings people hand-edit)
63
+ '.idea', '.vs',
64
+ // PHP / Go / Ruby dependency copies
65
+ 'vendor',
66
+ // Generic caches and scratch space
67
+ '.cache', '.temp', '.tmp'
68
+ ]);
69
+
70
+ /** Layer 1, by prefix: names that carry a variable suffix. */
71
+ const IGNORED_DIR_PREFIXES = [
72
+ 'cmake-build-' // CLion: cmake-build-debug, cmake-build-release, …
73
+ ];
74
+
75
+ /** Files that change constantly and never matter to the explorer. */
76
+ const IGNORED_FILES = new Set([
77
+ '.DS_Store',
78
+ 'Thumbs.db',
79
+ '.gitkeep',
80
+ '.gitignore~',
81
+ '.eslintcache',
82
+ '.stylelintcache'
83
+ ]);
84
+
85
+ /** Vim swap files (`.name.swp`, `.swo`, …) — rewritten on every keystroke. */
86
+ const EDITOR_SWAP_FILE = /^\..+\.sw[a-p]$/;
87
+
88
+ /**
89
+ * Layer 2: a name that is output only in the ecosystem whose manifest sits
90
+ * beside it. `marker` is tested against every sibling entry name.
91
+ */
92
+ interface MarkedOutputDir {
93
+ dir: RegExp;
94
+ marker: RegExp;
95
+ }
96
+
97
+ const MARKED_OUTPUT_DIRS: MarkedOutputDir[] = [
98
+ // Rust, Maven, sbt, Leiningen
99
+ { dir: /^target$/, marker: /^(Cargo\.toml|pom\.xml|build\.sbt|project\.clj)$/ },
100
+ // .NET (Unity generates .csproj files at its root too)
101
+ { dir: /^(bin|obj)$/, marker: /\.(cs|fs|vb)proj$/ },
102
+ // Elixir, Erlang (rebar3), OCaml (dune)
103
+ { dir: /^_build$/, marker: /^(mix\.exs|rebar\.config|dune-project)$/ },
104
+ { dir: /^deps$/, marker: /^mix\.exs$/ },
105
+ // Next.js static export
106
+ { dir: /^out$/, marker: /^next\.config\.(js|cjs|mjs|ts)$/ },
107
+ // CocoaPods
108
+ { dir: /^Pods$/, marker: /^Podfile$/ },
109
+ // Unity
110
+ { dir: /^(Library|Temp|Logs|UserSettings)$/, marker: /^ProjectSettings$/ },
111
+ // Unreal Engine
112
+ { dir: /^(Binaries|Intermediate|Saved|DerivedDataCache)$/, marker: /\.uproject$/ },
113
+ // Bazel output symlinks: bazel-bin, bazel-out, bazel-<workspace>, …
114
+ { dir: /^bazel-/, marker: /^(WORKSPACE|WORKSPACE\.bazel|MODULE\.bazel)$/ }
115
+ ];
116
+
117
+ /**
118
+ * Layer 3: an entry that marks the directory CONTAINING it as generated.
119
+ *
120
+ * - `CACHEDIR.TAG` is the cross-tool cache-directory standard
121
+ * (bford.info/cachedir); Cargo's `target/` and the pytest, mypy and ruff
122
+ * caches all write one.
123
+ * - `pyvenv.cfg` sits at the root of every Python virtualenv, whatever the
124
+ * folder is called (`env`, `venv`, `.env3`, `myenv`, …).
125
+ * - `conda-meta` does the same for conda environments.
126
+ */
127
+ const SIGNATURE_ENTRIES = new Set(['CACHEDIR.TAG', 'pyvenv.cfg', 'conda-meta']);
128
+
129
+ /** Whether one path segment is ignored by name alone (layer 1). */
130
+ export function isIgnoredName(name: string): boolean {
131
+ if (IGNORED_DIRS.has(name) || IGNORED_FILES.has(name)) return true;
132
+ if (EDITOR_SWAP_FILE.test(name)) return true;
133
+ return IGNORED_DIR_PREFIXES.some((prefix) => name.startsWith(prefix));
134
+ }
135
+
136
+ /** Whether a project-relative path crosses a segment ignored by name. */
137
+ export function isIgnoredPath(relativePath: string): boolean {
138
+ return relativePath.split('/').some(isIgnoredName);
139
+ }
140
+
141
+ /** Layer 2: whether `name` is generated output given its sibling entries. */
142
+ export function isMarkedOutputDir(name: string, siblingNames: readonly string[]): boolean {
143
+ return MARKED_OUTPUT_DIRS.some(
144
+ (rule) => rule.dir.test(name) && siblingNames.some((sibling) => rule.marker.test(sibling))
145
+ );
146
+ }
147
+
148
+ /** Layer 3: whether a directory's own entries declare it generated. */
149
+ export function hasGeneratedSignature(entryNames: readonly string[]): boolean {
150
+ return entryNames.some((name) => SIGNATURE_ENTRIES.has(name));
151
+ }
152
+
153
+ /** A signature entry: its arrival or removal re-decides its parent directory. */
154
+ export function isSignatureEntry(name: string): boolean {
155
+ return SIGNATURE_ENTRIES.has(name);
156
+ }
157
+
158
+ /** A manifest: its arrival or removal re-decides its sibling directories. */
159
+ export function isOutputMarker(name: string): boolean {
160
+ return MARKED_OUTPUT_DIRS.some((rule) => rule.marker.test(name));
161
+ }
162
+
163
+ /** Whether a directory name could be output under some manifest (layer 2). */
164
+ export function isMarkableDirName(name: string): boolean {
165
+ return MARKED_OUTPUT_DIRS.some((rule) => rule.dir.test(name));
166
+ }
167
+
168
+ async function listNames(dir: string): Promise<string[]> {
169
+ try {
170
+ return await readdir(dir);
171
+ } catch {
172
+ return [];
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Layers 2 and 3 need the disk, so their answers are cached per directory.
178
+ * The cache is kept honest by events rather than a clock: the watcher calls
179
+ * {@link forget} when a signature or manifest appears or disappears, and
180
+ * {@link forgetTree} when a directory is removed.
181
+ */
182
+ export class GeneratedDirClassifier {
183
+ private readonly decisions = new Map<string, Promise<boolean>>();
184
+
185
+ constructor(private readonly root: string) {}
186
+
187
+ /**
188
+ * Whether `absDir` is generated by layer 2 or 3. `siblingNames` and
189
+ * `ownNames` skip the directory reads when the caller already listed them.
190
+ */
191
+ isGenerated(absDir: string, siblingNames?: readonly string[], ownNames?: readonly string[]): Promise<boolean> {
192
+ const cached = this.decisions.get(absDir);
193
+ if (cached) return cached;
194
+ const decision = (async () => {
195
+ if (absDir === this.root) return false;
196
+ const name = basename(absDir);
197
+ if (isMarkableDirName(name)) {
198
+ const siblings = siblingNames ?? (await listNames(dirname(absDir)));
199
+ if (isMarkedOutputDir(name, siblings)) return true;
200
+ }
201
+ return hasGeneratedSignature(ownNames ?? (await listNames(absDir)));
202
+ })();
203
+ this.decisions.set(absDir, decision);
204
+ return decision;
205
+ }
206
+
207
+ /**
208
+ * Whether a project-relative path lies under a generated directory. Only
209
+ * ancestors are judged: the path itself is reported even when it is such a
210
+ * directory, so a freshly created `target/` still appears in the explorer.
211
+ */
212
+ async isInsideGenerated(relativePath: string): Promise<boolean> {
213
+ const segments = relativePath.split('/');
214
+ let dir = this.root;
215
+ for (let i = 0; i < segments.length - 1; i++) {
216
+ dir = join(dir, segments[i]);
217
+ if (await this.isGenerated(dir)) return true;
218
+ }
219
+ return false;
220
+ }
221
+
222
+ /** Drop the decision for one directory so the next query re-reads the disk. */
223
+ forget(absDir: string): void {
224
+ this.decisions.delete(absDir);
225
+ }
226
+
227
+ /**
228
+ * Drop the decisions a manifest in `parentDir` could change: its children
229
+ * whose names some ecosystem treats as output.
230
+ */
231
+ forgetMarkableChildren(parentDir: string): void {
232
+ for (const dir of this.decisions.keys()) {
233
+ if (dirname(dir) === parentDir && isMarkableDirName(basename(dir))) this.decisions.delete(dir);
234
+ }
235
+ }
236
+
237
+ /** Drop decisions for a directory and everything under it (it was removed). */
238
+ forgetTree(absDir: string): void {
239
+ const prefix = absDir.endsWith(sep) ? absDir : absDir + sep;
240
+ for (const dir of this.decisions.keys()) {
241
+ if (dir === absDir || dir.startsWith(prefix)) this.decisions.delete(dir);
242
+ }
243
+ }
244
+ }
@@ -20,6 +20,8 @@ export interface GitExecResult {
20
20
  stdout: string;
21
21
  stderr: string;
22
22
  exitCode: number;
23
+ /** Undecoded stdout, only when the call asked for `raw` output. */
24
+ stdoutBytes?: Buffer;
23
25
  }
24
26
 
25
27
  export interface GitExecOptions {
@@ -47,6 +49,12 @@ export interface GitExecOptions {
47
49
  * future variable might.
48
50
  */
49
51
  env?: Record<string, string>;
52
+ /**
53
+ * Keep stdout as bytes as well. Needed whenever stdout is file content
54
+ * (`cat-file`, `show`): decoding a binary blob as UTF-8 is lossy, and a
55
+ * hash of the decoded text would never match the file on disk.
56
+ */
57
+ raw?: boolean;
50
58
  }
51
59
 
52
60
  /**
@@ -60,7 +68,7 @@ export async function execGit(
60
68
  ): Promise<GitExecResult> {
61
69
  const options: GitExecOptions =
62
70
  typeof timeoutOrOptions === 'number' ? { timeout: timeoutOrOptions } : timeoutOrOptions;
63
- const { timeout = 30000, stdin, okExitCodes = [], env: extraEnv } = options;
71
+ const { timeout = 30000, stdin, okExitCodes = [], env: extraEnv, raw = false } = options;
64
72
  debug.log('git', `Executing: git ${args.join(' ')} in ${cwd}`);
65
73
 
66
74
  const gitPath = resolveBinary('git');
@@ -106,10 +114,12 @@ export async function execGit(
106
114
  }, timeout);
107
115
 
108
116
  try {
109
- const [stdout, stderr] = await Promise.all([
110
- new Response(proc.stdout).text(),
117
+ const [stdoutBuffer, stderr] = await Promise.all([
118
+ new Response(proc.stdout).arrayBuffer(),
111
119
  new Response(proc.stderr).text()
112
120
  ]);
121
+ const stdoutBytes = Buffer.from(stdoutBuffer);
122
+ const stdout = stdoutBytes.toString('utf8');
113
123
 
114
124
  const exitCode = await proc.exited;
115
125
  clearTimeout(timeoutId);
@@ -118,7 +128,7 @@ export async function execGit(
118
128
  debug.warn('git', `Command failed (exit ${exitCode}): git ${args.join(' ')}\n${stderr}`);
119
129
  }
120
130
 
121
- return { stdout, stderr, exitCode };
131
+ return raw ? { stdout, stderr, exitCode, stdoutBytes } : { stdout, stderr, exitCode };
122
132
  } catch (err) {
123
133
  clearTimeout(timeoutId);
124
134
  throw err;
package/backend/index.ts CHANGED
@@ -43,6 +43,7 @@ import { initializeDatabase, closeDatabase } from './database';
43
43
  import { bootstrapAfterDbInit } from './bootstrap';
44
44
  import { startEngineConfigWatcher } from './engine/config-revision';
45
45
  import { startEngineHotReload } from './engine/hot-reload';
46
+ import { pruneStaleChromeBuilds } from './engine/install-recipes';
46
47
  import { disposeAllEngines } from './engine';
47
48
  import { connectionManager } from './db-client/connection-manager';
48
49
  import { sshClientPool } from './ssh/client-pool';
@@ -78,7 +79,7 @@ import { integrationHooksRoute } from './http/integration-hooks';
78
79
  import { browserPreviewServiceManager } from './preview';
79
80
 
80
81
  // MCP remote server for Open Code custom tools
81
- import { handleMcpRequest, handleExternalMcpRequest, closeMcpServer, completeAuthorization } from './mcp';
82
+ import { handleMcpRequest, handleExternalMcpRequest, handleProjectMcpRequest, closeMcpServer, completeAuthorization } from './mcp';
82
83
 
83
84
  // Auth middleware
84
85
  import { checkRouteAccess, PUBLIC_ROUTES } from './auth/permissions';
@@ -188,6 +189,16 @@ const app = new Elysia()
188
189
  return handleExternalMcpRequest(request, params.slug);
189
190
  })
190
191
 
192
+ // Per-project proxy for servers a repository declares in `.agents/mcp.json`.
193
+ // Only served while an admin has approved the file's current content — see
194
+ // backend/mcp/external/project.ts.
195
+ .all('/mcp/proj/:projectId/:name', async ({ request, params, server }) => {
196
+ server?.timeout(request, 0);
197
+ let name = params.name;
198
+ try { name = decodeURIComponent(name); } catch { /* already decoded */ }
199
+ return handleProjectMcpRequest(request, params.projectId, name);
200
+ })
201
+
191
202
  // Stable OAuth redirect target for centralized MCP sign-in. The browser is
192
203
  // redirected here after the user consents; we exchange the code for tokens
193
204
  // (stored against the server) and show a self-closing confirmation page. The
@@ -298,6 +309,10 @@ async function startServer() {
298
309
  // Shared with the clear-data handler so a DB wipe on the live process
299
310
  // restores them without a restart.
300
311
  bootstrapAfterDbInit();
312
+ // Before anything can launch Chrome, so the build being deleted is never
313
+ // one that is running. Not in bootstrapAfterDbInit(): during "Clear All
314
+ // Data" the live process may have a browser open.
315
+ pruneStaleChromeBuilds();
301
316
  // Start expired session cleanup now that the database is ready
302
317
  sessionCleanupScheduler.start();
303
318
  uploadTempCleanup.start();
@@ -1,8 +1,10 @@
1
1
  /**
2
2
  * Instruction service — reads/writes the Clopen-managed instruction block for
3
- * the single global scope and per project. The content is materialized into each
4
- * engine's memory file as a MARKER-REGION (see `sync.ts`), so hand-written parts
5
- * of `CLAUDE.md` / `AGENTS.md` are never touched.
3
+ * the single global scope and per project. The global block is materialized into
4
+ * each engine's memory file as a MARKER-REGION (see `sync.ts`), so hand-written
5
+ * parts of `CLAUDE.md` / `AGENTS.md` are never touched. The per-project block is
6
+ * the Clopen-only layer: never committed, delivered per session by the project
7
+ * bridge (`backend/artifacts/project/bridge.ts`).
6
8
  *
7
9
  * This is distinct from Skills/Commands/Subagents (which are discrete
8
10
  * installable artifacts): Instructions is one managed block of prose per scope.
@@ -1,13 +1,11 @@
1
1
  /**
2
2
  * Engine sync for Instructions — writes the managed instruction block into each
3
3
  * engine's memory file as a marker-region (`<!-- CLOPEN:INSTRUCTIONS:START … -->`).
4
- * Global scope always applies; project scope applies to the repo memory file
5
- * when a project is being streamed.
4
+ * Global scope only — see {@link syncInstructions} for where project
5
+ * instructions go.
6
6
  *
7
7
  * Ownership is MARKER-REGION: only the delimited block is Clopen's; the rest of
8
8
  * `CLAUDE.md` / `AGENTS.md` (hand-written by the user) is preserved verbatim.
9
- * Writing into a project's `CLAUDE.md` touches the repo working tree, so callers
10
- * pass the repo path explicitly — this is never silent guesswork.
11
9
  *
12
10
  * Never throws — a stream never breaks because instructions couldn't sync.
13
11
  */
@@ -36,13 +34,14 @@ export function buildInstructionsPromptContext(): string {
36
34
  }
37
35
 
38
36
  /**
39
- * Sync the global (and, when a project is provided, project) instruction block
40
- * into one engine's memory file(s).
37
+ * Sync the global instruction block into one engine's memory file.
38
+ *
39
+ * The per-project block is deliberately NOT written anywhere: it is the
40
+ * Clopen-only layer (never committed), delivered per session by the project
41
+ * bridge (`backend/artifacts/project/bridge.ts`). The committed project layer is
42
+ * the managed block of the repo's `AGENTS.md`, edited explicitly from Settings.
41
43
  */
42
- export async function syncInstructions(
43
- engine: ArtifactEngine,
44
- project?: { id: string; path: string }
45
- ): Promise<void> {
44
+ export async function syncInstructions(engine: ArtifactEngine): Promise<void> {
46
45
  try {
47
46
  // Global scope → engine's isolated global memory file, but ONLY for engines
48
47
  // that actually read one. Writing `AGENTS.md` into Cline's or Cursor's
@@ -57,23 +56,7 @@ export async function syncInstructions(
57
56
  if (globalTarget) await writeManagedBlock(globalTarget, globalBlock, MARKERS);
58
57
  }
59
58
 
60
- // Project scope → repo memory file (touches the working tree).
61
- if (project) {
62
- const row = instructionQueries.getForProject(project.id);
63
- const projectTarget = resolveArtifact('instruction', { engine, scope: 'project', projectPath: project.path }).locateEffective({
64
- engine,
65
- scope: 'project',
66
- projectPath: project.path
67
- });
68
- const projectBlock = row && row.is_enabled === 1 ? row.content : '';
69
- // Only write when there is a managed block to add/update or a prior one to
70
- // clear — avoids creating an empty repo memory file for nothing.
71
- if (projectTarget && (projectBlock || row)) {
72
- await writeManagedBlock(projectTarget, projectBlock, MARKERS);
73
- }
74
- }
75
-
76
- debug.log('instructions', `📝 Synced instructions → ${engine}${project ? ' (+project)' : ''}`);
59
+ debug.log('instructions', `📝 Synced instructions → ${engine}`);
77
60
  } catch (error) {
78
61
  debug.warn('instructions', `⚠️ Instruction sync for ${engine} failed (continuing without):`, error);
79
62
  }
@@ -638,7 +638,7 @@ const mcpConfig = getOpenCodeMcpConfig();
638
638
 
639
639
  ##### Who is calling: the bridge URL carries the caller
640
640
 
641
- The in-process engines (Claude, Pi, Cline) wrap every tool handler in the
641
+ The in-process engines (Claude, Cline) wrap every tool handler in the
642
642
  stream's `McpExecutionContext`, so a handler that asks "which project is this?"
643
643
  always gets the right answer. An HTTP request carries no such context, and the
644
644
  fallback — the most recently *started* stream anywhere in the app — is the
@@ -651,7 +651,7 @@ lifetime allows, and `handleMcpRequest` binds that for the MCP session:
651
651
 
652
652
  | Engine | Query string | Why not more |
653
653
  | ------------- | --------------------------------------- | ------------ |
654
- | Copilot, Cursor, Qwen | `engine`, `project`, `session` | — built per stream |
654
+ | Copilot, Cursor, Pi, Qwen | `engine`, `project`, `session` | — built per stream |
655
655
  | Codex | `engine`, `project` | one client per project, shared by its chat sessions |
656
656
  | Open Code | `engine` | one pooled server per Profile, shared across projects |
657
657
 
@@ -24,6 +24,7 @@ import type { McpRemoteConfig } from '@opencode-ai/sdk';
24
24
  import type { MCPHTTPServerConfig as CopilotMcpServerConfig } from '@github/copilot-sdk';
25
25
  import type { CLIMcpServerConfig as QwenMcpServerConfig } from '@qwen-code/sdk';
26
26
  import type { McpServerConfig as CursorMcpServerConfig } from '@cursor/sdk';
27
+ import type { McpServerConfig as PiMcpServerConfig } from '@earendil-works/pi-coding-agent';
27
28
  import { debug } from '$shared/utils/logger';
28
29
  import { mcpServerQueries } from '$backend/database/queries';
29
30
  import { externalNamespace, MCP_TOOL_CALL_TIMEOUT_MS } from '../shared/constants';
@@ -32,6 +33,7 @@ import { SERVER_ENV } from '../../utils/env';
32
33
  import type { McpServerRow } from '$backend/database/queries';
33
34
  import type { EngineType } from '$shared/types/unified';
34
35
  import type { ResolvedExternalServer } from './types';
36
+ import { getTrustedProjectServers, knownProjectNamespaces } from './project';
35
37
 
36
38
  /**
37
39
  * Codex `mcp_servers.<name>` config, flattened by the SDK to `--config` flags.
@@ -56,6 +58,28 @@ function bridgeUrl(slug: string, engine: EngineType): string {
56
58
  return `http://localhost:${SERVER_ENV.PORT}/mcp/ext/${slug}?engine=${engine}`;
57
59
  }
58
60
 
61
+ /** Loopback URL of the per-project bridge for a server in `.agents/mcp.json`. */
62
+ function projectBridgeUrl(projectId: string, name: string, engine: EngineType): string {
63
+ return `http://localhost:${SERVER_ENV.PORT}/mcp/proj/${encodeURIComponent(projectId)}/${encodeURIComponent(name)}?engine=${engine}`;
64
+ }
65
+
66
+ /**
67
+ * Every bridge an engine should receive for this stream: the enabled installed
68
+ * servers (profile-filtered) plus, when the stream has a project, the servers of
69
+ * its APPROVED `.agents/mcp.json`. Project servers are not profile-filtered —
70
+ * they belong to the repository, not to a bundle — and never shadow an
71
+ * installed server that happens to share the namespace.
72
+ */
73
+ function bridgesFor(engine: EngineType, profileFilter?: Set<string>, projectId?: string | null): { namespace: string; url: string }[] {
74
+ const out = getEnabledExternalServers(profileFilter).map(s => ({ namespace: s.namespace, url: bridgeUrl(s.slug, engine) }));
75
+ const taken = new Set(out.map(b => b.namespace));
76
+ for (const s of getTrustedProjectServers(projectId)) {
77
+ if (taken.has(s.namespace)) continue;
78
+ out.push({ namespace: s.namespace, url: projectBridgeUrl(s.projectId, s.name, engine) });
79
+ }
80
+ return out;
81
+ }
82
+
59
83
  /** The service-token bearer header every engine→bridge hop carries. */
60
84
  function serviceAuthHeaders(): Record<string, string> {
61
85
  return { Authorization: `Bearer ${getMcpServiceToken()}` };
@@ -145,22 +169,22 @@ export function remoteNeedsOAuth(s: ResolvedExternalServer): boolean {
145
169
  // ---------------------------------------------------------------------------
146
170
 
147
171
  /** Claude Agent SDK: Streamable-HTTP remote keyed by namespace. */
148
- export function getClaudeExternalMcpConfig(profileFilter?: Set<string>): Record<string, McpServerConfig> {
172
+ export function getClaudeExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, McpServerConfig> {
149
173
  const out: Record<string, McpServerConfig> = {};
150
- for (const s of getEnabledExternalServers(profileFilter)) {
151
- out[s.namespace] = { type: 'http', url: bridgeUrl(s.slug, 'claude-code'), headers: serviceAuthHeaders() };
174
+ for (const b of bridgesFor('claude-code', profileFilter, projectId)) {
175
+ out[b.namespace] = { type: 'http', url: b.url, headers: serviceAuthHeaders() };
152
176
  }
153
177
  logBuilt('Claude', out);
154
178
  return out;
155
179
  }
156
180
 
157
181
  /** Open Code: `McpRemoteConfig` pointing at the bridge proxy. */
158
- export function getOpenCodeExternalMcpConfig(profileFilter?: Set<string>): Record<string, McpRemoteConfig> {
182
+ export function getOpenCodeExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, McpRemoteConfig> {
159
183
  const out: Record<string, McpRemoteConfig> = {};
160
- for (const s of getEnabledExternalServers(profileFilter)) {
161
- out[s.namespace] = {
184
+ for (const b of bridgesFor('opencode', profileFilter, projectId)) {
185
+ out[b.namespace] = {
162
186
  type: 'remote',
163
- url: bridgeUrl(s.slug, 'opencode'),
187
+ url: b.url,
164
188
  enabled: true,
165
189
  timeout: MCP_TOOL_CALL_TIMEOUT_MS,
166
190
  headers: serviceAuthHeaders()
@@ -170,6 +194,25 @@ export function getOpenCodeExternalMcpConfig(profileFilter?: Set<string>): Recor
170
194
  return out;
171
195
  }
172
196
 
197
+ /**
198
+ * Open Code entries for the project's approved `.agents/mcp.json` ONLY. The
199
+ * server pool caches the installed-server config per scope, so project servers
200
+ * are layered on at spawn-assembly time instead (see opencode/server.ts).
201
+ */
202
+ export function getOpenCodeProjectMcpConfig(projectId: string | null | undefined): Record<string, McpRemoteConfig> {
203
+ const out: Record<string, McpRemoteConfig> = {};
204
+ for (const s of getTrustedProjectServers(projectId)) {
205
+ out[s.namespace] = {
206
+ type: 'remote',
207
+ url: projectBridgeUrl(s.projectId, s.name, 'opencode'),
208
+ enabled: true,
209
+ timeout: MCP_TOOL_CALL_TIMEOUT_MS,
210
+ headers: serviceAuthHeaders()
211
+ };
212
+ }
213
+ return out;
214
+ }
215
+
173
216
  /**
174
217
  * Codex: `mcp_servers.<name>.url` pointing at the bridge proxy.
175
218
  *
@@ -179,26 +222,26 @@ export function getOpenCodeExternalMcpConfig(profileFilter?: Set<string>): Recor
179
222
  * The server is registered so interactive/known-tool flows work; this limit is
180
223
  * unchanged by the proxy.
181
224
  */
182
- export function getCodexExternalMcpConfig(profileFilter?: Set<string>): Record<string, CodexMcpServerConfig> {
225
+ export function getCodexExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, CodexMcpServerConfig> {
183
226
  const out: Record<string, CodexMcpServerConfig> = {};
184
- for (const s of getEnabledExternalServers(profileFilter)) {
185
- out[s.namespace] = { url: bridgeUrl(s.slug, 'codex'), http_headers: serviceAuthHeaders() };
227
+ for (const b of bridgesFor('codex', profileFilter, projectId)) {
228
+ out[b.namespace] = { url: b.url, http_headers: serviceAuthHeaders() };
186
229
  }
187
230
  logBuilt('Codex', out);
188
231
  return out;
189
232
  }
190
233
 
191
234
  /** Copilot: `MCPHTTPServerConfig` pointing at the bridge proxy. */
192
- export function getCopilotExternalMcpConfig(profileFilter?: Set<string>): Record<string, CopilotMcpServerConfig> {
235
+ export function getCopilotExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, CopilotMcpServerConfig> {
193
236
  const out: Record<string, CopilotMcpServerConfig> = {};
194
- for (const s of getEnabledExternalServers(profileFilter)) {
237
+ for (const b of bridgesFor('copilot', profileFilter, projectId)) {
195
238
  // `tools: ['*']` makes the Copilot runtime expose ALL of the proxy's
196
239
  // tools. Leaving it unset relies on the SDK's documented "undefined =
197
240
  // all" default, which the bundled CLI does not honour for dynamically
198
241
  // discovered servers — the tools never reach the model.
199
- out[s.namespace] = {
242
+ out[b.namespace] = {
200
243
  type: 'http',
201
- url: bridgeUrl(s.slug, 'copilot'),
244
+ url: b.url,
202
245
  tools: ['*'],
203
246
  timeout: MCP_TOOL_CALL_TIMEOUT_MS,
204
247
  headers: serviceAuthHeaders()
@@ -208,22 +251,38 @@ export function getCopilotExternalMcpConfig(profileFilter?: Set<string>): Record
208
251
  return out;
209
252
  }
210
253
 
254
+ /** Pi: `McpServerConfig` (http variant, `direct` exposure) pointing at the bridge proxy. */
255
+ export function getPiExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, PiMcpServerConfig> {
256
+ const out: Record<string, PiMcpServerConfig> = {};
257
+ for (const b of bridgesFor('pi', profileFilter, projectId)) {
258
+ out[b.namespace] = {
259
+ type: 'http',
260
+ url: b.url,
261
+ exposure: 'direct',
262
+ timeout: MCP_TOOL_CALL_TIMEOUT_MS / 1000,
263
+ headers: serviceAuthHeaders()
264
+ };
265
+ }
266
+ logBuilt('Pi', out);
267
+ return out;
268
+ }
269
+
211
270
  /** Qwen Code: `CLIMcpServerConfig` Streamable-HTTP (`httpUrl`) at the bridge proxy. */
212
271
  /** Cursor: `McpServerConfig` (http variant) pointing at the bridge proxy. */
213
- export function getCursorExternalMcpConfig(profileFilter?: Set<string>): Record<string, CursorMcpServerConfig> {
272
+ export function getCursorExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, CursorMcpServerConfig> {
214
273
  const out: Record<string, CursorMcpServerConfig> = {};
215
- for (const s of getEnabledExternalServers(profileFilter)) {
216
- out[s.namespace] = { type: 'http', url: bridgeUrl(s.slug, 'cursor'), headers: serviceAuthHeaders() };
274
+ for (const b of bridgesFor('cursor', profileFilter, projectId)) {
275
+ out[b.namespace] = { type: 'http', url: b.url, headers: serviceAuthHeaders() };
217
276
  }
218
277
  logBuilt('Cursor', out);
219
278
  return out;
220
279
  }
221
280
 
222
- export function getQwenExternalMcpConfig(profileFilter?: Set<string>): Record<string, QwenMcpServerConfig> {
281
+ export function getQwenExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, QwenMcpServerConfig> {
223
282
  const out: Record<string, QwenMcpServerConfig> = {};
224
- for (const s of getEnabledExternalServers(profileFilter)) {
225
- out[s.namespace] = {
226
- httpUrl: bridgeUrl(s.slug, 'qwen'),
283
+ for (const b of bridgesFor('qwen', profileFilter, projectId)) {
284
+ out[b.namespace] = {
285
+ httpUrl: b.url,
227
286
  timeout: MCP_TOOL_CALL_TIMEOUT_MS,
228
287
  trust: true,
229
288
  headers: serviceAuthHeaders()
@@ -251,8 +310,8 @@ export function getQwenExternalMcpConfig(profileFilter?: Set<string>): Record<st
251
310
  * Returns null if the name doesn't belong to any enabled external server.
252
311
  */
253
312
  export function resolveExternalToolName(toolName: string): string | null {
254
- for (const s of getEnabledExternalServers()) {
255
- const ns = s.namespace;
313
+ const namespaces = [...getEnabledExternalServers().map(s => s.namespace), ...knownProjectNamespaces()];
314
+ for (const ns of namespaces) {
256
315
  if (toolName.startsWith(`mcp__${ns}__`)) return toolName;
257
316
  for (const sep of ['_', '-']) {
258
317
  const prefix = `${ns}${sep}`;
@@ -293,6 +352,7 @@ export function getEngineConfigsForServer(slug: string): Record<string, unknown>
293
352
  codex: () => getCodexExternalMcpConfig() as Record<string, unknown>,
294
353
  copilot: () => getCopilotExternalMcpConfig() as Record<string, unknown>,
295
354
  cursor: () => getCursorExternalMcpConfig() as Record<string, unknown>,
355
+ pi: () => getPiExternalMcpConfig() as Record<string, unknown>,
296
356
  qwen: () => getQwenExternalMcpConfig() as Record<string, unknown>
297
357
  };
298
358