feat: make context compaction visible in channels (#5656)

* feat: surface context compaction lifecycle

* fix: complete and simplify context compaction notifications
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-05 20:21:54 +08:00
1 parent 455533169d
commit 5229989f28
52 files changed
+1849 -140

No files matched your search

+11 -2
View File
@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Any, Callable, Coroutine
from loguru import logger
from nanobot.bus.outbound_events import ContextCompactionCallback
from nanobot.session.manager import MIN_COMPACTED_REPLAY_MESSAGES, Session, SessionManager
from nanobot.session.summary import SessionSummary, session_summary_from_metadata
@@ -15,18 +16,22 @@ if TYPE_CHECKING:
from nanobot.agent.memory import Consolidator
from nanobot.utils.llm_runtime import LLMRuntime
IdleCompactionCallback = Callable[[str], ContextCompactionCallback | None]
class AutoCompact:
_RECENT_SUFFIX_MESSAGES = MIN_COMPACTED_REPLAY_MESSAGES
_INTERNAL_SESSION_PREFIXES = ("dream:",)
def __init__(self, sessions: SessionManager, consolidator: Consolidator,
session_ttl_minutes: int = 0):
session_ttl_minutes: int = 0,
bind_compaction: IdleCompactionCallback | None = None):
self.sessions = sessions
self.consolidator = consolidator
self._ttl = session_ttl_minutes
self._archiving: set[str] = set()
self._summaries: dict[str, SessionSummary] = {}
self._bind_compaction = bind_compaction
def _is_expired(self, ts: datetime | str | None,
now: datetime | None = None) -> bool:
@@ -48,7 +53,10 @@ class AutoCompact:
def _has_unarchived_messages(self, key: str) -> bool:
session = self.sessions.get_or_create(key)
return session.last_archived < len(session.messages)
return any(
not message.get("_command")
for message in session.messages[session.last_archived:]
)
@classmethod
def _is_internal_session(cls, key: str) -> bool:
@@ -88,6 +96,7 @@ class AutoCompact:
key,
runtime=runtime,
max_suffix=self._RECENT_SUFFIX_MESSAGES,
on_compaction=self._bind_compaction(key) if self._bind_compaction else None,
)
if summary and summary != "(nothing)":
session = self.sessions.get_or_create(key)
+121 -69
View File
@@ -8,16 +8,23 @@ session history list in place.
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from copy import deepcopy
from dataclasses import dataclass, replace
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, Any, cast
from uuid import uuid4
from loguru import logger
from nanobot.agent.context import TranscriptInput
from nanobot.bus.outbound_events import (
ContextCompactionCallback,
ContextCompactionEvent,
emit_context_compaction,
)
from nanobot.providers.base import (
LLMResponse,
LLMUsage,
@@ -198,6 +205,7 @@ class ModelRequestState:
tool_definitions: list[dict[str, Any]] | None = None
compaction: ContextCompactionState | None = None
provider_compaction_applied: bool = False
compaction_callback: ContextCompactionCallback | None = None
class ContextGovernor:
@@ -412,33 +420,6 @@ class ContextGovernor:
return None
return measured, source
def fit_request(
self,
config: ContextGovernanceConfig,
messages: list[dict[str, Any]],
usage: LLMUsage | None,
*,
usage_matches_messages: bool,
tool_definitions: list[dict[str, Any]] | None,
request_context_tokens: int | None = None,
) -> tuple[list[dict[str, Any]], bool]:
"""Fit the request when its measured or estimated input is pressured."""
pressure = self.request_pressure(
config,
messages,
usage,
usage_matches_messages=usage_matches_messages,
tool_definitions=tool_definitions,
request_context_tokens=request_context_tokens,
)
if pressure is None:
return messages, False
return self.fit_to_budget(
config,
messages,
tool_definitions=tool_definitions,
), True
@staticmethod
def _summary_transcript(
compaction: ContextCompactionState,
@@ -493,18 +474,44 @@ class ContextGovernor:
)
return
summary = await compaction.consolidate_provider_compaction(
response.provider_compaction_state,
deepcopy(accepted_messages),
compaction.active_summary,
compaction_id = uuid4().hex
await emit_context_compaction(
state.compaction_callback,
ContextCompactionEvent(compaction_id=compaction_id, phase="started"),
)
try:
summary = await compaction.consolidate_provider_compaction(
response.provider_compaction_state,
deepcopy(accepted_messages),
compaction.active_summary,
)
except (Exception, asyncio.CancelledError) as exc:
await emit_context_compaction(
state.compaction_callback,
ContextCompactionEvent(
compaction_id=compaction_id,
phase="cancelled" if isinstance(exc, asyncio.CancelledError) else "failed",
),
)
raise
if not summary:
await emit_context_compaction(
state.compaction_callback,
ContextCompactionEvent(compaction_id=compaction_id, phase="failed"),
)
return
compaction.active_summary = summary
compaction.summary_checkpoint = SessionSummaryCheckpoint(
summary=summary,
transcript_boundary=transcript_boundary,
)
await emit_context_compaction(
state.compaction_callback,
ContextCompactionEvent(
compaction_id=compaction_id,
phase="succeeded",
),
)
async def _compact_request_history(
self,
@@ -516,46 +523,68 @@ class ContextGovernor:
tool_definitions: list[dict[str, Any]] | None,
) -> list[dict[str, Any]]:
"""Replace accepted history H with a checkpoint while preserving delta."""
delta_messages = compaction.delta_after_accepted(messages)
consolidation_prefix = self.prepare_messages_for_model(
state.config,
compaction.accepted_messages,
measured, _source = pressure
compaction_id = uuid4().hex
await emit_context_compaction(
state.compaction_callback,
ContextCompactionEvent(compaction_id=compaction_id, phase="started"),
)
summary = await compaction.consolidate_history(
deepcopy(consolidation_prefix),
compaction.active_summary,
)
if not summary:
measured, source = pressure
raise ContextWindowExceededError(
session_key=state.config.session_key,
estimated_tokens=measured,
input_budget=self.input_budget(state.config),
source=source,
try:
delta_messages = compaction.delta_after_accepted(messages)
consolidation_prefix = self.prepare_messages_for_model(
state.config,
compaction.accepted_messages,
)
summary = await compaction.consolidate_history(
deepcopy(consolidation_prefix),
compaction.active_summary,
)
if not summary:
raise ContextWindowExceededError(
session_key=state.config.session_key,
estimated_tokens=measured,
input_budget=self.input_budget(state.config),
source=_source,
)
compaction.active_summary = summary
prepared = self.prepare_messages_for_model(
state.config,
[
*self._summary_transcript(compaction, summary),
{"role": "user", "content": SUMMARY_CONTINUATION_TEXT},
*delta_messages,
],
)
# Responses-style state is append-only. Replacing H with a
# checkpoint requires a fresh request; a successful response may
# establish a new provider-owned state at the rewritten boundary.
state.conversation.replace_transcript(compaction.raw_messages)
state.usage = None
prepared = self.ensure_request_fits(
state.config,
prepared,
tool_definitions=tool_definitions,
)
compaction.summary_checkpoint = SessionSummaryCheckpoint(
summary=summary,
transcript_boundary=compaction.raw_accepted_boundary,
compaction.active_summary = summary
prepared = self.prepare_messages_for_model(
state.config,
[
*self._summary_transcript(compaction, summary),
{"role": "user", "content": SUMMARY_CONTINUATION_TEXT},
*delta_messages,
],
)
# Responses-style state is append-only. Replacing H with a
# checkpoint requires a fresh request; a successful response may
# establish a new provider-owned state at the rewritten boundary.
state.conversation.replace_transcript(compaction.raw_messages)
state.usage = None
prepared = self.ensure_request_fits(
state.config,
prepared,
tool_definitions=tool_definitions,
)
compaction.summary_checkpoint = SessionSummaryCheckpoint(
summary=summary,
transcript_boundary=compaction.raw_accepted_boundary,
)
except (Exception, asyncio.CancelledError) as exc:
await emit_context_compaction(
state.compaction_callback,
ContextCompactionEvent(
compaction_id=compaction_id,
phase="cancelled" if isinstance(exc, asyncio.CancelledError) else "failed",
),
)
raise
await emit_context_compaction(
state.compaction_callback,
ContextCompactionEvent(
compaction_id=compaction_id,
phase="succeeded",
),
)
return prepared
@@ -590,7 +619,7 @@ class ContextGovernor:
request_was_fitted = False
compaction = state.compaction
if compaction is None:
prepared, request_was_fitted = self.fit_request(
pressure = self.request_pressure(
state.config,
prepared,
state.usage,
@@ -598,6 +627,29 @@ class ContextGovernor:
tool_definitions=tool_definitions,
request_context_tokens=request_context_tokens,
)
if pressure is not None:
compaction_id = uuid4().hex
await emit_context_compaction(
state.compaction_callback,
ContextCompactionEvent(compaction_id=compaction_id, phase="started"),
)
try:
prepared = self.fit_to_budget(
state.config,
prepared,
tool_definitions=tool_definitions,
)
except Exception:
await emit_context_compaction(
state.compaction_callback,
ContextCompactionEvent(compaction_id=compaction_id, phase="failed"),
)
raise
await emit_context_compaction(
state.compaction_callback,
ContextCompactionEvent(compaction_id=compaction_id, phase="succeeded"),
)
request_was_fitted = True
else:
pressure = self.request_pressure(
state.config,
+45 -8
View File
@@ -50,10 +50,14 @@ from nanobot.agent.turn_delivery import (
from nanobot.agent.turn_delivery import TurnRoute as TurnRoute
from nanobot.agent.turn_hooks import AgentTurnHookSpec, build_agent_turn_hook
from nanobot.bus.events import INBOUND_META_USER_SHELL, InboundMessage, OutboundMessage
from nanobot.bus.outbound_events import StreamedResponseEvent
from nanobot.bus.outbound_events import (
ContextCompactionCallback,
StreamedResponseEvent,
)
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import RuntimeEventBus
from nanobot.command import CommandContext, CommandRouter, register_builtin_commands
from nanobot.command.router import normalize_command_text
from nanobot.config.schema import AgentDefaults, ModelPresetConfig
from nanobot.llm_usage.context import source_from_request
from nanobot.providers.base import LLMProvider, LLMUsage, ProviderConversationState
@@ -456,6 +460,7 @@ class AgentLoop:
sessions=self.sessions,
consolidator=self.consolidator,
session_ttl_minutes=session_ttl_minutes,
bind_compaction=self._idle_compaction_callback,
)
self._idle_compact_check_interval_s = idle_compact_check_interval_seconds
self._next_idle_compact_check_at = time.monotonic()
@@ -798,6 +803,14 @@ class AgentLoop:
dispatch_fn: Callable[[CommandContext], Awaitable[OutboundMessage | None]],
) -> None:
"""Dispatch a command directly from the run() loop and publish the result."""
if normalize_command_text(raw).lower() == "/compact":
# Compaction must wait for the active turn to commit its session.
task = asyncio.create_task(self._dispatch(msg))
self._track_active_task(key, task)
# Enter dispatch's cancellation handler before consuming a queued /stop.
await asyncio.sleep(0)
return
async def dispatch_and_publish() -> None:
ctx = CommandContext(msg=msg, session=None, key=key, raw=raw, loop=self)
result = await dispatch_fn(ctx)
@@ -909,18 +922,27 @@ class AgentLoop:
return UNIFIED_SESSION_KEY
return msg.session_key
def _remember_unified_session_route(
def _idle_compaction_callback(
self,
session_key: str,
) -> ContextCompactionCallback | None:
"""Bind one idle compaction to its current user-facing destination."""
session = self.sessions.get_or_create(session_key)
return self.turn_delivery_factory.session_compaction_callback(
session_key, session.metadata,
)
def _remember_session_route(
self,
session: Session,
msg: InboundMessage,
*,
delivery: TurnDelivery,
is_user_turn: bool,
) -> None:
"""Remember the latest user-facing route for unified-session delivery."""
"""Remember the latest user-facing destination, including channel threads."""
if (
not self._unified_session
or session.key != UNIFIED_SESSION_KEY
or not is_user_turn
not is_user_turn
or msg.channel in {"cli", "system"}
or msg.sender_id == "subagent"
):
@@ -928,7 +950,9 @@ class AgentLoop:
_, automation_metadata = automation_history_overrides(msg.metadata)
if automation_metadata:
return
remember_last_channel(session.metadata, msg.channel, msg.chat_id)
delivery.remember_session_route(session.metadata)
if self._unified_session and session.key == UNIFIED_SESSION_KEY:
remember_last_channel(session.metadata, msg.channel, msg.chat_id)
async def _run_agent_loop(
self,
@@ -937,6 +961,7 @@ class AgentLoop:
on_stream: Callable[[str], Awaitable[None]] | None = None,
on_stream_end: Callable[..., Awaitable[None]] | None = None,
on_retry_wait: Callable[[str], Awaitable[None]] | None = None,
on_context_compaction: ContextCompactionCallback | None = None,
*,
runtime: LLMRuntime,
session: Session | None = None,
@@ -1222,6 +1247,7 @@ class AgentLoop:
channel=request_ctx.channel,
metadata=request_metadata,
),
compaction_callback=on_context_compaction,
))
finally:
turn_scope_stack.close()
@@ -1419,6 +1445,7 @@ class AgentLoop:
delivery = self.turn_delivery_factory.unrouted(msg, session_key)
pending: asyncio.Queue[InboundMessage] | None = None
completion_published = False
try:
async with lock, gate:
# Only the task that owns the session lock may publish the
@@ -1443,6 +1470,7 @@ class AgentLoop:
response,
publish_completion=not continuing,
)
completion_published = not continuing
for _, coordinator in self._automation_turn_coordinators:
coordinator.complete(msg, response=response)
except asyncio.CancelledError:
@@ -1520,6 +1548,10 @@ class AgentLoop:
if not turn_continuation.internal_continuation_pending(msg.metadata):
await delivery.idle()
await self._publish_next_deferred_automation_turn(session_key)
except asyncio.CancelledError:
if not completion_published and normalize_command_text(msg.content).lower() == "/compact":
await delivery.complete(None, publish_completion=True)
raise
finally:
if (
recovery_task_registered
@@ -1811,9 +1843,10 @@ class AgentLoop:
else:
logger.info("Processing message from {}:{}: [content hidden]", msg.channel, msg.sender_id)
self._remember_unified_session_route(
self._remember_session_route(
session,
msg,
delivery=ctx.delivery,
is_user_turn=ctx.original_user_text is not None,
)
await ctx.delivery.started()
@@ -1859,6 +1892,9 @@ class AgentLoop:
turn_scopes=ctx.turn_scopes,
)
result = await self.commands.dispatch(cmd_ctx)
if cmd_ctx.raw.lower() == "/compact":
# Compaction reports through events, not an archiveable command reply.
return True
if result is not None:
ctx.outbound = result
# Shortcut commands skip BUILD and SAVE, so we must persist the
@@ -2022,6 +2058,7 @@ class AgentLoop:
tools=ctx.tools,
request_context=ctx.request_context,
provider_state=ctx.provider_state,
on_context_compaction=ctx.delivery.context_compaction,
)
ctx.final_content = result.final_content
ctx.all_messages = result.messages
+56 -16
View File
@@ -17,9 +17,15 @@ from contextlib import suppress
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Iterator, cast
from uuid import uuid4
from loguru import logger
from nanobot.bus.outbound_events import (
ContextCompactionCallback,
ContextCompactionEvent,
emit_context_compaction,
)
from nanobot.llm_usage.context import llm_usage_source
from nanobot.providers.base import ProviderCallContext, ProviderConversationState
from nanobot.runtime_context import public_history_messages
@@ -930,9 +936,8 @@ class MemoryArchiver:
if not summary:
logger.warning("Memory archive provider summary was not safe to replay, raw-dumping")
return raw_fallback()
if summary == "(nothing)":
return "(nothing)"
self.store.append_history(summary, session_key=session_key)
if summary != "(nothing)":
self.store.append_history(summary, session_key=session_key)
return summary
async def archive_session(
@@ -944,7 +949,10 @@ class MemoryArchiver:
input_token_budget: int,
) -> str | None:
"""Archive a captured session prefix without mutating the session."""
messages = list(session.messages[session.last_archived:archive_end])
messages = [
message for message in session.messages[session.last_archived:archive_end]
if not message.get("_command")
]
if not messages:
return None
session_summary = session_summary_from_metadata(
@@ -1184,6 +1192,7 @@ class Consolidator:
*,
runtime: LLMRuntime,
max_suffix: int = MIN_COMPACTED_REPLAY_MESSAGES,
on_compaction: ContextCompactionCallback | None = None,
) -> str | None:
"""Archive the full idle tail while keeping recent messages replayable.
@@ -1205,25 +1214,56 @@ class Consolidator:
archive_start = session.last_archived
messages_to_archive = list(session.messages[archive_start:])
if not messages_to_archive:
if not any(not message.get("_command") for message in messages_to_archive):
return ""
compaction_id = uuid4().hex
await emit_context_compaction(
on_compaction,
ContextCompactionEvent(compaction_id=compaction_id, phase="started"),
)
last_active = session.updated_at
archive_end = archive_start + len(messages_to_archive)
summary = await self.archive_session(
session,
archive_end=archive_end,
runtime=runtime,
)
try:
summary = await self.archive_session(
session,
archive_end=archive_end,
runtime=runtime,
)
if summary is not None:
self._set_last_summary(
session,
summary,
last_active=last_active,
)
# A turn can append while the provider call is in flight. Advance only
# through the captured batch so new messages remain eligible next time.
session.last_archived = archive_end
self.sessions.save(session)
except (Exception, asyncio.CancelledError) as exc:
await emit_context_compaction(
on_compaction,
ContextCompactionEvent(
compaction_id=compaction_id,
phase="cancelled" if isinstance(exc, asyncio.CancelledError) else "failed",
),
)
raise
if summary is None:
await emit_context_compaction(
on_compaction,
ContextCompactionEvent(compaction_id=compaction_id, phase="failed"),
)
return None
self._set_last_summary(session, summary, last_active=last_active)
# A turn can append while the provider call is in flight. Advance only
# through the captured batch so new messages remain eligible next time.
session.last_archived = archive_end
self.sessions.save(session)
await emit_context_compaction(
on_compaction,
ContextCompactionEvent(
compaction_id=compaction_id,
phase="succeeded",
),
)
visible = session.get_history(
max_messages=MIN_COMPACTED_REPLAY_MESSAGES,
+3
View File
@@ -27,6 +27,7 @@ from nanobot.agent.context_governance import (
from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContext
from nanobot.agent.tools.execution import execute_tool_calls
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.bus.outbound_events import ContextCompactionCallback
from nanobot.llm_usage.context import (
LLMUsageSource,
bind_llm_usage_source,
@@ -116,6 +117,7 @@ class AgentRunSpec:
finalize_on_max_iterations: bool = True
provider_state: ProviderConversationState | None = None
llm_usage_source: LLMUsageSource | None = None
compaction_callback: ContextCompactionCallback | None = None
@dataclass(slots=True)
@@ -431,6 +433,7 @@ class AgentRunner:
config=governance_config,
conversation=conversation_state,
compaction=compaction,
compaction_callback=spec.compaction_callback,
)
for iteration in range(spec.max_iterations):
+79 -1
View File
@@ -5,11 +5,14 @@ from __future__ import annotations
import dataclasses
import time
from collections.abc import Awaitable, Callable
from copy import deepcopy
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, cast
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.outbound_events import (
ContextCompactionCallback,
ContextCompactionEvent,
RetryWaitEvent,
StreamDeltaEvent,
StreamedResponseEvent,
@@ -20,6 +23,7 @@ from nanobot.bus.progress import build_bus_progress_callback
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import RuntimeEventBus, RuntimeEventPublisher
from nanobot.providers.base import LLMUsage
from nanobot.session.keys import UNIFIED_SESSION_KEY, last_channel_from_metadata
if TYPE_CHECKING:
from nanobot.utils.llm_runtime import LLMRuntime
@@ -43,7 +47,7 @@ RetryWaitCallback = Callable[[str], Awaitable[None]]
class TurnDeliveryFactory:
"""Create per-turn delivery objects from an optional edge-owned route policy."""
"""Route turn delivery and session-level notifications."""
def __init__(
self,
@@ -91,6 +95,45 @@ class TurnDeliveryFactory:
),
)
def session_compaction_callback(
self,
session_key: str,
session_metadata: dict[str, Any],
) -> ContextCompactionCallback | None:
"""Bind idle notifications to one route without acquiring a turn owner."""
saved_route = session_metadata.get("_compaction_route")
if isinstance(saved_route, dict):
saved_route = cast(dict[str, Any], saved_route)
channel, chat_id = saved_route.get("channel"), saved_route.get("chat_id")
metadata = saved_route.get("metadata", {})
if not isinstance(channel, str) or not isinstance(chat_id, str):
return
if not isinstance(metadata, dict):
return
metadata = cast(dict[str, Any], metadata)
else:
# Older sessions have no route snapshot. Only direct clients have a
# session key that is also an unambiguous delivery address.
route = (
last_channel_from_metadata(session_metadata)
if session_key == UNIFIED_SESSION_KEY
else tuple(session_key.split(":", 1))
)
if not route or len(route) != 2 or route[0] not in {"websocket", "cli"}:
return
channel, chat_id = route
metadata = {}
metadata = deepcopy(metadata)
async def publish(event: ContextCompactionEvent) -> None:
await self.bus.publish_outbound(
outbound_message_for_event(
channel=channel, chat_id=chat_id, event=event, metadata=metadata,
)
)
return publish
@staticmethod
def _default_route(msg: InboundMessage, session_key: str) -> TurnRoute:
if msg.channel != "system":
@@ -174,6 +217,41 @@ class TurnDelivery:
return _on_retry_wait
async def context_compaction(self, event: ContextCompactionEvent) -> None:
"""Publish one compaction transition without completing the active turn."""
await self.bus.publish_outbound(
outbound_message_for_event(
channel=self.delivery_message.channel,
chat_id=self.delivery_message.chat_id,
event=event,
metadata=self.delivery_message.metadata,
)
)
def remember_session_route(self, session_metadata: dict[str, Any]) -> None:
"""Keep only routing fields needed to deliver a later idle notification."""
source = self.route.metadata
channel_type = self.route.channel.split(".", 1)[0]
fields = {
"telegram": ("message_thread_id",),
"matrix": ("thread_root_event_id", "thread_reply_to_event_id"),
"feishu": ("message_id", "thread_id", "chat_type"),
}.get(channel_type, ())
metadata = {
key: source[key] for key in fields if key in source
}
if channel_type in {"slack", "mattermost"}:
nested = source.get(channel_type)
if isinstance(nested, dict):
nested = cast(dict[str, Any], nested)
fields = ("thread_ts",) if channel_type == "slack" else ("root_id", "thread_ts")
metadata[channel_type] = {key: nested[key] for key in fields if key in nested}
session_metadata["_compaction_route"] = {
"channel": self.route.channel,
"chat_id": self.route.chat_id,
"metadata": metadata,
}
async def started(self) -> None:
if self.route.publish_lifecycle:
await self.runtime_event_publisher.session_turn_started(