Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript
8.9 KB
Raw Blame
/**
 * OpenClaw native plugin entry for Open Second Brain.
 *
 * Pure TypeScript that delegates to `src/core/*` so the OpenClaw runtime
 * shares the same source of truth as the CLI and MCP server.
 *
 * Exposes the current tool surface: `second_brain_status`,
 * `second_brain_query`, and `vault_health`.
 * No subprocess creation; passes the OpenClaw security scanner.
 */

import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";

import { discoverConfig, resolveAgentName } from "../core/config.ts";
import { redactConfigMapping } from "../core/egress/guard.ts";
import { resolvedSecretLiterals } from "../core/secret-resolver.ts";
import { probeVaultDirectory } from "../core/vault-presence.ts";
import { doctor } from "../core/doctor.ts";
import { buildReminder } from "../core/identity-reminder.ts";
import { listVaultPages } from "../core/vault.ts";
import { TRANSPORT_REACH, type TransportReach } from "../core/graph/transport-reach.ts";
import { ENTITY_STATUS_SCOPE, vaultPageInStatusScope } from "../core/brain/entities/page-scope.ts";
import { deriveRuntimeAgentName, normalizeAgentArgument } from "../core/agent-identity.ts";
import { vaultRelative as vaultRelativePath } from "../core/path-safety.ts";
import { vaultPathField } from "../mcp/vault-path-field.ts";

/**
 * What this runtime establishes about the caller of its tools.
 *
 * `remote`, and the distinction from the CLI is the caller rather than
 * the machine. A CLI verb is typed by the operator; these tools are
 * called by a model, over a conversation whose steering this plugin
 * cannot see. Running on the operator's own host proves that the PROCESS
 * has filesystem access, not that the party asking is entitled to a page
 * the operator reserved - so this surface takes the narrowest reach, and
 * an operator who wants those pages in this runtime reads them the way
 * they reserved them: locally.
 */
const OPENCLAW_TRANSPORT_REACH: TransportReach = TRANSPORT_REACH.remote;

interface PluginConfig {
  vault?: string;
  agentName?: string;
  timezone?: string;
  instanceName?: string;
}

function resolveVaultPath(api: { pluginConfig?: Record<string, unknown> }): string {
  const cfg = (api.pluginConfig ?? {}) as PluginConfig;
  return cfg.vault || process.env["VAULT_DIR"] || ".";
}

export default definePluginEntry({
  register(api): void {
    // Per-turn identity reminder via OpenClaw's `before_prompt_build` hook.
    // The hook fires before every model call and lets us append a short
    // string into the prompt, mirroring `pre_llm_call` in Hermes and
    // `UserPromptSubmit` in Claude Code / Codex. Without this, the agent
    // sees the identity reminder only once at MCP `initialize`, then drifts.
    //
    // We prefer `prependContext` (per-turn, not cached) over
    // `prependSystemContext` (cached system-prompt) because the cached
    // form has the same drift problem we are working around — the LLM
    // stops paying attention to it as the conversation grows.
    api.on("before_prompt_build", () => {
      const cfg = (api.pluginConfig ?? {}) as PluginConfig;
      const operator =
        normalizeAgentArgument(cfg.agentName ?? null) ??
        process.env["VAULT_AGENT_NAME"] ??
        resolveAgentName();
      if (operator === "agent") return undefined;
      // OpenClaw writes under its OWN host-qualified identity (vendor `openclaw`
      // + the operator's host), not the operator's name - so its Brain activity
      // is distinguishable per runtime and per device, matching grok/opencode.
      const agent = deriveRuntimeAgentName("openclaw", operator);
      return { prependContext: buildReminder(agent, "openclaw") };
    });

    api.registerTool({
      name: "second_brain_status",
      description: "Report Open Second Brain configuration and vault status.",
      parameters: {
        type: "object",
        properties: {},
        additionalProperties: false,
      },
      async execute(): Promise<unknown> {
        const vault = resolveVaultPath(api);
        const discovery = discoverConfig();
        // Shared with the primary runtime's status tool: a vault that
        // cannot be examined is not a vault that is not there, and this
        // payload is the one place that difference is the product.
        const presence = probeVaultDirectory(vault);
        const result = {
          config_path: discovery.path,
          config_exists: discovery.exists,
          config_keys: Object.keys(discovery.data).toSorted(),
          config: redactConfigMapping(discovery.data, {
            // The vault's known resolved values join the scan: a custody-
            // store credential under a quiet config key is scrubbed here
            // exactly as the primary runtime's status tool scrubs it. A
            // locked or absent store contributes nothing.
            resolvedLiterals: resolvedSecretLiterals(vault),
          }),
          vault_path: vaultPathField({ vault }),
          vault_exists: presence.unexaminable ?? presence.present,
        };
        return {
          content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
        };
      },
    });

    api.registerTool({
      name: "second_brain_query",
      description: "List vault pages with optional title substring filter.",
      parameters: {
        type: "object",
        properties: {
          pattern: {
            type: "string",
            description: "Optional case-insensitive substring matched against page titles.",
          },
          limit: {
            type: "integer",
            minimum: 1,
            maximum: 500,
            description: "Maximum number of matched pages to return (default 50).",
          },
        },
        additionalProperties: false,
      },
      async execute(_id, params): Promise<unknown> {
        const vault = resolveVaultPath(api);
        // Refuses either way, but the REASON has to be right: telling an
        // operator their vault is missing sends them to create one they
        // already have.
        const presence = probeVaultDirectory(vault);
        if (presence.unexaminable) throw new Error(presence.unexaminable.error);
        if (!presence.present) throw new Error(`vault directory missing: ${vault}`);
        const pattern = (params["pattern"] as string | undefined) ?? null;
        const limit = typeof params["limit"] === "number" ? (params["limit"] as number) : 50;
        if (limit < 1 || limit > 500) throw new Error("argument 'limit' must be between 1 and 500");

        // Entity records under quarantine entered the vault under untrusted
        // provenance, so their title is attacker-chosen. This listing filters
        // by title, which is exactly the surface that would hand one back, and
        // it is a page walker rather than an entity reader so the entity read
        // census does not cover it. Non-entity pages are unaffected.
        const pages = listVaultPages(vault, { reach: OPENCLAW_TRANSPORT_REACH }).filter((p) =>
          vaultPageInStatusScope(p.metadata, ENTITY_STATUS_SCOPE.readable),
        );
        const needle = pattern ? pattern.toLowerCase() : null;
        const matched = (
          needle === null ? pages : pages.filter((p) => p.title.toLowerCase().includes(needle))
        )
          .slice(0, limit)
          .map((p) => ({
            title: p.title,
            path: vaultRelativePath(p.path, vault),
            metadata: p.metadata,
          }));

        const result = {
          vault_path: vaultPathField({ vault }),
          total_pages: pages.length,
          returned: matched.length,
          limit,
          pattern,
          pages: matched,
        };
        return {
          content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
        };
      },
    });

    // Agents on this runtime record observations via the Brain writer
    // tools served by the MCP server (`brain_feedback`,
    // `brain_apply_evidence`, `brain_note`).

    api.registerTool({
      name: "vault_health",
      description: "Run vault, config, and plugin manifest health checks.",
      parameters: {
        type: "object",
        properties: {
          repo: {
            type: "string",
            description: "Optional repository root to validate plugin manifests.",
          },
        },
        additionalProperties: false,
      },
      async execute(_id, params): Promise<unknown> {
        const vault = resolveVaultPath(api);
        const repoRoot = (params["repo"] as string | undefined) ?? null;
        const results = doctor({ vault, repoRoot });
        const result = {
          vault_path: vaultPathField({ vault }),
          ok: results.every((r) => r.ok),
          checks: results.map((r) => ({
            name: r.name,
            ok: r.ok,
            message: r.message,
            ...(r.fix !== undefined ? { fix: r.fix } : {}),
          })),
        };
        return {
          content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
        };
      },
    });
  },
});