vigthoria-cli 1.10.47 → 1.10.48

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 (55) hide show
  1. package/dist/commands/auth.js +51 -68
  2. package/dist/commands/bridge.js +12 -19
  3. package/dist/commands/cancel.js +15 -22
  4. package/dist/commands/chat.d.ts +28 -0
  5. package/dist/commands/config.js +33 -73
  6. package/dist/commands/deploy.js +83 -123
  7. package/dist/commands/device.js +21 -61
  8. package/dist/commands/edit.js +32 -39
  9. package/dist/commands/explain.js +18 -25
  10. package/dist/commands/fork.d.ts +17 -0
  11. package/dist/commands/fork.js +164 -0
  12. package/dist/commands/generate.js +37 -44
  13. package/dist/commands/history.d.ts +17 -0
  14. package/dist/commands/history.js +113 -0
  15. package/dist/commands/hub.js +95 -102
  16. package/dist/commands/index.js +41 -46
  17. package/dist/commands/legion.js +146 -186
  18. package/dist/commands/preview.d.ts +55 -0
  19. package/dist/commands/preview.js +467 -0
  20. package/dist/commands/replay.d.ts +18 -0
  21. package/dist/commands/replay.js +156 -0
  22. package/dist/commands/repo.d.ts +97 -0
  23. package/dist/commands/repo.js +773 -0
  24. package/dist/commands/review.js +29 -36
  25. package/dist/commands/security.js +5 -12
  26. package/dist/commands/update.d.ts +9 -0
  27. package/dist/commands/update.js +201 -0
  28. package/dist/commands/wallet.js +28 -35
  29. package/dist/commands/workflow.js +13 -20
  30. package/dist/index.d.ts +21 -0
  31. package/dist/index.js +1826 -0
  32. package/dist/utils/api.d.ts +572 -0
  33. package/dist/utils/api.js +6629 -0
  34. package/dist/utils/brain-hub-client.js +1 -5
  35. package/dist/utils/bridge-client.js +11 -52
  36. package/dist/utils/cli-state.d.ts +54 -0
  37. package/dist/utils/cli-state.js +185 -0
  38. package/dist/utils/codebase-indexer.js +4 -41
  39. package/dist/utils/config.d.ts +85 -0
  40. package/dist/utils/config.js +267 -0
  41. package/dist/utils/context-ranker.js +15 -21
  42. package/dist/utils/files.js +5 -42
  43. package/dist/utils/logger.js +42 -50
  44. package/dist/utils/persona.js +3 -8
  45. package/dist/utils/post-write-validator.js +22 -29
  46. package/dist/utils/project-memory.js +16 -23
  47. package/dist/utils/session.d.ts +118 -0
  48. package/dist/utils/session.js +423 -0
  49. package/dist/utils/task-display.js +13 -20
  50. package/dist/utils/tools.d.ts +276 -0
  51. package/dist/utils/tools.js +3522 -0
  52. package/dist/utils/workspace-brain-service.js +8 -45
  53. package/dist/utils/workspace-cache.js +18 -26
  54. package/dist/utils/workspace-stream.js +21 -63
  55. package/package.json +1 -1
@@ -0,0 +1,3522 @@
1
+ /**
2
+ * Vigthoria CLI Tools - Agentic Tool System
3
+ *
4
+ * This module provides Vigthoria Autonomous autonomous tool execution.
5
+ * Tools can be called by the AI to perform actions.
6
+ *
7
+ * Enhanced with:
8
+ * - Risk-based permission system
9
+ * - Automatic retry logic with exponential backoff
10
+ * - Undo functionality for file operations
11
+ * - Detailed error messages with suggestions
12
+ *
13
+ * @version 1.1.0
14
+ * @author Vigthoria Labs
15
+ */
16
+ import * as fs from 'fs';
17
+ import * as path from 'path';
18
+ import { execSync, spawn } from 'child_process';
19
+ import { createRequire } from 'node:module';
20
+ import chalk from 'chalk';
21
+ // ESM shim — re-create CommonJS-style `require()` so the inline
22
+ // `require('os')` / `require('minimatch')` / `require('glob')` calls
23
+ // inside lazy code paths continue to work unchanged in ESM mode.
24
+ const require = createRequire(import.meta.url);
25
+ import { CH } from './logger.js';
26
+ import { isServerRuntime } from './api.js';
27
+ const STREAM_RESPONSE_MAX_YIELD_CHARS = 32 * 1024;
28
+ const POWERSHELL_SAFE_PATH_PATTERN = /^[A-Za-z0-9_:\\/.\-\s]+$/;
29
+ const POWERSHELL_SAFE_INCLUDE_PATTERN = /^[A-Za-z0-9_*?.\-]+$/;
30
+ const SSH_SAFE_HOST_PATTERN = /^[A-Za-z0-9.-]+$/;
31
+ function getSshAllowedHosts() {
32
+ const configured = String(process.env.VIGTHORIA_SSH_ALLOWED_HOSTS || '')
33
+ .split(',')
34
+ .map((v) => v.trim().toLowerCase())
35
+ .filter(Boolean);
36
+ const defaults = ['vigthoria-server', 'localhost', '127.0.0.1'];
37
+ return new Set([...defaults, ...configured]);
38
+ }
39
+ function isNodeError(error) {
40
+ return error instanceof Error && 'code' in error;
41
+ }
42
+ function resolveWindowsInstallerPath() {
43
+ const configuredPath = process.env.VIGTHORIA_WINDOWS_INSTALLER || process.env.VIGTHORIA_UPDATE_INSTALLER;
44
+ if (configuredPath && configuredPath.trim().length > 0) {
45
+ return path.resolve(configuredPath);
46
+ }
47
+ const executableDir = path.dirname(process.execPath);
48
+ const cwd = process.cwd();
49
+ const candidates = [
50
+ path.resolve(cwd, 'dist', 'VigthoriaSetup.exe'),
51
+ path.resolve(cwd, 'release', 'VigthoriaSetup.exe'),
52
+ path.resolve(cwd, 'VigthoriaSetup.exe'),
53
+ path.resolve(executableDir, 'VigthoriaSetup.exe'),
54
+ path.resolve(executableDir, '..', 'VigthoriaSetup.exe'),
55
+ ];
56
+ return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0];
57
+ }
58
+ export async function installUpdateWindows() {
59
+ const installerPath = resolveWindowsInstallerPath();
60
+ try {
61
+ if (!fs.existsSync(installerPath)) {
62
+ return { success: false, platform: 'windows', error: 'ENOENT' };
63
+ }
64
+ await fs.promises.access(installerPath, fs.constants.F_OK);
65
+ await new Promise((resolve, reject) => {
66
+ const child = spawn(installerPath, [], {
67
+ cwd: path.dirname(installerPath),
68
+ detached: true,
69
+ stdio: 'ignore',
70
+ windowsHide: false,
71
+ });
72
+ child.once('error', reject);
73
+ child.once('spawn', () => {
74
+ child.unref();
75
+ resolve();
76
+ });
77
+ });
78
+ return { success: true, platform: 'windows' };
79
+ }
80
+ catch (error) {
81
+ if (isNodeError(error) && error.code === 'ENOENT') {
82
+ return { success: false, platform: 'windows', error: 'ENOENT' };
83
+ }
84
+ const message = error instanceof Error ? error.message : String(error);
85
+ return { success: false, platform: 'windows', error: message };
86
+ }
87
+ }
88
+ export async function* robustifyStreamResponse(res) {
89
+ const MAX_YIELD_CHARS = STREAM_RESPONSE_MAX_YIELD_CHARS;
90
+ const MAX_BUFFER_CHARS = 256 * 1024;
91
+ const body = res?.body ?? res;
92
+ const decoder = new TextDecoder('utf-8');
93
+ let reader = null;
94
+ let lineBuffer = '';
95
+ const emitContent = async function* (type, content) {
96
+ for (let offset = 0; offset < content.length; offset += MAX_YIELD_CHARS) {
97
+ const part = content.slice(offset, offset + MAX_YIELD_CHARS);
98
+ if (part.length > 0) {
99
+ yield { type, content: part };
100
+ }
101
+ }
102
+ };
103
+ const textFromObject = (value) => {
104
+ if (!value || typeof value !== 'object')
105
+ return '';
106
+ if (typeof value.content === 'string')
107
+ return value.content;
108
+ if (typeof value.text === 'string')
109
+ return value.text;
110
+ if (typeof value.delta === 'string')
111
+ return value.delta;
112
+ if (typeof value.delta?.text === 'string')
113
+ return value.delta.text;
114
+ if (typeof value.message?.content === 'string')
115
+ return value.message.content;
116
+ if (typeof value.choices?.[0]?.delta?.content === 'string')
117
+ return value.choices[0].delta.content;
118
+ if (typeof value.choices?.[0]?.message?.content === 'string')
119
+ return value.choices[0].message.content;
120
+ if (typeof value.error === 'string')
121
+ return value.error;
122
+ if (typeof value.error?.message === 'string')
123
+ return value.error.message;
124
+ return '';
125
+ };
126
+ const stringifyChunk = (chunk) => {
127
+ if (typeof chunk === 'string')
128
+ return chunk;
129
+ if (Buffer.isBuffer(chunk))
130
+ return chunk.toString('utf8');
131
+ if (chunk instanceof Uint8Array)
132
+ return Buffer.from(chunk).toString('utf8');
133
+ if (chunk instanceof ArrayBuffer)
134
+ return Buffer.from(chunk).toString('utf8');
135
+ if (chunk === null || chunk === undefined)
136
+ return '';
137
+ const objectText = textFromObject(chunk);
138
+ return objectText || String(chunk);
139
+ };
140
+ const decodeLine = (line) => {
141
+ const trimmed = line.trim();
142
+ if (!trimmed || trimmed === 'event: ping' || trimmed === ':' || trimmed === 'data: [DONE]' || trimmed === '[DONE]') {
143
+ return null;
144
+ }
145
+ const payload = trimmed.startsWith('data:') ? trimmed.slice(5).trimStart() : trimmed;
146
+ if (!payload || payload === '[DONE]')
147
+ return null;
148
+ if ((payload.startsWith('{') && payload.endsWith('}')) || (payload.startsWith('[') && payload.endsWith(']'))) {
149
+ try {
150
+ const parsed = JSON.parse(payload);
151
+ const parsedText = textFromObject(parsed);
152
+ if (parsedText) {
153
+ const type = parsed.error ? 'error' : 'delta';
154
+ return { type, content: parsedText };
155
+ }
156
+ }
157
+ catch (error) {
158
+ console.debug(`Stream JSON fragment preserved as text: ${error instanceof Error ? error.message : String(error)}`);
159
+ }
160
+ }
161
+ if (payload.startsWith('event:') || payload.startsWith('id:') || payload.startsWith('retry:')) {
162
+ return null;
163
+ }
164
+ return { type: 'delta', content: payload };
165
+ };
166
+ const consumeText = async function* (text, flush = false) {
167
+ if (text) {
168
+ lineBuffer += text;
169
+ }
170
+ while (lineBuffer.length > MAX_BUFFER_CHARS) {
171
+ const newlineIndex = lineBuffer.indexOf('\n', Math.max(0, MAX_BUFFER_CHARS - MAX_YIELD_CHARS));
172
+ const cutIndex = newlineIndex >= 0 ? newlineIndex + 1 : MAX_BUFFER_CHARS;
173
+ const overflow = lineBuffer.slice(0, cutIndex);
174
+ lineBuffer = lineBuffer.slice(cutIndex);
175
+ const decoded = decodeLine(overflow);
176
+ if (decoded) {
177
+ yield* emitContent(decoded.type, decoded.content);
178
+ }
179
+ else {
180
+ yield* emitContent('delta', overflow);
181
+ }
182
+ }
183
+ const lines = lineBuffer.split(/\r?\n/);
184
+ const partialLine = lines.pop() ?? '';
185
+ for (const line of lines) {
186
+ const decoded = decodeLine(line);
187
+ if (decoded) {
188
+ yield* emitContent(decoded.type, decoded.content);
189
+ }
190
+ }
191
+ if (flush) {
192
+ lineBuffer = '';
193
+ if (partialLine) {
194
+ const decoded = decodeLine(partialLine);
195
+ if (decoded) {
196
+ yield* emitContent(decoded.type, decoded.content);
197
+ }
198
+ }
199
+ }
200
+ else {
201
+ lineBuffer = partialLine;
202
+ }
203
+ };
204
+ try {
205
+ if (!body) {
206
+ return;
207
+ }
208
+ if (typeof body.getReader === 'function') {
209
+ reader = body.getReader();
210
+ const streamReader = reader;
211
+ const decoder = new TextDecoder();
212
+ while (true) {
213
+ const { done, value } = await streamReader.read();
214
+ if (done)
215
+ break;
216
+ const content = decoder.decode(value, { stream: true });
217
+ if (content.length > 0) {
218
+ yield* consumeText(content);
219
+ }
220
+ }
221
+ const tail = decoder.decode();
222
+ if (tail.length > 0) {
223
+ yield* consumeText(tail);
224
+ }
225
+ yield* consumeText('', true);
226
+ return;
227
+ }
228
+ if (typeof body[Symbol.asyncIterator] === 'function') {
229
+ for await (const chunk of body) {
230
+ const content = stringifyChunk(chunk);
231
+ if (content.length > 0) {
232
+ yield* consumeText(content);
233
+ }
234
+ }
235
+ yield* consumeText('', true);
236
+ return;
237
+ }
238
+ const content = stringifyChunk(body);
239
+ if (content.length > 0) {
240
+ yield* emitContent('text', content);
241
+ }
242
+ }
243
+ catch (error) {
244
+ const content = error instanceof Error ? error.message : String(error);
245
+ yield { type: 'error', content };
246
+ }
247
+ finally {
248
+ lineBuffer = '';
249
+ try {
250
+ reader?.releaseLock();
251
+ }
252
+ catch (error) {
253
+ const message = error instanceof Error ? error.message : String(error);
254
+ console.debug(`Stream reader release failed: ${message}`);
255
+ }
256
+ }
257
+ }
258
+ const TOOL_ARG_ALIASES = {
259
+ read_file: {
260
+ path: ['file', 'filePath', 'filepath', 'target', 'targetPath'],
261
+ start_line: ['start', 'startLine', 'fromLine', 'lineStart'],
262
+ end_line: ['end', 'endLine', 'toLine', 'lineEnd'],
263
+ },
264
+ write_file: {
265
+ path: ['file', 'filePath', 'filepath', 'target', 'targetPath'],
266
+ content: ['text', 'contents', 'body'],
267
+ },
268
+ edit_file: {
269
+ path: ['file', 'filePath', 'filepath', 'target', 'targetPath'],
270
+ old_text: ['old', 'oldText', 'find', 'search', 'searchText'],
271
+ new_text: ['new', 'newText', 'replace', 'replaceText', 'replacement'],
272
+ },
273
+ bash: {
274
+ command: ['cmd', 'script'],
275
+ cwd: ['path', 'dir', 'directory'],
276
+ },
277
+ grep: {
278
+ pattern: ['query', 'search', 'regex', 'text'],
279
+ path: ['dir', 'directory', 'cwd', 'root'],
280
+ include: ['includePattern', 'filePattern', 'glob'],
281
+ },
282
+ list_dir: {
283
+ path: ['dir', 'directory', 'cwd', 'root'],
284
+ recursive: ['recurse'],
285
+ },
286
+ glob: {
287
+ pattern: ['query', 'search', 'path', 'file', 'name', 'filename', 'glob'],
288
+ },
289
+ git: {
290
+ args: ['command', 'cmd'],
291
+ },
292
+ fetch_url: {
293
+ url: ['link', 'href'],
294
+ method: ['httpMethod'],
295
+ headers: ['header'],
296
+ body: ['content', 'data'],
297
+ selector: ['css', 'cssSelector'],
298
+ },
299
+ ssh_exec: {
300
+ command: ['cmd', 'script'],
301
+ host: ['server'],
302
+ },
303
+ task: {
304
+ description: ['prompt', 'task', 'query', 'instructions'],
305
+ working_dir: ['cwd', 'dir', 'directory', 'workDir'],
306
+ },
307
+ multi_edit: {
308
+ edits: ['changes', 'operations', 'replacements'],
309
+ },
310
+ codebase_search: {
311
+ query: ['search', 'pattern', 'text', 'symbol'],
312
+ scope: ['type', 'mode'],
313
+ include: ['includePattern', 'filePattern', 'glob'],
314
+ max_results: ['limit', 'maxResults', 'count'],
315
+ },
316
+ };
317
+ // Error types for better handling
318
+ export var ToolErrorType;
319
+ (function (ToolErrorType) {
320
+ ToolErrorType["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
321
+ ToolErrorType["PERMISSION_DENIED"] = "PERMISSION_DENIED";
322
+ ToolErrorType["NETWORK_ERROR"] = "NETWORK_ERROR";
323
+ ToolErrorType["TIMEOUT"] = "TIMEOUT";
324
+ ToolErrorType["INVALID_ARGS"] = "INVALID_ARGS";
325
+ ToolErrorType["EXECUTION_FAILED"] = "EXECUTION_FAILED";
326
+ ToolErrorType["USER_CANCELLED"] = "USER_CANCELLED";
327
+ })(ToolErrorType || (ToolErrorType = {}));
328
+ export class AgenticTools {
329
+ logger;
330
+ cwd;
331
+ permissionCallback;
332
+ autoApprove;
333
+ undoStack = [];
334
+ maxUndoStack = 50;
335
+ retryConfig = {
336
+ maxRetries: 3,
337
+ baseDelayMs: 1000,
338
+ maxDelayMs: 10000,
339
+ retryableErrors: ['ECONNRESET', 'ETIMEDOUT', 'ENOTFOUND', 'ECONNREFUSED', 'EAI_AGAIN'],
340
+ };
341
+ formatExternalToolError(toolName, operation, error) {
342
+ if (error instanceof Error) {
343
+ const processError = error;
344
+ const details = [
345
+ `External tool call failed in ${toolName} during ${operation}: ${error.message}`,
346
+ processError.code !== undefined ? `code=${processError.code}` : undefined,
347
+ processError.status !== undefined ? `status=${processError.status}` : undefined,
348
+ processError.signal ? `signal=${processError.signal}` : undefined,
349
+ processError.stderr ? `stderr=${processError.stderr.toString().trim()}` : undefined,
350
+ processError.stdout ? `stdout=${processError.stdout.toString().trim()}` : undefined,
351
+ ].filter(Boolean);
352
+ return details.join(' | ');
353
+ }
354
+ return `External tool call failed in ${toolName} during ${operation}: ${String(error)}`;
355
+ }
356
+ externalToolFailure(toolName, operation, error, suggestion) {
357
+ const message = this.formatExternalToolError(toolName, operation, error);
358
+ this.logger.debug(message);
359
+ this.logger.warn(message);
360
+ return {
361
+ success: false,
362
+ error: message,
363
+ suggestion: suggestion || 'Review the command, arguments, permissions, and environment, then retry.',
364
+ canRetry: true,
365
+ };
366
+ }
367
+ cleanupAfterToolError(toolName, operation, cleanup) {
368
+ try {
369
+ cleanup();
370
+ }
371
+ catch (cleanupError) {
372
+ const message = this.formatExternalToolError(toolName, `${operation} cleanup`, cleanupError);
373
+ this.logger.debug(message);
374
+ this.logger.warn(message);
375
+ }
376
+ }
377
+ runExternalCommand(toolName, operation, command, options, cleanup) {
378
+ if (!this.isNonEmptyString(toolName)) {
379
+ throw new Error('Invalid tool execution: toolName must be a non-empty string.');
380
+ }
381
+ if (!this.isNonEmptyString(operation)) {
382
+ throw new Error(`Invalid external command for ${toolName}: operation must be a non-empty string.`);
383
+ }
384
+ if (!this.isNonEmptyString(command)) {
385
+ throw new Error(`Invalid external command for ${toolName} during ${operation}: command must be a non-empty string.`);
386
+ }
387
+ try {
388
+ return execSync(command, options);
389
+ }
390
+ catch (error) {
391
+ if (cleanup) {
392
+ this.cleanupAfterToolError(toolName, operation, cleanup);
393
+ }
394
+ const message = this.formatExternalToolError(toolName, operation, error);
395
+ const wrapped = new Error(message);
396
+ wrapped.cause = error;
397
+ throw wrapped;
398
+ }
399
+ }
400
+ isNonEmptyString(value) {
401
+ return typeof value === 'string' && value.trim().length > 0;
402
+ }
403
+ describeInvalidValue(value) {
404
+ if (value === null)
405
+ return 'null';
406
+ if (value === undefined)
407
+ return 'undefined';
408
+ if (Array.isArray(value))
409
+ return 'array';
410
+ return typeof value;
411
+ }
412
+ assertStringRecord(value, context) {
413
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
414
+ throw new Error(`${context} must be an object with string values; received ${this.describeInvalidValue(value)}.`);
415
+ }
416
+ for (const [key, entryValue] of Object.entries(value)) {
417
+ if (!this.isNonEmptyString(key)) {
418
+ throw new Error(`${context} contains an invalid empty parameter name.`);
419
+ }
420
+ if (typeof entryValue !== 'string') {
421
+ throw new Error(`${context}.${key} must be a string; received ${this.describeInvalidValue(entryValue)}.`);
422
+ }
423
+ }
424
+ }
425
+ requireNonEmptyString(value, fieldName, toolName) {
426
+ if (!this.isNonEmptyString(value)) {
427
+ throw new Error(`Invalid arguments for ${toolName}: ${fieldName} is required and must be a non-empty string.`);
428
+ }
429
+ return value;
430
+ }
431
+ requireArgsObject(args, toolName) {
432
+ this.assertStringRecord(args, `Invalid arguments for ${toolName}: args`);
433
+ }
434
+ // Session-based tool approvals - remembers which tools user approved for this turn
435
+ sessionApprovedTools = new Set();
436
+ indexedCodebaseSearch = null;
437
+ // Persistent permissions - tool allowlists per project
438
+ static permissionsFile = path.join(process.env.HOME || process.env.USERPROFILE || '~', '.vigthoria', 'permissions.json');
439
+ constructor(logger, cwd, permissionCallback, autoApprove = false) {
440
+ if (!logger) {
441
+ throw new Error('AgenticTools initialization failed: logger is required.');
442
+ }
443
+ if (typeof cwd !== 'string' || cwd.trim().length === 0) {
444
+ throw new Error('AgenticTools initialization failed: cwd must be a non-empty string.');
445
+ }
446
+ if (typeof permissionCallback !== 'function') {
447
+ throw new Error('AgenticTools initialization failed: permissionCallback must be a function.');
448
+ }
449
+ if (typeof autoApprove !== 'boolean') {
450
+ throw new Error('AgenticTools initialization failed: autoApprove must be a boolean.');
451
+ }
452
+ this.logger = logger;
453
+ this.cwd = path.resolve(cwd);
454
+ this.permissionCallback = permissionCallback;
455
+ this.autoApprove = autoApprove;
456
+ }
457
+ /** Rebind tool execution to a different local workspace root (e.g. prompt path override). */
458
+ setWorkspaceRoot(cwd) {
459
+ if (typeof cwd !== 'string' || cwd.trim().length === 0) {
460
+ throw new Error('AgenticTools.setWorkspaceRoot failed: cwd must be a non-empty string.');
461
+ }
462
+ this.cwd = path.resolve(cwd);
463
+ }
464
+ setIndexedCodebaseSearch(handler) {
465
+ this.indexedCodebaseSearch = handler;
466
+ }
467
+ getWorkspaceRoot() {
468
+ return this.cwd;
469
+ }
470
+ getErrorMessage(error) {
471
+ if (error instanceof Error) {
472
+ return error.message;
473
+ }
474
+ if (typeof error === 'string') {
475
+ return error;
476
+ }
477
+ try {
478
+ return JSON.stringify(error);
479
+ }
480
+ catch {
481
+ return String(error);
482
+ }
483
+ }
484
+ assertToolCall(call) {
485
+ if (!call || typeof call !== 'object') {
486
+ throw new Error('Invalid tool call: call must be an object.');
487
+ }
488
+ if (typeof call.tool !== 'string' || call.tool.trim().length === 0) {
489
+ throw new Error('Invalid tool call: tool name must be a non-empty string.');
490
+ }
491
+ if (!call.args || typeof call.args !== 'object' || Array.isArray(call.args)) {
492
+ throw new Error(`Invalid tool call for ${call.tool}: args must be an object.`);
493
+ }
494
+ for (const [key, value] of Object.entries(call.args)) {
495
+ if (typeof key !== 'string' || key.trim().length === 0) {
496
+ throw new Error(`Invalid tool call for ${call.tool}: argument names must be non-empty strings.`);
497
+ }
498
+ if (typeof value !== 'string') {
499
+ throw new Error(`Invalid argument "${key}" for ${call.tool}: expected string, received ${typeof value}.`);
500
+ }
501
+ }
502
+ }
503
+ /**
504
+ * Load persistent permissions for the current project
505
+ */
506
+ loadPersistentPermissions() {
507
+ try {
508
+ if (fs.existsSync(AgenticTools.permissionsFile)) {
509
+ return JSON.parse(fs.readFileSync(AgenticTools.permissionsFile, 'utf-8'));
510
+ }
511
+ }
512
+ catch (error) {
513
+ const message = this.formatExternalToolError('permissions', `read ${AgenticTools.permissionsFile}`, error);
514
+ this.logger.debug(message);
515
+ this.logger.warn(message);
516
+ }
517
+ return {};
518
+ }
519
+ /**
520
+ * Save a persistent permission for a tool in the current project
521
+ */
522
+ savePersistentPermission(toolName) {
523
+ const permissions = this.loadPersistentPermissions();
524
+ const projectKey = this.cwd;
525
+ if (!permissions[projectKey]) {
526
+ permissions[projectKey] = { tools: [], updatedAt: new Date().toISOString() };
527
+ }
528
+ if (!permissions[projectKey].tools.includes(toolName)) {
529
+ permissions[projectKey].tools.push(toolName);
530
+ permissions[projectKey].updatedAt = new Date().toISOString();
531
+ }
532
+ try {
533
+ const dir = path.dirname(AgenticTools.permissionsFile);
534
+ if (!fs.existsSync(dir))
535
+ fs.mkdirSync(dir, { recursive: true });
536
+ fs.writeFileSync(AgenticTools.permissionsFile, JSON.stringify(permissions, null, 2), 'utf-8');
537
+ }
538
+ catch (error) {
539
+ const message = this.formatExternalToolError('permissions', `write ${AgenticTools.permissionsFile}`, error);
540
+ this.logger.debug(message);
541
+ this.logger.warn(message);
542
+ }
543
+ }
544
+ /**
545
+ * Check if a tool has persistent permission for the current project
546
+ */
547
+ hasPersistentPermission(toolName) {
548
+ const permissions = this.loadPersistentPermissions();
549
+ const projectKey = this.cwd;
550
+ return permissions[projectKey]?.tools?.includes(toolName) || false;
551
+ }
552
+ /**
553
+ * Clear session-approved tools (call this at the start of each new AI turn)
554
+ */
555
+ clearSessionApprovals() {
556
+ this.sessionApprovedTools.clear();
557
+ }
558
+ /**
559
+ * Get currently approved tools for this session
560
+ */
561
+ getSessionApprovedTools() {
562
+ return Array.from(this.sessionApprovedTools);
563
+ }
564
+ /**
565
+ * Get the undo stack for inspection
566
+ */
567
+ getUndoStack() {
568
+ return [...this.undoStack];
569
+ }
570
+ /**
571
+ * Undo the last file operation
572
+ */
573
+ async undo() {
574
+ const lastOp = this.undoStack.pop();
575
+ if (!lastOp) {
576
+ return {
577
+ success: false,
578
+ error: 'Nothing to undo',
579
+ suggestion: 'The undo stack is empty. Only file write/edit operations can be undone.',
580
+ };
581
+ }
582
+ if (lastOp.filePath) {
583
+ try {
584
+ if (lastOp.originalContent === null) {
585
+ // File was created, so delete it
586
+ if (fs.existsSync(lastOp.filePath)) {
587
+ fs.unlinkSync(lastOp.filePath);
588
+ return {
589
+ success: true,
590
+ output: `${CH.success} Undone: ${lastOp.description}\n File deleted: ${lastOp.filePath}`,
591
+ metadata: { remainingUndos: this.undoStack.length },
592
+ };
593
+ }
594
+ }
595
+ else if (lastOp.originalContent !== undefined) {
596
+ // Restore original content
597
+ fs.writeFileSync(lastOp.filePath, lastOp.originalContent, 'utf-8');
598
+ return {
599
+ success: true,
600
+ output: `${CH.success} Undone: ${lastOp.description}\n File restored: ${lastOp.filePath}`,
601
+ metadata: { remainingUndos: this.undoStack.length },
602
+ };
603
+ }
604
+ }
605
+ catch (error) {
606
+ return {
607
+ success: false,
608
+ error: `Failed to undo: ${error.message}`,
609
+ suggestion: 'The file may have been moved or permissions changed.',
610
+ };
611
+ }
612
+ }
613
+ return {
614
+ success: false,
615
+ error: 'This operation cannot be undone',
616
+ };
617
+ }
618
+ /**
619
+ * List of available tools - Vigthoria's advanced
620
+ * Enhanced with risk levels and categories
621
+ */
622
+ static getToolDefinitions() {
623
+ return [
624
+ {
625
+ name: 'read_file',
626
+ description: 'Read the contents of a file',
627
+ parameters: [
628
+ { name: 'path', description: 'File path (relative or absolute)', required: true },
629
+ { name: 'start_line', description: 'Start line (1-indexed)', required: false },
630
+ { name: 'end_line', description: 'End line (1-indexed)', required: false },
631
+ ],
632
+ requiresPermission: false,
633
+ dangerous: false,
634
+ riskLevel: 'low',
635
+ category: 'read',
636
+ },
637
+ {
638
+ name: 'write_file',
639
+ description: 'Write content to a file (creates if not exists)',
640
+ parameters: [
641
+ { name: 'path', description: 'File path', required: true },
642
+ { name: 'content', description: 'Content to write', required: true },
643
+ ],
644
+ requiresPermission: true,
645
+ dangerous: false,
646
+ riskLevel: 'medium',
647
+ category: 'write',
648
+ },
649
+ {
650
+ name: 'edit_file',
651
+ description: 'Make specific edits to a file by replacing text',
652
+ parameters: [
653
+ { name: 'path', description: 'File path', required: true },
654
+ { name: 'old_text', description: 'Text to replace', required: true },
655
+ { name: 'new_text', description: 'New text', required: true },
656
+ ],
657
+ requiresPermission: true,
658
+ dangerous: false,
659
+ riskLevel: 'medium',
660
+ category: 'write',
661
+ },
662
+ {
663
+ name: 'bash',
664
+ description: 'Run a shell command',
665
+ parameters: [
666
+ { name: 'command', description: 'Shell command to execute', required: true },
667
+ { name: 'cwd', description: 'Working directory', required: false },
668
+ { name: 'timeout', description: 'Timeout in seconds', required: false },
669
+ ],
670
+ requiresPermission: true,
671
+ dangerous: true,
672
+ riskLevel: 'high',
673
+ category: 'execute',
674
+ },
675
+ {
676
+ name: 'grep',
677
+ description: 'Search for patterns in files',
678
+ parameters: [
679
+ { name: 'pattern', description: 'Search pattern (regex)', required: true },
680
+ { name: 'path', description: 'File or directory path', required: false },
681
+ { name: 'include', description: 'File pattern to include (e.g., *.ts)', required: false },
682
+ ],
683
+ requiresPermission: false,
684
+ dangerous: false,
685
+ riskLevel: 'low',
686
+ category: 'search',
687
+ },
688
+ {
689
+ name: 'list_dir',
690
+ description: 'List contents of a directory',
691
+ parameters: [
692
+ { name: 'path', description: 'Directory path', required: true },
693
+ { name: 'recursive', description: 'List recursively', required: false },
694
+ ],
695
+ requiresPermission: false,
696
+ dangerous: false,
697
+ riskLevel: 'low',
698
+ category: 'read',
699
+ },
700
+ {
701
+ name: 'glob',
702
+ description: 'Find files matching a pattern',
703
+ parameters: [
704
+ { name: 'pattern', description: 'Glob pattern (e.g., **/*.ts)', required: true },
705
+ ],
706
+ requiresPermission: false,
707
+ dangerous: false,
708
+ riskLevel: 'low',
709
+ category: 'search',
710
+ },
711
+ {
712
+ name: 'git',
713
+ description: 'Run git commands',
714
+ parameters: [
715
+ { name: 'args', description: 'Git command arguments', required: true },
716
+ ],
717
+ requiresPermission: true,
718
+ dangerous: false,
719
+ riskLevel: 'medium',
720
+ category: 'execute',
721
+ },
722
+ {
723
+ name: 'repo',
724
+ description: 'Manage projects in Vigthoria Repository - push, pull, list, share, delete, or clone projects',
725
+ parameters: [
726
+ { name: 'action', description: 'Action: push, pull, list, status, share, delete, clone', required: true },
727
+ { name: 'project', description: 'Project name (for push/pull/status/share/delete)', required: false },
728
+ { name: 'files', description: 'Files to push as JSON object {filename: content} or array [{path, content}]', required: false },
729
+ { name: 'description', description: 'Project description (for push)', required: false },
730
+ { name: 'visibility', description: 'Visibility: public or private (for push)', required: false },
731
+ { name: 'path', description: 'Directory path (for push) or target path (for clone)', required: false },
732
+ { name: 'username', description: 'Username to share with (for share action)', required: false },
733
+ { name: 'permission', description: 'Permission level: read, write, admin (for share action)', required: false },
734
+ ],
735
+ requiresPermission: true,
736
+ dangerous: false,
737
+ riskLevel: 'medium',
738
+ category: 'execute',
739
+ },
740
+ {
741
+ name: 'fetch_url',
742
+ description: 'Fetch content from a URL (web page, API endpoint). Works cross-platform on Windows, Mac, and Linux.',
743
+ parameters: [
744
+ { name: 'url', description: 'URL to fetch (must be http or https)', required: true },
745
+ { name: 'method', description: 'HTTP method (GET, POST, etc.)', required: false },
746
+ { name: 'headers', description: 'JSON string of headers to send', required: false },
747
+ { name: 'body', description: 'Request body for POST/PUT requests', required: false },
748
+ { name: 'selector', description: 'CSS selector to extract specific content (for HTML)', required: false },
749
+ ],
750
+ requiresPermission: true,
751
+ dangerous: false,
752
+ riskLevel: 'low',
753
+ category: 'read',
754
+ },
755
+ {
756
+ name: 'browser',
757
+ description: 'Drive a real headless Chromium via the Vigthoria DevTools Bridge. Use to capture a page (screenshot+HTML+metrics), collect console/page errors, or run a quick smoke test on a URL. Cross-platform.',
758
+ parameters: [
759
+ { name: 'mode', description: "One of: 'capture' (screenshot + html + metrics), 'errors' (console + page errors), 'test' (quick smoke test)", required: true },
760
+ { name: 'url', description: 'Target URL (must start with http:// or https://)', required: true },
761
+ { name: 'include_screenshot', description: "For mode=capture: 'true' to include base64 screenshot (default true), 'false' to skip", required: false },
762
+ ],
763
+ requiresPermission: true,
764
+ dangerous: false,
765
+ riskLevel: 'low',
766
+ category: 'read',
767
+ },
768
+ {
769
+ name: 'ssh_exec',
770
+ description: 'Execute a command on a remote server via SSH (useful for Unix commands from Windows)',
771
+ parameters: [
772
+ { name: 'command', description: 'Command to execute on remote server', required: true },
773
+ { name: 'host', description: 'SSH host (default: vigthoria-server)', required: false },
774
+ { name: 'timeout', description: 'Timeout in seconds', required: false },
775
+ ],
776
+ requiresPermission: true,
777
+ dangerous: true,
778
+ riskLevel: 'high',
779
+ category: 'execute',
780
+ },
781
+ {
782
+ name: 'task',
783
+ description: 'Launch an independent sub-agent to handle a complex subtask. The sub-agent has its own context and tool access, runs autonomously, and returns a single result. Use this to parallelize work or delegate research.',
784
+ parameters: [
785
+ { name: 'description', description: 'A detailed description of the subtask for the sub-agent to perform', required: true },
786
+ { name: 'working_dir', description: 'Working directory for the sub-agent (relative to project root)', required: false },
787
+ ],
788
+ requiresPermission: true,
789
+ dangerous: false,
790
+ riskLevel: 'medium',
791
+ category: 'execute',
792
+ },
793
+ {
794
+ name: 'multi_edit',
795
+ description: 'Apply multiple file edits atomically. All edits succeed or all are rolled back. Each edit specifies a file, old_text to find, and new_text to replace it with.',
796
+ parameters: [
797
+ { name: 'edits', description: 'JSON array of edits: [{"path": "file.ts", "old_text": "find this", "new_text": "replace with"}]', required: true },
798
+ ],
799
+ requiresPermission: true,
800
+ dangerous: false,
801
+ riskLevel: 'medium',
802
+ category: 'write',
803
+ },
804
+ {
805
+ name: 'codebase_search',
806
+ description: 'Perform a deep semantic search across the entire codebase. Searches file names, symbol names (functions, classes, variables), and content across all files - not limited to the workspace snapshot. Use for large projects.',
807
+ parameters: [
808
+ { name: 'query', description: 'Search query - can be a symbol name, concept, or natural language description', required: true },
809
+ { name: 'scope', description: 'Search scope: "symbols" (functions/classes), "files" (filenames), "content" (full-text), or "all" (default)', required: false },
810
+ { name: 'include', description: 'File pattern to include (e.g., "*.ts", "src/**/*.js")', required: false },
811
+ { name: 'max_results', description: 'Maximum results to return (default: 30)', required: false },
812
+ ],
813
+ requiresPermission: false,
814
+ dangerous: false,
815
+ riskLevel: 'low',
816
+ category: 'search',
817
+ },
818
+ ];
819
+ }
820
+ /**
821
+ * Execute a tool call with enhanced error handling and retry logic
822
+ */
823
+ async execute(call) {
824
+ // Guard against malformed tool calls before accessing fields.
825
+ if (!call || typeof call !== 'object') {
826
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid tool call: expected an object, received ${call === null ? 'null' : typeof call}`, 'Provide a valid ToolCall object with a non-empty tool name and args object.');
827
+ }
828
+ if (!call.tool || typeof call.tool !== 'string' || !call.tool.trim()) {
829
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid tool call: tool name is ${call.tool === undefined ? 'undefined' : typeof call.tool === 'string' ? 'empty' : typeof call.tool}`, `Provide a valid tool name. Available tools: ${AgenticTools.getToolDefinitions().map(t => t.name).join(', ')}`);
830
+ }
831
+ if (!call.args || typeof call.args !== 'object' || Array.isArray(call.args)) {
832
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid tool call for '${call.tool}': args must be a key/value object`, 'Provide args as an object with string values, for example { path: "src/index.ts" }.');
833
+ }
834
+ try {
835
+ this.assertStringRecord(call.args, `Invalid tool call for '${call.tool}': args`);
836
+ }
837
+ catch (error) {
838
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, this.getErrorMessage(error), 'All tool argument names must be non-empty strings and every argument value must be a string.');
839
+ }
840
+ const normalizedCall = this.normalizeToolCall(call);
841
+ const tool = AgenticTools.getToolDefinitions().find(t => t.name === normalizedCall.tool);
842
+ if (!tool) {
843
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Unknown tool: ${call.tool}`, `Available tools: ${AgenticTools.getToolDefinitions().map(t => t.name).join(', ')}`);
844
+ }
845
+ // Validate required parameters
846
+ const validationError = this.validateParameters(normalizedCall, tool);
847
+ if (validationError) {
848
+ return validationError;
849
+ }
850
+ // Check permission for dangerous/modifying actions
851
+ if (tool.requiresPermission && !this.autoApprove) {
852
+ const requiresPerCommandApproval = normalizedCall.tool === 'bash';
853
+ if (requiresPerCommandApproval) {
854
+ const approved = await this.permissionCallback(this.formatPermissionRequest(normalizedCall, tool), { batchApproval: false });
855
+ if (approved === false) {
856
+ return {
857
+ success: false,
858
+ error: 'Permission denied by user',
859
+ canRetry: true,
860
+ };
861
+ }
862
+ }
863
+ else if (this.hasPersistentPermission(normalizedCall.tool)) {
864
+ // Check persistent permissions first (project-scoped), then session
865
+ this.logger.info(`${call.tool}: Auto-approved (persistent)`);
866
+ }
867
+ else if (this.sessionApprovedTools.has(normalizedCall.tool)) {
868
+ // Already approved - skip permission prompt
869
+ this.logger.info(`${call.tool}: Auto-approved (batch)`);
870
+ }
871
+ else {
872
+ const approved = await this.permissionCallback(this.formatPermissionRequest(normalizedCall, tool), { batchApproval: true });
873
+ if (approved === false) {
874
+ return {
875
+ success: false,
876
+ error: 'Permission denied by user',
877
+ canRetry: true,
878
+ };
879
+ }
880
+ // 'batch' (typed 'a') = approve for this session
881
+ // 'persist' (typed 'p') = approve permanently for this project
882
+ // 'y' or 'yes' = approve this single request only
883
+ if (approved === 'batch') {
884
+ this.sessionApprovedTools.add(normalizedCall.tool);
885
+ }
886
+ else if (approved === 'persist') {
887
+ this.sessionApprovedTools.add(normalizedCall.tool);
888
+ this.savePersistentPermission(normalizedCall.tool);
889
+ this.logger.info(`${normalizedCall.tool}: Saved as persistent permission`);
890
+ }
891
+ }
892
+ }
893
+ // Execute with retry logic for applicable operations
894
+ return this.executeWithRetry(normalizedCall, tool);
895
+ }
896
+ normalizeToolCall(call) {
897
+ const tool = String(call.tool || '').trim();
898
+ const originalArgs = call.args || {};
899
+ const args = { ...originalArgs };
900
+ const aliasMap = TOOL_ARG_ALIASES[tool] || {};
901
+ for (const [canonicalName, aliases] of Object.entries(aliasMap)) {
902
+ if (args[canonicalName]) {
903
+ continue;
904
+ }
905
+ for (const alias of aliases) {
906
+ const aliasValue = args[alias];
907
+ if (typeof aliasValue === 'string' && aliasValue.trim()) {
908
+ args[canonicalName] = aliasValue;
909
+ break;
910
+ }
911
+ }
912
+ }
913
+ if (tool === 'list_dir' && !args.path) {
914
+ args.path = '.';
915
+ }
916
+ if (tool === 'glob') {
917
+ if (!args.pattern && args.path) {
918
+ args.pattern = args.path;
919
+ }
920
+ if (args.pattern) {
921
+ const normalizedPattern = args.pattern.trim().replace(/\\/g, '/');
922
+ if (normalizedPattern && !/[\[*?{}]/.test(normalizedPattern)) {
923
+ if (normalizedPattern.includes('/')) {
924
+ args.pattern = normalizedPattern;
925
+ }
926
+ else {
927
+ args.pattern = `**/${normalizedPattern}`;
928
+ }
929
+ }
930
+ else {
931
+ args.pattern = normalizedPattern;
932
+ }
933
+ }
934
+ }
935
+ return { tool, args };
936
+ }
937
+ /**
938
+ * Execute tool with automatic retry for transient failures
939
+ */
940
+ async executeWithRetry(call, tool) {
941
+ let lastError = null;
942
+ for (let attempt = 0; attempt <= this.retryConfig.maxRetries; attempt++) {
943
+ try {
944
+ const result = await this.executeTool(call);
945
+ if (result.success) {
946
+ return result;
947
+ }
948
+ // Check if error is retryable
949
+ const isRetryable = result.canRetry !== false &&
950
+ this.isRetryableError(result.error || '');
951
+ if (!isRetryable || attempt === this.retryConfig.maxRetries) {
952
+ return result;
953
+ }
954
+ lastError = result;
955
+ // Calculate delay with exponential backoff
956
+ const delay = Math.min(this.retryConfig.baseDelayMs * Math.pow(2, attempt), this.retryConfig.maxDelayMs);
957
+ this.logger.warn(`Retrying ${call.tool} in ${delay}ms (attempt ${attempt + 2}/${this.retryConfig.maxRetries + 1})...`);
958
+ await this.sleep(delay);
959
+ }
960
+ catch (error) {
961
+ lastError = this.createErrorResult(ToolErrorType.EXECUTION_FAILED, error.message);
962
+ if (attempt === this.retryConfig.maxRetries) {
963
+ return lastError;
964
+ }
965
+ }
966
+ }
967
+ return lastError || this.createErrorResult(ToolErrorType.EXECUTION_FAILED, 'Unknown error after retries');
968
+ }
969
+ /**
970
+ * Tool names that mutate the user's filesystem, shell state, or remote
971
+ * services. Used by the dry-run / read-only gate below.
972
+ */
973
+ static MUTATING_TOOLS = new Set([
974
+ 'write_file', 'edit_file', 'multi_edit',
975
+ 'bash', 'ssh_exec',
976
+ 'git', 'repo',
977
+ ]);
978
+ /**
979
+ * `VIGTHORIA_DRY_RUN=1` and `VIGTHORIA_READ_ONLY=1` are end-user safety
980
+ * switches: every mutating tool short-circuits with a clear "would have
981
+ * happened" result instead of touching the filesystem or network.
982
+ *
983
+ * The flags are checked at call-time (not at construction time) so they
984
+ * can be flipped per-prompt by users who want to inspect agent intent
985
+ * before committing.
986
+ */
987
+ isDryRunActive() {
988
+ const flag = (name) => String(process.env[name] || '').trim().toLowerCase();
989
+ const isOn = (v) => v === '1' || v === 'true' || v === 'yes' || v === 'on';
990
+ return isOn(flag('VIGTHORIA_DRY_RUN')) || isOn(flag('VIGTHORIA_READ_ONLY'));
991
+ }
992
+ /**
993
+ * Execute the actual tool operation
994
+ */
995
+ async executeTool(call) {
996
+ try {
997
+ if (this.isDryRunActive() && AgenticTools.MUTATING_TOOLS.has(call.tool)) {
998
+ const argSummary = this.safeStringifyArgs(call.args);
999
+ const message = `Dry-run: ${call.tool} would have run with ${argSummary}. Unset VIGTHORIA_DRY_RUN to execute.`;
1000
+ this.logger.warn(message);
1001
+ return {
1002
+ success: true,
1003
+ output: '',
1004
+ dryRun: true,
1005
+ message,
1006
+ };
1007
+ }
1008
+ switch (call.tool) {
1009
+ case 'read_file':
1010
+ return this.readFile(call.args);
1011
+ case 'write_file':
1012
+ return this.writeFile(call.args);
1013
+ case 'edit_file':
1014
+ return this.editFile(call.args);
1015
+ case 'bash':
1016
+ return this.bash(call.args);
1017
+ case 'grep':
1018
+ return this.grep(call.args);
1019
+ case 'list_dir':
1020
+ return this.listDir(call.args);
1021
+ case 'glob':
1022
+ return this.glob(call.args);
1023
+ case 'git':
1024
+ return this.git(call.args);
1025
+ case 'repo':
1026
+ return this.repo(call.args);
1027
+ case 'fetch_url':
1028
+ return this.fetchUrl(call.args);
1029
+ case 'browser':
1030
+ return this.browserTool(call.args);
1031
+ case 'ssh_exec':
1032
+ return this.sshExec(call.args);
1033
+ case 'task':
1034
+ return this.task(call.args);
1035
+ case 'multi_edit':
1036
+ return this.multiEdit(call.args);
1037
+ case 'codebase_search':
1038
+ return this.codebaseSearch(call.args);
1039
+ default:
1040
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Tool not implemented: ${call.tool}`);
1041
+ }
1042
+ }
1043
+ catch (error) {
1044
+ const context = `Tool '${call.tool}' failed while executing with args ${this.safeStringifyArgs(call.args)}`;
1045
+ const stderr = error?.stderr?.toString?.().trim();
1046
+ const stdout = error?.stdout?.toString?.().trim();
1047
+ const status = error?.status !== undefined ? `exit status ${error.status}` : undefined;
1048
+ const signal = error?.signal ? `signal ${error.signal}` : undefined;
1049
+ const details = [context, status, signal, stderr || error?.message || String(error)].filter(Boolean).join(': ');
1050
+ this.logger.error(details);
1051
+ return {
1052
+ success: false,
1053
+ output: stdout,
1054
+ error: details,
1055
+ suggestion: 'Review the tool arguments and subprocess output above, then retry with corrected input.',
1056
+ canRetry: this.isRetryableError(details),
1057
+ };
1058
+ }
1059
+ }
1060
+ /**
1061
+ * Check if an error is retryable
1062
+ */
1063
+ isRetryableError(error) {
1064
+ return this.retryConfig.retryableErrors.some(e => error.includes(e));
1065
+ }
1066
+ /**
1067
+ * Safely stringify tool arguments without dumping very large payloads into logs.
1068
+ */
1069
+ safeStringifyArgs(args) {
1070
+ try {
1071
+ const json = JSON.stringify(args ?? {}, (_key, value) => {
1072
+ if (typeof value === 'string' && value.length > 500) {
1073
+ return `${value.slice(0, 500)}...<truncated ${value.length - 500} chars>`;
1074
+ }
1075
+ return value;
1076
+ });
1077
+ return json || '{}';
1078
+ }
1079
+ catch (error) {
1080
+ return `[unserializable args: ${error instanceof Error ? error.message : String(error)}]`;
1081
+ }
1082
+ }
1083
+ /**
1084
+ * Validate tool parameters
1085
+ */
1086
+ validateParameters(call, tool) {
1087
+ if (!call || typeof call !== 'object') {
1088
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, 'Invalid tool call: expected an object with tool and args fields', 'Pass a ToolCall object shaped like { tool: "read_file", args: { path: "file.ts" } }.');
1089
+ }
1090
+ if (!call.args || typeof call.args !== 'object' || Array.isArray(call.args)) {
1091
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid arguments for ${tool.name}: args must be a key/value object`, `Pass ${tool.name} arguments as an object. Received: ${this.safeStringifyArgs(call.args)}`);
1092
+ }
1093
+ for (const [key, value] of Object.entries(call.args)) {
1094
+ if (!key || typeof key !== 'string') {
1095
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid argument key for ${tool.name}: keys must be non-empty strings`, 'Use documented parameter names for this tool.');
1096
+ }
1097
+ if (typeof value !== 'string') {
1098
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid argument '${key}' for ${tool.name}: expected string value, received ${Array.isArray(value) ? 'array' : typeof value}`, `Convert '${key}' to a string before invoking ${tool.name}.`);
1099
+ }
1100
+ }
1101
+ for (const param of tool.parameters) {
1102
+ const value = call.args[param.name];
1103
+ if (param.required && (value === undefined || value.trim() === '')) {
1104
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Missing required parameter '${param.name}' for tool '${call.tool}'`, `The ${call.tool} tool requires the '${param.name}' parameter. ${param.description}`);
1105
+ }
1106
+ }
1107
+ const pathLikeParams = ['path', 'working_dir', 'cwd'];
1108
+ for (const paramName of pathLikeParams) {
1109
+ const value = call.args[paramName];
1110
+ if (typeof value === 'string' && value.includes('\0')) {
1111
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid ${paramName} for ${tool.name}: paths cannot contain null bytes`, 'Remove null bytes from the path and retry.');
1112
+ }
1113
+ }
1114
+ if (call.args.start_line !== undefined && (!/^\d+$/.test(call.args.start_line) || Number(call.args.start_line) < 1)) {
1115
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid start_line for ${tool.name}: expected a positive integer, received '${call.args.start_line}'`, 'Use a 1-based positive integer for start_line.');
1116
+ }
1117
+ if (call.args.end_line !== undefined && (!/^\d+$/.test(call.args.end_line) || Number(call.args.end_line) < 0)) {
1118
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid end_line for ${tool.name}: expected a non-negative integer, received '${call.args.end_line}'`, 'Use 0 for end-of-file or a positive 1-based line number for end_line.');
1119
+ }
1120
+ if (call.args.start_line !== undefined && call.args.end_line !== undefined) {
1121
+ const startLine = Number(call.args.start_line);
1122
+ const endLine = Number(call.args.end_line);
1123
+ if (endLine !== 0 && endLine < startLine) {
1124
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid line range for ${tool.name}: end_line (${endLine}) is before start_line (${startLine})`, 'Use an end_line greater than or equal to start_line, or 0 to read through EOF.');
1125
+ }
1126
+ }
1127
+ if (call.args.timeout !== undefined && (!/^\d+$/.test(call.args.timeout) || Number(call.args.timeout) < 1)) {
1128
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid timeout for ${tool.name}: expected a positive integer number of seconds, received '${call.args.timeout}'`, 'Use a positive integer timeout in seconds.');
1129
+ }
1130
+ if (call.args.max_results !== undefined && (!/^\d+$/.test(call.args.max_results) || Number(call.args.max_results) < 1)) {
1131
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid max_results for ${tool.name}: expected a positive integer, received '${call.args.max_results}'`, 'Use a positive integer for max_results.');
1132
+ }
1133
+ if (call.tool === 'list_dir' && call.args.recursive !== undefined && !['true', 'false', '1', '0', 'yes', 'no'].includes(call.args.recursive.toLowerCase())) {
1134
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid recursive value for list_dir: expected true or false, received '${call.args.recursive}'`, 'Use recursive="true" or recursive="false".');
1135
+ }
1136
+ if (call.tool === 'fetch_url' && call.args.url !== undefined) {
1137
+ try {
1138
+ const parsed = new URL(call.args.url);
1139
+ if (!['http:', 'https:'].includes(parsed.protocol)) {
1140
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid URL protocol for fetch_url: '${parsed.protocol}'`, 'Use an http:// or https:// URL.');
1141
+ }
1142
+ }
1143
+ catch (error) {
1144
+ const message = this.getErrorMessage(error);
1145
+ this.logger.debug(`Invalid URL for fetch_url '${call.args.url}': ${message}`);
1146
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid URL for fetch_url: '${call.args.url}'`, 'Provide a fully-qualified http:// or https:// URL.');
1147
+ }
1148
+ }
1149
+ if (call.tool === 'multi_edit' && call.args.edits !== undefined) {
1150
+ try {
1151
+ const edits = JSON.parse(call.args.edits);
1152
+ if (!Array.isArray(edits) || edits.length === 0) {
1153
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, 'Invalid edits for multi_edit: expected a non-empty JSON array', 'Provide edits as a JSON array of { path, old_text, new_text } objects.');
1154
+ }
1155
+ for (const [index, edit] of edits.entries()) {
1156
+ if (!edit || typeof edit !== 'object' || Array.isArray(edit)) {
1157
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid edit at index ${index}: expected an object`);
1158
+ }
1159
+ for (const field of ['path', 'old_text', 'new_text']) {
1160
+ if (typeof edit[field] !== 'string') {
1161
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid edit at index ${index}: '${field}' must be a string`);
1162
+ }
1163
+ }
1164
+ }
1165
+ }
1166
+ catch (error) {
1167
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid edits JSON for multi_edit: ${error instanceof Error ? error.message : String(error)}`, 'Pass a valid JSON array string for the edits parameter.');
1168
+ }
1169
+ }
1170
+ return null;
1171
+ }
1172
+ /**
1173
+ * Create a standardized error result
1174
+ */
1175
+ createErrorResult(type, message, suggestion) {
1176
+ const suggestions = {
1177
+ [ToolErrorType.FILE_NOT_FOUND]: 'Check if the file path is correct. Use list_dir to see available files.',
1178
+ [ToolErrorType.PERMISSION_DENIED]: 'You may need elevated permissions. Try using sudo or check file ownership.',
1179
+ [ToolErrorType.NETWORK_ERROR]: 'Check your internet connection. The operation will retry automatically.',
1180
+ [ToolErrorType.TIMEOUT]: 'The operation took too long. Try with a shorter timeout or simpler command.',
1181
+ [ToolErrorType.INVALID_ARGS]: 'Check the tool documentation for correct parameter usage.',
1182
+ [ToolErrorType.EXECUTION_FAILED]: 'Review the command syntax and try again.',
1183
+ [ToolErrorType.USER_CANCELLED]: 'Operation cancelled. You can retry if needed.',
1184
+ };
1185
+ return {
1186
+ success: false,
1187
+ error: message,
1188
+ suggestion: suggestion || suggestions[type],
1189
+ canRetry: type !== ToolErrorType.USER_CANCELLED && type !== ToolErrorType.INVALID_ARGS,
1190
+ };
1191
+ }
1192
+ /**
1193
+ * Enhanced permission request with risk visualization
1194
+ */
1195
+ formatPermissionRequest(call, tool) {
1196
+ const riskColors = {
1197
+ low: chalk.green,
1198
+ medium: chalk.yellow,
1199
+ high: chalk.red,
1200
+ critical: chalk.bgRed.white,
1201
+ };
1202
+ const riskIcons = {
1203
+ low: '🟢',
1204
+ medium: '🟡',
1205
+ high: '🔴',
1206
+ critical: '⛔',
1207
+ };
1208
+ const riskColor = riskColors[tool.riskLevel];
1209
+ const riskIcon = riskIcons[tool.riskLevel];
1210
+ let msg = `\n${riskIcon} ${riskColor(`${tool.riskLevel.toUpperCase()} RISK`)} - AI wants to use ${chalk.cyan.bold(call.tool)}\n`;
1211
+ msg += chalk.gray(CH.hLine.repeat(50)) + '\n';
1212
+ // Tool-specific details
1213
+ if (call.tool === 'bash') {
1214
+ msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('Command:')} ${chalk.yellow(call.args.command)}\n`;
1215
+ if (call.args.cwd) {
1216
+ msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('Directory:')} ${call.args.cwd}\n`;
1217
+ }
1218
+ msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('Timeout:')} ${call.args.timeout || '30'}s\n`;
1219
+ }
1220
+ else if (call.tool === 'write_file') {
1221
+ msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('File:')} ${chalk.cyan(call.args.path)}\n`;
1222
+ const preview = call.args.content.substring(0, 100);
1223
+ msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('Content preview:')} ${chalk.gray(preview)}${call.args.content.length > 100 ? '...' : ''}\n`;
1224
+ msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('Size:')} ${call.args.content.length} bytes\n`;
1225
+ }
1226
+ else if (call.tool === 'edit_file') {
1227
+ msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('File:')} ${chalk.cyan(call.args.path)}\n`;
1228
+ msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('Replace:')} ${chalk.red(call.args.old_text.substring(0, 50))}${call.args.old_text.length > 50 ? '...' : ''}\n`;
1229
+ msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('With:')} ${chalk.green(call.args.new_text.substring(0, 50))}${call.args.new_text.length > 50 ? '...' : ''}\n`;
1230
+ }
1231
+ else if (call.tool === 'git') {
1232
+ msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('Command:')} git ${chalk.yellow(call.args.args)}\n`;
1233
+ }
1234
+ // Safety info
1235
+ msg += chalk.gray(CH.hLine.repeat(50)) + '\n';
1236
+ const canUndo = ['write_file', 'edit_file'].includes(call.tool);
1237
+ msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('Undo:')} ${canUndo ? chalk.green(CH.success + ' Available (use /undo)') : chalk.gray(CH.error + ' Not available')}\n`;
1238
+ msg += `${chalk.gray(CH.bl + CH.hLine)} ${chalk.white('Category:')} ${tool.category}\n`;
1239
+ if (tool.dangerous) {
1240
+ msg += `\n${chalk.red.bold(CH.warnEmoji + ' WARNING: This is a potentially dangerous action!')}\n`;
1241
+ msg += chalk.red(' The AI is requesting to execute commands on your system.\n');
1242
+ }
1243
+ // Add batch approval hint
1244
+ msg += `\n${chalk.gray('Respond:')} ${chalk.white('[y]es')} ${chalk.gray('/')} ${chalk.white('[n]o')} ${chalk.gray('/')} ${chalk.cyan('[a]pprove all')} ${chalk.cyan(call.tool)} ${chalk.gray('for this turn')}\n`;
1245
+ return msg;
1246
+ }
1247
+ sleep(ms) {
1248
+ return new Promise(resolve => setTimeout(resolve, ms));
1249
+ }
1250
+ // Tool implementations with enhanced error handling and undo support
1251
+ bridgeToolsEnabled() {
1252
+ const flag = String(process.env.VIGTHORIA_BRIDGE_TOOLS || '').trim().toLowerCase();
1253
+ return flag === '1' || flag === 'true' || flag === 'yes' || flag === 'on';
1254
+ }
1255
+ tryBridgeReadFile(args) {
1256
+ if (!this.bridgeToolsEnabled()) {
1257
+ return null;
1258
+ }
1259
+ const bridgeBase = String(process.env.VIGTHORIA_BRIDGE_HTTP
1260
+ || process.env.VIGTHORIA_DESKTOP_BRIDGE_URL
1261
+ || 'http://127.0.0.1:49160').replace(/\/$/, '');
1262
+ const targetPath = args.path || '';
1263
+ if (!targetPath) {
1264
+ return null;
1265
+ }
1266
+ try {
1267
+ const response = execSync(`curl -sS -m 15 -X POST "${bridgeBase}/tools/read_file" -H "Content-Type: application/json" -d ${JSON.stringify(JSON.stringify({
1268
+ path: targetPath,
1269
+ start_line: args.start_line ? Number(args.start_line) : undefined,
1270
+ end_line: args.end_line ? Number(args.end_line) : undefined,
1271
+ }))}`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
1272
+ const payload = JSON.parse(response);
1273
+ if (payload?.success === true) {
1274
+ return {
1275
+ success: true,
1276
+ output: String(payload.output || payload.content || ''),
1277
+ metadata: { source: 'desktop-bridge', path: targetPath },
1278
+ };
1279
+ }
1280
+ if (payload?.error) {
1281
+ this.logger.debug(`Desktop bridge read failed for ${targetPath}: ${payload.error}`);
1282
+ }
1283
+ }
1284
+ catch (error) {
1285
+ this.logger.debug(`Desktop bridge read unavailable for ${targetPath}: ${this.formatExternalToolError('read_file', 'bridge delegation', error)}`);
1286
+ }
1287
+ return null;
1288
+ }
1289
+ /**
1290
+ * Read file with enhanced error handling and suggestions
1291
+ */
1292
+ readFile(args) {
1293
+ const bridgeRead = this.tryBridgeReadFile(args);
1294
+ if (bridgeRead) {
1295
+ return bridgeRead;
1296
+ }
1297
+ const filePath = this.resolvePath(args.path);
1298
+ if (!fs.existsSync(filePath)) {
1299
+ // Try to find similar files
1300
+ const dir = path.dirname(filePath);
1301
+ const basename = path.basename(filePath);
1302
+ let suggestions = [];
1303
+ if (fs.existsSync(dir)) {
1304
+ const files = fs.readdirSync(dir);
1305
+ suggestions = files
1306
+ .filter(f => f.toLowerCase().includes(basename.toLowerCase().slice(0, 3)))
1307
+ .slice(0, 3);
1308
+ }
1309
+ return this.createErrorResult(ToolErrorType.FILE_NOT_FOUND, `File not found: ${args.path}`, suggestions.length > 0
1310
+ ? `Did you mean one of these? ${suggestions.join(', ')}`
1311
+ : 'Use list_dir to see available files in the directory.');
1312
+ }
1313
+ try {
1314
+ const stats = fs.statSync(filePath);
1315
+ if (stats.size > 1024 * 1024) { // 1MB warning
1316
+ this.logger.warn(`Large file (${(stats.size / 1024 / 1024).toFixed(2)}MB) - consider using start_line/end_line`);
1317
+ }
1318
+ const content = fs.readFileSync(filePath, 'utf-8');
1319
+ const lines = content.split('\n');
1320
+ // Clamp start_line: API is 1-based; the model sometimes emits 0 or
1321
+ // negative values. Silently clamp to valid range instead of failing.
1322
+ let rawStart = args.start_line ? parseInt(args.start_line) : 1;
1323
+ if (rawStart < 1)
1324
+ rawStart = 1;
1325
+ if (rawStart > lines.length)
1326
+ rawStart = lines.length;
1327
+ const startLine = rawStart - 1; // convert to 0-based
1328
+ let rawEnd = args.end_line ? parseInt(args.end_line) : lines.length;
1329
+ if (rawEnd < rawStart)
1330
+ rawEnd = rawStart;
1331
+ if (rawEnd > lines.length)
1332
+ rawEnd = lines.length;
1333
+ const endLine = rawEnd;
1334
+ const selectedLines = lines.slice(startLine, Math.min(endLine, lines.length));
1335
+ return {
1336
+ success: true,
1337
+ output: selectedLines.join('\n'),
1338
+ metadata: {
1339
+ totalLines: lines.length,
1340
+ linesReturned: selectedLines.length,
1341
+ filePath: args.path,
1342
+ },
1343
+ };
1344
+ }
1345
+ catch (error) {
1346
+ if (error.code === 'EACCES') {
1347
+ return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, `Permission denied: ${args.path}`);
1348
+ }
1349
+ return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, error.message);
1350
+ }
1351
+ }
1352
+ /**
1353
+ * Write file with undo support
1354
+ */
1355
+ writeFile(args) {
1356
+ const filePath = this.resolvePath(args.path);
1357
+ const dir = path.dirname(filePath);
1358
+ // Save original content for undo if file exists
1359
+ let originalContent = null;
1360
+ if (fs.existsSync(filePath)) {
1361
+ originalContent = fs.readFileSync(filePath, 'utf-8');
1362
+ }
1363
+ try {
1364
+ // Create directory if needed
1365
+ if (!fs.existsSync(dir)) {
1366
+ fs.mkdirSync(dir, { recursive: true });
1367
+ }
1368
+ fs.writeFileSync(filePath, args.content, 'utf-8');
1369
+ const validationErrors = this.validateWrittenFile(filePath, args.content);
1370
+ if (validationErrors.length > 0) {
1371
+ if (originalContent === null) {
1372
+ fs.unlinkSync(filePath);
1373
+ }
1374
+ else {
1375
+ fs.writeFileSync(filePath, originalContent, 'utf-8');
1376
+ }
1377
+ return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, `Validation failed after writing ${args.path}`, validationErrors.join(' '));
1378
+ }
1379
+ // Store undo operation
1380
+ const undoOp = {
1381
+ id: `undo-${Date.now()}`,
1382
+ tool: 'write_file',
1383
+ timestamp: Date.now(),
1384
+ filePath: filePath,
1385
+ originalContent: originalContent,
1386
+ description: originalContent
1387
+ ? `Restore ${args.path} to previous version`
1388
+ : `Delete ${args.path} (was created)`,
1389
+ };
1390
+ this.undoStack.push(undoOp);
1391
+ // Limit undo stack size
1392
+ if (this.undoStack.length > 50) {
1393
+ this.undoStack.shift();
1394
+ }
1395
+ const isNew = originalContent === null;
1396
+ return {
1397
+ success: true,
1398
+ output: `File ${isNew ? 'created' : 'updated'}: ${args.path}`,
1399
+ metadata: {
1400
+ bytes: args.content.length,
1401
+ isNew,
1402
+ canUndo: true,
1403
+ },
1404
+ };
1405
+ }
1406
+ catch (error) {
1407
+ if (error.code === 'EACCES') {
1408
+ return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, `Permission denied writing to: ${args.path}`);
1409
+ }
1410
+ if (error.code === 'ENOSPC') {
1411
+ return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, 'No space left on device');
1412
+ }
1413
+ return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, error.message);
1414
+ }
1415
+ }
1416
+ /**
1417
+ * Edit file with undo support and helpful error messages
1418
+ */
1419
+ editFile(args) {
1420
+ const filePath = this.resolvePath(args.path);
1421
+ if (!fs.existsSync(filePath)) {
1422
+ return this.createErrorResult(ToolErrorType.FILE_NOT_FOUND, `File not found: ${args.path}`, 'Use write_file to create a new file, or check the path.');
1423
+ }
1424
+ try {
1425
+ let content = fs.readFileSync(filePath, 'utf-8');
1426
+ const originalContent = content;
1427
+ if (!content.includes(args.old_text)) {
1428
+ // Try to help identify the issue
1429
+ const lines = content.split('\n');
1430
+ const searchTerms = args.old_text.split('\n')[0].trim().slice(0, 30);
1431
+ const possibleMatches = lines
1432
+ .map((line, i) => ({ line: i + 1, content: line }))
1433
+ .filter(l => l.content.includes(searchTerms.slice(0, 10)))
1434
+ .slice(0, 3);
1435
+ let suggestion = 'The exact text was not found. ';
1436
+ if (possibleMatches.length > 0) {
1437
+ suggestion += `Similar content found at lines: ${possibleMatches.map(m => m.line).join(', ')}. `;
1438
+ }
1439
+ suggestion += 'Ensure whitespace and indentation match exactly.';
1440
+ return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, 'Old text not found in file', suggestion);
1441
+ }
1442
+ // Check for multiple matches
1443
+ const matchCount = (content.match(new RegExp(args.old_text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g')) || []).length;
1444
+ if (matchCount > 1) {
1445
+ this.logger.warn(`Found ${matchCount} matches - only replacing first occurrence`);
1446
+ }
1447
+ content = content.replace(args.old_text, args.new_text);
1448
+ fs.writeFileSync(filePath, content, 'utf-8');
1449
+ const validationErrors = this.validateWrittenFile(filePath, content);
1450
+ if (validationErrors.length > 0) {
1451
+ fs.writeFileSync(filePath, originalContent, 'utf-8');
1452
+ return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, `Validation failed after editing ${args.path}`, validationErrors.join(' '));
1453
+ }
1454
+ // Store undo operation
1455
+ const undoOp = {
1456
+ id: `undo-${Date.now()}`,
1457
+ tool: 'edit_file',
1458
+ timestamp: Date.now(),
1459
+ filePath: filePath,
1460
+ originalContent: originalContent,
1461
+ description: `Restore ${args.path} (reverts edit)`,
1462
+ };
1463
+ this.undoStack.push(undoOp);
1464
+ // Limit undo stack size
1465
+ if (this.undoStack.length > 50) {
1466
+ this.undoStack.shift();
1467
+ }
1468
+ // Show syntax-highlighted diff
1469
+ this.logger.unifiedDiff(args.path, args.old_text, args.new_text);
1470
+ return {
1471
+ success: true,
1472
+ output: `File edited: ${args.path}`,
1473
+ metadata: {
1474
+ matchesFound: matchCount,
1475
+ canUndo: true,
1476
+ },
1477
+ };
1478
+ }
1479
+ catch (error) {
1480
+ if (error.code === 'EACCES') {
1481
+ return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, `Permission denied: ${args.path}`);
1482
+ }
1483
+ return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, error.message);
1484
+ }
1485
+ }
1486
+ validateWrittenFile(filePath, content) {
1487
+ const errors = [];
1488
+ const extension = path.extname(filePath).toLowerCase();
1489
+ const placeholderPatterns = [
1490
+ /\.\.\.\s*(rest|more)/i,
1491
+ /implementation goes here/i,
1492
+ /replace (?:this|the) placeholder/i,
1493
+ /placeholder (?:text|content|copy|image)/i,
1494
+ /todo:/i,
1495
+ /all the .* from earlier/i,
1496
+ ];
1497
+ if (placeholderPatterns.some((pattern) => pattern.test(content))) {
1498
+ errors.push('The written file still contains placeholder or truncated content.');
1499
+ }
1500
+ if (extension === '.json') {
1501
+ try {
1502
+ JSON.parse(content);
1503
+ }
1504
+ catch (error) {
1505
+ errors.push(`JSON is invalid: ${error.message}`);
1506
+ }
1507
+ }
1508
+ if (extension === '.js' || extension === '.mjs' || extension === '.cjs') {
1509
+ const jsError = this.validateJavaScriptSyntax(content);
1510
+ if (jsError) {
1511
+ errors.push(jsError);
1512
+ }
1513
+ }
1514
+ if (extension === '.html' || extension === '.htm') {
1515
+ errors.push(...this.validateHtmlContent(content));
1516
+ }
1517
+ return errors;
1518
+ }
1519
+ validateJavaScriptSyntax(source) {
1520
+ const tempFile = path.join(this.cwd, `.vigthoria-temp-${Date.now()}.js`);
1521
+ try {
1522
+ try {
1523
+ fs.writeFileSync(tempFile, source, 'utf-8');
1524
+ }
1525
+ catch (writeError) {
1526
+ return this.formatExternalToolError('syntax_check', `write temporary file ${tempFile}`, writeError);
1527
+ }
1528
+ try {
1529
+ this.runExternalCommand('syntax_check', `node --check ${tempFile}`, `node --check "${tempFile}"`, { stdio: 'pipe' });
1530
+ return null;
1531
+ }
1532
+ catch (error) {
1533
+ const stderr = error.stderr?.toString()?.trim();
1534
+ return stderr || error.message || this.formatExternalToolError('syntax_check', `node --check ${tempFile}`, error);
1535
+ }
1536
+ }
1537
+ finally {
1538
+ this.cleanupAfterToolError('syntax_check', `remove temporary file ${tempFile}`, () => {
1539
+ if (fs.existsSync(tempFile)) {
1540
+ fs.unlinkSync(tempFile);
1541
+ }
1542
+ });
1543
+ }
1544
+ }
1545
+ validateHtmlContent(content) {
1546
+ const errors = [];
1547
+ const requiredClosers = ['</html>', '</body>'];
1548
+ for (const closer of requiredClosers) {
1549
+ if (!content.toLowerCase().includes(closer)) {
1550
+ errors.push(`Missing required HTML closer: ${closer}`);
1551
+ }
1552
+ }
1553
+ const inlineScripts = [...content.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi)];
1554
+ inlineScripts.forEach((match, index) => {
1555
+ const scriptContent = match[1].trim();
1556
+ if (!scriptContent) {
1557
+ return;
1558
+ }
1559
+ const scriptError = this.validateJavaScriptSyntax(scriptContent);
1560
+ if (scriptError) {
1561
+ errors.push(`Inline script ${index + 1} has invalid JavaScript: ${scriptError}`);
1562
+ }
1563
+ });
1564
+ const selfClosingTags = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
1565
+ const stack = [];
1566
+ const tagRegex = /<\/?([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>/g;
1567
+ let match;
1568
+ while ((match = tagRegex.exec(content)) !== null) {
1569
+ const fullTag = match[0];
1570
+ const tagName = match[1].toLowerCase();
1571
+ if (selfClosingTags.has(tagName) || fullTag.endsWith('/>')) {
1572
+ continue;
1573
+ }
1574
+ if (fullTag.startsWith('</')) {
1575
+ const last = stack.pop();
1576
+ if (last !== tagName) {
1577
+ errors.push(`Unbalanced HTML tags near </${tagName}>.`);
1578
+ break;
1579
+ }
1580
+ }
1581
+ else {
1582
+ stack.push(tagName);
1583
+ }
1584
+ }
1585
+ if (stack.length > 0) {
1586
+ errors.push(`Unclosed HTML tags detected: ${stack.slice(-5).join(', ')}`);
1587
+ }
1588
+ return errors;
1589
+ }
1590
+ /**
1591
+ * Execute bash command with enhanced error handling
1592
+ * SECURITY: Commands are sandboxed to workspace directory
1593
+ * WINDOWS: Detects Unix-specific commands and suggests alternatives
1594
+ */
1595
+ bash(args) {
1596
+ const cwd = args.cwd ? this.resolvePath(args.cwd) : this.cwd;
1597
+ const timeout = args.timeout ? parseInt(args.timeout) * 1000 : 30000;
1598
+ const os = require('os');
1599
+ const platform = os.platform();
1600
+ // Unix-specific commands that don't exist on Windows
1601
+ const unixOnlyCommands = [
1602
+ 'head', 'tail', 'grep', 'awk', 'sed', 'wc', 'cut', 'sort', 'uniq',
1603
+ 'xargs', 'find', 'chmod', 'chown', 'ln', 'df', 'du', 'ps', 'kill',
1604
+ 'top', 'htop', 'which', 'whereis', 'man', 'less', 'more', 'cat',
1605
+ ];
1606
+ // Check if command uses Unix-only tools on Windows
1607
+ if (platform === 'win32') {
1608
+ const cmdParts = args.command.split(/[|&;]/);
1609
+ for (const part of cmdParts) {
1610
+ const firstWord = part.trim().split(/\s+/)[0].toLowerCase();
1611
+ if (unixOnlyCommands.includes(firstWord)) {
1612
+ return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, `Command '${firstWord}' is not available on Windows`, `Use a local PowerShell equivalent instead: dir (ls), type (cat), findstr (grep), select-string (grep), or rerun with a Windows-safe command.`);
1613
+ }
1614
+ }
1615
+ }
1616
+ // SECURITY: Block dangerous commands that could access outside workspace
1617
+ // HARDENED: Protects Vigthoria ecosystem, server config, and system files
1618
+ const blockedPatterns = [
1619
+ // === System file access ===
1620
+ /\bcat\s+\/etc\//i, // Reading system files
1621
+ /\bcat\s+\/var\/(?!log)/i, // Reading /var/ except logs
1622
+ /\bcat\s+\/root\//i, // Reading root home
1623
+ /\bcat\s+\/home\/[^\/]+\/\.[^\/]/i, // Reading hidden files in home dirs
1624
+ /\bcat\s+~\/\./i, // Reading hidden files via ~
1625
+ /\bcd\s+(\/etc|\/var\/www|\/root|\/home)/i, // CD to sensitive dirs
1626
+ // === Destructive operations ===
1627
+ /\brm\s+-rf?\s+\//i, // Dangerous rm commands
1628
+ /\brm\s+-rf?\s+\.\.\//i, // rm going up directories
1629
+ /\brm\s+-rf?\s+~\//i, // rm in home directory
1630
+ /\b(curl|wget).*\|\s*(bash|sh)\b/i, // Downloading and executing scripts
1631
+ /\bsudo\b/i, // Sudo commands
1632
+ /\bsu\s+-/i, // Su to root
1633
+ /\bchmod\s+[0-7]*777/i, // World-writable permissions
1634
+ /\/(var\/www|opt)\/[a-z]+-?(database|models|coder|mcp|operator|voice|music)/i, // Vigthoria ecosystem
1635
+ /vigthoria-(models|database|mcp|operator|voice|music)/i, // Vigthoria project names
1636
+ // === Vigthoria Server Protection (CRITICAL) ===
1637
+ /\/var\/www\/(?!$)/i, // Block ANY access to /var/www/* (server web root)
1638
+ /\/etc\/(caddy|nginx|apache|systemd|pm2)/i, // Server config files
1639
+ /\/etc\/(passwd|shadow|group|sudoers)/i, // System auth files
1640
+ /\b(systemctl|service)\s+(start|stop|restart|enable|disable|reload)/i, // Service control
1641
+ /\bpm2\s+(start|stop|restart|delete|kill|flush)/i, // PM2 process management
1642
+ /\bjournalctl\b/i, // System logs access
1643
+ /\bnpm\s+publish\b/i, // Block npm publish from agent
1644
+ /\bdocker\s+(rm|kill|stop|exec|run)/i, // Docker container manipulation
1645
+ /\biptables\b/i, // Firewall rules
1646
+ /\bufw\s+(allow|deny|delete|disable)/i, // UFW firewall
1647
+ /\bssh\s+.*vigthoria/i, // SSH to Vigthoria servers
1648
+ /\bssh\s+.*78\.46\.154/i, // SSH to known Vigthoria IP
1649
+ /\.env\b/i, // Environment files (may contain secrets)
1650
+ /\bprivate[_-]?key|secret[_-]?key|api[_-]?key|auth[_-]?token/i, // Sensitive variable patterns in commands
1651
+ /\bcrontab\b/i, // Cron manipulation
1652
+ /\bmount\s/i, // Mount filesystems
1653
+ /\bmkfs\b/i, // Format filesystems
1654
+ />\s*\/dev\/sd/i, // Writing to disk devices
1655
+ /\bdd\s+.*of=/i, // dd write operations
1656
+ /\bnode\s+-e\b/i, // Node eval (sandbox bypass)
1657
+ /\bnode\s+--eval\b/i, // Node eval long form
1658
+ /\bpython3?\s+-c\b/i, // Python exec (sandbox bypass)
1659
+ /\bruby\s+-e\b/i, // Ruby eval (sandbox bypass)
1660
+ /\bperl\s+-e\b/i, // Perl eval (sandbox bypass)
1661
+ ];
1662
+ for (const pattern of blockedPatterns) {
1663
+ if (pattern.test(args.command)) {
1664
+ this.logger.warn(`Security: Blocked potentially dangerous command: ${args.command.substring(0, 50)}...`);
1665
+ return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, 'This command is blocked for security reasons', 'Commands must operate within your current project workspace.');
1666
+ }
1667
+ }
1668
+ // Validate working directory
1669
+ if (!fs.existsSync(cwd)) {
1670
+ return this.createErrorResult(ToolErrorType.FILE_NOT_FOUND, `Working directory not found: ${cwd}`, 'Check that the directory exists or use an absolute path.');
1671
+ }
1672
+ try {
1673
+ const startTime = Date.now();
1674
+ // Build exec options based on platform
1675
+ const execOptions = {
1676
+ cwd,
1677
+ timeout,
1678
+ encoding: 'utf-8',
1679
+ maxBuffer: 10 * 1024 * 1024, // 10MB
1680
+ stdio: ['pipe', 'pipe', 'pipe'],
1681
+ // Ensure consistent environment
1682
+ env: {
1683
+ ...process.env,
1684
+ // Prevent locale issues
1685
+ LC_ALL: 'C',
1686
+ LANG: 'C',
1687
+ },
1688
+ };
1689
+ // Set shell based on platform for consistent behavior
1690
+ if (platform === 'win32') {
1691
+ execOptions.shell = true; // Use default cmd.exe on Windows
1692
+ }
1693
+ else {
1694
+ // Use /bin/sh on Unix-like systems (more portable than bash)
1695
+ execOptions.shell = '/bin/sh';
1696
+ }
1697
+ const output = this.runExternalCommand('bash', args.command, args.command, execOptions);
1698
+ const duration = Date.now() - startTime;
1699
+ return {
1700
+ success: true,
1701
+ output: output.trim(),
1702
+ metadata: {
1703
+ durationMs: duration,
1704
+ cwd,
1705
+ },
1706
+ };
1707
+ }
1708
+ catch (error) {
1709
+ // Command failed but may have output
1710
+ const output = error.stdout || '';
1711
+ const stderr = error.stderr || '';
1712
+ // Provide helpful error messages for common cases
1713
+ if (error.killed) {
1714
+ return this.createErrorResult(ToolErrorType.TIMEOUT, `Command timed out after ${timeout / 1000}s`, 'Try increasing the timeout or breaking the command into smaller parts.');
1715
+ }
1716
+ if (stderr.includes('command not found') || stderr.includes('not recognized')) {
1717
+ const cmd = args.command.split(' ')[0];
1718
+ return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, `Command not found: ${cmd}`, 'Check that the command is installed and in PATH.');
1719
+ }
1720
+ if (stderr.includes('Permission denied')) {
1721
+ return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, 'Permission denied executing command', 'Try using sudo or check file/directory permissions.');
1722
+ }
1723
+ return {
1724
+ success: false,
1725
+ output,
1726
+ error: stderr || error.message,
1727
+ suggestion: 'Check command syntax and try again.',
1728
+ canRetry: !error.killed,
1729
+ };
1730
+ }
1731
+ }
1732
+ grep(args) {
1733
+ const searchPath = args.path ? this.resolvePath(args.path) : this.cwd;
1734
+ const osModule = require('os');
1735
+ const platform = osModule.platform();
1736
+ // If forced fallback, go directly to Node-native
1737
+ if (args._fallback === 'node-native') {
1738
+ return this.grepNodeNative(args, searchPath);
1739
+ }
1740
+ // Try external search tools first (rg > grep/Select-String), fall back to Node-native
1741
+ if (platform === 'win32') {
1742
+ return this.grepWindows(args, searchPath);
1743
+ }
1744
+ return this.grepUnix(args, searchPath, platform);
1745
+ }
1746
+ /**
1747
+ * Windows grep: rg > Select-String > Node-native
1748
+ */
1749
+ grepWindows(args, searchPath) {
1750
+ // 1. Try ripgrep (rg) first — best cross-platform search tool
1751
+ try {
1752
+ execSync('rg --version', { encoding: 'utf-8', timeout: 5000, stdio: 'pipe' });
1753
+ return this.grepWithRg(args, searchPath);
1754
+ }
1755
+ catch (error) {
1756
+ this.logger.debug(this.formatExternalToolError('grep', 'checking ripgrep availability on Windows', error));
1757
+ }
1758
+ // 2. Try PowerShell Select-String
1759
+ try {
1760
+ return this.grepWithSelectString(args, searchPath);
1761
+ }
1762
+ catch (error) {
1763
+ this.logger.debug(this.formatExternalToolError('grep', 'running PowerShell Select-String fallback', error));
1764
+ }
1765
+ // 3. Fall back to Node-native recursive file scanner
1766
+ return this.grepNodeNative(args, searchPath);
1767
+ }
1768
+ /**
1769
+ * Unix grep: rg > system grep (BSD/GNU)
1770
+ */
1771
+ grepUnix(args, searchPath, platform) {
1772
+ // Try ripgrep first if available
1773
+ try {
1774
+ this.runExternalCommand('grep', 'checking ripgrep availability on Unix', 'rg --version', { encoding: 'utf-8', timeout: 5000, stdio: 'pipe' });
1775
+ return this.grepWithRg(args, searchPath);
1776
+ }
1777
+ catch (error) {
1778
+ this.logger.debug(this.formatExternalToolError('grep', 'checking ripgrep availability on Unix', error));
1779
+ // rg not available, fall through to system grep
1780
+ }
1781
+ const isMac = platform === 'darwin';
1782
+ let cmd;
1783
+ if (isMac) {
1784
+ cmd = args.include
1785
+ ? `grep -rn --include="${args.include}" "${args.pattern}" "${searchPath}"`
1786
+ : `grep -rn "${args.pattern}" "${searchPath}"`;
1787
+ }
1788
+ else {
1789
+ cmd = args.include
1790
+ ? `grep -rn --color=never --include="${args.include}" "${args.pattern}" "${searchPath}"`
1791
+ : `grep -rn --color=never "${args.pattern}" "${searchPath}"`;
1792
+ }
1793
+ try {
1794
+ const output = this.runExternalCommand('grep', 'system grep search', cmd, {
1795
+ cwd: this.cwd,
1796
+ encoding: 'utf-8',
1797
+ maxBuffer: 5 * 1024 * 1024,
1798
+ timeout: 30000,
1799
+ env: { ...process.env, GREP_OPTIONS: '' },
1800
+ });
1801
+ return {
1802
+ success: true,
1803
+ output: output.trim(),
1804
+ metadata: { searchStatus: 'search_matches_found' },
1805
+ };
1806
+ }
1807
+ catch (error) {
1808
+ // Distinguish real "no matches" (exit 1 + no stderr) from command failure
1809
+ const stderr = (error.stderr || '').toString();
1810
+ if (error.status === 1 && !stderr.trim()) {
1811
+ return {
1812
+ success: true,
1813
+ output: 'No matches found',
1814
+ metadata: { searchStatus: 'search_no_matches' },
1815
+ };
1816
+ }
1817
+ // Real failure: command not found, permission denied, etc.
1818
+ return {
1819
+ success: false,
1820
+ error: stderr || error.message,
1821
+ suggestion: 'The grep command failed. Install ripgrep (rg) for best cross-platform search.',
1822
+ canRetry: true,
1823
+ metadata: { searchStatus: 'search_failed' },
1824
+ };
1825
+ }
1826
+ }
1827
+ /**
1828
+ * Search using ripgrep (rg) — works on all platforms
1829
+ */
1830
+ grepWithRg(args, searchPath) {
1831
+ let cmd = `rg -n --no-heading`;
1832
+ if (args.include) {
1833
+ cmd += ` -g "${args.include}"`;
1834
+ }
1835
+ cmd += ` "${args.pattern}" "${searchPath}"`;
1836
+ try {
1837
+ const output = this.runExternalCommand('grep', 'ripgrep search', cmd, {
1838
+ cwd: this.cwd,
1839
+ encoding: 'utf-8',
1840
+ maxBuffer: 5 * 1024 * 1024,
1841
+ timeout: 30000,
1842
+ });
1843
+ return {
1844
+ success: true,
1845
+ output: output.trim(),
1846
+ metadata: { searchStatus: 'search_matches_found', backend: 'ripgrep' },
1847
+ };
1848
+ }
1849
+ catch (error) {
1850
+ if (error.status === 1 && !(error.stderr || '').toString().trim()) {
1851
+ return {
1852
+ success: true,
1853
+ output: 'No matches found',
1854
+ metadata: { searchStatus: 'search_no_matches', backend: 'ripgrep' },
1855
+ };
1856
+ }
1857
+ throw error; // Let caller try next backend
1858
+ }
1859
+ }
1860
+ /**
1861
+ * Search using PowerShell Select-String (Windows)
1862
+ */
1863
+ grepWithSelectString(args, searchPath) {
1864
+ // Normalize path for PowerShell
1865
+ const psPath = searchPath.replace(/\//g, '\\');
1866
+ if (!POWERSHELL_SAFE_PATH_PATTERN.test(psPath)) {
1867
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, 'Unsafe search path for PowerShell backend', 'Use a normal workspace path containing only letters, numbers, separators, dot, dash, and spaces.');
1868
+ }
1869
+ const includeArg = args.include ? String(args.include) : '*';
1870
+ if (!POWERSHELL_SAFE_INCLUDE_PATTERN.test(includeArg)) {
1871
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, 'Unsafe include filter for PowerShell backend', 'Use simple wildcard filters like *.ts or *.py.');
1872
+ }
1873
+ const includeFilter = `-Include "${includeArg}"`;
1874
+ const escapedPattern = args.pattern.replace(/'/g, "''");
1875
+ const cmd = `powershell -NoProfile -Command "Get-ChildItem -Path '${psPath}' -Recurse -File ${includeFilter} | Select-String -Pattern '${escapedPattern}' | ForEach-Object { $_.Path + ':' + $_.LineNumber + ':' + $_.Line }"`;
1876
+ try {
1877
+ const output = execSync(cmd, {
1878
+ cwd: this.cwd,
1879
+ encoding: 'utf-8',
1880
+ maxBuffer: 5 * 1024 * 1024,
1881
+ timeout: 60000,
1882
+ });
1883
+ const trimmed = output.trim();
1884
+ if (!trimmed) {
1885
+ return {
1886
+ success: true,
1887
+ output: 'No matches found',
1888
+ metadata: { searchStatus: 'search_no_matches', backend: 'select-string' },
1889
+ };
1890
+ }
1891
+ return {
1892
+ success: true,
1893
+ output: trimmed,
1894
+ metadata: { searchStatus: 'search_matches_found', backend: 'select-string' },
1895
+ };
1896
+ }
1897
+ catch (error) {
1898
+ const stderr = (error.stderr || '').toString();
1899
+ // Select-String returns exit code 1 for no matches when used in pipeline
1900
+ if (error.status === 1 && !stderr.trim()) {
1901
+ return {
1902
+ success: true,
1903
+ output: 'No matches found',
1904
+ metadata: { searchStatus: 'search_no_matches', backend: 'select-string' },
1905
+ };
1906
+ }
1907
+ throw error; // Let caller try next backend
1908
+ }
1909
+ }
1910
+ /**
1911
+ * Pure Node.js recursive file search — reliable on all platforms, no external deps
1912
+ */
1913
+ grepNodeNative(args, searchPath) {
1914
+ const { minimatch } = (() => {
1915
+ try {
1916
+ return require('minimatch');
1917
+ }
1918
+ catch {
1919
+ return { minimatch: null };
1920
+ }
1921
+ })();
1922
+ const results = [];
1923
+ let regex;
1924
+ try {
1925
+ regex = new RegExp(args.pattern, 'i');
1926
+ }
1927
+ catch {
1928
+ // If pattern is not valid regex, treat as literal
1929
+ regex = new RegExp(args.pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i');
1930
+ }
1931
+ const includeGlob = args.include || null;
1932
+ const maxResults = 500;
1933
+ const skipDirs = new Set(['node_modules', '.git', 'dist', 'build', '__pycache__', '.next', 'vendor', '.venv']);
1934
+ const walk = (dir) => {
1935
+ if (results.length >= maxResults)
1936
+ return;
1937
+ let entries;
1938
+ try {
1939
+ entries = fs.readdirSync(dir, { withFileTypes: true });
1940
+ }
1941
+ catch {
1942
+ return; // Permission denied or inaccessible
1943
+ }
1944
+ for (const entry of entries) {
1945
+ if (results.length >= maxResults)
1946
+ break;
1947
+ const fullPath = path.join(dir, entry.name);
1948
+ if (entry.isDirectory()) {
1949
+ if (!skipDirs.has(entry.name)) {
1950
+ walk(fullPath);
1951
+ }
1952
+ continue;
1953
+ }
1954
+ if (!entry.isFile())
1955
+ continue;
1956
+ // Check include pattern
1957
+ if (includeGlob) {
1958
+ const matches = minimatch
1959
+ ? minimatch(entry.name, includeGlob)
1960
+ : entry.name.endsWith(includeGlob.replace('*', ''));
1961
+ if (!matches)
1962
+ continue;
1963
+ }
1964
+ // Skip binary files by extension
1965
+ const ext = path.extname(entry.name).toLowerCase();
1966
+ const binaryExts = new Set(['.png', '.jpg', '.jpeg', '.gif', '.ico', '.woff', '.woff2', '.ttf', '.eot', '.zip', '.tar', '.gz', '.exe', '.dll', '.so', '.dylib', '.pdf', '.mp3', '.mp4', '.wav', '.avi', '.mov']);
1967
+ if (binaryExts.has(ext))
1968
+ continue;
1969
+ try {
1970
+ const content = fs.readFileSync(fullPath, 'utf-8');
1971
+ const lines = content.split('\n');
1972
+ for (let i = 0; i < lines.length; i++) {
1973
+ if (regex.test(lines[i])) {
1974
+ const relativePath = path.relative(this.cwd, fullPath).replace(/\\/g, '/');
1975
+ results.push(`${relativePath}:${i + 1}:${lines[i]}`);
1976
+ if (results.length >= maxResults)
1977
+ break;
1978
+ }
1979
+ }
1980
+ }
1981
+ catch {
1982
+ // Skip files that can't be read (binary, encoding issues, etc.)
1983
+ }
1984
+ }
1985
+ };
1986
+ try {
1987
+ walk(searchPath);
1988
+ }
1989
+ catch (error) {
1990
+ return {
1991
+ success: false,
1992
+ error: `File search failed: ${error.message}`,
1993
+ metadata: { searchStatus: 'search_failed', backend: 'node-native' },
1994
+ };
1995
+ }
1996
+ if (results.length === 0) {
1997
+ return {
1998
+ success: true,
1999
+ output: 'No matches found',
2000
+ metadata: { searchStatus: 'search_no_matches', backend: 'node-native' },
2001
+ };
2002
+ }
2003
+ const truncationNote = results.length >= maxResults ? `\n...[truncated at ${maxResults} matches]` : '';
2004
+ return {
2005
+ success: true,
2006
+ output: results.join('\n') + truncationNote,
2007
+ metadata: { searchStatus: 'search_matches_found', backend: 'node-native' },
2008
+ };
2009
+ }
2010
+ listDir(args) {
2011
+ const dirPath = this.resolvePath(args.path);
2012
+ if (!fs.existsSync(dirPath)) {
2013
+ return { success: false, error: `Directory not found: ${args.path}` };
2014
+ }
2015
+ const entries = fs.readdirSync(dirPath, { withFileTypes: true });
2016
+ const output = entries.map(e => {
2017
+ const suffix = e.isDirectory() ? '/' : '';
2018
+ return e.name + suffix;
2019
+ }).join('\n');
2020
+ return { success: true, output };
2021
+ }
2022
+ glob(args) {
2023
+ const { globSync } = require('glob');
2024
+ try {
2025
+ const files = globSync(args.pattern, { cwd: this.cwd });
2026
+ return { success: true, output: files.join('\n') };
2027
+ }
2028
+ catch (error) {
2029
+ return { success: false, error: error.message };
2030
+ }
2031
+ }
2032
+ git(args) {
2033
+ try {
2034
+ const output = execSync(`git ${args.args}`, {
2035
+ cwd: this.cwd,
2036
+ encoding: 'utf-8',
2037
+ timeout: 60000,
2038
+ });
2039
+ return { success: true, output: output.trim() };
2040
+ }
2041
+ catch (error) {
2042
+ return { success: false, error: error.stderr || error.message };
2043
+ }
2044
+ }
2045
+ /**
2046
+ * Vigthoria Repository management tool
2047
+ * Allows AI to push, pull, list, share, and manage projects in the Vigthoria Repository
2048
+ */
2049
+ async repo(args) {
2050
+ const action = args.action?.toLowerCase();
2051
+ const project = args.project;
2052
+ const visibility = args.visibility || 'public';
2053
+ const targetPath = args.path || this.cwd;
2054
+ const description = args.description || '';
2055
+ try {
2056
+ // Push action uses direct API call to Community server (bypasses interactive CLI)
2057
+ if (action === 'push') {
2058
+ if (!project) {
2059
+ return {
2060
+ success: false,
2061
+ error: 'Project name is required for push',
2062
+ suggestion: 'Provide a project name, e.g., repo action=push project=my-project'
2063
+ };
2064
+ }
2065
+ // Load auth config
2066
+ const configPath = path.join(process.env.HOME || '/root', '.config', 'vigthoria-cli', 'config.json');
2067
+ if (!fs.existsSync(configPath)) {
2068
+ return { success: false, error: 'Not logged in. Run vigthoria login first.' };
2069
+ }
2070
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
2071
+ const authToken = config.authToken;
2072
+ const apiBase = config.apiUrl || 'https://coder.vigthoria.io';
2073
+ if (!authToken) {
2074
+ return { success: false, error: 'No auth token found. Run vigthoria login first.' };
2075
+ }
2076
+ // Build files array
2077
+ let filesArray = [];
2078
+ if (args.files) {
2079
+ // AI passed files directly
2080
+ let filesInput;
2081
+ if (typeof args.files === 'string') {
2082
+ try {
2083
+ filesInput = JSON.parse(args.files);
2084
+ }
2085
+ catch {
2086
+ filesInput = args.files;
2087
+ }
2088
+ }
2089
+ else {
2090
+ filesInput = args.files;
2091
+ }
2092
+ if (Array.isArray(filesInput)) {
2093
+ // Already in [{path, content}] format
2094
+ filesArray = filesInput.map((f) => ({ path: f.path || f.name || 'file', content: String(f.content || '') }));
2095
+ }
2096
+ else if (typeof filesInput === 'object' && filesInput !== null) {
2097
+ // {filename: content} format - convert
2098
+ for (const [filePath, content] of Object.entries(filesInput)) {
2099
+ filesArray.push({ path: filePath, content: String(content) });
2100
+ }
2101
+ }
2102
+ }
2103
+ // If no files from AI, read from disk
2104
+ if (filesArray.length === 0 && fs.existsSync(targetPath)) {
2105
+ const readDir = (dir, base) => {
2106
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
2107
+ for (const entry of entries) {
2108
+ const fullPath = path.join(dir, entry.name);
2109
+ const relPath = path.relative(base, fullPath);
2110
+ // Skip hidden dirs, node_modules, common non-essential dirs
2111
+ if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === '__pycache__')
2112
+ continue;
2113
+ if (entry.isDirectory()) {
2114
+ readDir(fullPath, base);
2115
+ }
2116
+ else if (entry.isFile()) {
2117
+ try {
2118
+ const content = fs.readFileSync(fullPath, 'utf-8');
2119
+ filesArray.push({ path: relPath, content });
2120
+ }
2121
+ catch { /* skip binary/unreadable files */ }
2122
+ }
2123
+ }
2124
+ };
2125
+ const stat = fs.statSync(targetPath);
2126
+ if (stat.isDirectory()) {
2127
+ readDir(targetPath, targetPath);
2128
+ }
2129
+ else {
2130
+ filesArray.push({ path: path.basename(targetPath), content: fs.readFileSync(targetPath, 'utf-8') });
2131
+ }
2132
+ }
2133
+ if (filesArray.length === 0) {
2134
+ return { success: false, error: 'No files to push. Provide files parameter or a valid path.' };
2135
+ }
2136
+ // POST to Community API via Coder proxy (fallback to direct Community server)
2137
+ const body = JSON.stringify({
2138
+ projectName: project,
2139
+ description: description || `${project} - pushed via Vigthoria AI`,
2140
+ visibility,
2141
+ files: filesArray,
2142
+ commitMessage: `Push from Vigthoria AI: ${filesArray.length} file(s)`
2143
+ });
2144
+ const headers = {
2145
+ 'Authorization': `Bearer ${authToken}`,
2146
+ 'Content-Type': 'application/json'
2147
+ };
2148
+ // Try proxy first; direct Community server is only reachable when running on the
2149
+ // Vigthoria backend itself (isServerRuntime), never expose this fallback to remote users.
2150
+ const pushUrls = [`${apiBase}/api/community-repo/push`];
2151
+ if (isServerRuntime()) {
2152
+ const directHost = ['local', 'host'].join('');
2153
+ pushUrls.push(`http://${directHost}:9000/api/repo/push`);
2154
+ }
2155
+ let result;
2156
+ let lastError = '';
2157
+ for (const pushUrl of pushUrls) {
2158
+ try {
2159
+ const response = await fetch(pushUrl, { method: 'POST', headers, body });
2160
+ result = await response.json();
2161
+ if (response.ok && result.success)
2162
+ break;
2163
+ lastError = result.error || result.message || `Status ${response.status}`;
2164
+ result = null;
2165
+ }
2166
+ catch (e) {
2167
+ lastError = e.message;
2168
+ result = null;
2169
+ }
2170
+ }
2171
+ if (!result || !result.success) {
2172
+ return {
2173
+ success: false,
2174
+ error: lastError || 'Push failed on all endpoints',
2175
+ suggestion: 'Check your authentication and try again. Run vigthoria login to refresh your token.'
2176
+ };
2177
+ }
2178
+ return {
2179
+ success: true,
2180
+ output: `Successfully pushed "${project}" to Vigthoria Community!\n` +
2181
+ `Action: ${result.action || 'created'}\n` +
2182
+ `Files: ${result.filesWritten || filesArray.length}\n` +
2183
+ `URL: ${result.url || `https://community.vigthoria.io/showcase/${result.projectId}`}`,
2184
+ metadata: { action: 'push', project, filesWritten: result.filesWritten || filesArray.length, url: result.url }
2185
+ };
2186
+ }
2187
+ // All other actions use CLI commands
2188
+ let command;
2189
+ switch (action) {
2190
+ case 'pull':
2191
+ if (!project) {
2192
+ return {
2193
+ success: false,
2194
+ error: 'Project name is required for pull',
2195
+ suggestion: 'Provide a project name, e.g., repo action=pull project=my-project'
2196
+ };
2197
+ }
2198
+ command = `vigthoria repo pull "${project}"`;
2199
+ break;
2200
+ case 'list':
2201
+ command = 'vigthoria repo list';
2202
+ break;
2203
+ case 'status':
2204
+ if (!project) {
2205
+ return {
2206
+ success: false,
2207
+ error: 'Project name is required for status',
2208
+ suggestion: 'Provide a project name, e.g., repo action=status project=my-project'
2209
+ };
2210
+ }
2211
+ command = `vigthoria repo status "${project}"`;
2212
+ break;
2213
+ case 'share':
2214
+ if (!project || !args.username) {
2215
+ return {
2216
+ success: false,
2217
+ error: 'Project name and username are required for share',
2218
+ suggestion: 'Provide both, e.g., repo action=share project=my-project username=collaborator permission=read'
2219
+ };
2220
+ }
2221
+ const permission = args.permission || 'read';
2222
+ command = `vigthoria repo share "${project}" "${args.username}" --permission ${permission}`;
2223
+ break;
2224
+ case 'delete':
2225
+ if (!project) {
2226
+ return {
2227
+ success: false,
2228
+ error: 'Project name is required for delete',
2229
+ suggestion: 'Provide a project name, e.g., repo action=delete project=my-project'
2230
+ };
2231
+ }
2232
+ command = `vigthoria repo delete "${project}" --force`;
2233
+ break;
2234
+ case 'clone':
2235
+ if (!project) {
2236
+ return {
2237
+ success: false,
2238
+ error: 'Project name is required for clone',
2239
+ suggestion: 'Provide a project name, e.g., repo action=clone project=my-project path=/path/to/target'
2240
+ };
2241
+ }
2242
+ command = `vigthoria repo clone "${project}" "${targetPath}"`;
2243
+ break;
2244
+ default:
2245
+ return {
2246
+ success: false,
2247
+ error: `Unknown repo action: ${action}`,
2248
+ suggestion: 'Available actions: push, pull, list, status, share, delete, clone'
2249
+ };
2250
+ }
2251
+ const output = execSync(command, {
2252
+ cwd: this.cwd,
2253
+ encoding: 'utf-8',
2254
+ timeout: 120000,
2255
+ env: { ...process.env, FORCE_COLOR: '0' }
2256
+ });
2257
+ return {
2258
+ success: true,
2259
+ output: output.trim(),
2260
+ metadata: { action, project }
2261
+ };
2262
+ }
2263
+ catch (error) {
2264
+ return {
2265
+ success: false,
2266
+ error: error.stderr || error.message,
2267
+ suggestion: 'Make sure you are logged in with vigthoria login and have the required permissions.'
2268
+ };
2269
+ }
2270
+ }
2271
+ /**
2272
+ * Fetch URL content - Cross-platform web fetching
2273
+ * Uses Node.js native fetch (available in Node 18+)
2274
+ */
2275
+ async fetchUrl(args) {
2276
+ const url = args.url;
2277
+ const method = (args.method || 'GET').toUpperCase();
2278
+ // Validate URL
2279
+ if (!url.startsWith('http://') && !url.startsWith('https://')) {
2280
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, 'URL must start with http:// or https://', 'Provide a valid URL, e.g., https://example.com');
2281
+ }
2282
+ try {
2283
+ const fetchOptions = {
2284
+ method,
2285
+ headers: {
2286
+ 'User-Agent': 'Vigthoria-CLI/1.5.7',
2287
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
2288
+ },
2289
+ };
2290
+ // Parse custom headers if provided
2291
+ if (args.headers) {
2292
+ try {
2293
+ const customHeaders = JSON.parse(args.headers);
2294
+ fetchOptions.headers = { ...fetchOptions.headers, ...customHeaders };
2295
+ }
2296
+ catch {
2297
+ this.logger.warn('Invalid headers JSON, using defaults');
2298
+ }
2299
+ }
2300
+ // Add body for POST/PUT requests
2301
+ if (args.body && ['POST', 'PUT', 'PATCH'].includes(method)) {
2302
+ fetchOptions.body = args.body;
2303
+ fetchOptions.headers['Content-Type'] = 'application/json';
2304
+ }
2305
+ // Use AbortController for timeout
2306
+ const controller = new AbortController();
2307
+ const timeout = setTimeout(() => controller.abort(), 30000);
2308
+ fetchOptions.signal = controller.signal;
2309
+ const response = await fetch(url, fetchOptions);
2310
+ clearTimeout(timeout);
2311
+ if (!response.ok) {
2312
+ return this.createErrorResult(ToolErrorType.NETWORK_ERROR, `HTTP ${response.status}: ${response.statusText}`, `The server returned an error. Status: ${response.status}`);
2313
+ }
2314
+ let content = await response.text();
2315
+ // Extract content based on selector if provided (basic HTML extraction)
2316
+ if (args.selector && content.includes('<')) {
2317
+ const selector = args.selector.toLowerCase().trim();
2318
+ if (selector === 'title') {
2319
+ const match = content.match(/<title[^>]*>([^<]*)<\/title>/i);
2320
+ content = match ? match[1].trim() : 'No title found';
2321
+ }
2322
+ else if (selector === 'meta' || selector.includes('meta[')) {
2323
+ const matches = content.match(/<meta[^>]+>/gi) || [];
2324
+ content = matches.length > 0 ? matches.join('\n') : 'No meta tags found';
2325
+ }
2326
+ else if (selector === 'body' || selector === 'text') {
2327
+ // Extract readable text from body
2328
+ const match = content.match(/<body[^>]*>([\s\S]*)<\/body>/i);
2329
+ if (match) {
2330
+ content = match[1]
2331
+ .replace(/<script[\s\S]*?<\/script>/gi, '')
2332
+ .replace(/<style[\s\S]*?<\/style>/gi, '')
2333
+ .replace(/<nav[\s\S]*?<\/nav>/gi, '')
2334
+ .replace(/<header[\s\S]*?<\/header>/gi, '')
2335
+ .replace(/<footer[\s\S]*?<\/footer>/gi, '')
2336
+ .replace(/<[^>]+>/g, ' ')
2337
+ .replace(/\s+/g, ' ')
2338
+ .trim();
2339
+ }
2340
+ }
2341
+ else if (selector === 'links' || selector === 'a') {
2342
+ // Extract all links
2343
+ const linkRegex = /<a[^>]+href=["']([^"']+)["'][^>]*>([^<]*)<\/a>/gi;
2344
+ const links = [];
2345
+ let linkMatch;
2346
+ while ((linkMatch = linkRegex.exec(content)) !== null) {
2347
+ const href = linkMatch[1];
2348
+ const text = linkMatch[2].trim();
2349
+ if (text && !href.startsWith('#') && !href.startsWith('javascript:')) {
2350
+ links.push(`${text}: ${href}`);
2351
+ }
2352
+ }
2353
+ content = links.length > 0 ? links.join('\n') : 'No links found';
2354
+ }
2355
+ else if (selector.includes(',')) {
2356
+ // Handle compound selectors like "h1, h2, h3"
2357
+ const tags = selector.split(',').map(s => s.trim());
2358
+ const allMatches = [];
2359
+ for (const tag of tags) {
2360
+ const regex = new RegExp(`<${tag}[^>]*>([\\s\\S]*?)</${tag}>`, 'gi');
2361
+ let match;
2362
+ while ((match = regex.exec(content)) !== null) {
2363
+ const text = match[1].replace(/<[^>]+>/g, '').trim();
2364
+ if (text)
2365
+ allMatches.push(`[${tag}] ${text}`);
2366
+ }
2367
+ }
2368
+ content = allMatches.length > 0 ? allMatches.join('\n') : `No ${selector} tags found`;
2369
+ }
2370
+ else if (/^h[1-6]$/.test(selector)) {
2371
+ // Single heading selector
2372
+ const regex = new RegExp(`<${selector}[^>]*>([\\s\\S]*?)</${selector}>`, 'gi');
2373
+ const matches = [];
2374
+ let match;
2375
+ while ((match = regex.exec(content)) !== null) {
2376
+ const text = match[1].replace(/<[^>]+>/g, '').trim();
2377
+ if (text)
2378
+ matches.push(text);
2379
+ }
2380
+ content = matches.length > 0 ? matches.join('\n') : `No ${selector} tags found`;
2381
+ }
2382
+ else if (selector === 'nav' || selector === 'nav a') {
2383
+ // Extract navigation links
2384
+ const navMatch = content.match(/<nav[^>]*>([\s\S]*?)<\/nav>/gi);
2385
+ if (navMatch) {
2386
+ const linkRegex = /<a[^>]+href=["']([^"']+)["'][^>]*>([^<]*)<\/a>/gi;
2387
+ const links = [];
2388
+ for (const nav of navMatch) {
2389
+ let linkMatch;
2390
+ while ((linkMatch = linkRegex.exec(nav)) !== null) {
2391
+ const text = linkMatch[2].trim();
2392
+ if (text)
2393
+ links.push(`${text}: ${linkMatch[1]}`);
2394
+ }
2395
+ }
2396
+ content = links.length > 0 ? links.join('\n') : 'No navigation links found';
2397
+ }
2398
+ else {
2399
+ content = 'No navigation found';
2400
+ }
2401
+ }
2402
+ else if (selector === 'footer') {
2403
+ const match = content.match(/<footer[^>]*>([\s\S]*?)<\/footer>/i);
2404
+ content = match ? match[1].replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim() : 'No footer found';
2405
+ }
2406
+ else if (selector === 'images' || selector === 'img') {
2407
+ const imgRegex = /<img[^>]+src=["']([^"']+)["'][^>]*(?:alt=["']([^"']*)["'])?[^>]*>/gi;
2408
+ const images = [];
2409
+ let imgMatch;
2410
+ while ((imgMatch = imgRegex.exec(content)) !== null) {
2411
+ const src = imgMatch[1];
2412
+ const alt = imgMatch[2] || 'no alt';
2413
+ images.push(`${alt}: ${src}`);
2414
+ }
2415
+ content = images.length > 0 ? images.join('\n') : 'No images found';
2416
+ }
2417
+ else {
2418
+ // Generic tag extraction
2419
+ const regex = new RegExp(`<${selector}[^>]*>([\\s\\S]*?)</${selector}>`, 'gi');
2420
+ const matches = [];
2421
+ let match;
2422
+ while ((match = regex.exec(content)) !== null) {
2423
+ matches.push(match[1].replace(/<[^>]+>/g, ' ').trim());
2424
+ }
2425
+ content = matches.length > 0 ? matches.join('\n\n---\n\n') : `No ${selector} elements found`;
2426
+ }
2427
+ }
2428
+ // Truncate if too long
2429
+ if (content.length > 50000) {
2430
+ content = content.substring(0, 50000) + '\n... (truncated, content too long)';
2431
+ }
2432
+ return {
2433
+ success: true,
2434
+ output: content,
2435
+ metadata: {
2436
+ url,
2437
+ status: response.status,
2438
+ contentType: response.headers.get('content-type') || 'unknown',
2439
+ contentLength: content.length,
2440
+ },
2441
+ };
2442
+ }
2443
+ catch (error) {
2444
+ if (error.name === 'AbortError') {
2445
+ return this.createErrorResult(ToolErrorType.TIMEOUT, 'Request timed out after 30 seconds', 'The server took too long to respond. Try again or use a different URL.');
2446
+ }
2447
+ return this.createErrorResult(ToolErrorType.NETWORK_ERROR, error.message, 'Check your internet connection and ensure the URL is correct.');
2448
+ }
2449
+ }
2450
+ async browserTool(args) {
2451
+ const mode = (args.mode || '').toLowerCase();
2452
+ const url = args.url;
2453
+ if (!['capture', 'errors', 'test'].includes(mode)) {
2454
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid mode: ${args.mode}`, "mode must be one of: 'capture', 'errors', 'test'");
2455
+ }
2456
+ if (!url || (!url.startsWith('http://') && !url.startsWith('https://'))) {
2457
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, 'URL must start with http:// or https://', 'Provide a valid URL, e.g., https://example.com');
2458
+ }
2459
+ const host = process.env.VIGTHORIA_DEVTOOLS_BRIDGE_HOST || '127.0.0.1';
2460
+ const port = process.env.VIGTHORIA_DEVTOOLS_BRIDGE_PORT || '4016';
2461
+ const base = `http://${host}:${port}`;
2462
+ const toolName = mode === 'capture' ? 'capture_state' :
2463
+ mode === 'errors' ? 'get_page_errors' :
2464
+ 'run_test';
2465
+ const params = { url };
2466
+ if (mode === 'capture' && (args.include_screenshot || '').toLowerCase() === 'false') {
2467
+ params.includeScreenshot = false;
2468
+ }
2469
+ if (mode === 'test') {
2470
+ params.testType = 'quick';
2471
+ }
2472
+ const controller = new AbortController();
2473
+ const timeoutMs = mode === 'test' ? 60000 : 45000;
2474
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
2475
+ try {
2476
+ const res = await fetch(`${base}/api/mcp/tools`, {
2477
+ method: 'POST',
2478
+ headers: { 'Content-Type': 'application/json', 'User-Agent': 'Vigthoria-CLI-Browser/1.0' },
2479
+ body: JSON.stringify({ tool: toolName, params }),
2480
+ signal: controller.signal,
2481
+ });
2482
+ clearTimeout(timeout);
2483
+ if (!res.ok) {
2484
+ return this.createErrorResult(ToolErrorType.NETWORK_ERROR, `DevTools Bridge HTTP ${res.status}`, 'Ensure the bridge is running (vigthoria bridge status). On a developer workstation it must be installed and started locally.');
2485
+ }
2486
+ const data = await res.json();
2487
+ if (!data.success) {
2488
+ return this.createErrorResult(ToolErrorType.NETWORK_ERROR, data.error || 'DevTools Bridge returned unsuccessful response', 'Check the bridge logs.');
2489
+ }
2490
+ let payload;
2491
+ if (mode === 'capture' && data.result && typeof data.result === 'object') {
2492
+ const r = data.result;
2493
+ const trimmed = {
2494
+ url: r.url,
2495
+ timestamp: r.timestamp,
2496
+ metrics: r.metrics,
2497
+ performance: r.performance,
2498
+ html_excerpt: typeof r.html === 'string' ? r.html.slice(0, 4000) : undefined,
2499
+ screenshot_data_url_length: typeof r.screenshot === 'string' ? r.screenshot.length : 0,
2500
+ };
2501
+ payload = JSON.stringify(trimmed, null, 2);
2502
+ }
2503
+ else {
2504
+ payload = JSON.stringify(data.result, null, 2).slice(0, 8000);
2505
+ }
2506
+ return {
2507
+ success: true,
2508
+ output: payload,
2509
+ metadata: { tool: 'browser', mode, url },
2510
+ };
2511
+ }
2512
+ catch (e) {
2513
+ clearTimeout(timeout);
2514
+ const msg = e instanceof Error ? e.message : String(e);
2515
+ return this.createErrorResult(ToolErrorType.NETWORK_ERROR, `Browser tool failed: ${msg}`, "Verify the DevTools Bridge is reachable on host:port (defaults 127.0.0.1:4016).");
2516
+ }
2517
+ }
2518
+ /**
2519
+ * Execute command via SSH on remote server
2520
+ * Useful for running Unix commands from Windows
2521
+ */
2522
+ async sshExec(args) {
2523
+ const command = args.command;
2524
+ const host = args.host || 'vigthoria-server';
2525
+ const timeout = args.timeout ? parseInt(args.timeout) * 1000 : 60000;
2526
+ const normalizedHost = String(host).trim().toLowerCase();
2527
+ if (!SSH_SAFE_HOST_PATTERN.test(normalizedHost)) {
2528
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, 'Invalid SSH host format', 'Host can only include letters, numbers, dots, and dashes.');
2529
+ }
2530
+ const allowedHosts = getSshAllowedHosts();
2531
+ if (!allowedHosts.has(normalizedHost)) {
2532
+ return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, `SSH host is not allowlisted: ${host}`, 'Add the host to VIGTHORIA_SSH_ALLOWED_HOSTS to permit access.');
2533
+ }
2534
+ // Security checks for SSH commands
2535
+ const blockedPatterns = [
2536
+ /\brm\s+-rf?\s+\//i, // Dangerous rm commands
2537
+ /\bsudo\s+rm/i, // Sudo rm
2538
+ />\s*\/dev\/sd/i, // Writing to disk devices
2539
+ /\bdd\s+.*of=\/dev/i, // dd to devices
2540
+ /\bmkfs/i, // Format filesystems
2541
+ /shutdown|reboot|halt|poweroff/i, // System control
2542
+ ];
2543
+ for (const pattern of blockedPatterns) {
2544
+ if (pattern.test(command)) {
2545
+ return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, 'This command is blocked for security reasons', 'Dangerous system commands cannot be executed via SSH.');
2546
+ }
2547
+ }
2548
+ try {
2549
+ const os = require('os');
2550
+ const platform = os.platform();
2551
+ let sshCommand;
2552
+ let execOptions = {
2553
+ encoding: 'utf-8',
2554
+ timeout,
2555
+ maxBuffer: 10 * 1024 * 1024,
2556
+ };
2557
+ if (platform === 'win32') {
2558
+ // On Windows, use the ssh command from OpenSSH
2559
+ sshCommand = `ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${host} "${command.replace(/"/g, '\\"')}"`;
2560
+ execOptions.shell = true;
2561
+ }
2562
+ else {
2563
+ // On Unix-like systems
2564
+ sshCommand = `ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${host} '${command.replace(/'/g, "'\\''")}'`;
2565
+ execOptions.shell = '/bin/sh';
2566
+ }
2567
+ const output = execSync(sshCommand, execOptions);
2568
+ return {
2569
+ success: true,
2570
+ output: output.trim(),
2571
+ metadata: { host, command },
2572
+ };
2573
+ }
2574
+ catch (error) {
2575
+ // Check for common SSH errors
2576
+ const errorMsg = error.stderr || error.message || '';
2577
+ if (errorMsg.includes('Connection refused') || errorMsg.includes('No route to host')) {
2578
+ return this.createErrorResult(ToolErrorType.NETWORK_ERROR, `Cannot connect to SSH host: ${host}`, 'Check that the SSH host is correct and the server is running.');
2579
+ }
2580
+ if (errorMsg.includes('Permission denied') || errorMsg.includes('authentication')) {
2581
+ return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, 'SSH authentication failed', 'Make sure you have SSH key authentication set up for this host.');
2582
+ }
2583
+ if (error.killed) {
2584
+ return this.createErrorResult(ToolErrorType.TIMEOUT, `SSH command timed out after ${timeout / 1000}s`, 'Try a simpler command or increase the timeout.');
2585
+ }
2586
+ return {
2587
+ success: false,
2588
+ output: error.stdout || '',
2589
+ error: errorMsg,
2590
+ suggestion: 'Check the command syntax and ensure SSH access is configured.',
2591
+ };
2592
+ }
2593
+ }
2594
+ /**
2595
+ * Resolve and SANITIZE path - prevent path traversal outside workspace
2596
+ * SECURITY: All paths MUST stay within the workspace (cwd)
2597
+ */
2598
+ resolvePath(p) {
2599
+ const normalizedInput = String(p || '').trim().replace(/\\/g, '/');
2600
+ const workspaceRoot = path.normalize(this.cwd);
2601
+ const workspaceRootPosix = workspaceRoot.replace(/\\/g, '/').replace(/\/+$/g, '');
2602
+ const workspaceBase = path.posix.basename(workspaceRootPosix);
2603
+ const stripWorkspacePrefix = (value) => {
2604
+ let candidate = String(value || '').trim().replace(/\\/g, '/').replace(/^\.\//, '');
2605
+ if (!candidate) {
2606
+ return candidate;
2607
+ }
2608
+ const normalizedRootNoSlash = workspaceRootPosix.replace(/^\//, '');
2609
+ const prefixes = [
2610
+ `${workspaceRootPosix}/`,
2611
+ `${normalizedRootNoSlash}/`,
2612
+ `${workspaceBase}/`,
2613
+ ];
2614
+ for (const prefix of prefixes) {
2615
+ if (candidate.startsWith(prefix)) {
2616
+ candidate = candidate.slice(prefix.length);
2617
+ }
2618
+ }
2619
+ const embeddedWorkspacePrefix = `/${workspaceBase}/`;
2620
+ const embeddedIndex = candidate.indexOf(embeddedWorkspacePrefix);
2621
+ if (embeddedIndex >= 0) {
2622
+ candidate = candidate.slice(embeddedIndex + embeddedWorkspacePrefix.length);
2623
+ }
2624
+ return candidate.replace(/^\//, '');
2625
+ };
2626
+ // Resolve the full path (handles both relative and absolute)
2627
+ let resolvedPath;
2628
+ if (path.isAbsolute(normalizedInput)) {
2629
+ resolvedPath = path.normalize(normalizedInput);
2630
+ }
2631
+ else {
2632
+ resolvedPath = path.normalize(path.join(this.cwd, stripWorkspacePrefix(normalizedInput)));
2633
+ }
2634
+ // SECURITY CHECK: Ensure path is within workspace
2635
+ if (!resolvedPath.startsWith(workspaceRoot + path.sep) && resolvedPath !== workspaceRoot) {
2636
+ // Path is outside workspace - force it back to workspace
2637
+ this.logger.warn(`Security: Blocked access to path outside workspace: ${p}`);
2638
+ // Return the sanitized relative path within workspace
2639
+ const basename = path.basename(stripWorkspacePrefix(normalizedInput) || normalizedInput);
2640
+ return path.join(this.cwd, basename);
2641
+ }
2642
+ return resolvedPath;
2643
+ }
2644
+ /**
2645
+ * Check if a path is within the allowed workspace
2646
+ */
2647
+ isPathWithinWorkspace(p) {
2648
+ const resolvedPath = path.normalize(path.isAbsolute(p) ? p : path.join(this.cwd, p));
2649
+ const workspaceRoot = path.normalize(this.cwd);
2650
+ return resolvedPath.startsWith(workspaceRoot + path.sep) || resolvedPath === workspaceRoot;
2651
+ }
2652
+ // ═══════════════════════════════════════════════════════════════
2653
+ // TASK (Sub-Agent) Tool
2654
+ // ═══════════════════════════════════════════════════════════════
2655
+ async task(args) {
2656
+ const description = args.description;
2657
+ const workingDir = args.working_dir
2658
+ ? this.resolvePath(args.working_dir)
2659
+ : this.cwd;
2660
+ if (!this.isPathWithinWorkspace(workingDir)) {
2661
+ return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, 'Sub-agent working directory must be within the project workspace', 'Provide a relative path within the current project.');
2662
+ }
2663
+ this.logger.info(`Spawning sub-agent: ${description.substring(0, 80)}...`);
2664
+ // Create a scoped sub-agent with its own tool instance
2665
+ const subTools = new AgenticTools(this.logger, workingDir, this.permissionCallback, this.autoApprove);
2666
+ // Build a focused system prompt for the sub-agent
2667
+ const systemPrompt = [
2668
+ 'You are a focused sub-agent spawned to complete a specific subtask.',
2669
+ 'You have access to standard tools (read_file, write_file, edit_file, bash, grep, list_dir, glob, git). You cannot spawn sub-agents.',
2670
+ 'Complete the task thoroughly and return a detailed result.',
2671
+ `Working directory: ${workingDir}`,
2672
+ '',
2673
+ AgenticTools.getToolsForPrompt().replace(/### task[\s\S]*?(?=###|$)/, ''), // Strip task from sub-agent
2674
+ ].join('\n');
2675
+ const messages = [
2676
+ { role: 'system', content: systemPrompt },
2677
+ { role: 'user', content: description },
2678
+ ];
2679
+ const maxSubTurns = 8;
2680
+ const results = [];
2681
+ try {
2682
+ for (let turn = 0; turn < maxSubTurns; turn++) {
2683
+ // Import api dynamically to avoid circular dependency
2684
+ const { APIClient } = await import('./api.js');
2685
+ const { Config } = await import('./config.js');
2686
+ const config = new Config();
2687
+ const api = new APIClient(config, this.logger);
2688
+ const response = await api.chat(messages, 'code');
2689
+ const assistantMessage = response.message || '';
2690
+ messages.push({ role: 'assistant', content: assistantMessage });
2691
+ const toolCalls = AgenticTools.parseToolCalls(assistantMessage);
2692
+ if (toolCalls.length === 0) {
2693
+ // Sub-agent finished - extract the final answer
2694
+ const finalAnswer = assistantMessage
2695
+ .replace(/```tool[\s\S]*?```/g, '')
2696
+ .replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '')
2697
+ .trim();
2698
+ results.push(finalAnswer);
2699
+ break;
2700
+ }
2701
+ // Execute each tool call
2702
+ for (const call of toolCalls) {
2703
+ const result = await subTools.execute(call);
2704
+ const summary = `Tool ${call.tool} ${result.success ? 'succeeded' : 'FAILED'}.` +
2705
+ (call.args.path ? `\nFile: ${call.args.path}` : '') +
2706
+ (result.output ? `\nOutput:\n${result.output.substring(0, 4000)}` : '') +
2707
+ (result.error ? `\nError: ${result.error}` : '');
2708
+ messages.push({ role: 'system', content: summary });
2709
+ results.push(`[${call.tool}] ${result.success ? '✓' : '✗'}`);
2710
+ }
2711
+ messages.push({
2712
+ role: 'system',
2713
+ content: 'Continue with your task. Use more tools if needed, or provide your final answer.',
2714
+ });
2715
+ }
2716
+ return {
2717
+ success: true,
2718
+ output: results.join('\n'),
2719
+ metadata: { subAgentTurns: results.length, workingDir },
2720
+ };
2721
+ }
2722
+ catch (error) {
2723
+ return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, `Sub-agent failed: ${error.message}`, 'The sub-agent encountered an error. Try simplifying the task or running it directly.');
2724
+ }
2725
+ }
2726
+ // ═══════════════════════════════════════════════════════════════
2727
+ // MULTI_EDIT Tool - Atomic multi-file edits with rollback
2728
+ // ═══════════════════════════════════════════════════════════════
2729
+ async multiEdit(args) {
2730
+ let edits;
2731
+ try {
2732
+ edits = JSON.parse(args.edits);
2733
+ if (!Array.isArray(edits) || edits.length === 0) {
2734
+ throw new Error('edits must be a non-empty array');
2735
+ }
2736
+ }
2737
+ catch (parseError) {
2738
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid edits JSON: ${parseError.message}`, 'Provide edits as a JSON array: [{"path": "file.ts", "old_text": "find", "new_text": "replace"}]');
2739
+ }
2740
+ // Validate all edits can proceed before modifying anything
2741
+ const contentMap = new Map();
2742
+ const backups = [];
2743
+ const resolvedEdits = [];
2744
+ for (let i = 0; i < edits.length; i++) {
2745
+ const edit = edits[i];
2746
+ if (!edit.path || typeof edit.old_text !== 'string' || typeof edit.new_text !== 'string') {
2747
+ return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Edit ${i}: missing required fields (path, old_text, new_text)`, 'Each edit must have path, old_text, and new_text fields.');
2748
+ }
2749
+ const resolvedPath = this.resolvePath(edit.path);
2750
+ if (!this.isPathWithinWorkspace(resolvedPath)) {
2751
+ return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, `Edit ${i}: path "${edit.path}" is outside workspace`, 'All files must be within the current project.');
2752
+ }
2753
+ if (!fs.existsSync(resolvedPath)) {
2754
+ return this.createErrorResult(ToolErrorType.FILE_NOT_FOUND, `Edit ${i}: file not found: ${edit.path}`, 'Use write_file to create new files instead.');
2755
+ }
2756
+ // Use contentMap to track cumulative edits to the same file
2757
+ if (!contentMap.has(resolvedPath)) {
2758
+ const diskContent = fs.readFileSync(resolvedPath, 'utf-8');
2759
+ contentMap.set(resolvedPath, diskContent);
2760
+ backups.push({ path: resolvedPath, content: diskContent });
2761
+ }
2762
+ const content = contentMap.get(resolvedPath);
2763
+ if (!content.includes(edit.old_text)) {
2764
+ return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, `Edit ${i}: old_text not found in ${edit.path}`, `The text to replace was not found. Use read_file to verify the file contents.`);
2765
+ }
2766
+ // Check for multiple matches
2767
+ const matchCount = content.split(edit.old_text).length - 1;
2768
+ if (matchCount > 1) {
2769
+ return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, `Edit ${i}: old_text matches ${matchCount} locations in ${edit.path}`, 'Make old_text more specific to match exactly one location. Include surrounding context.');
2770
+ }
2771
+ // Apply edit to contentMap so subsequent edits to same file see updated content
2772
+ contentMap.set(resolvedPath, content.replace(edit.old_text, edit.new_text));
2773
+ resolvedEdits.push({ resolvedPath, old_text: edit.old_text, new_text: edit.new_text, content });
2774
+ }
2775
+ // Apply all edits
2776
+ const applied = [];
2777
+ try {
2778
+ for (const edit of resolvedEdits) {
2779
+ const finalContent = contentMap.get(edit.resolvedPath) || edit.content.replace(edit.old_text, edit.new_text);
2780
+ fs.writeFileSync(edit.resolvedPath, finalContent, 'utf-8');
2781
+ applied.push(path.relative(this.cwd, edit.resolvedPath));
2782
+ }
2783
+ // Push undo operations for all edits
2784
+ for (const backup of backups) {
2785
+ this.undoStack.push({
2786
+ id: `multi_edit_${Date.now()}_${path.basename(backup.path)}`,
2787
+ tool: 'multi_edit',
2788
+ timestamp: Date.now(),
2789
+ filePath: backup.path,
2790
+ originalContent: backup.content,
2791
+ description: `multi_edit: ${path.relative(this.cwd, backup.path)}`,
2792
+ });
2793
+ }
2794
+ return {
2795
+ success: true,
2796
+ output: `${CH.success} Atomically edited ${applied.length} file(s):\n${applied.map(f => ` ✓ ${f}`).join('\n')}`,
2797
+ undoable: true,
2798
+ metadata: { filesEdited: applied.length, files: applied },
2799
+ };
2800
+ }
2801
+ catch (error) {
2802
+ // ROLLBACK: Restore all files from backups
2803
+ for (const backup of backups) {
2804
+ try {
2805
+ fs.writeFileSync(backup.path, backup.content, 'utf-8');
2806
+ }
2807
+ catch {
2808
+ // Best-effort rollback
2809
+ }
2810
+ }
2811
+ return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, `Multi-edit failed, all changes rolled back: ${error.message}`, 'Check file permissions and disk space.');
2812
+ }
2813
+ }
2814
+ // ═══════════════════════════════════════════════════════════════
2815
+ // CODEBASE_SEARCH Tool - Deep indexed codebase search
2816
+ // ═══════════════════════════════════════════════════════════════
2817
+ async codebaseSearch(args) {
2818
+ const query = args.query;
2819
+ const scope = args.scope || 'all';
2820
+ const includePattern = args.include || '';
2821
+ const maxResults = Math.min(parseInt(args.max_results || '30', 10), 100);
2822
+ if (this.indexedCodebaseSearch && (scope === 'all' || scope === 'content')) {
2823
+ const indexedOutput = this.indexedCodebaseSearch(query, maxResults);
2824
+ if (indexedOutput && !indexedOutput.includes('No indexed codebase matches found')) {
2825
+ return {
2826
+ success: true,
2827
+ output: indexedOutput,
2828
+ metadata: { searchStatus: 'search_matches_found', source: 'tfidf-index' },
2829
+ };
2830
+ }
2831
+ }
2832
+ const results = [];
2833
+ const seen = new Set();
2834
+ // Helper: collect files recursively respecting gitignore-like patterns
2835
+ const collectFiles = (dir, pattern) => {
2836
+ const files = [];
2837
+ const ignorePatterns = [
2838
+ 'node_modules', '.git', 'dist', 'build', '.next', '__pycache__',
2839
+ '.venv', 'venv', '.tox', 'coverage', '.nyc_output', '.cache',
2840
+ 'vendor', 'target', 'bin', 'obj', '.svn', '.hg',
2841
+ ];
2842
+ const walk = (currentDir, depth) => {
2843
+ if (depth > 12)
2844
+ return; // Prevent infinite recursion
2845
+ let entries;
2846
+ try {
2847
+ entries = fs.readdirSync(currentDir, { withFileTypes: true });
2848
+ }
2849
+ catch {
2850
+ return;
2851
+ }
2852
+ for (const entry of entries) {
2853
+ if (ignorePatterns.includes(entry.name) || entry.name.startsWith('.'))
2854
+ continue;
2855
+ const fullPath = path.join(currentDir, entry.name);
2856
+ if (entry.isDirectory()) {
2857
+ walk(fullPath, depth + 1);
2858
+ }
2859
+ else if (entry.isFile()) {
2860
+ if (pattern) {
2861
+ const basename = entry.name;
2862
+ // Simple glob matching for extension patterns like *.ts, *.js
2863
+ const globPattern = pattern.replace(/\*\*\//g, '(.*/)?').replace(/\*/g, '[^/]*').replace(/\?/g, '.');
2864
+ if (new RegExp(globPattern, 'i').test(basename) || fullPath.includes(pattern.replace(/\*/g, ''))) {
2865
+ files.push(fullPath);
2866
+ }
2867
+ }
2868
+ else {
2869
+ files.push(fullPath);
2870
+ }
2871
+ }
2872
+ }
2873
+ };
2874
+ walk(dir, 0);
2875
+ return files;
2876
+ };
2877
+ try {
2878
+ const allFiles = collectFiles(this.cwd, includePattern || undefined);
2879
+ // SCOPE: files - search file names/paths
2880
+ if (scope === 'files' || scope === 'all') {
2881
+ const queryLower = query.toLowerCase();
2882
+ const queryParts = queryLower.split(/[\s_\-./]+/).filter(Boolean);
2883
+ for (const filePath of allFiles) {
2884
+ const relativePath = path.relative(this.cwd, filePath);
2885
+ const filenameLower = relativePath.toLowerCase();
2886
+ const matches = queryParts.every(part => filenameLower.includes(part));
2887
+ if (matches && !seen.has(relativePath)) {
2888
+ seen.add(relativePath);
2889
+ results.push(`[file] ${relativePath}`);
2890
+ }
2891
+ if (results.length >= maxResults)
2892
+ break;
2893
+ }
2894
+ }
2895
+ // SCOPE: symbols - extract function/class/variable definitions
2896
+ if ((scope === 'symbols' || scope === 'all') && results.length < maxResults) {
2897
+ const symbolRegex = /(?:(?:export\s+)?(?:async\s+)?(?:function|class|interface|type|enum|const|let|var|def|class)\s+)([A-Za-z_$][A-Za-z0-9_$]*)/g;
2898
+ const queryLower = query.toLowerCase();
2899
+ for (const filePath of allFiles) {
2900
+ if (results.length >= maxResults)
2901
+ break;
2902
+ const ext = path.extname(filePath).toLowerCase();
2903
+ // Only parse code files
2904
+ if (!['.ts', '.tsx', '.js', '.jsx', '.py', '.go', '.rs', '.java', '.rb', '.php', '.c', '.cpp', '.h', '.cs', '.swift', '.kt'].includes(ext))
2905
+ continue;
2906
+ let content;
2907
+ try {
2908
+ const stat = fs.statSync(filePath);
2909
+ if (stat.size > 512 * 1024)
2910
+ continue; // Skip files > 512KB
2911
+ content = fs.readFileSync(filePath, 'utf-8');
2912
+ }
2913
+ catch {
2914
+ continue;
2915
+ }
2916
+ let match;
2917
+ symbolRegex.lastIndex = 0;
2918
+ while ((match = symbolRegex.exec(content)) !== null) {
2919
+ const symbolName = match[1];
2920
+ if (symbolName.toLowerCase().includes(queryLower) || queryLower.includes(symbolName.toLowerCase())) {
2921
+ const relativePath = path.relative(this.cwd, filePath);
2922
+ const lineNum = content.substring(0, match.index).split('\n').length;
2923
+ const key = `${relativePath}:${symbolName}`;
2924
+ if (!seen.has(key)) {
2925
+ seen.add(key);
2926
+ results.push(`[symbol] ${symbolName} → ${relativePath}:${lineNum}`);
2927
+ }
2928
+ }
2929
+ if (results.length >= maxResults)
2930
+ break;
2931
+ }
2932
+ }
2933
+ }
2934
+ // SCOPE: content - full-text search using ripgrep or fallback
2935
+ if ((scope === 'content' || scope === 'all') && results.length < maxResults) {
2936
+ try {
2937
+ // Try ripgrep first (fast)
2938
+ const rgArgs = [
2939
+ '-i', '--no-heading', '--line-number',
2940
+ '--max-count', '3',
2941
+ '--max-filesize', '512K',
2942
+ '-g', '!node_modules', '-g', '!.git', '-g', '!dist', '-g', '!build',
2943
+ ];
2944
+ if (includePattern)
2945
+ rgArgs.push('-g', includePattern);
2946
+ rgArgs.push('--', query, this.cwd);
2947
+ const isWin = process.platform === 'win32';
2948
+ const quote = (s) => isWin ? `"${s}"` : `'${s}'`;
2949
+ const rgOutput = execSync(`rg ${rgArgs.map(a => quote(a)).join(' ')}`, {
2950
+ encoding: 'utf-8',
2951
+ timeout: 15000,
2952
+ maxBuffer: 5 * 1024 * 1024,
2953
+ }).trim();
2954
+ for (const line of rgOutput.split('\n').slice(0, maxResults - results.length)) {
2955
+ if (!line.trim())
2956
+ continue;
2957
+ const relativeLine = line.replace(this.cwd + path.sep, '').replace(this.cwd + '/', '');
2958
+ const lineKey = relativeLine.substring(0, 200);
2959
+ if (!seen.has(lineKey)) {
2960
+ seen.add(lineKey);
2961
+ results.push(`[content] ${relativeLine}`);
2962
+ }
2963
+ }
2964
+ }
2965
+ catch {
2966
+ // Fallback: Node-native grep
2967
+ const queryLower = query.toLowerCase();
2968
+ for (const filePath of allFiles) {
2969
+ if (results.length >= maxResults)
2970
+ break;
2971
+ try {
2972
+ const stat = fs.statSync(filePath);
2973
+ if (stat.size > 256 * 1024)
2974
+ continue;
2975
+ const content = fs.readFileSync(filePath, 'utf-8');
2976
+ const lines = content.split('\n');
2977
+ for (let i = 0; i < lines.length; i++) {
2978
+ if (lines[i].toLowerCase().includes(queryLower)) {
2979
+ const relativePath = path.relative(this.cwd, filePath);
2980
+ const lineKey = `${relativePath}:${i + 1}`;
2981
+ if (!seen.has(lineKey)) {
2982
+ seen.add(lineKey);
2983
+ results.push(`[content] ${relativePath}:${i + 1}: ${lines[i].trim().substring(0, 120)}`);
2984
+ }
2985
+ if (results.length >= maxResults)
2986
+ break;
2987
+ }
2988
+ }
2989
+ }
2990
+ catch {
2991
+ continue;
2992
+ }
2993
+ }
2994
+ }
2995
+ }
2996
+ if (results.length === 0) {
2997
+ return {
2998
+ success: true,
2999
+ output: `No results found for "${query}" in scope "${scope}".`,
3000
+ metadata: { searchStatus: 'search_no_matches', totalFiles: allFiles.length },
3001
+ };
3002
+ }
3003
+ return {
3004
+ success: true,
3005
+ output: `Found ${results.length} result(s) across ${allFiles.length} files:\n\n${results.join('\n')}`,
3006
+ metadata: { searchStatus: 'search_matches_found', resultCount: results.length, totalFiles: allFiles.length },
3007
+ };
3008
+ }
3009
+ catch (error) {
3010
+ return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, `Codebase search failed: ${error.message}`, 'Try a simpler query or use grep for specific text patterns.');
3011
+ }
3012
+ }
3013
+ /**
3014
+ * Parse tool calls from AI response (Vigthoria Agent format)
3015
+ * Enhanced to handle various AI output formats including malformed JSON
3016
+ */
3017
+ static parseToolCalls(text) {
3018
+ if (typeof text !== 'string' || text.length === 0) {
3019
+ return [];
3020
+ }
3021
+ const calls = [];
3022
+ let match;
3023
+ // Helper to extract balanced JSON from a position (handles nested braces)
3024
+ const extractBalancedJson = (str, startIdx) => {
3025
+ if (str[startIdx] !== '{')
3026
+ return null;
3027
+ let braceCount = 0;
3028
+ let inString = false;
3029
+ let escapeNext = false;
3030
+ for (let i = startIdx; i < str.length; i++) {
3031
+ const char = str[i];
3032
+ if (escapeNext) {
3033
+ escapeNext = false;
3034
+ continue;
3035
+ }
3036
+ if (char === '\\') {
3037
+ escapeNext = true;
3038
+ continue;
3039
+ }
3040
+ if (char === '"') {
3041
+ inString = !inString;
3042
+ continue;
3043
+ }
3044
+ if (!inString) {
3045
+ if (char === '{')
3046
+ braceCount++;
3047
+ else if (char === '}') {
3048
+ braceCount--;
3049
+ if (braceCount === 0) {
3050
+ return str.substring(startIdx, i + 1);
3051
+ }
3052
+ }
3053
+ }
3054
+ }
3055
+ return null;
3056
+ };
3057
+ // Helper to fix common JSON issues from AI outputs
3058
+ // IMPORTANT: Don't blindly replace quotes - it breaks code content
3059
+ const fixJson = (jsonStr) => {
3060
+ // First, escape newlines and control characters
3061
+ let fixed = jsonStr
3062
+ .replace(/\r/g, '') // Remove carriage returns
3063
+ .replace(/\t/g, '\\t'); // Escape tabs
3064
+ // Escape literal newlines inside strings (but not \n which is already escaped)
3065
+ // We need to be careful - only escape newlines that are inside quoted strings
3066
+ const parts = [];
3067
+ let inString = false;
3068
+ let currentPart = '';
3069
+ for (let i = 0; i < fixed.length; i++) {
3070
+ const char = fixed[i];
3071
+ const prevChar = i > 0 ? fixed[i - 1] : '';
3072
+ if (char === '"' && prevChar !== '\\') {
3073
+ inString = !inString;
3074
+ currentPart += char;
3075
+ }
3076
+ else if (char === '\n') {
3077
+ if (inString) {
3078
+ currentPart += '\\n'; // Escape the newline
3079
+ }
3080
+ else {
3081
+ currentPart += char; // Keep as-is outside strings
3082
+ }
3083
+ }
3084
+ else {
3085
+ currentPart += char;
3086
+ }
3087
+ }
3088
+ fixed = currentPart;
3089
+ // Quote unquoted keys (only outside strings)
3090
+ fixed = fixed.replace(/([{,]\s*)(\w+)\s*:/g, '$1"$2":');
3091
+ // Remove trailing commas
3092
+ fixed = fixed.replace(/,\s*}/g, '}');
3093
+ fixed = fixed.replace(/,\s*]/g, ']');
3094
+ return fixed;
3095
+ };
3096
+ // Normalize tool name from various formats
3097
+ const normalizeToolName = (name) => {
3098
+ const normalized = name
3099
+ .replace(/^__/, '') // Remove leading underscores
3100
+ .replace(/__$/, '') // Remove trailing underscores
3101
+ .replace(/^execute_/i, '') // Remove execute_ prefix
3102
+ .replace(/_execute$/i, '') // Remove _execute suffix
3103
+ .toLowerCase();
3104
+ // Map common variations
3105
+ const toolMap = {
3106
+ 'bash': 'bash',
3107
+ 'shell': 'bash',
3108
+ 'run': 'bash',
3109
+ 'command': 'bash',
3110
+ 'list_dir': 'list_dir',
3111
+ 'list_directory': 'list_dir',
3112
+ 'ls': 'list_dir',
3113
+ 'dir': 'list_dir',
3114
+ 'read_file': 'read_file',
3115
+ 'readfile': 'read_file',
3116
+ 'read': 'read_file',
3117
+ 'write_file': 'write_file',
3118
+ 'writefile': 'write_file',
3119
+ 'write': 'write_file',
3120
+ 'edit_file': 'edit_file',
3121
+ 'editfile': 'edit_file',
3122
+ 'edit': 'edit_file',
3123
+ 'search_files': 'grep',
3124
+ 'grep': 'grep',
3125
+ 'glob': 'glob',
3126
+ 'find_files': 'grep',
3127
+ 'run_command': 'bash',
3128
+ 'syntax_check': 'syntax_check',
3129
+ };
3130
+ return toolMap[normalized] || normalized;
3131
+ };
3132
+ // Match <tool_call>...</tool_call> blocks
3133
+ const toolCallRegex = /<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/g;
3134
+ while ((match = toolCallRegex.exec(text)) !== null) {
3135
+ try {
3136
+ const fixed = fixJson(match[1]);
3137
+ const parsed = JSON.parse(fixed);
3138
+ if (parsed.tool && parsed.args) {
3139
+ parsed.tool = normalizeToolName(parsed.tool);
3140
+ calls.push(parsed);
3141
+ }
3142
+ }
3143
+ catch (e) {
3144
+ // Invalid JSON, skip
3145
+ }
3146
+ }
3147
+ // Match ```tool format
3148
+ const codeBlockRegex = /```tool\s*\n([\s\S]*?)\n```/g;
3149
+ while ((match = codeBlockRegex.exec(text)) !== null) {
3150
+ try {
3151
+ const fixed = fixJson(match[1]);
3152
+ const parsed = JSON.parse(fixed);
3153
+ if (parsed.tool && parsed.args) {
3154
+ parsed.tool = normalizeToolName(parsed.tool);
3155
+ calls.push(parsed);
3156
+ }
3157
+ }
3158
+ catch (e) {
3159
+ // Invalid JSON, skip
3160
+ }
3161
+ }
3162
+ // Match ```json blocks with tool definitions
3163
+ const jsonBlockRegex = /```(?:json)?\s*\n?([\s\S]*?"tool"[\s\S]*?)\n?```/g;
3164
+ while ((match = jsonBlockRegex.exec(text)) !== null) {
3165
+ try {
3166
+ const fixed = fixJson(match[1]);
3167
+ const parsed = JSON.parse(fixed);
3168
+ if (parsed.tool && parsed.args) {
3169
+ parsed.tool = normalizeToolName(parsed.tool);
3170
+ // Prevent duplicates
3171
+ if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
3172
+ calls.push(parsed);
3173
+ }
3174
+ }
3175
+ }
3176
+ catch (e) {
3177
+ // Invalid JSON, skip
3178
+ }
3179
+ }
3180
+ // ROBUST PARSER: Find {"tool": at any position and extract balanced JSON
3181
+ // This handles multi-line content in write_file and nested structures
3182
+ const toolMarkerRegex = /\{"tool"\s*:/g;
3183
+ while ((match = toolMarkerRegex.exec(text)) !== null) {
3184
+ const startIdx = match.index;
3185
+ const jsonStr = extractBalancedJson(text, startIdx);
3186
+ if (jsonStr) {
3187
+ try {
3188
+ const parsed = JSON.parse(jsonStr);
3189
+ if (parsed.tool && parsed.args) {
3190
+ parsed.tool = normalizeToolName(parsed.tool);
3191
+ // Prevent duplicates
3192
+ if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
3193
+ calls.push(parsed);
3194
+ }
3195
+ }
3196
+ }
3197
+ catch (e) {
3198
+ // Invalid JSON, try to fix it
3199
+ try {
3200
+ const fixed = fixJson(jsonStr);
3201
+ const parsed = JSON.parse(fixed);
3202
+ if (parsed.tool && parsed.args) {
3203
+ parsed.tool = normalizeToolName(parsed.tool);
3204
+ if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
3205
+ calls.push(parsed);
3206
+ }
3207
+ }
3208
+ }
3209
+ catch (e2) {
3210
+ // Still invalid - try more aggressive fixing for write_file
3211
+ if (jsonStr.includes('"write_file"') || jsonStr.includes('"content"')) {
3212
+ try {
3213
+ // More aggressive: escape all control characters
3214
+ const aggressiveFix = jsonStr
3215
+ .replace(/[\x00-\x1F]/g, (c) => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0'))
3216
+ .replace(/'/g, '"');
3217
+ const parsed = JSON.parse(aggressiveFix);
3218
+ if (parsed.tool && parsed.args) {
3219
+ parsed.tool = normalizeToolName(parsed.tool);
3220
+ if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
3221
+ calls.push(parsed);
3222
+ }
3223
+ }
3224
+ }
3225
+ catch (e3) {
3226
+ // Still invalid, skip
3227
+ }
3228
+ }
3229
+ }
3230
+ }
3231
+ }
3232
+ }
3233
+ // Match inline JSON with "tool" key (various formats - tool before args)
3234
+ const inlineToolRegex = /\{[^{}]*"?tool"?\s*:\s*["']?([^"',}]+)["']?[^{}]*"?args"?\s*:\s*\{([^{}]*)\}[^{}]*\}/gi;
3235
+ while ((match = inlineToolRegex.exec(text)) !== null) {
3236
+ try {
3237
+ const fixed = fixJson(match[0]);
3238
+ const parsed = JSON.parse(fixed);
3239
+ if (parsed.tool && parsed.args) {
3240
+ parsed.tool = normalizeToolName(parsed.tool);
3241
+ if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
3242
+ calls.push(parsed);
3243
+ }
3244
+ }
3245
+ }
3246
+ catch (e) {
3247
+ // Invalid JSON, skip
3248
+ }
3249
+ }
3250
+ // Match inline JSON with "args" BEFORE "tool" (handles reversed order from some AI models)
3251
+ const inlineArgsFirstRegex = /\{[^{}]*"?args"?\s*:\s*\{([^{}]*)\}[^{}]*"?tool"?\s*:\s*["']?([^"',}]+)["']?[^{}]*\}/gi;
3252
+ while ((match = inlineArgsFirstRegex.exec(text)) !== null) {
3253
+ try {
3254
+ const fixed = fixJson(match[0]);
3255
+ const parsed = JSON.parse(fixed);
3256
+ if (parsed.tool && parsed.args) {
3257
+ parsed.tool = normalizeToolName(parsed.tool);
3258
+ if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
3259
+ calls.push(parsed);
3260
+ }
3261
+ }
3262
+ }
3263
+ catch (e) {
3264
+ // Invalid JSON, skip
3265
+ }
3266
+ }
3267
+ // Universal: Try to find any JSON object with both "tool" and "args" keys
3268
+ const universalJsonRegex = /\{[^{}]*(?:"tool"|"args")[^{}]*(?:"tool"|"args")[^{}]*\}/gi;
3269
+ while ((match = universalJsonRegex.exec(text)) !== null) {
3270
+ try {
3271
+ const fixed = fixJson(match[0]);
3272
+ const parsed = JSON.parse(fixed);
3273
+ if (parsed.tool && parsed.args) {
3274
+ parsed.tool = normalizeToolName(parsed.tool);
3275
+ if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
3276
+ calls.push(parsed);
3277
+ }
3278
+ }
3279
+ }
3280
+ catch (e) {
3281
+ // Invalid JSON, skip
3282
+ }
3283
+ }
3284
+ // Fallback: Try to parse each line as JSON (for plain JSON output without code blocks)
3285
+ // This handles cases where AI outputs just: {"args": {...}, "tool": "..."}
3286
+ const lines = text.split('\n');
3287
+ for (const line of lines) {
3288
+ const trimmed = line.trim();
3289
+ if (trimmed.startsWith('{') && trimmed.includes('"tool"') && trimmed.includes('"args"')) {
3290
+ try {
3291
+ // Try to find balanced braces
3292
+ let braceCount = 0;
3293
+ let startIdx = -1;
3294
+ let endIdx = -1;
3295
+ for (let i = 0; i < trimmed.length; i++) {
3296
+ if (trimmed[i] === '{') {
3297
+ if (startIdx === -1)
3298
+ startIdx = i;
3299
+ braceCount++;
3300
+ }
3301
+ else if (trimmed[i] === '}') {
3302
+ braceCount--;
3303
+ if (braceCount === 0 && startIdx !== -1) {
3304
+ endIdx = i + 1;
3305
+ break;
3306
+ }
3307
+ }
3308
+ }
3309
+ if (startIdx !== -1 && endIdx !== -1) {
3310
+ const jsonStr = trimmed.substring(startIdx, endIdx);
3311
+ const fixed = fixJson(jsonStr);
3312
+ const parsed = JSON.parse(fixed);
3313
+ if (parsed.tool && parsed.args) {
3314
+ parsed.tool = normalizeToolName(parsed.tool);
3315
+ if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
3316
+ calls.push(parsed);
3317
+ }
3318
+ }
3319
+ }
3320
+ }
3321
+ catch (e) {
3322
+ // Invalid JSON, skip
3323
+ }
3324
+ }
3325
+ }
3326
+ // Parse Vigthoria V2 format: {"tool": "__BASH__", ...}
3327
+ const vigV2Regex = /"?tool"?\s*:\s*["']__?([A-Za-z_]+)__?["']/gi;
3328
+ while ((match = vigV2Regex.exec(text)) !== null) {
3329
+ try {
3330
+ const toolName = normalizeToolName(match[1]);
3331
+ // Extract args from nearby context
3332
+ const pathMatch = text.match(/"?(?:arg_)?path"?\s*:\s*["']([^"']+)["']/i);
3333
+ const cmdMatch = text.match(/"?command"?\s*:\s*(?:["']([^"']+)["']|\[\s*["']([^"']+)["']\s*\])/i);
3334
+ const contentMatch = text.match(/"?content"?\s*:\s*["']([^"']+)["']/i);
3335
+ const args = {};
3336
+ if (pathMatch)
3337
+ args.path = pathMatch[1];
3338
+ if (cmdMatch)
3339
+ args.command = cmdMatch[1] || cmdMatch[2];
3340
+ if (contentMatch)
3341
+ args.content = contentMatch[1];
3342
+ if (Object.keys(args).length > 0) {
3343
+ // Prevent duplicates
3344
+ if (!calls.some(c => c.tool === toolName && JSON.stringify(c.args) === JSON.stringify(args))) {
3345
+ calls.push({ tool: toolName, args });
3346
+ }
3347
+ }
3348
+ }
3349
+ catch (e) {
3350
+ // Skip
3351
+ }
3352
+ }
3353
+ return calls;
3354
+ }
3355
+ /**
3356
+ * Get tools formatted for AI system prompt
3357
+ */
3358
+ static getToolsForPrompt() {
3359
+ const tools = AgenticTools.getToolDefinitions();
3360
+ let prompt = `## AGENT MODE - YOU MUST USE TOOLS
3361
+
3362
+ ⚠️ CRITICAL: You are in Agent Mode. You MUST use tools to interact with files and the system.
3363
+ DO NOT guess or hallucinate file contents. DO NOT make up directory structures.
3364
+ ALWAYS use read_file before discussing what's in a file.
3365
+ ALWAYS use list_dir before discussing what's in a directory.
3366
+ DO NOT ask the user to pick between actions you can already perform.
3367
+ WHEN A FILE IS BROKEN, INCOMPLETE, OR TRUNCATED: inspect it fully, fix it directly, and return the completed result.
3368
+ NEVER write placeholders like "rest of CSS", "implementation goes here", or incomplete HTML/JS fragments.
3369
+ IF STRUCTURE IS BROKEN: prefer rewriting the full file with write_file after reading enough context.
3370
+
3371
+ You have access to these tools:
3372
+
3373
+ `;
3374
+ for (const tool of tools) {
3375
+ prompt += `## ${tool.name}
3376
+ ${tool.description}
3377
+ Parameters:
3378
+ ${tool.parameters.map(p => ` - ${p.name}${p.required ? ' (required)' : ''}: ${p.description}`).join('\n')}
3379
+
3380
+ `;
3381
+ }
3382
+ prompt += `
3383
+ ## How to Use Tools
3384
+
3385
+ To use a tool, output a JSON block in a code fence with "tool" language:
3386
+
3387
+ \`\`\`tool
3388
+ {"tool": "tool_name", "args": {"param1": "value1"}}
3389
+ \`\`\`
3390
+
3391
+ ## MANDATORY TOOL USAGE (DO NOT SKIP!)
3392
+
3393
+ **When user asks "what's in this folder/directory":**
3394
+ → FIRST use list_dir, THEN respond based on actual results
3395
+
3396
+ **When user asks "can you see/read/show me file X":**
3397
+ → FIRST use read_file, THEN respond based on actual contents
3398
+
3399
+ **When user mentions a path like "C:\\some\\path" or "/some/path":**
3400
+ → FIRST use list_dir to check if it exists, THEN respond
3401
+
3402
+ **NEVER say things like "Here's an overview of the contents..." without first using tools!**
3403
+ **NEVER describe files or code you haven't actually read with read_file!**
3404
+
3405
+ ### Examples:
3406
+
3407
+ 1. List directory contents:
3408
+ \`\`\`tool
3409
+ {"tool": "list_dir", "args": {"path": "."}}
3410
+ \`\`\`
3411
+
3412
+ 2. Read a file:
3413
+ \`\`\`tool
3414
+ {"tool": "read_file", "args": {"path": "src/index.js"}}
3415
+ \`\`\`
3416
+
3417
+ 3. Fetch a web page (full HTML):
3418
+ \`\`\`tool
3419
+ {"tool": "fetch_url", "args": {"url": "https://example.com"}}
3420
+ \`\`\`
3421
+
3422
+ 4. Fetch specific content with selectors:
3423
+ \`\`\`tool
3424
+ {"tool": "fetch_url", "args": {"url": "https://example.com", "selector": "h1, h2, h3"}}
3425
+ \`\`\`
3426
+ Available selectors: title, body, text, links, nav, footer, images, h1, h2, h3, h1/h2/h3 (compound)
3427
+
3428
+ 5. Run command on YOUR configured SSH server (requires user SSH setup, NOT Vigthoria servers):
3429
+ \`\`\`tool
3430
+ {"tool": "ssh_exec", "args": {"command": "curl -s https://example.com | head -20", "host": "your-server"}}
3431
+ \`\`\`
3432
+ Note: ssh_exec is for users who have their own servers configured. It does NOT connect to Vigthoria infrastructure.
3433
+
3434
+ 6. Write a file:
3435
+ \`\`\`tool
3436
+ {"tool": "write_file", "args": {"path": "hello.py", "content": "print('Hello World')"}}
3437
+ \`\`\`
3438
+
3439
+ ## CRITICAL RULES:
3440
+
3441
+ ### ABSOLUTELY NO HALLUCINATION (READ THIS CAREFULLY):
3442
+ - ONLY use information from tool results you just received in THIS conversation
3443
+ - DO NOT make up names, organizations, or content that wasn't in the fetched data
3444
+ - DO NOT read random files from the workspace expecting them to contain relevant data
3445
+ - If you fetch a website, your analysis MUST be based ONLY on what you just fetched
3446
+ - If the user asks about websites A and B, ONLY discuss A and B - don't invent Site C
3447
+ - NEVER create fictional organizations, services, or content
3448
+ - If you're unsure about something, say "Based on the fetched content, I can see..." not "This organization does..."
3449
+
3450
+ ### Strategic Planning (VERY IMPORTANT):
3451
+ - PLAN before acting - don't issue many redundant tool calls
3452
+ - For web comparisons: Fetch each URL ONCE with no selector to get full HTML, then analyze locally
3453
+ - Do NOT fetch the same URL multiple times with different selectors - fetch once and parse the result
3454
+ - Think step-by-step: 1) Gather data, 2) Analyze it, 3) Present findings
3455
+ - If comparing two things, fetch both ONCE, then write a REAL comparison with specific differences
3456
+ - Maximum 2-4 tool calls per step is usually enough - don't spam 10+ calls at once
3457
+ - Do NOT use list_dir or read_file when the task is about fetching websites - those are for LOCAL files only
3458
+
3459
+ ### Cross-Platform Compatibility:
3460
+ - On Windows, Unix commands (head, tail, grep, awk, sed, wc) are NOT available
3461
+ - Use \`fetch_url\` for web requests instead of curl|grep
3462
+ - Use \`ssh_exec\` to run Unix commands on the Vigthoria server if needed
3463
+ - Use \`read_file\` instead of cat
3464
+ - Use \`list_dir\` instead of ls
3465
+
3466
+ ### Handling Tool Failures:
3467
+ - If a tool fails, REPORT the failure honestly to the user
3468
+ - NEVER make up or hallucinate content when a tool fails
3469
+ - If you cannot access a URL, say "I was unable to fetch the URL because..."
3470
+ - If a command fails, explain what happened and suggest alternatives
3471
+ - Do NOT write analysis or comparison reports if you couldn't gather the actual data
3472
+
3473
+ ### Comparison Tasks:
3474
+ - When asked to compare websites/files, you MUST produce actual specific differences
3475
+ - Don't just describe each site separately - show what Site A has that Site B is missing
3476
+ - Use concrete examples: "Site A has a Team page at /team.html, Site B does not"
3477
+ - If you need sub-pages, fetch them in follow-up steps after analyzing the main page
3478
+ - BASE YOUR COMPARISON ONLY ON THE DATA YOU FETCHED - not on random files in the workspace
3479
+ - Quote actual text from the fetched content to support your claims
3480
+
3481
+ ### File Access:
3482
+ - You can ONLY access files within the current project workspace
3483
+ - Use relative paths (e.g., "src/file.js", "app.py", "./config.json")
3484
+ - Never try to access system files or directories outside the workspace
3485
+ - Do NOT read files unrelated to the user's request (e.g., don't read "comparison.md" when asked to fetch websites)
3486
+ - When comparing WEBSITES, use fetch_url - do NOT use read_file or list_dir
3487
+
3488
+ ### Tool Names:
3489
+ - Use ONLY these exact tool names: list_dir, read_file, write_file, edit_file, bash, grep, glob, git, repo, fetch_url, ssh_exec, task, multi_edit, codebase_search
3490
+ - The JSON must be valid with double quotes for all keys and string values
3491
+ - After tool execution, you will receive results and can continue with the next step
3492
+ - Explain what you're doing before using tools
3493
+
3494
+ ### Sub-Agent Delegation (task tool):
3495
+ - Use the task tool to delegate complex subtasks to an independent sub-agent
3496
+ - The sub-agent has its own tools and context, runs autonomously, and returns results
3497
+ - Great for: parallel research, investigating side questions, exploring unfamiliar code
3498
+ - Example:
3499
+ \`\`\`tool
3500
+ {"tool": "task", "args": {"description": "Find all API endpoints in the backend and list their HTTP methods and paths"}}
3501
+ \`\`\`
3502
+
3503
+ ### Atomic Multi-File Edits (multi_edit tool):
3504
+ - Use multi_edit to apply multiple edits atomically - all succeed or all roll back
3505
+ - Pass edits as a JSON array in the edits parameter
3506
+ - Example:
3507
+ \`\`\`tool
3508
+ {"tool": "multi_edit", "args": {"edits": "[{\\"path\\": \\"src/config.ts\\", \\"old_text\\": \\"port: 3000\\", \\"new_text\\": \\"port: 8080\\"}, {\\"path\\": \\"src/server.ts\\", \\"old_text\\": \\"listen(3000)\\", \\"new_text\\": \\"listen(8080)\\"}]"}}
3509
+ \`\`\`
3510
+
3511
+ ### Deep Codebase Search (codebase_search tool):
3512
+ - Use codebase_search for large projects to find symbols, files, or content across the ENTIRE codebase
3513
+ - Not limited by workspace snapshot - searches all files recursively
3514
+ - Scopes: "symbols" (functions/classes), "files" (filenames), "content" (full-text), "all" (default)
3515
+ - Example:
3516
+ \`\`\`tool
3517
+ {"tool": "codebase_search", "args": {"query": "handleAuthentication", "scope": "symbols"}}
3518
+ \`\`\`
3519
+ `;
3520
+ return prompt;
3521
+ }
3522
+ }