/**
 * Vigthoria CLI Tools - Agentic Tool System
 *
 * This module provides Vigthoria Autonomous autonomous tool execution.
 * Tools can be called by the AI to perform actions.
 *
 * Enhanced with:
 * - Risk-based permission system
 * - Automatic retry logic with exponential backoff
 * - Undo functionality for file operations
 * - Detailed error messages with suggestions
 *
 * @version 1.1.0
 * @author Vigthoria Labs
 */
import * as fs from 'fs';
import * as path from 'path';
import { execSync, spawn } from 'child_process';
import { createRequire } from 'node:module';
import chalk from 'chalk';
// ESM shim — re-create CommonJS-style `require()` so the inline
// `require('os')` / `require('minimatch')` / `require('glob')` calls
// inside lazy code paths continue to work unchanged in ESM mode.
const require = createRequire(import.meta.url);
import { CH } from './logger.js';
import { isServerRuntime } from './api.js';
const STREAM_RESPONSE_MAX_YIELD_CHARS = 32 * 1024;
const POWERSHELL_SAFE_PATH_PATTERN = /^[A-Za-z0-9_:\\/.\-\s]+$/;
const POWERSHELL_SAFE_INCLUDE_PATTERN = /^[A-Za-z0-9_*?.\-]+$/;
const SSH_SAFE_HOST_PATTERN = /^[A-Za-z0-9.-]+$/;
function getSshAllowedHosts() {
    const configured = String(process.env.VIGTHORIA_SSH_ALLOWED_HOSTS || '')
        .split(',')
        .map((v) => v.trim().toLowerCase())
        .filter(Boolean);
    const defaults = ['vigthoria-server', 'localhost', '127.0.0.1'];
    return new Set([...defaults, ...configured]);
}
function isNodeError(error) {
    return error instanceof Error && 'code' in error;
}
function resolveWindowsInstallerPath() {
    const configuredPath = process.env.VIGTHORIA_WINDOWS_INSTALLER || process.env.VIGTHORIA_UPDATE_INSTALLER;
    if (configuredPath && configuredPath.trim().length > 0) {
        return path.resolve(configuredPath);
    }
    const executableDir = path.dirname(process.execPath);
    const cwd = process.cwd();
    const candidates = [
        path.resolve(cwd, 'dist', 'VigthoriaSetup.exe'),
        path.resolve(cwd, 'release', 'VigthoriaSetup.exe'),
        path.resolve(cwd, 'VigthoriaSetup.exe'),
        path.resolve(executableDir, 'VigthoriaSetup.exe'),
        path.resolve(executableDir, '..', 'VigthoriaSetup.exe'),
    ];
    return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0];
}
export async function installUpdateWindows() {
    const installerPath = resolveWindowsInstallerPath();
    try {
        if (!fs.existsSync(installerPath)) {
            return { success: false, platform: 'windows', error: 'ENOENT' };
        }
        await fs.promises.access(installerPath, fs.constants.F_OK);
        await new Promise((resolve, reject) => {
            const child = spawn(installerPath, [], {
                cwd: path.dirname(installerPath),
                detached: true,
                stdio: 'ignore',
                windowsHide: false,
            });
            child.once('error', reject);
            child.once('spawn', () => {
                child.unref();
                resolve();
            });
        });
        return { success: true, platform: 'windows' };
    }
    catch (error) {
        if (isNodeError(error) && error.code === 'ENOENT') {
            return { success: false, platform: 'windows', error: 'ENOENT' };
        }
        const message = error instanceof Error ? error.message : String(error);
        return { success: false, platform: 'windows', error: message };
    }
}
export async function* robustifyStreamResponse(res) {
    const MAX_YIELD_CHARS = STREAM_RESPONSE_MAX_YIELD_CHARS;
    const MAX_BUFFER_CHARS = 256 * 1024;
    const body = res?.body ?? res;
    const decoder = new TextDecoder('utf-8');
    let reader = null;
    let lineBuffer = '';
    const emitContent = async function* (type, content) {
        for (let offset = 0; offset < content.length; offset += MAX_YIELD_CHARS) {
            const part = content.slice(offset, offset + MAX_YIELD_CHARS);
            if (part.length > 0) {
                yield { type, content: part };
            }
        }
    };
    const textFromObject = (value) => {
        if (!value || typeof value !== 'object')
            return '';
        if (typeof value.content === 'string')
            return value.content;
        if (typeof value.text === 'string')
            return value.text;
        if (typeof value.delta === 'string')
            return value.delta;
        if (typeof value.delta?.text === 'string')
            return value.delta.text;
        if (typeof value.message?.content === 'string')
            return value.message.content;
        if (typeof value.choices?.[0]?.delta?.content === 'string')
            return value.choices[0].delta.content;
        if (typeof value.choices?.[0]?.message?.content === 'string')
            return value.choices[0].message.content;
        if (typeof value.error === 'string')
            return value.error;
        if (typeof value.error?.message === 'string')
            return value.error.message;
        return '';
    };
    const stringifyChunk = (chunk) => {
        if (typeof chunk === 'string')
            return chunk;
        if (Buffer.isBuffer(chunk))
            return chunk.toString('utf8');
        if (chunk instanceof Uint8Array)
            return Buffer.from(chunk).toString('utf8');
        if (chunk instanceof ArrayBuffer)
            return Buffer.from(chunk).toString('utf8');
        if (chunk === null || chunk === undefined)
            return '';
        const objectText = textFromObject(chunk);
        return objectText || String(chunk);
    };
    const decodeLine = (line) => {
        const trimmed = line.trim();
        if (!trimmed || trimmed === 'event: ping' || trimmed === ':' || trimmed === 'data: [DONE]' || trimmed === '[DONE]') {
            return null;
        }
        const payload = trimmed.startsWith('data:') ? trimmed.slice(5).trimStart() : trimmed;
        if (!payload || payload === '[DONE]')
            return null;
        if ((payload.startsWith('{') && payload.endsWith('}')) || (payload.startsWith('[') && payload.endsWith(']'))) {
            try {
                const parsed = JSON.parse(payload);
                const parsedText = textFromObject(parsed);
                if (parsedText) {
                    const type = parsed.error ? 'error' : 'delta';
                    return { type, content: parsedText };
                }
            }
            catch (error) {
                console.debug(`Stream JSON fragment preserved as text: ${error instanceof Error ? error.message : String(error)}`);
            }
        }
        if (payload.startsWith('event:') || payload.startsWith('id:') || payload.startsWith('retry:')) {
            return null;
        }
        return { type: 'delta', content: payload };
    };
    const consumeText = async function* (text, flush = false) {
        if (text) {
            lineBuffer += text;
        }
        while (lineBuffer.length > MAX_BUFFER_CHARS) {
            const newlineIndex = lineBuffer.indexOf('\n', Math.max(0, MAX_BUFFER_CHARS - MAX_YIELD_CHARS));
            const cutIndex = newlineIndex >= 0 ? newlineIndex + 1 : MAX_BUFFER_CHARS;
            const overflow = lineBuffer.slice(0, cutIndex);
            lineBuffer = lineBuffer.slice(cutIndex);
            const decoded = decodeLine(overflow);
            if (decoded) {
                yield* emitContent(decoded.type, decoded.content);
            }
            else {
                yield* emitContent('delta', overflow);
            }
        }
        const lines = lineBuffer.split(/\r?\n/);
        const partialLine = lines.pop() ?? '';
        for (const line of lines) {
            const decoded = decodeLine(line);
            if (decoded) {
                yield* emitContent(decoded.type, decoded.content);
            }
        }
        if (flush) {
            lineBuffer = '';
            if (partialLine) {
                const decoded = decodeLine(partialLine);
                if (decoded) {
                    yield* emitContent(decoded.type, decoded.content);
                }
            }
        }
        else {
            lineBuffer = partialLine;
        }
    };
    try {
        if (!body) {
            return;
        }
        if (typeof body.getReader === 'function') {
            reader = body.getReader();
            const streamReader = reader;
            const decoder = new TextDecoder();
            while (true) {
                const { done, value } = await streamReader.read();
                if (done)
                    break;
                const content = decoder.decode(value, { stream: true });
                if (content.length > 0) {
                    yield* consumeText(content);
                }
            }
            const tail = decoder.decode();
            if (tail.length > 0) {
                yield* consumeText(tail);
            }
            yield* consumeText('', true);
            return;
        }
        if (typeof body[Symbol.asyncIterator] === 'function') {
            for await (const chunk of body) {
                const content = stringifyChunk(chunk);
                if (content.length > 0) {
                    yield* consumeText(content);
                }
            }
            yield* consumeText('', true);
            return;
        }
        const content = stringifyChunk(body);
        if (content.length > 0) {
            yield* emitContent('text', content);
        }
    }
    catch (error) {
        const content = error instanceof Error ? error.message : String(error);
        yield { type: 'error', content };
    }
    finally {
        lineBuffer = '';
        try {
            reader?.releaseLock();
        }
        catch (error) {
            const message = error instanceof Error ? error.message : String(error);
            console.debug(`Stream reader release failed: ${message}`);
        }
    }
}
const TOOL_ARG_ALIASES = {
    read_file: {
        path: ['file', 'filePath', 'filepath', 'target', 'targetPath'],
        start_line: ['start', 'startLine', 'fromLine', 'lineStart'],
        end_line: ['end', 'endLine', 'toLine', 'lineEnd'],
    },
    write_file: {
        path: ['file', 'filePath', 'filepath', 'target', 'targetPath'],
        content: ['text', 'contents', 'body'],
    },
    edit_file: {
        path: ['file', 'filePath', 'filepath', 'target', 'targetPath'],
        old_text: ['old', 'oldText', 'find', 'search', 'searchText'],
        new_text: ['new', 'newText', 'replace', 'replaceText', 'replacement'],
    },
    bash: {
        command: ['cmd', 'script'],
        cwd: ['path', 'dir', 'directory'],
    },
    grep: {
        pattern: ['query', 'search', 'regex', 'text'],
        path: ['dir', 'directory', 'cwd', 'root'],
        include: ['includePattern', 'filePattern', 'glob'],
    },
    list_dir: {
        path: ['dir', 'directory', 'cwd', 'root'],
        recursive: ['recurse'],
    },
    glob: {
        pattern: ['query', 'search', 'path', 'file', 'name', 'filename', 'glob'],
    },
    git: {
        args: ['command', 'cmd'],
    },
    fetch_url: {
        url: ['link', 'href'],
        method: ['httpMethod'],
        headers: ['header'],
        body: ['content', 'data'],
        selector: ['css', 'cssSelector'],
    },
    ssh_exec: {
        command: ['cmd', 'script'],
        host: ['server'],
    },
    task: {
        description: ['prompt', 'task', 'query', 'instructions'],
        working_dir: ['cwd', 'dir', 'directory', 'workDir'],
    },
    multi_edit: {
        edits: ['changes', 'operations', 'replacements'],
    },
    codebase_search: {
        query: ['search', 'pattern', 'text', 'symbol'],
        scope: ['type', 'mode'],
        include: ['includePattern', 'filePattern', 'glob'],
        max_results: ['limit', 'maxResults', 'count'],
    },
};
// Error types for better handling
export var ToolErrorType;
(function (ToolErrorType) {
    ToolErrorType["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
    ToolErrorType["PERMISSION_DENIED"] = "PERMISSION_DENIED";
    ToolErrorType["NETWORK_ERROR"] = "NETWORK_ERROR";
    ToolErrorType["TIMEOUT"] = "TIMEOUT";
    ToolErrorType["INVALID_ARGS"] = "INVALID_ARGS";
    ToolErrorType["EXECUTION_FAILED"] = "EXECUTION_FAILED";
    ToolErrorType["USER_CANCELLED"] = "USER_CANCELLED";
})(ToolErrorType || (ToolErrorType = {}));
export class AgenticTools {
    logger;
    cwd;
    permissionCallback;
    autoApprove;
    undoStack = [];
    maxUndoStack = 50;
    retryConfig = {
        maxRetries: 3,
        baseDelayMs: 1000,
        maxDelayMs: 10000,
        retryableErrors: ['ECONNRESET', 'ETIMEDOUT', 'ENOTFOUND', 'ECONNREFUSED', 'EAI_AGAIN'],
    };
    formatExternalToolError(toolName, operation, error) {
        if (error instanceof Error) {
            const processError = error;
            const details = [
                `External tool call failed in ${toolName} during ${operation}: ${error.message}`,
                processError.code !== undefined ? `code=${processError.code}` : undefined,
                processError.status !== undefined ? `status=${processError.status}` : undefined,
                processError.signal ? `signal=${processError.signal}` : undefined,
                processError.stderr ? `stderr=${processError.stderr.toString().trim()}` : undefined,
                processError.stdout ? `stdout=${processError.stdout.toString().trim()}` : undefined,
            ].filter(Boolean);
            return details.join(' | ');
        }
        return `External tool call failed in ${toolName} during ${operation}: ${String(error)}`;
    }
    externalToolFailure(toolName, operation, error, suggestion) {
        const message = this.formatExternalToolError(toolName, operation, error);
        this.logger.debug(message);
        this.logger.warn(message);
        return {
            success: false,
            error: message,
            suggestion: suggestion || 'Review the command, arguments, permissions, and environment, then retry.',
            canRetry: true,
        };
    }
    cleanupAfterToolError(toolName, operation, cleanup) {
        try {
            cleanup();
        }
        catch (cleanupError) {
            const message = this.formatExternalToolError(toolName, `${operation} cleanup`, cleanupError);
            this.logger.debug(message);
            this.logger.warn(message);
        }
    }
    runExternalCommand(toolName, operation, command, options, cleanup) {
        if (!this.isNonEmptyString(toolName)) {
            throw new Error('Invalid tool execution: toolName must be a non-empty string.');
        }
        if (!this.isNonEmptyString(operation)) {
            throw new Error(`Invalid external command for ${toolName}: operation must be a non-empty string.`);
        }
        if (!this.isNonEmptyString(command)) {
            throw new Error(`Invalid external command for ${toolName} during ${operation}: command must be a non-empty string.`);
        }
        try {
            return execSync(command, options);
        }
        catch (error) {
            if (cleanup) {
                this.cleanupAfterToolError(toolName, operation, cleanup);
            }
            const message = this.formatExternalToolError(toolName, operation, error);
            const wrapped = new Error(message);
            wrapped.cause = error;
            throw wrapped;
        }
    }
    isNonEmptyString(value) {
        return typeof value === 'string' && value.trim().length > 0;
    }
    describeInvalidValue(value) {
        if (value === null)
            return 'null';
        if (value === undefined)
            return 'undefined';
        if (Array.isArray(value))
            return 'array';
        return typeof value;
    }
    assertStringRecord(value, context) {
        if (!value || typeof value !== 'object' || Array.isArray(value)) {
            throw new Error(`${context} must be an object with string values; received ${this.describeInvalidValue(value)}.`);
        }
        for (const [key, entryValue] of Object.entries(value)) {
            if (!this.isNonEmptyString(key)) {
                throw new Error(`${context} contains an invalid empty parameter name.`);
            }
            if (typeof entryValue !== 'string') {
                throw new Error(`${context}.${key} must be a string; received ${this.describeInvalidValue(entryValue)}.`);
            }
        }
    }
    requireNonEmptyString(value, fieldName, toolName) {
        if (!this.isNonEmptyString(value)) {
            throw new Error(`Invalid arguments for ${toolName}: ${fieldName} is required and must be a non-empty string.`);
        }
        return value;
    }
    requireArgsObject(args, toolName) {
        this.assertStringRecord(args, `Invalid arguments for ${toolName}: args`);
    }
    // Session-based tool approvals - remembers which tools user approved for this turn
    sessionApprovedTools = new Set();
    // Persistent permissions - tool allowlists per project
    static permissionsFile = path.join(process.env.HOME || process.env.USERPROFILE || '~', '.vigthoria', 'permissions.json');
    constructor(logger, cwd, permissionCallback, autoApprove = false) {
        if (!logger) {
            throw new Error('AgenticTools initialization failed: logger is required.');
        }
        if (typeof cwd !== 'string' || cwd.trim().length === 0) {
            throw new Error('AgenticTools initialization failed: cwd must be a non-empty string.');
        }
        if (typeof permissionCallback !== 'function') {
            throw new Error('AgenticTools initialization failed: permissionCallback must be a function.');
        }
        if (typeof autoApprove !== 'boolean') {
            throw new Error('AgenticTools initialization failed: autoApprove must be a boolean.');
        }
        this.logger = logger;
        this.cwd = cwd;
        this.permissionCallback = permissionCallback;
        this.autoApprove = autoApprove;
    }
    getErrorMessage(error) {
        if (error instanceof Error) {
            return error.message;
        }
        if (typeof error === 'string') {
            return error;
        }
        try {
            return JSON.stringify(error);
        }
        catch {
            return String(error);
        }
    }
    assertToolCall(call) {
        if (!call || typeof call !== 'object') {
            throw new Error('Invalid tool call: call must be an object.');
        }
        if (typeof call.tool !== 'string' || call.tool.trim().length === 0) {
            throw new Error('Invalid tool call: tool name must be a non-empty string.');
        }
        if (!call.args || typeof call.args !== 'object' || Array.isArray(call.args)) {
            throw new Error(`Invalid tool call for ${call.tool}: args must be an object.`);
        }
        for (const [key, value] of Object.entries(call.args)) {
            if (typeof key !== 'string' || key.trim().length === 0) {
                throw new Error(`Invalid tool call for ${call.tool}: argument names must be non-empty strings.`);
            }
            if (typeof value !== 'string') {
                throw new Error(`Invalid argument "${key}" for ${call.tool}: expected string, received ${typeof value}.`);
            }
        }
    }
    /**
     * Load persistent permissions for the current project
     */
    loadPersistentPermissions() {
        try {
            if (fs.existsSync(AgenticTools.permissionsFile)) {
                return JSON.parse(fs.readFileSync(AgenticTools.permissionsFile, 'utf-8'));
            }
        }
        catch (error) {
            const message = this.formatExternalToolError('permissions', `read ${AgenticTools.permissionsFile}`, error);
            this.logger.debug(message);
            this.logger.warn(message);
        }
        return {};
    }
    /**
     * Save a persistent permission for a tool in the current project
     */
    savePersistentPermission(toolName) {
        const permissions = this.loadPersistentPermissions();
        const projectKey = this.cwd;
        if (!permissions[projectKey]) {
            permissions[projectKey] = { tools: [], updatedAt: new Date().toISOString() };
        }
        if (!permissions[projectKey].tools.includes(toolName)) {
            permissions[projectKey].tools.push(toolName);
            permissions[projectKey].updatedAt = new Date().toISOString();
        }
        try {
            const dir = path.dirname(AgenticTools.permissionsFile);
            if (!fs.existsSync(dir))
                fs.mkdirSync(dir, { recursive: true });
            fs.writeFileSync(AgenticTools.permissionsFile, JSON.stringify(permissions, null, 2), 'utf-8');
        }
        catch (error) {
            const message = this.formatExternalToolError('permissions', `write ${AgenticTools.permissionsFile}`, error);
            this.logger.debug(message);
            this.logger.warn(message);
        }
    }
    /**
     * Check if a tool has persistent permission for the current project
     */
    hasPersistentPermission(toolName) {
        const permissions = this.loadPersistentPermissions();
        const projectKey = this.cwd;
        return permissions[projectKey]?.tools?.includes(toolName) || false;
    }
    /**
     * Clear session-approved tools (call this at the start of each new AI turn)
     */
    clearSessionApprovals() {
        this.sessionApprovedTools.clear();
    }
    /**
     * Get currently approved tools for this session
     */
    getSessionApprovedTools() {
        return Array.from(this.sessionApprovedTools);
    }
    /**
     * Get the undo stack for inspection
     */
    getUndoStack() {
        return [...this.undoStack];
    }
    /**
     * Undo the last file operation
     */
    async undo() {
        const lastOp = this.undoStack.pop();
        if (!lastOp) {
            return {
                success: false,
                error: 'Nothing to undo',
                suggestion: 'The undo stack is empty. Only file write/edit operations can be undone.',
            };
        }
        if (lastOp.filePath) {
            try {
                if (lastOp.originalContent === null) {
                    // File was created, so delete it
                    if (fs.existsSync(lastOp.filePath)) {
                        fs.unlinkSync(lastOp.filePath);
                        return {
                            success: true,
                            output: `${CH.success} Undone: ${lastOp.description}\n  File deleted: ${lastOp.filePath}`,
                            metadata: { remainingUndos: this.undoStack.length },
                        };
                    }
                }
                else if (lastOp.originalContent !== undefined) {
                    // Restore original content
                    fs.writeFileSync(lastOp.filePath, lastOp.originalContent, 'utf-8');
                    return {
                        success: true,
                        output: `${CH.success} Undone: ${lastOp.description}\n  File restored: ${lastOp.filePath}`,
                        metadata: { remainingUndos: this.undoStack.length },
                    };
                }
            }
            catch (error) {
                return {
                    success: false,
                    error: `Failed to undo: ${error.message}`,
                    suggestion: 'The file may have been moved or permissions changed.',
                };
            }
        }
        return {
            success: false,
            error: 'This operation cannot be undone',
        };
    }
    /**
     * List of available tools - Vigthoria's advanced
     * Enhanced with risk levels and categories
     */
    static getToolDefinitions() {
        return [
            {
                name: 'read_file',
                description: 'Read the contents of a file',
                parameters: [
                    { name: 'path', description: 'File path (relative or absolute)', required: true },
                    { name: 'start_line', description: 'Start line (1-indexed)', required: false },
                    { name: 'end_line', description: 'End line (1-indexed)', required: false },
                ],
                requiresPermission: false,
                dangerous: false,
                riskLevel: 'low',
                category: 'read',
            },
            {
                name: 'write_file',
                description: 'Write content to a file (creates if not exists)',
                parameters: [
                    { name: 'path', description: 'File path', required: true },
                    { name: 'content', description: 'Content to write', required: true },
                ],
                requiresPermission: true,
                dangerous: false,
                riskLevel: 'medium',
                category: 'write',
            },
            {
                name: 'edit_file',
                description: 'Make specific edits to a file by replacing text',
                parameters: [
                    { name: 'path', description: 'File path', required: true },
                    { name: 'old_text', description: 'Text to replace', required: true },
                    { name: 'new_text', description: 'New text', required: true },
                ],
                requiresPermission: true,
                dangerous: false,
                riskLevel: 'medium',
                category: 'write',
            },
            {
                name: 'bash',
                description: 'Run a shell command',
                parameters: [
                    { name: 'command', description: 'Shell command to execute', required: true },
                    { name: 'cwd', description: 'Working directory', required: false },
                    { name: 'timeout', description: 'Timeout in seconds', required: false },
                ],
                requiresPermission: true,
                dangerous: true,
                riskLevel: 'high',
                category: 'execute',
            },
            {
                name: 'grep',
                description: 'Search for patterns in files',
                parameters: [
                    { name: 'pattern', description: 'Search pattern (regex)', required: true },
                    { name: 'path', description: 'File or directory path', required: false },
                    { name: 'include', description: 'File pattern to include (e.g., *.ts)', required: false },
                ],
                requiresPermission: false,
                dangerous: false,
                riskLevel: 'low',
                category: 'search',
            },
            {
                name: 'list_dir',
                description: 'List contents of a directory',
                parameters: [
                    { name: 'path', description: 'Directory path', required: true },
                    { name: 'recursive', description: 'List recursively', required: false },
                ],
                requiresPermission: false,
                dangerous: false,
                riskLevel: 'low',
                category: 'read',
            },
            {
                name: 'glob',
                description: 'Find files matching a pattern',
                parameters: [
                    { name: 'pattern', description: 'Glob pattern (e.g., **/*.ts)', required: true },
                ],
                requiresPermission: false,
                dangerous: false,
                riskLevel: 'low',
                category: 'search',
            },
            {
                name: 'git',
                description: 'Run git commands',
                parameters: [
                    { name: 'args', description: 'Git command arguments', required: true },
                ],
                requiresPermission: true,
                dangerous: false,
                riskLevel: 'medium',
                category: 'execute',
            },
            {
                name: 'repo',
                description: 'Manage projects in Vigthoria Repository - push, pull, list, share, delete, or clone projects',
                parameters: [
                    { name: 'action', description: 'Action: push, pull, list, status, share, delete, clone', required: true },
                    { name: 'project', description: 'Project name (for push/pull/status/share/delete)', required: false },
                    { name: 'files', description: 'Files to push as JSON object {filename: content} or array [{path, content}]', required: false },
                    { name: 'description', description: 'Project description (for push)', required: false },
                    { name: 'visibility', description: 'Visibility: public or private (for push)', required: false },
                    { name: 'path', description: 'Directory path (for push) or target path (for clone)', required: false },
                    { name: 'username', description: 'Username to share with (for share action)', required: false },
                    { name: 'permission', description: 'Permission level: read, write, admin (for share action)', required: false },
                ],
                requiresPermission: true,
                dangerous: false,
                riskLevel: 'medium',
                category: 'execute',
            },
            {
                name: 'fetch_url',
                description: 'Fetch content from a URL (web page, API endpoint). Works cross-platform on Windows, Mac, and Linux.',
                parameters: [
                    { name: 'url', description: 'URL to fetch (must be http or https)', required: true },
                    { name: 'method', description: 'HTTP method (GET, POST, etc.)', required: false },
                    { name: 'headers', description: 'JSON string of headers to send', required: false },
                    { name: 'body', description: 'Request body for POST/PUT requests', required: false },
                    { name: 'selector', description: 'CSS selector to extract specific content (for HTML)', required: false },
                ],
                requiresPermission: true,
                dangerous: false,
                riskLevel: 'low',
                category: 'read',
            },
            {
                name: 'browser',
                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.',
                parameters: [
                    { name: 'mode', description: "One of: 'capture' (screenshot + html + metrics), 'errors' (console + page errors), 'test' (quick smoke test)", required: true },
                    { name: 'url', description: 'Target URL (must start with http:// or https://)', required: true },
                    { name: 'include_screenshot', description: "For mode=capture: 'true' to include base64 screenshot (default true), 'false' to skip", required: false },
                ],
                requiresPermission: true,
                dangerous: false,
                riskLevel: 'low',
                category: 'read',
            },
            {
                name: 'ssh_exec',
                description: 'Execute a command on a remote server via SSH (useful for Unix commands from Windows)',
                parameters: [
                    { name: 'command', description: 'Command to execute on remote server', required: true },
                    { name: 'host', description: 'SSH host (default: vigthoria-server)', required: false },
                    { name: 'timeout', description: 'Timeout in seconds', required: false },
                ],
                requiresPermission: true,
                dangerous: true,
                riskLevel: 'high',
                category: 'execute',
            },
            {
                name: 'task',
                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.',
                parameters: [
                    { name: 'description', description: 'A detailed description of the subtask for the sub-agent to perform', required: true },
                    { name: 'working_dir', description: 'Working directory for the sub-agent (relative to project root)', required: false },
                ],
                requiresPermission: true,
                dangerous: false,
                riskLevel: 'medium',
                category: 'execute',
            },
            {
                name: 'multi_edit',
                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.',
                parameters: [
                    { name: 'edits', description: 'JSON array of edits: [{"path": "file.ts", "old_text": "find this", "new_text": "replace with"}]', required: true },
                ],
                requiresPermission: true,
                dangerous: false,
                riskLevel: 'medium',
                category: 'write',
            },
            {
                name: 'codebase_search',
                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.',
                parameters: [
                    { name: 'query', description: 'Search query - can be a symbol name, concept, or natural language description', required: true },
                    { name: 'scope', description: 'Search scope: "symbols" (functions/classes), "files" (filenames), "content" (full-text), or "all" (default)', required: false },
                    { name: 'include', description: 'File pattern to include (e.g., "*.ts", "src/**/*.js")', required: false },
                    { name: 'max_results', description: 'Maximum results to return (default: 30)', required: false },
                ],
                requiresPermission: false,
                dangerous: false,
                riskLevel: 'low',
                category: 'search',
            },
        ];
    }
    /**
     * Execute a tool call with enhanced error handling and retry logic
     */
    async execute(call) {
        // Guard against malformed tool calls before accessing fields.
        if (!call || typeof call !== 'object') {
            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.');
        }
        if (!call.tool || typeof call.tool !== 'string' || !call.tool.trim()) {
            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(', ')}`);
        }
        if (!call.args || typeof call.args !== 'object' || Array.isArray(call.args)) {
            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" }.');
        }
        try {
            this.assertStringRecord(call.args, `Invalid tool call for '${call.tool}': args`);
        }
        catch (error) {
            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.');
        }
        const normalizedCall = this.normalizeToolCall(call);
        const tool = AgenticTools.getToolDefinitions().find(t => t.name === normalizedCall.tool);
        if (!tool) {
            return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Unknown tool: ${call.tool}`, `Available tools: ${AgenticTools.getToolDefinitions().map(t => t.name).join(', ')}`);
        }
        // Validate required parameters
        const validationError = this.validateParameters(normalizedCall, tool);
        if (validationError) {
            return validationError;
        }
        // Check permission for dangerous/modifying actions
        if (tool.requiresPermission && !this.autoApprove) {
            // Check persistent permissions first (project-scoped), then session
            if (this.hasPersistentPermission(normalizedCall.tool)) {
                this.logger.info(`${call.tool}: Auto-approved (persistent)`);
            }
            else if (this.sessionApprovedTools.has(normalizedCall.tool)) {
                // Already approved - skip permission prompt
                this.logger.info(`${call.tool}: Auto-approved (batch)`);
            }
            else {
                const approved = await this.permissionCallback(this.formatPermissionRequest(normalizedCall, tool), { batchApproval: true });
                if (approved === false) {
                    return {
                        success: false,
                        error: 'Permission denied by user',
                        canRetry: true,
                    };
                }
                // 'batch' (typed 'a') = approve for this session
                // 'persist' (typed 'p') = approve permanently for this project
                // 'y' or 'yes' = approve this single request only
                if (approved === 'batch') {
                    this.sessionApprovedTools.add(normalizedCall.tool);
                }
                else if (approved === 'persist') {
                    this.sessionApprovedTools.add(normalizedCall.tool);
                    this.savePersistentPermission(normalizedCall.tool);
                    this.logger.info(`${normalizedCall.tool}: Saved as persistent permission`);
                }
            }
        }
        // Execute with retry logic for applicable operations
        return this.executeWithRetry(normalizedCall, tool);
    }
    normalizeToolCall(call) {
        const tool = String(call.tool || '').trim();
        const originalArgs = call.args || {};
        const args = { ...originalArgs };
        const aliasMap = TOOL_ARG_ALIASES[tool] || {};
        for (const [canonicalName, aliases] of Object.entries(aliasMap)) {
            if (args[canonicalName]) {
                continue;
            }
            for (const alias of aliases) {
                const aliasValue = args[alias];
                if (typeof aliasValue === 'string' && aliasValue.trim()) {
                    args[canonicalName] = aliasValue;
                    break;
                }
            }
        }
        if (tool === 'list_dir' && !args.path) {
            args.path = '.';
        }
        if (tool === 'glob') {
            if (!args.pattern && args.path) {
                args.pattern = args.path;
            }
            if (args.pattern) {
                const normalizedPattern = args.pattern.trim().replace(/\\/g, '/');
                if (normalizedPattern && !/[\[*?{}]/.test(normalizedPattern)) {
                    if (normalizedPattern.includes('/')) {
                        args.pattern = normalizedPattern;
                    }
                    else {
                        args.pattern = `**/${normalizedPattern}`;
                    }
                }
                else {
                    args.pattern = normalizedPattern;
                }
            }
        }
        return { tool, args };
    }
    /**
     * Execute tool with automatic retry for transient failures
     */
    async executeWithRetry(call, tool) {
        let lastError = null;
        for (let attempt = 0; attempt <= this.retryConfig.maxRetries; attempt++) {
            try {
                const result = await this.executeTool(call);
                if (result.success) {
                    return result;
                }
                // Check if error is retryable
                const isRetryable = result.canRetry !== false &&
                    this.isRetryableError(result.error || '');
                if (!isRetryable || attempt === this.retryConfig.maxRetries) {
                    return result;
                }
                lastError = result;
                // Calculate delay with exponential backoff
                const delay = Math.min(this.retryConfig.baseDelayMs * Math.pow(2, attempt), this.retryConfig.maxDelayMs);
                this.logger.warn(`Retrying ${call.tool} in ${delay}ms (attempt ${attempt + 2}/${this.retryConfig.maxRetries + 1})...`);
                await this.sleep(delay);
            }
            catch (error) {
                lastError = this.createErrorResult(ToolErrorType.EXECUTION_FAILED, error.message);
                if (attempt === this.retryConfig.maxRetries) {
                    return lastError;
                }
            }
        }
        return lastError || this.createErrorResult(ToolErrorType.EXECUTION_FAILED, 'Unknown error after retries');
    }
    /**
     * Tool names that mutate the user's filesystem, shell state, or remote
     * services.  Used by the dry-run / read-only gate below.
     */
    static MUTATING_TOOLS = new Set([
        'write_file', 'edit_file', 'multi_edit',
        'bash', 'ssh_exec',
        'git', 'repo',
    ]);
    /**
     * `VIGTHORIA_DRY_RUN=1` and `VIGTHORIA_READ_ONLY=1` are end-user safety
     * switches: every mutating tool short-circuits with a clear "would have
     * happened" result instead of touching the filesystem or network.
     *
     * The flags are checked at call-time (not at construction time) so they
     * can be flipped per-prompt by users who want to inspect agent intent
     * before committing.
     */
    isDryRunActive() {
        const flag = (name) => String(process.env[name] || '').trim().toLowerCase();
        const isOn = (v) => v === '1' || v === 'true' || v === 'yes' || v === 'on';
        return isOn(flag('VIGTHORIA_DRY_RUN')) || isOn(flag('VIGTHORIA_READ_ONLY'));
    }
    /**
     * Execute the actual tool operation
     */
    async executeTool(call) {
        try {
            if (this.isDryRunActive() && AgenticTools.MUTATING_TOOLS.has(call.tool)) {
                const argSummary = this.safeStringifyArgs(call.args);
                const message = `Dry-run: ${call.tool} would have run with ${argSummary}. Unset VIGTHORIA_DRY_RUN to execute.`;
                this.logger.warn(message);
                return {
                    success: true,
                    output: '',
                    dryRun: true,
                    message,
                };
            }
            switch (call.tool) {
                case 'read_file':
                    return this.readFile(call.args);
                case 'write_file':
                    return this.writeFile(call.args);
                case 'edit_file':
                    return this.editFile(call.args);
                case 'bash':
                    return this.bash(call.args);
                case 'grep':
                    return this.grep(call.args);
                case 'list_dir':
                    return this.listDir(call.args);
                case 'glob':
                    return this.glob(call.args);
                case 'git':
                    return this.git(call.args);
                case 'repo':
                    return this.repo(call.args);
                case 'fetch_url':
                    return this.fetchUrl(call.args);
                case 'browser':
                    return this.browserTool(call.args);
                case 'ssh_exec':
                    return this.sshExec(call.args);
                case 'task':
                    return this.task(call.args);
                case 'multi_edit':
                    return this.multiEdit(call.args);
                case 'codebase_search':
                    return this.codebaseSearch(call.args);
                default:
                    return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Tool not implemented: ${call.tool}`);
            }
        }
        catch (error) {
            const context = `Tool '${call.tool}' failed while executing with args ${this.safeStringifyArgs(call.args)}`;
            const stderr = error?.stderr?.toString?.().trim();
            const stdout = error?.stdout?.toString?.().trim();
            const status = error?.status !== undefined ? `exit status ${error.status}` : undefined;
            const signal = error?.signal ? `signal ${error.signal}` : undefined;
            const details = [context, status, signal, stderr || error?.message || String(error)].filter(Boolean).join(': ');
            this.logger.error(details);
            return {
                success: false,
                output: stdout,
                error: details,
                suggestion: 'Review the tool arguments and subprocess output above, then retry with corrected input.',
                canRetry: this.isRetryableError(details),
            };
        }
    }
    /**
     * Check if an error is retryable
     */
    isRetryableError(error) {
        return this.retryConfig.retryableErrors.some(e => error.includes(e));
    }
    /**
     * Safely stringify tool arguments without dumping very large payloads into logs.
     */
    safeStringifyArgs(args) {
        try {
            const json = JSON.stringify(args ?? {}, (_key, value) => {
                if (typeof value === 'string' && value.length > 500) {
                    return `${value.slice(0, 500)}...<truncated ${value.length - 500} chars>`;
                }
                return value;
            });
            return json || '{}';
        }
        catch (error) {
            return `[unserializable args: ${error instanceof Error ? error.message : String(error)}]`;
        }
    }
    /**
     * Validate tool parameters
     */
    validateParameters(call, tool) {
        if (!call || typeof call !== 'object') {
            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" } }.');
        }
        if (!call.args || typeof call.args !== 'object' || Array.isArray(call.args)) {
            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)}`);
        }
        for (const [key, value] of Object.entries(call.args)) {
            if (!key || typeof key !== 'string') {
                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.');
            }
            if (typeof value !== 'string') {
                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}.`);
            }
        }
        for (const param of tool.parameters) {
            const value = call.args[param.name];
            if (param.required && (value === undefined || value.trim() === '')) {
                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}`);
            }
        }
        const pathLikeParams = ['path', 'working_dir', 'cwd'];
        for (const paramName of pathLikeParams) {
            const value = call.args[paramName];
            if (typeof value === 'string' && value.includes('\0')) {
                return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid ${paramName} for ${tool.name}: paths cannot contain null bytes`, 'Remove null bytes from the path and retry.');
            }
        }
        if (call.args.start_line !== undefined && (!/^\d+$/.test(call.args.start_line) || Number(call.args.start_line) < 1)) {
            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.');
        }
        if (call.args.end_line !== undefined && (!/^\d+$/.test(call.args.end_line) || Number(call.args.end_line) < 0)) {
            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.');
        }
        if (call.args.start_line !== undefined && call.args.end_line !== undefined) {
            const startLine = Number(call.args.start_line);
            const endLine = Number(call.args.end_line);
            if (endLine !== 0 && endLine < startLine) {
                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.');
            }
        }
        if (call.args.timeout !== undefined && (!/^\d+$/.test(call.args.timeout) || Number(call.args.timeout) < 1)) {
            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.');
        }
        if (call.args.max_results !== undefined && (!/^\d+$/.test(call.args.max_results) || Number(call.args.max_results) < 1)) {
            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.');
        }
        if (call.tool === 'list_dir' && call.args.recursive !== undefined && !['true', 'false', '1', '0', 'yes', 'no'].includes(call.args.recursive.toLowerCase())) {
            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".');
        }
        if (call.tool === 'fetch_url' && call.args.url !== undefined) {
            try {
                const parsed = new URL(call.args.url);
                if (!['http:', 'https:'].includes(parsed.protocol)) {
                    return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid URL protocol for fetch_url: '${parsed.protocol}'`, 'Use an http:// or https:// URL.');
                }
            }
            catch (error) {
                const message = this.getErrorMessage(error);
                this.logger.debug(`Invalid URL for fetch_url '${call.args.url}': ${message}`);
                return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid URL for fetch_url: '${call.args.url}'`, 'Provide a fully-qualified http:// or https:// URL.');
            }
        }
        if (call.tool === 'multi_edit' && call.args.edits !== undefined) {
            try {
                const edits = JSON.parse(call.args.edits);
                if (!Array.isArray(edits) || edits.length === 0) {
                    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.');
                }
                for (const [index, edit] of edits.entries()) {
                    if (!edit || typeof edit !== 'object' || Array.isArray(edit)) {
                        return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid edit at index ${index}: expected an object`);
                    }
                    for (const field of ['path', 'old_text', 'new_text']) {
                        if (typeof edit[field] !== 'string') {
                            return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid edit at index ${index}: '${field}' must be a string`);
                        }
                    }
                }
            }
            catch (error) {
                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.');
            }
        }
        return null;
    }
    /**
     * Create a standardized error result
     */
    createErrorResult(type, message, suggestion) {
        const suggestions = {
            [ToolErrorType.FILE_NOT_FOUND]: 'Check if the file path is correct. Use list_dir to see available files.',
            [ToolErrorType.PERMISSION_DENIED]: 'You may need elevated permissions. Try using sudo or check file ownership.',
            [ToolErrorType.NETWORK_ERROR]: 'Check your internet connection. The operation will retry automatically.',
            [ToolErrorType.TIMEOUT]: 'The operation took too long. Try with a shorter timeout or simpler command.',
            [ToolErrorType.INVALID_ARGS]: 'Check the tool documentation for correct parameter usage.',
            [ToolErrorType.EXECUTION_FAILED]: 'Review the command syntax and try again.',
            [ToolErrorType.USER_CANCELLED]: 'Operation cancelled. You can retry if needed.',
        };
        return {
            success: false,
            error: message,
            suggestion: suggestion || suggestions[type],
            canRetry: type !== ToolErrorType.USER_CANCELLED && type !== ToolErrorType.INVALID_ARGS,
        };
    }
    /**
     * Enhanced permission request with risk visualization
     */
    formatPermissionRequest(call, tool) {
        const riskColors = {
            low: chalk.green,
            medium: chalk.yellow,
            high: chalk.red,
            critical: chalk.bgRed.white,
        };
        const riskIcons = {
            low: '🟢',
            medium: '🟡',
            high: '🔴',
            critical: '⛔',
        };
        const riskColor = riskColors[tool.riskLevel];
        const riskIcon = riskIcons[tool.riskLevel];
        let msg = `\n${riskIcon} ${riskColor(`${tool.riskLevel.toUpperCase()} RISK`)} - AI wants to use ${chalk.cyan.bold(call.tool)}\n`;
        msg += chalk.gray(CH.hLine.repeat(50)) + '\n';
        // Tool-specific details
        if (call.tool === 'bash') {
            msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('Command:')} ${chalk.yellow(call.args.command)}\n`;
            if (call.args.cwd) {
                msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('Directory:')} ${call.args.cwd}\n`;
            }
            msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('Timeout:')} ${call.args.timeout || '30'}s\n`;
        }
        else if (call.tool === 'write_file') {
            msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('File:')} ${chalk.cyan(call.args.path)}\n`;
            const preview = call.args.content.substring(0, 100);
            msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('Content preview:')} ${chalk.gray(preview)}${call.args.content.length > 100 ? '...' : ''}\n`;
            msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('Size:')} ${call.args.content.length} bytes\n`;
        }
        else if (call.tool === 'edit_file') {
            msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('File:')} ${chalk.cyan(call.args.path)}\n`;
            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`;
            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`;
        }
        else if (call.tool === 'git') {
            msg += `${chalk.gray(CH.teeR + CH.hLine)} ${chalk.white('Command:')} git ${chalk.yellow(call.args.args)}\n`;
        }
        // Safety info
        msg += chalk.gray(CH.hLine.repeat(50)) + '\n';
        const canUndo = ['write_file', 'edit_file'].includes(call.tool);
        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`;
        msg += `${chalk.gray(CH.bl + CH.hLine)} ${chalk.white('Category:')} ${tool.category}\n`;
        if (tool.dangerous) {
            msg += `\n${chalk.red.bold(CH.warnEmoji + '  WARNING: This is a potentially dangerous action!')}\n`;
            msg += chalk.red('   The AI is requesting to execute commands on your system.\n');
        }
        // Add batch approval hint
        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`;
        return msg;
    }
    sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
    // Tool implementations with enhanced error handling and undo support
    /**
     * Read file with enhanced error handling and suggestions
     */
    readFile(args) {
        const filePath = this.resolvePath(args.path);
        if (!fs.existsSync(filePath)) {
            // Try to find similar files
            const dir = path.dirname(filePath);
            const basename = path.basename(filePath);
            let suggestions = [];
            if (fs.existsSync(dir)) {
                const files = fs.readdirSync(dir);
                suggestions = files
                    .filter(f => f.toLowerCase().includes(basename.toLowerCase().slice(0, 3)))
                    .slice(0, 3);
            }
            return this.createErrorResult(ToolErrorType.FILE_NOT_FOUND, `File not found: ${args.path}`, suggestions.length > 0
                ? `Did you mean one of these? ${suggestions.join(', ')}`
                : 'Use list_dir to see available files in the directory.');
        }
        try {
            const stats = fs.statSync(filePath);
            if (stats.size > 1024 * 1024) { // 1MB warning
                this.logger.warn(`Large file (${(stats.size / 1024 / 1024).toFixed(2)}MB) - consider using start_line/end_line`);
            }
            const content = fs.readFileSync(filePath, 'utf-8');
            const lines = content.split('\n');
            // Clamp start_line: API is 1-based; the model sometimes emits 0 or
            // negative values.  Silently clamp to valid range instead of failing.
            let rawStart = args.start_line ? parseInt(args.start_line) : 1;
            if (rawStart < 1)
                rawStart = 1;
            if (rawStart > lines.length)
                rawStart = lines.length;
            const startLine = rawStart - 1; // convert to 0-based
            let rawEnd = args.end_line ? parseInt(args.end_line) : lines.length;
            if (rawEnd < rawStart)
                rawEnd = rawStart;
            if (rawEnd > lines.length)
                rawEnd = lines.length;
            const endLine = rawEnd;
            const selectedLines = lines.slice(startLine, Math.min(endLine, lines.length));
            return {
                success: true,
                output: selectedLines.join('\n'),
                metadata: {
                    totalLines: lines.length,
                    linesReturned: selectedLines.length,
                    filePath: args.path,
                },
            };
        }
        catch (error) {
            if (error.code === 'EACCES') {
                return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, `Permission denied: ${args.path}`);
            }
            return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, error.message);
        }
    }
    /**
     * Write file with undo support
     */
    writeFile(args) {
        const filePath = this.resolvePath(args.path);
        const dir = path.dirname(filePath);
        // Save original content for undo if file exists
        let originalContent = null;
        if (fs.existsSync(filePath)) {
            originalContent = fs.readFileSync(filePath, 'utf-8');
        }
        try {
            // Create directory if needed
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir, { recursive: true });
            }
            fs.writeFileSync(filePath, args.content, 'utf-8');
            const validationErrors = this.validateWrittenFile(filePath, args.content);
            if (validationErrors.length > 0) {
                if (originalContent === null) {
                    fs.unlinkSync(filePath);
                }
                else {
                    fs.writeFileSync(filePath, originalContent, 'utf-8');
                }
                return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, `Validation failed after writing ${args.path}`, validationErrors.join(' '));
            }
            // Store undo operation
            const undoOp = {
                id: `undo-${Date.now()}`,
                tool: 'write_file',
                timestamp: Date.now(),
                filePath: filePath,
                originalContent: originalContent,
                description: originalContent
                    ? `Restore ${args.path} to previous version`
                    : `Delete ${args.path} (was created)`,
            };
            this.undoStack.push(undoOp);
            // Limit undo stack size
            if (this.undoStack.length > 50) {
                this.undoStack.shift();
            }
            const isNew = originalContent === null;
            return {
                success: true,
                output: `File ${isNew ? 'created' : 'updated'}: ${args.path}`,
                metadata: {
                    bytes: args.content.length,
                    isNew,
                    canUndo: true,
                },
            };
        }
        catch (error) {
            if (error.code === 'EACCES') {
                return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, `Permission denied writing to: ${args.path}`);
            }
            if (error.code === 'ENOSPC') {
                return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, 'No space left on device');
            }
            return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, error.message);
        }
    }
    /**
     * Edit file with undo support and helpful error messages
     */
    editFile(args) {
        const filePath = this.resolvePath(args.path);
        if (!fs.existsSync(filePath)) {
            return this.createErrorResult(ToolErrorType.FILE_NOT_FOUND, `File not found: ${args.path}`, 'Use write_file to create a new file, or check the path.');
        }
        try {
            let content = fs.readFileSync(filePath, 'utf-8');
            const originalContent = content;
            if (!content.includes(args.old_text)) {
                // Try to help identify the issue
                const lines = content.split('\n');
                const searchTerms = args.old_text.split('\n')[0].trim().slice(0, 30);
                const possibleMatches = lines
                    .map((line, i) => ({ line: i + 1, content: line }))
                    .filter(l => l.content.includes(searchTerms.slice(0, 10)))
                    .slice(0, 3);
                let suggestion = 'The exact text was not found. ';
                if (possibleMatches.length > 0) {
                    suggestion += `Similar content found at lines: ${possibleMatches.map(m => m.line).join(', ')}. `;
                }
                suggestion += 'Ensure whitespace and indentation match exactly.';
                return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, 'Old text not found in file', suggestion);
            }
            // Check for multiple matches
            const matchCount = (content.match(new RegExp(args.old_text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g')) || []).length;
            if (matchCount > 1) {
                this.logger.warn(`Found ${matchCount} matches - only replacing first occurrence`);
            }
            content = content.replace(args.old_text, args.new_text);
            fs.writeFileSync(filePath, content, 'utf-8');
            const validationErrors = this.validateWrittenFile(filePath, content);
            if (validationErrors.length > 0) {
                fs.writeFileSync(filePath, originalContent, 'utf-8');
                return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, `Validation failed after editing ${args.path}`, validationErrors.join(' '));
            }
            // Store undo operation
            const undoOp = {
                id: `undo-${Date.now()}`,
                tool: 'edit_file',
                timestamp: Date.now(),
                filePath: filePath,
                originalContent: originalContent,
                description: `Restore ${args.path} (reverts edit)`,
            };
            this.undoStack.push(undoOp);
            // Limit undo stack size
            if (this.undoStack.length > 50) {
                this.undoStack.shift();
            }
            // Show syntax-highlighted diff
            this.logger.unifiedDiff(args.path, args.old_text, args.new_text);
            return {
                success: true,
                output: `File edited: ${args.path}`,
                metadata: {
                    matchesFound: matchCount,
                    canUndo: true,
                },
            };
        }
        catch (error) {
            if (error.code === 'EACCES') {
                return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, `Permission denied: ${args.path}`);
            }
            return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, error.message);
        }
    }
    validateWrittenFile(filePath, content) {
        const errors = [];
        const extension = path.extname(filePath).toLowerCase();
        const placeholderPatterns = [
            /\.\.\.\s*(rest|more)/i,
            /implementation goes here/i,
            /replace (?:this|the) placeholder/i,
            /placeholder (?:text|content|copy|image)/i,
            /todo:/i,
            /all the .* from earlier/i,
        ];
        if (placeholderPatterns.some((pattern) => pattern.test(content))) {
            errors.push('The written file still contains placeholder or truncated content.');
        }
        if (extension === '.json') {
            try {
                JSON.parse(content);
            }
            catch (error) {
                errors.push(`JSON is invalid: ${error.message}`);
            }
        }
        if (extension === '.js' || extension === '.mjs' || extension === '.cjs') {
            const jsError = this.validateJavaScriptSyntax(content);
            if (jsError) {
                errors.push(jsError);
            }
        }
        if (extension === '.html' || extension === '.htm') {
            errors.push(...this.validateHtmlContent(content));
        }
        return errors;
    }
    validateJavaScriptSyntax(source) {
        const tempFile = path.join(this.cwd, `.vigthoria-temp-${Date.now()}.js`);
        try {
            try {
                fs.writeFileSync(tempFile, source, 'utf-8');
            }
            catch (writeError) {
                return this.formatExternalToolError('syntax_check', `write temporary file ${tempFile}`, writeError);
            }
            try {
                this.runExternalCommand('syntax_check', `node --check ${tempFile}`, `node --check "${tempFile}"`, { stdio: 'pipe' });
                return null;
            }
            catch (error) {
                const stderr = error.stderr?.toString()?.trim();
                return stderr || error.message || this.formatExternalToolError('syntax_check', `node --check ${tempFile}`, error);
            }
        }
        finally {
            this.cleanupAfterToolError('syntax_check', `remove temporary file ${tempFile}`, () => {
                if (fs.existsSync(tempFile)) {
                    fs.unlinkSync(tempFile);
                }
            });
        }
    }
    validateHtmlContent(content) {
        const errors = [];
        const requiredClosers = ['</html>', '</body>'];
        for (const closer of requiredClosers) {
            if (!content.toLowerCase().includes(closer)) {
                errors.push(`Missing required HTML closer: ${closer}`);
            }
        }
        const inlineScripts = [...content.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi)];
        inlineScripts.forEach((match, index) => {
            const scriptContent = match[1].trim();
            if (!scriptContent) {
                return;
            }
            const scriptError = this.validateJavaScriptSyntax(scriptContent);
            if (scriptError) {
                errors.push(`Inline script ${index + 1} has invalid JavaScript: ${scriptError}`);
            }
        });
        const selfClosingTags = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
        const stack = [];
        const tagRegex = /<\/?([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>/g;
        let match;
        while ((match = tagRegex.exec(content)) !== null) {
            const fullTag = match[0];
            const tagName = match[1].toLowerCase();
            if (selfClosingTags.has(tagName) || fullTag.endsWith('/>')) {
                continue;
            }
            if (fullTag.startsWith('</')) {
                const last = stack.pop();
                if (last !== tagName) {
                    errors.push(`Unbalanced HTML tags near </${tagName}>.`);
                    break;
                }
            }
            else {
                stack.push(tagName);
            }
        }
        if (stack.length > 0) {
            errors.push(`Unclosed HTML tags detected: ${stack.slice(-5).join(', ')}`);
        }
        return errors;
    }
    /**
     * Execute bash command with enhanced error handling
     * SECURITY: Commands are sandboxed to workspace directory
     * WINDOWS: Detects Unix-specific commands and suggests alternatives
     */
    bash(args) {
        const cwd = args.cwd ? this.resolvePath(args.cwd) : this.cwd;
        const timeout = args.timeout ? parseInt(args.timeout) * 1000 : 30000;
        const os = require('os');
        const platform = os.platform();
        // Unix-specific commands that don't exist on Windows
        const unixOnlyCommands = [
            'head', 'tail', 'grep', 'awk', 'sed', 'wc', 'cut', 'sort', 'uniq',
            'xargs', 'find', 'chmod', 'chown', 'ln', 'df', 'du', 'ps', 'kill',
            'top', 'htop', 'which', 'whereis', 'man', 'less', 'more', 'cat',
        ];
        // Check if command uses Unix-only tools on Windows
        if (platform === 'win32') {
            const cmdParts = args.command.split(/[|&;]/);
            for (const part of cmdParts) {
                const firstWord = part.trim().split(/\s+/)[0].toLowerCase();
                if (unixOnlyCommands.includes(firstWord)) {
                    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, ` +
                        `or use 'fetch_url' for web requests. ` +
                        `PowerShell alternatives: dir (ls), type (cat), findstr (grep), select-string (grep)`);
                }
            }
            // Check for pipe to Unix command
            if (args.command.includes('|')) {
                const pipedCommands = args.command.split('|').map(c => c.trim().split(/\s+/)[0].toLowerCase());
                for (const cmd of pipedCommands) {
                    if (unixOnlyCommands.includes(cmd)) {
                        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.`);
                    }
                }
            }
        }
        // SECURITY: Block dangerous commands that could access outside workspace
        // HARDENED: Protects Vigthoria ecosystem, server config, and system files
        const blockedPatterns = [
            // === System file access ===
            /\bcat\s+\/etc\//i, // Reading system files
            /\bcat\s+\/var\/(?!log)/i, // Reading /var/ except logs
            /\bcat\s+\/root\//i, // Reading root home
            /\bcat\s+\/home\/[^\/]+\/\.[^\/]/i, // Reading hidden files in home dirs
            /\bcat\s+~\/\./i, // Reading hidden files via ~
            /\bcd\s+(\/etc|\/var\/www|\/root|\/home)/i, // CD to sensitive dirs
            // === Destructive operations ===
            /\brm\s+-rf?\s+\//i, // Dangerous rm commands
            /\brm\s+-rf?\s+\.\.\//i, // rm going up directories
            /\brm\s+-rf?\s+~\//i, // rm in home directory
            /\b(curl|wget).*\|\s*(bash|sh)\b/i, // Downloading and executing scripts
            /\bsudo\b/i, // Sudo commands
            /\bsu\s+-/i, // Su to root
            /\bchmod\s+[0-7]*777/i, // World-writable permissions
            /\/(var\/www|opt)\/[a-z]+-?(database|models|coder|mcp|operator|voice|music)/i, // Vigthoria ecosystem
            /vigthoria-(models|database|mcp|operator|voice|music)/i, // Vigthoria project names
            // === Vigthoria Server Protection (CRITICAL) ===
            /\/var\/www\/(?!$)/i, // Block ANY access to /var/www/* (server web root)
            /\/etc\/(caddy|nginx|apache|systemd|pm2)/i, // Server config files
            /\/etc\/(passwd|shadow|group|sudoers)/i, // System auth files
            /\b(systemctl|service)\s+(start|stop|restart|enable|disable|reload)/i, // Service control
            /\bpm2\s+(start|stop|restart|delete|kill|flush)/i, // PM2 process management
            /\bjournalctl\b/i, // System logs access
            /\bnpm\s+publish\b/i, // Block npm publish from agent
            /\bdocker\s+(rm|kill|stop|exec|run)/i, // Docker container manipulation
            /\biptables\b/i, // Firewall rules
            /\bufw\s+(allow|deny|delete|disable)/i, // UFW firewall
            /\bssh\s+.*vigthoria/i, // SSH to Vigthoria servers
            /\bssh\s+.*78\.46\.154/i, // SSH to known Vigthoria IP
            /\.env\b/i, // Environment files (may contain secrets)
            /\bprivate[_-]?key|secret[_-]?key|api[_-]?key|auth[_-]?token/i, // Sensitive variable patterns in commands
            /\bcrontab\b/i, // Cron manipulation
            /\bmount\s/i, // Mount filesystems
            /\bmkfs\b/i, // Format filesystems
            />\s*\/dev\/sd/i, // Writing to disk devices
            /\bdd\s+.*of=/i, // dd write operations
            /\bnode\s+-e\b/i, // Node eval (sandbox bypass)
            /\bnode\s+--eval\b/i, // Node eval long form
            /\bpython3?\s+-c\b/i, // Python exec (sandbox bypass)
            /\bruby\s+-e\b/i, // Ruby eval (sandbox bypass)
            /\bperl\s+-e\b/i, // Perl eval (sandbox bypass)
        ];
        for (const pattern of blockedPatterns) {
            if (pattern.test(args.command)) {
                this.logger.warn(`Security: Blocked potentially dangerous command: ${args.command.substring(0, 50)}...`);
                return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, 'This command is blocked for security reasons', 'Commands must operate within your current project workspace.');
            }
        }
        // Validate working directory
        if (!fs.existsSync(cwd)) {
            return this.createErrorResult(ToolErrorType.FILE_NOT_FOUND, `Working directory not found: ${cwd}`, 'Check that the directory exists or use an absolute path.');
        }
        try {
            const startTime = Date.now();
            // Build exec options based on platform
            const execOptions = {
                cwd,
                timeout,
                encoding: 'utf-8',
                maxBuffer: 10 * 1024 * 1024, // 10MB
                stdio: ['pipe', 'pipe', 'pipe'],
                // Ensure consistent environment
                env: {
                    ...process.env,
                    // Prevent locale issues
                    LC_ALL: 'C',
                    LANG: 'C',
                },
            };
            // Set shell based on platform for consistent behavior
            if (platform === 'win32') {
                execOptions.shell = true; // Use default cmd.exe on Windows
            }
            else {
                // Use /bin/sh on Unix-like systems (more portable than bash)
                execOptions.shell = '/bin/sh';
            }
            const output = this.runExternalCommand('bash', args.command, args.command, execOptions);
            const duration = Date.now() - startTime;
            return {
                success: true,
                output: output.trim(),
                metadata: {
                    durationMs: duration,
                    cwd,
                },
            };
        }
        catch (error) {
            // Command failed but may have output
            const output = error.stdout || '';
            const stderr = error.stderr || '';
            // Provide helpful error messages for common cases
            if (error.killed) {
                return this.createErrorResult(ToolErrorType.TIMEOUT, `Command timed out after ${timeout / 1000}s`, 'Try increasing the timeout or breaking the command into smaller parts.');
            }
            if (stderr.includes('command not found') || stderr.includes('not recognized')) {
                const cmd = args.command.split(' ')[0];
                return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, `Command not found: ${cmd}`, 'Check that the command is installed and in PATH.');
            }
            if (stderr.includes('Permission denied')) {
                return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, 'Permission denied executing command', 'Try using sudo or check file/directory permissions.');
            }
            return {
                success: false,
                output,
                error: stderr || error.message,
                suggestion: 'Check command syntax and try again.',
                canRetry: !error.killed,
            };
        }
    }
    grep(args) {
        const searchPath = args.path ? this.resolvePath(args.path) : this.cwd;
        const osModule = require('os');
        const platform = osModule.platform();
        // If forced fallback, go directly to Node-native
        if (args._fallback === 'node-native') {
            return this.grepNodeNative(args, searchPath);
        }
        // Try external search tools first (rg > grep/Select-String), fall back to Node-native
        if (platform === 'win32') {
            return this.grepWindows(args, searchPath);
        }
        return this.grepUnix(args, searchPath, platform);
    }
    /**
     * Windows grep: rg > Select-String > Node-native
     */
    grepWindows(args, searchPath) {
        // 1. Try ripgrep (rg) first — best cross-platform search tool
        try {
            execSync('rg --version', { encoding: 'utf-8', timeout: 5000, stdio: 'pipe' });
            return this.grepWithRg(args, searchPath);
        }
        catch (error) {
            this.logger.debug(this.formatExternalToolError('grep', 'checking ripgrep availability on Windows', error));
        }
        // 2. Try PowerShell Select-String
        try {
            return this.grepWithSelectString(args, searchPath);
        }
        catch (error) {
            this.logger.debug(this.formatExternalToolError('grep', 'running PowerShell Select-String fallback', error));
        }
        // 3. Fall back to Node-native recursive file scanner
        return this.grepNodeNative(args, searchPath);
    }
    /**
     * Unix grep: rg > system grep (BSD/GNU)
     */
    grepUnix(args, searchPath, platform) {
        // Try ripgrep first if available
        try {
            this.runExternalCommand('grep', 'checking ripgrep availability on Unix', 'rg --version', { encoding: 'utf-8', timeout: 5000, stdio: 'pipe' });
            return this.grepWithRg(args, searchPath);
        }
        catch (error) {
            this.logger.debug(this.formatExternalToolError('grep', 'checking ripgrep availability on Unix', error));
            // rg not available, fall through to system grep
        }
        const isMac = platform === 'darwin';
        let cmd;
        if (isMac) {
            cmd = args.include
                ? `grep -rn --include="${args.include}" "${args.pattern}" "${searchPath}"`
                : `grep -rn "${args.pattern}" "${searchPath}"`;
        }
        else {
            cmd = args.include
                ? `grep -rn --color=never --include="${args.include}" "${args.pattern}" "${searchPath}"`
                : `grep -rn --color=never "${args.pattern}" "${searchPath}"`;
        }
        try {
            const output = this.runExternalCommand('grep', 'system grep search', cmd, {
                cwd: this.cwd,
                encoding: 'utf-8',
                maxBuffer: 5 * 1024 * 1024,
                timeout: 30000,
                env: { ...process.env, GREP_OPTIONS: '' },
            });
            return {
                success: true,
                output: output.trim(),
                metadata: { searchStatus: 'search_matches_found' },
            };
        }
        catch (error) {
            // Distinguish real "no matches" (exit 1 + no stderr) from command failure
            const stderr = (error.stderr || '').toString();
            if (error.status === 1 && !stderr.trim()) {
                return {
                    success: true,
                    output: 'No matches found',
                    metadata: { searchStatus: 'search_no_matches' },
                };
            }
            // Real failure: command not found, permission denied, etc.
            return {
                success: false,
                error: stderr || error.message,
                suggestion: 'The grep command failed. Install ripgrep (rg) for best cross-platform search.',
                canRetry: true,
                metadata: { searchStatus: 'search_failed' },
            };
        }
    }
    /**
     * Search using ripgrep (rg) — works on all platforms
     */
    grepWithRg(args, searchPath) {
        let cmd = `rg -n --no-heading`;
        if (args.include) {
            cmd += ` -g "${args.include}"`;
        }
        cmd += ` "${args.pattern}" "${searchPath}"`;
        try {
            const output = this.runExternalCommand('grep', 'ripgrep search', cmd, {
                cwd: this.cwd,
                encoding: 'utf-8',
                maxBuffer: 5 * 1024 * 1024,
                timeout: 30000,
            });
            return {
                success: true,
                output: output.trim(),
                metadata: { searchStatus: 'search_matches_found', backend: 'ripgrep' },
            };
        }
        catch (error) {
            if (error.status === 1 && !(error.stderr || '').toString().trim()) {
                return {
                    success: true,
                    output: 'No matches found',
                    metadata: { searchStatus: 'search_no_matches', backend: 'ripgrep' },
                };
            }
            throw error; // Let caller try next backend
        }
    }
    /**
     * Search using PowerShell Select-String (Windows)
     */
    grepWithSelectString(args, searchPath) {
        // Normalize path for PowerShell
        const psPath = searchPath.replace(/\//g, '\\');
        if (!POWERSHELL_SAFE_PATH_PATTERN.test(psPath)) {
            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.');
        }
        const includeArg = args.include ? String(args.include) : '*';
        if (!POWERSHELL_SAFE_INCLUDE_PATTERN.test(includeArg)) {
            return this.createErrorResult(ToolErrorType.INVALID_ARGS, 'Unsafe include filter for PowerShell backend', 'Use simple wildcard filters like *.ts or *.py.');
        }
        const includeFilter = `-Include "${includeArg}"`;
        const escapedPattern = args.pattern.replace(/'/g, "''");
        const cmd = `powershell -NoProfile -Command "Get-ChildItem -Path '${psPath}' -Recurse -File ${includeFilter} | Select-String -Pattern '${escapedPattern}' | ForEach-Object { $_.Path + ':' + $_.LineNumber + ':' + $_.Line }"`;
        try {
            const output = execSync(cmd, {
                cwd: this.cwd,
                encoding: 'utf-8',
                maxBuffer: 5 * 1024 * 1024,
                timeout: 60000,
            });
            const trimmed = output.trim();
            if (!trimmed) {
                return {
                    success: true,
                    output: 'No matches found',
                    metadata: { searchStatus: 'search_no_matches', backend: 'select-string' },
                };
            }
            return {
                success: true,
                output: trimmed,
                metadata: { searchStatus: 'search_matches_found', backend: 'select-string' },
            };
        }
        catch (error) {
            const stderr = (error.stderr || '').toString();
            // Select-String returns exit code 1 for no matches when used in pipeline
            if (error.status === 1 && !stderr.trim()) {
                return {
                    success: true,
                    output: 'No matches found',
                    metadata: { searchStatus: 'search_no_matches', backend: 'select-string' },
                };
            }
            throw error; // Let caller try next backend
        }
    }
    /**
     * Pure Node.js recursive file search — reliable on all platforms, no external deps
     */
    grepNodeNative(args, searchPath) {
        const { minimatch } = (() => {
            try {
                return require('minimatch');
            }
            catch {
                return { minimatch: null };
            }
        })();
        const results = [];
        let regex;
        try {
            regex = new RegExp(args.pattern, 'i');
        }
        catch {
            // If pattern is not valid regex, treat as literal
            regex = new RegExp(args.pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i');
        }
        const includeGlob = args.include || null;
        const maxResults = 500;
        const skipDirs = new Set(['node_modules', '.git', 'dist', 'build', '__pycache__', '.next', 'vendor', '.venv']);
        const walk = (dir) => {
            if (results.length >= maxResults)
                return;
            let entries;
            try {
                entries = fs.readdirSync(dir, { withFileTypes: true });
            }
            catch {
                return; // Permission denied or inaccessible
            }
            for (const entry of entries) {
                if (results.length >= maxResults)
                    break;
                const fullPath = path.join(dir, entry.name);
                if (entry.isDirectory()) {
                    if (!skipDirs.has(entry.name)) {
                        walk(fullPath);
                    }
                    continue;
                }
                if (!entry.isFile())
                    continue;
                // Check include pattern
                if (includeGlob) {
                    const matches = minimatch
                        ? minimatch(entry.name, includeGlob)
                        : entry.name.endsWith(includeGlob.replace('*', ''));
                    if (!matches)
                        continue;
                }
                // Skip binary files by extension
                const ext = path.extname(entry.name).toLowerCase();
                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']);
                if (binaryExts.has(ext))
                    continue;
                try {
                    const content = fs.readFileSync(fullPath, 'utf-8');
                    const lines = content.split('\n');
                    for (let i = 0; i < lines.length; i++) {
                        if (regex.test(lines[i])) {
                            const relativePath = path.relative(this.cwd, fullPath).replace(/\\/g, '/');
                            results.push(`${relativePath}:${i + 1}:${lines[i]}`);
                            if (results.length >= maxResults)
                                break;
                        }
                    }
                }
                catch {
                    // Skip files that can't be read (binary, encoding issues, etc.)
                }
            }
        };
        try {
            walk(searchPath);
        }
        catch (error) {
            return {
                success: false,
                error: `File search failed: ${error.message}`,
                metadata: { searchStatus: 'search_failed', backend: 'node-native' },
            };
        }
        if (results.length === 0) {
            return {
                success: true,
                output: 'No matches found',
                metadata: { searchStatus: 'search_no_matches', backend: 'node-native' },
            };
        }
        const truncationNote = results.length >= maxResults ? `\n...[truncated at ${maxResults} matches]` : '';
        return {
            success: true,
            output: results.join('\n') + truncationNote,
            metadata: { searchStatus: 'search_matches_found', backend: 'node-native' },
        };
    }
    listDir(args) {
        const dirPath = this.resolvePath(args.path);
        if (!fs.existsSync(dirPath)) {
            return { success: false, error: `Directory not found: ${args.path}` };
        }
        const entries = fs.readdirSync(dirPath, { withFileTypes: true });
        const output = entries.map(e => {
            const suffix = e.isDirectory() ? '/' : '';
            return e.name + suffix;
        }).join('\n');
        return { success: true, output };
    }
    glob(args) {
        const { globSync } = require('glob');
        try {
            const files = globSync(args.pattern, { cwd: this.cwd });
            return { success: true, output: files.join('\n') };
        }
        catch (error) {
            return { success: false, error: error.message };
        }
    }
    git(args) {
        try {
            const output = execSync(`git ${args.args}`, {
                cwd: this.cwd,
                encoding: 'utf-8',
                timeout: 60000,
            });
            return { success: true, output: output.trim() };
        }
        catch (error) {
            return { success: false, error: error.stderr || error.message };
        }
    }
    /**
     * Vigthoria Repository management tool
     * Allows AI to push, pull, list, share, and manage projects in the Vigthoria Repository
     */
    async repo(args) {
        const action = args.action?.toLowerCase();
        const project = args.project;
        const visibility = args.visibility || 'public';
        const targetPath = args.path || this.cwd;
        const description = args.description || '';
        try {
            // Push action uses direct API call to Community server (bypasses interactive CLI)
            if (action === 'push') {
                if (!project) {
                    return {
                        success: false,
                        error: 'Project name is required for push',
                        suggestion: 'Provide a project name, e.g., repo action=push project=my-project'
                    };
                }
                // Load auth config
                const configPath = path.join(process.env.HOME || '/root', '.config', 'vigthoria-cli', 'config.json');
                if (!fs.existsSync(configPath)) {
                    return { success: false, error: 'Not logged in. Run vigthoria login first.' };
                }
                const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
                const authToken = config.authToken;
                const apiBase = config.apiUrl || 'https://coder.vigthoria.io';
                if (!authToken) {
                    return { success: false, error: 'No auth token found. Run vigthoria login first.' };
                }
                // Build files array
                let filesArray = [];
                if (args.files) {
                    // AI passed files directly
                    let filesInput;
                    if (typeof args.files === 'string') {
                        try {
                            filesInput = JSON.parse(args.files);
                        }
                        catch {
                            filesInput = args.files;
                        }
                    }
                    else {
                        filesInput = args.files;
                    }
                    if (Array.isArray(filesInput)) {
                        // Already in [{path, content}] format
                        filesArray = filesInput.map((f) => ({ path: f.path || f.name || 'file', content: String(f.content || '') }));
                    }
                    else if (typeof filesInput === 'object' && filesInput !== null) {
                        // {filename: content} format - convert
                        for (const [filePath, content] of Object.entries(filesInput)) {
                            filesArray.push({ path: filePath, content: String(content) });
                        }
                    }
                }
                // If no files from AI, read from disk
                if (filesArray.length === 0 && fs.existsSync(targetPath)) {
                    const readDir = (dir, base) => {
                        const entries = fs.readdirSync(dir, { withFileTypes: true });
                        for (const entry of entries) {
                            const fullPath = path.join(dir, entry.name);
                            const relPath = path.relative(base, fullPath);
                            // Skip hidden dirs, node_modules, common non-essential dirs
                            if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === '__pycache__')
                                continue;
                            if (entry.isDirectory()) {
                                readDir(fullPath, base);
                            }
                            else if (entry.isFile()) {
                                try {
                                    const content = fs.readFileSync(fullPath, 'utf-8');
                                    filesArray.push({ path: relPath, content });
                                }
                                catch { /* skip binary/unreadable files */ }
                            }
                        }
                    };
                    const stat = fs.statSync(targetPath);
                    if (stat.isDirectory()) {
                        readDir(targetPath, targetPath);
                    }
                    else {
                        filesArray.push({ path: path.basename(targetPath), content: fs.readFileSync(targetPath, 'utf-8') });
                    }
                }
                if (filesArray.length === 0) {
                    return { success: false, error: 'No files to push. Provide files parameter or a valid path.' };
                }
                // POST to Community API via Coder proxy (fallback to direct Community server)
                const body = JSON.stringify({
                    projectName: project,
                    description: description || `${project} - pushed via Vigthoria AI`,
                    visibility,
                    files: filesArray,
                    commitMessage: `Push from Vigthoria AI: ${filesArray.length} file(s)`
                });
                const headers = {
                    'Authorization': `Bearer ${authToken}`,
                    'Content-Type': 'application/json'
                };
                // Try proxy first; direct Community server is only reachable when running on the
                // Vigthoria backend itself (isServerRuntime), never expose this fallback to remote users.
                const pushUrls = [`${apiBase}/api/community-repo/push`];
                if (isServerRuntime()) {
                    const directHost = ['local', 'host'].join('');
                    pushUrls.push(`http://${directHost}:9000/api/repo/push`);
                }
                let result;
                let lastError = '';
                for (const pushUrl of pushUrls) {
                    try {
                        const response = await fetch(pushUrl, { method: 'POST', headers, body });
                        result = await response.json();
                        if (response.ok && result.success)
                            break;
                        if (result.code === 'REPOSITORY_SECURITY_REVIEW') {
                            return {
                                success: false,
                                error: result.error || 'Repository security review required',
                                metadata: {
                                    code: result.code,
                                    review: {
                                        reviewId: result.reviewId,
                                        status: result.status,
                                        riskScore: result.riskScore,
                                        findings: result.findings || [],
                                        actionItems: result.actionItems || [],
                                        retryCommand: result.retryCommand,
                                    },
                                },
                                suggestion: `Inspect with "vigthoria repo review ${result.reviewId}" and retry corrected content with "${result.retryCommand || `vigthoria repo push --retry ${result.reviewId}`}".`,
                            };
                        }
                        lastError = result.error || result.message || `Status ${response.status}`;
                        result = null;
                    }
                    catch (e) {
                        lastError = e.message;
                        result = null;
                    }
                }
                if (!result || !result.success) {
                    return {
                        success: false,
                        error: lastError || 'Push failed on all endpoints',
                        suggestion: 'Check your authentication and try again. Run vigthoria login to refresh your token.'
                    };
                }
                return {
                    success: true,
                    output: `Successfully pushed "${project}" to Vigthoria Community!\n` +
                        `Action: ${result.action || 'created'}\n` +
                        `Files: ${result.filesWritten || filesArray.length}\n` +
                        `URL: ${result.url || `https://community.vigthoria.io/showcase/${result.projectId}`}`,
                    metadata: { action: 'push', project, filesWritten: result.filesWritten || filesArray.length, url: result.url }
                };
            }
            // All other actions use CLI commands
            let command;
            switch (action) {
                case 'pull':
                    if (!project) {
                        return {
                            success: false,
                            error: 'Project name is required for pull',
                            suggestion: 'Provide a project name, e.g., repo action=pull project=my-project'
                        };
                    }
                    command = `vigthoria repo pull "${project}"`;
                    break;
                case 'list':
                    command = 'vigthoria repo list';
                    break;
                case 'status':
                    if (!project) {
                        return {
                            success: false,
                            error: 'Project name is required for status',
                            suggestion: 'Provide a project name, e.g., repo action=status project=my-project'
                        };
                    }
                    command = `vigthoria repo status "${project}"`;
                    break;
                case 'share':
                    if (!project || !args.username) {
                        return {
                            success: false,
                            error: 'Project name and username are required for share',
                            suggestion: 'Provide both, e.g., repo action=share project=my-project username=collaborator permission=read'
                        };
                    }
                    const permission = args.permission || 'read';
                    command = `vigthoria repo share "${project}" "${args.username}" --permission ${permission}`;
                    break;
                case 'delete':
                    if (!project) {
                        return {
                            success: false,
                            error: 'Project name is required for delete',
                            suggestion: 'Provide a project name, e.g., repo action=delete project=my-project'
                        };
                    }
                    command = `vigthoria repo delete "${project}" --force`;
                    break;
                case 'clone':
                    if (!project) {
                        return {
                            success: false,
                            error: 'Project name is required for clone',
                            suggestion: 'Provide a project name, e.g., repo action=clone project=my-project path=/path/to/target'
                        };
                    }
                    command = `vigthoria repo clone "${project}" "${targetPath}"`;
                    break;
                default:
                    return {
                        success: false,
                        error: `Unknown repo action: ${action}`,
                        suggestion: 'Available actions: push, pull, list, status, share, delete, clone'
                    };
            }
            const output = execSync(command, {
                cwd: this.cwd,
                encoding: 'utf-8',
                timeout: 120000,
                env: { ...process.env, FORCE_COLOR: '0' }
            });
            return {
                success: true,
                output: output.trim(),
                metadata: { action, project }
            };
        }
        catch (error) {
            return {
                success: false,
                error: error.stderr || error.message,
                suggestion: 'Make sure you are logged in with vigthoria login and have the required permissions.'
            };
        }
    }
    /**
     * Fetch URL content - Cross-platform web fetching
     * Uses Node.js native fetch (available in Node 18+)
     */
    async fetchUrl(args) {
        const url = args.url;
        const method = (args.method || 'GET').toUpperCase();
        // Validate URL
        if (!url.startsWith('http://') && !url.startsWith('https://')) {
            return this.createErrorResult(ToolErrorType.INVALID_ARGS, 'URL must start with http:// or https://', 'Provide a valid URL, e.g., https://example.com');
        }
        try {
            const fetchOptions = {
                method,
                headers: {
                    'User-Agent': 'Vigthoria-CLI/1.5.7',
                    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                },
            };
            // Parse custom headers if provided
            if (args.headers) {
                try {
                    const customHeaders = JSON.parse(args.headers);
                    fetchOptions.headers = { ...fetchOptions.headers, ...customHeaders };
                }
                catch {
                    this.logger.warn('Invalid headers JSON, using defaults');
                }
            }
            // Add body for POST/PUT requests
            if (args.body && ['POST', 'PUT', 'PATCH'].includes(method)) {
                fetchOptions.body = args.body;
                fetchOptions.headers['Content-Type'] = 'application/json';
            }
            // Use AbortController for timeout
            const controller = new AbortController();
            const timeout = setTimeout(() => controller.abort(), 30000);
            fetchOptions.signal = controller.signal;
            const response = await fetch(url, fetchOptions);
            clearTimeout(timeout);
            if (!response.ok) {
                return this.createErrorResult(ToolErrorType.NETWORK_ERROR, `HTTP ${response.status}: ${response.statusText}`, `The server returned an error. Status: ${response.status}`);
            }
            let content = await response.text();
            // Extract content based on selector if provided (basic HTML extraction)
            if (args.selector && content.includes('<')) {
                const selector = args.selector.toLowerCase().trim();
                if (selector === 'title') {
                    const match = content.match(/<title[^>]*>([^<]*)<\/title>/i);
                    content = match ? match[1].trim() : 'No title found';
                }
                else if (selector === 'meta' || selector.includes('meta[')) {
                    const matches = content.match(/<meta[^>]+>/gi) || [];
                    content = matches.length > 0 ? matches.join('\n') : 'No meta tags found';
                }
                else if (selector === 'body' || selector === 'text') {
                    // Extract readable text from body
                    const match = content.match(/<body[^>]*>([\s\S]*)<\/body>/i);
                    if (match) {
                        content = match[1]
                            .replace(/<script[\s\S]*?<\/script>/gi, '')
                            .replace(/<style[\s\S]*?<\/style>/gi, '')
                            .replace(/<nav[\s\S]*?<\/nav>/gi, '')
                            .replace(/<header[\s\S]*?<\/header>/gi, '')
                            .replace(/<footer[\s\S]*?<\/footer>/gi, '')
                            .replace(/<[^>]+>/g, ' ')
                            .replace(/\s+/g, ' ')
                            .trim();
                    }
                }
                else if (selector === 'links' || selector === 'a') {
                    // Extract all links
                    const linkRegex = /<a[^>]+href=["']([^"']+)["'][^>]*>([^<]*)<\/a>/gi;
                    const links = [];
                    let linkMatch;
                    while ((linkMatch = linkRegex.exec(content)) !== null) {
                        const href = linkMatch[1];
                        const text = linkMatch[2].trim();
                        if (text && !href.startsWith('#') && !href.startsWith('javascript:')) {
                            links.push(`${text}: ${href}`);
                        }
                    }
                    content = links.length > 0 ? links.join('\n') : 'No links found';
                }
                else if (selector.includes(',')) {
                    // Handle compound selectors like "h1, h2, h3"
                    const tags = selector.split(',').map(s => s.trim());
                    const allMatches = [];
                    for (const tag of tags) {
                        const regex = new RegExp(`<${tag}[^>]*>([\\s\\S]*?)</${tag}>`, 'gi');
                        let match;
                        while ((match = regex.exec(content)) !== null) {
                            const text = match[1].replace(/<[^>]+>/g, '').trim();
                            if (text)
                                allMatches.push(`[${tag}] ${text}`);
                        }
                    }
                    content = allMatches.length > 0 ? allMatches.join('\n') : `No ${selector} tags found`;
                }
                else if (/^h[1-6]$/.test(selector)) {
                    // Single heading selector
                    const regex = new RegExp(`<${selector}[^>]*>([\\s\\S]*?)</${selector}>`, 'gi');
                    const matches = [];
                    let match;
                    while ((match = regex.exec(content)) !== null) {
                        const text = match[1].replace(/<[^>]+>/g, '').trim();
                        if (text)
                            matches.push(text);
                    }
                    content = matches.length > 0 ? matches.join('\n') : `No ${selector} tags found`;
                }
                else if (selector === 'nav' || selector === 'nav a') {
                    // Extract navigation links
                    const navMatch = content.match(/<nav[^>]*>([\s\S]*?)<\/nav>/gi);
                    if (navMatch) {
                        const linkRegex = /<a[^>]+href=["']([^"']+)["'][^>]*>([^<]*)<\/a>/gi;
                        const links = [];
                        for (const nav of navMatch) {
                            let linkMatch;
                            while ((linkMatch = linkRegex.exec(nav)) !== null) {
                                const text = linkMatch[2].trim();
                                if (text)
                                    links.push(`${text}: ${linkMatch[1]}`);
                            }
                        }
                        content = links.length > 0 ? links.join('\n') : 'No navigation links found';
                    }
                    else {
                        content = 'No navigation found';
                    }
                }
                else if (selector === 'footer') {
                    const match = content.match(/<footer[^>]*>([\s\S]*?)<\/footer>/i);
                    content = match ? match[1].replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim() : 'No footer found';
                }
                else if (selector === 'images' || selector === 'img') {
                    const imgRegex = /<img[^>]+src=["']([^"']+)["'][^>]*(?:alt=["']([^"']*)["'])?[^>]*>/gi;
                    const images = [];
                    let imgMatch;
                    while ((imgMatch = imgRegex.exec(content)) !== null) {
                        const src = imgMatch[1];
                        const alt = imgMatch[2] || 'no alt';
                        images.push(`${alt}: ${src}`);
                    }
                    content = images.length > 0 ? images.join('\n') : 'No images found';
                }
                else {
                    // Generic tag extraction
                    const regex = new RegExp(`<${selector}[^>]*>([\\s\\S]*?)</${selector}>`, 'gi');
                    const matches = [];
                    let match;
                    while ((match = regex.exec(content)) !== null) {
                        matches.push(match[1].replace(/<[^>]+>/g, ' ').trim());
                    }
                    content = matches.length > 0 ? matches.join('\n\n---\n\n') : `No ${selector} elements found`;
                }
            }
            // Truncate if too long
            if (content.length > 50000) {
                content = content.substring(0, 50000) + '\n... (truncated, content too long)';
            }
            return {
                success: true,
                output: content,
                metadata: {
                    url,
                    status: response.status,
                    contentType: response.headers.get('content-type') || 'unknown',
                    contentLength: content.length,
                },
            };
        }
        catch (error) {
            if (error.name === 'AbortError') {
                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.');
            }
            return this.createErrorResult(ToolErrorType.NETWORK_ERROR, error.message, 'Check your internet connection and ensure the URL is correct.');
        }
    }
    async browserTool(args) {
        const mode = (args.mode || '').toLowerCase();
        const url = args.url;
        if (!['capture', 'errors', 'test'].includes(mode)) {
            return this.createErrorResult(ToolErrorType.INVALID_ARGS, `Invalid mode: ${args.mode}`, "mode must be one of: 'capture', 'errors', 'test'");
        }
        if (!url || (!url.startsWith('http://') && !url.startsWith('https://'))) {
            return this.createErrorResult(ToolErrorType.INVALID_ARGS, 'URL must start with http:// or https://', 'Provide a valid URL, e.g., https://example.com');
        }
        const host = process.env.VIGTHORIA_DEVTOOLS_BRIDGE_HOST || '127.0.0.1';
        const port = process.env.VIGTHORIA_DEVTOOLS_BRIDGE_PORT || '4016';
        const base = `http://${host}:${port}`;
        const toolName = mode === 'capture' ? 'capture_state' :
            mode === 'errors' ? 'get_page_errors' :
                'run_test';
        const params = { url };
        if (mode === 'capture' && (args.include_screenshot || '').toLowerCase() === 'false') {
            params.includeScreenshot = false;
        }
        if (mode === 'test') {
            params.testType = 'quick';
        }
        const controller = new AbortController();
        const timeoutMs = mode === 'test' ? 60000 : 45000;
        const timeout = setTimeout(() => controller.abort(), timeoutMs);
        try {
            const res = await fetch(`${base}/api/mcp/tools`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'User-Agent': 'Vigthoria-CLI-Browser/1.0' },
                body: JSON.stringify({ tool: toolName, params }),
                signal: controller.signal,
            });
            clearTimeout(timeout);
            if (!res.ok) {
                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.');
            }
            const data = await res.json();
            if (!data.success) {
                return this.createErrorResult(ToolErrorType.NETWORK_ERROR, data.error || 'DevTools Bridge returned unsuccessful response', 'Check the bridge logs.');
            }
            let payload;
            if (mode === 'capture' && data.result && typeof data.result === 'object') {
                const r = data.result;
                const trimmed = {
                    url: r.url,
                    timestamp: r.timestamp,
                    metrics: r.metrics,
                    performance: r.performance,
                    html_excerpt: typeof r.html === 'string' ? r.html.slice(0, 4000) : undefined,
                    screenshot_data_url_length: typeof r.screenshot === 'string' ? r.screenshot.length : 0,
                };
                payload = JSON.stringify(trimmed, null, 2);
            }
            else {
                payload = JSON.stringify(data.result, null, 2).slice(0, 8000);
            }
            return {
                success: true,
                output: payload,
                metadata: { tool: 'browser', mode, url },
            };
        }
        catch (e) {
            clearTimeout(timeout);
            const msg = e instanceof Error ? e.message : String(e);
            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).");
        }
    }
    /**
     * Execute command via SSH on remote server
     * Useful for running Unix commands from Windows
     */
    async sshExec(args) {
        const command = args.command;
        const host = args.host || 'vigthoria-server';
        const timeout = args.timeout ? parseInt(args.timeout) * 1000 : 60000;
        const normalizedHost = String(host).trim().toLowerCase();
        if (!SSH_SAFE_HOST_PATTERN.test(normalizedHost)) {
            return this.createErrorResult(ToolErrorType.INVALID_ARGS, 'Invalid SSH host format', 'Host can only include letters, numbers, dots, and dashes.');
        }
        const allowedHosts = getSshAllowedHosts();
        if (!allowedHosts.has(normalizedHost)) {
            return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, `SSH host is not allowlisted: ${host}`, 'Add the host to VIGTHORIA_SSH_ALLOWED_HOSTS to permit access.');
        }
        // Security checks for SSH commands
        const blockedPatterns = [
            /\brm\s+-rf?\s+\//i, // Dangerous rm commands
            /\bsudo\s+rm/i, // Sudo rm
            />\s*\/dev\/sd/i, // Writing to disk devices
            /\bdd\s+.*of=\/dev/i, // dd to devices
            /\bmkfs/i, // Format filesystems
            /shutdown|reboot|halt|poweroff/i, // System control
        ];
        for (const pattern of blockedPatterns) {
            if (pattern.test(command)) {
                return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, 'This command is blocked for security reasons', 'Dangerous system commands cannot be executed via SSH.');
            }
        }
        try {
            const os = require('os');
            const platform = os.platform();
            let sshCommand;
            let execOptions = {
                encoding: 'utf-8',
                timeout,
                maxBuffer: 10 * 1024 * 1024,
            };
            if (platform === 'win32') {
                // On Windows, use the ssh command from OpenSSH
                sshCommand = `ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${host} "${command.replace(/"/g, '\\"')}"`;
                execOptions.shell = true;
            }
            else {
                // On Unix-like systems
                sshCommand = `ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${host} '${command.replace(/'/g, "'\\''")}'`;
                execOptions.shell = '/bin/sh';
            }
            const output = execSync(sshCommand, execOptions);
            return {
                success: true,
                output: output.trim(),
                metadata: { host, command },
            };
        }
        catch (error) {
            // Check for common SSH errors
            const errorMsg = error.stderr || error.message || '';
            if (errorMsg.includes('Connection refused') || errorMsg.includes('No route to host')) {
                return this.createErrorResult(ToolErrorType.NETWORK_ERROR, `Cannot connect to SSH host: ${host}`, 'Check that the SSH host is correct and the server is running.');
            }
            if (errorMsg.includes('Permission denied') || errorMsg.includes('authentication')) {
                return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, 'SSH authentication failed', 'Make sure you have SSH key authentication set up for this host.');
            }
            if (error.killed) {
                return this.createErrorResult(ToolErrorType.TIMEOUT, `SSH command timed out after ${timeout / 1000}s`, 'Try a simpler command or increase the timeout.');
            }
            return {
                success: false,
                output: error.stdout || '',
                error: errorMsg,
                suggestion: 'Check the command syntax and ensure SSH access is configured.',
            };
        }
    }
    /**
     * Resolve and SANITIZE path - prevent path traversal outside workspace
     * SECURITY: All paths MUST stay within the workspace (cwd)
     */
    resolvePath(p) {
        const normalizedInput = String(p || '').trim().replace(/\\/g, '/');
        const workspaceRoot = path.normalize(this.cwd);
        const workspaceRootPosix = workspaceRoot.replace(/\\/g, '/').replace(/\/+$/g, '');
        const workspaceBase = path.posix.basename(workspaceRootPosix);
        const stripWorkspacePrefix = (value) => {
            let candidate = String(value || '').trim().replace(/\\/g, '/').replace(/^\.\//, '');
            if (!candidate) {
                return candidate;
            }
            const redactedWorkspaceAliases = [
                'www/[internal]/',
                'var/www/[internal]/',
                '/var/www/[internal]/',
                '[internal]/',
            ];
            for (const alias of redactedWorkspaceAliases) {
                if (candidate.startsWith(alias)) {
                    candidate = candidate.slice(alias.length);
                    break;
                }
            }
            if (candidate === 'www/[internal]' || candidate === 'var/www/[internal]' || candidate === '/var/www/[internal]' || candidate === '[internal]') {
                return '';
            }
            const normalizedRootNoSlash = workspaceRootPosix.replace(/^\//, '');
            const prefixes = [
                `${workspaceRootPosix}/`,
                `${normalizedRootNoSlash}/`,
                `${workspaceBase}/`,
                'workspace/',
            ];
            for (const prefix of prefixes) {
                if (candidate.startsWith(prefix)) {
                    candidate = candidate.slice(prefix.length);
                }
            }
            const embeddedWorkspacePrefix = `/${workspaceBase}/`;
            const embeddedIndex = candidate.indexOf(embeddedWorkspacePrefix);
            if (embeddedIndex >= 0) {
                candidate = candidate.slice(embeddedIndex + embeddedWorkspacePrefix.length);
            }
            return candidate.replace(/^\//, '');
        };
        // Resolve the full path after removing workspace aliases emitted by remote models.
        const safeInput = stripWorkspacePrefix(normalizedInput);
        let resolvedPath;
        if (path.isAbsolute(safeInput)) {
            resolvedPath = path.normalize(safeInput);
        }
        else {
            resolvedPath = path.normalize(path.join(this.cwd, safeInput));
        }
        // SECURITY CHECK: Ensure path is within workspace
        if (!resolvedPath.startsWith(workspaceRoot + path.sep) && resolvedPath !== workspaceRoot) {
            // Path is outside workspace - force it back to workspace
            this.logger.warn(`Security: Blocked access to path outside workspace: ${p}`);
            // Return the sanitized relative path within workspace
            const basename = path.basename(stripWorkspacePrefix(normalizedInput) || normalizedInput);
            return path.join(this.cwd, basename);
        }
        return resolvedPath;
    }
    /**
     * Check if a path is within the allowed workspace
     */
    isPathWithinWorkspace(p) {
        const resolvedPath = path.normalize(path.isAbsolute(p) ? p : path.join(this.cwd, p));
        const workspaceRoot = path.normalize(this.cwd);
        return resolvedPath.startsWith(workspaceRoot + path.sep) || resolvedPath === workspaceRoot;
    }
    // ═══════════════════════════════════════════════════════════════
    // TASK (Sub-Agent) Tool
    // ═══════════════════════════════════════════════════════════════
    async task(args) {
        const description = args.description;
        const workingDir = args.working_dir
            ? this.resolvePath(args.working_dir)
            : this.cwd;
        if (!this.isPathWithinWorkspace(workingDir)) {
            return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, 'Sub-agent working directory must be within the project workspace', 'Provide a relative path within the current project.');
        }
        this.logger.info(`Spawning sub-agent: ${description.substring(0, 80)}...`);
        // Create a scoped sub-agent with its own tool instance
        const subTools = new AgenticTools(this.logger, workingDir, this.permissionCallback, this.autoApprove);
        // Build a focused system prompt for the sub-agent
        const systemPrompt = [
            'You are a focused sub-agent spawned to complete a specific subtask.',
            'You have access to standard tools (read_file, write_file, edit_file, bash, grep, list_dir, glob, git). You cannot spawn sub-agents.',
            'Complete the task thoroughly and return a detailed result.',
            `Working directory: ${workingDir}`,
            '',
            AgenticTools.getToolsForPrompt().replace(/### task[\s\S]*?(?=###|$)/, ''), // Strip task from sub-agent
        ].join('\n');
        const messages = [
            { role: 'system', content: systemPrompt },
            { role: 'user', content: description },
        ];
        const maxSubTurns = 8;
        const results = [];
        try {
            for (let turn = 0; turn < maxSubTurns; turn++) {
                // Import api dynamically to avoid circular dependency
                const { APIClient } = await import('./api.js');
                const { Config } = await import('./config.js');
                const config = new Config();
                const api = new APIClient(config, this.logger);
                const response = await api.chat(messages, 'code');
                const assistantMessage = response.message || '';
                messages.push({ role: 'assistant', content: assistantMessage });
                const toolCalls = AgenticTools.parseToolCalls(assistantMessage);
                if (toolCalls.length === 0) {
                    // Sub-agent finished - extract the final answer
                    const finalAnswer = assistantMessage
                        .replace(/```tool[\s\S]*?```/g, '')
                        .replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '')
                        .trim();
                    results.push(finalAnswer);
                    break;
                }
                // Execute each tool call
                for (const call of toolCalls) {
                    const result = await subTools.execute(call);
                    const summary = `Tool ${call.tool} ${result.success ? 'succeeded' : 'FAILED'}.` +
                        (call.args.path ? `\nFile: ${call.args.path}` : '') +
                        (result.output ? `\nOutput:\n${result.output.substring(0, 4000)}` : '') +
                        (result.error ? `\nError: ${result.error}` : '');
                    messages.push({ role: 'system', content: summary });
                    results.push(`[${call.tool}] ${result.success ? '✓' : '✗'}`);
                }
                messages.push({
                    role: 'system',
                    content: 'Continue with your task. Use more tools if needed, or provide your final answer.',
                });
            }
            return {
                success: true,
                output: results.join('\n'),
                metadata: { subAgentTurns: results.length, workingDir },
            };
        }
        catch (error) {
            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.');
        }
    }
    // ═══════════════════════════════════════════════════════════════
    // MULTI_EDIT Tool - Atomic multi-file edits with rollback
    // ═══════════════════════════════════════════════════════════════
    async multiEdit(args) {
        let edits;
        try {
            edits = JSON.parse(args.edits);
            if (!Array.isArray(edits) || edits.length === 0) {
                throw new Error('edits must be a non-empty array');
            }
        }
        catch (parseError) {
            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"}]');
        }
        // Validate all edits can proceed before modifying anything
        const contentMap = new Map();
        const backups = [];
        const resolvedEdits = [];
        for (let i = 0; i < edits.length; i++) {
            const edit = edits[i];
            if (!edit.path || typeof edit.old_text !== 'string' || typeof edit.new_text !== 'string') {
                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.');
            }
            const resolvedPath = this.resolvePath(edit.path);
            if (!this.isPathWithinWorkspace(resolvedPath)) {
                return this.createErrorResult(ToolErrorType.PERMISSION_DENIED, `Edit ${i}: path "${edit.path}" is outside workspace`, 'All files must be within the current project.');
            }
            if (!fs.existsSync(resolvedPath)) {
                return this.createErrorResult(ToolErrorType.FILE_NOT_FOUND, `Edit ${i}: file not found: ${edit.path}`, 'Use write_file to create new files instead.');
            }
            // Use contentMap to track cumulative edits to the same file
            if (!contentMap.has(resolvedPath)) {
                const diskContent = fs.readFileSync(resolvedPath, 'utf-8');
                contentMap.set(resolvedPath, diskContent);
                backups.push({ path: resolvedPath, content: diskContent });
            }
            const content = contentMap.get(resolvedPath);
            if (!content.includes(edit.old_text)) {
                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.`);
            }
            // Check for multiple matches
            const matchCount = content.split(edit.old_text).length - 1;
            if (matchCount > 1) {
                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.');
            }
            // Apply edit to contentMap so subsequent edits to same file see updated content
            contentMap.set(resolvedPath, content.replace(edit.old_text, edit.new_text));
            resolvedEdits.push({ resolvedPath, old_text: edit.old_text, new_text: edit.new_text, content });
        }
        // Apply all edits
        const applied = [];
        try {
            for (const edit of resolvedEdits) {
                const finalContent = contentMap.get(edit.resolvedPath) || edit.content.replace(edit.old_text, edit.new_text);
                fs.writeFileSync(edit.resolvedPath, finalContent, 'utf-8');
                applied.push(path.relative(this.cwd, edit.resolvedPath));
            }
            // Push undo operations for all edits
            for (const backup of backups) {
                this.undoStack.push({
                    id: `multi_edit_${Date.now()}_${path.basename(backup.path)}`,
                    tool: 'multi_edit',
                    timestamp: Date.now(),
                    filePath: backup.path,
                    originalContent: backup.content,
                    description: `multi_edit: ${path.relative(this.cwd, backup.path)}`,
                });
            }
            return {
                success: true,
                output: `${CH.success} Atomically edited ${applied.length} file(s):\n${applied.map(f => `  ✓ ${f}`).join('\n')}`,
                undoable: true,
                metadata: { filesEdited: applied.length, files: applied },
            };
        }
        catch (error) {
            // ROLLBACK: Restore all files from backups
            for (const backup of backups) {
                try {
                    fs.writeFileSync(backup.path, backup.content, 'utf-8');
                }
                catch {
                    // Best-effort rollback
                }
            }
            return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, `Multi-edit failed, all changes rolled back: ${error.message}`, 'Check file permissions and disk space.');
        }
    }
    // ═══════════════════════════════════════════════════════════════
    // CODEBASE_SEARCH Tool - Deep indexed codebase search
    // ═══════════════════════════════════════════════════════════════
    async codebaseSearch(args) {
        const query = args.query;
        const scope = args.scope || 'all';
        const includePattern = args.include || '';
        const maxResults = Math.min(parseInt(args.max_results || '30', 10), 100);
        const results = [];
        const seen = new Set();
        // Helper: collect files recursively respecting gitignore-like patterns
        const collectFiles = (dir, pattern) => {
            const files = [];
            const ignorePatterns = [
                'node_modules', '.git', 'dist', 'build', '.next', '__pycache__',
                '.venv', 'venv', '.tox', 'coverage', '.nyc_output', '.cache',
                'vendor', 'target', 'bin', 'obj', '.svn', '.hg',
            ];
            const walk = (currentDir, depth) => {
                if (depth > 12)
                    return; // Prevent infinite recursion
                let entries;
                try {
                    entries = fs.readdirSync(currentDir, { withFileTypes: true });
                }
                catch {
                    return;
                }
                for (const entry of entries) {
                    if (ignorePatterns.includes(entry.name) || entry.name.startsWith('.'))
                        continue;
                    const fullPath = path.join(currentDir, entry.name);
                    if (entry.isDirectory()) {
                        walk(fullPath, depth + 1);
                    }
                    else if (entry.isFile()) {
                        if (pattern) {
                            const basename = entry.name;
                            // Simple glob matching for extension patterns like *.ts, *.js
                            const globPattern = pattern.replace(/\*\*\//g, '(.*/)?').replace(/\*/g, '[^/]*').replace(/\?/g, '.');
                            if (new RegExp(globPattern, 'i').test(basename) || fullPath.includes(pattern.replace(/\*/g, ''))) {
                                files.push(fullPath);
                            }
                        }
                        else {
                            files.push(fullPath);
                        }
                    }
                }
            };
            walk(dir, 0);
            return files;
        };
        try {
            const allFiles = collectFiles(this.cwd, includePattern || undefined);
            // SCOPE: files - search file names/paths
            if (scope === 'files' || scope === 'all') {
                const queryLower = query.toLowerCase();
                const queryParts = queryLower.split(/[\s_\-./]+/).filter(Boolean);
                for (const filePath of allFiles) {
                    const relativePath = path.relative(this.cwd, filePath);
                    const filenameLower = relativePath.toLowerCase();
                    const matches = queryParts.every(part => filenameLower.includes(part));
                    if (matches && !seen.has(relativePath)) {
                        seen.add(relativePath);
                        results.push(`[file] ${relativePath}`);
                    }
                    if (results.length >= maxResults)
                        break;
                }
            }
            // SCOPE: symbols - extract function/class/variable definitions
            if ((scope === 'symbols' || scope === 'all') && results.length < maxResults) {
                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;
                const queryLower = query.toLowerCase();
                for (const filePath of allFiles) {
                    if (results.length >= maxResults)
                        break;
                    const ext = path.extname(filePath).toLowerCase();
                    // Only parse code files
                    if (!['.ts', '.tsx', '.js', '.jsx', '.py', '.go', '.rs', '.java', '.rb', '.php', '.c', '.cpp', '.h', '.cs', '.swift', '.kt'].includes(ext))
                        continue;
                    let content;
                    try {
                        const stat = fs.statSync(filePath);
                        if (stat.size > 512 * 1024)
                            continue; // Skip files > 512KB
                        content = fs.readFileSync(filePath, 'utf-8');
                    }
                    catch {
                        continue;
                    }
                    let match;
                    symbolRegex.lastIndex = 0;
                    while ((match = symbolRegex.exec(content)) !== null) {
                        const symbolName = match[1];
                        if (symbolName.toLowerCase().includes(queryLower) || queryLower.includes(symbolName.toLowerCase())) {
                            const relativePath = path.relative(this.cwd, filePath);
                            const lineNum = content.substring(0, match.index).split('\n').length;
                            const key = `${relativePath}:${symbolName}`;
                            if (!seen.has(key)) {
                                seen.add(key);
                                results.push(`[symbol] ${symbolName} → ${relativePath}:${lineNum}`);
                            }
                        }
                        if (results.length >= maxResults)
                            break;
                    }
                }
            }
            // SCOPE: content - full-text search using ripgrep or fallback
            if ((scope === 'content' || scope === 'all') && results.length < maxResults) {
                try {
                    // Try ripgrep first (fast)
                    const rgArgs = [
                        '-i', '--no-heading', '--line-number',
                        '--max-count', '3',
                        '--max-filesize', '512K',
                        '-g', '!node_modules', '-g', '!.git', '-g', '!dist', '-g', '!build',
                    ];
                    if (includePattern)
                        rgArgs.push('-g', includePattern);
                    rgArgs.push('--', query, this.cwd);
                    const isWin = process.platform === 'win32';
                    const quote = (s) => isWin ? `"${s}"` : `'${s}'`;
                    const rgOutput = execSync(`rg ${rgArgs.map(a => quote(a)).join(' ')}`, {
                        encoding: 'utf-8',
                        timeout: 15000,
                        maxBuffer: 5 * 1024 * 1024,
                    }).trim();
                    for (const line of rgOutput.split('\n').slice(0, maxResults - results.length)) {
                        if (!line.trim())
                            continue;
                        const relativeLine = line.replace(this.cwd + path.sep, '').replace(this.cwd + '/', '');
                        const lineKey = relativeLine.substring(0, 200);
                        if (!seen.has(lineKey)) {
                            seen.add(lineKey);
                            results.push(`[content] ${relativeLine}`);
                        }
                    }
                }
                catch {
                    // Fallback: Node-native grep
                    const queryLower = query.toLowerCase();
                    for (const filePath of allFiles) {
                        if (results.length >= maxResults)
                            break;
                        try {
                            const stat = fs.statSync(filePath);
                            if (stat.size > 256 * 1024)
                                continue;
                            const content = fs.readFileSync(filePath, 'utf-8');
                            const lines = content.split('\n');
                            for (let i = 0; i < lines.length; i++) {
                                if (lines[i].toLowerCase().includes(queryLower)) {
                                    const relativePath = path.relative(this.cwd, filePath);
                                    const lineKey = `${relativePath}:${i + 1}`;
                                    if (!seen.has(lineKey)) {
                                        seen.add(lineKey);
                                        results.push(`[content] ${relativePath}:${i + 1}: ${lines[i].trim().substring(0, 120)}`);
                                    }
                                    if (results.length >= maxResults)
                                        break;
                                }
                            }
                        }
                        catch {
                            continue;
                        }
                    }
                }
            }
            if (results.length === 0) {
                return {
                    success: true,
                    output: `No results found for "${query}" in scope "${scope}".`,
                    metadata: { searchStatus: 'search_no_matches', totalFiles: allFiles.length },
                };
            }
            return {
                success: true,
                output: `Found ${results.length} result(s) across ${allFiles.length} files:\n\n${results.join('\n')}`,
                metadata: { searchStatus: 'search_matches_found', resultCount: results.length, totalFiles: allFiles.length },
            };
        }
        catch (error) {
            return this.createErrorResult(ToolErrorType.EXECUTION_FAILED, `Codebase search failed: ${error.message}`, 'Try a simpler query or use grep for specific text patterns.');
        }
    }
    /**
     * Parse tool calls from AI response (Vigthoria Agent format)
     * Enhanced to handle various AI output formats including malformed JSON
     */
    static parseToolCalls(text) {
        if (typeof text !== 'string' || text.length === 0) {
            return [];
        }
        const calls = [];
        let match;
        // Helper to extract balanced JSON from a position (handles nested braces)
        const extractBalancedJson = (str, startIdx) => {
            if (str[startIdx] !== '{')
                return null;
            let braceCount = 0;
            let inString = false;
            let escapeNext = false;
            for (let i = startIdx; i < str.length; i++) {
                const char = str[i];
                if (escapeNext) {
                    escapeNext = false;
                    continue;
                }
                if (char === '\\') {
                    escapeNext = true;
                    continue;
                }
                if (char === '"') {
                    inString = !inString;
                    continue;
                }
                if (!inString) {
                    if (char === '{')
                        braceCount++;
                    else if (char === '}') {
                        braceCount--;
                        if (braceCount === 0) {
                            return str.substring(startIdx, i + 1);
                        }
                    }
                }
            }
            return null;
        };
        // Helper to fix common JSON issues from AI outputs
        // IMPORTANT: Don't blindly replace quotes - it breaks code content
        const fixJson = (jsonStr) => {
            // First, escape newlines and control characters
            let fixed = jsonStr
                .replace(/\r/g, '') // Remove carriage returns
                .replace(/\t/g, '\\t'); // Escape tabs
            // Escape literal newlines inside strings (but not \n which is already escaped)
            // We need to be careful - only escape newlines that are inside quoted strings
            const parts = [];
            let inString = false;
            let currentPart = '';
            for (let i = 0; i < fixed.length; i++) {
                const char = fixed[i];
                const prevChar = i > 0 ? fixed[i - 1] : '';
                if (char === '"' && prevChar !== '\\') {
                    inString = !inString;
                    currentPart += char;
                }
                else if (char === '\n') {
                    if (inString) {
                        currentPart += '\\n'; // Escape the newline
                    }
                    else {
                        currentPart += char; // Keep as-is outside strings
                    }
                }
                else {
                    currentPart += char;
                }
            }
            fixed = currentPart;
            // Quote unquoted keys (only outside strings)
            fixed = fixed.replace(/([{,]\s*)(\w+)\s*:/g, '$1"$2":');
            // Remove trailing commas
            fixed = fixed.replace(/,\s*}/g, '}');
            fixed = fixed.replace(/,\s*]/g, ']');
            return fixed;
        };
        // Normalize tool name from various formats
        const normalizeToolName = (name) => {
            const normalized = name
                .replace(/^__/, '') // Remove leading underscores
                .replace(/__$/, '') // Remove trailing underscores
                .replace(/^execute_/i, '') // Remove execute_ prefix
                .replace(/_execute$/i, '') // Remove _execute suffix
                .toLowerCase();
            // Map common variations
            const toolMap = {
                'bash': 'bash',
                'shell': 'bash',
                'run': 'bash',
                'command': 'bash',
                'list_dir': 'list_dir',
                'list_directory': 'list_dir',
                'ls': 'list_dir',
                'dir': 'list_dir',
                'read_file': 'read_file',
                'readfile': 'read_file',
                'read': 'read_file',
                'write_file': 'write_file',
                'writefile': 'write_file',
                'write': 'write_file',
                'edit_file': 'edit_file',
                'editfile': 'edit_file',
                'edit': 'edit_file',
            };
            return toolMap[normalized] || normalized;
        };
        // Match <tool_call>...</tool_call> blocks
        const toolCallRegex = /<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/g;
        while ((match = toolCallRegex.exec(text)) !== null) {
            try {
                const fixed = fixJson(match[1]);
                const parsed = JSON.parse(fixed);
                if (parsed.tool && parsed.args) {
                    parsed.tool = normalizeToolName(parsed.tool);
                    calls.push(parsed);
                }
            }
            catch (e) {
                // Invalid JSON, skip
            }
        }
        // Match ```tool format
        const codeBlockRegex = /```tool\s*\n([\s\S]*?)\n```/g;
        while ((match = codeBlockRegex.exec(text)) !== null) {
            try {
                const fixed = fixJson(match[1]);
                const parsed = JSON.parse(fixed);
                if (parsed.tool && parsed.args) {
                    parsed.tool = normalizeToolName(parsed.tool);
                    calls.push(parsed);
                }
            }
            catch (e) {
                // Invalid JSON, skip
            }
        }
        // Match ```json blocks with tool definitions
        const jsonBlockRegex = /```(?:json)?\s*\n?([\s\S]*?"tool"[\s\S]*?)\n?```/g;
        while ((match = jsonBlockRegex.exec(text)) !== null) {
            try {
                const fixed = fixJson(match[1]);
                const parsed = JSON.parse(fixed);
                if (parsed.tool && parsed.args) {
                    parsed.tool = normalizeToolName(parsed.tool);
                    // Prevent duplicates
                    if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
                        calls.push(parsed);
                    }
                }
            }
            catch (e) {
                // Invalid JSON, skip
            }
        }
        // ROBUST PARSER: Find {"tool": at any position and extract balanced JSON
        // This handles multi-line content in write_file and nested structures
        const toolMarkerRegex = /\{"tool"\s*:/g;
        while ((match = toolMarkerRegex.exec(text)) !== null) {
            const startIdx = match.index;
            const jsonStr = extractBalancedJson(text, startIdx);
            if (jsonStr) {
                try {
                    const parsed = JSON.parse(jsonStr);
                    if (parsed.tool && parsed.args) {
                        parsed.tool = normalizeToolName(parsed.tool);
                        // Prevent duplicates
                        if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
                            calls.push(parsed);
                        }
                    }
                }
                catch (e) {
                    // Invalid JSON, try to fix it
                    try {
                        const fixed = fixJson(jsonStr);
                        const parsed = JSON.parse(fixed);
                        if (parsed.tool && parsed.args) {
                            parsed.tool = normalizeToolName(parsed.tool);
                            if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
                                calls.push(parsed);
                            }
                        }
                    }
                    catch (e2) {
                        // Still invalid - try more aggressive fixing for write_file
                        if (jsonStr.includes('"write_file"') || jsonStr.includes('"content"')) {
                            try {
                                // More aggressive: escape all control characters
                                const aggressiveFix = jsonStr
                                    .replace(/[\x00-\x1F]/g, (c) => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0'))
                                    .replace(/'/g, '"');
                                const parsed = JSON.parse(aggressiveFix);
                                if (parsed.tool && parsed.args) {
                                    parsed.tool = normalizeToolName(parsed.tool);
                                    if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
                                        calls.push(parsed);
                                    }
                                }
                            }
                            catch (e3) {
                                // Still invalid, skip
                            }
                        }
                    }
                }
            }
        }
        // Match inline JSON with "tool" key (various formats - tool before args)
        const inlineToolRegex = /\{[^{}]*"?tool"?\s*:\s*["']?([^"',}]+)["']?[^{}]*"?args"?\s*:\s*\{([^{}]*)\}[^{}]*\}/gi;
        while ((match = inlineToolRegex.exec(text)) !== null) {
            try {
                const fixed = fixJson(match[0]);
                const parsed = JSON.parse(fixed);
                if (parsed.tool && parsed.args) {
                    parsed.tool = normalizeToolName(parsed.tool);
                    if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
                        calls.push(parsed);
                    }
                }
            }
            catch (e) {
                // Invalid JSON, skip
            }
        }
        // Match inline JSON with "args" BEFORE "tool" (handles reversed order from some AI models)
        const inlineArgsFirstRegex = /\{[^{}]*"?args"?\s*:\s*\{([^{}]*)\}[^{}]*"?tool"?\s*:\s*["']?([^"',}]+)["']?[^{}]*\}/gi;
        while ((match = inlineArgsFirstRegex.exec(text)) !== null) {
            try {
                const fixed = fixJson(match[0]);
                const parsed = JSON.parse(fixed);
                if (parsed.tool && parsed.args) {
                    parsed.tool = normalizeToolName(parsed.tool);
                    if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
                        calls.push(parsed);
                    }
                }
            }
            catch (e) {
                // Invalid JSON, skip
            }
        }
        // Universal: Try to find any JSON object with both "tool" and "args" keys
        const universalJsonRegex = /\{[^{}]*(?:"tool"|"args")[^{}]*(?:"tool"|"args")[^{}]*\}/gi;
        while ((match = universalJsonRegex.exec(text)) !== null) {
            try {
                const fixed = fixJson(match[0]);
                const parsed = JSON.parse(fixed);
                if (parsed.tool && parsed.args) {
                    parsed.tool = normalizeToolName(parsed.tool);
                    if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
                        calls.push(parsed);
                    }
                }
            }
            catch (e) {
                // Invalid JSON, skip
            }
        }
        // Fallback: Try to parse each line as JSON (for plain JSON output without code blocks)
        // This handles cases where AI outputs just: {"args": {...}, "tool": "..."}
        const lines = text.split('\n');
        for (const line of lines) {
            const trimmed = line.trim();
            if (trimmed.startsWith('{') && trimmed.includes('"tool"') && trimmed.includes('"args"')) {
                try {
                    // Try to find balanced braces
                    let braceCount = 0;
                    let startIdx = -1;
                    let endIdx = -1;
                    for (let i = 0; i < trimmed.length; i++) {
                        if (trimmed[i] === '{') {
                            if (startIdx === -1)
                                startIdx = i;
                            braceCount++;
                        }
                        else if (trimmed[i] === '}') {
                            braceCount--;
                            if (braceCount === 0 && startIdx !== -1) {
                                endIdx = i + 1;
                                break;
                            }
                        }
                    }
                    if (startIdx !== -1 && endIdx !== -1) {
                        const jsonStr = trimmed.substring(startIdx, endIdx);
                        const fixed = fixJson(jsonStr);
                        const parsed = JSON.parse(fixed);
                        if (parsed.tool && parsed.args) {
                            parsed.tool = normalizeToolName(parsed.tool);
                            if (!calls.some(c => c.tool === parsed.tool && JSON.stringify(c.args) === JSON.stringify(parsed.args))) {
                                calls.push(parsed);
                            }
                        }
                    }
                }
                catch (e) {
                    // Invalid JSON, skip
                }
            }
        }
        // Parse Vigthoria V2 format: {"tool": "__BASH__", ...}
        const vigV2Regex = /"?tool"?\s*:\s*["']__?([A-Za-z_]+)__?["']/gi;
        while ((match = vigV2Regex.exec(text)) !== null) {
            try {
                const toolName = normalizeToolName(match[1]);
                // Extract args from nearby context
                const pathMatch = text.match(/"?(?:arg_)?path"?\s*:\s*["']([^"']+)["']/i);
                const cmdMatch = text.match(/"?command"?\s*:\s*(?:["']([^"']+)["']|\[\s*["']([^"']+)["']\s*\])/i);
                const contentMatch = text.match(/"?content"?\s*:\s*["']([^"']+)["']/i);
                const args = {};
                if (pathMatch)
                    args.path = pathMatch[1];
                if (cmdMatch)
                    args.command = cmdMatch[1] || cmdMatch[2];
                if (contentMatch)
                    args.content = contentMatch[1];
                if (Object.keys(args).length > 0) {
                    // Prevent duplicates
                    if (!calls.some(c => c.tool === toolName && JSON.stringify(c.args) === JSON.stringify(args))) {
                        calls.push({ tool: toolName, args });
                    }
                }
            }
            catch (e) {
                // Skip
            }
        }
        return calls;
    }
    /**
     * Get tools formatted for AI system prompt
     */
    static getToolsForPrompt() {
        const tools = AgenticTools.getToolDefinitions();
        let prompt = `## AGENT MODE - YOU MUST USE TOOLS

⚠️ CRITICAL: You are in Agent Mode. You MUST use tools to interact with files and the system.
DO NOT guess or hallucinate file contents. DO NOT make up directory structures.
ALWAYS use read_file before discussing what's in a file.
ALWAYS use list_dir before discussing what's in a directory.
  DO NOT ask the user to pick between actions you can already perform.
  WHEN A FILE IS BROKEN, INCOMPLETE, OR TRUNCATED: inspect it fully, fix it directly, and return the completed result.
  NEVER write placeholders like "rest of CSS", "implementation goes here", or incomplete HTML/JS fragments.
  IF STRUCTURE IS BROKEN: prefer rewriting the full file with write_file after reading enough context.

You have access to these tools:

`;
        for (const tool of tools) {
            prompt += `## ${tool.name}
${tool.description}
Parameters:
${tool.parameters.map(p => `  - ${p.name}${p.required ? ' (required)' : ''}: ${p.description}`).join('\n')}

`;
        }
        prompt += `
## How to Use Tools

To use a tool, output a JSON block in a code fence with "tool" language:

\`\`\`tool
{"tool": "tool_name", "args": {"param1": "value1"}}
\`\`\`

## MANDATORY TOOL USAGE (DO NOT SKIP!)

**When user asks "what's in this folder/directory":**
→ FIRST use list_dir, THEN respond based on actual results

**When user asks "can you see/read/show me file X":**
→ FIRST use read_file, THEN respond based on actual contents

**When user mentions a path like "C:\\some\\path" or "/some/path":**
→ FIRST use list_dir to check if it exists, THEN respond

**NEVER say things like "Here's an overview of the contents..." without first using tools!**
**NEVER describe files or code you haven't actually read with read_file!**

### Examples:

1. List directory contents:
\`\`\`tool
{"tool": "list_dir", "args": {"path": "."}}
\`\`\`

2. Read a file:
\`\`\`tool
{"tool": "read_file", "args": {"path": "src/index.js"}}
\`\`\`

3. Fetch a web page (full HTML):
\`\`\`tool
{"tool": "fetch_url", "args": {"url": "https://example.com"}}
\`\`\`

4. Fetch specific content with selectors:
\`\`\`tool
{"tool": "fetch_url", "args": {"url": "https://example.com", "selector": "h1, h2, h3"}}
\`\`\`
   Available selectors: title, body, text, links, nav, footer, images, h1, h2, h3, h1/h2/h3 (compound)

5. Run command on YOUR configured SSH server (requires user SSH setup, NOT Vigthoria servers):
\`\`\`tool
{"tool": "ssh_exec", "args": {"command": "curl -s https://example.com | head -20", "host": "your-server"}}
\`\`\`
   Note: ssh_exec is for users who have their own servers configured. It does NOT connect to Vigthoria infrastructure.

6. Write a file:
\`\`\`tool
{"tool": "write_file", "args": {"path": "hello.py", "content": "print('Hello World')"}}
\`\`\`

## CRITICAL RULES:

### ABSOLUTELY NO HALLUCINATION (READ THIS CAREFULLY):
- ONLY use information from tool results you just received in THIS conversation
- DO NOT make up names, organizations, or content that wasn't in the fetched data
- DO NOT read random files from the workspace expecting them to contain relevant data
- If you fetch a website, your analysis MUST be based ONLY on what you just fetched
- If the user asks about websites A and B, ONLY discuss A and B - don't invent Site C
- NEVER create fictional organizations, services, or content
- If you're unsure about something, say "Based on the fetched content, I can see..." not "This organization does..."

### Strategic Planning (VERY IMPORTANT):
- PLAN before acting - don't issue many redundant tool calls
- For web comparisons: Fetch each URL ONCE with no selector to get full HTML, then analyze locally
- Do NOT fetch the same URL multiple times with different selectors - fetch once and parse the result
- Think step-by-step: 1) Gather data, 2) Analyze it, 3) Present findings
- If comparing two things, fetch both ONCE, then write a REAL comparison with specific differences
- Maximum 2-4 tool calls per step is usually enough - don't spam 10+ calls at once
- Do NOT use list_dir or read_file when the task is about fetching websites - those are for LOCAL files only

### Cross-Platform Compatibility:
- On Windows, Unix commands (head, tail, grep, awk, sed, wc) are NOT available
- Use \`fetch_url\` for web requests instead of curl|grep
- Use \`ssh_exec\` to run Unix commands on the Vigthoria server if needed
- Use \`read_file\` instead of cat
- Use \`list_dir\` instead of ls

### Handling Tool Failures:
- If a tool fails, REPORT the failure honestly to the user
- NEVER make up or hallucinate content when a tool fails
- If you cannot access a URL, say "I was unable to fetch the URL because..."
- If a command fails, explain what happened and suggest alternatives
- Do NOT write analysis or comparison reports if you couldn't gather the actual data

### Comparison Tasks:
- When asked to compare websites/files, you MUST produce actual specific differences
- Don't just describe each site separately - show what Site A has that Site B is missing
- Use concrete examples: "Site A has a Team page at /team.html, Site B does not"
- If you need sub-pages, fetch them in follow-up steps after analyzing the main page
- BASE YOUR COMPARISON ONLY ON THE DATA YOU FETCHED - not on random files in the workspace
- Quote actual text from the fetched content to support your claims

### File Access:
- You can ONLY access files within the current project workspace
- Use relative paths (e.g., "src/file.js", "app.py", "./config.json")
- Never try to access system files or directories outside the workspace
- Do NOT read files unrelated to the user's request (e.g., don't read "comparison.md" when asked to fetch websites)
- When comparing WEBSITES, use fetch_url - do NOT use read_file or list_dir

### Tool Names:
- 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
- The JSON must be valid with double quotes for all keys and string values
- After tool execution, you will receive results and can continue with the next step
- Explain what you're doing before using tools

### Sub-Agent Delegation (task tool):
- Use the task tool to delegate complex subtasks to an independent sub-agent
- The sub-agent has its own tools and context, runs autonomously, and returns results
- Great for: parallel research, investigating side questions, exploring unfamiliar code
- Example:
\`\`\`tool
{"tool": "task", "args": {"description": "Find all API endpoints in the backend and list their HTTP methods and paths"}}
\`\`\`

### Atomic Multi-File Edits (multi_edit tool):
- Use multi_edit to apply multiple edits atomically - all succeed or all roll back
- Pass edits as a JSON array in the edits parameter
- Example:
\`\`\`tool
{"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)\\"}]"}}
\`\`\`

### Deep Codebase Search (codebase_search tool):
- Use codebase_search for large projects to find symbols, files, or content across the ENTIRE codebase
- Not limited by workspace snapshot - searches all files recursively
- Scopes: "symbols" (functions/classes), "files" (filenames), "content" (full-text), "all" (default)
- Example:
\`\`\`tool
{"tool": "codebase_search", "args": {"query": "handleAuthentication", "scope": "symbols"}}
\`\`\`
`;
        return prompt;
    }
}
