How context-mode Integrates with OpenClaw as a Native Gateway Plugin

context-mode integrates with OpenClaw by registering as a native plugin via openclaw.plugin.json, exposing a register(api) function that wires lifecycle hooks to enforce routing rules, capture tool events in SQLite, and inject context snapshots into the LLM prompt.

The mksglu/context-mode repository provides stateful context management for AI agent sessions. It operates as a native OpenClaw gateway plugin by intercepting tool calls, persisting session data, and managing workspace routing without requiring external services.

Plugin Registration and Initialization

OpenClaw discovers the plugin through the openclaw.plugin.json entry point in the repository root. This manifest declares the extension path and metadata:

{
  "extensions": [
    {
      "id": "context-mode",
      "path": "./src/openclaw-plugin.ts"
    }
  ]
}

When OpenClaw starts an agent session, it executes the register(api) function exported from src/openclaw-plugin.ts. This function receives an OpenClaw Plugin API object (api) that provides typed lifecycle hooks and command registration.

During initialization (lines 18–38), the plugin resolves the build directory and creates a per-project SQLite database via OpenClawSessionDB. The database is stored under ~/.openclaw/context-mode/sessions/ and scoped to each project using a SHA-256 hash of the project directory. A singleton pattern ensures all sessions within the same process share the same storage instance.

Lifecycle Hooks and Session Management

The plugin registers multiple lifecycle hooks via api.on and api.registerHook to synchronize OpenClaw's ephemeral agent state with persistent SQLite storage.

Tool Call Interception and Routing

The before_tool_call hook (lines 71–93) enforces security and routing rules before any tool executes. It loads the routing module from hooks/core/routing.mjs and evaluates whether to deny, ask, or modify the tool call:

api.on("before_tool_call", async (ev) => {
  const { routing } = await initPromise;
  const decision = routing.routePreToolUse(
    ev.toolName, 
    ev.params, 
    process.cwd(), 
    "openclaw"
  );
  
  if (decision?.action === "deny") {
    return { block: true, blockReason: decision.reason };
  }
  
  if (decision?.action === "modify") {
    Object.assign(ev.params, decision.updatedInput);
  }
});

After the tool executes, the after_tool_call hook (lines 84–115) extracts tool-use events via extractEvents() and persists them to the session database. It uses WorkspaceRouter to resolve the correct session ID from tool parameters, handling OpenClaw-specific tool name mapping before storage.

Session State and Persistence

The session_start hook (lines 46–82) performs a critical session re-keying operation. Because the plugin initializes with a temporary session ID before OpenClaw assigns the permanent session identifier, this hook migrates the database records to the final session_id using the session_key mapping table defined in src/adapters/openclaw/session-db.ts.

The plugin also listens to command hooks (command:new, command:reset, command:stop) to clean up stale sessions and remove workspace registrations when users reset or stop agents.

Context Compaction and Recovery

To prevent context loss during OpenClaw's conversation compaction, the plugin implements before_compaction and after_compaction hooks (lines 94–116). The before hook writes a resume snapshot to the database via buildResumeSnapshot(), while the after hook increments the compact count. Later, the before_prompt_build hook (priority 10, lines 138–168) re-injects this snapshot into the system prompt, ensuring the LLM retains awareness of previous context after truncation.

Workspace Routing and Path Resolution

The WorkspaceRouter class in src/openclaw/workspace-router.ts manages multi-workspace environments by scanning paths for the /openclaw/workspace-<name> pattern. It extracts workspace roots and maps them to stable session keys, enabling the plugin to attribute tool events to the correct session when agents operate across multiple directories.

The router provides resolveSessionId(params, fallback), which after_tool_call invokes to determine the appropriate database session for storing events based on the tool's working directory or file path parameters.

Prompt Injection and Routing Instructions

The plugin enhances LLM behavior by injecting content during the prompt building phase. The before_prompt_build hook operates at two priority levels:

  1. Priority 10 (lines 138–168): Injects the resume snapshot containing previous context and conversation state.
  2. Priority 5 (lines 71–85): Injects optional routing instructions loaded from configs/openclaw/AGENTS.md. This file allows users to define custom rules (e.g., denying specific shell commands) that the model sees before generating tool calls.

Additionally, the before_model_resolve hook (lines 131–145) captures the raw user message as a "user_message" event for audit trails.

Slash Commands and Diagnostics

The plugin exposes three diagnostic commands via api.registerCommand (lines 118–176):

  • /ctx-stats: Returns a markdown summary of the current session database statistics and event counts.
  • /ctx-doctor: Runs diagnostic checks on the database and workspace routing configuration.
  • /ctx-upgrade: Handles database schema migrations and plugin updates.

These commands allow users to inspect context-mode state directly within OpenClaw chat sessions without external tools.

Summary

  • Native Integration: The plugin loads via openclaw.plugin.json and exports a register(api) function in src/openclaw-plugin.ts that receives the OpenClaw Plugin API.
  • Lifecycle Hooks: Implements before_tool_call, after_tool_call, session_start, compaction hooks, and prompt building hooks to intercept and persist agent behavior.
  • SQLite Persistence: Uses OpenClawSessionDB in src/adapters/openclaw/session-db.ts with session key mapping to maintain state across OpenClaw's session lifecycle.
  • Workspace Routing: WorkspaceRouter in src/openclaw/workspace-router.ts handles multi-workspace path resolution for /openclaw/workspace-<name> patterns.
  • Context Recovery: Injects resume snapshots during before_prompt_build to survive conversation compaction, and loads user-defined routing rules from configs/openclaw/AGENTS.md.

Frequently Asked Questions

How does context-mode maintain state across OpenClaw conversation compactions?

The plugin registers before_compaction and after_compaction hooks that snapshot the current database state using buildResumeSnapshot(). When OpenClaw truncates the conversation, the before_prompt_build hook (priority 10) retrieves this snapshot and injects it into the system prompt, effectively restoring the previous context for the LLM.

Can context-mode block dangerous tool calls in OpenClaw?

Yes. The before_tool_call hook runs a routing engine that can deny, ask for confirmation, or modify tool parameters before execution. Security rules can be defined in hooks/core/routing.mjs (OpenClaw-side) and supplemented by user-editable instructions in configs/openclaw/AGENTS.md that get injected into the prompt.

What is the session_key used for in the database?

The session_key provides a temporary identifier used during plugin initialization before OpenClaw assigns the permanent session ID. When the session_start hook fires, the plugin calls renameSession() in src/adapters/openclaw/session-db.ts to migrate all temporary records to the final session ID, ensuring no events are lost during the startup sequence.

Where is the session data stored when using OpenClaw?

Session data is stored in a SQLite database located at ~/.openclaw/context-mode/sessions/. The database file is scoped per project using a SHA-256 hash of the project directory, ensuring isolation between different codebases while allowing shared access to the singleton database instance within the same OpenClaw process.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →