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 storageSession Lifecycle
A session moves through a well-defined lifecycle:
CREATE → USE (read/write working memory) → COMMIT (optional) → EXPIRE/DELETE1. 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
| Parameter | Default | Description |
|---|---|---|
session_id | auto-generated | Client-provided session ID |
workspace_id | _default | Workspace to bind the session to |
ttl_seconds | 3600 | Session TTL (60 to 86400 seconds) |
context_id | _default | Context within the workspace |
working_memory | null | Initial key-value pairs to populate |
metadata | {} | Arbitrary session metadata |
briefing | false | Include a briefing with relevant memories on start |
briefing_options | null | lookback_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 memoryawait client.set_context( session.id, "current_task", {"description": "Debugging auth", "file": "auth.py"})
# Retrieve working memorycontext = await client.get_context(session.id, ["current_task"])TypeScript
// Store working memoryawait client.setWorkingMemory(session.id, "current_task", { description: "Debugging auth", file: "auth.py",});
// Retrieve working memoryconst 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 hourawait 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 TTLresult = await client.touch_session(session.id)print(result["expires_at"])# Reset expiry to now + 2 hourscurl -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:
| Field | Description |
|---|---|
memories_extracted | Total memories extracted from session |
memories_deduplicated | Number of duplicates removed |
memories_created | Number of new memories created |
breakdown | Memory count by category |
extraction_time_ms | Time taken for extraction |
Commit Options
| Option | Default | Description |
|---|---|---|
min_importance | 0.5 | Minimum importance threshold for extraction |
deduplicate | true | Remove duplicate memories during extraction |
categories | all | Specific category names to extract |
max_memories | 50 | Maximum 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 defaultsession = await client.create_session(ttl_seconds=3600)
# Working memory is stored during the sessionawait client.set_context(session.id, "decision", { "choice": "Use PostgreSQL for persistence", "reason": "Need ACID guarantees"})
# When the session expires, working memory is committed automaticallyEnd 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 creationconst { session, briefing } = await client.createSession({ ttlSeconds: 3600, briefing: true,});# Standalone briefing: GET /v1/sessions/briefingbriefing = 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:
| Section | Description |
|---|---|
workspace_summary | Total memories, recent activity counts |
recent_activity | Recent session summaries and key decisions |
open_threads | Ongoing topics that may need attention |
contradictions_detected | Memories with contradictory relationships |
memories | Relevant 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_segmentcontent_hash: the lowercase SHA-256 of the segmentidempotency_key: makes retries safe- optional
source_kind(defaulttranscript),source_sequence, andsource_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 promptcursor = pack.cursor # for incremental updatesPOST /v1/sessions/{session_id}/context-pack fields:
| Field | Default | Description |
|---|---|---|
topic | — | Optional topic focus |
entity_ids, entity_names | [] | Focus on specific entities |
budget_tokens | 2048 | Token budget (32–200000) |
section_limits | directives 8, working_memory 20, recent_activity 20, contradictions 5, checkpoints 8 | Per-section item caps |
include_directives, include_working_memory, include_recent_activity, include_contradictions, include_sandbox_summary, include_checkpoint_recovery | true | Section 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 pagesCursors 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 taskawait client.set_context(session.id, "task", { "goal": "Fix authentication bug", "files_modified": [], "decisions": []})
# During worktask = 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 learningsawait client.commit_session(session.id)Claude Code Sessions
The MCP server’s session tools are designed for Claude Code workflows:
memory_session_start— Initialize at session startmemory_remember— Store decisions and learnings during workmemory_session_endwithcommit: 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 1await 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 preservedStructured Session Memory
For complex sessions, organize working memory into semantic sections:
# Store context about the current taskawait client.set_context(session.id, "context", [ "Working on payment service refactoring", "Using FastAPI with SQLAlchemy"])
# Track decisions made during the sessionawait 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 encounteredawait client.set_context(session.id, "errors", [ "ConnectionPool exhaustion under load — fixed by increasing pool size"])