vigthoria-cli 1.6.1 → 1.6.4

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 (46) hide show
  1. package/README.md +52 -1
  2. package/dist/commands/chat.d.ts +31 -45
  3. package/dist/commands/chat.d.ts.map +1 -1
  4. package/dist/commands/chat.js +374 -855
  5. package/dist/commands/chat.js.map +1 -1
  6. package/dist/commands/repo.d.ts +10 -0
  7. package/dist/commands/repo.d.ts.map +1 -1
  8. package/dist/commands/repo.js +215 -97
  9. package/dist/commands/repo.js.map +1 -1
  10. package/dist/index.js +32 -4
  11. package/dist/index.js.map +1 -1
  12. package/dist/utils/api.d.ts +8 -0
  13. package/dist/utils/api.d.ts.map +1 -1
  14. package/dist/utils/api.js +183 -42
  15. package/dist/utils/api.js.map +1 -1
  16. package/dist/utils/config.d.ts.map +1 -1
  17. package/dist/utils/config.js +2 -1
  18. package/dist/utils/config.js.map +1 -1
  19. package/dist/utils/tools.d.ts +3 -0
  20. package/dist/utils/tools.d.ts.map +1 -1
  21. package/dist/utils/tools.js +252 -14
  22. package/dist/utils/tools.js.map +1 -1
  23. package/package.json +13 -2
  24. package/install.ps1 +0 -290
  25. package/install.sh +0 -307
  26. package/src/commands/auth.ts +0 -226
  27. package/src/commands/chat.ts +0 -1101
  28. package/src/commands/config.ts +0 -306
  29. package/src/commands/deploy.ts +0 -609
  30. package/src/commands/edit.ts +0 -310
  31. package/src/commands/explain.ts +0 -115
  32. package/src/commands/generate.ts +0 -222
  33. package/src/commands/hub.ts +0 -382
  34. package/src/commands/repo.ts +0 -742
  35. package/src/commands/review.ts +0 -186
  36. package/src/index.ts +0 -601
  37. package/src/types/marked-terminal.d.ts +0 -31
  38. package/src/utils/api.ts +0 -526
  39. package/src/utils/config.ts +0 -241
  40. package/src/utils/files.ts +0 -273
  41. package/src/utils/logger.ts +0 -130
  42. package/src/utils/session.ts +0 -179
  43. package/src/utils/tools.ts +0 -1964
  44. package/test-parse.js +0 -105
  45. package/test-parse2.js +0 -35
  46. package/tsconfig.json +0 -20
@@ -1,1964 +0,0 @@
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
-
17
- import * as fs from 'fs';
18
- import * as path from 'path';
19
- import { execSync, spawn } from 'child_process';
20
- import chalk from 'chalk';
21
- import { Logger } from './logger.js';
22
-
23
- // Risk levels for operations
24
- export type RiskLevel = 'low' | 'medium' | 'high' | 'critical';
25
-
26
- export interface ToolResult {
27
- success: boolean;
28
- output?: string;
29
- error?: string;
30
- suggestion?: string; // Actionable suggestion for errors
31
- canRetry?: boolean; // Whether operation can be retried
32
- undoable?: boolean; // Whether operation can be undone
33
- metadata?: { // Additional tool-specific data
34
- [key: string]: any;
35
- };
36
- }
37
-
38
- export interface ToolCall {
39
- tool: string;
40
- args: Record<string, string>;
41
- }
42
-
43
- export interface ToolDefinition {
44
- name: string;
45
- description: string;
46
- parameters: {
47
- name: string;
48
- description: string;
49
- required: boolean;
50
- }[];
51
- requiresPermission: boolean;
52
- dangerous: boolean;
53
- riskLevel: RiskLevel; // NEW: Risk classification
54
- category: 'read' | 'write' | 'execute' | 'search'; // NEW: Tool category
55
- }
56
-
57
- // Undo operation tracking
58
- interface UndoOperation {
59
- id: string;
60
- tool: string;
61
- timestamp: number;
62
- filePath?: string;
63
- originalContent?: string | null; // null means file was created (delete on undo)
64
- description: string;
65
- }
66
-
67
- // Error types for better handling
68
- export enum ToolErrorType {
69
- FILE_NOT_FOUND = 'FILE_NOT_FOUND',
70
- PERMISSION_DENIED = 'PERMISSION_DENIED',
71
- NETWORK_ERROR = 'NETWORK_ERROR',
72
- TIMEOUT = 'TIMEOUT',
73
- INVALID_ARGS = 'INVALID_ARGS',
74
- EXECUTION_FAILED = 'EXECUTION_FAILED',
75
- USER_CANCELLED = 'USER_CANCELLED',
76
- }
77
-
78
- export class AgenticTools {
79
- private logger: Logger;
80
- private cwd: string;
81
- private permissionCallback: (action: string, options?: { batchApproval?: boolean }) => Promise<boolean | 'batch'>;
82
- private autoApprove: boolean;
83
- private undoStack: UndoOperation[] = [];
84
- private maxUndoStack: number = 50;
85
- private retryConfig = {
86
- maxRetries: 3,
87
- baseDelayMs: 1000,
88
- maxDelayMs: 10000,
89
- retryableErrors: ['ECONNRESET', 'ETIMEDOUT', 'ENOTFOUND', 'ECONNREFUSED', 'EAI_AGAIN'],
90
- };
91
-
92
- // Session-based tool approvals - remembers which tools user approved for this turn
93
- private sessionApprovedTools: Set<string> = new Set();
94
-
95
- constructor(
96
- logger: Logger,
97
- cwd: string,
98
- permissionCallback: (action: string, options?: { batchApproval?: boolean }) => Promise<boolean | 'batch'>,
99
- autoApprove: boolean = false
100
- ) {
101
- this.logger = logger;
102
- this.cwd = cwd;
103
- this.permissionCallback = permissionCallback;
104
- this.autoApprove = autoApprove;
105
- }
106
-
107
- /**
108
- * Clear session-approved tools (call this at the start of each new AI turn)
109
- */
110
- clearSessionApprovals(): void {
111
- this.sessionApprovedTools.clear();
112
- }
113
-
114
- /**
115
- * Get currently approved tools for this session
116
- */
117
- getSessionApprovedTools(): string[] {
118
- return Array.from(this.sessionApprovedTools);
119
- }
120
-
121
- /**
122
- * Get the undo stack for inspection
123
- */
124
- getUndoStack(): UndoOperation[] {
125
- return [...this.undoStack];
126
- }
127
-
128
- /**
129
- * Undo the last file operation
130
- */
131
- async undo(): Promise<ToolResult> {
132
- const lastOp = this.undoStack.pop();
133
-
134
- if (!lastOp) {
135
- return {
136
- success: false,
137
- error: 'Nothing to undo',
138
- suggestion: 'The undo stack is empty. Only file write/edit operations can be undone.',
139
- };
140
- }
141
-
142
- if (lastOp.filePath) {
143
- try {
144
- if (lastOp.originalContent === null) {
145
- // File was created, so delete it
146
- if (fs.existsSync(lastOp.filePath)) {
147
- fs.unlinkSync(lastOp.filePath);
148
- return {
149
- success: true,
150
- output: `✓ Undone: ${lastOp.description}\n File deleted: ${lastOp.filePath}`,
151
- metadata: { remainingUndos: this.undoStack.length },
152
- };
153
- }
154
- } else if (lastOp.originalContent !== undefined) {
155
- // Restore original content
156
- fs.writeFileSync(lastOp.filePath, lastOp.originalContent, 'utf-8');
157
- return {
158
- success: true,
159
- output: `✓ Undone: ${lastOp.description}\n File restored: ${lastOp.filePath}`,
160
- metadata: { remainingUndos: this.undoStack.length },
161
- };
162
- }
163
- } catch (error) {
164
- return {
165
- success: false,
166
- error: `Failed to undo: ${(error as Error).message}`,
167
- suggestion: 'The file may have been moved or permissions changed.',
168
- };
169
- }
170
- }
171
-
172
- return {
173
- success: false,
174
- error: 'This operation cannot be undone',
175
- };
176
- }
177
-
178
- /**
179
- * List of available tools - Vigthoria's advanced
180
- * Enhanced with risk levels and categories
181
- */
182
- static getToolDefinitions(): ToolDefinition[] {
183
- return [
184
- {
185
- name: 'read_file',
186
- description: 'Read the contents of a file',
187
- parameters: [
188
- { name: 'path', description: 'File path (relative or absolute)', required: true },
189
- { name: 'start_line', description: 'Start line (1-indexed)', required: false },
190
- { name: 'end_line', description: 'End line (1-indexed)', required: false },
191
- ],
192
- requiresPermission: false,
193
- dangerous: false,
194
- riskLevel: 'low',
195
- category: 'read',
196
- },
197
- {
198
- name: 'write_file',
199
- description: 'Write content to a file (creates if not exists)',
200
- parameters: [
201
- { name: 'path', description: 'File path', required: true },
202
- { name: 'content', description: 'Content to write', required: true },
203
- ],
204
- requiresPermission: true,
205
- dangerous: false,
206
- riskLevel: 'medium',
207
- category: 'write',
208
- },
209
- {
210
- name: 'edit_file',
211
- description: 'Make specific edits to a file by replacing text',
212
- parameters: [
213
- { name: 'path', description: 'File path', required: true },
214
- { name: 'old_text', description: 'Text to replace', required: true },
215
- { name: 'new_text', description: 'New text', required: true },
216
- ],
217
- requiresPermission: true,
218
- dangerous: false,
219
- riskLevel: 'medium',
220
- category: 'write',
221
- },
222
- {
223
- name: 'bash',
224
- description: 'Run a shell command',
225
- parameters: [
226
- { name: 'command', description: 'Shell command to execute', required: true },
227
- { name: 'cwd', description: 'Working directory', required: false },
228
- { name: 'timeout', description: 'Timeout in seconds', required: false },
229
- ],
230
- requiresPermission: true,
231
- dangerous: true,
232
- riskLevel: 'high',
233
- category: 'execute',
234
- },
235
- {
236
- name: 'grep',
237
- description: 'Search for patterns in files',
238
- parameters: [
239
- { name: 'pattern', description: 'Search pattern (regex)', required: true },
240
- { name: 'path', description: 'File or directory path', required: false },
241
- { name: 'include', description: 'File pattern to include (e.g., *.ts)', required: false },
242
- ],
243
- requiresPermission: false,
244
- dangerous: false,
245
- riskLevel: 'low',
246
- category: 'search',
247
- },
248
- {
249
- name: 'list_dir',
250
- description: 'List contents of a directory',
251
- parameters: [
252
- { name: 'path', description: 'Directory path', required: true },
253
- { name: 'recursive', description: 'List recursively', required: false },
254
- ],
255
- requiresPermission: false,
256
- dangerous: false,
257
- riskLevel: 'low',
258
- category: 'read',
259
- },
260
- {
261
- name: 'glob',
262
- description: 'Find files matching a pattern',
263
- parameters: [
264
- { name: 'pattern', description: 'Glob pattern (e.g., **/*.ts)', required: true },
265
- ],
266
- requiresPermission: false,
267
- dangerous: false,
268
- riskLevel: 'low',
269
- category: 'search',
270
- },
271
- {
272
- name: 'git',
273
- description: 'Run git commands',
274
- parameters: [
275
- { name: 'args', description: 'Git command arguments', required: true },
276
- ],
277
- requiresPermission: true,
278
- dangerous: false,
279
- riskLevel: 'medium',
280
- category: 'execute',
281
- },
282
- {
283
- name: 'repo',
284
- description: 'Manage projects in Vigthoria Repository - push, pull, list, share, delete, or clone projects',
285
- parameters: [
286
- { name: 'action', description: 'Action: push, pull, list, status, share, delete, clone', required: true },
287
- { name: 'project', description: 'Project name (for push/pull/status/share/delete)', required: false },
288
- { name: 'visibility', description: 'Visibility: public or private (for push)', required: false },
289
- { name: 'path', description: 'Directory path (for push) or target path (for clone)', required: false },
290
- { name: 'username', description: 'Username to share with (for share action)', required: false },
291
- { name: 'permission', description: 'Permission level: read, write, admin (for share action)', required: false },
292
- ],
293
- requiresPermission: true,
294
- dangerous: false,
295
- riskLevel: 'medium',
296
- category: 'execute',
297
- },
298
- {
299
- name: 'fetch_url',
300
- description: 'Fetch content from a URL (web page, API endpoint). Works cross-platform on Windows, Mac, and Linux.',
301
- parameters: [
302
- { name: 'url', description: 'URL to fetch (must be http or https)', required: true },
303
- { name: 'method', description: 'HTTP method (GET, POST, etc.)', required: false },
304
- { name: 'headers', description: 'JSON string of headers to send', required: false },
305
- { name: 'body', description: 'Request body for POST/PUT requests', required: false },
306
- { name: 'selector', description: 'CSS selector to extract specific content (for HTML)', required: false },
307
- ],
308
- requiresPermission: true,
309
- dangerous: false,
310
- riskLevel: 'low',
311
- category: 'read',
312
- },
313
- {
314
- name: 'ssh_exec',
315
- description: 'Execute a command on a remote server via SSH (useful for Unix commands from Windows)',
316
- parameters: [
317
- { name: 'command', description: 'Command to execute on remote server', required: true },
318
- { name: 'host', description: 'SSH host (default: vigthoria-server)', required: false },
319
- { name: 'timeout', description: 'Timeout in seconds', required: false },
320
- ],
321
- requiresPermission: true,
322
- dangerous: true,
323
- riskLevel: 'high',
324
- category: 'execute',
325
- },
326
- ];
327
- }
328
-
329
- /**
330
- * Execute a tool call with enhanced error handling and retry logic
331
- */
332
- async execute(call: ToolCall): Promise<ToolResult> {
333
- const tool = AgenticTools.getToolDefinitions().find(t => t.name === call.tool);
334
-
335
- if (!tool) {
336
- return this.createErrorResult(
337
- ToolErrorType.INVALID_ARGS,
338
- `Unknown tool: ${call.tool}`,
339
- `Available tools: ${AgenticTools.getToolDefinitions().map(t => t.name).join(', ')}`
340
- );
341
- }
342
-
343
- // Validate required parameters
344
- const validationError = this.validateParameters(call, tool);
345
- if (validationError) {
346
- return validationError;
347
- }
348
-
349
- // Check permission for dangerous/modifying actions
350
- if (tool.requiresPermission && !this.autoApprove) {
351
- // Check if this tool was already approved for this session/turn
352
- if (this.sessionApprovedTools.has(call.tool)) {
353
- // Already approved - skip permission prompt
354
- this.logger.info(`${call.tool}: Auto-approved (batch)`);
355
- } else {
356
- const approved = await this.permissionCallback(
357
- this.formatPermissionRequest(call, tool),
358
- { batchApproval: true }
359
- );
360
-
361
- if (approved === false) {
362
- return {
363
- success: false,
364
- error: 'Permission denied by user',
365
- canRetry: true,
366
- };
367
- }
368
-
369
- // Only add to session approvals if user chose 'batch' (typed 'a')
370
- // 'y' or 'yes' only approves this single request
371
- if (approved === 'batch') {
372
- this.sessionApprovedTools.add(call.tool);
373
- }
374
- }
375
- }
376
-
377
- // Execute with retry logic for applicable operations
378
- return this.executeWithRetry(call, tool);
379
- }
380
-
381
- /**
382
- * Execute tool with automatic retry for transient failures
383
- */
384
- private async executeWithRetry(call: ToolCall, tool: ToolDefinition): Promise<ToolResult> {
385
- let lastError: ToolResult | null = null;
386
-
387
- for (let attempt = 0; attempt <= this.retryConfig.maxRetries; attempt++) {
388
- try {
389
- const result = await this.executeTool(call);
390
-
391
- if (result.success) {
392
- return result;
393
- }
394
-
395
- // Check if error is retryable
396
- const isRetryable = result.canRetry !== false &&
397
- this.isRetryableError(result.error || '');
398
-
399
- if (!isRetryable || attempt === this.retryConfig.maxRetries) {
400
- return result;
401
- }
402
-
403
- lastError = result;
404
-
405
- // Calculate delay with exponential backoff
406
- const delay = Math.min(
407
- this.retryConfig.baseDelayMs * Math.pow(2, attempt),
408
- this.retryConfig.maxDelayMs
409
- );
410
-
411
- this.logger.warn(`Retrying ${call.tool} in ${delay}ms (attempt ${attempt + 2}/${this.retryConfig.maxRetries + 1})...`);
412
- await this.sleep(delay);
413
-
414
- } catch (error) {
415
- lastError = this.createErrorResult(
416
- ToolErrorType.EXECUTION_FAILED,
417
- (error as Error).message
418
- );
419
-
420
- if (attempt === this.retryConfig.maxRetries) {
421
- return lastError;
422
- }
423
- }
424
- }
425
-
426
- return lastError || this.createErrorResult(
427
- ToolErrorType.EXECUTION_FAILED,
428
- 'Unknown error after retries'
429
- );
430
- }
431
-
432
- /**
433
- * Execute the actual tool operation
434
- */
435
- private async executeTool(call: ToolCall): Promise<ToolResult> {
436
- switch (call.tool) {
437
- case 'read_file':
438
- return this.readFile(call.args);
439
- case 'write_file':
440
- return this.writeFile(call.args);
441
- case 'edit_file':
442
- return this.editFile(call.args);
443
- case 'bash':
444
- return this.bash(call.args);
445
- case 'grep':
446
- return this.grep(call.args);
447
- case 'list_dir':
448
- return this.listDir(call.args);
449
- case 'glob':
450
- return this.glob(call.args);
451
- case 'git':
452
- return this.git(call.args);
453
- case 'repo':
454
- return this.repo(call.args);
455
- case 'fetch_url':
456
- return this.fetchUrl(call.args);
457
- case 'ssh_exec':
458
- return this.sshExec(call.args);
459
- default:
460
- return this.createErrorResult(
461
- ToolErrorType.INVALID_ARGS,
462
- `Tool not implemented: ${call.tool}`
463
- );
464
- }
465
- }
466
-
467
- /**
468
- * Check if an error is retryable
469
- */
470
- private isRetryableError(error: string): boolean {
471
- return this.retryConfig.retryableErrors.some(e => error.includes(e));
472
- }
473
-
474
- /**
475
- * Validate tool parameters
476
- */
477
- private validateParameters(call: ToolCall, tool: ToolDefinition): ToolResult | null {
478
- for (const param of tool.parameters) {
479
- if (param.required && !call.args[param.name]) {
480
- return this.createErrorResult(
481
- ToolErrorType.INVALID_ARGS,
482
- `Missing required parameter: ${param.name}`,
483
- `The ${call.tool} tool requires the '${param.name}' parameter. ${param.description}`
484
- );
485
- }
486
- }
487
- return null;
488
- }
489
-
490
- /**
491
- * Create a standardized error result
492
- */
493
- private createErrorResult(
494
- type: ToolErrorType,
495
- message: string,
496
- suggestion?: string
497
- ): ToolResult {
498
- const suggestions: Record<ToolErrorType, string> = {
499
- [ToolErrorType.FILE_NOT_FOUND]: 'Check if the file path is correct. Use list_dir to see available files.',
500
- [ToolErrorType.PERMISSION_DENIED]: 'You may need elevated permissions. Try using sudo or check file ownership.',
501
- [ToolErrorType.NETWORK_ERROR]: 'Check your internet connection. The operation will retry automatically.',
502
- [ToolErrorType.TIMEOUT]: 'The operation took too long. Try with a shorter timeout or simpler command.',
503
- [ToolErrorType.INVALID_ARGS]: 'Check the tool documentation for correct parameter usage.',
504
- [ToolErrorType.EXECUTION_FAILED]: 'Review the command syntax and try again.',
505
- [ToolErrorType.USER_CANCELLED]: 'Operation cancelled. You can retry if needed.',
506
- };
507
-
508
- return {
509
- success: false,
510
- error: message,
511
- suggestion: suggestion || suggestions[type],
512
- canRetry: type !== ToolErrorType.USER_CANCELLED && type !== ToolErrorType.INVALID_ARGS,
513
- };
514
- }
515
-
516
- /**
517
- * Enhanced permission request with risk visualization
518
- */
519
- private formatPermissionRequest(call: ToolCall, tool: ToolDefinition): string {
520
- const riskColors: Record<RiskLevel, (text: string) => string> = {
521
- low: chalk.green,
522
- medium: chalk.yellow,
523
- high: chalk.red,
524
- critical: chalk.bgRed.white,
525
- };
526
-
527
- const riskIcons: Record<RiskLevel, string> = {
528
- low: '🟢',
529
- medium: '🟡',
530
- high: '🔴',
531
- critical: '⛔',
532
- };
533
-
534
- const riskColor = riskColors[tool.riskLevel];
535
- const riskIcon = riskIcons[tool.riskLevel];
536
-
537
- let msg = `\n${riskIcon} ${riskColor(`${tool.riskLevel.toUpperCase()} RISK`)} - AI wants to use ${chalk.cyan.bold(call.tool)}\n`;
538
- msg += chalk.gray('─'.repeat(50)) + '\n';
539
-
540
- // Tool-specific details
541
- if (call.tool === 'bash') {
542
- msg += `${chalk.gray('├─')} ${chalk.white('Command:')} ${chalk.yellow(call.args.command)}\n`;
543
- if (call.args.cwd) {
544
- msg += `${chalk.gray('├─')} ${chalk.white('Directory:')} ${call.args.cwd}\n`;
545
- }
546
- msg += `${chalk.gray('├─')} ${chalk.white('Timeout:')} ${call.args.timeout || '30'}s\n`;
547
- } else if (call.tool === 'write_file') {
548
- msg += `${chalk.gray('├─')} ${chalk.white('File:')} ${chalk.cyan(call.args.path)}\n`;
549
- const preview = call.args.content.substring(0, 100);
550
- msg += `${chalk.gray('├─')} ${chalk.white('Content preview:')} ${chalk.gray(preview)}${call.args.content.length > 100 ? '...' : ''}\n`;
551
- msg += `${chalk.gray('├─')} ${chalk.white('Size:')} ${call.args.content.length} bytes\n`;
552
- } else if (call.tool === 'edit_file') {
553
- msg += `${chalk.gray('├─')} ${chalk.white('File:')} ${chalk.cyan(call.args.path)}\n`;
554
- msg += `${chalk.gray('├─')} ${chalk.white('Replace:')} ${chalk.red(call.args.old_text.substring(0, 50))}${call.args.old_text.length > 50 ? '...' : ''}\n`;
555
- msg += `${chalk.gray('├─')} ${chalk.white('With:')} ${chalk.green(call.args.new_text.substring(0, 50))}${call.args.new_text.length > 50 ? '...' : ''}\n`;
556
- } else if (call.tool === 'git') {
557
- msg += `${chalk.gray('├─')} ${chalk.white('Command:')} git ${chalk.yellow(call.args.args)}\n`;
558
- }
559
-
560
- // Safety info
561
- msg += chalk.gray('─'.repeat(50)) + '\n';
562
-
563
- const canUndo = ['write_file', 'edit_file'].includes(call.tool);
564
- msg += `${chalk.gray('├─')} ${chalk.white('Undo:')} ${canUndo ? chalk.green('✓ Available (use /undo)') : chalk.gray('✗ Not available')}\n`;
565
- msg += `${chalk.gray('└─')} ${chalk.white('Category:')} ${tool.category}\n`;
566
-
567
- if (tool.dangerous) {
568
- msg += `\n${chalk.red.bold('⚠️ WARNING: This is a potentially dangerous action!')}\n`;
569
- msg += chalk.red(' The AI is requesting to execute commands on your system.\n');
570
- }
571
-
572
- // Add batch approval hint
573
- 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`;
574
-
575
- return msg;
576
- }
577
-
578
- private sleep(ms: number): Promise<void> {
579
- return new Promise(resolve => setTimeout(resolve, ms));
580
- }
581
-
582
- // Tool implementations with enhanced error handling and undo support
583
-
584
- /**
585
- * Read file with enhanced error handling and suggestions
586
- */
587
- private readFile(args: Record<string, string>): ToolResult {
588
- const filePath = this.resolvePath(args.path);
589
-
590
- if (!fs.existsSync(filePath)) {
591
- // Try to find similar files
592
- const dir = path.dirname(filePath);
593
- const basename = path.basename(filePath);
594
- let suggestions: string[] = [];
595
-
596
- if (fs.existsSync(dir)) {
597
- const files = fs.readdirSync(dir);
598
- suggestions = files
599
- .filter(f => f.toLowerCase().includes(basename.toLowerCase().slice(0, 3)))
600
- .slice(0, 3);
601
- }
602
-
603
- return this.createErrorResult(
604
- ToolErrorType.FILE_NOT_FOUND,
605
- `File not found: ${args.path}`,
606
- suggestions.length > 0
607
- ? `Did you mean one of these? ${suggestions.join(', ')}`
608
- : 'Use list_dir to see available files in the directory.'
609
- );
610
- }
611
-
612
- try {
613
- const stats = fs.statSync(filePath);
614
- if (stats.size > 1024 * 1024) { // 1MB warning
615
- this.logger.warn(`Large file (${(stats.size / 1024 / 1024).toFixed(2)}MB) - consider using start_line/end_line`);
616
- }
617
-
618
- const content = fs.readFileSync(filePath, 'utf-8');
619
- const lines = content.split('\n');
620
-
621
- const startLine = args.start_line ? parseInt(args.start_line) - 1 : 0;
622
- const endLine = args.end_line ? parseInt(args.end_line) : lines.length;
623
-
624
- // Validate line numbers
625
- if (startLine < 0 || startLine >= lines.length) {
626
- return this.createErrorResult(
627
- ToolErrorType.INVALID_ARGS,
628
- `Invalid start_line: ${args.start_line}. File has ${lines.length} lines.`
629
- );
630
- }
631
-
632
- const selectedLines = lines.slice(startLine, Math.min(endLine, lines.length));
633
-
634
- return {
635
- success: true,
636
- output: selectedLines.join('\n'),
637
- metadata: {
638
- totalLines: lines.length,
639
- linesReturned: selectedLines.length,
640
- filePath: args.path,
641
- },
642
- };
643
- } catch (error: any) {
644
- if (error.code === 'EACCES') {
645
- return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, `Permission denied: ${args.path}`);
646
- }
647
- return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, error.message);
648
- }
649
- }
650
-
651
- /**
652
- * Write file with undo support
653
- */
654
- private writeFile(args: Record<string, string>): ToolResult {
655
- const filePath = this.resolvePath(args.path);
656
- const dir = path.dirname(filePath);
657
-
658
- // Save original content for undo if file exists
659
- let originalContent: string | null = null;
660
- if (fs.existsSync(filePath)) {
661
- originalContent = fs.readFileSync(filePath, 'utf-8');
662
- }
663
-
664
- try {
665
- // Create directory if needed
666
- if (!fs.existsSync(dir)) {
667
- fs.mkdirSync(dir, { recursive: true });
668
- }
669
-
670
- fs.writeFileSync(filePath, args.content, 'utf-8');
671
-
672
- // Store undo operation
673
- const undoOp: UndoOperation = {
674
- id: `undo-${Date.now()}`,
675
- tool: 'write_file',
676
- timestamp: Date.now(),
677
- filePath: filePath,
678
- originalContent: originalContent,
679
- description: originalContent
680
- ? `Restore ${args.path} to previous version`
681
- : `Delete ${args.path} (was created)`,
682
- };
683
- this.undoStack.push(undoOp);
684
-
685
- // Limit undo stack size
686
- if (this.undoStack.length > 50) {
687
- this.undoStack.shift();
688
- }
689
-
690
- const isNew = originalContent === null;
691
- return {
692
- success: true,
693
- output: `File ${isNew ? 'created' : 'updated'}: ${args.path}`,
694
- metadata: {
695
- bytes: args.content.length,
696
- isNew,
697
- canUndo: true,
698
- },
699
- };
700
- } catch (error: any) {
701
- if (error.code === 'EACCES') {
702
- return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, `Permission denied writing to: ${args.path}`);
703
- }
704
- if (error.code === 'ENOSPC') {
705
- return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, 'No space left on device');
706
- }
707
- return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, error.message);
708
- }
709
- }
710
-
711
- /**
712
- * Edit file with undo support and helpful error messages
713
- */
714
- private editFile(args: Record<string, string>): ToolResult {
715
- const filePath = this.resolvePath(args.path);
716
-
717
- if (!fs.existsSync(filePath)) {
718
- return this.createErrorResult(
719
- ToolErrorType.FILE_NOT_FOUND,
720
- `File not found: ${args.path}`,
721
- 'Use write_file to create a new file, or check the path.'
722
- );
723
- }
724
-
725
- try {
726
- let content = fs.readFileSync(filePath, 'utf-8');
727
- const originalContent = content;
728
-
729
- if (!content.includes(args.old_text)) {
730
- // Try to help identify the issue
731
- const lines = content.split('\n');
732
- const searchTerms = args.old_text.split('\n')[0].trim().slice(0, 30);
733
- const possibleMatches = lines
734
- .map((line, i) => ({ line: i + 1, content: line }))
735
- .filter(l => l.content.includes(searchTerms.slice(0, 10)))
736
- .slice(0, 3);
737
-
738
- let suggestion = 'The exact text was not found. ';
739
- if (possibleMatches.length > 0) {
740
- suggestion += `Similar content found at lines: ${possibleMatches.map(m => m.line).join(', ')}. `;
741
- }
742
- suggestion += 'Ensure whitespace and indentation match exactly.';
743
-
744
- return this.createErrorResult(
745
- ToolErrorType.EXECUTION_FAILED,
746
- 'Old text not found in file',
747
- suggestion
748
- );
749
- }
750
-
751
- // Check for multiple matches
752
- const matchCount = (content.match(new RegExp(args.old_text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g')) || []).length;
753
- if (matchCount > 1) {
754
- this.logger.warn(`Found ${matchCount} matches - only replacing first occurrence`);
755
- }
756
-
757
- content = content.replace(args.old_text, args.new_text);
758
- fs.writeFileSync(filePath, content, 'utf-8');
759
-
760
- // Store undo operation
761
- const undoOp: UndoOperation = {
762
- id: `undo-${Date.now()}`,
763
- tool: 'edit_file',
764
- timestamp: Date.now(),
765
- filePath: filePath,
766
- originalContent: originalContent,
767
- description: `Restore ${args.path} (reverts edit)`,
768
- };
769
- this.undoStack.push(undoOp);
770
-
771
- // Limit undo stack size
772
- if (this.undoStack.length > 50) {
773
- this.undoStack.shift();
774
- }
775
-
776
- return {
777
- success: true,
778
- output: `File edited: ${args.path}`,
779
- metadata: {
780
- matchesFound: matchCount,
781
- canUndo: true,
782
- },
783
- };
784
- } catch (error: any) {
785
- if (error.code === 'EACCES') {
786
- return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, `Permission denied: ${args.path}`);
787
- }
788
- return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, error.message);
789
- }
790
- }
791
-
792
- /**
793
- * Execute bash command with enhanced error handling
794
- * SECURITY: Commands are sandboxed to workspace directory
795
- * WINDOWS: Detects Unix-specific commands and suggests alternatives
796
- */
797
- private bash(args: Record<string, string>): ToolResult {
798
- const cwd = args.cwd ? this.resolvePath(args.cwd) : this.cwd;
799
- const timeout = args.timeout ? parseInt(args.timeout) * 1000 : 30000;
800
- const os = require('os');
801
- const platform = os.platform();
802
-
803
- // Unix-specific commands that don't exist on Windows
804
- const unixOnlyCommands = [
805
- 'head', 'tail', 'grep', 'awk', 'sed', 'wc', 'cut', 'sort', 'uniq',
806
- 'xargs', 'find', 'chmod', 'chown', 'ln', 'df', 'du', 'ps', 'kill',
807
- 'top', 'htop', 'which', 'whereis', 'man', 'less', 'more', 'cat',
808
- ];
809
-
810
- // Check if command uses Unix-only tools on Windows
811
- if (platform === 'win32') {
812
- const cmdParts = args.command.split(/[|&;]/);
813
- for (const part of cmdParts) {
814
- const firstWord = part.trim().split(/\s+/)[0].toLowerCase();
815
- if (unixOnlyCommands.includes(firstWord)) {
816
- return this.createErrorResult(
817
- ToolErrorType.EXECUTION_FAILED,
818
- `Command '${firstWord}' is not available on Windows`,
819
- `Use the 'ssh_exec' tool to run Unix commands on the server, ` +
820
- `or use 'fetch_url' for web requests. ` +
821
- `PowerShell alternatives: dir (ls), type (cat), findstr (grep), select-string (grep)`
822
- );
823
- }
824
- }
825
-
826
- // Check for pipe to Unix command
827
- if (args.command.includes('|')) {
828
- const pipedCommands = args.command.split('|').map(c => c.trim().split(/\s+/)[0].toLowerCase());
829
- for (const cmd of pipedCommands) {
830
- if (unixOnlyCommands.includes(cmd)) {
831
- return this.createErrorResult(
832
- ToolErrorType.EXECUTION_FAILED,
833
- `Piped command '${cmd}' is not available on Windows`,
834
- `Windows doesn't have '${cmd}'. Use 'ssh_exec' tool to run this command on the Vigthoria server instead.`
835
- );
836
- }
837
- }
838
- }
839
- }
840
-
841
- // SECURITY: Block dangerous commands that could access outside workspace
842
- const blockedPatterns = [
843
- /\bcat\s+\/etc\//i, // Reading system files
844
- /\bcat\s+\/var\/(?!log)/i, // Reading /var/ except logs
845
- /\bcat\s+\/root\//i, // Reading root home
846
- /\bcat\s+\/home\/[^\/]+\/\.[^\/]/i, // Reading hidden files in home dirs
847
- /\bcat\s+~\/\./i, // Reading hidden files via ~
848
- /\bcd\s+(\/etc|\/var\/www|\/root|\/home)/i, // CD to sensitive dirs
849
- /\brm\s+-rf?\s+\//i, // Dangerous rm commands
850
- /\b(curl|wget).*\|\s*(bash|sh)\b/i, // Downloading and executing scripts
851
- /\bsudo\b/i, // Sudo commands
852
- /\bsu\s+-/i, // Su to root
853
- /\bchmod\s+[0-7]*777/i, // World-writable permissions
854
- /\/(var\/www|opt)\/[a-z]+-?(database|models|coder|mcp|operator|voice|music)/i, // Vigthoria ecosystem
855
- /vigthoria-(models|database|mcp|operator|voice|music)/i, // Vigthoria project names
856
- ];
857
-
858
- for (const pattern of blockedPatterns) {
859
- if (pattern.test(args.command)) {
860
- this.logger.warn(`Security: Blocked potentially dangerous command: ${args.command.substring(0, 50)}...`);
861
- return this.createErrorResult(
862
- ToolErrorType.PERMISSION_DENIED,
863
- 'This command is blocked for security reasons',
864
- 'Commands must operate within your current project workspace.'
865
- );
866
- }
867
- }
868
-
869
- // Validate working directory
870
- if (!fs.existsSync(cwd)) {
871
- return this.createErrorResult(
872
- ToolErrorType.FILE_NOT_FOUND,
873
- `Working directory not found: ${cwd}`,
874
- 'Check that the directory exists or use an absolute path.'
875
- );
876
- }
877
-
878
- try {
879
- const startTime = Date.now();
880
-
881
- // Build exec options based on platform
882
- const execOptions: any = {
883
- cwd,
884
- timeout,
885
- encoding: 'utf-8',
886
- maxBuffer: 10 * 1024 * 1024, // 10MB
887
- stdio: ['pipe', 'pipe', 'pipe'],
888
- // Ensure consistent environment
889
- env: {
890
- ...process.env,
891
- // Prevent locale issues
892
- LC_ALL: 'C',
893
- LANG: 'C',
894
- },
895
- };
896
-
897
- // Set shell based on platform for consistent behavior
898
- if (platform === 'win32') {
899
- execOptions.shell = true; // Use default cmd.exe on Windows
900
- } else {
901
- // Use /bin/sh on Unix-like systems (more portable than bash)
902
- execOptions.shell = '/bin/sh';
903
- }
904
-
905
- const output = execSync(args.command, execOptions) as string;
906
-
907
- const duration = Date.now() - startTime;
908
-
909
- return {
910
- success: true,
911
- output: output.trim(),
912
- metadata: {
913
- durationMs: duration,
914
- cwd,
915
- },
916
- };
917
- } catch (error: any) {
918
- // Command failed but may have output
919
- const output = error.stdout || '';
920
- const stderr = error.stderr || '';
921
-
922
- // Provide helpful error messages for common cases
923
- if (error.killed) {
924
- return this.createErrorResult(
925
- ToolErrorType.TIMEOUT,
926
- `Command timed out after ${timeout/1000}s`,
927
- 'Try increasing the timeout or breaking the command into smaller parts.'
928
- );
929
- }
930
-
931
- if (stderr.includes('command not found') || stderr.includes('not recognized')) {
932
- const cmd = args.command.split(' ')[0];
933
- return this.createErrorResult(
934
- ToolErrorType.EXECUTION_FAILED,
935
- `Command not found: ${cmd}`,
936
- 'Check that the command is installed and in PATH.'
937
- );
938
- }
939
-
940
- if (stderr.includes('Permission denied')) {
941
- return this.createErrorResult(
942
- ToolErrorType.PERMISSION_DENIED,
943
- 'Permission denied executing command',
944
- 'Try using sudo or check file/directory permissions.'
945
- );
946
- }
947
-
948
- return {
949
- success: false,
950
- output,
951
- error: stderr || error.message,
952
- suggestion: 'Check command syntax and try again.',
953
- canRetry: !error.killed,
954
- };
955
- }
956
- }
957
-
958
- private grep(args: Record<string, string>): ToolResult {
959
- const searchPath = args.path ? this.resolvePath(args.path) : this.cwd;
960
- const include = args.include || '*';
961
- const os = require('os');
962
-
963
- // macOS uses BSD grep which has different options than GNU grep
964
- const isMac = os.platform() === 'darwin';
965
-
966
- let cmd: string;
967
- if (isMac) {
968
- // BSD grep: use -r for recursive, -n for line numbers
969
- // Note: BSD grep doesn't support --color=never, just omit it
970
- if (args.include) {
971
- cmd = `grep -rn --include="${args.include}" "${args.pattern}" "${searchPath}"`;
972
- } else {
973
- cmd = `grep -rn "${args.pattern}" "${searchPath}"`;
974
- }
975
- } else {
976
- // GNU grep (Linux)
977
- if (args.include) {
978
- cmd = `grep -rn --color=never --include="${args.include}" "${args.pattern}" "${searchPath}"`;
979
- } else {
980
- cmd = `grep -rn --color=never "${args.pattern}" "${searchPath}"`;
981
- }
982
- }
983
-
984
- try {
985
- const output = execSync(cmd, {
986
- cwd: this.cwd,
987
- encoding: 'utf-8',
988
- maxBuffer: 5 * 1024 * 1024,
989
- timeout: 30000,
990
- env: { ...process.env, GREP_OPTIONS: '' }, // Prevent user's grep options from interfering
991
- });
992
-
993
- return { success: true, output: output.trim() };
994
- } catch (error: any) {
995
- if (error.status === 1) {
996
- // No matches found
997
- return { success: true, output: 'No matches found' };
998
- }
999
- return { success: false, error: error.message };
1000
- }
1001
- }
1002
-
1003
- private listDir(args: Record<string, string>): ToolResult {
1004
- const dirPath = this.resolvePath(args.path);
1005
-
1006
- if (!fs.existsSync(dirPath)) {
1007
- return { success: false, error: `Directory not found: ${args.path}` };
1008
- }
1009
-
1010
- const entries = fs.readdirSync(dirPath, { withFileTypes: true });
1011
- const output = entries.map(e => {
1012
- const suffix = e.isDirectory() ? '/' : '';
1013
- return e.name + suffix;
1014
- }).join('\n');
1015
-
1016
- return { success: true, output };
1017
- }
1018
-
1019
- private glob(args: Record<string, string>): ToolResult {
1020
- const { globSync } = require('glob');
1021
-
1022
- try {
1023
- const files = globSync(args.pattern, { cwd: this.cwd });
1024
- return { success: true, output: files.join('\n') };
1025
- } catch (error) {
1026
- return { success: false, error: (error as Error).message };
1027
- }
1028
- }
1029
-
1030
- private git(args: Record<string, string>): ToolResult {
1031
- try {
1032
- const output = execSync(`git ${args.args}`, {
1033
- cwd: this.cwd,
1034
- encoding: 'utf-8',
1035
- timeout: 60000,
1036
- });
1037
- return { success: true, output: output.trim() };
1038
- } catch (error: any) {
1039
- return { success: false, error: error.stderr || error.message };
1040
- }
1041
- }
1042
-
1043
- /**
1044
- * Vigthoria Repository management tool
1045
- * Allows AI to push, pull, list, share, and manage projects in the Vigthoria Repository
1046
- */
1047
- private async repo(args: Record<string, string>): Promise<ToolResult> {
1048
- const action = args.action?.toLowerCase();
1049
- const project = args.project;
1050
- const visibility = args.visibility || 'private';
1051
- const targetPath = args.path || this.cwd;
1052
-
1053
- try {
1054
- // Use vigthoria CLI for repo operations
1055
- let command: string;
1056
-
1057
- switch (action) {
1058
- case 'push':
1059
- if (!project) {
1060
- return {
1061
- success: false,
1062
- error: 'Project name is required for push',
1063
- suggestion: 'Provide a project name, e.g., repo action=push project=my-project'
1064
- };
1065
- }
1066
- command = `vigthoria repo push "${project}" "${targetPath}" --visibility ${visibility}`;
1067
- break;
1068
-
1069
- case 'pull':
1070
- if (!project) {
1071
- return {
1072
- success: false,
1073
- error: 'Project name is required for pull',
1074
- suggestion: 'Provide a project name, e.g., repo action=pull project=my-project'
1075
- };
1076
- }
1077
- command = `vigthoria repo pull "${project}"`;
1078
- break;
1079
-
1080
- case 'list':
1081
- command = 'vigthoria repo list';
1082
- break;
1083
-
1084
- case 'status':
1085
- if (!project) {
1086
- return {
1087
- success: false,
1088
- error: 'Project name is required for status',
1089
- suggestion: 'Provide a project name, e.g., repo action=status project=my-project'
1090
- };
1091
- }
1092
- command = `vigthoria repo status "${project}"`;
1093
- break;
1094
-
1095
- case 'share':
1096
- if (!project || !args.username) {
1097
- return {
1098
- success: false,
1099
- error: 'Project name and username are required for share',
1100
- suggestion: 'Provide both, e.g., repo action=share project=my-project username=collaborator permission=read'
1101
- };
1102
- }
1103
- const permission = args.permission || 'read';
1104
- command = `vigthoria repo share "${project}" "${args.username}" --permission ${permission}`;
1105
- break;
1106
-
1107
- case 'delete':
1108
- if (!project) {
1109
- return {
1110
- success: false,
1111
- error: 'Project name is required for delete',
1112
- suggestion: 'Provide a project name, e.g., repo action=delete project=my-project'
1113
- };
1114
- }
1115
- command = `vigthoria repo delete "${project}" --force`;
1116
- break;
1117
-
1118
- case 'clone':
1119
- if (!project) {
1120
- return {
1121
- success: false,
1122
- error: 'Project name is required for clone',
1123
- suggestion: 'Provide a project name, e.g., repo action=clone project=my-project path=/path/to/target'
1124
- };
1125
- }
1126
- command = `vigthoria repo clone "${project}" "${targetPath}"`;
1127
- break;
1128
-
1129
- default:
1130
- return {
1131
- success: false,
1132
- error: `Unknown repo action: ${action}`,
1133
- suggestion: 'Available actions: push, pull, list, status, share, delete, clone'
1134
- };
1135
- }
1136
-
1137
- const output = execSync(command, {
1138
- cwd: this.cwd,
1139
- encoding: 'utf-8',
1140
- timeout: 120000, // 2 minute timeout for repo operations
1141
- env: { ...process.env, FORCE_COLOR: '0' } // Disable colors for clean output
1142
- });
1143
-
1144
- return {
1145
- success: true,
1146
- output: output.trim(),
1147
- metadata: { action, project }
1148
- };
1149
- } catch (error: any) {
1150
- return {
1151
- success: false,
1152
- error: error.stderr || error.message,
1153
- suggestion: 'Make sure you are logged in with vigthoria login and have the required permissions.'
1154
- };
1155
- }
1156
- }
1157
-
1158
- /**
1159
- * Fetch URL content - Cross-platform web fetching
1160
- * Uses Node.js native fetch (available in Node 18+)
1161
- */
1162
- private async fetchUrl(args: Record<string, string>): Promise<ToolResult> {
1163
- const url = args.url;
1164
- const method = (args.method || 'GET').toUpperCase();
1165
-
1166
- // Validate URL
1167
- if (!url.startsWith('http://') && !url.startsWith('https://')) {
1168
- return this.createErrorResult(
1169
- ToolErrorType.INVALID_ARGS,
1170
- 'URL must start with http:// or https://',
1171
- 'Provide a valid URL, e.g., https://example.com'
1172
- );
1173
- }
1174
-
1175
- try {
1176
- const fetchOptions: RequestInit = {
1177
- method,
1178
- headers: {
1179
- 'User-Agent': 'Vigthoria-CLI/1.5.7',
1180
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
1181
- },
1182
- };
1183
-
1184
- // Parse custom headers if provided
1185
- if (args.headers) {
1186
- try {
1187
- const customHeaders = JSON.parse(args.headers);
1188
- fetchOptions.headers = { ...fetchOptions.headers, ...customHeaders };
1189
- } catch {
1190
- this.logger.warn('Invalid headers JSON, using defaults');
1191
- }
1192
- }
1193
-
1194
- // Add body for POST/PUT requests
1195
- if (args.body && ['POST', 'PUT', 'PATCH'].includes(method)) {
1196
- fetchOptions.body = args.body;
1197
- (fetchOptions.headers as Record<string, string>)['Content-Type'] = 'application/json';
1198
- }
1199
-
1200
- // Use AbortController for timeout
1201
- const controller = new AbortController();
1202
- const timeout = setTimeout(() => controller.abort(), 30000);
1203
- fetchOptions.signal = controller.signal;
1204
-
1205
- const response = await fetch(url, fetchOptions);
1206
- clearTimeout(timeout);
1207
-
1208
- if (!response.ok) {
1209
- return this.createErrorResult(
1210
- ToolErrorType.NETWORK_ERROR,
1211
- `HTTP ${response.status}: ${response.statusText}`,
1212
- `The server returned an error. Status: ${response.status}`
1213
- );
1214
- }
1215
-
1216
- let content = await response.text();
1217
-
1218
- // Extract content based on selector if provided (basic HTML extraction)
1219
- if (args.selector && content.includes('<')) {
1220
- const selector = args.selector.toLowerCase().trim();
1221
-
1222
- if (selector === 'title') {
1223
- const match = content.match(/<title[^>]*>([^<]*)<\/title>/i);
1224
- content = match ? match[1].trim() : 'No title found';
1225
- } else if (selector === 'meta' || selector.includes('meta[')) {
1226
- const matches = content.match(/<meta[^>]+>/gi) || [];
1227
- content = matches.length > 0 ? matches.join('\n') : 'No meta tags found';
1228
- } else if (selector === 'body' || selector === 'text') {
1229
- // Extract readable text from body
1230
- const match = content.match(/<body[^>]*>([\s\S]*)<\/body>/i);
1231
- if (match) {
1232
- content = match[1]
1233
- .replace(/<script[\s\S]*?<\/script>/gi, '')
1234
- .replace(/<style[\s\S]*?<\/style>/gi, '')
1235
- .replace(/<nav[\s\S]*?<\/nav>/gi, '')
1236
- .replace(/<header[\s\S]*?<\/header>/gi, '')
1237
- .replace(/<footer[\s\S]*?<\/footer>/gi, '')
1238
- .replace(/<[^>]+>/g, ' ')
1239
- .replace(/\s+/g, ' ')
1240
- .trim();
1241
- }
1242
- } else if (selector === 'links' || selector === 'a') {
1243
- // Extract all links
1244
- const linkRegex = /<a[^>]+href=["']([^"']+)["'][^>]*>([^<]*)<\/a>/gi;
1245
- const links: string[] = [];
1246
- let linkMatch;
1247
- while ((linkMatch = linkRegex.exec(content)) !== null) {
1248
- const href = linkMatch[1];
1249
- const text = linkMatch[2].trim();
1250
- if (text && !href.startsWith('#') && !href.startsWith('javascript:')) {
1251
- links.push(`${text}: ${href}`);
1252
- }
1253
- }
1254
- content = links.length > 0 ? links.join('\n') : 'No links found';
1255
- } else if (selector.includes(',')) {
1256
- // Handle compound selectors like "h1, h2, h3"
1257
- const tags = selector.split(',').map(s => s.trim());
1258
- const allMatches: string[] = [];
1259
- for (const tag of tags) {
1260
- const regex = new RegExp(`<${tag}[^>]*>([\\s\\S]*?)</${tag}>`, 'gi');
1261
- let match;
1262
- while ((match = regex.exec(content)) !== null) {
1263
- const text = match[1].replace(/<[^>]+>/g, '').trim();
1264
- if (text) allMatches.push(`[${tag}] ${text}`);
1265
- }
1266
- }
1267
- content = allMatches.length > 0 ? allMatches.join('\n') : `No ${selector} tags found`;
1268
- } else if (/^h[1-6]$/.test(selector)) {
1269
- // Single heading selector
1270
- const regex = new RegExp(`<${selector}[^>]*>([\\s\\S]*?)</${selector}>`, 'gi');
1271
- const matches: string[] = [];
1272
- let match;
1273
- while ((match = regex.exec(content)) !== null) {
1274
- const text = match[1].replace(/<[^>]+>/g, '').trim();
1275
- if (text) matches.push(text);
1276
- }
1277
- content = matches.length > 0 ? matches.join('\n') : `No ${selector} tags found`;
1278
- } else if (selector === 'nav' || selector === 'nav a') {
1279
- // Extract navigation links
1280
- const navMatch = content.match(/<nav[^>]*>([\s\S]*?)<\/nav>/gi);
1281
- if (navMatch) {
1282
- const linkRegex = /<a[^>]+href=["']([^"']+)["'][^>]*>([^<]*)<\/a>/gi;
1283
- const links: string[] = [];
1284
- for (const nav of navMatch) {
1285
- let linkMatch;
1286
- while ((linkMatch = linkRegex.exec(nav)) !== null) {
1287
- const text = linkMatch[2].trim();
1288
- if (text) links.push(`${text}: ${linkMatch[1]}`);
1289
- }
1290
- }
1291
- content = links.length > 0 ? links.join('\n') : 'No navigation links found';
1292
- } else {
1293
- content = 'No navigation found';
1294
- }
1295
- } else if (selector === 'footer') {
1296
- const match = content.match(/<footer[^>]*>([\s\S]*?)<\/footer>/i);
1297
- content = match ? match[1].replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim() : 'No footer found';
1298
- } else if (selector === 'images' || selector === 'img') {
1299
- const imgRegex = /<img[^>]+src=["']([^"']+)["'][^>]*(?:alt=["']([^"']*)["'])?[^>]*>/gi;
1300
- const images: string[] = [];
1301
- let imgMatch;
1302
- while ((imgMatch = imgRegex.exec(content)) !== null) {
1303
- const src = imgMatch[1];
1304
- const alt = imgMatch[2] || 'no alt';
1305
- images.push(`${alt}: ${src}`);
1306
- }
1307
- content = images.length > 0 ? images.join('\n') : 'No images found';
1308
- } else {
1309
- // Generic tag extraction
1310
- const regex = new RegExp(`<${selector}[^>]*>([\\s\\S]*?)</${selector}>`, 'gi');
1311
- const matches: string[] = [];
1312
- let match;
1313
- while ((match = regex.exec(content)) !== null) {
1314
- matches.push(match[1].replace(/<[^>]+>/g, ' ').trim());
1315
- }
1316
- content = matches.length > 0 ? matches.join('\n\n---\n\n') : `No ${selector} elements found`;
1317
- }
1318
- }
1319
-
1320
- // Truncate if too long
1321
- if (content.length > 50000) {
1322
- content = content.substring(0, 50000) + '\n... (truncated, content too long)';
1323
- }
1324
-
1325
- return {
1326
- success: true,
1327
- output: content,
1328
- metadata: {
1329
- url,
1330
- status: response.status,
1331
- contentType: response.headers.get('content-type') || 'unknown',
1332
- contentLength: content.length,
1333
- },
1334
- };
1335
- } catch (error: any) {
1336
- if (error.name === 'AbortError') {
1337
- return this.createErrorResult(
1338
- ToolErrorType.TIMEOUT,
1339
- 'Request timed out after 30 seconds',
1340
- 'The server took too long to respond. Try again or use a different URL.'
1341
- );
1342
- }
1343
-
1344
- return this.createErrorResult(
1345
- ToolErrorType.NETWORK_ERROR,
1346
- error.message,
1347
- 'Check your internet connection and ensure the URL is correct.'
1348
- );
1349
- }
1350
- }
1351
-
1352
- /**
1353
- * Execute command via SSH on remote server
1354
- * Useful for running Unix commands from Windows
1355
- */
1356
- private async sshExec(args: Record<string, string>): Promise<ToolResult> {
1357
- const command = args.command;
1358
- const host = args.host || 'vigthoria-server';
1359
- const timeout = args.timeout ? parseInt(args.timeout) * 1000 : 60000;
1360
-
1361
- // Security checks for SSH commands
1362
- const blockedPatterns = [
1363
- /\brm\s+-rf?\s+\//i, // Dangerous rm commands
1364
- /\bsudo\s+rm/i, // Sudo rm
1365
- />\s*\/dev\/sd/i, // Writing to disk devices
1366
- /\bdd\s+.*of=\/dev/i, // dd to devices
1367
- /\bmkfs/i, // Format filesystems
1368
- /shutdown|reboot|halt|poweroff/i, // System control
1369
- ];
1370
-
1371
- for (const pattern of blockedPatterns) {
1372
- if (pattern.test(command)) {
1373
- return this.createErrorResult(
1374
- ToolErrorType.PERMISSION_DENIED,
1375
- 'This command is blocked for security reasons',
1376
- 'Dangerous system commands cannot be executed via SSH.'
1377
- );
1378
- }
1379
- }
1380
-
1381
- try {
1382
- const os = require('os');
1383
- const platform = os.platform();
1384
-
1385
- let sshCommand: string;
1386
- let execOptions: any = {
1387
- encoding: 'utf-8',
1388
- timeout,
1389
- maxBuffer: 10 * 1024 * 1024,
1390
- };
1391
-
1392
- if (platform === 'win32') {
1393
- // On Windows, use the ssh command from OpenSSH
1394
- sshCommand = `ssh -o BatchMode=yes -o StrictHostKeyChecking=no -o ConnectTimeout=10 ${host} "${command.replace(/"/g, '\\"')}"`;
1395
- execOptions.shell = true;
1396
- } else {
1397
- // On Unix-like systems
1398
- sshCommand = `ssh -o BatchMode=yes -o StrictHostKeyChecking=no -o ConnectTimeout=10 ${host} '${command.replace(/'/g, "'\\''")}'`;
1399
- execOptions.shell = '/bin/sh';
1400
- }
1401
-
1402
- const output = execSync(sshCommand, execOptions) as string;
1403
-
1404
- return {
1405
- success: true,
1406
- output: output.trim(),
1407
- metadata: { host, command },
1408
- };
1409
- } catch (error: any) {
1410
- // Check for common SSH errors
1411
- const errorMsg = error.stderr || error.message || '';
1412
-
1413
- if (errorMsg.includes('Connection refused') || errorMsg.includes('No route to host')) {
1414
- return this.createErrorResult(
1415
- ToolErrorType.NETWORK_ERROR,
1416
- `Cannot connect to SSH host: ${host}`,
1417
- 'Check that the SSH host is correct and the server is running.'
1418
- );
1419
- }
1420
-
1421
- if (errorMsg.includes('Permission denied') || errorMsg.includes('authentication')) {
1422
- return this.createErrorResult(
1423
- ToolErrorType.PERMISSION_DENIED,
1424
- 'SSH authentication failed',
1425
- 'Make sure you have SSH key authentication set up for this host.'
1426
- );
1427
- }
1428
-
1429
- if (error.killed) {
1430
- return this.createErrorResult(
1431
- ToolErrorType.TIMEOUT,
1432
- `SSH command timed out after ${timeout/1000}s`,
1433
- 'Try a simpler command or increase the timeout.'
1434
- );
1435
- }
1436
-
1437
- return {
1438
- success: false,
1439
- output: error.stdout || '',
1440
- error: errorMsg,
1441
- suggestion: 'Check the command syntax and ensure SSH access is configured.',
1442
- };
1443
- }
1444
- }
1445
-
1446
- /**
1447
- * Resolve and SANITIZE path - prevent path traversal outside workspace
1448
- * SECURITY: All paths MUST stay within the workspace (cwd)
1449
- */
1450
- private resolvePath(p: string): string {
1451
- // Resolve the full path (handles both relative and absolute)
1452
- let resolvedPath: string;
1453
- if (path.isAbsolute(p)) {
1454
- resolvedPath = path.normalize(p);
1455
- } else {
1456
- resolvedPath = path.normalize(path.join(this.cwd, p));
1457
- }
1458
-
1459
- // SECURITY CHECK: Ensure path is within workspace
1460
- const workspaceRoot = path.normalize(this.cwd);
1461
- if (!resolvedPath.startsWith(workspaceRoot + path.sep) && resolvedPath !== workspaceRoot) {
1462
- // Path is outside workspace - force it back to workspace
1463
- this.logger.warn(`Security: Blocked access to path outside workspace: ${p}`);
1464
- // Return the sanitized relative path within workspace
1465
- const basename = path.basename(p);
1466
- return path.join(this.cwd, basename);
1467
- }
1468
-
1469
- return resolvedPath;
1470
- }
1471
-
1472
- /**
1473
- * Check if a path is within the allowed workspace
1474
- */
1475
- private isPathWithinWorkspace(p: string): boolean {
1476
- const resolvedPath = path.normalize(path.isAbsolute(p) ? p : path.join(this.cwd, p));
1477
- const workspaceRoot = path.normalize(this.cwd);
1478
- return resolvedPath.startsWith(workspaceRoot + path.sep) || resolvedPath === workspaceRoot;
1479
- }
1480
-
1481
- /**
1482
- * Parse tool calls from AI response (Vigthoria Agent format)
1483
- * Enhanced to handle various AI output formats including malformed JSON
1484
- */
1485
- static parseToolCalls(text: string): ToolCall[] {
1486
- const calls: ToolCall[] = [];
1487
- let match;
1488
-
1489
- // Helper to extract balanced JSON from a position (handles nested braces)
1490
- const extractBalancedJson = (str: string, startIdx: number): string | null => {
1491
- if (str[startIdx] !== '{') return null;
1492
- let braceCount = 0;
1493
- let inString = false;
1494
- let escapeNext = false;
1495
-
1496
- for (let i = startIdx; i < str.length; i++) {
1497
- const char = str[i];
1498
-
1499
- if (escapeNext) {
1500
- escapeNext = false;
1501
- continue;
1502
- }
1503
-
1504
- if (char === '\\') {
1505
- escapeNext = true;
1506
- continue;
1507
- }
1508
-
1509
- if (char === '"') {
1510
- inString = !inString;
1511
- continue;
1512
- }
1513
-
1514
- if (!inString) {
1515
- if (char === '{') braceCount++;
1516
- else if (char === '}') {
1517
- braceCount--;
1518
- if (braceCount === 0) {
1519
- return str.substring(startIdx, i + 1);
1520
- }
1521
- }
1522
- }
1523
- }
1524
- return null;
1525
- };
1526
-
1527
- // Helper to fix common JSON issues from AI outputs
1528
- // IMPORTANT: Don't blindly replace quotes - it breaks code content
1529
- const fixJson = (jsonStr: string): string => {
1530
- // First, escape newlines and control characters
1531
- let fixed = jsonStr
1532
- .replace(/\r/g, '') // Remove carriage returns
1533
- .replace(/\t/g, '\\t'); // Escape tabs
1534
-
1535
- // Escape literal newlines inside strings (but not \n which is already escaped)
1536
- // We need to be careful - only escape newlines that are inside quoted strings
1537
- const parts: string[] = [];
1538
- let inString = false;
1539
- let currentPart = '';
1540
-
1541
- for (let i = 0; i < fixed.length; i++) {
1542
- const char = fixed[i];
1543
- const prevChar = i > 0 ? fixed[i - 1] : '';
1544
-
1545
- if (char === '"' && prevChar !== '\\') {
1546
- inString = !inString;
1547
- currentPart += char;
1548
- } else if (char === '\n') {
1549
- if (inString) {
1550
- currentPart += '\\n'; // Escape the newline
1551
- } else {
1552
- currentPart += char; // Keep as-is outside strings
1553
- }
1554
- } else {
1555
- currentPart += char;
1556
- }
1557
- }
1558
- fixed = currentPart;
1559
-
1560
- // Quote unquoted keys (only outside strings)
1561
- fixed = fixed.replace(/([{,]\s*)(\w+)\s*:/g, '$1"$2":');
1562
-
1563
- // Remove trailing commas
1564
- fixed = fixed.replace(/,\s*}/g, '}');
1565
- fixed = fixed.replace(/,\s*]/g, ']');
1566
-
1567
- return fixed;
1568
- };
1569
-
1570
- // Normalize tool name from various formats
1571
- const normalizeToolName = (name: string): string => {
1572
- const normalized = name
1573
- .replace(/^__/, '') // Remove leading underscores
1574
- .replace(/__$/, '') // Remove trailing underscores
1575
- .replace(/^execute_/i, '') // Remove execute_ prefix
1576
- .replace(/_execute$/i, '') // Remove _execute suffix
1577
- .toLowerCase();
1578
-
1579
- // Map common variations
1580
- const toolMap: Record<string, string> = {
1581
- 'bash': 'bash',
1582
- 'shell': 'bash',
1583
- 'run': 'bash',
1584
- 'command': 'bash',
1585
- 'list_dir': 'list_dir',
1586
- 'list_directory': 'list_dir',
1587
- 'ls': 'list_dir',
1588
- 'dir': 'list_dir',
1589
- 'read_file': 'read_file',
1590
- 'readfile': 'read_file',
1591
- 'read': 'read_file',
1592
- 'write_file': 'write_file',
1593
- 'writefile': 'write_file',
1594
- 'write': 'write_file',
1595
- 'edit_file': 'edit_file',
1596
- 'editfile': 'edit_file',
1597
- 'edit': 'edit_file',
1598
- };
1599
-
1600
- return toolMap[normalized] || normalized;
1601
- };
1602
-
1603
- // Match <tool_call>...</tool_call> blocks
1604
- const toolCallRegex = /<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/g;
1605
- while ((match = toolCallRegex.exec(text)) !== null) {
1606
- try {
1607
- const fixed = fixJson(match[1]);
1608
- const parsed = JSON.parse(fixed);
1609
- if (parsed.tool && parsed.args) {
1610
- parsed.tool = normalizeToolName(parsed.tool);
1611
- calls.push(parsed);
1612
- }
1613
- } catch (e) {
1614
- // Invalid JSON, skip
1615
- }
1616
- }
1617
-
1618
- // Match ```tool format
1619
- const codeBlockRegex = /```tool\s*\n([\s\S]*?)\n```/g;
1620
- while ((match = codeBlockRegex.exec(text)) !== null) {
1621
- try {
1622
- const fixed = fixJson(match[1]);
1623
- const parsed = JSON.parse(fixed);
1624
- if (parsed.tool && parsed.args) {
1625
- parsed.tool = normalizeToolName(parsed.tool);
1626
- calls.push(parsed);
1627
- }
1628
- } catch (e) {
1629
- // Invalid JSON, skip
1630
- }
1631
- }
1632
-
1633
- // Match ```json blocks with tool definitions
1634
- const jsonBlockRegex = /```(?:json)?\s*\n?([\s\S]*?"tool"[\s\S]*?)\n?```/g;
1635
- while ((match = jsonBlockRegex.exec(text)) !== null) {
1636
- try {
1637
- const fixed = fixJson(match[1]);
1638
- const parsed = JSON.parse(fixed);
1639
- if (parsed.tool && parsed.args) {
1640
- parsed.tool = normalizeToolName(parsed.tool);
1641
- // Prevent duplicates
1642
- if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
1643
- calls.push(parsed);
1644
- }
1645
- }
1646
- } catch (e) {
1647
- // Invalid JSON, skip
1648
- }
1649
- }
1650
-
1651
- // ROBUST PARSER: Find {"tool": at any position and extract balanced JSON
1652
- // This handles multi-line content in write_file and nested structures
1653
- const toolMarkerRegex = /\{"tool"\s*:/g;
1654
- while ((match = toolMarkerRegex.exec(text)) !== null) {
1655
- const startIdx = match.index;
1656
- const jsonStr = extractBalancedJson(text, startIdx);
1657
-
1658
- if (jsonStr) {
1659
- try {
1660
- const parsed = JSON.parse(jsonStr);
1661
- if (parsed.tool && parsed.args) {
1662
- parsed.tool = normalizeToolName(parsed.tool);
1663
- // Prevent duplicates
1664
- if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
1665
- calls.push(parsed);
1666
- }
1667
- }
1668
- } catch (e) {
1669
- // Invalid JSON, try to fix it
1670
- try {
1671
- const fixed = fixJson(jsonStr);
1672
- const parsed = JSON.parse(fixed);
1673
- if (parsed.tool && parsed.args) {
1674
- parsed.tool = normalizeToolName(parsed.tool);
1675
- if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
1676
- calls.push(parsed);
1677
- }
1678
- }
1679
- } catch (e2) {
1680
- // Still invalid - try more aggressive fixing for write_file
1681
- if (jsonStr.includes('"write_file"') || jsonStr.includes('"content"')) {
1682
- try {
1683
- // More aggressive: escape all control characters
1684
- const aggressiveFix = jsonStr
1685
- .replace(/[\x00-\x1F]/g, (c) => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0'))
1686
- .replace(/'/g, '"');
1687
- const parsed = JSON.parse(aggressiveFix);
1688
- if (parsed.tool && parsed.args) {
1689
- parsed.tool = normalizeToolName(parsed.tool);
1690
- if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
1691
- calls.push(parsed);
1692
- }
1693
- }
1694
- } catch (e3) {
1695
- // Still invalid, skip
1696
- }
1697
- }
1698
- }
1699
- }
1700
- }
1701
- }
1702
-
1703
- // Match inline JSON with "tool" key (various formats - tool before args)
1704
- const inlineToolRegex = /\{[^{}]*"?tool"?\s*:\s*["']?([^"',}]+)["']?[^{}]*"?args"?\s*:\s*\{([^{}]*)\}[^{}]*\}/gi;
1705
- while ((match = inlineToolRegex.exec(text)) !== null) {
1706
- try {
1707
- const fixed = fixJson(match[0]);
1708
- const parsed = JSON.parse(fixed);
1709
- if (parsed.tool && parsed.args) {
1710
- parsed.tool = normalizeToolName(parsed.tool);
1711
- if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
1712
- calls.push(parsed);
1713
- }
1714
- }
1715
- } catch (e) {
1716
- // Invalid JSON, skip
1717
- }
1718
- }
1719
-
1720
- // Match inline JSON with "args" BEFORE "tool" (handles reversed order from some AI models)
1721
- const inlineArgsFirstRegex = /\{[^{}]*"?args"?\s*:\s*\{([^{}]*)\}[^{}]*"?tool"?\s*:\s*["']?([^"',}]+)["']?[^{}]*\}/gi;
1722
- while ((match = inlineArgsFirstRegex.exec(text)) !== null) {
1723
- try {
1724
- const fixed = fixJson(match[0]);
1725
- const parsed = JSON.parse(fixed);
1726
- if (parsed.tool && parsed.args) {
1727
- parsed.tool = normalizeToolName(parsed.tool);
1728
- if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
1729
- calls.push(parsed);
1730
- }
1731
- }
1732
- } catch (e) {
1733
- // Invalid JSON, skip
1734
- }
1735
- }
1736
-
1737
- // Universal: Try to find any JSON object with both "tool" and "args" keys
1738
- const universalJsonRegex = /\{[^{}]*(?:"tool"|"args")[^{}]*(?:"tool"|"args")[^{}]*\}/gi;
1739
- while ((match = universalJsonRegex.exec(text)) !== null) {
1740
- try {
1741
- const fixed = fixJson(match[0]);
1742
- const parsed = JSON.parse(fixed);
1743
- if (parsed.tool && parsed.args) {
1744
- parsed.tool = normalizeToolName(parsed.tool);
1745
- if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
1746
- calls.push(parsed);
1747
- }
1748
- }
1749
- } catch (e) {
1750
- // Invalid JSON, skip
1751
- }
1752
- }
1753
-
1754
- // Fallback: Try to parse each line as JSON (for plain JSON output without code blocks)
1755
- // This handles cases where AI outputs just: {"args": {...}, "tool": "..."}
1756
- const lines = text.split('\n');
1757
- for (const line of lines) {
1758
- const trimmed = line.trim();
1759
- if (trimmed.startsWith('{') && trimmed.includes('"tool"') && trimmed.includes('"args"')) {
1760
- try {
1761
- // Try to find balanced braces
1762
- let braceCount = 0;
1763
- let startIdx = -1;
1764
- let endIdx = -1;
1765
- for (let i = 0; i < trimmed.length; i++) {
1766
- if (trimmed[i] === '{') {
1767
- if (startIdx === -1) startIdx = i;
1768
- braceCount++;
1769
- } else if (trimmed[i] === '}') {
1770
- braceCount--;
1771
- if (braceCount === 0 && startIdx !== -1) {
1772
- endIdx = i + 1;
1773
- break;
1774
- }
1775
- }
1776
- }
1777
- if (startIdx !== -1 && endIdx !== -1) {
1778
- const jsonStr = trimmed.substring(startIdx, endIdx);
1779
- const fixed = fixJson(jsonStr);
1780
- const parsed = JSON.parse(fixed);
1781
- if (parsed.tool && parsed.args) {
1782
- parsed.tool = normalizeToolName(parsed.tool);
1783
- if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
1784
- calls.push(parsed);
1785
- }
1786
- }
1787
- }
1788
- } catch (e) {
1789
- // Invalid JSON, skip
1790
- }
1791
- }
1792
- }
1793
-
1794
- // Parse Vigthoria V2 format: {"tool": "__BASH__", ...}
1795
- const vigV2Regex = /"?tool"?\s*:\s*["']__?([A-Za-z_]+)__?["']/gi;
1796
- while ((match = vigV2Regex.exec(text)) !== null) {
1797
- try {
1798
- const toolName = normalizeToolName(match[1]);
1799
- // Extract args from nearby context
1800
- const pathMatch = text.match(/"?(?:arg_)?path"?\s*:\s*["']([^"']+)["']/i);
1801
- const cmdMatch = text.match(/"?command"?\s*:\s*(?:["']([^"']+)["']|\[\s*["']([^"']+)["']\s*\])/i);
1802
- const contentMatch = text.match(/"?content"?\s*:\s*["']([^"']+)["']/i);
1803
-
1804
- const args: Record<string, string> = {};
1805
- if (pathMatch) args.path = pathMatch[1];
1806
- if (cmdMatch) args.command = cmdMatch[1] || cmdMatch[2];
1807
- if (contentMatch) args.content = contentMatch[1];
1808
-
1809
- if (Object.keys(args).length > 0) {
1810
- // Prevent duplicates
1811
- if (!calls.some(c => c.tool === toolName && JSON.stringify(c.args) === JSON.stringify(args))) {
1812
- calls.push({ tool: toolName, args });
1813
- }
1814
- }
1815
- } catch (e) {
1816
- // Skip
1817
- }
1818
- }
1819
-
1820
- return calls;
1821
- }
1822
-
1823
- /**
1824
- * Get tools formatted for AI system prompt
1825
- */
1826
- static getToolsForPrompt(): string {
1827
- const tools = AgenticTools.getToolDefinitions();
1828
-
1829
- let prompt = `## AGENT MODE - YOU MUST USE TOOLS
1830
-
1831
- ⚠️ CRITICAL: You are in Agent Mode. You MUST use tools to interact with files and the system.
1832
- DO NOT guess or hallucinate file contents. DO NOT make up directory structures.
1833
- ALWAYS use read_file before discussing what's in a file.
1834
- ALWAYS use list_dir before discussing what's in a directory.
1835
-
1836
- You have access to these tools:
1837
-
1838
- `;
1839
-
1840
- for (const tool of tools) {
1841
- prompt += `## ${tool.name}
1842
- ${tool.description}
1843
- Parameters:
1844
- ${tool.parameters.map(p => ` - ${p.name}${p.required ? ' (required)' : ''}: ${p.description}`).join('\n')}
1845
-
1846
- `;
1847
- }
1848
-
1849
- prompt += `
1850
- ## How to Use Tools
1851
-
1852
- To use a tool, output a JSON block in a code fence with "tool" language:
1853
-
1854
- \`\`\`tool
1855
- {"tool": "tool_name", "args": {"param1": "value1"}}
1856
- \`\`\`
1857
-
1858
- ## MANDATORY TOOL USAGE (DO NOT SKIP!)
1859
-
1860
- **When user asks "what's in this folder/directory":**
1861
- → FIRST use list_dir, THEN respond based on actual results
1862
-
1863
- **When user asks "can you see/read/show me file X":**
1864
- → FIRST use read_file, THEN respond based on actual contents
1865
-
1866
- **When user mentions a path like "C:\\some\\path" or "/some/path":**
1867
- → FIRST use list_dir to check if it exists, THEN respond
1868
-
1869
- **NEVER say things like "Here's an overview of the contents..." without first using tools!**
1870
- **NEVER describe files or code you haven't actually read with read_file!**
1871
-
1872
- ### Examples:
1873
-
1874
- 1. List directory contents:
1875
- \`\`\`tool
1876
- {"tool": "list_dir", "args": {"path": "."}}
1877
- \`\`\`
1878
-
1879
- 2. Read a file:
1880
- \`\`\`tool
1881
- {"tool": "read_file", "args": {"path": "src/index.js"}}
1882
- \`\`\`
1883
-
1884
- 3. Fetch a web page (full HTML):
1885
- \`\`\`tool
1886
- {"tool": "fetch_url", "args": {"url": "https://example.com"}}
1887
- \`\`\`
1888
-
1889
- 4. Fetch specific content with selectors:
1890
- \`\`\`tool
1891
- {"tool": "fetch_url", "args": {"url": "https://example.com", "selector": "h1, h2, h3"}}
1892
- \`\`\`
1893
- Available selectors: title, body, text, links, nav, footer, images, h1, h2, h3, h1/h2/h3 (compound)
1894
-
1895
- 5. Run command on YOUR configured SSH server (requires user SSH setup, NOT Vigthoria servers):
1896
- \`\`\`tool
1897
- {"tool": "ssh_exec", "args": {"command": "curl -s https://example.com | head -20", "host": "your-server"}}
1898
- \`\`\`
1899
- Note: ssh_exec is for users who have their own servers configured. It does NOT connect to Vigthoria infrastructure.
1900
-
1901
- 6. Write a file:
1902
- \`\`\`tool
1903
- {"tool": "write_file", "args": {"path": "hello.py", "content": "print('Hello World')"}}
1904
- \`\`\`
1905
-
1906
- ## CRITICAL RULES:
1907
-
1908
- ### ABSOLUTELY NO HALLUCINATION (READ THIS CAREFULLY):
1909
- - ONLY use information from tool results you just received in THIS conversation
1910
- - DO NOT make up names, organizations, or content that wasn't in the fetched data
1911
- - DO NOT read random files from the workspace expecting them to contain relevant data
1912
- - If you fetch a website, your analysis MUST be based ONLY on what you just fetched
1913
- - If the user asks about websites A and B, ONLY discuss A and B - don't invent Site C
1914
- - NEVER create fictional organizations, services, or content
1915
- - If you're unsure about something, say "Based on the fetched content, I can see..." not "This organization does..."
1916
-
1917
- ### Strategic Planning (VERY IMPORTANT):
1918
- - PLAN before acting - don't issue many redundant tool calls
1919
- - For web comparisons: Fetch each URL ONCE with no selector to get full HTML, then analyze locally
1920
- - Do NOT fetch the same URL multiple times with different selectors - fetch once and parse the result
1921
- - Think step-by-step: 1) Gather data, 2) Analyze it, 3) Present findings
1922
- - If comparing two things, fetch both ONCE, then write a REAL comparison with specific differences
1923
- - Maximum 2-4 tool calls per step is usually enough - don't spam 10+ calls at once
1924
- - Do NOT use list_dir or read_file when the task is about fetching websites - those are for LOCAL files only
1925
-
1926
- ### Cross-Platform Compatibility:
1927
- - On Windows, Unix commands (head, tail, grep, awk, sed, wc) are NOT available
1928
- - Use \`fetch_url\` for web requests instead of curl|grep
1929
- - Use \`ssh_exec\` to run Unix commands on the Vigthoria server if needed
1930
- - Use \`read_file\` instead of cat
1931
- - Use \`list_dir\` instead of ls
1932
-
1933
- ### Handling Tool Failures:
1934
- - If a tool fails, REPORT the failure honestly to the user
1935
- - NEVER make up or hallucinate content when a tool fails
1936
- - If you cannot access a URL, say "I was unable to fetch the URL because..."
1937
- - If a command fails, explain what happened and suggest alternatives
1938
- - Do NOT write analysis or comparison reports if you couldn't gather the actual data
1939
-
1940
- ### Comparison Tasks:
1941
- - When asked to compare websites/files, you MUST produce actual specific differences
1942
- - Don't just describe each site separately - show what Site A has that Site B is missing
1943
- - Use concrete examples: "Site A has a Team page at /team.html, Site B does not"
1944
- - If you need sub-pages, fetch them in follow-up steps after analyzing the main page
1945
- - BASE YOUR COMPARISON ONLY ON THE DATA YOU FETCHED - not on random files in the workspace
1946
- - Quote actual text from the fetched content to support your claims
1947
-
1948
- ### File Access:
1949
- - You can ONLY access files within the current project workspace
1950
- - Use relative paths (e.g., "src/file.js", "app.py", "./config.json")
1951
- - Never try to access system files or directories outside the workspace
1952
- - Do NOT read files unrelated to the user's request (e.g., don't read "comparison.md" when asked to fetch websites)
1953
- - When comparing WEBSITES, use fetch_url - do NOT use read_file or list_dir
1954
-
1955
- ### Tool Names:
1956
- - Use ONLY these exact tool names: list_dir, read_file, write_file, edit_file, bash, grep, glob, git, repo, fetch_url, ssh_exec
1957
- - The JSON must be valid with double quotes for all keys and string values
1958
- - After tool execution, you will receive results and can continue with the next step
1959
- - Explain what you're doing before using tools
1960
- `;
1961
-
1962
- return prompt;
1963
- }
1964
- }