It seems the `nanobot/session/memory.py` file was not found. However, based on the available files (`loop.py` and `goal_state.py`), we can piece together a good understanding of `nanobot`'s architecture, particularly regarding context management and history.

Here's a high-level overview:

**1. Core Architecture: The Agent Loop (`loop.py`)**

The `AgentLoop` class is the heart of `nanobot`. It orchestrates the entire process of handling user input, interacting with AI models, managing state, and generating output.

*   **Message Handling**: It receives messages from various channels (CLI, WebSocket, etc.) via a `MessageBus`.
*   **State Machine**: The `AgentLoop` operates as a state machine, progressing through distinct phases for each turn: `RESTORE`, `COMPACT`, `COMMAND`, `BUILD`, `RUN`, `SAVE`, `RESPOND`, `DONE`.
*   **Context Building (`ContextBuilder`)**: In the `BUILD` state, the `AgentLoop` uses a `ContextBuilder` to prepare the input for the LLM. This involves:
    *   Retrieving conversation history from the `SessionManager`.
    *   Potentially summarizing or compacting older parts of the conversation (handled by `Consolidator` and `AutoCompact` from `session/` components).
    *   Incorporating tool results and memory.
    *   Formatting the input according to the specific requirements of the selected AI model.
*   **LLM Interaction (`AgentRunner`)**: The prepared context is passed to an `AgentRunner`, which interacts with the configured LLM `Provider` (e.g., OpenAI, Anthropic, local models).
    *   **Provider Abstraction**: `nanobot` uses an abstract `LLMProvider` interface (`providers/base.py`), with concrete implementations for various models and services. The `factory.py` and `registry.py` files (as seen in previous explorations) manage the selection and instantiation of these providers.
    *   **Model-Specific Context**: The `ContextBuilder` and the `LLMProvider` implementations are responsible for adapting the context to each model's specific needs, including:
        *   **Context Window Management**: The `Consolidator` and `AutoCompact` logic (part of `session/`) likely plays a role in truncating or summarizing older parts of the conversation history to fit within the current model's context window. The `AgentLoop` is configured with `context_window_tokens` and `context_block_limit` to manage this.
        *   **Prompt Formatting**: Different models may have slightly different prompt structures (e.g., system messages, user/assistant roles, tool call formatting). The `LLMProvider` and `ContextBuilder` handle these variations.
*   **Tool Execution**: If the LLM's response includes tool calls, the `AgentLoop`'s `AgentRunner` executes them, capturing their results.
*   **Saving State (`SessionManager`)**: In the `SAVE` state, the `AgentLoop` updates the conversation history and any relevant state within a `SessionManager`.

**2. Session and History Management (`session/`)**

The `nanobot/session/` directory (specifically `goal_state.py` and the implied `manager.py` and `memory.py`) handles persistent state for conversations.

*   **`SessionManager`**: This component likely manages multiple conversation sessions, keyed by a `session_key` (derived from channel, chat ID, etc.). It stores and retrieves session data, including conversation history.
*   **Conversation History**: Each `Session` object contains a list of messages representing the conversation history. This history is used by the `ContextBuilder` to create the LLM's input.
*   **Context Compaction (`Consolidator`, `AutoCompact`)**:
    *   To manage long conversations within LLM context window limits, `nanobot` employs compaction strategies.
    *   The `Consolidator` likely handles summarizing older parts of the conversation, condensing them into a single "summary" message that is still included in the LLM's context. The `context_window_tokens`, `consolidation_ratio`, and `max_messages` parameters in `AgentLoop` influence this process.
    *   `AutoCompact` is responsible for triggering this consolidation based on various criteria, such as time-to-live (`session_ttl_minutes`) or when the conversation exceeds a certain message limit.
*   **Sustained Goals (`goal_state.py`)**: This module specifically manages state for long-running tasks or "goals." It allows parts of the conversation context (like the objective or a UI summary) to be persisted and potentially override standard context window limits for the LLM's input, allowing for very long-running tasks without losing track of the primary objective. It also influences LLM timeouts, disabling them for sustained goals to prevent premature interruption.

**How it Manages Context for Different AI Models:**

1.  **Provider Abstraction**: `nanobot` uses an `LLMProvider` interface. Each concrete provider (e.g., `OpenAICompatProvider`, `AnthropicProvider`) knows how to format requests and interpret responses for its specific model.
2.  **Configuration**: The `registry.py` and `factory.py` map model names or provider keywords to specific `ProviderSpec` entries, which include details like `default_api_base`, `backend`, and model-specific parameters.
3.  **Context Builder's Role**: The `ContextBuilder` (used by `AgentLoop`) is designed to adapt the conversation history and available tools into a format suitable for the selected LLM. It takes into account:
    *   **Model's Max Tokens**: The `context_window_tokens` parameter and the `Consolidator`'s logic ensure that the input, including history and tools, does not exceed the model's limit.
    *   **Model's Prompt Structure**: Providers might inject system messages, format tool descriptions differently, or handle multi-turn conversation structures in specific ways, all managed within their respective provider classes.
    *   **Tool Definitions**: Tools are registered and their definitions are passed to the LLM in a format it understands, often JSON schema.

**How it Keeps History of User Actions:**

1.  **Session Management**: The `SessionManager` is central to maintaining history. Each conversation is associated with a `Session` object.
2.  **Message Storage**: As user messages and LLM responses (including tool calls and their results) are processed, they are added as entries to the `Session` object's `messages` list.
3.  **Persistence**: The `SessionManager` is responsible for persisting this session data (likely to files, e.g., in the workspace or `~/.nanobot/sessions/`).
4.  **Context Building from History**: When a new turn begins, the `AgentLoop` retrieves the relevant history from the `SessionManager`.
5.  **Compaction/Summarization**: For long conversations, older messages are compacted or summarized by the `Consolidator` and `AutoCompact` mechanisms to fit within the LLM's context window, ensuring that even long-running dialogues can be managed effectively. The "summary" of older turns is then included in the prompt to the LLM.
6.  **Runtime Checkpoints**: `nanobot` also implements runtime checkpoints (`_RUNTIME_CHECKPOINT_KEY` in `loop.py`) to save the state of an ongoing LLM call (e.g., partial tool results) before a new message or interruption occurs. This allows for resuming a turn or gracefully handling cancellations.

In essence, `nanobot` employs a layered approach: a central `AgentLoop` orchestrates turns, `ContextBuilder` prepares model-specific inputs, `LLMProvider`s handle the low-level API interactions, and `SessionManager` with its compaction logic preserves conversation history and state across turns and models.The `nanobot` architecture is designed around a robust message-processing loop that handles conversations, context management, and interaction with various AI models and tools. Here's a high-level breakdown:

**1. Core Orchestration: The `AgentLoop` (`loop.py`)**

The `AgentLoop` is the central component that manages the lifecycle of a `nanobot` session. It acts as a state machine, processing messages and orchestrating actions across different parts of the system.

*   **Message Ingestion**: It receives messages from various channels (CLI, WebSocket, etc.) via a `MessageBus`.
*   **State Machine Workflow**: It progresses through distinct states for each turn:
    *   `RESTORE`: Loads session state, including conversation history and any runtime checkpoints.
    *   `COMPACT`: Manages conversation history, potentially summarizing older turns to fit within model context windows using `Consolidator` and `AutoCompact` logic.
    *   `COMMAND`: Checks for and dispatches internal commands (e.g., `/stop`).
    *   `BUILD`: Constructs the prompt for the LLM, incorporating history, tool definitions, and context, using `ContextBuilder`.
    *   `RUN`: Invokes the configured LLM `Provider` (via `AgentRunner`) to generate a response.
    *   `SAVE`: Persists the turn's results (user message, LLM response, tool outputs) back into the `SessionManager`.
    *   `RESPOND`: Formats and sends the final output back through the `MessageBus`.
    *   `DONE`: Marks the completion of a turn.
*   **Asynchronous Processing**: It heavily relies on `asyncio` to handle concurrent operations, allowing it to be responsive to new messages while processing ongoing LLM calls or tool executions.

**2. Context Management for Different AI Models**

`nanobot` achieves model-agnostic context management through abstraction and configuration:

*   **Provider Abstraction**: It defines a base `LLMProvider` interface (`providers/base.py`). Concrete implementations (e.g., `OpenAICompatProvider`, `AnthropicProvider`, local model providers) handle model-specific requirements.
*   **Provider Registry (`registry.py`, `factory.py`)**: A registry (`PROVIDERS`) maps model names, keywords, or API endpoints to specific `ProviderSpec` definitions. This allows `nanobot` to identify which provider to use based on configuration.
*   **Context Builder (`ContextBuilder`)**: This component (`agent/context.py`) is responsible for preparing the LLM's input. It takes into account:
    *   **Model Context Window**: It uses configured parameters like `context_window_tokens` and `context_block_limit` to ensure the prompt doesn't exceed the LLM's limits.
    *   **History Compaction**: The `Consolidator` and `AutoCompact` (`session/`) logic summarizes older parts of the conversation, condensing them into a manageable "summary" that is still included in the prompt, enabling long conversations.
    *   **Prompt Formatting**: It formats messages (including system prompts, user messages, assistant responses, and tool definitions) according to the specific syntax expected by the chosen LLM provider.
    *   **Tool Integration**: Tool definitions are translated into formats compatible with the LLM's tool-calling capabilities.
*   **Local LLM Handling**: For local LLMs, `nanobot` detects them via `is_local=True` flags in `ProviderSpec` or by analyzing API base URLs pointing to private network addresses. It adjusts client configurations (e.g., disabling HTTP keep-alive for local endpoints) to ensure stable connections.

**3. History of User Actions and Session Management (`session/`)**

`nanobot` meticulously tracks conversation history and session state:

*   **`SessionManager`**: This is the primary component for managing conversation state. It stores `Session` objects, each representing a distinct conversation.
*   **Conversation History**: Each `Session` object contains a list of messages (`session.messages`), storing user inputs, LLM responses, tool calls, and tool results chronologically.
*   **Persistence**: Session data is persisted (likely to files) so that conversations can be resumed.
*   **Context Compaction (`Consolidator`, `AutoCompact`)**: As conversations grow long, older messages are compacted or summarized by the `Consolidator` to fit within the LLM's context window. `AutoCompact` triggers this process based on defined rules (e.g., time-to-live, message count). The summary itself is stored and included in future prompts.
*   **Runtime Checkpoints**: The `AgentLoop` can create runtime checkpoints (`_RUNTIME_CHECKPOINT_KEY`) of an ongoing LLM turn, allowing it to gracefully handle interruptions (like `/stop` commands or crashes) and resume the turn from where it left off.
*   **Sustained Goals (`goal_state.py`)**: For long-running tasks, `nanobot` can track a "goal state" within the session metadata. This allows for objectives that span many turns, influencing LLM timeouts and providing specific UI feedback without needing to include the entire objective in every prompt.

In summary, `nanobot` manages context by abstracting LLM providers and adapting conversation history (including compacted summaries) to fit each model's requirements. It maintains history through a `SessionManager` and intelligently compacts or summarizes older parts of long conversations to ensure responsiveness and manage context window limitations.
