2026-04-10 17:43:42 +08:00
|
|
|
"""Auto compact: proactive compression of idle sessions to reduce token cost and latency."""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
2026-04-13 11:27:16 +08:00
|
|
|
from collections.abc import Collection
|
2026-04-10 17:43:42 +08:00
|
|
|
from datetime import datetime
|
2026-08-19 15:29:22 +08:00
|
|
|
from typing import TYPE_CHECKING, Any, Callable, Coroutine
|
2026-04-10 17:43:42 +08:00
|
|
|
|
|
|
|
|
from loguru import logger
|
2026-05-07 16:17:27 +08:00
|
|
|
|
2026-09-06 02:11:19 +08:00
|
|
|
from nanobot.events import NO_EVENTS, EventSink
|
2026-09-23 14:05:54 +08:00
|
|
|
from nanobot.session.keys import is_dream_session
|
2026-09-08 13:16:45 +08:00
|
|
|
from nanobot.session.manager import Session, SessionManager
|
|
|
|
|
from nanobot.session.summary import (
|
|
|
|
|
SessionSummary,
|
|
|
|
|
is_summary_checkpoint,
|
|
|
|
|
session_summary_from_metadata,
|
|
|
|
|
)
|
2026-04-10 17:43:42 +08:00
|
|
|
|
|
|
|
|
if TYPE_CHECKING:
|
|
|
|
|
from nanobot.agent.memory import Consolidator
|
2026-07-10 14:52:51 +08:00
|
|
|
from nanobot.utils.llm_runtime import LLMRuntime
|
2026-04-10 17:43:42 +08:00
|
|
|
|
2026-09-06 02:11:19 +08:00
|
|
|
SessionEventFactory = Callable[[str], EventSink]
|
2026-09-05 20:21:54 +08:00
|
|
|
|
2026-04-10 17:43:42 +08:00
|
|
|
|
|
|
|
|
class AutoCompact:
|
|
|
|
|
def __init__(self, sessions: SessionManager, consolidator: Consolidator,
|
2026-09-05 20:21:54 +08:00
|
|
|
session_ttl_minutes: int = 0,
|
2026-09-06 02:11:19 +08:00
|
|
|
bind_events: SessionEventFactory | None = None):
|
2026-04-10 17:43:42 +08:00
|
|
|
self.sessions = sessions
|
|
|
|
|
self.consolidator = consolidator
|
|
|
|
|
self._ttl = session_ttl_minutes
|
|
|
|
|
self._archiving: set[str] = set()
|
2026-08-19 15:29:22 +08:00
|
|
|
self._summaries: dict[str, SessionSummary] = {}
|
2026-09-06 02:11:19 +08:00
|
|
|
self._bind_events = bind_events
|
2026-04-10 17:43:42 +08:00
|
|
|
|
2026-04-13 11:27:16 +08:00
|
|
|
def _is_expired(self, ts: datetime | str | None,
|
|
|
|
|
now: datetime | None = None) -> bool:
|
2026-06-30 21:13:53 +08:00
|
|
|
if self._ttl <= 0 or not ts:
|
2026-04-10 17:43:42 +08:00
|
|
|
return False
|
2026-07-27 19:10:24 +08:00
|
|
|
try:
|
|
|
|
|
if isinstance(ts, str):
|
|
|
|
|
ts = datetime.fromisoformat(ts)
|
|
|
|
|
current = now or datetime.now()
|
|
|
|
|
if getattr(ts, "tzinfo", None) is not None or current.tzinfo is not None:
|
|
|
|
|
idle_seconds = current.timestamp() - ts.timestamp()
|
|
|
|
|
else:
|
|
|
|
|
idle_seconds = (current - ts).total_seconds()
|
|
|
|
|
except (OSError, OverflowError, TypeError, ValueError):
|
|
|
|
|
# list_sessions() forwards raw persisted metadata; an unusable value
|
|
|
|
|
# must not escape the idle scan and stop the agent loop.
|
|
|
|
|
return False
|
|
|
|
|
return idle_seconds >= self._ttl * 60
|
2026-06-30 18:00:41 +08:00
|
|
|
|
2026-08-07 11:26:03 +08:00
|
|
|
def _has_unarchived_messages(self, key: str) -> bool:
|
2026-06-30 20:49:45 +08:00
|
|
|
session = self.sessions.get_or_create(key)
|
2026-09-05 20:21:54 +08:00
|
|
|
return any(
|
2026-09-08 13:16:45 +08:00
|
|
|
not message.get("_command") and not is_summary_checkpoint(message)
|
2026-09-05 20:21:54 +08:00
|
|
|
for message in session.messages[session.last_archived:]
|
|
|
|
|
)
|
2026-04-10 17:43:42 +08:00
|
|
|
|
2026-07-10 14:52:51 +08:00
|
|
|
def check_expired(
|
|
|
|
|
self,
|
2026-07-29 21:37:11 +08:00
|
|
|
schedule_background: Callable[[Coroutine[Any, Any, None]], None],
|
2026-07-23 00:38:49 +08:00
|
|
|
resolve_runtime: Callable[[Session], LLMRuntime],
|
2026-07-10 14:52:51 +08:00
|
|
|
active_session_keys: Collection[str] = (),
|
|
|
|
|
) -> None:
|
2026-04-13 11:27:16 +08:00
|
|
|
"""Schedule archival for idle sessions, skipping those with in-flight agent tasks."""
|
|
|
|
|
now = datetime.now()
|
2026-04-10 17:43:42 +08:00
|
|
|
for info in self.sessions.list_sessions():
|
|
|
|
|
key = info.get("key", "")
|
2026-09-23 14:05:54 +08:00
|
|
|
# Dream sessions are per-run; persistent maintenance sessions still compact.
|
|
|
|
|
if not key or is_dream_session(key) or key in self._archiving:
|
2026-04-13 11:27:16 +08:00
|
|
|
continue
|
|
|
|
|
if key in active_session_keys:
|
|
|
|
|
continue
|
2026-06-30 18:00:41 +08:00
|
|
|
updated_at = info.get("updated_at")
|
2026-08-07 11:26:03 +08:00
|
|
|
if self._is_expired(updated_at, now) and self._has_unarchived_messages(key):
|
2026-07-23 00:38:49 +08:00
|
|
|
session = self.sessions.get_or_create(key)
|
|
|
|
|
try:
|
|
|
|
|
runtime = resolve_runtime(session)
|
|
|
|
|
except (KeyError, ValueError):
|
|
|
|
|
# Invalid session selections remain recoverable through /model.
|
|
|
|
|
continue
|
2026-04-10 17:43:42 +08:00
|
|
|
self._archiving.add(key)
|
2026-07-10 14:52:51 +08:00
|
|
|
schedule_background(self._archive(key, runtime=runtime))
|
2026-04-10 17:43:42 +08:00
|
|
|
|
2026-07-10 14:52:51 +08:00
|
|
|
async def _archive(self, key: str, *, runtime: LLMRuntime) -> None:
|
2026-09-23 14:05:54 +08:00
|
|
|
if is_dream_session(key):
|
2026-06-02 22:46:47 +08:00
|
|
|
self._archiving.discard(key)
|
|
|
|
|
return
|
2026-04-10 17:43:42 +08:00
|
|
|
try:
|
2026-05-17 21:30:44 +08:00
|
|
|
summary = await self.consolidator.compact_idle_session(
|
2026-07-10 14:52:51 +08:00
|
|
|
key,
|
|
|
|
|
runtime=runtime,
|
2026-09-06 02:11:19 +08:00
|
|
|
events=self._bind_events(key) if self._bind_events else NO_EVENTS,
|
2026-05-17 21:30:44 +08:00
|
|
|
)
|
2026-09-08 13:16:45 +08:00
|
|
|
if summary:
|
2026-05-17 21:30:44 +08:00
|
|
|
session = self.sessions.get_or_create(key)
|
2026-08-19 16:18:05 +08:00
|
|
|
stored = session_summary_from_metadata(
|
2026-08-19 15:29:22 +08:00
|
|
|
session.metadata,
|
|
|
|
|
fallback_last_active=session.updated_at,
|
|
|
|
|
)
|
|
|
|
|
if stored is not None:
|
|
|
|
|
self._summaries[key] = stored
|
2026-04-10 17:43:42 +08:00
|
|
|
except Exception:
|
|
|
|
|
logger.exception("Auto-compact: failed for {}", key)
|
|
|
|
|
finally:
|
|
|
|
|
self._archiving.discard(key)
|
|
|
|
|
|
2026-08-19 15:35:29 +08:00
|
|
|
def prepare_session(self, session: Session, key: str) -> tuple[Session, SessionSummary | None]:
|
2026-09-23 14:05:54 +08:00
|
|
|
if is_dream_session(key):
|
2026-06-02 22:46:47 +08:00
|
|
|
self._archiving.discard(key)
|
|
|
|
|
self._summaries.pop(key, None)
|
|
|
|
|
return session, None
|
2026-04-10 17:43:42 +08:00
|
|
|
if key in self._archiving or self._is_expired(session.updated_at):
|
|
|
|
|
logger.info("Auto-compact: reloading session {} (archiving={})", key, key in self._archiving)
|
|
|
|
|
session = self.sessions.get_or_create(key)
|
2026-04-10 18:14:14 +08:00
|
|
|
# Hot path: summary from in-memory dict (process hasn't restarted).
|
2026-04-10 17:43:42 +08:00
|
|
|
entry = self._summaries.pop(key, None)
|
|
|
|
|
if entry:
|
2026-08-19 15:29:22 +08:00
|
|
|
return session, entry
|
2026-05-07 16:17:27 +08:00
|
|
|
# Cold path: summary persisted in session metadata (process restarted).
|
2026-07-27 21:55:04 +08:00
|
|
|
# Persisted metadata may outlive schema changes; a malformed summary must
|
|
|
|
|
# not abort turn preparation.
|
2026-08-19 16:18:05 +08:00
|
|
|
return session, session_summary_from_metadata(
|
2026-08-19 15:29:22 +08:00
|
|
|
session.metadata,
|
|
|
|
|
fallback_last_active=session.updated_at,
|
|
|
|
|
)
|