@myrialabs/clopen 0.3.22 → 0.4.1

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 (61) hide show
  1. package/backend/auth/permissions.ts +12 -1
  2. package/backend/chat/stream-manager.ts +14 -3
  3. package/backend/database/migrations/040_create_mcp_servers_table.ts +34 -0
  4. package/backend/database/migrations/index.ts +7 -0
  5. package/backend/database/queries/index.ts +3 -1
  6. package/backend/database/queries/mcp-server-queries.ts +166 -0
  7. package/backend/engine/README.md +2 -2
  8. package/backend/engine/adapters/codex/message-converter.ts +1 -1
  9. package/backend/engine/adapters/codex/stream.ts +1 -1
  10. package/backend/engine/adapters/copilot/message-converter.ts +1 -1
  11. package/backend/engine/adapters/copilot/stream.ts +1 -1
  12. package/backend/engine/adapters/qwen/message-converter.ts +1 -1
  13. package/backend/engine/adapters/qwen/stream.ts +1 -1
  14. package/backend/engine/docs/adapter-contract.md +2 -2
  15. package/backend/engine/docs/lessons-learned.md +3 -3
  16. package/backend/engine/docs/quick-reference.md +1 -1
  17. package/backend/git/git-parser.ts +58 -29
  18. package/backend/git/git-service.ts +79 -10
  19. package/backend/git/git-spawn-validation.ts +3 -3
  20. package/backend/index.ts +5 -1
  21. package/backend/mcp/README.md +67 -32
  22. package/backend/mcp/external/config.ts +200 -0
  23. package/backend/mcp/external/registry-client.ts +214 -0
  24. package/backend/mcp/external/types.ts +69 -0
  25. package/backend/mcp/index.ts +104 -19
  26. package/backend/mcp/{config.ts → internal/config.ts} +82 -18
  27. package/backend/mcp/{remote-server.test.ts → internal/remote-server.test.ts} +3 -3
  28. package/backend/mcp/{servers → internal/servers}/browser-automation/actions.ts +1 -1
  29. package/backend/mcp/{servers → internal/servers}/browser-automation/browser.ts +1 -1
  30. package/backend/mcp/{servers → internal/servers}/browser-automation/index.ts +2 -0
  31. package/backend/mcp/{servers → internal/servers}/browser-automation/inspection.ts +1 -1
  32. package/backend/mcp/{servers → internal/servers}/helper.ts +11 -0
  33. package/backend/mcp/{servers → internal/servers}/index.ts +0 -2
  34. package/backend/mcp/{types.ts → internal/types.ts} +3 -3
  35. package/backend/mcp/shared/constants.ts +66 -0
  36. package/backend/projects/project-cleanup.ts +1 -1
  37. package/backend/ws/engine/index.ts +3 -1
  38. package/backend/ws/engine/restart.ts +54 -0
  39. package/backend/ws/git/branch.ts +3 -2
  40. package/backend/ws/git/commit.ts +14 -0
  41. package/backend/ws/git/remote.ts +85 -0
  42. package/backend/ws/index.ts +5 -1
  43. package/backend/ws/mcp/catalog.ts +56 -0
  44. package/backend/ws/mcp/crud.ts +174 -0
  45. package/backend/ws/mcp/index.ts +18 -0
  46. package/backend/ws/settings/crud.ts +31 -0
  47. package/dist/assets/main-DKLZPDUN.css +1 -0
  48. package/dist/assets/main-qT_RedHf.js +377 -0
  49. package/dist/index.html +2 -2
  50. package/package.json +1 -1
  51. package/shared/types/git.ts +4 -0
  52. package/shared/types/stores/settings.ts +2 -0
  53. package/backend/mcp/servers/weather/get-temperature.ts +0 -56
  54. package/backend/mcp/servers/weather/index.ts +0 -31
  55. package/dist/assets/main-Ba19ADkk.js +0 -377
  56. package/dist/assets/main-CwCZzMVm.css +0 -1
  57. /package/backend/mcp/{output-validator.test.ts → internal/output-validator.test.ts} +0 -0
  58. /package/backend/mcp/{output-validator.ts → internal/output-validator.ts} +0 -0
  59. /package/backend/mcp/{project-context.test.ts → internal/project-context.test.ts} +0 -0
  60. /package/backend/mcp/{project-context.ts → internal/project-context.ts} +0 -0
  61. /package/backend/mcp/{remote-server.ts → internal/remote-server.ts} +0 -0
@@ -36,6 +36,7 @@ export const ADMIN_ONLY_ROUTES = new Set([
36
36
  'projects:create',
37
37
  'projects:delete',
38
38
  'settings:update',
39
+ 'settings:update-system',
39
40
  'settings:update-batch',
40
41
  'system:run-update',
41
42
  'system:clear-data',
@@ -80,6 +81,7 @@ export const ADMIN_ONLY_ROUTES = new Set([
80
81
  'engine:opencode-account-rename',
81
82
  'engine:opencode-server-restart',
82
83
  'engine:opencode-models-dev-fetch',
84
+ 'engine:restart-all',
83
85
  // Tunnel — remote/local management mutates global Cloudflare credentials,
84
86
  // cloudflared auth, and ingress rules. Quick Tunnel is ephemeral and stays
85
87
  // open. Read-only routes (status, *-list, ingress, auth-status) stay open so
@@ -97,7 +99,16 @@ export const ADMIN_ONLY_ROUTES = new Set([
97
99
  'tunnel:local:ingress:add',
98
100
  'tunnel:local:ingress:remove',
99
101
  'tunnel:local:start',
100
- 'tunnel:local:stop'
102
+ 'tunnel:local:stop',
103
+ // External MCP — installing/removing servers from the official registry is a
104
+ // global, system-wide operation (it applies to every engine and project), so
105
+ // the whole surface is admin-only, mirroring System Tools and Engines.
106
+ 'mcp:catalog',
107
+ 'mcp:list',
108
+ 'mcp:install',
109
+ 'mcp:toggle',
110
+ 'mcp:update-config',
111
+ 'mcp:uninstall'
101
112
  ]);
102
113
 
103
114
  /**
@@ -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/project-context';
38
+ import { projectContextService } from '../mcp';
39
39
  import { browserMcpControl } from '../preview';
40
40
  import { extractMessageText } from '../snapshot/helpers';
41
41
  import { debug } from '$shared/utils/logger';
@@ -649,14 +649,25 @@ class StreamManager extends EventEmitter {
649
649
  // ── System Init ────────────────────────────────────────
650
650
  case 'system_init': {
651
651
  const initEvent = output as SystemInitEvent;
652
- const failedServers = initEvent.mcpServers.filter(s => s.status !== 'connected');
652
+ // Suppress the toast for "soft" statuses: `pending` (still
653
+ // connecting) and `needs-auth` (server expects OAuth/credentials
654
+ // configured in Settings → MCP). These are not errors — a scary
655
+ // toast for them is confusing. (Status is the raw SDK string,
656
+ // wider than the EngineOutput union, hence the cast.)
657
+ const SOFT_STATUSES = new Set(['pending', 'needs-auth']);
658
+ const failedServers = initEvent.mcpServers.filter(
659
+ s => s.status !== 'connected' && !SOFT_STATUSES.has(s.status as string)
660
+ );
661
+ initEvent.mcpServers
662
+ .filter(s => SOFT_STATUSES.has(s.status as string))
663
+ .forEach(s => debug.log('mcp', `MCP server "${s.name}" not ready (${s.status}) — suppressing toast`));
653
664
  failedServers.forEach(server => {
654
665
  debug.warn('mcp', `MCP server connection failed: ${server.name} (${server.status})`);
655
666
  this.emitStreamEvent(streamState, 'notification', {
656
667
  notification: {
657
668
  type: 'warning',
658
669
  title: 'MCP Server Connection Failed',
659
- message: `Failed to connect to custom MCP server "${server.name}". Status: ${server.status}`,
670
+ message: `Failed to connect to MCP server "${server.name}".`,
660
671
  },
661
672
  timestamp: new Date().toISOString()
662
673
  });
@@ -0,0 +1,34 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create mcp_servers table for external (user-installed) MCP servers';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Creating mcp_servers table...');
8
+ db.exec(`
9
+ CREATE TABLE IF NOT EXISTS mcp_servers (
10
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
11
+ slug TEXT NOT NULL UNIQUE,
12
+ name TEXT NOT NULL,
13
+ description TEXT,
14
+ registry_name TEXT,
15
+ version TEXT,
16
+ transport TEXT NOT NULL,
17
+ command TEXT,
18
+ args TEXT NOT NULL DEFAULT '[]',
19
+ env TEXT NOT NULL DEFAULT '{}',
20
+ url TEXT,
21
+ headers TEXT NOT NULL DEFAULT '{}',
22
+ source TEXT NOT NULL DEFAULT 'registry',
23
+ is_enabled INTEGER NOT NULL DEFAULT 1,
24
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
25
+ )
26
+ `);
27
+ debug.log('migration', 'mcp_servers table created');
28
+ };
29
+
30
+ export const down = (db: DatabaseConnection): void => {
31
+ debug.log('migration', 'Dropping mcp_servers table...');
32
+ db.exec('DROP TABLE IF EXISTS mcp_servers');
33
+ debug.log('migration', 'mcp_servers table dropped');
34
+ };
@@ -38,6 +38,7 @@ import * as migration036 from './036_create_auth_audit_log';
38
38
  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
+ import * as migration040 from './040_create_mcp_servers_table';
41
42
 
42
43
  // Export all migrations in order
43
44
  export const migrations = [
@@ -274,6 +275,12 @@ export const migrations = [
274
275
  description: migration039.description,
275
276
  up: migration039.up,
276
277
  down: migration039.down
278
+ },
279
+ {
280
+ id: '040',
281
+ description: migration040.description,
282
+ up: migration040.up,
283
+ down: migration040.down
277
284
  }
278
285
  ];
279
286
 
@@ -11,4 +11,6 @@ export { authQueries } from './auth-queries';
11
11
  export { dbClientConnectionQueries } from './db-client-connection-queries';
12
12
  export { dbClientQueryHistoryQueries } from './db-client-query-history-queries';
13
13
  export { auditLogQueries } from './audit-log-queries';
14
- export { fileAuditLogQueries } from './file-audit-log-queries';
14
+ export { fileAuditLogQueries } from './file-audit-log-queries';
15
+ export { mcpServerQueries } from './mcp-server-queries';
16
+ export type { McpServerRow, McpServerInput, McpTransport, McpSource } from './mcp-server-queries';
@@ -0,0 +1,166 @@
1
+ /**
2
+ * External MCP Server Queries
3
+ *
4
+ * CRUD for user-installed (external) MCP servers — the servers managed from
5
+ * Settings → MCP, sourced from the official MCP registry. This is distinct
6
+ * from the INTERNAL custom-tool servers in `backend/mcp/internal/servers/`,
7
+ * which are defined in code and not stored in the DB.
8
+ *
9
+ * Conventions:
10
+ * - `slug` : unique machine id, used to derive the `<slug>` MCP
11
+ * namespace. Only `[a-z0-9-]`.
12
+ * - `transport`: 'stdio' | 'http' | 'sse'.
13
+ * - `args`/`env`/`headers` are stored as JSON strings.
14
+ */
15
+
16
+ import { getDatabase } from '../index';
17
+
18
+ export type McpTransport = 'stdio' | 'http' | 'sse';
19
+ export type McpSource = 'registry' | 'custom' | 'internal';
20
+
21
+ /** Raw DB row. */
22
+ export interface McpServerRow {
23
+ id: number;
24
+ slug: string;
25
+ name: string;
26
+ description: string | null;
27
+ registry_name: string | null;
28
+ version: string | null;
29
+ transport: McpTransport;
30
+ command: string | null;
31
+ args: string;
32
+ env: string;
33
+ url: string | null;
34
+ headers: string;
35
+ source: McpSource;
36
+ is_enabled: number;
37
+ created_at: string;
38
+ }
39
+
40
+ export interface McpServerInput {
41
+ slug: string;
42
+ name: string;
43
+ description?: string | null;
44
+ registryName?: string | null;
45
+ version?: string | null;
46
+ transport: McpTransport;
47
+ command?: string | null;
48
+ args?: string[];
49
+ env?: Record<string, string>;
50
+ url?: string | null;
51
+ headers?: Record<string, string>;
52
+ source?: McpSource;
53
+ }
54
+
55
+ export const mcpServerQueries = {
56
+ getAll(): McpServerRow[] {
57
+ const db = getDatabase();
58
+ return db.prepare(`SELECT * FROM mcp_servers ORDER BY created_at ASC`).all() as McpServerRow[];
59
+ },
60
+
61
+ getEnabled(): McpServerRow[] {
62
+ const db = getDatabase();
63
+ return db.prepare(`SELECT * FROM mcp_servers WHERE is_enabled = 1 ORDER BY created_at ASC`).all() as McpServerRow[];
64
+ },
65
+
66
+ getById(id: number): McpServerRow | null {
67
+ const db = getDatabase();
68
+ return db.prepare(`SELECT * FROM mcp_servers WHERE id = ?`).get(id) as McpServerRow | null;
69
+ },
70
+
71
+ getBySlug(slug: string): McpServerRow | null {
72
+ const db = getDatabase();
73
+ return db.prepare(`SELECT * FROM mcp_servers WHERE slug = ?`).get(slug) as McpServerRow | null;
74
+ },
75
+
76
+ getBySource(source: McpSource): McpServerRow[] {
77
+ const db = getDatabase();
78
+ return db.prepare(`SELECT * FROM mcp_servers WHERE source = ? ORDER BY created_at ASC`).all(source) as McpServerRow[];
79
+ },
80
+
81
+ insert(input: McpServerInput): McpServerRow {
82
+ const db = getDatabase();
83
+ const result = db.prepare(
84
+ `INSERT INTO mcp_servers
85
+ (slug, name, description, registry_name, version, transport, command, args, env, url, headers, source)
86
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
87
+ ).run(
88
+ input.slug,
89
+ input.name,
90
+ input.description ?? null,
91
+ input.registryName ?? null,
92
+ input.version ?? null,
93
+ input.transport,
94
+ input.command ?? null,
95
+ JSON.stringify(input.args ?? []),
96
+ JSON.stringify(input.env ?? {}),
97
+ input.url ?? null,
98
+ JSON.stringify(input.headers ?? {}),
99
+ input.source ?? 'registry'
100
+ ) as { lastInsertRowid: number | bigint };
101
+ const id = Number(result.lastInsertRowid);
102
+ return this.getById(id)!;
103
+ },
104
+
105
+ setEnabled(id: number, enabled: boolean): void {
106
+ const db = getDatabase();
107
+ db.prepare(`UPDATE mcp_servers SET is_enabled = ? WHERE id = ?`).run(enabled ? 1 : 0, id);
108
+ },
109
+
110
+ /** Update the stored env (e.g. user-provided API keys) for a server. */
111
+ updateEnv(id: number, env: Record<string, string>): void {
112
+ const db = getDatabase();
113
+ db.prepare(`UPDATE mcp_servers SET env = ? WHERE id = ?`).run(JSON.stringify(env), id);
114
+ },
115
+
116
+ /** Update both env (stdio) and headers (remote auth) for a server. */
117
+ updateConfig(id: number, env: Record<string, string>, headers: Record<string, string>): void {
118
+ const db = getDatabase();
119
+ db.prepare(`UPDATE mcp_servers SET env = ?, headers = ? WHERE id = ?`).run(
120
+ JSON.stringify(env),
121
+ JSON.stringify(headers),
122
+ id
123
+ );
124
+ },
125
+
126
+ remove(id: number): void {
127
+ const db = getDatabase();
128
+ db.prepare(`DELETE FROM mcp_servers WHERE id = ?`).run(id);
129
+ },
130
+
131
+ /**
132
+ * Insert or refresh an INTERNAL (code-defined) server row.
133
+ *
134
+ * Internal servers are defined in `backend/mcp/internal/servers/` — the DB
135
+ * row is only a mirror used for listing + the enable/disable toggle. On
136
+ * update we refresh the display metadata (title/description/version) but
137
+ * PRESERVE `is_enabled` so the user's toggle survives restarts. New rows
138
+ * default to enabled and `stdio` transport (they run in-process / via the
139
+ * `/mcp` bridge, surfaced to the user as "local (stdio)").
140
+ */
141
+ upsertInternal(input: { slug: string; name: string; description: string | null; version: string }): McpServerRow {
142
+ const db = getDatabase();
143
+ const existing = this.getBySlug(input.slug);
144
+ if (existing) {
145
+ db.prepare(
146
+ `UPDATE mcp_servers SET name = ?, description = ?, version = ?, transport = 'stdio', source = 'internal' WHERE slug = ?`
147
+ ).run(input.name, input.description, input.version, input.slug);
148
+ return this.getBySlug(input.slug)!;
149
+ }
150
+ db.prepare(
151
+ `INSERT INTO mcp_servers (slug, name, description, version, transport, source, is_enabled)
152
+ VALUES (?, ?, ?, ?, 'stdio', 'internal', 1)`
153
+ ).run(input.slug, input.name, input.description, input.version);
154
+ return this.getBySlug(input.slug)!;
155
+ },
156
+
157
+ /** Remove internal rows whose code definition no longer exists (keeps the slugs in `keep`). */
158
+ pruneInternalExcept(keep: string[]): void {
159
+ const db = getDatabase();
160
+ const rows = this.getBySource('internal');
161
+ const keepSet = new Set(keep);
162
+ for (const row of rows) {
163
+ if (!keepSet.has(row.slug)) db.prepare(`DELETE FROM mcp_servers WHERE id = ?`).run(row.id);
164
+ }
165
+ }
166
+ };
@@ -97,13 +97,13 @@ Three key rules that **every** layer upholds:
97
97
  > Two design pitfalls have repeatedly tripped people adding new adapters.
98
98
  > Before sketching architecture, double-check:
99
99
  >
100
- > 1. **MCP over HTTP already exists.** `backend/mcp/remote-server.ts` mounts
100
+ > 1. **MCP over HTTP already exists.** `backend/mcp/internal/remote-server.ts` mounts
101
101
  > every `defineServer()`-registered MCP server as a Streamable HTTP
102
102
  > endpoint at `http://localhost:<port>/mcp`. OpenCode consumes it via
103
103
  > `getOpenCodeMcpConfig()`. Any engine whose CLI/SDK accepts a
104
104
  > `streamable-http` MCP URL (Codex, future engines) reuses **the same
105
105
  > URL** by adding a sibling `getXxxMcpConfig()` helper in
106
- > `backend/mcp/config.ts`. Do **NOT** propose a "new MCP bridge",
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
108
  > 2. **Shared CLI dotfiles are swapped from DB, not isolated.** When a CLI
109
109
  > stores its credentials in a known location (e.g. `~/.codex/auth.json`),
@@ -75,7 +75,7 @@ import type {
75
75
  ThreadStartedEvent,
76
76
  TurnCompletedEvent,
77
77
  } from '@openai/codex-sdk';
78
- import { resolveOpenCodeToolName } from '../../../mcp/config';
78
+ import { resolveOpenCodeToolName } from '../../../mcp';
79
79
  import { readLastTokenUsageFromRollout } from './usage-rollout';
80
80
  import { readApplyPatchesFromRollout, findMatchingPatch } from './patch-rollout';
81
81
 
@@ -26,7 +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 { getCodexMcpConfig } from '../../../mcp/config';
29
+ import { getCodexMcpConfig } from '../../../mcp';
30
30
  import { CODEX_MODELS } from './models';
31
31
  import { debug } from '$shared/utils/logger';
32
32
  import { handleStreamError, buildTurnError } from './error-handler';
@@ -49,7 +49,7 @@ import type {
49
49
  } from '$shared/types/unified';
50
50
  import { toCanonicalToolName } from '$shared/types/unified';
51
51
  import type { SessionEvent } from '@github/copilot-sdk';
52
- import { resolveOpenCodeToolName } from '../../../mcp/config';
52
+ import { resolveOpenCodeToolName } from '../../../mcp';
53
53
 
54
54
  // Derive data payload types from the SessionEvent discriminated union so we
55
55
  // don't depend on internal type re-exports that aren't part of the SDK's
@@ -20,7 +20,7 @@ import { buildJsonPrompt, extractJson } from '../../structured-helpers';
20
20
  import { engineQueries } from '$backend/database/queries/engine-queries';
21
21
  import { resolveOsPath } from '$backend/utils/paths';
22
22
  import { debug } from '$shared/utils/logger';
23
- import { getCopilotMcpConfig } from '../../../mcp/config';
23
+ import { getCopilotMcpConfig } from '../../../mcp';
24
24
  import { handleStreamError, buildSessionError } from './error-handler';
25
25
  import { fetchCopilotModels } from './models';
26
26
 
@@ -51,7 +51,7 @@ import type {
51
51
  AskUserQuestion,
52
52
  } from '$shared/types/unified';
53
53
  import { toCanonicalToolName } from '$shared/types/unified';
54
- import { resolveOpenCodeToolName } from '../../../mcp/config';
54
+ import { resolveOpenCodeToolName } from '../../../mcp';
55
55
 
56
56
  // ============================================================
57
57
  // Qwen-specific tool-result content markers
@@ -45,7 +45,7 @@ import { getEngineEnv } from './environment';
45
45
  import { handleStreamError } from './error-handler';
46
46
  import { createSdkMessageConverter, toSdkUserMessage, type SdkMessageConverter } from './message-converter';
47
47
  import { fetchQwenModels } from './models';
48
- import { getQwenMcpConfig } from '../../../mcp/config';
48
+ import { getQwenMcpConfig } from '../../../mcp';
49
49
  import { forkQwenSessionState, sessionStateExists } from './session-fork';
50
50
 
51
51
  interface PendingAskUserQuestion {
@@ -122,8 +122,8 @@ calling `getEnabledMcpServers(options.mcpContext)`.
122
122
  - ❌ Use `console.*` — use `debug` from `$shared/utils/logger` with
123
123
  category `'engine'`, `'chat'`, or `'mcp'`.
124
124
  - ❌ **Build a new MCP HTTP server for the adapter.** Use the existing
125
- `backend/mcp/remote-server.ts` and add a `getXxxMcpConfig()` helper in
126
- `backend/mcp/config.ts` returning the URL in the engine's expected
125
+ `backend/mcp/internal/remote-server.ts` and add a `getXxxMcpConfig()` helper in
126
+ `backend/mcp/internal/config.ts` returning the URL in the engine's expected
127
127
  shape. New MCP servers are added via `defineServer()` — never via a
128
128
  parallel HTTP listener.
129
129
  - ❌ **Create per-account isolated home directories** to multiplex two
@@ -352,7 +352,7 @@ async dispose(): Promise<void> {
352
352
 
353
353
  ### 9.12 Reuse the existing MCP HTTP infrastructure — never build a new bridge
354
354
 
355
- `backend/mcp/remote-server.ts` already mounts every server registered via
355
+ `backend/mcp/internal/remote-server.ts` already mounts every server registered via
356
356
  `defineServer()` as a **Streamable HTTP MCP** endpoint at
357
357
  `http://localhost:<port>/mcp`. OpenCode consumes it via
358
358
  `getOpenCodeMcpConfig()`. Tool handlers run **in-process** in the Clopen
@@ -383,9 +383,9 @@ When you add an engine whose CLI/SDK accepts a streamable-http MCP URL
383
383
  - In the adapter, name the local variable holding the helper's return
384
384
  value **`mcpConfig`**, not `mcpServers`. The latter shadows both the
385
385
  SDK's config field name AND the registry exported from
386
- `backend/mcp/config.ts`, and reads as a bug at the call site.
386
+ `backend/mcp/internal/config.ts`, and reads as a bug at the call site.
387
387
 
388
- 2. Use `resolveOpenCodeToolName()` (in `backend/mcp/config.ts`) on
388
+ 2. Use `resolveOpenCodeToolName()` (in `backend/mcp/internal/config.ts`) on
389
389
  incoming tool names; it strips the `clopen-mcp_` / `clopen-mcp-`
390
390
  prefix and reverse-maps to `mcp__<server>__<tool>`. The same helper
391
391
  works for any engine that uses the same naming convention.
@@ -16,7 +16,7 @@
16
16
  | Fork session (native vs. on-disk workaround) | `claude/stream.ts` (`forkSession: true`), `opencode/stream.ts` (`client.session.fork`), `copilot/stream.ts` (`client.rpc.sessions.fork`), `codex/session-fork.ts` + `qwen/session-fork.ts` (copy disk state) |
17
17
  | Sub-agent (`Task`/`Agent`) routing | `claude/message-converter.ts` (`parent_tool_use_id`), `opencode/message-converter.ts::convertSubtaskToolUseOnly`, `copilot/message-converter.ts::resolveParentToolUseId` + `agentParentMap` (see §9.15) |
18
18
  | AskUserQuestion event + HTTP fallback | `opencode/stream.ts::resolveUserAnswer`, `claude/stream.ts::canUseTool` |
19
- | MCP servers exposed over HTTP (single source) | `backend/mcp/remote-server.ts`, `backend/mcp/config.ts::getOpenCodeMcpConfig` (and future `getXxxMcpConfig`) |
19
+ | MCP servers exposed over HTTP (single source) | `backend/mcp/internal/remote-server.ts`, `backend/mcp/internal/config.ts::getOpenCodeMcpConfig` (and future `getXxxMcpConfig`) |
20
20
  | Auth-blob swap into shared CLI dotfile | Pattern only (no implementation yet); see §3.3 callout + §9.13 |
21
21
  | Restart-Server pattern (long-lived engines) | `backend/ws/engine/opencode/providers.ts::engine:opencode-server-restart`, `frontend/components/chat/input/components/EngineModelPicker.svelte::restartOCServer`, `AIEnginesSettings.svelte::handleRestartServer`/`forceRestartServer` |
22
22
  | `generateStructured` (no tools, JSON) | `claude/stream.ts::generateStructured` (native `outputFormat`), `codex/stream.ts::generateStructured` (native `outputSchema`), `opencode/stream.ts::generateStructured` + `copilot/stream.ts::generateStructured` + `qwen/stream.ts::generateStructured` (prompt-engineered via `backend/engine/structured-helpers.ts`). See §9.16 for the strict-schema + part-fallback gotchas. |
@@ -101,7 +101,16 @@ export function parseStatus(output: string): GitStatus {
101
101
  }
102
102
 
103
103
  /**
104
- * Parse `git branch -a -v --format` output
104
+ * Parse `git for-each-ref` output for branches into structured info.
105
+ *
106
+ * Expects lines in the custom format produced by `gitService.getBranches`:
107
+ * - local: `*|main|abc1234|commit subject|2024-01-15T10:30:00+07:00`
108
+ * ` |dev |abc1234|another subject|2024-01-14T09:00:00+07:00`
109
+ * - remote: `origin/main|abc1234|commit subject|2024-01-15T10:30:00+07:00`
110
+ *
111
+ * The date is strict ISO 8601 and never contains `|`, so `lastIndexOf('|')`
112
+ * safely extracts it. The subject (which may itself contain `|`) is kept
113
+ * whole by limiting the head split to 4 / 3 parts.
105
114
  */
106
115
  export function parseBranches(localOutput: string, remoteOutput: string): GitBranchInfo {
107
116
  const local: GitBranch[] = [];
@@ -111,23 +120,18 @@ export function parseBranches(localOutput: string, remoteOutput: string): GitBra
111
120
  // Parse local branches
112
121
  const localLines = localOutput.split('\n').filter(Boolean);
113
122
  for (const line of localLines) {
114
- // Format: "* main abc1234 commit message" or " dev abc1234 commit message"
115
- const isCurrent = line.startsWith('*');
116
- const trimmed = line.replace(/^\*?\s+/, '');
117
-
118
- // When HEAD is detached, git emits a parenthesized pseudo-ref instead of a
119
- // branch name, e.g. "* (no branch, rebasing main)" or "* (HEAD detached at
120
- // abc1234)". These are not real branches — skip them so they never leak into
121
- // the branch list or get treated as the current branch (which produced the
122
- // bogus "(no" branch name). Match git's exact pseudo-ref prefixes so legit
123
- // branch names containing parentheses (e.g. "feature(x)") are preserved. The
124
- // real current branch / detached state is resolved authoritatively in
125
- // git-service. Output is forced to en_US locale, so these strings are stable.
126
- if (isCurrent && /^\((?:HEAD detached|no branch)\b/.test(trimmed)) continue;
127
-
128
- const parts = trimmed.split(/\s+/);
129
- const name = parts[0];
130
- const lastCommit = parts[1] || '';
123
+ const dateSep = line.lastIndexOf('|');
124
+ if (dateSep === -1) continue;
125
+ const lastCommitDate = line.substring(dateSep + 1);
126
+ const head = line.substring(0, dateSep);
127
+
128
+ // head = "<*>|<name>|<hash>|<subject>"
129
+ const parts = head.split('|', 4);
130
+ if (parts.length < 4) continue;
131
+ const isCurrent = parts[0] === '*';
132
+ const name = parts[1];
133
+ const lastCommit = parts[2];
134
+ const lastCommitMessage = parts[3];
131
135
 
132
136
  if (isCurrent) current = name;
133
137
 
@@ -137,18 +141,30 @@ export function parseBranches(localOutput: string, remoteOutput: string): GitBra
137
141
  isRemote: false,
138
142
  ahead: 0,
139
143
  behind: 0,
140
- lastCommit
141
- });
144
+ lastCommit,
145
+ lastCommitMessage,
146
+ lastCommitDate
147
+ } as GitBranch);
142
148
  }
143
149
 
144
150
  // Parse remote branches
145
151
  const remoteLines = remoteOutput.split('\n').filter(Boolean);
146
152
  for (const line of remoteLines) {
147
- const trimmed = line.trim();
148
- if (trimmed.includes('->')) continue; // Skip HEAD pointers
149
- const parts = trimmed.split(/\s+/);
153
+ const dateSep = line.lastIndexOf('|');
154
+ if (dateSep === -1) continue;
155
+ const lastCommitDate = line.substring(dateSep + 1);
156
+ const head = line.substring(0, dateSep);
157
+
158
+ // head = "<name>|<hash>|<subject>"
159
+ const parts = head.split('|', 3);
160
+ if (parts.length < 3) continue;
150
161
  const name = parts[0];
151
- const lastCommit = parts[1] || '';
162
+ // Skip symbolic HEAD pointers like `origin/HEAD -> origin/main`
163
+ // (these only show up in the old `git branch -r` output, not in
164
+ // `for-each-ref refs/remotes/`, but guard anyway).
165
+ if (name.endsWith('/HEAD')) continue;
166
+ const lastCommit = parts[1];
167
+ const lastCommitMessage = parts[2];
152
168
 
153
169
  remote.push({
154
170
  name,
@@ -156,8 +172,10 @@ export function parseBranches(localOutput: string, remoteOutput: string): GitBra
156
172
  isRemote: true,
157
173
  ahead: 0,
158
174
  behind: 0,
159
- lastCommit
160
- });
175
+ lastCommit,
176
+ lastCommitMessage,
177
+ lastCommitDate
178
+ } as GitBranch);
161
179
  }
162
180
 
163
181
  return { current, local, remote, ahead: 0, behind: 0 };
@@ -342,19 +360,30 @@ export function parseRemotes(output: string): GitRemote[] {
342
360
  }
343
361
 
344
362
  /**
345
- * Parse `git stash list` output
363
+ * Parse `git stash list` output.
364
+ *
365
+ * Expects lines in the custom format produced by `git stash list --format="%gd: %gs | %cI"`:
366
+ * `stash@{0}: WIP on main: abc1234 message | 2024-01-15T10:30:00+07:00`
367
+ *
368
+ * The ` | ` separator is safe because `%cI` (strict ISO 8601) never contains it.
369
+ * Falls back to the plain format (`stash@{N}: message`) when the separator is
370
+ * missing — e.g. older snapshots or a git version that ignores `--format`.
346
371
  */
347
372
  export function parseStashList(output: string): GitStashEntry[] {
348
373
  const entries: GitStashEntry[] = [];
349
374
  const lines = output.split('\n').filter(Boolean);
350
375
 
351
376
  for (const line of lines) {
352
- const match = line.match(/^stash@\{(\d+)\}:\s*(.+)$/);
377
+ const sepIdx = line.lastIndexOf(' | ');
378
+ const head = sepIdx === -1 ? line : line.substring(0, sepIdx);
379
+ const date = sepIdx === -1 ? '' : line.substring(sepIdx + 3);
380
+
381
+ const match = head.match(/^stash@\{(\d+)\}:\s*(.+)$/);
353
382
  if (match) {
354
383
  entries.push({
355
384
  index: parseInt(match[1]),
356
385
  message: match[2],
357
- date: ''
386
+ date
358
387
  });
359
388
  }
360
389
  }