@myrialabs/clopen 0.3.11 → 0.3.13
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/auth/session-invalidation.test.ts +116 -0
- package/backend/auth/session-invalidation.ts +78 -0
- package/backend/chat/stream-manager.ts +4 -0
- package/backend/database/migrations/036_create_auth_audit_log.ts +30 -0
- package/backend/database/migrations/037_repair_auth_audit_log_schema.ts +38 -0
- package/backend/database/migrations/index.ts +14 -0
- package/backend/database/queries/audit-log-queries.test.ts +162 -0
- package/backend/database/queries/audit-log-queries.ts +98 -0
- package/backend/database/queries/index.ts +2 -1
- package/backend/engine/README.md +101 -29
- package/backend/engine/adapters/claude/message-converter.ts +1 -0
- package/backend/engine/adapters/codex/stream.ts +54 -1
- package/backend/engine/adapters/copilot/stream.ts +79 -19
- package/backend/engine/adapters/opencode/stream.ts +23 -23
- package/backend/engine/adapters/qwen/stream.ts +83 -1
- package/backend/engine/structured-helpers.ts +59 -0
- package/backend/files/file-archive.ts +191 -0
- package/backend/files/file-operations.ts +25 -61
- package/backend/files/file-size-limit.test.ts +85 -0
- package/backend/files/file-size-limit.ts +52 -0
- package/backend/git/git-service.ts +48 -4
- package/backend/http/files-upload.ts +168 -0
- package/backend/index.ts +14 -0
- package/backend/mcp/config.ts +4 -1
- package/backend/mcp/output-validator.test.ts +52 -0
- package/backend/mcp/output-validator.ts +103 -0
- package/backend/mcp/project-context.test.ts +22 -0
- package/backend/mcp/project-context.ts +35 -0
- package/backend/mcp/servers/helper.ts +11 -2
- package/backend/project/status-manager.test.ts +32 -0
- package/backend/project/status-manager.ts +7 -0
- package/backend/projects/project-cleanup-registry.test.ts +48 -0
- package/backend/projects/project-cleanup-registry.ts +44 -0
- package/backend/projects/project-cleanup.integration.test.ts +36 -0
- package/backend/projects/project-cleanup.ts +32 -0
- package/backend/terminal/pty-session-manager.ts +3 -0
- package/backend/terminal/stream-manager.ts +1 -1
- package/backend/utils/ws.ts +46 -0
- package/backend/ws/auth/index.ts +4 -0
- package/backend/ws/auth/login.ts +31 -19
- package/backend/ws/auth/users.ts +21 -2
- package/backend/ws/chat/stream.ts +11 -0
- package/backend/ws/files/path-access.test.ts +166 -0
- package/backend/ws/files/path-access.ts +56 -22
- package/backend/ws/files/read.ts +5 -5
- package/backend/ws/files/search.ts +4 -0
- package/backend/ws/files/write.ts +47 -25
- package/backend/ws/git/commit-message.ts +12 -5
- package/backend/ws/git/remote.ts +6 -3
- package/backend/ws/message-rate-limiter.test.ts +79 -0
- package/backend/ws/message-rate-limiter.ts +134 -0
- package/backend/ws/projects/crud.ts +3 -0
- package/backend/ws/terminal/session.ts +1 -0
- package/dist/assets/main-BqiSLc8F.css +1 -0
- package/dist/assets/main-DOVudc3_.js +354 -0
- package/dist/index.html +2 -2
- package/package.json +8 -7
- package/shared/types/git.ts +4 -2
- package/shared/types/stores/settings.ts +4 -0
- package/shared/types/unified/index.ts +1 -0
- package/shared/types/unified/stream.ts +8 -0
- package/shared/utils/logger.ts +1 -0
- package/shared/utils/ws-server.ts +17 -6
- package/backend/engine/adapters/copilot/session-fork.ts +0 -111
- package/dist/assets/index-DmghE6mf.js +0 -2
- package/dist/assets/main-DiDuzJJh.js +0 -318
- package/dist/assets/main-N1w7Llvp.css +0 -1
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP upload route for files.
|
|
3
|
+
*
|
|
4
|
+
* The WebSocket-based upload path was wedging on the Vite dev proxy for
|
|
5
|
+
* large transfers — the proxy reports `write EPIPE` and the client request
|
|
6
|
+
* times out. HTTP is purpose-built for streaming large request bodies and
|
|
7
|
+
* the same Vite proxy forwards it cleanly, so we route uploads here.
|
|
8
|
+
*
|
|
9
|
+
* Auth: `Authorization: Bearer <session-token>` (same token issued by
|
|
10
|
+
* `auth:login` and stored in `localStorage` on the frontend).
|
|
11
|
+
*
|
|
12
|
+
* Query: `targetPath`, `fileName`, `fileSize` (decimal bytes).
|
|
13
|
+
*
|
|
14
|
+
* Body: raw file bytes (no multipart wrapping).
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { Elysia } from 'elysia';
|
|
18
|
+
import { join } from 'node:path';
|
|
19
|
+
import { mkdir, rename, stat, unlink } from 'node:fs/promises';
|
|
20
|
+
|
|
21
|
+
import { debug } from '$shared/utils/logger';
|
|
22
|
+
import { hashToken } from '../auth/tokens';
|
|
23
|
+
import { authQueries } from '../database/queries';
|
|
24
|
+
import { requireFilePathAccessFor } from '../ws/files/path-access';
|
|
25
|
+
import { validateFileSize } from '../files/file-size-limit';
|
|
26
|
+
|
|
27
|
+
type AuthIdentity = { userId: string; role: string };
|
|
28
|
+
|
|
29
|
+
function authenticate(request: Request): AuthIdentity {
|
|
30
|
+
const header = request.headers.get('authorization') || request.headers.get('Authorization');
|
|
31
|
+
if (!header || !header.toLowerCase().startsWith('bearer ')) {
|
|
32
|
+
throw Object.assign(new Error('Authorization required'), { status: 401 });
|
|
33
|
+
}
|
|
34
|
+
const token = header.slice(7).trim();
|
|
35
|
+
if (!token) {
|
|
36
|
+
throw Object.assign(new Error('Authorization required'), { status: 401 });
|
|
37
|
+
}
|
|
38
|
+
const session = authQueries.getSessionByTokenHash(hashToken(token));
|
|
39
|
+
if (!session) {
|
|
40
|
+
throw Object.assign(new Error('Invalid session token'), { status: 401 });
|
|
41
|
+
}
|
|
42
|
+
if (new Date(session.expires_at) < new Date()) {
|
|
43
|
+
throw Object.assign(new Error('Session expired'), { status: 401 });
|
|
44
|
+
}
|
|
45
|
+
const user = authQueries.getUserById(session.user_id);
|
|
46
|
+
if (!user) {
|
|
47
|
+
throw Object.assign(new Error('User not found'), { status: 401 });
|
|
48
|
+
}
|
|
49
|
+
authQueries.updateLastActive(session.id);
|
|
50
|
+
return { userId: user.id, role: user.role };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({ request, query }) => {
|
|
54
|
+
let identity: AuthIdentity;
|
|
55
|
+
try {
|
|
56
|
+
identity = authenticate(request);
|
|
57
|
+
} catch (error) {
|
|
58
|
+
const status = (error as { status?: number }).status ?? 401;
|
|
59
|
+
const message = error instanceof Error ? error.message : 'Unauthorized';
|
|
60
|
+
return new Response(message, { status });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const targetPathParam = typeof query.targetPath === 'string' ? query.targetPath : '';
|
|
64
|
+
const fileNameParam = typeof query.fileName === 'string' ? query.fileName : '';
|
|
65
|
+
const fileSizeParam = typeof query.fileSize === 'string' ? Number(query.fileSize) : NaN;
|
|
66
|
+
|
|
67
|
+
if (!targetPathParam || !fileNameParam) {
|
|
68
|
+
return new Response('Missing required query parameters: targetPath, fileName', { status: 400 });
|
|
69
|
+
}
|
|
70
|
+
if (!Number.isFinite(fileSizeParam) || fileSizeParam < 0) {
|
|
71
|
+
return new Response('Invalid fileSize query parameter', { status: 400 });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
try {
|
|
75
|
+
validateFileSize(fileSizeParam);
|
|
76
|
+
} catch (error) {
|
|
77
|
+
return new Response(error instanceof Error ? error.message : 'Invalid file size', { status: 413 });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
let resolvedTarget: string;
|
|
81
|
+
let resolvedFinal: string;
|
|
82
|
+
try {
|
|
83
|
+
resolvedTarget = await requireFilePathAccessFor(targetPathParam, identity.role, identity.userId);
|
|
84
|
+
const tentativeFinal = join(resolvedTarget, fileNameParam);
|
|
85
|
+
resolvedFinal = await requireFilePathAccessFor(tentativeFinal, identity.role, identity.userId);
|
|
86
|
+
} catch (error) {
|
|
87
|
+
const message = error instanceof Error ? error.message : 'Access denied';
|
|
88
|
+
return new Response(message, { status: 403 });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
try {
|
|
92
|
+
const targetStat = await stat(resolvedTarget).catch(() => null);
|
|
93
|
+
if (!targetStat) {
|
|
94
|
+
await mkdir(resolvedTarget, { recursive: true });
|
|
95
|
+
}
|
|
96
|
+
} catch (error) {
|
|
97
|
+
const message = error instanceof Error ? error.message : 'Failed to prepare target directory';
|
|
98
|
+
return new Response(message, { status: 500 });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (await Bun.file(resolvedFinal).exists()) {
|
|
102
|
+
return new Response('File already exists', { status: 409 });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (!request.body) {
|
|
106
|
+
return new Response('Request body is empty', { status: 400 });
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const tempPath = `${resolvedFinal}.${crypto.randomUUID()}.partial`;
|
|
110
|
+
const writer = Bun.file(tempPath).writer();
|
|
111
|
+
let written = 0;
|
|
112
|
+
|
|
113
|
+
const cleanupTemp = async () => {
|
|
114
|
+
try { await writer.end(); } catch { /* best-effort */ }
|
|
115
|
+
try { await unlink(tempPath); } catch { /* best-effort */ }
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
try {
|
|
119
|
+
const reader = request.body.getReader();
|
|
120
|
+
while (true) {
|
|
121
|
+
const { done, value } = await reader.read();
|
|
122
|
+
if (done) break;
|
|
123
|
+
if (!value) continue;
|
|
124
|
+
const incoming = value.byteLength;
|
|
125
|
+
if (written + incoming > fileSizeParam) {
|
|
126
|
+
await cleanupTemp();
|
|
127
|
+
return new Response('Received more bytes than declared file size', { status: 400 });
|
|
128
|
+
}
|
|
129
|
+
writer.write(value);
|
|
130
|
+
written += incoming;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
await writer.end();
|
|
134
|
+
|
|
135
|
+
if (written !== fileSizeParam) {
|
|
136
|
+
await unlink(tempPath).catch(() => {});
|
|
137
|
+
return new Response(`Incomplete upload: received ${written} of ${fileSizeParam} bytes`, { status: 400 });
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
try {
|
|
141
|
+
validateFileSize(written);
|
|
142
|
+
} catch (error) {
|
|
143
|
+
await unlink(tempPath).catch(() => {});
|
|
144
|
+
return new Response(error instanceof Error ? error.message : 'File too large', { status: 413 });
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Race-check: refuse to overwrite if the destination appeared mid-upload.
|
|
148
|
+
if (await Bun.file(resolvedFinal).exists()) {
|
|
149
|
+
await unlink(tempPath).catch(() => {});
|
|
150
|
+
return new Response('File already exists', { status: 409 });
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
await rename(tempPath, resolvedFinal);
|
|
154
|
+
const stats = await stat(resolvedFinal);
|
|
155
|
+
|
|
156
|
+
return Response.json({
|
|
157
|
+
message: 'File uploaded successfully',
|
|
158
|
+
path: resolvedFinal,
|
|
159
|
+
size: stats.size,
|
|
160
|
+
modified: stats.mtime.toISOString()
|
|
161
|
+
});
|
|
162
|
+
} catch (error) {
|
|
163
|
+
await cleanupTemp();
|
|
164
|
+
debug.error('file', 'HTTP upload error:', error);
|
|
165
|
+
const message = error instanceof Error ? error.message : 'Upload failed';
|
|
166
|
+
return new Response(message, { status: 500 });
|
|
167
|
+
}
|
|
168
|
+
});
|
package/backend/index.ts
CHANGED
|
@@ -28,6 +28,10 @@ import { statSync } from 'node:fs';
|
|
|
28
28
|
// Import WebSocket router
|
|
29
29
|
import { wsRouter } from './ws';
|
|
30
30
|
|
|
31
|
+
// HTTP upload route — bypasses the Vite WS proxy, which corrupts sustained
|
|
32
|
+
// binary transfers with `write EPIPE`. See backend/http/files-upload.ts.
|
|
33
|
+
import { filesUploadRoute } from './http/files-upload';
|
|
34
|
+
|
|
31
35
|
// Import browser preview manager for graceful shutdown
|
|
32
36
|
import { browserPreviewServiceManager } from './preview';
|
|
33
37
|
|
|
@@ -39,6 +43,7 @@ import { checkRouteAccess } from './auth/permissions';
|
|
|
39
43
|
import { authRateLimiter } from './auth';
|
|
40
44
|
import { sessionCleanupScheduler } from './auth/session-cleanup';
|
|
41
45
|
import { ws as wsServer } from './utils/ws';
|
|
46
|
+
import { messageRateLimiter } from './ws/message-rate-limiter';
|
|
42
47
|
|
|
43
48
|
// Register auth gate on WebSocket router — blocks unauthenticated/unauthorized access
|
|
44
49
|
wsRouter.setAuthMiddleware(async (conn, action) => {
|
|
@@ -47,6 +52,11 @@ wsRouter.setAuthMiddleware(async (conn, action) => {
|
|
|
47
52
|
return checkRouteAccess(action, isAuth, role);
|
|
48
53
|
});
|
|
49
54
|
|
|
55
|
+
// Register message rate limiter on WebSocket router — prevents DoS via message spam
|
|
56
|
+
wsRouter.setRateLimiter((conn, action) => {
|
|
57
|
+
return messageRateLimiter.checkRateLimit(conn, action);
|
|
58
|
+
});
|
|
59
|
+
|
|
50
60
|
/**
|
|
51
61
|
* Clopen - Elysia Backend Server
|
|
52
62
|
*
|
|
@@ -86,6 +96,10 @@ const app = new Elysia()
|
|
|
86
96
|
// Handles GET (SSE stream), POST (JSON-RPC), DELETE (session close)
|
|
87
97
|
.all('/mcp', async ({ request }) => handleMcpRequest(request))
|
|
88
98
|
|
|
99
|
+
// HTTP file upload — mounted before the WS plugin so /api/files/upload
|
|
100
|
+
// stays on the HTTP path through the Vite dev proxy.
|
|
101
|
+
.use(filesUploadRoute)
|
|
102
|
+
|
|
89
103
|
// Mount WebSocket router (all functionality now via WebSocket)
|
|
90
104
|
.use(wsRouter.asPlugin('/ws'));
|
|
91
105
|
|
package/backend/mcp/config.ts
CHANGED
|
@@ -15,6 +15,7 @@ import { serverRegistry, serverFactories, serverMetadata } from './servers';
|
|
|
15
15
|
import { projectContextService } from './project-context';
|
|
16
16
|
import { debug } from '$shared/utils/logger';
|
|
17
17
|
import { SERVER_ENV } from '../utils/env';
|
|
18
|
+
import { validateMcpOutput } from './output-validator';
|
|
18
19
|
|
|
19
20
|
/**
|
|
20
21
|
* User-defined MCP Servers Configuration
|
|
@@ -117,7 +118,9 @@ export function getEnabledMcpServers(context?: McpExecutionContext): Record<stri
|
|
|
117
118
|
if (signal?.aborted) {
|
|
118
119
|
return abortedToolResult(toolName);
|
|
119
120
|
}
|
|
120
|
-
|
|
121
|
+
const result = await def.handler(args);
|
|
122
|
+
result.content = validateMcpOutput(result.content, toolName);
|
|
123
|
+
return result;
|
|
121
124
|
});
|
|
122
125
|
};
|
|
123
126
|
return tool(toolName, def.description, def.schema, boundHandler as any);
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { validateMcpOutput } from './output-validator';
|
|
3
|
+
|
|
4
|
+
const MB = 1024 * 1024;
|
|
5
|
+
|
|
6
|
+
describe('validateMcpOutput', () => {
|
|
7
|
+
test('truncates oversized text output to the configured text budget', () => {
|
|
8
|
+
const oversizedText = 'a'.repeat((10 * MB) + 8_192);
|
|
9
|
+
|
|
10
|
+
const result = validateMcpOutput([{ type: 'text', text: oversizedText }], 'tool-a');
|
|
11
|
+
|
|
12
|
+
expect(result).toHaveLength(1);
|
|
13
|
+
expect(result[0].type).toBe('text');
|
|
14
|
+
expect(result[0].text).toContain('[Content truncated due to size limit]');
|
|
15
|
+
expect(new TextEncoder().encode(result[0].text ?? '').length).toBeLessThanOrEqual(10 * MB);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
test('replaces oversized image output with explanatory text', () => {
|
|
19
|
+
const oversizedImage = 'a'.repeat(Math.ceil((6 * MB) / 0.75));
|
|
20
|
+
|
|
21
|
+
const result = validateMcpOutput([
|
|
22
|
+
{ type: 'image', data: oversizedImage, mimeType: 'image/png' }
|
|
23
|
+
], 'take_screenshot');
|
|
24
|
+
|
|
25
|
+
expect(result).toEqual([
|
|
26
|
+
{
|
|
27
|
+
type: 'text',
|
|
28
|
+
text: expect.stringContaining('[Image omitted: size')
|
|
29
|
+
}
|
|
30
|
+
]);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('stops once sanitized total output exceeds the overall cap', () => {
|
|
34
|
+
const elevenMbText = 'b'.repeat(11 * MB);
|
|
35
|
+
const sixMbText = 'c'.repeat(6 * MB);
|
|
36
|
+
const trailingText = 'should never appear';
|
|
37
|
+
|
|
38
|
+
const result = validateMcpOutput([
|
|
39
|
+
{ type: 'text', text: elevenMbText },
|
|
40
|
+
{ type: 'text', text: sixMbText },
|
|
41
|
+
{ type: 'text', text: trailingText }
|
|
42
|
+
], 'tool-b');
|
|
43
|
+
|
|
44
|
+
expect(result).toHaveLength(2);
|
|
45
|
+
expect(result[0].text).toContain('[Content truncated due to size limit]');
|
|
46
|
+
expect(result[1]).toEqual({
|
|
47
|
+
type: 'text',
|
|
48
|
+
text: '\n\n[Additional content omitted due to total size limit]'
|
|
49
|
+
});
|
|
50
|
+
expect(result.some(item => item.text === trailingText)).toBe(false);
|
|
51
|
+
});
|
|
52
|
+
});
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP Tool Output Validator
|
|
3
|
+
*
|
|
4
|
+
* Validates and sanitizes MCP tool outputs before forwarding to AI models.
|
|
5
|
+
* Prevents memory pressure from oversized tool responses.
|
|
6
|
+
*
|
|
7
|
+
* Limits:
|
|
8
|
+
* - Text content: 10 MB per tool response
|
|
9
|
+
* - Image content: 5 MB per image
|
|
10
|
+
* - Total content array: 15 MB per tool call
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { debug } from '$shared/utils/logger';
|
|
14
|
+
|
|
15
|
+
const LIMITS = {
|
|
16
|
+
maxTextSize: 10 * 1024 * 1024,
|
|
17
|
+
maxImageSize: 5 * 1024 * 1024,
|
|
18
|
+
maxTotalSize: 15 * 1024 * 1024
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
interface MCPContent {
|
|
22
|
+
type: string;
|
|
23
|
+
text?: string;
|
|
24
|
+
data?: string;
|
|
25
|
+
mimeType?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function estimateTextSize(text: string): number {
|
|
29
|
+
return new TextEncoder().encode(text).length;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function estimateImageSize(base64Data: string): number {
|
|
33
|
+
return Math.ceil(base64Data.length * 0.75);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function truncateText(text: string, maxSize: number): string {
|
|
37
|
+
if (estimateTextSize(text) <= maxSize) return text;
|
|
38
|
+
|
|
39
|
+
const truncationMessage = '\n\n[Content truncated due to size limit]';
|
|
40
|
+
const messageSize = estimateTextSize(truncationMessage);
|
|
41
|
+
if (messageSize >= maxSize) return truncationMessage;
|
|
42
|
+
|
|
43
|
+
let low = 0;
|
|
44
|
+
let high = text.length;
|
|
45
|
+
while (low < high) {
|
|
46
|
+
const mid = Math.ceil((low + high) / 2);
|
|
47
|
+
const candidate = text.substring(0, mid) + truncationMessage;
|
|
48
|
+
if (estimateTextSize(candidate) <= maxSize) {
|
|
49
|
+
low = mid;
|
|
50
|
+
} else {
|
|
51
|
+
high = mid - 1;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return text.substring(0, low) + truncationMessage;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function validateMcpOutput(content: MCPContent[], toolName: string): MCPContent[] {
|
|
59
|
+
if (!content || content.length === 0) return content;
|
|
60
|
+
|
|
61
|
+
let totalSize = 0;
|
|
62
|
+
const sanitized: MCPContent[] = [];
|
|
63
|
+
|
|
64
|
+
for (const item of content) {
|
|
65
|
+
let sanitizedItem: MCPContent = item;
|
|
66
|
+
let itemSize = 0;
|
|
67
|
+
|
|
68
|
+
if (item.type === 'text' && item.text) {
|
|
69
|
+
const textSize = estimateTextSize(item.text);
|
|
70
|
+
if (textSize > LIMITS.maxTextSize) {
|
|
71
|
+
debug.warn('mcp', `Tool ${toolName} text output exceeded limit: ${(textSize / 1024 / 1024).toFixed(2)} MB > ${(LIMITS.maxTextSize / 1024 / 1024).toFixed(0)} MB`);
|
|
72
|
+
sanitizedItem = { type: 'text', text: truncateText(item.text, LIMITS.maxTextSize) };
|
|
73
|
+
}
|
|
74
|
+
itemSize = estimateTextSize(sanitizedItem.text ?? '');
|
|
75
|
+
} else if (item.type === 'image' && item.data) {
|
|
76
|
+
const imageSize = estimateImageSize(item.data);
|
|
77
|
+
if (imageSize > LIMITS.maxImageSize) {
|
|
78
|
+
debug.warn('mcp', `Tool ${toolName} image output exceeded limit: ${(imageSize / 1024 / 1024).toFixed(2)} MB > ${(LIMITS.maxImageSize / 1024 / 1024).toFixed(0)} MB`);
|
|
79
|
+
sanitizedItem = {
|
|
80
|
+
type: 'text',
|
|
81
|
+
text: `[Image omitted: size ${(imageSize / 1024 / 1024).toFixed(2)} MB exceeds limit of ${(LIMITS.maxImageSize / 1024 / 1024).toFixed(0)} MB]`
|
|
82
|
+
};
|
|
83
|
+
itemSize = estimateTextSize(sanitizedItem.text ?? '');
|
|
84
|
+
} else {
|
|
85
|
+
itemSize = imageSize;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
totalSize += itemSize;
|
|
90
|
+
if (totalSize > LIMITS.maxTotalSize) {
|
|
91
|
+
debug.warn('mcp', `Tool ${toolName} total output exceeded limit: ${(totalSize / 1024 / 1024).toFixed(2)} MB > ${(LIMITS.maxTotalSize / 1024 / 1024).toFixed(0)} MB`);
|
|
92
|
+
sanitized.push({
|
|
93
|
+
type: 'text',
|
|
94
|
+
text: '\n\n[Additional content omitted due to total size limit]'
|
|
95
|
+
});
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
sanitized.push(sanitizedItem);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return sanitized;
|
|
103
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { describe, expect, test, beforeEach } from 'bun:test';
|
|
2
|
+
import { projectContextService } from './project-context';
|
|
3
|
+
|
|
4
|
+
describe('projectContextService.clearByProjectId', () => {
|
|
5
|
+
beforeEach(() => {
|
|
6
|
+
projectContextService.clear();
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
test('removes session and stream mappings for the project only', () => {
|
|
10
|
+
projectContextService.registerSession('session-a', 'project-1');
|
|
11
|
+
projectContextService.registerStream('stream-a', 'project-1', 'session-a');
|
|
12
|
+
projectContextService.registerSession('session-b', 'project-2');
|
|
13
|
+
projectContextService.registerStream('stream-b', 'project-2', 'session-b');
|
|
14
|
+
|
|
15
|
+
projectContextService.clearByProjectId('project-1');
|
|
16
|
+
|
|
17
|
+
expect(projectContextService.getProjectIdForSession('session-a')).toBeNull();
|
|
18
|
+
expect(projectContextService.getProjectIdForStream('stream-a')).toBeNull();
|
|
19
|
+
expect(projectContextService.getProjectIdForSession('session-b')).toBe('project-2');
|
|
20
|
+
expect(projectContextService.getLastUsedProjectId()).toBe('project-2');
|
|
21
|
+
});
|
|
22
|
+
});
|
|
@@ -206,13 +206,48 @@ class ProjectContextService {
|
|
|
206
206
|
}));
|
|
207
207
|
}
|
|
208
208
|
|
|
209
|
+
/**
|
|
210
|
+
* Remove all session/stream mappings for a project (e.g. when the project
|
|
211
|
+
* row is deleted and no users remain).
|
|
212
|
+
*/
|
|
213
|
+
clearByProjectId(projectId: string): void {
|
|
214
|
+
for (const [sessionId, pid] of [...this.sessionProjectMap.entries()]) {
|
|
215
|
+
if (pid === projectId) {
|
|
216
|
+
this.sessionProjectMap.delete(sessionId);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const streamIds = new Set<string>();
|
|
221
|
+
for (const [streamId, pid] of this.streamProjectMap.entries()) {
|
|
222
|
+
if (pid === projectId) {
|
|
223
|
+
streamIds.add(streamId);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
for (const [streamId, info] of this.activeStreams.entries()) {
|
|
227
|
+
if (info.projectId === projectId) {
|
|
228
|
+
streamIds.add(streamId);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
for (const streamId of streamIds) {
|
|
232
|
+
this.unregisterStream(streamId);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if (this.lastUsedProjectId === projectId) {
|
|
236
|
+
this.lastUsedProjectId = null;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
debug.log('mcp', `Cleared MCP project context for project ${projectId}`);
|
|
240
|
+
}
|
|
241
|
+
|
|
209
242
|
/**
|
|
210
243
|
* Clear all mappings (for testing or cleanup)
|
|
211
244
|
*/
|
|
212
245
|
clear(): void {
|
|
213
246
|
this.sessionProjectMap.clear();
|
|
214
247
|
this.streamProjectMap.clear();
|
|
248
|
+
this.activeStreams.clear();
|
|
215
249
|
this.streamSignals.clear();
|
|
250
|
+
this.mostRecentActiveStream = null;
|
|
216
251
|
this.lastUsedProjectId = null;
|
|
217
252
|
debug.log('mcp', '🧹 Cleared all project context mappings');
|
|
218
253
|
}
|
|
@@ -13,6 +13,7 @@ import { createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk";
|
|
|
13
13
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
14
14
|
import type { z } from "zod";
|
|
15
15
|
import { projectContextService } from '../project-context';
|
|
16
|
+
import { validateMcpOutput } from '../output-validator';
|
|
16
17
|
|
|
17
18
|
/**
|
|
18
19
|
* Infer argument types from Zod schema
|
|
@@ -190,7 +191,11 @@ export function createRemoteMcpServer(
|
|
|
190
191
|
|
|
191
192
|
mcpServer.registerTool(toolName as string, {
|
|
192
193
|
description: def.description,
|
|
193
|
-
inputSchema
|
|
194
|
+
// MCP SDK 1.29 typed `inputSchema` as `ZodRawShapeCompat` (Record of
|
|
195
|
+
// z3 | z4-core schemas). Our shapes are zod v4 instances whose
|
|
196
|
+
// nominal type doesn't satisfy that union, but they are accepted
|
|
197
|
+
// at runtime. Cast to bridge the mismatch.
|
|
198
|
+
inputSchema: def.schema as Record<string, any>,
|
|
194
199
|
}, async (args: Record<string, unknown>) => {
|
|
195
200
|
// Fast-fail when the owning chat stream has already been
|
|
196
201
|
// cancelled — the handler never runs. Without this, the
|
|
@@ -204,7 +209,11 @@ export function createRemoteMcpServer(
|
|
|
204
209
|
isError: true,
|
|
205
210
|
} as any;
|
|
206
211
|
}
|
|
207
|
-
|
|
212
|
+
const result = await def.handler(args) as any;
|
|
213
|
+
if (result?.content) {
|
|
214
|
+
result.content = validateMcpOutput(result.content, toolName as string);
|
|
215
|
+
}
|
|
216
|
+
return result;
|
|
208
217
|
});
|
|
209
218
|
}
|
|
210
219
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import {
|
|
3
|
+
clearProjectPresence,
|
|
4
|
+
getProjectStatusData,
|
|
5
|
+
updateUserPresence
|
|
6
|
+
} from './status-manager';
|
|
7
|
+
|
|
8
|
+
async function getSingleProjectStatus(projectId: string) {
|
|
9
|
+
const status = await getProjectStatusData(projectId);
|
|
10
|
+
if (Array.isArray(status)) {
|
|
11
|
+
throw new Error('expected single-project status payload');
|
|
12
|
+
}
|
|
13
|
+
return status;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
describe('clearProjectPresence', () => {
|
|
17
|
+
test('removes active users for the project from status data', async () => {
|
|
18
|
+
updateUserPresence('proj-presence', 'user-1', 'Alice', 'join');
|
|
19
|
+
|
|
20
|
+
const before = await getSingleProjectStatus('proj-presence');
|
|
21
|
+
expect(before.activeUsers).toHaveLength(1);
|
|
22
|
+
|
|
23
|
+
clearProjectPresence('proj-presence');
|
|
24
|
+
|
|
25
|
+
const after = await getSingleProjectStatus('proj-presence');
|
|
26
|
+
expect(after.activeUsers).toEqual([]);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test('is a no-op when the project has no presence entry', () => {
|
|
30
|
+
expect(() => clearProjectPresence('proj-never-seen')).not.toThrow();
|
|
31
|
+
});
|
|
32
|
+
});
|
|
@@ -176,6 +176,13 @@ export async function getProjectStatusData(projectId?: string) {
|
|
|
176
176
|
}
|
|
177
177
|
}
|
|
178
178
|
|
|
179
|
+
/**
|
|
180
|
+
* Drop in-memory presence for a project (e.g. after full project delete).
|
|
181
|
+
*/
|
|
182
|
+
export function clearProjectPresence(projectId: string): void {
|
|
183
|
+
projectUsers.delete(projectId);
|
|
184
|
+
}
|
|
185
|
+
|
|
179
186
|
// Update user presence
|
|
180
187
|
export function updateUserPresence(projectId: string, userId: string, userName: string, action: string) {
|
|
181
188
|
cleanupInactiveUsers();
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { beforeEach, describe, expect, test } from 'bun:test';
|
|
2
|
+
import { projectCleanupRegistry } from './project-cleanup-registry';
|
|
3
|
+
|
|
4
|
+
describe('projectCleanupRegistry', () => {
|
|
5
|
+
beforeEach(() => {
|
|
6
|
+
projectCleanupRegistry._clearHandlers();
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
test('runAll invokes registered handlers', async () => {
|
|
10
|
+
const calls: string[] = [];
|
|
11
|
+
projectCleanupRegistry.register({
|
|
12
|
+
name: 'test-a',
|
|
13
|
+
run: async (projectId) => {
|
|
14
|
+
calls.push(`a:${projectId}`);
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
projectCleanupRegistry.register({
|
|
18
|
+
name: 'test-b',
|
|
19
|
+
run: (projectId) => {
|
|
20
|
+
calls.push(`b:${projectId}`);
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
await projectCleanupRegistry.runAll('proj-1');
|
|
25
|
+
|
|
26
|
+
expect(calls).toEqual(['a:proj-1', 'b:proj-1']);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test('runAll continues when a handler throws', async () => {
|
|
30
|
+
const calls: string[] = [];
|
|
31
|
+
projectCleanupRegistry.register({
|
|
32
|
+
name: 'failing',
|
|
33
|
+
run: () => {
|
|
34
|
+
throw new Error('boom');
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
projectCleanupRegistry.register({
|
|
38
|
+
name: 'ok',
|
|
39
|
+
run: () => {
|
|
40
|
+
calls.push('ok');
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
await projectCleanupRegistry.runAll('proj-2');
|
|
45
|
+
|
|
46
|
+
expect(calls).toEqual(['ok']);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { debug } from '$shared/utils/logger';
|
|
2
|
+
|
|
3
|
+
export type ProjectCleanupHandler = {
|
|
4
|
+
name: string;
|
|
5
|
+
run: (projectId: string) => void | Promise<void>;
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
class ProjectCleanupRegistry {
|
|
9
|
+
private handlers: ProjectCleanupHandler[] = [];
|
|
10
|
+
|
|
11
|
+
register(handler: ProjectCleanupHandler): void {
|
|
12
|
+
this.handlers.push(handler);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async runAll(projectId: string): Promise<void> {
|
|
16
|
+
for (const handler of this.handlers) {
|
|
17
|
+
try {
|
|
18
|
+
await handler.run(projectId);
|
|
19
|
+
} catch (error) {
|
|
20
|
+
debug.warn('project', `Cleanup handler "${handler.name}" failed for ${projectId}:`, error);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** @internal Test helper */
|
|
26
|
+
_getHandlerNames(): string[] {
|
|
27
|
+
return this.handlers.map((handler) => handler.name);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** @internal Test helper */
|
|
31
|
+
_clearHandlers(): void {
|
|
32
|
+
this.handlers = [];
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const projectCleanupRegistry = new ProjectCleanupRegistry();
|
|
37
|
+
|
|
38
|
+
export function registerProjectCleanup(handler: ProjectCleanupHandler): void {
|
|
39
|
+
projectCleanupRegistry.register(handler);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function runProjectCleanups(projectId: string): Promise<void> {
|
|
43
|
+
await projectCleanupRegistry.runAll(projectId);
|
|
44
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { projectCleanupRegistry, runProjectCleanups } from './project-cleanup-registry';
|
|
3
|
+
|
|
4
|
+
import './project-cleanup';
|
|
5
|
+
|
|
6
|
+
const DEFAULT_CLEANUP_HANDLERS = ['engine', 'mcp-context', 'file-watcher', 'presence'] as const;
|
|
7
|
+
|
|
8
|
+
describe('project cleanup integration', () => {
|
|
9
|
+
test('registers default backend handlers when project-cleanup is loaded', () => {
|
|
10
|
+
const names = projectCleanupRegistry._getHandlerNames();
|
|
11
|
+
for (const expected of DEFAULT_CLEANUP_HANDLERS) {
|
|
12
|
+
expect(names).toContain(expected);
|
|
13
|
+
}
|
|
14
|
+
expect(names.indexOf('engine')).toBeLessThan(names.indexOf('mcp-context'));
|
|
15
|
+
expect(names.indexOf('mcp-context')).toBeLessThan(names.indexOf('file-watcher'));
|
|
16
|
+
expect(names.indexOf('file-watcher')).toBeLessThan(names.indexOf('presence'));
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
test('runProjectCleanups runs default handlers without throwing', async () => {
|
|
20
|
+
await expect(runProjectCleanups('proj-cleanup-integration')).resolves.toBeUndefined();
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test('runProjectCleanups forwards the project id to registered handlers', async () => {
|
|
24
|
+
const received: string[] = [];
|
|
25
|
+
projectCleanupRegistry.register({
|
|
26
|
+
name: 'integration-spy',
|
|
27
|
+
run: (projectId) => {
|
|
28
|
+
received.push(projectId);
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
await runProjectCleanups('proj-cleanup-spy');
|
|
33
|
+
|
|
34
|
+
expect(received).toEqual(['proj-cleanup-spy']);
|
|
35
|
+
});
|
|
36
|
+
});
|