initial commit heh

This commit is contained in:
timka123 committed 2026-11-07 22:34:12 +03:00
commit 5eea9d0f2c
78 files changed
+11181

No files matched your search

+78
View File
@@ -0,0 +1,78 @@
"""Example custom extension: Quick Scratchpad & Local Notes.
Shows how easy it is to write and drop a new extension into HomeAgent.
Any file with @tool decorated functions in extensions/ is automatically discovered!
"""
import json
from pathlib import Path
from typing import Optional
from homeagent.tools.base import tool
NOTES_FILE = Path("data") / "scratchpad_notes.json"
def _read_notes() -> dict[str, str]:
if not NOTES_FILE.exists():
return {}
try:
with open(NOTES_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
return {}
def _save_notes(notes: dict[str, str]) -> None:
NOTES_FILE.parent.mkdir(parents=True, exist_ok=True)
with open(NOTES_FILE, "w", encoding="utf-8") as f:
json.dump(notes, f, ensure_ascii=False, indent=2)
@tool(
name="save_note",
description="Сохранить локальную текстовую заметку с уникальным заголовком.",
)
def save_note(title: str, content: str) -> str:
"""Сохранение заметки в блокнот.
Args:
title: Заголовок заметки
content: Содержимое заметки
"""
notes = _read_notes()
notes[title.strip()] = content.strip()
_save_notes(notes)
return f"Заметка '{title}' успешно сохранена."
@tool(
name="get_note",
description="Прочитать сохраненную локальную заметку по ее заголовку.",
)
def get_note(title: str) -> str:
"""Чтение заметки.
Args:
title: Заголовок заметки
"""
notes = _read_notes()
content = notes.get(title.strip())
if content is None:
return f"Заметка с заголовком '{title}' не найдена."
return f"**{title}**:\n{content}"
@tool(
name="list_notes",
description="Показать список всех сохраненных локальных заметок.",
)
def list_notes() -> str:
"""Список всех заметок."""
notes = _read_notes()
if not notes:
return "Список заметок пуст."
lines = ["Сохраненные заметки:"]
for title in notes.keys():
lines.append(f"- {title}")
return "\n".join(lines)
+33
View File
@@ -0,0 +1,33 @@
"""Gitea extension package for HomeAgent."""
from extensions.gitea.tools import (
gitea_add_issue_comment,
gitea_create_branch,
gitea_create_issue,
gitea_create_pull_request,
gitea_get_file_or_dir,
gitea_get_issue,
gitea_get_repo,
gitea_list_branches,
gitea_list_issues,
gitea_list_pull_requests,
gitea_list_repos,
gitea_save_file,
gitea_search_repos,
)
__all__ = [
"gitea_list_repos",
"gitea_search_repos",
"gitea_get_repo",
"gitea_get_file_or_dir",
"gitea_save_file",
"gitea_list_branches",
"gitea_create_branch",
"gitea_list_issues",
"gitea_get_issue",
"gitea_create_issue",
"gitea_add_issue_comment",
"gitea_list_pull_requests",
"gitea_create_pull_request",
]
+237
View File
@@ -0,0 +1,237 @@
"""Asynchronous Gitea / Forgejo REST API v1 Client."""
import base64
import logging
from typing import Any, Optional
import httpx
from homeagent.config import get_settings
logger = logging.getLogger(__name__)
class GiteaClient:
"""Async Client for Gitea / Forgejo REST API v1."""
def __init__(
self,
base_url: Optional[str] = None,
token: Optional[str] = None,
) -> None:
settings = get_settings()
raw_url = (base_url or settings.GITEA_URL or "https://git.timka.su").rstrip("/")
if not raw_url.endswith("/api/v1"):
self.api_url = f"{raw_url}/api/v1"
else:
self.api_url = raw_url
self.web_url = raw_url.replace("/api/v1", "")
self.token = (
token
or (settings.GITEA_TOKEN.get_secret_value() if settings.GITEA_TOKEN else "")
)
def is_configured(self) -> bool:
return bool(self.token)
def _get_headers(self) -> dict[str, str]:
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
}
if self.token:
headers["Authorization"] = f"token {self.token}"
return headers
async def _request(
self,
method: str,
endpoint: str,
params: Optional[dict[str, Any]] = None,
json_data: Optional[dict[str, Any]] = None,
) -> Any:
url = f"{self.api_url}/{endpoint.lstrip('/')}"
headers = self._get_headers()
async with httpx.AsyncClient(timeout=25.0) as client:
response = await client.request(
method=method,
url=url,
headers=headers,
params=params,
json=json_data,
)
if response.status_code == 204 or not response.content:
return None
if response.is_error:
error_body = response.text
logger.error("Gitea API error %d on %s: %s", response.status_code, url, error_body)
raise RuntimeError(f"Gitea API error ({response.status_code}): {error_body}")
return response.json()
async def get_current_user(self) -> dict[str, Any]:
"""Get profile of authenticated user."""
return await self._request("GET", "user")
async def list_user_repos(self, limit: int = 30) -> list[dict[str, Any]]:
"""List repositories accessible to the authenticated user."""
return await self._request("GET", "user/repos", params={"limit": limit})
async def search_repos(self, query: str, limit: int = 15) -> list[dict[str, Any]]:
"""Search repositories by keyword."""
data = await self._request("GET", "repos/search", params={"q": query, "limit": limit})
return data.get("data", []) if isinstance(data, dict) else data
async def get_repo(self, owner: str, repo: str) -> dict[str, Any]:
"""Get repository details."""
return await self._request("GET", f"repos/{owner}/{repo}")
async def get_contents(
self,
owner: str,
repo: str,
filepath: str = "",
ref: Optional[str] = None,
) -> Any:
"""Get contents of a file or directory in a repository."""
params = {}
if ref:
params["ref"] = ref
endpoint = f"repos/{owner}/{repo}/contents/{filepath.lstrip('/')}"
return await self._request("GET", endpoint, params=params)
async def create_or_update_file(
self,
owner: str,
repo: str,
filepath: str,
content: str,
commit_message: str,
branch: Optional[str] = None,
) -> dict[str, Any]:
"""Create or update file in repository (Vibecoding)."""
clean_path = filepath.lstrip("/")
b64_content = base64.b64encode(content.encode("utf-8")).decode("utf-8")
# Check if file exists to get SHA for update
existing_sha = None
try:
existing = await self.get_contents(owner, repo, clean_path, ref=branch)
if isinstance(existing, dict) and "sha" in existing:
existing_sha = existing["sha"]
except Exception:
# File does not exist yet
pass
payload: dict[str, Any] = {
"content": b64_content,
"message": commit_message,
}
if branch:
payload["branch"] = branch
if existing_sha:
# Update existing file
payload["sha"] = existing_sha
return await self._request("PUT", f"repos/{owner}/{repo}/contents/{clean_path}", json_data=payload)
else:
# Create new file
return await self._request("POST", f"repos/{owner}/{repo}/contents/{clean_path}", json_data=payload)
async def list_branches(self, owner: str, repo: str) -> list[dict[str, Any]]:
"""List branches in repository."""
return await self._request("GET", f"repos/{owner}/{repo}/branches")
async def create_branch(
self,
owner: str,
repo: str,
new_branch: str,
old_ref: Optional[str] = None,
) -> dict[str, Any]:
"""Create a new branch from an existing ref/branch."""
payload: dict[str, Any] = {"new_branch_name": new_branch}
if old_ref:
payload["old_ref_name"] = old_ref
return await self._request("POST", f"repos/{owner}/{repo}/branches", json_data=payload)
async def list_issues(
self,
owner: str,
repo: str,
state: str = "open",
limit: int = 20,
) -> list[dict[str, Any]]:
"""List issues for a repository."""
return await self._request(
"GET",
f"repos/{owner}/{repo}/issues",
params={"state": state, "limit": limit},
)
async def get_issue(self, owner: str, repo: str, index: int) -> dict[str, Any]:
"""Get issue details by index."""
return await self._request("GET", f"repos/{owner}/{repo}/issues/{index}")
async def create_issue(
self,
owner: str,
repo: str,
title: str,
body: str = "",
) -> dict[str, Any]:
"""Create a new issue."""
return await self._request(
"POST",
f"repos/{owner}/{repo}/issues",
json_data={"title": title, "body": body},
)
async def add_issue_comment(
self,
owner: str,
repo: str,
index: int,
comment: str,
) -> dict[str, Any]:
"""Add a comment to an issue or pull request."""
return await self._request(
"POST",
f"repos/{owner}/{repo}/issues/{index}/comments",
json_data={"body": comment},
)
async def list_pull_requests(
self,
owner: str,
repo: str,
state: str = "open",
limit: int = 20,
) -> list[dict[str, Any]]:
"""List pull requests for a repository."""
return await self._request(
"GET",
f"repos/{owner}/{repo}/pulls",
params={"state": state, "limit": limit},
)
async def create_pull_request(
self,
owner: str,
repo: str,
title: str,
head: str,
base: str = "main",
body: str = "",
) -> dict[str, Any]:
"""Create a new pull request."""
payload = {
"title": title,
"head": head,
"base": base,
"body": body,
}
return await self._request("POST", f"repos/{owner}/{repo}/pulls", json_data=payload)
+580
View File
@@ -0,0 +1,580 @@
"""Gitea tools exposed to HomeAgent and Gemini for repository interaction and vibecoding."""
import base64
import logging
from typing import Optional
from extensions.gitea.client import GiteaClient
from homeagent.config import get_settings
from homeagent.tools.base import tool
logger = logging.getLogger(__name__)
_client: Optional[GiteaClient] = None
def get_gitea_client() -> GiteaClient:
global _client
if _client is None:
_client = GiteaClient()
return _client
@tool(
name="gitea_list_repos",
description="Получить список доступных репозиториев текущего пользователя в Gitea (git.timka.su).",
)
async def gitea_list_repos(limit: int = 30) -> str:
"""Список репозиториев в Gitea.
Args:
limit: Максимальное количество репозиториев (по умолчанию 30)
"""
settings = get_settings()
if not settings.GITEA_ENABLED:
return "Интеграция с Gitea отключена в настройках (GITEA_ENABLED=False)."
client = get_gitea_client()
if not client.is_configured():
return f"Gitea не настроена. Укажите GITEA_TOKEN в файле .env (инстанс: {client.web_url})"
try:
repos = await client.list_user_repos(limit=limit)
if not repos:
return "Репозитории не найдены."
lines = [f"Доступные репозитории в Gitea ({len(repos)}):"]
for repo in repos:
full_name = repo.get("full_name") or repo.get("name", "")
html_url = repo.get("html_url", "")
desc = repo.get("description") or "Без описания"
default_branch = repo.get("default_branch", "main")
is_private = "🔒 Приватный" if repo.get("private") else "🌐 Публичный"
stars = repo.get("stars_count", 0)
open_issues = repo.get("open_issues_count", 0)
lines.append(
f"- **[{full_name}]({html_url})** ({is_private})\n"
f" {desc} (Ветка: `{default_branch}`, Issues: {open_issues}, Stars: {stars})"
)
return "\n".join(lines)
except Exception as e:
return f"Ошибка получения репозиториев Gitea: {type(e).__name__}: {str(e)}"
@tool(
name="gitea_search_repos",
description="Поиск репозиториев в Gitea по ключевому слову или названию.",
)
async def gitea_search_repos(query: str, limit: int = 15) -> str:
"""Поиск репозиториев в Gitea.
Args:
query: Поисковый запрос (например: 'bot', 'infra', 'agent')
limit: Максимальное количество результатов
"""
settings = get_settings()
if not settings.GITEA_ENABLED:
return "Интеграция с Gitea отключена."
client = get_gitea_client()
if not client.is_configured():
return f"Gitea не настроена. Укажите GITEA_TOKEN в файле .env"
try:
repos = await client.search_repos(query=query, limit=limit)
if not repos:
return f"По запросу '{query}' репозитории не найдены."
lines = [f"Результаты поиска репозиториев по '{query}' ({len(repos)}):"]
for repo in repos:
full_name = repo.get("full_name") or repo.get("name", "")
html_url = repo.get("html_url", "")
desc = repo.get("description") or "Без описания"
lines.append(f"- **[{full_name}]({html_url})**: {desc}")
return "\n".join(lines)
except Exception as e:
return f"Ошибка поиска репозиториев: {type(e).__name__}: {str(e)}"
@tool(
name="gitea_get_repo",
description="Получить подробную информацию о конкретном репозитории в Gitea.",
)
async def gitea_get_repo(owner: str, repo: str) -> str:
"""Детальная информация о репозитории.
Args:
owner: Владелец репозитория (пользователь или организация)
repo: Имя репозитория
"""
client = get_gitea_client()
if not client.is_configured():
return "Gitea не настроена в .env"
try:
data = await client.get_repo(owner, repo)
full_name = data.get("full_name", f"{owner}/{repo}")
html_url = data.get("html_url", "")
clone_ssh = data.get("ssh_url", "")
clone_http = data.get("clone_url", "")
desc = data.get("description") or "Без описания"
default_branch = data.get("default_branch", "main")
is_private = "🔒 Приватный" if data.get("private") else "🌐 Публичный"
stars = data.get("stars_count", 0)
forks = data.get("forks_count", 0)
open_issues = data.get("open_issues_count", 0)
open_prs = data.get("open_pr_counter", 0)
details = [
f"**Репозиторий [{full_name}]({html_url})** ({is_private})",
f"- **Описание**: {desc}",
f"- **Основная ветка**: `{default_branch}`",
f"- **Статистика**: Stars: {stars}, Forks: {forks}, Открытых Issues: {open_issues}, PRs: {open_prs}",
f"- **Клонирование**: HTTPS: `{clone_http}` | SSH: `{clone_ssh}`",
]
return "\n".join(details)
except Exception as e:
return f"Ошибка получения репозитория {owner}/{repo}: {type(e).__name__}: {str(e)}"
@tool(
name="gitea_get_file_or_dir",
description="Просмотреть содержимое файла или структуру папки/директории в репозитории Gitea.",
)
async def gitea_get_file_or_dir(
owner: str,
repo: str,
path: str = "",
branch: Optional[str] = None,
) -> str:
"""Просмотр файлов и директорий репозитория.
Args:
owner: Владелец репозитория
repo: Имя репозитория
path: Путь к файлу или папке (пустая строка для корневой папки)
branch: Ветка, тэг или коммит (опционально, по умолчанию основная ветка)
"""
client = get_gitea_client()
if not client.is_configured():
return "Gitea не настроена в .env"
try:
data = await client.get_contents(owner, repo, filepath=path, ref=branch)
# If data is a list -> it's a directory
if isinstance(data, list):
dir_label = path.strip("/") if path.strip("/") else "/"
lines = [f"Содержимое директории `{dir_label}` в `{owner}/{repo}` (ветка: {branch or 'default'}):"]
# Sort: directories first, then files
sorted_items = sorted(
data,
key=lambda x: (0 if x.get("type") in ("dir", "submodule") else 1, x.get("name", "").lower()),
)
for item in sorted_items:
item_name = item.get("name", "")
item_type = item.get("type", "file")
item_size = item.get("size", 0)
if item_type == "dir":
lines.append(f"- 📁 **{item_name}/**")
elif item_type == "submodule":
lines.append(f"- 📦 **{item_name}** (submodule)")
else:
size_kb = f"{item_size / 1024:.1f} KB" if item_size > 1024 else f"{item_size} B"
lines.append(f"- 📄 `{item_name}` ({size_kb})")
return "\n".join(lines)
# If data is a dict -> single file
if isinstance(data, dict):
file_name = data.get("name", path)
file_size = data.get("size", 0)
encoding = data.get("encoding", "")
raw_content = data.get("content", "")
if encoding == "base64" and raw_content:
try:
decoded = base64.b64decode(raw_content).decode("utf-8", errors="replace")
except Exception:
decoded = "[Не удалось декодировать бинарное содержимое в UTF-8]"
else:
decoded = raw_content or "[Пустой файл]"
max_preview = 12000
truncated = False
if len(decoded) > max_preview:
decoded = decoded[:max_preview]
truncated = True
ext = file_name.split(".")[-1] if "." in file_name else ""
res = [
f"**Файл `{path}`** в `{owner}/{repo}` ({file_size} B, ветка: {branch or 'default'}):",
f"```{ext}\n{decoded}\n```",
]
if truncated:
res.append(f"\n_... [Содержимое обрезано, показаны первые {max_preview} символов]_")
return "\n".join(res)
return f"Не удалось получить содержимое пути '{path}'."
except Exception as e:
return f"Ошибка чтения '{path}' в {owner}/{repo}: {type(e).__name__}: {str(e)}"
@tool(
name="gitea_save_file",
description="Создать новый файл или обновить существующий файл в репозитории Gitea с коммитом (вайбкодинг).",
)
async def gitea_save_file(
owner: str,
repo: str,
filepath: str,
content: str,
commit_message: str,
branch: Optional[str] = None,
) -> str:
"""Создание или обновление файла в Gitea.
Args:
owner: Владелец репозитория
repo: Имя репозитория
filepath: Путь к файлу (например, 'src/main.py' или 'README.md')
content: Полный текст файла для записи
commit_message: Сообщение коммита (например: 'feat: add metrics endpoint')
branch: Ветка для коммита (опционально, по умолчанию default ветка репозитория)
"""
client = get_gitea_client()
if not client.is_configured():
return "Gitea не настроена в .env"
try:
clean_path = filepath.strip("/")
res = await client.create_or_update_file(
owner=owner,
repo=repo,
filepath=clean_path,
content=content,
commit_message=commit_message,
branch=branch,
)
commit_sha = (res.get("commit") or {}).get("sha", "")
sha_str = f" (SHA: `{commit_sha[:8]}`)" if commit_sha else ""
branch_str = f" в ветку `{branch}`" if branch else ""
web_link = f"{client.web_url}/{owner}/{repo}/src/branch/{branch or 'main'}/{clean_path}"
return (
f"✅ Файл `[{clean_path}]({web_link})` успешно сохранен в репозитории "
f"**{owner}/{repo}**{branch_str}{sha_str}.\n"
f"Коммит: _{commit_message}_"
)
except Exception as e:
return f"Ошибка сохранения файла '{filepath}': {type(e).__name__}: {str(e)}"
@tool(
name="gitea_list_branches",
description="Получить список всех веток в репозитории Gitea.",
)
async def gitea_list_branches(owner: str, repo: str) -> str:
"""Список веток в репозитории.
Args:
owner: Владелец репозитория
repo: Имя репозитория
"""
client = get_gitea_client()
if not client.is_configured():
return "Gitea не настроена в .env"
try:
branches = await client.list_branches(owner, repo)
if not branches:
return f"Ветки в репозитории {owner}/{repo} не найдены."
lines = [f"Ветки в репозитории {owner}/{repo} ({len(branches)}):"]
for b in branches:
name = b.get("name", "")
commit = b.get("commit", {})
sha = commit.get("id", "")[:7]
msg = (commit.get("message") or "").strip().split("\n")[0]
lines.append(f"- 🌿 `{name}` (последний коммит: `{sha}`: {msg})")
return "\n".join(lines)
except Exception as e:
return f"Ошибка получения веток: {type(e).__name__}: {str(e)}"
@tool(
name="gitea_create_branch",
description="Создать новую ветку в репозитории Gitea от существующей ветки или коммита.",
)
async def gitea_create_branch(
owner: str,
repo: str,
new_branch: str,
base_branch: Optional[str] = None,
) -> str:
"""Создание новой ветки.
Args:
owner: Владелец репозитория
repo: Имя репозитория
new_branch: Название новой ветки (например, 'feature/telegram-bot')
base_branch: Базовая ветка или реф (опционально, по умолчанию main/master)
"""
client = get_gitea_client()
if not client.is_configured():
return "Gitea не настроена в .env"
try:
res = await client.create_branch(
owner=owner,
repo=repo,
new_branch=new_branch,
old_ref=base_branch,
)
created_name = res.get("name", new_branch)
base_info = f" от `{base_branch}`" if base_branch else ""
return f"✅ Ветка `🌿 {created_name}` успешно создана в репозитории **{owner}/{repo}**{base_info}."
except Exception as e:
return f"Ошибка создания ветки '{new_branch}': {type(e).__name__}: {str(e)}"
@tool(
name="gitea_list_issues",
description="Получить список задач (issues) в репозитории Gitea с фильтром по статусу (open / closed).",
)
async def gitea_list_issues(
owner: str,
repo: str,
state: str = "open",
limit: int = 20,
) -> str:
"""Список задач (issues) репозитория.
Args:
owner: Владелец репозитория
repo: Имя репозитория
state: Статус задач ('open', 'closed', 'all')
limit: Максимальное количество задач
"""
client = get_gitea_client()
if not client.is_configured():
return "Gitea не настроена в .env"
try:
issues = await client.list_issues(owner, repo, state=state, limit=limit)
if not issues:
return f"Задачи со статусом '{state}' в репозитории {owner}/{repo} не найдены."
lines = [f"Задачи ({state}) в {owner}/{repo} ({len(issues)}):"]
for issue in issues:
is_pr = bool(issue.get("pull_request"))
prefix = "🔀 PR" if is_pr else "📌 Issue"
index = issue.get("number") or issue.get("index", 0)
title = issue.get("title", "")
html_url = issue.get("html_url", "")
user = (issue.get("user") or {}).get("login", "Unknown")
comments = issue.get("comments", 0)
lines.append(f"- {prefix} **[#{index}]({html_url})**: {title} [Автор: {user}, Комментов: {comments}]")
return "\n".join(lines)
except Exception as e:
return f"Ошибка получения задач: {type(e).__name__}: {str(e)}"
@tool(
name="gitea_get_issue",
description="Получить детальную информацию о конкретной задаче (issue) в Gitea по её номеру.",
)
async def gitea_get_issue(owner: str, repo: str, index: int) -> str:
"""Детали задачи (issue) в Gitea.
Args:
owner: Владелец репозитория
repo: Имя репозитория
index: Номер задачи (#)
"""
client = get_gitea_client()
if not client.is_configured():
return "Gitea не настроена в .env"
try:
issue = await client.get_issue(owner, repo, index)
title = issue.get("title", "")
html_url = issue.get("html_url", "")
state = issue.get("state", "open")
body = issue.get("body") or "Нет описания"
user = (issue.get("user") or {}).get("login", "Unknown")
created_at = issue.get("created_at", "")[:10]
assignee = (issue.get("assignee") or {}).get("login", "Не назначен")
details = [
f"**Задача [#{index}]({html_url})**: {title}",
f"- **Статус**: {state.upper()}",
f"- **Автор**: {user}",
f"- **Исполнитель**: {assignee}",
f"- **Дата создания**: {created_at}",
f"- **Описание**:\n{body}",
]
return "\n".join(details)
except Exception as e:
return f"Ошибка получения задачи #{index}: {type(e).__name__}: {str(e)}"
@tool(
name="gitea_create_issue",
description="Создать новую задачу (issue) в репозитории Gitea.",
)
async def gitea_create_issue(
owner: str,
repo: str,
title: str,
body: str = "",
) -> str:
"""Создание новой задачи в Gitea.
Args:
owner: Владелец репозитория
repo: Имя репозитория
title: Название задачи
body: Описание задачи в Markdown
"""
client = get_gitea_client()
if not client.is_configured():
return "Gitea не настроена в .env"
try:
issue = await client.create_issue(owner, repo, title=title, body=body)
index = issue.get("number") or issue.get("index", 0)
html_url = issue.get("html_url", "")
return f"✅ Задача **[#{index}]({html_url})** '{title}' успешно создана в репозитории **{owner}/{repo}**!"
except Exception as e:
return f"Ошибка создания задачи: {type(e).__name__}: {str(e)}"
@tool(
name="gitea_add_issue_comment",
description="Добавить комментарий к задаче (issue) или pull request в Gitea.",
)
async def gitea_add_issue_comment(
owner: str,
repo: str,
index: int,
comment: str,
) -> str:
"""Добавить комментарий к задаче или PR.
Args:
owner: Владелец репозитория
repo: Имя репозитория
index: Номер задачи или PR
comment: Текст комментария в Markdown
"""
client = get_gitea_client()
if not client.is_configured():
return "Gitea не настроена в .env"
try:
res = await client.add_issue_comment(owner, repo, index=index, comment=comment)
html_url = res.get("html_url", "")
url_str = f" ([Ссылка]({html_url}))" if html_url else ""
return f"✅ Комментарий к задаче/PR #{index} в **{owner}/{repo}** успешно добавлен{url_str}."
except Exception as e:
return f"Ошибка добавления комментария к #{index}: {type(e).__name__}: {str(e)}"
@tool(
name="gitea_list_pull_requests",
description="Получить список Pull Requests в репозитории Gitea.",
)
async def gitea_list_pull_requests(
owner: str,
repo: str,
state: str = "open",
limit: int = 20,
) -> str:
"""Список Pull Requests в репозитории.
Args:
owner: Владелец репозитория
repo: Имя репозитория
state: Статус PR ('open', 'closed', 'all')
limit: Максимальное количество PR
"""
client = get_gitea_client()
if not client.is_configured():
return "Gitea не настроена в .env"
try:
prs = await client.list_pull_requests(owner, repo, state=state, limit=limit)
if not prs:
return f"Pull Requests со статусом '{state}' в репозитории {owner}/{repo} не найдены."
lines = [f"Pull Requests ({state}) в {owner}/{repo} ({len(prs)}):"]
for pr in prs:
index = pr.get("number") or pr.get("index", 0)
title = pr.get("title", "")
html_url = pr.get("html_url", "")
head = (pr.get("head") or {}).get("label") or (pr.get("head") or {}).get("ref", "?")
base = (pr.get("base") or {}).get("label") or (pr.get("base") or {}).get("ref", "?")
user = (pr.get("user") or {}).get("login", "Unknown")
lines.append(f"- 🔀 **[#{index}]({html_url})**: {title} [`{head}` → `{base}`, Автор: {user}]")
return "\n".join(lines)
except Exception as e:
return f"Ошибка получения Pull Requests: {type(e).__name__}: {str(e)}"
@tool(
name="gitea_create_pull_request",
description="Создать новый Pull Request в репозитории Gitea.",
)
async def gitea_create_pull_request(
owner: str,
repo: str,
title: str,
head_branch: str,
base_branch: str = "main",
body: str = "",
) -> str:
"""Создание Pull Request.
Args:
owner: Владелец репозитория
repo: Имя репозитория
title: Название Pull Request
head_branch: Ветка с вашими изменениями (source branch)
base_branch: Ветка, в которую нужно влить изменения (target branch, по умолчанию 'main')
body: Описание Pull Request
"""
client = get_gitea_client()
if not client.is_configured():
return "Gitea не настроена в .env"
try:
pr = await client.create_pull_request(
owner=owner,
repo=repo,
title=title,
head=head_branch,
base=base_branch,
body=body,
)
index = pr.get("number") or pr.get("index", 0)
html_url = pr.get("html_url", "")
return (
f"✅ Pull Request **[#{index}]({html_url})** '{title}' успешно создан в репозитории **{owner}/{repo}**!\n"
f"Ветка: `{head_branch}` → `{base_branch}`"
)
except Exception as e:
return f"Ошибка создания Pull Request: {type(e).__name__}: {str(e)}"
+21
View File
@@ -0,0 +1,21 @@
"""Google Calendar extension package with multi-calendar support."""
from extensions.google_calendar.tools import (
calendar_create_event,
calendar_date_schedule,
calendar_delete_event,
calendar_list_calendars,
calendar_list_events,
calendar_today_schedule,
calendar_tomorrow_schedule,
)
__all__ = [
"calendar_list_calendars",
"calendar_list_events",
"calendar_today_schedule",
"calendar_tomorrow_schedule",
"calendar_date_schedule",
"calendar_create_event",
"calendar_delete_event",
]
+356
View File
@@ -0,0 +1,356 @@
"""Google Calendar client supporting both Service Account and OAuth2 across all calendars."""
import asyncio
import logging
import time
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Optional
from google.auth.transport.requests import Request
from google.oauth2 import service_account
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from homeagent.config import get_settings
logger = logging.getLogger(__name__)
SCOPES = ["https://www.googleapis.com/auth/calendar"]
def _execute_with_retry(request: Any, retries: int = 3, initial_delay: float = 0.5) -> Any:
"""Execute Google API request with retry on transient SSL/network errors."""
for attempt in range(retries):
try:
return request.execute()
except Exception as e:
if attempt == retries - 1:
raise
logger.warning(
"Google Calendar API call attempt %d failed: %s. Retrying in %.1fs...",
attempt + 1,
e,
initial_delay * (2 ** attempt),
)
time.sleep(initial_delay * (2 ** attempt))
class GoogleCalendarClient:
"""Client for Google Calendar v3 supporting Service Account and OAuth2 across multiple calendars."""
def __init__(self) -> None:
self.settings = get_settings()
self.default_calendar_id = self.settings.GOOGLE_CALENDAR_ID or "primary"
self._service: Optional[Any] = None
def _get_credentials(self) -> Optional[Any]:
auth_type = self.settings.GOOGLE_AUTH_TYPE
sa_file = Path(self.settings.GOOGLE_SERVICE_ACCOUNT_FILE or "service_account.json")
oauth_creds_file = Path(self.settings.GOOGLE_OAUTH_CREDENTIALS_FILE or "credentials.json")
oauth_token_file = Path(self.settings.GOOGLE_OAUTH_TOKEN_FILE)
# 1. Service Account
if auth_type in ("service_account", "auto") and sa_file.exists():
try:
logger.info("Using Google Calendar Service Account credentials from %s", sa_file)
return service_account.Credentials.from_service_account_file(
str(sa_file), scopes=SCOPES
)
except Exception as e:
logger.error("Failed to load service account credentials: %s", e)
if auth_type == "service_account":
raise
# 2. OAuth2
if auth_type in ("oauth2", "auto"):
creds = None
if oauth_token_file.exists():
try:
creds = Credentials.from_authorized_user_file(str(oauth_token_file), SCOPES)
except Exception as e:
logger.warning("Could not read token file %s: %s", oauth_token_file, e)
if creds and creds.valid:
return creds
if creds and creds.expired and creds.refresh_token:
try:
creds.refresh(Request())
oauth_token_file.parent.mkdir(parents=True, exist_ok=True)
with open(oauth_token_file, "w", encoding="utf-8") as token_f:
token_f.write(creds.to_json())
return creds
except Exception as e:
logger.warning("Failed refreshing token: %s", e)
if oauth_creds_file.exists():
logger.info("Credentials file found (%s). Initiating OAuth flow...", oauth_creds_file)
try:
flow = InstalledAppFlow.from_client_secrets_file(str(oauth_creds_file), SCOPES)
creds = flow.run_local_server(port=0)
oauth_token_file.parent.mkdir(parents=True, exist_ok=True)
with open(oauth_token_file, "w", encoding="utf-8") as token_f:
token_f.write(creds.to_json())
return creds
except Exception as e:
logger.error("OAuth flow failed: %s", e)
if auth_type == "oauth2":
raise
return None
def is_configured(self) -> bool:
try:
return self._get_credentials() is not None
except Exception:
return False
def _get_service(self) -> Any:
if self._service is None:
creds = self._get_credentials()
if not creds:
raise ValueError(
"Google Calendar credentials not found. Provide either 'service_account.json' "
"or 'credentials.json' (OAuth2) as configured in .env."
)
self._service = build("calendar", "v3", credentials=creds, cache_discovery=False)
return self._service
async def list_calendars(self) -> list[dict[str, Any]]:
"""List all calendars accessible by the user/service account."""
service = self._get_service()
def _fetch_calendars() -> list[dict[str, Any]]:
configured_ids: list[str] = []
if self.default_calendar_id and self.default_calendar_id != "primary":
configured_ids.append(self.default_calendar_id)
for cid in self.settings.GOOGLE_ADDITIONAL_CALENDAR_IDS:
if cid not in configured_ids:
configured_ids.append(cid)
creds = self._get_credentials()
sa_email = getattr(creds, "service_account_email", None)
# 1. If service account, auto-sync configured calendars into service account calendarList
if sa_email and configured_ids:
for cid in configured_ids:
try:
_execute_with_retry(service.calendarList().insert(body={"id": cid}))
logger.debug("Registered calendar %s in service account calendarList", cid)
except Exception:
# 409 already exists or no permission, safe to ignore
pass
# 2. Query calendarList with retry
calendar_items: list[dict[str, Any]] = []
try:
result = _execute_with_retry(service.calendarList().list())
calendar_items = result.get("items", [])
except Exception as e:
logger.warning("Could not list calendars via calendarList(): %s", e)
# 3. Filter out service account's own empty primary calendar
filtered_items: list[dict[str, Any]] = []
for item in calendar_items:
cal_id = item.get("id", "")
if sa_email and cal_id == sa_email:
# Skip service account's internal empty primary calendar
continue
filtered_items.append(item)
# 4. Ensure all configured calendars are present
existing_ids = {item.get("id") for item in filtered_items}
for cid in configured_ids:
if cid not in existing_ids:
try:
meta = _execute_with_retry(service.calendars().get(calendarId=cid))
filtered_items.append({
"id": cid,
"summary": meta.get("summary") or cid,
"primary": (cid == self.default_calendar_id),
"description": meta.get("description", ""),
})
existing_ids.add(cid)
except Exception as e:
logger.warning("Could not fetch calendar metadata for %s: %s", cid, e)
filtered_items.append({
"id": cid,
"summary": cid,
"primary": (cid == self.default_calendar_id),
})
existing_ids.add(cid)
# 5. Determine primary calendar
has_primary = False
for item in filtered_items:
if self.default_calendar_id and self.default_calendar_id != "primary":
if item.get("id") == self.default_calendar_id:
item["primary"] = True
has_primary = True
else:
item["primary"] = False
elif item.get("primary"):
has_primary = True
if not has_primary and filtered_items:
filtered_items[0]["primary"] = True
if not filtered_items:
return [{"id": self.default_calendar_id, "summary": "Основной", "primary": True}]
return filtered_items
return await asyncio.to_thread(_fetch_calendars)
async def resolve_calendar_id(self, identifier: Optional[str]) -> str:
"""Resolve calendar name or ID to an actual calendarId."""
calendars = await self.list_calendars()
if not identifier or identifier.lower() in ("primary", "основной", "default"):
for cal in calendars:
if cal.get("primary"):
return cal["id"]
if self.default_calendar_id != "primary":
return self.default_calendar_id
if calendars:
return calendars[0]["id"]
return "primary"
clean = identifier.strip().lower()
# Check by ID exact match
for cal in calendars:
if cal.get("id", "").lower() == clean:
return cal["id"]
# Check by Summary substring / exact match
for cal in calendars:
summary = cal.get("summary", "").lower()
if clean in summary or summary in clean:
return cal["id"]
# Fallback to passed identifier
return identifier.strip()
async def list_events(
self,
time_min: Optional[datetime] = None,
time_max: Optional[datetime] = None,
max_results: int = 25,
calendar_id: Optional[str] = None,
) -> list[dict[str, Any]]:
"""List events in time window across all calendars (if calendar_id is None) or a specific calendar."""
service = self._get_service()
if time_min is None:
time_min = datetime.now(timezone.utc)
if time_max is None:
time_max = time_min + timedelta(days=7)
t_min_str = time_min.isoformat()
t_max_str = time_max.isoformat()
# Determine target calendars
if calendar_id:
resolved_id = await self.resolve_calendar_id(calendar_id)
target_calendars = [{"id": resolved_id, "summary": resolved_id}]
else:
target_calendars = await self.list_calendars()
def _fetch_from_calendars() -> list[dict[str, Any]]:
all_events: list[dict[str, Any]] = []
for cal in target_calendars:
cal_id = cal.get("id")
if not cal_id:
continue
cal_name = cal.get("summary", "Календарь")
try:
request = service.events().list(
calendarId=cal_id,
timeMin=t_min_str,
timeMax=t_max_str,
maxResults=max_results,
singleEvents=True,
orderBy="startTime",
)
events_result = _execute_with_retry(request)
items = events_result.get("items", [])
for item in items:
item["_calendar_id"] = cal_id
item["_calendar_name"] = cal_name
item["_is_primary"] = cal.get("primary", False)
all_events.append(item)
except Exception as e:
logger.warning("Failed to fetch events from calendar '%s' (%s): %s", cal_name, cal_id, e)
# Sort all combined events chronologically by start date/time
def _get_start_key(ev: dict[str, Any]) -> str:
start = ev.get("start", {})
return str(start.get("dateTime") or start.get("date") or "")
all_events.sort(key=_get_start_key)
return all_events[:max_results]
return await asyncio.to_thread(_fetch_from_calendars)
async def create_event(
self,
summary: str,
start_time: datetime,
end_time: datetime,
description: str = "",
attendees: Optional[list[str]] = None,
calendar_id: Optional[str] = None,
) -> dict[str, Any]:
"""Create a new event in calendar."""
service = self._get_service()
target_cal_id = await self.resolve_calendar_id(calendar_id or self.default_calendar_id)
event_body: dict[str, Any] = {
"summary": summary,
"description": description,
"start": {"dateTime": start_time.isoformat()},
"end": {"dateTime": end_time.isoformat()},
}
if attendees:
event_body["attendees"] = [{"email": email} for email in attendees]
def _insert() -> dict[str, Any]:
return _execute_with_retry(service.events().insert(calendarId=target_cal_id, body=event_body))
return await asyncio.to_thread(_insert)
async def delete_event(self, event_id: str, calendar_id: Optional[str] = None) -> None:
"""Delete an event by ID, searching across calendars if calendar_id is not specified."""
service = self._get_service()
if calendar_id:
target_cal_id = await self.resolve_calendar_id(calendar_id)
await asyncio.to_thread(
lambda: _execute_with_retry(service.events().delete(calendarId=target_cal_id, eventId=event_id))
)
return
# If calendar not specified, search and delete
calendars = await self.list_calendars()
def _search_and_delete() -> None:
last_err = None
for cal in calendars:
cal_id = cal.get("id")
if not cal_id:
continue
try:
_execute_with_retry(service.events().delete(calendarId=cal_id, eventId=event_id))
logger.info("Deleted event %s from calendar %s", event_id, cal_id)
return
except Exception as e:
last_err = e
if last_err:
raise last_err
await asyncio.to_thread(_search_and_delete)
+334
View File
@@ -0,0 +1,334 @@
"""Google Calendar tools exposed to HomeAgent and Gemini (multi-calendar support)."""
from datetime import datetime, time, timedelta, timezone
from typing import Optional
from extensions.google_calendar.client import GoogleCalendarClient
from homeagent.config import get_settings
from homeagent.tools.base import tool
_calendar_client: Optional[GoogleCalendarClient] = None
def get_calendar_client() -> GoogleCalendarClient:
global _calendar_client
if _calendar_client is None:
_calendar_client = GoogleCalendarClient()
return _calendar_client
def _parse_iso_datetime(dt_str: str) -> datetime:
"""Parse ISO formatted string into datetime."""
dt_str = dt_str.strip()
if dt_str.endswith("Z"):
dt_str = dt_str[:-1] + "+00:00"
dt = datetime.fromisoformat(dt_str)
if dt.tzinfo is None:
dt = dt.astimezone()
return dt
@tool(
name="calendar_list_calendars",
description="Показать список всех доступных Google Календарей (основной, рабочие, личные, командные).",
)
async def calendar_list_calendars() -> str:
"""Список доступных календарей."""
settings = get_settings()
if not settings.GOOGLE_CALENDAR_ENABLED:
return "Интеграция с Google Календарем отключена (GOOGLE_CALENDAR_ENABLED=False)."
client = get_calendar_client()
if not client.is_configured():
return (
"Google Календарь не настроен. Добавьте service_account.json или credentials.json "
"согласно инструкциям в docs/SETUP.md"
)
try:
calendars = await client.list_calendars()
if not calendars:
return "Не найдено ни одного доступного календаря."
lines = [f"Доступные Google Календари ({len(calendars)}):"]
for cal in calendars:
cal_id = cal.get("id", "")
summary = cal.get("summary", "Без названия")
primary_tag = " ⭐ (Основной)" if cal.get("primary") else ""
lines.append(f"- **{summary}**{primary_tag} [ID: `{cal_id}`]")
return "\n".join(lines)
except Exception as e:
return f"Ошибка получения списка календарей: {type(e).__name__}: {str(e)}"
@tool(
name="calendar_list_events",
description="Получить события и встречи сразу со ВСЕХ доступных Google Календарей (или из конкретного календаря) на указанное количество дней вперед.",
)
async def calendar_list_events(
days_ahead: int = 7,
max_results: int = 25,
calendar: Optional[str] = None,
) -> str:
"""Список событий календаря.
Args:
days_ahead: На сколько дней вперед искать события (по умолчанию 7)
max_results: Максимальное количество событий (по умолчанию 25)
calendar: Имя или ID конкретного календаря, если нужно отфильтровать (по умолчанию проверяются ВСЕ календари)
"""
settings = get_settings()
if not settings.GOOGLE_CALENDAR_ENABLED:
return "Интеграция с Google Календарем отключена (GOOGLE_CALENDAR_ENABLED=False)."
client = get_calendar_client()
if not client.is_configured():
return (
"Google Календарь не настроен. Добавьте service_account.json или credentials.json "
"в корень проекта согласно инструкциям в docs/SETUP.md"
)
try:
now = datetime.now().astimezone()
future = now + timedelta(days=days_ahead)
events = await client.list_events(
time_min=now,
time_max=future,
max_results=max_results,
calendar_id=calendar,
)
scope_desc = f"календаря '{calendar}'" if calendar else "всех доступных календарей"
if not events:
return f"В ближайшие {days_ahead} дн. событий из {scope_desc} не найдено."
lines = [f"События из {scope_desc} на ближайшие {days_ahead} дн. (найдено: {len(events)}):"]
for event in events:
event_id = event.get("id", "")
summary = event.get("summary", "Без названия")
start = event.get("start", {}).get("dateTime") or event.get("start", {}).get("date")
end = event.get("end", {}).get("dateTime") or event.get("end", {}).get("date")
cal_label = f"[{event.get('_calendar_name', 'Календарь')}] " if not calendar else ""
lines.append(f"- {cal_label}**{summary}**: c {start} по {end} [ID: `{event_id}`]")
return "\n".join(lines)
except Exception as e:
return f"Ошибка получения событий календаря: {type(e).__name__}: {str(e)}"
@tool(
name="calendar_today_schedule",
description="Получить расписание встреч и событий на сегодня (или захватить завтра) сразу со ВСЕХ доступных Google Календарей (личных, рабочих, учебных, командных).",
)
async def calendar_today_schedule(calendar: Optional[str] = None, include_tomorrow: bool = False) -> str:
"""Расписание на сегодняшний день по всем календарям.
Args:
calendar: Опционально: фильтр по конкретному календарю (название или ID)
include_tomorrow: Если True, включить также расписание на завтрашний день
"""
client = get_calendar_client()
if not client.is_configured():
return "Google Календарь не настроен в .env"
try:
now = datetime.now().astimezone()
start_of_day = datetime.combine(now.date(), time.min).replace(tzinfo=now.tzinfo)
target_date = now.date() + timedelta(days=1) if include_tomorrow else now.date()
end_of_day = datetime.combine(target_date, time.max).replace(tzinfo=now.tzinfo)
events = await client.list_events(
time_min=start_of_day,
time_max=end_of_day,
max_results=50,
calendar_id=calendar,
)
scope_desc = f"календарю '{calendar}'" if calendar else "всем календарям"
period_title = f"сегодня ({now.strftime('%d.%m.%Y')})" if not include_tomorrow else f"сегодня и завтра ({now.strftime('%d.%m')} - {target_date.strftime('%d.%m.%Y')})"
if not events:
return f"На {period_title} по {scope_desc} запланированных встреч нет."
lines = [f"📅 Расписание на {period_title} по {scope_desc}:"]
for event in events:
summary = event.get("summary", "Без названия")
start = event.get("start", {}).get("dateTime") or event.get("start", {}).get("date")
end = event.get("end", {}).get("dateTime") or event.get("end", {}).get("date")
desc = event.get("description", "")
desc_note = f" ({desc[:60]}...)" if desc else ""
cal_label = f"[{event.get('_calendar_name', 'Календарь')}] " if not calendar else ""
lines.append(f"- {cal_label}**{summary}**: {start} - {end}{desc_note}")
return "\n".join(lines)
except Exception as e:
return f"Ошибка получения расписания: {type(e).__name__}: {str(e)}"
@tool(
name="calendar_tomorrow_schedule",
description="Получить расписание встреч и событий на ЗАВТРА сразу со ВСЕХ доступных Google Календарей (личных, рабочих, учебных, командных).",
)
async def calendar_tomorrow_schedule(calendar: Optional[str] = None) -> str:
"""Расписание на завтрашний день по всем календарям.
Args:
calendar: Опционально: фильтр по конкретному календарю (название или ID)
"""
client = get_calendar_client()
if not client.is_configured():
return "Google Календарь не настроен в .env"
try:
now = datetime.now().astimezone()
tomorrow_date = now.date() + timedelta(days=1)
start_of_day = datetime.combine(tomorrow_date, time.min).replace(tzinfo=now.tzinfo)
end_of_day = datetime.combine(tomorrow_date, time.max).replace(tzinfo=now.tzinfo)
events = await client.list_events(
time_min=start_of_day,
time_max=end_of_day,
max_results=50,
calendar_id=calendar,
)
scope_desc = f"календарю '{calendar}'" if calendar else "всем календарям"
if not events:
return f"На завтра ({tomorrow_date.strftime('%d.%m.%Y')}) по {scope_desc} запланированных встреч нет."
lines = [f"📅 Расписание на завтра ({tomorrow_date.strftime('%A, %d.%m.%Y')}) по {scope_desc}:"]
for event in events:
summary = event.get("summary", "Без названия")
start = event.get("start", {}).get("dateTime") or event.get("start", {}).get("date")
end = event.get("end", {}).get("dateTime") or event.get("end", {}).get("date")
desc = event.get("description", "")
desc_note = f" ({desc[:60]}...)" if desc else ""
cal_label = f"[{event.get('_calendar_name', 'Календарь')}] " if not calendar else ""
lines.append(f"- {cal_label}**{summary}**: {start} - {end}{desc_note}")
return "\n".join(lines)
except Exception as e:
return f"Ошибка получения расписания на завтра: {type(e).__name__}: {str(e)}"
@tool(
name="calendar_date_schedule",
description="Получить расписание встреч и событий на любую конкретную дату (формат 'YYYY-MM-DD' или ключевые слова 'сегодня', 'завтра') со всех доступных Google Календарей.",
)
async def calendar_date_schedule(date_str: str, calendar: Optional[str] = None) -> str:
"""Расписание на указанную дату.
Args:
date_str: Дата в формате 'YYYY-MM-DD' (например '2026-11-08') или слова 'today', 'сегодня', 'tomorrow', 'завтра'
calendar: Опционально: фильтр по конкретному календарю
"""
client = get_calendar_client()
if not client.is_configured():
return "Google Календарь не настроен в .env"
try:
now = datetime.now().astimezone()
clean = date_str.strip().lower()
if clean in ("today", "сегодня"):
target_date = now.date()
elif clean in ("tomorrow", "завтра"):
target_date = now.date() + timedelta(days=1)
elif clean in ("yesterday", "вчера"):
target_date = now.date() - timedelta(days=1)
else:
target_date = datetime.strptime(clean, "%Y-%m-%d").date()
start_of_day = datetime.combine(target_date, time.min).replace(tzinfo=now.tzinfo)
end_of_day = datetime.combine(target_date, time.max).replace(tzinfo=now.tzinfo)
events = await client.list_events(
time_min=start_of_day,
time_max=end_of_day,
max_results=50,
calendar_id=calendar,
)
scope_desc = f"календарю '{calendar}'" if calendar else "всем календарям"
if not events:
return f"На дату {target_date.strftime('%d.%m.%Y')} по {scope_desc} запланированных встреч нет."
lines = [f"📅 Расписание на {target_date.strftime('%A, %d.%m.%Y')} по {scope_desc}:"]
for event in events:
summary = event.get("summary", "Без названия")
start = event.get("start", {}).get("dateTime") or event.get("start", {}).get("date")
end = event.get("end", {}).get("dateTime") or event.get("end", {}).get("date")
desc = event.get("description", "")
desc_note = f" ({desc[:60]}...)" if desc else ""
cal_label = f"[{event.get('_calendar_name', 'Календарь')}] " if not calendar else ""
lines.append(f"- {cal_label}**{summary}**: {start} - {end}{desc_note}")
return "\n".join(lines)
except Exception as e:
return f"Ошибка получения расписания на {date_str}: {type(e).__name__}: {str(e)}"
@tool(
name="calendar_create_event",
description="Создать новое событие или встречу в Google Календаре. Можно указать в какой именно календарь добавить (по умолчанию — в основной).",
)
async def calendar_create_event(
summary: str,
start_iso: str,
end_iso: str,
description: str = "",
attendees: Optional[list[str]] = None,
calendar: Optional[str] = "primary",
) -> str:
"""Создать встречу в календаре.
Args:
summary: Название встречи или события
start_iso: Время начала в формате ISO 8601 (например: '2026-11-08T10:00:00+03:00')
end_iso: Время окончания в формате ISO 8601 (например: '2026-11-08T11:00:00+03:00')
description: Описание или повестка встречи
attendees: Список email участников
calendar: Название или ID календаря, в который добавить событие (по умолчанию 'primary' — основной)
"""
client = get_calendar_client()
if not client.is_configured():
return "Google Календарь не настроен в .env"
try:
start_dt = _parse_iso_datetime(start_iso)
end_dt = _parse_iso_datetime(end_iso)
event = await client.create_event(
summary=summary,
start_time=start_dt,
end_time=end_dt,
description=description,
attendees=attendees,
calendar_id=calendar,
)
event_id = event.get("id", "")
link = event.get("htmlLink", "")
return f"Событие '{summary}' успешно создано в календаре! ID: {event_id}. Ссылка: {link}"
except Exception as e:
return f"Ошибка создания события: {type(e).__name__}: {str(e)}"
@tool(
name="calendar_delete_event",
description="Удалить событие из Google Календаря по его ID.",
)
async def calendar_delete_event(event_id: str, calendar: Optional[str] = None) -> str:
"""Удалить событие из календаря.
Args:
event_id: ID события (полученный из calendar_list_events)
calendar: Название или ID календаря (если известно)
"""
client = get_calendar_client()
if not client.is_configured():
return "Google Календарь не настроен в .env"
try:
await client.delete_event(event_id=event_id.strip(), calendar_id=calendar)
return f"Событие с ID '{event_id}' успешно удалено."
except Exception as e:
return f"Ошибка удаления события '{event_id}': {type(e).__name__}: {str(e)}"
+26
View File
@@ -0,0 +1,26 @@
"""Jira extension package."""
from extensions.jira.tools import (
jira_add_comment,
jira_create_issue,
jira_get_editable_fields,
jira_get_issue,
jira_my_issues,
jira_search,
jira_search_users,
jira_transition_issue,
jira_update_issue,
)
__all__ = [
"jira_search",
"jira_get_issue",
"jira_create_issue",
"jira_add_comment",
"jira_transition_issue",
"jira_my_issues",
"jira_update_issue",
"jira_get_editable_fields",
"jira_search_users",
]
+347
View File
@@ -0,0 +1,347 @@
"""Asynchronous Jira REST API client for HomeAgent supporting Jira Cloud v3 enhanced search."""
import logging
from typing import Any, Optional
import httpx
from homeagent.config import get_settings
logger = logging.getLogger(__name__)
# Jira Cloud enhanced search endpoint (token-paginated). Replaces deprecated /rest/api/2/search.
_SEARCH_PATH = "rest/api/3/search/jql"
_DEFAULT_FIELDS = [
"summary",
"status",
"assignee",
"priority",
"created",
"updated",
"description",
"duedate",
"project",
]
def text_to_adf(text: str) -> dict[str, Any]:
"""Convert plain text to Atlassian Document Format (ADF) for Jira v3."""
return {
"version": 1,
"type": "doc",
"content": [
{
"type": "paragraph",
"content": [{"type": "text", "text": text}],
}
],
}
def extract_adf_text(content: Any) -> str:
"""Extract human-readable text from Atlassian Document Format (ADF) or plain string."""
if not content:
return ""
if isinstance(content, str):
return content
if isinstance(content, list):
return "".join(extract_adf_text(item) for item in content)
if isinstance(content, dict):
text = content.get("text", "")
children = "".join(extract_adf_text(child) for child in content.get("content", []))
if content.get("type") in ("paragraph", "heading"):
return f"{text}{children}\n"
return f"{text}{children}"
return str(content)
class JiraClient:
"""Jira Cloud & Server REST API Client."""
def __init__(
self,
base_url: Optional[str] = None,
email: Optional[str] = None,
api_token: Optional[str] = None,
pat: Optional[str] = None,
):
settings = get_settings()
self.base_url = (base_url or settings.JIRA_URL or "").rstrip("/")
self.email = email or settings.JIRA_EMAIL or ""
self.api_token = (
api_token
or (settings.JIRA_API_TOKEN.get_secret_value() if settings.JIRA_API_TOKEN else "")
)
self.pat = (
pat
or (settings.JIRA_PERSONAL_ACCESS_TOKEN.get_secret_value() if settings.JIRA_PERSONAL_ACCESS_TOKEN else "")
)
def is_configured(self) -> bool:
if not self.base_url:
return False
return bool(self.pat or (self.email and self.api_token))
def browse_url(self, issue_key: str) -> str:
"""Human-facing URL for an issue, e.g. https://site.atlassian.net/browse/ABC-123."""
return f"{self.base_url}/browse/{issue_key}"
def _get_headers_and_auth(self) -> tuple[dict[str, str], Optional[httpx.BasicAuth]]:
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
}
auth = None
if self.pat:
headers["Authorization"] = f"Bearer {self.pat}"
elif self.email and self.api_token:
auth = httpx.BasicAuth(self.email, self.api_token)
return headers, auth
async def _request(
self,
method: str,
endpoint: str,
params: Optional[dict[str, Any]] = None,
json_data: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
if not self.is_configured():
raise ValueError(
"Jira is not configured. Please set JIRA_URL and JIRA_API_TOKEN/EMAIL or JIRA_PERSONAL_ACCESS_TOKEN in .env"
)
url = f"{self.base_url}/{endpoint.lstrip('/')}"
headers, auth = self._get_headers_and_auth()
async with httpx.AsyncClient(timeout=20.0) as client:
response = await client.request(
method=method,
url=url,
headers=headers,
auth=auth,
params=params,
json=json_data,
)
if response.status_code == 204:
return {"status": "success", "status_code": 204}
if response.is_error:
error_body = response.text
logger.error("Jira API error %d on %s: %s", response.status_code, url, error_body)
raise RuntimeError(f"Jira API error ({response.status_code}): {error_body}")
return response.json()
async def get_myself(self) -> dict[str, Any]:
"""Fetch current authenticated user profile."""
try:
return await self._request("GET", "rest/api/3/myself")
except RuntimeError:
return await self._request("GET", "rest/api/2/myself")
async def search_issues(
self,
jql: str,
max_results: int = 10,
fields: Optional[list[str]] = None,
) -> list[dict[str, Any]]:
"""Search issues using token-paginated Jira Cloud API /rest/api/3/search/jql with fallback for Server."""
requested_fields = fields or _DEFAULT_FIELDS
page_size = min(max_results, 50)
payload: dict[str, Any] = {
"jql": jql,
"maxResults": page_size,
"fields": requested_fields,
}
# 1. Try Jira Cloud enhanced search (POST /rest/api/3/search/jql)
try:
all_issues: list[dict[str, Any]] = []
while len(all_issues) < max_results:
data = await self._request("POST", _SEARCH_PATH, json_data=payload)
issues = data.get("issues", [])
all_issues.extend(issues)
next_token = data.get("nextPageToken")
if not next_token or not issues or len(all_issues) >= max_results:
break
payload["nextPageToken"] = next_token
return all_issues[:max_results]
except RuntimeError as e:
# 2. Fallback to /rest/api/2/search for Jira Server / Data Center
if "404" in str(e) or "405" in str(e):
logger.info("Falling back to /rest/api/2/search for Jira Server/DC")
params = {
"jql": jql,
"maxResults": max_results,
"fields": ",".join(requested_fields),
}
data = await self._request("GET", "rest/api/2/search", params=params)
return data.get("issues", [])
raise
async def get_issue(self, issue_key: str) -> dict[str, Any]:
"""Get details of an issue by key (e.g. PROJ-123)."""
try:
return await self._request("GET", f"rest/api/3/issue/{issue_key}")
except RuntimeError:
return await self._request("GET", f"rest/api/2/issue/{issue_key}")
async def create_issue(
self,
project_key: str,
summary: str,
description: str,
issue_type: str = "Task",
priority: Optional[str] = None,
) -> dict[str, Any]:
"""Create a new Jira issue."""
fields: dict[str, Any] = {
"project": {"key": project_key},
"summary": summary,
"description": text_to_adf(description),
"issuetype": {"name": issue_type},
}
if priority:
fields["priority"] = {"name": priority}
try:
return await self._request("POST", "rest/api/3/issue", json_data={"fields": fields})
except RuntimeError:
# Fallback for Jira Server (plain text description)
fields["description"] = description
return await self._request("POST", "rest/api/2/issue", json_data={"fields": fields})
async def add_comment(self, issue_key: str, comment: str) -> dict[str, Any]:
"""Add a comment to an issue."""
try:
return await self._request(
"POST",
f"rest/api/3/issue/{issue_key}/comment",
json_data={"body": text_to_adf(comment)},
)
except RuntimeError:
# Fallback for Jira Server
return await self._request(
"POST",
f"rest/api/2/issue/{issue_key}/comment",
json_data={"body": comment},
)
async def get_transitions(self, issue_key: str) -> list[dict[str, Any]]:
"""Get available status transitions for an issue."""
try:
data = await self._request("GET", f"rest/api/3/issue/{issue_key}/transitions")
except RuntimeError:
data = await self._request("GET", f"rest/api/2/issue/{issue_key}/transitions")
return data.get("transitions", [])
async def transition_issue(self, issue_key: str, transition_id: str) -> None:
"""Perform a status transition on an issue."""
try:
await self._request(
"POST",
f"rest/api/3/issue/{issue_key}/transitions",
json_data={"transition": {"id": transition_id}},
)
except RuntimeError:
await self._request(
"POST",
f"rest/api/2/issue/{issue_key}/transitions",
json_data={"transition": {"id": transition_id}},
)
async def update_issue(
self,
issue_key: str,
fields: dict[str, Any],
) -> dict[str, Any]:
"""Update issue fields in Jira. Supports standard and custom fields."""
try:
return await self._request(
"PUT",
f"rest/api/3/issue/{issue_key}",
json_data={"fields": fields},
)
except RuntimeError:
# Fallback for Jira Server / DC
fallback_fields = dict(fields)
if "description" in fallback_fields and isinstance(fallback_fields["description"], dict):
fallback_fields["description"] = extract_adf_text(fallback_fields["description"])
return await self._request(
"PUT",
f"rest/api/2/issue/{issue_key}",
json_data={"fields": fallback_fields},
)
async def get_edit_meta(self, issue_key: str) -> dict[str, Any]:
"""Get editable metadata (fields, schemas, allowed values) for an issue."""
try:
return await self._request("GET", f"rest/api/3/issue/{issue_key}/editmeta")
except RuntimeError:
return await self._request("GET", f"rest/api/2/issue/{issue_key}/editmeta")
async def search_users(self, query: str, max_results: int = 10) -> list[dict[str, Any]]:
"""Search users in Jira by name or email."""
try:
res = await self._request(
"GET",
"rest/api/3/user/search",
params={"query": query, "maxResults": max_results},
)
if isinstance(res, list):
return res
return []
except RuntimeError:
# Fallback for Jira Server / DC
res = await self._request(
"GET",
"rest/api/2/user/search",
params={"username": query, "maxResults": max_results},
)
if isinstance(res, list):
return res
return []
async def assign_issue(
self,
issue_key: str,
account_id_or_name: Optional[str] = None,
) -> dict[str, Any]:
"""Assign issue to a user or unassign if None."""
try:
return await self._request(
"PUT",
f"rest/api/3/issue/{issue_key}/assignee",
json_data={"accountId": account_id_or_name},
)
except RuntimeError:
return await self._request(
"PUT",
f"rest/api/2/issue/{issue_key}/assignee",
json_data={"name": account_id_or_name},
)
async def resolve_user(self, query: str) -> Optional[dict[str, Any]]:
"""Resolve a user by name, email, or account ID."""
q = query.strip()
if not q or q.lower() in ("unassigned", "none", "никто", "снять", "null"):
return None
users = await self.search_users(q, max_results=5)
if not users:
# Assume query itself is an accountId or username
return {"accountId": q, "name": q, "displayName": q}
# Look for exact email or displayName match
q_lower = q.lower()
for u in users:
if u.get("emailAddress", "").lower() == q_lower or u.get("displayName", "").lower() == q_lower:
return u
# Fallback to first user in search results
return users[0]
+490
View File
@@ -0,0 +1,490 @@
"""Jira tools exposed to HomeAgent and Gemini with v3 enhanced search support."""
import json
from typing import Any, Optional
from extensions.jira.client import JiraClient, extract_adf_text, text_to_adf
from homeagent.config import get_settings
from homeagent.tools.base import tool
_client: Optional[JiraClient] = None
def get_jira_client() -> JiraClient:
global _client
if _client is None:
_client = JiraClient()
return _client
@tool(
name="jira_search",
description="Поиск задач в Jira по JQL-запросу. Возвращает список ключей, названий, статусов, исполнителей и ссылок.",
)
async def jira_search(jql: str, max_results: int = 10) -> str:
"""Поиск задач в Jira по JQL.
Args:
jql: JQL запрос (например: 'assignee = currentUser() AND statusCategory != Done ORDER BY updated DESC')
max_results: Максимальное количество задач (по умолчанию 10)
"""
settings = get_settings()
if not settings.JIRA_ENABLED:
return "Интеграция с Jira отключена в настройках (JIRA_ENABLED=False)."
client = get_jira_client()
if not client.is_configured():
return "Jira не настроена. Укажите JIRA_URL и JIRA_API_TOKEN в файле .env"
try:
issues = await client.search_issues(jql=jql, max_results=max_results)
if not issues:
return f"По запросу '{jql}' ничего не найдено."
lines = [f"Найдено задач: {len(issues)}"]
for issue in issues:
key = issue.get("key", "")
fields = issue.get("fields", {})
summary = fields.get("summary", "")
status = fields.get("status", {}).get("name", "Unknown")
priority = fields.get("priority", {}).get("name", "None")
assignee = (fields.get("assignee") or {}).get("displayName", "Unassigned")
duedate = fields.get("duedate")
due_str = f", Дедлайн: {duedate}" if duedate else ""
url = client.browse_url(key)
lines.append(f"- **[{key}]({url})**: {summary} [Статус: {status}, Приоритет: {priority}, Исполнитель: {assignee}{due_str}]")
return "\n".join(lines)
except Exception as e:
return f"Ошибка поиска в Jira: {type(e).__name__}: {str(e)}"
@tool(
name="jira_get_issue",
description="Получить детальную информацию о конкретной задаче в Jira по ее ключу (например, PROJ-123).",
)
async def jira_get_issue(issue_key: str) -> str:
"""Детали задачи Jira.
Args:
issue_key: Ключ задачи, например 'PROJ-101'
"""
client = get_jira_client()
if not client.is_configured():
return "Jira не настроена в .env"
try:
clean_key = issue_key.strip().upper()
issue = await client.get_issue(clean_key)
fields = issue.get("fields", {})
summary = fields.get("summary", "Без названия")
raw_desc = fields.get("description")
desc = extract_adf_text(raw_desc).strip() or "Нет описания"
status = fields.get("status", {}).get("name", "Unknown")
priority = fields.get("priority", {}).get("name", "None")
assignee = (fields.get("assignee") or {}).get("displayName", "Unassigned")
issue_type = fields.get("issuetype", {}).get("name", "Task")
duedate = fields.get("duedate") or "Не указан"
url = client.browse_url(clean_key)
details = [
f"**Задача [{clean_key}]({url})**: {summary}",
f"- **Тип**: {issue_type}",
f"- **Статус**: {status}",
f"- **Приоритет**: {priority}",
f"- **Исполнитель**: {assignee}",
f"- **Дедлайн**: {duedate}",
f"- **Описание**:\n{desc}",
]
return "\n".join(details)
except Exception as e:
return f"Ошибка получения задачи '{issue_key}': {type(e).__name__}: {str(e)}"
@tool(
name="jira_create_issue",
description="Создать новую задачу в Jira в указанном проекте.",
)
async def jira_create_issue(
project_key: str,
summary: str,
description: str,
issue_type: str = "Task",
priority: Optional[str] = None,
) -> str:
"""Создание новой задачи в Jira.
Args:
project_key: Ключ проекта (например: 'KAN', 'DEV')
summary: Краткое название задачи
description: Подробное описание задачи
issue_type: Тип задачи (Task, Bug, Story)
priority: Приоритет (Highest, High, Medium, Low, Lowest)
"""
client = get_jira_client()
if not client.is_configured():
return "Jira не настроена в .env"
try:
clean_proj = project_key.strip().upper()
result = await client.create_issue(
project_key=clean_proj,
summary=summary,
description=description,
issue_type=issue_type,
priority=priority,
)
key = result.get("key", "Unknown")
url = client.browse_url(key)
return f"Задача успешно создана! Ключ: [{key}]({url})"
except Exception as e:
return f"Ошибка создания задачи: {type(e).__name__}: {str(e)}"
@tool(
name="jira_add_comment",
description="Добавить комментарий к задаче в Jira.",
)
async def jira_add_comment(issue_key: str, comment: str) -> str:
"""Добавить комментарий к задаче.
Args:
issue_key: Ключ задачи (например: 'PROJ-123')
comment: Текст комментария
"""
client = get_jira_client()
if not client.is_configured():
return "Jira не настроена в .env"
try:
clean_key = issue_key.strip().upper()
await client.add_comment(issue_key=clean_key, comment=comment)
return f"Комментарий успешно добавлен к задаче {clean_key}."
except Exception as e:
return f"Ошибка добавления комментария: {type(e).__name__}: {str(e)}"
@tool(
name="jira_transition_issue",
description="Перевести задачу в другой статус (например: In Progress, Done, Review, В работе, Готово).",
)
async def jira_transition_issue(issue_key: str, transition_name: str) -> str:
"""Сменить статус задачи.
Args:
issue_key: Ключ задачи
transition_name: Название желаемого статуса или перехода (например: 'In Progress', 'Done', 'В работе', 'Готово')
"""
client = get_jira_client()
if not client.is_configured():
return "Jira не настроена в .env"
try:
clean_key = issue_key.strip().upper()
transitions = await client.get_transitions(clean_key)
target_name = transition_name.strip().lower()
matched = None
available_names = []
for t in transitions:
t_name = t.get("name", "")
available_names.append(t_name)
t_lower = t_name.lower()
if t_lower == target_name or target_name in t_lower or t_lower in target_name:
matched = t
break
if not matched:
return (
f"Переход '{transition_name}' не найден для задачи {clean_key}. "
f"Доступные переходы: {', '.join(available_names)}"
)
await client.transition_issue(clean_key, matched["id"])
return f"Статус задачи {clean_key} успешно изменен на '{matched.get('name')}'."
except Exception as e:
return f"Ошибка изменения статуса: {type(e).__name__}: {str(e)}"
@tool(
name="jira_my_issues",
description="Получить список задач, назначенных на текущего пользователя, с фильтром по статусу или открытых задач.",
)
async def jira_my_issues(status: Optional[str] = None, max_results: int = 10) -> str:
"""Список моих задач в Jira.
Args:
status: Опциональный статус задачи (например: 'In Progress', 'To Do', 'В работе', 'Открытые')
max_results: Максимальное количество задач
"""
jql = "assignee = currentUser()"
if status:
s_lower = status.strip().lower()
if "progress" in s_lower or "работ" in s_lower:
jql += ' AND (statusCategory = "In Progress" OR status ~ "В работе")'
elif "to do" in s_lower or "выполнен" in s_lower or "очеред" in s_lower:
jql += ' AND (statusCategory = "To Do" OR status ~ "К выполнению")'
elif "done" in s_lower or "готов" in s_lower or "закрыт" in s_lower:
jql += ' AND (statusCategory = "Done" OR status ~ "Готово")'
else:
jql += f' AND (statusCategory ~ "{status}" OR status ~ "{status}")'
else:
# Default: all active open tasks across the entire site
jql += " AND statusCategory != Done"
jql += " ORDER BY updated DESC"
return await jira_search(jql=jql, max_results=max_results)
@tool(
name="jira_get_editable_fields",
description="Получить список всех редактируемых полей (включая кастомные поля и Story Points) и допустимых значений для конкретной задачи Jira.",
)
async def jira_get_editable_fields(issue_key: str) -> str:
"""Получить схему редактируемых полей задачи Jira.
Args:
issue_key: Ключ задачи (например: 'PROJ-123')
"""
client = get_jira_client()
if not client.is_configured():
return "Jira не настроена в .env"
try:
clean_key = issue_key.strip().upper()
meta = await client.get_edit_meta(clean_key)
fields = meta.get("fields", {})
if not fields:
return f"Для задачи {clean_key} не найдено доступных для редактирования полей."
lines = [f"Редактируемые поля для задачи {clean_key} (всего: {len(fields)}):"]
for field_key, field_info in fields.items():
name = field_info.get("name", field_key)
schema = field_info.get("schema", {})
f_type = schema.get("type", "unknown")
is_required = " [Обязательное]" if field_info.get("required") else ""
allowed = field_info.get("allowedValues")
allowed_str = ""
if allowed and isinstance(allowed, list):
allowed_names = [v.get("name") or v.get("value") or str(v) for v in allowed if isinstance(v, dict)]
if allowed_names:
allowed_str = f" (Допустимые: {', '.join(allowed_names[:10])})"
lines.append(f"- **{field_key}** ('{name}'): тип `{f_type}`{is_required}{allowed_str}")
return "\n".join(lines)
except Exception as e:
return f"Ошибка получения полей задачи '{issue_key}': {type(e).__name__}: {str(e)}"
@tool(
name="jira_search_users",
description="Поиск пользователей в Jira по имени или email для назначения исполнителем.",
)
async def jira_search_users(query: str, max_results: int = 10) -> str:
"""Поиск пользователей в Jira.
Args:
query: Строка поиска (имя, фамилия или email)
max_results: Максимальное количество результатов (по умолчанию 10)
"""
client = get_jira_client()
if not client.is_configured():
return "Jira не настроена в .env"
try:
users = await client.search_users(query=query.strip(), max_results=max_results)
if not users:
return f"Пользователи по запросу '{query}' не найдены."
lines = [f"Найдено пользователей в Jira ({len(users)}):"]
for u in users:
name = u.get("displayName", "Без имени")
email = u.get("emailAddress", "нет email")
account_id = u.get("accountId") or u.get("name") or "unknown"
active = "Активен" if u.get("active", True) else "Неактивен"
lines.append(f"- **{name}** (ID: `{account_id}`, email: `{email}`, статус: {active})")
return "\n".join(lines)
except Exception as e:
return f"Ошибка поиска пользователей: {type(e).__name__}: {str(e)}"
@tool(
name="jira_update_issue",
description=(
"Изменить любые поля задачи в Jira: название, описание, статус, исполнителя, "
"приоритет, дедлайн, метки, компоненты, тип задачи и любые кастомные поля (custom_fields)."
),
)
async def jira_update_issue(
issue_key: str,
summary: Optional[str] = None,
description: Optional[str] = None,
status: Optional[str] = None,
assignee: Optional[str] = None,
priority: Optional[str] = None,
duedate: Optional[str] = None,
labels: Optional[list[str]] = None,
components: Optional[list[str]] = None,
issue_type: Optional[str] = None,
custom_fields: Optional[dict[str, Any]] = None,
) -> str:
"""Обновить поля задачи в Jira.
Args:
issue_key: Ключ задачи (например: 'PROJ-123')
summary: Новое название / тема задачи
description: Новое описание задачи
status: Новый статус или переход (например: 'In Progress', 'Done', 'В работе', 'Готово')
assignee: Исполнитель (имя, email, accountId, или 'unassigned'/'снять' для отмены назначения)
priority: Новый приоритет (Highest, High, Medium, Low, Lowest)
duedate: Срок выполнения в формате YYYY-MM-DD (или 'clear'/'снять' для удаления дедлайна)
labels: Список меток (например: ['frontend', 'bug'])
components: Список названий компонентов (например: ['API', 'Frontend'])
issue_type: Тип задачи (Task, Bug, Story)
custom_fields: Словарь кастомных полей (например: {'customfield_10016': 5} или {'Story Points': 5})
"""
client = get_jira_client()
if not client.is_configured():
return "Jira не настроена в .env"
try:
clean_key = issue_key.strip().upper()
updated_items: list[str] = []
# 1. Update status via transition if provided
status_warning = ""
if status is not None and status.strip():
target_status = status.strip()
transitions = await client.get_transitions(clean_key)
target_lower = target_status.lower()
matched = None
available_names = []
for t in transitions:
t_name = t.get("name", "")
available_names.append(t_name)
t_lower = t_name.lower()
if t_lower == target_lower or target_lower in t_lower or t_lower in target_lower:
matched = t
break
if matched:
await client.transition_issue(clean_key, matched["id"])
updated_items.append(f"Статус -> '{matched.get('name')}'")
else:
status_warning = (
f"\n⚠️ Переход '{target_status}' не найден. "
f"Доступные переходы: {', '.join(available_names)}"
)
# 2. Build fields dictionary
fields_payload: dict[str, Any] = {}
if summary is not None:
fields_payload["summary"] = summary
updated_items.append(f"Название -> '{summary}'")
if description is not None:
fields_payload["description"] = text_to_adf(description)
updated_items.append("Описание обновлено")
if priority is not None:
fields_payload["priority"] = {"name": priority}
updated_items.append(f"Приоритет -> '{priority}'")
if duedate is not None:
clean_due = duedate.strip()
if clean_due.lower() in ("", "none", "clear", "снять", "null", "удалить"):
fields_payload["duedate"] = None
updated_items.append("Дедлайн -> Снят")
else:
fields_payload["duedate"] = clean_due
updated_items.append(f"Дедлайн -> '{clean_due}'")
if labels is not None:
fields_payload["labels"] = labels
updated_items.append(f"Метки -> {labels}")
if components is not None:
fields_payload["components"] = [{"name": c} for c in components]
updated_items.append(f"Компоненты -> {components}")
if issue_type is not None:
fields_payload["issuetype"] = {"name": issue_type}
updated_items.append(f"Тип задачи -> '{issue_type}'")
if assignee is not None:
clean_assignee = assignee.strip()
if clean_assignee.lower() in ("", "none", "unassigned", "никто", "снять", "null", "удалить"):
fields_payload["assignee"] = None
updated_items.append("Исполнитель -> Снят (Unassigned)")
else:
resolved_user = await client.resolve_user(clean_assignee)
if resolved_user:
account_id = resolved_user.get("accountId")
name = resolved_user.get("name")
display_name = resolved_user.get("displayName") or clean_assignee
if account_id:
fields_payload["assignee"] = {"accountId": account_id}
elif name:
fields_payload["assignee"] = {"name": name}
else:
fields_payload["assignee"] = {"accountId": clean_assignee}
updated_items.append(f"Исполнитель -> '{display_name}'")
else:
fields_payload["assignee"] = {"accountId": clean_assignee}
updated_items.append(f"Исполнитель -> '{clean_assignee}'")
# 3. Handle custom fields
if custom_fields is not None:
# Handle if passed as string JSON
if isinstance(custom_fields, str):
try:
custom_fields = json.loads(custom_fields)
except Exception:
pass
if isinstance(custom_fields, dict) and custom_fields:
meta_fields: Optional[dict[str, Any]] = None
for cf_key, cf_val in custom_fields.items():
actual_key = cf_key
if not cf_key.startswith("customfield_") and cf_key not in fields_payload:
if meta_fields is None:
try:
meta = await client.get_edit_meta(clean_key)
meta_fields = meta.get("fields", {})
except Exception:
meta_fields = {}
cf_lower = cf_key.lower()
for f_id, f_data in meta_fields.items():
if f_data.get("name", "").lower() == cf_lower:
actual_key = f_id
break
fields_payload[actual_key] = cf_val
updated_items.append(f"Поле '{cf_key}' ({actual_key}) -> {cf_val}")
# 4. Send update request if fields are present
if fields_payload:
await client.update_issue(clean_key, fields_payload)
if not updated_items and not status_warning:
return f"Не указаны поля для обновления задачи {clean_key}."
url = client.browse_url(clean_key)
res_lines = [f"Задача **[{clean_key}]({url})** успешно обновлена!"]
if updated_items:
res_lines.append("Измененные поля:")
for item in updated_items:
res_lines.append(f"- {item}")
if status_warning:
res_lines.append(status_warning)
return "\n".join(res_lines)
except Exception as e:
return f"Ошибка обновления задачи '{issue_key}': {type(e).__name__}: {str(e)}"
+17
View File
@@ -0,0 +1,17 @@
"""Safe isolated code execution sandbox extension for HomeAgent."""
from extensions.sandbox.tools import (
code_execute,
sandbox_file_read,
sandbox_file_write,
sandbox_reset,
sandbox_run_command,
)
__all__ = [
"code_execute",
"sandbox_run_command",
"sandbox_file_write",
"sandbox_file_read",
"sandbox_reset",
]
+42
View File
@@ -0,0 +1,42 @@
"""Base classes and data types for the Code Sandbox extension."""
from abc import ABC, abstractmethod
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
@dataclass
class ExecutionResult:
"""Result of sandbox code or command execution."""
stdout: str
stderr: str
exit_code: int
duration_seconds: float
timed_out: bool = False
@property
def success(self) -> bool:
return self.exit_code == 0 and not self.timed_out
class BaseSandboxBackend(ABC):
"""Abstract interface for a sandbox execution backend."""
@abstractmethod
def is_available(self) -> bool:
"""Check if this backend can be used on the current host system."""
pass
@abstractmethod
async def execute(
self,
cmd: list[str],
workspace_dir: Path,
timeout: int,
allow_network: bool = False,
env: Optional[dict[str, str]] = None,
) -> ExecutionResult:
"""Execute a command inside the isolated sandbox."""
pass
+135
View File
@@ -0,0 +1,135 @@
"""Bubblewrap (bwrap) sandbox backend providing Linux namespace isolation."""
import asyncio
import logging
import os
from pathlib import Path
import shutil
import signal
import time
from typing import Optional
from extensions.sandbox.base import BaseSandboxBackend, ExecutionResult
from homeagent.config import get_settings
logger = logging.getLogger(__name__)
class BubblewrapBackend(BaseSandboxBackend):
"""Executes processes inside an unprivileged Bubblewrap container namespace."""
def __init__(self) -> None:
self.settings = get_settings()
self.bwrap_bin = shutil.which("bwrap")
def is_available(self) -> bool:
return bool(self.bwrap_bin and os.path.exists("/usr"))
async def execute(
self,
cmd: list[str],
workspace_dir: Path,
timeout: int,
allow_network: bool = False,
env: Optional[dict[str, str]] = None,
) -> ExecutionResult:
if not self.bwrap_bin:
raise RuntimeError("bwrap executable is not installed or not in PATH.")
workspace_dir.mkdir(parents=True, exist_ok=True)
mem_kb = self.settings.SANDBOX_MEMORY_LIMIT_MB * 1024
bwrap_args: list[str] = [
self.bwrap_bin,
"--ro-bind", "/usr", "/usr",
"--proc", "/proc",
"--dev", "/dev",
"--tmpfs", "/tmp",
"--bind", str(workspace_dir), "/workspace",
"--chdir", "/workspace",
"--die-with-parent",
"--setenv", "PATH", "/usr/bin:/bin",
"--setenv", "HOME", "/workspace",
"--setenv", "LANG", "C.UTF-8",
"--setenv", "LC_ALL", "C.UTF-8",
"--setenv", "PYTHONIOENCODING", "utf-8",
]
# Standard symlinks across modern Linux
if os.path.exists("/lib64"):
bwrap_args.extend(["--symlink", "usr/lib64", "/lib64"])
if os.path.exists("/lib"):
bwrap_args.extend(["--symlink", "usr/lib", "/lib"])
if os.path.exists("/bin"):
bwrap_args.extend(["--symlink", "usr/bin", "/bin"])
if os.path.exists("/sbin"):
bwrap_args.extend(["--symlink", "usr/bin", "/sbin"])
# Network isolation
if not allow_network:
bwrap_args.append("--unshare-all")
else:
bwrap_args.extend(["--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup"])
if os.path.exists("/etc/resolv.conf"):
bwrap_args.extend(["--ro-bind", "/etc/resolv.conf", "/etc/resolv.conf"])
if os.path.exists("/etc/ssl"):
bwrap_args.extend(["--ro-bind", "/etc/ssl", "/etc/ssl"])
if os.path.exists("/etc/ca-certificates"):
bwrap_args.extend(["--ro-bind", "/etc/ca-certificates", "/etc/ca-certificates"])
# Custom environment variables
if env:
for k, v in env.items():
bwrap_args.extend(["--setenv", k, v])
# Apply memory ulimit via bash wrapper
quoted_cmd = " ".join(f'"{c}"' if " " in c else c for c in cmd)
wrapped_script = f"ulimit -v {mem_kb} 2>/dev/null; exec {quoted_cmd}"
full_cmd = bwrap_args + ["bash", "-c", wrapped_script]
start_time = time.monotonic()
try:
proc = await asyncio.create_subprocess_exec(
*full_cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
preexec_fn=os.setsid,
)
try:
stdout_data, stderr_data = await asyncio.wait_for(
proc.communicate(),
timeout=float(timeout),
)
duration = time.monotonic() - start_time
return ExecutionResult(
stdout=stdout_data.decode("utf-8", errors="replace"),
stderr=stderr_data.decode("utf-8", errors="replace"),
exit_code=proc.returncode if proc.returncode is not None else -1,
duration_seconds=round(duration, 3),
timed_out=False,
)
except asyncio.TimeoutError:
duration = time.monotonic() - start_time
logger.warning("Sandbox process timed out after %ds, killing process group", timeout)
try:
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
except ProcessLookupError:
pass
return ExecutionResult(
stdout="",
stderr=f"Ошибка: превышен максимальный таймаут выполнения ({timeout} сек). Процесс принудительно остановлен.",
exit_code=-1,
duration_seconds=round(duration, 3),
timed_out=True,
)
except Exception as e:
duration = time.monotonic() - start_time
logger.error("Failed to execute in Bubblewrap sandbox: %s", e)
return ExecutionResult(
stdout="",
stderr=f"Bubblewrap execution error: {type(e).__name__}: {str(e)}",
exit_code=-1,
duration_seconds=round(duration, 3),
timed_out=False,
)
+133
View File
@@ -0,0 +1,133 @@
"""Docker sandbox backend providing container isolation."""
import asyncio
import logging
import os
from pathlib import Path
import shutil
import signal
import subprocess
import time
from typing import Optional
from extensions.sandbox.base import BaseSandboxBackend, ExecutionResult
from homeagent.config import get_settings
logger = logging.getLogger(__name__)
class DockerBackend(BaseSandboxBackend):
"""Executes processes inside isolated Docker containers."""
def __init__(self) -> None:
self.settings = get_settings()
self.docker_bin = shutil.which("docker")
self._available: Optional[bool] = None
def is_available(self) -> bool:
if self._available is not None:
return self._available
if not self.docker_bin:
self._available = False
return False
try:
# Check if Docker daemon is running and accessible
res = subprocess.run(
[self.docker_bin, "info"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=3.0,
)
self._available = (res.returncode == 0)
except Exception:
self._available = False
return self._available
async def execute(
self,
cmd: list[str],
workspace_dir: Path,
timeout: int,
allow_network: bool = False,
env: Optional[dict[str, str]] = None,
) -> ExecutionResult:
if not self.is_available():
raise RuntimeError("Docker is not available or daemon is not running.")
workspace_dir.mkdir(parents=True, exist_ok=True)
mem_mb = self.settings.SANDBOX_MEMORY_LIMIT_MB
cpus = self.settings.SANDBOX_CPU_LIMIT
image = self.settings.SANDBOX_DOCKER_IMAGE
docker_args: list[str] = [
self.docker_bin,
"run",
"--rm",
"-i",
"--read-only",
"--tmpfs", "/tmp:rw,noexec,nosuid,size=64m",
"--memory", f"{mem_mb}m",
"--cpus", str(cpus),
"-v", f"{workspace_dir}:/workspace:rw",
"-w", "/workspace",
]
if not allow_network:
docker_args.extend(["--network", "none"])
if env:
for k, v in env.items():
docker_args.extend(["-e", f"{k}={v}"])
docker_args.append(image)
docker_args.extend(cmd)
start_time = time.monotonic()
try:
proc = await asyncio.create_subprocess_exec(
*docker_args,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
preexec_fn=os.setsid,
)
try:
stdout_data, stderr_data = await asyncio.wait_for(
proc.communicate(),
timeout=float(timeout),
)
duration = time.monotonic() - start_time
return ExecutionResult(
stdout=stdout_data.decode("utf-8", errors="replace"),
stderr=stderr_data.decode("utf-8", errors="replace"),
exit_code=proc.returncode if proc.returncode is not None else -1,
duration_seconds=round(duration, 3),
timed_out=False,
)
except asyncio.TimeoutError:
duration = time.monotonic() - start_time
logger.warning("Docker sandbox timed out after %ds, killing container", timeout)
try:
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
except ProcessLookupError:
pass
return ExecutionResult(
stdout="",
stderr=f"Ошибка: превышен максимальный таймаут выполнения ({timeout} сек).",
exit_code=-1,
duration_seconds=round(duration, 3),
timed_out=True,
)
except Exception as e:
duration = time.monotonic() - start_time
logger.error("Failed to execute in Docker sandbox: %s", e)
return ExecutionResult(
stdout="",
stderr=f"Docker sandbox error: {type(e).__name__}: {str(e)}",
exit_code=-1,
duration_seconds=round(duration, 3),
timed_out=False,
)
+164
View File
@@ -0,0 +1,164 @@
"""Sandbox Manager for managing workspace files and selecting the active isolation backend."""
import logging
import os
from pathlib import Path
import shutil
from typing import Optional
from extensions.sandbox.base import BaseSandboxBackend, ExecutionResult
from extensions.sandbox.bwrap_backend import BubblewrapBackend
from extensions.sandbox.docker_backend import DockerBackend
from extensions.sandbox.process_backend import ProcessBackend
from homeagent.config import get_settings
logger = logging.getLogger(__name__)
class SandboxManager:
"""Manages the isolated workspace and executes code/commands via the selected sandbox backend."""
def __init__(self) -> None:
self.settings = get_settings()
self.workspace_dir: Path = self.settings.DATA_DIR / "sandbox_workspace"
self.workspace_dir.mkdir(parents=True, exist_ok=True)
self._bwrap = BubblewrapBackend()
self._docker = DockerBackend()
self._process = ProcessBackend()
self._active_backend: Optional[BaseSandboxBackend] = None
def get_backend(self) -> BaseSandboxBackend:
if self._active_backend is not None:
return self._active_backend
choice = self.settings.SANDBOX_BACKEND.lower()
if choice == "bwrap":
if self._bwrap.is_available():
self._active_backend = self._bwrap
logger.info("Sandbox using Bubblewrap (bwrap) backend.")
return self._active_backend
logger.warning("Configured backend 'bwrap' unavailable, falling back to process.")
elif choice == "docker":
if self._docker.is_available():
self._active_backend = self._docker
logger.info("Sandbox using Docker backend.")
return self._active_backend
logger.warning("Configured backend 'docker' unavailable, falling back to process.")
elif choice == "process":
self._active_backend = self._process
logger.info("Sandbox using Process backend.")
return self._active_backend
# Auto detection: bwrap -> docker -> process
if self._bwrap.is_available():
self._active_backend = self._bwrap
logger.info("Sandbox auto-selected Bubblewrap (bwrap) backend.")
elif self._docker.is_available():
self._active_backend = self._docker
logger.info("Sandbox auto-selected Docker backend.")
else:
self._active_backend = self._process
logger.info("Sandbox auto-selected Process backend.")
return self._active_backend
def get_backend_name(self) -> str:
backend = self.get_backend()
if isinstance(backend, BubblewrapBackend):
return "Bubblewrap (bwrap, Linux Namespaces)"
if isinstance(backend, DockerBackend):
return "Docker Container"
return "Process Sandbox (Resource Limits)"
def _resolve_safe_path(self, filename: str) -> Path:
"""Resolve path inside workspace and prevent directory traversal outside workspace."""
clean_name = filename.strip().lstrip("/\\")
target_path = (self.workspace_dir / clean_name).resolve()
workspace_resolved = self.workspace_dir.resolve()
if not str(target_path).startswith(str(workspace_resolved)):
raise ValueError(f"Access denied: path '{filename}' points outside the sandbox workspace.")
return target_path
def write_file(self, filename: str, content: str) -> Path:
"""Safely write a file to the sandbox workspace."""
path = self._resolve_safe_path(filename)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
return path
def read_file(self, filename: str, max_chars: int = 8000) -> str:
"""Safely read a file from the sandbox workspace."""
path = self._resolve_safe_path(filename)
if not path.exists() or not path.is_file():
raise FileNotFoundError(f"File '{filename}' does not exist in sandbox workspace.")
content = path.read_text(encoding="utf-8", errors="replace")
if len(content) > max_chars:
content = content[:max_chars] + f"\n\n... [Файл обрезан, показано первые {max_chars} символов]"
return content
def clean_workspace(self) -> None:
"""Remove all files inside sandbox workspace."""
if self.workspace_dir.exists():
for item in self.workspace_dir.iterdir():
try:
if item.is_dir():
shutil.rmtree(item)
else:
item.unlink()
except Exception as e:
logger.warning("Could not delete workspace item %s: %s", item, e)
async def run_code(
self,
code: str,
language: str = "python",
timeout: Optional[int] = None,
) -> ExecutionResult:
"""Execute code in the isolated sandbox."""
lang = language.lower().strip()
effective_timeout = timeout or self.settings.SANDBOX_TIMEOUT_SECONDS
backend = self.get_backend()
if lang in ("python", "py", "python3"):
script_path = self.write_file("main.py", code)
cmd = ["python3", "main.py"]
elif lang in ("bash", "sh"):
script_path = self.write_file("script.sh", code)
cmd = ["bash", "script.sh"]
elif lang in ("javascript", "js", "node"):
script_path = self.write_file("index.js", code)
cmd = ["node", "index.js"]
else:
raise ValueError(
f"Unsupported language '{language}'. Supported languages: 'python', 'bash', 'javascript'."
)
return await backend.execute(
cmd=cmd,
workspace_dir=self.workspace_dir,
timeout=effective_timeout,
allow_network=self.settings.SANDBOX_ALLOW_NETWORK,
)
async def run_command(
self,
command: str,
timeout: Optional[int] = None,
) -> ExecutionResult:
"""Execute a shell command inside the isolated sandbox."""
effective_timeout = timeout or self.settings.SANDBOX_TIMEOUT_SECONDS
backend = self.get_backend()
cmd = ["bash", "-c", command]
return await backend.execute(
cmd=cmd,
workspace_dir=self.workspace_dir,
timeout=effective_timeout,
allow_network=self.settings.SANDBOX_ALLOW_NETWORK,
)
+116
View File
@@ -0,0 +1,116 @@
"""Process sandbox backend using resource limits and sanitized environment."""
import asyncio
import logging
import os
from pathlib import Path
import resource
import signal
import time
from typing import Optional
from extensions.sandbox.base import BaseSandboxBackend, ExecutionResult
from homeagent.config import get_settings
logger = logging.getLogger(__name__)
class ProcessBackend(BaseSandboxBackend):
"""Fallback sandbox running subprocess with resource limits and stripped environment."""
def __init__(self) -> None:
self.settings = get_settings()
def is_available(self) -> bool:
return True
async def execute(
self,
cmd: list[str],
workspace_dir: Path,
timeout: int,
allow_network: bool = False,
env: Optional[dict[str, str]] = None,
) -> ExecutionResult:
workspace_dir.mkdir(parents=True, exist_ok=True)
mem_bytes = self.settings.SANDBOX_MEMORY_LIMIT_MB * 1024 * 1024
def _setup_child_limits() -> None:
# Set new process group so we can cleanly kill all children
os.setsid()
try:
# Limit virtual memory
resource.setrlimit(resource.RLIMIT_AS, (mem_bytes, mem_bytes))
except Exception:
pass
try:
# Limit CPU time
resource.setrlimit(resource.RLIMIT_CPU, (timeout + 5, timeout + 5))
except Exception:
pass
try:
# Limit max open files
resource.setrlimit(resource.RLIMIT_NOFILE, (128, 128))
except Exception:
pass
# Completely sanitize environment: do NOT leak host variables or secrets (.env)
safe_env = {
"PATH": os.environ.get("PATH", "/usr/bin:/bin"),
"LANG": "C.UTF-8",
"LC_ALL": "C.UTF-8",
"HOME": str(workspace_dir),
"TMPDIR": str(workspace_dir),
"PYTHONIOENCODING": "utf-8",
}
if env:
safe_env.update(env)
start_time = time.monotonic()
try:
proc = await asyncio.create_subprocess_exec(
*cmd,
cwd=str(workspace_dir),
env=safe_env,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
preexec_fn=_setup_child_limits,
)
try:
stdout_data, stderr_data = await asyncio.wait_for(
proc.communicate(),
timeout=float(timeout),
)
duration = time.monotonic() - start_time
return ExecutionResult(
stdout=stdout_data.decode("utf-8", errors="replace"),
stderr=stderr_data.decode("utf-8", errors="replace"),
exit_code=proc.returncode if proc.returncode is not None else -1,
duration_seconds=round(duration, 3),
timed_out=False,
)
except asyncio.TimeoutError:
duration = time.monotonic() - start_time
logger.warning("Process sandbox timed out after %ds", timeout)
try:
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
except ProcessLookupError:
pass
return ExecutionResult(
stdout="",
stderr=f"Ошибка: превышен максимальный таймаут выполнения ({timeout} сек).",
exit_code=-1,
duration_seconds=round(duration, 3),
timed_out=True,
)
except Exception as e:
duration = time.monotonic() - start_time
logger.error("Failed to execute in Process sandbox: %s", e)
return ExecutionResult(
stdout="",
stderr=f"Process execution error: {type(e).__name__}: {str(e)}",
exit_code=-1,
duration_seconds=round(duration, 3),
timed_out=False,
)
+190
View File
@@ -0,0 +1,190 @@
"""Sandbox tools exposed to HomeAgent, Gemini, DeepSeek, and subagents."""
import logging
from typing import Optional
from extensions.sandbox.manager import SandboxManager
from homeagent.config import get_settings
from homeagent.tools.base import tool
logger = logging.getLogger(__name__)
_sandbox_manager: Optional[SandboxManager] = None
def get_sandbox_manager() -> SandboxManager:
global _sandbox_manager
if _sandbox_manager is None:
_sandbox_manager = SandboxManager()
return _sandbox_manager
@tool(
name="code_execute",
description=(
"Безопасно выполнить код (Python, Bash, JavaScript) в изолированной песочнице (Sandbox). "
"Песочница полностью изолирована от хостовой системы (файлы хоста и секреты .env скрыты, сеть заблокирована, "
"лимит RAM 512МБ, строгий таймаут). Используй для математических вычислений, обработки данных, симуляций и проверки алгоритмов."
),
)
async def code_execute(
code: str,
language: str = "python",
timeout: int = 30,
) -> str:
"""Выполнить код в защищенной песочнице.
Args:
code: Исходный код программы (Python, Bash, JavaScript)
language: Язык программирования ('python', 'bash', 'javascript')
timeout: Максимальное время выполнения в секундах (по умолчанию 30, максимум 120)
"""
settings = get_settings()
if not settings.SANDBOX_ENABLED:
return "Изолированная песочница отключена в настройках (SANDBOX_ENABLED=False)."
clean_code = code.strip()
if not clean_code:
return "Ошибка: код для выполнения не может быть пустым."
mgr = get_sandbox_manager()
limit_timeout = max(1, min(timeout, 120))
try:
res = await mgr.run_code(clean_code, language=language, timeout=limit_timeout)
backend_name = mgr.get_backend_name()
lines = [f"⚙️ **[Sandbox: {backend_name}]** Язык: `{language}`, время: `{res.duration_seconds}s`, статус: `{'OK (код 0)' if res.exit_code == 0 else f'Ошибка (код {res.exit_code})'}`"]
if res.timed_out:
lines.append("⚠️ **Превышен лимит времени выполнения!** Процесс был принудительно завершен.")
if res.stdout.strip():
lines.append(f"\n**Вывод (stdout):**\n```\n{res.stdout.strip()}\n```")
if res.stderr.strip():
lines.append(f"\n**Ошибки (stderr):**\n```\n{res.stderr.strip()}\n```")
if not res.stdout.strip() and not res.stderr.strip():
lines.append("\n*(Программа завершилась без вывода в консоль)*")
return "\n".join(lines)
except Exception as e:
logger.error("code_execute failed: %s", e)
return f"Ошибка выполнения в песочнице: {type(e).__name__}: {str(e)}"
@tool(
name="sandbox_run_command",
description=(
"Выполнить консольную команду (Bash) внутри изолированной песочницы (Sandbox). "
"Хостовая файловая система и сеть изолированы, изменения производятся только во временной рабочей директории /workspace."
),
)
async def sandbox_run_command(
command: str,
timeout: int = 30,
) -> str:
"""Выполнить команду в песочнице.
Args:
command: Консольная команда для выполнения (например: 'ls -la', 'python3 -V', 'grep ...')
timeout: Максимальное время выполнения в секундах (по умолчанию 30)
"""
settings = get_settings()
if not settings.SANDBOX_ENABLED:
return "Изолированная песочница отключена в настройках (SANDBOX_ENABLED=False)."
clean_cmd = command.strip()
if not clean_cmd:
return "Ошибка: команда не может быть пустой."
mgr = get_sandbox_manager()
limit_timeout = max(1, min(timeout, 120))
try:
res = await mgr.run_command(clean_cmd, timeout=limit_timeout)
backend_name = mgr.get_backend_name()
lines = [f"💻 **[Sandbox: {backend_name}]** Команда: `{clean_cmd}`, время: `{res.duration_seconds}s`"]
if res.timed_out:
lines.append("⚠️ **Превышен лимит времени выполнения!** Команда была принудительно остановлена.")
if res.stdout.strip():
lines.append(f"\n**Вывод (stdout):**\n```\n{res.stdout.strip()}\n```")
if res.stderr.strip():
lines.append(f"\n**Ошибки (stderr):**\n```\n{res.stderr.strip()}\n```")
if not res.stdout.strip() and not res.stderr.strip():
lines.append("\n*(Команда выполнена успешно, вывод пуст)*")
return "\n".join(lines)
except Exception as e:
logger.error("sandbox_run_command failed: %s", e)
return f"Ошибка выполнения команды в песочнице: {type(e).__name__}: {str(e)}"
@tool(
name="sandbox_file_write",
description="Создать или перезаписать файл внутри изолированного рабочего пространства песочницы (/workspace).",
)
async def sandbox_file_write(filename: str, content: str) -> str:
"""Записать файл в песочницу.
Args:
filename: Имя файла или относительный путь (например 'data.csv', 'test.py', 'input.json')
content: Содержимое файла
"""
settings = get_settings()
if not settings.SANDBOX_ENABLED:
return "Изолированная песочница отключена в настройках (SANDBOX_ENABLED=False)."
mgr = get_sandbox_manager()
try:
saved_path = mgr.write_file(filename, content)
return f"Файл '{filename}' успешно создан в песочнице (размер: {len(content.encode('utf-8'))} байт)."
except Exception as e:
return f"Ошибка записи файла в песочницу: {type(e).__name__}: {str(e)}"
@tool(
name="sandbox_file_read",
description="Прочитать содержимое файла, созданного или обработанного внутри песочницы (/workspace).",
)
async def sandbox_file_read(filename: str, max_chars: int = 8000) -> str:
"""Прочитать файл из песочницы.
Args:
filename: Имя файла или относительный путь внутри песочницы
max_chars: Максимальное количество символов (по умолчанию 8000)
"""
settings = get_settings()
if not settings.SANDBOX_ENABLED:
return "Изолированная песочница отключена в настройках (SANDBOX_ENABLED=False)."
mgr = get_sandbox_manager()
try:
content = mgr.read_file(filename, max_chars=max(100, min(max_chars, 32000)))
return f"📄 Файл '{filename}' из песочницы:\n```\n{content}\n```"
except Exception as e:
return f"Ошибка чтения файла из песочницы: {type(e).__name__}: {str(e)}"
@tool(
name="sandbox_reset",
description="Очистить рабочее пространство песочницы (удалить все временные файлы и скрипты из /workspace).",
)
async def sandbox_reset() -> str:
"""Очистить рабочее пространство песочницы."""
settings = get_settings()
if not settings.SANDBOX_ENABLED:
return "Изолированная песочница отключена в настройках."
mgr = get_sandbox_manager()
try:
mgr.clean_workspace()
return "Рабочее пространство песочницы успешно очищено."
except Exception as e:
return f"Ошибка очистки песочницы: {type(e).__name__}: {str(e)}"
+8
View File
@@ -0,0 +1,8 @@
"""Web search and page content extraction extension for HomeAgent."""
from extensions.web_search.tools import web_fetch_page, web_search
__all__ = [
"web_search",
"web_fetch_page",
]
+161
View File
@@ -0,0 +1,161 @@
"""Web search and page content extraction client."""
import asyncio
from html.parser import HTMLParser
import logging
import re
from typing import Any, Optional
import httpx
from homeagent.config import get_settings
logger = logging.getLogger(__name__)
class _HTMLTextExtractor(HTMLParser):
"""HTML parser that strips scripts, styles, and chrome, extracting clean readable text."""
def __init__(self) -> None:
super().__init__()
self._pieces: list[str] = []
self._ignore_stack: list[str] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, Optional[str]]]) -> None:
tag_lower = tag.lower()
if tag_lower in ("script", "style", "noscript", "svg", "head", "header", "footer", "nav", "aside"):
self._ignore_stack.append(tag_lower)
elif tag_lower in ("p", "div", "br", "li", "h1", "h2", "h3", "h4", "h5", "h6", "tr", "article", "section"):
self._pieces.append("\n")
def handle_endtag(self, tag: str) -> None:
tag_lower = tag.lower()
if self._ignore_stack and self._ignore_stack[-1] == tag_lower:
self._ignore_stack.pop()
elif tag_lower in ("p", "div", "br", "li", "h1", "h2", "h3", "h4", "h5", "h6", "tr", "article", "section"):
self._pieces.append("\n")
def handle_data(self, data: str) -> None:
if not self._ignore_stack:
clean_text = data.strip()
if clean_text:
self._pieces.append(clean_text + " ")
def get_text(self) -> str:
raw = "".join(self._pieces)
# Collapse multiple empty lines and horizontal spaces
raw = re.sub(r"[ \t]+", " ", raw)
raw = re.sub(r"\n\s*\n\s*\n+", "\n\n", raw)
return raw.strip()
class WebSearchClient:
"""Client for web searches and fetching page content."""
def __init__(self) -> None:
self.settings = get_settings()
async def search(self, query: str, max_results: int = 5) -> list[dict[str, str]]:
"""Search the web for query using the configured provider.
Returns:
List of dicts: [{"title": ..., "url": ..., "snippet": ...}]
"""
provider = self.settings.WEB_SEARCH_PROVIDER.lower()
if provider == "tavily" and self.settings.TAVILY_API_KEY:
return await self._search_tavily(query, max_results)
elif provider == "searxng" and self.settings.SEARXNG_URL:
return await self._search_searxng(query, max_results)
# Default: DuckDuckGo (ddgs)
return await self._search_duckduckgo(query, max_results)
async def _search_duckduckgo(self, query: str, max_results: int = 5) -> list[dict[str, str]]:
def _ddg_sync() -> list[dict[str, str]]:
from ddgs import DDGS
ddgs = DDGS()
raw_results = list(ddgs.text(query, max_results=max_results))
out: list[dict[str, str]] = []
for item in raw_results:
out.append({
"title": item.get("title", "Без названия"),
"url": item.get("href", ""),
"snippet": item.get("body", ""),
})
return out
try:
return await asyncio.to_thread(_ddg_sync)
except Exception as e:
logger.error("DuckDuckGo search error for '%s': %s", query, e)
raise
async def _search_tavily(self, query: str, max_results: int = 5) -> list[dict[str, str]]:
api_key = self.settings.TAVILY_API_KEY.get_secret_value() if self.settings.TAVILY_API_KEY else ""
url = "https://api.tavily.com/search"
payload = {
"api_key": api_key,
"query": query,
"max_results": max_results,
"search_depth": "basic",
}
async with httpx.AsyncClient(timeout=15.0) as client:
resp = await client.post(url, json=payload)
resp.raise_for_status()
data = resp.json()
out: list[dict[str, str]] = []
for item in data.get("results", []):
out.append({
"title": item.get("title", "Без названия"),
"url": item.get("url", ""),
"snippet": item.get("content", ""),
})
return out
async def _search_searxng(self, query: str, max_results: int = 5) -> list[dict[str, str]]:
base_url = self.settings.SEARXNG_URL.rstrip("/") if self.settings.SEARXNG_URL else ""
url = f"{base_url}/search"
params = {"q": query, "format": "json"}
async with httpx.AsyncClient(timeout=15.0) as client:
resp = await client.get(url, params=params)
resp.raise_for_status()
data = resp.json()
out: list[dict[str, str]] = []
for item in data.get("results", [])[:max_results]:
out.append({
"title": item.get("title", "Без названия"),
"url": item.get("url", ""),
"snippet": item.get("content", ""),
})
return out
async def fetch_page(self, url: str, max_length: int = 4000) -> str:
"""Fetch URL and extract clean text content."""
headers = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/124.0.0.0 Safari/537.36 HomeAgent/1.0"
),
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7",
}
async with httpx.AsyncClient(timeout=15.0, follow_redirects=True, headers=headers) as client:
resp = await client.get(url)
resp.raise_for_status()
content_type = resp.headers.get("content-type", "").lower()
if "json" in content_type:
text = resp.text
elif "text" in content_type or "html" in content_type or not content_type:
parser = _HTMLTextExtractor()
parser.feed(resp.text)
text = parser.get_text()
else:
text = f"[Бинарный контент или неподдерживаемый тип: {content_type}]"
if len(text) > max_length:
text = text[:max_length] + "\n\n... [Контент обрезан из-за превышения длины]"
return text
+98
View File
@@ -0,0 +1,98 @@
"""Web search tools exposed to HomeAgent, Gemini, DeepSeek, and subagents."""
import logging
from typing import Optional
from extensions.web_search.client import WebSearchClient
from homeagent.config import get_settings
from homeagent.tools.base import tool
logger = logging.getLogger(__name__)
_search_client: Optional[WebSearchClient] = None
def get_search_client() -> WebSearchClient:
global _search_client
if _search_client is None:
_search_client = WebSearchClient()
return _search_client
@tool(
name="web_search",
description=(
"Искать актуальную информацию, новости, документацию, статьи или факты в интернете через поисковую систему. "
"Возвращает список релевантных ссылок с заголовками и краткими описаниями (сниппетами)."
),
)
async def web_search(query: str, max_results: int = 5) -> str:
"""Поиск информации в интернете.
Args:
query: Поисковый запрос (ключевые слова или вопрос)
max_results: Максимальное количество результатов (по умолчанию 5, максимум 10)
"""
settings = get_settings()
if not settings.WEB_SEARCH_ENABLED:
return "Поиск в интернете отключен в настройках (WEB_SEARCH_ENABLED=False)."
clean_query = query.strip()
if not clean_query:
return "Ошибка: поисковый запрос не может быть пустым."
limit = max(1, min(max_results, 10))
client = get_search_client()
try:
results = await client.search(clean_query, max_results=limit)
if not results:
return f"По запросу '{clean_query}' в интернете ничего не найдено."
lines = [f"🔍 Результаты поиска по запросу «{clean_query}» ({len(results)}):"]
for i, item in enumerate(results, 1):
title = item.get("title", "Без названия")
url = item.get("url", "")
snippet = item.get("snippet", "").strip()
lines.append(f"{i}. **[{title}]({url})**")
if snippet:
lines.append(f" {snippet}")
return "\n".join(lines)
except Exception as e:
logger.error("web_search failed for '%s': %s", clean_query, e)
return f"Ошибка при выполнении поиска в интернете: {type(e).__name__}: {str(e)}"
@tool(
name="web_fetch_page",
description=(
"Загрузить и прочитать текстовое содержимое веб-страницы по указанному URL (HTTP/HTTPS). "
"Полезно для детального изучения статей, новостей или технической документации, найденных через web_search."
),
)
async def web_fetch_page(url: str, max_length: int = 4000) -> str:
"""Загрузить и прочитать содержимое веб-страницы.
Args:
url: Полный URL веб-страницы (начинающийся с http:// или https://)
max_length: Максимальное количество символов для извлечения (по умолчанию 4000)
"""
settings = get_settings()
if not settings.WEB_SEARCH_ENABLED:
return "Поиск и чтение веб-страниц отключены в настройках (WEB_SEARCH_ENABLED=False)."
clean_url = url.strip()
if not clean_url.startswith(("http://", "https://")):
return f"Ошибка: некорректный URL '{clean_url}'. URL должен начинаться с http:// или https://"
client = get_search_client()
try:
content = await client.fetch_page(clean_url, max_length=max(500, min(max_length, 12000)))
if not content:
return f"Страница {clean_url} вернула пустой ответ или не содержит текста."
return f"📄 Содержимое страницы [{clean_url}]:\n---\n{content}"
except Exception as e:
logger.error("web_fetch_page failed for '%s': %s", clean_url, e)
return f"Ошибка при загрузке страницы {clean_url}: {type(e).__name__}: {str(e)}"