Session Management
WednesdayAI treats one direct-chat session per agent as primary. Direct chats collapse toagent:<agentId>:<mainKey> (default main), while group/channel chats get their own keys. session.mainKey is honored.
Use session.dmScope to control how direct messages are grouped:
main(default): all DMs share the main session for continuity.per-peer: isolate by sender id across channels.per-channel-peer: isolate by channel + sender (recommended for multi-user inboxes).per-account-channel-peer: isolate by account + channel + sender (recommended for multi-account inboxes). Usesession.identityLinksto map provider-prefixed peer ids to a canonical identity so the same person shares a DM session across channels when usingper-peer,per-channel-peer, orper-account-channel-peer. Gateway clients (web client, Control UI) send their turns asdevice:<deviceId>; link each account to the person withwednesdayai identity link <name> <value>(or the self-service/linkcode) so their web chats resolve to the same identity. See Identities.
Secure DM mode (recommended for multi-user setups)
Security Warning: If your agent can receive DMs from multiple people, you should strongly consider enabling secure DM mode. Without it, all users share the same conversation context, which can leak private information between users.Example of the problem with default settings:
- Alice (
<SENDER_A>) messages your agent about a private topic (for example, a medical appointment) - Bob (
<SENDER_B>) messages your agent asking “What were we talking about?” - Because both DMs share the same session, the model may answer Bob using Alice’s prior context.
dmScope to isolate sessions per user:
- You have pairing approvals for more than one sender
- You use a DM allowlist with multiple entries
- You set
dmPolicy: "open" - Multiple phone numbers or accounts can message your agent
- Default is
dmScope: "main"for continuity (all DMs share the main session). This is fine for single-user setups. - Local CLI onboarding writes
session.dmScope: "per-channel-peer"by default when unset (existing explicit values are preserved). - For multi-account inboxes on the same channel, prefer
per-account-channel-peer. - If the same person contacts you on multiple channels, link all of their accounts to one identity (
wednesdayai identity link <name> <value>; see Identities) so their DM sessions collapse into that canonical identity. - You can verify your DM settings with
wednesdayai security audit(see security). - Session isolation and Workspace Lanes solve different problems.
dmScopeseparates conversation history; workspace lanes separate user-specific workspace files for multi-user-capable personas.
Gateway is the source of truth
All session state is owned by the gateway. UI clients (macOS app, WebChat, etc.) must query the gateway for session lists and token counts instead of reading local files.- In remote mode, the session store you care about lives on the remote gateway host, not your Mac.
- Token counts shown in UIs come from the gateway’s store fields (
inputTokens,outputTokens,totalTokens,contextTokens). Clients do not read stored transcripts to “fix up” totals.
Where state lives
- On the gateway host:
- Session database:
<state-dir>/sessions.db(SQLite by default; override withsession.storage.backend: "postgres"plussession.storage.databaseUrl). - Per-agent store path:
~/.openclaw/agents/<agentId>/sessions/sessions.json. Under SQL session storage this path is an identity for the agent’s index and the place the one-time import looks for legacy JSON session files; it is not a file the gateway writes or reads afterwards.
- Session database:
- The session index and every conversation entry live in the database; there are no transcript
files and no
sessions.jsonshadow copy while the gateway runs. - Ownership of the database is exclusive: the running gateway holds it (SQLite:
<sessions.db>.owner.lockplus an<sessions.db>.owner.jsonholder sidecar; Postgres: an advisory lock plus actx_storage_ownerrow). A CLI command that needs session data goes over the gateway when one runs, or takes ownership itself when none does. - The session index is a map
sessionKey -> { sessionId, updatedAt, ... }in the database. Deleting an entry tombstones it; it is recreated on demand. - Group entries may include
displayName,channel,subject,room, andspaceto label sessions in UIs. - Session entries include
originmetadata (label + routing hints) so UIs can explain where a session came from. - WednesdayAI does not read legacy Pi/Tau session folders.
Maintenance
WednesdayAI applies session maintenance to bound the session index over time. Conversation history is append-only and never deleted: maintenance (warn/enforce, pruneAfter,
maxEntries) only retires idle or over-cap sessions from the session index (tombstones, based on
the index entry’s last update); the conversation rows stay and remain readable. There is no
automatic space reclamation (ADR 0098, dev-docs/adr/0098-conversation-history-is-never-deleted.md).
Defaults
session.maintenance.mode:warnsession.maintenance.pruneAfter:30dsession.maintenance.maxEntries:500
rotateBytes, maxDiskBytes, highWaterBytes, resetArchiveRetention)
are retired: they applied to JSONL transcript files, which SQL session storage never writes. Configs
that still set them are migrated automatically on load (see
Upgrading from JSON session files).
How it works
Maintenance only ever touches the session index, and never at startup: gateway activation runs only the startup backfill chains (user ids, session identity / actor columns, token counts, usage columns) — no index retirement, even inenforce mode. Index upkeep happens when the index is
written:
- Index upkeep on writes. Ordinary session-index writes (and
wednesdayai sessions cleanup) maintain the index record itself: inenforcemode they drop index rows whoseupdatedAtis older thanpruneAfterand cap the index atmaxEntriesrows (a tombstone per dropped row); the session being written is never dropped. Inwarnmode they only warn when the active session would be evicted. Because capping rides on writes, restarting with a lowermaxEntriesapplies it on the next index write (or manual cleanup), not at startup.
updatedAt, so it
no longer qualifies when maintenance runs. Reset (/new, /reset) and sessions.delete also
only tombstone the index row; the conversation rows stay and remain readable (ADR 0098).
Performance caveat for large stores
Large stores are common in high-volume setups. Retirement rides on index writes, so the first write after switchingmode: "enforce" on pays the whole batch: on a very large store that write
can take a while.
What increases cost most:
- long
pruneAfterwindows that keep many index entries eligible for retirement - very high
session.maintenance.maxEntriesvalues
- start in
mode: "warn", then switch to"enforce"once the thresholds look right - set both time and count limits (
pruneAfter+maxEntries), not just one - run
wednesdayai sessions cleanup --dry-run --jsonafter config changes to verify projected impact before enforcing - to check whether a busy session would be evicted, pass
--active-key <key>to a warn-modewednesdayai sessions cleanupand read the warning
Customize examples
Use a conservative enforce policy:Plugin correlation and privacy
Plugins can receive resolved runtime identity and turn correlation fields so they can log, dedupe, and run background analysis without parsing session keys or reading raw identity configuration. For operators, the important boundary is:session.identityLinksremains configuration used by core identity resolution. Plugin contexts expose resolved fields such ascanonicalIdentityandsenderIsOwner; they do not expose rawidentityLinks. Plugins additionally seeidentitySource("sender"|"parent-session"|"job-config") describing how the identity was resolved — rawidentityLinksare still never exposed.channelConversationIdidentifies the transport conversation or thread. Legacy plugin fields namedconversationIdrefer to this channel identity.providerConversationIdis an opaque provider/cache correlation id derived by WednesdayAI for model calls. It is not a session storage column and should be stored only as an opaque value.turn.turnIdidentifies one user turn and is the same string value asrunIdin the v1 plugin contract.sessionIdandsessionKeymay be absent during very earlymessage_receivedhooks. WednesdayAI omits them when no real session exists instead of fabricating a session value.
turnId. Dedupe append fan-out with the turn id plus the entry id, cursor entry id, or raw entry hash.
This feature does not make untrusted plugins safe. Plugins still run in-process with gateway trust, but the public SDK now gives them resolved identity and opaque correlation fields instead of requiring them to read private config or reverse-engineer session key formats.
Session storage
By default, the session index and every conversation entry are stored in a local SQLite database at<state-dir>/sessions.db (normally ~/.openclaw/sessions.db) on the gateway host. For shared
Postgres storage with an optional Redis hot cache, configure session.storage. See the
session.storage section in Gateway configuration.
SQL session storage is the only session storage: there is no JSONL backend and no file fallback.
The per-agent sessions.json paths survive only as (a) the identity of each agent’s index and
(b) import sources for the one-time legacy upgrade described in
Upgrading from JSON session files.
Backends
sqlite(default): entries are read and written through the SQLitectx_session_entriestable via a worker thread; the write-ahead log plus DB transactions are the durability story.postgres: entries are read and written through the Postgresctx_session_entriestable.cache: "redis"adds a write-through hot cache that is never authoritative — the database always wins.
CREATE TABLE/INDEX IF NOT EXISTS, idempotent column adds); no manual migrations are required.
If Postgres is unreachable at boot, the gateway exits with the probe cause instead of serving a
degraded view; the service manager restarts it. The wait is bounded by
session.storage.recovery.startupProbeTimeoutMs (default 600s).
Planner statistics (#2239). A fresh (or freshly-migrated) Postgres store has empty planner
statistics until autoanalyze kicks in; on a large import the planner then mis-costs session-index
reads — the observed symptom is 100% DB CPU and multi-second session lists. The one-line
mitigation on an affected host is ANALYZE ctx_sessions;. Stores now self-ANALYZE: after schema
creation on a fresh database, after a legacy-import sweep or pre-publish index import that
ingested entries, and (inbox store) after schema open and each bulk-ingest pass, debounced.
SQLite stores run the cheap PRAGMA optimize at open and a full ANALYZE after bulk loads.
An owner open that hits its startup deadline, or a shutdown, while the post-import Postgres
ANALYZE runs cancels that statement on the server (pg_cancel_backend) instead of waiting
for it. The gateway logs post-import ANALYZE failed with aborted: true, and statistics
catch up at the next import that ingests entries or at autoanalyze.
Single owner
The running gateway is the single owner of the session database, enforced by a storage-owner lock keyed to the database (SQLite:<sessions.db>.owner.lock with an <sessions.db>.owner.json
holder sidecar; Postgres: pg_try_advisory_lock plus a ctx_storage_owner row).
- While a gateway runs, every CLI storage operation — reads included — goes over the gateway RPC
and never opens the database. A
gateway.mode: "remote"config always routes to the remote gateway the same way. - With no gateway, a CLI command takes ownership as
clifor the duration of the command: index import on open, on-access transcript import, no automatic retention, no background sweep. - A second owner is refused with the holder’s host and pid.
wednesdayai agent --localrefuses while a gateway owns the database. Onlywednesdayai session-storage restoreneeds the gateway stopped.
Append-only history
Conversation entries are append-only: no code path updates or deletes stored content. Compaction appends a compaction entry and keeps the pre-compaction entries. Derived views (tool-output trimming, history limits, thinking stripping) are computed per request and never persisted. Maintenance never deletes conversation rows — it only retires session index entries (see Maintenance).Sub-agent and announce output
Sub-agent runs (sessions_spawn) and their announce step read the same database the run wrote to,
so sub-agent output renders correctly.
Upgrading from JSON session files
Installs that keep history in legacysessions.json / *.jsonl files upgrade online, with no
operator step. The first gateway start after upgrading:
- Auto-migrates retired config keys on load (
session.storage.backend: "fs-jsonl",session.storage.mode,session.storage.fallbackToJsonlOnError, obsoletesession.storage.recovery.*and file-onlysession.maintenance.*keys, prune-onlysession.storage.consumerClaims.progressWindowMsandmaxRetentionBackstopMs, learning-corefs-jsonlbackend) and logs each change. - Takes storage ownership and, before the gateway publishes storage, imports every agent’s
sessions.jsonindex. Database rows and tombstones always win: a legacy index entry never changes the current session for a key that already exists or was deleted in the database. This first start also writes one pre-import snapshot of the SQLite database to<state-dir>/backups/sessions-pre-legacy-import-<timestamp>.db; because the snapshot runs before storage is published, that first startup takes longer once. - Publishes storage and starts the gateway. From then on: a legacy session’s transcript is
imported the first time that session is accessed, and a throttled background sweep imports the
rest newest-first, archiving each source under
<state-dir>/legacy-session-archive/<agentId>/(files0600, dirs0700).
wednesdayai session-storage import retries). If an on-access import fails, the turn still proceeds
— availability over completeness — and the failure stays visible in
wednesdayai session-storage status and wednesdayai doctor until a retry succeeds. Containment
compares symlink-resolved paths, so a state dir reached through a symlink (for example the macOS
/var -> /private/var link) imports the same transcripts as a plain path.
Only the importer moves legacy source transcripts. Session reset, delete, and corruption
recovery leave those source files untouched so an in-flight or failed import cannot lose its
only copy. One-shot slug/journal generation, voice consult, plugin analysis, and wake-gate
helpers run without persisting extra session history.
Legacy unqualified session keys under a non-default agent keep their stored identity.
An ID-only agent request cannot target those sessions safely: it is rejected with
INVALID_REQUEST naming the stored key instead of guessing an alias or choosing another agent.
Use the explicit session key with the owning agent, not --session-id alone. This restriction
does not discard the imported history.
Status and manual import
status reports the import state (none | pending | running | completed | error), how many
sources are done, and the pre-import snapshot path when one exists.
Archives
- Import sources are archived, not deleted:
<state-dir>/legacy-session-archive/<agentId>/. Reset, deleted and replayed transcript archives,session-runs.jsonl, and oldrecovery/**manifests are archived without import and kept — the archive is their only copy. - Purge rule: a gateway sweep deletes an archived copy after 30 days only when its source was fully imported with zero rejected lines. Archive-only sources, failed sources, and sources with rejected lines are kept indefinitely.
Backups and rollback
wednesdayai session-storage backupwrites an online SQLite backup (VACUUM INTOon a separate read-only connection, so appends never wait); default output<state-dir>/backups/sessions-<timestamp>.db(0600). Under a running gateway the file is written under<state-dir>/backups/. The backup connection waits up to 5 seconds for a lock, so a backup no longer fails immediately withdatabase is lockedwhen it races another backup or the pre-import snapshot on a cold WAL database.wednesdayai session-storage restore <file>is offline: stop the gateway, then the CLI replacessessions.db(the previous file is kept assessions.db.pre-restore-<timestamp>).- Rollback means restoring a backup with a SQL-capable build of WednesdayAI. There is no downgrade to JSONL serving.
Data retention after upgrade
History imported from JSONL follows the same rules as native history: append-only and never deleted.session.maintenance (session.maintenance.mode: "enforce" plus
pruneAfter/maxEntries) only retires idle or over-cap sessions from the session index
(tombstones); the conversation rows stay readable. Set "enforce" only after
previewing with wednesdayai sessions cleanup --dry-run.
Session pruning
WednesdayAI trims old tool results from the in-memory context right before LLM calls by default. This never rewrites stored history. See /concepts/session-pruning.Pre-compaction memory flush
When a session nears auto-compaction, WednesdayAI can run a silent memory flush turn that reminds the model to write durable notes to disk. This only runs when the workspace is writable. See Memory and Compaction.Mapping transports → session keys
- Direct chats follow
session.dmScope(defaultmain).main:agent:<agentId>:<mainKey>(continuity across devices/channels).- Multiple phone numbers and channels can map to the same agent main key; they act as transports into one conversation.
per-peer:agent:<agentId>:direct:<peerId>.per-channel-peer:agent:<agentId>:<channel>:direct:<peerId>.per-account-channel-peer:agent:<agentId>:<channel>:<accountId>:direct:<peerId>(accountId defaults todefault).- If
session.identityLinksmatches a provider-prefixed peer id (for exampletelegram:123), the canonical key replaces<peerId>so the same person shares a session across channels. - An inbound, unlinked sender whose raw peer id equals an
identityLinkscanonical key is contained instead of merged: it gets its own bucket with araw~peer prefix (for exampleagent:main:direct:raw~alice). Theraw~prefix is reserved — canonical keys starting withraw~are rejected at config load. Sessions merged before this containment landed stay merged. - Because a contained
raw~bucket is a distinct session key, peer-specificsendPolicyrules (and any other per-key config) do not carry over automatically: a rule matchingagent:<agentId>:direct:<canonicalKey>does not matchagent:<agentId>:direct:raw~<peerId>or vice versa. Add separatekeyPrefix/rawKeyPrefixrules for contained senders, and keep canonical-identity rules separate.
- Group chats isolate state:
agent:<agentId>:<channel>:group:<id>(rooms/channels useagent:<agentId>:<channel>:channel:<id>).- Telegram forum topics append
:topic:<threadId>to the group id for isolation. - Legacy
group:<id>keys are still recognized for migration.
- Telegram forum topics append
- Inbound contexts may still use
group:<id>; the channel is inferred fromProviderand normalized to the canonicalagent:<agentId>:<channel>:group:<id>form. - Other sources:
- Isolated cron assistant-task jobs:
cron:<job.id> - Webhooks:
hook:<uuid>(unless explicitly set by the hook) - Node runs:
node-<nodeId>
- Isolated cron assistant-task jobs:
Lifecycle
- Reset policy: sessions are reused until they expire, and expiry is evaluated on the next inbound message.
- Daily reset: defaults to 4:00 AM local time on the gateway host. A session is stale once its last update is earlier than the most recent daily reset time.
- Idle reset (optional):
idleMinutesadds a sliding idle window. When both daily and idle resets are configured, whichever expires first forces a new session. - Legacy idle-only: if you set
session.idleMinuteswithout anysession.reset/resetByTypeconfig, WednesdayAI stays in idle-only mode for backward compatibility. - Per-type overrides (optional):
resetByTypelets you override the policy fordirect,group, andthreadsessions (thread = Slack/Discord threads, Telegram topics, Matrix threads when provided by the connector). - Per-channel overrides (optional):
resetByChanneloverrides the reset policy for a channel (applies to all session types for that channel and takes precedence overreset/resetByType). - Reset triggers: exact
/newor/reset(plus any extras inresetTriggers) start a fresh session id and pass the remainder of the message through./new <model>accepts a model alias,provider/model, or provider name (fuzzy match) to set the new session model. If/newor/resetis sent alone, WednesdayAI runs a short “hello” greeting turn to confirm the reset. - Manual reset: delete specific keys from the store; the next message recreates them. The deleted session’s conversation rows stay in the database forever — maintenance only retires index entries and never deletes conversation rows (see Maintenance).
- Isolated cron assistant-task jobs always mint a fresh
sessionIdper run (no idle reuse). Main-session cron jobs enqueue anagent.turn(kindcron) on the existing main session, except that main-session jobs withpayload.kind === "wakeGate"route throughrequestNudge(akind=nudgeturn) instead. They do not create acron:<job.id>chat session and do not run through the heartbeat tick.
Delivery routes go stale
A session entry stores the last external delivery route (lastChannel,
lastAccountId, and the peer id) so follow-up replies can be sent back without
re-resolving the target. That route is not validated when it is stored, so it can
outlive the account it points at: a bot account removed from
channels.<channel>.accounts leaves the session entry behind as a dead route.
Every stored-route consumer treats a dead route as no route rather than
falling back to the channel’s default account. A route counts as dead when it
names a non-default account and the channel lists a non-empty set of configured
accounts that doesn’t include it; routes on the default account, and channels
that don’t list accounts, are left alone:
- Heartbeat and system-event output (cron
--system-event, ACP nudges) is appended to the session chat instead (see Heartbeat for the fallback reason shown inwednesdayai status --deep). - Sub-agent completion announces run inside the requester session with no external send, and session notices are queued as a system event (see Sub-agents).
chat.sendreplies from the web clients stay in the session chat and are not mirrored to the dead route.
Send policy (optional)
Block delivery for specific session types without listing individual ids.channel and chatType match the session’s stored identity (the channel and peer kind recorded
when the conversation arrived, or the session’s recorded channel), never the session key text.
keyPrefix and rawKeyPrefix match the key itself.
/send on→ allow for this session/send off→ deny for this session/send inherit→ clear override and use config rules Send these as standalone messages so they register.
Configuration (optional rename example)
Inspecting
wednesdayai status— shows store path and recent sessions.wednesdayai sessions --json— dumps every entry (filter with--active <minutes>).wednesdayai gateway call sessions.list --params '{}'— fetch sessions from the running gateway (use--url/--tokenfor remote gateway access).- Send
/statusas a standalone message in chat to see whether the agent is reachable, how much of the session context is used, current thinking/verbose toggles, and when your WhatsApp web creds were last refreshed (helps spot relink needs). - Send
/context listor/context detailto see what’s in the system prompt and injected workspace files (and the biggest context contributors). - Send
/stop(or standalone abort phrases likestop,stop action,stop run,stop openclaw) to abort the current run, clear queued followups for that session, and stop any sub-agent runs spawned from it (the reply includes the stopped count). - Send
/compact(optional instructions) as a standalone message to summarize older context and free up window space. See /concepts/compaction. - To review full turns, page the transcript with the gateway
sessions.exportmethod (the macOS app’s “Open session log” uses it), or usewednesdayai sessions --jsonfor index metadata.
Tips
- Keep the primary key dedicated to 1:1 traffic; let groups keep their own keys.
- When automating cleanup, delete individual keys instead of the whole store to preserve context elsewhere.
Troubleshooting
Two different people share context in DMs (privacy leak)dmScope: "main" is the default and routes all direct messages into one session. Set dmScope: "per-channel-peer" (or "per-account-channel-peer" for multi-account inboxes) so each sender gets an isolated context. Run wednesdayai security audit to confirm your DM isolation settings.
Session does not reset at the expected daily time
The daily reset uses the gateway host’s local time (default 4:00 AM). If the gateway host is in a different timezone than expected, the reset fires at the wrong wall-clock time. Adjust session.reset.atHour to match your preferred local time, or set the gateway host’s timezone. Also verify the gateway restarted after the config change.
Session database grows very large
By default history is kept forever and is never deleted automatically — there is no automatic
space reclamation. session.maintenance (warn/enforce, pruneAfter, maxEntries) only
retires idle or over-cap sessions from the session index (tombstones); the conversation rows stay.
Use wednesdayai sessions cleanup --dry-run --json to preview which index entries would be retired.
Related
Session origin metadata
Each session entry records where it came from (best-effort) inorigin:
label: human label (resolved from conversation label + group subject/channel)provider: normalized channel id (including extensions)from/to: raw routing ids from the inbound envelopeaccountId: provider account id (when multi-account)threadId: thread/topic id when the channel supports it The origin fields are populated for direct messages, channels, and groups. If a connector only updates delivery routing (for example, to keep a DM main session fresh), it should still provide inbound context so the session keeps its explainer metadata. Extensions can do this by sendingConversationLabel,GroupSubject,GroupChannel,GroupSpace, andSenderNamein the inbound context and callingrecordSessionMetaFromInbound(or passing the same context toupdateLastRoute).