Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

7.8 KB
Raw Blame
/**
 * OpenCode V1 plugin adapter.
 *
 * V1 plugins are an async factory that RETURNS a hooks object, keyed by
 * OpenCode's hook names. Kept for OpenCode 1.3.4+, which loads the module's
 * default export and calls `server()`. V2 reads `id` + `setup()` instead (see
 * ./v2.ts); the entry module serves both.
 */

import { z } from "zod";
import { createCore, type ClaudeMemCore, type CoreContext } from "./core.js";
import { type RealOpenCodeEventType } from "./contract.js";

interface OpenCodeProject {
  name?: string;
  path?: string;
}

export interface OpenCodePluginContextV1 extends CoreContext {
  project?: OpenCodeProject;
  worktree?: string;
  serverUrl?: URL;
  $?: unknown;
}

export interface ToolExecuteAfterInput {
  tool: string;
  sessionID: string;
  callID: string;
  // OpenCode passes the tool arguments here, on the hook's FIRST argument —
  // the output object never carries them (#3678 diagnosis by kevinchiha;
  // cross-checked against OpenCode 1.18's Hooks type, where the output is
  // only { title, output, metadata }).
  args?: Record<string, unknown>;
}

export interface ToolExecuteAfterOutput {
  title: string;
  output: string;
  metadata: Record<string, unknown>;
  args?: Record<string, unknown>;
}

export interface ChatMessageInput {
  // OpenCode passes the host's selected model on the chat.message input. Only
  // `modelID` is endpoint-ready; `providerID` is the map key for the session's
  // endpoints, never an inference model name and never concatenated into one.
  sessionID?: string;
  model?: { providerID?: string; modelID?: string };
}

export interface ChatMessageOutput {
  message: {
    id?: string;
    role?: string;
    sessionID?: string;
  };
  parts: Array<{ type: string; text?: string }>;
}

export interface SessionCompactingInput {
  sessionID: string;
}

export interface BusEvent {
  type: string;
  properties?: {
    sessionID?: string;
    info?: { id?: string };
  };
}

function textOfParts(parts: Array<{ type: string; text?: string }>): string {
  return (parts || [])
    .filter((part) => part.type === "text" && typeof part.text === "string")
    .map((part) => part.text as string)
    .join("\n");
}

export function createV1Hooks(ctx: OpenCodePluginContextV1) {
  console.log(`[claude-mem] OpenCode plugin loading (directory: ${ctx.directory})`);
  const core: ClaudeMemCore = createCore(ctx);

  return {
    // Capture every tool execution as an observation. This is the primary
    // capture path (#2419).
    "tool.execute.after": async (
      input: ToolExecuteAfterInput,
      output: ToolExecuteAfterOutput,
    ): Promise<void> => {
      await core.captureTool({
        tool: input.tool,
        sessionID: input.sessionID,
        toolUseId: input.callID,
        args: input.args,
        output: output.output || "",
      });
    },

    // Capture each real user prompt with session init, and assistant messages
    // as observations.
    "chat.message": async (
      input: ChatMessageInput,
      output: ChatMessageOutput,
    ): Promise<void> => {
      const sessionID = output.message?.sessionID;
      if (!sessionID) return;

      if (output.message?.role === "user") {
        const promptText = textOfParts(output.parts).trim();
        if (promptText) {
          // Read the model and provider from this prompt's own hook input; no
          // cache, no system.transform handler. An absent or unreadable model
          // must not fail the prompt, so forward it only as a non-empty string
          // and let core omit the key (the worker's global fallback applies).
          const modelID = input.model?.modelID;
          const observerModel =
            typeof modelID === "string" && modelID.trim() ? modelID : undefined;
          // The provider id rides beside the model, never concatenated into it:
          // it selects a map entry in the session's endpoints, not a model name.
          const providerID = input.model?.providerID;
          const observerProvider =
            typeof providerID === "string" && providerID.trim() ? providerID.trim() : undefined;
          await core.captureUserPrompt(sessionID, promptText, observerModel, observerProvider);
          core.primeSemanticContext(sessionID, promptText);
        } else {
          core.forgetSemanticContext(sessionID);
        }
        return;
      }
      if (output.message?.role !== "assistant") return;

      await core.captureAssistantMessage(sessionID, textOfParts(output.parts));
    },

    // Summarize when a session compacts. This is OpenCode's real compaction
    // hook (the old `session.compacted` bus event never existed). Compaction
    // also drops the cached memory, so the next system prompt carries fresh
    // context; an idle summary keeps it.
    "experimental.session.compacting": async (
      input: SessionCompactingInput,
    ): Promise<void> => {
      core.forgetMemoryContext(input.sessionID);
      await core.captureSummary(input.sessionID);
    },

    // Inject memory context into the system prompt OpenCode builds for each
    // request: this project's own memory, current, rather than one global
    // AGENTS.md block shared by every project.
    "experimental.chat.system.transform": async (
      input: { sessionID?: string },
      output: { system: string[] },
    ): Promise<void> => {
      const context = await core.memoryContext(input.sessionID ?? "");
      if (context?.trim()) output.system.push(context);
      if (input.sessionID) {
        const semantic = (await core.semanticContext(input.sessionID))?.trim();
        if (semantic) output.system.push(semantic);
      }
    },

    // Generic bus events. Only `session.idle` and `session.deleted` are real
    // and acted upon (see REAL_OPENCODE_EVENT_TYPES).
    event: async ({ event }: { event: BusEvent }): Promise<void> => {
      const eventType = event?.type as RealOpenCodeEventType | undefined;
      const sessionID = event?.properties?.sessionID || event?.properties?.info?.id;
      if (!sessionID) return;

      switch (eventType) {
        case "session.idle": {
          // Best-effort summarize once a session goes idle. The platform
          // source must match the one session-init used, or the worker's
          // source-scoped session lookup misses and summarizes into a fresh,
          // mis-attributed session row (#3678).
          await core.captureSummary(sessionID);
          break;
        }
        case "session.deleted": {
          core.forgetSession(sessionID);
          break;
        }
        default:
          // Ignore all other bus events.
          break;
      }
    },

    tool: {
      claude_mem_search: {
        description:
          "Smart search (default), step 1: get a memory index. Review claude_mem_timeline, then fetch only selected IDs with claude_mem_get_observations.",
        args: {
          query: z.string().describe("Search query for memory observations"),
        },
        execute: async (args: Record<string, unknown>): Promise<string> =>
          core.search(String(args.query || "")),
      },
      claude_mem_timeline: {
        description: "Smart search, step 2: inspect context around an observation ID from claude_mem_search.",
        args: { anchor: z.number().int().describe("Observation ID from the memory index") },
        execute: async (args: Record<string, unknown>): Promise<string> => core.timeline(Number(args.anchor)),
      },
      claude_mem_get_observations: {
        description: "Smart search, step 3: fetch only IDs selected after reviewing the index and timeline. At most 100 ids per call; split larger selections.",
        args: { ids: z.array(z.number().int()).min(1).max(100).describe("Selected observation IDs (at most 100; split larger selections)") },
        execute: async (args: Record<string, unknown>): Promise<string> => core.getObservations(args.ids as number[]),
      },
    },
  };
}

export type OpenCodeV1Hooks = ReturnType<typeof createV1Hooks>;