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

11.9 KB
Raw Blame
import { spawnHidden } from '../../shared/spawn.js';
import { sanitizeEnv } from '../../supervisor/env-sanitizer.js';
import { existsSync } from 'fs';
import { join } from 'path';
import { styleText } from 'node:util';
import { ensureServerEmbedder, getBunPath, hasServerEmbedder } from '../install/setup-runtime.js';
import { npmPackageRootDirectory } from '../utils/paths.js';
import { SettingsDefaultsManager } from '../../shared/SettingsDefaultsManager.js';
import { resolvePluginRoot, buildWorkerUrl, withWorkerAuth } from '../../shared/worker-utils.js';
import { isConnectionRefusedError } from '../../shared/connection-errors.js';
import { BUN_NO_AUTO_INSTALL_FLAG } from '../../shared/bun-auto-install.js';

/**
 * The plugin root the worker spawns from — the shared resolveWorkerScript()
 * oracle (cache, marketplace, or dev checkout) — or exit(1) when none exists.
 * A cache-only install the hooks run from is therefore not "not installed".
 */
function pluginRootOrExit(): string {
  const resolved = resolvePluginRoot();
  if (!resolved) {
    console.error(styleText('red', 'claude-mem is not installed.'));
    console.error(`Run: ${styleText('bold', 'npx claude-mem install')}`);
    process.exit(1);
  }
  return resolved.root;
}

function resolveBunOrExit(): string {
  const bunPath = getBunPath();
  if (!bunPath) {
    console.error(styleText('red', 'Bun not found.'));
    console.error('Install Bun: https://bun.sh');
    console.error('After installation, restart your terminal.');
    process.exit(1);
  }
  return bunPath;
}

function workerServiceScriptPath(pluginRoot: string): string {
  return join(pluginRoot, 'scripts', 'worker-service.cjs');
}

function serverServiceScriptPath(pluginRoot: string): string {
  // Plan §1c line 149: prefer the renamed `server-service.cjs`, but fall
  // back to the legacy `server-beta-service.cjs` for installed plugin
  // caches that pre-date the rename (forced reinstall not required).
  const scriptsDir = join(pluginRoot, 'scripts');
  const renamed = join(scriptsDir, 'server-service.cjs');
  if (existsSync(renamed)) {
    return renamed;
  }
  return join(scriptsDir, 'server-beta-service.cjs');
}

function packagePluginScriptPath(scriptName: string): string {
  return join(npmPackageRootDirectory(), 'plugin', 'scripts', scriptName);
}

/**
 * Spawn a plugin .cjs script under Bun with inherited stdio, exiting this
 * process with the child's exit code. `args[0]` is the script path. Sanitizes
 * host CLI bleed-through and Anthropic credentials before launch; credentials
 * are re-read from ~/.claude-mem/.env at SDK spawn time (#2357 / #2375).
 * Bun's auto-install is off: the worker, server and transcript watcher can
 * load sharp, which auto-install resolves to a wasm build that freezes on its
 * first decode (#5601).
 */
function spawnPlugin(bunPath: string, args: string[], cwd: string, startFailureLabel = 'Bun'): void {
  const child = spawnHidden(bunPath, [BUN_NO_AUTO_INSTALL_FLAG, ...args], {
    stdio: 'inherit',
    cwd,
    env: sanitizeEnv(process.env),
  });

  child.on('error', (error) => {
    console.error(styleText('red', `Failed to start ${startFailureLabel}: ${error.message}`));
    process.exit(1);
  });

  child.on('close', (exitCode) => {
    process.exit(exitCode ?? 1);
  });
}

/** Use this CLI's matching worker bundle so a PR can be tested alongside an older installation. */
export function runHistoricalChatImportCommand(args: string[]): void {
  spawnPlugin(resolveBunOrExit(), [packagePluginScriptPath('worker-service.cjs'), 'import-chats', ...args], process.cwd());
}

function spawnBunWorkerCommand(command: string, extraArgs: string[] = []): void {
  const pluginRoot = pluginRootOrExit();
  const bunPath = resolveBunOrExit();
  const workerScript = workerServiceScriptPath(pluginRoot);

  if (!existsSync(workerScript)) {
    console.error(styleText('red', `Worker script not found at: ${workerScript}`));
    console.error('The installation may be corrupted. Try: npx claude-mem install');
    process.exit(1);
  }

  spawnPlugin(bunPath, [workerScript, command, ...extraArgs], pluginRoot);
}

function spawnBunServerCommand(command: string, extraArgs: string[] = []): void {
  const pluginRoot = pluginRootOrExit();
  const bunPath = resolveBunOrExit();
  const serverScript = serverServiceScriptPath(pluginRoot);

  if (!existsSync(serverScript)) {
    console.error(styleText('red', `Server script not found at: ${serverScript}`));
    console.error('The installation may be corrupted. Try: npx claude-mem install');
    process.exit(1);
  }

  spawnPlugin(bunPath, [serverScript, command, ...extraArgs], pluginRoot);
}

/**
 * Whether the server may search by meaning: CLAUDE_MEM_SERVER_VECTOR_SEARCH is
 * anything but 'false', read as the server reads it (vectorSearchMode).
 */
export function serverVectorSearchAllowed(): boolean {
  return SettingsDefaultsManager.get('CLAUDE_MEM_SERVER_VECTOR_SEARCH').toLowerCase() !== 'false';
}

/**
 * Start a server process, first installing the embedder the plugin install
 * leaves out (installPluginDependencies). Without it the server still runs,
 * searching by keyword only.
 */
async function spawnBunServerWithEmbedder(command: string, extraArgs: string[] = []): Promise<void> {
  const pluginRoot = pluginRootOrExit();
  const bunPath = resolveBunOrExit();
  // With search by meaning off, the server never loads the embedder, so the
  // install is skipped; the spawned server reads the same environment.
  if (!serverVectorSearchAllowed()) {
    spawnBunServerCommand(command, extraArgs);
    return;
  }
  try {
    if (!hasServerEmbedder(pluginRoot)) {
      console.error('Installing the embedder for search by meaning (about 300 MB, once)...');
    }
    await ensureServerEmbedder(pluginRoot, bunPath);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.error(styleText('yellow', `Could not install the embedder; the server will search by keyword only.\n${message}`));
  }
  spawnBunServerCommand(command, extraArgs);
}

export function runServerStartCommand(): void {
  void spawnBunServerWithEmbedder('start');
}

export function runServerStopCommand(): void {
  spawnBunServerCommand('stop');
}

export function runServerRestartCommand(): void {
  void spawnBunServerWithEmbedder('restart');
}

export function runServerStatusCommand(): void {
  spawnBunServerCommand('status');
}

// Phase 10 — start the BullMQ generation worker (no HTTP). Use this in
// Compose to scale generation horizontally while a single (or multiple)
// HTTP-only server replicas serve writes/reads.
export function runServerWorkerStartCommand(): void {
  void spawnBunServerWithEmbedder('worker', ['start']);
}

export function runStartCommand(): void {
  spawnBunWorkerCommand('start');
}

export function runStopCommand(): void {
  spawnBunWorkerCommand('stop');
}

export function runRestartCommand(): void {
  spawnBunWorkerCommand('restart');
}

export function runStatusCommand(): void {
  spawnBunWorkerCommand('status');
}

export function runServerApiKeyCommand(extraArgs: string[] = []): void {
  spawnBunWorkerCommand('server', ['api-key', ...extraArgs]);
}

export function runAdoptCommand(extraArgs: string[] = []): void {
  const pluginRoot = pluginRootOrExit();
  const bunPath = resolveBunOrExit();
  const workerScript = workerServiceScriptPath(pluginRoot);

  if (!existsSync(workerScript)) {
    console.error(styleText('red', `Worker script not found at: ${workerScript}`));
    console.error('The installation may be corrupted. Try: npx claude-mem install');
    process.exit(1);
  }

  const userCwd = process.cwd();
  spawnPlugin(bunPath, [workerScript, 'adopt', '--cwd', userCwd, ...extraArgs], pluginRoot);
}

export function runProjectCommand(extraArgs: string[] = []): void {
  spawnBunWorkerCommand('project', extraArgs);
}

export function runCleanupCommand(extraArgs: string[] = []): void {
  spawnBunWorkerCommand('cleanup', extraArgs);
}

export function runMcpCommand(): void {
  const mcpScript = packagePluginScriptPath('mcp-server.cjs');
  if (!existsSync(mcpScript)) {
    console.error(styleText('red', `MCP server script not found at: ${mcpScript}`));
    process.exit(1);
  }

  const child = spawnHidden(process.execPath, [mcpScript], {
    stdio: 'inherit',
    env: sanitizeEnv(process.env),
  });

  child.on('error', (error) => {
    console.error(styleText('red', `Failed to start MCP server: ${error.message}`));
    process.exit(1);
  });

  child.on('close', (exitCode) => {
    process.exit(exitCode ?? 1);
  });
}

export function runHookCommand(extraArgs: string[] = []): void {
  const workerScript = workerServiceScriptPath(pluginRootOrExit());
  if (!existsSync(workerScript)) {
    console.error(styleText('red', `Worker script not found at: ${workerScript}`));
    process.exit(1);
  }

  const bunPath = resolveBunOrExit();
  const child = spawnHidden(bunPath, [workerScript, 'hook', ...extraArgs], {
    stdio: 'inherit',
    cwd: process.cwd(),
    env: sanitizeEnv(process.env),
  });

  child.on('error', (error) => {
    console.error(styleText('red', `Failed to start Cursor hook forwarding: ${error.message}`));
    process.exit(1);
  });

  child.on('close', (exitCode) => {
    process.exit(exitCode ?? 1);
  });
}

export async function runSearchCommand(queryParts: string[]): Promise<void> {
  const query = queryParts.join(' ').trim();
  if (!query) {
    console.error(styleText('red', 'Usage: npx claude-mem search <query>'));
    process.exit(1);
  }

  const searchUrl = buildWorkerUrl(`/api/search?query=${encodeURIComponent(query)}`);

  let response: Response;
  try {
    response = await fetch(searchUrl, withWorkerAuth());
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : String(error);
    if (isConnectionRefusedError(error)) {
      console.error(styleText('red', 'Worker is not running.'));
      console.error(`Start it with: ${styleText('bold', 'npx claude-mem start')}`);
      process.exit(1);
    }
    console.error(styleText('red', `Search failed: ${message}`));
    process.exit(1);
  }

  if (!response.ok) {
    if (response.status === 404) {
      console.error(styleText('red', 'Search endpoint not found. Is the worker running?'));
      console.error(`Try: ${styleText('bold', 'npx claude-mem start')}`);
      process.exit(1);
    }
    console.error(styleText('red', `Search failed: HTTP ${response.status}`));
    process.exit(1);
  }

  let data: unknown;
  try {
    data = await response.json();
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : String(error);
    console.error(styleText('red', `Search failed: invalid JSON response (${message})`));
    process.exit(1);
  }

  // /api/search answers in the MCP tool shape: print its rendered text.
  const content = (data as { content?: unknown } | null)?.content;
  if (Array.isArray(content)) {
    console.log(content
      .filter((block): block is { type: 'text'; text: string } => block?.type === 'text' && typeof block.text === 'string')
      .map(block => block.text)
      .join('\n\n'));
    if ((data as { isError?: unknown }).isError === true) {
      process.exit(1);
    }
  } else if (typeof data === 'object' && data !== null) {
    console.log(JSON.stringify(data, null, 2));
  } else {
    console.log(data);
  }
}

export function runTranscriptWatchCommand(): void {
  const pluginRoot = pluginRootOrExit();
  const bunPath = resolveBunOrExit();

  const transcriptWatcherPath = join(pluginRoot, 'scripts', 'transcript-watcher.cjs');

  if (!existsSync(transcriptWatcherPath)) {
    spawnBunWorkerCommand('transcript', ['watch']);
    return;
  }

  spawnPlugin(bunPath, [transcriptWatcherPath, 'watch'], pluginRoot, 'transcript watcher');
}

// The worker script runs from the plugin root, so the directory the user ran
// this in travels as --cwd, as it does for adopt. Another checkout is chosen
// with --source, which resolves against this directory.
export function runMemoryIngestCommand(extraArgs: string[] = []): void {
  spawnBunWorkerCommand('memory', ['ingest', '--cwd', process.cwd(), ...extraArgs]);
}