> ## Documentation Index
> Fetch the complete documentation index at: https://docs.memanto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Session Management

> Activate, inspect, and deactivate agent sessions.

# Session Management

Sessions control when agents are active and gate memory operations behind a short-lived token.

## Understanding Sessions

### Session Basics

A **session** is a time-bounded window (configured server-side, default \~6 hours) where:

* The agent can store and retrieve memories
* The session token authenticates memory operations
* Memories persist after the session ends
* Multiple sessions can exist over time

Sessions serve two core purposes:

1. **Authorization** — the session token proves your client is allowed to perform memory operations against a specific agent.
2. **State boundaries** — sessions create a clear active/inactive boundary for long-running workflows and produce a per-session summary on deactivation.

<Note>
  The Moorcheh API key is configured **on the Memanto server** (`MOORCHEH_API_KEY`). Clients never send it. The only client-side credential is the `X-Session-Token` header, used on memory endpoints.
</Note>

### Session Properties

Each session includes:

* **session\_id** — unique identifier
* **session\_token** — JWT used in `X-Session-Token`
* **agent\_id** — which agent the session is bound to
* **namespace** — `memanto_agent_{agent_id}`
* **started\_at** / **expires\_at** — lifetime
* **pattern** — `support`, `project`, or `tool`
* **status** — `active`, `expired`, or `terminated`

### Session Lifecycle

```
Activate → Use (until expiry, auto-renewed near expiry) → Deactivate
```

### Session States

```text theme={null}
+-----------------------------------------+
|   ACTIVE                                |
|   - Can store memories                  |
|   - Can recall memories                 |
|   - Session token valid                 |
+-----------------+-----------------------+
                  |
        (token expires or deactivate)
                  v
+-----------------------------------------+
|   INACTIVE                              |
|   - Memories still exist                |
|   - Cannot access without new session   |
|   - Can reactivate anytime              |
+-----------------------------------------+
```

## Managing Sessions

Sessions can be activated, inspected, and deactivated using the CLI or REST API.

* **CLI Reference**: see [activate](/cli/sessions/activate), [info](/cli/sessions/info), [deactivate](/cli/sessions/deactivate).
* **API Reference**: see [Activate Agent](/api-reference/sessions/activate-agent), [Get Current Session](/api-reference/sessions/get-current-session), [Deactivate Agent](/api-reference/sessions/deactivate-agent).

## Session Token Management

### Token Handling

A session token is a JWT returned when activating an agent. It carries the agent ID and expiry, and must be sent with all memory operations:

```python theme={null}
import httpx

headers = {
    "X-Session-Token": session_token,
    "Content-Type": "application/json",
}

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

### Automatic Token Refresh

Memanto auto-renews sessions that are near expiry on the next memory request — no separate "extend" call is needed. The CLI inherits this behavior:

```bash theme={null}
memanto status   # if the session is near expiry, Memanto renews it
```

For API clients, simply keep using the current `session_token`; if Memanto renews it, the next response carries the refreshed expiration.

### Automatic Recreation After Expiry

If a session has *already* lapsed past its expiry, Memanto issues a brand-new session on the next request rather than failing with `401`. This is what keeps a CLI that has been idle overnight working — `memanto status` picks up where it left off instead of reporting *No active session*.

Recreation only happens when the caller clears the same management-access check as an explicit activation: a valid management credential (`Authorization: Bearer` / `X-Api-Key`) or a request from the loopback interface. A remote caller holding nothing but a stale token still gets `401`. It is governed by `SESSION_AUTO_RECREATE_ENABLED` (default `True`), settable as an environment variable, as `session.auto_recreate_enabled` in `config.yaml`, or from the Web UI settings panel.

Two cases are never recreated:

* A session ended deliberately with `POST /api/v2/agents/{agent_id}/deactivate` — logout is authoritative, so activate explicitly afterwards.
* A stale token whose agent has since started a newer session — the newer session is never superseded.

The replacement token comes back in the `X-Session-Token` response header (or the refreshed `memanto_session_token` cookie for browser clients), the same handoff used for auto-renewal.

## Multi-Session Patterns

### Sequential Sessions

Same agent, different times:

```
Session 1 (Day 1) → Store facts about customer
     ↓ (session ends)
Session 2 (Day 1 later) → Recall facts, add new info
     ↓ (session ends)
Session 3 (Day 2) → Continue with full context
```

All memories persist across sessions.

### Session vs Memory

Sessions are temporary. Memories are persistent.

```
Session A ends
    ↓
Memories remain
    ↓
Session B can still recall them
```

### Parallel Sessions

Different agents, same time:

```python theme={null}
import httpx

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"
    )
    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 using token in X-Session-Token
    ...
```

## Session Persistence

### Across Runs

Session information is tracked under `~/.memanto/sessions/` on the server, and the CLI cached state allows the same active session to be picked up across runs.

### Explicit Session Management

For long-running processes, use this pattern:

1. Try the existing token.
2. On `401 Unauthorized`, activate a new session. (With auto-recreation enabled, an authorized caller usually gets a fresh session transparently instead — but keep this fallback for the cases it does not cover.)
3. Cache and continue — reading any `X-Session-Token` response header, since a renewed or recreated session invalidates the token you sent.

```python theme={null}
import httpx

def ensure_session(agent_id: str, token: str | None) -> str:
    if token and is_token_valid(token):
        return token
    resp = httpx.post(
        f"http://localhost:8000/api/v2/agents/{agent_id}/activate"
    )
    return resp.json()["session_token"]
```

## Session Timeouts & Limits

### Default Duration

* **Standard session**: configured server-side via `SESSION_DEFAULT_DURATION_HOURS` (typically 6 hours).
* **Auto-renewal**: Memanto extends sessions near expiry automatically when memory requests are made.
* **Auto-recreation**: an authorized caller presenting an already-expired token gets a fresh session instead of a `401` (`SESSION_AUTO_RECREATE_ENABLED`, default `True`).
* **Manual renewal**: re-activate the agent to obtain a fresh token.

### Handling Expiry

On `401 Unauthorized`, treat the token as expired:

```python theme={null}
import httpx

resp = httpx.post(url, headers=headers, json=body)
if resp.status_code == 401:
    new_token = httpx.post(
        f"http://localhost:8000/api/v2/agents/{agent_id}/activate"
    ).json()["session_token"]
    headers["X-Session-Token"] = new_token
    resp = httpx.post(url, headers=headers, json=body)
```

## Best Practices

### <Icon icon="check" /> DO

* Let Memanto auto-renew and auto-recreate sessions; only re-activate after a `401` that survives both
* Store session tokens in process memory, not on disk
* Deactivate sessions when a workflow finishes to capture a session summary

### <Icon icon="xmark" /> DON'T

* Create a new session for every request
* Send the Moorcheh API key from clients (Memanto reads it server-side)
* Reuse a session token across different agents

## Next Steps

* **Memory Operations**: [Memory Operations Guide](./memory-operations)
* **CLI Reference**: [Session commands](/cli/sessions/activate)
* **API Reference**: [Session endpoints](/api-reference/sessions/activate-agent)

***

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