@myrialabs/clopen 0.4.32 → 0.4.33
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.
- package/backend/chat/stream-manager.ts +4 -1
- package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/db-client-connection-queries.ts +7 -2
- package/backend/database/queries/file-audit-log-queries.ts +1 -0
- package/backend/database/queries/index.ts +3 -0
- package/backend/database/queries/ssh-connection-queries.ts +244 -0
- package/backend/database/queries/ssh-known-host-queries.ts +67 -0
- package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
- package/backend/db-client/connection-manager.ts +8 -1
- package/backend/engine/adapters/codex/message-converter.ts +18 -12
- package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
- package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
- package/backend/engine/adapters/codex/stream.ts +33 -4
- package/backend/engine/adapters/copilot/stream.ts +1 -1
- package/backend/engine/adapters/cursor/stream.ts +1 -1
- package/backend/engine/adapters/qwen/stream.ts +1 -1
- package/backend/engine/docs/adapter-contract.md +7 -0
- package/backend/files/file-watcher.ts +283 -51
- package/backend/files/git-events.test.ts +110 -0
- package/backend/git/git-dirs.test.ts +132 -0
- package/backend/git/git-dirs.ts +0 -0
- package/backend/git/nested-repos.test.ts +108 -5
- package/backend/git/nested-repos.ts +103 -18
- package/backend/http/audio.ts +5 -32
- package/backend/http/bearer-auth.ts +47 -0
- package/backend/http/files-download.test.ts +146 -0
- package/backend/http/files-download.ts +109 -0
- package/backend/http/files-upload.ts +3 -29
- package/backend/http/ssh-sftp.ts +133 -0
- package/backend/index.ts +16 -2
- package/backend/mcp/README.md +34 -6
- package/backend/mcp/index.ts +8 -8
- package/backend/mcp/internal/config.ts +69 -19
- package/backend/mcp/internal/project-context.test.ts +40 -0
- package/backend/mcp/internal/project-context.ts +80 -7
- package/backend/mcp/internal/remote-server.test.ts +17 -2
- package/backend/mcp/internal/remote-server.ts +36 -3
- package/backend/mcp/internal/servers/helper.ts +48 -18
- package/backend/preview/browser/browser-video-capture.ts +51 -4
- package/backend/ssh/client-pool.ts +196 -0
- package/backend/ssh/connect.ts +375 -0
- package/backend/ssh/disk-usage.test.ts +134 -0
- package/backend/ssh/disk-usage.ts +214 -0
- package/backend/ssh/forwards.ts +309 -0
- package/backend/ssh/health.ts +141 -0
- package/backend/ssh/known-hosts.ts +96 -0
- package/backend/ssh/pty-backend.ts +215 -0
- package/backend/ssh/ptykit.ts +66 -0
- package/backend/ssh/sftp.test.ts +242 -0
- package/backend/ssh/sftp.ts +967 -0
- package/backend/ssh/socks5.test.ts +167 -0
- package/backend/ssh/socks5.ts +164 -0
- package/backend/ssh/tunnel.ts +87 -0
- package/backend/ws/db-client/connections.ts +1 -0
- package/backend/ws/files/watch.ts +5 -1
- package/backend/ws/index.ts +4 -0
- package/backend/ws/ssh/access.ts +31 -0
- package/backend/ws/ssh/connections.ts +224 -0
- package/backend/ws/ssh/forwards.ts +109 -0
- package/backend/ws/ssh/index.ts +18 -0
- package/backend/ws/ssh/sftp.ts +259 -0
- package/backend/ws/ssh/tunnel.ts +93 -0
- package/dist/assets/{index-DSvGoxp2.js → index-BF4buYmI.js} +1 -1
- package/dist/assets/{index-hu17G6tX.js → index-BW0DA8NV.js} +1 -1
- package/dist/assets/{main-BccclZsC.js → main-BbwWLJRN.js} +499 -473
- package/dist/assets/main-CCvRMXlP.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/database/schema.ts +49 -0
- package/shared/types/db-client/connection.ts +6 -0
- package/shared/types/ssh/connection.ts +80 -0
- package/shared/types/ssh/forward.ts +46 -0
- package/shared/types/ssh/index.ts +8 -0
- package/shared/types/ssh/known-host.ts +19 -0
- package/shared/types/ssh/sftp.ts +141 -0
- package/shared/utils/logger.ts +1 -0
- package/dist/assets/main-Ciuw0wF0.css +0 -1
|
@@ -20,3 +20,43 @@ describe('projectContextService.clearByProjectId', () => {
|
|
|
20
20
|
expect(projectContextService.getLastUsedProjectId()).toBe('project-2');
|
|
21
21
|
});
|
|
22
22
|
});
|
|
23
|
+
|
|
24
|
+
describe('projectContextService bridge identity', () => {
|
|
25
|
+
beforeEach(() => {
|
|
26
|
+
projectContextService.clear();
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test('a bound project wins over the most recently started stream', () => {
|
|
30
|
+
projectContextService.registerSession('session-a', 'project-a');
|
|
31
|
+
projectContextService.registerStream('stream-a', 'project-a', 'session-a', 'codex');
|
|
32
|
+
// The user moves to another project and prompts there — this is the stream
|
|
33
|
+
// the old ambient fallback would have attributed project-a's tool call to.
|
|
34
|
+
projectContextService.registerSession('session-b', 'project-b');
|
|
35
|
+
projectContextService.registerStream('stream-b', 'project-b', 'session-b', 'codex');
|
|
36
|
+
|
|
37
|
+
projectContextService.runWithContext({ projectId: 'project-a' }, () => {
|
|
38
|
+
expect(projectContextService.getCurrentProjectId()).toBe('project-a');
|
|
39
|
+
expect(projectContextService.getCurrentChatSessionId()).toBe('session-a');
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test('engine scoping ignores streams belonging to another engine', () => {
|
|
44
|
+
projectContextService.registerSession('session-a', 'project-a');
|
|
45
|
+
projectContextService.registerStream('stream-a', 'project-a', 'session-a', 'opencode');
|
|
46
|
+
projectContextService.registerSession('session-b', 'project-b');
|
|
47
|
+
projectContextService.registerStream('stream-b', 'project-b', 'session-b', 'claude-code');
|
|
48
|
+
|
|
49
|
+
expect(projectContextService.getContextForEngine('opencode')).toMatchObject({
|
|
50
|
+
projectId: 'project-a',
|
|
51
|
+
chatSessionId: 'session-a'
|
|
52
|
+
});
|
|
53
|
+
expect(projectContextService.getContextForEngine('cursor')).toBeUndefined();
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test('an unidentified caller still falls back to the most recent stream', () => {
|
|
57
|
+
projectContextService.registerSession('session-a', 'project-a');
|
|
58
|
+
projectContextService.registerStream('stream-a', 'project-a', 'session-a', 'codex');
|
|
59
|
+
|
|
60
|
+
expect(projectContextService.getCurrentProjectId()).toBe('project-a');
|
|
61
|
+
});
|
|
62
|
+
});
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
13
13
|
import { debug } from '$shared/utils/logger';
|
|
14
|
+
import type { EngineType } from '$shared/types/unified';
|
|
14
15
|
|
|
15
16
|
// Execution context for MCP tool handlers
|
|
16
17
|
interface ExecutionContext {
|
|
@@ -30,7 +31,10 @@ class ProjectContextService {
|
|
|
30
31
|
private streamProjectMap = new Map<string, string>();
|
|
31
32
|
|
|
32
33
|
// Track active streams (streamId -> context)
|
|
33
|
-
private activeStreams = new Map<
|
|
34
|
+
private activeStreams = new Map<
|
|
35
|
+
string,
|
|
36
|
+
{ chatSessionId: string; projectId: string; startedAt: number; engine?: EngineType }
|
|
37
|
+
>();
|
|
34
38
|
|
|
35
39
|
// Track the most recently active stream (for MCP tool execution context)
|
|
36
40
|
private mostRecentActiveStream: { streamId: string; chatSessionId: string; projectId: string } | null = null;
|
|
@@ -42,9 +46,10 @@ class ProjectContextService {
|
|
|
42
46
|
* Per-stream AbortSignal map. The stream-manager registers each stream's
|
|
43
47
|
* AbortController.signal here when the stream starts so MCP tool handlers
|
|
44
48
|
* can fast-fail on cancellation. The remote-MCP HTTP transport (used by
|
|
45
|
-
* OpenCode/Codex/Copilot/Qwen) does not preserve the engine's
|
|
46
|
-
* AsyncLocalStorage context across the HTTP boundary
|
|
47
|
-
*
|
|
49
|
+
* OpenCode/Codex/Copilot/Qwen/Cursor) does not preserve the engine's
|
|
50
|
+
* AsyncLocalStorage context across the HTTP boundary; the bridge re-creates
|
|
51
|
+
* it from the identity in its URL, and `mostRecentActiveStream` is the last
|
|
52
|
+
* resort for a caller that could not be identified at all.
|
|
48
53
|
*/
|
|
49
54
|
private streamSignals = new Map<string, AbortSignal>();
|
|
50
55
|
|
|
@@ -69,7 +74,7 @@ class ProjectContextService {
|
|
|
69
74
|
* Register a stream ID with its project ID
|
|
70
75
|
* Should be called when a chat stream starts
|
|
71
76
|
*/
|
|
72
|
-
registerStream(streamId: string, projectId: string, chatSessionId?: string): void {
|
|
77
|
+
registerStream(streamId: string, projectId: string, chatSessionId?: string, engine?: EngineType): void {
|
|
73
78
|
if (!streamId || !projectId) {
|
|
74
79
|
debug.warn('mcp', `⚠️ Cannot register stream: streamId='${streamId}' projectId='${projectId}'`);
|
|
75
80
|
return;
|
|
@@ -82,7 +87,8 @@ class ProjectContextService {
|
|
|
82
87
|
this.activeStreams.set(streamId, {
|
|
83
88
|
chatSessionId,
|
|
84
89
|
projectId,
|
|
85
|
-
startedAt: Date.now()
|
|
90
|
+
startedAt: Date.now(),
|
|
91
|
+
engine
|
|
86
92
|
});
|
|
87
93
|
|
|
88
94
|
// Update most recent active stream
|
|
@@ -156,6 +162,13 @@ class ProjectContextService {
|
|
|
156
162
|
}
|
|
157
163
|
}
|
|
158
164
|
}
|
|
165
|
+
if (context?.projectId) {
|
|
166
|
+
const inProject = this.mostRecentStreamInProject(context.projectId);
|
|
167
|
+
if (inProject) {
|
|
168
|
+
const signal = this.streamSignals.get(inProject.streamId);
|
|
169
|
+
if (signal) return signal;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
159
172
|
if (this.mostRecentActiveStream) {
|
|
160
173
|
return this.streamSignals.get(this.mostRecentActiveStream.streamId);
|
|
161
174
|
}
|
|
@@ -188,6 +201,60 @@ class ProjectContextService {
|
|
|
188
201
|
}
|
|
189
202
|
}
|
|
190
203
|
|
|
204
|
+
/**
|
|
205
|
+
* The most recently started live stream in `projectId`.
|
|
206
|
+
*
|
|
207
|
+
* The bridge can bind a project without a chat session — Codex's client, and
|
|
208
|
+
* therefore its bridge URL, is built once per project and shared by every
|
|
209
|
+
* chat session in it. Resolving the session inside that project is still a
|
|
210
|
+
* guess when several of them stream at once, but it is a guess confined to
|
|
211
|
+
* the right project, which is what tab ownership and cancellation need.
|
|
212
|
+
*/
|
|
213
|
+
private mostRecentStreamInProject(projectId: string): { streamId: string; chatSessionId: string } | undefined {
|
|
214
|
+
let best: { streamId: string; chatSessionId: string; startedAt: number } | undefined;
|
|
215
|
+
for (const [streamId, info] of this.activeStreams) {
|
|
216
|
+
if (info.projectId !== projectId) continue;
|
|
217
|
+
if (!best || info.startedAt > best.startedAt) {
|
|
218
|
+
best = { streamId, chatSessionId: info.chatSessionId, startedAt: info.startedAt };
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return best ? { streamId: best.streamId, chatSessionId: best.chatSessionId } : undefined;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* The execution context of the most recent stream running on `engine`.
|
|
226
|
+
*
|
|
227
|
+
* For the engines whose MCP bridge URL cannot carry the calling stream —
|
|
228
|
+
* Open Code bakes its MCP config into a server that is pooled per Profile
|
|
229
|
+
* and shared by every project — this is as precise as the bridge can be. It
|
|
230
|
+
* is still strictly narrower than "the most recent stream anywhere", which
|
|
231
|
+
* is what sent a tool call from the project the agent is working in to
|
|
232
|
+
* whichever project the user had most recently prompted in.
|
|
233
|
+
*/
|
|
234
|
+
getContextForEngine(engine: EngineType): ExecutionContext | undefined {
|
|
235
|
+
let best: { streamId: string; chatSessionId: string; projectId: string; startedAt: number } | undefined;
|
|
236
|
+
let candidates = 0;
|
|
237
|
+
|
|
238
|
+
for (const [streamId, info] of this.activeStreams) {
|
|
239
|
+
if (info.engine !== engine) continue;
|
|
240
|
+
candidates++;
|
|
241
|
+
if (!best || info.startedAt > best.startedAt) {
|
|
242
|
+
best = { streamId, chatSessionId: info.chatSessionId, projectId: info.projectId, startedAt: info.startedAt };
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
if (!best) return undefined;
|
|
247
|
+
if (candidates > 1) {
|
|
248
|
+
debug.warn(
|
|
249
|
+
'mcp',
|
|
250
|
+
`⚠️ ${candidates} ${engine} streams are live and the bridge cannot tell them apart — ` +
|
|
251
|
+
`attributing this call to the most recent one (project ${best.projectId})`
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return { chatSessionId: best.chatSessionId, projectId: best.projectId, streamId: best.streamId };
|
|
256
|
+
}
|
|
257
|
+
|
|
191
258
|
/**
|
|
192
259
|
* Get the last used project ID (fallback)
|
|
193
260
|
* This is used as a last resort when no session context is available
|
|
@@ -286,7 +353,13 @@ class ProjectContextService {
|
|
|
286
353
|
return context.chatSessionId;
|
|
287
354
|
}
|
|
288
355
|
|
|
289
|
-
// 2.
|
|
356
|
+
// 2. Within the bound project, when the caller could only name that much
|
|
357
|
+
if (context?.projectId) {
|
|
358
|
+
const inProject = this.mostRecentStreamInProject(context.projectId);
|
|
359
|
+
if (inProject) return inProject.chatSessionId;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// 3. Fallback to most recent active stream
|
|
290
363
|
if (this.mostRecentActiveStream) {
|
|
291
364
|
return this.mostRecentActiveStream.chatSessionId;
|
|
292
365
|
}
|
|
@@ -37,10 +37,10 @@ function sessionCount(userId: string): number {
|
|
|
37
37
|
return row.count;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
function mcpRequest(token?: string): Request {
|
|
40
|
+
function mcpRequest(token?: string, query = ''): Request {
|
|
41
41
|
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
|
42
42
|
if (token) headers['Authorization'] = `Bearer ${token}`;
|
|
43
|
-
return new Request(
|
|
43
|
+
return new Request(`http://localhost/mcp${query}`, {
|
|
44
44
|
method: 'POST',
|
|
45
45
|
headers,
|
|
46
46
|
body: JSON.stringify({
|
|
@@ -134,6 +134,21 @@ describe('MCP Remote Server Authentication', () => {
|
|
|
134
134
|
expect(response.status).not.toBe(401);
|
|
135
135
|
});
|
|
136
136
|
|
|
137
|
+
test('accepts a caller-identified bridge URL', async () => {
|
|
138
|
+
// Each engine's config builder addresses the bridge with the project (and
|
|
139
|
+
// where its config lives that long, the chat session) driving the call, so
|
|
140
|
+
// tool handlers are bound to it instead of guessing from ambient state.
|
|
141
|
+
// Routing must not care that the query string is there.
|
|
142
|
+
const query = '?engine=codex&project=project-a&session=session-a';
|
|
143
|
+
const response = await handleMcpRequest(mcpRequest(getMcpServiceToken(), query));
|
|
144
|
+
expect(response.status).not.toBe(401);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
test('rejects a caller-identified bridge URL without a token', async () => {
|
|
148
|
+
const response = await handleMcpRequest(mcpRequest(undefined, '?engine=opencode'));
|
|
149
|
+
expect(response.status).toBe(401);
|
|
150
|
+
});
|
|
151
|
+
|
|
137
152
|
test('accepts a valid PAT token', async () => {
|
|
138
153
|
const response = await handleMcpRequest(mcpRequest(patToken));
|
|
139
154
|
expect(response.status).not.toBe(401);
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
|
|
19
19
|
import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
|
|
20
20
|
import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
|
|
21
|
-
import { createRemoteMcpServer } from './servers/helper';
|
|
21
|
+
import { createRemoteMcpServer, type RemoteMcpCaller } from './servers/helper';
|
|
22
22
|
import { createExternalProxyServer } from '../external/proxy';
|
|
23
23
|
import { debug } from '$shared/utils/logger';
|
|
24
24
|
import { authQueries } from '$backend/database/queries';
|
|
@@ -213,14 +213,47 @@ async function handleStreamable(
|
|
|
213
213
|
return jsonRpcError(400, -32000, 'Bad Request: No valid session ID provided');
|
|
214
214
|
}
|
|
215
215
|
|
|
216
|
+
/**
|
|
217
|
+
* Who is on the other end of an internal-bridge request.
|
|
218
|
+
*
|
|
219
|
+
* Read from the query string each engine's config builder writes (see
|
|
220
|
+
* `internalBridgeUrl` in `./config.ts`), which says as much as that config's
|
|
221
|
+
* lifetime allows: the calling stream, its project, or only the engine. A URL
|
|
222
|
+
* with none of it — an older config, or a client that stripped the query —
|
|
223
|
+
* yields `undefined` and the handlers fall back to their own resolution, which
|
|
224
|
+
* is what every engine did before this existed.
|
|
225
|
+
*/
|
|
226
|
+
function callerFromRequest(request: Request): RemoteMcpCaller | undefined {
|
|
227
|
+
const params = new URL(request.url).searchParams;
|
|
228
|
+
const projectId = params.get('project') ?? undefined;
|
|
229
|
+
const chatSessionId = params.get('session') ?? undefined;
|
|
230
|
+
const engine = (params.get('engine') as EngineType | null) ?? undefined;
|
|
231
|
+
|
|
232
|
+
if (projectId) return { context: { projectId, ...(chatSessionId && { chatSessionId }) }, engine };
|
|
233
|
+
if (engine) return { engine };
|
|
234
|
+
return undefined;
|
|
235
|
+
}
|
|
236
|
+
|
|
216
237
|
/**
|
|
217
238
|
* Handle an incoming request to the INTERNAL `clopen-mcp` bridge (`/mcp`).
|
|
218
239
|
* Serves the in-process custom tools defined via `defineServer()`.
|
|
240
|
+
*
|
|
241
|
+
* The caller is read from the initialize request only, and the resulting server
|
|
242
|
+
* stays bound to that session — the same way the external bridge binds its
|
|
243
|
+
* per-engine tool filter. That is correct because the identity in the URL is a
|
|
244
|
+
* property of the engine session, not of a single tool call: a Codex turn gets
|
|
245
|
+
* a fresh subprocess and therefore a fresh MCP session, while Copilot/Qwen/
|
|
246
|
+
* Cursor keep one per chat session, which is exactly the scope of `session`.
|
|
219
247
|
*/
|
|
220
248
|
export async function handleMcpRequest(request: Request): Promise<Response> {
|
|
221
|
-
|
|
249
|
+
const caller = callerFromRequest(request);
|
|
250
|
+
const label = caller?.context
|
|
251
|
+
? `Remote MCP (${caller.engine ?? 'engine'}, project ${caller.context.projectId})`
|
|
252
|
+
: `Remote MCP${caller?.engine ? ` (${caller.engine})` : ''}`;
|
|
253
|
+
|
|
254
|
+
return handleStreamable(request, label, async () => {
|
|
222
255
|
const { allServers, enabledConfig } = await getServerDeps();
|
|
223
|
-
return { server: createRemoteMcpServer(allServers, enabledConfig) };
|
|
256
|
+
return { server: createRemoteMcpServer(allServers, enabledConfig, caller) };
|
|
224
257
|
});
|
|
225
258
|
}
|
|
226
259
|
|
|
@@ -13,6 +13,8 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
|
13
13
|
import type { z } from "zod";
|
|
14
14
|
import { projectContextService } from '../project-context';
|
|
15
15
|
import { validateMcpOutput } from '../output-validator';
|
|
16
|
+
import type { McpExecutionContext } from '$backend/engine/types';
|
|
17
|
+
import type { EngineType } from '$shared/types/unified';
|
|
16
18
|
|
|
17
19
|
/**
|
|
18
20
|
* Infer argument types from Zod schema
|
|
@@ -143,6 +145,21 @@ export function buildServerRegistries<
|
|
|
143
145
|
// Remote MCP Server for Open Code (HTTP transport, in-process execution)
|
|
144
146
|
// ============================================================================
|
|
145
147
|
|
|
148
|
+
/**
|
|
149
|
+
* Who the bridge is talking to.
|
|
150
|
+
*
|
|
151
|
+
* `context` is the calling stream, named by the query string its engine's
|
|
152
|
+
* config builder put on the bridge URL — the HTTP equivalent of the
|
|
153
|
+
* `McpExecutionContext` the in-process engines bind directly. `engine` alone is
|
|
154
|
+
* the fallback for a config that cannot name the caller (Open Code's pooled
|
|
155
|
+
* server), and is resolved per call rather than pinned, because the stream it
|
|
156
|
+
* refers to changes while the MCP session stays open.
|
|
157
|
+
*/
|
|
158
|
+
export interface RemoteMcpCaller {
|
|
159
|
+
context?: McpExecutionContext;
|
|
160
|
+
engine?: EngineType;
|
|
161
|
+
}
|
|
162
|
+
|
|
146
163
|
/**
|
|
147
164
|
* Create a McpServer instance (from @modelcontextprotocol/sdk) with tools registered
|
|
148
165
|
* from the same RawToolDef definitions used by Claude Code.
|
|
@@ -152,10 +169,12 @@ export function buildServerRegistries<
|
|
|
152
169
|
*
|
|
153
170
|
* @param servers - Server definitions from defineServer()
|
|
154
171
|
* @param enabledConfig - Which servers/tools are enabled (from mcpServersConfig)
|
|
172
|
+
* @param caller - Identity of the engine/stream on the other end of the bridge
|
|
155
173
|
*/
|
|
156
174
|
export function createRemoteMcpServer(
|
|
157
175
|
servers: readonly ServerWithMeta<string, readonly string[]>[],
|
|
158
|
-
enabledConfig: Record<string, { enabled: boolean; tools: readonly string[] }
|
|
176
|
+
enabledConfig: Record<string, { enabled: boolean; tools: readonly string[] }>,
|
|
177
|
+
caller?: RemoteMcpCaller
|
|
159
178
|
): McpServer {
|
|
160
179
|
const mcpServer = new McpServer({
|
|
161
180
|
name: 'clopen-mcp',
|
|
@@ -178,23 +197,34 @@ export function createRemoteMcpServer(
|
|
|
178
197
|
// at runtime. Cast to bridge the mismatch.
|
|
179
198
|
inputSchema: def.schema as Record<string, any>,
|
|
180
199
|
}, async (args: Record<string, unknown>) => {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
200
|
+
const run = async () => {
|
|
201
|
+
// Fast-fail when the owning chat stream has already been
|
|
202
|
+
// cancelled — the handler never runs. Without this, the
|
|
203
|
+
// engine subprocess dies on cancel but in-flight HTTP-MCP
|
|
204
|
+
// tool calls continue to drive puppeteer ops, surfacing as
|
|
205
|
+
// "preview keeps moving by itself" after interrupt.
|
|
206
|
+
const signal = projectContextService.getCurrentSignal();
|
|
207
|
+
if (signal?.aborted) {
|
|
208
|
+
return {
|
|
209
|
+
content: [{ type: 'text' as const, text: `Tool ${String(toolName)} was cancelled because the chat stream was interrupted.` }],
|
|
210
|
+
isError: true,
|
|
211
|
+
} as any;
|
|
212
|
+
}
|
|
213
|
+
const result = await def.handler(args) as any;
|
|
214
|
+
if (result?.content) {
|
|
215
|
+
result.content = validateMcpOutput(result.content, toolName as string);
|
|
216
|
+
}
|
|
217
|
+
return result;
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
// Bind the caller for the duration of the handler, exactly as the
|
|
221
|
+
// in-process path does. Without it every handler that asks "which
|
|
222
|
+
// project is this?" answers with the most recently started stream
|
|
223
|
+
// anywhere in the app.
|
|
224
|
+
const bound = caller?.context
|
|
225
|
+
?? (caller?.engine ? projectContextService.getContextForEngine(caller.engine) : undefined);
|
|
226
|
+
|
|
227
|
+
return bound ? projectContextService.runWithContextAsync(bound, run) : run();
|
|
198
228
|
});
|
|
199
229
|
}
|
|
200
230
|
}
|
|
@@ -169,6 +169,13 @@ interface VideoStreamSession {
|
|
|
169
169
|
lastEncodedAt: number;
|
|
170
170
|
/** Guards the watchdog against re-entering while a repair is in flight. */
|
|
171
171
|
repairing: boolean;
|
|
172
|
+
/**
|
|
173
|
+
* Repairs attempted since the stream last produced anything. A repair that
|
|
174
|
+
* did not restore frames must escalate rather than be repeated: the cheap
|
|
175
|
+
* one asks the page what it thinks, and a page whose own answer is the
|
|
176
|
+
* wrong one will give the same answer every time.
|
|
177
|
+
*/
|
|
178
|
+
stallRounds: number;
|
|
172
179
|
/** Codecs every viewer can decode — one encoder serves them all. */
|
|
173
180
|
codecSupport: ClientCodecSupport;
|
|
174
181
|
/** Display metrics of the most demanding viewer. */
|
|
@@ -587,6 +594,12 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
587
594
|
*/
|
|
588
595
|
private static readonly STREAM_STALL_MS = 6_000;
|
|
589
596
|
|
|
597
|
+
/**
|
|
598
|
+
* Cheap stall repairs before the watchdog stops taking the page's word for
|
|
599
|
+
* its own health and rebuilds the peer from scratch.
|
|
600
|
+
*/
|
|
601
|
+
private static readonly STALL_REPAIR_ROUNDS = 1;
|
|
602
|
+
|
|
590
603
|
private sessions = new Map<string, VideoStreamSession>();
|
|
591
604
|
private feeders = new Map<string, ScreencastFeeder>();
|
|
592
605
|
private preInjectPromises = new Map<string, Promise<boolean>>();
|
|
@@ -729,6 +742,7 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
729
742
|
scriptsPreInjected: false,
|
|
730
743
|
lastEncodedAt: 0,
|
|
731
744
|
repairing: false,
|
|
745
|
+
stallRounds: 0,
|
|
732
746
|
codecSupport: { ...DEFAULT_CODEC_SUPPORT },
|
|
733
747
|
display: {},
|
|
734
748
|
profile,
|
|
@@ -978,6 +992,20 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
978
992
|
const codecChanged = injection.codecSignature !== this.codecSignature(videoSession);
|
|
979
993
|
const needsInjection = epochMismatch || codecChanged;
|
|
980
994
|
|
|
995
|
+
// In push mode the page is only the encoder — the frames come from a CDP
|
|
996
|
+
// screencast this process owns. `capturing: true` then means "willing",
|
|
997
|
+
// not "being fed", so a feeder that has gone away leaves a session both
|
|
998
|
+
// halves call healthy and which produces nothing at all. That state is
|
|
999
|
+
// self-sustaining: the page keeps answering, so this check keeps taking
|
|
1000
|
+
// the cheap branch, and the viewer keeps waiting for a first frame that
|
|
1001
|
+
// no longer has a source.
|
|
1002
|
+
const sourceMissing =
|
|
1003
|
+
!needsInjection &&
|
|
1004
|
+
!!health?.capturing &&
|
|
1005
|
+
health.captureMode === 'push' &&
|
|
1006
|
+
!videoSession.paused &&
|
|
1007
|
+
!this.feeders.has(sessionId);
|
|
1008
|
+
|
|
981
1009
|
if (needsInjection) {
|
|
982
1010
|
const reason = options.force
|
|
983
1011
|
? 'forced'
|
|
@@ -993,7 +1021,10 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
993
1021
|
this.feeders.get(sessionId)?.invalidatePeerHandle();
|
|
994
1022
|
}
|
|
995
1023
|
|
|
996
|
-
if (needsInjection || !health?.capturing) {
|
|
1024
|
+
if (needsInjection || !health?.capturing || sourceMissing) {
|
|
1025
|
+
if (sourceMissing) {
|
|
1026
|
+
debug.warn('webcodecs', `Page for ${sessionId} reports capturing with no frame source — rebuilding it`);
|
|
1027
|
+
}
|
|
997
1028
|
const started = await this.startPageCapture(page);
|
|
998
1029
|
if (!started) {
|
|
999
1030
|
debug.error('webcodecs', `Page refused to start capturing for ${sessionId}`);
|
|
@@ -1593,10 +1624,23 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
1593
1624
|
if (videoSession.lastEncodedAt === 0 || silentFor < BrowserVideoCapture.STREAM_STALL_MS) return;
|
|
1594
1625
|
|
|
1595
1626
|
const { sessionId, tab } = videoSession;
|
|
1596
|
-
|
|
1627
|
+
videoSession.stallRounds++;
|
|
1628
|
+
|
|
1629
|
+
// The first round asks the page what state it is in and repairs from
|
|
1630
|
+
// that answer, which is cheap and keeps every viewer's peer intact. Once
|
|
1631
|
+
// that has been tried and the stream is still silent, the page's own
|
|
1632
|
+
// account is the thing that cannot be trusted — so rebuild the peer
|
|
1633
|
+
// outright. Viewers lose their connection and re-handshake, which is a
|
|
1634
|
+
// visible hiccup, but they are looking at a frozen picture either way.
|
|
1635
|
+
const force = videoSession.stallRounds > BrowserVideoCapture.STALL_REPAIR_ROUNDS;
|
|
1636
|
+
debug.warn(
|
|
1637
|
+
'webcodecs',
|
|
1638
|
+
`Stream for ${sessionId} produced nothing for ${silentFor}ms — ` +
|
|
1639
|
+
`${force ? 'rebuilding the page peer' : 'repairing'} (round ${videoSession.stallRounds})`
|
|
1640
|
+
);
|
|
1597
1641
|
|
|
1598
1642
|
videoSession.repairing = true;
|
|
1599
|
-
void this.ensureLive(sessionId, tab, () => !tab.isDestroyed)
|
|
1643
|
+
void this.ensureLive(sessionId, tab, () => !tab.isDestroyed, { force })
|
|
1600
1644
|
.then((live) => {
|
|
1601
1645
|
if (live) return this.requestKeyframe(sessionId, tab);
|
|
1602
1646
|
})
|
|
@@ -1620,7 +1664,10 @@ export class BrowserVideoCapture extends EventEmitter {
|
|
|
1620
1664
|
// Frames reaching the encoder is the one signal that means the pipeline
|
|
1621
1665
|
// is genuinely alive end to end. The counter is per-window, so any
|
|
1622
1666
|
// non-zero report is proof of life for this window.
|
|
1623
|
-
if (stats.framesAttempted > 0)
|
|
1667
|
+
if (stats.framesAttempted > 0) {
|
|
1668
|
+
videoSession.lastEncodedAt = Date.now();
|
|
1669
|
+
videoSession.stallRounds = 0;
|
|
1670
|
+
}
|
|
1624
1671
|
|
|
1625
1672
|
// In-page capture can end on its own — the captured surface goes away
|
|
1626
1673
|
// on some navigations — and the page has no way to start a screencast.
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ssh-client — one live ssh2 client per saved connection, shared by everything.
|
|
3
|
+
*
|
|
4
|
+
* SSH multiplexes channels over a single transport, so a host's terminal tabs,
|
|
5
|
+
* its file browser and its port forwards all ride one authenticated connection
|
|
6
|
+
* — the user authenticates once, not once per feature.
|
|
7
|
+
*
|
|
8
|
+
* Leases decide when that connection may close. A terminal tab or a running
|
|
9
|
+
* forward holds a lease for as long as it lives; a one-shot SFTP call holds one
|
|
10
|
+
* for the length of the call. An entry with no leases is swept after IDLE_MS.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { Client as SshClient } from 'ssh2';
|
|
14
|
+
import { sshConnectionQueries } from '../database/queries';
|
|
15
|
+
import { closeChain, dial, type DialResult } from './connect';
|
|
16
|
+
import { debug } from '$shared/utils/logger';
|
|
17
|
+
|
|
18
|
+
/** How long a lease-free connection stays warm before being dropped. */
|
|
19
|
+
const IDLE_MS = 60 * 1000;
|
|
20
|
+
const SWEEP_INTERVAL_MS = 30 * 1000;
|
|
21
|
+
|
|
22
|
+
interface PoolEntry {
|
|
23
|
+
dialed: DialResult;
|
|
24
|
+
leases: number;
|
|
25
|
+
lastUsedAt: number;
|
|
26
|
+
alive: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface SshLease {
|
|
30
|
+
client: SshClient;
|
|
31
|
+
/** Release this lease. Idempotent — calling it twice does not double-count. */
|
|
32
|
+
release(): void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
class SshClientPool {
|
|
36
|
+
private entries = new Map<string, PoolEntry>();
|
|
37
|
+
private pending = new Map<string, Promise<PoolEntry>>();
|
|
38
|
+
/**
|
|
39
|
+
* Hosts the user explicitly disconnected. The pool dials on demand, so
|
|
40
|
+
* without this a "Disconnect" would be undone by the next keystroke in a
|
|
41
|
+
* terminal or click in the file browser — the button has to actually mean
|
|
42
|
+
* something. Runtime-only: a restart starts every host reconnectable.
|
|
43
|
+
*/
|
|
44
|
+
private suspended = new Set<string>();
|
|
45
|
+
private sweeperHandle: ReturnType<typeof setInterval> | null = null;
|
|
46
|
+
|
|
47
|
+
private startSweeper(): void {
|
|
48
|
+
if (this.sweeperHandle) return;
|
|
49
|
+
this.sweeperHandle = setInterval(() => this.sweepIdle(), SWEEP_INTERVAL_MS);
|
|
50
|
+
// Don't keep the process alive just for this timer.
|
|
51
|
+
(this.sweeperHandle as unknown as { unref?: () => void }).unref?.();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
private async openEntry(connectionId: string): Promise<PoolEntry> {
|
|
55
|
+
const connection = sshConnectionQueries.get(connectionId);
|
|
56
|
+
if (!connection) throw new Error('ssh connection not found');
|
|
57
|
+
|
|
58
|
+
const dialed = await dial(connection);
|
|
59
|
+
const entry: PoolEntry = { dialed, leases: 0, lastUsedAt: Date.now(), alive: true };
|
|
60
|
+
|
|
61
|
+
// A dropped transport must not be handed to the next caller. Mark the
|
|
62
|
+
// entry dead and drop it so the following acquire dials fresh.
|
|
63
|
+
const invalidate = (): void => {
|
|
64
|
+
if (!entry.alive) return;
|
|
65
|
+
entry.alive = false;
|
|
66
|
+
if (this.entries.get(connectionId) === entry) {
|
|
67
|
+
this.entries.delete(connectionId);
|
|
68
|
+
}
|
|
69
|
+
debug.log('ssh', `connection ${connectionId} closed`);
|
|
70
|
+
};
|
|
71
|
+
dialed.client.on('close', invalidate);
|
|
72
|
+
dialed.client.on('end', invalidate);
|
|
73
|
+
dialed.client.on('error', (error: Error) => {
|
|
74
|
+
debug.warn('ssh', `connection ${connectionId} error: ${error.message}`);
|
|
75
|
+
invalidate();
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
sshConnectionQueries.markUsed(connectionId);
|
|
79
|
+
return entry;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Take a lease on the connection, dialing it if needed. Concurrent callers
|
|
84
|
+
* for the same host share one dial rather than racing two handshakes.
|
|
85
|
+
*/
|
|
86
|
+
async acquire(connectionId: string): Promise<SshLease> {
|
|
87
|
+
if (this.suspended.has(connectionId)) {
|
|
88
|
+
throw new Error('This host is disconnected — use Connect to open it again');
|
|
89
|
+
}
|
|
90
|
+
this.startSweeper();
|
|
91
|
+
|
|
92
|
+
const existing = this.entries.get(connectionId);
|
|
93
|
+
if (existing?.alive) {
|
|
94
|
+
return this.leaseOf(connectionId, existing);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
let inFlight = this.pending.get(connectionId);
|
|
98
|
+
if (!inFlight) {
|
|
99
|
+
inFlight = this.openEntry(connectionId).finally(() => this.pending.delete(connectionId));
|
|
100
|
+
this.pending.set(connectionId, inFlight);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const entry = await inFlight;
|
|
104
|
+
// Another caller's dial may already be registered; prefer whichever entry
|
|
105
|
+
// is live so both callers end up on the same transport.
|
|
106
|
+
const current = this.entries.get(connectionId);
|
|
107
|
+
if (current?.alive && current !== entry) {
|
|
108
|
+
closeChain(entry.dialed.chain);
|
|
109
|
+
return this.leaseOf(connectionId, current);
|
|
110
|
+
}
|
|
111
|
+
this.entries.set(connectionId, entry);
|
|
112
|
+
return this.leaseOf(connectionId, entry);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private leaseOf(connectionId: string, entry: PoolEntry): SshLease {
|
|
116
|
+
entry.leases++;
|
|
117
|
+
entry.lastUsedAt = Date.now();
|
|
118
|
+
let released = false;
|
|
119
|
+
return {
|
|
120
|
+
client: entry.dialed.client,
|
|
121
|
+
release: () => {
|
|
122
|
+
if (released) return;
|
|
123
|
+
released = true;
|
|
124
|
+
entry.leases = Math.max(0, entry.leases - 1);
|
|
125
|
+
entry.lastUsedAt = Date.now();
|
|
126
|
+
debug.log('ssh', `lease released for ${connectionId} (${entry.leases} remaining)`);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Run one operation under a lease, releasing it even if the operation throws. */
|
|
132
|
+
async use<T>(connectionId: string, operation: (client: SshClient) => Promise<T>): Promise<T> {
|
|
133
|
+
const lease = await this.acquire(connectionId);
|
|
134
|
+
try {
|
|
135
|
+
return await operation(lease.client);
|
|
136
|
+
} finally {
|
|
137
|
+
lease.release();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** True when the host currently has a live, authenticated transport. */
|
|
142
|
+
isLive(connectionId: string): boolean {
|
|
143
|
+
return this.entries.get(connectionId)?.alive === true;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** True when the user disconnected this host and has not reconnected it. */
|
|
147
|
+
isSuspended(connectionId: string): boolean {
|
|
148
|
+
return this.suspended.has(connectionId);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Close the host and refuse to redial it until `resume` is called. */
|
|
152
|
+
suspend(connectionId: string): void {
|
|
153
|
+
this.suspended.add(connectionId);
|
|
154
|
+
this.release(connectionId);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Allow the host to be dialed again. */
|
|
158
|
+
resume(connectionId: string): void {
|
|
159
|
+
this.suspended.delete(connectionId);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Close a host's transport now, whatever its leases. Used on edit and delete. */
|
|
163
|
+
release(connectionId: string): void {
|
|
164
|
+
const entry = this.entries.get(connectionId);
|
|
165
|
+
if (!entry) return;
|
|
166
|
+
this.entries.delete(connectionId);
|
|
167
|
+
entry.alive = false;
|
|
168
|
+
closeChain(entry.dialed.chain);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
private sweepIdle(): void {
|
|
172
|
+
const now = Date.now();
|
|
173
|
+
for (const [connectionId, entry] of this.entries) {
|
|
174
|
+
if (entry.leases > 0) continue;
|
|
175
|
+
if (!entry.alive || now - entry.lastUsedAt > IDLE_MS) {
|
|
176
|
+
debug.log('ssh', `idle sweep: closing ${connectionId}`);
|
|
177
|
+
this.entries.delete(connectionId);
|
|
178
|
+
entry.alive = false;
|
|
179
|
+
closeChain(entry.dialed.chain);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
closeAll(): void {
|
|
185
|
+
this.suspended.clear();
|
|
186
|
+
for (const connectionId of [...this.entries.keys()]) {
|
|
187
|
+
this.release(connectionId);
|
|
188
|
+
}
|
|
189
|
+
if (this.sweeperHandle) {
|
|
190
|
+
clearInterval(this.sweeperHandle);
|
|
191
|
+
this.sweeperHandle = null;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export const sshClientPool = new SshClientPool();
|