Skip to main content
Sonzai Docs

OpenClaw Integration

Replace OpenClaw's default memory with the Sonzai Mind Layer — persistent memory, personality evolution, mood tracking, and relationship modeling for every agent.

What is OpenClaw?

OpenClaw is an open-source framework for building conversational AI agents. It uses a modular plugin system with named slots — each slot controls a specific part of the agent pipeline.

The most important slot is contextEngine. This is the plugin responsible for deciding what context gets injected into the system prompt before every LLM call. It controls what your agent remembers, knows, and feels.

How the Plugin System Works

OpenClaw's plugin system works like middleware. Each plugin implements lifecycle hooks that fire at specific points during a conversation turn:

bootstrap(sessionId)Called when a new chat session starts. The plugin initializes any connections or state it needs.
assemble(messages, tokenBudget)Called before every LLM call. The plugin returns a systemPromptAddition — extra context injected into the system prompt.
afterTurn(sessionId)Called after the LLM responds. The plugin processes the conversation (e.g., extract facts, update state).
compact(sessionId)Called when context needs to be consolidated (e.g., merging short-term memory into long-term).
dispose()Called when the session ends. Clean up connections and state.

By default, OpenClaw ships with a basic context engine that stores memories as local Markdown files. The Sonzai plugin replaces this with the Mind Layer — giving your agent persistent memory, personality evolution, mood tracking, and relationship modeling with zero additional code.

How plugin registration works

When you install @sonzai-labs/openclaw-context, the package exports a register() function as its default export. On startup, OpenClaw loads all installed plugins and calls their register functions. Ours registers a context engine factory under the name "sonzai":

// Inside @sonzai-labs/openclaw-context (you don't write this)
export default function register(api) {
  api.registerContextEngine("sonzai", () => {
    return new SonzaiContextEngine(client, config);
  });
}

Then in openclaw.json, you tell OpenClaw which registered engine to use for the contextEngine slot. The name "sonzai" must match what the plugin registered:

{
  "plugins": {
    "slots": {
      "contextEngine": "sonzai"    // ← matches the name from register()
    },
    "entries": {
      "sonzai": {                  // ← config passed to the plugin
        "enabled": true,
        "apiKey": "sk-your-api-key",
        "agentId": "your-agent-uuid"
      }
    }
  }
}

So the flow is: install the npm package → OpenClaw discovers and calls register() → the plugin registers under "sonzai" → your config assigns it to the contextEngine slot.

Why Sonzai as a Context Layer?

Sonzai serves as a pure context engine for OpenClaw. Instead of the framework managing its own memory files, every conversation flows through the Mind Layer — which handles fact extraction, semantic search, mood updates, and personality evolution automatically. Your OpenClaw agent gets rich, structured context without writing any memory logic.

Quick Start

1. Get Your API Key

Get an API key from your Sonzai project settings. You'll paste it during the setup wizard, and it will be saved to your openclaw.json.

2. Install the Plugin

# Install via OpenClaw CLI
openclaw plugins install @sonzai-labs/openclaw-context

# Or install directly with your package manager
npm install @sonzai-labs/openclaw-context
# bun add @sonzai-labs/openclaw-context

3. Run the Setup Wizard

The setup wizard walks you through connecting your OpenClaw project to the Mind Layer:

npx @sonzai-labs/openclaw-context setup

The wizard will:

  • Ask for your API key (or detect SONZAI_API_KEY from the environment)
  • Ask if you have an existing agent ID, or create a new one with a name you choose
  • Validate the API key against the Mind Layer
  • Save your API key and plugin config to openclaw.json

After setup, your openclaw.json will look like this:

{
  "plugins": {
    "slots": {
      "contextEngine": "sonzai"
    },
    "entries": {
      "sonzai": {
        "enabled": true,
        "apiKey": "sk-your-api-key",
        "agentId": "a1b2c3d4-..."
      }
    }
  }
}

API Key Storage

Your API key is stored in openclaw.json alongside your plugin config — no environment variables needed. Make sure openclaw.json is in your .gitignore to avoid committing secrets.

4. Start Chatting

Launch OpenClaw as usual. The plugin registers as the sonzai context engine and takes over context assembly automatically:

openclaw chat

That's it. Every conversation now flows through the Mind Layer — your agent has persistent memory, personality, and mood from the first message.

Configuration Reference

All settings go in openclaw.json under plugins.entries.sonzai. Environment variables are supported as overrides.

OptionEnv OverrideDefaultDescription
apiKeySONZAI_API_KEY--Project API key (required)
agentIdSONZAI_AGENT_IDauto-provisionedPre-provisioned agent UUID
baseUrlSONZAI_BASE_URLhttps://api.sonz.aiPlatform API base URL
agentName--openclaw-agentName for auto-provisioned agents
defaultUserId--ownerFallback user ID for 1:1 sessions
contextTokenBudget--2000Max tokens for injected context
extractionProvider----LLM provider for fact extraction
extractionModel----LLM model for fact extraction

Disabling Context Sources

You can selectively disable specific context sources via the disablemap. This is useful when you want the Mind Layer for memory but don't need mood tracking, or when you want to reduce token usage:

{
  "plugins": {
    "entries": {
      "sonzai": {
        "enabled": true,
        "apiKey": "sk-your-api-key",
        "agentId": "your-agent-uuid",
        "disable": {
          "mood": true,
          "personality": false,
          "relationships": true,
          "memory": false,
          "goals": true,
          "interests": true,
          "habits": true
        }
      }
    }
  }
}

With the config above, only personality and memory context will be injected — ideal for using the Mind Layer as a pure memory and personality store.

Injected Context

On each turn, the plugin injects a structured <sonzai-context> block into the system prompt. Sections are ordered by priority and dropped lowest-first if the token budget is exceeded:

Personality1 (highest)Character definition, primary traits, speech patterns, Big5 profile
Relevant Memories2Semantically searched facts matching the latest user message
Current Mood34D emotional state (valence, arousal, tension, affiliation)
Relationship4Relationship narrative, love scores, chemistry with the current user
Goals5Active goals (growth, mastery, relationship, discovery)
Interests6Detected interests with confidence levels
Habits7 (lowest)Behavioral patterns with strength scores

Token Budget

The default budget is 2000 tokens (~8000 characters). The plugin estimates token count at ~4 characters per token and drops the lowest-priority sections first when the budget is exceeded. Adjust with contextTokenBudget in your config.

Session Key Resolution

The plugin automatically extracts user identity from OpenClaw's session key format. This enables per-user memory and relationships without any configuration:

Session FormatExampleResolved User ID
CLI (1:1)agent:abc:mainKeyowner
Telegram DMagent:abc:telegram:direct:123123
WhatsApp DMagent:abc:whatsapp:direct:+1555...+1555...
Discord Groupagent:abc:discord:group:guild789guild789
Cron / Webhookcron:daily-checkowner

Programmatic Setup (B2B)

For multi-tenant deployments where you provision agents programmatically, use the setup() function directly:

import { setup } from "@sonzai-labs/openclaw-context";

const result = await setup({
  apiKey: "sk-project-key",
  agentName: "customer-support-bot",
  configPath: "/path/to/openclaw.json",
});

console.log(result.agentId);   // deterministic UUID (SHA1 of tenantID + agentName)
console.log(result.written);   // true — config file updated

Idempotent Provisioning

Agent IDs are generated deterministically from SHA1(tenantID + agentName). Calling setup multiple times with the same name returns the same agent — safe for restarts and redeployments.

Architecture

The Sonzai context engine plugs into OpenClaw's lifecycle hooks. Here's the flow for a single conversation turn:

OpenClaw Runtime                SonzaiContextEngine              Sonzai Mind Layer
      |                                    |                                |
      |-- bootstrap(sessionId) ----------->|                                |
      |                                    |-- resolve agent + session ---->|
      |                                    |<-- session state cached -------|
      |                                    |                                |
      |-- assemble(messages, budget) ----->|                                |
      |                                    |-- fetch context (memory,       |
      |                                    |   personality, mood,           |
      |                                    |   relationships) ------------>|
      |                                    |<-- ranked context blocks ------|
      |                                    |                                |
      |<-- systemPromptAddition -----------|   (priority-ordered,           |
      |                                    |    budget-trimmed)             |
      |                                    |                                |
      |  [LLM call with enriched prompt]   |                                |
      |                                    |                                |
      |-- afterTurn(sessionId) ----------->|                                |
      |                                    |-- send conversation ---------> |
      |                                    |   Mind Layer extracts facts,   |
      |                                    |   updates mood, evolves        |
      |                                    |   personality automatically    |
      |                                    |                                |
      |-- compact(sessionId) ------------->|                                |
      |                                    |-- merge short-term → long-term>|
      |                                    |<-- compacted ------------------|

The context engine handles all communication with the Mind Layer. During assemble, it fetches context sources (memory, personality, mood, relationships, goals, interests, habits), ranks them by priority, and trims to the token budget. During afterTurn, it sends the conversation back for fact extraction and state updates. The engine never runs LLM calls locally — all intelligence lives on the Sonzai side.

Graceful Degradation

All API calls are wrapped in error handlers. If the Mind Layer is unreachable, the engine returns empty context and never blocks OpenClaw — your agent continues working without enriched context.

Exports

The package exports the following for advanced usage:

ExportDescription
defaultPlugin registration (auto-loaded by OpenClaw)
SonzaiContextEngineCore engine class — usable outside OpenClaw
setup()Programmatic setup for B2B deployments
resolveConfig()Merge openclaw.json + env vars + config into resolved options
parseSessionKey()Extract user identity from OpenClaw session keys
buildSystemPromptAddition()Format context into the injection block
estimateTokens()Estimate token count for a string (~4 chars/token)
SessionCacheTTL-based cache for session state

Next Steps