Skip to main content

Session Management

Sessions control when agents are active and manage long-lived connections.

Understanding Sessions

Session Basics

A session is a 6-hour window where:
  • Agent can store and retrieve memories
  • Session token authenticates requests
  • Memories persist after session ends
  • Multiple sessions can exist over time

Session Lifecycle

Activate → Use (up to 6 hours) → Extend or Deactivate

Session States

┌─────────────────────────────────────────┐
│   ACTIVE (0-6 hours)                    │
│   - Can store memories                  │
│   - Can recall memories                 │
│   - Session token valid                 │
└─────────────────┬───────────────────────┘

         (6 hours pass or deactivate)

┌─────────────────────────────────────────┐
│   INACTIVE                              │
│   - Memories still exist                │
│   - Cannot access without new session   │
│   - Can reactivate anytime              │
└─────────────────────────────────────────┘

Session Operations

Activate Session

Start a new session:
memanto agent activate customer-support
Output:
✓ Session activated for agent 'customer-support'
Session ID:    session_xyz789
Session Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Created At:    2025-03-30 16:30:00 UTC
Expires At:    2025-03-31 22:30:00 UTC
Expires In:    6h 0m
Via REST API:
response = httpx.post(
    f"http://localhost:8000/api/v2/agents/{agent_id}/activate",
    headers={"Authorization": f"Bearer {api_key}"}
)
data = response.json()
session_token = data["session_token"]
print(f"Session expires: {data['expires_at']}")

Check Current Session

View active session details:
memanto session info
Output:
Current Session Information

Agent:     customer-support
Status:    ACTIVE
Created:   2025-03-30 16:30:00 UTC
Expires:   2025-03-31 22:30:00 UTC
Remaining: 5h 45m
Via REST API:
response = httpx.get(
    "http://localhost:8000/api/v2/session/current",
    headers={
        "Authorization": f"Bearer {api_key}",
        "X-Session-Token": session_token
    }
)
session_info = response.json()
print(f"Expires at: {session_info['expires_at']}")

Extend Session

Keep agent active beyond 6 hours:
memanto session extend --hours 6
Output:
✓ Session extended successfully
New Expiry: 2025-04-01 04:30:00 UTC
Hours Added: 6
Extend multiple times:
# Add 12 more hours
memanto session extend --hours 12
Via REST API:
response = httpx.post(
    "http://localhost:8000/api/v2/session/extend",
    params={"extend_hours": 12},
    headers={
        "Authorization": f"Bearer {api_key}",
        "X-Session-Token": session_token
    }
)
new_expiry = response.json()["expires_at"]
print(f"New expiry: {new_expiry}")

Deactivate Session

End the current session:
memanto agent deactivate
Output:
✓ Session deactivated for agent 'customer-support'
Session Summary:
- Duration: 2h 15m
- Memories Stored: 12
- Memories Retrieved: 8
Via REST API:
response = httpx.post(
    f"http://localhost:8000/api/v2/agents/{agent_id}/deactivate",
    headers={
        "Authorization": f"Bearer {api_key}",
        "X-Session-Token": session_token
    }
)

Session Token Management

What’s a Session Token?

A JWT (JSON Web Token) that:
  • Authenticates agent operations
  • Contains agent ID and expiry time
  • Is cryptographically signed
  • Never changes during session
  • Must be sent with memory operations

Token Format

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJhZ2VudF9pZCI6ImN1c3RvbWVyLXN1cHBvcnQiLCJleHBpcmVzX2F0IjoiMjAyNS0wMy0zMVQyMjozMDowMFoifQ.
[signature]

Token Handling

Always include token with API calls:
headers = {
    "Authorization": f"Bearer {api_key}",
    "X-Session-Token": session_token
}

response = httpx.post(
    f"http://localhost:8000/api/v2/agents/{agent_id}/remember",
    params={"content": "...", "type": "fact"},
    headers=headers
)

Automatic Token Refresh

MEMANTO automatically refreshes tokens before expiry:
# This is handled automatically by MEMANTO CLI
# Token is checked and renewed if near expiry
memanto status  # Token auto-renewed if needed
For manual renewal:
import jwt
from datetime import datetime

payload = jwt.decode(
    session_token,
    options={"verify_signature": False}
)
expires_at = datetime.fromisoformat(payload["expires_at"])

if datetime.utcnow() > expires_at:
    # Token expired - extend session
    httpx.post(
        "http://localhost:8000/api/v2/session/extend",
        params={"extend_hours": 6},
        headers={
            "Authorization": f"Bearer {api_key}",
            "X-Session-Token": session_token
        }
    )

Multi-Session Patterns

Sequential Sessions

Same agent, different times:
Session 1 (Day 1) → Store facts about customer
     ↓ (6 hours)
Session 2 (Day 1 later) → Recall facts, add new info
     ↓ (6 hours)
Session 3 (Day 2) → Continue with full context
All memories persist across sessions.

Parallel Sessions

Different agents, same time:
agents = ["customer-support", "billing-bot", "technical-support"]

sessions = {}
for agent_id in agents:
    response = httpx.post(
        f"http://localhost:8000/api/v2/agents/{agent_id}/activate",
        headers={"Authorization": f"Bearer {api_key}"}
    )
    sessions[agent_id] = response.json()["session_token"]

# Now can use all agents simultaneously
for agent_id, token in sessions.items():
    # Perform operations with each agent

Agent Rotation

When one agent’s session expires, activate another:
import time

def use_agent_rotation(agents, duration_hours=24):
    """Rotate through multiple agents over extended time."""

    sessions = {}
    agent_index = 0

    start_time = time.time()
    while (time.time() - start_time) < duration_hours * 3600:
        # Get current agent
        agent_id = agents[agent_index % len(agents)]

        if agent_id not in sessions:
            # Activate new session
            response = httpx.post(
                f"http://localhost:8000/api/v2/agents/{agent_id}/activate",
                headers={"Authorization": f"Bearer {api_key}"}
            )
            sessions[agent_id] = response.json()["session_token"]

        # Do work with current agent
        httpx.post(
            f"http://localhost:8000/api/v2/agents/{agent_id}/remember",
            params={"content": "...", "type": "fact"},
            headers={
                "Authorization": f"Bearer {api_key}",
                "X-Session-Token": sessions[agent_id]
            }
        )

        # Rotate to next agent
        agent_index += 1
        time.sleep(60)

Session Persistence

Across Runs

Session information persists in config:
# First run - activate session
python agent.py
# Creates session_token in ~/.memanto/config.json

# Second run - session still active
python agent.py
# Uses same session_token (if not expired)

Explicit Session Management

For long-running processes:
# Start of program
def init_agent():
    agent_id = "my-agent"
    api_key = os.getenv("MOORCHEH_API_KEY")

    # Try to use existing session
    config = load_config()
    session_token = config.get("active_session_token")

    if session_token and is_token_valid(session_token):
        return agent_id, session_token

    # Otherwise activate new session
    response = httpx.post(
        f"http://localhost:8000/api/v2/agents/{agent_id}/activate",
        headers={"Authorization": f"Bearer {api_key}"}
    )
    session_token = response.json()["session_token"]
    save_config(session_token)
    return agent_id, session_token

Session Timeouts & Limits

Default Duration

  • Standard session: 6 hours
  • Can extend up to: 24+ hours (extend multiple times)
  • Cannot create: Sessions longer than 24 hours at creation

Handling Expiry

When session expires:
try:
    response = httpx.post(
        f"http://localhost:8000/api/v2/agents/{agent_id}/remember",
        params={"content": "...", "type": "fact"},
        headers={
            "Authorization": f"Bearer {api_key}",
            "X-Session-Token": expired_token
        }
    )
except httpx.HTTPStatusError as e:
    if e.response.status_code == 401:
        # Session expired - get new one
        response = httpx.post(
            f"http://localhost:8000/api/v2/agents/{agent_id}/activate",
            headers={"Authorization": f"Bearer {api_key}"}
        )
        new_token = response.json()["session_token"]
        # Retry with new token

Proactive Extension

Extend before expiry:
def extend_if_needed(session_token, min_hours_remaining=2):
    """Extend session if less than min_hours_remaining."""

    payload = jwt.decode(
        session_token,
        options={"verify_signature": False}
    )
    expires_at = datetime.fromisoformat(payload["expires_at"])
    hours_left = (expires_at - datetime.utcnow()).total_seconds() / 3600

    if hours_left < min_hours_remaining:
        httpx.post(
            "http://localhost:8000/api/v2/session/extend",
            params={"extend_hours": 6},
            headers={
                "Authorization": f"Bearer {api_key}",
                "X-Session-Token": session_token
            }
        )
        return True  # Extended
    return False  # Not needed

Best Practices

DO

  • Extend sessions proactively before expiry
  • Store session tokens securely
  • Use one session per agent at a time
  • Deactivate sessions when done
  • Monitor session expiration times

DON’T

  • Create new sessions unnecessarily
  • Hardcode session tokens
  • Keep tokens in logs
  • Ignore expiry warnings
  • Use expired tokens (extend instead)

Next Steps


Session management ensures reliable, long-running agent operations. Master it for production reliability!