@myrialabs/clopen 0.4.17 → 0.4.18

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 (89) hide show
  1. package/README.md +3 -3
  2. package/backend/auth/auth-service.ts +265 -13
  3. package/backend/auth/permissions.ts +3 -0
  4. package/backend/auth/rate-limiter.ts +1 -0
  5. package/backend/auth/session-cleanup.ts +5 -0
  6. package/backend/auth/tokens.ts +8 -1
  7. package/backend/chat/stream-manager.ts +8 -0
  8. package/backend/database/migrations/060_create_device_codes_table.ts +38 -0
  9. package/backend/database/migrations/061_add_session_device_metadata.ts +42 -0
  10. package/backend/database/migrations/062_add_session_source.ts +43 -0
  11. package/backend/database/migrations/063_add_invite_project_ids.ts +42 -0
  12. package/backend/database/migrations/064_create_messages_fts.ts +71 -0
  13. package/backend/database/migrations/index.ts +35 -0
  14. package/backend/database/queries/auth-queries.ts +100 -6
  15. package/backend/database/queries/message-queries.ts +44 -0
  16. package/backend/database/queries/session-queries.ts +117 -12
  17. package/backend/engine/README.md +21 -4
  18. package/backend/engine/adapters/claude/stream.ts +4 -2
  19. package/backend/engine/adapters/cline/agent-tool.ts +3 -2
  20. package/backend/engine/adapters/cline/ask-question-tool.ts +3 -2
  21. package/backend/engine/adapters/cline/credential.ts +2 -1
  22. package/backend/engine/adapters/cline/mcp-tools.ts +2 -1
  23. package/backend/engine/adapters/cline/models.ts +3 -1
  24. package/backend/engine/adapters/cline/presets.ts +5 -3
  25. package/backend/engine/adapters/cline/stream.ts +10 -7
  26. package/backend/engine/adapters/codex/stream.ts +3 -1
  27. package/backend/engine/adapters/copilot/stream.ts +8 -1
  28. package/backend/engine/adapters/cursor/environment.ts +4 -2
  29. package/backend/engine/adapters/cursor/models.ts +2 -1
  30. package/backend/engine/adapters/cursor/stream.ts +5 -3
  31. package/backend/engine/adapters/pi/presets.ts +3 -1
  32. package/backend/engine/adapters/pi/session-fork.ts +3 -1
  33. package/backend/engine/adapters/pi/stream.ts +11 -8
  34. package/backend/engine/bootstrap-default-engine.ts +69 -0
  35. package/backend/engine/docs/adding-an-engine.md +29 -6
  36. package/backend/engine/docs/frontend-and-chat.md +21 -5
  37. package/backend/engine/docs/lessons-learned.md +41 -0
  38. package/backend/engine/docs/quick-reference.md +3 -2
  39. package/backend/engine/docs/system-tools.md +65 -9
  40. package/backend/engine/docs/websocket-routes.md +4 -3
  41. package/backend/engine/engine-setup.ts +72 -0
  42. package/backend/engine/install-recipes.ts +82 -77
  43. package/backend/engine/install-runner.ts +27 -2
  44. package/backend/engine/sdk-loader.ts +180 -0
  45. package/backend/engine/version-check.ts +6 -6
  46. package/backend/http/files-upload.test.ts +4 -1
  47. package/backend/index.ts +32 -2
  48. package/backend/mcp/README.md +26 -8
  49. package/backend/mcp/index.ts +2 -2
  50. package/backend/mcp/internal/config.ts +54 -63
  51. package/backend/mcp/internal/remote-server.test.ts +4 -1
  52. package/backend/mcp/internal/servers/helper.ts +4 -34
  53. package/backend/mcp/internal/servers/index.ts +4 -13
  54. package/backend/tunnel/public-origin.ts +118 -0
  55. package/backend/utils/ws.ts +126 -1
  56. package/backend/ws/auth/device.ts +239 -0
  57. package/backend/ws/auth/index.ts +8 -0
  58. package/backend/ws/auth/invites.ts +16 -6
  59. package/backend/ws/auth/login.test.ts +2 -2
  60. package/backend/ws/auth/login.ts +12 -6
  61. package/backend/ws/engine/claude/status.ts +4 -4
  62. package/backend/ws/engine/cline/accounts.ts +3 -2
  63. package/backend/ws/engine/cline/status.ts +4 -12
  64. package/backend/ws/engine/codex/status.ts +4 -12
  65. package/backend/ws/engine/copilot/status.ts +5 -12
  66. package/backend/ws/engine/cursor/accounts.ts +2 -1
  67. package/backend/ws/engine/cursor/status.ts +5 -12
  68. package/backend/ws/engine/opencode/status.ts +4 -4
  69. package/backend/ws/engine/pi/status.ts +4 -12
  70. package/backend/ws/engine/qwen/status.ts +5 -12
  71. package/backend/ws/sessions/crud.ts +29 -4
  72. package/backend/ws/settings/crud.ts +10 -1
  73. package/backend/ws/system/operations.ts +34 -18
  74. package/backend/ws/system-tools/install.ts +3 -0
  75. package/backend/ws/system-tools/status.ts +7 -2
  76. package/backend/ws/tunnel/index.ts +3 -1
  77. package/backend/ws/tunnel/share.ts +27 -0
  78. package/bin/clopen.ts +1 -1
  79. package/dist/assets/{index-kME3THy5.js → index-Cz8HVhsm.js} +1 -1
  80. package/dist/assets/{index-Bu5loFQE.js → index-SI4Gcd0p.js} +1 -1
  81. package/dist/assets/main-Cry3pLcl.css +1 -0
  82. package/dist/assets/{main-HirJLquI.js → main-Dlba-fXF.js} +337 -330
  83. package/dist/index.html +2 -2
  84. package/package.json +15 -14
  85. package/shared/constants/engines.ts +39 -40
  86. package/shared/constants/tool-icons.ts +49 -0
  87. package/shared/types/stores/settings.ts +9 -0
  88. package/shared/utils/logger.ts +1 -0
  89. package/dist/assets/main-D7ATW8pp.css +0 -1
@@ -12,12 +12,11 @@ type VersionSource =
12
12
  | { type: 'github-release'; repo: string }
13
13
  | { type: 'chrome-for-testing' };
14
14
 
15
- const SOURCES: Record<ToolId, VersionSource> = {
16
- claude: { type: 'npm', pkg: '@anthropic-ai/claude-code' },
17
- opencode: { type: 'npm', pkg: 'opencode-ai' },
18
- copilot: { type: 'npm', pkg: '@github/copilot' },
19
- codex: { type: 'npm', pkg: '@openai/codex' },
20
- qwen: { type: 'npm', pkg: '@qwen-code/qwen-code' },
15
+ // Engines are intentionally absent: their SDK versions are pinned in
16
+ // package.json (the single source of truth) and move in lockstep with clopen
17
+ // releases, so we do not nag users to drift off the tested version. Only host
18
+ // tools (git, chrome) self-update independently.
19
+ const SOURCES: Partial<Record<ToolId, VersionSource>> = {
21
20
  git: { type: 'homebrew-formula', formula: 'git' },
22
21
  chrome: { type: 'chrome-for-testing' },
23
22
  };
@@ -118,6 +117,7 @@ export async function checkToolUpdate(
118
117
  installedVersion: string | null
119
118
  ): Promise<UpdateCheckResult> {
120
119
  const source = SOURCES[tool];
120
+ if (!source) return { latestVersion: null, hasUpdate: null };
121
121
 
122
122
  let latestVersion: string | null;
123
123
  switch (source.type) {
@@ -76,7 +76,10 @@ beforeAll(async () => {
76
76
  token_hash: hashToken(testToken),
77
77
  expires_at: expiresAt,
78
78
  created_at: new Date().toISOString(),
79
- last_active_at: new Date().toISOString()
79
+ last_active_at: new Date().toISOString(),
80
+ user_agent: null,
81
+ ip_address: null,
82
+ source: null
80
83
  });
81
84
 
82
85
  // Create test project
package/backend/index.ts CHANGED
@@ -23,6 +23,7 @@ import { loggerMiddleware } from './middleware/logger';
23
23
 
24
24
  // Database initialization
25
25
  import { initializeDatabase, closeDatabase } from './database';
26
+ import { ensureDefaultEngineInstalled } from './engine/bootstrap-default-engine';
26
27
  import { syncInternalServers } from './mcp';
27
28
  import { disposeAllEngines } from './engine';
28
29
  import { connectionManager } from './db-client/connection-manager';
@@ -49,18 +50,43 @@ import { browserPreviewServiceManager } from './preview';
49
50
  import { handleMcpRequest, handleExternalMcpRequest, closeMcpServer, completeAuthorization } from './mcp';
50
51
 
51
52
  // Auth middleware
52
- import { checkRouteAccess } from './auth/permissions';
53
+ import { checkRouteAccess, PUBLIC_ROUTES } from './auth/permissions';
54
+ import { getAuthMode } from './auth/auth-service';
55
+ import { authQueries } from './database/queries';
53
56
  import { authRateLimiter } from './auth';
54
57
  import { sessionCleanupScheduler } from './auth/session-cleanup';
55
58
  import { uploadTempCleanup } from './http/upload-temp-cleanup';
56
59
  import { ws as wsServer } from './utils/ws';
57
60
  import { messageRateLimiter } from './ws/message-rate-limiter';
58
61
 
62
+ /** How often (ms) the auth gate re-confirms a connection's session against the DB. */
63
+ const SESSION_REVALIDATE_MS = 15_000;
64
+
59
65
  // Register auth gate on WebSocket router — blocks unauthenticated/unauthorized access
60
66
  wsRouter.setAuthMiddleware(async (conn, action) => {
61
67
  const isAuth = wsServer.isAuthenticated(conn);
62
68
  const role = wsServer.getRole(conn);
63
- return checkRouteAccess(action, isAuth, role);
69
+ const result = checkRouteAccess(action, isAuth, role);
70
+ if (!result.allowed) return result;
71
+
72
+ // Defense-in-depth: an authenticated connection trusts the in-memory auth set
73
+ // at login. If its session was revoked/expired/deleted afterwards (sign-out
74
+ // from another device, admin removal, expiry), the live socket would otherwise
75
+ // keep full access until it reconnects. Periodically re-confirm the session
76
+ // still exists in the DB and kick the connection the moment it doesn't.
77
+ if (isAuth && getAuthMode() === 'required' && !PUBLIC_ROUTES.has(action)) {
78
+ if (wsServer.dueForSessionCheck(conn, SESSION_REVALIDATE_MS)) {
79
+ const hash = wsServer.getSessionTokenHash(conn);
80
+ const session = hash ? authQueries.getSessionByTokenHash(hash) : null;
81
+ const valid = !!session && new Date(session.expires_at) >= new Date();
82
+ if (!valid) {
83
+ wsServer.invalidateConnection(conn, 'Your session has ended');
84
+ return { allowed: false, error: 'Session ended' };
85
+ }
86
+ }
87
+ }
88
+
89
+ return result;
64
90
  });
65
91
 
66
92
  // Register message rate limiter on WebSocket router — prevents DoS via message spam
@@ -215,6 +241,10 @@ async function startServer() {
215
241
  // Start expired session cleanup now that the database is ready
216
242
  sessionCleanupScheduler.start();
217
243
  uploadTempCleanup.start();
244
+ // Fresh installs: auto-install OpenCode (free, no account) in the
245
+ // background so first-time users have a working engine without any manual
246
+ // setup. Non-blocking; no-ops once any engine is already installed.
247
+ void ensureDefaultEngineInstalled();
218
248
  } catch (error) {
219
249
  debug.warn('database', '⚠️ Database initialization failed:', error);
220
250
  }
@@ -52,7 +52,14 @@ System for adding custom tools to AI engines with type-safe TypeScript definitio
52
52
 
53
53
  **Features:**
54
54
  - Single source of truth — define tools once, use in every engine
55
- - In-process execution for Claude Code via `createSdkMcpServer`
55
+ - **Decoupled from the Claude Agent SDK.** `internal/` holds only
56
+ engine-agnostic raw tool defs (built on `@modelcontextprotocol/sdk`). The
57
+ Claude-SDK-shaped in-process servers are built **lazily** — only on the Claude
58
+ path — inside `getEnabledMcpServers()` (now `async`), which lazy-loads
59
+ `createSdkMcpServer`/`tool` from `@anthropic-ai/claude-agent-sdk` via
60
+ `loadEngineSdk`. Non-Claude engines never touch the Claude SDK; they already
61
+ use the remote HTTP bridge (`createRemoteMcpServer`).
62
+ - In-process execution for Claude Code via `createSdkMcpServer` (loaded on demand)
56
63
  - Remote HTTP MCP server (Streamable HTTP) for Open Code, Codex, and
57
64
  Copilot via `createRemoteMcpServer` mounted at `/mcp`
58
65
  - All engines execute handlers in-process (no subprocess, no bridge)
@@ -238,7 +245,8 @@ servers/browser-automation/
238
245
  └─> User config merged with registry automatically
239
246
  ↓
240
247
  4. Claude Agent SDK (stream.ts)
241
- └─> Uses getEnabledMcpServers()
248
+ └─> Uses await getEnabledMcpServers() — builds Claude-SDK servers lazily
249
+ from the raw defs (lazy-loads @anthropic-ai/claude-agent-sdk)
242
250
  ↓
243
251
  5. Claude uses the tool (in-process handler execution)
244
252
  ↓
@@ -272,8 +280,11 @@ servers/browser-automation/
272
280
 
273
281
  **`defineServer`**
274
282
  Helper function to define MCP server with automatic metadata extraction.
275
- Stores both Claude SDK server instance AND raw tool definitions (`toolDefs`)
276
- for reuse by both engines.
283
+ Stores **engine-agnostic** raw tool definitions (`toolDefs`, built on
284
+ `@modelcontextprotocol/sdk`) — no Claude SDK dependency. The Claude-SDK-shaped
285
+ in-process server is constructed lazily from these defs on the Claude path only
286
+ (`getEnabledMcpServers()`); the remote HTTP bridge (`createRemoteMcpServer`)
287
+ builds its `McpServer` from the same defs for every other engine.
277
288
 
278
289
  **`buildServerRegistries`**
279
290
  Function to build server registries from server array.
@@ -529,13 +540,18 @@ const weatherServer = serverRegistry["weather-service"];
529
540
  ### Main Functions
530
541
 
531
542
  #### `getEnabledMcpServers()`
532
- Returns all enabled MCP servers for use with Claude SDK.
543
+ Returns all enabled MCP servers as Claude-SDK-shaped in-process servers. This
544
+ is the **only** path that touches the Claude Agent SDK: it is `async` and
545
+ lazy-loads `createSdkMcpServer`/`tool` from `@anthropic-ai/claude-agent-sdk`
546
+ (via `loadEngineSdk`) only when called — so non-Claude engines never pull the
547
+ Claude SDK in. Every other engine consumes the raw tool defs through the remote
548
+ HTTP bridge instead.
533
549
 
534
550
  ```typescript
535
551
  import { getEnabledMcpServers } from '$backend/mcp';
536
552
 
537
- const servers = getEnabledMcpServers();
538
- // Returns: Record<string, McpServerConfig>
553
+ const servers = await getEnabledMcpServers();
554
+ // Returns: Promise<Record<string, McpServerConfig>>
539
555
  ```
540
556
 
541
557
  #### `getAllowedMcpTools()`
@@ -1127,7 +1143,9 @@ export default defineServer({
1127
1143
  **Problem:** TypeScript errors in custom tool.
1128
1144
 
1129
1145
  **Solutions:**
1130
- 1. Install dependencies: `bun install zod @anthropic-ai/claude-agent-sdk`
1146
+ 1. Install dependencies: `bun install` (internal tools depend only on `zod`
1147
+ + `@modelcontextprotocol/sdk` — NOT the Claude Agent SDK, which is loaded on
1148
+ demand elsewhere)
1131
1149
  2. Verify you're importing `defineServer` from `../helper`
1132
1150
  3. Check that server name matches between `defineServer` and `config.ts`
1133
1151
  4. Verify tool names in `config.ts` match tool keys in `defineServer`
@@ -105,9 +105,9 @@ export type { ParsedMcpServer, ParsedField, ParseResult } from './external/parse
105
105
  // existing behaviour, unchanged.
106
106
 
107
107
  /** Claude Agent SDK `mcpServers`: in-process internal servers + external stdio/remote. */
108
- export function getEnabledMcpServers(context?: McpExecutionContext, profileFilter?: Set<string>): Record<string, McpServerConfig> {
108
+ export async function getEnabledMcpServers(context?: McpExecutionContext, profileFilter?: Set<string>): Promise<Record<string, McpServerConfig>> {
109
109
  return {
110
- ...internal.getEnabledMcpServers(context, profileFilter),
110
+ ...(await internal.getEnabledMcpServers(context, profileFilter)),
111
111
  ...external.getClaudeExternalMcpConfig(profileFilter)
112
112
  };
113
113
  }
@@ -5,14 +5,15 @@
5
5
  * to avoid duplication and make it easier to add new servers.
6
6
  */
7
7
 
8
- import { createSdkMcpServer, tool, type McpSdkServerConfigWithInstance, type McpServerConfig } from "@anthropic-ai/claude-agent-sdk";
8
+ import type { McpServerConfig } from "@anthropic-ai/claude-agent-sdk";
9
9
  import type { McpRemoteConfig } from '@opencode-ai/sdk';
10
10
  import type { MCPHTTPServerConfig } from '@github/copilot-sdk';
11
11
  import type { CLIMcpServerConfig as QwenMcpServerConfig } from '@qwen-code/sdk';
12
12
  import type { McpServerConfig as CursorMcpServerConfig } from '@cursor/sdk';
13
13
  import type { ServerConfig, ParsedMcpToolName, ServerName } from './types';
14
14
  import type { McpExecutionContext } from '../../engine/types';
15
- import { serverRegistry, serverFactories, serverMetadata } from './servers';
15
+ import { serverMetadata } from './servers';
16
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
16
17
  import { projectContextService } from './project-context';
17
18
  import { mcpServerQueries } from '$backend/database/queries';
18
19
  import { debug } from '$shared/utils/logger';
@@ -56,30 +57,14 @@ export const mcpServersConfig: Record<ServerName, ServerConfig> = {
56
57
  };
57
58
 
58
59
  /**
59
- * Helper to merge user config with server instances from registry
60
- */
61
- function createServerConfig<T extends Record<ServerName, ServerConfig>>(
62
- config: T
63
- ): { [K in keyof T]: T[K] & { instance: McpSdkServerConfigWithInstance } } {
64
- const result = {} as any;
65
-
66
- for (const [serverName, serverConfig] of Object.entries(config)) {
67
- result[serverName] = {
68
- ...serverConfig,
69
- instance: serverRegistry[serverName as ServerName]
70
- };
71
- }
72
-
73
- return result;
74
- }
75
-
76
- /**
77
- * MCP Servers Configuration with instances
60
+ * MCP Servers Configuration
78
61
  *
79
- * This is the final configuration used throughout the application.
80
- * Automatically merges user config with server instances.
62
+ * The final configuration used throughout the application. SDK-shaped
63
+ * in-process server instances (Claude Code) are built on demand in
64
+ * `getEnabledMcpServers`; every other path works off server names + the raw
65
+ * tool defs held in `serverMetadata`.
81
66
  */
82
- export const mcpServers: Record<string, ServerConfig & { instance: McpSdkServerConfigWithInstance }> = createServerConfig(mcpServersConfig);
67
+ export const mcpServers: Record<string, ServerConfig> = mcpServersConfig;
83
68
 
84
69
  // ============================================================================
85
70
  // Runtime enabled state (DB-backed)
@@ -130,50 +115,56 @@ function serverEnabled(serverName: string): boolean {
130
115
  * propagation — without this, background streams from Project A would
131
116
  * resolve to Project B's preview browser when the user switches projects.
132
117
  */
133
- export function getEnabledMcpServers(context?: McpExecutionContext, profileFilter?: Set<string>): Record<string, McpServerConfig> {
118
+ export async function getEnabledMcpServers(context?: McpExecutionContext, profileFilter?: Set<string>): Promise<Record<string, McpServerConfig>> {
134
119
  const enabledServers: Record<string, McpServerConfig> = {};
135
120
  const active = new Set(activeInternalServerNames(profileFilter));
121
+ const activeNames = Object.keys(mcpServers).filter(name => active.has(name));
136
122
 
137
- Object.entries(mcpServers).forEach(([serverName, serverConfig]) => {
138
- if (active.has(serverName)) {
139
- if (context) {
140
- // Create context-bound instance: wrap each tool handler so
141
- // AsyncLocalStorage context is restored on invocation, then
142
- // short-circuit if the owning stream's AbortSignal has fired
143
- // — handler never runs, no half-completed browser ops.
144
- const meta = serverMetadata[serverName as ServerName];
145
- const sdkTools = (serverConfig.tools as readonly string[]).map(toolName => {
146
- const def = meta.toolDefs[toolName];
147
- const boundHandler = async (args: any) => {
148
- return projectContextService.runWithContextAsync(context, async () => {
149
- const signal = projectContextService.getCurrentSignal();
150
- if (signal?.aborted) {
151
- return abortedToolResult(toolName);
152
- }
153
- const result = await def.handler(args);
154
- result.content = validateMcpOutput(result.content, toolName);
155
- return result;
156
- });
157
- };
158
- return tool(toolName, def.description, def.schema, boundHandler as any);
159
- });
160
- enabledServers[serverName] = createSdkMcpServer({
161
- name: meta.name,
162
- version: '1.0.0',
163
- tools: sdkTools
164
- });
165
- } else {
166
- const factory = serverFactories[serverName as ServerName];
167
- enabledServers[serverName] = factory ? factory() : serverConfig.instance;
168
- }
169
- debug.log('mcp', `✓ Enabled MCP server: ${serverName}${context ? ' (context-bound)' : ''}`);
170
- } else {
171
- debug.log('mcp', `✗ Disabled MCP server: ${serverName}`);
172
- }
173
- });
123
+ // Nothing to build → don't load the Claude Agent SDK at all.
124
+ if (activeNames.length === 0) {
125
+ debug.log('mcp', 'Total enabled MCP servers: 0');
126
+ return enabledServers;
127
+ }
174
128
 
175
- debug.log('mcp', `Total enabled MCP servers: ${Object.keys(enabledServers).length}`);
129
+ // This is the Claude in-process path ONLY (other engines consume the remote
130
+ // HTTP bridge via createRemoteMcpServer, which uses @modelcontextprotocol/sdk
131
+ // directly). Load the Claude Agent SDK's `createSdkMcpServer`/`tool` lazily so
132
+ // it is never required unless the Claude engine actually streams.
133
+ const { createSdkMcpServer, tool } = await loadEngineSdk<typeof import('@anthropic-ai/claude-agent-sdk')>(
134
+ 'claude-code', '@anthropic-ai/claude-agent-sdk'
135
+ );
176
136
 
137
+ for (const serverName of activeNames) {
138
+ const serverConfig = mcpServers[serverName];
139
+ const meta = serverMetadata[serverName as ServerName];
140
+ const sdkTools = (serverConfig.tools as readonly string[]).map(toolName => {
141
+ const def = meta.toolDefs[toolName];
142
+ // With context: wrap each handler so AsyncLocalStorage context is
143
+ // restored on invocation, then short-circuit if the owning stream's
144
+ // AbortSignal has fired — handler never runs, no half-completed
145
+ // browser ops. Without context: the raw handler (unchanged behavior).
146
+ const handler = context
147
+ ? async (args: any) => projectContextService.runWithContextAsync(context, async () => {
148
+ const signal = projectContextService.getCurrentSignal();
149
+ if (signal?.aborted) {
150
+ return abortedToolResult(toolName);
151
+ }
152
+ const result = await def.handler(args);
153
+ result.content = validateMcpOutput(result.content, toolName);
154
+ return result;
155
+ })
156
+ : def.handler;
157
+ return tool(toolName, def.description, def.schema, handler as any);
158
+ });
159
+ enabledServers[serverName] = createSdkMcpServer({
160
+ name: meta.name,
161
+ version: '1.0.0',
162
+ tools: sdkTools
163
+ });
164
+ debug.log('mcp', `✓ Enabled MCP server: ${serverName}${context ? ' (context-bound)' : ''}`);
165
+ }
166
+
167
+ debug.log('mcp', `Total enabled MCP servers: ${Object.keys(enabledServers).length}`);
177
168
  return enabledServers;
178
169
  }
179
170
 
@@ -70,7 +70,10 @@ beforeAll(async () => {
70
70
  token_hash: hashToken(sessionToken),
71
71
  expires_at: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
72
72
  created_at: new Date().toISOString(),
73
- last_active_at: new Date().toISOString()
73
+ last_active_at: new Date().toISOString(),
74
+ user_agent: null,
75
+ ip_address: null,
76
+ source: null
74
77
  });
75
78
  });
76
79
 
@@ -9,7 +9,6 @@
9
9
  * Open Code: createRemoteMcpServer() → HTTP MCP server (same process, same handlers)
10
10
  */
11
11
 
12
- import { createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk";
13
12
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
14
13
  import type { z } from "zod";
15
14
  import { projectContextService } from '../project-context';
@@ -56,9 +55,6 @@ interface ServerWithMeta<
56
55
  TName extends string,
57
56
  TToolNames extends readonly string[]
58
57
  > {
59
- server: ReturnType<typeof createSdkMcpServer>;
60
- /** Factory that creates a fresh SDK server instance (new Protocol, safe for concurrent use) */
61
- createInstance: () => ReturnType<typeof createSdkMcpServer>;
62
58
  meta: {
63
59
  readonly name: TName;
64
60
  /** Human-facing title shown in Settings → MCP and the Chat tool header. */
@@ -96,10 +92,8 @@ export function defineServer<
96
92
  // Extract tool names
97
93
  const toolNames = Object.keys(config.tools) as Array<keyof TConfig['tools'] & string>;
98
94
 
99
- // Build raw tool definitions (engine-agnostic)
95
+ // Build raw tool definitions (engine-agnostic) and store for reuse.
100
96
  const toolDefs: Record<string, RawToolDef> = {};
101
-
102
- // Build raw tool definitions (engine-agnostic) and store for reuse
103
97
  toolNames.forEach((toolName) => {
104
98
  const toolDef = config.tools[toolName] as any;
105
99
  const schema = toolDef.schema || {};
@@ -111,24 +105,10 @@ export function defineServer<
111
105
  };
112
106
  });
113
107
 
114
- // Factory: creates a fresh SDK server instance with new Protocol (safe for concurrent use)
115
- const createInstance = () => {
116
- const sdkTools = toolNames.map((toolName) => {
117
- const def = toolDefs[toolName as string];
118
- return tool(toolName as string, def.description, def.schema, def.handler as any);
119
- });
120
-
121
- return createSdkMcpServer({
122
- name: config.name,
123
- version: config.version,
124
- tools: sdkTools
125
- });
126
- };
127
-
128
- // Return server with metadata and factory
108
+ // Return metadata + raw tool defs only. The SDK-shaped in-process server
109
+ // instances (Claude Code) are built lazily in mcp/internal/config.ts, so the
110
+ // Claude Agent SDK is not imported unless the Claude engine actually streams.
129
111
  return {
130
- server: createInstance(),
131
- createInstance,
132
112
  meta: {
133
113
  name: config.name,
134
114
  title: config.title,
@@ -147,24 +127,14 @@ export function buildServerRegistries<
147
127
  T extends readonly ServerWithMeta<string, readonly string[]>[]
148
128
  >(servers: T) {
149
129
  const metadata = {} as any;
150
- const registry = {} as any;
151
- const factories = {} as any;
152
130
 
153
131
  for (const server of servers) {
154
132
  metadata[server.meta.name] = server.meta;
155
- registry[server.meta.name] = server.server;
156
- factories[server.meta.name] = server.createInstance;
157
133
  }
158
134
 
159
135
  return {
160
136
  metadata: metadata as {
161
137
  [K in T[number]['meta']['name']]: Extract<T[number], { meta: { name: K } }>['meta']
162
- },
163
- registry: registry as {
164
- [K in T[number]['meta']['name']]: Extract<T[number], { meta: { name: K } }>['server']
165
- },
166
- factories: factories as {
167
- [K in T[number]['meta']['name']]: () => Extract<T[number], { meta: { name: K } }>['server']
168
138
  }
169
139
  };
170
140
  }
@@ -29,21 +29,12 @@ export const allServers = [
29
29
  ] as const;
30
30
 
31
31
  /**
32
- * Auto-build registries from server array
32
+ * Auto-build the metadata registry from the server array. Only engine-agnostic
33
+ * metadata + raw tool defs live here; SDK-shaped instances are built on demand.
33
34
  */
34
- const { metadata, registry, factories } = buildServerRegistries(allServers);
35
+ const { metadata } = buildServerRegistries(allServers);
35
36
 
36
37
  /**
37
38
  * Server Metadata Registry - Defines available servers and their tools
38
39
  */
39
- export const serverMetadata = metadata;
40
-
41
- /**
42
- * Server Instance Registry - Maps server names to SDK instances
43
- */
44
- export const serverRegistry = registry;
45
-
46
- /**
47
- * Server Factory Registry - Creates fresh SDK instances (safe for concurrent streams)
48
- */
49
- export const serverFactories = factories;
40
+ export const serverMetadata = metadata;
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Public origin resolution for Remote Access.
3
+ *
4
+ * "Make this Clopen reachable from another device" needs a public origin to
5
+ * build share links against. Where that origin comes from is adaptive, so the
6
+ * caller never has to think about tunnels vs domains:
7
+ *
8
+ * 1. `configured` — an admin-set public URL (system setting `publicBaseUrl`),
9
+ * for VPS/reverse-proxy deployments where the browser can't see the real
10
+ * hostname.
11
+ * 2. `domain` — the browser is already hitting Clopen on a non-local origin
12
+ * (a real deployment), so reuse that origin directly. No tunnel needed.
13
+ * 3. `tunnel` — local install: start (or reuse) a Cloudflare quick tunnel to
14
+ * Clopen's own server port and use its `*.trycloudflare.com` URL.
15
+ */
16
+
17
+ import { tunnelKit, portFromService } from './tunnel-config';
18
+ import { SERVER_ENV } from '../utils/env';
19
+ import { settingsQueries } from '$backend/database/queries';
20
+ import { debug } from '$shared/utils/logger';
21
+
22
+ export type PublicOriginSource = 'configured' | 'domain' | 'tunnel';
23
+
24
+ export interface PublicOrigin {
25
+ /** Absolute origin, no trailing slash (e.g. https://foo.trycloudflare.com). */
26
+ origin: string;
27
+ source: PublicOriginSource;
28
+ }
29
+
30
+ /** Hostnames that are not reachable by another device — force a tunnel. */
31
+ function isLocalHostname(hostname: string): boolean {
32
+ const h = hostname.toLowerCase();
33
+ if (h === 'localhost' || h.endsWith('.localhost')) return true;
34
+ if (h === '127.0.0.1' || h === '::1' || h === '0.0.0.0') return true;
35
+ // Private LAN ranges (RFC1918 + link-local + CGNAT).
36
+ if (/^10\./.test(h)) return true;
37
+ if (/^192\.168\./.test(h)) return true;
38
+ if (/^172\.(1[6-9]|2\d|3[01])\./.test(h)) return true;
39
+ if (/^169\.254\./.test(h)) return true;
40
+ if (/^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./.test(h)) return true;
41
+ // `.local` mDNS names resolve on-LAN only.
42
+ if (h.endsWith('.local')) return true;
43
+ return false;
44
+ }
45
+
46
+ /** Strip a trailing slash so callers can append `/#invite/...` cleanly. */
47
+ function normalizeOrigin(url: string): string {
48
+ return url.replace(/\/+$/, '');
49
+ }
50
+
51
+ /** Read the admin-configured public base URL from system settings, if any. */
52
+ function getConfiguredPublicBaseUrl(): string | null {
53
+ try {
54
+ const setting = settingsQueries.get('system:settings');
55
+ if (!setting?.value) return null;
56
+ const parsed = typeof setting.value === 'string' ? JSON.parse(setting.value) : setting.value;
57
+ const url = parsed?.publicBaseUrl;
58
+ if (typeof url === 'string' && url.trim()) {
59
+ return normalizeOrigin(url.trim());
60
+ }
61
+ } catch {
62
+ // Settings may not exist yet.
63
+ }
64
+ return null;
65
+ }
66
+
67
+ /** Find an already-running quick tunnel pointing at the given local port. */
68
+ function findQuickTunnelForPort(port: number): string | null {
69
+ for (const t of tunnelKit.list()) {
70
+ if (t.type === 'quick' && portFromService(t.service) === port && t.publicUrl) {
71
+ return normalizeOrigin(t.publicUrl);
72
+ }
73
+ }
74
+ return null;
75
+ }
76
+
77
+ /**
78
+ * Resolve a public origin for Remote Access share links. `requestOrigin` is the
79
+ * browser's own `window.location.origin` (passed by the client), used to detect
80
+ * the already-public `domain` case.
81
+ */
82
+ export async function resolvePublicOrigin(requestOrigin?: string): Promise<PublicOrigin> {
83
+ // 1. Explicitly configured public URL wins.
84
+ const configured = getConfiguredPublicBaseUrl();
85
+ if (configured) {
86
+ return { origin: configured, source: 'configured' };
87
+ }
88
+
89
+ // 2. Already served on a real (non-local) origin — reuse it.
90
+ if (requestOrigin) {
91
+ try {
92
+ const url = new URL(requestOrigin);
93
+ if (!isLocalHostname(url.hostname)) {
94
+ return { origin: normalizeOrigin(requestOrigin), source: 'domain' };
95
+ }
96
+ } catch {
97
+ // Malformed origin — fall through to tunnel.
98
+ }
99
+ }
100
+
101
+ // 3. Local install — tunnel Clopen's own port. In dev the app is served by
102
+ // Vite on PORT_FRONTEND (which proxies to the backend), so tunnel that; in
103
+ // production frontend and backend share PORT.
104
+ const port = SERVER_ENV.isDevelopment ? SERVER_ENV.PORT_FRONTEND : SERVER_ENV.PORT;
105
+
106
+ const existing = findQuickTunnelForPort(port);
107
+ if (existing) {
108
+ return { origin: existing, source: 'tunnel' };
109
+ }
110
+
111
+ debug.log('tunnel', `[remote-access] Starting quick tunnel for Clopen port ${port}`);
112
+ await tunnelKit.bin.ensure();
113
+ const { publicUrl } = await tunnelKit.quick.start({ service: port, autoStopMinutes: 0 });
114
+ if (!publicUrl) {
115
+ throw new Error('Failed to establish a public tunnel');
116
+ }
117
+ return { origin: normalizeOrigin(publicUrl), source: 'tunnel' };
118
+ }