Skip to content
Back to search

MoltBrain

Long-term memory layer for OpenClaw & MoltBook agents that learns and recalls your project context automatically.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/nhevers/MoltBrain with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/nhevers/MoltBrain'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/nhevers--moltbrain/badge.svg)](/listings/nhevers--moltbrain)

HTML

<a href="/listings/nhevers--moltbrain"><img src="/api/listings/nhevers--moltbrain/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

<p align="center">

╔══════════════════════════════════════════════════════════════════════╗
║                                                                      ║
║   Step 1    /plugin marketplace add nhevers/moltbrain                ║
║   Step 2    /plugin install moltbrain                                ║
║                                                                      ║
╚══════════════════════════════════════════════════════════════════════╝

</p>

<p align="center"><em>That's it. MoltBrain starts working automatically.</em></p>

---

<br>

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 18 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. {
  2. "name": "nhevers",
  3. "owner": {
  4. "name": "nhevers"
  5. },
  6. "metadata": {
  7. "description": "Plugins by nhevers",
  8. "homepage": "https://github.com/nhevers/claude-recall"
  9. },
  10. "plugins": [
  11. {
  12. "name": "claude-recall",
  13. "version": "9.0.9",
  14. "source": "./plugin",
  15. "description": "Persistent memory system for Claude Code - context compression across sessions"
  16. }
  17. ]
  18. }
README.md · README · 468 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <p align="center">
  2. <img width="1344" height="768" alt="Untitled design (32)" src="https://github.com/user-attachments/assets/03483342-0950-4d80-8bd2-423cd644b6ba" />
  3. </p>
  4. <p align="center">
  5. </p>
  6. <p align="center">
  7. <strong>Long-term memory layer for OpenClaw, MoltBook & Claude Code that learns and recalls your project context automatically.</strong>
  8. </p>
  9. <p align="center">
  10. <a href="#-quick-install">Install</a> •
  11. <a href="#-features">Features</a> •
  12. <a href="#-how-it-works">How It Works</a> •
  13. <a href="#-storage-dapp">Storage</a> •
  14. <a href="#-virtuals-protocol-integration">Virtuals</a> •
  15. <a href="#-openclaw-integration">OpenClaw</a> •
  16. <a href="#%EF%B8%8F-configuration">Config</a> •
  17. <a href="#-api">API</a>
  18. </p>
  19. ---
  20. <br>
  21. ## ⚡ Quick Install
  22. <p align="center">
  23. ```
  24. ╔══════════════════════════════════════════════════════════════════════╗
  25. ║ ║
  26. ║ Step 1 /plugin marketplace add nhevers/moltbrain ║
  27. ║ Step 2 /plugin install moltbrain ║
  28. ║ ║
  29. ╚══════════════════════════════════════════════════════════════════════╝
  30. ```
  31. </p>
  32. <p align="center"><em>That's it. MoltBrain starts working automatically.</em></p>
  33. ---
  34. <br>
  35. ## 🧠 What It Does
  36. ```
  37. ╭──────────────────────────────────────────────────────────────────────────────╮
  38. │ │
  39. │ ┌─────────────────┐ ┌─────────────────┐ │
  40. │ │ SESSION #1 │ │ SESSION #47 │ │
  41. │ │─────────────────│ │─────────────────│ │
  42. │ │ │ │ │ │
  43. │ │ "Set up auth │ │ "Add password │ │
  44. │ │ with OAuth" │ │ reset flow" │ │
  45. │ │ │ │ │ │
  46. │ └────────┬────────┘ └────────┬────────┘ │
  47. │ │ │ │
  48. │ │ Claude discovers: │ Claude remembers: │
  49. │ │ • OAuth2 + PKCE flow │ • Your auth setup │
  50. │ │ • JWT with 1hr expiry │ • Token structure │
  51. │ │ • bcrypt cost factor 12 │ • Security choices │
  52. │ │ │ │
  53. │ ▼ ▲ │
  54. │ ┌────────────────┐ ┌────────────────┐ │
  55. │ │ CAPTURE │ ──────────────────► │ INJECT │ │
  56. │ │ & LEARN │ MEMORY │ & RECALL │ │
  57. │ └────────────────┘ └────────────────┘ │
  58. │ │
  59. ╰──────────────────────────────────────────────────────────────────────────────╯
  60. ```
  61. <br>
  62. ---
  63. ## ✨ Features
  64. ```
  65. +-------------------------+-------------------------+-------------------------+
  66. | | | |
  67. | OBSERVATIONS | SMART SEARCH | WEB VIEWER |
  68. | ---------------- | ---------------- | ---------------- |
  69. | Auto-captures | Semantic search | Browse history |
  70. | discoveries, | via MCP tools | at localhost |
  71. | decisions & code | finds context | :37777 |
  72. | | | |
  73. +-------------------------+-------------------------+-------------------------+
  74. | | | |
  75. | ANALYTICS | TAGS & FILTERS | FAVORITES |
  76. | ---------------- | ---------------- | ---------------- |
  77. | Track tokens, | Organize with | Bookmark your |
  78. | sessions, and | custom tags & | most important |
  79. | concept trends | smart filters | observations |
  80. | | | |
  81. +-------------------------+-------------------------+-------------------------+
  82. | | | |
  83. | EXPORT | THEMES | SHORTCUTS |
  84. | ---------------- | ---------------- | ---------------- |
  85. | JSON, CSV, or | Dark & light | Full keyboard |
  86. | Markdown with | mode with | navigation in |
  87. | custom templates | custom themes | the web viewer |
  88. | | | |
  89. +-------------------------+-------------------------+-------------------------+
  90. ```
  91. <br>
  92. ---
  93. ## 🔧 How It Works
  94. ```
  95. ╔═══════════════════════════════════╗
  96. ║ CLAUDE CODE SESSION ║
  97. ╚═══════════════╤═══════════════════╝
  98. │
  99. ┌────────────────────┼────────────────────┐
  100. │ │ │
  101. ▼ ▼ ▼
  102. ╔════════════════╗ ╔════════════════╗ ╔════════════════╗
  103. ║ SessionStart ║ ║ PostToolUse ║ ║ Stop ║
  104. ║────────────────║ ║────────────────║ ║────────────────║
  105. ║ Inject context ║ ║ Capture output ║ ║ Generate ║
  106. ║ from memory ║ ║ extract facts ║ ║ summary ║
  107. ╚═══════╤════════╝ ╚═══════╤════════╝ ╚═══════╤════════╝
  108. │ │ │
  109. └────────────────────┼────────────────────┘
  110. │
  111. ╔══════════════╧══════════════╗
  112. ║ WORKER SERVICE ║
  113. ║ http://localhost:37777 ║
  114. ╚══════════════╤══════════════╝
  115. │
  116. ┌─────────────────────────┼─────────────────────────┐
  117. │ │ │
  118. ▼ ▼ ▼
  119. ╔════════════════╗ ╔════════════════╗ ╔════════════════╗
  120. ║ SQLite ║ ║ ChromaDB ║ ║ Web Viewer ║
  121. ║ Database ║ ║ Vector Search ║ ║ UI ║
  122. ║────────────────║ ║────────────────║ ║────────────────║
  123. ║ Observations ║ ║ Semantic ║ ║ Timeline ║
  124. ║ Summaries ║ ║ similarity ║ ║ Search ║
  125. ║ Sessions ║ ║ matching ║ ║ Analytics ║
  126. ╚════════════════╝ ╚════════════════╝ ╚════════════════╝
  127. ```
  128. <br>
  129. ---
  130. ## ⚙️ Configuration
  131. Settings stored in `~/.moltbrain/settings.json`:
  132. ```
  133. ┌──────────────────────────────────────┬─────────┬────────────────────────────┐
  134. │ SETTING │ DEFAULT │ DESCRIPTION │
  135. ├──────────────────────────────────────┼─────────┼────────────────────────────┤
  136. │ MOLTBRAIN_WORKER_PORT │ 37777 │ Worker service port │
  137. ├──────────────────────────────────────┼─────────┼────────────────────────────┤
  138. │ MOLTBRAIN_CONTEXT_OBSERVATIONS │ 50 │ Max observations to inject │
  139. ├──────────────────────────────────────┼─────────┼────────────────────────────┤
  140. │ MOLTBRAIN_PROVIDER │ claude │ AI provider for summaries │
  141. ├──────────────────────────────────────┼─────────┼────────────────────────────┤
  142. │ MOLTBRAIN_PRUNE_DAYS │ 0 │ Auto-prune (0 = disabled) │
  143. ├──────────────────────────────────────┼─────────┼────────────────────────────┤
  144. │ MOLTBRAIN_THEME │ system │ UI theme (dark/light/sys) │
  145. ├──────────────────────────────────────┼─────────┼────────────────────────────┤
  146. │ MOLTBRAIN_LOG_LEVEL │ info │ Logging verbosity level │
  147. └──────────────────────────────────────┴─────────┴────────────────────────────┘
  148. ```
  149. <br>
  150. ---
  151. ## 💻 CLI Commands
  152. ```bash
  153. moltbrain stats # Show memory statistics
  154. moltbrain export # Export to markdown
  155. moltbrain tag <id> <t> # Tag an observation
  156. moltbrain prune # Manual cleanup
  157. moltbrain search <q> # Search observations
  158. ```
  159. <br>
  160. ---
  161. ## 📁 Project Structure
  162. ```
  163. moltbrain/
  164. │
  165. ├── 📊 benchmarks/ Performance tests
  166. ├── 🎨 contrib/ Community modes & themes
  167. ├── 📚 docs/ Documentation
  168. ├── 📖 examples/ Usage examples & guides
  169. │
  170. ├── 🔌 extension/
  171. │ ├── profiles/ Observation modes
  172. │ ├── runtime/ Worker scripts
  173. │ ├── themes/ UI themes (dark/light)
  174. │ ├── snippets/ Code snippets
  175. │ └── templates/ Summary templates
  176. │
  177. ├── 🌍 locales/ i18n (en, es, fr)
  178. ├── 🗄️ migrations/ Database migrations
  179. ├── 📋 schemas/ JSON validation schemas
  180. ├── 🛠️ scripts/ Build & utility scripts
  181. │
  182. ├── 💻 src/
  183. │ ├── analytics/ Token & session tracking
  184. │ ├── cache/ Query & context caching
  185. │ ├── core/ Core engine
  186. │ ├── export/ JSON/CSV/MD exporters
  187. │ ├── favorites/ Bookmark system
  188. │ ├── filters/ Date/type/project filters
  189. │ ├── formatters/ Output formatters
  190. │ ├── mcp/ MCP server for OpenClaw & MoltBook
  191. │ ├── shortcuts/ Keyboard shortcuts
  192. │ ├── themes/ Theme system
  193. │ └── validators/ Input validation
  194. │
  195. ├── 🦞 integrations/
  196. │ └── clawd/ Clawd extension & skill
  197. │
  198. ├── 📝 templates/ Export templates
  199. ├── 🧪 tests/ Test suites
  200. └── 🔧 tools/ CLI utilities
  201. ```
  202. <br>
  203. ---
  204. ## 🔌 API
  205. The worker exposes a REST API at `http://localhost:37777`:
  206. ```bash
  207. # Health check
  208. curl http://localhost:37777/health
  209. # Search observations
  210. curl "http://localhost:37777/api/search?q=authentication"
  211. # Get timeline
  212. curl "http://localhost:37777/api/timeline?project=my-app&days=7"
  213. # Export data
  214. curl "http://localhost:37777/api/export?format=json" > backup.json
  215. # Get statistics
  216. curl "http://localhost:37777/api/stats"
  217. ```
  218. <br>
  219. ---
  220. ## 🗄️ Storage Dapp
  221. Persistent, Postgres-backed storage for agents and apps. Live at **[app.moltbrain.dev/storage](https://app.moltbrain.dev/storage)**.
  222. ```
  223. +-----------------------------------------------------------------------------+
  224. | |
  225. | BLOB STORAGE Content-addressed JSON blobs via SHA-256 |
  226. | ---------- Store and retrieve data by hash. $0.01 per request. |
  227. | |
  228. | MEMORY SLOTS Named key-value slots for agent state |
  229. | ---------- Allocate, write, read. Persistent across sessions. |
  230. | |
  231. | AGENT VAULT Per-wallet scoping with label badges |
  232. | ---------- Connect the same wallet your agents use. |
  233. | Browse, view, and delete what they stored. |
  234. | |
  235. +-----------------------------------------------------------------------------+
  236. ```
  237. All endpoints are paid via [x402](https://www.x402.org) micropayments ($0.01 USDC on Base). Data is scoped per wallet, backed by Postgres, and survives redeploys.
  238. Agents can tag stored data with a `label` (e.g. `"openclaw_session"`, `"virtuals_agent"`) so the vault shows what stored each item.
  239. ```bash
  240. # Store a blob
  241. curl -X POST https://app.moltbrain.dev/api/x402/store \
  242. -H "X-PAYMENT: <x402_header>" \
  243. -d '{"data": {"key": "value"}, "label": "my_agent"}'
  244. # List your blobs
  245. curl https://app.moltbrain.dev/api/x402/list/blobs \
  246. -H "X-PAYMENT: <x402_header>"
  247. # Full catalog
  248. curl https://app.moltbrain.dev/api/x402/catalog
  249. ```
  250. <br>
  251. ---
  252. ## 🎮 Virtuals Protocol Integration
  253. GAME SDK plugin that gives any [Virtuals Protocol](https://virtuals.io) AI agent persistent memory and storage via MoltBrain.
  254. ```bash
  255. npm install @moltbrain/game-plugin
  256. ```
  257. ```typescript
  258. import { GameAgent } from "@virtuals-protocol/game";
  259. import { MoltBrainPlugin } from "@moltbrain/game-plugin";
  260. const moltbrain = new MoltBrainPlugin({
  261. privateKey: process.env.AGENT_PRIVATE_KEY!, // wallet with USDC on Base
  262. });
  263. const agent = new GameAgent(process.env.GAME_API_KEY!, {
  264. name: "My Agent",
  265. goal: "Remember everything across sessions",
  266. description: "An agent with persistent memory via MoltBrain",
  267. workers: [moltbrain.getWorker()],
  268. });
  269. await agent.init();
  270. await agent.step({ verbose: true });
  271. ```
  272. 9 functions available: `moltbrain_chat`, `moltbrain_search`, `moltbrain_store`, `moltbrain_retrieve`, `moltbrain_allocate_slot`, `moltbrain_write_slot`, `moltbrain_read_slot`, `moltbrain_stats`, `moltbrain_capacity`.
  273. Everything the agent stores shows up in the vault dapp at [app.moltbrain.dev/storage](https://app.moltbrain.dev/storage). Connect the same wallet to browse it.
  274. See the full plugin repo: **[github.com/nhevers/Moltbrain-virtuals](https://github.com/nhevers/Moltbrain-virtuals)**
  275. <br>
  276. ---
  277. ## 🦞 OpenClaw Integration
  278. Works with [OpenClaw](https://github.com/openclaw/openclaw) (116k+ stars) - the popular personal AI assistant!
  279. ```
  280. +-----------------------------------------------------------------------------+
  281. | |
  282. | EXTENSION Add to OpenClaw's extensions/ folder |
  283. | ---------- Full lifecycle hooks integration |
  284. | |
  285. | SKILL Install as an OpenClaw skill |
  286. | ---------- recall_context, search_memories, save_memory tools |
  287. | |
  288. | MCP SERVER Protocol-based integration |
  289. | ---------- Works with any MCP-compatible client |
  290. | |
  291. +-----------------------------------------------------------------------------+
  292. ```
  293. **Quick setup:**
  294. ```bash
  295. # As OpenClaw extension
  296. cd ~/.openclaw/extensions
  297. git clone https://github.com/nhevers/moltbrain.git moltbrain
  298. cd moltbrain/integrations/openclaw
  299. npm install && npm run build
  300. # Enable the plugin (required for bundled installations)
  301. pnpm openclaw plugins enable moltbrain
  302. # Or via MCP
  303. npm run mcp:start
  304. ```
  305. **Note:** If installing as a bundled extension (in OpenClaw's `extensions/` directory), you must explicitly enable it: `pnpm openclaw plugins enable moltbrain`
  306. See [integrations/openclaw/README.md](integrations/openclaw/README.md) for full setup guide.
  307. <br>
  308. ---
  309. ## 📚 MoltBook Integration
  310. Works with [MoltBook](https://moltbook.com) - the social network for AI agents! Share memories, learn from other agents, and build collective knowledge.
  311. **Quick setup:**
  312. ```bash
  313. # Install MoltBook MCP integration
  314. npm install --save @moltbrain/moltbook-mcp
  315. # Configure in your MoltBrain settings
  316. {
  317. "MOLTBRAIN_MOLTBOOK_ENABLED": true,
  318. "MOLTBRAIN_MOLTBOOK_API_URL": "https://moltbook.com"
  319. }
  320. ```
  321. See [integrations/moltbook/README.md](integrations/moltbook/README.md) for full setup guide.
  322. <br>
  323. ---
  324. ## 💻 Claude Code Integration
  325. Works with Claude Code via the plugin marketplace:
  326. ```bash
  327. /plugin marketplace add nhevers/moltbrain
  328. /plugin install moltbrain
  329. ```
  330. <br>
  331. ---
  332. ## 📋 Requirements
  333. ```
  334. ╔══════════════════════════════════════╗
  335. ║ ║
  336. ║ • Node.js 18+ or Bun 1.0+ ║
  337. ║ • OpenClaw, MoltBook, or Claude Code ║
  338. ║ ║
  339. ╚══════════════════════════════════════╝
  340. ```
  341. <br>
  342. ---
  343. ## 📄 License
  344. AGPL-3.0
  345. ---
  346. <br>
  347. <p align="center">
  348. <sub>━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━</sub>
  349. </p>
  350. <p align="center">
  351. <strong>Built with care for the OpenClaw, MoltBook & Claude Code community</strong>
  352. </p>
  353. <p align="center">
  354. <a href="https://app.moltbrain.dev">App</a> •
  355. <a href="https://app.moltbrain.dev/storage">Storage Dapp</a> •
  356. <a href="https://github.com/nhevers/Moltbrain-virtuals">Virtuals Plugin</a> •
  357. <a href="https://www.x402.org">x402 Protocol</a>
  358. </p>
  359. <p align="center">
  360. <sub>━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━</sub>
  361. </p>
plugin/scripts/bun-wrapper.cjs · Bundled script · 68 lines · 1 finding marked
  1. #!/usr/bin/env node
  2. /**
  3. * Bun Wrapper - Finds bun executable and runs command
  4. *
  5. * This wrapper ensures bun can be found even when not in PATH.
  6. * Used by hooks when Claude Code's environment doesn't have bun in PATH.
  7. */
  8. const { spawnSync, execSync } = require('child_process');
  9. const { existsSync } = require('fs');
  10. const { join } = require('path');
  11. const { homedir } = require('os');
  12. const IS_WINDOWS = process.platform === 'win32';
  13. /**
  14. * Get the Bun executable path (from PATH or common install locations)
  15. */
  16. function getBunPath() {
  17. // Try PATH first
  18. try {
  19. const result = spawnSync('bun', ['--version'], {
  20. encoding: 'utf-8',
  21. stdio: ['pipe', 'pipe', 'pipe'],
  22. shell: IS_WINDOWS
  23. });
  24. if (result.status === 0) return 'bun';
  25. } catch {
  26. // Not in PATH
  27. }
  28. // Check common installation paths
  29. const bunPaths = IS_WINDOWS
  30. ? [join(homedir(), '.bun', 'bin', 'bun.exe')]
  31. : [join(homedir(), '.bun', 'bin', 'bun'), '/usr/local/bin/bun', '/opt/homebrew/bin/bun'];
  32. for (const bunPath of bunPaths) {
  33. if (existsSync(bunPath)) return bunPath;
  34. }
  35. return null;
  36. }
  37. // Get bun path and execute command
  38. const bunPath = getBunPath();
  39. if (!bunPath) {
  40. console.error('❌ Bun not found. Please install Bun:');
  41. if (IS_WINDOWS) {
  42. console.error(' powershell -c "irm bun.sh/install.ps1 | iex"');
  43. } else {
  44. console.error(' curl -fsSL https://bun.sh/install | bash');
  45. }
  46. process.exit(1);
  47. }
  48. // Get all arguments after the script name
  49. const args = process.argv.slice(2);
  50. // Quote bun path if it contains spaces (Windows)
  51. const bunCmd = IS_WINDOWS && bunPath.includes(' ') ? `"${bunPath}"` : bunPath;
  52. // Execute bun with the provided arguments
  53. const result = spawnSync(bunCmd, args, {
  54. stdio: 'inherit',
  55. shell: IS_WINDOWS
  56. });
  57. process.exit(result.status || 0);
plugin/scripts/smart-install.js · Bundled script · 438 lines · 2 findings marked
  1. #!/usr/bin/env node
  2. /**
  3. * Smart Install Script for claude-recall
  4. *
  5. * Ensures Bun runtime and uv (Python package manager) are installed
  6. * (auto-installs if missing) and handles dependency installation when needed.
  7. */
  8. import { existsSync, readFileSync, writeFileSync } from 'fs';
  9. import { execSync, spawnSync } from 'child_process';
  10. import { join } from 'path';
  11. import { homedir } from 'os';
  12. const ROOT = join(homedir(), '.claude', 'plugins', 'marketplaces', 'nhevers');
  13. const MARKER = join(ROOT, '.install-version');
  14. const IS_WINDOWS = process.platform === 'win32';
  15. /**
  16. * Check if Bun is installed and accessible
  17. */
  18. function isBunInstalled() {
  19. try {
  20. const result = spawnSync('bun', ['--version'], {
  21. encoding: 'utf-8',
  22. stdio: ['pipe', 'pipe', 'pipe'],
  23. shell: IS_WINDOWS
  24. });
  25. if (result.status === 0) return true;
  26. } catch {
  27. // PATH check failed, try common installation paths
  28. }
  29. // Check common installation paths (handles fresh installs before PATH reload)
  30. const bunPaths = IS_WINDOWS
  31. ? [join(homedir(), '.bun', 'bin', 'bun.exe')]
  32. : [join(homedir(), '.bun', 'bin', 'bun'), '/usr/local/bin/bun', '/opt/homebrew/bin/bun'];
  33. return bunPaths.some(existsSync);
  34. }
  35. /**
  36. * Get the Bun executable path (from PATH or common install locations)
  37. */
  38. function getBunPath() {
  39. // Try PATH first
  40. try {
  41. const result = spawnSync('bun', ['--version'], {
  42. encoding: 'utf-8',
  43. stdio: ['pipe', 'pipe', 'pipe'],
  44. shell: IS_WINDOWS
  45. });
  46. if (result.status === 0) return 'bun';
  47. } catch {
  48. // Not in PATH
  49. }
  50. // Check common installation paths
  51. const bunPaths = IS_WINDOWS
  52. ? [join(homedir(), '.bun', 'bin', 'bun.exe')]
  53. : [join(homedir(), '.bun', 'bin', 'bun'), '/usr/local/bin/bun', '/opt/homebrew/bin/bun'];
  54. for (const bunPath of bunPaths) {
  55. if (existsSync(bunPath)) return bunPath;
  56. }
  57. return null;
  58. }
  59. /**
  60. * Get Bun version if installed
  61. */
  62. function getBunVersion() {
  63. const bunPath = getBunPath();
  64. if (!bunPath) return null;
  65. try {
  66. const result = spawnSync(bunPath, ['--version'], {
  67. encoding: 'utf-8',
  68. stdio: ['pipe', 'pipe', 'pipe'],
  69. shell: IS_WINDOWS
  70. });
  71. return result.status === 0 ? result.stdout.trim() : null;
  72. } catch {
  73. return null;
  74. }
  75. }
  76. /**
  77. * Check if uv is installed and accessible
  78. */
  79. function isUvInstalled() {
  80. try {
  81. const result = spawnSync('uv', ['--version'], {
  82. encoding: 'utf-8',
  83. stdio: ['pipe', 'pipe', 'pipe'],
  84. shell: IS_WINDOWS
  85. });
  86. if (result.status === 0) return true;
  87. } catch {
  88. // PATH check failed, try common installation paths
  89. }
  90. // Check common installation paths (handles fresh installs before PATH reload)
  91. const uvPaths = IS_WINDOWS
  92. ? [join(homedir(), '.local', 'bin', 'uv.exe'), join(homedir(), '.cargo', 'bin', 'uv.exe')]
  93. : [join(homedir(), '.local', 'bin', 'uv'), join(homedir(), '.cargo', 'bin', 'uv'), '/usr/local/bin/uv', '/opt/homebrew/bin/uv'];
  94. return uvPaths.some(existsSync);
  95. }
  96. /**
  97. * Get uv version if installed
  98. */
  99. function getUvVersion() {
  100. try {
  101. const result = spawnSync('uv', ['--version'], {
  102. encoding: 'utf-8',
  103. stdio: ['pipe', 'pipe', 'pipe'],
  104. shell: IS_WINDOWS
  105. });
  106. return result.status === 0 ? result.stdout.trim() : null;
  107. } catch {
  108. return null;
  109. }
  110. }
  111. /**
  112. * Install Bun automatically based on platform
  113. */
  114. function installBun() {
  115. console.error('🔧 Bun not found. Installing Bun runtime...');
  116. try {
  117. if (IS_WINDOWS) {
  118. // Windows: Use PowerShell installer
  119. console.error(' Installing via PowerShell...');
  120. execSync('powershell -c "irm bun.sh/install.ps1 | iex"', {
  121. stdio: 'inherit',
  122. shell: true
  123. });
  124. } else {
  125. // Unix/macOS: Use curl installer
  126. console.error(' Installing via curl...');
  127. execSync('curl -fsSL https://bun.sh/install | bash', {
  128. stdio: 'inherit',
  129. shell: true
  130. });
  131. }
  132. // Verify installation
  133. if (isBunInstalled()) {
  134. const version = getBunVersion();
  135. console.error(`✅ Bun ${version} installed successfully`);
  136. return true;
  137. } else {
  138. // Bun may be installed but not in PATH yet for this session
  139. // Try common installation paths
  140. const bunPaths = IS_WINDOWS
  141. ? [join(homedir(), '.bun', 'bin', 'bun.exe')]
  142. : [join(homedir(), '.bun', 'bin', 'bun'), '/usr/local/bin/bun', '/opt/homebrew/bin/bun'];
  143. for (const bunPath of bunPaths) {
  144. if (existsSync(bunPath)) {
  145. console.error(`✅ Bun installed at ${bunPath}`);
  146. console.error('⚠️ Please restart your terminal or add Bun to PATH:');
  147. if (IS_WINDOWS) {
  148. console.error(` $env:Path += ";${join(homedir(), '.bun', 'bin')}"`);
  149. } else {
  150. console.error(` export PATH="$HOME/.bun/bin:$PATH"`);
  151. }
  152. return true;
  153. }
  154. }
  155. throw new Error('Bun installation completed but binary not found');
  156. }
  157. } catch (error) {
  158. console.error('❌ Failed to install Bun automatically');
  159. console.error(' Please install manually:');
  160. if (IS_WINDOWS) {
  161. console.error(' - winget install Oven-sh.Bun');
  162. console.error(' - Or: powershell -c "irm bun.sh/install.ps1 | iex"');
  163. } else {
  164. console.error(' - curl -fsSL https://bun.sh/install | bash');
  165. console.error(' - Or: brew install oven-sh/bun/bun');
  166. }
  167. console.error(' Then restart your terminal and try again.');
  168. throw error;
  169. }
  170. }
  171. /**
  172. * Install uv automatically based on platform
  173. */
  174. function installUv() {
  175. console.error('🐍 Installing uv for Python/Chroma support...');
  176. try {
  177. if (IS_WINDOWS) {
  178. // Windows: Use PowerShell installer
  179. console.error(' Installing via PowerShell...');
  180. execSync('powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"', {
  181. stdio: 'inherit',
  182. shell: true
  183. });
  184. } else {
  185. // Unix/macOS: Use curl installer
  186. console.error(' Installing via curl...');
  187. execSync('curl -LsSf https://astral.sh/uv/install.sh | sh', {
  188. stdio: 'inherit',
  189. shell: true
  190. });
  191. }
  192. // Verify installation
  193. if (isUvInstalled()) {
  194. const version = getUvVersion();
  195. console.error(`✅ uv ${version} installed successfully`);
  196. return true;
  197. } else {
  198. // uv may be installed but not in PATH yet for this session
  199. // Try common installation paths
  200. const uvPaths = IS_WINDOWS
  201. ? [join(homedir(), '.local', 'bin', 'uv.exe'), join(homedir(), '.cargo', 'bin', 'uv.exe')]
  202. : [join(homedir(), '.local', 'bin', 'uv'), join(homedir(), '.cargo', 'bin', 'uv'), '/usr/local/bin/uv', '/opt/homebrew/bin/uv'];
  203. for (const uvPath of uvPaths) {
  204. if (existsSync(uvPath)) {
  205. console.error(`✅ uv installed at ${uvPath}`);
  206. console.error('⚠️ Please restart your terminal or add uv to PATH:');
  207. if (IS_WINDOWS) {
  208. console.error(` $env:Path += ";${join(homedir(), '.local', 'bin')}"`);
  209. } else {
  210. console.error(` export PATH="$HOME/.local/bin:$PATH"`);
  211. }
  212. return true;
  213. }
  214. }
  215. throw new Error('uv installation completed but binary not found');
  216. }
  217. } catch (error) {
  218. console.error('❌ Failed to install uv automatically');
  219. console.error(' Please install manually:');
  220. if (IS_WINDOWS) {
  221. console.error(' - winget install astral-sh.uv');
  222. console.error(' - Or: powershell -c "irm https://astral.sh/uv/install.ps1 | iex"');
  223. } else {
  224. console.error(' - curl -LsSf https://astral.sh/uv/install.sh | sh');
  225. console.error(' - Or: brew install uv (macOS)');
  226. }
  227. console.error(' Then restart your terminal and try again.');
  228. throw error;
  229. }
  230. }
  231. /**
  232. * Add shell alias for claude-recall command
  233. */
  234. function installCLI() {
  235. const WORKER_CLI = join(ROOT, 'plugin', 'scripts', 'engine-runtime.cjs');
  236. const bunPath = getBunPath() || 'bun';
  237. const aliasLine = `alias claude-recall='${bunPath} "${WORKER_CLI}"'`;
  238. const markerPath = join(ROOT, '.cli-installed');
  239. // Skip if already installed
  240. if (existsSync(markerPath)) return;
  241. try {
  242. if (IS_WINDOWS) {
  243. // Windows: Add to PATH via PowerShell profile
  244. const profilePath = join(process.env.USERPROFILE || homedir(), 'Documents', 'PowerShell', 'Microsoft.PowerShell_profile.ps1');
  245. const profileDir = join(process.env.USERPROFILE || homedir(), 'Documents', 'PowerShell');
  246. const functionDef = `function claude-recall { & "${bunPath}" "${WORKER_CLI}" $args }\n`;
  247. if (!existsSync(profileDir)) {
  248. execSync(`mkdir "${profileDir}"`, { stdio: 'ignore', shell: true });
  249. }
  250. const existingContent = existsSync(profilePath) ? readFileSync(profilePath, 'utf-8') : '';
  251. if (!existingContent.includes('function claude-recall')) {
  252. writeFileSync(profilePath, existingContent + '\n' + functionDef);
  253. console.error(`✅ PowerShell function added to profile`);
  254. console.error(' Restart your terminal to use: claude-recall <command>');
  255. }
  256. } else {
  257. // Unix: Add alias to shell configs
  258. const shellConfigs = [
  259. join(homedir(), '.bashrc'),
  260. join(homedir(), '.zshrc')
  261. ];
  262. for (const config of shellConfigs) {
  263. if (existsSync(config)) {
  264. const content = readFileSync(config, 'utf-8');
  265. if (!content.includes('alias claude-recall=')) {
  266. writeFileSync(config, content + '\n' + aliasLine + '\n');
  267. console.error(`✅ Alias added to ${config}`);
  268. }
  269. }
  270. }
  271. console.error(' Restart your terminal to use: claude-recall <command>');
  272. }
  273. writeFileSync(markerPath, new Date().toISOString());
  274. } catch (error) {
  275. console.error(`⚠️ Could not add shell alias: ${error.message}`);
  276. console.error(` Use directly: ${bunPath} "${WORKER_CLI}" <command>`);
  277. }
  278. }
  279. /**
  280. * Check if dependencies need to be installed
  281. */
  282. function needsInstall() {
  283. if (!existsSync(join(ROOT, 'node_modules'))) return true;
  284. try {
  285. const pkg = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf-8'));
  286. const marker = JSON.parse(readFileSync(MARKER, 'utf-8'));
  287. return pkg.version !== marker.version || getBunVersion() !== marker.bun;
  288. } catch {
  289. return true;
  290. }
  291. }
  292. /**
  293. * Install dependencies using Bun with npm fallback
  294. *
  295. * Bun has issues with npm alias packages (e.g., string-width-cjs, strip-ansi-cjs)
  296. * that are defined in package-lock.json. When bun fails with 404 errors for these
  297. * packages, we fall back to npm which handles aliases correctly.
  298. */
  299. function installDeps() {
  300. const bunPath = getBunPath();
  301. if (!bunPath) {
  302. throw new Error('Bun executable not found');
  303. }
  304. console.error('📦 Installing dependencies with Bun...');
  305. // Quote path for Windows paths with spaces
  306. const bunCmd = IS_WINDOWS && bunPath.includes(' ') ? `"${bunPath}"` : bunPath;
  307. let bunSucceeded = false;
  308. try {
  309. execSync(`${bunCmd} install`, { cwd: ROOT, stdio: 'inherit', shell: IS_WINDOWS });
  310. bunSucceeded = true;
  311. } catch {
  312. // First attempt failed, try with force flag
  313. try {
  314. execSync(`${bunCmd} install --force`, { cwd: ROOT, stdio: 'inherit', shell: IS_WINDOWS });
  315. bunSucceeded = true;
  316. } catch {
  317. // Bun failed completely, will try npm fallback
  318. }
  319. }
  320. // Fallback to npm if bun failed (handles npm alias packages correctly)
  321. if (!bunSucceeded) {
  322. console.error('⚠️ Bun install failed, falling back to npm...');
  323. console.error(' (This can happen with npm alias packages like *-cjs)');
  324. try {
  325. execSync('npm install', { cwd: ROOT, stdio: 'inherit', shell: IS_WINDOWS });
  326. } catch (npmError) {
  327. throw new Error('Both bun and npm install failed: ' + npmError.message);
  328. }
  329. }
  330. // Write version marker
  331. const pkg = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf-8'));
  332. writeFileSync(MARKER, JSON.stringify({
  333. version: pkg.version,
  334. bun: getBunVersion(),
  335. uv: getUvVersion(),
  336. installedAt: new Date().toISOString()
  337. }));
  338. }
  339. // Main execution
  340. try {
  341. // Step 1: Ensure Bun is installed (REQUIRED)
  342. if (!isBunInstalled()) {
  343. installBun();
  344. // Re-check after installation
  345. if (!isBunInstalled()) {
  346. console.error('❌ Bun is required but not available in PATH');
  347. console.error(' Please restart your terminal after installation');
  348. process.exit(1);
  349. }
  350. }
  351. // Step 2: Ensure uv is installed (REQUIRED for vector search)
  352. if (!isUvInstalled()) {
  353. installUv();
  354. // Re-check after installation
  355. if (!isUvInstalled()) {
  356. console.error('❌ uv is required but not available in PATH');
  357. console.error(' Please restart your terminal after installation');
  358. process.exit(1);
  359. }
  360. }
  361. // Step 3: Install dependencies if needed
  362. if (needsInstall()) {
  363. const pkg = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf-8'));
  364. const newVersion = pkg.version;
  365. installDeps();
  366. console.error('✅ Dependencies installed');
  367. // Auto-restart worker to pick up new code
  368. const port = process.env.CLAUDE_RECALL_WORKER_PORT || 37777;
  369. console.error(`[claude-recall] Plugin updated to v${newVersion} - restarting worker...`);
  370. try {
  371. // Graceful shutdown via HTTP (curl is cross-platform enough)
  372. execSync(`curl -s -X POST http://127.0.0.1:${port}/api/admin/shutdown`, {
  373. stdio: 'ignore',
  374. shell: IS_WINDOWS,
  375. timeout: 5000
  376. });
  377. // Brief wait for port to free
  378. execSync(IS_WINDOWS ? 'timeout /t 1 /nobreak >nul' : 'sleep 0.5', {
  379. stdio: 'ignore',
  380. shell: true
  381. });
  382. } catch {
  383. // Worker wasn't running or already stopped - that's fine
  384. }
  385. // Worker will be started fresh by next hook in chain (engine-runtime.cjs start)
  386. }
  387. // Step 4: Install CLI to PATH
  388. installCLI();
  389. } catch (e) {
  390. console.error('❌ Installation failed:', e.message);
  391. process.exit(1);
  392. }
scripts/smart-install.js · Bundled script · 259 lines · 2 findings marked
  1. #!/usr/bin/env node
  2. /**
  3. * Smart Install Script for claude-recall
  4. *
  5. * Ensures Bun runtime and uv (Python package manager) are installed
  6. * (auto-installs if missing) and handles dependency installation when needed.
  7. */
  8. import { existsSync, readFileSync, writeFileSync } from 'fs';
  9. import { execSync, spawnSync } from 'child_process';
  10. import { join } from 'path';
  11. import { homedir } from 'os';
  12. const ROOT = join(homedir(), '.claude', 'plugins', 'marketplaces', 'nhevers');
  13. const MARKER = join(ROOT, '.install-version');
  14. const IS_WINDOWS = process.platform === 'win32';
  15. // Common installation paths (handles fresh installs before PATH reload)
  16. const BUN_COMMON_PATHS = IS_WINDOWS
  17. ? [join(homedir(), '.bun', 'bin', 'bun.exe')]
  18. : [join(homedir(), '.bun', 'bin', 'bun'), '/usr/local/bin/bun', '/opt/homebrew/bin/bun'];
  19. const UV_COMMON_PATHS = IS_WINDOWS
  20. ? [join(homedir(), '.local', 'bin', 'uv.exe'), join(homedir(), '.cargo', 'bin', 'uv.exe')]
  21. : [join(homedir(), '.local', 'bin', 'uv'), join(homedir(), '.cargo', 'bin', 'uv'), '/usr/local/bin/uv', '/opt/homebrew/bin/uv'];
  22. /**
  23. * Get the Bun executable path (from PATH or common install locations)
  24. */
  25. function getBunPath() {
  26. // Try PATH first
  27. try {
  28. const result = spawnSync('bun', ['--version'], {
  29. encoding: 'utf-8',
  30. stdio: ['pipe', 'pipe', 'pipe'],
  31. shell: IS_WINDOWS
  32. });
  33. if (result.status === 0) return 'bun';
  34. } catch {
  35. // Not in PATH
  36. }
  37. // Check common installation paths
  38. return BUN_COMMON_PATHS.find(existsSync) || null;
  39. }
  40. /**
  41. * Check if Bun is installed and accessible
  42. */
  43. function isBunInstalled() {
  44. return getBunPath() !== null;
  45. }
  46. /**
  47. * Get Bun version if installed
  48. */
  49. function getBunVersion() {
  50. const bunPath = getBunPath();
  51. if (!bunPath) return null;
  52. try {
  53. const result = spawnSync(bunPath, ['--version'], {
  54. encoding: 'utf-8',
  55. stdio: ['pipe', 'pipe', 'pipe'],
  56. shell: IS_WINDOWS
  57. });
  58. return result.status === 0 ? result.stdout.trim() : null;
  59. } catch {
  60. return null;
  61. }
  62. }
  63. /**
  64. * Get the uv executable path (from PATH or common install locations)
  65. */
  66. function getUvPath() {
  67. // Try PATH first
  68. try {
  69. const result = spawnSync('uv', ['--version'], {
  70. encoding: 'utf-8',
  71. stdio: ['pipe', 'pipe', 'pipe'],
  72. shell: IS_WINDOWS
  73. });
  74. if (result.status === 0) return 'uv';
  75. } catch {
  76. // Not in PATH
  77. }
  78. // Check common installation paths
  79. return UV_COMMON_PATHS.find(existsSync) || null;
  80. }
  81. /**
  82. * Check if uv is installed and accessible
  83. */
  84. function isUvInstalled() {
  85. return getUvPath() !== null;
  86. }
  87. /**
  88. * Get uv version if installed
  89. */
  90. function getUvVersion() {
  91. const uvPath = getUvPath();
  92. if (!uvPath) return null;
  93. try {
  94. const result = spawnSync(uvPath, ['--version'], {
  95. encoding: 'utf-8',
  96. stdio: ['pipe', 'pipe', 'pipe'],
  97. shell: IS_WINDOWS
  98. });
  99. return result.status === 0 ? result.stdout.trim() : null;
  100. } catch {
  101. return null;
  102. }
  103. }
  104. /**
  105. * Install Bun automatically based on platform
  106. */
  107. function installBun() {
  108. console.error('🔧 Bun not found. Installing Bun runtime...');
  109. try {
  110. if (IS_WINDOWS) {
  111. console.error(' Installing via PowerShell...');
  112. execSync('powershell -c "irm bun.sh/install.ps1 | iex"', {
  113. stdio: 'inherit',
  114. shell: true
  115. });
  116. } else {
  117. console.error(' Installing via curl...');
  118. execSync('curl -fsSL https://bun.sh/install | bash', {
  119. stdio: 'inherit',
  120. shell: true
  121. });
  122. }
  123. if (!isBunInstalled()) {
  124. throw new Error(
  125. 'Bun installation completed but binary not found. ' +
  126. 'Please restart your terminal and try again.'
  127. );
  128. }
  129. const version = getBunVersion();
  130. console.error(`✅ Bun ${version} installed successfully`);
  131. } catch (error) {
  132. console.error('❌ Failed to install Bun');
  133. console.error(' Please install manually:');
  134. if (IS_WINDOWS) {
  135. console.error(' - winget install Oven-sh.Bun');
  136. console.error(' - Or: powershell -c "irm bun.sh/install.ps1 | iex"');
  137. } else {
  138. console.error(' - curl -fsSL https://bun.sh/install | bash');
  139. console.error(' - Or: brew install oven-sh/bun/bun');
  140. }
  141. console.error(' Then restart your terminal and try again.');
  142. throw error;
  143. }
  144. }
  145. /**
  146. * Install uv automatically based on platform
  147. */
  148. function installUv() {
  149. console.error('🐍 Installing uv for Python/Chroma support...');
  150. try {
  151. if (IS_WINDOWS) {
  152. console.error(' Installing via PowerShell...');
  153. execSync('powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"', {
  154. stdio: 'inherit',
  155. shell: true
  156. });
  157. } else {
  158. console.error(' Installing via curl...');
  159. execSync('curl -LsSf https://astral.sh/uv/install.sh | sh', {
  160. stdio: 'inherit',
  161. shell: true
  162. });
  163. }
  164. if (!isUvInstalled()) {
  165. throw new Error(
  166. 'uv installation completed but binary not found. ' +
  167. 'Please restart your terminal and try again.'
  168. );
  169. }
  170. const version = getUvVersion();
  171. console.error(`✅ uv ${version} installed successfully`);
  172. } catch (error) {
  173. console.error('❌ Failed to install uv');
  174. console.error(' Please install manually:');
  175. if (IS_WINDOWS) {
  176. console.error(' - winget install astral-sh.uv');
  177. console.error(' - Or: powershell -c "irm https://astral.sh/uv/install.ps1 | iex"');
  178. } else {
  179. console.error(' - curl -LsSf https://astral.sh/uv/install.sh | sh');
  180. console.error(' - Or: brew install uv (macOS)');
  181. }
  182. console.error(' Then restart your terminal and try again.');
  183. throw error;
  184. }
  185. }
  186. /**
  187. * Check if dependencies need to be installed
  188. */
  189. function needsInstall() {
  190. if (!existsSync(join(ROOT, 'node_modules'))) return true;
  191. try {
  192. const pkg = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf-8'));
  193. const marker = JSON.parse(readFileSync(MARKER, 'utf-8'));
  194. return pkg.version !== marker.version || getBunVersion() !== marker.bun;
  195. } catch {
  196. return true;
  197. }
  198. }
  199. /**
  200. * Install dependencies using Bun
  201. */
  202. function installDeps() {
  203. const bunPath = getBunPath();
  204. if (!bunPath) {
  205. throw new Error('Bun executable not found');
  206. }
  207. console.error('📦 Installing dependencies with Bun...');
  208. // Quote path for Windows paths with spaces
  209. const bunCmd = IS_WINDOWS && bunPath.includes(' ') ? `"${bunPath}"` : bunPath;
  210. execSync(`${bunCmd} install`, { cwd: ROOT, stdio: 'inherit', shell: IS_WINDOWS });
  211. // Write version marker
  212. const pkg = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf-8'));
  213. writeFileSync(MARKER, JSON.stringify({
  214. version: pkg.version,
  215. bun: getBunVersion(),
  216. uv: getUvVersion(),
  217. installedAt: new Date().toISOString()
  218. }));
  219. }
  220. // Main execution
  221. try {
  222. if (!isBunInstalled()) installBun();
  223. if (!isUvInstalled()) installUv();
  224. if (needsInstall()) {
  225. installDeps();
  226. console.error('✅ Dependencies installed');
  227. }
  228. } catch (e) {
  229. console.error('❌ Installation failed:', e.message);
  230. process.exit(1);
  231. }

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.