suna/backend/admin/api.py

70 lines
2.6 KiB
Python

from fastapi import APIRouter, HTTPException, Depends
from typing import Optional, Dict
from utils.auth_utils import verify_admin_api_key
from utils.suna_default_agent_service import SunaDefaultAgentService
from utils.logger import logger
from utils.config import config, EnvMode
from dotenv import load_dotenv, set_key, find_dotenv, dotenv_values
router = APIRouter(prefix="/admin", tags=["admin"])
@router.post("/suna-agents/install-user/{account_id}")
async def admin_install_suna_for_user(
account_id: str,
replace_existing: bool = False,
_: bool = Depends(verify_admin_api_key)
):
logger.debug(f"Admin installing Suna agent for user: {account_id}")
service = SunaDefaultAgentService()
agent_id = await service.install_suna_agent_for_user(account_id, replace_existing)
if agent_id:
return {
"success": True,
"message": f"Successfully installed Suna agent for user {account_id}",
"agent_id": agent_id
}
else:
raise HTTPException(
status_code=500,
detail=f"Failed to install Suna agent for user {account_id}"
)
@router.get("/env-vars")
def get_env_vars() -> Dict[str, str]:
"""Get environment variables (local mode only)."""
if config.ENV_MODE != EnvMode.LOCAL:
raise HTTPException(status_code=403, detail="Env vars management only available in local mode")
try:
env_path = find_dotenv()
if not env_path:
logger.error("Could not find .env file")
return {}
return dotenv_values(env_path)
except Exception as e:
logger.error(f"Failed to get env vars: {e}")
raise HTTPException(status_code=500, detail=f"Failed to get env variables: {e}")
@router.post("/env-vars")
def save_env_vars(request: Dict[str, str]) -> Dict[str, str]:
"""Save environment variables (local mode only)."""
if config.ENV_MODE != EnvMode.LOCAL:
raise HTTPException(status_code=403, detail="Env vars management only available in local mode")
try:
env_path = find_dotenv()
if not env_path:
raise HTTPException(status_code=500, detail="Could not find .env file")
for key, value in request.items():
set_key(env_path, key, value)
load_dotenv(override=True)
logger.debug(f"Env variables saved successfully: {request}")
return {"message": "Env variables saved successfully"}
except Exception as e:
logger.error(f"Failed to save env variables: {e}")
raise HTTPException(status_code=500, detail=f"Failed to save env variables: {e}")