File size: 3,799 Bytes
eca5751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
"""
Tool Base Class - Nền tảng cho tất cả tools
============================================
Định nghĩa interface chung cho mọi tool trong Nexus Coder.
"""
from __future__ import annotations

from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
from enum import Enum


class ToolSafety(str, Enum):
    """Mức độ an toàn của tool."""
    SAFE = "safe"            # Read-only, no side effects
    MODERATE = "moderate"    # Writes to local files
    DANGEROUS = "dangerous"  # Executes commands, network ops
    DESTRUCTIVE = "destructive"  # Can delete data, requires confirmation


class ToolCategory(str, Enum):
    """Phân loại tools."""
    FILE = "file"
    EXEC = "exec"
    WEB = "web"
    CODE = "code"
    MATH = "math"
    PARSER = "parser"
    SYSTEM = "system"
    NETWORK = "network"
    CRYPTO = "crypto"
    DATA = "data"
    # v0.3 NEW categories
    DATABASE = "database"
    DEVOPS = "devops"
    CLOUD = "cloud"
    ML = "ml"
    SECURITY = "security"
    CONVERT = "convert"
    GIT = "git"
    MONITOR = "monitor"
    BLOCKCHAIN = "blockchain"
    MEDIA = "media"


@dataclass
class ToolContext:
    """Context cho tool execution.
    
    Attributes:
        working_dir: Thư mục làm việc
        timeout: Timeout seconds
        env: Environment variables
        sandbox: Có chạy trong sandbox không
        user_id: ID của user (cho audit)
        dry_run: Chỉ simulate, không thực sự chạy
    """
    working_dir: str = "."
    timeout: int = 30
    env: Dict[str, str] = field(default_factory=dict)
    sandbox: bool = True
    user_id: Optional[str] = None
    dry_run: bool = False


@dataclass
class ToolResult:
    """Kết quả trả về từ tool.
    
    Attributes:
        success: Có thành công không
        output: Output text (stdout)
        error: Error output (stderr)
        return_code: Exit code (nếu có)
        artifacts: Files được tạo/sửa
        metadata: Extra metadata
        duration: Thời gian thực thi (seconds)
    """
    success: bool = True
    output: str = ""
    error: Optional[str] = None
    return_code: int = 0
    artifacts: List[str] = field(default_factory=list)
    metadata: Dict[str, Any] = field(default_factory=dict)
    duration: float = 0.0


class Tool(ABC):
    """Base class cho mọi tool trong Nexus Coder.
    
    Mỗi tool phải implement:
    - name: Tên định danh duy nhất
    - description: Mô tả ngắn
    - execute: Hàm chính thực thi tool
    - validate_args: Validate arguments trước khi chạy
    """
    
    category: ToolCategory = ToolCategory.FILE
    safety: ToolSafety = ToolSafety.SAFE
    requires_confirmation: bool = False
    timeout: int = 30
    
    @property
    @abstractmethod
    def name(self) -> str:
        """Tên duy nhất của tool (snake_case)."""
        ...
    
    @property
    @abstractmethod
    def description(self) -> str:
        """Mô tả ngắn gọn tool làm gì."""
        ...
    
    @property
    def parameters(self) -> Dict[str, Any]:
        """JSON schema cho parameters."""
        return {}
    
    @property
    def version(self) -> str:
        return "0.3.0"
    
    @property
    def author(self) -> str:
        return "Hieu Louis"
    
    def validate_args(self, args: Dict[str, Any]) -> Optional[str]:
        """Validate args. Trả về error message nếu invalid, None nếu OK."""
        return None
    
    @abstractmethod
    def execute(self, args: Dict[str, Any], context: ToolContext) -> ToolResult:
        """Thực thi tool với args và context."""
        ...
    
    def __repr__(self) -> str:
        return f"<Tool {self.name} (safety={self.safety.value})>"