crystalbrain-hermes 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ node_modules
2
+ .next
3
+ .env*.local
4
+ .vercel
5
+ next-env.d.ts
6
+ tsconfig.tsbuildinfo
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Cutover Consulting
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.4
2
+ Name: crystalbrain-hermes
3
+ Version: 0.1.0
4
+ Summary: CrystalBrain memory for Hermes Agent: recall before each turn, conversations saved, one memory per user.
5
+ Project-URL: Homepage, https://crystalbrain.ai/tools/hermes-agent-memory
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: Programming Language :: Python :: 3
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+
12
+ # CrystalBrain memory for Hermes Agent
13
+
14
+ A memory provider plugin that gives [Hermes Agent](https://github.com/NousResearch/hermes-agent) a long-term memory per
15
+ user, kept in [CrystalBrain](https://crystalbrain.ai).
16
+
17
+ - **Recall before each turn**: the user's message is searched in CrystalBrain and what fits (memories, document
18
+ passages) is added to that message. Hermes adds it to the copy sent to the model, never to the stored conversation.
19
+ - **Saved when the session ends**: the conversation (user and assistant text only) goes to CrystalBrain, which turns
20
+ it into memories (facts, preferences, decisions…) and refuses near-duplicates. A session with fewer than 2 real user
21
+ messages is not saved. Cron runs and subagents never save.
22
+ - **Two tools**: `crystalbrain_search` (another question than the current message) and `crystalbrain_save`
23
+ (save one thing now, when the user asks to remember it).
24
+ - **One memory per person**: on a messaging gateway (Telegram, Discord, Slack…), each Hermes user becomes the
25
+ CrystalBrain end user `hermes:<platform>:<user_id>`, created on its first save. On the CLI, the user named by
26
+ `CRYSTALBRAIN_USER`, or your own account's memory when it is unset.
27
+
28
+ Hermes' own `MEMORY.md` / `USER.md` stay active beside it; only one external provider can be active at a time.
29
+ Tested with Hermes Agent 0.19.0.
30
+
31
+ ## Install
32
+
33
+ You need a CrystalBrain API key: dashboard, Connections › API keys (the Free plan is enough to start).
34
+
35
+ **One command** (Linux, macOS, WSL; needs `python3`):
36
+
37
+ ```bash
38
+ curl -fsSL https://crystalbrain.ai/hermes/install.sh | bash
39
+ ```
40
+
41
+ **Or from PyPI**:
42
+
43
+ ```bash
44
+ pip install crystalbrain-hermes
45
+ crystalbrain-hermes install
46
+ ```
47
+
48
+ Both copy the plugin to `~/.hermes/plugins/crystalbrain/`, save the key in `~/.hermes/.env` and select the provider
49
+ (`memory.provider: crystalbrain`). For another profile, add `--profile <name>` (with the script:
50
+ `| bash -s -- --profile <name>`). Then restart Hermes and its gateway, and check with `hermes memory status`.
51
+
52
+ **By hand**: copy the three files of this folder (`__init__.py`, `plugin.yaml`, `README.md`, also served at
53
+ `https://crystalbrain.ai/hermes/crystalbrain/<file>`) to `$HERMES_HOME/plugins/crystalbrain/`, add
54
+ `CRYSTALBRAIN_API_KEY=…` to the profile's `.env`, and set in its `config.yaml`:
55
+
56
+ ```yaml
57
+ memory:
58
+ provider: crystalbrain
59
+ ```
60
+
61
+ Optional, in the same `.env`: `CRYSTALBRAIN_USER` (the CrystalBrain user for CLI sessions) and
62
+ `CRYSTALBRAIN_BASE_URL` (default `https://crystalbrain.ai`).
63
+
64
+ **Uninstall**: `crystalbrain-hermes uninstall` (or `curl -fsSL https://crystalbrain.ai/hermes/install.sh | bash -s -- uninstall`).
65
+ Hermes goes back to its built-in memory; what CrystalBrain saved stays in your dashboard.
66
+
67
+ ## What is sent to CrystalBrain
68
+
69
+ - Each non-trivial user message (as the search query), with the user ID above and the model name.
70
+ - At session end: the user and assistant messages as text. System prompts, tool calls and tool results are not sent.
71
+ Long conversations keep their last 50,000 characters.
72
+
73
+ ## Costs and limits
74
+
75
+ Each saved session is tidied by CrystalBrain's AI and counts against the workspace's monthly AI credit; each gateway
76
+ user counts as a tracked user (plan quota). CrystalBrain accepts at most 60 AI-written memories per user in 10 minutes.
77
+
78
+ The plugin uses the Python standard library only: nothing to install in Hermes' environment.
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["hatchling==1.27.0"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "crystalbrain-hermes"
7
+ version = "0.1.0"
8
+ description = "CrystalBrain memory for Hermes Agent: recall before each turn, conversations saved, one memory per user."
9
+ readme = "src/crystalbrain_hermes/plugin/README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ dependencies = []
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ ]
17
+
18
+ [project.urls]
19
+ Homepage = "https://crystalbrain.ai/tools/hermes-agent-memory"
20
+
21
+ [project.scripts]
22
+ crystalbrain-hermes = "crystalbrain_hermes.installer:main"
23
+
24
+ # For Hermes versions that discover pip-installed memory providers (not 0.19.0): select it with memory.provider: crystalbrain.
25
+ [project.entry-points."hermes_agent.memory_providers"]
26
+ crystalbrain = "crystalbrain_hermes.plugin:register"
27
+
28
+ [tool.hatch.build.targets.wheel]
29
+ packages = ["src/crystalbrain_hermes"]
@@ -0,0 +1,4 @@
1
+ """CrystalBrain memory provider for Hermes Agent: the plugin (crystalbrain_hermes.plugin, copied into a Hermes profile)
2
+ and its installer (crystalbrain_hermes.installer, the `crystalbrain-hermes` command)."""
3
+
4
+ __version__ = "0.1.0"
@@ -0,0 +1,134 @@
1
+ """Installs the CrystalBrain memory provider in a Hermes Agent profile, or removes it.
2
+
3
+ pip install crystalbrain-hermes && crystalbrain-hermes install [--profile NAME] [--key KEY]
4
+ crystalbrain-hermes uninstall [--profile NAME]
5
+ curl -fsSL https://crystalbrain.ai/hermes/install.sh | bash (the same file, run from the site)
6
+
7
+ Install: copies the plugin to <Hermes home>/plugins/crystalbrain/ (from this package, or downloaded from the site when
8
+ this file runs alone), writes CRYSTALBRAIN_API_KEY in <Hermes home>/.env (mode 600), and selects the provider with
9
+ `hermes config set memory.provider crystalbrain`. The key comes from --key, CRYSTALBRAIN_API_KEY, the .env already
10
+ there, or is asked once. Running it again updates the plugin and keeps the rest.
11
+ Hermes home: ~/.hermes/profiles/<NAME> with --profile, else $HERMES_HOME, else ~/.hermes.
12
+ Standard library only: the site serves this same file at /hermes/install.py.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import getpass
19
+ import os
20
+ import shutil
21
+ import subprocess
22
+ import sys
23
+ import urllib.request
24
+ from pathlib import Path
25
+
26
+ BASE_URL = os.environ.get("CRYSTALBRAIN_URL", "https://crystalbrain.ai").rstrip("/")
27
+ PLUGIN_NAME = "crystalbrain"
28
+ PLUGIN_FILES = ("__init__.py", "plugin.yaml", "README.md")
29
+ KEY_VAR = "CRYSTALBRAIN_API_KEY"
30
+
31
+
32
+ def hermes_home(profile: str | None) -> Path:
33
+ if profile:
34
+ return Path.home() / ".hermes" / "profiles" / profile
35
+ return Path(os.environ.get("HERMES_HOME") or Path.home() / ".hermes")
36
+
37
+
38
+ def packaged_plugin() -> Path | None:
39
+ """The plugin's folder in this package, or None when this file runs alone (from the site)."""
40
+ folder = Path(__file__).resolve().parent / "plugin"
41
+ return folder if (folder / "__init__.py").is_file() else None
42
+
43
+
44
+ def copy_plugin(dest: Path) -> None:
45
+ dest.mkdir(parents=True, exist_ok=True)
46
+ source = packaged_plugin()
47
+ for name in PLUGIN_FILES:
48
+ if source:
49
+ shutil.copyfile(source / name, dest / name)
50
+ else:
51
+ with urllib.request.urlopen(f"{BASE_URL}/hermes/{PLUGIN_NAME}/{name}", timeout=30) as response:
52
+ (dest / name).write_bytes(response.read())
53
+
54
+
55
+ def env_key(env_file: Path) -> str:
56
+ """The key already written in the profile's .env, or ""."""
57
+ if not env_file.is_file():
58
+ return ""
59
+ for line in env_file.read_text(encoding="utf-8").splitlines():
60
+ name, sep, value = line.partition("=")
61
+ if sep and name.strip() == KEY_VAR:
62
+ return value.strip().strip("'\"")
63
+ return ""
64
+
65
+
66
+ def write_env_key(env_file: Path, key: str) -> None:
67
+ """Sets the key in the .env, replacing an earlier value and keeping every other line; the file is made private."""
68
+ lines = env_file.read_text(encoding="utf-8").splitlines() if env_file.is_file() else []
69
+ kept = [line for line in lines if line.partition("=")[0].strip() != KEY_VAR]
70
+ kept.append(f"{KEY_VAR}={key}")
71
+ env_file.parent.mkdir(parents=True, exist_ok=True)
72
+ env_file.write_text("\n".join(kept) + "\n", encoding="utf-8")
73
+ env_file.chmod(0o600)
74
+
75
+
76
+ def ask_key() -> str:
77
+ print("Your CrystalBrain API key is in the dashboard, Connections › API keys (https://crystalbrain.ai).")
78
+ try:
79
+ return getpass.getpass("CrystalBrain API key: ").strip()
80
+ except (EOFError, KeyboardInterrupt):
81
+ return ""
82
+
83
+
84
+ def hermes(profile: str | None, *args: str) -> subprocess.CompletedProcess[str] | None:
85
+ """Runs the hermes command for the profile, or None when it is not on the PATH."""
86
+ command = shutil.which("hermes")
87
+ if not command:
88
+ return None
89
+ return subprocess.run([command, *(["-p", profile] if profile else []), *args], capture_output=True, text=True)
90
+
91
+
92
+ def install(profile: str | None, key: str | None) -> int:
93
+ home = hermes_home(profile)
94
+ if not home.is_dir():
95
+ print(f"No Hermes home at {home}: install Hermes Agent first, or name the profile with --profile.", file=sys.stderr)
96
+ return 1
97
+ env_file = home / ".env"
98
+ key = (key or os.environ.get(KEY_VAR) or env_key(env_file) or ask_key()).strip()
99
+ if not key:
100
+ print(f"No API key: pass --key, or set {KEY_VAR}.", file=sys.stderr)
101
+ return 1
102
+ copy_plugin(home / "plugins" / PLUGIN_NAME)
103
+ write_env_key(env_file, key)
104
+ print(f"Plugin copied to {home / 'plugins' / PLUGIN_NAME}, API key saved in {env_file}.")
105
+ result = hermes(profile, "config", "set", "memory.provider", PLUGIN_NAME)
106
+ if result is not None and result.returncode == 0:
107
+ print("Memory provider selected: crystalbrain.")
108
+ else:
109
+ print(f"Select the provider yourself: in {home / 'config.yaml'}, set memory: provider: crystalbrain.")
110
+ print("Restart Hermes (and its gateway) to use it. To check: hermes memory status")
111
+ return 0
112
+
113
+
114
+ def uninstall(profile: str | None) -> int:
115
+ home = hermes_home(profile)
116
+ shutil.rmtree(home / "plugins" / PLUGIN_NAME, ignore_errors=True)
117
+ current = hermes(profile, "config", "get", "memory.provider")
118
+ if current is not None and current.stdout.strip() == PLUGIN_NAME:
119
+ hermes(profile, "config", "unset", "memory.provider")
120
+ print(f"CrystalBrain plugin removed from {home}. Hermes' built-in memory stays on. {KEY_VAR} is left in {home / '.env'}.")
121
+ return 0
122
+
123
+
124
+ def main(argv: list[str] | None = None) -> int:
125
+ parser = argparse.ArgumentParser(prog="crystalbrain-hermes", description="CrystalBrain memory for Hermes Agent.")
126
+ parser.add_argument("action", nargs="?", choices=["install", "uninstall"], default="install")
127
+ parser.add_argument("--profile", help="the Hermes profile (default: the default profile)")
128
+ parser.add_argument("--key", help=f"the CrystalBrain API key (else {KEY_VAR}, the profile's .env, or asked)")
129
+ args = parser.parse_args(argv)
130
+ return install(args.profile, args.key) if args.action == "install" else uninstall(args.profile)
131
+
132
+
133
+ if __name__ == "__main__":
134
+ sys.exit(main())
@@ -0,0 +1,67 @@
1
+ # CrystalBrain memory for Hermes Agent
2
+
3
+ A memory provider plugin that gives [Hermes Agent](https://github.com/NousResearch/hermes-agent) a long-term memory per
4
+ user, kept in [CrystalBrain](https://crystalbrain.ai).
5
+
6
+ - **Recall before each turn**: the user's message is searched in CrystalBrain and what fits (memories, document
7
+ passages) is added to that message. Hermes adds it to the copy sent to the model, never to the stored conversation.
8
+ - **Saved when the session ends**: the conversation (user and assistant text only) goes to CrystalBrain, which turns
9
+ it into memories (facts, preferences, decisions…) and refuses near-duplicates. A session with fewer than 2 real user
10
+ messages is not saved. Cron runs and subagents never save.
11
+ - **Two tools**: `crystalbrain_search` (another question than the current message) and `crystalbrain_save`
12
+ (save one thing now, when the user asks to remember it).
13
+ - **One memory per person**: on a messaging gateway (Telegram, Discord, Slack…), each Hermes user becomes the
14
+ CrystalBrain end user `hermes:<platform>:<user_id>`, created on its first save. On the CLI, the user named by
15
+ `CRYSTALBRAIN_USER`, or your own account's memory when it is unset.
16
+
17
+ Hermes' own `MEMORY.md` / `USER.md` stay active beside it; only one external provider can be active at a time.
18
+ Tested with Hermes Agent 0.19.0.
19
+
20
+ ## Install
21
+
22
+ You need a CrystalBrain API key: dashboard, Connections › API keys (the Free plan is enough to start).
23
+
24
+ **One command** (Linux, macOS, WSL; needs `python3`):
25
+
26
+ ```bash
27
+ curl -fsSL https://crystalbrain.ai/hermes/install.sh | bash
28
+ ```
29
+
30
+ **Or from PyPI**:
31
+
32
+ ```bash
33
+ pip install crystalbrain-hermes
34
+ crystalbrain-hermes install
35
+ ```
36
+
37
+ Both copy the plugin to `~/.hermes/plugins/crystalbrain/`, save the key in `~/.hermes/.env` and select the provider
38
+ (`memory.provider: crystalbrain`). For another profile, add `--profile <name>` (with the script:
39
+ `| bash -s -- --profile <name>`). Then restart Hermes and its gateway, and check with `hermes memory status`.
40
+
41
+ **By hand**: copy the three files of this folder (`__init__.py`, `plugin.yaml`, `README.md`, also served at
42
+ `https://crystalbrain.ai/hermes/crystalbrain/<file>`) to `$HERMES_HOME/plugins/crystalbrain/`, add
43
+ `CRYSTALBRAIN_API_KEY=…` to the profile's `.env`, and set in its `config.yaml`:
44
+
45
+ ```yaml
46
+ memory:
47
+ provider: crystalbrain
48
+ ```
49
+
50
+ Optional, in the same `.env`: `CRYSTALBRAIN_USER` (the CrystalBrain user for CLI sessions) and
51
+ `CRYSTALBRAIN_BASE_URL` (default `https://crystalbrain.ai`).
52
+
53
+ **Uninstall**: `crystalbrain-hermes uninstall` (or `curl -fsSL https://crystalbrain.ai/hermes/install.sh | bash -s -- uninstall`).
54
+ Hermes goes back to its built-in memory; what CrystalBrain saved stays in your dashboard.
55
+
56
+ ## What is sent to CrystalBrain
57
+
58
+ - Each non-trivial user message (as the search query), with the user ID above and the model name.
59
+ - At session end: the user and assistant messages as text. System prompts, tool calls and tool results are not sent.
60
+ Long conversations keep their last 50,000 characters.
61
+
62
+ ## Costs and limits
63
+
64
+ Each saved session is tidied by CrystalBrain's AI and counts against the workspace's monthly AI credit; each gateway
65
+ user counts as a tracked user (plan quota). CrystalBrain accepts at most 60 AI-written memories per user in 10 minutes.
66
+
67
+ The plugin uses the Python standard library only: nothing to install in Hermes' environment.
@@ -0,0 +1,314 @@
1
+ """CrystalBrain memory provider for Hermes Agent.
2
+
3
+ Recall: before each turn, prefetch() searches CrystalBrain for the current user and returns its context block
4
+ (Hermes adds it to the API copy of the user's message, never to the stored transcript).
5
+ Save: when a session ends, on_session_end() sends the conversation (user and assistant text only, no tool calls or
6
+ tool results) to CrystalBrain, which structures it into memories. Two tools: crystalbrain_search, crystalbrain_save.
7
+ Users: a gateway user becomes the CrystalBrain end user "hermes:<platform>:<user_id>"; without one (CLI), the user
8
+ named by CRYSTALBRAIN_USER, or the account's own memory when it is unset.
9
+ Config: CRYSTALBRAIN_API_KEY (required), CRYSTALBRAIN_BASE_URL and CRYSTALBRAIN_USER (optional), all read from the
10
+ profile's scoped secrets (.env), so each Hermes profile has its own.
11
+ Standard library only: nothing to install in Hermes' Python environment. Installed by `crystalbrain-hermes install`
12
+ (PyPI package crystalbrain-hermes) or https://crystalbrain.ai/hermes/install.sh, into $HERMES_HOME/plugins/crystalbrain/.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import logging
19
+ import re
20
+ import urllib.error
21
+ import urllib.request
22
+ from datetime import datetime, timezone
23
+ from typing import Any
24
+
25
+ from agent.memory_provider import MemoryProvider
26
+ from agent.secret_scope import get_secret
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ DEFAULT_BASE_URL = "https://crystalbrain.ai"
31
+ APP = "hermes" # the calling app, as CrystalBrain logs it
32
+ SEARCH_TIMEOUT_S = 6 # Hermes stops waiting for an external prefetch after 8 s
33
+ SAVE_TIMEOUT_S = 60 # the server structures the conversation with an LLM before it answers
34
+ MIN_USER_MESSAGES = 2 # a session with fewer real user messages is not saved
35
+ SOURCE_TEXT_MAX = 50_000 # the API's limit on source_text
36
+ CONTENT_MAX = 2_000
37
+ NOTHING_FOUND = "No relevant memory found."
38
+
39
+ MEMORY_TYPES = [
40
+ "fact", "preference", "instruction", "goal", "episode", "learning", "decision",
41
+ "entity", "example", "procedure", "term", "constraint", "question",
42
+ ]
43
+
44
+ # Messages with nothing to remember or search for: empty, slash commands, bare acknowledgements and greetings.
45
+ _TRIVIAL = re.compile(
46
+ r"^(yes|no|ok|okay|sure|thanks|thank you|yep|nope|hi|hey|hello|continue|go ahead|done|next|"
47
+ r"oui|non|merci|bonjour|salut|d'accord|vas-y)[\s!?.,:;]*$",
48
+ re.IGNORECASE,
49
+ )
50
+
51
+
52
+ class CrystalBrainApiError(RuntimeError):
53
+ """An error answered by the CrystalBrain API (its code, e.g. RATE_LIMITED or MTU_QUOTA_REACHED, is in the message)."""
54
+
55
+
56
+ class Api:
57
+ """The two CrystalBrain REST calls the plugin makes (POST /api/v1/search and /api/v1/save)."""
58
+
59
+ def __init__(self, api_key: str, base_url: str, timeout: float):
60
+ self._api_key = api_key
61
+ self._base_url = base_url.rstrip("/")
62
+ self._timeout = timeout
63
+
64
+ def search(self, **body: Any) -> dict[str, Any]:
65
+ return self._post("/api/v1/search", body)
66
+
67
+ def save(self, **body: Any) -> dict[str, Any]:
68
+ return self._post("/api/v1/save", body)
69
+
70
+ def _post(self, path: str, body: dict[str, Any]) -> dict[str, Any]:
71
+ request = urllib.request.Request(
72
+ self._base_url + path,
73
+ data=json.dumps(body).encode(),
74
+ method="POST",
75
+ headers={
76
+ "Authorization": f"Bearer {self._api_key}",
77
+ "Content-Type": "application/json",
78
+ "Accept": "application/json",
79
+ "User-Agent": "crystalbrain-hermes",
80
+ },
81
+ )
82
+ try:
83
+ with urllib.request.urlopen(request, timeout=self._timeout) as response:
84
+ payload = json.loads(response.read().decode() or "null")
85
+ return payload if isinstance(payload, dict) else {}
86
+ except urllib.error.HTTPError as err:
87
+ try:
88
+ payload = json.loads(err.read().decode() or "null")
89
+ except ValueError:
90
+ payload = None
91
+ error = payload if isinstance(payload, dict) else {}
92
+ code = f" {error['code']}" if error.get("code") else ""
93
+ raise CrystalBrainApiError(f"CrystalBrain answered {err.code}{code}: {error.get('error') or err.reason}") from None
94
+
95
+
96
+ def is_trivial(text: str | None) -> bool:
97
+ stripped = (text or "").strip()
98
+ return not stripped or stripped.startswith("/") or bool(_TRIVIAL.match(stripped))
99
+
100
+
101
+ def end_user(platform: str, user_id: Any, configured: str) -> str | None:
102
+ """The CrystalBrain end user of this session: the gateway user, else the configured one, else None (the
103
+ account's own memory). CrystalBrain creates an unknown user on its first save, with this value as its ID."""
104
+ uid = str(user_id or "").strip()
105
+ if uid:
106
+ return f"hermes:{platform or 'gateway'}:{uid}"
107
+ return configured.strip() or None
108
+
109
+
110
+ def _text(content: Any) -> str:
111
+ """The text of an OpenAI-style message content: a string, or the text parts of a list."""
112
+ if isinstance(content, str):
113
+ return content.strip()
114
+ if isinstance(content, list):
115
+ parts = [p.get("text", "") for p in content if isinstance(p, dict) and p.get("type") == "text"]
116
+ return "\n".join(t for t in parts if t).strip()
117
+ return ""
118
+
119
+
120
+ def conversation(messages: list[dict[str, Any]]) -> tuple[list[str], str]:
121
+ """The user's messages, and the exchange as text ("User: …" / "Assistant: …"), user and assistant text only.
122
+ When it is longer than the API accepts, the end is kept."""
123
+ user_texts: list[str] = []
124
+ lines: list[str] = []
125
+ for m in messages or []:
126
+ role = m.get("role")
127
+ if role not in ("user", "assistant"):
128
+ continue
129
+ text = _text(m.get("content"))
130
+ if not text:
131
+ continue
132
+ if role == "user":
133
+ user_texts.append(text)
134
+ lines.append(f"{'User' if role == 'user' else 'Assistant'}: {text}")
135
+ transcript = "\n\n".join(lines)
136
+ if len(transcript) > SOURCE_TEXT_MAX:
137
+ marker = "[earlier messages cut]\n\n"
138
+ transcript = marker + transcript[-(SOURCE_TEXT_MAX - len(marker)):]
139
+ return user_texts, transcript
140
+
141
+
142
+ SEARCH_SCHEMA = {
143
+ "name": "crystalbrain_search",
144
+ "description": (
145
+ "Search the user's long-term memory in CrystalBrain: facts, preferences, standing instructions, decisions, "
146
+ "past outcomes, people. What fits the user's message is already added before each turn; call this for "
147
+ "another question or a specific past topic."
148
+ ),
149
+ "parameters": {
150
+ "type": "object",
151
+ "properties": {"query": {"type": "string", "description": "What to look for, in a short sentence"}},
152
+ "required": ["query"],
153
+ },
154
+ }
155
+
156
+ SAVE_SCHEMA = {
157
+ "name": "crystalbrain_save",
158
+ "description": (
159
+ "Save one durable thing about the user to CrystalBrain now: a fact, preference, standing instruction, "
160
+ "decision and its reason, goal, person. The whole conversation is also saved when the session ends, so "
161
+ "call this when the user asks you to remember something or when it must not wait. One idea per call."
162
+ ),
163
+ "parameters": {
164
+ "type": "object",
165
+ "properties": {
166
+ "type": {"type": "string", "enum": MEMORY_TYPES},
167
+ "title": {"type": "string", "description": "Short title, under 120 characters"},
168
+ "content": {"type": "string", "description": "The information itself, self-contained"},
169
+ },
170
+ "required": ["type", "title", "content"],
171
+ },
172
+ }
173
+
174
+
175
+ class CrystalBrainMemoryProvider(MemoryProvider):
176
+ """Long-term memory per user in CrystalBrain: recall before each turn, conversation saved at session end."""
177
+
178
+ def __init__(self) -> None:
179
+ self._search_client: Any = None
180
+ self._save_client: Any = None
181
+ self._user: str | None = None
182
+ self._session_id = ""
183
+ self._platform = ""
184
+ self._model = ""
185
+ self._writes = True
186
+
187
+ @property
188
+ def name(self) -> str:
189
+ return "crystalbrain"
190
+
191
+ def is_available(self) -> bool:
192
+ return bool(get_secret("CRYSTALBRAIN_API_KEY", ""))
193
+
194
+ def unavailable_reason(self) -> str:
195
+ return "Set CRYSTALBRAIN_API_KEY (CrystalBrain dashboard, Connections › API keys) in the profile's .env."
196
+
197
+ def get_config_schema(self) -> list[dict[str, Any]]:
198
+ return [
199
+ {
200
+ "key": "api_key",
201
+ "description": "CrystalBrain API key",
202
+ "secret": True,
203
+ "required": True,
204
+ "env_var": "CRYSTALBRAIN_API_KEY",
205
+ "url": "https://crystalbrain.ai",
206
+ },
207
+ ]
208
+
209
+ def initialize(self, session_id: str, **kwargs: Any) -> None:
210
+ api_key = get_secret("CRYSTALBRAIN_API_KEY", "") or ""
211
+ base_url = get_secret("CRYSTALBRAIN_BASE_URL", "") or DEFAULT_BASE_URL
212
+ self._search_client = Api(api_key, base_url, SEARCH_TIMEOUT_S)
213
+ self._save_client = Api(api_key, base_url, SAVE_TIMEOUT_S)
214
+ self._session_id = session_id
215
+ self._platform = str(kwargs.get("platform") or "")
216
+ self._user = end_user(self._platform, kwargs.get("user_id"), get_secret("CRYSTALBRAIN_USER", "") or "")
217
+ # Cron runs, subagents and flushes read memory but never write it (MemoryProvider.initialize).
218
+ self._writes = (kwargs.get("agent_context") or "primary") == "primary"
219
+
220
+ def system_prompt_block(self) -> str:
221
+ return (
222
+ "# CrystalBrain memory\n"
223
+ "The user's long-term memory is kept in CrystalBrain. What it knows that fits the user's message is "
224
+ "added to that message before each turn. Use crystalbrain_search for another question, and "
225
+ "crystalbrain_save when the user asks you to remember something. The conversation is saved when the "
226
+ "session ends."
227
+ )
228
+
229
+ def _who(self) -> dict[str, str]:
230
+ who: dict[str, str] = {"app": APP}
231
+ if self._user:
232
+ who["user"] = self._user
233
+ if self._model:
234
+ who["model"] = self._model
235
+ return who
236
+
237
+ def on_turn_start(self, turn_number: int, message: str, **kwargs: Any) -> None:
238
+ self._model = str(kwargs.get("model") or self._model)
239
+
240
+ def prefetch(self, query: str, *, session_id: str = "") -> str:
241
+ """Called once per turn, before the tool loop, in a thread Hermes stops waiting for after 8 s."""
242
+ if not self._search_client or is_trivial(query):
243
+ return ""
244
+ try:
245
+ result = self._search_client.search(query=query, **self._who())
246
+ except Exception as exc: # recall never breaks a turn
247
+ logger.warning("CrystalBrain search failed: %s", exc)
248
+ return ""
249
+ block = str(result.get("context_block") or "").strip()
250
+ if not block or block == NOTHING_FOUND or block.startswith("No memory for user"):
251
+ return ""
252
+ return block
253
+
254
+ def on_session_end(self, messages: list[dict[str, Any]]) -> None:
255
+ """Runs on Hermes' background worker at a real session boundary: the conversation goes to CrystalBrain,
256
+ which structures it (one episode plus separate memories) and refuses near-duplicates."""
257
+ if not self._save_client or not self._writes:
258
+ return
259
+ user_texts, transcript = conversation(messages)
260
+ if sum(1 for t in user_texts if not is_trivial(t)) < MIN_USER_MESSAGES:
261
+ return
262
+ day = datetime.now(timezone.utc).strftime("%Y-%m-%d")
263
+ where = f" on {self._platform}" if self._platform else ""
264
+ said = "\n".join(f"- {t}" for t in user_texts)
265
+ content = f"Conversation with the Hermes agent{where} on {day}. What the user said:\n{said}"
266
+ if len(content) > CONTENT_MAX:
267
+ content = content[: CONTENT_MAX - 1] + "…"
268
+ try:
269
+ self._save_client.save(
270
+ type="episode",
271
+ title=f"Conversation with Hermes{where}, {day}",
272
+ content=content,
273
+ source_text=transcript,
274
+ source_ref=f"hermes:{self._session_id}",
275
+ **self._who(),
276
+ )
277
+ except Exception as exc:
278
+ logger.warning("CrystalBrain could not save the session: %s", exc)
279
+
280
+ def on_session_switch(self, new_session_id: str, **kwargs: Any) -> None:
281
+ self._session_id = new_session_id
282
+
283
+ def get_tool_schemas(self) -> list[dict[str, Any]]:
284
+ return [SEARCH_SCHEMA, SAVE_SCHEMA]
285
+
286
+ def handle_tool_call(self, tool_name: str, args: dict[str, Any], **kwargs: Any) -> str:
287
+ if not self._search_client:
288
+ return json.dumps({"error": "CrystalBrain is not initialized"})
289
+ try:
290
+ if tool_name == "crystalbrain_search":
291
+ if not str(args.get("query") or "").strip():
292
+ return json.dumps({"error": "query is required"})
293
+ result = self._search_client.search(query=str(args["query"]), **self._who())
294
+ return json.dumps({"context_block": result.get("context_block"), "entries": result.get("entries", [])})
295
+ if tool_name == "crystalbrain_save":
296
+ missing = [k for k in ("type", "title", "content") if not str(args.get(k) or "").strip()]
297
+ if missing:
298
+ return json.dumps({"error": f"{', '.join(missing)} required"})
299
+ result = self._save_client.save(
300
+ type=str(args["type"]),
301
+ title=str(args["title"])[:120],
302
+ content=str(args["content"]),
303
+ source_ref=f"hermes:{self._session_id}",
304
+ **self._who(),
305
+ )
306
+ return json.dumps(result)
307
+ return json.dumps({"error": f"Unknown tool: {tool_name}"})
308
+ except Exception as exc:
309
+ return json.dumps({"error": str(exc)})
310
+
311
+
312
+ def register(ctx: Any) -> None:
313
+ """Called by Hermes' memory plugin discovery."""
314
+ ctx.register_memory_provider(CrystalBrainMemoryProvider())
@@ -0,0 +1,9 @@
1
+ name: crystalbrain
2
+ version: 0.1.0
3
+ description: "CrystalBrain — long-term memory per user: recall before each turn, conversation saved when the session ends."
4
+ requires_env:
5
+ - CRYSTALBRAIN_API_KEY
6
+ hooks:
7
+ - on_turn_start
8
+ - on_session_end
9
+ - on_session_switch
@@ -0,0 +1,259 @@
1
+ """Tests of the Hermes provider with fake CrystalBrain clients: no network, no Hermes needed (the two Hermes modules
2
+ it imports are stubbed when Hermes is not installed).
3
+ Run from the repo root: python3 -m unittest discover integrations/hermes/tests"""
4
+
5
+ import importlib.util
6
+ import json
7
+ import os
8
+ import sys
9
+ import types
10
+ import unittest
11
+ from abc import ABC
12
+ from pathlib import Path
13
+ from unittest import mock
14
+
15
+ try:
16
+ import agent.memory_provider # noqa: F401 (real Hermes installed)
17
+ except ImportError:
18
+ hermes_agent = types.ModuleType("agent")
19
+ provider_module = types.ModuleType("agent.memory_provider")
20
+ secret_module = types.ModuleType("agent.secret_scope")
21
+ provider_module.MemoryProvider = type("MemoryProvider", (ABC,), {})
22
+ secret_module.get_secret = lambda name, default=None: os.environ.get(name, default)
23
+ sys.modules.update({"agent": hermes_agent, "agent.memory_provider": provider_module, "agent.secret_scope": secret_module})
24
+
25
+ # Loaded from its file, as Hermes loads a plugin folder (as _hermes_user_memory.crystalbrain).
26
+ _PLUGIN = Path(__file__).parents[1] / "src" / "crystalbrain_hermes" / "plugin" / "__init__.py"
27
+ _spec = importlib.util.spec_from_file_location("crystalbrain_hermes_plugin", _PLUGIN)
28
+ plugin = importlib.util.module_from_spec(_spec)
29
+ _spec.loader.exec_module(plugin)
30
+
31
+
32
+ class FakeClient:
33
+ def __init__(self, search_result=None, fail=False):
34
+ self.search_result = search_result if search_result is not None else {"context_block": "", "entries": []}
35
+ self.fail = fail
36
+ self.searches, self.saves = [], []
37
+
38
+ def search(self, **body):
39
+ if self.fail:
40
+ raise RuntimeError("network down")
41
+ self.searches.append(body)
42
+ return self.search_result
43
+
44
+ def save(self, **body):
45
+ if self.fail:
46
+ raise RuntimeError("network down")
47
+ self.saves.append(body)
48
+ return {"saved": True, "id": "m1"}
49
+
50
+
51
+ def provider(client=None, user="hermes:telegram:42", platform="telegram", writes=True):
52
+ p = plugin.CrystalBrainMemoryProvider()
53
+ p._search_client = p._save_client = client or FakeClient()
54
+ p._user, p._platform, p._session_id, p._writes = user, platform, "s1", writes
55
+ return p
56
+
57
+
58
+ def exchange(*user_texts):
59
+ messages = [{"role": "system", "content": "You are Hermes."}]
60
+ for text in user_texts:
61
+ messages += [{"role": "user", "content": text}, {"role": "assistant", "content": f"answer to {text}"}]
62
+ return messages
63
+
64
+
65
+ class EndUserTest(unittest.TestCase):
66
+ def test_gateway_user_is_namespaced_by_platform(self):
67
+ self.assertEqual(plugin.end_user("telegram", 12345, ""), "hermes:telegram:12345")
68
+ self.assertEqual(plugin.end_user("", "abc", "me"), "hermes:gateway:abc")
69
+
70
+ def test_without_gateway_user_the_configured_one_then_the_account(self):
71
+ self.assertEqual(plugin.end_user("cli", None, " Michel "), "Michel")
72
+ self.assertIsNone(plugin.end_user("cli", "", ""))
73
+
74
+
75
+ class ConversationTest(unittest.TestCase):
76
+ def test_keeps_user_and_assistant_text_only(self):
77
+ messages = [
78
+ {"role": "system", "content": "secret system prompt"},
79
+ {"role": "user", "content": [{"type": "text", "text": "Plan my trip"}, {"type": "image_url", "image_url": {}}]},
80
+ {"role": "assistant", "content": None, "tool_calls": [{"id": "t1"}]},
81
+ {"role": "tool", "content": "raw tool output"},
82
+ {"role": "assistant", "content": "Here is a plan."},
83
+ ]
84
+ users, transcript = plugin.conversation(messages)
85
+ self.assertEqual(users, ["Plan my trip"])
86
+ self.assertEqual(transcript, "User: Plan my trip\n\nAssistant: Here is a plan.")
87
+
88
+ def test_a_long_exchange_keeps_its_end(self):
89
+ users, transcript = plugin.conversation(exchange("a" * 30_000, "b" * 30_000))
90
+ self.assertEqual(len(transcript), plugin.SOURCE_TEXT_MAX)
91
+ self.assertTrue(transcript.startswith("[earlier messages cut]"))
92
+ self.assertTrue(transcript.endswith("Assistant: answer to " + "b" * 30_000))
93
+
94
+
95
+ class TrivialTest(unittest.TestCase):
96
+ def test_trivial_messages(self):
97
+ for text in ["", " ", "/new", "ok", "Merci !", "thanks", "d'accord."]:
98
+ self.assertTrue(plugin.is_trivial(text), text)
99
+ for text in ["ok so what about Lisbon?", "Remember I prefer trains", "note"]:
100
+ self.assertFalse(plugin.is_trivial(text), text)
101
+
102
+
103
+ class PrefetchTest(unittest.TestCase):
104
+ def test_returns_the_context_block_for_the_user(self):
105
+ client = FakeClient({"context_block": "Stored notes below…\n- [preference] (Travel) Prefers trains", "entries": [{"id": "m"}]})
106
+ p = provider(client)
107
+ p._model = "some-model"
108
+ self.assertEqual(p.prefetch("Plan a trip to Lisbon"), "Stored notes below…\n- [preference] (Travel) Prefers trains")
109
+ self.assertEqual(client.searches, [{"query": "Plan a trip to Lisbon", "app": "hermes", "user": "hermes:telegram:42", "model": "some-model"}])
110
+
111
+ def test_nothing_found_injects_nothing(self):
112
+ self.assertEqual(provider(FakeClient({"context_block": "No relevant memory found.", "entries": []})).prefetch("Plan a trip"), "")
113
+ self.assertEqual(provider(FakeClient({"context_block": 'No memory for user "x" yet.', "entries": []})).prefetch("Plan a trip"), "")
114
+
115
+ def test_trivial_messages_are_not_searched(self):
116
+ client = FakeClient()
117
+ provider(client).prefetch("ok")
118
+ self.assertEqual(client.searches, [])
119
+
120
+ def test_a_failure_never_breaks_the_turn(self):
121
+ self.assertEqual(provider(FakeClient(fail=True)).prefetch("Plan a trip"), "")
122
+
123
+ def test_without_user_the_account_memory_is_searched(self):
124
+ client = FakeClient()
125
+ provider(client, user=None).prefetch("Plan a trip")
126
+ self.assertNotIn("user", client.searches[0])
127
+
128
+
129
+ class SessionEndTest(unittest.TestCase):
130
+ def test_saves_the_conversation_as_one_episode_with_its_source_text(self):
131
+ client = FakeClient()
132
+ provider(client).on_session_end(exchange("I moved to Lyon", "Find me a climbing gym"))
133
+ self.assertEqual(len(client.saves), 1)
134
+ body = client.saves[0]
135
+ self.assertEqual(body["type"], "episode")
136
+ self.assertEqual(body["user"], "hermes:telegram:42")
137
+ self.assertEqual(body["app"], "hermes")
138
+ self.assertEqual(body["source_ref"], "hermes:s1")
139
+ self.assertIn("- I moved to Lyon\n- Find me a climbing gym", body["content"])
140
+ self.assertTrue(body["title"].startswith("Conversation with Hermes on telegram, "))
141
+ self.assertTrue(body["source_text"].startswith("User: I moved to Lyon\n\nAssistant: answer to I moved to Lyon"))
142
+ self.assertLessEqual(len(body["title"]), 120)
143
+
144
+ def test_a_short_session_is_not_saved(self):
145
+ client = FakeClient()
146
+ provider(client).on_session_end(exchange("hi", "What time is it?", "thanks"))
147
+ self.assertEqual(client.saves, [])
148
+
149
+ def test_cron_and_subagent_sessions_are_not_saved(self):
150
+ client = FakeClient()
151
+ provider(client, writes=False).on_session_end(exchange("I moved to Lyon", "Find me a climbing gym"))
152
+ self.assertEqual(client.saves, [])
153
+
154
+ def test_long_content_is_cut(self):
155
+ client = FakeClient()
156
+ provider(client).on_session_end(exchange("x" * 3_000, "y" * 3_000))
157
+ self.assertEqual(len(client.saves[0]["content"]), plugin.CONTENT_MAX)
158
+
159
+ def test_a_failure_is_logged_not_raised(self):
160
+ with self.assertLogs(plugin.logger, level="WARNING"):
161
+ provider(FakeClient(fail=True)).on_session_end(exchange("I moved to Lyon", "Find me a climbing gym"))
162
+
163
+
164
+ class ToolsTest(unittest.TestCase):
165
+ def test_schemas(self):
166
+ names = [s["name"] for s in provider().get_tool_schemas()]
167
+ self.assertEqual(names, ["crystalbrain_search", "crystalbrain_save"])
168
+
169
+ def test_search_tool(self):
170
+ client = FakeClient({"context_block": "block", "entries": [{"id": "m"}]})
171
+ answer = json.loads(provider(client).handle_tool_call("crystalbrain_search", {"query": "trains"}))
172
+ self.assertEqual(answer, {"context_block": "block", "entries": [{"id": "m"}]})
173
+
174
+ def test_save_tool(self):
175
+ client = FakeClient()
176
+ answer = json.loads(provider(client).handle_tool_call("crystalbrain_save", {"type": "preference", "title": "Trains", "content": "Prefers trains"}))
177
+ self.assertEqual(answer["saved"], True)
178
+ self.assertEqual(client.saves[0]["type"], "preference")
179
+ self.assertEqual(client.saves[0]["user"], "hermes:telegram:42")
180
+
181
+ def test_missing_arguments_and_unknown_tool(self):
182
+ p = provider()
183
+ self.assertIn("error", json.loads(p.handle_tool_call("crystalbrain_search", {"query": " "})))
184
+ self.assertIn("title", json.loads(p.handle_tool_call("crystalbrain_save", {"type": "fact", "content": "x"}))["error"])
185
+ self.assertIn("error", json.loads(p.handle_tool_call("other_tool", {})))
186
+
187
+ def test_errors_come_back_as_json(self):
188
+ answer = json.loads(provider(FakeClient(fail=True)).handle_tool_call("crystalbrain_search", {"query": "trains"}))
189
+ self.assertEqual(answer, {"error": "network down"})
190
+
191
+
192
+ class FakeResponse:
193
+ def __init__(self, body):
194
+ self.body = body
195
+
196
+ def read(self):
197
+ return self.body
198
+
199
+ def __enter__(self):
200
+ return self
201
+
202
+ def __exit__(self, *exc):
203
+ return False
204
+
205
+
206
+ class ApiTest(unittest.TestCase):
207
+ def test_posts_json_with_the_key(self):
208
+ sent = {}
209
+
210
+ def urlopen(request, timeout):
211
+ sent.update(url=request.full_url, method=request.get_method(), headers=dict(request.header_items()),
212
+ body=json.loads(request.data), timeout=timeout)
213
+ return FakeResponse(b'{"context_block": "block", "entries": []}')
214
+
215
+ with mock.patch.object(plugin.urllib.request, "urlopen", urlopen):
216
+ result = plugin.Api("cb_key", "https://example.test/", 6).search(query="trains", user="u")
217
+ self.assertEqual(result, {"context_block": "block", "entries": []})
218
+ self.assertEqual(sent["url"], "https://example.test/api/v1/search")
219
+ self.assertEqual(sent["method"], "POST")
220
+ self.assertEqual(sent["headers"]["Authorization"], "Bearer cb_key")
221
+ self.assertEqual(sent["body"], {"query": "trains", "user": "u"})
222
+ self.assertEqual(sent["timeout"], 6)
223
+
224
+ def test_an_api_error_carries_its_code_and_message(self):
225
+ error = plugin.urllib.error.HTTPError("https://example.test/api/v1/save", 429, "Too Many Requests", {}, None)
226
+ error.read = lambda: b'{"code": "RATE_LIMITED", "error": "Too many saves"}'
227
+
228
+ def urlopen(request, timeout):
229
+ raise error
230
+
231
+ with mock.patch.object(plugin.urllib.request, "urlopen", urlopen):
232
+ with self.assertRaises(plugin.CrystalBrainApiError) as ctx:
233
+ plugin.Api("cb_key", "https://example.test", 60).save(type="fact", title="t", content="c")
234
+ self.assertEqual(str(ctx.exception), "CrystalBrain answered 429 RATE_LIMITED: Too many saves")
235
+
236
+
237
+ class InitializeTest(unittest.TestCase):
238
+ def test_binds_user_session_and_write_scope(self):
239
+ env = {"CRYSTALBRAIN_API_KEY": "cb_test", "CRYSTALBRAIN_USER": ""}
240
+ with mock.patch.dict(os.environ, env), mock.patch.object(plugin, "get_secret", lambda n, d=None: os.environ.get(n, d)):
241
+ p = plugin.CrystalBrainMemoryProvider()
242
+ self.assertTrue(p.is_available())
243
+ p.initialize("s9", hermes_home="/tmp/h", platform="discord", user_id="77", agent_context="cron")
244
+ self.assertEqual(p._user, "hermes:discord:77")
245
+ self.assertIsInstance(p._search_client, plugin.Api)
246
+ self.assertEqual(p._session_id, "s9")
247
+ self.assertFalse(p._writes)
248
+ p.on_session_switch("s10", reset=True)
249
+ self.assertEqual(p._session_id, "s10")
250
+
251
+ def test_unavailable_without_key(self):
252
+ with mock.patch.object(plugin, "get_secret", lambda n, d=None: d):
253
+ p = plugin.CrystalBrainMemoryProvider()
254
+ self.assertFalse(p.is_available())
255
+ self.assertIn("CRYSTALBRAIN_API_KEY", p.unavailable_reason())
256
+
257
+
258
+ if __name__ == "__main__":
259
+ unittest.main()
@@ -0,0 +1,133 @@
1
+ """Tests of the installer (crystalbrain-hermes install / uninstall) on a temporary Hermes home, with a fake `hermes`
2
+ command on the PATH: no network, no Hermes needed. Run from the repo root: python3 -m unittest discover integrations/hermes/tests"""
3
+
4
+ import importlib.util
5
+ import json
6
+ import os
7
+ import stat
8
+ import sys
9
+ import tempfile
10
+ import unittest
11
+ from pathlib import Path
12
+ from unittest import mock
13
+
14
+ _SRC = Path(__file__).parents[1] / "src" / "crystalbrain_hermes"
15
+ _spec = importlib.util.spec_from_file_location("crystalbrain_hermes_installer", _SRC / "installer.py")
16
+ installer = importlib.util.module_from_spec(_spec)
17
+ _spec.loader.exec_module(installer)
18
+
19
+ # Records its arguments in $FAKE_HERMES_LOG; `config get memory.provider` prints $FAKE_PROVIDER.
20
+ FAKE_HERMES = f"""#!{sys.executable}
21
+ import json, os, sys
22
+ with open(os.environ["FAKE_HERMES_LOG"], "a") as log:
23
+ log.write(json.dumps(sys.argv[1:]) + "\\n")
24
+ if sys.argv[-3:] == ["config", "get", "memory.provider"]:
25
+ print(os.environ.get("FAKE_PROVIDER", ""))
26
+ """
27
+
28
+
29
+ class InstallerTest(unittest.TestCase):
30
+ def setUp(self):
31
+ self.tmp = Path(tempfile.mkdtemp())
32
+ self.home = self.tmp / "hermes"
33
+ self.home.mkdir()
34
+ bin_dir = self.tmp / "bin"
35
+ bin_dir.mkdir()
36
+ fake = bin_dir / "hermes"
37
+ fake.write_text(FAKE_HERMES)
38
+ fake.chmod(0o755)
39
+ self.log = self.tmp / "hermes.log"
40
+ self.env = mock.patch.dict(os.environ, {
41
+ "HERMES_HOME": str(self.home), "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}",
42
+ "FAKE_HERMES_LOG": str(self.log), "CRYSTALBRAIN_API_KEY": "",
43
+ })
44
+ self.env.start()
45
+ self.addCleanup(self.env.stop)
46
+ self.quiet = mock.patch("builtins.print")
47
+ self.quiet.start()
48
+ self.addCleanup(self.quiet.stop)
49
+
50
+ def calls(self):
51
+ return [json.loads(line) for line in self.log.read_text().splitlines()] if self.log.exists() else []
52
+
53
+ def test_install_copies_the_plugin_saves_the_key_and_selects_the_provider(self):
54
+ (self.home / ".env").write_text("OPENROUTER_API_KEY=or_1\nCRYSTALBRAIN_API_KEY=old\n")
55
+ self.assertEqual(installer.main(["install", "--key", "cb_new"]), 0)
56
+ plugin = self.home / "plugins" / "crystalbrain"
57
+ for name in installer.PLUGIN_FILES:
58
+ self.assertEqual((plugin / name).read_bytes(), (_SRC / "plugin" / name).read_bytes())
59
+ self.assertEqual((self.home / ".env").read_text(), "OPENROUTER_API_KEY=or_1\nCRYSTALBRAIN_API_KEY=cb_new\n")
60
+ self.assertEqual(stat.S_IMODE((self.home / ".env").stat().st_mode), 0o600)
61
+ self.assertEqual(self.calls(), [["config", "set", "memory.provider", "crystalbrain"]])
62
+
63
+ def test_the_key_comes_from_the_environment_then_the_env_file_then_a_prompt(self):
64
+ with mock.patch.dict(os.environ, {"CRYSTALBRAIN_API_KEY": "cb_env"}):
65
+ installer.main([])
66
+ self.assertEqual(installer.env_key(self.home / ".env"), "cb_env")
67
+ with mock.patch.object(installer.getpass, "getpass", side_effect=AssertionError("must not ask")):
68
+ self.assertEqual(installer.main([]), 0) # the .env value is reused
69
+ (self.home / ".env").unlink()
70
+ with mock.patch.object(installer.getpass, "getpass", return_value=" cb_typed "):
71
+ installer.main([])
72
+ self.assertEqual(installer.env_key(self.home / ".env"), "cb_typed")
73
+
74
+ def test_no_key_and_no_home_are_refused(self):
75
+ with mock.patch.object(installer.getpass, "getpass", side_effect=EOFError):
76
+ self.assertEqual(installer.main([]), 1)
77
+ self.assertFalse((self.home / "plugins").exists())
78
+ with mock.patch.dict(os.environ, {"HERMES_HOME": str(self.tmp / "missing")}):
79
+ self.assertEqual(installer.main(["--key", "cb_1"]), 1)
80
+
81
+ def test_a_profile_is_passed_to_hermes(self):
82
+ with mock.patch.object(installer.Path, "home", return_value=self.tmp):
83
+ (self.tmp / ".hermes" / "profiles" / "work").mkdir(parents=True)
84
+ self.assertEqual(installer.main(["--profile", "work", "--key", "cb_1"]), 0)
85
+ self.assertTrue((self.tmp / ".hermes" / "profiles" / "work" / "plugins" / "crystalbrain" / "__init__.py").is_file())
86
+ self.assertEqual(self.calls(), [["-p", "work", "config", "set", "memory.provider", "crystalbrain"]])
87
+
88
+ def test_without_hermes_on_the_path_it_still_installs(self):
89
+ with mock.patch.object(installer.shutil, "which", return_value=None):
90
+ self.assertEqual(installer.main(["--key", "cb_1"]), 0)
91
+ self.assertTrue((self.home / "plugins" / "crystalbrain" / "plugin.yaml").is_file())
92
+
93
+ def test_run_alone_it_downloads_the_plugin_from_the_site(self):
94
+ fetched = []
95
+
96
+ class Response:
97
+ def __init__(self, url):
98
+ self.url = url
99
+
100
+ def read(self):
101
+ return f"content of {self.url}".encode()
102
+
103
+ def __enter__(self):
104
+ return self
105
+
106
+ def __exit__(self, *exc):
107
+ return False
108
+
109
+ def urlopen(url, timeout):
110
+ fetched.append(url)
111
+ return Response(url)
112
+
113
+ with mock.patch.object(installer, "packaged_plugin", return_value=None), mock.patch.object(installer.urllib.request, "urlopen", urlopen):
114
+ installer.main(["--key", "cb_1"])
115
+ self.assertEqual(fetched, [f"{installer.BASE_URL}/hermes/crystalbrain/{n}" for n in installer.PLUGIN_FILES])
116
+ self.assertEqual((self.home / "plugins" / "crystalbrain" / "plugin.yaml").read_text(), f"content of {fetched[1]}")
117
+
118
+ def test_uninstall_removes_the_plugin_and_unselects_it(self):
119
+ installer.main(["--key", "cb_1"])
120
+ with mock.patch.dict(os.environ, {"FAKE_PROVIDER": "crystalbrain"}):
121
+ self.assertEqual(installer.main(["uninstall"]), 0)
122
+ self.assertFalse((self.home / "plugins" / "crystalbrain").exists())
123
+ self.assertEqual(self.calls()[-2:], [["config", "get", "memory.provider"], ["config", "unset", "memory.provider"]])
124
+ self.assertEqual(installer.env_key(self.home / ".env"), "cb_1") # the key is left
125
+
126
+ def test_uninstall_leaves_another_provider_selected(self):
127
+ with mock.patch.dict(os.environ, {"FAKE_PROVIDER": "honcho"}):
128
+ installer.main(["uninstall"])
129
+ self.assertNotIn(["config", "unset", "memory.provider"], self.calls())
130
+
131
+
132
+ if __name__ == "__main__":
133
+ unittest.main()