# allecosay/respmanager architecture

> Architecture diagram of the GitHub repository allecosay/respmanager, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-17). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/allecosay/respmanager
- Repository: https://github.com/allecosay/respmanager

## Overview

1. **Overall shape**
   This is a Telegram assistant built around a long-lived Telethon user session, not the Telegram Bot API. Its core job is to ingest group messages into PostgreSQL, maintain several derived state tables, and answer commands or trigger autonomous replies using an LLM via OpenRouter.

2. **Startup and runtime boundary**
   `app/main.py` is the application entrypoint. It wires together env-based runtime settings, YAML-backed feature configs, logging, the PostgreSQL session, the Telethon client, and the background services. The container startup also runs Alembic migrations, so schema changes are part of normal deployment.

3. **Telegram ingress layer**
   `app/telegram_client/` wraps Telethon with a project-specific client and adapter layer. Raw Telegram updates are converted into internal types, then handed to message ingestion, command handling, reaction processing, and pollers. The Telethon session is persisted under `config/` so restarts do not require a new login.

4. **Command handling path**
   `app/bot/command_handlers.py` and `app/bot/commands.py` parse `/ai`, `/tldr`, `/stats`, `/help`, `/whitelist`, and related commands. These handlers are thin orchestration code: they perform access checks, call the relevant service, and format the reply for Telegram. The formatting module keeps the chat-facing output separate from business logic.

5. **Access control and authorization**
   `app/auth/` manages admin and whitelist policy using YAML-backed storage. This is the gate in front of sensitive commands and AI access. The repository is explicitly designed to refuse unsafe startup modes unless the allowlist is intentional.

6. **Persistence model**
   `app/db/models.py`, `repositories.py`, and `session.py` form the persistence boundary. PostgreSQL stores the canonical message history plus derived tables for reactions, activity reply state, memory profiles, bot identity profiles, and statistics-related data. The Alembic versions show the system evolving around message reactions, reply state, memory, and identity features.

7. **AI answer pipeline**
   `/ai` is served by `app/services/ai_answer_service.py`. It uses `context_builder.py` and the various LLM config modules to assemble a thread-aware prompt from nearby messages and cross-thread context, then calls `app/llm/openrouter_client.py`. This is the main read path from stored chat history into the external LLM service.

8. **Summarization and context services**
   `/tldr` is implemented by `app/services/tldr_service.py`, which summarizes recent message windows rather than doing general question answering. `app/llm/context_builder.py`, `thread_activity.py`, and related helpers define how much history is considered and how thread boundaries influence the context sent to the model.

9. **Autonomous background behavior**
   Three poller-driven subsystems operate off the stored chat history:
   - `reaction_poller` / `reaction_service` watch reaction snapshots and may post an LLM-generated response when thresholds are met.
   - `activity_poller` / `activity_service` detect lively chats and can inject spontaneous replies or follow-ups.
   - `memory_poller` / `memory_service` refresh long-term per-chat memory and user profiles based on activity, keywords, and staleness.
   These are separate from command handling and are designed to survive restarts by persisting state in PostgreSQL.

10. **Statistics pipeline**
   `app/services/stats_service.py`, `stats_report.py`, `stats_renderer.py`, and `stats_image_renderer.py` build `/stats` output from existing database rows. This path does not call the LLM. It can render either as an image chart or as ASCII/text, depending on configuration, and it pulls from the same message, reaction, command, and usage history maintained elsewhere.

11. **Auxiliary services**
   There are a few smaller but important side systems: `auto_delete_config.py` controls cleanup of bot replies after posting; `bot_identity_service.py` and `avatar_service.py` manage bot identity/profile behavior; `telegram_links.py` and `utils/telegram.py` encapsulate Telegram-specific link and formatting logic; and `image_generation_client.py` supports image-producing workflows where needed.

12. **Configuration topology**
   Secrets and deployment settings live in `.env`, while behavior is mostly driven by hot-reloaded YAML under `config/`. The YAML files split policy by domain: prompts, context limits, reactions, activity, memory, stats, auto-delete, identity, and access lists. That separation is a major architectural boundary: runtime credentials and infrastructure settings are distinct from feature behavior.

13. **Key data flow for diagramming**
   The most important end-to-end flow is: Telegram event → Telethon adapter → ingestion/command/poller service → PostgreSQL read/write → optional OpenRouter call → Telegram reply. The second major flow is the autonomous one: database state and pollers → eligibility/rule evaluation → LLM or formatted output → Telegram message/reaction/state update.

14. **Operational boundaries**
   The app is containerized with Docker Compose and expects PostgreSQL plus a Telegram-auth bootstrap container. Tests cover config parsing, adapter conversion, formatting, pollers, and the service logic, which suggests a design that keeps Telegram I/O, persistence, and business rules cleanly separated.

Main entry points: [`app/main.py`](https://github.com/allecosay/respmanager/blob/master/app/main.py) (Main), [`app/db/repositories.py`](https://github.com/allecosay/respmanager/blob/master/app/db/repositories.py) (Repositories), [`app/bot/command_handlers.py`](https://github.com/allecosay/respmanager/blob/master/app/bot/command_handlers.py) (Handlers), [`app/telegram_client/telethon_adapter.py`](https://github.com/allecosay/respmanager/blob/master/app/telegram_client/telethon_adapter.py) (Adapter)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_runtime["Runtime"]
  node_main["Main<br/>entrypoint<br/>[main.py]"]
  node_runtime_config["Runtime cfg<br/>config<br/>[runtime_config.py]"]
end

subgraph group_telegram["Telegram"]
  node_telegram_client["Telethon client<br/>[client.py]"]
  node_telethon_adapter["Adapter"]
  node_message_ingestion["Ingestion"]
end

subgraph group_bot["Bot"]
  node_command_handlers["Handlers<br/>command orchestration"]
  node_commands["Commands<br/>command parsing<br/>[commands.py]"]
  node_formatting["Formatting<br/>presentation<br/>[formatting.py]"]
end

subgraph group_policy["Policy"]
  node_access_control["Access control<br/>policy<br/>[access_control.py]"]
  node_yaml_store["YAML store<br/>policy storage<br/>[yaml_store.py]"]
end

subgraph group_persistence["Persistence"]
  node_db_session[("DB session<br/>postgres session<br/>[session.py]")]
  node_db_models["Models<br/>[models.py]"]
  node_db_repositories["Repositories<br/>data access<br/>[repositories.py]"]
  node_migrations["Migrations<br/>schema evolution"]
end

subgraph group_llm["LLM"]
  node_ai_answer_service["AI answer<br/>llm service"]
  node_tldr_service["TL;DR<br/>summarizer<br/>[tldr_service.py]"]
  node_context_builder["Context builder<br/>prompt assembly<br/>[context_builder.py]"]
  node_openrouter_client["OpenRouter<br/>llm client"]
end

subgraph group_autonomous["Autonomy"]
  node_reaction_poller["Reaction poller<br/>background poller<br/>[reaction_poller.py]"]
  node_reaction_service["Reaction svc<br/>reaction workflow"]
  node_activity_poller["Activity poller<br/>background poller<br/>[activity_poller.py]"]
  node_activity_service["Activity svc<br/>activity workflow"]
  node_memory_poller["Memory poller<br/>background poller<br/>[memory_poller.py]"]
  node_memory_service["Memory svc<br/>memory workflow<br/>[memory_service.py]"]
end

subgraph group_stats["Stats"]
  node_stats_service["Stats svc<br/>report service<br/>[stats_service.py]"]
  node_stats_report["Stats report<br/>aggregation<br/>[stats_report.py]"]
  node_stats_renderer["Stats renderer<br/>text renderer<br/>[stats_renderer.py]"]
  node_stats_image_renderer["Stats image<br/>image renderer"]
end

subgraph group_identity["Identity"]
  node_bot_identity_service["Identity svc<br/>identity workflow"]
  node_avatar_service["Avatar svc<br/>avatar workflow<br/>[avatar_service.py]"]
  node_image_generation_client["Image gen<br/>media client"]
end

node_main -->|"loads"| node_runtime_config
node_main -->|"opens"| node_db_session
node_main -->|"starts"| node_telegram_client
node_main -->|"wires"| node_command_handlers
node_main -->|"wires"| node_message_ingestion
node_main -->|"starts"| node_reaction_poller
node_main -->|"starts"| node_activity_poller
node_main -->|"starts"| node_memory_poller
node_telegram_client -->|"uses"| node_telethon_adapter
node_telethon_adapter -->|"emits"| node_message_ingestion
node_telethon_adapter -->|"emits"| node_command_handlers
node_telethon_adapter -->|"feeds"| node_reaction_poller
node_command_handlers -->|"parses"| node_commands
node_command_handlers -->|"checks"| node_access_control
node_command_handlers -->|"formats"| node_formatting
node_access_control -->|"reads"| node_yaml_store
node_message_ingestion -->|"writes"| node_db_session
node_message_ingestion -->|"uses"| node_db_repositories
node_db_repositories -->|"maps"| node_db_models
node_db_models -->|"evolves"| node_migrations
node_ai_answer_service -->|"builds"| node_context_builder
node_ai_answer_service -->|"calls"| node_openrouter_client
node_ai_answer_service -->|"reads"| node_db_repositories
node_tldr_service -->|"uses"| node_context_builder
node_tldr_service -->|"reads"| node_db_repositories
node_reaction_poller -->|"drives"| node_reaction_service
node_reaction_service -->|"reads/writes"| node_db_repositories
node_reaction_service -->|"may call"| node_openrouter_client
node_activity_poller -->|"drives"| node_activity_service
node_activity_service -->|"reads/writes"| node_db_repositories
node_activity_service -->|"may call"| node_openrouter_client
node_memory_poller -->|"drives"| node_memory_service
node_memory_service -->|"reads/writes"| node_db_repositories
node_stats_service -->|"builds"| node_stats_report
node_stats_report -->|"reads"| node_db_repositories
node_stats_service -->|"renders"| node_stats_renderer
node_stats_service -->|"renders"| node_stats_image_renderer
node_bot_identity_service -->|"reads/writes"| node_db_repositories
node_avatar_service -->|"supports"| node_bot_identity_service
node_avatar_service -->|"may call"| node_image_generation_client

click node_main "https://github.com/allecosay/respmanager/blob/master/app/main.py"
click node_runtime_config "https://github.com/allecosay/respmanager/blob/master/app/llm/runtime_config.py"
click node_telegram_client "https://github.com/allecosay/respmanager/blob/master/app/telegram_client/client.py"
click node_telethon_adapter "https://github.com/allecosay/respmanager/blob/master/app/telegram_client/telethon_adapter.py"
click node_message_ingestion "https://github.com/allecosay/respmanager/blob/master/app/services/message_ingestion.py"
click node_command_handlers "https://github.com/allecosay/respmanager/blob/master/app/bot/command_handlers.py"
click node_commands "https://github.com/allecosay/respmanager/blob/master/app/bot/commands.py"
click node_formatting "https://github.com/allecosay/respmanager/blob/master/app/bot/formatting.py"
click node_access_control "https://github.com/allecosay/respmanager/blob/master/app/auth/access_control.py"
click node_yaml_store "https://github.com/allecosay/respmanager/blob/master/app/auth/yaml_store.py"
click node_db_session "https://github.com/allecosay/respmanager/blob/master/app/db/session.py"
click node_db_models "https://github.com/allecosay/respmanager/blob/master/app/db/models.py"
click node_db_repositories "https://github.com/allecosay/respmanager/blob/master/app/db/repositories.py"
click node_migrations "https://github.com/allecosay/respmanager/blob/master/app/db/migrations/versions/0001_initial_schema.py"
click node_ai_answer_service "https://github.com/allecosay/respmanager/blob/master/app/services/ai_answer_service.py"
click node_tldr_service "https://github.com/allecosay/respmanager/blob/master/app/services/tldr_service.py"
click node_context_builder "https://github.com/allecosay/respmanager/blob/master/app/llm/context_builder.py"
click node_openrouter_client "https://github.com/allecosay/respmanager/blob/master/app/llm/openrouter_client.py"
click node_reaction_poller "https://github.com/allecosay/respmanager/blob/master/app/services/reaction_poller.py"
click node_reaction_service "https://github.com/allecosay/respmanager/blob/master/app/services/reaction_service.py"
click node_activity_poller "https://github.com/allecosay/respmanager/blob/master/app/services/activity_poller.py"
click node_activity_service "https://github.com/allecosay/respmanager/blob/master/app/services/activity_service.py"
click node_memory_poller "https://github.com/allecosay/respmanager/blob/master/app/services/memory_poller.py"
click node_memory_service "https://github.com/allecosay/respmanager/blob/master/app/services/memory_service.py"
click node_stats_service "https://github.com/allecosay/respmanager/blob/master/app/services/stats_service.py"
click node_stats_report "https://github.com/allecosay/respmanager/blob/master/app/services/stats_report.py"
click node_stats_renderer "https://github.com/allecosay/respmanager/blob/master/app/services/stats_renderer.py"
click node_stats_image_renderer "https://github.com/allecosay/respmanager/blob/master/app/services/stats_image_renderer.py"
click node_bot_identity_service "https://github.com/allecosay/respmanager/blob/master/app/services/bot_identity_service.py"
click node_avatar_service "https://github.com/allecosay/respmanager/blob/master/app/services/avatar_service.py"
click node_image_generation_client "https://github.com/allecosay/respmanager/blob/master/app/services/image_generation_client.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_main,node_runtime_config,node_reaction_poller,node_reaction_service,node_activity_poller,node_activity_service,node_memory_poller,node_memory_service toneBlue
class node_telegram_client,node_telethon_adapter,node_message_ingestion,node_stats_service,node_stats_report,node_stats_renderer,node_stats_image_renderer toneAmber
class node_command_handlers,node_commands,node_formatting,node_bot_identity_service,node_avatar_service,node_image_generation_client toneMint
class node_access_control,node_yaml_store toneRose
class node_db_session,node_db_models,node_db_repositories,node_migrations toneIndigo
class node_ai_answer_service,node_tldr_service,node_context_builder,node_openrouter_client toneTeal
```

## Components

### Runtime

Application startup and shared runtime wiring

- [Main](https://github.com/allecosay/respmanager/blob/master/app/main.py): entrypoint · Bootstraps config, database, Telegram client, and background services · `app/main.py`
- [Runtime cfg](https://github.com/allecosay/respmanager/blob/master/app/llm/runtime_config.py): config · Environment-driven runtime settings · `app/llm/runtime_config.py`

### Telegram

Telegram client boundary and update ingress

- [Telethon client](https://github.com/allecosay/respmanager/blob/master/app/telegram_client/client.py): client · Project-specific wrapper around the long-lived Telegram session · `app/telegram_client/client.py`
- [Adapter](https://github.com/allecosay/respmanager/blob/master/app/telegram_client/telethon_adapter.py): ingress adapter · Converts raw Telegram updates into internal event types · `app/telegram_client/telethon_adapter.py`
- [Ingestion](https://github.com/allecosay/respmanager/blob/master/app/services/message_ingestion.py): service · Persists incoming chat messages and derived state · `app/services/message_ingestion.py`

### Bot

Command handling and chat-facing output

- [Handlers](https://github.com/allecosay/respmanager/blob/master/app/bot/command_handlers.py): command orchestration · Dispatches and executes Telegram commands · `app/bot/command_handlers.py`
- [Commands](https://github.com/allecosay/respmanager/blob/master/app/bot/commands.py): command parsing · Parses supported slash commands · `app/bot/commands.py`
- [Formatting](https://github.com/allecosay/respmanager/blob/master/app/bot/formatting.py): presentation · Builds chat-facing replies and message text · `app/bot/formatting.py`

### Policy

Access control and YAML-backed feature settings

- [Access control](https://github.com/allecosay/respmanager/blob/master/app/auth/access_control.py): policy · Admin and whitelist checks for sensitive actions · `app/auth/access_control.py`
- [YAML store](https://github.com/allecosay/respmanager/blob/master/app/auth/yaml_store.py): policy storage · Loads policy and allowlist data from YAML · `app/auth/yaml_store.py`

### Persistence

Database schema, session, and repositories

- [DB session](https://github.com/allecosay/respmanager/blob/master/app/db/session.py): postgres session · Database connection and transactional session boundary · `app/db/session.py`
- [Models](https://github.com/allecosay/respmanager/blob/master/app/db/models.py): schema models · Canonical message, reaction, memory, identity, and stats tables · `app/db/models.py`
- [Repositories](https://github.com/allecosay/respmanager/blob/master/app/db/repositories.py): data access · Repository layer for persisted chat state · `app/db/repositories.py`
- [Migrations](https://github.com/allecosay/respmanager/blob/master/app/db/migrations/versions/0001_initial_schema.py): schema evolution · Alembic migration history for PostgreSQL schema changes · `app/db/migrations/versions/0001_initial_schema.py`

### LLM

Context assembly and external model calls

- [AI answer](https://github.com/allecosay/respmanager/blob/master/app/services/ai_answer_service.py): llm service · Answers /ai using stored chat context and OpenRouter · `app/services/ai_answer_service.py`
- [TL;DR](https://github.com/allecosay/respmanager/blob/master/app/services/tldr_service.py): summarizer · Summarizes recent message windows for /tldr · `app/services/tldr_service.py`
- [Context builder](https://github.com/allecosay/respmanager/blob/master/app/llm/context_builder.py): prompt assembly · Builds thread-aware context from nearby and related messages · `app/llm/context_builder.py`
- [OpenRouter](https://github.com/allecosay/respmanager/blob/master/app/llm/openrouter_client.py): llm client · External model API client · `app/llm/openrouter_client.py`

### Autonomy

Background pollers that react to stored chat state

- [Reaction poller](https://github.com/allecosay/respmanager/blob/master/app/services/reaction_poller.py): background poller · Watches reaction snapshots and triggers reactions workflows · `app/services/reaction_poller.py`
- [Reaction svc](https://github.com/allecosay/respmanager/blob/master/app/services/reaction_service.py): reaction workflow · Evaluates thresholds and may generate replies from reactions · `app/services/reaction_service.py`
- [Activity poller](https://github.com/allecosay/respmanager/blob/master/app/services/activity_poller.py): background poller · Detects lively chats and schedules spontaneous follow-ups · `app/services/activity_poller.py`
- [Activity svc](https://github.com/allecosay/respmanager/blob/master/app/services/activity_service.py): activity workflow · Decides when a chat is active enough for autonomous responses · `app/services/activity_service.py`
- [Memory poller](https://github.com/allecosay/respmanager/blob/master/app/services/memory_poller.py): background poller · Refreshes long-term chat memory and user profiles · `app/services/memory_poller.py`
- [Memory svc](https://github.com/allecosay/respmanager/blob/master/app/services/memory_service.py): memory workflow · Maintains per-chat memory and profile state · `app/services/memory_service.py`

### Stats

Reporting and rendering pipeline

- [Stats svc](https://github.com/allecosay/respmanager/blob/master/app/services/stats_service.py): report service · Builds /stats output from stored usage and chat rows · `app/services/stats_service.py`
- [Stats report](https://github.com/allecosay/respmanager/blob/master/app/services/stats_report.py): aggregation · Assembles statistics data from database history · `app/services/stats_report.py`
- [Stats renderer](https://github.com/allecosay/respmanager/blob/master/app/services/stats_renderer.py): text renderer · Renders stats as formatted text or ASCII · `app/services/stats_renderer.py`
- [Stats image](https://github.com/allecosay/respmanager/blob/master/app/services/stats_image_renderer.py): image renderer · Renders stats as charts/images · `app/services/stats_image_renderer.py`

### Identity

Bot identity, avatar, and media helpers

- [Identity svc](https://github.com/allecosay/respmanager/blob/master/app/services/bot_identity_service.py): identity workflow · Manages bot identity/profile behavior · `app/services/bot_identity_service.py`
- [Avatar svc](https://github.com/allecosay/respmanager/blob/master/app/services/avatar_service.py): avatar workflow · Handles avatar-related behavior for the bot identity · `app/services/avatar_service.py`
- [Image gen](https://github.com/allecosay/respmanager/blob/master/app/services/image_generation_client.py): media client · External image generation support · `app/services/image_generation_client.py`

## Connections

- Main → Runtime cfg: loads · Reads deployment and runtime settings
- Main → DB session: opens · Creates the PostgreSQL session boundary
- Main → Telethon client: starts · Initializes the long-lived Telegram session
- Main → Handlers: wires · Connects command processing into runtime
- Main → Ingestion: wires · Connects message ingestion into runtime
- Main → Reaction poller: starts · Launches background reaction scanning
- Main → Activity poller: starts · Launches background activity scanning
- Main → Memory poller: starts · Launches background memory refresh
- Telethon client → Adapter: uses · Normalizes raw Telegram updates
- Adapter → Ingestion: emits · Forwards message events for storage
- Adapter → Handlers: emits · Routes command updates
- Adapter → Reaction poller: feeds · Provides reaction snapshots and update context
- Handlers → Commands: parses · Interprets slash command input
- Handlers → Access control: checks · Enforces admin and whitelist policy
- Handlers → Formatting: formats · Builds user-facing replies
- Access control → YAML store: reads · Loads allowlists and policy state
- Ingestion → DB session: writes · Persists incoming messages and derived rows
- Ingestion → Repositories: uses · Stores data through repositories
- Repositories → Models: maps · Implements the persistence model
- Models → Migrations: evolves · Schema changes track model growth
- AI answer → Context builder: builds · Assembles thread-aware prompt context
- AI answer → OpenRouter: calls · Sends prompt to external model service
- AI answer → Repositories: reads · Pulls nearby and cross-thread chat history
- TL;DR → Context builder: uses · Selects summarization context window
- TL;DR → Repositories: reads · Loads recent messages for summarization
- Reaction poller → Reaction svc: drives · Hands reaction snapshots to workflow logic
- Reaction svc → Repositories: reads/writes · Evaluates reaction state and records outcomes
- Reaction svc → OpenRouter: may call · Generates LLM-based reaction replies when needed
- Activity poller → Activity svc: drives · Feeds activity evaluation loop
- Activity svc → Repositories: reads/writes · Uses stored activity and reply state
- Activity svc → OpenRouter: may call · Can generate autonomous follow-up replies
- Memory poller → Memory svc: drives · Feeds memory refresh loop
- Memory svc → Repositories: reads/writes · Maintains long-term memory and profiles
- Stats svc → Stats report: builds · Aggregates usage and chat history
- Stats report → Repositories: reads · Consumes persisted message, command, and reaction rows
- Stats svc → Stats renderer: renders · Produces text/ASCII output
- Stats svc → Stats image: renders · Produces chart/image output
- Identity svc → Repositories: reads/writes · Stores and loads identity profiles
- Avatar svc → Identity svc: supports · Feeds identity/avatar behavior
- Avatar svc → Image gen: may call · Requests generated imagery when needed
