@myrialabs/clopen 0.3.21 → 0.3.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/backend/engine/adapters/claude/environment.ts +0 -17
  2. package/backend/engine/adapters/claude/error-handler.ts +0 -4
  3. package/backend/engine/install-recipes.ts +26 -95
  4. package/backend/files/file-operations.test.ts +75 -0
  5. package/backend/files/file-operations.ts +10 -56
  6. package/backend/files/image-processing.test.ts +52 -0
  7. package/backend/files/image-processing.ts +11 -1
  8. package/backend/files/path-browsing.ts +141 -139
  9. package/backend/git/git-service.ts +13 -2
  10. package/backend/http/files-upload.test.ts +174 -0
  11. package/backend/http/files-upload.ts +27 -7
  12. package/backend/http/upload-temp-cleanup.ts +53 -0
  13. package/backend/index.ts +4 -0
  14. package/backend/mcp/remote-server.test.ts +150 -0
  15. package/backend/mcp/remote-server.ts +68 -0
  16. package/backend/terminal/pty-session-manager.ts +18 -11
  17. package/backend/ws/files/index.ts +5 -0
  18. package/backend/ws/files/reveal.ts +61 -0
  19. package/backend/ws/files/search.test.ts +115 -0
  20. package/backend/ws/files/search.ts +77 -26
  21. package/backend/ws/files/write.ts +3 -1
  22. package/backend/ws/git/branch-name.ts +170 -0
  23. package/backend/ws/git/branch.ts +15 -2
  24. package/backend/ws/git/commit-message.ts +8 -2
  25. package/backend/ws/git/index.ts +3 -1
  26. package/backend/ws/user/crud.ts +8 -4
  27. package/dist/assets/main-Ba19ADkk.js +377 -0
  28. package/dist/assets/main-CwCZzMVm.css +1 -0
  29. package/dist/index.html +2 -2
  30. package/package.json +1 -1
  31. package/shared/constants/git.ts +5 -0
  32. package/shared/types/git.ts +5 -0
  33. package/shared/types/stores/settings.ts +17 -0
  34. package/dist/assets/main-BgOiIS43.js +0 -360
  35. package/dist/assets/main-CJdJeen6.css +0 -1
@@ -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
- try {
186
- if (useRegex) {
187
- let regexStr = query;
188
- if (wholeWord) regexStr = `\\b${regexStr}\\b`;
189
- searchPattern = new RegExp(regexStr, caseSensitive ? 'g' : 'gi');
190
- } else {
191
- let escaped = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
192
- if (wholeWord) escaped = `\\b${escaped}\\b`;
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
- try {
298
- const flags = caseSensitive ? 'g' : 'gi';
299
- if (useRegex) {
300
- let regexStr = searchQuery;
301
- if (wholeWord) regexStr = `\\b${regexStr}\\b`;
302
- pattern = new RegExp(regexStr, flags);
303
- } else {
304
- let escaped = searchQuery.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
305
- if (wholeWord) escaped = `\\b${escaped}\\b`;
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);
@@ -267,4 +267,6 @@ export const writeHandler = createRouter()
267
267
  newPath,
268
268
  modified: newStats.mtime.toISOString()
269
269
  };
270
- });
270
+ })
271
+
272
+
@@ -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
+ });
@@ -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 prompt = `Analyze the following git diff and generate a conventional commit message.
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>({
@@ -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);
@@ -110,7 +110,8 @@ export const crudHandler = createRouter()
110
110
  lastView: t.Union([t.String(), t.Null()]),
111
111
  settings: t.Union([t.Any(), t.Null()]),
112
112
  unreadSessions: t.Union([t.Any(), t.Null()]),
113
- todoPanelState: t.Union([t.Any(), t.Null()])
113
+ todoPanelState: t.Union([t.Any(), t.Null()]),
114
+ projectOrder: t.Union([t.Array(t.String()), t.Null()])
114
115
  })
115
116
  }, async ({ conn }) => {
116
117
  const userId = ws.getUserId(conn);
@@ -120,12 +121,14 @@ export const crudHandler = createRouter()
120
121
  const userSettings = getUserState(userId, 'settings');
121
122
  const unreadSessions = getUserState(userId, 'unreadSessions');
122
123
  const todoPanelState = getUserState(userId, 'todoPanelState');
124
+ const projectOrder = getUserState(userId, 'projectOrder');
123
125
 
124
126
  debug.log('user', `Restored state for ${userId}:`, {
125
127
  currentProjectId,
126
128
  lastView,
127
129
  hasSettings: !!userSettings,
128
- unreadSessionsCount: unreadSessions ? Object.keys(unreadSessions).length : 0
130
+ unreadSessionsCount: unreadSessions ? Object.keys(unreadSessions).length : 0,
131
+ projectOrderCount: Array.isArray(projectOrder) ? projectOrder.length : 0
129
132
  });
130
133
 
131
134
  return {
@@ -133,7 +136,8 @@ export const crudHandler = createRouter()
133
136
  lastView: lastView ?? null,
134
137
  settings: userSettings ?? null,
135
138
  unreadSessions: unreadSessions ?? null,
136
- todoPanelState: todoPanelState ?? null
139
+ todoPanelState: todoPanelState ?? null,
140
+ projectOrder: Array.isArray(projectOrder) ? projectOrder : null
137
141
  };
138
142
  })
139
143
 
@@ -150,7 +154,7 @@ export const crudHandler = createRouter()
150
154
  const userId = ws.getUserId(conn);
151
155
 
152
156
  // Validate allowed keys to prevent arbitrary data storage
153
- const allowedKeys = ['currentProjectId', 'lastView', 'settings', 'unreadSessions', 'todoPanelState'];
157
+ const allowedKeys = ['currentProjectId', 'lastView', 'settings', 'unreadSessions', 'todoPanelState', 'projectOrder'];
154
158
  if (!allowedKeys.includes(data.key)) {
155
159
  throw new Error(`Invalid state key: ${data.key}. Allowed: ${allowedKeys.join(', ')}`);
156
160
  }