vigthoria-cli 1.10.47 → 1.10.49

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