@myrialabs/clopen 0.4.45 → 0.4.47

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 (73) hide show
  1. package/backend/artifacts/project/sources.ts +2 -2
  2. package/backend/engine/adapters/claude/models.test.ts +49 -0
  3. package/backend/engine/adapters/claude/models.ts +81 -562
  4. package/backend/engine/adapters/claude/stream.ts +5 -4
  5. package/backend/engine/adapters/cline/credential.ts +42 -18
  6. package/backend/engine/adapters/cline/message-converter.ts +31 -1
  7. package/backend/engine/adapters/cline/models.test.ts +77 -0
  8. package/backend/engine/adapters/cline/models.ts +89 -3
  9. package/backend/engine/adapters/cline/presets.ts +5 -0
  10. package/backend/engine/adapters/cline/stream.ts +9 -2
  11. package/backend/engine/adapters/codex/message-converter.ts +1 -1
  12. package/backend/engine/adapters/codex/models.ts +54 -31
  13. package/backend/engine/adapters/codex/patch-rollout.test.ts +36 -1
  14. package/backend/engine/adapters/codex/patch-rollout.ts +60 -29
  15. package/backend/engine/adapters/codex/session-fork.ts +5 -0
  16. package/backend/engine/adapters/codex/stream.ts +8 -7
  17. package/backend/engine/adapters/copilot/models.test.ts +40 -0
  18. package/backend/engine/adapters/copilot/models.ts +51 -24
  19. package/backend/engine/adapters/copilot/permissions.test.ts +47 -0
  20. package/backend/engine/adapters/copilot/permissions.ts +72 -0
  21. package/backend/engine/adapters/copilot/stream.ts +77 -67
  22. package/backend/engine/adapters/cursor/stream.ts +8 -4
  23. package/backend/engine/adapters/opencode/presets.ts +27 -2
  24. package/backend/engine/adapters/opencode/server.ts +6 -4
  25. package/backend/engine/adapters/pi/credential.test.ts +83 -0
  26. package/backend/engine/adapters/pi/credential.ts +68 -12
  27. package/backend/engine/adapters/pi/environment.ts +9 -5
  28. package/backend/engine/adapters/pi/mcp.test.ts +194 -0
  29. package/backend/engine/adapters/pi/mcp.ts +88 -0
  30. package/backend/engine/adapters/pi/message-converter.ts +6 -4
  31. package/backend/engine/adapters/pi/presets.ts +10 -5
  32. package/backend/engine/adapters/pi/stream.ts +42 -38
  33. package/backend/engine/adapters/qwen/environment.ts +39 -2
  34. package/backend/engine/adapters/qwen/message-converter.test.ts +64 -0
  35. package/backend/engine/adapters/qwen/message-converter.ts +40 -23
  36. package/backend/engine/adapters/qwen/models.test.ts +25 -0
  37. package/backend/engine/adapters/qwen/models.ts +42 -5
  38. package/backend/engine/adapters/qwen/session-store.test.ts +39 -0
  39. package/backend/engine/adapters/qwen/session-store.ts +66 -0
  40. package/backend/engine/adapters/qwen/stream.ts +110 -87
  41. package/backend/engine/docs/adapter-contract.md +7 -4
  42. package/backend/engine/docs/lessons-learned.md +405 -62
  43. package/backend/engine/docs/quick-reference.md +2 -2
  44. package/backend/engine/docs/stack.md +17 -4
  45. package/backend/engine/docs/websocket-routes.md +5 -5
  46. package/backend/engine/install-recipes.test.ts +105 -5
  47. package/backend/engine/install-recipes.ts +102 -42
  48. package/backend/engine/install-runner.ts +56 -2
  49. package/backend/engine/stack-project.ts +71 -1
  50. package/backend/index.ts +5 -0
  51. package/backend/mcp/README.md +2 -2
  52. package/backend/mcp/external/config.ts +18 -0
  53. package/backend/mcp/external/proxy.ts +2 -2
  54. package/backend/mcp/index.ts +8 -0
  55. package/backend/mcp/internal/config.ts +42 -3
  56. package/backend/memory/embedding/install.ts +29 -1
  57. package/backend/utils/keyed-lock.test.ts +33 -0
  58. package/backend/utils/keyed-lock.ts +17 -0
  59. package/backend/utils/port-utils.test.ts +29 -0
  60. package/backend/utils/port-utils.ts +19 -0
  61. package/backend/ws/engine/cline/accounts.ts +26 -6
  62. package/backend/ws/engine/codex/accounts.test.ts +49 -0
  63. package/backend/ws/engine/codex/accounts.ts +17 -13
  64. package/backend/ws/engine/opencode/providers.ts +2 -1
  65. package/backend/ws/engine/pi/accounts.ts +61 -6
  66. package/dist/assets/{index-D-Ad1N96.js → index-BTcR1byF.js} +1 -1
  67. package/dist/assets/{index-Am-rJRxA.js → index-CwuKQelV.js} +1 -1
  68. package/dist/assets/{main--PLCDxSy.css → main-BiDNMWb3.css} +1 -1
  69. package/dist/assets/{main-DelPm2Xt.js → main-BlhKWz2B.js} +595 -593
  70. package/dist/index.html +2 -2
  71. package/package.json +19 -15
  72. package/backend/engine/adapters/pi/mcp-tools.ts +0 -153
  73. package/backend/engine/adapters/qwen/session-fork.ts +0 -109
@@ -66,8 +66,8 @@ its pinned SDK package(s) (`ENGINE_PACKAGES`, versions read from `package.json`
66
66
  via `getRequiredSdkVersion`) and installs them with `bun add <pkg>@<version>`
67
67
  run with `recipe.cwd = getStackEnginesDir()`, so they land in
68
68
  `~/.clopen/stack/engines` instead of the global store. Installing the SDK also
69
- pulls whatever CLI binary it bundles; the drifting Copilot CLI is pinned exact
70
- (`@github/copilot`). Because everything is fully clopen-managed, engine recipes
69
+ pulls whatever runtime binary it ships as a platform package (Copilot, Claude,
70
+ Codex). Because everything is fully clopen-managed, engine recipes
71
71
  carry **no** `manualInstructions` — there is no command for the user to run by
72
72
  hand. `install-runner.ts` bootstraps the stack dir + a minimal `package.json`
73
73
  before the first `bun add`.
@@ -76,7 +76,8 @@ before the first `bun add`.
76
76
 
77
77
  `getToolStatus(tool)` returns `{ tool, installed, version, source }` (engines
78
78
  additionally carry `requiredVersion` + `needsUpdate`):
79
- - `chrome` has a special path (puppeteer cache scan + system Chrome).
79
+ - `chrome` has a special path (puppeteer cache scan, newest build first +
80
+ system Chrome).
80
81
  - `cloudflared` at `~/.clopen/bin/cloudflared` is marked `source: 'clopen'`.
81
82
  - **Engine SDKs** are detected by `readEngineSdkVersion(pkg)` — the SDK's
82
83
  version inside the stack dir, NOT a CLI on PATH. `source` is the stack dir;
@@ -97,9 +98,21 @@ additionally carry `requiredVersion` + `needsUpdate`):
97
98
  4. `Bun.spawn(spawnArgs, { stdout: 'pipe', stderr: 'pipe', stdin: 'ignore', env })`.
98
99
  5. Streams stdout/stderr per-line into a ring buffer (10k lines) + emits
99
100
  `stack:install-stream` to the user room.
100
- 6. On exit: emits `stack:install-finished` + retains the session
101
+ 6. After a successful engine install, prunes the stack dir
102
+ (`pruneStackDependencies`): `bun remove`s packages that
103
+ `knownStackEnginePackages()` no longer lists, then sweeps `node_modules`
104
+ entries `bun.lock` does not resolve — bun leaves a dropped package's
105
+ platform binary behind on its own. Skipped while another install shares
106
+ the dir; a failed prune never fails the install.
107
+ 7. On exit: emits `stack:install-finished` + retains the session
101
108
  for 5 minutes for re-attach.
102
109
 
110
+ The other managed stacks prune themselves too: the embedding artifact removes
111
+ other version directories once the current one loads, and superseded Chrome
112
+ for Testing builds are deleted at server startup (before anything can launch
113
+ one). `resolveClopenChromePath()` picks the newest build by numeric build id —
114
+ directory order is alphabetical, which used to select the oldest.
115
+
103
116
  Exit-code hints (`explainFailure(137|143, cancelled)`) explain SIGKILL OOM
104
117
  or SIGTERM with actual total/free memory readings.
105
118
 
@@ -119,16 +119,16 @@ separate restart event.
119
119
  | `engine:copilot-accounts-switch` | Set active |
120
120
  | `engine:copilot-accounts-delete` | |
121
121
  | `engine:copilot-accounts-rename` | |
122
- | `engine:copilot-server-restart` | Restart cached `CopilotClient` so a new PAT applies — same Restart-Server pattern as §4.2 |
123
122
 
124
123
  The Copilot setup flow does not need a PTY — the user pastes a GitHub
125
124
  Personal Access Token in the UI (Copilot Requests + read:user scope), and
126
125
  the handler stores it via `engineQueries.createAccount`. No re-auth dance.
127
126
 
128
- Copilot follows the **same Restart-Server pattern** documented in §4.2
129
- because `CopilotClient` takes the PAT at construction time. Account
130
- add / remove / switch flips a `needsRestart` flag in the UI that surfaces
131
- a "Restart Server" button in both Settings → Engines and Chat Input.
127
+ Account add / remove / switch bumps the engine config revision, which
128
+ retires the cached `CopilotClient` so the next stream starts one on the
129
+ current active account. A chat that picks another account needs no restart
130
+ at all: each session carries its own token (`SessionConfig.gitHubToken`) —
131
+ see `lessons-learned.md` §10.9.
132
132
 
133
133
  ### 4.4 Stack — `stack:*`
134
134
 
@@ -24,15 +24,16 @@
24
24
  */
25
25
 
26
26
  import { describe, expect, test } from 'bun:test';
27
- import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
27
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
28
28
  import { tmpdir } from 'node:os';
29
29
  import { join } from 'node:path';
30
30
  import type { EngineType } from '$shared/types/unified';
31
- import { ENGINE_PACKAGES, engineInstallArgs, type ToolId } from './install-recipes';
31
+ import { ENGINE_PACKAGES, engineInstallArgs, knownStackEnginePackages, pruneStaleChromeBuilds, resolveClopenChromePath, type ToolId } from './install-recipes';
32
+ import { getClopenDir } from '$backend/utils/paths';
32
33
  import { ENGINE_SDK, TOOL_FOR_ENGINE } from './engine-setup';
33
34
  import { getRequiredSdkVersion } from './sdk-loader';
34
35
  import { ENGINE_CLI, engineCliTrustedPackages, getRequiredCliVersion } from './engine-cli';
35
- import { ensureStackProject } from './stack-project';
36
+ import { ensureStackProject, staleStackDependencies, sweepOrphanedModules } from './stack-project';
36
37
 
37
38
  const pkg = JSON.parse(
38
39
  readFileSync(join(import.meta.dir, '..', '..', 'package.json'), 'utf8')
@@ -182,7 +183,7 @@ describe('on-demand engine CLIs', () => {
182
183
  const dir = mkdtempSync(join(tmpdir(), 'clopen-stack-'));
183
184
  writeFileSync(
184
185
  join(dir, 'package.json'),
185
- JSON.stringify({ name: 'clopen-stack-engines', private: true, version: '0.0.0', dependencies: { '@opencode-ai/sdk': '1.18.18' } })
186
+ JSON.stringify({ name: 'clopen-stack-engines', private: true, version: '0.0.0', dependencies: { '@opencode-ai/sdk': '1.18.34' } })
186
187
  );
187
188
 
188
189
  ensureStackProject(dir);
@@ -191,9 +192,108 @@ describe('on-demand engine CLIs', () => {
191
192
  dependencies?: Record<string, string>;
192
193
  trustedDependencies?: string[];
193
194
  };
194
- expect(merged.dependencies).toEqual({ '@opencode-ai/sdk': '1.18.18' });
195
+ expect(merged.dependencies).toEqual({ '@opencode-ai/sdk': '1.18.34' });
195
196
  for (const pkg of engineCliTrustedPackages()) {
196
197
  expect(merged.trustedDependencies).toContain(pkg);
197
198
  }
198
199
  });
199
200
  });
201
+
202
+ describe('stack dir pruning', () => {
203
+ function stackDir(dependencies: Record<string, string>): string {
204
+ const dir = mkdtempSync(join(tmpdir(), 'clopen-stack-'));
205
+ writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'clopen-stack-engines', dependencies }));
206
+ return dir;
207
+ }
208
+
209
+ test('every package an install adds counts as known', () => {
210
+ // Otherwise the prune after an install would remove what it just added.
211
+ const known = knownStackEnginePackages();
212
+ const installed = (Object.keys(ENGINE_PACKAGES) as ToolId[])
213
+ .flatMap(tool => engineInstallArgs(tool))
214
+ .map(arg => arg.replace(/@[^@/]+$/, ''));
215
+ expect(installed.filter(name => !known.has(name))).toEqual([]);
216
+ });
217
+
218
+ test('a package clopen stopped installing is stale', () => {
219
+ // e.g. a CLI that used to be pinned beside its SDK until the SDK bundled it.
220
+ const dir = stackDir({ '@acme/retired-engine-cli': '1.0.0', '@opencode-ai/sdk': '1.18.34', 'opencode-ai': '1.18.34' });
221
+ expect(staleStackDependencies(dir, knownStackEnginePackages())).toEqual(['@acme/retired-engine-cli']);
222
+ });
223
+
224
+ test('modules bun.lock no longer resolves are swept, with their bin links', () => {
225
+ // bun leaves a dropped package's platform binary behind, even through
226
+ // `bun install --force` — this is what kept ~330 MB of the old Copilot CLI.
227
+ const dir = stackDir({ '@github/copilot-sdk': '1.0.16' });
228
+ writeFileSync(join(dir, 'bun.lock'), `{
229
+ "lockfileVersion": 1,
230
+ "packages": {
231
+ "@github/copilot-sdk": ["@github/copilot-sdk@1.0.16", "", {}, ""],
232
+ "koffi": ["koffi@3.2.1", "", {}, ""],
233
+ "koffi/nested": ["nested@1.0.0", "", {}, ""],
234
+ },
235
+ }`);
236
+ const modules = join(dir, 'node_modules');
237
+ for (const name of ['@github/copilot-sdk', '@github/copilot-darwin-arm64', 'koffi', 'detect-libc']) {
238
+ mkdirSync(join(modules, name), { recursive: true });
239
+ }
240
+ mkdirSync(join(modules, '.bin'));
241
+ symlinkSync(join(modules, '@github/copilot-darwin-arm64', 'copilot'), join(modules, '.bin', 'copilot-darwin-arm64'));
242
+
243
+ expect(sweepOrphanedModules(dir)).toEqual(['@github/copilot-darwin-arm64', 'detect-libc']);
244
+ expect(existsSync(join(modules, '@github/copilot-sdk'))).toBe(true);
245
+ expect(existsSync(join(modules, 'koffi'))).toBe(true);
246
+ expect(existsSync(join(modules, '@github/copilot-darwin-arm64'))).toBe(false);
247
+ expect(existsSync(join(modules, '.bin', 'copilot-darwin-arm64'))).toBe(false);
248
+ });
249
+
250
+ test('nothing is swept without a readable lockfile', () => {
251
+ const dir = stackDir({});
252
+ mkdirSync(join(dir, 'node_modules', 'anything'), { recursive: true });
253
+ expect(sweepOrphanedModules(dir)).toEqual([]);
254
+ expect(existsSync(join(dir, 'node_modules', 'anything'))).toBe(true);
255
+ });
256
+
257
+ test('a dir without dependencies has nothing stale', () => {
258
+ expect(staleStackDependencies(stackDir({}), knownStackEnginePackages())).toEqual([]);
259
+ expect(staleStackDependencies(mkdtempSync(join(tmpdir(), 'clopen-stack-')), knownStackEnginePackages())).toEqual([]);
260
+ });
261
+ });
262
+
263
+ describe('managed Chrome builds', () => {
264
+ const cacheDir = join(getClopenDir(), 'bin', 'chrome');
265
+
266
+ /** Lay out a fake build the way @puppeteer/browsers does. */
267
+ function fakeBuild(buildId: string): string {
268
+ const buildDir = join(cacheDir, `${process.platform === 'win32' ? 'win64' : process.platform === 'darwin' ? 'mac_arm' : 'linux'}-${buildId}`);
269
+ const executable = process.platform === 'darwin'
270
+ ? join(buildDir, 'chrome-mac-arm64', 'Google Chrome for Testing.app', 'Contents', 'MacOS', 'Google Chrome for Testing')
271
+ : process.platform === 'win32'
272
+ ? join(buildDir, 'chrome-win64', 'chrome.exe')
273
+ : join(buildDir, 'chrome-linux64', 'chrome');
274
+ mkdirSync(join(executable, '..'), { recursive: true });
275
+ writeFileSync(executable, '');
276
+ return executable;
277
+ }
278
+
279
+ test('the newest build wins and older ones are pruned', () => {
280
+ rmSync(cacheDir, { recursive: true, force: true });
281
+ try {
282
+ // Alphabetical order puts 99 last and 100 first; numeric order must not.
283
+ const older = fakeBuild('99.0.4844.51');
284
+ const newest = fakeBuild('141.0.7390.54');
285
+ const middle = fakeBuild('140.0.7339.80');
286
+ writeFileSync(join(cacheDir, '.metadata'), '{}');
287
+
288
+ expect(resolveClopenChromePath()).toBe(newest);
289
+
290
+ pruneStaleChromeBuilds();
291
+ expect(existsSync(newest)).toBe(true);
292
+ expect(existsSync(middle)).toBe(false);
293
+ expect(existsSync(older)).toBe(false);
294
+ expect(existsSync(join(cacheDir, '.metadata'))).toBe(true);
295
+ } finally {
296
+ rmSync(cacheDir, { recursive: true, force: true });
297
+ }
298
+ });
299
+ });
@@ -13,14 +13,15 @@
13
13
  * surface a copy-able command and a docs link, regardless of platform.
14
14
  */
15
15
 
16
- import { existsSync, readdirSync } from 'node:fs';
16
+ import { existsSync, readdirSync, rmSync } from 'node:fs';
17
17
  import { join } from 'node:path';
18
+ import { debug } from '$shared/utils/logger';
18
19
  import { isElevated } from '$backend/utils/privilege';
19
20
  import { getClopenDir } from '$backend/utils/paths';
20
21
  import { resolveBinary, resolveBinaryWithRefresh } from '$backend/utils/cli';
21
22
  import { resolveStaticCurlAsset } from '$backend/utils/static-curl';
22
23
  import { getStackEnginesDir, readEngineSdkVersion, getRequiredSdkVersion } from './sdk-loader';
23
- import { engineCliInstallArg, getEngineCliSpec, getRequiredEngineCliSpec, resolveEngineCli } from './engine-cli';
24
+ import { engineCliInstallArg, engineCliTrustedPackages, getEngineCliSpec, getRequiredEngineCliSpec, resolveEngineCli } from './engine-cli';
24
25
 
25
26
  export type ToolId = 'git' | 'claude' | 'opencode' | 'copilot' | 'codex' | 'qwen' | 'pi' | 'cline' | 'cursor' | 'chrome';
26
27
 
@@ -85,8 +86,8 @@ export interface ToolStatus {
85
86
  /**
86
87
  * Engine → the npm package(s) clopen must install to run that engine on demand.
87
88
  * The FIRST entry is the SDK clopen imports (used for install-state detection);
88
- * any extras pin something the SDK would otherwise float — a transitive CLI
89
- * (copilot), a sibling package (pi, cline), or an unmet PEER dependency.
89
+ * any extras pin something the SDK would otherwise float — a sibling package
90
+ * (pi, cline) or an unmet PEER dependency.
90
91
  *
91
92
  * Peers are the subtle case. `@anthropic-ai/claude-agent-sdk` declares
92
93
  * `@anthropic-ai/sdk`, `@modelcontextprotocol/sdk` and `zod` as peers and ships
@@ -112,14 +113,36 @@ export const ENGINE_PACKAGES: Partial<Record<ToolId, string[]>> = {
112
113
  'zod'
113
114
  ],
114
115
  opencode: ['@opencode-ai/sdk'],
115
- copilot: ['@github/copilot-sdk', '@github/copilot'],
116
+ copilot: ['@github/copilot-sdk'],
116
117
  codex: ['@openai/codex-sdk'],
117
118
  qwen: ['@qwen-code/sdk'],
118
- pi: ['@earendil-works/pi-coding-agent', '@earendil-works/pi-ai', '@earendil-works/pi-agent-core'],
119
+ // Pi's packages ship in lockstep but depend on each other with `^` ranges,
120
+ // and 1.0.1 dropped the shrinkwrap that used to hold them together — pin
121
+ // every sibling so a later Pi release can't mix into this install.
122
+ pi: [
123
+ '@earendil-works/pi-coding-agent',
124
+ '@earendil-works/pi-ai',
125
+ '@earendil-works/pi-agent-core',
126
+ '@earendil-works/pi-mcp',
127
+ '@earendil-works/pi-codemode',
128
+ '@earendil-works/pi-tui',
129
+ '@earendil-works/pi-telemetry',
130
+ '@earendil-works/chord'
131
+ ],
119
132
  cline: ['@cline/sdk', '@cline/agents'],
120
133
  cursor: ['@cursor/sdk'],
121
134
  };
122
135
 
136
+ /**
137
+ * Every package clopen may declare in the stack project: each engine's
138
+ * packages plus the CLI packages installed beside them. Anything else declared
139
+ * there was dropped from this list by a later clopen (Copilot's CLI, once the
140
+ * SDK began shipping its own runtime) and is pruned after the next install.
141
+ */
142
+ export function knownStackEnginePackages(): Set<string> {
143
+ return new Set([...Object.values(ENGINE_PACKAGES).flat(), ...engineCliTrustedPackages()]);
144
+ }
145
+
123
146
  function isEngineTool(tool: ToolId): boolean {
124
147
  return tool in ENGINE_PACKAGES;
125
148
  }
@@ -175,48 +198,85 @@ function detectMacPkgMgr(): 'brew' | null {
175
198
  // Chrome detection
176
199
  // ─────────────────────────────────────────────────────────────────────────────
177
200
 
201
+ /** Chrome for Testing builds live under `<cache>/chrome/<platform>-<buildId>/`. */
202
+ function getClopenChromeCacheDir(): string {
203
+ return join(getClopenDir(), 'bin', 'chrome');
204
+ }
205
+
206
+ function chromeExecutableIn(buildDir: string): string | null {
207
+ const candidates = process.platform === 'darwin'
208
+ ? ['chrome-mac-arm64', 'chrome-mac-x64', 'chrome-mac'].map(dir => join(
209
+ buildDir, dir,
210
+ 'Google Chrome for Testing.app',
211
+ 'Contents', 'MacOS', 'Google Chrome for Testing'
212
+ ))
213
+ : process.platform === 'win32'
214
+ ? ['chrome-win64', 'chrome-win'].map(dir => join(buildDir, dir, 'chrome.exe'))
215
+ : ['chrome-linux64', 'chrome-linux'].map(dir => join(buildDir, dir, 'chrome'));
216
+ return candidates.find(candidate => existsSync(candidate)) ?? null;
217
+ }
218
+
219
+ /** Numeric compare of dotted build ids (`141.0.7390.54`), highest first. */
220
+ function compareBuildIdsDesc(a: string, b: string): number {
221
+ const pa = a.split('.').map(Number);
222
+ const pb = b.split('.').map(Number);
223
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
224
+ const diff = (pb[i] || 0) - (pa[i] || 0);
225
+ if (diff !== 0) return diff;
226
+ }
227
+ return 0;
228
+ }
229
+
230
+ /**
231
+ * Installed Chrome for Testing builds, newest first. `chrome@stable` installs
232
+ * each new build BESIDE the old one, and directory order is alphabetical — so
233
+ * picking the first entry used to keep launching the oldest build after an
234
+ * update. `.metadata` and anything without a binary are skipped.
235
+ */
236
+ function listClopenChromeBuilds(): { dir: string; executable: string }[] {
237
+ const cacheDir = getClopenChromeCacheDir();
238
+ if (!existsSync(cacheDir)) return [];
239
+ try {
240
+ return readdirSync(cacheDir)
241
+ .filter(entry => entry.includes('-'))
242
+ .sort((a, b) => compareBuildIdsDesc(a.slice(a.indexOf('-') + 1), b.slice(b.indexOf('-') + 1)))
243
+ .flatMap(entry => {
244
+ const dir = join(cacheDir, entry);
245
+ const executable = chromeExecutableIn(dir);
246
+ return executable ? [{ dir, executable }] : [];
247
+ });
248
+ } catch {
249
+ return [];
250
+ }
251
+ }
252
+
178
253
  /**
179
- * Resolve the Chrome for Testing executable path under ~/.clopen/bin using
180
- * the @puppeteer/browsers cache layout: <cache>/chrome/<platform>-<buildId>/<archive>/<binary>.
181
- * Only macOS and Windows install Chrome this way — on Linux we install
182
- * Google Chrome via the distro package manager and skip this scan.
254
+ * Resolve the newest Chrome for Testing executable under ~/.clopen/bin (the
255
+ * @puppeteer/browsers cache layout). Only macOS and Windows install Chrome
256
+ * this way — on Linux we install Google Chrome via the distro package manager.
183
257
  */
184
258
  export function resolveClopenChromePath(): string | null {
185
- const cacheDir = join(getClopenDir(), 'bin', 'chrome');
186
- if (!existsSync(cacheDir)) return null;
259
+ return listClopenChromeBuilds()[0]?.executable ?? null;
260
+ }
187
261
 
188
- try {
189
- const entries = readdirSync(cacheDir);
190
- for (const entry of entries) {
191
- const buildDir = join(cacheDir, entry);
192
- if (process.platform === 'darwin') {
193
- const macDirs = ['chrome-mac-arm64', 'chrome-mac-x64', 'chrome-mac'];
194
- for (const dir of macDirs) {
195
- const candidate = join(
196
- buildDir, dir,
197
- 'Google Chrome for Testing.app',
198
- 'Contents', 'MacOS', 'Google Chrome for Testing'
199
- );
200
- if (existsSync(candidate)) return candidate;
201
- }
202
- } else if (process.platform === 'win32') {
203
- const winDirs = ['chrome-win64', 'chrome-win'];
204
- for (const dir of winDirs) {
205
- const candidate = join(buildDir, dir, 'chrome.exe');
206
- if (existsSync(candidate)) return candidate;
207
- }
208
- } else {
209
- const linuxDirs = ['chrome-linux64', 'chrome-linux'];
210
- for (const dir of linuxDirs) {
211
- const candidate = join(buildDir, dir, 'chrome');
212
- if (existsSync(candidate)) return candidate;
213
- }
214
- }
262
+ /**
263
+ * Remove every Chrome for Testing build but the newest. Each one is a few
264
+ * hundred MB, and an update never removes its predecessor.
265
+ *
266
+ * Runs at server startup, before anything launches Chrome: right after an
267
+ * update the old build may still be running, and deleting a live app bundle
268
+ * (macOS) or a locked executable (Windows) is not safe. A failed removal is
269
+ * left for the next start.
270
+ */
271
+ export function pruneStaleChromeBuilds(): void {
272
+ for (const { dir } of listClopenChromeBuilds().slice(1)) {
273
+ try {
274
+ rmSync(dir, { recursive: true, force: true });
275
+ debug.log('server', `Removed superseded Chrome build: ${dir}`);
276
+ } catch (error) {
277
+ debug.warn('server', `Could not remove superseded Chrome build ${dir}:`, error);
215
278
  }
216
- } catch {
217
- // Fall through
218
279
  }
219
- return null;
220
280
  }
221
281
 
222
282
  function detectSystemChrome(): string | null {
@@ -24,8 +24,8 @@ import { getCleanSpawnEnv } from '$backend/utils/env';
24
24
  import { refreshProcessPath } from '$backend/utils/path-enrich';
25
25
  import { ensureCurlAvailable } from '$backend/utils/static-curl';
26
26
  import type { Recipe, ToolId } from './install-recipes';
27
- import { resolveRecipe } from './install-recipes';
28
- import { ensureStackProject } from './stack-project';
27
+ import { knownStackEnginePackages, resolveRecipe } from './install-recipes';
28
+ import { ensureStackProject, staleStackDependencies, sweepOrphanedModules } from './stack-project';
29
29
  import { invalidateEngineCliCache } from './engine-cli';
30
30
 
31
31
  const RING_BUFFER_LINES = 10_000;
@@ -304,10 +304,64 @@ async function runInstall(session: Session, env: Record<string, string>): Promis
304
304
  if (exitCode !== 0) {
305
305
  const hint = explainFailure(exitCode, session.status === 'cancelled');
306
306
  if (hint) emitStream(session, 'stderr', hint + '\n');
307
+ } else if (recipe.cwd && session.status === 'running') {
308
+ await pruneStackDependencies(session, recipe.cwd, env);
307
309
  }
308
310
  finalizeSession(session, exitCode === 0 ? 'success' : 'failed', exitCode);
309
311
  }
310
312
 
313
+ /**
314
+ * Drop what the stack project no longer needs, in two steps:
315
+ * 1. `bun remove` packages it still declares but clopen no longer installs.
316
+ * Safe even while an older SDK still depends on one: bun keeps it as a
317
+ * transitive dependency until nothing needs it.
318
+ * 2. Sweep node_modules entries bun.lock no longer resolves — bun leaves
319
+ * those behind on its own (see `sweepOrphanedModules`).
320
+ *
321
+ * Runs only after a successful install, so the previous set stays usable if
322
+ * the install fails. A failed prune never fails the install that preceded it;
323
+ * the leftover is retried after the next one.
324
+ */
325
+ async function pruneStackDependencies(session: Session, cwd: string, env: Record<string, string>): Promise<void> {
326
+ // Another install in the same dir may have extracted packages its bun.lock
327
+ // write hasn't recorded yet; sweeping now would delete them. The last
328
+ // install to finish does the cleanup instead.
329
+ const sharing = [...sessions.values()].some(other =>
330
+ other !== session && other.status === 'running' && other.recipe.cwd === cwd
331
+ );
332
+ if (sharing) return;
333
+
334
+ const stale = staleStackDependencies(cwd, knownStackEnginePackages());
335
+ if (stale.length > 0) await removeStackDependencies(session, cwd, env, stale);
336
+
337
+ try {
338
+ const swept = sweepOrphanedModules(cwd);
339
+ if (swept.length > 0) emitStream(session, 'stdout', `» Removed leftover packages: ${swept.join(', ')}\n`);
340
+ } catch (err) {
341
+ emitStream(session, 'stderr', `Could not remove leftover packages: ${err instanceof Error ? err.message : String(err)}\n`);
342
+ }
343
+ }
344
+
345
+ async function removeStackDependencies(session: Session, cwd: string, env: Record<string, string>, stale: string[]): Promise<void> {
346
+ emitStream(session, 'stdout', `» Removing packages clopen no longer uses: ${stale.join(', ')}\n`);
347
+ try {
348
+ const proc = Bun.spawn(['bun', 'remove', ...stale], {
349
+ stdout: 'pipe',
350
+ stderr: 'pipe',
351
+ stdin: 'ignore',
352
+ env,
353
+ cwd
354
+ });
355
+ session.proc = proc;
356
+ const exitCode = await runStreamedProcess(session, proc);
357
+ if (exitCode !== 0) {
358
+ emitStream(session, 'stderr', `Could not remove unused packages (exit ${exitCode}); will retry after the next install.\n`);
359
+ }
360
+ } catch (err) {
361
+ emitStream(session, 'stderr', `Could not remove unused packages: ${err instanceof Error ? err.message : String(err)}\n`);
362
+ }
363
+ }
364
+
311
365
  /**
312
366
  * Owner id for installs clopen starts itself (startup repair), rather than a
313
367
  * user clicking Install. Sessions carry an owner so one admin cannot drive
@@ -17,7 +17,7 @@
17
17
  * written by an older clopen picks the field up on its next install.
18
18
  */
19
19
 
20
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
20
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
21
21
  import { join } from 'node:path';
22
22
  import { debug } from '$shared/utils/logger';
23
23
  import { engineCliTrustedPackages } from './engine-cli';
@@ -70,3 +70,73 @@ export function ensureStackProject(dir: string): void {
70
70
  writeFileSync(path, next);
71
71
  debug.log('engine', `Stack project package.json ${existing ? 'updated' : 'created'}: ${path}`);
72
72
  }
73
+
74
+ /**
75
+ * Dependencies declared in the stack project that clopen no longer installs.
76
+ * `bun add` only ever adds or re-pins, so a package dropped from the engine
77
+ * package list stays declared — and installed — forever without this.
78
+ */
79
+ export function staleStackDependencies(dir: string, known: Set<string>): string[] {
80
+ const existing = readExisting(join(dir, 'package.json'));
81
+ const deps = existing?.dependencies;
82
+ if (!deps || typeof deps !== 'object') return [];
83
+ return Object.keys(deps as Record<string, string>).filter(name => !known.has(name)).sort();
84
+ }
85
+
86
+ /** Top-level package names the stack project's bun.lock resolves, or null if unreadable. */
87
+ function lockedPackages(dir: string): Set<string> | null {
88
+ try {
89
+ const lock = Bun.JSONC.parse(readFileSync(join(dir, 'bun.lock'), 'utf8')) as { packages?: Record<string, unknown> };
90
+ if (!lock.packages || typeof lock.packages !== 'object') return null;
91
+ // Nested installs are keyed `parent/child` (or `@scope/parent/child`);
92
+ // only the hoisted top level maps onto `node_modules/<name>`.
93
+ return new Set(Object.keys(lock.packages).filter(key => key.split('/').length === (key.startsWith('@') ? 2 : 1)));
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Delete package directories under the stack's node_modules that bun.lock no
101
+ * longer resolves, plus `.bin` links left pointing at them.
102
+ *
103
+ * bun never removes them itself: dropping a package that carried per-platform
104
+ * optional dependencies leaves the platform package behind, even through
105
+ * `bun install --force`. Copilot's old CLI left ~330 MB this way. The lockfile
106
+ * is the authority — without a readable one nothing is touched.
107
+ */
108
+ export function sweepOrphanedModules(dir: string): string[] {
109
+ const locked = lockedPackages(dir);
110
+ const modules = join(dir, 'node_modules');
111
+ if (!locked || !existsSync(modules)) return [];
112
+
113
+ const installed: string[] = [];
114
+ for (const entry of readdirSync(modules)) {
115
+ if (entry.startsWith('.')) continue;
116
+ if (entry.startsWith('@')) {
117
+ for (const name of readdirSync(join(modules, entry))) installed.push(`${entry}/${name}`);
118
+ } else {
119
+ installed.push(entry);
120
+ }
121
+ }
122
+
123
+ const removed = installed.filter(name => !locked.has(name)).sort();
124
+ for (const name of removed) {
125
+ rmSync(join(modules, name), { recursive: true, force: true });
126
+ }
127
+
128
+ const bin = join(modules, '.bin');
129
+ if (removed.length > 0 && existsSync(bin)) {
130
+ for (const link of readdirSync(bin)) {
131
+ const path = join(bin, link);
132
+ try {
133
+ statSync(path);
134
+ } catch {
135
+ if (lstatSync(path).isSymbolicLink()) rmSync(path, { force: true });
136
+ }
137
+ }
138
+ }
139
+
140
+ if (removed.length > 0) debug.log('engine', `Swept orphaned stack packages: ${removed.join(', ')}`);
141
+ return removed;
142
+ }
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';
@@ -308,6 +309,10 @@ async function startServer() {
308
309
  // Shared with the clear-data handler so a DB wipe on the live process
309
310
  // restores them without a restart.
310
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();
311
316
  // Start expired session cleanup now that the database is ready
312
317
  sessionCleanupScheduler.start();
313
318
  uploadTempCleanup.start();
@@ -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';
@@ -250,6 +251,22 @@ export function getCopilotExternalMcpConfig(profileFilter?: Set<string>, project
250
251
  return out;
251
252
  }
252
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
+
253
270
  /** Qwen Code: `CLIMcpServerConfig` Streamable-HTTP (`httpUrl`) at the bridge proxy. */
254
271
  /** Cursor: `McpServerConfig` (http variant) pointing at the bridge proxy. */
255
272
  export function getCursorExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, CursorMcpServerConfig> {
@@ -335,6 +352,7 @@ export function getEngineConfigsForServer(slug: string): Record<string, unknown>
335
352
  codex: () => getCodexExternalMcpConfig() as Record<string, unknown>,
336
353
  copilot: () => getCopilotExternalMcpConfig() as Record<string, unknown>,
337
354
  cursor: () => getCursorExternalMcpConfig() as Record<string, unknown>,
355
+ pi: () => getPiExternalMcpConfig() as Record<string, unknown>,
338
356
  qwen: () => getQwenExternalMcpConfig() as Record<string, unknown>
339
357
  };
340
358
 
@@ -305,12 +305,12 @@ async function withProjectUpstreamClient<T>(projectId: string, name: string, fn:
305
305
  }
306
306
  }
307
307
 
308
- /** Sanitized tools of a trusted project server — for the in-process engines (Pi, Cline). */
308
+ /** Sanitized tools of a trusted project server — for the in-process engine (Cline). */
309
309
  export async function listProjectServerTools(projectId: string, name: string): Promise<Tool[]> {
310
310
  return withProjectUpstreamClient(projectId, name, async (client) => (await listAllToolsRaw(client)).map(sanitizeTool));
311
311
  }
312
312
 
313
- /** Call one tool of a trusted project server — for the in-process engines (Pi, Cline). */
313
+ /** Call one tool of a trusted project server — for the in-process engine (Cline). */
314
314
  export async function callProjectServerTool(projectId: string, name: string, toolName: string, args: unknown): Promise<unknown> {
315
315
  return withProjectUpstreamClient(projectId, name, async (client) =>
316
316
  client.request(