@myrialabs/clopen 0.3.21 → 0.4.0
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/permissions.ts +11 -1
- package/backend/chat/stream-manager.ts +14 -3
- package/backend/database/migrations/040_create_mcp_servers_table.ts +34 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/index.ts +3 -1
- package/backend/database/queries/mcp-server-queries.ts +166 -0
- package/backend/engine/README.md +2 -2
- package/backend/engine/adapters/claude/environment.ts +0 -17
- package/backend/engine/adapters/claude/error-handler.ts +0 -4
- package/backend/engine/adapters/codex/message-converter.ts +1 -1
- package/backend/engine/adapters/codex/stream.ts +1 -1
- package/backend/engine/adapters/copilot/message-converter.ts +1 -1
- package/backend/engine/adapters/copilot/stream.ts +1 -1
- package/backend/engine/adapters/qwen/message-converter.ts +1 -1
- package/backend/engine/adapters/qwen/stream.ts +1 -1
- package/backend/engine/docs/adapter-contract.md +2 -2
- package/backend/engine/docs/lessons-learned.md +3 -3
- package/backend/engine/docs/quick-reference.md +1 -1
- package/backend/engine/install-recipes.ts +26 -95
- package/backend/files/file-operations.test.ts +75 -0
- package/backend/files/file-operations.ts +10 -56
- package/backend/files/image-processing.test.ts +52 -0
- package/backend/files/image-processing.ts +11 -1
- package/backend/files/path-browsing.ts +141 -139
- package/backend/git/git-service.ts +13 -2
- package/backend/http/files-upload.test.ts +174 -0
- package/backend/http/files-upload.ts +27 -7
- package/backend/http/upload-temp-cleanup.ts +53 -0
- package/backend/index.ts +9 -1
- package/backend/mcp/README.md +67 -32
- package/backend/mcp/external/config.ts +200 -0
- package/backend/mcp/external/registry-client.ts +214 -0
- package/backend/mcp/external/types.ts +69 -0
- package/backend/mcp/index.ts +104 -19
- package/backend/mcp/{config.ts → internal/config.ts} +82 -18
- package/backend/mcp/internal/remote-server.test.ts +150 -0
- package/backend/mcp/{remote-server.ts → internal/remote-server.ts} +68 -0
- package/backend/mcp/{servers → internal/servers}/browser-automation/actions.ts +1 -1
- package/backend/mcp/{servers → internal/servers}/browser-automation/browser.ts +1 -1
- package/backend/mcp/{servers → internal/servers}/browser-automation/index.ts +2 -0
- package/backend/mcp/{servers → internal/servers}/browser-automation/inspection.ts +1 -1
- package/backend/mcp/{servers → internal/servers}/helper.ts +11 -0
- package/backend/mcp/{servers → internal/servers}/index.ts +0 -2
- package/backend/mcp/{types.ts → internal/types.ts} +3 -3
- package/backend/mcp/shared/constants.ts +66 -0
- package/backend/projects/project-cleanup.ts +1 -1
- package/backend/terminal/pty-session-manager.ts +18 -11
- package/backend/ws/engine/index.ts +3 -1
- package/backend/ws/engine/restart.ts +54 -0
- package/backend/ws/files/index.ts +5 -0
- package/backend/ws/files/reveal.ts +61 -0
- package/backend/ws/files/search.test.ts +115 -0
- package/backend/ws/files/search.ts +77 -26
- package/backend/ws/files/write.ts +3 -1
- package/backend/ws/git/branch-name.ts +170 -0
- package/backend/ws/git/branch.ts +15 -2
- package/backend/ws/git/commit-message.ts +8 -2
- package/backend/ws/git/index.ts +3 -1
- package/backend/ws/index.ts +5 -1
- package/backend/ws/mcp/catalog.ts +56 -0
- package/backend/ws/mcp/crud.ts +174 -0
- package/backend/ws/mcp/index.ts +18 -0
- package/backend/ws/user/crud.ts +8 -4
- package/dist/assets/main-B7f2Gzb3.css +1 -0
- package/dist/assets/main-DYt1fDrp.js +383 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/constants/git.ts +5 -0
- package/shared/types/git.ts +5 -0
- package/shared/types/stores/settings.ts +19 -0
- package/backend/mcp/servers/weather/get-temperature.ts +0 -56
- package/backend/mcp/servers/weather/index.ts +0 -31
- package/dist/assets/main-BgOiIS43.js +0 -360
- package/dist/assets/main-CJdJeen6.css +0 -1
- /package/backend/mcp/{output-validator.test.ts → internal/output-validator.test.ts} +0 -0
- /package/backend/mcp/{output-validator.ts → internal/output-validator.ts} +0 -0
- /package/backend/mcp/{project-context.test.ts → internal/project-context.test.ts} +0 -0
- /package/backend/mcp/{project-context.ts → internal/project-context.ts} +0 -0
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Restart-all-engines handler.
|
|
3
|
+
*
|
|
4
|
+
* Disposes every cached engine instance (global + per-project) and the shared
|
|
5
|
+
* OpenCode server/client so the next chat turn re-initialises from scratch.
|
|
6
|
+
* Needed after changing MCP servers (install/uninstall/enable/disable/config)
|
|
7
|
+
* or other global engine config — the engines read that config when they
|
|
8
|
+
* (re)initialise, not mid-session.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { t } from 'elysia';
|
|
12
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
13
|
+
import { debug } from '$shared/utils/logger';
|
|
14
|
+
import { disposeAllEngines } from '../../engine';
|
|
15
|
+
import { disposeOpenCodeClient } from '../../engine/adapters/opencode/server';
|
|
16
|
+
import { streamManager } from '../../chat';
|
|
17
|
+
|
|
18
|
+
export const engineRestartRouter = createRouter()
|
|
19
|
+
.http('engine:restart-all', {
|
|
20
|
+
data: t.Object({
|
|
21
|
+
force: t.Optional(t.Boolean()),
|
|
22
|
+
}),
|
|
23
|
+
response: t.Object({
|
|
24
|
+
success: t.Boolean(),
|
|
25
|
+
activeChats: t.Optional(t.Number()),
|
|
26
|
+
needsConfirmation: t.Optional(t.Boolean()),
|
|
27
|
+
})
|
|
28
|
+
}, async ({ data }) => {
|
|
29
|
+
const activeStreams = streamManager.getActiveStreams();
|
|
30
|
+
|
|
31
|
+
// Restarting kills in-flight chats — ask first unless forced.
|
|
32
|
+
if (activeStreams.length > 0 && !data.force) {
|
|
33
|
+
return { success: false, activeChats: activeStreams.length, needsConfirmation: true };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (activeStreams.length > 0) {
|
|
37
|
+
debug.log('engine', `Force-aborting ${activeStreams.length} active stream(s) before restart-all`);
|
|
38
|
+
for (const stream of activeStreams) {
|
|
39
|
+
try {
|
|
40
|
+
await streamManager.cancelStream(stream.streamId);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
debug.warn('engine', `Failed to abort stream ${stream.streamId}:`, error);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
await disposeAllEngines();
|
|
48
|
+
// OpenCode keeps a separate persistent server/client beyond the engine
|
|
49
|
+
// instance — purge it too so it respawns with fresh MCP config.
|
|
50
|
+
await disposeOpenCodeClient(true);
|
|
51
|
+
|
|
52
|
+
debug.log('engine', 'All engines disposed (restart-all). Will re-initialize on next use.');
|
|
53
|
+
return { success: true };
|
|
54
|
+
});
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* Structure:
|
|
7
7
|
* - read.ts: HTTP endpoints for reading (list-tree, browse, read-file, read-content)
|
|
8
8
|
* - write.ts: HTTP endpoints for writing (write, create, rename, duplicate, upload, delete)
|
|
9
|
+
* - reveal.ts: HTTP endpoint for revealing files in the OS file manager
|
|
9
10
|
* - search.ts: HTTP endpoints for searching (search-files, search-code)
|
|
10
11
|
* - watch.ts: Event handlers for real-time file watching
|
|
11
12
|
*/
|
|
@@ -13,6 +14,7 @@
|
|
|
13
14
|
import { createRouter } from '$shared/utils/ws-server';
|
|
14
15
|
import { readHandler } from './read';
|
|
15
16
|
import { writeHandler } from './write';
|
|
17
|
+
import { revealHandler } from './reveal';
|
|
16
18
|
import { imageEditHandler } from './image-edit';
|
|
17
19
|
import { fileSearchHandler } from './search';
|
|
18
20
|
import { watchHandler } from './watch';
|
|
@@ -25,6 +27,9 @@ export const filesRouter = createRouter()
|
|
|
25
27
|
// Write Operations (HTTP)
|
|
26
28
|
.merge(writeHandler)
|
|
27
29
|
|
|
30
|
+
// Reveal in File Manager (HTTP)
|
|
31
|
+
.merge(revealHandler)
|
|
32
|
+
|
|
28
33
|
// Image Edit Operation (HTTP)
|
|
29
34
|
.merge(imageEditHandler)
|
|
30
35
|
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Files Reveal in File Manager Operation
|
|
3
|
+
*
|
|
4
|
+
* Opens the default file manager to reveal a file or directory, using the
|
|
5
|
+
* platform-native command: `open -R` (macOS), `cmd /c start /max explorer /select,`
|
|
6
|
+
* (Windows, via cmd to avoid minimized window), or `xdg-open` on the parent
|
|
7
|
+
* directory (Linux).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { sep } from 'node:path';
|
|
11
|
+
import { t } from 'elysia';
|
|
12
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
13
|
+
import { requireFilePathAccess } from './path-access';
|
|
14
|
+
|
|
15
|
+
export const revealHandler = createRouter()
|
|
16
|
+
|
|
17
|
+
.http('files:reveal-in-file-manager', {
|
|
18
|
+
data: t.Object({
|
|
19
|
+
path: t.String()
|
|
20
|
+
}),
|
|
21
|
+
response: t.Object({
|
|
22
|
+
ok: t.Boolean()
|
|
23
|
+
})
|
|
24
|
+
}, async ({ data, conn }) => {
|
|
25
|
+
const targetPath = await requireFilePathAccess(conn, data.path);
|
|
26
|
+
|
|
27
|
+
if (process.platform === 'darwin') {
|
|
28
|
+
const proc = Bun.spawn(['open', '-R', targetPath], {
|
|
29
|
+
stdout: 'ignore',
|
|
30
|
+
stderr: 'pipe'
|
|
31
|
+
});
|
|
32
|
+
const exitCode = await proc.exited;
|
|
33
|
+
if (exitCode !== 0) {
|
|
34
|
+
const stderr = proc.stderr ? (await new Response(proc.stderr).text()).trim() : '';
|
|
35
|
+
throw new Error(stderr || 'Failed to reveal item in Finder');
|
|
36
|
+
}
|
|
37
|
+
} else if (process.platform === 'win32') {
|
|
38
|
+
const winPath = targetPath.split('/').join(sep);
|
|
39
|
+
Bun.spawn(['cmd', '/c', 'start', '', '/max', 'explorer', '/select,' + winPath], {
|
|
40
|
+
stdout: 'ignore',
|
|
41
|
+
stderr: 'ignore'
|
|
42
|
+
});
|
|
43
|
+
} else if (process.platform === 'linux') {
|
|
44
|
+
const parentDir = targetPath.lastIndexOf('/') > 0
|
|
45
|
+
? targetPath.slice(0, targetPath.lastIndexOf('/'))
|
|
46
|
+
: '/';
|
|
47
|
+
const proc = Bun.spawn(['xdg-open', parentDir], {
|
|
48
|
+
stdout: 'ignore',
|
|
49
|
+
stderr: 'pipe'
|
|
50
|
+
});
|
|
51
|
+
const exitCode = await proc.exited;
|
|
52
|
+
if (exitCode !== 0) {
|
|
53
|
+
const stderr = proc.stderr ? (await new Response(proc.stderr).text()).trim() : '';
|
|
54
|
+
throw new Error(stderr || 'Failed to open file manager');
|
|
55
|
+
}
|
|
56
|
+
} else {
|
|
57
|
+
throw new Error('Reveal in file manager is not supported on this platform');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return { ok: true };
|
|
61
|
+
});
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { describe, it, expect } from 'bun:test';
|
|
2
|
+
import { createSafeRegex } from './search';
|
|
3
|
+
|
|
4
|
+
describe('ReDoS Protection', () => {
|
|
5
|
+
describe('Alternation-based ReDoS patterns', () => {
|
|
6
|
+
it('should reject (a|aa)+ pattern', () => {
|
|
7
|
+
const result = createSafeRegex('(a|aa)+', 'gi');
|
|
8
|
+
expect(result).toBeNull();
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
it('should reject (foo|foobar)+ pattern', () => {
|
|
12
|
+
const result = createSafeRegex('(foo|foobar)+', 'gi');
|
|
13
|
+
expect(result).toBeNull();
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it('should reject (a|b|c)+ pattern', () => {
|
|
17
|
+
const result = createSafeRegex('(a|b|c)+', 'gi');
|
|
18
|
+
expect(result).toBeNull();
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it('should reject (hello|helloworld)* pattern', () => {
|
|
22
|
+
const result = createSafeRegex('(hello|helloworld)*', 'gi');
|
|
23
|
+
expect(result).toBeNull();
|
|
24
|
+
});
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
describe('Nested quantifier patterns', () => {
|
|
28
|
+
it('should reject (a+)+ pattern', () => {
|
|
29
|
+
const result = createSafeRegex('(a+)+', 'gi');
|
|
30
|
+
expect(result).toBeNull();
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('should reject (.*)+b pattern', () => {
|
|
34
|
+
const result = createSafeRegex('(.*)+b', 'gi');
|
|
35
|
+
expect(result).toBeNull();
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('should reject (a*)* pattern', () => {
|
|
39
|
+
const result = createSafeRegex('(a*)*', 'gi');
|
|
40
|
+
expect(result).toBeNull();
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('should reject (x{1,5})+ pattern', () => {
|
|
44
|
+
const result = createSafeRegex('(x{1,5})+', 'gi');
|
|
45
|
+
expect(result).toBeNull();
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
describe('Adjacent character class quantifiers', () => {
|
|
50
|
+
it('should reject [a-z]*[a-z]+ pattern', () => {
|
|
51
|
+
const result = createSafeRegex('[a-z]*[a-z]+', 'gi');
|
|
52
|
+
expect(result).toBeNull();
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('should reject [0-9]+[0-9]* pattern', () => {
|
|
56
|
+
const result = createSafeRegex('[0-9]+[0-9]*', 'gi');
|
|
57
|
+
expect(result).toBeNull();
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
describe('Safe patterns', () => {
|
|
62
|
+
it('should accept simple string pattern', () => {
|
|
63
|
+
const result = createSafeRegex('hello', 'gi');
|
|
64
|
+
expect(result).not.toBeNull();
|
|
65
|
+
expect(result).toBeInstanceOf(RegExp);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('should accept simple alternation without quantifier', () => {
|
|
69
|
+
const result = createSafeRegex('(foo|bar)', 'gi');
|
|
70
|
+
expect(result).not.toBeNull();
|
|
71
|
+
expect(result).toBeInstanceOf(RegExp);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it('should accept single quantifier pattern', () => {
|
|
75
|
+
const result = createSafeRegex('a+', 'gi');
|
|
76
|
+
expect(result).not.toBeNull();
|
|
77
|
+
expect(result).toBeInstanceOf(RegExp);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it('should accept word boundary pattern', () => {
|
|
81
|
+
const result = createSafeRegex('\\btest\\b', 'gi');
|
|
82
|
+
expect(result).not.toBeNull();
|
|
83
|
+
expect(result).toBeInstanceOf(RegExp);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('should accept character class pattern', () => {
|
|
87
|
+
const result = createSafeRegex('[a-z]+', 'gi');
|
|
88
|
+
expect(result).not.toBeNull();
|
|
89
|
+
expect(result).toBeInstanceOf(RegExp);
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
describe('Invalid regex patterns', () => {
|
|
94
|
+
it('should reject invalid regex with unclosed group', () => {
|
|
95
|
+
const result = createSafeRegex('(abc', 'gi');
|
|
96
|
+
expect(result).toBeNull();
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('should reject invalid regex with unclosed bracket', () => {
|
|
100
|
+
const result = createSafeRegex('[a-z', 'gi');
|
|
101
|
+
expect(result).toBeNull();
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
describe('Execution timeout protection', () => {
|
|
106
|
+
it('should complete quickly for safe patterns', () => {
|
|
107
|
+
const startTime = Date.now();
|
|
108
|
+
const result = createSafeRegex('test.*pattern', 'gi');
|
|
109
|
+
const elapsed = Date.now() - startTime;
|
|
110
|
+
|
|
111
|
+
expect(result).not.toBeNull();
|
|
112
|
+
expect(elapsed).toBeLessThan(100);
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
});
|
|
@@ -6,6 +6,54 @@ import { readdir } from 'fs/promises';
|
|
|
6
6
|
import { requireProjectPathAccess } from './path-access';
|
|
7
7
|
import { validateFileSize } from '../../files/file-size-limit';
|
|
8
8
|
|
|
9
|
+
// Heuristic patterns that indicate potential ReDoS risk:
|
|
10
|
+
// 1. Nested quantifiers: (a+)+, (.*)+, (a*)*, (x{1,5})+
|
|
11
|
+
// 2. Alternation (with OR without quantifiers inside) under quantifier: (a|aa)+, (foo|foobar)+, (.*)+
|
|
12
|
+
// 3. Character classes with adjacent quantifiers: [a-z]*[a-z]+
|
|
13
|
+
const REDOS_PATTERNS = [
|
|
14
|
+
/\(.*[+*?{].*\)[+*?{]/, // nested quantifiers like (a+)+, (.*)+, or (x{1,5})+
|
|
15
|
+
/\([^)]*\|[^)]*\)[+*?{]/, // ANY alternation under quantifier: (a|aa)+, (foo|bar)+
|
|
16
|
+
/\[[^\]]+\]\s*[+*?]\s*\[[^\]]+\]\s*[+*?]/, // adjacent char-class quantifiers
|
|
17
|
+
];
|
|
18
|
+
|
|
19
|
+
// Maximum execution time for regex test (milliseconds)
|
|
20
|
+
const REGEX_TIMEOUT_MS = 100;
|
|
21
|
+
|
|
22
|
+
export function createSafeRegex(pattern: string, flags: string): RegExp | null {
|
|
23
|
+
// Check against ReDoS heuristics
|
|
24
|
+
for (const heuristic of REDOS_PATTERNS) {
|
|
25
|
+
if (heuristic.test(pattern)) {
|
|
26
|
+
debug.warn('file', 'ReDoS-risk pattern rejected:', pattern);
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
let regex: RegExp;
|
|
32
|
+
try {
|
|
33
|
+
regex = new RegExp(pattern, flags);
|
|
34
|
+
} catch (error) {
|
|
35
|
+
debug.warn('file', 'Invalid regex pattern:', pattern);
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Test execution time with a worst-case string to detect catastrophic backtracking
|
|
40
|
+
const testString = 'a'.repeat(50); // 50-char string of 'a'
|
|
41
|
+
const startTime = Date.now();
|
|
42
|
+
try {
|
|
43
|
+
regex.test(testString);
|
|
44
|
+
const elapsed = Date.now() - startTime;
|
|
45
|
+
if (elapsed > REGEX_TIMEOUT_MS) {
|
|
46
|
+
debug.warn('file', `ReDoS-risk pattern rejected (execution timeout: ${elapsed}ms):`, pattern);
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
} catch (error) {
|
|
50
|
+
debug.warn('file', 'Regex execution error:', pattern, error);
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return regex;
|
|
55
|
+
}
|
|
56
|
+
|
|
9
57
|
// Directories to skip during search
|
|
10
58
|
const SKIP_DIRS = new Set([
|
|
11
59
|
'node_modules', '.git', '.svelte-kit', 'build', 'dist', 'coverage',
|
|
@@ -180,22 +228,23 @@ async function searchCodeContent(
|
|
|
180
228
|
|
|
181
229
|
const results: CodeSearchResult[] = [];
|
|
182
230
|
|
|
183
|
-
// Build the search regex
|
|
184
|
-
let searchPattern: RegExp;
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
231
|
+
// Build the search regex with ReDoS protection
|
|
232
|
+
let searchPattern: RegExp | null;
|
|
233
|
+
if (useRegex) {
|
|
234
|
+
let regexStr = query;
|
|
235
|
+
if (wholeWord) regexStr = `\\b${regexStr}\\b`;
|
|
236
|
+
searchPattern = createSafeRegex(regexStr, caseSensitive ? 'g' : 'gi');
|
|
237
|
+
} else {
|
|
238
|
+
let escaped = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
239
|
+
if (wholeWord) escaped = `\\b${escaped}\\b`;
|
|
240
|
+
try {
|
|
193
241
|
searchPattern = new RegExp(escaped, caseSensitive ? 'g' : 'gi');
|
|
242
|
+
} catch (error) {
|
|
243
|
+
debug.error('file', 'Invalid escaped search pattern:', error);
|
|
244
|
+
return [];
|
|
194
245
|
}
|
|
195
|
-
} catch (error) {
|
|
196
|
-
debug.error('file', 'Invalid search pattern:', error);
|
|
197
|
-
return [];
|
|
198
246
|
}
|
|
247
|
+
if (!searchPattern) return [];
|
|
199
248
|
|
|
200
249
|
// Parse include/exclude filters
|
|
201
250
|
const includes = parseFilterPattern(includePattern);
|
|
@@ -292,22 +341,24 @@ async function replaceInFiles(
|
|
|
292
341
|
|
|
293
342
|
const results: ReplaceResult[] = [];
|
|
294
343
|
|
|
295
|
-
// Build replace regex
|
|
296
|
-
let pattern: RegExp;
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
344
|
+
// Build replace regex with ReDoS protection
|
|
345
|
+
let pattern: RegExp | null;
|
|
346
|
+
const flags = caseSensitive ? 'g' : 'gi';
|
|
347
|
+
if (useRegex) {
|
|
348
|
+
let regexStr = searchQuery;
|
|
349
|
+
if (wholeWord) regexStr = `\\b${regexStr}\\b`;
|
|
350
|
+
pattern = createSafeRegex(regexStr, flags);
|
|
351
|
+
} else {
|
|
352
|
+
let escaped = searchQuery.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
353
|
+
if (wholeWord) escaped = `\\b${escaped}\\b`;
|
|
354
|
+
try {
|
|
306
355
|
pattern = new RegExp(escaped, flags);
|
|
356
|
+
} catch (error) {
|
|
357
|
+
debug.error('file', 'Invalid escaped replace pattern:', error);
|
|
358
|
+
return [];
|
|
307
359
|
}
|
|
308
|
-
} catch {
|
|
309
|
-
return [];
|
|
310
360
|
}
|
|
361
|
+
if (!pattern) return [];
|
|
311
362
|
|
|
312
363
|
for (const searchResult of searchResults) {
|
|
313
364
|
const fullPath = join(projectPath, searchResult.relativePath);
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Git Branch Name Generator Handler
|
|
3
|
+
*
|
|
4
|
+
* Uses AI engines to generate a branch name from staged diffs before commit.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { t } from 'elysia';
|
|
8
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
9
|
+
import { execGit } from '../../git/git-executor';
|
|
10
|
+
import { initializeEngine } from '../../engine';
|
|
11
|
+
import type { EngineType } from '$shared/types/unified';
|
|
12
|
+
import type { GeneratedBranchName } from '$shared/types/git';
|
|
13
|
+
import {
|
|
14
|
+
DEFAULT_BRANCH_NAME_PREFIX,
|
|
15
|
+
DEFAULT_BRANCH_SEPARATOR,
|
|
16
|
+
MAX_BRANCH_SEPARATOR_LENGTH,
|
|
17
|
+
RELEASE_BRANCH_NAME_PREFIX,
|
|
18
|
+
TEST_BRANCH_NAME_PREFIX
|
|
19
|
+
} from '$shared/constants/git';
|
|
20
|
+
import { debug } from '$shared/utils/logger';
|
|
21
|
+
import { requireProjectAccess } from '../access';
|
|
22
|
+
|
|
23
|
+
const INVALID_BRANCH_SEPARATOR_CHARS = /[\s\0~^:?*[\]\\]+/g;
|
|
24
|
+
const GENERATED_BRANCH_PREFIXES = [
|
|
25
|
+
DEFAULT_BRANCH_NAME_PREFIX,
|
|
26
|
+
RELEASE_BRANCH_NAME_PREFIX,
|
|
27
|
+
TEST_BRANCH_NAME_PREFIX
|
|
28
|
+
];
|
|
29
|
+
const GENERIC_BRANCH_DESCRIPTION_WORDS = new Set([
|
|
30
|
+
'add',
|
|
31
|
+
'added',
|
|
32
|
+
'change',
|
|
33
|
+
'create',
|
|
34
|
+
'fix',
|
|
35
|
+
'implement',
|
|
36
|
+
'improve',
|
|
37
|
+
'make',
|
|
38
|
+
'remove',
|
|
39
|
+
'update'
|
|
40
|
+
]);
|
|
41
|
+
const MAX_BRANCH_DESCRIPTION_WORDS = 3;
|
|
42
|
+
|
|
43
|
+
function sanitizeBranchDescription(input: string, maxWords = MAX_BRANCH_DESCRIPTION_WORDS): string {
|
|
44
|
+
const withoutPrefix = GENERATED_BRANCH_PREFIXES.reduce((value, prefix) => {
|
|
45
|
+
return value.replace(new RegExp(`^${prefix}[/#._-]+`, 'i'), '');
|
|
46
|
+
}, input.trim());
|
|
47
|
+
|
|
48
|
+
const sanitized = withoutPrefix
|
|
49
|
+
.trim()
|
|
50
|
+
.toLowerCase()
|
|
51
|
+
.replace(/[^a-z0-9._-]+/g, '-')
|
|
52
|
+
.replace(/[._]+/g, '-')
|
|
53
|
+
.replace(/-+/g, '-')
|
|
54
|
+
.replace(/^[.-]+|[.-]+$/g, '')
|
|
55
|
+
.slice(0, 72)
|
|
56
|
+
.replace(/[.-]$/g, '');
|
|
57
|
+
const words = sanitized
|
|
58
|
+
.split('-')
|
|
59
|
+
.filter(word => word && !GENERIC_BRANCH_DESCRIPTION_WORDS.has(word))
|
|
60
|
+
.slice(0, maxWords);
|
|
61
|
+
|
|
62
|
+
return words.join('-');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function normalizeBranchSeparator(input: string | undefined): string {
|
|
66
|
+
const cleaned = (input ?? DEFAULT_BRANCH_SEPARATOR)
|
|
67
|
+
.trim()
|
|
68
|
+
.replace(INVALID_BRANCH_SEPARATOR_CHARS, '')
|
|
69
|
+
.slice(0, MAX_BRANCH_SEPARATOR_LENGTH);
|
|
70
|
+
|
|
71
|
+
if (!cleaned || cleaned.includes('..') || cleaned.includes('//') || cleaned.includes('@{')) {
|
|
72
|
+
return DEFAULT_BRANCH_SEPARATOR;
|
|
73
|
+
}
|
|
74
|
+
return cleaned;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function getBranchPrefix(currentBranch: string): string {
|
|
78
|
+
if (currentBranch === 'main' || currentBranch === 'master') return RELEASE_BRANCH_NAME_PREFIX;
|
|
79
|
+
if (currentBranch === 'test' || currentBranch === 'testing') return TEST_BRANCH_NAME_PREFIX;
|
|
80
|
+
return DEFAULT_BRANCH_NAME_PREFIX;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const BRANCH_NAME_SCHEMA = {
|
|
84
|
+
type: 'object',
|
|
85
|
+
additionalProperties: false,
|
|
86
|
+
properties: {
|
|
87
|
+
description: {
|
|
88
|
+
type: 'string',
|
|
89
|
+
description: 'Very short lowercase kebab-case branch topic, 1-3 words, no prefix'
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
required: ['description']
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
function formatCurrentBranchForPrompt(currentBranch: string): string {
|
|
96
|
+
return currentBranch || 'detached or unknown';
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function createBranchNameInstructions(currentBranch: string, prefix: string, separator: string): string {
|
|
100
|
+
return `Analyze the following staged git diff and generate a git branch name description.
|
|
101
|
+
|
|
102
|
+
Current branch: ${formatCurrentBranchForPrompt(currentBranch)}
|
|
103
|
+
Resolved prefix: ${prefix}
|
|
104
|
+
|
|
105
|
+
Rules:
|
|
106
|
+
- Use this repository format: ${prefix}${separator}<description>
|
|
107
|
+
- Prefix is fixed by the current branch: main/master -> release, test/testing -> test, anything else -> dev
|
|
108
|
+
- Return only the description field; do not include "${prefix}", "${separator}", or any branch prefix in the description
|
|
109
|
+
- description: lowercase kebab-case, 1-3 words maximum, no trailing punctuation
|
|
110
|
+
- Prefer the shortest changed area/topic over action phrases: login page changes -> login, auth form changes -> auth-form
|
|
111
|
+
- Avoid generic action words like add, fix, update, change, implement, improve, create, remove
|
|
112
|
+
- Do not include ticket IDs unless they appear in the diff`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export const branchNameHandler = createRouter()
|
|
116
|
+
.http('git:generate-branch-name', {
|
|
117
|
+
data: t.Object({
|
|
118
|
+
projectId: t.String(),
|
|
119
|
+
engine: t.String(),
|
|
120
|
+
providerSlug: t.String(),
|
|
121
|
+
modelId: t.String(),
|
|
122
|
+
branchSeparator: t.Optional(t.String()),
|
|
123
|
+
maxWords: t.Optional(t.Number()),
|
|
124
|
+
customPrompt: t.Optional(t.String())
|
|
125
|
+
}),
|
|
126
|
+
response: t.Object({
|
|
127
|
+
branchName: t.String()
|
|
128
|
+
})
|
|
129
|
+
}, async ({ data, conn }) => {
|
|
130
|
+
const project = requireProjectAccess(conn, data.projectId);
|
|
131
|
+
|
|
132
|
+
const diffResult = await execGit(['diff', '--cached'], project.path);
|
|
133
|
+
const rawDiff = diffResult.stdout;
|
|
134
|
+
|
|
135
|
+
if (!rawDiff.trim()) {
|
|
136
|
+
throw new Error('No staged changes to generate a branch name for');
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const engineType = data.engine as EngineType;
|
|
140
|
+
const engine = await initializeEngine(engineType);
|
|
141
|
+
|
|
142
|
+
if (!engine.generateStructured) {
|
|
143
|
+
throw new Error(`Engine "${engineType}" does not support structured generation`);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const branchResult = await execGit(['branch', '--show-current'], project.path);
|
|
147
|
+
const currentBranch = branchResult.stdout.trim();
|
|
148
|
+
const prefix = getBranchPrefix(currentBranch);
|
|
149
|
+
const separator = normalizeBranchSeparator(data.branchSeparator);
|
|
150
|
+
const instructions = createBranchNameInstructions(currentBranch, prefix, separator);
|
|
151
|
+
const extra = data.customPrompt?.trim();
|
|
152
|
+
const prompt = `${instructions}${extra ? `\n\nAdditional constraints:\n${extra}` : ''}\n\nGit diff:\n${rawDiff}`;
|
|
153
|
+
|
|
154
|
+
debug.log('git', `Generating branch name via ${engineType}/${data.modelId}`);
|
|
155
|
+
|
|
156
|
+
const result = await engine.generateStructured<GeneratedBranchName>({
|
|
157
|
+
prompt,
|
|
158
|
+
providerSlug: data.providerSlug,
|
|
159
|
+
modelId: data.modelId,
|
|
160
|
+
schema: BRANCH_NAME_SCHEMA,
|
|
161
|
+
projectPath: project.path
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
const description = sanitizeBranchDescription(result.description, data.maxWords ?? MAX_BRANCH_DESCRIPTION_WORDS);
|
|
165
|
+
if (!description) {
|
|
166
|
+
throw new Error('Generated branch description was empty');
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return { branchName: `${prefix}${separator}${description}` };
|
|
170
|
+
});
|
package/backend/ws/git/branch.ts
CHANGED
|
@@ -59,6 +59,18 @@ export const branchHandler = createRouter()
|
|
|
59
59
|
return { ok: true };
|
|
60
60
|
})
|
|
61
61
|
|
|
62
|
+
.http('git:checkout-commit', {
|
|
63
|
+
data: t.Object({
|
|
64
|
+
projectId: t.String(),
|
|
65
|
+
commitHash: t.String()
|
|
66
|
+
}),
|
|
67
|
+
response: t.Object({ ok: t.Boolean() })
|
|
68
|
+
}, async ({ data, conn }) => {
|
|
69
|
+
const project = requireProjectAccess(conn, data.projectId);
|
|
70
|
+
await gitService.checkoutCommit(project.path, data.commitHash);
|
|
71
|
+
return { ok: true };
|
|
72
|
+
})
|
|
73
|
+
|
|
62
74
|
.http('git:delete-branch', {
|
|
63
75
|
data: t.Object({
|
|
64
76
|
projectId: t.String(),
|
|
@@ -88,7 +100,8 @@ export const branchHandler = createRouter()
|
|
|
88
100
|
.http('git:merge-branch', {
|
|
89
101
|
data: t.Object({
|
|
90
102
|
projectId: t.String(),
|
|
91
|
-
branchName: t.String()
|
|
103
|
+
branchName: t.String(),
|
|
104
|
+
noFastForward: t.Optional(t.Boolean())
|
|
92
105
|
}),
|
|
93
106
|
response: t.Object({
|
|
94
107
|
success: t.Boolean(),
|
|
@@ -96,5 +109,5 @@ export const branchHandler = createRouter()
|
|
|
96
109
|
})
|
|
97
110
|
}, async ({ data, conn }) => {
|
|
98
111
|
const project = requireProjectAccess(conn, data.projectId);
|
|
99
|
-
return await gitService.mergeBranch(project.path, data.branchName);
|
|
112
|
+
return await gitService.mergeBranch(project.path, data.branchName, data.noFastForward ?? false);
|
|
100
113
|
});
|
|
@@ -51,7 +51,8 @@ export const commitMessageHandler = createRouter()
|
|
|
51
51
|
engine: t.String(),
|
|
52
52
|
providerSlug: t.String(),
|
|
53
53
|
modelId: t.String(),
|
|
54
|
-
format: t.Union([t.Literal('single-line'), t.Literal('multi-line')])
|
|
54
|
+
format: t.Union([t.Literal('single-line'), t.Literal('multi-line')]),
|
|
55
|
+
customPrompt: t.Optional(t.String())
|
|
55
56
|
}),
|
|
56
57
|
response: t.Object({
|
|
57
58
|
message: t.String()
|
|
@@ -78,7 +79,7 @@ export const commitMessageHandler = createRouter()
|
|
|
78
79
|
? 'Generate a multi-line conventional commit message with type, scope, subject, AND body fields. The body should explain WHY the change was made.'
|
|
79
80
|
: 'Generate a single-line conventional commit message with type, optional scope, and subject. Leave body empty.';
|
|
80
81
|
|
|
81
|
-
const
|
|
82
|
+
const defaultPrompt = `Analyze the following git diff and generate a conventional commit message.
|
|
82
83
|
|
|
83
84
|
Rules:
|
|
84
85
|
- type: one of feat, fix, refactor, docs, test, chore, style, perf, ci, build
|
|
@@ -89,6 +90,11 @@ Rules:
|
|
|
89
90
|
Git diff:
|
|
90
91
|
${rawDiff}`;
|
|
91
92
|
|
|
93
|
+
const extra = data.customPrompt?.trim();
|
|
94
|
+
const prompt = extra
|
|
95
|
+
? `${defaultPrompt}\n\nAdditional constraints:\n${extra}`
|
|
96
|
+
: defaultPrompt;
|
|
97
|
+
|
|
92
98
|
debug.log('git', `Generating commit message via ${engineType}/${data.modelId}`);
|
|
93
99
|
|
|
94
100
|
const result = await engine.generateStructured<GeneratedCommitMessage>({
|
package/backend/ws/git/index.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { logHandler } from './log';
|
|
|
13
13
|
import { remoteHandler } from './remote';
|
|
14
14
|
import { conflictHandler } from './conflict';
|
|
15
15
|
import { commitMessageHandler } from './commit-message';
|
|
16
|
+
import { branchNameHandler } from './branch-name';
|
|
16
17
|
|
|
17
18
|
export const gitRouter = createRouter()
|
|
18
19
|
.merge(statusHandler)
|
|
@@ -23,4 +24,5 @@ export const gitRouter = createRouter()
|
|
|
23
24
|
.merge(logHandler)
|
|
24
25
|
.merge(remoteHandler)
|
|
25
26
|
.merge(conflictHandler)
|
|
26
|
-
.merge(commitMessageHandler)
|
|
27
|
+
.merge(commitMessageHandler)
|
|
28
|
+
.merge(branchNameHandler);
|
package/backend/ws/index.ts
CHANGED
|
@@ -31,6 +31,7 @@ import { gitRouter } from './git';
|
|
|
31
31
|
import { engineRouter } from './engine';
|
|
32
32
|
import { systemToolsRouter } from './system-tools';
|
|
33
33
|
import { dbClientRouter } from './db-client';
|
|
34
|
+
import { mcpRouter } from './mcp';
|
|
34
35
|
|
|
35
36
|
// ============================================
|
|
36
37
|
// Main App Router - Merge All Module Routers
|
|
@@ -73,7 +74,10 @@ export const wsRouter = createRouter()
|
|
|
73
74
|
.merge(systemToolsRouter)
|
|
74
75
|
|
|
75
76
|
// DB Client (global database management)
|
|
76
|
-
.merge(dbClientRouter)
|
|
77
|
+
.merge(dbClientRouter)
|
|
78
|
+
|
|
79
|
+
// External MCP server management (install from the official registry)
|
|
80
|
+
.merge(mcpRouter);
|
|
77
81
|
|
|
78
82
|
// Export API type for frontend type-safe access
|
|
79
83
|
export type WSAPI = typeof wsRouter['$api'];
|