@tensorspark/dravix-code 0.0.0-stage → 1.5.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/dist/cli/commands.js +127 -0
- package/dist/cli/index.js +321 -0
- package/dist/cli/repl.js +3433 -0
- package/dist/services/ai.js +296 -0
- package/dist/services/auth.js +67 -0
- package/dist/services/context.js +260 -0
- package/dist/services/conversations.js +79 -0
- package/dist/services/executor.js +944 -0
- package/dist/services/undo.js +181 -0
- package/dist/services/usage.js +60 -0
- package/dist/utils/display.js +265 -0
- package/dist/utils/fileops.js +17 -0
- package/dist/utils/layout.js +82 -0
- package/package.json +38 -4
- package/README.md +0 -3
|
@@ -0,0 +1,944 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import { spawn } from 'child_process';
|
|
4
|
+
import { backupFile, recordWrite, recordEdit, recordDelete, startUndoSession, saveUndoSession } from './undo.js';
|
|
5
|
+
const SKIP_DIRS = new Set([
|
|
6
|
+
'node_modules', '.git', 'dist', 'build', '.next', 'out',
|
|
7
|
+
'.cache', 'coverage', '__pycache__', '.venv', 'venv', 'env',
|
|
8
|
+
'vendor', '.tox', '.eggs', '.mypy_cache', '.pytest_cache',
|
|
9
|
+
]);
|
|
10
|
+
function safeResolvePath(cwd, userPath) {
|
|
11
|
+
const base = path.resolve(cwd);
|
|
12
|
+
const full = path.resolve(cwd, userPath);
|
|
13
|
+
if (full !== base && !full.startsWith(base + path.sep))
|
|
14
|
+
return null;
|
|
15
|
+
return full;
|
|
16
|
+
}
|
|
17
|
+
function findFile(name, cwd) {
|
|
18
|
+
const target = path.basename(name);
|
|
19
|
+
function search(dir, depth) {
|
|
20
|
+
if (depth > 10)
|
|
21
|
+
return null;
|
|
22
|
+
let entries;
|
|
23
|
+
try {
|
|
24
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
// Check files first (breadth-first)
|
|
30
|
+
for (const entry of entries) {
|
|
31
|
+
if (!SKIP_DIRS.has(entry.name) && entry.isFile() && entry.name === target) {
|
|
32
|
+
return path.relative(cwd, path.join(dir, entry.name)).replace(/\\/g, '/');
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
for (const entry of entries) {
|
|
36
|
+
if (!SKIP_DIRS.has(entry.name) && entry.isDirectory()) {
|
|
37
|
+
const found = search(path.join(dir, entry.name), depth + 1);
|
|
38
|
+
if (found)
|
|
39
|
+
return found;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
return search(cwd, 0);
|
|
45
|
+
}
|
|
46
|
+
export function computeDiff(oldText, newText) {
|
|
47
|
+
const o = oldText.split('\n');
|
|
48
|
+
const n = newText.split('\n');
|
|
49
|
+
if (o[o.length - 1] === '')
|
|
50
|
+
o.pop();
|
|
51
|
+
if (n[n.length - 1] === '')
|
|
52
|
+
n.pop();
|
|
53
|
+
const m = o.length, N = n.length;
|
|
54
|
+
// For very large files skip full LCS diff — caller should use snippet diff instead
|
|
55
|
+
if (m > 2500 || N > 2500)
|
|
56
|
+
return [];
|
|
57
|
+
// LCS-based diff (prefix dp)
|
|
58
|
+
const dp = Array.from({ length: m + 1 }, () => new Array(N + 1).fill(0));
|
|
59
|
+
for (let i = 1; i <= m; i++) {
|
|
60
|
+
for (let j = 1; j <= N; j++) {
|
|
61
|
+
if (o[i - 1].trimEnd() === n[j - 1].trimEnd()) {
|
|
62
|
+
dp[i][j] = dp[i - 1][j - 1] + 1;
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
// Traceback from (m, N)
|
|
70
|
+
const result = [];
|
|
71
|
+
let i = m, j = N;
|
|
72
|
+
while (i > 0 || j > 0) {
|
|
73
|
+
if (i > 0 && j > 0 && o[i - 1].trimEnd() === n[j - 1].trimEnd()) {
|
|
74
|
+
result.push({ kind: 'context', text: n[j - 1].trimEnd(), lineNo: j });
|
|
75
|
+
i--;
|
|
76
|
+
j--;
|
|
77
|
+
}
|
|
78
|
+
else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
|
|
79
|
+
result.push({ kind: 'add', text: n[j - 1].trimEnd(), lineNo: j });
|
|
80
|
+
j--;
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
result.push({ kind: 'remove', text: o[i - 1].trimEnd(), lineNo: i });
|
|
84
|
+
i--;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
result.reverse();
|
|
88
|
+
// Re-order each non-context block so removes always precede adds
|
|
89
|
+
const sorted = [];
|
|
90
|
+
let idx = 0;
|
|
91
|
+
while (idx < result.length) {
|
|
92
|
+
if (result[idx].kind === 'context') {
|
|
93
|
+
sorted.push(result[idx++]);
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
const block = [];
|
|
97
|
+
while (idx < result.length && result[idx].kind !== 'context')
|
|
98
|
+
block.push(result[idx++]);
|
|
99
|
+
for (const l of block)
|
|
100
|
+
if (l.kind === 'remove')
|
|
101
|
+
sorted.push(l);
|
|
102
|
+
for (const l of block)
|
|
103
|
+
if (l.kind === 'add')
|
|
104
|
+
sorted.push(l);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return sorted;
|
|
108
|
+
}
|
|
109
|
+
export function parseOps(text) {
|
|
110
|
+
const ops = [];
|
|
111
|
+
// Q = accept both " and ' for attribute values
|
|
112
|
+
const Q = `["']`;
|
|
113
|
+
const AV = (q) => `[^${q}]`;
|
|
114
|
+
const writeRe = /<write_file\s+path=(["'])([^"']+)\1>([\s\S]*?)<\/write_file>/g;
|
|
115
|
+
let m;
|
|
116
|
+
while ((m = writeRe.exec(text)) !== null) {
|
|
117
|
+
ops.push({ type: 'write', path: m[2], content: m[3].replace(/^\n/, '') });
|
|
118
|
+
}
|
|
119
|
+
const editRe = /<edit_file\s+path=(["'])([^"']+)\1>[\s\S]*?<find>([\s\S]*?)<\/find>[\s\S]*?<replace>([\s\S]*?)<\/replace>[\s\S]*?<\/edit_file>/g;
|
|
120
|
+
while ((m = editRe.exec(text)) !== null) {
|
|
121
|
+
ops.push({ type: 'edit', path: m[2], find: m[3], replace: m[4] });
|
|
122
|
+
}
|
|
123
|
+
const mkdirRe = /<create_folder\s+path=(["'])([^"']+)\1\s*(?:\/>|><\/create_folder>)/g;
|
|
124
|
+
while ((m = mkdirRe.exec(text)) !== null) {
|
|
125
|
+
ops.push({ type: 'mkdir', path: m[2] });
|
|
126
|
+
}
|
|
127
|
+
const deleteRe = /<delete_file\s+path=(["'])([^"']+)\1\s*(?:\/>|><\/delete_file>)/g;
|
|
128
|
+
while ((m = deleteRe.exec(text)) !== null) {
|
|
129
|
+
ops.push({ type: 'delete', path: m[2] });
|
|
130
|
+
}
|
|
131
|
+
const runRe = /<run_command(?:\s+cwd=(["'])([^"']*)\2)?>([\s\S]*?)<\/run_command>/g;
|
|
132
|
+
while ((m = runRe.exec(text)) !== null) {
|
|
133
|
+
ops.push({ type: 'run', command: m[3].trim(), workdir: m[2] || undefined });
|
|
134
|
+
}
|
|
135
|
+
const readRe = /<read_file\s+path=(["'])([^"']+)\1(?:\s+lines=(["'])([^"']+)\3)?\s*(?:\/>|><\/read_file>)/g;
|
|
136
|
+
while ((m = readRe.exec(text)) !== null) {
|
|
137
|
+
ops.push({ type: 'read_file', path: m[2], lines: m[4] || undefined });
|
|
138
|
+
}
|
|
139
|
+
const readFolderRe = /<read_folder\s+path=(["'])([^"']+)\1\s*(?:\/>|><\/read_folder>)/g;
|
|
140
|
+
while ((m = readFolderRe.exec(text)) !== null) {
|
|
141
|
+
ops.push({ type: 'read_folder', path: m[2] });
|
|
142
|
+
}
|
|
143
|
+
const searchRe = /<search_code\s+pattern=(["'])([^"']+)\1(?:\s+path=(["'])([^"']*)\3)?(?:\s+include=(["'])([^"']*)\5)?(?:\s+context=(["'])(\d+)\7)?(?:\s+regex=(["'])(true|false)\9)?\s*(?:\/>|><\/search_code>)/g;
|
|
144
|
+
while ((m = searchRe.exec(text)) !== null) {
|
|
145
|
+
ops.push({
|
|
146
|
+
type: 'search_code',
|
|
147
|
+
pattern: m[2],
|
|
148
|
+
path: m[4] || undefined,
|
|
149
|
+
include: m[6] || undefined,
|
|
150
|
+
context: m[8] ? parseInt(m[8]) : undefined,
|
|
151
|
+
regex: m[10] === 'true' ? true : m[10] === 'false' ? false : undefined,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
const globRe = /<glob_files\s+pattern=(["'])([^"']+)\1(?:\s+path=(["'])([^"']*)\3)?\s*(?:\/>|><\/glob_files>)/g;
|
|
155
|
+
while ((m = globRe.exec(text)) !== null) {
|
|
156
|
+
ops.push({ type: 'glob_files', pattern: m[2], path: m[4] || undefined });
|
|
157
|
+
}
|
|
158
|
+
// suppress unused-variable warnings for Q / AV helpers used only for readability
|
|
159
|
+
void Q;
|
|
160
|
+
void AV;
|
|
161
|
+
return ops;
|
|
162
|
+
}
|
|
163
|
+
export async function executeSingleOp(op, cwd, onStage) {
|
|
164
|
+
const stage = (msg) => onStage?.(msg);
|
|
165
|
+
// ── write ────────────────────────────────────────────────────────────────
|
|
166
|
+
if (op.type === 'write' && op.path && op.content !== undefined) {
|
|
167
|
+
try {
|
|
168
|
+
const fullPath = safeResolvePath(cwd, op.path);
|
|
169
|
+
if (!fullPath)
|
|
170
|
+
return { type: 'error', message: `Access denied: ${op.path} is outside the project directory` };
|
|
171
|
+
const exists = fs.existsSync(fullPath);
|
|
172
|
+
stage(exists ? `Writing ${op.path}` : `Creating ${op.path}`);
|
|
173
|
+
// Backup before write (for undo)
|
|
174
|
+
const backupPath = exists ? backupFile(fullPath, cwd) : null;
|
|
175
|
+
if (exists)
|
|
176
|
+
recordWrite(fullPath, backupPath);
|
|
177
|
+
const oldContent = exists ? fs.readFileSync(fullPath, 'utf-8') : '';
|
|
178
|
+
if (exists && oldContent === op.content)
|
|
179
|
+
return { type: 'skipped', path: op.path };
|
|
180
|
+
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
|
181
|
+
fs.writeFileSync(fullPath, op.content, 'utf-8');
|
|
182
|
+
if (exists) {
|
|
183
|
+
const diff = computeDiff(oldContent, op.content);
|
|
184
|
+
const tooLarge = diff.length === 0 && oldContent !== op.content;
|
|
185
|
+
return {
|
|
186
|
+
type: 'modified', path: op.path, diff,
|
|
187
|
+
...(tooLarge ? {
|
|
188
|
+
linesBefore: oldContent.split('\n').length,
|
|
189
|
+
linesAfter: op.content.split('\n').length,
|
|
190
|
+
} : {}),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
return { type: 'created', path: op.path };
|
|
194
|
+
}
|
|
195
|
+
catch (e) {
|
|
196
|
+
return { type: 'error', message: `Failed to write ${op.path}: ${e instanceof Error ? e.message : String(e)}` };
|
|
197
|
+
}
|
|
198
|
+
// ── edit ─────────────────────────────────────────────────────────────────
|
|
199
|
+
}
|
|
200
|
+
else if (op.type === 'edit' && op.path && op.find !== undefined && op.replace !== undefined) {
|
|
201
|
+
try {
|
|
202
|
+
stage(`Searching ${path.basename(op.path)}`);
|
|
203
|
+
let fullPath = safeResolvePath(cwd, op.path);
|
|
204
|
+
if (!fullPath)
|
|
205
|
+
return { type: 'error', message: `Access denied: ${op.path} is outside the project directory` };
|
|
206
|
+
let resolvedPath = op.path;
|
|
207
|
+
if (!fs.existsSync(fullPath)) {
|
|
208
|
+
const found = findFile(op.path, cwd);
|
|
209
|
+
if (!found)
|
|
210
|
+
return { type: 'error', message: `File not found: ${op.path}` };
|
|
211
|
+
const foundFull = safeResolvePath(cwd, found);
|
|
212
|
+
if (!foundFull)
|
|
213
|
+
return { type: 'error', message: `Access denied: ${found} is outside the project directory` };
|
|
214
|
+
resolvedPath = found;
|
|
215
|
+
fullPath = foundFull;
|
|
216
|
+
}
|
|
217
|
+
stage(`Reading ${resolvedPath}`);
|
|
218
|
+
const oldContent = fs.readFileSync(fullPath, 'utf-8');
|
|
219
|
+
// ── Multi-stage robust match ────────────────────────────────────────────
|
|
220
|
+
let actualFind = op.find;
|
|
221
|
+
if (!oldContent.includes(op.find)) {
|
|
222
|
+
const oldLines = oldContent.split('\n');
|
|
223
|
+
const rawFind = op.find.split('\n');
|
|
224
|
+
// Try to find findLines inside oldLines — compare with trimEnd per line
|
|
225
|
+
const tryMatch = (findLines) => {
|
|
226
|
+
if (findLines.length === 0 || findLines.length > oldLines.length)
|
|
227
|
+
return -1;
|
|
228
|
+
outer2: for (let i = 0; i <= oldLines.length - findLines.length; i++) {
|
|
229
|
+
for (let j = 0; j < findLines.length; j++) {
|
|
230
|
+
if (oldLines[i + j].trimEnd() !== findLines[j].trimEnd())
|
|
231
|
+
continue outer2;
|
|
232
|
+
}
|
|
233
|
+
return i;
|
|
234
|
+
}
|
|
235
|
+
return -1;
|
|
236
|
+
};
|
|
237
|
+
// Strip " 42 │ " / "42: " / "42| " line-number prefixes AI copies from read_file
|
|
238
|
+
const stripLineNums = (lines) => lines.map(l => l.replace(/^\s*\d+\s*[│|:]\s?/, ''));
|
|
239
|
+
// Trim leading and trailing blank-only lines
|
|
240
|
+
const trimBlanks = (lines) => {
|
|
241
|
+
let s = 0, e = lines.length - 1;
|
|
242
|
+
while (s <= e && !lines[s].trim())
|
|
243
|
+
s++;
|
|
244
|
+
while (e >= s && !lines[e].trim())
|
|
245
|
+
e--;
|
|
246
|
+
return s <= e ? lines.slice(s, e + 1) : [];
|
|
247
|
+
};
|
|
248
|
+
let matchStart = -1;
|
|
249
|
+
let matchLen = rawFind.length;
|
|
250
|
+
// Stage 2: trimEnd normalization
|
|
251
|
+
matchStart = tryMatch(rawFind);
|
|
252
|
+
// Stage 3: strip line-number prefixes
|
|
253
|
+
if (matchStart < 0) {
|
|
254
|
+
const stripped = stripLineNums(rawFind);
|
|
255
|
+
matchStart = tryMatch(stripped);
|
|
256
|
+
if (matchStart >= 0)
|
|
257
|
+
matchLen = stripped.length;
|
|
258
|
+
}
|
|
259
|
+
// Stage 4: trim surrounding blank lines
|
|
260
|
+
if (matchStart < 0) {
|
|
261
|
+
const trimmed = trimBlanks(rawFind);
|
|
262
|
+
if (trimmed.length > 0 && trimmed.length < rawFind.length) {
|
|
263
|
+
matchStart = tryMatch(trimmed);
|
|
264
|
+
if (matchStart >= 0)
|
|
265
|
+
matchLen = trimmed.length;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
// Stage 5: strip line numbers + trim blanks
|
|
269
|
+
if (matchStart < 0) {
|
|
270
|
+
const trimmed = trimBlanks(stripLineNums(rawFind));
|
|
271
|
+
if (trimmed.length > 0) {
|
|
272
|
+
matchStart = tryMatch(trimmed);
|
|
273
|
+
if (matchStart >= 0)
|
|
274
|
+
matchLen = trimmed.length;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
if (matchStart >= 0) {
|
|
278
|
+
// Rebuild actualFind from the REAL file lines so replaceAll is exact
|
|
279
|
+
actualFind = oldLines.slice(matchStart, matchStart + matchLen).join('\n');
|
|
280
|
+
}
|
|
281
|
+
else {
|
|
282
|
+
// Truly not found — give AI a useful hint
|
|
283
|
+
const firstLine = rawFind.map(l => l.replace(/^\s*\d+\s*[│|:]\s?/, '')).find(l => l.trim()) ?? '';
|
|
284
|
+
const safePattern = firstLine.replace(/['"<>]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 40);
|
|
285
|
+
let hintLine = -1;
|
|
286
|
+
const searchKey = firstLine.trim().slice(0, Math.min(30, firstLine.trim().length));
|
|
287
|
+
if (searchKey.length > 4) {
|
|
288
|
+
for (let i = 0; i < oldLines.length; i++) {
|
|
289
|
+
if (oldLines[i].includes(searchKey)) {
|
|
290
|
+
hintLine = i + 1;
|
|
291
|
+
break;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
const hint = hintLine > 0
|
|
296
|
+
? ` First line found near line ${hintLine} but block did not match exactly.` +
|
|
297
|
+
` Use <read_file path="${resolvedPath}" lines="${Math.max(1, hintLine - 2)}-${hintLine + 25}"/> to get the EXACT text, then copy it verbatim (no line numbers) into <find>.`
|
|
298
|
+
: ` Text not found anywhere in ${resolvedPath}.` +
|
|
299
|
+
(safePattern.length > 3 ? ` Try <search_code pattern="${safePattern}" path="${resolvedPath}"/> to locate it.` : '') +
|
|
300
|
+
` Then use <read_file lines="N-M"/> to read that section and copy the EXACT text into <find>.`;
|
|
301
|
+
return { type: 'error', message: `Text not found in ${resolvedPath}.${hint}` };
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
// Count occurrences — replaceAll on non-unique text corrupts multiple locations
|
|
305
|
+
let occurrenceCount = 0;
|
|
306
|
+
let scanPos = 0;
|
|
307
|
+
while ((scanPos = oldContent.indexOf(actualFind, scanPos)) !== -1) {
|
|
308
|
+
occurrenceCount++;
|
|
309
|
+
scanPos += actualFind.length;
|
|
310
|
+
}
|
|
311
|
+
if (occurrenceCount > 1) {
|
|
312
|
+
const safePattern = actualFind
|
|
313
|
+
.split('\n').find(l => l.trim())?.replace(/['"<>{}()\[\]]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 40) ?? '';
|
|
314
|
+
return {
|
|
315
|
+
type: 'error',
|
|
316
|
+
message: `Found ${occurrenceCount} identical occurrences in ${resolvedPath}. ` +
|
|
317
|
+
`The <find> text must match EXACTLY ONE location. ` +
|
|
318
|
+
`Add more surrounding lines to make it unique, or use ` +
|
|
319
|
+
`<read_file path="${resolvedPath}" lines="N-M"/> to get the exact block.` +
|
|
320
|
+
(safePattern.length > 4 ? ` (First line: "${safePattern}")` : ''),
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
stage(`Applying ${resolvedPath}`);
|
|
324
|
+
// Backup before edit (for undo)
|
|
325
|
+
const editBackupPath = backupFile(fullPath, cwd);
|
|
326
|
+
recordEdit(fullPath, editBackupPath);
|
|
327
|
+
const newContent = oldContent.replace(actualFind, op.replace);
|
|
328
|
+
// No actual change — skip write and return skipped
|
|
329
|
+
if (newContent === oldContent)
|
|
330
|
+
return { type: 'skipped', path: resolvedPath };
|
|
331
|
+
fs.writeFileSync(fullPath, newContent, 'utf-8');
|
|
332
|
+
// Try full diff first (fast for files <= 2500 lines)
|
|
333
|
+
const diff = computeDiff(oldContent, newContent);
|
|
334
|
+
if (diff.length > 0) {
|
|
335
|
+
const adds = diff.filter(d => d.kind === 'add').length;
|
|
336
|
+
const removes = diff.filter(d => d.kind === 'remove').length;
|
|
337
|
+
if (adds > 0 || removes > 0) {
|
|
338
|
+
return { type: 'modified', path: resolvedPath, diff };
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
// Full diff empty or no changes detected — use snippet diff for accurate display
|
|
342
|
+
const snippetDiff = computeDiff(op.find, op.replace);
|
|
343
|
+
if (snippetDiff.length > 0) {
|
|
344
|
+
const adds = snippetDiff.filter(d => d.kind === 'add').length;
|
|
345
|
+
const removes = snippetDiff.filter(d => d.kind === 'remove').length;
|
|
346
|
+
if (adds > 0 || removes > 0) {
|
|
347
|
+
const findIdx = oldContent.indexOf(op.find);
|
|
348
|
+
const lineOffset = findIdx >= 0 ? oldContent.slice(0, findIdx).split('\n').length - 1 : 0;
|
|
349
|
+
const adjusted = snippetDiff.map(d => ({ ...d, lineNo: d.lineNo + lineOffset }));
|
|
350
|
+
return { type: 'modified', path: resolvedPath, diff: adjusted };
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
return {
|
|
354
|
+
type: 'modified', path: resolvedPath, diff: [],
|
|
355
|
+
linesBefore: oldContent.split('\n').length,
|
|
356
|
+
linesAfter: newContent.split('\n').length,
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
catch (e) {
|
|
360
|
+
return { type: 'error', message: `Failed to edit ${op.path}: ${e instanceof Error ? e.message : String(e)}` };
|
|
361
|
+
}
|
|
362
|
+
// ── mkdir ─────────────────────────────────────────────────────────────────
|
|
363
|
+
}
|
|
364
|
+
else if (op.type === 'mkdir' && op.path) {
|
|
365
|
+
try {
|
|
366
|
+
stage(`Creating ${op.path}`);
|
|
367
|
+
const mkdirFull = safeResolvePath(cwd, op.path);
|
|
368
|
+
if (!mkdirFull)
|
|
369
|
+
return { type: 'error', message: `Access denied: ${op.path} is outside the project directory` };
|
|
370
|
+
fs.mkdirSync(mkdirFull, { recursive: true });
|
|
371
|
+
return { type: 'folder_created', path: op.path };
|
|
372
|
+
}
|
|
373
|
+
catch (e) {
|
|
374
|
+
return { type: 'error', message: `Failed to create folder ${op.path}: ${e instanceof Error ? e.message : String(e)}` };
|
|
375
|
+
}
|
|
376
|
+
// ── delete ────────────────────────────────────────────────────────────────
|
|
377
|
+
}
|
|
378
|
+
else if (op.type === 'delete' && op.path) {
|
|
379
|
+
try {
|
|
380
|
+
stage(`Searching ${path.basename(op.path)}`);
|
|
381
|
+
let fullPath = safeResolvePath(cwd, op.path);
|
|
382
|
+
if (!fullPath)
|
|
383
|
+
return { type: 'error', message: `Access denied: ${op.path} is outside the project directory` };
|
|
384
|
+
let resolvedPath = op.path;
|
|
385
|
+
if (!fs.existsSync(fullPath)) {
|
|
386
|
+
const found = findFile(op.path, cwd);
|
|
387
|
+
if (!found)
|
|
388
|
+
return { type: 'error', message: `Not found: ${op.path}` };
|
|
389
|
+
const foundFull = safeResolvePath(cwd, found);
|
|
390
|
+
if (!foundFull)
|
|
391
|
+
return { type: 'error', message: `Access denied: ${found} is outside the project directory` };
|
|
392
|
+
resolvedPath = found;
|
|
393
|
+
fullPath = foundFull;
|
|
394
|
+
}
|
|
395
|
+
stage(`Deleting ${resolvedPath}`);
|
|
396
|
+
// Record for undo before deleting
|
|
397
|
+
recordDelete(fullPath);
|
|
398
|
+
const stat = fs.statSync(fullPath);
|
|
399
|
+
if (stat.isDirectory()) {
|
|
400
|
+
fs.rmSync(fullPath, { recursive: true, force: true });
|
|
401
|
+
}
|
|
402
|
+
else {
|
|
403
|
+
fs.unlinkSync(fullPath);
|
|
404
|
+
}
|
|
405
|
+
return { type: 'deleted', path: resolvedPath };
|
|
406
|
+
}
|
|
407
|
+
catch (e) {
|
|
408
|
+
return { type: 'error', message: `Failed to delete ${op.path}: ${e instanceof Error ? e.message : String(e)}` };
|
|
409
|
+
}
|
|
410
|
+
// ── run ───────────────────────────────────────────────────────────────────
|
|
411
|
+
}
|
|
412
|
+
else if (op.type === 'run' && op.command) {
|
|
413
|
+
try {
|
|
414
|
+
const runCwd = op.workdir ? path.resolve(cwd, op.workdir) : cwd;
|
|
415
|
+
stage(`Running ${op.command.slice(0, 55)}`);
|
|
416
|
+
// Detect long-running server commands — capture initial output then detach
|
|
417
|
+
const isServerCmd = /(?:^|\s)(?:npm|yarn|pnpm|bun)\s+(?:run\s+(?:dev|start|serve|watch|preview)|start)(?:\s|$)/i.test(op.command)
|
|
418
|
+
|| /(?:^|\s)(?:node|ts-node|tsx|nodemon)\s+/i.test(op.command)
|
|
419
|
+
|| /(?:^|\s)(?:python|python3|uvicorn|gunicorn|flask|django-admin)\s+.*(?:runserver|run|serve|start)/i.test(op.command)
|
|
420
|
+
|| /(?:^|\s)python3?\s+-m\s+(?:http\.server|flask|uvicorn)/i.test(op.command)
|
|
421
|
+
|| /(?:^|\s)npx\s+(?:--yes\s+)?(?:serve|live-server|http-server|@web\/dev-server|vite|parcel)(?:\s|$)/i.test(op.command)
|
|
422
|
+
|| /(?:^|\s)(?:live-server|http-server|serve)\s*/i.test(op.command)
|
|
423
|
+
|| /(?:^|\s)php\s+-S\s+/i.test(op.command)
|
|
424
|
+
|| /(?:^|\s)ruby\s+.*(?:-p\s+\d+|WEBrick|rails\s+s)/i.test(op.command);
|
|
425
|
+
// Auto-add --yes to npx commands so they never block on "Ok to proceed? (y)"
|
|
426
|
+
const safeCmd = /(?:^|\s)npx\s+(?!--yes\b)/i.test(op.command)
|
|
427
|
+
? op.command.replace(/(?<=(?:^|\s))npx(\s+)/i, 'npx --yes$1')
|
|
428
|
+
: op.command;
|
|
429
|
+
const isWindows = process.platform === 'win32';
|
|
430
|
+
// On PowerShell 5.1, 'curl' is an alias for Invoke-WebRequest — use curl.exe for real HTTP
|
|
431
|
+
const finalCmd = isWindows
|
|
432
|
+
? safeCmd.replace(/\bcurl\b(?!\.\w)/g, 'curl.exe')
|
|
433
|
+
: safeCmd;
|
|
434
|
+
const out = await new Promise((res, rej) => {
|
|
435
|
+
const child = isWindows
|
|
436
|
+
? spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', finalCmd], { cwd: runCwd, windowsHide: true })
|
|
437
|
+
: spawn('bash', ['-c', finalCmd], { cwd: runCwd });
|
|
438
|
+
child.stdout?.setEncoding('utf-8');
|
|
439
|
+
child.stderr?.setEncoding('utf-8');
|
|
440
|
+
let stdout = '';
|
|
441
|
+
let stderr = '';
|
|
442
|
+
let settled = false;
|
|
443
|
+
const settle = (output, isErr = false) => {
|
|
444
|
+
if (settled)
|
|
445
|
+
return;
|
|
446
|
+
settled = true;
|
|
447
|
+
clearTimeout(killTimer);
|
|
448
|
+
try {
|
|
449
|
+
child.stdout?.destroy();
|
|
450
|
+
child.stderr?.destroy();
|
|
451
|
+
}
|
|
452
|
+
catch { /* ignore */ }
|
|
453
|
+
if (isErr)
|
|
454
|
+
rej(new Error(output));
|
|
455
|
+
else
|
|
456
|
+
res(output);
|
|
457
|
+
};
|
|
458
|
+
// Match Vite/Next/CRA/Express server ready signals (check both stdout+stderr)
|
|
459
|
+
const SUCCESS_PAT = /localhost:\d{2,5}|Local:\s*http|ready in \d|server running|listening on|started on port|\blistening\b.*\d{4}|Serving\s+HTTP|Available\s+on:|http:\/\/127\.0\.0\.1:\d|http:\/\/0\.0\.0\.0:\d|Serving!|Accepting connections|─+\n.*\n.*localhost/i;
|
|
460
|
+
const FATAL_PAT = /EADDRINUSE|EACCES|cannot find module|MODULE_NOT_FOUND/i;
|
|
461
|
+
const checkSuccess = () => {
|
|
462
|
+
const combined = stdout + stderr;
|
|
463
|
+
if (SUCCESS_PAT.test(combined)) {
|
|
464
|
+
child.unref();
|
|
465
|
+
settle(combined.trim());
|
|
466
|
+
}
|
|
467
|
+
else if (FATAL_PAT.test(combined)) {
|
|
468
|
+
settle(combined.trim(), true);
|
|
469
|
+
}
|
|
470
|
+
};
|
|
471
|
+
const timeoutMs = isServerCmd ? 25_000 : 600_000;
|
|
472
|
+
const killTimer = setTimeout(() => {
|
|
473
|
+
if (isServerCmd) {
|
|
474
|
+
child.unref();
|
|
475
|
+
const combined = (stdout + stderr).trim();
|
|
476
|
+
settle(combined || 'Server started (running in background)');
|
|
477
|
+
}
|
|
478
|
+
else {
|
|
479
|
+
try {
|
|
480
|
+
child.kill();
|
|
481
|
+
}
|
|
482
|
+
catch { /* ignore */ }
|
|
483
|
+
settle(`Command timed out`, true);
|
|
484
|
+
}
|
|
485
|
+
}, timeoutMs);
|
|
486
|
+
child.stdout?.on('data', (d) => { stdout += d; if (isServerCmd)
|
|
487
|
+
checkSuccess(); });
|
|
488
|
+
child.stderr?.on('data', (d) => { stderr += d; if (isServerCmd)
|
|
489
|
+
checkSuccess(); });
|
|
490
|
+
child.on('close', (code) => {
|
|
491
|
+
if (code !== 0 && !settled) {
|
|
492
|
+
settle([stderr.trim(), stdout.trim()].filter(Boolean).join('\n') || `Exit code ${code}`, true);
|
|
493
|
+
}
|
|
494
|
+
else {
|
|
495
|
+
settle((stdout + stderr).trim());
|
|
496
|
+
}
|
|
497
|
+
});
|
|
498
|
+
child.on('error', (e) => settle(e.message, true));
|
|
499
|
+
});
|
|
500
|
+
return { type: 'run', message: op.command, output: out };
|
|
501
|
+
}
|
|
502
|
+
catch (e) {
|
|
503
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
504
|
+
return { type: 'error', message: msg.slice(0, 600) };
|
|
505
|
+
}
|
|
506
|
+
// ── read_file ─────────────────────────────────────────────────
|
|
507
|
+
}
|
|
508
|
+
else if (op.type === 'read_file' && op.path) {
|
|
509
|
+
try {
|
|
510
|
+
stage(`Searching ${path.basename(op.path)}`);
|
|
511
|
+
let fullPath = safeResolvePath(cwd, op.path);
|
|
512
|
+
if (!fullPath)
|
|
513
|
+
return { type: 'error', message: `Access denied: ${op.path} is outside the project directory` };
|
|
514
|
+
let resolvedPath = op.path;
|
|
515
|
+
if (!fs.existsSync(fullPath)) {
|
|
516
|
+
const found = findFile(op.path, cwd);
|
|
517
|
+
if (!found)
|
|
518
|
+
return { type: 'error', message: `File not found: ${op.path}` };
|
|
519
|
+
const foundFull = safeResolvePath(cwd, found);
|
|
520
|
+
if (!foundFull)
|
|
521
|
+
return { type: 'error', message: `Access denied: ${found} is outside the project directory` };
|
|
522
|
+
resolvedPath = found;
|
|
523
|
+
fullPath = foundFull;
|
|
524
|
+
}
|
|
525
|
+
stage(`Reading ${resolvedPath}`);
|
|
526
|
+
const raw = fs.readFileSync(fullPath, 'utf-8');
|
|
527
|
+
const allLines = raw.split('\n');
|
|
528
|
+
const total = allLines.length;
|
|
529
|
+
// Files under 6000 lines → always return full content so AI has complete context
|
|
530
|
+
const LARGE_FILE_THRESHOLD = 6000;
|
|
531
|
+
// Only truly huge files (>6000 lines) get paginated — return first 2000 lines + hint
|
|
532
|
+
if (!op.lines && total > LARGE_FILE_THRESHOLD) {
|
|
533
|
+
const PAGE = 2000;
|
|
534
|
+
const preview = allLines.slice(0, PAGE).map((l, i) => `${String(i + 1).padStart(4)} │ ${l}`).join('\n');
|
|
535
|
+
const pages = Math.ceil(total / PAGE);
|
|
536
|
+
const output = `[File: ${resolvedPath} — ${total} lines — page 1/${pages}]\n` +
|
|
537
|
+
`⚠ In <find>, copy ONLY the content AFTER " │ " — never include line number or "│"\n` +
|
|
538
|
+
`⚠ To read next page: <read_file path="${resolvedPath}" lines="${PAGE + 1}-${PAGE * 2}"/>\n\n` +
|
|
539
|
+
preview +
|
|
540
|
+
`\n\n... (${total - PAGE} more lines — next page: lines ${PAGE + 1}-${PAGE * 2})`;
|
|
541
|
+
return { type: 'run', message: resolvedPath, output };
|
|
542
|
+
}
|
|
543
|
+
let startLine = 1;
|
|
544
|
+
let endLine = total;
|
|
545
|
+
if (op.lines) {
|
|
546
|
+
const parts = op.lines.split('-').map(s => parseInt(s.trim(), 10));
|
|
547
|
+
if (parts.length === 2 && !isNaN(parts[0]) && !isNaN(parts[1])) {
|
|
548
|
+
startLine = Math.max(1, parts[0]);
|
|
549
|
+
endLine = Math.min(total, parts[1]);
|
|
550
|
+
}
|
|
551
|
+
else if (parts.length === 1 && !isNaN(parts[0])) {
|
|
552
|
+
startLine = Math.max(1, parts[0]);
|
|
553
|
+
endLine = Math.min(total, parts[0] + 199);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
const slice = allLines.slice(startLine - 1, endLine);
|
|
557
|
+
// Format: " 42 │ code" — the " │ " separator makes it clear numbers are NOT file content
|
|
558
|
+
const numbered = slice.map((line, i) => `${String(startLine + i).padStart(4)} │ ${line}`).join('\n');
|
|
559
|
+
const header = op.lines
|
|
560
|
+
? `[File: ${resolvedPath} — lines ${startLine}-${endLine} of ${total}]\n` +
|
|
561
|
+
`⚠ In <find>, copy ONLY the content AFTER " │ " — never include the line number or "│"\n`
|
|
562
|
+
: `[File: ${resolvedPath} — ${total} lines]\n` +
|
|
563
|
+
`⚠ In <find>, copy ONLY the content AFTER " │ " — never include the line number or "│"\n`;
|
|
564
|
+
return { type: 'run', message: resolvedPath, output: header + numbered };
|
|
565
|
+
}
|
|
566
|
+
catch (e) {
|
|
567
|
+
return { type: 'error', message: `Failed to read ${op.path}: ${e instanceof Error ? e.message : String(e)}` };
|
|
568
|
+
}
|
|
569
|
+
// ── read_folder ──────────────────────────────────────────────
|
|
570
|
+
}
|
|
571
|
+
else if (op.type === 'read_folder' && op.path) {
|
|
572
|
+
try {
|
|
573
|
+
const fullDir = safeResolvePath(cwd, op.path);
|
|
574
|
+
if (!fullDir)
|
|
575
|
+
return { type: 'error', message: `Access denied: ${op.path} is outside the project directory` };
|
|
576
|
+
if (!fs.existsSync(fullDir) || !fs.statSync(fullDir).isDirectory()) {
|
|
577
|
+
return { type: 'error', message: `Folder not found: ${op.path}` };
|
|
578
|
+
}
|
|
579
|
+
stage(`Reading ${op.path}`);
|
|
580
|
+
const entries = [];
|
|
581
|
+
function walkDir(dir, rel, depth) {
|
|
582
|
+
if (depth > 6)
|
|
583
|
+
return;
|
|
584
|
+
let de;
|
|
585
|
+
try {
|
|
586
|
+
de = fs.readdirSync(dir, { withFileTypes: true });
|
|
587
|
+
}
|
|
588
|
+
catch {
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
const sorted = [...de].sort((a, b) => {
|
|
592
|
+
if (a.isDirectory() && !b.isDirectory())
|
|
593
|
+
return -1;
|
|
594
|
+
if (!a.isDirectory() && b.isDirectory())
|
|
595
|
+
return 1;
|
|
596
|
+
return a.name.localeCompare(b.name);
|
|
597
|
+
});
|
|
598
|
+
for (const e of sorted) {
|
|
599
|
+
if (SKIP_DIRS.has(e.name))
|
|
600
|
+
continue;
|
|
601
|
+
if (e.name.startsWith('.') && e.name !== '.env' && e.name !== '.gitignore')
|
|
602
|
+
continue;
|
|
603
|
+
const eRel = rel ? `${rel}/${e.name}` : e.name;
|
|
604
|
+
const eFull = path.join(dir, e.name);
|
|
605
|
+
if (e.isDirectory()) {
|
|
606
|
+
entries.push({ rel: eRel + '/', isDir: true, depth });
|
|
607
|
+
walkDir(eFull, eRel, depth + 1);
|
|
608
|
+
}
|
|
609
|
+
else {
|
|
610
|
+
let size;
|
|
611
|
+
try {
|
|
612
|
+
size = fs.statSync(eFull).size;
|
|
613
|
+
}
|
|
614
|
+
catch { /* ignore */ }
|
|
615
|
+
entries.push({ rel: eRel, size, isDir: false, depth });
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
walkDir(fullDir, '', 0);
|
|
620
|
+
const fileCount = entries.filter(e => !e.isDir).length;
|
|
621
|
+
const dirCount = entries.filter(e => e.isDir).length;
|
|
622
|
+
const lines = [`Folder: ${op.path} (${fileCount} files, ${dirCount} dirs)`, ''];
|
|
623
|
+
for (const e of entries) {
|
|
624
|
+
const indent = ' '.repeat(e.depth);
|
|
625
|
+
const name = e.rel.split('/').filter(Boolean).pop() ?? e.rel;
|
|
626
|
+
const sizeStr = e.size !== undefined
|
|
627
|
+
? ` (${e.size < 1024 ? e.size + 'B' : e.size < 1_048_576 ? (e.size / 1024).toFixed(1) + 'KB' : (e.size / 1_048_576).toFixed(1) + 'MB'})`
|
|
628
|
+
: '';
|
|
629
|
+
lines.push(`${indent}${name}${e.isDir ? '/' : sizeStr}`);
|
|
630
|
+
}
|
|
631
|
+
return { type: 'run', message: `folder:${op.path}`, output: lines.join('\n') };
|
|
632
|
+
}
|
|
633
|
+
catch (e) {
|
|
634
|
+
return { type: 'error', message: `Failed to read folder ${op.path}: ${e instanceof Error ? e.message : String(e)}` };
|
|
635
|
+
}
|
|
636
|
+
// ── search_code ───────────────────────────────────────────────
|
|
637
|
+
}
|
|
638
|
+
else if (op.type === 'search_code' && op.pattern) {
|
|
639
|
+
try {
|
|
640
|
+
const searchRoot = safeResolvePath(cwd, op.path ?? '.');
|
|
641
|
+
if (!searchRoot)
|
|
642
|
+
return { type: 'error', message: `Access denied: path is outside the project directory` };
|
|
643
|
+
stage(`Searching ${op.pattern.slice(0, 45)}`);
|
|
644
|
+
const TEXT_EXTS = new Set([
|
|
645
|
+
'.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs',
|
|
646
|
+
'.py', '.go', '.java', '.c', '.cpp', '.h', '.hpp', '.cs', '.rs', '.rb', '.php',
|
|
647
|
+
'.vue', '.svelte', '.html', '.css', '.scss', '.sass', '.less',
|
|
648
|
+
'.json', '.yaml', '.yml', '.toml', '.xml', '.md', '.txt', '.sh', '.bash', '.zsh',
|
|
649
|
+
'.env', '.sql', '.graphql', '.prisma', '.proto', '.swift', '.kt', '.dart',
|
|
650
|
+
]);
|
|
651
|
+
// Build regex or literal matcher
|
|
652
|
+
let matcher;
|
|
653
|
+
let useRegex = op.regex ?? false;
|
|
654
|
+
if (useRegex) {
|
|
655
|
+
try {
|
|
656
|
+
const re = new RegExp(op.pattern, 'i');
|
|
657
|
+
matcher = (line) => re.test(line);
|
|
658
|
+
}
|
|
659
|
+
catch {
|
|
660
|
+
// Invalid regex — fall back to literal
|
|
661
|
+
const patternLower = op.pattern.toLowerCase();
|
|
662
|
+
matcher = (line) => line.toLowerCase().includes(patternLower);
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
else {
|
|
666
|
+
const patternLower = op.pattern.toLowerCase();
|
|
667
|
+
matcher = (line) => line.toLowerCase().includes(patternLower);
|
|
668
|
+
}
|
|
669
|
+
// File extension filter
|
|
670
|
+
const includeFilter = op.include ? op.include.toLowerCase().replace(/^\*\./, '.') : null;
|
|
671
|
+
const contextLines = op.context ?? 0;
|
|
672
|
+
const matches = [];
|
|
673
|
+
const MAX_MATCHES = 200;
|
|
674
|
+
function walkSearch(dir) {
|
|
675
|
+
if (matches.length >= MAX_MATCHES)
|
|
676
|
+
return;
|
|
677
|
+
let de;
|
|
678
|
+
try {
|
|
679
|
+
de = fs.readdirSync(dir, { withFileTypes: true });
|
|
680
|
+
}
|
|
681
|
+
catch {
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
for (const entry of de) {
|
|
685
|
+
if (matches.length >= MAX_MATCHES)
|
|
686
|
+
return;
|
|
687
|
+
if (SKIP_DIRS.has(entry.name))
|
|
688
|
+
continue;
|
|
689
|
+
if (entry.name.startsWith('.') && entry.name !== '.env' && entry.name !== '.gitignore')
|
|
690
|
+
continue;
|
|
691
|
+
const eFull = path.join(dir, entry.name);
|
|
692
|
+
if (entry.isDirectory()) {
|
|
693
|
+
walkSearch(eFull);
|
|
694
|
+
}
|
|
695
|
+
else {
|
|
696
|
+
const ext = path.extname(entry.name).toLowerCase();
|
|
697
|
+
if (!TEXT_EXTS.has(ext))
|
|
698
|
+
continue;
|
|
699
|
+
if (includeFilter && ext !== includeFilter)
|
|
700
|
+
continue;
|
|
701
|
+
let content;
|
|
702
|
+
try {
|
|
703
|
+
content = fs.readFileSync(eFull, 'utf-8');
|
|
704
|
+
}
|
|
705
|
+
catch {
|
|
706
|
+
continue;
|
|
707
|
+
}
|
|
708
|
+
const fileLines = content.split('\n');
|
|
709
|
+
const relFile = path.relative(cwd, eFull).replace(/\\/g, '/');
|
|
710
|
+
for (let i = 0; i < fileLines.length; i++) {
|
|
711
|
+
if (matches.length >= MAX_MATCHES)
|
|
712
|
+
break;
|
|
713
|
+
if (matcher(fileLines[i])) {
|
|
714
|
+
const before = contextLines > 0
|
|
715
|
+
? fileLines.slice(Math.max(0, i - contextLines), i).map(l => ` ${l}`)
|
|
716
|
+
: undefined;
|
|
717
|
+
const after = contextLines > 0
|
|
718
|
+
? fileLines.slice(i + 1, Math.min(fileLines.length, i + 1 + contextLines)).map(l => ` ${l}`)
|
|
719
|
+
: undefined;
|
|
720
|
+
matches.push({ file: relFile, line: i + 1, content: fileLines[i].trim().slice(0, 200), before, after });
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
walkSearch(searchRoot);
|
|
727
|
+
if (matches.length === 0) {
|
|
728
|
+
return { type: 'run', message: `search:${op.pattern}`, output: `No matches found for "${op.pattern}"` };
|
|
729
|
+
}
|
|
730
|
+
const byFile = new Map();
|
|
731
|
+
for (const fm of matches) {
|
|
732
|
+
if (!byFile.has(fm.file))
|
|
733
|
+
byFile.set(fm.file, []);
|
|
734
|
+
byFile.get(fm.file).push(fm);
|
|
735
|
+
}
|
|
736
|
+
const outLines = [];
|
|
737
|
+
for (const [file, fileMatches] of byFile) {
|
|
738
|
+
for (const fm of fileMatches) {
|
|
739
|
+
if (fm.before)
|
|
740
|
+
outLines.push(...fm.before);
|
|
741
|
+
outLines.push(`${file}:${fm.line}: ${fm.content}`);
|
|
742
|
+
if (fm.after)
|
|
743
|
+
outLines.push(...fm.after);
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
if (matches.length >= MAX_MATCHES)
|
|
747
|
+
outLines.push(`... truncated at ${MAX_MATCHES} matches`);
|
|
748
|
+
outLines.push(`\nTotal: ${matches.length} match${matches.length !== 1 ? 'es' : ''} in ${byFile.size} file${byFile.size !== 1 ? 's' : ''}`);
|
|
749
|
+
return { type: 'run', message: `search:${op.pattern}`, output: outLines.join('\n') };
|
|
750
|
+
}
|
|
751
|
+
catch (e) {
|
|
752
|
+
return { type: 'error', message: `Search failed: ${e instanceof Error ? e.message : String(e)}` };
|
|
753
|
+
}
|
|
754
|
+
// ── glob_files ────────────────────────────────────────────────
|
|
755
|
+
}
|
|
756
|
+
else if (op.type === 'glob_files' && op.pattern) {
|
|
757
|
+
try {
|
|
758
|
+
const searchRoot = safeResolvePath(cwd, op.path ?? '.');
|
|
759
|
+
if (!searchRoot)
|
|
760
|
+
return { type: 'error', message: `Access denied: path is outside the project directory` };
|
|
761
|
+
stage(`Globbing ${op.pattern.slice(0, 45)}`);
|
|
762
|
+
// Parse glob pattern: support **, *, ?, and negation with !
|
|
763
|
+
const pattern = op.pattern;
|
|
764
|
+
const isRecursive = pattern.includes('**');
|
|
765
|
+
// Extract file extension or name pattern from glob
|
|
766
|
+
// e.g., "**/*.ts" → match all .ts files recursively
|
|
767
|
+
// e.g., "src/**/*.tsx" → match .tsx files in src/ recursively
|
|
768
|
+
// e.g., "*.json" → match .json files in current dir only
|
|
769
|
+
const extMatch = pattern.match(/\*(?:\.\w+)?$/);
|
|
770
|
+
const targetExt = extMatch ? extMatch[0].replace(/^\*\./, '.') : null;
|
|
771
|
+
const nameMatch = pattern.match(/\/([^/*?]+)$/);
|
|
772
|
+
const targetName = nameMatch ? nameMatch[1] : null;
|
|
773
|
+
// Extract base directory from pattern
|
|
774
|
+
const baseDir = pattern.includes('/')
|
|
775
|
+
? pattern.split('*')[0].replace(/\/$/, '')
|
|
776
|
+
: '';
|
|
777
|
+
const resolvedBase = baseDir ? path.join(searchRoot, baseDir) : searchRoot;
|
|
778
|
+
const files = [];
|
|
779
|
+
const MAX_FILES = 500;
|
|
780
|
+
function walkGlob(dir, depth = 0) {
|
|
781
|
+
if (files.length >= MAX_FILES)
|
|
782
|
+
return;
|
|
783
|
+
if (depth > (isRecursive ? 20 : 1))
|
|
784
|
+
return;
|
|
785
|
+
let de;
|
|
786
|
+
try {
|
|
787
|
+
de = fs.readdirSync(dir, { withFileTypes: true });
|
|
788
|
+
}
|
|
789
|
+
catch {
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
for (const entry of de) {
|
|
793
|
+
if (files.length >= MAX_FILES)
|
|
794
|
+
return;
|
|
795
|
+
if (SKIP_DIRS.has(entry.name))
|
|
796
|
+
continue;
|
|
797
|
+
if (entry.name.startsWith('.') && entry.name !== '.env' && entry.name !== '.gitignore')
|
|
798
|
+
continue;
|
|
799
|
+
const eFull = path.join(dir, entry.name);
|
|
800
|
+
if (entry.isDirectory()) {
|
|
801
|
+
if (isRecursive || depth === 0)
|
|
802
|
+
walkGlob(eFull, depth + 1);
|
|
803
|
+
}
|
|
804
|
+
else {
|
|
805
|
+
// Match against pattern
|
|
806
|
+
let matches = false;
|
|
807
|
+
if (targetName) {
|
|
808
|
+
matches = entry.name === targetName;
|
|
809
|
+
}
|
|
810
|
+
else if (targetExt) {
|
|
811
|
+
matches = path.extname(entry.name).toLowerCase() === targetExt;
|
|
812
|
+
}
|
|
813
|
+
else {
|
|
814
|
+
// Simple wildcard match
|
|
815
|
+
const nameParts = pattern.split('*');
|
|
816
|
+
if (nameParts.length === 2) {
|
|
817
|
+
matches = entry.name.startsWith(nameParts[0]) && entry.name.endsWith(nameParts[1]);
|
|
818
|
+
}
|
|
819
|
+
else {
|
|
820
|
+
matches = true;
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
if (matches) {
|
|
824
|
+
try {
|
|
825
|
+
const stat = fs.statSync(eFull);
|
|
826
|
+
files.push({
|
|
827
|
+
path: path.relative(cwd, eFull).replace(/\\/g, '/'),
|
|
828
|
+
size: stat.size,
|
|
829
|
+
modified: stat.mtime.toISOString().split('T')[0],
|
|
830
|
+
});
|
|
831
|
+
}
|
|
832
|
+
catch {
|
|
833
|
+
files.push({
|
|
834
|
+
path: path.relative(cwd, eFull).replace(/\\/g, '/'),
|
|
835
|
+
size: 0,
|
|
836
|
+
modified: '',
|
|
837
|
+
});
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
if (fs.existsSync(resolvedBase)) {
|
|
844
|
+
walkGlob(resolvedBase);
|
|
845
|
+
}
|
|
846
|
+
// Sort by path
|
|
847
|
+
files.sort((a, b) => a.path.localeCompare(b.path));
|
|
848
|
+
if (files.length === 0) {
|
|
849
|
+
return { type: 'run', message: `glob:${op.pattern}`, output: `No files matched pattern "${op.pattern}"` };
|
|
850
|
+
}
|
|
851
|
+
const outLines = files.map(f => {
|
|
852
|
+
const sizeStr = f.size > 1024 * 1024 ? `${(f.size / 1024 / 1024).toFixed(1)}MB`
|
|
853
|
+
: f.size > 1024 ? `${(f.size / 1024).toFixed(1)}KB`
|
|
854
|
+
: `${f.size}B`;
|
|
855
|
+
return `${f.path} ${sizeStr} ${f.modified}`;
|
|
856
|
+
});
|
|
857
|
+
if (files.length >= MAX_FILES)
|
|
858
|
+
outLines.push(`... truncated at ${MAX_FILES} files`);
|
|
859
|
+
outLines.push(`\nTotal: ${files.length} file${files.length !== 1 ? 's' : ''}`);
|
|
860
|
+
return { type: 'run', message: `glob:${op.pattern}`, output: outLines.join('\n') };
|
|
861
|
+
}
|
|
862
|
+
catch (e) {
|
|
863
|
+
return { type: 'error', message: `Glob failed: ${e instanceof Error ? e.message : String(e)}` };
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
return { type: 'error', message: 'Unknown operation' };
|
|
867
|
+
}
|
|
868
|
+
export async function executeOps(ops, cwd) {
|
|
869
|
+
// Start undo session for this batch of operations
|
|
870
|
+
startUndoSession();
|
|
871
|
+
const results = [];
|
|
872
|
+
// Separate read-only ops from write/mutation ops
|
|
873
|
+
const READ_OPS = new Set(['read_file', 'read_folder', 'search_code', 'glob_files']);
|
|
874
|
+
const readOps = [];
|
|
875
|
+
const writeOps = [];
|
|
876
|
+
for (let i = 0; i < ops.length; i++) {
|
|
877
|
+
if (READ_OPS.has(ops[i].type)) {
|
|
878
|
+
readOps.push({ idx: i, op: ops[i] });
|
|
879
|
+
}
|
|
880
|
+
else {
|
|
881
|
+
writeOps.push({ idx: i, op: ops[i] });
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
// Initialize results array
|
|
885
|
+
for (let i = 0; i < ops.length; i++) {
|
|
886
|
+
results[i] = { type: 'skipped', message: 'pending' };
|
|
887
|
+
}
|
|
888
|
+
// Execute read-only ops in parallel (max 6 concurrent)
|
|
889
|
+
const MAX_CONCURRENT = 6;
|
|
890
|
+
for (let i = 0; i < readOps.length; i += MAX_CONCURRENT) {
|
|
891
|
+
const batch = readOps.slice(i, i + MAX_CONCURRENT);
|
|
892
|
+
const batchResults = await Promise.all(batch.map(({ op }) => executeSingleOp(op, cwd)));
|
|
893
|
+
for (let j = 0; j < batch.length; j++) {
|
|
894
|
+
results[batch[j].idx] = batchResults[j];
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
// Execute write ops sequentially with atomic rollback on failure
|
|
898
|
+
const executedWrites = [];
|
|
899
|
+
let atomicFailed = false;
|
|
900
|
+
for (const { idx, op } of writeOps) {
|
|
901
|
+
const result = await executeSingleOp(op, cwd);
|
|
902
|
+
results[idx] = result;
|
|
903
|
+
if (result.type === 'error') {
|
|
904
|
+
// Atomic mode: if any write fails, rollback all previous writes
|
|
905
|
+
atomicFailed = true;
|
|
906
|
+
for (const prev of executedWrites) {
|
|
907
|
+
// Try to rollback each previous operation
|
|
908
|
+
try {
|
|
909
|
+
if (prev.op.type === 'write' && prev.op.path) {
|
|
910
|
+
const fullPath = path.resolve(cwd, prev.op.path);
|
|
911
|
+
if (prev.result.type === 'modified' || prev.result.type === 'created') {
|
|
912
|
+
// Restore from backup if available
|
|
913
|
+
const backupDir = path.join(require('os').homedir(), '.dravix-code', 'undo');
|
|
914
|
+
const files = fs.readdirSync(backupDir).filter(f => f.endsWith('.json')).sort().reverse();
|
|
915
|
+
if (files.length > 0) {
|
|
916
|
+
const session = JSON.parse(fs.readFileSync(path.join(backupDir, files[0]), 'utf-8'));
|
|
917
|
+
const backup = session.operations?.find((o) => o.path === fullPath && o.backupPath);
|
|
918
|
+
if (backup?.backupPath && fs.existsSync(backup.backupPath)) {
|
|
919
|
+
fs.copyFileSync(backup.backupPath, fullPath);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
catch { /* ignore rollback errors */ }
|
|
926
|
+
}
|
|
927
|
+
break; // Stop executing remaining writes
|
|
928
|
+
}
|
|
929
|
+
executedWrites.push({ idx, op, result });
|
|
930
|
+
}
|
|
931
|
+
// Save undo session after all operations complete
|
|
932
|
+
saveUndoSession();
|
|
933
|
+
return results;
|
|
934
|
+
}
|
|
935
|
+
// Execute all ops in parallel (for use when order doesn't matter, e.g., all reads)
|
|
936
|
+
export async function executeOpsParallel(ops, cwd, maxConcurrent = 6) {
|
|
937
|
+
const results = [];
|
|
938
|
+
for (let i = 0; i < ops.length; i += maxConcurrent) {
|
|
939
|
+
const batch = ops.slice(i, i + maxConcurrent);
|
|
940
|
+
const batchResults = await Promise.all(batch.map(op => executeSingleOp(op, cwd)));
|
|
941
|
+
results.push(...batchResults);
|
|
942
|
+
}
|
|
943
|
+
return results;
|
|
944
|
+
}
|