Sessions & Multi-Agent

One gateway serves many people. If every direct message shares one session, Bob can ask for Alice's PIN and get it. Give each sender on each chat app its own session and the leak is gone.

Pick a DM scope and press Play the conversation. Alice tells the agent her PIN on WhatsApp. Bob asks for "that number". Then Alice asks again from Telegram. Count the sessions and watch who gets the PIN. Then we build the router piece by piece: keys, scopes, resets, limits, agents, bindings and sub-agents.

You need to have used a chat app and to know what a dictionary and a string are in Python. Lessons 1 to 6 help but are not required. We build the rest from zero.

Lesson 7 of 11 in Anatomy of an Agent Gateway. The running example is OpenClaw, a self-hosted gateway between chat apps and an AI agent. We checked every OpenClaw detail here against its documentation in November 2026.

Play one conversation

Illustrative toy: we made up the people, the PIN and the replies. The three scope names and what they do are OpenClaw's session.dmScope values; main is its default.

Chapter 0

One Agent, Many Conversations

See how one shared transcript lets one person read another, and split it into sessions

Your sister asks the agent for a recipe on WhatsApp. A coworker asks it to sum up a document in Slack. You test it from a terminal. Three people talk to one gateway process and one agent.

Suppose the gateway keeps one transcript, the list of every message and reply, and adds each new message to the end. Alice writes "my PIN is 4471". Later Bob, a stranger, asks "what was that number?" The agent reads the one transcript and answers 4471. That is a cross-user leak: one person's words reach another person.

How bad does it get as more people share? Call the number of people who write into one transcript n. Each pair of them can leak to each other. Call the number of such pairs L.

Say it aloud

L equals n times n minus one, divided by two.

L
L the number of pairs of people who can read each other's words through the shared transcript.
n
n the number of people who write into the same transcript.
In plain words

Each of the n people can leak to each of the other n minus 1. That counts every pair twice, so divide by 2. The result is L.

With numbers

With made-up numbers: n = 3 people gives L = 3 × 2 / 2 = 3 pairs. At n = 10 it is 45 pairs. Give each person a separate transcript and n = 1 everywhere, so L = 0.

Share one transcript

Each line is a pair who can read each other. Add people, then press Split into sessions.

3

The pair count is exact. Whether a leak happens depends on what people ask; the pairs are the paths it can take.

The fix is a session: one transcript plus its state, for one conversation only. When the agent answers a message, it reads that message's session and nothing else. Every inbound message then raises two questions.

  1. Which session does it belong to? Chapters 1 to 5.
  2. Which agent should answer it? Chapters 6 to 8.

The road

  1. Session keys: a string computed from where a message comes from.
  2. Direct messages: the dmScope setting, and the default that leaks.
  3. Where sessions live and when they reset: storage, timestamps, resets.
  4. Maintenance: delete stale sessions and cap how many stay.
  5. Compaction: keep one long conversation inside the model's window.
  6. Agents as personas: separate files, logins and sessions for each agent.
  7. Bindings: the most specific rule picks the agent.
  8. Sub-agents: slow work that runs beside the chat.
  9. The whole router, live: both answers for every message.
  10. Field guide: terms, numbers, a checklist and the core code.
Why can the gateway not keep one transcript and add every message to it?

Chapter 1

Session Keys: Route by Origin

Compute a session's name from where a message came from, never from what it says

A session key is the string that names a session. Two messages with the same key share a session and its memory. Two messages with different keys never see each other. So isolation comes down to one job: compute the right key.

The gateway computes the key from the message's origin. The origin is the agent, the chat app, the sender and the kind of chat. The text never matters. A key that changed with the text would scatter one conversation across many sessions.

Kind of chatRuleOpenClaw key shape
direct messageset by session.dmScope (Chapter 2); default: all DMs share oneagent:<agentId>:main
group or roomone session per groupagent:<agentId>:<channel>:group:<id>
threadthe group key plus the threadSlack, Discord: …:thread:<threadId>
cron runa fresh session for each runnew every time
webhookone session per hookisolated per hook

A cron run is a job the gateway starts on a timer, with no person on the other end. Each run gets a fresh session, so the 8:00 mail summary does not inherit yesterday's leftovers. The key always starts with the agent's id, so two agents never share a session.

Build a key from an origin

Pick a kind, an app and a sender, then press Send. The same origin lands in the same stack; a cron run always opens a new one.

DM scope is main here, OpenClaw's default. The main and group key shapes are from the OpenClaw docs. The cron key text is our sketch; the docs say only that each run is fresh.

A cron job sums up your unread mail every morning. How should its session be keyed?

Chapter 2

Direct Messages and the dmScope Setting

Choose how finely direct messages split into sessions, and see which choice stops the leak

A group is easy: the room is the conversation, so everyone in it shares one session. A cron run is easy: it is always fresh. The hard case is the direct message (DM), one person writing privately to the agent.

OpenClaw sets this with one config value, session.dmScope. Its default is main: every DM from anyone shares the agent's main session. That suits one owner on one phone. With two people it is the PIN leak from Chapter 0.

dmScopeKey fromEffect
main (default)nothingall DMs share one session
per-peersenderone session per person, across apps
per-channel-peerapp + senderone session per person per app (recommended)
per-account-channel-peeraccount + app + senderalso splits two accounts on one app

How many DM sessions does each setting make? Apply the key rule to every message and count the different keys. Call the set of messages M, one message m, and the key rule for the chosen scope k. Call the session count S.

Say it aloud

S equals the count of distinct values of k of m, for every m in M.

S
S the number of DM sessions the gateway creates.
#{ }
the count of distinct how many different values sit inside the braces; repeats count once.
k(m)
k of m the session key the chosen scope gives message m.
m ∈ M
m in M each message m from the set M of direct messages.
In plain words

Run the key rule k on every message m in M. Cross out repeats. The number of keys left is S.

With numbers

With made-up numbers: 6 DMs from Alice, Bob and Carol on WhatsApp and Telegram. Bob writes to two WhatsApp accounts. main gives S = 1, per-peer S = 3, per-channel-peer S = 4, per-account-channel-peer S = 5. Only S = 1 puts two people in one session.

Turn the dmScope dial

Six DMs on the left, sessions on the right. Choose a scope. A red stack holds two people's words. Turn on the group to see that dmScope leaves it alone.

Illustrative messages. The four scopes and their meaning are from the OpenClaw session docs.

Why per-channel-peer, and not per-peer? A person on WhatsApp and the "same" name on Telegram are two ids. The gateway cannot prove they are one human. Keeping them apart is the safe choice. If you know they are one person, OpenClaw can link identities on purpose.

Changing dmScope never touches groups. Their scope is a separate setting, session.groupScope, whose default per-group keeps each room apart.

You set dmScope to per-channel-peer. What happens to a busy Slack group that many teammates share?

Chapter 3

Where Sessions Live and When They Reset

Store each agent's sessions on disk, stamp them with three times, and start fresh on a rule

The gateway restarts after a crash, a reboot or an update. Your conversations must survive that, so every session lives on disk. Each agent has its own store, so two agents never share a file.

In current OpenClaw, session rows and transcripts live in one SQLite database per agent: ~/.openclaw/agents/<agentId>/agent/openclaw-agent.sqlite. Older versions kept a sessions.json index and one .jsonl transcript file per session, under sessions/. That folder now holds archived transcripts. The split is the same idea in both: a small row to list sessions, a long transcript to replay one.

Each session row carries three timestamps.

FieldMeaningUsed for
sessionStartedAtwhen the current session beganthe daily reset
lastInteractionAtthe last message from a person or channelthe idle reset
updatedAtthe last write to the rowlisting and maintenance

A reset starts a new session, with a new id and an empty transcript, for the same key. OpenClaw's default is no automatic reset. You can turn on two rules, and /new or /reset in the chat always works. Call the idle limit I, the time now tnow and the last interaction tlast. Call the first daily reset hour after the session started b.

Say it aloud

Reset if t-now minus t-last is greater than I, or if t-now is at or after b.

reset
reset the next message opens a new session for the same key.
tnow
t-now the time the new message arrives.
tlast
t-last lastInteractionAt, the last message from a person. Heartbeats, cron and exec events do not move it.
I
I the idle limit, session.reset.idleMinutes.
or
or either rule is enough; the one that expires first wins.
b
b the first daily reset hour after sessionStartedAt; the hour is session.reset.atHour, default 4, on the gateway host's clock.
In plain words

Subtract t-last from t-now. If the gap is longer than I, reset. Also reset if t-now has passed b, the first reset hour since the session began.

With numbers

With made-up numbers: I = 120 minutes, the session began at 21:00, t-last = 23:30, t-now = 07:00. The gap is 450 minutes, more than 120, so reset; b = 04:00 has also passed. At t-now = 10:00 after t-last = 09:10 the gap is 50 minutes and b is tomorrow, so no reset.

Reset a session on a timeline

Dots are messages over 30 hours. Each colour band is one session. Set the idle limit and turn the daily reset on or off.

off

Illustrative message times. The rules, the default hour 4 and "whichever expires first" are from the OpenClaw session docs.

Idle reset is 60 minutes. The last message from Alice was 50 minutes ago, and a heartbeat ran 5 minutes ago. She writes now. Does the session reset?

Chapter 4

Maintenance: Keep the Store Bounded

Delete sessions nobody touched for a month, then cap how many rows remain

Every cron run and every new sender adds a session. Resets add more. With no limit, the store grows forever. So the gateway runs maintenance: a sweep that removes old session rows.

OpenClaw's session.maintenance has two limits. pruneAfter, default 30 days, removes sessions that have been idle that long. maxEntries, default 5,000, caps how many unarchived session rows stay. In enforce mode, the default, it applies them. In warn mode it only reports.

Call the number of rows before the sweep N, the rows touched within pruneAfter Nfresh, the cap E, and the rows left Nkept.

Say it aloud

N-kept equals the minimum of N-fresh and E.

Nkept
N-kept the session rows left after the sweep.
min( , )
the minimum of the smaller of the two numbers.
Nfresh
N-fresh the rows touched within pruneAfter, 30 days by default.
E
E the cap, maxEntries, 5,000 rows by default.
In plain words

Drop every row older than pruneAfter; N-fresh rows remain. If N-fresh is more than E, remove rows until E remain. The count left is N-kept.

With numbers

With made-up numbers: N = 7,000 rows and 1,500 are older than 30 days, so N-fresh = 5,500. N-kept = min(5,500, 5,000) = 5,000. The cap removes 500 more rows.

Run the maintenance sweep

Each dot is 100 session rows, placed by days since last use. Move the two limits. Grey rings are rows the sweep removes. Try warn.

30
5,000

Illustrative ages. The two limits, their defaults and the modes are OpenClaw's. Which rows the cap removes first is our choice here (the oldest); the docs state the cap, not the order.

After pruning, 4,200 session rows remain and maxEntries is 5,000. How many rows does the cap remove?

Chapter 5

Compaction: Keep a Long Chat in the Window

Summarize the old turns of one conversation before they overflow the model's context window

Maintenance removes whole sessions. It cannot help a conversation that is alive and long. The model reads the session's turns as its prompt. The prompt has a ceiling: the context window, the most tokens the model can read at once.

Compaction replaces the oldest turns with a short summary and keeps the recent turns as they are. The model sees the summary plus the recent turns. The full transcript stays on disk, and OpenClaw saves the summary into it as one more entry.

When does it run? Call the context window W and the tokens in the prompt T. Call a reserve of tokens kept free for the compaction work R, and the threshold Tc.

Say it aloud

T-c equals the minimum of zero point seven five W, and W minus R.

Tc
T-c the token count at which compaction starts. It runs once the prompt's tokens T reach it.
min( , )
the minimum of the smaller of the two numbers, so the stricter limit wins.
W
W the model's context window, in tokens.
R
R the compaction reserve: tokens kept free for the work of compacting.
In plain words

Take three quarters of W. Take W minus R. The smaller one is T-c. When the prompt's tokens T reach T-c, summarize the old turns.

With numbers

With made-up numbers: W = 200,000 and R = 40,000. 0.75 W = 150,000 and W − R = 160,000, so T-c = 150,000. For a small model, W = 32,000 and R = 10,000: 24,000 against 22,000, so T-c = 22,000 and the reserve decides.

Fill the window, then compact

Each block is a turn. Press Add turns until the bar reaches the threshold line. Change the window and the reserve to move the line.

40k

Illustrative turn sizes (6% of the window each) and summary size. The threshold rule is from the OpenClaw compaction docs; the reserve value is ours.

Compaction also runs when the model replies with a context overflow error, and then the turn retries. Type /compact to force it, with an optional topic to focus the summary. OpenClaw's default safeguard mode audits the summary's quality, and its default identifier policy asks the summary to keep exact ids.

A session is active and nearing the context window. What does the gateway do?

Chapter 6

Agents as Separate Personas

Give each agent its own files, logins and sessions, so one cannot reach another's data

One gateway can host several agents. A terse coding agent and a warm family helper can run in the same daemon. In OpenClaw each agent is a full persona with an id and three things of its own.

PartWhat it holdsDefault path
workspacefiles, AGENTS.md, SOUL.md, USER.md, notes, persona rulesset per agent
agentDirauth profiles, model registry, per-agent config~/.openclaw/agents/<agentId>/agent
session storechat history and routing state<agentDir>/openclaw-agent.sqlite

You declare agents under agents.entries, keyed by agent id, each with a workspace. Older configs used agents.list; openclaw doctor --fix migrates them. Each agent can also have its own tool limits and sandbox (Lesson 10).

Now the first part of every session key makes sense. The key starts agent:<agentId>. If Mom writes to the family agent and to the work agent, she gets two keys, two sessions and two memories.

Ask the family persona for the work key

Choose how to build the two personas, then press Ask. Someone in the family chat asks for the work API key.

Illustrative request. The parts each agent owns are from the OpenClaw multi-agent docs.

Two system prompts on one agent look like two assistants. They still share one login store, one workspace and one set of sessions. A trick played on one persona reaches the other's secrets. Separate agents shrink the blast radius, the damage one mistake can do.

What makes two OpenClaw agents separate personas, and not two prompts on one agent?

Chapter 7

Bindings: the Most Specific Rule Wins

Walk a fixed ladder of rules from one person down to a whole channel, and stop at the first match

A message arrives. Which agent answers it? The gateway checks its bindings. A binding is a rule that maps part of a message's origin to an agent. For example: "Mom goes to the family agent".

Rules overlap. Mom posting in the eng team matches both. OpenClaw settles it with a fixed order of nine tiers, from most specific to least.

  1. peer: this exact sender or chat.
  2. parent peer: a thread inherits its parent's agent.
  3. peer wildcard: any peer of a kind.
  4. guild + roles: a Discord server, members with given roles.
  5. guild: a whole Discord server.
  6. team: a Slack workspace.
  7. account: one connected account of a channel.
  8. channel: every account of a channel (accountId: "*").
  9. fallback owner: used when nothing above matches.

Number the tiers 1 to 9. For a message m, write matchi(m) for "some binding in tier i matches m". The winning tier is i*.

Say it aloud

i-star equals the smallest i such that match-i of m is true.

i*
i-star the tier that decides the agent.
min { }
the smallest the lowest tier number in the set, so the most specific tier wins.
i
i a tier number, 1 (peer) to 9 (fallback owner).
matchi(m)
match-i of m true when a binding in tier i fits message m. A binding with several fields matches only if all of them fit.
In plain words

Start at tier 1. Ask whether any binding in that tier matches m. If yes, stop: i-star is that tier. If no, go down one tier. If two bindings match in tier i-star, the first one in the config wins.

With numbers

With made-up numbers: Mom posts in the eng team. She matches a peer binding (tier 1) and a team binding (tier 6). i* = min{1, 6} = 1, so the family agent answers.

Walk the routing ladder

Choose a message and press Route. The marker walks down the tiers and stops at the first match. Switch bindings off to see who wins next.

Illustrative bindings and agents; the fallback owner here is the agent main. The tier order and the tie rule are from the OpenClaw channel routing docs.

Why a fixed order? A peer binding is a choice you made for one person. A broad team rule must never override it by chance. With a fixed ladder the same message reaches the same agent every time, and you can say why.

Two details catch people. A binding that omits accountId matches only the channel's default account. If nothing matches and there are several agents with no fallback owner, OpenClaw does not dispatch the message.

A message matches a peer binding and a team binding. Which agent answers?

Chapter 8

Sub-agents Run Beside the Chat

Spawn slow work as its own session on its own lane, so the conversation never waits for it

You ask the agent to read a long report. It takes minutes. Meanwhile you type "are you there?" Who answers?

Lesson 6 showed that the gateway runs one turn at a time in each session. If the agent reads the report inside your session, your next message waits behind it. A sub-agent fixes this. It is a background agent run that the agent spawns, with its own session and its own context. OpenClaw spawns it with the sessions_spawn tool and gives it the key agent:<agentId>:subagent:<uuid>. When it finishes, it announces the result back to the session that asked.

Spawn the crawl, then say hi

Choose where the crawl runs and press Run. At second 5 you send "hi". Watch how long the reply takes.

Illustrative times: a 40 s crawl and a 3 s reply. One turn at a time per session, the sub-agent key and the announce step are from the OpenClaw docs.

A lane is a queue with its own limit on parallel runs. Inbound chat turns run on the main lane. Sub-agents run on a lane named for the session that spawned them, subagent:<session>, with agents.defaults.subagents.maxConcurrent slots, default 8 per session. How wide is the main lane? Call the number of CPU threads the host offers c, and the main lane's limit Cmain.

Say it aloud

C-main equals the maximum of eight and four c.

Cmain
C-main how many inbound turns the main lane may run at once, across all sessions.
max( , )
the maximum of the larger of the two numbers, so the lane never drops below 8.
c
c the CPU parallelism the host reports.
In plain words

Multiply c by 4. If that is under 8, use 8. The result is C-main. agents.defaults.maxConcurrent can cap it lower.

With numbers

A host with c = 4 gives C-main = max(8, 16) = 16 turns at once. A host with c = 1 gives max(8, 4) = 8. Each session still runs one turn at a time inside that limit.

An agent spawns a sub-agent to crawl a long document while you keep chatting. Why does your chat not freeze?

Chapter 9

The Whole Router, Live

Send messages through both routing questions at once: which agent, then which session

Every inbound message gets two answers. The bindings pick the agent. Then the origin and the scope settings pick the session key, which starts with that agent's id. The order matters: the agent comes first because the key contains it.

Route every message

Pick a sender and press Send. The card shows the winning tier, the agent and the key. Two different people on one key turn red.

Illustrative people and bindings; the fallback owner is main. The main and group key shapes are OpenClaw's; the per-channel-peer DM key text is our sketch of its parts.

Try this order. Send both strangers under main: one key, two people, red. Switch to per-channel-peer and send them again: two keys. Turn off the peer binding and send Mom: she falls to the fallback owner and joins the strangers' agent.

Under dmScope main, two strangers DM and no binding matches either. What happens?

Chapter 10

Field Guide

Keep the terms, the defaults, a checklist and the core code in one place

A session key comes from the origin. dmScope decides how DMs split, and its default shares them. Resets, maintenance and compaction keep state bounded. Each agent owns its files, logins and sessions. Bindings pick the agent, most specific tier first. Sub-agents run in their own sessions beside the chat.

TermMeaningOpenClaw value
session keythe name of one conversationagent:<agentId>:main, agent:<agentId>:<channel>:group:<id>
dmScopehow DMs splitmain (default), per-peer, per-channel-peer (recommended), per-account-channel-peer
groupScopehow groups splitper-group (default)
session storerows and transcripts~/.openclaw/agents/<agentId>/agent/openclaw-agent.sqlite
resetnew session id for a keydefault none; daily at atHour 4; idle idleMinutes; /new, /reset
maintenanceremoves old session rowsenforce; pruneAfter 30d; maxEntries 5,000
compactionsummary of old turnsat min(75% of W, W − reserve); /compact
agentan isolated personaagents.entries: workspace, agentDir, session store
bindingorigin to agent rule9 tiers, peer first, fallback owner last; ties by config order
sub-agentbackground agent runsessions_spawn; key agent:<agentId>:subagent:<uuid>; 8 per session
main laneinbound turns at oncemax(8, 4 × CPU parallelism)

Checklist for many users on one gateway

The core, in code

A toy router for both questions. It is a sketch for reading, not OpenClaw's code.

pythonimport uuid

TIERS = ["peer", "parentPeer", "peerWildcard", "guildRoles",
         "guild", "team", "account", "channel"]

def pick_agent(m, bindings, fallback):           # question 2 first: which agent?
    for tier in TIERS:                              # most specific tier first
        for b in bindings:                          # config order breaks ties
            if b["tier"] == tier and b["match"](m):
                return b["agent"]
    return fallback                                 # tier 9: the fallback owner

def session_key(agent, m, dm_scope):             # question 1: which session?
    a = f"agent:{agent}"                            # every key starts with the agent
    if m["kind"] == "group": return f"{a}:{m['channel']}:group:{m['group']}"
    if m["kind"] == "cron":  return f"{a}:cron:{uuid.uuid4()}"    # fresh each run
    if dm_scope == "per-peer":         return f"{a}:direct:{m['peer']}"
    if dm_scope == "per-channel-peer": return f"{a}:{m['channel']}:direct:{m['peer']}"
    return f"{a}:main"                          # the default: every DM shares

def route(m, cfg):
    agent = pick_agent(m, cfg["bindings"], cfg["fallback"])
    return agent, session_key(agent, m, cfg["dmScope"])

Where each thread continues

The takeaway. Pick the agent by the most specific binding, key the session by origin with the agent first, isolate DMs per app and sender, bound the store, compact long chats, and push slow work into sub-agents.
In one sentence, what does this lesson add to the gateway?

Now press Present or Teach and explain it from memory. Cover the leak, keys from the origin, the four DM scopes, resets, maintenance against compaction, what an agent owns, the nine tiers and sub-agents. Then go back to the hero and play the conversation under each scope.

Anatomy of an Agent Gateway, Lesson 7: Sessions and Multi-Agent
OpenClaw docs · Next: agent memory · Back to Gleams