Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0f8fe091e3 | ||
|
|
f8da5b24c4 | ||
|
|
6bf62bc331 |
No files matched your search
+8
-5
@@ -8,14 +8,17 @@ services:
|
|||||||
init: true
|
init: true
|
||||||
env_file:
|
env_file:
|
||||||
- .env
|
- .env
|
||||||
environment:
|
|
||||||
# Application path inside the container; this must match the mount target.
|
|
||||||
DATA_DIR: /app/data
|
|
||||||
extra_hosts:
|
extra_hosts:
|
||||||
|
# Allows reaching host services (e.g. local Ollama, SearXNG, local Gitea) via host.docker.internal
|
||||||
- "host.docker.internal:host-gateway"
|
- "host.docker.internal:host-gateway"
|
||||||
volumes:
|
volumes:
|
||||||
# Override DATA_DIR_HOST in .env for a path outside the project directory.
|
# Persistent data: sessions, global memory, scratchpad notes, tokens
|
||||||
- "${DATA_DIR_HOST:-./data}:/app/data"
|
- ./data:/app/data
|
||||||
|
# Skills and extensions mounted for customization without rebuilding
|
||||||
- ./skills:/app/skills:ro
|
- ./skills:/app/skills:ro
|
||||||
- ./extensions:/app/extensions:ro
|
- ./extensions:/app/extensions:ro
|
||||||
- ./gcal.json:/app/gcal.json:ro
|
- ./gcal.json:/app/gcal.json:ro
|
||||||
|
# Uncomment to mount credentials files if placed in project root:
|
||||||
|
# - ./service_account.json:/app/service_account.json:ro
|
||||||
|
# - ./credentials.json:/app/credentials.json:ro
|
||||||
|
# - ./gcal.json:/app/gcal.json:ro
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
# ==============================================================================
|
|
||||||
# 5. Persistent Docker data directory (optional)
|
|
||||||
# ==============================================================================
|
|
||||||
# Host directory mounted to /app/data by docker-compose.yml.
|
|
||||||
# Default is ./data next to docker-compose.yml.
|
|
||||||
# Use an absolute path if the project directory is ephemeral:
|
|
||||||
# DATA_DIR_HOST=/srv/homeagent/data
|
|
||||||
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
# Durable Docker state
|
|
||||||
|
|
||||||
The bot stores runtime state in `/app/data`:
|
|
||||||
|
|
||||||
- `global_memory.json` — global facts and preferences;
|
|
||||||
- `sessions/` — conversation history;
|
|
||||||
- `calendar_token.json` — Google OAuth token, if enabled.
|
|
||||||
|
|
||||||
`docker-compose.yml` mounts the host directory `${DATA_DIR_HOST:-./data}` to `/app/data` and sets `DATA_DIR=/app/data` inside the container.
|
|
||||||
|
|
||||||
## First deployment / migration
|
|
||||||
|
|
||||||
Back up the existing state before recreating the container:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
mkdir -p data
|
|
||||||
cp -a data "data.backup.$(date +%Y%m%d-%H%M%S)"
|
|
||||||
|
|
||||||
# If the old container has the only copy, copy it BEFORE removing it:
|
|
||||||
docker cp homeagent:/app/data/. ./data/
|
|
||||||
|
|
||||||
docker compose config
|
|
||||||
docker compose up -d --build
|
|
||||||
```
|
|
||||||
|
|
||||||
If the old state was written into the container layer at another path, find it first:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker exec homeagent sh -lc 'find /app /root -maxdepth 4 -type f \( -name global_memory.json -o -path "*/sessions/*.json" \) -print'
|
|
||||||
```
|
|
||||||
|
|
||||||
## Verify after restart
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker compose exec homeagent sh -lc '\
|
|
||||||
printf "DATA_DIR=%s\\n" "$DATA_DIR"; \
|
|
||||||
mount | grep /app/data; \
|
|
||||||
ls -la /app/data; \
|
|
||||||
find /app/data/sessions -type f 2>/dev/null | head'
|
|
||||||
```
|
|
||||||
|
|
||||||
Then restart and verify the same files remain:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker compose restart homeagent
|
|
||||||
```
|
|
||||||
|
|
||||||
## Important
|
|
||||||
|
|
||||||
- Do not run `docker compose down -v` before backing up `data/`.
|
|
||||||
- Check `df -h .` and `docker system df`: a previous `No space left on device` error can prevent writes.
|
|
||||||
- This change cannot recover data that was already deleted; it only prevents future loss once deployed.
|
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
"""Retry Telegram requests that hit flood control (HTTP 429 / TelegramRetryAfter)."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
from typing import TYPE_CHECKING, Any, Iterable
|
||||||
|
|
||||||
|
from aiogram.client.session.middlewares.base import BaseRequestMiddleware, NextRequestMiddlewareType
|
||||||
|
from aiogram.exceptions import TelegramRetryAfter
|
||||||
|
from aiogram.methods import TelegramMethod
|
||||||
|
from aiogram.methods.base import Response, TelegramType
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from aiogram import Bot
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Methods used to deliver the final answer to the user.
|
||||||
|
# Progress edits (editMessageText) and deletes are intentionally excluded:
|
||||||
|
# they are cosmetic and must not stall the agent while it waits out a flood limit.
|
||||||
|
DEFAULT_RETRY_METHODS: frozenset[str] = frozenset(
|
||||||
|
{
|
||||||
|
"sendRichMessage",
|
||||||
|
"sendMessage",
|
||||||
|
"answerGuestQuery",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FloodRetryMiddleware(BaseRequestMiddleware):
|
||||||
|
"""Session middleware that waits `retry_after` seconds and retries on flood control.
|
||||||
|
|
||||||
|
Only TelegramRetryAfter is retried: Telegram guarantees the request was rejected,
|
||||||
|
so a retry cannot produce a duplicate message. Network/5xx errors are not retried
|
||||||
|
because the message might already have been delivered.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
max_retries: int = 3,
|
||||||
|
max_wait: float = 60.0,
|
||||||
|
extra_delay: float = 0.5,
|
||||||
|
methods: Iterable[str] = DEFAULT_RETRY_METHODS,
|
||||||
|
) -> None:
|
||||||
|
self.max_retries = max_retries
|
||||||
|
self.max_wait = max_wait
|
||||||
|
self.extra_delay = extra_delay
|
||||||
|
self.methods = frozenset(methods)
|
||||||
|
|
||||||
|
def _should_retry(self, method: TelegramMethod[Any]) -> bool:
|
||||||
|
return getattr(method, "__api_method__", None) in self.methods
|
||||||
|
|
||||||
|
async def __call__(
|
||||||
|
self,
|
||||||
|
make_request: NextRequestMiddlewareType[TelegramType],
|
||||||
|
bot: "Bot",
|
||||||
|
method: TelegramMethod[TelegramType],
|
||||||
|
) -> Response[TelegramType]:
|
||||||
|
if not self._should_retry(method):
|
||||||
|
return await make_request(bot, method)
|
||||||
|
|
||||||
|
attempt = 0
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
return await make_request(bot, method)
|
||||||
|
except TelegramRetryAfter as e:
|
||||||
|
attempt += 1
|
||||||
|
wait = float(e.retry_after) + self.extra_delay
|
||||||
|
if attempt > self.max_retries or wait > self.max_wait:
|
||||||
|
logger.error(
|
||||||
|
"Flood control on %s: giving up after %d attempt(s) (retry_after=%ss)",
|
||||||
|
method.__api_method__,
|
||||||
|
attempt,
|
||||||
|
e.retry_after,
|
||||||
|
)
|
||||||
|
raise
|
||||||
|
logger.warning(
|
||||||
|
"Flood control on %s: retry %d/%d in %.1fs",
|
||||||
|
method.__api_method__,
|
||||||
|
attempt,
|
||||||
|
self.max_retries,
|
||||||
|
wait,
|
||||||
|
)
|
||||||
|
await asyncio.sleep(wait)
|
||||||
@@ -13,6 +13,7 @@ from homeagent.agent.base import BaseAgent
|
|||||||
from homeagent.agent.factory import create_agent
|
from homeagent.agent.factory import create_agent
|
||||||
from homeagent.bot.handlers import create_bot_router
|
from homeagent.bot.handlers import create_bot_router
|
||||||
from homeagent.bot.middlewares import WhitelistMiddleware
|
from homeagent.bot.middlewares import WhitelistMiddleware
|
||||||
|
from homeagent.bot.retry import FloodRetryMiddleware
|
||||||
from homeagent.config import Settings, get_settings
|
from homeagent.config import Settings, get_settings
|
||||||
from homeagent.skills.manager import SkillManager
|
from homeagent.skills.manager import SkillManager
|
||||||
from homeagent.tools.loader import load_extensions_from_directory
|
from homeagent.tools.loader import load_extensions_from_directory
|
||||||
@@ -50,6 +51,8 @@ class TelegramAgentApp:
|
|||||||
token=token,
|
token=token,
|
||||||
default=DefaultBotProperties(parse_mode=ParseMode.MARKDOWN),
|
default=DefaultBotProperties(parse_mode=ParseMode.MARKDOWN),
|
||||||
)
|
)
|
||||||
|
# Retry final-answer sends (sendRichMessage/sendMessage/answerGuestQuery) on flood control
|
||||||
|
self.bot.session.middleware(FloodRetryMiddleware())
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning("Could not initialize Telegram Bot with provided token: %s", e)
|
logger.warning("Could not initialize Telegram Bot with provided token: %s", e)
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
|
||||||
import tempfile
|
|
||||||
import uuid
|
import uuid
|
||||||
from dataclasses import asdict, dataclass, field
|
from dataclasses import asdict, dataclass, field
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
@@ -25,7 +23,7 @@ class GlobalMemory:
|
|||||||
"""Persistent global memory store shared across all forum topics."""
|
"""Persistent global memory store shared across all forum topics."""
|
||||||
|
|
||||||
def __init__(self, storage_path: Path):
|
def __init__(self, storage_path: Path):
|
||||||
self.storage_path = Path(storage_path).expanduser().resolve()
|
self.storage_path = storage_path
|
||||||
self._items: dict[str, MemoryItem] = {}
|
self._items: dict[str, MemoryItem] = {}
|
||||||
self._load()
|
self._load()
|
||||||
|
|
||||||
@@ -33,10 +31,8 @@ class GlobalMemory:
|
|||||||
if not self.storage_path.exists():
|
if not self.storage_path.exists():
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
with self.storage_path.open("r", encoding="utf-8") as f:
|
with open(self.storage_path, "r", encoding="utf-8") as f:
|
||||||
data = json.load(f)
|
data = json.load(f)
|
||||||
if not isinstance(data, list):
|
|
||||||
raise ValueError("memory file must contain a JSON list")
|
|
||||||
for item_data in data:
|
for item_data in data:
|
||||||
item = MemoryItem(**item_data)
|
item = MemoryItem(**item_data)
|
||||||
self._items[item.id] = item
|
self._items[item.id] = item
|
||||||
@@ -45,73 +41,70 @@ class GlobalMemory:
|
|||||||
logger.error("Failed to load global memory from %s: %s", self.storage_path, e)
|
logger.error("Failed to load global memory from %s: %s", self.storage_path, e)
|
||||||
|
|
||||||
def _save(self) -> None:
|
def _save(self) -> None:
|
||||||
|
try:
|
||||||
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
|
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
payload = json.dumps([asdict(item) for item in self._items.values()], ensure_ascii=False, indent=2)
|
with open(self.storage_path, "w", encoding="utf-8") as f:
|
||||||
fd, temporary_path = tempfile.mkstemp(
|
json.dump([asdict(item) for item in self._items.values()], f, ensure_ascii=False, indent=2)
|
||||||
prefix=f".{self.storage_path.name}.", suffix=".tmp", dir=self.storage_path.parent
|
except Exception as e:
|
||||||
)
|
logger.error("Failed to save global memory to %s: %s", self.storage_path, e)
|
||||||
try:
|
|
||||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
||||||
f.write(payload)
|
|
||||||
f.flush()
|
|
||||||
os.fsync(f.fileno())
|
|
||||||
os.replace(temporary_path, self.storage_path)
|
|
||||||
except Exception:
|
|
||||||
try:
|
|
||||||
os.unlink(temporary_path)
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
raise
|
|
||||||
|
|
||||||
def add_fact(self, fact: str, category: str = "general") -> MemoryItem:
|
def add_fact(self, fact: str, category: str = "general") -> MemoryItem:
|
||||||
item = MemoryItem(id=str(uuid.uuid4())[:8], fact=fact.strip(), category=category.strip().lower())
|
"""Add a new fact or preference to global memory."""
|
||||||
self._items[item.id] = item
|
item_id = str(uuid.uuid4())[:8]
|
||||||
|
item = MemoryItem(id=item_id, fact=fact.strip(), category=category.strip().lower())
|
||||||
|
self._items[item_id] = item
|
||||||
self._save()
|
self._save()
|
||||||
logger.info("Added fact [%s] in category '%s': %s", item.id, item.category, item.fact)
|
logger.info("Added fact [%s] in category '%s': %s", item_id, item.category, item.fact)
|
||||||
return item
|
return item
|
||||||
|
|
||||||
def remove_fact(self, fact_id: str) -> bool:
|
def remove_fact(self, fact_id: str) -> bool:
|
||||||
if fact_id not in self._items:
|
"""Remove a fact by its ID."""
|
||||||
return False
|
if fact_id in self._items:
|
||||||
del self._items[fact_id]
|
del self._items[fact_id]
|
||||||
self._save()
|
self._save()
|
||||||
return True
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
def list_facts(self, category: Optional[str] = None) -> list[MemoryItem]:
|
def list_facts(self, category: Optional[str] = None) -> list[MemoryItem]:
|
||||||
|
"""List all facts, optionally filtered by category."""
|
||||||
if category:
|
if category:
|
||||||
cat = category.strip().lower()
|
cat = category.strip().lower()
|
||||||
return [item for item in self._items.values() if item.category == cat]
|
return [item for item in self._items.values() if item.category == cat]
|
||||||
return list(self._items.values())
|
return list(self._items.values())
|
||||||
|
|
||||||
def search(self, query: str) -> list[MemoryItem]:
|
def search(self, query: str) -> list[MemoryItem]:
|
||||||
|
"""Search memory for keywords in query."""
|
||||||
q = query.lower()
|
q = query.lower()
|
||||||
return [item for item in self._items.values() if q in item.fact.lower() or q in item.category.lower()]
|
return [
|
||||||
|
item for item in self._items.values()
|
||||||
|
if q in item.fact.lower() or q in item.category.lower()
|
||||||
|
]
|
||||||
|
|
||||||
def clear(self) -> None:
|
def clear(self) -> None:
|
||||||
|
"""Clear all stored memory."""
|
||||||
self._items.clear()
|
self._items.clear()
|
||||||
self._save()
|
self._save()
|
||||||
|
|
||||||
def get_memory_summary(self, max_items: int = 30) -> str:
|
def get_memory_summary(self, max_items: int = 30) -> str:
|
||||||
|
"""Produce a formatted summary of remembered facts for the system prompt."""
|
||||||
if not self._items:
|
if not self._items:
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
lines = ["\n[ГЛОБАЛЬНАЯ ПАМЯТЬ / ФАКТЫ О ПОЛЬЗОВАТЕЛЕ И ПРОЕКТЕ]:"]
|
lines = ["\n[ГЛОБАЛЬНАЯ ПАМЯТЬ / ФАКТЫ О ПОЛЬЗОВАТЕЛЕ И ПРОЕКТЕ]:"]
|
||||||
for item in list(self._items.values())[-max_items:]:
|
items = list(self._items.values())[-max_items:]
|
||||||
|
for item in items:
|
||||||
lines.append(f"- (id: {item.id}, категория: {item.category}) {item.fact}")
|
lines.append(f"- (id: {item.id}, категория: {item.category}) {item.fact}")
|
||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
_global_memory_instances: dict[Path, GlobalMemory] = {}
|
# Singleton instance container
|
||||||
|
_global_memory_instance: Optional[GlobalMemory] = None
|
||||||
|
|
||||||
|
|
||||||
def get_global_memory(storage_path: Optional[Path] = None) -> GlobalMemory:
|
def get_global_memory(storage_path: Optional[Path] = None) -> GlobalMemory:
|
||||||
"""Get the memory store keyed by its absolute path.
|
global _global_memory_instance
|
||||||
|
if _global_memory_instance is None:
|
||||||
DATA_DIR is used in Docker and keeps this store aligned with the mounted
|
|
||||||
application directory even when the process working directory changes.
|
|
||||||
"""
|
|
||||||
if storage_path is None:
|
if storage_path is None:
|
||||||
storage_path = Path(os.environ.get("DATA_DIR", "data")) / "global_memory.json"
|
storage_path = Path("data") / "global_memory.json"
|
||||||
path = Path(storage_path).expanduser().resolve()
|
_global_memory_instance = GlobalMemory(storage_path)
|
||||||
if path not in _global_memory_instances:
|
return _global_memory_instance
|
||||||
_global_memory_instances[path] = GlobalMemory(path)
|
|
||||||
return _global_memory_instances[path]
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
"""Regression tests for durable global memory."""
|
|
||||||
|
|
||||||
from homeagent.memory.global_memory import GlobalMemory, get_global_memory
|
|
||||||
|
|
||||||
|
|
||||||
def test_memory_survives_new_instance(tmp_path):
|
|
||||||
path = tmp_path / "data" / "global_memory.json"
|
|
||||||
memory = GlobalMemory(path)
|
|
||||||
item = memory.add_fact("сохранить после рестарта", category="reliability")
|
|
||||||
|
|
||||||
restarted = GlobalMemory(path)
|
|
||||||
assert restarted.search("рестарта")[0].id == item.id
|
|
||||||
assert not list(path.parent.glob("*.tmp"))
|
|
||||||
|
|
||||||
|
|
||||||
def test_memory_uses_distinct_paths(tmp_path):
|
|
||||||
first_path = tmp_path / "one" / "global_memory.json"
|
|
||||||
second_path = tmp_path / "two" / "global_memory.json"
|
|
||||||
first = get_global_memory(first_path)
|
|
||||||
second = get_global_memory(second_path)
|
|
||||||
|
|
||||||
assert first is not second
|
|
||||||
first.add_fact("только в первом")
|
|
||||||
assert second.list_facts() == []
|
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"""Unit tests for FloodRetryMiddleware (Telegram flood control retries)."""
|
||||||
|
|
||||||
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from aiogram.exceptions import TelegramBadRequest, TelegramRetryAfter
|
||||||
|
from aiogram.methods import EditMessageText, SendMessage
|
||||||
|
|
||||||
|
import homeagent.bot.retry as retry_mod
|
||||||
|
from homeagent.bot.retry import FloodRetryMiddleware
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def no_sleep(monkeypatch):
|
||||||
|
sleep = AsyncMock()
|
||||||
|
monkeypatch.setattr(retry_mod.asyncio, "sleep", sleep)
|
||||||
|
return sleep
|
||||||
|
|
||||||
|
|
||||||
|
def _flood(method, seconds: int = 3) -> TelegramRetryAfter:
|
||||||
|
return TelegramRetryAfter(method=method, message="Too Many Requests", retry_after=seconds)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_retries_then_succeeds(no_sleep):
|
||||||
|
method = SendMessage(chat_id=1, text="final answer")
|
||||||
|
make_request = AsyncMock(side_effect=[_flood(method, 3), _flood(method, 5), "ok"])
|
||||||
|
|
||||||
|
result = await FloodRetryMiddleware(extra_delay=0.5)(make_request, MagicMock(), method)
|
||||||
|
|
||||||
|
assert result == "ok"
|
||||||
|
assert make_request.await_count == 3
|
||||||
|
assert [c.args[0] for c in no_sleep.await_args_list] == [3.5, 5.5]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_gives_up_after_max_retries(no_sleep):
|
||||||
|
method = SendMessage(chat_id=1, text="final answer")
|
||||||
|
make_request = AsyncMock(side_effect=_flood(method, 1))
|
||||||
|
|
||||||
|
with pytest.raises(TelegramRetryAfter):
|
||||||
|
await FloodRetryMiddleware(max_retries=2)(make_request, MagicMock(), method)
|
||||||
|
|
||||||
|
assert make_request.await_count == 3 # 1 initial + 2 retries
|
||||||
|
|
||||||
|
|
||||||
|
async def test_gives_up_when_wait_too_long(no_sleep):
|
||||||
|
method = SendMessage(chat_id=1, text="final answer")
|
||||||
|
make_request = AsyncMock(side_effect=_flood(method, 600))
|
||||||
|
|
||||||
|
with pytest.raises(TelegramRetryAfter):
|
||||||
|
await FloodRetryMiddleware(max_wait=60)(make_request, MagicMock(), method)
|
||||||
|
|
||||||
|
assert make_request.await_count == 1
|
||||||
|
no_sleep.assert_not_awaited()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_does_not_retry_progress_edits(no_sleep):
|
||||||
|
method = EditMessageText(chat_id=1, message_id=1, text="⏳")
|
||||||
|
make_request = AsyncMock(side_effect=_flood(method, 1))
|
||||||
|
|
||||||
|
with pytest.raises(TelegramRetryAfter):
|
||||||
|
await FloodRetryMiddleware()(make_request, MagicMock(), method)
|
||||||
|
|
||||||
|
assert make_request.await_count == 1
|
||||||
|
no_sleep.assert_not_awaited()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_does_not_retry_other_errors(no_sleep):
|
||||||
|
method = SendMessage(chat_id=1, text="bad *markdown")
|
||||||
|
make_request = AsyncMock(side_effect=TelegramBadRequest(method=method, message="can't parse entities"))
|
||||||
|
|
||||||
|
with pytest.raises(TelegramBadRequest):
|
||||||
|
await FloodRetryMiddleware()(make_request, MagicMock(), method)
|
||||||
|
|
||||||
|
assert make_request.await_count == 1
|
||||||
Reference in new issue
Block a user