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:
1 parent
455533169d
commit
5229989f28
52 files changed
+1849
-140
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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
@@ -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
@@ -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,
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -7,9 +7,11 @@ message's explicit ``event`` field rather than in reserved metadata flags.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from collections.abc import Awaitable, Callable, Mapping
|
||||
from dataclasses import dataclass, replace
|
||||
from typing import Any, cast
|
||||
from typing import Any, Literal, cast
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.providers.base import LLMUsage
|
||||
@@ -114,6 +116,30 @@ class TurnModelUpdatedEvent(OutboundEvent):
|
||||
fallback: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ContextCompactionEvent(OutboundEvent):
|
||||
"""A channel-safe transition for one logical context compaction."""
|
||||
|
||||
compaction_id: str
|
||||
phase: Literal["started", "succeeded", "failed", "cancelled"]
|
||||
|
||||
|
||||
ContextCompactionCallback = Callable[[ContextCompactionEvent], Awaitable[None]]
|
||||
|
||||
|
||||
async def emit_context_compaction(
|
||||
callback: ContextCompactionCallback | None,
|
||||
event: ContextCompactionEvent,
|
||||
) -> None:
|
||||
"""Notify observers without allowing delivery failure to alter compaction."""
|
||||
if callback is None:
|
||||
return
|
||||
try:
|
||||
await callback(event)
|
||||
except Exception:
|
||||
logger.exception("Failed to publish context compaction event")
|
||||
|
||||
|
||||
def outbound_message_for_event(
|
||||
*,
|
||||
channel: str,
|
||||
@@ -162,6 +188,14 @@ def _event_content(event: OutboundEvent) -> str:
|
||||
ProgressEvent | RetryWaitEvent | StreamDeltaEvent | StreamEndEvent | UserInputEvent,
|
||||
):
|
||||
return event.content
|
||||
if isinstance(event, ContextCompactionEvent):
|
||||
if event.phase == "started":
|
||||
return "Compressing context…"
|
||||
if event.phase == "failed":
|
||||
return "Unable to compact context."
|
||||
if event.phase == "cancelled":
|
||||
return "Context compaction cancelled."
|
||||
return "Context compacted."
|
||||
return ""
|
||||
|
||||
|
||||
|
||||
@@ -1388,7 +1388,14 @@ class WebSocketChannel(BaseChannel):
|
||||
"""Persist as requested, frame, and fan out one encoded WebUI payload."""
|
||||
conns = list(self._subs.get(chat_id, ()))
|
||||
body: dict[str, Any] = dict(payload)
|
||||
if persistence == "turn_complete":
|
||||
if persistence == "turn_activity":
|
||||
self._persist_turn_transcript_event(
|
||||
chat_id,
|
||||
body,
|
||||
metadata=metadata,
|
||||
phase="activity",
|
||||
)
|
||||
elif persistence == "turn_complete":
|
||||
canonical_webui_turn = (metadata or {}).get("webui") is True
|
||||
prior_persistence_failure = (
|
||||
canonical_webui_turn
|
||||
|
||||
@@ -24,6 +24,7 @@ from nanobot.bus.events import (
|
||||
OutboundMessage,
|
||||
)
|
||||
from nanobot.bus.outbound_events import (
|
||||
ContextCompactionEvent,
|
||||
GoalStateSyncEvent,
|
||||
GoalStatusEvent,
|
||||
ProgressEvent,
|
||||
@@ -2805,6 +2806,68 @@ async def test_send_turn_end_emits_turn_end_event() -> None:
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_context_compaction_started_is_live_only() -> None:
|
||||
bus = MagicMock()
|
||||
channel = WebSocketChannel(
|
||||
{"enabled": True, "allowFrom": ["*"]},
|
||||
bus,
|
||||
gateway=_basic_handler(bus),
|
||||
)
|
||||
mock_ws = AsyncMock()
|
||||
channel._attach(mock_ws, "chat-compaction-started")
|
||||
|
||||
await channel.send(OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id="chat-compaction-started",
|
||||
content="Compressing context…",
|
||||
event=ContextCompactionEvent(
|
||||
compaction_id="compact-started",
|
||||
phase="started",
|
||||
),
|
||||
))
|
||||
|
||||
assert _sent_ws_payloads(mock_ws) == [{
|
||||
"event": "context_compaction",
|
||||
"chat_id": "chat-compaction-started",
|
||||
"compaction_id": "compact-started",
|
||||
"phase": "started",
|
||||
}]
|
||||
assert read_transcript_lines("websocket:chat-compaction-started") == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_context_compaction_is_structured_persisted_and_summary_free() -> None:
|
||||
bus = MagicMock()
|
||||
channel = WebSocketChannel(
|
||||
{"enabled": True, "allowFrom": ["*"]},
|
||||
bus,
|
||||
gateway=_basic_handler(bus),
|
||||
)
|
||||
mock_ws = AsyncMock()
|
||||
channel._attach(mock_ws, "chat-compaction")
|
||||
|
||||
await channel.send(OutboundMessage(
|
||||
channel="websocket",
|
||||
chat_id="chat-compaction",
|
||||
content="Context compacted · LLM summary",
|
||||
event=ContextCompactionEvent(
|
||||
compaction_id="compact-1",
|
||||
phase="succeeded",
|
||||
),
|
||||
))
|
||||
|
||||
expected = {
|
||||
"event": "context_compaction",
|
||||
"chat_id": "chat-compaction",
|
||||
"compaction_id": "compact-1",
|
||||
"phase": "succeeded",
|
||||
}
|
||||
assert _sent_ws_payloads(mock_ws) == [expected]
|
||||
[persisted] = read_transcript_lines("websocket:chat-compaction")
|
||||
assert {key: persisted[key] for key in expected} == expected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_recovery_state_is_a_structured_event_not_assistant_text() -> None:
|
||||
bus = MagicMock()
|
||||
|
||||
@@ -24,6 +24,7 @@ from rich.text import Text
|
||||
|
||||
from nanobot import __logo__
|
||||
from nanobot.bus.outbound_events import (
|
||||
ContextCompactionEvent,
|
||||
ProgressEvent,
|
||||
RetryWaitEvent,
|
||||
outbound_event_from_message,
|
||||
@@ -369,6 +370,9 @@ async def _maybe_print_interactive_progress(
|
||||
reasoning_buffer: _ReasoningBuffer | None = None,
|
||||
) -> bool:
|
||||
event = outbound_event_from_message(msg)
|
||||
if isinstance(event, ContextCompactionEvent):
|
||||
await _print_interactive_progress_line(msg.content, thinking, renderer)
|
||||
return True
|
||||
if isinstance(event, RetryWaitEvent):
|
||||
await _print_interactive_progress_line(msg.content, thinking, renderer)
|
||||
return True
|
||||
|
||||
@@ -11,6 +11,8 @@ from contextlib import suppress
|
||||
from dataclasses import dataclass, replace
|
||||
from typing import TYPE_CHECKING, Any, Literal, cast
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot import __version__
|
||||
from nanobot.bus.events import INBOUND_META_USER_SHELL, OutboundMessage
|
||||
from nanobot.command.router import CommandContext, CommandRouter, normalize_command_text
|
||||
@@ -71,6 +73,12 @@ BUILTIN_COMMAND_SPECS: tuple[BuiltinCommandSpec, ...] = (
|
||||
"square-pen",
|
||||
lifecycle="finalize_active_turn",
|
||||
),
|
||||
BuiltinCommandSpec(
|
||||
"/compact",
|
||||
"Compact context",
|
||||
"Compact this chat's context and continue the conversation.",
|
||||
"archive",
|
||||
),
|
||||
BuiltinCommandSpec(
|
||||
"/stop",
|
||||
"Stop current task",
|
||||
@@ -337,6 +345,29 @@ async def cmd_new(ctx: CommandContext) -> OutboundMessage:
|
||||
)
|
||||
|
||||
|
||||
async def cmd_compact(ctx: CommandContext) -> None:
|
||||
"""Compact the current session without resetting the conversation."""
|
||||
loop = ctx.loop
|
||||
session = ctx.session or loop.sessions.get_or_create(ctx.key)
|
||||
runtime = ctx.runtime or loop.runtime_for_session(session)
|
||||
delivery = loop.turn_delivery_factory.create(ctx.msg, ctx.key)
|
||||
|
||||
try:
|
||||
summary = await loop.consolidator.compact_idle_session(
|
||||
ctx.key,
|
||||
runtime=runtime,
|
||||
on_compaction=delivery.context_compaction,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Manual context compaction failed for {}", ctx.key)
|
||||
return
|
||||
|
||||
if summary:
|
||||
refreshed = loop.sessions.get_or_create(ctx.key)
|
||||
refreshed.provider_state = None
|
||||
loop.sessions.save(refreshed)
|
||||
|
||||
|
||||
def _format_preset_names(names: list[str]) -> str:
|
||||
return ", ".join(f"`{name}`" for name in names) if names else "(none configured)"
|
||||
|
||||
@@ -1044,6 +1075,7 @@ def register_builtin_commands(router: CommandRouter) -> None:
|
||||
router.priority("/restart", cmd_restart)
|
||||
router.priority("/status", cmd_status)
|
||||
router.exact("/new", cmd_new)
|
||||
router.exact("/compact", cmd_compact)
|
||||
router.exact("/status", cmd_status)
|
||||
router.exact("/model", cmd_model)
|
||||
router.prefix("/model ", cmd_model)
|
||||
|
||||
@@ -8,6 +8,7 @@ from loguru import logger
|
||||
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import (
|
||||
ContextCompactionEvent,
|
||||
GoalStateSyncEvent,
|
||||
GoalStatusEvent,
|
||||
ProgressEvent,
|
||||
@@ -28,6 +29,7 @@ from nanobot.webui.metadata import (
|
||||
from nanobot.webui.outbound_wire import (
|
||||
WebUIWirePayload,
|
||||
WebUIWirePersistence,
|
||||
encode_context_compaction,
|
||||
encode_recovery_state,
|
||||
encode_turn_end,
|
||||
)
|
||||
@@ -152,6 +154,7 @@ class WebUIOutboundProjector:
|
||||
SessionUpdatedEvent,
|
||||
GoalStatusEvent,
|
||||
GoalStateSyncEvent,
|
||||
ContextCompactionEvent,
|
||||
)
|
||||
log = (
|
||||
logger.debug
|
||||
@@ -187,6 +190,14 @@ class WebUIOutboundProjector:
|
||||
persistence="transient",
|
||||
)
|
||||
return
|
||||
if isinstance(event, ContextCompactionEvent):
|
||||
await self._transport.send_payload(
|
||||
msg.chat_id,
|
||||
encode_context_compaction(msg.chat_id, event),
|
||||
persistence="transient" if event.phase == "started" else "turn_activity",
|
||||
metadata=msg.metadata,
|
||||
)
|
||||
return
|
||||
if isinstance(event, GoalStateSyncEvent):
|
||||
if conns:
|
||||
await self._transport.send_goal_state(
|
||||
|
||||
@@ -5,7 +5,11 @@ from __future__ import annotations
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, Literal, NotRequired, TypeAlias, TypedDict
|
||||
|
||||
from nanobot.bus.outbound_events import RecoveryStateEvent, TurnEndEvent
|
||||
from nanobot.bus.outbound_events import (
|
||||
ContextCompactionEvent,
|
||||
RecoveryStateEvent,
|
||||
TurnEndEvent,
|
||||
)
|
||||
from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY
|
||||
|
||||
|
||||
@@ -32,8 +36,20 @@ class TurnEndWirePayload(_ChatWirePayload):
|
||||
context_window_tokens: NotRequired[int]
|
||||
|
||||
|
||||
WebUIWirePayload: TypeAlias = RecoveryStateWirePayload | TurnEndWirePayload
|
||||
WebUIWirePersistence: TypeAlias = Literal["transient", "turn_complete"]
|
||||
class ContextCompactionWirePayload(_ChatWirePayload):
|
||||
event: Literal["context_compaction"]
|
||||
compaction_id: str
|
||||
phase: str
|
||||
|
||||
|
||||
WebUIWirePayload: TypeAlias = (
|
||||
ContextCompactionWirePayload | RecoveryStateWirePayload | TurnEndWirePayload
|
||||
)
|
||||
WebUIWirePersistence: TypeAlias = Literal[
|
||||
"transient",
|
||||
"turn_activity",
|
||||
"turn_complete",
|
||||
]
|
||||
|
||||
|
||||
def encode_recovery_state(
|
||||
@@ -55,6 +71,20 @@ def encode_recovery_state(
|
||||
return payload
|
||||
|
||||
|
||||
def encode_context_compaction(
|
||||
chat_id: str,
|
||||
event: ContextCompactionEvent,
|
||||
) -> ContextCompactionWirePayload:
|
||||
"""Project one summary-free compaction transition onto its stable wire shape."""
|
||||
payload: ContextCompactionWirePayload = {
|
||||
"event": "context_compaction",
|
||||
"chat_id": chat_id,
|
||||
"compaction_id": event.compaction_id,
|
||||
"phase": event.phase,
|
||||
}
|
||||
return payload
|
||||
|
||||
|
||||
def encode_turn_end(
|
||||
chat_id: str,
|
||||
event: TurnEndEvent,
|
||||
|
||||
@@ -2321,6 +2321,48 @@ def replay_transcript_to_ui_messages(
|
||||
close_reasoning(messages)
|
||||
continue
|
||||
|
||||
if ev == "context_compaction":
|
||||
compaction_id = rec.get("compaction_id")
|
||||
phase = rec.get("phase")
|
||||
if (
|
||||
not isinstance(compaction_id, str)
|
||||
or not compaction_id
|
||||
or phase not in {"started", "succeeded", "failed", "cancelled"}
|
||||
):
|
||||
continue
|
||||
compaction: dict[str, Any] = {
|
||||
"id": compaction_id,
|
||||
"phase": phase,
|
||||
}
|
||||
payload: dict[str, Any] = {
|
||||
"id": f"compaction-{compaction_id}",
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"kind": "compaction",
|
||||
"createdAt": _created_at_ms(rec, idx),
|
||||
"compaction": compaction,
|
||||
**_turn_fields(rec, "activity"),
|
||||
}
|
||||
existing = next(
|
||||
(
|
||||
message_index
|
||||
for message_index, message in enumerate(messages)
|
||||
if message.get("id") == payload["id"]
|
||||
),
|
||||
None,
|
||||
)
|
||||
if existing is None:
|
||||
messages.append(payload)
|
||||
else:
|
||||
payload["createdAt"] = messages[existing].get(
|
||||
"createdAt",
|
||||
payload["createdAt"],
|
||||
)
|
||||
messages[existing] = payload
|
||||
active_activity_segment_id = None
|
||||
active_file_edit_segment_id = None
|
||||
continue
|
||||
|
||||
if ev == "message":
|
||||
if suppress_until_turn_end and rec.get("kind") in (
|
||||
"tool_hint",
|
||||
|
||||
Reference in new issue
Block a user