@myrialabs/clopen 0.4.2 → 0.4.4

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 (41) hide show
  1. package/README.md +2 -0
  2. package/backend/auth/permissions.ts +4 -1
  3. package/backend/chat/stream-manager.ts +7 -1
  4. package/backend/database/migrations/041_add_mcp_config_schema.ts +16 -0
  5. package/backend/database/migrations/042_add_mcp_oauth.ts +20 -0
  6. package/backend/database/migrations/043_relocate_engine_config_dirs.ts +71 -0
  7. package/backend/database/migrations/index.ts +21 -0
  8. package/backend/database/queries/index.ts +1 -1
  9. package/backend/database/queries/mcp-server-queries.ts +42 -2
  10. package/backend/engine/README.md +12 -8
  11. package/backend/engine/adapters/claude/environment.ts +3 -3
  12. package/backend/engine/adapters/codex/credential.ts +6 -2
  13. package/backend/engine/adapters/codex/stream.ts +6 -0
  14. package/backend/engine/adapters/copilot/stream.ts +5 -1
  15. package/backend/engine/adapters/opencode/server.ts +57 -21
  16. package/backend/engine/adapters/qwen/environment.ts +7 -0
  17. package/backend/engine/adapters/qwen/session-fork.ts +13 -1
  18. package/backend/engine/docs/adding-an-engine.md +8 -0
  19. package/backend/engine/docs/database.md +9 -6
  20. package/backend/engine/docs/lessons-learned.md +177 -16
  21. package/backend/git/git-service.ts +21 -2
  22. package/backend/index.ts +23 -1
  23. package/backend/mcp/README.md +81 -0
  24. package/backend/mcp/external/config.ts +70 -14
  25. package/backend/mcp/external/oauth.ts +329 -0
  26. package/backend/mcp/external/probe.ts +308 -0
  27. package/backend/mcp/external/registry-client.ts +8 -1
  28. package/backend/mcp/index.ts +12 -1
  29. package/backend/mcp/internal/config.ts +6 -0
  30. package/backend/mcp/internal/remote-server.test.ts +14 -0
  31. package/backend/mcp/internal/remote-server.ts +8 -0
  32. package/backend/mcp/internal/service-token.ts +51 -0
  33. package/backend/utils/paths.ts +16 -0
  34. package/backend/ws/engine/codex/accounts.ts +3 -0
  35. package/backend/ws/git/remote.ts +3 -2
  36. package/backend/ws/mcp/crud.ts +131 -12
  37. package/dist/assets/{main-qT_RedHf.js → main-AqTMkV9D.js} +272 -266
  38. package/dist/assets/main-DJf71Zum.css +1 -0
  39. package/dist/index.html +2 -2
  40. package/package.json +1 -1
  41. package/dist/assets/main-DKLZPDUN.css +0 -1
package/README.md CHANGED
@@ -136,6 +136,8 @@ bun run check # Type checking
136
136
 
137
137
  When running in development mode, Clopen uses `~/.clopen-dev` instead of `~/.clopen`, keeping dev data separate from any production instance.
138
138
 
139
+ Each AI engine's config/state (credentials, sessions, logs) is isolated under `~/.clopen/engine/<engine>/user/` rather than the engine's global location (`~/.codex`, `~/.copilot`, `~/.qwen`, the OpenCode XDG dirs), so Clopen never mixes with — or disturbs — your own standalone CLI usage.
140
+
139
141
  See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines and [DECISIONS.md](DECISIONS.md) for architectural decisions.
140
142
 
141
143
  ---
@@ -108,7 +108,10 @@ export const ADMIN_ONLY_ROUTES = new Set([
108
108
  'mcp:install',
109
109
  'mcp:toggle',
110
110
  'mcp:update-config',
111
- 'mcp:uninstall'
111
+ 'mcp:uninstall',
112
+ 'mcp:status',
113
+ 'mcp:oauth-start',
114
+ 'mcp:oauth-complete'
112
115
  ]);
113
116
 
114
117
  /**
@@ -35,7 +35,7 @@ import type { DatabaseMessage } from '$shared/types/database/schema';
35
35
  import { getProjectEngine, initializeProjectEngine } from '../engine';
36
36
  import { messageQueries, sessionQueries } from '../database/queries';
37
37
  import { snapshotService } from '../snapshot/snapshot-service';
38
- import { projectContextService } from '../mcp';
38
+ import { projectContextService, refreshExpiringExternalOAuth } from '../mcp';
39
39
  import { browserMcpControl } from '../preview';
40
40
  import { extractMessageText } from '../snapshot/helpers';
41
41
  import { debug } from '$shared/utils/logger';
@@ -608,6 +608,12 @@ class StreamManager extends EventEmitter {
608
608
  // large repo could begin editing while the baseline scan is still running.
609
609
  if (baselineInitPromise) await baselineInitPromise;
610
610
 
611
+ // Refresh any near-expiry managed MCP OAuth tokens so the engine's
612
+ // (synchronous) MCP config builders below inject a still-valid bearer.
613
+ await refreshExpiringExternalOAuth().catch(error =>
614
+ debug.warn('chat', 'MCP OAuth refresh failed:', error)
615
+ );
616
+
611
617
  // Stream EngineOutput events through the engine adapter
612
618
  const streamIterable = engine.streamQuery({
613
619
  projectPath,
@@ -0,0 +1,16 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Add config_schema column to mcp_servers (UI field metadata)';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Adding config_schema column to mcp_servers...');
8
+ db.exec(`ALTER TABLE mcp_servers ADD COLUMN config_schema TEXT NOT NULL DEFAULT '[]'`);
9
+ debug.log('migration', 'config_schema column added');
10
+ };
11
+
12
+ export const down = (db: DatabaseConnection): void => {
13
+ debug.log('migration', 'Dropping config_schema column from mcp_servers...');
14
+ db.exec('ALTER TABLE mcp_servers DROP COLUMN config_schema');
15
+ debug.log('migration', 'config_schema column dropped');
16
+ };
@@ -0,0 +1,20 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Add oauth column to mcp_servers (centralized OAuth client registration + tokens)';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Adding oauth column to mcp_servers...');
8
+ // Holds the JSON OAuth state Clopen manages on the user's behalf: dynamic
9
+ // client registration + access/refresh tokens. NULL = no OAuth. Kept separate
10
+ // from the user-editable `headers` so a refreshed token never clobbers manual
11
+ // config, and so every engine can be handed `Authorization: Bearer <token>`.
12
+ db.exec(`ALTER TABLE mcp_servers ADD COLUMN oauth TEXT`);
13
+ debug.log('migration', 'oauth column added');
14
+ };
15
+
16
+ export const down = (db: DatabaseConnection): void => {
17
+ debug.log('migration', 'Dropping oauth column from mcp_servers...');
18
+ db.exec('ALTER TABLE mcp_servers DROP COLUMN oauth');
19
+ debug.log('migration', 'oauth column dropped');
20
+ };
@@ -0,0 +1,71 @@
1
+ import fs from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import type { DatabaseConnection } from '$shared/types/database/connection';
4
+ import { getClopenDir } from '../../utils/paths';
5
+ import { debug } from '$shared/utils/logger';
6
+
7
+ export const description = 'Relocate per-engine config dirs from {clopenDir}/{engine}/user to {clopenDir}/engine/{engine}/user';
8
+
9
+ /**
10
+ * Earlier builds isolated each engine at `{clopenDir}/{engine}/user/`; the
11
+ * layout has since moved under an `engine/` parent: `{clopenDir}/engine/{engine}/user/`
12
+ * (see `getEngineUserConfigDir`). This migration relocates any directory the
13
+ * previous build already created so existing sessions/credentials carry over.
14
+ *
15
+ * Safe by construction: it only ever touches `{clopenDir}/{engine}/user/`,
16
+ * which is a path **Clopen itself created** — never the engine's global home
17
+ * (`~/.codex`, `~/.copilot`, …). A user's standalone CLI usage is untouched.
18
+ *
19
+ * Filesystem-only + idempotent: if the new dir already exists (current build
20
+ * ran first) the old one is left in place rather than clobbering live data.
21
+ */
22
+
23
+ const ENGINES = ['claude', 'codex', 'copilot', 'qwen', 'opencode'] as const;
24
+
25
+ export const up = (db: DatabaseConnection): void => {
26
+ const clopenDir = getClopenDir();
27
+ const engineParent = join(clopenDir, 'engine');
28
+
29
+ for (const engine of ENGINES) {
30
+ const oldUserDir = join(clopenDir, engine, 'user'); // {clopenDir}/{engine}/user
31
+ const newUserDir = join(engineParent, engine, 'user'); // {clopenDir}/engine/{engine}/user
32
+
33
+ try {
34
+ if (!fs.existsSync(oldUserDir)) continue;
35
+
36
+ if (fs.existsSync(newUserDir)) {
37
+ debug.warn('migration', `engine-dir: ${newUserDir} already exists — leaving ${oldUserDir} in place (no clobber)`);
38
+ continue;
39
+ }
40
+
41
+ fs.mkdirSync(join(engineParent, engine), { recursive: true });
42
+ fs.renameSync(oldUserDir, newUserDir);
43
+ debug.log('migration', `engine-dir: moved ${oldUserDir} → ${newUserDir}`);
44
+
45
+ // Remove the now-empty {clopenDir}/{engine} parent left behind.
46
+ try {
47
+ const oldParent = join(clopenDir, engine);
48
+ if (fs.readdirSync(oldParent).length === 0) fs.rmdirSync(oldParent);
49
+ } catch {
50
+ // Parent not empty or already gone — leave it.
51
+ }
52
+ } catch (err) {
53
+ // Non-fatal: the engine just starts fresh at the new dir on next use.
54
+ debug.warn('migration', `engine-dir: failed to move ${oldUserDir} → ${newUserDir}: ${err instanceof Error ? err.message : String(err)}`);
55
+ }
56
+ }
57
+
58
+ // Drop any persisted OpenCode server pointer: a cached URL/datadir from the
59
+ // pre-move location would otherwise be reuse-checked against the new dir.
60
+ // Clearing it forces a clean re-spawn into the relocated data dir.
61
+ try {
62
+ db.exec(`DELETE FROM settings WHERE key IN ('opencode.server.url', 'opencode.server.datadir')`);
63
+ } catch (err) {
64
+ debug.warn('migration', `engine-dir: failed to clear opencode server settings: ${err instanceof Error ? err.message : String(err)}`);
65
+ }
66
+ };
67
+
68
+ export const down = (): void => {
69
+ // No-op. Directory relocation is forward-only and data-preserving; reversing
70
+ // it would re-fragment state across the old/new layouts for no benefit.
71
+ };
@@ -39,6 +39,9 @@ import * as migration037 from './037_repair_auth_audit_log_schema';
39
39
  import * as migration038 from './038_add_workspace_state_to_user_projects';
40
40
  import * as migration039 from './039_create_file_audit_log';
41
41
  import * as migration040 from './040_create_mcp_servers_table';
42
+ import * as migration041 from './041_add_mcp_config_schema';
43
+ import * as migration042 from './042_add_mcp_oauth';
44
+ import * as migration043 from './043_relocate_engine_config_dirs';
42
45
 
43
46
  // Export all migrations in order
44
47
  export const migrations = [
@@ -281,6 +284,24 @@ export const migrations = [
281
284
  description: migration040.description,
282
285
  up: migration040.up,
283
286
  down: migration040.down
287
+ },
288
+ {
289
+ id: '041',
290
+ description: migration041.description,
291
+ up: migration041.up,
292
+ down: migration041.down
293
+ },
294
+ {
295
+ id: '042',
296
+ description: migration042.description,
297
+ up: migration042.up,
298
+ down: migration042.down
299
+ },
300
+ {
301
+ id: '043',
302
+ description: migration043.description,
303
+ up: migration043.up,
304
+ down: migration043.down
284
305
  }
285
306
  ];
286
307
 
@@ -13,4 +13,4 @@ export { dbClientQueryHistoryQueries } from './db-client-query-history-queries';
13
13
  export { auditLogQueries } from './audit-log-queries';
14
14
  export { fileAuditLogQueries } from './file-audit-log-queries';
15
15
  export { mcpServerQueries } from './mcp-server-queries';
16
- export type { McpServerRow, McpServerInput, McpTransport, McpSource } from './mcp-server-queries';
16
+ export type { McpServerRow, McpServerInput, McpTransport, McpSource, McpConfigField } from './mcp-server-queries';
@@ -18,6 +18,21 @@ import { getDatabase } from '../index';
18
18
  export type McpTransport = 'stdio' | 'http' | 'sse';
19
19
  export type McpSource = 'registry' | 'custom' | 'internal';
20
20
 
21
+ /**
22
+ * A single configurable field, captured from the registry catalog at install
23
+ * time so the "Configure" UI can render the same labelled fields it showed at
24
+ * install. Purely UI metadata — engines read the actual values from
25
+ * `env`/`headers`, never from here. `kind` decides whether the value lands in
26
+ * the env map (stdio) or the headers map (remote auth).
27
+ */
28
+ export interface McpConfigField {
29
+ name: string;
30
+ kind: 'env' | 'header';
31
+ description?: string;
32
+ isRequired: boolean;
33
+ isSecret: boolean;
34
+ }
35
+
21
36
  /** Raw DB row. */
22
37
  export interface McpServerRow {
23
38
  id: number;
@@ -32,6 +47,9 @@ export interface McpServerRow {
32
47
  env: string;
33
48
  url: string | null;
34
49
  headers: string;
50
+ config_schema: string;
51
+ /** JSON OAuth state Clopen manages (registration + tokens), or null. */
52
+ oauth: string | null;
35
53
  source: McpSource;
36
54
  is_enabled: number;
37
55
  created_at: string;
@@ -49,6 +67,7 @@ export interface McpServerInput {
49
67
  env?: Record<string, string>;
50
68
  url?: string | null;
51
69
  headers?: Record<string, string>;
70
+ configSchema?: McpConfigField[];
52
71
  source?: McpSource;
53
72
  }
54
73
 
@@ -82,8 +101,8 @@ export const mcpServerQueries = {
82
101
  const db = getDatabase();
83
102
  const result = db.prepare(
84
103
  `INSERT INTO mcp_servers
85
- (slug, name, description, registry_name, version, transport, command, args, env, url, headers, source)
86
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
104
+ (slug, name, description, registry_name, version, transport, command, args, env, url, headers, config_schema, source)
105
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
87
106
  ).run(
88
107
  input.slug,
89
108
  input.name,
@@ -96,6 +115,7 @@ export const mcpServerQueries = {
96
115
  JSON.stringify(input.env ?? {}),
97
116
  input.url ?? null,
98
117
  JSON.stringify(input.headers ?? {}),
118
+ JSON.stringify(input.configSchema ?? []),
99
119
  input.source ?? 'registry'
100
120
  ) as { lastInsertRowid: number | bigint };
101
121
  const id = Number(result.lastInsertRowid);
@@ -123,6 +143,26 @@ export const mcpServerQueries = {
123
143
  );
124
144
  },
125
145
 
146
+ /**
147
+ * Update a stdio server's command + args. Lets users repair incomplete
148
+ * registry metadata (e.g. a CLI that needs a `mcp` subcommand to start) that
149
+ * would otherwise leave the server permanently unreachable.
150
+ */
151
+ updateCommand(id: number, command: string, args: string[]): void {
152
+ const db = getDatabase();
153
+ db.prepare(`UPDATE mcp_servers SET command = ?, args = ? WHERE id = ?`).run(
154
+ command,
155
+ JSON.stringify(args),
156
+ id
157
+ );
158
+ },
159
+
160
+ /** Store (or clear with null) the managed OAuth state JSON for a server. */
161
+ setOAuth(id: number, oauth: string | null): void {
162
+ const db = getDatabase();
163
+ db.prepare(`UPDATE mcp_servers SET oauth = ? WHERE id = ?`).run(oauth, id);
164
+ },
165
+
126
166
  remove(id: number): void {
127
167
  const db = getDatabase();
128
168
  db.prepare(`DELETE FROM mcp_servers WHERE id = ?`).run(id);
@@ -105,14 +105,18 @@ Three key rules that **every** layer upholds:
105
105
  > URL** by adding a sibling `getXxxMcpConfig()` helper in
106
106
  > `backend/mcp/internal/config.ts`. Do **NOT** propose a "new MCP bridge",
107
107
  > "per-engine MCP server", or "per-stream MCP path". See §9.12.
108
- > 2. **Shared CLI dotfiles are swapped from DB, not isolated.** When a CLI
109
- > stores its credentials in a known location (e.g. `~/.codex/auth.json`),
110
- > the multi-account approach is to snapshot that file into the DB on
111
- > login and write the chosen account's snapshot back on switch. Do
112
- > **NOT** propose per-account isolated home directories
113
- > (`CODEX_HOME=/foo/account-1/`); that path complicates session-state
114
- > sharing, token refresh persistence, and user-level config inheritance.
115
- > See §9.13.
108
+ > 2. **Engine home dirs are isolated per-engine (Clopen vs. global), but
109
+ > multi-account stays DB-swap.** Two different axes — don't conflate them:
110
+ > - **Clopen vs. the user's global CLI usage:** every engine's home/config
111
+ > is redirected to `{clopenDir}/engine/{engine}/user/` via that engine's env
112
+ > var (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `COPILOT_HOME` via
113
+ > `baseDirectory`, `QWEN_RUNTIME_DIR`, `XDG_*` for OpenCode) so Clopen
114
+ > never touches `~/.codex`, `~/.copilot`, … See §9.19.
115
+ > - **Multiple accounts *within* Clopen:** still the auth-blob swap — one
116
+ > shared dotfile inside that isolated home, snapshotted to/from the DB on
117
+ > login/switch. Do **NOT** propose **per-account** home dirs
118
+ > (`CODEX_HOME=/foo/account-1/`); that splits session-state, breaks
119
+ > fork-by-copy, and loses token-refresh persistence. See §9.13.
116
120
 
117
121
  ---
118
122
 
@@ -10,17 +10,17 @@
10
10
  import { join } from 'path';
11
11
  import { engineQueries } from '../../../database/queries';
12
12
  import { debug } from '$shared/utils/logger';
13
- import { getCleanSpawnEnv, getClopenDir } from '../../../utils/index.js';
13
+ import { getCleanSpawnEnv, getEngineUserConfigDir } from '../../../utils/index.js';
14
14
 
15
15
  let _ready = false;
16
16
  let _initPromise: Promise<void> | null = null;
17
17
  let _envOverrides: Record<string, string> = {};
18
18
 
19
19
  /**
20
- * Returns the isolated Claude config directory under {clopenDir}/claude/user/
20
+ * Returns the isolated Claude config directory under {clopenDir}/engine/claude/user/
21
21
  */
22
22
  export function getClaudeUserConfigDir(): string {
23
- return join(getClopenDir(), 'claude', 'user');
23
+ return getEngineUserConfigDir('claude');
24
24
  }
25
25
 
26
26
  /**
@@ -19,11 +19,15 @@
19
19
 
20
20
  import fs from 'node:fs';
21
21
  import path from 'node:path';
22
- import os from 'node:os';
23
22
  import { engineQueries, type EngineAccount } from '../../../database/queries/engine-queries';
23
+ import { getEngineUserConfigDir } from '$backend/utils/paths';
24
24
  import { debug } from '$shared/utils/logger';
25
25
 
26
- const CODEX_HOME = path.join(os.homedir(), '.codex');
26
+ // Isolate Codex state (auth.json, sessions) to {clopenDir}/engine/codex/user/ instead
27
+ // of the shared ~/.codex so Clopen never mixes with the user's own Codex CLI
28
+ // usage. The same path is forwarded to every spawned `codex` subprocess via the
29
+ // CODEX_HOME env var (see ./stream.ts and ws/engine/codex/accounts.ts).
30
+ const CODEX_HOME = getEngineUserConfigDir('codex');
27
31
  const AUTH_JSON_PATH = path.join(CODEX_HOME, 'auth.json');
28
32
  const AUTH_JSON_TMP_PATH = path.join(CODEX_HOME, 'auth.json.tmp');
29
33
 
@@ -26,6 +26,7 @@ import { extractJson } from '../../structured-helpers';
26
26
  import { engineQueries } from '$backend/database/queries/engine-queries';
27
27
  import { resolveOsPath } from '$backend/utils/paths';
28
28
  import { resolveBinary } from '$backend/utils/cli';
29
+ import { getCleanSpawnEnv } from '$backend/utils/index.js';
29
30
  import { getCodexMcpConfig } from '../../../mcp';
30
31
  import { CODEX_MODELS } from './models';
31
32
  import { debug } from '$shared/utils/logger';
@@ -44,6 +45,7 @@ import {
44
45
  parseCodexCredential,
45
46
  applyAccountAuth,
46
47
  snapshotAuthJsonToActiveAccount,
48
+ getCodexHomeDir,
47
49
  } from './credential';
48
50
  import { forkCodexSessionState, sessionStateExists } from './session-fork';
49
51
  import path from 'node:path';
@@ -103,9 +105,13 @@ export class CodexEngine implements AIEngine {
103
105
  // `workspace-write` sandbox relies on platform primitives (Seatbelt on
104
106
  // macOS, Landlock on Linux) that are absent on Windows, where the CLI
105
107
  // degrades to read-only — using full-access keeps behaviour consistent.
108
+ // The SDK does NOT inherit process.env when `env` is provided, so we
109
+ // pass the full clean spawn env and layer CODEX_HOME on top to redirect
110
+ // the subprocess's auth.json + sessions into Clopen's isolated dir.
106
111
  this.codex = new Codex({
107
112
  apiKey: credential.kind === 'api_key' ? credential.apiKey : undefined,
108
113
  ...(codexBinary ? { codexPathOverride: codexBinary } : {}),
114
+ env: { ...getCleanSpawnEnv(), CODEX_HOME: getCodexHomeDir() },
109
115
  config: {
110
116
  show_raw_agent_reasoning: true,
111
117
  ...(Object.keys(mcpConfig).length > 0 ? { mcp_servers: mcpConfig } : {}),
@@ -18,7 +18,7 @@ import type { EngineOutput, EngineModel } from '$shared/types/unified';
18
18
  import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
19
19
  import { buildJsonPrompt, extractJson } from '../../structured-helpers';
20
20
  import { engineQueries } from '$backend/database/queries/engine-queries';
21
- import { resolveOsPath } from '$backend/utils/paths';
21
+ import { resolveOsPath, getEngineUserConfigDir } from '$backend/utils/paths';
22
22
  import { debug } from '$shared/utils/logger';
23
23
  import { getCopilotMcpConfig } from '../../../mcp';
24
24
  import { handleStreamError, buildSessionError } from './error-handler';
@@ -123,6 +123,10 @@ export class CopilotEngine implements AIEngine {
123
123
  this.client = new CopilotClient({
124
124
  gitHubToken: account.credential,
125
125
  useLoggedInUser: false,
126
+ // Isolate Copilot state (session-state, session-store.db, logs) to
127
+ // {clopenDir}/engine/copilot/user/ instead of the shared ~/.copilot. The SDK
128
+ // forwards this as COPILOT_HOME to the spawned runtime.
129
+ baseDirectory: getEngineUserConfigDir('copilot'),
126
130
  });
127
131
 
128
132
  await this.client.start();
@@ -17,10 +17,16 @@ import { getOpenCodeMcpConfig } from '../../../mcp';
17
17
  import { settingsQueries } from '../../../database/queries';
18
18
  import { generateOpenCodeProviderConfig } from './config';
19
19
  import { resolveBinaryWithRefresh } from '$backend/utils/cli';
20
+ import { getEngineUserConfigDir } from '$backend/utils/paths';
20
21
  import { debug } from '$shared/utils/logger';
21
22
 
22
23
  const OPENCODE_HOST = '127.0.0.1';
23
24
  const DB_KEY = 'opencode.server.url';
25
+ // The isolated data dir the persisted server was spawned with. A reused server
26
+ // inherits the env it was spawned with, so if our target dir has changed (code
27
+ // update that moves the isolation path, or a server left over from before
28
+ // isolation existed) we must NOT reuse it — respawn into the right dir instead.
29
+ const DB_KEY_DATADIR = 'opencode.server.datadir';
24
30
  const HEALTH_TIMEOUT = 1500;
25
31
  const SERVER_START_TIMEOUT = 30_000; // 30s — generous for slow devices
26
32
 
@@ -76,6 +82,7 @@ export async function ensureClient(): Promise<OpencodeClient> {
76
82
  // Do NOT clear initPromise — another caller may have started one
77
83
  debug.log('engine', 'Open Code server disconnected, recovering...');
78
84
  settingsQueries.delete(DB_KEY);
85
+ settingsQueries.delete(DB_KEY_DATADIR);
79
86
  clearClientState();
80
87
  }
81
88
 
@@ -99,12 +106,24 @@ export async function ensureClient(): Promise<OpencodeClient> {
99
106
  async function init(): Promise<void> {
100
107
  debug.log('engine', 'Initializing Open Code client...');
101
108
 
102
- // 1. Try to reuse an existing server persisted in DB
109
+ // Isolate OpenCode's state (opencode.db, snapshots, logs, config) to
110
+ // {clopenDir}/engine/opencode/user/ instead of the shared XDG dirs
111
+ // (~/.local/share/opencode, ~/.config/opencode) so Clopen never mixes with
112
+ // the user's own OpenCode CLI usage. OpenCode follows the XDG base-dir spec
113
+ // and appends `/opencode` to each base. Credentials + MCP config are injected
114
+ // via OPENCODE_CONFIG_CONTENT, so no auth file needs to carry over.
115
+ const opencodeUserDir = getEngineUserConfigDir('opencode');
116
+
117
+ // 1. Try to reuse an existing server persisted in DB — but only if it was
118
+ // spawned with the SAME isolated data dir we'd use now. A mismatch means the
119
+ // stored server points at a stale location (pre-isolation, or a moved path);
120
+ // reusing it would silently keep writing to the wrong dir.
103
121
  const stored = settingsQueries.get(DB_KEY);
122
+ const storedDataDir = settingsQueries.get(DB_KEY_DATADIR)?.value;
104
123
  if (stored?.value) {
105
124
  debug.log('engine', `Found stored Open Code server: ${stored.value}, checking...`);
106
125
 
107
- if (await isServerAlive(stored.value)) {
126
+ if (storedDataDir === opencodeUserDir && await isServerAlive(stored.value)) {
108
127
  const { createOpencodeClient } = await import('@opencode-ai/sdk');
109
128
  client = createOpencodeClient({ baseUrl: stored.value });
110
129
  serverHandle = { url: stored.value, close() {} };
@@ -114,8 +133,13 @@ async function init(): Promise<void> {
114
133
  return;
115
134
  }
116
135
 
117
- debug.log('engine', 'Stored server not responding, spawning new one...');
136
+ if (storedDataDir !== opencodeUserDir) {
137
+ debug.log('engine', `Stored Open Code server data dir mismatch (${storedDataDir ?? 'unknown'} ≠ ${opencodeUserDir}), spawning fresh...`);
138
+ } else {
139
+ debug.log('engine', 'Stored server not responding, spawning new one...');
140
+ }
118
141
  settingsQueries.delete(DB_KEY);
142
+ settingsQueries.delete(DB_KEY_DATADIR);
119
143
  }
120
144
 
121
145
  // 2. Spawn a new server via Bun.spawn with absolute binary path.
@@ -125,25 +149,30 @@ async function init(): Promise<void> {
125
149
  if (!command) throw new Error('opencode binary not found on PATH');
126
150
  const args = [command, 'serve', `--hostname=${OPENCODE_HOST}`, '--port=0'];
127
151
 
128
- // Build MCP config — but only inject if the MCP endpoint is actually reachable.
129
- // The opencode binary may initialize MCP connections synchronously before printing
130
- // "opencode server listening", so an unreachable/slow MCP endpoint can stall startup.
131
- let mcpConfig = getOpenCodeMcpConfig();
152
+ // Build MCP config — but only inject remote servers whose endpoint is
153
+ // actually reachable. The opencode binary may initialize MCP connections
154
+ // synchronously before printing "opencode server listening", so an
155
+ // unreachable/slow remote endpoint can stall startup. Drop ONLY the
156
+ // unreachable remote entries; stdio/local servers (no `url`) are independent
157
+ // of the HTTP bridge and must always survive — they were previously thrown
158
+ // out together with the bridge when it wasn't reachable yet.
159
+ const mcpConfig = getOpenCodeMcpConfig();
132
160
  if (Object.keys(mcpConfig).length > 0) {
133
- const mcpUrls = Object.values(mcpConfig).map(c => (c as any).url).filter(Boolean);
134
- const reachable = await Promise.all(
135
- mcpUrls.map(url => isServerAlive(url))
161
+ const entries = Object.entries(mcpConfig);
162
+ const reachability = await Promise.all(
163
+ entries.map(([, c]) => {
164
+ const url = (c as any).url as string | undefined;
165
+ return url ? isServerAlive(url) : Promise.resolve(true);
166
+ })
136
167
  );
137
-
138
- if (reachable.every(Boolean)) {
139
- debug.log('engine', `Open Code server: injecting ${Object.keys(mcpConfig).length} MCP server(s)`);
140
- for (const [name, config] of Object.entries(mcpConfig)) {
141
- debug.log('engine', ` → ${name}: ${config.type} (${(config as any).url || (config as any).command?.join(' ')})`);
168
+ entries.forEach(([name, config], i) => {
169
+ if (reachability[i]) {
170
+ debug.log('engine', `Open Code server: injecting MCP server → ${name}: ${config.type} (${(config as any).url || (config as any).command?.join(' ')})`);
171
+ } else {
172
+ debug.warn('engine', `Open Code server: MCP endpoint for "${name}" not reachable, skipping it`);
173
+ delete mcpConfig[name];
142
174
  }
143
- } else {
144
- debug.warn('engine', 'Open Code server: MCP endpoint not reachable, starting without MCP');
145
- mcpConfig = {};
146
- }
175
+ });
147
176
  }
148
177
 
149
178
  // Build provider config from DB (enabled providers + env vars)
@@ -167,7 +196,7 @@ async function init(): Promise<void> {
167
196
  ? JSON.stringify(mergedConfig)
168
197
  : '{}';
169
198
 
170
- debug.log('engine', `Spawning: ${args.join(' ')}`);
199
+ debug.log('engine', `Spawning: ${args.join(' ')} (data dir: ${opencodeUserDir})`);
171
200
 
172
201
  const proc = Bun.spawn(args, {
173
202
  stdout: 'pipe',
@@ -175,6 +204,10 @@ async function init(): Promise<void> {
175
204
  env: {
176
205
  ...process.env,
177
206
  ...providerConfig.envVars,
207
+ XDG_DATA_HOME: opencodeUserDir,
208
+ XDG_CONFIG_HOME: opencodeUserDir,
209
+ XDG_STATE_HOME: opencodeUserDir,
210
+ XDG_CACHE_HOME: opencodeUserDir,
178
211
  OPENCODE_CONFIG_CONTENT: configContent,
179
212
  },
180
213
  });
@@ -238,7 +271,8 @@ async function init(): Promise<void> {
238
271
  ready = true;
239
272
 
240
273
  settingsQueries.set(DB_KEY, url);
241
- debug.log('engine', `Open Code client ready (server: ${url})`);
274
+ settingsQueries.set(DB_KEY_DATADIR, opencodeUserDir);
275
+ debug.log('engine', `Open Code client ready (server: ${url}, data dir: ${opencodeUserDir})`);
242
276
  }
243
277
 
244
278
  export function getClient(): OpencodeClient | null {
@@ -280,6 +314,7 @@ export async function disposeOpenCodeClient(forRestart = false): Promise<void> {
280
314
  }
281
315
  }
282
316
  settingsQueries.delete(DB_KEY);
317
+ settingsQueries.delete(DB_KEY_DATADIR);
283
318
  } catch (error) {
284
319
  debug.error('engine', 'Error stopping Open Code server:', error);
285
320
  }
@@ -287,6 +322,7 @@ export async function disposeOpenCodeClient(forRestart = false): Promise<void> {
287
322
  } else if (forRestart) {
288
323
  // No active handle but forRestart requested — ensure DB is clean
289
324
  settingsQueries.delete(DB_KEY);
325
+ settingsQueries.delete(DB_KEY_DATADIR);
290
326
  }
291
327
 
292
328
  clearClientState();
@@ -21,6 +21,7 @@ import type { EngineAccount } from '$backend/database/queries/engine-queries';
21
21
  import { getCleanSpawnEnv } from '$backend/utils/index.js';
22
22
  import { debug } from '$shared/utils/logger';
23
23
  import { parseQwenCredential, resolveQwenBaseUrl } from './credential';
24
+ import { getQwenRuntimeDir } from './session-fork';
24
25
 
25
26
  export interface QwenEnvResolution {
26
27
  env: Record<string, string>;
@@ -68,6 +69,12 @@ export function getEngineEnv(accountId?: number): QwenEnvResolution | null {
68
69
 
69
70
  env['OPENAI_API_KEY'] = credential.apiKey;
70
71
  env['OPENAI_BASE_URL'] = baseUrl;
72
+ // Isolate Qwen's runtime output (chats/sessions, history, logs, tmp) to
73
+ // {clopenDir}/engine/qwen/user/ instead of the shared ~/.qwen. Mirrors the path
74
+ // the fork helper reads from (see ./session-fork.ts). The CLI's global
75
+ // settings.json stays in ~/.qwen — there is no env override for it — but
76
+ // Clopen uses paste-token auth so that file is irrelevant here.
77
+ env['QWEN_RUNTIME_DIR'] = getQwenRuntimeDir();
71
78
  // Strip any inherited Qwen OAuth hints — if the host shell exports them
72
79
  // the bundled CLI prefers the OAuth path even when API-key env vars are
73
80
  // present, surfacing the "OAuth free tier discontinued" error.
@@ -34,9 +34,21 @@
34
34
  import fs from 'node:fs';
35
35
  import path from 'node:path';
36
36
  import os from 'node:os';
37
+ import { getEngineUserConfigDir } from '$backend/utils/paths';
37
38
  import { debug } from '$shared/utils/logger';
38
39
 
39
- const QWEN_PROJECTS_DIR = path.join(os.homedir(), '.qwen', 'projects');
40
+ /**
41
+ * Qwen's runtime output base, forwarded to the CLI via `QWEN_RUNTIME_DIR`
42
+ * (see ./environment.ts). The bundled CLI writes chats under
43
+ * `<runtimeBase>/projects/<sanitized-cwd>/chats/` (Storage.getProjectDir →
44
+ * getRuntimeBaseDir), so this helper must resolve to the SAME base the env
45
+ * var sets or the fork would land in a directory the CLI never reads.
46
+ */
47
+ export function getQwenRuntimeDir(): string {
48
+ return getEngineUserConfigDir('qwen');
49
+ }
50
+
51
+ const QWEN_PROJECTS_DIR = path.join(getQwenRuntimeDir(), 'projects');
40
52
 
41
53
  /**
42
54
  * Mirror of `sanitizeCwd` in @qwen-code/sdk's bundled CLI
@@ -52,6 +52,14 @@ mandatory files; optional files use the canonical names from §2.6.
52
52
  - [ ] `backend/engine/index.ts`: import + add a case in
53
53
  `createEngine(type)`. If there is a shared subprocess, call
54
54
  `disposeXxxClient()` from `disposeAllProjectEngines()`.
55
+ - [ ] MCP config (if the SDK accepts a streamable-HTTP MCP URL):
56
+ - [ ] Internal bridge — add `getXxxMcpConfig()` in
57
+ `backend/mcp/internal/config.ts` (reuse `clopen-mcp`; see §9.12).
58
+ - [ ] External servers — add `getXxxExternalMcpConfig()` in
59
+ `backend/mcp/external/config.ts` and **forward `headers`** so the
60
+ centralized OAuth bearer reaches the engine. Use the SDK's real
61
+ header field — **Codex uses `http_headers`, not `bearer_token`**.
62
+ See §9.18 and `backend/mcp/README.md`.
55
63
 
56
64
  ### Stage 3 — Database (if a default provider needs to be seeded)
57
65