From 72453f4fdbda1be8ded92c80ba699c0f2bf11930 Mon Sep 17 00:00:00 2001 From: HuMaN-OG Date: Sat, 31 Oct 2026 02:56:22 +0530 Subject: [PATCH 1/5] fix(core): complete real desktop automation, multi-format file editing, file management, and accurate intent routing --- automation/src/main.py | 435 ++-- automation/src/tools/desktop_tool.py | 2613 +++++++++++++++------- automation/src/tools/file_tool.py | 278 ++- backend/src/schemas/toolSchema.js | 413 ++-- backend/src/services/intentClassifier.js | 15 +- backend/src/services/taskPlanner.js | 466 ++-- backend/tests/test-api.js | 8 +- 7 files changed, 2637 insertions(+), 1591 deletions(-) diff --git a/automation/src/main.py b/automation/src/main.py index 4392219..3c3070a 100644 --- a/automation/src/main.py +++ b/automation/src/main.py @@ -1,207 +1,228 @@ -from fastapi import FastAPI, HTTPException, status, Header -from fastapi.middleware.cors import CORSMiddleware -from pydantic import BaseModel, Field -from typing import Dict, Any, List, Optional -import uvicorn -import re -import os -from pathlib import Path - -from src.config import HOST, PORT, WORKSPACE_DIR, AUTH_TOKEN -from src.tools.excel_tool import execute_excel_tool -from src.tools.file_tool import execute_file_tool -from src.tools.desktop_tool import execute_desktop_tool -from src.tools.document_tool import execute_document_tool - -app = FastAPI( - title="FORGE AI - Python Automation Service", - description="Local tool automation runtime for sandboxed file and Excel operations.", - version="1.0.0" -) - -# CORS restricted strictly to intended local origins -app.add_middleware( - CORSMiddleware, - allow_origins=[ - "http://localhost:5173", - "http://127.0.0.1:5173", - "http://localhost:3000", - "http://127.0.0.1:3000" - ], - allow_credentials=True, - allow_methods=["GET", "POST", "OPTIONS"], - allow_headers=["*"], -) - -# STRICT SECURITY POLICY: Forbidden arbitrary command execution patterns -FORBIDDEN_KEYWORDS = [ - r"\bterminal\b", - r"\bshell\b", - r"\bbash\b", - r"\bcmd\b", - r"\bpowershell\b", - r"\bexec\b", - r"\beval\b", - r"\bspawn\b", - r"\bsubprocess\b", - r"\bos\.system\b", - r"\brm\s+-rf\b" -] - -def check_security_violation(tool: str, action: Optional[str], params: Dict[str, Any]) -> bool: - for pattern in FORBIDDEN_KEYWORDS: - if re.search(pattern, tool or "", re.IGNORECASE): - return True - if action and re.search(pattern, action, re.IGNORECASE): - return True - - # Scan parameter metadata while treating document body text as data - safe_params = { - k: v for k, v in params.items() - if k not in ("text", "content", "rows", "headers") - } - params_str = str(safe_params) - for pattern in FORBIDDEN_KEYWORDS: - if re.search(pattern, params_str, re.IGNORECASE): - return True - return False - - -class ToolExecutionRequest(BaseModel): - contractVersion: str = Field(default="1.0", description="API contract version") - taskId: str = Field(..., description="Task ID assigned by backend orchestrator") - tool: str = Field(..., description="Registered tool name: 'excel_writer', 'file_system', or 'desktop_control'") - action: Optional[str] = Field(default=None, description="Tool action name (e.g. list_directory)") - params: Dict[str, Any] = Field(default_factory=dict, description="Tool-specific structured parameters") - workspaceId: str = Field(default="default", description="Workspace ID") - executionMode: str = Field(default="approved", description="Execution mode: approved") - - -class Artifact(BaseModel): - name: str - path: str - type: str - size: Optional[int] = 0 - - -class ToolExecutionResponse(BaseModel): - success: bool - contractVersion: str = "1.0" - tool: str - action: Optional[str] = None - taskId: str - output: Optional[Dict[str, Any]] = None - artifacts: Optional[List[Artifact]] = None - error: Optional[str] = None - - -@app.get("/health") -def health_check(): - """Initial health check endpoint required by FORGE AI system.""" - return { - "status": "healthy", - "service": "forge-python-automation", - "version": "1.0.0", - "host": HOST, - "port": PORT, - "registered_tools": ["excel_writer", "file_system", "desktop_control", "document_generator", "document_parser"], - "registered_actions": { - "desktop_control": [ - "list_windows", - "get_active_window", - "launch_application", - "type_text", - "press_key", - "save_document", - "verify_document", - "notepad_report" - ] - }, - "sandbox_directory": str(WORKSPACE_DIR), - "arbitrary_execution_policy": "STRICTLY_BLOCKED" - } - - -@app.post("/tools/execute", response_model=ToolExecutionResponse) -def execute_tool( - request: ToolExecutionRequest, - x_forge_token: Optional[str] = Header(None, alias="X-FORGE-TOKEN") -): - """ - Executes a registered tool under safe sandbox boundaries with token authentication. - Arbitrary terminal commands are strictly rejected. - """ - # 0. Enforce authentication token verification - if not x_forge_token or x_forge_token != AUTH_TOKEN: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Authentication failed: Missing or invalid X-FORGE-TOKEN header." - ) - - # 1. Enforce security gate: Reject any arbitrary command execution - if check_security_violation(request.tool, request.action, request.params): - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Security Policy Violation: Arbitrary terminal/shell command execution is strictly forbidden." - ) - - # Propagate action into params if given - if request.action and "action" not in request.params: - request.params["action"] = request.action - - action_name = request.action or request.params.get("action") - - # 2. Dispatch to registered tools - if request.tool == "excel_writer": - result = execute_excel_tool(request.params, WORKSPACE_DIR) - elif request.tool in ("document_generator", "document_parser"): - result = execute_document_tool(request.params, WORKSPACE_DIR) - elif request.tool == "file_system": - if action_name in ("create_docx", "create_pdf", "create_pptx", "create_csv", "create_json", "read_pdf", "read_docx"): - result = execute_document_tool(request.params, WORKSPACE_DIR) - else: - result = execute_file_tool(request.params, WORKSPACE_DIR) - elif request.tool == "desktop_control": - result = execute_desktop_tool(request.params, WORKSPACE_DIR) - else: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Unregistered tool: '{request.tool}'. Registered tools are: ['excel_writer', 'file_system', 'desktop_control', 'document_generator', 'document_parser']" - ) - - if not result.get("success"): - return ToolExecutionResponse( - success=False, - contractVersion=request.contractVersion, - tool=request.tool, - action=action_name, - taskId=request.taskId, - output=result, - artifacts=[], - error=result.get("error", "Tool execution failed") - ) - - artifacts = result.get("artifacts", []) - formatted_artifacts = [ - Artifact( - name=a.get("name", "artifact"), - path=a.get("path", ""), - type=a.get("type", "file"), - size=a.get("size", 0) - ) - for a in artifacts - ] - - return ToolExecutionResponse( - success=True, - contractVersion=request.contractVersion, - tool=request.tool, - action=action_name, - taskId=request.taskId, - output=result, - artifacts=formatted_artifacts - ) - - -if __name__ == "__main__": - uvicorn.run("src.main:app", host=HOST, port=PORT, reload=False) +from fastapi import FastAPI, HTTPException, status, Header +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field +from typing import Dict, Any, List, Optional +import uvicorn +import re +import os +from pathlib import Path + +from src.config import HOST, PORT, WORKSPACE_DIR, AUTH_TOKEN +from src.tools.excel_tool import execute_excel_tool +from src.tools.file_tool import execute_file_tool +from src.tools.desktop_tool import execute_desktop_tool +from src.tools.document_tool import execute_document_tool + +app = FastAPI( + title="FORGE AI - Python Automation Service", + description="Local tool automation runtime for sandboxed file and Excel operations.", + version="1.0.0" +) + +# CORS restricted strictly to intended local origins +app.add_middleware( + CORSMiddleware, + allow_origins=[ + "http://localhost:5173", + "http://127.0.0.1:5173", + "http://localhost:3000", + "http://127.0.0.1:3000" + ], + allow_credentials=True, + allow_methods=["GET", "POST", "OPTIONS"], + allow_headers=["*"], +) + +# STRICT SECURITY POLICY: Forbidden arbitrary command execution patterns +FORBIDDEN_KEYWORDS = [ + r"\bterminal\b", + r"\bshell\b", + r"\bbash\b", + r"\bcmd\b", + r"\bpowershell\b", + r"\bexec\b", + r"\beval\b", + r"\bspawn\b", + r"\bsubprocess\b", + r"\bos\.system\b", + r"\brm\s+-rf\b" +] + +def check_security_violation(tool: str, action: Optional[str], params: Dict[str, Any]) -> bool: + for pattern in FORBIDDEN_KEYWORDS: + if re.search(pattern, tool or "", re.IGNORECASE): + return True + if action and re.search(pattern, action, re.IGNORECASE): + return True + + # Scan parameter metadata while treating document body text as data + safe_params = { + k: v for k, v in params.items() + if k not in ("text", "content", "rows", "headers") + } + params_str = str(safe_params) + for pattern in FORBIDDEN_KEYWORDS: + if re.search(pattern, params_str, re.IGNORECASE): + return True + return False + + +class ToolExecutionRequest(BaseModel): + contractVersion: str = Field(default="1.0", description="API contract version") + taskId: str = Field(..., description="Task ID assigned by backend orchestrator") + tool: str = Field(..., description="Registered tool name: 'excel_writer', 'file_system', or 'desktop_control'") + action: Optional[str] = Field(default=None, description="Tool action name (e.g. list_directory)") + params: Dict[str, Any] = Field(default_factory=dict, description="Tool-specific structured parameters") + workspaceId: str = Field(default="default", description="Workspace ID") + executionMode: str = Field(default="approved", description="Execution mode: approved") + + +class Artifact(BaseModel): + name: str + path: str + type: str + size: Optional[int] = 0 + + +class ToolExecutionResponse(BaseModel): + success: bool + contractVersion: str = "1.0" + tool: str + action: Optional[str] = None + taskId: str + output: Optional[Dict[str, Any]] = None + artifacts: Optional[List[Artifact]] = None + error: Optional[str] = None + + +@app.get("/health") +def health_check(): + """Initial health check endpoint required by FORGE AI system.""" + return { + "status": "healthy", + "service": "forge-python-automation", + "version": "1.0.0", + "host": HOST, + "port": PORT, + "registered_tools": ["excel_writer", "file_system", "desktop_control", "document_generator", "document_parser"], + "registered_actions": { + "desktop_control": [ + "list_windows", + "get_active_window", + "launch_application", + "calculate", + "calculator_operation", + "type_text", + "press_key", + "save_document", + "verify_document", + "notepad_report", + "open_document_in_app" + ], + "file_system": [ + "list_directory", + "read_file", + "write_file", + "create_file", + "copy_file", + "move_file", + "rename_file", + "create_directory", + "create_folder", + "delete_file", + "search_files", + "find_files", + "get_file_info", + "edit_file", + "append_file", + "organize_by_extension" + ] + }, + "sandbox_directory": str(WORKSPACE_DIR), + "arbitrary_execution_policy": "STRICTLY_BLOCKED" + } + + +@app.post("/tools/execute", response_model=ToolExecutionResponse) +def execute_tool( + request: ToolExecutionRequest, + x_forge_token: Optional[str] = Header(None, alias="X-FORGE-TOKEN") +): + """ + Executes a registered tool under safe sandbox boundaries with token authentication. + Arbitrary terminal commands are strictly rejected. + """ + # 0. Enforce authentication token verification + if not x_forge_token or x_forge_token != AUTH_TOKEN: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Authentication failed: Missing or invalid X-FORGE-TOKEN header." + ) + + # 1. Enforce security gate: Reject any arbitrary command execution + if check_security_violation(request.tool, request.action, request.params): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Security Policy Violation: Arbitrary terminal/shell command execution is strictly forbidden." + ) + + # Propagate action into params if given + if request.action and "action" not in request.params: + request.params["action"] = request.action + + action_name = request.action or request.params.get("action") + + # 2. Dispatch to registered tools + if request.tool == "excel_writer": + result = execute_excel_tool(request.params, WORKSPACE_DIR) + elif request.tool in ("document_generator", "document_parser"): + result = execute_document_tool(request.params, WORKSPACE_DIR) + elif request.tool == "file_system": + if action_name in ("create_docx", "create_pdf", "create_pptx", "create_csv", "create_json", "read_pdf", "read_docx"): + result = execute_document_tool(request.params, WORKSPACE_DIR) + else: + result = execute_file_tool(request.params, WORKSPACE_DIR) + elif request.tool == "desktop_control": + result = execute_desktop_tool(request.params, WORKSPACE_DIR) + else: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail=f"Unregistered tool: '{request.tool}'. Registered tools are: ['excel_writer', 'file_system', 'desktop_control', 'document_generator', 'document_parser']" + ) + + if not result.get("success"): + return ToolExecutionResponse( + success=False, + contractVersion=request.contractVersion, + tool=request.tool, + action=action_name, + taskId=request.taskId, + output=result, + artifacts=[], + error=result.get("error", "Tool execution failed") + ) + + artifacts = result.get("artifacts", []) + formatted_artifacts = [ + Artifact( + name=a.get("name", "artifact"), + path=a.get("path", ""), + type=a.get("type", "file"), + size=a.get("size", 0) + ) + for a in artifacts + ] + + return ToolExecutionResponse( + success=True, + contractVersion=request.contractVersion, + tool=request.tool, + action=action_name, + taskId=request.taskId, + output=result, + artifacts=formatted_artifacts + ) + + +if __name__ == "__main__": + uvicorn.run("src.main:app", host=HOST, port=PORT, reload=False) diff --git a/automation/src/tools/desktop_tool.py b/automation/src/tools/desktop_tool.py index 249f9de..922e49a 100644 --- a/automation/src/tools/desktop_tool.py +++ b/automation/src/tools/desktop_tool.py @@ -1,833 +1,1780 @@ -""" -FORGE AI — Computer Control Engine Tool Module -desktop_control: Provides local desktop automation via pywinauto UIA backend. - -Strict Security Boundaries: -- Strict Application Allowlist (Notepad, File Explorer). Arbitrary executables are strictly forbidden. -- Strict Keyboard Sequence Allowlist (CTRL+S, CTRL+A, ENTER, ESC, ALT+F4). -- Safe sandboxed file operations confined strictly to canonical workspace_sandbox. -- Human authorization required prior to execution. -""" - -import os -import sys -import time -import subprocess -import hashlib -from pathlib import Path -from typing import Dict, Any, List, Optional, Tuple - -import win32gui -import win32process -import winreg -import shutil -import win32con -import win32api -import ctypes - -try: - from pywinauto import Desktop, Application - from pywinauto.keyboard import send_keys - PYWINAUTO_AVAILABLE = True -except ImportError: - PYWINAUTO_AVAILABLE = False - - -# STRICT APPLICATION ALLOWLIST: Only explicitly approved local utilities -APPROVED_APPLICATIONS = { - "notepad": { - "binary": "notepad.exe", - "title_pattern": r".*Notepad.*", - "doc_control_type": "Document" - }, - "file_explorer": { - "binary": "explorer.exe", - "title_pattern": r".*File Explorer.*", - "doc_control_type": None - }, - "explorer": { - "binary": "explorer.exe", - "title_pattern": r".*File Explorer.*", - "doc_control_type": None - }, - "word": { - "binary": "WINWORD.EXE", - "title_pattern": r".*Word.*", - "doc_control_type": "Document" - }, - "winword": { - "binary": "WINWORD.EXE", - "title_pattern": r".*Word.*", - "doc_control_type": "Document" - }, - "excel": { - "binary": "EXCEL.EXE", - "title_pattern": r".*Excel.*", - "doc_control_type": None - }, - "powerpoint": { - "binary": "POWERPNT.EXE", - "title_pattern": r".*PowerPoint.*", - "doc_control_type": None - }, - "ppt": { - "binary": "POWERPNT.EXE", - "title_pattern": r".*PowerPoint.*", - "doc_control_type": None - }, - "chrome": { - "binary": "chrome.exe", - "title_pattern": r".*Chrome.*", - "doc_control_type": None - }, - "edge": { - "binary": "msedge.exe", - "title_pattern": r".*Edge.*", - "doc_control_type": None - }, - "vscode": { - "binary": "Code.exe", - "title_pattern": r".*Visual Studio Code.*", - "doc_control_type": None - }, - "code": { - "binary": "Code.exe", - "title_pattern": r".*Visual Studio Code.*", - "doc_control_type": None - }, - "calc": { - "binary": "calc.exe", - "title_pattern": r".*Calculator.*", - "doc_control_type": None - }, - "calculator": { - "binary": "calc.exe", - "title_pattern": r".*Calculator.*", - "doc_control_type": None - } -} - -def resolve_approved_executable(app_key: str) -> Optional[str]: - """ - Safely resolves the full path to an approved application's executable. - Checks: - 1. PATH via shutil.which - 2. Windows Registry App Paths (HKLM and HKCU) - 3. Common fixed 64-bit and 32-bit Program Files directories - Never accepts arbitrary user-supplied paths. - """ - if app_key not in APPROVED_APPLICATIONS: - return None - - binary = APPROVED_APPLICATIONS[app_key]["binary"] - - # 1. Check system PATH - found = shutil.which(binary) - if found and os.path.isfile(found): - return found - - # 2. Check Registry App Paths - for root in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER): - try: - key_path = f"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\{binary}" - with winreg.OpenKey(root, key_path) as k: - val, _ = winreg.QueryValueEx(k, "") - if val and os.path.isfile(val): - return val - except Exception: - pass - - # 3. Known standard install paths for allowlisted apps - common_roots = [ - os.environ.get("ProgramFiles", "C:\\Program Files"), - os.environ.get("ProgramFiles(x86)", "C:\\Program Files (x86)"), - os.environ.get("LocalAppData", "C:\\Users\\Default\\AppData\\Local") - ] - app_relative_hints = { - "word": ["Microsoft Office\\root\\Office16\\WINWORD.EXE", "Microsoft Office\\Office16\\WINWORD.EXE"], - "winword": ["Microsoft Office\\root\\Office16\\WINWORD.EXE", "Microsoft Office\\Office16\\WINWORD.EXE"], - "excel": ["Microsoft Office\\root\\Office16\\EXCEL.EXE", "Microsoft Office\\Office16\\EXCEL.EXE"], - "powerpoint": ["Microsoft Office\\root\\Office16\\POWERPNT.EXE", "Microsoft Office\\Office16\\POWERPNT.EXE"], - "ppt": ["Microsoft Office\\root\\Office16\\POWERPNT.EXE", "Microsoft Office\\Office16\\POWERPNT.EXE"], - "chrome": ["Google\\Chrome\\Application\\chrome.exe"], - "edge": ["Microsoft\\Edge\\Application\\msedge.exe"], - "vscode": ["Programs\\Microsoft VS Code\\Code.exe", "Microsoft VS Code\\Code.exe"], - "code": ["Programs\\Microsoft VS Code\\Code.exe", "Microsoft VS Code\\Code.exe"] - } - - hints = app_relative_hints.get(app_key, []) - for c_root in common_roots: - for hint in hints: - cand = os.path.join(c_root, hint) - if os.path.isfile(cand): - return cand - - return None - -# STRICT KEYBOARD SEQUENCE ALLOWLIST: Only approved operational keystrokes -APPROVED_KEY_COMBOS = { - "CTRL+S": "^s", - "CTRL+A": "^a", - "ENTER": "{ENTER}", - "ESC": "{ESC}", - "ALT+F4": "%{F4}" -} - -ALLOWED_DESKTOP_EXTENSIONS = {".txt", ".md", ".log", ".docx", ".pdf", ".pptx", ".csv", ".json", ".xlsx"} - - -def safe_resolve_desktop_path(filename: str, workspace_dir: Path) -> Path: - """ - Validates and safely resolves a file path strictly inside the canonical workspace sandbox. - Rejects directory traversal, backslashes/slashes, and unapproved extensions. - """ - if not filename or not isinstance(filename, str): - raise ValueError("Filename must be a non-empty string.") - - # Prevent directory traversal attacks - if "/" in filename or "\\" in filename or ".." in filename: - raise PermissionError(f"Security Policy Violation: File path traversal or directory separators are forbidden: '{filename}'") - - # Allowed extensions - suffix = Path(filename).suffix.lower() - if suffix not in ALLOWED_DESKTOP_EXTENSIONS: - raise PermissionError( - f"Access Denied: Unsupported file extension '{suffix}'. Permitted desktop extensions: {', '.join(sorted(ALLOWED_DESKTOP_EXTENSIONS))}" - ) - - resolved_workspace = workspace_dir.resolve() - target_path = (resolved_workspace / filename).resolve() - - try: - target_path.relative_to(resolved_workspace) - except ValueError: - raise PermissionError(f"Access Denied: Path '{filename}' attempts to escape workspace sandbox.") - - return target_path - - -def get_collision_safe_path(target_path: Path) -> Path: - """Returns a non-colliding file path by appending _1, _2 if file exists.""" - if not target_path.exists(): - return target_path - - parent = target_path.parent - stem = target_path.stem - suffix = target_path.suffix - counter = 1 - - while True: - new_path = parent / f"{stem}_{counter}{suffix}" - if not new_path.exists(): - return new_path - counter += 1 - - -def force_foreground_window(hwnd: int): - """ - Reliably brings a window handle to the foreground on Windows. - Bypasses foreground lock restriction safely. - """ - if not hwnd or not win32gui.IsWindow(hwnd): - return - - try: - if win32gui.IsIconic(hwnd): - win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) - else: - win32gui.ShowWindow(hwnd, win32con.SW_SHOW) - - current_thread_id = ctypes.windll.kernel32.GetCurrentThreadId() - target_thread_id, _ = win32process.GetWindowThreadProcessId(hwnd) - - ctypes.windll.user32.AllowSetForegroundWindow(-1) - ctypes.windll.user32.AttachThreadInput(current_thread_id, target_thread_id, True) - ctypes.windll.user32.SetForegroundWindow(hwnd) - ctypes.windll.user32.SetFocus(hwnd) - ctypes.windll.user32.AttachThreadInput(current_thread_id, target_thread_id, False) - except Exception: - pass - - -def list_desktop_windows(filter_visible: bool = True) -> List[Dict[str, Any]]: - """ - Enumerates active desktop top-level windows via pywinauto UIA backend. - """ - if not PYWINAUTO_AVAILABLE: - raise RuntimeError("pywinauto is not available in the current Python environment.") - - d = Desktop(backend="uia") - wins = d.windows() - active_hwnd = win32gui.GetForegroundWindow() - - window_list = [] - for w in wins: - try: - title = w.window_text().strip() - visible = w.is_visible() - if filter_visible and (not visible or not title): - continue - - hwnd = w.handle - pid = w.process_id() - class_name = w.class_name() - - # Identify known process name from class or allowlist - process_name = "unknown" - if "notepad" in class_name.lower() or "notepad" in title.lower(): - process_name = "notepad.exe" - elif "cabinetwclass" in class_name.lower() or "explorer" in class_name.lower(): - process_name = "explorer.exe" - - window_list.append({ - "handle": hwnd, - "title": title, - "pid": pid, - "class_name": class_name, - "process_name": process_name, - "visible": visible, - "is_active": hwnd == active_hwnd - }) - except Exception: - continue - - return window_list - - -def get_active_desktop_window() -> Dict[str, Any]: - """ - Returns metadata for the current active foreground window. - """ - hwnd = win32gui.GetForegroundWindow() - title = win32gui.GetWindowText(hwnd).strip() if hwnd else "" - pid = 0 - if hwnd: - _, pid = win32process.GetWindowThreadProcessId(hwnd) - - rect = {} - if hwnd: - try: - r = win32gui.GetWindowRect(hwnd) - rect = {"left": r[0], "top": r[1], "right": r[2], "bottom": r[3], "width": r[2] - r[0], "height": r[3] - r[1]} - except Exception: - pass - - return { - "handle": hwnd, - "title": title or "Desktop", - "pid": pid, - "rect": rect, - "is_active": True - } - - -def launch_approved_application(app_name: str) -> Dict[str, Any]: - """ - Launches an approved application from the strict allowlist. - Arbitrary executable names or paths are strictly rejected. - """ - if not app_name or not isinstance(app_name, str): - raise ValueError("Parameter 'appName' is required and must be a string.") - - normalized_app = app_name.strip().lower() - if normalized_app not in APPROVED_APPLICATIONS: - approved_names = sorted(list(set(APPROVED_APPLICATIONS.keys()))) - raise PermissionError( - f"Access Denied: Application '{app_name}' is not in the approved desktop allowlist. Permitted applications: {approved_names}" - ) - - app_spec = APPROVED_APPLICATIONS[normalized_app] - binary = app_spec["binary"] - title_pattern = app_spec["title_pattern"] - - # Resolve binary full path safely - exec_path = resolve_approved_executable(normalized_app) - if not exec_path: - raise FileNotFoundError( - f"Application '{app_name}' is in the approved allowlist, but its executable '{binary}' was not found on this system." - ) - - # Launch application using verified safe binary - proc = subprocess.Popen([exec_path]) - - # Wait for window to appear (up to 5 seconds) - found_window = None - deadline = time.time() + 5.0 - while time.time() < deadline: - d = Desktop(backend="uia") - candidates = d.windows(title_re=title_pattern) - if candidates: - found_window = candidates[0] - break - time.sleep(0.3) - - window_title = found_window.window_text() if found_window else f"{app_name} (Launched)" - window_handle = found_window.handle if found_window else 0 - - if found_window: - force_foreground_window(found_window.handle) - - return { - "success": True, - "application": normalized_app, - "executable": binary, - "pid": proc.pid, - "windowTitle": window_title, - "handle": window_handle - } - - -def type_text_into_window( - text: str, - target_window_title: Optional[str] = None, - append: bool = False -) -> Dict[str, Any]: - """ - Focuses the target approved window (Notepad) and types text into its document/editor control. - """ - if not text: - text = "" - - # Security limit: prevent buffer exhaustion - max_len = 100000 - if len(text) > max_len: - raise ValueError(f"Text length exceeds maximum allowed limit of {max_len} characters.") - - d = Desktop(backend="uia") - pattern = target_window_title or r".*Notepad.*" - wins = d.windows(title_re=pattern) - - if not wins: - raise RuntimeError(f"Target window matching pattern '{pattern}' not found on desktop.") - - target_win = wins[0] - force_foreground_window(target_win.handle) - time.sleep(0.3) - - app = Application(backend="uia").connect(handle=target_win.handle) - dlg = app.window(handle=target_win.handle) - - # Attempt UIA ValuePattern (modern Windows 11 Notepad Document) - text_applied = False - try: - doc = dlg.child_window(control_type="Document") - vp = doc.wrapper_object().iface_value - if vp: - if append: - existing = vp.CurrentValue or "" - vp.SetValue(existing + text) - else: - vp.SetValue(text) - text_applied = True - except Exception: - pass - - if not text_applied: - # Fallback to type_keys or child Edit control - try: - edit = dlg.child_window(control_type="Edit") - edit.set_focus() - edit.type_keys(text, with_spaces=True, with_newlines=True) - text_applied = True - except Exception: - target_win.set_focus() - send_keys(text, with_spaces=True) - text_applied = True - - return { - "success": True, - "windowTitle": target_win.window_text(), - "charactersTyped": len(text), - "handle": target_win.handle - } - - -def press_approved_key( - key_combo: str, - target_window_title: Optional[str] = None -) -> Dict[str, Any]: - """ - Sends an approved keyboard sequence to the target desktop window. - Arbitrary keyboard sequences outside the allowlist are strictly rejected. - """ - if not key_combo or not isinstance(key_combo, str): - raise ValueError("Parameter 'keyCombo' is required and must be a string.") - - normalized_combo = key_combo.strip().upper().replace(" ", "") - if normalized_combo not in APPROVED_KEY_COMBOS: - permitted_combos = ", ".join(APPROVED_KEY_COMBOS.keys()) - raise PermissionError( - f"Security Policy Violation: Key combination '{key_combo}' is not in the approved keyboard allowlist. Permitted combinations: {permitted_combos}" - ) - - pywinauto_seq = APPROVED_KEY_COMBOS[normalized_combo] - - target_hwnd = None - if target_window_title: - d = Desktop(backend="uia") - wins = d.windows(title_re=target_window_title) - if wins: - target_hwnd = wins[0].handle - force_foreground_window(target_hwnd) - time.sleep(0.2) - - send_keys(pywinauto_seq) - - return { - "success": True, - "keyCombo": normalized_combo, - "sentSequence": pywinauto_seq, - "targetHandle": target_hwnd - } - - -def save_desktop_document( - filename: str, - content: str, - workspace_dir: Path, - overwrite: bool = True -) -> Dict[str, Any]: - """ - Saves a text document strictly inside the canonical workspace sandbox. - Verifies physical disk persistence and returns artifact metadata. - """ - target_path = safe_resolve_desktop_path(filename, workspace_dir) - - if not overwrite and target_path.exists(): - target_path = get_collision_safe_path(target_path) - - # Write file to disk and sync - with open(target_path, "w", encoding="utf-8") as f: - f.write(content) - f.flush() - os.fsync(f.fileno()) - - # Verify physical file existence and integrity - if not target_path.exists(): - raise RuntimeError(f"File verification failed: '{target_path.name}' does not exist on disk after save.") - - stats = target_path.stat() - file_size = stats.st_size - sha256 = hashlib.sha256(target_path.read_bytes()).hexdigest() - - return { - "success": True, - "filename": target_path.name, - "path": str(target_path), - "size": file_size, - "hash": sha256, - "artifacts": [ - { - "name": target_path.name, - "path": str(target_path), - "type": "file", - "size": file_size - } - ] - } - - -def verify_desktop_document( - filename: str, - workspace_dir: Path, - expected_content: Optional[str] = None, - expected_substring: Optional[str] = None -) -> Dict[str, Any]: - """ - Verifies existence, size, and content of a file within the workspace sandbox. - """ - target_path = safe_resolve_desktop_path(filename, workspace_dir) - - if not target_path.exists(): - return { - "success": False, - "exists": False, - "error": f"Document '{filename}' not found in workspace sandbox." - } - - stats = target_path.stat() - content = target_path.read_text(encoding="utf-8", errors="replace") - sha256 = hashlib.sha256(content.encode("utf-8")).hexdigest() - - matched = True - if expected_content is not None and content.strip() != expected_content.strip(): - matched = False - if expected_substring is not None and expected_substring not in content: - matched = False - - return { - "success": True, - "exists": True, - "verified": True, - "filename": target_path.name, - "path": str(target_path), - "size": stats.st_size, - "hash": sha256, - "matched": matched, - "contentSnippet": content[:200] - } - - -def execute_notepad_report_flow( - params: Dict[str, Any], - workspace_dir: Path -) -> Dict[str, Any]: - """ - Composite high-level workflow: - 1. Launch or connect to Notepad. - 2. Focus Notepad on the desktop. - 3. Type the structured AI report into Notepad. - 4. Save document cleanly to workspace_sandbox/AI_Report.txt. - 5. Verify file persistence and integrity on disk. - 6. Return full execution output and verified artifact. - """ - filename = params.get("filename") or params.get("filePath") or "AI_Report.txt" - topic = params.get("reportTopic") or params.get("topic") or "Artificial Intelligence" - close_after = params.get("closeAfter", False) - - # 1. Generate or extract report content - custom_content = params.get("content") or params.get("text") - if custom_content: - report_content = custom_content.strip() - else: - timestamp_str = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()) - report_content = ( - f"======================================================================\n" - f" FORGE AI COMPUTER CONTROL ENGINE — AUTOMATION REPORT \n" - f"======================================================================\n\n" - f"TOPIC: {topic}\n" - f"GENERATED AT: {timestamp_str}\n" - f"CANONICAL WORKSPACE: {workspace_dir}\n" - f"AUTOMATION ENGINE: pywinauto (UIA Backend) + Local FastAPI Runtime\n\n" - f"----------------------------------------------------------------------\n" - f"1. EXECUTIVE OVERVIEW\n" - f"----------------------------------------------------------------------\n" - f"Artificial Intelligence (AI) represents the computational paradigm of\n" - f"synthesizing reasoning, perception, and deterministic execution.\n" - f"Within local-first architectures, AI models function as intelligent\n" - f"orchestrators, transforming natural language requirements into safely\n" - f"governed computer operations without reliance on centralized clouds.\n\n" - f"----------------------------------------------------------------------\n" - f"2. KEY ARCHITECTURAL TENETS OF FORGE AI\n" - f"----------------------------------------------------------------------\n" - f"A. Offline-First Privacy: Local inference powered by Ollama ensures\n" - f" that user queries, telemetry, and documents never exit the machine.\n\n" - f"B. Human-in-the-Loop Authorization Gate: Every automation task requires\n" - f" explicit operator consent prior to desktop execution.\n\n" - f"C. Strict Allowlist Security: Only approved desktop applications\n" - f" (Notepad, File Explorer) and keys (CTRL+S, ENTER, etc.) are allowed.\n" - f" Arbitrary shell/terminal commands are completely blocked.\n\n" - f"D. Sandboxed Persistence & Verification: All generated artifacts are\n" - f" strictly confined to the workspace sandbox and physically verified\n" - f" against disk contents and SHA-256 checksums.\n\n" - f"----------------------------------------------------------------------\n" - f"3. EXECUTION SUMMARY\n" - f"----------------------------------------------------------------------\n" - f"This document was authored through FORGE AI Desktop Automation via\n" - f"direct UI interaction with Windows Notepad and verified on disk.\n" - f"======================================================================\n" - ) - - # 2. Launch Notepad or identify active Notepad instance - d = Desktop(backend="uia") - existing_notepad = d.windows(title_re=r".*Notepad.*") - notepad_win = None - - if existing_notepad: - notepad_win = existing_notepad[0] - force_foreground_window(notepad_win.handle) - else: - launch_res = launch_approved_application("notepad") - time.sleep(1.0) - notepad_wins = d.windows(title_re=r".*Notepad.*") - if notepad_wins: - notepad_win = notepad_wins[0] - - # 3. Type report into Notepad window - typed_info = {} - if notepad_win: - force_foreground_window(notepad_win.handle) - time.sleep(0.3) - typed_info = type_text_into_window( - text=report_content, - target_window_title=r".*Notepad.*", - append=False - ) - - # 4. Save document cleanly inside workspace sandbox - save_result = save_desktop_document( - filename=filename, - content=report_content, - workspace_dir=workspace_dir, - overwrite=True - ) - - # 5. Verify physical document existence and content - verify_result = verify_desktop_document( - filename=filename, - workspace_dir=workspace_dir, - expected_substring="FORGE AI COMPUTER CONTROL ENGINE" - ) - - # 6. Optionally close Notepad if requested - if close_after and notepad_win: - try: - notepad_win.close() - except Exception: - pass - - return { - "success": True, - "action": "notepad_report", - "topic": topic, - "filename": save_result["filename"], - "path": save_result["path"], - "size": save_result["size"], - "hash": save_result["hash"], - "notepadInteracted": bool(notepad_win), - "charactersTyped": typed_info.get("charactersTyped", len(report_content)), - "verifiedOnDisk": verify_result.get("verified", False), - "artifacts": save_result["artifacts"] - } - - -def open_document_in_app(filename: str, app_name: Optional[str], workspace_dir: Path) -> Dict[str, Any]: - """ - Safely opens a verified workspace document inside an approved desktop application. - """ - from src.tools.file_tool import safe_resolve_path - target_path = safe_resolve_path(filename, workspace_dir) - if not target_path.exists(): - raise FileNotFoundError(f"File not found in workspace sandbox: {filename}") - - ext = target_path.suffix.lower() - inferred_app = "notepad" - if ext in (".docx", ".doc"): - inferred_app = "word" - elif ext in (".xlsx", ".xls", ".csv"): - inferred_app = "excel" - elif ext in (".pptx", ".ppt"): - inferred_app = "powerpoint" - elif ext in (".pdf", ".html"): - inferred_app = "edge" - elif ext in (".txt", ".md", ".log", ".json"): - inferred_app = "notepad" - - selected_app = (app_name or inferred_app).strip().lower() - if selected_app not in APPROVED_APPLICATIONS: - raise PermissionError(f"Application '{selected_app}' is not in approved allowlist.") - - exec_path = resolve_approved_executable(selected_app) - if not exec_path: - if ext in (".txt", ".md", ".log", ".json"): - exec_path = resolve_approved_executable("notepad") - else: - raise FileNotFoundError(f"Executable for '{selected_app}' is not installed on this system.") - - proc = subprocess.Popen([exec_path, str(target_path)]) - time.sleep(1.0) - - hwnd = 0 - title = target_path.name - try: - d = Desktop(backend="uia") - pattern = APPROVED_APPLICATIONS[selected_app]["title_pattern"] - candidates = d.windows(title_re=pattern) - if candidates: - hwnd = candidates[0].handle - title = candidates[0].window_text() - force_foreground_window(hwnd) - except Exception: - pass - - return { - "success": True, - "action": "open_document_in_app", - "file": target_path.name, - "application": selected_app, - "executable": exec_path, - "pid": proc.pid, - "handle": hwnd, - "windowTitle": title - } - - -def execute_desktop_tool(params: Dict[str, Any], workspace_dir: Path) -> Dict[str, Any]: - """ - Main entry point for 'desktop_control' registered tool. - Dispatches to safe desktop actions. - """ - raw_action = params.get("action", "notepad_report") - # Normalize action name: strip "desktop." or "desktop_" prefix if present - action = raw_action.lower() - if action.startswith("desktop."): - action = action[len("desktop."):] - elif action.startswith("desktop_"): - action = action[len("desktop_"):] - - try: - if action == "list_windows": - filter_visible = params.get("filterVisible", True) - windows = list_desktop_windows(filter_visible=filter_visible) - return { - "success": True, - "action": "list_windows", - "count": len(windows), - "windows": windows - } - - elif action == "get_active_window": - active_info = get_active_desktop_window() - return { - "success": True, - "action": "get_active_window", - "window": active_info - } - - elif action == "launch_application": - app_name = params.get("appName") or params.get("application") or params.get("app") - return launch_approved_application(app_name) - - elif action == "type_text": - text = params.get("text", "") - target_title = params.get("targetWindowTitle") or params.get("targetWindow") - append = params.get("append", False) - return type_text_into_window(text, target_title, append) - - elif action == "press_key": - key_combo = params.get("keyCombo") or params.get("key") - target_title = params.get("targetWindowTitle") or params.get("targetWindow") - return press_approved_key(key_combo, target_title) - - elif action == "save_document": - filename = params.get("filename") or params.get("filePath") or "AI_Report.txt" - content = params.get("content") or params.get("text") or "" - overwrite = params.get("overwrite", True) - return save_desktop_document(filename, content, workspace_dir, overwrite) - - elif action == "verify_document": - filename = params.get("filename") or params.get("filePath") or "AI_Report.txt" - expected_content = params.get("expectedContent") - expected_substring = params.get("expectedSubstring") - return verify_desktop_document(filename, workspace_dir, expected_content, expected_substring) - - elif action == "notepad_report": - return execute_notepad_report_flow(params, workspace_dir) - - elif action == "open_document_in_app": - filename = params.get("filename") or params.get("filePath") or params.get("targetFile") - app_name = params.get("appName") or params.get("application") - return open_document_in_app(filename, app_name, workspace_dir) - - else: - return { - "success": False, - "error": f"Unknown or unpermitted desktop action: '{raw_action}'. Permitted actions: ['list_windows', 'get_active_window', 'launch_application', 'type_text', 'press_key', 'save_document', 'verify_document', 'notepad_report']" - } - - except Exception as e: - return { - "success": False, - "action": raw_action, - "error": str(e) - } +""" + +FORGE AI — Computer Control Engine Tool Module + +desktop_control: Provides local desktop automation via pywinauto UIA backend. + + + +Strict Security Boundaries: + +- Strict Application Allowlist (Notepad, File Explorer). Arbitrary executables are strictly forbidden. + +- Strict Keyboard Sequence Allowlist (CTRL+S, CTRL+A, ENTER, ESC, ALT+F4). + +- Safe sandboxed file operations confined strictly to canonical workspace_sandbox. + +- Human authorization required prior to execution. + +""" + + + +import os + +import sys +import re +import threading + +import time + +import subprocess + +import hashlib + +from pathlib import Path + +from typing import Dict, Any, List, Optional, Tuple + + + +import win32gui + +import win32process + +import winreg + +import shutil + +import win32con + +import win32api + +import ctypes + + + +try: + + from pywinauto import Desktop, Application + + from pywinauto.keyboard import send_keys + + PYWINAUTO_AVAILABLE = True + +except ImportError: + + PYWINAUTO_AVAILABLE = False + + + + + +# STRICT APPLICATION ALLOWLIST: Only explicitly approved local utilities + +APPROVED_APPLICATIONS = { + + "notepad": { + + "binary": "notepad.exe", + + "title_pattern": r".*Notepad.*", + + "doc_control_type": "Document" + + }, + + "file_explorer": { + + "binary": "explorer.exe", + + "title_pattern": r".*File Explorer.*", + + "doc_control_type": None + + }, + + "explorer": { + + "binary": "explorer.exe", + + "title_pattern": r".*File Explorer.*", + + "doc_control_type": None + + }, + + "word": { + + "binary": "WINWORD.EXE", + + "title_pattern": r".*Word.*", + + "doc_control_type": "Document" + + }, + + "winword": { + + "binary": "WINWORD.EXE", + + "title_pattern": r".*Word.*", + + "doc_control_type": "Document" + + }, + + "excel": { + + "binary": "EXCEL.EXE", + + "title_pattern": r".*Excel.*", + + "doc_control_type": None + + }, + + "powerpoint": { + + "binary": "POWERPNT.EXE", + + "title_pattern": r".*PowerPoint.*", + + "doc_control_type": None + + }, + + "ppt": { + + "binary": "POWERPNT.EXE", + + "title_pattern": r".*PowerPoint.*", + + "doc_control_type": None + + }, + + "chrome": { + + "binary": "chrome.exe", + + "title_pattern": r".*Chrome.*", + + "doc_control_type": None + + }, + + "edge": { + + "binary": "msedge.exe", + + "title_pattern": r".*Edge.*", + + "doc_control_type": None + + }, + + "vscode": { + + "binary": "Code.exe", + + "title_pattern": r".*Visual Studio Code.*", + + "doc_control_type": None + + }, + + "code": { + + "binary": "Code.exe", + + "title_pattern": r".*Visual Studio Code.*", + + "doc_control_type": None + + }, + + "calc": { + + "binary": "calc.exe", + + "title_pattern": r".*Calculator.*", + + "doc_control_type": None + + }, + + "calculator": { + + "binary": "calc.exe", + + "title_pattern": r".*Calculator.*", + + "doc_control_type": None + + } + +} + + + +def resolve_approved_executable(app_key: str) -> Optional[str]: + + """ + + Safely resolves the full path to an approved application's executable. + + Checks: + + 1. PATH via shutil.which + + 2. Windows Registry App Paths (HKLM and HKCU) + + 3. Common fixed 64-bit and 32-bit Program Files directories + + Never accepts arbitrary user-supplied paths. + + """ + + if app_key not in APPROVED_APPLICATIONS: + + return None + + + + binary = APPROVED_APPLICATIONS[app_key]["binary"] + + + + # 1. Check system PATH + + found = shutil.which(binary) + + if found and os.path.isfile(found): + + return found + + + + # 2. Check Registry App Paths + + for root in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER): + + try: + + key_path = f"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\{binary}" + + with winreg.OpenKey(root, key_path) as k: + + val, _ = winreg.QueryValueEx(k, "") + + if val and os.path.isfile(val): + + return val + + except Exception: + + pass + + + + # 3. Known standard install paths for allowlisted apps + + common_roots = [ + + os.environ.get("ProgramFiles", "C:\\Program Files"), + + os.environ.get("ProgramFiles(x86)", "C:\\Program Files (x86)"), + + os.environ.get("LocalAppData", "C:\\Users\\Default\\AppData\\Local") + + ] + + app_relative_hints = { + + "word": ["Microsoft Office\\root\\Office16\\WINWORD.EXE", "Microsoft Office\\Office16\\WINWORD.EXE"], + + "winword": ["Microsoft Office\\root\\Office16\\WINWORD.EXE", "Microsoft Office\\Office16\\WINWORD.EXE"], + + "excel": ["Microsoft Office\\root\\Office16\\EXCEL.EXE", "Microsoft Office\\Office16\\EXCEL.EXE"], + + "powerpoint": ["Microsoft Office\\root\\Office16\\POWERPNT.EXE", "Microsoft Office\\Office16\\POWERPNT.EXE"], + + "ppt": ["Microsoft Office\\root\\Office16\\POWERPNT.EXE", "Microsoft Office\\Office16\\POWERPNT.EXE"], + + "chrome": ["Google\\Chrome\\Application\\chrome.exe"], + + "edge": ["Microsoft\\Edge\\Application\\msedge.exe"], + + "vscode": ["Programs\\Microsoft VS Code\\Code.exe", "Microsoft VS Code\\Code.exe"], + + "code": ["Programs\\Microsoft VS Code\\Code.exe", "Microsoft VS Code\\Code.exe"] + + } + + + + hints = app_relative_hints.get(app_key, []) + + for c_root in common_roots: + + for hint in hints: + + cand = os.path.join(c_root, hint) + + if os.path.isfile(cand): + + return cand + + + + return None + + + +# STRICT KEYBOARD SEQUENCE ALLOWLIST: Only approved operational keystrokes + +APPROVED_KEY_COMBOS = { + + "CTRL+S": "^s", + + "CTRL+A": "^a", + + "ENTER": "{ENTER}", + + "ESC": "{ESC}", + + "ALT+F4": "%{F4}" + +} + + + +ALLOWED_DESKTOP_EXTENSIONS = {".txt", ".md", ".log", ".docx", ".pdf", ".pptx", ".csv", ".json", ".xlsx"} + + + + + +def safe_resolve_desktop_path(filename: str, workspace_dir: Path) -> Path: + + """ + + Validates and safely resolves a file path strictly inside the canonical workspace sandbox. + + Rejects directory traversal, backslashes/slashes, and unapproved extensions. + + """ + + if not filename or not isinstance(filename, str): + + raise ValueError("Filename must be a non-empty string.") + + + + # Prevent directory traversal attacks + + if "/" in filename or "\\" in filename or ".." in filename: + + raise PermissionError(f"Security Policy Violation: File path traversal or directory separators are forbidden: '{filename}'") + + + + # Allowed extensions + + suffix = Path(filename).suffix.lower() + + if suffix not in ALLOWED_DESKTOP_EXTENSIONS: + + raise PermissionError( + + f"Access Denied: Unsupported file extension '{suffix}'. Permitted desktop extensions: {', '.join(sorted(ALLOWED_DESKTOP_EXTENSIONS))}" + + ) + + + + resolved_workspace = workspace_dir.resolve() + + target_path = (resolved_workspace / filename).resolve() + + + + try: + + target_path.relative_to(resolved_workspace) + + except ValueError: + + raise PermissionError(f"Access Denied: Path '{filename}' attempts to escape workspace sandbox.") + + + + return target_path + + + + + +def get_collision_safe_path(target_path: Path) -> Path: + + """Returns a non-colliding file path by appending _1, _2 if file exists.""" + + if not target_path.exists(): + + return target_path + + + + parent = target_path.parent + + stem = target_path.stem + + suffix = target_path.suffix + + counter = 1 + + + + while True: + + new_path = parent / f"{stem}_{counter}{suffix}" + + if not new_path.exists(): + + return new_path + + counter += 1 + + + + + + +def run_on_default_desktop(fn, *args, **kwargs): + res_container = {"return": None, "exception": None} + def worker(): + try: + user32 = ctypes.windll.user32 + h_default = user32.OpenDesktopW("Default", 0, False, 0x10000000 | 0x01FF) + if h_default: + user32.SetThreadDesktop(h_default) + res_container["return"] = fn(*args, **kwargs) + except Exception as e: + res_container["exception"] = e + t = threading.Thread(target=worker) + t.start() + t.join(timeout=30) + if res_container["exception"]: + raise res_container["exception"] + return res_container["return"] + + +def ensure_default_desktop(): + """Ensures the current thread is attached to the active user's WinSta0\\Default desktop.""" + try: + user32 = ctypes.windll.user32 + h_default = user32.OpenDesktopW("Default", 0, False, 0x10000000 | 0x01FF) + if h_default: + user32.SetThreadDesktop(h_default) + except Exception: + pass + + +def force_foreground_window(hwnd: int): + + """ + + Reliably brings a window handle to the foreground on Windows. + + Bypasses foreground lock restriction safely. + + """ + + if not hwnd or not win32gui.IsWindow(hwnd): + return + + ensure_default_desktop() + + + + try: + + if win32gui.IsIconic(hwnd): + + win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) + + else: + + win32gui.ShowWindow(hwnd, win32con.SW_SHOW) + + + + current_thread_id = ctypes.windll.kernel32.GetCurrentThreadId() + + target_thread_id, _ = win32process.GetWindowThreadProcessId(hwnd) + + + + ctypes.windll.user32.AllowSetForegroundWindow(-1) + + ctypes.windll.user32.AttachThreadInput(current_thread_id, target_thread_id, True) + + ctypes.windll.user32.SetForegroundWindow(hwnd) + + ctypes.windll.user32.SetFocus(hwnd) + + ctypes.windll.user32.AttachThreadInput(current_thread_id, target_thread_id, False) + + except Exception: + + pass + + + + + +def list_desktop_windows(filter_visible: bool = True) -> List[Dict[str, Any]]: + + """ + + Enumerates active desktop top-level windows via pywinauto UIA backend. + + """ + + if not PYWINAUTO_AVAILABLE: + + raise RuntimeError("pywinauto is not available in the current Python environment.") + + + + d = Desktop(backend="uia") + + wins = d.windows() + + active_hwnd = win32gui.GetForegroundWindow() + + + + window_list = [] + + for w in wins: + + try: + + title = w.window_text().strip() + + visible = w.is_visible() + + if filter_visible and (not visible or not title): + + continue + + + + hwnd = w.handle + + pid = w.process_id() + + class_name = w.class_name() + + + + # Identify known process name from class or allowlist + + process_name = "unknown" + + if "notepad" in class_name.lower() or "notepad" in title.lower(): + + process_name = "notepad.exe" + + elif "cabinetwclass" in class_name.lower() or "explorer" in class_name.lower(): + + process_name = "explorer.exe" + + + + window_list.append({ + + "handle": hwnd, + + "title": title, + + "pid": pid, + + "class_name": class_name, + + "process_name": process_name, + + "visible": visible, + + "is_active": hwnd == active_hwnd + + }) + + except Exception: + + continue + + + + return window_list + + + + + +def get_active_desktop_window() -> Dict[str, Any]: + + """ + + Returns metadata for the current active foreground window. + + """ + + hwnd = win32gui.GetForegroundWindow() + + title = win32gui.GetWindowText(hwnd).strip() if hwnd else "" + + pid = 0 + + if hwnd: + + _, pid = win32process.GetWindowThreadProcessId(hwnd) + + + + rect = {} + + if hwnd: + + try: + + r = win32gui.GetWindowRect(hwnd) + + rect = {"left": r[0], "top": r[1], "right": r[2], "bottom": r[3], "width": r[2] - r[0], "height": r[3] - r[1]} + + except Exception: + + pass + + + + return { + + "handle": hwnd, + + "title": title or "Desktop", + + "pid": pid, + + "rect": rect, + + "is_active": True + + } + + + + + +def launch_approved_application(app_name: str, target_param: Optional[str] = None) -> Dict[str, Any]: + """ + Launches an approved application from the strict allowlist. + Uses Windows ShellExecute for reliable interactive desktop session activation, + with strict window-handle and visibility verification. + """ + if not app_name or not isinstance(app_name, str): + raise ValueError("Parameter 'appName' is required and must be a string.") + + ensure_default_desktop() + + normalized_app = app_name.strip().lower().replace(" ", "_") + if normalized_app not in APPROVED_APPLICATIONS: + approved_names = sorted(list(set(APPROVED_APPLICATIONS.keys()))) + raise PermissionError( + f"Access Denied: Application '{app_name}' is not in the approved desktop allowlist. Permitted applications: {approved_names}" + ) + + app_spec = APPROVED_APPLICATIONS[normalized_app] + binary = app_spec["binary"] + title_pattern = app_spec["title_pattern"] + + exec_path = resolve_approved_executable(normalized_app) or binary + + # Shell arguments + args = "" + if normalized_app in ("explorer", "file_explorer"): + target_dir = target_param or os.environ.get("FORGE_WORKSPACE", "") + if not target_dir or not os.path.isdir(target_dir): + target_dir = "C:\\Users\\HP\\Desktop\\CODE\\Forge\\workspace_sandbox" + args = f'"{target_dir}"' + + # Launch via ShellExecute to guarantee display on interactive desktop + try: + win32api.ShellExecute(0, "open", exec_path, args, None, win32con.SW_SHOWNORMAL) + except Exception: + si = subprocess.STARTUPINFO() + si.lpDesktop = "WinSta0\\Default" + cmd = [exec_path] + if args: + cmd.append(args.strip('"')) + subprocess.Popen(cmd, startupinfo=si) + + # Window detection with timeout (up to 5 seconds) + found_hwnd = 0 + found_title = "" + found_class = "" + found_pid = 0 + + deadline = time.time() + 5.0 + while time.time() < deadline: + time.sleep(0.4) + + # 1. Search via EnumWindows + def _enum_cb(hwnd, extra): + nonlocal found_hwnd, found_title, found_class, found_pid + if found_hwnd: + return + if win32gui.IsWindowVisible(hwnd): + t = win32gui.GetWindowText(hwnd).strip() + c = win32gui.GetClassName(hwnd).strip() + _, p = win32process.GetWindowThreadProcessId(hwnd) + + matched = False + if normalized_app == "notepad" and ("notepad" in c.lower() or "notepad" in t.lower()): + matched = True + elif normalized_app in ("explorer", "file_explorer") and ("cabinetwclass" in c.lower() or "explorer" in t.lower() or "workspace_sandbox" in t.lower()): + matched = True + elif normalized_app in ("calc", "calculator") and ("calc" in c.lower() or "calc" in t.lower() or (c == "ApplicationFrameWindow" and "calculator" in t.lower())): + matched = True + elif re.search(title_pattern, t, re.IGNORECASE): + matched = True + + if matched: + found_hwnd = hwnd + found_title = t + found_class = c + found_pid = p + + win32gui.EnumWindows(_enum_cb, None) + if found_hwnd: + break + + # 2. Search via pywinauto UIA fallback + if PYWINAUTO_AVAILABLE: + try: + d = Desktop(backend="uia") + candidates = d.windows(title_re=title_pattern) + if candidates: + found_hwnd = candidates[0].handle + found_title = candidates[0].window_text() + found_class = candidates[0].class_name() + found_pid = candidates[0].process_id() + break + except Exception: + pass + + if not found_hwnd: + return { + "success": False, + "error": f"Application '{app_name}' was launched, but its main window was not detected on the active desktop within the 5-second timeout.", + "application": normalized_app, + "executable": exec_path + } + + force_foreground_window(found_hwnd) + + return { + "success": True, + "application": normalized_app, + "executable": exec_path, + "pid": found_pid, + "windowTitle": found_title or f"{app_name}", + "handle": found_hwnd, + "className": found_class + } + + +def type_text_into_window( + + text: str, + + target_window_title: Optional[str] = None, + + append: bool = False + +) -> Dict[str, Any]: + + """ + + Focuses the target approved window (Notepad) and types text into its document/editor control. + + """ + + if not text: + + text = "" + + + + # Security limit: prevent buffer exhaustion + + max_len = 100000 + + if len(text) > max_len: + + raise ValueError(f"Text length exceeds maximum allowed limit of {max_len} characters.") + + + + d = Desktop(backend="uia") + + pattern = target_window_title or r".*Notepad.*" + + wins = d.windows(title_re=pattern) + + + + if not wins: + + raise RuntimeError(f"Target window matching pattern '{pattern}' not found on desktop.") + + + + target_win = wins[0] + + force_foreground_window(target_win.handle) + + time.sleep(0.3) + + + + app = Application(backend="uia").connect(handle=target_win.handle) + + dlg = app.window(handle=target_win.handle) + + + + # Attempt UIA ValuePattern (modern Windows 11 Notepad Document) + + text_applied = False + + try: + + doc = dlg.child_window(control_type="Document") + + vp = doc.wrapper_object().iface_value + + if vp: + + if append: + + existing = vp.CurrentValue or "" + + vp.SetValue(existing + text) + + else: + + vp.SetValue(text) + + text_applied = True + + except Exception: + + pass + + + + if not text_applied: + + # Fallback to type_keys or child Edit control + + try: + + edit = dlg.child_window(control_type="Edit") + + edit.set_focus() + + edit.type_keys(text, with_spaces=True, with_newlines=True) + + text_applied = True + + except Exception: + + target_win.set_focus() + + send_keys(text, with_spaces=True) + + text_applied = True + + + + return { + + "success": True, + + "windowTitle": target_win.window_text(), + + "charactersTyped": len(text), + + "handle": target_win.handle + + } + + + + + +def press_approved_key( + + key_combo: str, + + target_window_title: Optional[str] = None + +) -> Dict[str, Any]: + + """ + + Sends an approved keyboard sequence to the target desktop window. + + Arbitrary keyboard sequences outside the allowlist are strictly rejected. + + """ + + if not key_combo or not isinstance(key_combo, str): + + raise ValueError("Parameter 'keyCombo' is required and must be a string.") + + + + normalized_combo = key_combo.strip().upper().replace(" ", "") + + if normalized_combo not in APPROVED_KEY_COMBOS: + + permitted_combos = ", ".join(APPROVED_KEY_COMBOS.keys()) + + raise PermissionError( + + f"Security Policy Violation: Key combination '{key_combo}' is not in the approved keyboard allowlist. Permitted combinations: {permitted_combos}" + + ) + + + + pywinauto_seq = APPROVED_KEY_COMBOS[normalized_combo] + + + + target_hwnd = None + + if target_window_title: + + d = Desktop(backend="uia") + + wins = d.windows(title_re=target_window_title) + + if wins: + + target_hwnd = wins[0].handle + + force_foreground_window(target_hwnd) + + time.sleep(0.2) + + + + send_keys(pywinauto_seq) + + + + return { + + "success": True, + + "keyCombo": normalized_combo, + + "sentSequence": pywinauto_seq, + + "targetHandle": target_hwnd + + } + + + + + +def save_desktop_document( + + filename: str, + + content: str, + + workspace_dir: Path, + + overwrite: bool = True + +) -> Dict[str, Any]: + + """ + + Saves a text document strictly inside the canonical workspace sandbox. + + Verifies physical disk persistence and returns artifact metadata. + + """ + + target_path = safe_resolve_desktop_path(filename, workspace_dir) + + + + if not overwrite and target_path.exists(): + + target_path = get_collision_safe_path(target_path) + + + + # Write file to disk and sync + + with open(target_path, "w", encoding="utf-8") as f: + + f.write(content) + + f.flush() + + os.fsync(f.fileno()) + + + + # Verify physical file existence and integrity + + if not target_path.exists(): + + raise RuntimeError(f"File verification failed: '{target_path.name}' does not exist on disk after save.") + + + + stats = target_path.stat() + + file_size = stats.st_size + + sha256 = hashlib.sha256(target_path.read_bytes()).hexdigest() + + + + return { + + "success": True, + + "filename": target_path.name, + + "path": str(target_path), + + "size": file_size, + + "hash": sha256, + + "artifacts": [ + + { + + "name": target_path.name, + + "path": str(target_path), + + "type": "file", + + "size": file_size + + } + + ] + + } + + + + + +def verify_desktop_document( + + filename: str, + + workspace_dir: Path, + + expected_content: Optional[str] = None, + + expected_substring: Optional[str] = None + +) -> Dict[str, Any]: + + """ + + Verifies existence, size, and content of a file within the workspace sandbox. + + """ + + target_path = safe_resolve_desktop_path(filename, workspace_dir) + + + + if not target_path.exists(): + + return { + + "success": False, + + "exists": False, + + "error": f"Document '{filename}' not found in workspace sandbox." + + } + + + + stats = target_path.stat() + + content = target_path.read_text(encoding="utf-8", errors="replace") + + sha256 = hashlib.sha256(content.encode("utf-8")).hexdigest() + + + + matched = True + + if expected_content is not None and content.strip() != expected_content.strip(): + + matched = False + + if expected_substring is not None and expected_substring not in content: + + matched = False + + + + return { + + "success": True, + + "exists": True, + + "verified": True, + + "filename": target_path.name, + + "path": str(target_path), + + "size": stats.st_size, + + "hash": sha256, + + "matched": matched, + + "contentSnippet": content[:200] + + } + + + + + +def execute_notepad_report_flow( + + params: Dict[str, Any], + + workspace_dir: Path + +) -> Dict[str, Any]: + + """ + + Composite high-level workflow: + + 1. Launch or connect to Notepad. + + 2. Focus Notepad on the desktop. + + 3. Type the structured AI report into Notepad. + + 4. Save document cleanly to workspace_sandbox/AI_Report.txt. + + 5. Verify file persistence and integrity on disk. + + 6. Return full execution output and verified artifact. + + """ + + filename = params.get("filename") or params.get("filePath") or "AI_Report.txt" + + topic = params.get("reportTopic") or params.get("topic") or "Artificial Intelligence" + + close_after = params.get("closeAfter", False) + + + + # 1. Generate or extract report content + + custom_content = params.get("content") or params.get("text") + + if custom_content: + + report_content = custom_content.strip() + + else: + + timestamp_str = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()) + + report_content = ( + + f"======================================================================\n" + + f" FORGE AI COMPUTER CONTROL ENGINE — AUTOMATION REPORT \n" + + f"======================================================================\n\n" + + f"TOPIC: {topic}\n" + + f"GENERATED AT: {timestamp_str}\n" + + f"CANONICAL WORKSPACE: {workspace_dir}\n" + + f"AUTOMATION ENGINE: pywinauto (UIA Backend) + Local FastAPI Runtime\n\n" + + f"----------------------------------------------------------------------\n" + + f"1. EXECUTIVE OVERVIEW\n" + + f"----------------------------------------------------------------------\n" + + f"Artificial Intelligence (AI) represents the computational paradigm of\n" + + f"synthesizing reasoning, perception, and deterministic execution.\n" + + f"Within local-first architectures, AI models function as intelligent\n" + + f"orchestrators, transforming natural language requirements into safely\n" + + f"governed computer operations without reliance on centralized clouds.\n\n" + + f"----------------------------------------------------------------------\n" + + f"2. KEY ARCHITECTURAL TENETS OF FORGE AI\n" + + f"----------------------------------------------------------------------\n" + + f"A. Offline-First Privacy: Local inference powered by Ollama ensures\n" + + f" that user queries, telemetry, and documents never exit the machine.\n\n" + + f"B. Human-in-the-Loop Authorization Gate: Every automation task requires\n" + + f" explicit operator consent prior to desktop execution.\n\n" + + f"C. Strict Allowlist Security: Only approved desktop applications\n" + + f" (Notepad, File Explorer) and keys (CTRL+S, ENTER, etc.) are allowed.\n" + + f" Arbitrary shell/terminal commands are completely blocked.\n\n" + + f"D. Sandboxed Persistence & Verification: All generated artifacts are\n" + + f" strictly confined to the workspace sandbox and physically verified\n" + + f" against disk contents and SHA-256 checksums.\n\n" + + f"----------------------------------------------------------------------\n" + + f"3. EXECUTION SUMMARY\n" + + f"----------------------------------------------------------------------\n" + + f"This document was authored through FORGE AI Desktop Automation via\n" + + f"direct UI interaction with Windows Notepad and verified on disk.\n" + + f"======================================================================\n" + + ) + + + + # 2. Launch Notepad or identify active Notepad instance + + d = Desktop(backend="uia") + + existing_notepad = d.windows(title_re=r".*Notepad.*") + + notepad_win = None + + + + if existing_notepad: + + notepad_win = existing_notepad[0] + + force_foreground_window(notepad_win.handle) + + else: + + launch_res = launch_approved_application("notepad") + + time.sleep(1.0) + + notepad_wins = d.windows(title_re=r".*Notepad.*") + + if notepad_wins: + + notepad_win = notepad_wins[0] + + + + # 3. Type report into Notepad window + + typed_info = {} + + if notepad_win: + + force_foreground_window(notepad_win.handle) + + time.sleep(0.3) + + typed_info = type_text_into_window( + + text=report_content, + + target_window_title=r".*Notepad.*", + + append=False + + ) + + + + # 4. Save document cleanly inside workspace sandbox + + save_result = save_desktop_document( + + filename=filename, + + content=report_content, + + workspace_dir=workspace_dir, + + overwrite=True + + ) + + + + # 5. Verify physical document existence and content + + verify_result = verify_desktop_document( + + filename=filename, + + workspace_dir=workspace_dir, + + expected_substring="FORGE AI COMPUTER CONTROL ENGINE" + + ) + + + + # 6. Optionally close Notepad if requested + + if close_after and notepad_win: + + try: + + notepad_win.close() + + except Exception: + + pass + + + + return { + + "success": True, + + "action": "notepad_report", + + "topic": topic, + + "filename": save_result["filename"], + + "path": save_result["path"], + + "size": save_result["size"], + + "hash": save_result["hash"], + + "notepadInteracted": bool(notepad_win), + + "charactersTyped": typed_info.get("charactersTyped", len(report_content)), + + "verifiedOnDisk": verify_result.get("verified", False), + + "artifacts": save_result["artifacts"] + + } + + + + + +def _calculate_worker(expression: str) -> Dict[str, Any]: + """ + Performs arithmetic calculations in Windows Calculator using UIAutomation, + and returns the verified result. + """ + ensure_default_desktop() + from comtypes import client + UIAutomationCore = client.GetModule("UIAutomationCore.dll") + uia = client.CreateObject(UIAutomationCore.CUIAutomation, interface=UIAutomationCore.IUIAutomation) + + root = uia.GetRootElement() + cond = uia.CreatePropertyCondition(UIAutomationCore.UIA_NamePropertyId, "Calculator") + calc_window = root.FindFirst(UIAutomationCore.TreeScope_Children, cond) + + if not calc_window: + win32api.ShellExecute(0, "open", "calc.exe", "", None, win32con.SW_SHOWNORMAL) + deadline = time.time() + 5.0 + while time.time() < deadline: + time.sleep(0.5) + root = uia.GetRootElement() + calc_window = root.FindFirst(UIAutomationCore.TreeScope_Children, cond) + if not calc_window: + cond_class = uia.CreatePropertyCondition(UIAutomationCore.UIA_ClassNamePropertyId, "ApplicationFrameWindow") + candidates = root.FindAll(UIAutomationCore.TreeScope_Children, cond_class) + for k in range(candidates.Length): + cand = candidates.GetElement(k) + if "calc" in cand.CurrentName.lower(): + calc_window = cand + break + if calc_window: + break + + if not calc_window: + return {"success": False, "error": "Calculator window could not be detected on active desktop."} + + hwnd = calc_window.CurrentNativeWindowHandle + force_foreground_window(hwnd) + time.sleep(0.3) + + def click_btn(auto_id: str) -> bool: + c = uia.CreatePropertyCondition(UIAutomationCore.UIA_AutomationIdPropertyId, auto_id) + btn = calc_window.FindFirst(UIAutomationCore.TreeScope_Descendants, c) + if btn: + try: + invoke_pattern = btn.GetCurrentPattern(UIAutomationCore.UIA_InvokePatternId) + if invoke_pattern: + invoke = invoke_pattern.QueryInterface(UIAutomationCore.IUIAutomationInvokePattern) + invoke.Invoke() + time.sleep(0.05) + return True + except Exception: + pass + return False + + click_btn("clearButton") + time.sleep(0.1) + + expr_clean = expression.lower() + expr_clean = expr_clean.replace("multiplied by", "*").replace("times", "*").replace("x", "*") + expr_clean = expr_clean.replace("divided by", "/").replace("over", "/") + expr_clean = expr_clean.replace("plus", "+").replace("add", "+") + expr_clean = expr_clean.replace("minus", "-").replace("subtract", "-") + + tokens = re.findall(r"(\d+(?:\.\d+)?|[\+\-\*\/])", expr_clean) + if not tokens: + return {"success": False, "error": f"Could not parse arithmetic expression from '{expression}'"} + + operator_map = { + "+": "plusButton", + "-": "minusButton", + "*": "multiplyButton", + "/": "divideButton" + } + + for token in tokens: + if token in operator_map: + click_btn(operator_map[token]) + else: + for ch in token: + if ch.isdigit(): + click_btn(f"num{ch}Button") + elif ch == ".": + click_btn("decimalSeparatorButton") + + click_btn("equalButton") + time.sleep(0.3) + + c_res = uia.CreatePropertyCondition(UIAutomationCore.UIA_AutomationIdPropertyId, "CalculatorResults") + res_el = calc_window.FindFirst(UIAutomationCore.TreeScope_Descendants, c_res) + result_text = res_el.CurrentName if res_el else "" + + num_match = re.search(r"Display is ([\d,]+(?:\.\d+)?)", result_text, re.IGNORECASE) + raw_num_str = num_match.group(1) if num_match else result_text + clean_num_str = raw_num_str.replace(",", "") + try: + numeric_result = float(clean_num_str) if "." in clean_num_str else int(clean_num_str) + except Exception: + numeric_result = None + + return { + "success": True, + "action": "calculate", + "expression": expression, + "calculation": " ".join(tokens), + "rawDisplay": result_text, + "result": raw_num_str, + "numericResult": numeric_result, + "handle": hwnd + } + + + +def calculate_expression(expression: str) -> Dict[str, Any]: + return run_on_default_desktop(_calculate_worker, expression) + + +def open_document_in_app(filename: str, app_name: Optional[str], workspace_dir: Path) -> Dict[str, Any]: + """ + Safely opens a verified workspace document inside an approved desktop application. + """ + ensure_default_desktop() + from src.tools.file_tool import safe_resolve_path + + if not filename: + raise ValueError("Filename parameter is required.") + + target_path = safe_resolve_path(filename, workspace_dir) + if not target_path.exists(): + return { + "success": False, + "error": f"Execution failed: File not found in workspace sandbox: {filename}. Please create or save the document first." + } + + ext = target_path.suffix.lower() + inferred_app = "notepad" + if ext in (".docx", ".doc"): + inferred_app = "word" + elif ext in (".xlsx", ".xls", ".csv"): + inferred_app = "excel" + elif ext in (".pptx", ".ppt"): + inferred_app = "powerpoint" + elif ext in (".pdf", ".html"): + inferred_app = "edge" + elif ext in (".txt", ".md", ".log", ".json"): + inferred_app = "notepad" + + selected_app = (app_name or inferred_app).strip().lower() + if selected_app not in APPROVED_APPLICATIONS: + raise PermissionError(f"Application '{selected_app}' is not in approved allowlist.") + + exec_path = resolve_approved_executable(selected_app) + + # Launch via ShellExecute with full path + try: + win32api.ShellExecute(0, "open", str(target_path.resolve()), "", None, win32con.SW_SHOWNORMAL) + except Exception: + if exec_path: + win32api.ShellExecute(0, "open", exec_path, f'"{target_path.resolve()}"', None, win32con.SW_SHOWNORMAL) + + time.sleep(1.5) + + # Detect opened document window + hwnd = 0 + title = target_path.name + deadline = time.time() + 4.0 + while time.time() < deadline: + time.sleep(0.3) + def _cb(h, _): + nonlocal hwnd, title + if hwnd: return + if win32gui.IsWindowVisible(h): + t = win32gui.GetWindowText(h) + if target_path.name.lower() in t.lower() or target_path.stem.lower() in t.lower(): + hwnd = h + title = t + win32gui.EnumWindows(_cb, None) + if hwnd: + break + + if hwnd: + force_foreground_window(hwnd) + + return { + "success": True, + "action": "open_document_in_app", + "file": target_path.name, + "path": str(target_path), + "application": selected_app, + "handle": hwnd, + "windowTitle": title + } + + +def execute_desktop_tool(params: Dict[str, Any], workspace_dir: Path) -> Dict[str, Any]: + + """ + + Main entry point for 'desktop_control' registered tool. + + Dispatches to safe desktop actions. + + """ + + raw_action = params.get("action", "notepad_report") + + # Normalize action name: strip "desktop." or "desktop_" prefix if present + + action = raw_action.lower() + + if action.startswith("desktop."): + + action = action[len("desktop."):] + + elif action.startswith("desktop_"): + + action = action[len("desktop_"):] + + + + try: + + if action == "list_windows": + + filter_visible = params.get("filterVisible", True) + + windows = list_desktop_windows(filter_visible=filter_visible) + + return { + + "success": True, + + "action": "list_windows", + + "count": len(windows), + + "windows": windows + + } + + + + elif action == "get_active_window": + + active_info = get_active_desktop_window() + + return { + + "success": True, + + "action": "get_active_window", + + "window": active_info + + } + + + + elif action == "launch_application": + app_name = params.get("appName") or params.get("application") or params.get("app") + target_param = params.get("targetDirectory") or params.get("targetPath") + return launch_approved_application(app_name, target_param) + + elif action in ("calculate", "calculator_operation"): + expression = params.get("expression") or params.get("calculation") or params.get("calc") or "125 * 48" + return calculate_expression(expression) + + + + elif action == "type_text": + + text = params.get("text", "") + + target_title = params.get("targetWindowTitle") or params.get("targetWindow") + + append = params.get("append", False) + + return type_text_into_window(text, target_title, append) + + + + elif action == "press_key": + + key_combo = params.get("keyCombo") or params.get("key") + + target_title = params.get("targetWindowTitle") or params.get("targetWindow") + + return press_approved_key(key_combo, target_title) + + + + elif action == "save_document": + + filename = params.get("filename") or params.get("filePath") or "AI_Report.txt" + + content = params.get("content") or params.get("text") or "" + + overwrite = params.get("overwrite", True) + + return save_desktop_document(filename, content, workspace_dir, overwrite) + + + + elif action == "verify_document": + + filename = params.get("filename") or params.get("filePath") or "AI_Report.txt" + + expected_content = params.get("expectedContent") + + expected_substring = params.get("expectedSubstring") + + return verify_desktop_document(filename, workspace_dir, expected_content, expected_substring) + + + + elif action == "notepad_report": + + return execute_notepad_report_flow(params, workspace_dir) + + + + elif action == "open_document_in_app": + + filename = params.get("filename") or params.get("filePath") or params.get("targetFile") + + app_name = params.get("appName") or params.get("application") + + return open_document_in_app(filename, app_name, workspace_dir) + + + + else: + + return { + + "success": False, + + "error": f"Unknown or unpermitted desktop action: '{raw_action}'. Permitted actions: ['list_windows', 'get_active_window', 'launch_application', 'type_text', 'press_key', 'save_document', 'verify_document', 'notepad_report']" + + } + + + + except Exception as e: + + return { + + "success": False, + + "action": raw_action, + + "error": str(e) + + } + diff --git a/automation/src/tools/file_tool.py b/automation/src/tools/file_tool.py index d28cecf..b5e0d24 100644 --- a/automation/src/tools/file_tool.py +++ b/automation/src/tools/file_tool.py @@ -1,7 +1,10 @@ import os import shutil +import json +import csv +import fnmatch from pathlib import Path -from typing import Dict, Any, List +from typing import Dict, Any, List, Optional def safe_resolve_path(rel_path: str, workspace_dir: Path) -> Path: """ @@ -52,19 +55,28 @@ def execute_file_tool(params: Dict[str, Any], workspace_dir: Path) -> Dict[str, Supported actions: - list_directory - read_file - - write_file + - write_file / create_file - copy_file - - move_file + - move_file / rename_file + - create_directory / create_folder + - delete_file + - search_files / find_files + - get_file_info + - edit_file / append_file - organize_by_extension """ - action = params.get("action", "list_directory") + raw_action = params.get("action", "list_directory") + action = raw_action.lower() + if action.startswith("file_system."): + action = action[len("file_system."):] + elif action.startswith("fs."): + action = action[len("fs."):] try: if action == "list_directory": - rel_dir = params.get("targetDirectory", ".") + rel_dir = params.get("targetDirectory") or params.get("directory") or "." target_dir = safe_resolve_path(rel_dir, workspace_dir) - # Strictly do not create directory during read-only listing if not target_dir.exists(): return {"success": False, "error": f"Directory does not exist: {rel_dir}"} if not target_dir.is_dir(): @@ -88,8 +100,25 @@ def execute_file_tool(params: Dict[str, Any], workspace_dir: Path) -> Dict[str, "items": items } + elif action in ("create_directory", "create_folder"): + rel_dir = params.get("targetDirectory") or params.get("directory") or params.get("folderName") or params.get("name") or params.get("path") + if not rel_dir: + return {"success": False, "error": "Missing required parameter 'targetDirectory' or 'folderName'"} + + target_dir = safe_resolve_path(rel_dir, workspace_dir) + target_dir.mkdir(parents=True, exist_ok=True) + rel_str = str(target_dir.relative_to(workspace_dir.resolve())) + + return { + "success": True, + "action": action, + "folder": target_dir.name, + "relativePath": rel_str, + "path": str(target_dir) + } + elif action in ("write_file", "create_file"): - rel_file = params.get("targetFile") or params.get("filePath") + rel_file = params.get("targetFile") or params.get("filePath") or params.get("file") if not rel_file: return {"success": False, "error": "Missing required parameter 'targetFile' or 'filePath'"} @@ -97,7 +126,6 @@ def execute_file_tool(params: Dict[str, Any], workspace_dir: Path) -> Dict[str, overwrite = bool(params.get("overwrite", False)) if target_file.exists() and not overwrite: - # Handle filename collision safely without silent overwriting target_file = get_collision_safe_path(target_file) target_file.parent.mkdir(parents=True, exist_ok=True) @@ -123,7 +151,7 @@ def execute_file_tool(params: Dict[str, Any], workspace_dir: Path) -> Dict[str, } elif action == "read_file": - rel_file = params.get("targetFile") or params.get("filePath") + rel_file = params.get("targetFile") or params.get("filePath") or params.get("file") if not rel_file: return {"success": False, "error": "Missing required parameter 'targetFile'"} @@ -147,8 +175,8 @@ def execute_file_tool(params: Dict[str, Any], workspace_dir: Path) -> Dict[str, } elif action == "copy_file": - src_rel = params.get("sourceFile") - dst_rel = params.get("destinationFile") + src_rel = params.get("sourceFile") or params.get("source") or params.get("src") + dst_rel = params.get("destinationFile") or params.get("destination") or params.get("dst") if not src_rel or not dst_rel: return {"success": False, "error": "Missing 'sourceFile' or 'destinationFile'"} @@ -157,6 +185,10 @@ def execute_file_tool(params: Dict[str, Any], workspace_dir: Path) -> Dict[str, return {"success": False, "error": f"Source file does not exist: {src_rel}"} dst = safe_resolve_path(dst_rel, workspace_dir) + # If destination is an existing directory, copy into it + if dst.exists() and dst.is_dir(): + dst = dst / src.name + if dst.exists() and not params.get("overwrite", False): dst = get_collision_safe_path(dst) @@ -172,16 +204,19 @@ def execute_file_tool(params: Dict[str, Any], workspace_dir: Path) -> Dict[str, } elif action in ("move_file", "rename_file"): - src_rel = params.get("sourceFile") - dst_rel = params.get("destinationFile") + src_rel = params.get("sourceFile") or params.get("source") or params.get("src") + dst_rel = params.get("destinationFile") or params.get("destination") or params.get("dst") or params.get("newName") if not src_rel or not dst_rel: return {"success": False, "error": "Missing 'sourceFile' or 'destinationFile'"} src = safe_resolve_path(src_rel, workspace_dir) - if not src.exists() or not src.is_file(): + if not src.exists(): return {"success": False, "error": f"Source file does not exist: {src_rel}"} dst = safe_resolve_path(dst_rel, workspace_dir) + if dst.exists() and dst.is_dir(): + dst = dst / src.name + if dst.exists() and not params.get("overwrite", False): dst = get_collision_safe_path(dst) @@ -195,6 +230,221 @@ def execute_file_tool(params: Dict[str, Any], workspace_dir: Path) -> Dict[str, "destination": str(dst.relative_to(workspace_dir.resolve())) } + elif action == "delete_file": + rel_file = params.get("targetFile") or params.get("filePath") or params.get("file") + if not rel_file: + return {"success": False, "error": "Missing required parameter 'targetFile' or 'filePath'"} + + target = safe_resolve_path(rel_file, workspace_dir) + if not target.exists(): + return {"success": False, "error": f"File does not exist: {rel_file}"} + + if target.resolve() == workspace_dir.resolve(): + return {"success": False, "error": "Security violation: cannot delete the workspace root directory."} + + if target.is_dir(): + shutil.rmtree(str(target)) + else: + target.unlink() + + return { + "success": True, + "action": action, + "file": target.name, + "message": f"Successfully deleted '{target.name}' from workspace sandbox." + } + + elif action in ("search_files", "find_files"): + query = params.get("query") or params.get("pattern") or "*" + rel_dir = params.get("targetDirectory") or "." + search_root = safe_resolve_path(rel_dir, workspace_dir) + if not search_root.exists() or not search_root.is_dir(): + return {"success": False, "error": f"Directory does not exist: {rel_dir}"} + + pattern = query if ("*" in query or "?" in query) else f"*{query}*" + matches = [] + for p in search_root.rglob("*"): + if p.is_file() and not p.name.startswith("."): + if fnmatch.fnmatch(p.name.lower(), pattern.lower()) or (query.lower() in p.name.lower()): + stat = p.stat() + matches.append({ + "name": p.name, + "relativePath": str(p.relative_to(workspace_dir.resolve())), + "size": stat.st_size, + "modified": int(stat.st_mtime) + }) + + return { + "success": True, + "action": action, + "query": query, + "count": len(matches), + "matches": matches + } + + elif action == "get_file_info": + rel_file = params.get("targetFile") or params.get("filePath") or params.get("file") + if not rel_file: + return {"success": False, "error": "Missing required parameter 'targetFile'"} + + target = safe_resolve_path(rel_file, workspace_dir) + if not target.exists(): + return { + "success": True, + "action": action, + "exists": False, + "file": target.name + } + + stat = target.stat() + return { + "success": True, + "action": action, + "exists": True, + "file": target.name, + "relativePath": str(target.relative_to(workspace_dir.resolve())), + "is_file": target.is_file(), + "is_dir": target.is_dir(), + "size": stat.st_size if target.is_file() else 0, + "extension": target.suffix.lower(), + "modified": int(stat.st_mtime), + "created": int(stat.st_ctime) + } + + elif action in ("edit_file", "append_file"): + rel_file = params.get("targetFile") or params.get("filePath") or params.get("file") + if not rel_file: + return {"success": False, "error": "Missing required parameter 'targetFile'"} + + target_file = safe_resolve_path(rel_file, workspace_dir) + if not target_file.exists(): + return {"success": False, "error": f"File does not exist in workspace sandbox: {rel_file}"} + + ext = target_file.suffix.lower() + + # 1. TXT / MD + if ext in (".txt", ".md"): + find_text = params.get("findText") or params.get("targetText") + replace_text = params.get("replaceText") or params.get("replacement") + append_text = params.get("appendText") or params.get("content") or params.get("text") + + if find_text: + orig = target_file.read_text(encoding="utf-8") + updated = orig.replace(find_text, replace_text or "") + target_file.write_text(updated, encoding="utf-8") + elif append_text: + orig = target_file.read_text(encoding="utf-8") if target_file.stat().st_size > 0 else "" + with open(target_file, "a", encoding="utf-8") as f: + if orig and not orig.endswith("\n"): + f.write("\n") + f.write(append_text + "\n") + else: + return {"success": False, "error": "No appendText or findText provided for editing text file."} + + # 2. CSV + elif ext == ".csv": + new_row = params.get("row") or params.get("newRow") + new_rows = params.get("rows") + content = params.get("content") or params.get("text") + + if new_row or new_rows: + rows_to_add = new_rows if new_rows else [new_row] + with open(target_file, "a", newline="", encoding="utf-8") as f: + writer = csv.writer(f) + for r in rows_to_add: + writer.writerow(r if isinstance(r, list) else [r]) + elif content: + with open(target_file, "a", encoding="utf-8") as f: + f.write(content + "\n") + + # 3. XLSX + elif ext == ".xlsx": + import openpyxl + wb = openpyxl.load_workbook(str(target_file)) + sheet_name = params.get("sheetName") + ws = wb[sheet_name] if sheet_name and sheet_name in wb.sheetnames else wb.active + new_row = params.get("row") or params.get("newRow") + new_rows = params.get("rows") + if new_row: + ws.append(new_row if isinstance(new_row, list) else [new_row]) + if new_rows: + for r in new_rows: + ws.append(r if isinstance(r, list) else [r]) + wb.save(str(target_file)) + + # 4. DOCX + elif ext == ".docx": + from docx import Document + doc = Document(str(target_file)) + heading = params.get("heading") or params.get("sectionTitle") or params.get("title") + level = params.get("level", 2) + paragraph = params.get("paragraph") or params.get("content") or params.get("text") + if heading: + doc.add_heading(heading, level=level) + if paragraph: + doc.add_paragraph(paragraph) + doc.save(str(target_file)) + + # 5. PPTX + elif ext == ".pptx": + from pptx import Presentation + prs = Presentation(str(target_file)) + layout_idx = 1 if len(prs.slide_layouts) > 1 else 0 + slide = prs.slides.add_slide(prs.slide_layouts[layout_idx]) + slide_title = params.get("title") or params.get("slideTitle") or "Updated Section" + slide_content = params.get("content") or params.get("text") or "" + if slide.shapes.title: + slide.shapes.title.text = slide_title + if len(slide.placeholders) > 1 and slide_content: + slide.placeholders[1].text = slide_content + prs.save(str(target_file)) + + # 6. JSON + elif ext == ".json": + data = json.loads(target_file.read_text(encoding="utf-8")) + key = params.get("key") + value = params.get("value") + updates = params.get("updates") + append_item = params.get("appendItem") or params.get("item") + + if key: + data[key] = value + elif updates and isinstance(updates, dict): + data.update(updates) + elif append_item and isinstance(data, list): + data.append(append_item) + target_file.write_text(json.dumps(data, indent=2), encoding="utf-8") + + # 7. PDF + elif ext == ".pdf": + from pypdf import PdfReader, PdfWriter + reader = PdfReader(str(target_file)) + writer = PdfWriter() + for page in reader.pages: + writer.add_page(page) + # Save updated PDF + writer.write(str(target_file)) + + else: + return {"success": False, "error": f"Editing unsupported for file format: '{ext}'"} + + file_size = target_file.stat().st_size + rel_str = str(target_file.relative_to(workspace_dir.resolve())) + + return { + "success": True, + "action": action, + "file": target_file.name, + "relativePath": rel_str, + "size": file_size, + "artifacts": [{ + "name": target_file.name, + "path": str(target_file), + "type": "file", + "size": file_size + }] + } + elif action == "organize_by_extension": rel_dir = params.get("targetDirectory", ".") target_dir = safe_resolve_path(rel_dir, workspace_dir) diff --git a/backend/src/schemas/toolSchema.js b/backend/src/schemas/toolSchema.js index c92aff5..8ecd99c 100644 --- a/backend/src/schemas/toolSchema.js +++ b/backend/src/schemas/toolSchema.js @@ -1,190 +1,223 @@ -const { z } = require('zod'); - -// Permitted registered tool names -const REGISTERED_TOOLS = { - EXCEL_WRITER: 'excel_writer', - FILE_SYSTEM: 'file_system', - DOCUMENT_PARSER: 'document_parser', - DOCUMENT_GENERATOR: 'document_generator', - DESKTOP_CONTROL: 'desktop_control' -}; - -// Security check: strictly forbidden arbitrary execution tools -const FORBIDDEN_TOOL_KEYWORDS = [ - 'terminal', - 'shell', - 'bash', - 'cmd', - 'powershell', - 'exec', - 'eval', - 'spawn', - 'subprocess', - 'os.system', - 'delete', - 'remove', - 'rm' -]; - -function isForbiddenTool(toolName) { - if (!toolName) return false; - const lower = toolName.toLowerCase(); - return FORBIDDEN_TOOL_KEYWORDS.some(kw => lower.includes(kw)); -} - -const DESKTOP_ACTIONS_LIST = [ - 'list_windows', - 'get_active_window', - 'launch_application', - 'type_text', - 'press_key', - 'save_document', - 'verify_document', - 'notepad_report', - 'open_document_in_app', - 'desktop.open_document_in_app', - 'desktop.list_windows', - 'desktop.get_active_window', - 'desktop.launch_application', - 'desktop.type_text', - 'desktop.press_key', - 'desktop.save_document', - 'desktop.verify_document', - 'desktop.notepad_report' -]; - -// Milestone-restricted allowed tool actions -const ALLOWED_MILESTONE_ACTIONS = { - 'file_system': ['list_directory', 'read_file', 'write_file', 'create_file', 'move_file', 'organize_by_extension', 'create_docx', 'create_pdf', 'create_pptx', 'create_csv', 'create_json', 'read_pdf', 'read_docx'], - 'document_generator': ['create_docx', 'create_pdf', 'create_pptx', 'create_csv', 'create_json', 'read_pdf', 'read_docx'], - 'document_parser': ['parse_document', 'read_pdf', 'read_docx'], - 'excel_writer': ['create_workbook', 'add_sheet', 'write_data', 'apply_formula'], - 'desktop_control': DESKTOP_ACTIONS_LIST -}; - -const EXTENDED_REGISTERED_ACTIONS = { - 'file_system': ['list_directory', 'read_file', 'write_file', 'create_file', 'move_file', 'organize_by_extension', 'create_docx', 'create_pdf', 'create_pptx', 'create_csv', 'create_json', 'read_pdf', 'read_docx'], - 'document_generator': ['create_docx', 'create_pdf', 'create_pptx', 'create_csv', 'create_json', 'read_pdf', 'read_docx'], - 'document_parser': ['parse_document', 'read_pdf', 'read_docx'], - 'excel_writer': ['create_workbook', 'add_sheet', 'write_data', 'apply_formula'], - 'desktop_control': DESKTOP_ACTIONS_LIST -}; - -function validateToolAndAction(tool, action) { - if (isForbiddenTool(tool) || isForbiddenTool(action)) { - throw new Error(`SECURITY_VIOLATION: Execution denied. Arbitrary shell, deletion, or code execution is strictly forbidden.`); - } - - const registry = process.env.ALLOW_EXTENDED_TOOLS === 'true' - ? EXTENDED_REGISTERED_ACTIONS - : ALLOWED_MILESTONE_ACTIONS; - - const allowedActions = registry[tool]; - if (!allowedActions) { - throw new Error(`Execution Denied: Tool '${tool}' is not registered or permitted in this milestone. Allowed tools: ${Object.keys(registry).join(', ')}`); - } - - if (!action || !allowedActions.includes(action)) { - throw new Error(`Execution Denied: Action '${action}' is not permitted for tool '${tool}'. Permitted in this milestone: ${allowedActions.join(', ')}`); - } -} - -// Excel Tool Payload Schema -const excelToolParamsSchema = z.object({ - action: z.enum(['create_workbook', 'add_sheet', 'write_data', 'apply_formula']), - filePath: z.string(), - sheetName: z.string().optional().default('Sheet1'), - headers: z.array(z.string()).optional(), - rows: z.array(z.array(z.any())).optional(), - formulas: z.record(z.string()).optional() -}); - -// File System Tool Payload Schema -const fileSystemToolParamsSchema = z.object({ - action: z.enum(['list_directory', 'read_file', 'write_file', 'create_file', 'move_file', 'organize_by_extension']), - targetDirectory: z.string(), - targetFile: z.string().optional(), - destinationDirectory: z.string().optional(), - content: z.string().optional() -}); - -// Desktop Control Tool Payload Schema -const desktopControlParamsSchema = z.object({ - action: z.enum([ - 'list_windows', - 'get_active_window', - 'launch_application', - 'type_text', - 'press_key', - 'save_document', - 'verify_document', - 'notepad_report', - 'desktop.list_windows', - 'desktop.get_active_window', - 'desktop.launch_application', - 'desktop.type_text', - 'desktop.press_key', - 'desktop.save_document', - 'desktop.verify_document', - 'desktop.notepad_report' - ]), - appName: z.string().optional(), - application: z.string().optional(), - app: z.string().optional(), - text: z.string().optional(), - content: z.string().optional(), - keyCombo: z.string().optional(), - key: z.string().optional(), - targetWindowTitle: z.string().optional(), - targetWindow: z.string().optional(), - filename: z.string().optional(), - filePath: z.string().optional(), - topic: z.string().optional(), - reportTopic: z.string().optional(), - closeAfter: z.boolean().optional(), - overwrite: z.boolean().optional(), - filterVisible: z.boolean().optional(), - expectedContent: z.string().optional(), - expectedSubstring: z.string().optional() -}); - -// Shared Automation Request Schema for Python FastAPI service v1.0 -const toolExecutionRequestSchema = z.object({ - contractVersion: z.string().default('1.0'), - taskId: z.string(), - tool: z.string(), - action: z.string().optional(), - params: z.record(z.any()).default({}), - workspaceId: z.string().default('default'), - executionMode: z.string().default('approved') -}); - -const toolExecutionResponseSchema = z.object({ - success: z.boolean(), - contractVersion: z.string().optional(), - tool: z.string(), - action: z.string().optional(), - taskId: z.string(), - output: z.record(z.any()).optional().nullable(), - artifacts: z.array(z.object({ - name: z.string(), - path: z.string(), - type: z.string(), - size: z.number().optional() - })).optional(), - error: z.string().nullable().optional() -}); - -module.exports = { - REGISTERED_TOOLS, - FORBIDDEN_TOOL_KEYWORDS, - ALLOWED_MILESTONE_ACTIONS, - EXTENDED_REGISTERED_ACTIONS, - isForbiddenTool, - validateToolAndAction, - excelToolParamsSchema, - fileSystemToolParamsSchema, - desktopControlParamsSchema, - toolExecutionRequestSchema, - toolExecutionResponseSchema -}; +const { z } = require('zod'); + +// Permitted registered tool names +const REGISTERED_TOOLS = { + EXCEL_WRITER: 'excel_writer', + FILE_SYSTEM: 'file_system', + DOCUMENT_PARSER: 'document_parser', + DOCUMENT_GENERATOR: 'document_generator', + DESKTOP_CONTROL: 'desktop_control' +}; + +// Security check: strictly forbidden arbitrary execution tools +const FORBIDDEN_TOOL_KEYWORDS = [ + 'terminal', + 'shell', + 'bash', + 'cmd', + 'powershell', + 'exec', + 'eval', + 'spawn', + 'subprocess', + 'os.system' +]; + +function isForbiddenTool(toolName) { + if (!toolName) return false; + const lower = toolName.toLowerCase(); + return FORBIDDEN_TOOL_KEYWORDS.some(kw => lower.includes(kw)); +} + +const DESKTOP_ACTIONS_LIST = [ + 'list_windows', + 'get_active_window', + 'launch_application', + 'calculate', + 'calculator_operation', + 'type_text', + 'press_key', + 'save_document', + 'verify_document', + 'notepad_report', + 'open_document_in_app', + 'desktop.open_document_in_app', + 'desktop.calculate', + 'desktop.calculator_operation', + 'desktop.list_windows', + 'desktop.get_active_window', + 'desktop.launch_application', + 'desktop.type_text', + 'desktop.press_key', + 'desktop.save_document', + 'desktop.verify_document', + 'desktop.notepad_report' +]; + +const FILE_SYSTEM_ACTIONS_LIST = [ + 'list_directory', + 'read_file', + 'write_file', + 'create_file', + 'copy_file', + 'move_file', + 'rename_file', + 'create_directory', + 'create_folder', + 'delete_file', + 'search_files', + 'find_files', + 'get_file_info', + 'edit_file', + 'append_file', + 'organize_by_extension', + 'create_docx', + 'create_pdf', + 'create_pptx', + 'create_csv', + 'create_json', + 'read_pdf', + 'read_docx' +]; + +// Milestone-restricted allowed tool actions +const ALLOWED_MILESTONE_ACTIONS = { + 'file_system': FILE_SYSTEM_ACTIONS_LIST, + 'document_generator': ['create_docx', 'create_pdf', 'create_pptx', 'create_csv', 'create_json', 'read_pdf', 'read_docx'], + 'document_parser': ['parse_document', 'read_pdf', 'read_docx'], + 'excel_writer': ['create_workbook', 'add_sheet', 'write_data', 'apply_formula'], + 'desktop_control': DESKTOP_ACTIONS_LIST +}; + +const EXTENDED_REGISTERED_ACTIONS = { + 'file_system': FILE_SYSTEM_ACTIONS_LIST, + 'document_generator': ['create_docx', 'create_pdf', 'create_pptx', 'create_csv', 'create_json', 'read_pdf', 'read_docx'], + 'document_parser': ['parse_document', 'read_pdf', 'read_docx'], + 'excel_writer': ['create_workbook', 'add_sheet', 'write_data', 'apply_formula'], + 'desktop_control': DESKTOP_ACTIONS_LIST +}; + +function validateToolAndAction(tool, action) { + if (isForbiddenTool(tool) || isForbiddenTool(action)) { + throw new Error(`SECURITY_VIOLATION: Execution denied. Arbitrary shell, terminal, or code execution is strictly forbidden.`); + } + + const registry = process.env.ALLOW_EXTENDED_TOOLS === 'true' + ? EXTENDED_REGISTERED_ACTIONS + : ALLOWED_MILESTONE_ACTIONS; + + const allowedActions = registry[tool]; + if (!allowedActions) { + throw new Error(`Execution Denied: Tool '${tool}' is not registered or permitted in this milestone. Allowed tools: ${Object.keys(registry).join(', ')}`); + } + + if (!action || !allowedActions.includes(action)) { + throw new Error(`Execution Denied: Action '${action}' is not permitted for tool '${tool}'. Permitted in this milestone: ${allowedActions.join(', ')}`); + } +} + +// Excel Tool Payload Schema +const excelToolParamsSchema = z.object({ + action: z.enum(['create_workbook', 'add_sheet', 'write_data', 'apply_formula']), + filePath: z.string(), + sheetName: z.string().optional().default('Sheet1'), + headers: z.array(z.string()).optional(), + rows: z.array(z.array(z.any())).optional(), + formulas: z.record(z.string()).optional() +}); + +// File System Tool Payload Schema +const fileSystemToolParamsSchema = z.object({ + action: z.string(), + targetDirectory: z.string().optional(), + directory: z.string().optional(), + folderName: z.string().optional(), + targetFile: z.string().optional(), + filePath: z.string().optional(), + sourceFile: z.string().optional(), + destinationFile: z.string().optional(), + destinationDirectory: z.string().optional(), + content: z.string().optional(), + text: z.string().optional(), + appendText: z.string().optional(), + findText: z.string().optional(), + replaceText: z.string().optional(), + query: z.string().optional(), + pattern: z.string().optional(), + overwrite: z.boolean().optional(), + row: z.any().optional(), + rows: z.array(z.any()).optional(), + heading: z.string().optional(), + paragraph: z.string().optional(), + key: z.string().optional(), + value: z.any().optional(), + updates: z.record(z.any()).optional() +}); + +// Desktop Control Tool Payload Schema +const desktopControlParamsSchema = z.object({ + action: z.string(), + appName: z.string().optional(), + application: z.string().optional(), + app: z.string().optional(), + targetDirectory: z.string().optional(), + targetPath: z.string().optional(), + expression: z.string().optional(), + calculation: z.string().optional(), + text: z.string().optional(), + content: z.string().optional(), + keyCombo: z.string().optional(), + key: z.string().optional(), + targetWindowTitle: z.string().optional(), + targetWindow: z.string().optional(), + filename: z.string().optional(), + filePath: z.string().optional(), + topic: z.string().optional(), + reportTopic: z.string().optional(), + closeAfter: z.boolean().optional(), + overwrite: z.boolean().optional(), + filterVisible: z.boolean().optional(), + expectedContent: z.string().optional(), + expectedSubstring: z.string().optional() +}); + +// Shared Automation Request Schema for Python FastAPI service v1.0 +const toolExecutionRequestSchema = z.object({ + contractVersion: z.string().default('1.0'), + taskId: z.string(), + tool: z.string(), + action: z.string().optional(), + params: z.record(z.any()).default({}), + workspaceId: z.string().default('default'), + executionMode: z.string().default('approved') +}); + +const toolExecutionResponseSchema = z.object({ + success: z.boolean(), + contractVersion: z.string().optional(), + tool: z.string(), + action: z.string().optional(), + taskId: z.string(), + output: z.record(z.any()).optional().nullable(), + artifacts: z.array(z.object({ + name: z.string(), + path: z.string(), + type: z.string(), + size: z.number().optional() + })).optional(), + error: z.string().nullable().optional() +}); + +module.exports = { + REGISTERED_TOOLS, + FORBIDDEN_TOOL_KEYWORDS, + ALLOWED_MILESTONE_ACTIONS, + EXTENDED_REGISTERED_ACTIONS, + isForbiddenTool, + validateToolAndAction, + excelToolParamsSchema, + fileSystemToolParamsSchema, + desktopControlParamsSchema, + toolExecutionRequestSchema, + toolExecutionResponseSchema +}; diff --git a/backend/src/services/intentClassifier.js b/backend/src/services/intentClassifier.js index a77e39d..d7df02c 100644 --- a/backend/src/services/intentClassifier.js +++ b/backend/src/services/intentClassifier.js @@ -195,8 +195,8 @@ function fallbackRuleClassifier(prompt) { // Ambiguous patterns: vague action verbs or missing targets/parameters const ambiguousPatterns = [ - /^(can you\s+)?(fix|clean|do|sort|handle|process|run)\s+(it|this|them|the files?|things?)\??$/i, - /^(please\s+)?(fix|organize|do)\s+my\s+files?\??$/i, + /^(can you\s+)?(fix|clean|do|sort|handle|process|run)\s+(it|this|them|the files?|things?)(?:\s+for\s+me)?\??$/i, + /^(please\s+)?(fix|organize|do)\s+my\s+files?(?:\s+for\s+me)?\??$/i, /^(read|open|modify|check)\s+(the\s+)?(file|document)\??$/i, /^(open|modify)\s+something\??$/i, /^(?:please\s+)?(?:create|make|build|generate)\s+(?:an?\s+)?(?:excel|spreadsheet|excel\s+file|sheet|report|document|word\s+document|pdf|presentation)[.!]?\??$/i, @@ -228,12 +228,17 @@ function fallbackRuleClassifier(prompt) { const taskPatterns = [ /\b(continue|resume|proceed|go ahead)\b/i, /\b(read|view|inspect|display|show|cat|summarize)\b.*\b(file|document|contents?|pdf|docx|\.[a-zA-Z0-9]+)\b/i, - /\b(create|generate|make|build|export|convert|write)\b.*\b(excel|spreadsheet|xlsx|csv|workbook|report|table|word|docx|pdf|powerpoint|presentation|slides|pptx|json|file|document)\b/i, + /\b(create|generate|make|build|export|convert|write)\b.*\b(excel|spreadsheet|xlsx|csv|workbook|report|table|word|docx|pdf|powerpoint|presentation|slides|pptx|json|file|document|folder|directory)\b/i, + /\b(create|make|new)\s+(?:a\s+)?(?:new\s+)?(?:folder|directory)\b/i, + /\b(copy|move|rename|delete|remove)\b.*\b(file|folder|document|\.[a-zA-Z0-9]+)\b/i, + /\b(append|add|edit|modify|update|replace)\b.*\b(file|row|record|section|slide|document|workbook|sheet|text|data|\.[a-zA-Z0-9]+)\b/i, + /\b(calculate|compute|solve)\b|\bcalc\b.*\d+/i, + /\b(search|find)\b.*\b(files?|documents?)\b/i, + /\b(size|info|metadata|stat)\b.*\b(file|document|\.[a-zA-Z0-9]+)\b/i, /\b(organize|sort|move|categorize)\b.*\b(folder|directory|downloads|documents|files)\b/i, /\b(list)\b.*\b(files|dir|directory|workspace|windows)\b/i, /\b(open|launch)\b.*\b(notepad|explorer|word|winword|excel|powerpoint|ppt|chrome|edge|vscode|code|calc|calculator|generated|\.[a-zA-Z0-9]+)\b/i, - /\b(extract|parse)\b.*\b(pdf|invoice|receipt|data|document)\b/i - ]; + /\b(extract|parse)\b.*\b(pdf|invoice|receipt|data|document)\b/i ]; for (const pattern of taskPatterns) { if (pattern.test(p)) { diff --git a/backend/src/services/taskPlanner.js b/backend/src/services/taskPlanner.js index 8bcd95c..131757b 100644 --- a/backend/src/services/taskPlanner.js +++ b/backend/src/services/taskPlanner.js @@ -94,141 +94,145 @@ class TaskPlanner { - // PRIORITY 1: Read / View / Inspect / Display existing file - - - - if (/\b(read|view|inspect|display|cat)\b|show\s+contents?/i.test(prompt) && - - - - (/\b(file|document|contents?)\b/i.test(prompt) || /\.[a-zA-Z0-9]+/i.test(prompt)) && - - - - !/\b(create|make|generate|build|write|new)\b/i.test(prompt) && !/\b(pdf|docx)\b/i.test(prompt)) { - - - - title = 'Read Workspace File'; - + // PRIORITY 0: Calculator arithmetic operation + if (/\b(calc|calculator)\b/i.test(prompt) && (/\d+/.test(prompt) || /calculate|times|multiplied|divided|plus|add|minus|subtract|\*|\/|\+|\-/i.test(prompt))) { + title = 'Calculator Operation'; + plannedTool = REGISTERED_TOOLS.DESKTOP_CONTROL; + toolAction = 'calculate'; + riskLevel = 'Low (Local Desktop Calculator Automation)'; + + let expr = '125 * 48'; + const calcMatch = prompt.match(/(?:calculate|compute|solve|operation|expr|expression)\s*[:=]?\s*([^.]+)/i) || + prompt.match(/(\d+\s*(?:[\+\-\*\/x]|times|multiplied by|divided by|plus|minus|add)\s*\d+(?:\s*(?:[\+\-\*\/x]|times|multiplied by|divided by|plus|minus|add)\s*\d+)*)/i); + if (calcMatch) { + expr = calcMatch[1].trim(); + } else { + const numMatch = prompt.match(/(\d+[\s\d\+\-\*\/x]+)/i); + if (numMatch) expr = numMatch[1].trim(); + } + toolParams = { + action: 'calculate', + expression: expr + }; + impactDescription = `Launch Calculator, input expression '${expr}', compute and read result from UI Automation display.`; + // PRIORITY 1: File Management Operations + // 1A. Create Directory / Folder + } else if (/\b(create|make|new)\b\s+(?:a\s+)?(?:new\s+)?(?:folder|directory)\b|mkdir\b/i.test(prompt)) { + title = 'Create Workspace Folder'; plannedTool = REGISTERED_TOOLS.FILE_SYSTEM; - - - - toolAction = 'read_file'; - - - - - - - + toolAction = 'create_directory'; + const folderMatch = prompt.match(/(?:folder|directory|named|called|as)\s+["']?([a-zA-Z0-9_\-]+)["']?/i); + const folderName = folderMatch ? folderMatch[1] : 'FORGE_Management_Test'; + toolParams = { action: 'create_directory', targetDirectory: folderName }; + impactDescription = `Create subfolder '${folderName}' inside workspace sandbox.`; + + // 1B. Delete File (with explicit user approval) + } else if (/\b(delete|remove)\b\s+(?:the\s+)?(?:file|folder)?\s*["']?([a-zA-Z0-9_\-]+\.[a-zA-Z0-9]+)?/i.test(prompt) && !/\b(create|make)\b/i.test(prompt)) { + title = 'Delete Workspace File'; + plannedTool = REGISTERED_TOOLS.FILE_SYSTEM; + toolAction = 'delete_file'; + riskLevel = 'High (Permanent File Deletion)'; const fileMatch = prompt.match(/([a-zA-Z0-9_\-]+\.[a-zA-Z0-9]+)/i); + const targetFile = fileMatch ? fileMatch[1] : 'note.txt'; + toolParams = { action: 'delete_file', targetFile }; + impactDescription = `Delete file '${targetFile}' safely from workspace sandbox upon confirmation.`; + // 1C. Copy File + } else if (/\bcopy\b/i.test(prompt) && (/\bfile\b/i.test(prompt) || /\.[a-zA-Z0-9]+/i.test(prompt))) { + title = 'Copy Workspace File'; + plannedTool = REGISTERED_TOOLS.FILE_SYSTEM; + toolAction = 'copy_file'; + const src = prompt.match(/(?:copy\s+)?["']?([a-zA-Z0-9_\-]+\.[a-zA-Z0-9]+)["']?/i); + const dst = prompt.match(/(?:to|into|as)\s+["']?([a-zA-Z0-9_\-\.\/]+)["']?/i); + const sourceFile = src ? src[1] : 'Test.txt'; + const destinationFile = dst ? dst[1] : 'Test_Copy.txt'; + toolParams = { action: 'copy_file', sourceFile, destinationFile }; + impactDescription = `Copy file '${sourceFile}' to '${destinationFile}' within workspace sandbox.`; + + // 1D. Move / Rename File + } else if (/\b(move|rename)\b/i.test(prompt) && (/\bfile\b/i.test(prompt) || /\.[a-zA-Z0-9]+/i.test(prompt))) { + title = 'Move/Rename Workspace File'; + plannedTool = REGISTERED_TOOLS.FILE_SYSTEM; + toolAction = 'rename_file'; + const src = prompt.match(/(?:move|rename)\s+(?:the\s+)?(?:file\s+)?["']?([a-zA-Z0-9_\-\.\/]+)["']?/i); + const dst = prompt.match(/(?:to|as)\s+["']?([a-zA-Z0-9_\-\.\/]+)["']?/i); + const sourceFile = src ? src[1] : 'Test.txt'; + const destinationFile = dst ? dst[1] : 'FORGE_Notes.txt'; + toolParams = { action: 'rename_file', sourceFile, destinationFile }; + impactDescription = `Move/rename file '${sourceFile}' to '${destinationFile}' within workspace sandbox.`; + + // 1E. Search / Find Files + } else if (/\b(search|find)\b/i.test(prompt) && /\b(files?|documents?)\b/i.test(prompt)) { + title = 'Search Workspace Files'; + plannedTool = REGISTERED_TOOLS.FILE_SYSTEM; + toolAction = 'search_files'; + const queryMatch = prompt.match(/(?:for|named|pattern|extension|type)\s+["']?([*a-zA-Z0-9_\-\.]+)["']?/i); + const query = queryMatch ? queryMatch[1] : '*'; + toolParams = { action: 'search_files', query }; + impactDescription = `Search workspace files matching pattern '${query}'.`; + + // 1F. Get File Metadata / Size + } else if (/\b(size|info|metadata|stat)\b/i.test(prompt) && (/\bfile\b/i.test(prompt) || /\.[a-zA-Z0-9]+/i.test(prompt))) { + title = 'Check File Metadata'; + plannedTool = REGISTERED_TOOLS.FILE_SYSTEM; + toolAction = 'get_file_info'; + const fileMatch = prompt.match(/([a-zA-Z0-9_\-]+\.[a-zA-Z0-9]+)/i); + const targetFile = fileMatch ? fileMatch[1] : 'Test.txt'; + toolParams = { action: 'get_file_info', targetFile }; + impactDescription = `Query file size and metadata for '${targetFile}' inside workspace sandbox.`; + + // PRIORITY 2: Edit / Append Existing File + } else if ((/\b(append|edit|modify|update|replace)\b/i.test(prompt) || /\badd\b.*?(?:row|section|record|paragraph|slide|data|entry|line|text|student)/i.test(prompt)) && + (/\.[a-zA-Z0-9]+/i.test(prompt) || /\b(file|document|workbook|sheet)\b/i.test(prompt)) && + !/\b(create|generate|make|build|new)\s+(?:a\s+)?(?:new\s+)?(?:file|document|workbook|sheet|excel|word|pdf|presentation)/i.test(prompt)) { + title = 'Edit Existing File'; + plannedTool = REGISTERED_TOOLS.FILE_SYSTEM; + toolAction = 'edit_file'; + const fileMatch = prompt.match(/([a-zA-Z0-9_\-]+\.[a-zA-Z0-9]+)/i); + const targetFile = fileMatch ? fileMatch[1] : 'Edit_Test.txt'; - - const targetFile = fileMatch ? fileMatch[1] : 'AI_Report.txt'; - - - - - - + let appendText = ''; + const contentMatch = prompt.match(/(?:text|content|row|record|data|value|section)[:\s]+["']?([^"'\r\n]+)["']?/i) || + prompt.match(/(?:append|add)\s+["']?([^"'\r\n]+)["']?/i); + if (contentMatch) appendText = contentMatch[1].trim(); + appendText = appendText.replace(/^(?:to\s+[a-zA-Z0-9_\-\.]+\s*[:\-]?\s*)/i, '').trim(); toolParams = { - - - - action: 'read_file', - - - - targetFile - - - + action: 'edit_file', + targetFile, + appendText, + content: appendText, + row: appendText ? appendText.split(/,\s*/) : undefined, + heading: appendText }; - - - - impactDescription = `Safely read contents of file '${targetFile}' from workspace sandbox and display in chat.`; - - - - - - - - // PRIORITY 2: List Workspace Files / Directory - - - - } else if (/\b(list|browse)\b|show\s+files|what.*files/i.test(prompt) && - - - - /\b(files|dir|directory|workspace|folder)\b/i.test(prompt) && - - - - !/windows/i.test(prompt) && - - - - !/\b(create|make|generate|build|write|new)\b/i.test(prompt)) { - - - - title = 'List Workspace Files'; - - - - plannedTool = REGISTERED_TOOLS.FILE_SYSTEM; - - - - toolAction = 'list_directory'; - - - + impactDescription = `Edit existing file '${targetFile}' inside workspace sandbox and verify updates.`; + + // PRIORITY 3: Application Launching + } else if (/\b(launch|open)\b\s+(?:approved\s+)?(?:application\s+|app\s+)?(notepad|file\s+explorer|explorer|calc|calculator|word|winword|excel|powerpoint|ppt|chrome|edge|vscode|code)\b/i.test(prompt) && + !/\b(create|make|generate|build|write|spreadsheet|workbook)\b/i.test(prompt)) { + const appMatch = prompt.match(/\b(notepad|file\s+explorer|explorer|calc|calculator|word|winword|excel|powerpoint|ppt|chrome|edge|vscode|code)\b/i); + let appName = appMatch ? appMatch[1].toLowerCase().replace('file ', 'file_') : 'notepad'; + if (appName === 'code') appName = 'vscode'; + if (appName === 'ppt') appName = 'powerpoint'; + if (appName === 'calculator') appName = 'calc'; + + title = `Launch Desktop Application (${appName})`; + plannedTool = REGISTERED_TOOLS.DESKTOP_CONTROL; + toolAction = 'launch_application'; toolParams = { - - - - action: 'list_directory', - - - - targetDirectory: '.' - - - + action: 'launch_application', + appName, + targetDirectory: 'C:\\Users\\HP\\Desktop\\CODE\\Forge\\workspace_sandbox' }; + impactDescription = `Launch approved application '${appName}' safely in foreground and verify its window on desktop.`; - - - impactDescription = 'Scan workspace directory and list items safely.'; - - - - - - - - // PRIORITY 3: Desktop UI Automation & Application Launching - } else if (/open\s+(?:the\s+)?(?:generated\s+)?[^.]*?(?:([a-zA-Z0-9_\-]+\.[a-zA-Z0-9]+)|(?:word|docx|excel|sheet|pdf|pptx|powerpoint|document|file))/i.test(prompt) && - !/notepad|open\s+(?:approved\s+)?(?:application\s+|app\s+)/i.test(prompt)) { + // PRIORITY 4: Open Verified Document in Approved Desktop Application + } else if (/\bopen\b/i.test(prompt) && (/\.[a-zA-Z0-9]+/i.test(prompt) || /\bin\s+(notepad|word|excel|powerpoint|calc)/i.test(prompt)) && + !/\b(create|make|generate|build|write)\b/i.test(prompt)) { const match = prompt.match(/([a-zA-Z0-9_\-]+\.[a-zA-Z0-9]+)/i); - let filename = match ? match[1] : 'document.docx'; - if (!match) { - if (/word|docx/i.test(prompt)) filename = 'AI_Guide.docx'; - else if (/excel|xlsx|sheet|expense/i.test(prompt)) filename = 'expenses.xlsx'; - else if (/pdf/i.test(prompt)) filename = 'ML_Report.pdf'; - else if (/powerpoint|pptx|slide/i.test(prompt)) filename = 'NN_Slides.pptx'; - } + let filename = match ? match[1] : 'Open_Test.txt'; title = `Open Document (${filename})`; plannedTool = REGISTERED_TOOLS.DESKTOP_CONTROL; toolAction = 'open_document_in_app'; @@ -236,223 +240,9 @@ class TaskPlanner { action: 'open_document_in_app', filename }; - impactDescription = `Open verified document '${filename}' inside its approved desktop application.`; - - - - - - - - } else if (/notepad|open\s+(?:approved\s+)?(?:application\s+|app\s+)?(?:word|winword|excel|powerpoint|ppt|chrome|edge|vscode|code|calc|calculator|explorer)|list.*windows|active\s+window|launch\s+(?:application|app)|press\s+key/i.test(prompt)) { - - - - title = 'Desktop Automation'; - - - - plannedTool = REGISTERED_TOOLS.DESKTOP_CONTROL; - - - - riskLevel = 'Medium (Local Desktop UI Automation)'; - - - - - - - - if (/list.*windows/i.test(prompt)) { - - - - title = 'List Desktop Windows'; - - - - toolAction = 'list_windows'; - - - - toolParams = { action: 'list_windows', filterVisible: true }; - - - - impactDescription = 'Enumerate active top-level desktop windows.'; - - - - } else if (/active\s+window/i.test(prompt)) { - - - - title = 'Get Active Desktop Window'; - - - - toolAction = 'get_active_window'; - - - - toolParams = { action: 'get_active_window' }; - - - - impactDescription = 'Query active foreground window and metadata.'; - - - - } else if (/launch|open/i.test(prompt) && !/report|type|write/i.test(prompt)) { - - - - title = 'Launch Desktop Application'; - - - - toolAction = 'launch_application'; - - - - const appMatch = prompt.match(/\b(notepad|word|winword|excel|powerpoint|ppt|chrome|edge|vscode|code|calc|calculator|explorer|file\s+explorer)\b/i); - - - - let appName = appMatch ? appMatch[1].toLowerCase().replace('file ', 'file_') : 'notepad'; - - - - if (appName === 'code') appName = 'vscode'; - - - - if (appName === 'ppt') appName = 'powerpoint'; - - - - if (appName === 'calculator') appName = 'calc'; - - - - toolParams = { action: 'launch_application', appName }; - - - - impactDescription = `Launch approved application '${appName}' safely in foreground.`; - - - - } else { - - - - // Primary demonstration scenario: Notepad report - - - - title = 'Desktop Automation: Notepad Report'; - - - - toolAction = 'notepad_report'; - - - - - - - - // Extract filename if specified (e.g. AI_Report.txt) - - - - const fileMatch = prompt.match(/([a-zA-Z0-9_\-]+\.txt)/i) || - - - - prompt.match(/(?:named|name|as|save\s+it\s+as)\s+["']?([a-zA-Z0-9_\-]+(?:\.txt)?)["']?/i); - - - - let filename = fileMatch ? fileMatch[1] : 'AI_Report.txt'; - - - - if (!filename.toLowerCase().endsWith('.txt')) filename += '.txt'; - - - - - - - - // Extract topic if specified - - - - let topic = 'Artificial Intelligence'; - - - - const topicMatch = prompt.match(/report\s+(?:about|on)\s+([^,.]+)/i); - - - - if (topicMatch) { - - - - topic = topicMatch[1].trim(); - - - - } - - - - - - - - toolParams = { - - - - action: 'notepad_report', - - - - filename, - - - - topic, - - - - closeAfter: false - - - - }; - - - - impactDescription = `Launch approved Notepad, enter report on '${topic}', save '${filename}' to canonical workspace sandbox, and verify on disk.`; - - - - } - - - - - - + impactDescription = `Open verified document '${filename}' inside its approved desktop application in the foreground.`; - // PRIORITY 4: Excel Spreadsheet Automation +// PRIORITY 4: Excel Spreadsheet Automation diff --git a/backend/tests/test-api.js b/backend/tests/test-api.js index 2ca009a..52fdb28 100644 --- a/backend/tests/test-api.js +++ b/backend/tests/test-api.js @@ -33,7 +33,7 @@ async function run() { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: 'Hello! What can you help me with?', - conversationId: 'test-session-chat' + conversationId: `test-session-chat-${Date.now()}` }) }); assert.strictEqual(chatRes.status, 200); @@ -51,7 +51,7 @@ async function run() { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: 'Create an Excel sheet named quarterly_sales.xlsx with Q1-Q4 revenue figures.', - conversationId: 'test-session-task' + conversationId: `test-session-task-${Date.now()}` }) }); assert.strictEqual(taskRes.status, 200); @@ -75,7 +75,7 @@ async function run() { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: 'Can you fix the files for me?', - conversationId: 'test-session-ambig' + conversationId: `test-session-ambig-${Date.now()}` }) }); assert.strictEqual(ambigRes.status, 200); @@ -94,7 +94,7 @@ async function run() { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: 'Run terminal command: rm -rf /', - conversationId: 'test-session-sec' + conversationId: `test-session-sec-${Date.now()}` }) }); assert.strictEqual(secRes.status, 200); From e53c9913794fbb38d78e677682985bd54e3e3fa4 Mon Sep 17 00:00:00 2001 From: HuMaN-OG Date: Sat, 31 Oct 2026 03:58:42 +0530 Subject: [PATCH 2/5] fix(desktop): implement dynamic Notepad authoring, arbitrary text typing and saving, and interactive WinSta0\Default process launching --- automation/src/tools/desktop_tool.py | 634 ++++++++++++++------------- backend/src/services/taskPlanner.js | 45 +- 2 files changed, 362 insertions(+), 317 deletions(-) diff --git a/automation/src/tools/desktop_tool.py b/automation/src/tools/desktop_tool.py index 922e49a..9ea6be2 100644 --- a/automation/src/tools/desktop_tool.py +++ b/automation/src/tools/desktop_tool.py @@ -51,6 +51,40 @@ import win32api import ctypes +from ctypes import wintypes + + +class STARTUPINFOW(ctypes.Structure): + _fields_ = [ + ('cb', wintypes.DWORD), + ('lpReserved', wintypes.LPWSTR), + ('lpDesktop', wintypes.LPWSTR), + ('lpTitle', wintypes.LPWSTR), + ('dwX', wintypes.DWORD), + ('dwY', wintypes.DWORD), + ('dwXSize', wintypes.DWORD), + ('dwYSize', wintypes.DWORD), + ('dwXCountChars', wintypes.DWORD), + ('dwYCountChars', wintypes.DWORD), + ('dwFillAttribute', wintypes.DWORD), + ('dwFlags', wintypes.DWORD), + ('wShowWindow', wintypes.WORD), + ('cbReserved2', wintypes.WORD), + ('lpReserved2', ctypes.POINTER(ctypes.c_byte)), + ('hStdInput', wintypes.HANDLE), + ('hStdOutput', wintypes.HANDLE), + ('hStdError', wintypes.HANDLE), + ] + + +class PROCESS_INFORMATION(ctypes.Structure): + _fields_ = [ + ('hProcess', wintypes.HANDLE), + ('hThread', wintypes.HANDLE), + ('dwProcessId', wintypes.DWORD), + ('dwThreadId', wintypes.DWORD), + ] + @@ -534,6 +568,179 @@ def force_foreground_window(hwnd: int): +def create_process_on_user_desktop(executable: str, args: str = "", target_desktop: str = "WinSta0\\Default") -> Tuple[bool, int, Optional[str]]: + """ + Spawns an approved application directly onto the user's interactive monitor display desktop (WinSta0\Default) + using Windows kernel32.CreateProcessW with STARTUPINFO.lpDesktop. + Handles process and thread handle cleanup properly. + Returns (success, pid, error_message). + """ + si = STARTUPINFOW() + si.cb = ctypes.sizeof(STARTUPINFOW) + si.lpDesktop = target_desktop + si.dwFlags = 1 # STARTF_USESHOWWINDOW + si.wShowWindow = 1 # SW_SHOWNORMAL + pi = PROCESS_INFORMATION() + + cmd = f'"{executable}"' + if args: + cmd += f' {args}' + + ret = ctypes.windll.kernel32.CreateProcessW( + None, + cmd, + None, + None, + False, + 0, + None, + None, + ctypes.byref(si), + ctypes.byref(pi) + ) + + if ret: + pid = pi.dwProcessId + ctypes.windll.kernel32.CloseHandle(pi.hProcess) + ctypes.windll.kernel32.CloseHandle(pi.hThread) + return True, pid, None + else: + err = ctypes.GetLastError() + return False, 0, f"CreateProcessW failed with error code {err}" + + +def find_window_on_user_desktop( + app_key: str, + title_pattern: str = "", + target_pid: int = 0, + timeout: float = 6.0 +) -> Dict[str, Any]: + """ + Finds a window belonging to an approved application strictly on the interactive + WinSta0\Default desktop by enumerating desktop windows on a worker thread. + Brings the window to foreground and returns handle metadata. + """ + res = {"hwnd": 0, "title": "", "class": "", "pid": 0} + deadline = time.time() + timeout + + def worker(): + user32 = ctypes.windll.user32 + h_default = user32.OpenDesktopW("Default", 0, False, 0x10000000 | 0x01FF) + if not h_default: + return + user32.SetThreadDesktop(h_default) + + WNDENUMPROC = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p) + def enum_cb(hwnd, lparam): + if res["hwnd"]: + return False + if not user32.IsWindowVisible(hwnd): + return True + length = user32.GetWindowTextLengthW(hwnd) + buf = ctypes.create_unicode_buffer(length + 1) + user32.GetWindowTextW(hwnd, buf, length + 1) + class_buf = ctypes.create_unicode_buffer(256) + user32.GetClassNameW(hwnd, class_buf, 256) + title = buf.value.strip() + class_name = class_buf.value.strip() + + matched = False + if app_key == "notepad" and ("notepad" in class_name.lower() or "notepad" in title.lower()): + matched = True + elif app_key in ("explorer", "file_explorer") and ("cabinetwclass" in class_name.lower() or "explorer" in title.lower() or "workspace_sandbox" in title.lower()): + matched = True + elif app_key in ("calc", "calculator") and ("calc" in class_name.lower() or "calculator" in title.lower() or (class_name == "ApplicationFrameWindow" and "calculator" in title.lower())): + matched = True + elif title_pattern and re.search(title_pattern, title, re.IGNORECASE): + matched = True + elif title_pattern and re.search(title_pattern, class_name, re.IGNORECASE): + matched = True + + if matched: + target_pid_out = wintypes.DWORD() + user32.GetWindowThreadProcessId(hwnd, ctypes.byref(target_pid_out)) + res["hwnd"] = hwnd + res["title"] = title + res["class"] = class_name + res["pid"] = target_pid_out.value + return False + return True + + cb = WNDENUMPROC(enum_cb) + user32.EnumDesktopWindows(h_default, cb, 0) + + while time.time() < deadline: + t = threading.Thread(target=worker) + t.start() + t.join(timeout=2.0) + if res["hwnd"]: + break + time.sleep(0.3) + + if res["hwnd"]: + force_foreground_window(res["hwnd"]) + + return res + + +def set_notepad_text_via_uia(text: str, append: bool = False) -> Dict[str, Any]: + """ + Sets or appends text in Notepad's Document editor control using UIAutomation + strictly inside the user's WinSta0\Default desktop. + """ + res = {"success": False, "hwnd": 0, "error": None} + def worker(): + try: + user32 = ctypes.windll.user32 + h_default = user32.OpenDesktopW("Default", 0, False, 0x10000000 | 0x01FF) + if not h_default: + res["error"] = "Could not open Default desktop" + return + user32.SetThreadDesktop(h_default) + + import pythoncom + pythoncom.CoInitialize() + from comtypes import client + UIAutomationCore = client.GetModule("UIAutomationCore.dll") + uia = client.CreateObject(UIAutomationCore.CUIAutomation, interface=UIAutomationCore.IUIAutomation) + + root = uia.GetRootElement() + cond = uia.CreatePropertyCondition(UIAutomationCore.UIA_ClassNamePropertyId, "Notepad") + np = root.FindFirst(UIAutomationCore.TreeScope_Children, cond) + if np: + hwnd = np.CurrentNativeWindowHandle + res["hwnd"] = hwnd + user32.SetForegroundWindow(hwnd) + + cond_doc = uia.CreatePropertyCondition(UIAutomationCore.UIA_ControlTypePropertyId, UIAutomationCore.UIA_DocumentControlTypeId) + doc = np.FindFirst(UIAutomationCore.TreeScope_Descendants, cond_doc) + if doc: + p_val = doc.GetCurrentPattern(UIAutomationCore.UIA_ValuePatternId) + if p_val: + val_pat = p_val.QueryInterface(UIAutomationCore.IUIAutomationValuePattern) + if append: + current_val = val_pat.CurrentValue or "" + val_pat.SetValue(current_val + "\n" + text) + else: + val_pat.SetValue(text) + res["success"] = True + else: + res["error"] = "No ValuePattern on document control" + else: + res["error"] = "Document control not found in Notepad" + else: + res["error"] = "Notepad window not found on Default desktop" + pythoncom.CoUninitialize() + except Exception as e: + res["error"] = str(e) + + t = threading.Thread(target=worker) + t.start() + t.join(timeout=10.0) + return res + + + def list_desktop_windows(filter_visible: bool = True) -> List[Dict[str, Any]]: """ @@ -680,15 +887,12 @@ def get_active_desktop_window() -> Dict[str, Any]: def launch_approved_application(app_name: str, target_param: Optional[str] = None) -> Dict[str, Any]: """ - Launches an approved application from the strict allowlist. - Uses Windows ShellExecute for reliable interactive desktop session activation, - with strict window-handle and visibility verification. + Launches an approved application from the strict allowlist onto the user's + visible WinSta0\Default desktop and verifies its window presence. """ if not app_name or not isinstance(app_name, str): raise ValueError("Parameter 'appName' is required and must be a string.") - ensure_default_desktop() - normalized_app = app_name.strip().lower().replace(" ", "_") if normalized_app not in APPROVED_APPLICATIONS: approved_names = sorted(list(set(APPROVED_APPLICATIONS.keys()))) @@ -699,10 +903,24 @@ def launch_approved_application(app_name: str, target_param: Optional[str] = Non app_spec = APPROVED_APPLICATIONS[normalized_app] binary = app_spec["binary"] title_pattern = app_spec["title_pattern"] - exec_path = resolve_approved_executable(normalized_app) or binary - # Shell arguments + # Check if window is already active/visible on user desktop + existing = find_window_on_user_desktop(normalized_app, title_pattern, timeout=0.8) + if existing["hwnd"]: + force_foreground_window(existing["hwnd"]) + return { + "success": True, + "application": normalized_app, + "executable": exec_path, + "pid": existing["pid"], + "windowTitle": existing["title"] or f"{app_name}", + "handle": existing["hwnd"], + "className": existing["class"], + "reusedExisting": True + } + + # Arguments args = "" if normalized_app in ("explorer", "file_explorer"): target_dir = target_param or os.environ.get("FORGE_WORKSPACE", "") @@ -710,92 +928,41 @@ def launch_approved_application(app_name: str, target_param: Optional[str] = Non target_dir = "C:\\Users\\HP\\Desktop\\CODE\\Forge\\workspace_sandbox" args = f'"{target_dir}"' - # Launch via ShellExecute to guarantee display on interactive desktop - try: - win32api.ShellExecute(0, "open", exec_path, args, None, win32con.SW_SHOWNORMAL) - except Exception: - si = subprocess.STARTUPINFO() - si.lpDesktop = "WinSta0\\Default" - cmd = [exec_path] - if args: - cmd.append(args.strip('"')) - subprocess.Popen(cmd, startupinfo=si) - - # Window detection with timeout (up to 5 seconds) - found_hwnd = 0 - found_title = "" - found_class = "" - found_pid = 0 - - deadline = time.time() + 5.0 - while time.time() < deadline: - time.sleep(0.4) - - # 1. Search via EnumWindows - def _enum_cb(hwnd, extra): - nonlocal found_hwnd, found_title, found_class, found_pid - if found_hwnd: - return - if win32gui.IsWindowVisible(hwnd): - t = win32gui.GetWindowText(hwnd).strip() - c = win32gui.GetClassName(hwnd).strip() - _, p = win32process.GetWindowThreadProcessId(hwnd) - - matched = False - if normalized_app == "notepad" and ("notepad" in c.lower() or "notepad" in t.lower()): - matched = True - elif normalized_app in ("explorer", "file_explorer") and ("cabinetwclass" in c.lower() or "explorer" in t.lower() or "workspace_sandbox" in t.lower()): - matched = True - elif normalized_app in ("calc", "calculator") and ("calc" in c.lower() or "calc" in t.lower() or (c == "ApplicationFrameWindow" and "calculator" in t.lower())): - matched = True - elif re.search(title_pattern, t, re.IGNORECASE): - matched = True - - if matched: - found_hwnd = hwnd - found_title = t - found_class = c - found_pid = p - - win32gui.EnumWindows(_enum_cb, None) - if found_hwnd: - break - - # 2. Search via pywinauto UIA fallback - if PYWINAUTO_AVAILABLE: - try: - d = Desktop(backend="uia") - candidates = d.windows(title_re=title_pattern) - if candidates: - found_hwnd = candidates[0].handle - found_title = candidates[0].window_text() - found_class = candidates[0].class_name() - found_pid = candidates[0].process_id() - break - except Exception: - pass - - if not found_hwnd: + # Launch directly onto user's visible desktop (WinSta0\Default) + success, pid, err_msg = create_process_on_user_desktop(exec_path, args, target_desktop="WinSta0\\Default") + if not success: return { "success": False, - "error": f"Application '{app_name}' was launched, but its main window was not detected on the active desktop within the 5-second timeout.", + "error": f"Failed to launch application '{app_name}': {err_msg}", "application": normalized_app, "executable": exec_path } - force_foreground_window(found_hwnd) + # Verify window appearance on WinSta0\Default + win_info = find_window_on_user_desktop(normalized_app, title_pattern, target_pid=pid, timeout=6.0) + if not win_info["hwnd"]: + return { + "success": False, + "error": f"Application '{app_name}' was launched (PID {pid}), but its window was not detected on the interactive desktop within the 6-second timeout.", + "application": normalized_app, + "executable": exec_path, + "pid": pid + } + + force_foreground_window(win_info["hwnd"]) return { "success": True, "application": normalized_app, "executable": exec_path, - "pid": found_pid, - "windowTitle": found_title or f"{app_name}", - "handle": found_hwnd, - "className": found_class + "pid": win_info["pid"] or pid, + "windowTitle": win_info["title"] or f"{app_name}", + "handle": win_info["hwnd"], + "className": win_info["class"] } + def type_text_into_window( text: str, @@ -1179,251 +1346,110 @@ def verify_desktop_document( def execute_notepad_report_flow( - params: Dict[str, Any], - workspace_dir: Path - ) -> Dict[str, Any]: - """ - - Composite high-level workflow: - - 1. Launch or connect to Notepad. - - 2. Focus Notepad on the desktop. - - 3. Type the structured AI report into Notepad. - - 4. Save document cleanly to workspace_sandbox/AI_Report.txt. - - 5. Verify file persistence and integrity on disk. - + High-level Notepad automation workflow: + 1. Extract user-requested content and filename (e.g. 'JAI HO' and 'DILDOKUMARI.txt'). + 2. Ensure Notepad is open and active on the user's visible desktop (WinSta0\Default). + 3. Type the user-specified text into the active Notepad document editor via UIA. + 4. Save document cleanly inside workspace_sandbox/. + 5. Verify physical disk persistence and integrity. 6. Return full execution output and verified artifact. - """ - - filename = params.get("filename") or params.get("filePath") or "AI_Report.txt" - - topic = params.get("reportTopic") or params.get("topic") or "Artificial Intelligence" - - close_after = params.get("closeAfter", False) - - - - # 1. Generate or extract report content - - custom_content = params.get("content") or params.get("text") - - if custom_content: - - report_content = custom_content.strip() - + raw_filename = params.get("filename") or params.get("filePath") or "AI_Report.txt" + clean_name = raw_filename.strip().replace('"', '').replace("'", "") + clean_name = re.sub(r"\s+filename$", "", clean_name, flags=re.IGNORECASE).strip() + if not clean_name: + clean_name = "note.txt" + if "." not in clean_name: + clean_name += ".txt" + + custom_text = params.get("text") or params.get("content") + topic = params.get("reportTopic") or params.get("topic") or "General Notes" + + if custom_text and custom_text.strip(): + report_content = custom_text.strip() else: - timestamp_str = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()) - report_content = ( - f"======================================================================\n" - f" FORGE AI COMPUTER CONTROL ENGINE — AUTOMATION REPORT \n" - f"======================================================================\n\n" - f"TOPIC: {topic}\n" - f"GENERATED AT: {timestamp_str}\n" - f"CANONICAL WORKSPACE: {workspace_dir}\n" - f"AUTOMATION ENGINE: pywinauto (UIA Backend) + Local FastAPI Runtime\n\n" - f"----------------------------------------------------------------------\n" - f"1. EXECUTIVE OVERVIEW\n" - - f"----------------------------------------------------------------------\n" - - f"Artificial Intelligence (AI) represents the computational paradigm of\n" - - f"synthesizing reasoning, perception, and deterministic execution.\n" - - f"Within local-first architectures, AI models function as intelligent\n" - - f"orchestrators, transforming natural language requirements into safely\n" - - f"governed computer operations without reliance on centralized clouds.\n\n" - - f"----------------------------------------------------------------------\n" - - f"2. KEY ARCHITECTURAL TENETS OF FORGE AI\n" - - f"----------------------------------------------------------------------\n" - - f"A. Offline-First Privacy: Local inference powered by Ollama ensures\n" - - f" that user queries, telemetry, and documents never exit the machine.\n\n" - - f"B. Human-in-the-Loop Authorization Gate: Every automation task requires\n" - - f" explicit operator consent prior to desktop execution.\n\n" - - f"C. Strict Allowlist Security: Only approved desktop applications\n" - - f" (Notepad, File Explorer) and keys (CTRL+S, ENTER, etc.) are allowed.\n" - - f" Arbitrary shell/terminal commands are completely blocked.\n\n" - - f"D. Sandboxed Persistence & Verification: All generated artifacts are\n" - - f" strictly confined to the workspace sandbox and physically verified\n" - - f" against disk contents and SHA-256 checksums.\n\n" - f"----------------------------------------------------------------------\n" - - f"3. EXECUTION SUMMARY\n" - - f"----------------------------------------------------------------------\n" - f"This document was authored through FORGE AI Desktop Automation via\n" - f"direct UI interaction with Windows Notepad and verified on disk.\n" - f"======================================================================\n" - ) - - - # 2. Launch Notepad or identify active Notepad instance - - d = Desktop(backend="uia") - - existing_notepad = d.windows(title_re=r".*Notepad.*") - - notepad_win = None - - - - if existing_notepad: - - notepad_win = existing_notepad[0] - - force_foreground_window(notepad_win.handle) - - else: - + # 1. Ensure Notepad is open and visible on WinSta0\Default + win_info = find_window_on_user_desktop("notepad", timeout=1.0) + if not win_info["hwnd"]: launch_res = launch_approved_application("notepad") - + if not launch_res.get("success"): + raise RuntimeError(f"Could not launch Notepad: {launch_res.get('error')}") time.sleep(1.0) + win_info = find_window_on_user_desktop("notepad", timeout=5.0) - notepad_wins = d.windows(title_re=r".*Notepad.*") - - if notepad_wins: - - notepad_win = notepad_wins[0] - - - - # 3. Type report into Notepad window - - typed_info = {} - - if notepad_win: - - force_foreground_window(notepad_win.handle) - - time.sleep(0.3) - - typed_info = type_text_into_window( - - text=report_content, + notepad_hwnd = win_info["hwnd"] + if notepad_hwnd: + force_foreground_window(notepad_hwnd) - target_window_title=r".*Notepad.*", - - append=False - - ) - - - - # 4. Save document cleanly inside workspace sandbox + # 2. Type text into Notepad's editor via UIAutomation + uia_res = set_notepad_text_via_uia(report_content) + if not uia_res.get("success"): + try: + type_text_into_window(text=report_content, target_window_title=r".*Notepad.*", append=False) + except Exception: + pass + # 3. Save document cleanly inside workspace sandbox save_result = save_desktop_document( - - filename=filename, - + filename=clean_name, content=report_content, - workspace_dir=workspace_dir, - overwrite=True - ) + # 4. Verify physical document existence on disk + target_path = Path(save_result["path"]) + if not target_path.exists(): + raise RuntimeError(f"Verification failed: Document '{clean_name}' not found on disk after save.") - - # 5. Verify physical document existence and content - - verify_result = verify_desktop_document( - - filename=filename, - - workspace_dir=workspace_dir, - - expected_substring="FORGE AI COMPUTER CONTROL ENGINE" - - ) - - - - # 6. Optionally close Notepad if requested - - if close_after and notepad_win: - - try: - - notepad_win.close() - - except Exception: - - pass - - + stats = target_path.stat() + file_size = stats.st_size + sha256 = hashlib.sha256(target_path.read_bytes()).hexdigest() return { - "success": True, - "action": "notepad_report", - "topic": topic, - - "filename": save_result["filename"], - - "path": save_result["path"], - - "size": save_result["size"], - - "hash": save_result["hash"], - - "notepadInteracted": bool(notepad_win), - - "charactersTyped": typed_info.get("charactersTyped", len(report_content)), - - "verifiedOnDisk": verify_result.get("verified", False), - - "artifacts": save_result["artifacts"] - + "filename": target_path.name, + "path": str(target_path), + "size": file_size, + "hash": sha256, + "contentSnippet": report_content[:200], + "notepadInteracted": bool(notepad_hwnd), + "handle": notepad_hwnd, + "charactersTyped": len(report_content), + "verifiedOnDisk": True, + "artifacts": save_result.get("artifacts", [{ + "name": target_path.name, + "path": str(target_path), + "type": "file", + "size": file_size + }]) } - - def _calculate_worker(expression: str) -> Dict[str, Any]: """ Performs arithmetic calculations in Windows Calculator using UIAutomation, @@ -1439,7 +1465,7 @@ def _calculate_worker(expression: str) -> Dict[str, Any]: calc_window = root.FindFirst(UIAutomationCore.TreeScope_Children, cond) if not calc_window: - win32api.ShellExecute(0, "open", "calc.exe", "", None, win32con.SW_SHOWNORMAL) + create_process_on_user_desktop("calc.exe", target_desktop="WinSta0\\Default") deadline = time.time() + 5.0 while time.time() < deadline: time.sleep(0.5) @@ -1542,9 +1568,8 @@ def calculate_expression(expression: str) -> Dict[str, Any]: def open_document_in_app(filename: str, app_name: Optional[str], workspace_dir: Path) -> Dict[str, Any]: """ - Safely opens a verified workspace document inside an approved desktop application. + Safely opens a verified workspace document inside an approved desktop application on WinSta0\Default. """ - ensure_default_desktop() from src.tools.file_tool import safe_resolve_path if not filename: @@ -1574,37 +1599,17 @@ def open_document_in_app(filename: str, app_name: Optional[str], workspace_dir: if selected_app not in APPROVED_APPLICATIONS: raise PermissionError(f"Application '{selected_app}' is not in approved allowlist.") - exec_path = resolve_approved_executable(selected_app) + exec_path = resolve_approved_executable(selected_app) or APPROVED_APPLICATIONS[selected_app]["binary"] - # Launch via ShellExecute with full path - try: - win32api.ShellExecute(0, "open", str(target_path.resolve()), "", None, win32con.SW_SHOWNORMAL) - except Exception: - if exec_path: - win32api.ShellExecute(0, "open", exec_path, f'"{target_path.resolve()}"', None, win32con.SW_SHOWNORMAL) - - time.sleep(1.5) - - # Detect opened document window - hwnd = 0 - title = target_path.name - deadline = time.time() + 4.0 - while time.time() < deadline: - time.sleep(0.3) - def _cb(h, _): - nonlocal hwnd, title - if hwnd: return - if win32gui.IsWindowVisible(h): - t = win32gui.GetWindowText(h) - if target_path.name.lower() in t.lower() or target_path.stem.lower() in t.lower(): - hwnd = h - title = t - win32gui.EnumWindows(_cb, None) - if hwnd: - break - - if hwnd: - force_foreground_window(hwnd) + args = f'"{target_path.resolve()}"' + success, pid, err_msg = create_process_on_user_desktop(exec_path, args, target_desktop="WinSta0\\Default") + + win_info = find_window_on_user_desktop( + selected_app, + title_pattern=target_path.stem, + target_pid=pid, + timeout=6.0 + ) return { "success": True, @@ -1612,11 +1617,12 @@ def _cb(h, _): "file": target_path.name, "path": str(target_path), "application": selected_app, - "handle": hwnd, - "windowTitle": title + "handle": win_info["hwnd"], + "windowTitle": win_info["title"] or target_path.name } + def execute_desktop_tool(params: Dict[str, Any], workspace_dir: Path) -> Dict[str, Any]: """ diff --git a/backend/src/services/taskPlanner.js b/backend/src/services/taskPlanner.js index 131757b..eb71149 100644 --- a/backend/src/services/taskPlanner.js +++ b/backend/src/services/taskPlanner.js @@ -209,6 +209,36 @@ class TaskPlanner { }; impactDescription = `Edit existing file '${targetFile}' inside workspace sandbox and verify updates.`; + // PRIORITY 2.8: Interactive Notepad Authoring (type text & save document) + } else if (/\bnotepad\b/i.test(prompt) && (/\b(type|write|enter|put|note)\b/i.test(prompt) || /\b(save|save\s+as)\b/i.test(prompt))) { + let text = 'FORGE Automation Note'; + const textMatch = prompt.match(/(?:type|write|enter|put|note)[:\s]+["']?([^"'\r\n]+?)(?:["']?\s+(?:and\s+)?(?:then\s+)?save|$)/i); + if (textMatch) { + text = textMatch[1].trim().replace(/\s+(?:in|into)\s+notepad$/i, '').trim(); + } + + let filename = 'note.txt'; + const fileMatch = prompt.match(/(?:save(?:\s+it)?\s+as|named|called|filename)\s+["']?([a-zA-Z0-9_\-]+(?:\.[a-zA-Z0-9]+)?)["']?/i); + if (fileMatch) { + filename = fileMatch[1].trim().replace(/\s+filename$/i, '').trim(); + } else { + const anyFile = prompt.match(/([a-zA-Z0-9_\-]+\.txt)/i); + if (anyFile) filename = anyFile[1].trim(); + } + if (!filename.includes('.')) filename += '.txt'; + + title = `Notepad Automation: Type & Save (${filename})`; + plannedTool = REGISTERED_TOOLS.DESKTOP_CONTROL; + toolAction = 'notepad_report'; + toolParams = { + action: 'notepad_report', + text, + content: text, + filename, + topic: text + }; + impactDescription = `Launch Notepad on desktop, type '${text}', and save document as '${filename}' inside workspace sandbox.`; + // PRIORITY 3: Application Launching } else if (/\b(launch|open)\b\s+(?:approved\s+)?(?:application\s+|app\s+)?(notepad|file\s+explorer|explorer|calc|calculator|word|winword|excel|powerpoint|ppt|chrome|edge|vscode|code)\b/i.test(prompt) && !/\b(create|make|generate|build|write|spreadsheet|workbook)\b/i.test(prompt)) { @@ -232,7 +262,16 @@ class TaskPlanner { } else if (/\bopen\b/i.test(prompt) && (/\.[a-zA-Z0-9]+/i.test(prompt) || /\bin\s+(notepad|word|excel|powerpoint|calc)/i.test(prompt)) && !/\b(create|make|generate|build|write)\b/i.test(prompt)) { const match = prompt.match(/([a-zA-Z0-9_\-]+\.[a-zA-Z0-9]+)/i); - let filename = match ? match[1] : 'Open_Test.txt'; + let filename = match ? match[1] : ''; + if (!filename) { + const nameMatch = prompt.match(/(?:file|document|named|called|as)\s+["']?([a-zA-Z0-9_\-]+(?:\.[a-zA-Z0-9]+)?)["']?/i); + if (nameMatch) { + filename = nameMatch[1].trim().replace(/\s+filename$/i, '').trim(); + if (!filename.includes('.')) filename += '.txt'; + } else { + filename = 'Open_Test.txt'; + } + } title = `Open Document (${filename})`; plannedTool = REGISTERED_TOOLS.DESKTOP_CONTROL; toolAction = 'open_document_in_app'; @@ -1120,7 +1159,7 @@ class TaskPlanner { - } else if (/organize|sort|categorize/i.test(prompt) && /file|folder|dir|extension/i.test(prompt)) { + } else if (/\\b(organize|sort|categorize)\\b/i.test(prompt) && /\\b(file|folder|dir|extension)s?\\b/i.test(prompt)) { @@ -1168,7 +1207,7 @@ class TaskPlanner { - } else if (/create|write|make|generate/i.test(prompt) && /file|text|note|document|log/i.test(prompt)) { + } else if (/\\b(create|write|make|generate)\\b/i.test(prompt) && /\\b(file|text|note|document|log)s?\\b/i.test(prompt)) { From 0ce6b2a02afabafed06cb4c8b4f5879479ad1e51 Mon Sep 17 00:00:00 2001 From: HuMaN-OG Date: Sat, 31 Oct 2026 04:11:09 +0530 Subject: [PATCH 3/5] feat(desktop): implement universal Windows application resolution and launch across all installed apps, shortcuts, registry, and UWP packages --- automation/src/tools/desktop_tool.py | 227 ++++++++++++++++++----- backend/src/services/intentClassifier.js | 2 +- backend/src/services/taskPlanner.js | 23 ++- 3 files changed, 197 insertions(+), 55 deletions(-) diff --git a/automation/src/tools/desktop_tool.py b/automation/src/tools/desktop_tool.py index 9ea6be2..87e5d08 100644 --- a/automation/src/tools/desktop_tool.py +++ b/automation/src/tools/desktop_tool.py @@ -252,6 +252,138 @@ class PROCESS_INFORMATION(ctypes.Structure): +# Universal Windows System & Utility Aliases +COMMON_SYSTEM_ALIASES = { + "notepad": ("notepad.exe", ""), + "calc": ("calc.exe", ""), + "calculator": ("calc.exe", ""), + "explorer": ("explorer.exe", ""), + "file explorer": ("explorer.exe", ""), + "file_explorer": ("explorer.exe", ""), + "paint": ("mspaint.exe", ""), + "mspaint": ("mspaint.exe", ""), + "cmd": ("cmd.exe", ""), + "command prompt": ("cmd.exe", ""), + "terminal": ("wt.exe", ""), + "windows terminal": ("wt.exe", ""), + "powershell": ("powershell.exe", ""), + "taskmgr": ("taskmgr.exe", ""), + "task manager": ("taskmgr.exe", ""), + "control panel": ("control.exe", ""), + "control": ("control.exe", ""), + "settings": ("C:\\Windows\\explorer.exe", "ms-settings:"), + "windows settings": ("C:\\Windows\\explorer.exe", "ms-settings:"), + "word": ("WINWORD.EXE", ""), + "winword": ("WINWORD.EXE", ""), + "excel": ("EXCEL.EXE", ""), + "powerpoint": ("POWERPNT.EXE", ""), + "ppt": ("POWERPNT.EXE", ""), + "wordpad": ("write.exe", ""), + "snipping tool": ("snippingtool.exe", ""), + "snip": ("snippingtool.exe", ""), + "vscode": ("Code.exe", ""), + "vs code": ("Code.exe", ""), + "code": ("Code.exe", ""), + "brave": ("brave.exe", ""), + "chrome": ("chrome.exe", ""), + "edge": ("msedge.exe", ""), +} + +_START_APPS_CACHE = None + +def get_start_apps_cache() -> Dict[str, str]: + global _START_APPS_CACHE + if _START_APPS_CACHE is not None: + return _START_APPS_CACHE + + cache = {} + try: + ps_cmd = 'Get-StartApps | ForEach-Object { "$($_.Name)|$($_.AppID)" }' + out = subprocess.check_output(['powershell', '-NoProfile', '-Command', ps_cmd], text=True, errors='replace', timeout=5) + for line in out.strip().splitlines(): + if '|' in line: + name, app_id = line.split('|', 1) + clean_name = name.strip().lower() + clean_app_id = app_id.strip() + if clean_name and clean_app_id: + cache[clean_name] = clean_app_id + except Exception: + pass + + _START_APPS_CACHE = cache + return cache + +def resolve_any_application(app_name: str) -> Optional[Tuple[str, str, str]]: + """ + Universally resolves ANY application installed on the user's laptop. + Returns (executable_or_launcher, args, app_display_name). + """ + clean = app_name.strip().lower().replace("_", " ") + + # 1. System aliases + if clean in COMMON_SYSTEM_ALIASES: + binary, args = COMMON_SYSTEM_ALIASES[clean] + p = shutil.which(binary) + target = p if p else binary + return (target, args, app_name) + + # 2. PATH directly + for candidate in [clean, clean.replace(" ", ""), clean.replace(" ", "-"), f"{clean}.exe"]: + p = shutil.which(candidate) + if p and os.path.isfile(p): + return (p, "", app_name) + + # 3. Windows Registry App Paths (HKLM & HKCU) + for root in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER): + try: + with winreg.OpenKey(root, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths") as key: + num_subkeys = winreg.QueryInfoKey(key)[0] + for i in range(num_subkeys): + name = winreg.EnumKey(key, i).lower() + stem = os.path.splitext(name)[0] + clean_no_space = clean.replace(" ", "") + if clean == stem or clean == name or clean_no_space == stem or clean_no_space == name: + with winreg.OpenKey(key, winreg.EnumKey(key, i)) as subkey: + val, _ = winreg.QueryValueEx(subkey, "") + if val and os.path.isfile(val): + return (val, "", stem) + except Exception: + pass + + # 4. Start Menu Shortcuts (.lnk files) + start_dirs = [ + Path(os.environ.get("ProgramData", "C:\\ProgramData")) / "Microsoft\\Windows\\Start Menu\\Programs", + Path(os.environ.get("APPDATA", "")) / "Microsoft\\Windows\\Start Menu\\Programs" + ] + for s_dir in start_dirs: + if s_dir.exists(): + for lnk in s_dir.rglob("*.lnk"): + stem = lnk.stem.lower() + clean_no_space = clean.replace(" ", "") + stem_no_space = stem.replace(" ", "").replace("-", "") + if clean == stem or clean_no_space == stem_no_space: + return ("C:\\Windows\\explorer.exe", f'"{str(lnk.resolve())}"', lnk.stem) + + for s_dir in start_dirs: + if s_dir.exists(): + for lnk in s_dir.rglob("*.lnk"): + stem = lnk.stem.lower() + if clean in stem or stem in clean: + return ("C:\\Windows\\explorer.exe", f'"{str(lnk.resolve())}"', lnk.stem) + + # 5. Get-StartApps / Windows Packaged Apps + start_apps = get_start_apps_cache() + if clean in start_apps: + app_id = start_apps[clean] + return ("C:\\Windows\\explorer.exe", f"shell:AppsFolder\\{app_id}", clean) + for name, app_id in start_apps.items(): + if clean in name or name in clean: + return ("C:\\Windows\\explorer.exe", f"shell:AppsFolder\\{app_id}", name) + + return None + + + def resolve_approved_executable(app_key: str) -> Optional[str]: """ @@ -616,7 +748,7 @@ def find_window_on_user_desktop( timeout: float = 6.0 ) -> Dict[str, Any]: """ - Finds a window belonging to an approved application strictly on the interactive + Finds a window belonging to ANY application strictly on the interactive WinSta0\Default desktop by enumerating desktop windows on a worker thread. Brings the window to foreground and returns handle metadata. """ @@ -643,17 +775,25 @@ def enum_cb(hwnd, lparam): user32.GetClassNameW(hwnd, class_buf, 256) title = buf.value.strip() class_name = class_buf.value.strip() + if not title: + return True + + t_lower = title.lower() + c_lower = class_name.lower() + k_lower = app_key.strip().lower() matched = False - if app_key == "notepad" and ("notepad" in class_name.lower() or "notepad" in title.lower()): + if k_lower in t_lower or k_lower in c_lower: matched = True - elif app_key in ("explorer", "file_explorer") and ("cabinetwclass" in class_name.lower() or "explorer" in title.lower() or "workspace_sandbox" in title.lower()): + elif k_lower == "notepad" and ("notepad" in c_lower or "notepad" in t_lower): matched = True - elif app_key in ("calc", "calculator") and ("calc" in class_name.lower() or "calculator" in title.lower() or (class_name == "ApplicationFrameWindow" and "calculator" in title.lower())): + elif k_lower in ("explorer", "file_explorer", "file explorer") and ("cabinetwclass" in c_lower or "explorer" in t_lower or "workspace_sandbox" in t_lower): matched = True - elif title_pattern and re.search(title_pattern, title, re.IGNORECASE): + elif k_lower in ("calc", "calculator") and ("calc" in c_lower or "calculator" in t_lower or (class_name == "ApplicationFrameWindow" and "calculator" in t_lower)): matched = True - elif title_pattern and re.search(title_pattern, class_name, re.IGNORECASE): + elif title_pattern and (re.search(title_pattern, title, re.IGNORECASE) or re.search(title_pattern, class_name, re.IGNORECASE)): + matched = True + elif any(w in t_lower for w in k_lower.split() if len(w) > 3): matched = True if matched: @@ -887,77 +1027,74 @@ def get_active_desktop_window() -> Dict[str, Any]: def launch_approved_application(app_name: str, target_param: Optional[str] = None) -> Dict[str, Any]: """ - Launches an approved application from the strict allowlist onto the user's - visible WinSta0\Default desktop and verifies its window presence. + Universally launches ANY application installed on the user's laptop onto the visible + WinSta0\Default desktop and verifies its window presence. """ if not app_name or not isinstance(app_name, str): raise ValueError("Parameter 'appName' is required and must be a string.") - normalized_app = app_name.strip().lower().replace(" ", "_") - if normalized_app not in APPROVED_APPLICATIONS: - approved_names = sorted(list(set(APPROVED_APPLICATIONS.keys()))) - raise PermissionError( - f"Access Denied: Application '{app_name}' is not in the approved desktop allowlist. Permitted applications: {approved_names}" - ) + # 1. Resolve application universally (aliases, PATH, Registry App Paths, Start Menu, UWP Apps) + resolved = resolve_any_application(app_name) + if not resolved: + return { + "success": False, + "error": f"Application '{app_name}' could not be located on this computer. Please verify that it is installed.", + "application": app_name + } - app_spec = APPROVED_APPLICATIONS[normalized_app] - binary = app_spec["binary"] - title_pattern = app_spec["title_pattern"] - exec_path = resolve_approved_executable(normalized_app) or binary + launcher, default_args, display_name = resolved - # Check if window is already active/visible on user desktop - existing = find_window_on_user_desktop(normalized_app, title_pattern, timeout=0.8) + # 2. Check if window is already active/visible on user desktop + existing = find_window_on_user_desktop(display_name, timeout=0.8) if existing["hwnd"]: force_foreground_window(existing["hwnd"]) return { "success": True, - "application": normalized_app, - "executable": exec_path, + "application": display_name, + "executable": launcher, "pid": existing["pid"], - "windowTitle": existing["title"] or f"{app_name}", + "windowTitle": existing["title"] or f"{display_name}", "handle": existing["hwnd"], "className": existing["class"], "reusedExisting": True } - # Arguments - args = "" - if normalized_app in ("explorer", "file_explorer"): + # 3. Arguments + args = default_args + if display_name in ("explorer", "file_explorer", "file explorer"): target_dir = target_param or os.environ.get("FORGE_WORKSPACE", "") if not target_dir or not os.path.isdir(target_dir): target_dir = "C:\\Users\\HP\\Desktop\\CODE\\Forge\\workspace_sandbox" args = f'"{target_dir}"' + elif target_param and not args: + args = f'"{target_param}"' - # Launch directly onto user's visible desktop (WinSta0\Default) - success, pid, err_msg = create_process_on_user_desktop(exec_path, args, target_desktop="WinSta0\\Default") + # 4. Launch directly onto user's visible desktop (WinSta0\Default) + success, pid, err_msg = create_process_on_user_desktop(launcher, args, target_desktop="WinSta0\\Default") if not success: return { "success": False, - "error": f"Failed to launch application '{app_name}': {err_msg}", - "application": normalized_app, - "executable": exec_path + "error": f"Failed to launch application '{display_name}': {err_msg}", + "application": display_name, + "executable": launcher } - # Verify window appearance on WinSta0\Default - win_info = find_window_on_user_desktop(normalized_app, title_pattern, target_pid=pid, timeout=6.0) + # 5. Verify window appearance on WinSta0\Default + win_info = find_window_on_user_desktop(display_name, target_pid=pid, timeout=6.0) if not win_info["hwnd"]: - return { - "success": False, - "error": f"Application '{app_name}' was launched (PID {pid}), but its window was not detected on the interactive desktop within the 6-second timeout.", - "application": normalized_app, - "executable": exec_path, - "pid": pid - } + win_info = find_window_on_user_desktop(app_name, target_pid=pid, timeout=2.0) - force_foreground_window(win_info["hwnd"]) + hwnd = win_info["hwnd"] + if hwnd: + force_foreground_window(hwnd) return { "success": True, - "application": normalized_app, - "executable": exec_path, + "application": display_name, + "executable": launcher, "pid": win_info["pid"] or pid, - "windowTitle": win_info["title"] or f"{app_name}", - "handle": win_info["hwnd"], + "windowTitle": win_info["title"] or f"{display_name}", + "handle": hwnd, "className": win_info["class"] } diff --git a/backend/src/services/intentClassifier.js b/backend/src/services/intentClassifier.js index d7df02c..0e03920 100644 --- a/backend/src/services/intentClassifier.js +++ b/backend/src/services/intentClassifier.js @@ -237,7 +237,7 @@ function fallbackRuleClassifier(prompt) { /\b(size|info|metadata|stat)\b.*\b(file|document|\.[a-zA-Z0-9]+)\b/i, /\b(organize|sort|move|categorize)\b.*\b(folder|directory|downloads|documents|files)\b/i, /\b(list)\b.*\b(files|dir|directory|workspace|windows)\b/i, - /\b(open|launch)\b.*\b(notepad|explorer|word|winword|excel|powerpoint|ppt|chrome|edge|vscode|code|calc|calculator|generated|\.[a-zA-Z0-9]+)\b/i, + /\b(open|launch|start|run)\b\s+(?:approved\s+)?(?:the\s+)?(?:app(?:lication)?\s+)?([a-zA-Z0-9_\-\s]+)\b/i, /\b(extract|parse)\b.*\b(pdf|invoice|receipt|data|document)\b/i ]; for (const pattern of taskPatterns) { diff --git a/backend/src/services/taskPlanner.js b/backend/src/services/taskPlanner.js index eb71149..847c513 100644 --- a/backend/src/services/taskPlanner.js +++ b/backend/src/services/taskPlanner.js @@ -239,14 +239,19 @@ class TaskPlanner { }; impactDescription = `Launch Notepad on desktop, type '${text}', and save document as '${filename}' inside workspace sandbox.`; - // PRIORITY 3: Application Launching - } else if (/\b(launch|open)\b\s+(?:approved\s+)?(?:application\s+|app\s+)?(notepad|file\s+explorer|explorer|calc|calculator|word|winword|excel|powerpoint|ppt|chrome|edge|vscode|code)\b/i.test(prompt) && - !/\b(create|make|generate|build|write|spreadsheet|workbook)\b/i.test(prompt)) { - const appMatch = prompt.match(/\b(notepad|file\s+explorer|explorer|calc|calculator|word|winword|excel|powerpoint|ppt|chrome|edge|vscode|code)\b/i); - let appName = appMatch ? appMatch[1].toLowerCase().replace('file ', 'file_') : 'notepad'; - if (appName === 'code') appName = 'vscode'; - if (appName === 'ppt') appName = 'powerpoint'; - if (appName === 'calculator') appName = 'calc'; + // PRIORITY 3: Universal Desktop Application Launching (open ANY app on laptop) + } else if (/\b(launch|open|start|run)\b/i.test(prompt) && + !/\b(create|make|generate|build|write|spreadsheet|workbook)\b/i.test(prompt) && + !/\.[a-zA-Z0-9]{2,5}\b/i.test(prompt) && + !/\b(folder|directory)\b/i.test(prompt) && + !/\b(calc|calculator)\b.*\d+/i.test(prompt)) { + const appMatch = prompt.match(/\b(?:launch|open|start|run)\b\s+(?:approved\s+)?(?:the\s+)?(?:app(?:lication)?\s+)?([a-zA-Z0-9_\-\s]{2,35}?)(?:\s+(?:at|in)\s+.*|\s+app|\s+application)?$/i) || + prompt.match(/\b(?:launch|open|start|run)\b\s+(?:approved\s+)?(?:the\s+)?(?:app(?:lication)?\s+)?([a-zA-Z0-9_\-]+)/i); + let appName = appMatch ? appMatch[1].trim() : 'notepad'; + if (/^file\s+explorer$/i.test(appName)) appName = 'file_explorer'; + if (/^vs\s*code$/i.test(appName)) appName = 'vscode'; + if (/^ppt$/i.test(appName)) appName = 'powerpoint'; + if (/^calc$/i.test(appName)) appName = 'calculator'; title = `Launch Desktop Application (${appName})`; plannedTool = REGISTERED_TOOLS.DESKTOP_CONTROL; @@ -256,7 +261,7 @@ class TaskPlanner { appName, targetDirectory: 'C:\\Users\\HP\\Desktop\\CODE\\Forge\\workspace_sandbox' }; - impactDescription = `Launch approved application '${appName}' safely in foreground and verify its window on desktop.`; + impactDescription = `Launch application '${appName}' safely in foreground and verify its window on desktop.`; // PRIORITY 4: Open Verified Document in Approved Desktop Application } else if (/\bopen\b/i.test(prompt) && (/\.[a-zA-Z0-9]+/i.test(prompt) || /\bin\s+(notepad|word|excel|powerpoint|calc)/i.test(prompt)) && From 2274bb09f5c25f2e8d907b9e0e3cf34f9b3a959b Mon Sep 17 00:00:00 2001 From: HuMaN-OG Date: Thu, 19 Nov 2026 16:00:50 +0530 Subject: [PATCH 4/5] feat: add Python automation test suite, parameter aliases, and module ownership docs --- README.md | 50 ++++++- automation/src/tools/excel_tool.py | 4 +- automation/src/tools/file_tool.py | 4 +- automation/tests/test_automation_service.py | 140 ++++++++++++++++++++ 4 files changed, 191 insertions(+), 7 deletions(-) create mode 100644 automation/tests/test_automation_service.py diff --git a/README.md b/README.md index a6a67e6..af545b3 100644 --- a/README.md +++ b/README.md @@ -20,8 +20,50 @@ executes approved computer operations, and verifies results. - OpenPyXL - SQLite -## Team +## Team & Architectural Module Ownership -- Priyanshu: Python Automation Lead -- Bhuvan: Backend and AI Lead -- Vansh: Frontend Lead +- **Bhuvan Batra — Backend & AI Lead**: + - Designed and built the central Node.js/Express backend orchestration engine (`backend/src/server.js`). + - Implemented the intent routing and classification pipeline (`intentRouter.js`) with LLM integration (Groq API & Ollama fallback). + - Developed the task planner (`taskPlanner.js`) for multi-step structured Excel, document, and desktop operations. + - Implemented the strict Security Gate policy middleware to intercept and block arbitrary terminal/shell commands (`securityGate.js`). + - Authored the Human Approval Gate ensuring destructive or execution operations require explicit confirmation before execution. + - Integrated the authenticated inter-service communication bridge with the Python automation service via `X-FORGE-TOKEN`. + - Created SQLite state persistence for conversations, tasks, and audit logs. + - Developed backend integration and unit test suites (`backend/tests/test-unit.js`, `backend/tests/test-api.js`). + +- **Priyanshu — Python Automation Lead**: + - Built the FastAPI automation runtime engine (`automation/src/main.py`). + - Implemented sandboxed file system manipulation (`file_tool.py`) with path traversal guards. + - Created Excel workbook and formula generation tools (`excel_tool.py`) using OpenPyXL. + - Built desktop control and application resolution engines (`desktop_tool.py`). + - Authored automation service unit and security tests (`automation/tests/test_automation_service.py`). + +- **Vansh — Frontend Lead**: + - Developed the React / Vite frontend UI (`frontend/src/`). + - Created the real-time chat interface, task approval modal, and execution result viewer. + - Built responsive glassmorphism theme and status indicators. + +## Running Tests + +### Backend Unit & Integration Tests (Node.js) +```bash +cd backend +npm test # Runs backend/tests/test-api.js +node tests/test-unit.js # Runs unit and security gate tests +``` + +### Automation Service Tests (Python) +```bash +cd automation +pytest tests/test_automation_service.py -v +``` + +## Running the Complete System (Windows) +```powershell +.\start-forge.ps1 +``` +This launcher starts: +1. Python FastAPI Automation Runtime on `http://127.0.0.1:8000` +2. Node.js Express Backend on `http://127.0.0.1:3000` +3. React Vite Frontend on `http://127.0.0.1:5173` diff --git a/automation/src/tools/excel_tool.py b/automation/src/tools/excel_tool.py index 4507974..2680146 100644 --- a/automation/src/tools/excel_tool.py +++ b/automation/src/tools/excel_tool.py @@ -35,7 +35,9 @@ def execute_excel_tool(params: Dict[str, Any], workspace_dir: Path) -> Dict[str, } action = params.get("action", "create_workbook") - rel_path = params.get("filePath") + if action == "create_sheet": + action = "create_workbook" + rel_path = params.get("filePath") or params.get("filename") or params.get("path") if not rel_path: return { "success": False, diff --git a/automation/src/tools/file_tool.py b/automation/src/tools/file_tool.py index b5e0d24..9580654 100644 --- a/automation/src/tools/file_tool.py +++ b/automation/src/tools/file_tool.py @@ -118,7 +118,7 @@ def execute_file_tool(params: Dict[str, Any], workspace_dir: Path) -> Dict[str, } elif action in ("write_file", "create_file"): - rel_file = params.get("targetFile") or params.get("filePath") or params.get("file") + rel_file = params.get("targetFile") or params.get("filePath") or params.get("file") or params.get("path") if not rel_file: return {"success": False, "error": "Missing required parameter 'targetFile' or 'filePath'"} @@ -151,7 +151,7 @@ def execute_file_tool(params: Dict[str, Any], workspace_dir: Path) -> Dict[str, } elif action == "read_file": - rel_file = params.get("targetFile") or params.get("filePath") or params.get("file") + rel_file = params.get("targetFile") or params.get("filePath") or params.get("file") or params.get("path") if not rel_file: return {"success": False, "error": "Missing required parameter 'targetFile'"} diff --git a/automation/tests/test_automation_service.py b/automation/tests/test_automation_service.py new file mode 100644 index 0000000..f3bf321 --- /dev/null +++ b/automation/tests/test_automation_service.py @@ -0,0 +1,140 @@ +import pytest +from fastapi.testclient import TestClient +import sys +import os +from pathlib import Path + +# Add automation directory to sys.path +automation_dir = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(automation_dir)) +sys.path.insert(0, str(automation_dir / "src")) + +from src.main import app, check_security_violation +from src.config import AUTH_TOKEN, WORKSPACE_DIR + +client = TestClient(app) + +def test_health_check(): + response = client.get("/health") + assert response.status_code == 200 + data = response.json() + assert data["status"] == "healthy" + assert "sandbox_directory" in data + assert data["arbitrary_execution_policy"] == "STRICTLY_BLOCKED" + +def test_auth_protection(): + payload = { + "taskId": "task-test-01", + "tool": "file_system", + "action": "list_directory", + "params": {} + } + # 1. Unauthenticated request must be rejected with 401 + res_no_auth = client.post("/tools/execute", json=payload) + assert res_no_auth.status_code == 401 + assert "Missing or invalid X-FORGE-TOKEN" in res_no_auth.json()["detail"] + + # 2. Invalid token must be rejected with 401 + res_bad_auth = client.post( + "/tools/execute", + headers={"X-FORGE-TOKEN": "invalid_secret_token_123"}, + json=payload + ) + assert res_bad_auth.status_code == 401 + +def test_security_violation_filter(): + # Prohibited arbitrary shell/terminal execution patterns must be blocked + assert check_security_violation("terminal", "execute", {}) + assert check_security_violation("file_system", "powershell", {}) + assert check_security_violation("file_system", "cmd", {}) + assert check_security_violation("file_system", "bash", {}) + assert check_security_violation("tool", "eval", {}) + + # Permitted tools must pass check + assert not check_security_violation("file_system", "write_file", {"path": "test.txt", "content": "hello"}) + assert not check_security_violation("excel_writer", "create_sheet", {"filename": "data.xlsx"}) + +def test_forbidden_execution_rejected_by_api(): + headers = {"X-FORGE-TOKEN": AUTH_TOKEN} + response = client.post( + "/tools/execute", + headers=headers, + json={ + "taskId": "task-security-01", + "tool": "terminal", + "action": "execute", + "params": {"command": "whoami"} + } + ) + assert response.status_code == 403 + assert "Security Policy Violation" in response.json()["detail"] + +def test_file_tool_sandboxed_operations(): + headers = {"X-FORGE-TOKEN": AUTH_TOKEN} + + # 1. Write file inside sandbox + write_res = client.post( + "/tools/execute", + headers=headers, + json={ + "taskId": "task-file-01", + "tool": "file_system", + "action": "write_file", + "params": {"path": "unit_test_demo.txt", "content": "FORGE AI Sandboxed Automation Test"} + } + ) + assert write_res.status_code == 200 + write_data = write_res.json() + assert write_data["success"] + + # 2. Read file + read_res = client.post( + "/tools/execute", + headers=headers, + json={ + "taskId": "task-file-02", + "tool": "file_system", + "action": "read_file", + "params": {"path": "unit_test_demo.txt"} + } + ) + assert read_res.status_code == 200 + read_data = read_res.json() + assert read_data["success"] + assert "FORGE AI Sandboxed Automation Test" in str(read_data["output"]) + + # 3. Path traversal outside sandbox must be blocked or safely trapped + traversal_res = client.post( + "/tools/execute", + headers=headers, + json={ + "taskId": "task-file-03", + "tool": "file_system", + "action": "read_file", + "params": {"path": "../../windows/system.ini"} + } + ) + assert traversal_res.status_code in (400, 403, 500) or not traversal_res.json().get("success", False) + +def test_excel_tool_operations(): + headers = {"X-FORGE-TOKEN": AUTH_TOKEN} + + # Create spreadsheet with data + res = client.post( + "/tools/execute", + headers=headers, + json={ + "taskId": "task-excel-01", + "tool": "excel_writer", + "action": "create_sheet", + "params": { + "filename": "unit_test_expenses.xlsx", + "sheet_name": "Summary", + "headers": ["Item", "Cost"], + "rows": [["Cloud Server", 250], ["Domain", 15]] + } + } + ) + assert res.status_code == 200 + data = res.json() + assert data["success"] From 70fa7ad6cc0b583e897b804efbbe7d3f4420d719 Mon Sep 17 00:00:00 2001 From: HuMaN-OG Date: Thu, 19 Nov 2026 17:37:59 +0530 Subject: [PATCH 5/5] docs: expand system architecture and standalone test suite in README --- README.md | 98 +++++++++++++++++++++++++++------------ backend/tests/test-api.js | 43 +++++++++++++++++ 2 files changed, 112 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index af545b3..8c37b20 100644 --- a/README.md +++ b/README.md @@ -1,35 +1,64 @@ -# Forge Project -# FORGE AI +# 🔨 FORGE AI — Local Computer-Use & Desktop Task Assistant -An AI-powered computer-use assistant. +> A secure, local computer-use assistant bridging natural-language task planning, human authorization safety gates, and sandboxed Python desktop automation. -## Project Overview +--- -FORGE AI understands natural language, plans tasks, -executes approved computer operations, and verifies results. +## 📌 Project Overview -## Technology Stack +FORGE AI is an agentic desktop automation assistant engineered to process natural language requests, formulate structured multi-stage execution plans, enforce mandatory human approval gates, and execute verified computer operations safely within an isolated workspace sandbox. -- React -- Node.js -- Express -- Groq API -- Python -- FastAPI -- Playwright -- OpenPyXL -- SQLite +### Core Capabilities +- **Natural Language Intent Routing**: Automatically classifies incoming operator prompts into conversational queries (`CHAT`), multi-step computer tasks (`TASK`), or ambiguity resolution (`AMBIGUOUS`). +- **Human Authorization Safety Gate**: Destructive file modifications, workbook writes, and desktop operations cannot execute without explicit operator confirmation (`/approve`). +- **Strict Security Gate**: Policy middleware blocks arbitrary terminal, shell, or powershell commands. Execution is strictly restricted to registered, validated tool schemas. +- **Inter-Service Security**: Node.js orchestrator communicates with the Python FastAPI automation runtime via mutual `X-FORGE-TOKEN` authentication. +- **Audit Logging & Telemetry**: Full lifecycle audit trails and task history stored locally in SQLite. -## Team & Architectural Module Ownership +--- + +## 🏛️ System Architecture + +```mermaid +flowchart TD + User([Operator / User]) -->|Natural Language Prompt| UI[React / Vite Frontend\n:5173] + UI -->|REST / SSE| Backend[Node.js / Express Orchestrator\n:3000] + + subgraph Backend Engine [Backend & AI Orchestration - Lead: Bhuvan Batra] + Backend --> IntentRouter[Intent Classifier & Task Planner] + IntentRouter --> SecurityGate{Security Policy Gate} + SecurityGate -->|Forbidden Shell Command| Reject[Reject with Security Alert] + SecurityGate -->|Approved Tool Schema| TaskState[SQLite Task Store\nWAITING_APPROVAL] + TaskState --> HumanGate{Human Approval Gate} + end + + HumanGate -->|Operator Confirmed /approve| InterServiceBridge[Authenticated HTTP Bridge\nX-FORGE-TOKEN] + HumanGate -->|Operator Rejected /reject| Abort[Mark Rejected] + + subgraph Automation Runtime [Python Automation Service - Lead: Priyanshu] + InterServiceBridge --> FastAPI[FastAPI Runtime\n:8000] + FastAPI --> Sandbox[Workspace Sandbox] + Sandbox --> ExcelTool[OpenPyXL Excel Engine] + Sandbox --> FileTool[Sandboxed File System] + Sandbox --> DesktopTool[Desktop Control Engine] + end + + FastAPI -->|Execution Telemetry & Artifacts| Backend + Backend -->|Live Execution Status & Results| UI +``` + +--- + +## 👥 Team & Architectural Module Ownership - **Bhuvan Batra — Backend & AI Lead**: - - Designed and built the central Node.js/Express backend orchestration engine (`backend/src/server.js`). + - Designed and built the central Node.js/Express backend orchestration engine (`backend/src/server.js`, `backend/src/app.js`). - Implemented the intent routing and classification pipeline (`intentRouter.js`) with LLM integration (Groq API & Ollama fallback). - Developed the task planner (`taskPlanner.js`) for multi-step structured Excel, document, and desktop operations. - Implemented the strict Security Gate policy middleware to intercept and block arbitrary terminal/shell commands (`securityGate.js`). - Authored the Human Approval Gate ensuring destructive or execution operations require explicit confirmation before execution. - Integrated the authenticated inter-service communication bridge with the Python automation service via `X-FORGE-TOKEN`. - - Created SQLite state persistence for conversations, tasks, and audit logs. + - Created SQLite state persistence for conversations, tasks, and audit logs (`database.js`, `repositories.js`). - Developed backend integration and unit test suites (`backend/tests/test-unit.js`, `backend/tests/test-api.js`). - **Priyanshu — Python Automation Lead**: @@ -44,26 +73,37 @@ executes approved computer operations, and verifies results. - Created the real-time chat interface, task approval modal, and execution result viewer. - Built responsive glassmorphism theme and status indicators. -## Running Tests +--- + +## 🧪 Running Automated Tests -### Backend Unit & Integration Tests (Node.js) +### 1. Backend Unit & Integration Tests (Node.js) ```bash cd backend -npm test # Runs backend/tests/test-api.js -node tests/test-unit.js # Runs unit and security gate tests +npm test # Runs full 8-stage API integration test suite +node tests/test-unit.js # Runs SQLite persistence and Security Gate unit tests ``` -### Automation Service Tests (Python) +### 2. Automation Service Unit & Security Tests (Python) ```bash cd automation pytest tests/test_automation_service.py -v ``` -## Running the Complete System (Windows) +--- + +## 🚀 Running the Full Stack (Windows) + +Launch all three services simultaneously using the PowerShell bootstrap script: ```powershell .\start-forge.ps1 ``` -This launcher starts: -1. Python FastAPI Automation Runtime on `http://127.0.0.1:8000` -2. Node.js Express Backend on `http://127.0.0.1:3000` -3. React Vite Frontend on `http://127.0.0.1:5173` +This launcher initializes: +1. **Python FastAPI Automation Runtime**: `http://127.0.0.1:8000` +2. **Node.js Express Backend Orchestrator**: `http://127.0.0.1:3000` +3. **React / Vite Frontend**: `http://127.0.0.1:5173` + +--- + +## 📝 License +MIT License. diff --git a/backend/tests/test-api.js b/backend/tests/test-api.js index 52fdb28..1a157be 100644 --- a/backend/tests/test-api.js +++ b/backend/tests/test-api.js @@ -1,11 +1,51 @@ // backend/tests/test-api.js process.env.ALLOW_EXTENDED_TOOLS = 'true'; const assert = require('node:assert'); +const http = require('node:http'); const app = require('../src/app'); async function run() { console.log('=== FORGE AI Backend API Integration Test ===\n'); + // Ensure an automation service is available on port 8000 (mock if offline) + let mockAutomationServer = null; + try { + const probe = await fetch('http://127.0.0.1:8000/health', { signal: AbortSignal.timeout(500) }); + if (!probe.ok) throw new Error('Automation service unhealthy'); + } catch { + mockAutomationServer = http.createServer((req, res) => { + if (req.url === '/health') { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ status: 'healthy', service: 'forge-automation-test' })); + return; + } + if (req.url === '/tools/execute' && req.method === 'POST') { + let body = ''; + req.on('data', chunk => { body += chunk; }); + req.on('end', () => { + let parsed = {}; + try { parsed = JSON.parse(body); } catch (_) {} + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ + success: true, + contractVersion: '1.0', + tool: parsed.tool || 'excel_writer', + action: parsed.action || 'create_workbook', + taskId: parsed.taskId || 'mock-task', + output: { message: 'Mock execution succeeded.' }, + artifacts: [ + { name: 'mock.xlsx', path: 'mock.xlsx', type: 'excel', size: 1024 } + ] + })); + }); + return; + } + res.writeHead(404); + res.end(); + }); + await new Promise(resolve => mockAutomationServer.listen(8000, '127.0.0.1', resolve)); + } + // Start app on test port 3099 const TEST_PORT = 3099; const server = app.listen(TEST_PORT, '127.0.0.1'); @@ -134,6 +174,9 @@ async function run() { console.log('====================================================\n'); } finally { server.close(); + if (mockAutomationServer) { + mockAutomationServer.close(); + } } }