> ## 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. If the token has fully expired (`401`), call `/activate` again to obtain a new one.

## 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.
3. Cache and continue.

```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.
* **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 sessions; only re-activate after a hard `401`
* 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!
