Agent Mode Setup

← Back to Alpanzo

Agent Mode enables Alpanzo to securely interact with your local computer, allowing it to create files, manage directories, and run terminal commands. Follow the steps below to establish the connection bridge.

1. Install Python Dependencies

Ensure you have Python installed on your computer. Open your terminal or command prompt and install the required packages for the web server:

pip install flask flask-cors

2. Create the Bridge Script

Create a new file named agent_bridge.py in the folder where you want Alpanzo to operate. Copy and paste the following secure bridge code into it:

Note: When you run this script, it will automatically create an alpanzo_workspace folder. The AI agent is completely restricted to this folder and cannot modify files outside of it, ensuring your system remains safe.

import os
import subprocess
import shutil
import re
from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app) # Allow cross-origin to permit Alpanzo's frontend to talk to this API

# IMPORTANT: Set this to a highly secure password.
# It must exactly match the "Bridge Password" setting in Alpanzo.
PASSWORD = "supersecretpassword"

# Create an isolated workspace directory to protect the rest of your system
BASE_DIR = os.path.abspath("./alpanzo_workspace")
os.makedirs(BASE_DIR, exist_ok=True)

def get_safe_path(requested_path):
    target = os.path.abspath(os.path.join(BASE_DIR, requested_path))
    if os.path.commonpath([BASE_DIR, target]) != BASE_DIR:
        raise PermissionError(f"Security Alert: Path traversal detected. Access to '{requested_path}' is denied.")
    return target

@app.route('/execute', methods=['POST'])
def execute():
    data = request.json
    if not data or data.get('password') != PASSWORD:
        return jsonify({"error": "Unauthorized. Invalid password."}), 401
    
    tool = data.get('tool')
    arg = data.get('arg', '')
    content = data.get('content', '')

    try:
        if tool == 'RUN':
            if ".." in arg or arg.startswith("/") or arg.startswith("\\"):
                return jsonify({"error": "Action Blocked: Command contains forbidden path traversal characters."}), 403
            result = subprocess.run(arg, shell=True, capture_output=True, text=True, cwd=BASE_DIR, timeout=60)
            out = (result.stdout + result.stderr).strip()
            if len(out) > 3000:
                out = out[:1400] + f"\n\n...[OUTPUT TRUNCATED]...\n\n" + out[-1400:]
            return jsonify({"output": out or "Command executed successfully (no output)."})
        elif tool == 'READ':
            with open(get_safe_path(arg), 'r', encoding='utf-8') as f: return jsonify({"output": f.read()})
        elif tool == 'WRITE':
            path = get_safe_path(arg)
            os.makedirs(os.path.dirname(path), exist_ok=True)
            with open(path, 'w', encoding='utf-8') as f: f.write(content)
            return jsonify({"output": f"Successfully wrote to {arg}"})
        elif tool == 'MKDIR':
            os.makedirs(get_safe_path(arg), exist_ok=True)
            return jsonify({"output": f"Created directory {arg}"})
        elif tool == 'DELETE':
            path = get_safe_path(arg)
            shutil.rmtree(path) if os.path.isdir(path) else os.remove(path)
            return jsonify({"output": f"Deleted {arg}"})
        elif tool == 'PYTHON':
            script_path = os.path.join(BASE_DIR, 'script.py')
            with open(script_path, 'w', encoding='utf-8') as f:
                f.write(content)
            out = ""
            for _ in range(3):
                result = subprocess.run(['python', 'script.py'], capture_output=True, text=True, cwd=BASE_DIR, timeout=60)
                out = (result.stdout + result.stderr).strip()
                if result.returncode != 0 and "ModuleNotFoundError: No module named" in out:
                    match = re.search(r"ModuleNotFoundError: No module named '([^']+)'", out)
                    if match:
                        subprocess.run(['python', '-m', 'pip', 'install', match.group(1)], capture_output=True)
                        continue
                break
            if len(out) > 3000:
                out = out[:1400] + f"\n\n...[OUTPUT TRUNCATED]...\n\n" + out[-1400:]
            return jsonify({"output": out or "Python script executed successfully (no output)."})
        else:
            return jsonify({"error": f"Unknown tool: {tool}"}), 400
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    app.run(port=5000, debug=False)

3. Start the Server

Run the script you just created to start the local bridge. Keep this terminal window open.

python agent_bridge.py

4. Expose the Server with Ngrok

Open a new terminal window and start Ngrok to securely expose your local port 5000 to the internet.

ngrok http 5000

5. Connect and Initialize

1. Copy the secure https://...ngrok-free.app URL that Ngrok generated in your terminal.

2. Return to Alpanzo, open Settings > Agent Mode, paste the URL, enter your password, and hit save.

3. Go to the chat and type /agent init.alpanzo to activate your agent.


Launch Alpanzo