Skip to content

Sessions & Working Memory

Sessions provide working memory — temporary context that persists across API calls within a session and can optionally be committed to long-term storage.

How Sessions Work

Session Start
↓
Store working memory (key-value pairs)
↓
Working memory persists across requests
↓
Session End → optionally commit to long-term storage

Session Lifecycle

A session moves through a well-defined lifecycle:

CREATE → USE (read/write working memory) → COMMIT (optional) → EXPIRE/DELETE

1. Create

Sessions are created with a TTL (time-to-live) that determines how long the session stays active. The server auto-creates the target workspace if it does not already exist.

2. Use

During a session, you store and retrieve key-value pairs in working memory. Each API call that uses the session keeps it alive within its TTL window.

3. Commit

Before a session ends, its working memory can be committed to long-term storage. This extracts important information from the session and stores it as permanent memories.

4. Expire or Delete

Sessions expire automatically when their TTL elapses, or they can be deleted explicitly. A background cleanup task commits each expired, not-yet-committed session before deleting it. Every session has auto_commit: true. Turn this off server-wide with MEMORYLAYER_BACKGROUND_SESSION_AUTO_COMMIT=false.

Sessions are stored durably by default (MEMORYLAYER_SESSION_SERVICE=persistent since 0.2.0), so they and their working memory survive a server restart. Set in-memory for ephemeral deployments.

Creating a Session

Python

session = await client.create_session(
ttl_seconds=3600,
workspace_id="my-workspace"
)
print(f"Session ID: {session.id}")

TypeScript

const { session, briefing } = await client.createSession({
workspaceId: "my-workspace",
ttlSeconds: 3600,
briefing: true, // Get briefing on session start
});

Session Options

ParameterDefaultDescription
session_idauto-generatedClient-provided session ID
workspace_id_defaultWorkspace to bind the session to
ttl_seconds3600Session TTL (60 to 86400 seconds)
context_id_defaultContext within the workspace
working_memorynullInitial key-value pairs to populate
metadata{}Arbitrary session metadata
briefingfalseInclude a briefing with relevant memories on start
briefing_optionsnulllookback_hours, detail_level, limit for the start-up briefing

The Python SDK’s create_session() takes ttl_seconds, workspace_id, and context_id. It also makes the new session the client’s active session. Use the TypeScript SDK or the REST API to request a briefing at creation time.

Working Memory

Working memory is a key-value store scoped to a session. Values are JSON-serializable and persist across API calls for the session’s lifetime.

Python

# Store working memory
await client.set_context(
session.id,
"current_task",
{"description": "Debugging auth", "file": "auth.py"}
)
# Retrieve working memory
context = await client.get_context(session.id, ["current_task"])

TypeScript

// Store working memory
await client.setWorkingMemory(session.id, "current_task", {
description: "Debugging auth",
file: "auth.py",
});
// Retrieve working memory
const memory = await client.getWorkingMemory(session.id, "current_task");

Working Memory TTL

Individual working memory entries can have their own TTL that overrides the session TTL:

# This entry expires in 5 minutes, even if the session lasts an hour
await client.set_context(
session.id,
"temp_calculation",
{"result": 42},
ttl_seconds=300
)

MCP Tools

When using via MCP server (Claude Code, Claude Desktop), use the session tools:

// memory_session_start — Start a session (workspace is auto-detected)
{ "metadata": { "task": "auth refactor" } }
// memory_session_status — Check session status
{}
// memory_session_commit — Commit working memory to long-term storage
{ "importance_threshold": 0.5, "clear_after_commit": false }
// memory_session_end — End session
{ "commit": true, "importance_threshold": 0.5 }

Session TTL and Touch/Extend

Sessions have a TTL set at creation time. To keep a session alive, touch it. Touching is a sliding window: it resets the expiry to now + TTL. The TTL is MEMORYLAYER_SESSION_TOUCH_TTL (default 3600 seconds) unless you pass extend_seconds.

# Reset expiry to now + the server's touch TTL
result = await client.touch_session(session.id)
print(result["expires_at"])
Terminal window
# Reset expiry to now + 2 hours
curl -X POST "http://localhost:61001/v1/sessions/$SESSION_ID/touch?extend_seconds=7200"

Committing Sessions

Committing extracts important working memory items and stores them as permanent memories.

Explicit Commit

result = await client.commit_session(
session_id,
min_importance=0.5,
deduplicate=True
)
print(f"Created {result['memories_created']} long-term memories")

The commit response includes details about what was extracted:

FieldDescription
memories_extractedTotal memories extracted from session
memories_deduplicatedNumber of duplicates removed
memories_createdNumber of new memories created
breakdownMemory count by category
extraction_time_msTime taken for extraction

Commit Options

OptionDefaultDescription
min_importance0.5Minimum importance threshold for extraction
deduplicatetrueRemove duplicate memories during extraction
categoriesallSpecific category names to extract
max_memories50Maximum memories to extract per commit

Auto-Commit on Session End

When auto_commit is enabled (the default), sessions are automatically committed when they expire. This ensures working memory is not lost even if the client disconnects:

# Auto-commit is on by default
session = await client.create_session(ttl_seconds=3600)
# Working memory is stored during the session
await client.set_context(session.id, "decision", {
"choice": "Use PostgreSQL for persistence",
"reason": "Need ACID guarantees"
})
# When the session expires, working memory is committed automatically

End a Session

await client.delete_session(session.id)

Session Briefings

Briefings provide a summary of recent activity and relevant context when starting a new session. Request a briefing at session creation time or separately:

// Briefing at session creation
const { session, briefing } = await client.createSession({
ttlSeconds: 3600,
briefing: true,
});
# Standalone briefing: GET /v1/sessions/briefing
briefing = await client.get_briefing(lookback_minutes=24 * 60, detail_level="overview", limit=10)
print(briefing.workspace_summary)

GET /v1/sessions/briefing takes lookback_minutes (default 60), detail_level (default abstract), limit (default 10), include_memories, and include_contradictions.

A briefing includes:

SectionDescription
workspace_summaryTotal memories, recent activity counts
recent_activityRecent session summaries and key decisions
open_threadsOngoing topics that may need attention
contradictions_detectedMemories with contradictory relationships
memoriesRelevant memories for the new session
const briefing = await client.getBriefing({ lookbackMinutes: 24 * 60 });
console.log(briefing.workspace_summary);
console.log(briefing.open_threads);

Checkpoints, Context Packs, and Deltas

0.2.0 adds three deterministic building blocks for agents that lose their context window, for example when a conversation is compacted.

Raw Session Checkpoints

A checkpoint durably stores an exact transcript segment before it would be lost. The Claude Code and OpenCode plugins call this before compaction.

import hashlib
segment = "...raw transcript text..."
cp = await client.create_checkpoint(
session.id,
segment,
content_hash=hashlib.sha256(segment.encode("utf-8")).hexdigest(),
idempotency_key="turns-120-180",
)
print(cp.capture_status, cp.raw_memory_id)

POST /v1/sessions/{session_id}/checkpoints takes:

  • transcript_segment
  • content_hash: the lowercase SHA-256 of the segment
  • idempotency_key: makes retries safe
  • optional source_kind (default transcript), source_sequence, and source_boundary

The response reports capture_status (durable or failed) separately from index_status and enrichment_status, so a capture counts as safe before indexing finishes. Segments are limited to MEMORYLAYER_SESSION_CHECKPOINT_MAX_BYTES (default 1 MiB). To disable capture, set MEMORYLAYER_SESSION_CHECKPOINT_CAPTURE_ENABLED=false, and the endpoint returns 503.

Context Packs

A context pack is a budgeted, rendered bundle of what an agent needs to resume: directives, working memory, recent activity, unresolved contradictions, a context-sandbox summary, and checkpoint recovery pointers.

pack = await client.get_context_pack(session.id, topic="auth refactor", budget_tokens=4000)
print(pack.rendered) # ready to drop into a prompt
cursor = pack.cursor # for incremental updates

POST /v1/sessions/{session_id}/context-pack fields:

FieldDefaultDescription
topic—Optional topic focus
entity_ids, entity_names[]Focus on specific entities
budget_tokens2048Token budget (32–200000)
section_limitsdirectives 8, working_memory 20, recent_activity 20, contradictions 5, checkpoints 8Per-section item caps
include_directives, include_working_memory, include_recent_activity, include_contradictions, include_sandbox_summary, include_checkpoint_recoverytrueSection toggles

The response contains rendered, items, open_threads, unresolved_contradictions, budget_summary, generation_summary, degradation_notices, and a cursor.

Context Deltas

Instead of rebuilding the pack, send its cursor to get only what changed:

delta = await client.get_context_delta(session.id, cursor, budget_tokens=1024)
cursor = delta.cursor # keep following; delta.has_more signals more pages

Cursors are HMAC-signed. The default MEMORYLAYER_CONTEXT_CURSOR_SECRET is a fixed public value, so set your own in production. Change events are kept for MEMORYLAYER_CONTEXT_EVENT_RETENTION_DAYS (default 30). A cursor older than that returns 409 cursor_expired, and the client should then fetch a fresh pack. MEMORYLAYER_CONTEXT_PACK_ENABLED=false turns off both endpoints.

These are also available as:

  • MCP tools: memory_session_checkpoint, memory_context_pack, memory_context_delta
  • TypeScript SDK methods: createCheckpoint, getContextPack, getContextDelta
  • the Go SDK

Practical Patterns

Agent Task Tracking

# Start of task
await client.set_context(session.id, "task", {
"goal": "Fix authentication bug",
"files_modified": [],
"decisions": []
})
# During work
task = await client.get_context(session.id, ["task"])
task["files_modified"].append("auth.py")
await client.set_context(session.id, "task", task)
# End of task — commit learnings
await client.commit_session(session.id)

Claude Code Sessions

The MCP server’s session tools are designed for Claude Code workflows:

  1. memory_session_start — Initialize at session start
  2. memory_remember — Store decisions and learnings during work
  3. memory_session_end with commit: true — Persist working memory at session end

Multi-Turn Conversations

Sessions keep context across multiple API calls without re-fetching:

session = await client.create_session(ttl_seconds=7200)
# Turn 1
await client.set_context(session.id, "user_name", "Alice")
await client.set_context(session.id, "topic", "Python debugging")
# Turn 2 (different API call, same session)
name = await client.get_context(session.id, ["user_name"])
# Returns "Alice" — context preserved

Structured Session Memory

For complex sessions, organize working memory into semantic sections:

# Store context about the current task
await client.set_context(session.id, "context", [
"Working on payment service refactoring",
"Using FastAPI with SQLAlchemy"
])
# Track decisions made during the session
await client.set_context(session.id, "decisions", [
"Use circuit breaker pattern for external API calls",
"Switch from REST to gRPC for inter-service communication"
])
# Record errors encountered
await client.set_context(session.id, "errors", [
"ConnectionPool exhaustion under load — fixed by increasing pool size"
])