Skip to content

Backend Architecture

RTC Agent Server is a Go service responsible for AI reasoning orchestration, context management, real-time communication, and tool call scheduling. Core components include the WebSocket Gateway, Agent engine, context management, memory system, and RTC handler.

LayerResponsibilityKey Modules
🌐 Access LayerProtocol adaptation, authentication & authorizationWebSocket Gateway, OAuth2 Handler
📋 Use Case LayerBusiness orchestration, RPC processingSession / Message / Turn / RTC use cases
🤖 Domain LayerAI reasoning, state managementAgent Engine, Context Management, Memory System
💾 Infrastructure LayerData persistence, message passingPostgreSQL, Redis, Centrifuge

OAuth2 Authentication: The system uses the OAuth2 authorization code flow. The frontend completes authorization via iframe redirect, obtaining an Access Token (1-hour validity) and Refresh Token (30-day validity). WebSocket connections use the Access Token for authentication. See Authentication Flow.

The Gateway is the entry point for frontend-backend communication, managing all WebSocket connections and RPC routing.

ResponsibilityDescription
Connection ManagementHandles WebSocket connection establishment, authentication, heartbeats, and disconnection
RPC RoutingDispatches the 18 RPC methods to their corresponding use case handlers
Event PushPushes events generated by the Agent to the frontend via Centrifuge
RTC RelayForwards AI tool call requests to the frontend and receives execution results

18 RPC Methods by Category:

CategoryMethods
Sessionsession.list, session.get, session.close, session.update, session.fork, session.compact
Messagemessage.send, message.list, message.get
Turnturn.list, turn.get, turn.stop
RTCrtc.list, rtc.get, rtc.update_status, rtc.submit_result

See WebSocket RPC.

The Agent engine is the core of AI reasoning — assembling prompts, calling the LLM, handling tool calls, and managing the reasoning loop.

CapabilityDescription
Reasoning LoopCall LLM → Process response → Tool call → Continue reasoning, until the final reply is generated
Tool SchedulingManages 6 built-in tools (ls / read / write / grep / find / script)
Streaming OutputPushes LLM output to the frontend in real-time
Sub-AgentsComplex tasks are automatically decomposed, with multiple specialized sub-agents working in parallel (see below)

When task complexity exceeds the capacity of a single reasoning pass, the Agent engine automatically decomposes the task and creates sub-agents for parallel processing:

  • Independent context: Each sub-agent has its own session and context, no interference
  • Parallel execution: Multiple sub-agents can call the LLM and tools simultaneously
  • Result aggregation: The main Agent collects results from all sub-agents and generates the final reply

Context management is responsible for building the complete prompt sent to the LLM, and automatically compressing it when conversations become too long.

When conversation length approaches the token limit, the system uses a three-layer progressive compression approach:

StrategyTriggerCompression MethodRetained Content
MicrocompactAfter tool callsCleans up earlier tool results, keeping only the most recent 5Messages with time gaps > 60 minutes
Auto CompactToken reaches thresholdLLM summarizes earlier conversations (9-part structured summary)Most recent 10K tokens + 5 messages
Session Memory CompactAuto Compact fails 3 timesDirectly uses Session Memory as summarySession Memory’s 5 categories

Circuit breaker: If Auto Compact fails 3 consecutive times, the system stops auto-compression to avoid infinite loops consuming tokens.

See Context Management.

A dual-layer memory architecture that gives AI both short-term and long-term memory.

Independently maintained per session, used for long-conversation context compression:

CategoryDescription
decisionDecisions and choices made by the user
contextBackground information for the current task
progressCompleted work and progress
issueEncountered problems and blockers
learningsLessons learned from the task
  • Capacity: Max 20 entries, approximately 12K tokens
  • Extraction: Dual-track — background Agent automatic extraction + Agent proactive saving
  • Usage: Source for Session Memory Compact summaries; 5 entries injected into context per conversation turn

Cross-session long-term memory, storing user preferences and historical facts:

CategoryDescription
userUser identity (role, expertise, preferences)
feedbackUser feedback on working style
projectOngoing projects, goals, constraints
referenceExternal resource pointers (URLs, docs, tickets)
  • Importance levels: low / medium / high / critical
  • Capacity: Max 1000 entries
  • Extraction: Agent proactive saving only
  • Retrieval: Hybrid retrieval (vector cosine similarity top-20 + keyword full-text search top-20 → RRF fusion → importance weighting → top 5)

See Memory System.

The RTC handler manages the full lifecycle of tool calls — from creating RTC records to saving checkpoints, pausing Turns, waiting for results, and resuming reasoning.

FeatureDescription
CheckpointSaves the current reasoning state to Redis, with a 24-hour TTL
Crash RecoveryCan recover from a checkpoint after server restart
Serial ExecutionRTC calls within the same session are strictly serialized to avoid file conflicts
100% DeliveryFrontend result submission retries indefinitely; idempotency is guaranteed

Different work modes have different confirmation strategies for tool calls:

Tool Typemanualeditplanautobypass
Read-only tools (ls/read/grep/find)✅ Auto✅ Auto✅ Auto✅ Auto✅ Auto
Write tools (write)⚠️ Confirm✅ Auto⚠️ Confirm✅ Auto✅ Auto
script tool⚠️ Confirm⚠️ Confirm⚠️ Confirm⚠️ Confirm✅ Auto

See Work Modes.

ChannelPurposeCharacteristics
TopicState change events (Session, Message, Turn, RTC)Persisted, offset tracking, offline recovery
LiveStreaming output intermediate chunksNon-persistent, Redis PUB/SUB, low latency, lossy
  • Brief disconnection (< 5 seconds): Missing events are automatically pushed after reconnection
  • Long disconnection: Client detects offset gap and proactively pulls history
  • Epoch change: After server restart, epoch changes; client resets offset and pulls full state

See Real-Time Communication.