hydradb-hermes 1.0.1__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
+ __pycache__/
2
+ *.egg-info/
3
+ .pytest_cache/
4
+ build/
5
+ dist/
6
+ .venv/
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2025 HydraDB Contributors
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.5
2
+ Name: hydradb-hermes
3
+ Version: 1.0.1
4
+ Summary: HydraDB memory provider for Hermes Agent.
5
+ Project-URL: Homepage, https://hydradb.com
6
+ Project-URL: Repository, https://github.com/hydra-db/hydradb-hermes
7
+ Author-email: HydraDB <support@hydradb.com>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: hermes,hydradb,memory,recall,retain
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
16
+ Requires-Python: >=3.10
17
+ Requires-Dist: requests>=2.28
18
+ Provides-Extra: test
19
+ Requires-Dist: pytest>=7; extra == 'test'
20
+ Requires-Dist: responses>=0.24; extra == 'test'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # HydraDB for Hermes Agent
24
+
25
+ A [Hermes Agent](https://hermes-agent.nousresearch.com/docs/) **memory provider**
26
+ backed by [HydraDB](https://hydradb.com): relevant context is recalled before
27
+ each turn and completed turns are persisted - the proper native way to make
28
+ HydraDB Hermes' long-term memory (like the supermemory / retaindb / ham providers).
29
+
30
+ ## How it works
31
+
32
+ Implements Hermes' `MemoryProvider` contract:
33
+
34
+ | Method | Role → HydraDB |
35
+ |---|---|
36
+ | `prefetch(query, *, session_id)` | **auto-recall** - returns context injected before the API call → hybrid `POST /query` (prefers server `llm_prompt`) |
37
+ | `sync_turn(user, assistant, ...)` | persist the turn (**non-blocking**, off-thread) → `POST /context/ingest` |
38
+ | `is_available()` | `bool(HYDRADB_API_KEY)` |
39
+ | `get_config_schema()` / `save_config()` | setup wizard (api key, tenant) |
40
+ | `name` | `"hydradb"` |
41
+
42
+ Public API only (recall + knowledge ingest); no HydraDB SDK required.
43
+
44
+ ## Prerequisites
45
+
46
+ - Python >= 3.10, a Hermes Agent install
47
+ - A HydraDB account: API key + tenant ID ([hydradb.com](https://hydradb.com))
48
+
49
+ ## Install
50
+
51
+ **Directory (drop-in):** copy the `hydradb_hermes/` folder into
52
+ `~/.hermes/plugins/memory/hydradb/` (it contains `__init__.py` + `plugin.yaml`).
53
+
54
+ **pip (entry point):** `pip install hydradb-hermes` - registered via the
55
+ `hermes_agent.memory_providers` entry point.
56
+
57
+ Then enable it in `config.yaml` (memory providers are single-select):
58
+
59
+ ```yaml
60
+ memory:
61
+ provider: hydradb
62
+ ```
63
+
64
+ Credentials come from the environment:
65
+
66
+ ```bash
67
+ export HYDRADB_API_KEY="your-api-key"
68
+ export HYDRADB_DATABASE="your-tenant-id"
69
+ ```
70
+
71
+ ## Test
72
+
73
+ ```bash
74
+ pip install -e ".[test]"
75
+ pytest
76
+ ```
77
+
78
+ ## MCP alternative
79
+
80
+ For pull-style recall (agent-invoked tools) instead of automatic memory, point
81
+ Hermes at the MCP server (see `hermes-mcp.snippet.json`). The provider gives
82
+ automatic recall/retain, so MCP is optional.
83
+
84
+ ## License
85
+
86
+ Apache-2.0 - Copyright (c) 2026 HydraDB
@@ -0,0 +1,64 @@
1
+ # HydraDB for Hermes Agent
2
+
3
+ A [Hermes Agent](https://hermes-agent.nousresearch.com/docs/) **memory provider**
4
+ backed by [HydraDB](https://hydradb.com): relevant context is recalled before
5
+ each turn and completed turns are persisted - the proper native way to make
6
+ HydraDB Hermes' long-term memory (like the supermemory / retaindb / ham providers).
7
+
8
+ ## How it works
9
+
10
+ Implements Hermes' `MemoryProvider` contract:
11
+
12
+ | Method | Role → HydraDB |
13
+ |---|---|
14
+ | `prefetch(query, *, session_id)` | **auto-recall** - returns context injected before the API call → hybrid `POST /query` (prefers server `llm_prompt`) |
15
+ | `sync_turn(user, assistant, ...)` | persist the turn (**non-blocking**, off-thread) → `POST /context/ingest` |
16
+ | `is_available()` | `bool(HYDRADB_API_KEY)` |
17
+ | `get_config_schema()` / `save_config()` | setup wizard (api key, tenant) |
18
+ | `name` | `"hydradb"` |
19
+
20
+ Public API only (recall + knowledge ingest); no HydraDB SDK required.
21
+
22
+ ## Prerequisites
23
+
24
+ - Python >= 3.10, a Hermes Agent install
25
+ - A HydraDB account: API key + tenant ID ([hydradb.com](https://hydradb.com))
26
+
27
+ ## Install
28
+
29
+ **Directory (drop-in):** copy the `hydradb_hermes/` folder into
30
+ `~/.hermes/plugins/memory/hydradb/` (it contains `__init__.py` + `plugin.yaml`).
31
+
32
+ **pip (entry point):** `pip install hydradb-hermes` - registered via the
33
+ `hermes_agent.memory_providers` entry point.
34
+
35
+ Then enable it in `config.yaml` (memory providers are single-select):
36
+
37
+ ```yaml
38
+ memory:
39
+ provider: hydradb
40
+ ```
41
+
42
+ Credentials come from the environment:
43
+
44
+ ```bash
45
+ export HYDRADB_API_KEY="your-api-key"
46
+ export HYDRADB_DATABASE="your-tenant-id"
47
+ ```
48
+
49
+ ## Test
50
+
51
+ ```bash
52
+ pip install -e ".[test]"
53
+ pytest
54
+ ```
55
+
56
+ ## MCP alternative
57
+
58
+ For pull-style recall (agent-invoked tools) instead of automatic memory, point
59
+ Hermes at the MCP server (see `hermes-mcp.snippet.json`). The provider gives
60
+ automatic recall/retain, so MCP is optional.
61
+
62
+ ## License
63
+
64
+ Apache-2.0 - Copyright (c) 2026 HydraDB
@@ -0,0 +1,8 @@
1
+ {
2
+ "mcpServers": {
3
+ "hydradb": {
4
+ "url": "https://mcp.hydradb.com",
5
+ "headers": { "Authorization": "Bearer ${HYDRADB_API_KEY}" }
6
+ }
7
+ }
8
+ }
@@ -0,0 +1,49 @@
1
+ # HydraDB memory provider for Hermes
2
+
3
+ Long-term memory for [Hermes Agent](https://hermes-agent.nousresearch.com/docs/),
4
+ backed by [HydraDB](https://hydradb.com). Context is recalled before each turn and
5
+ completed turns are persisted, over the public HydraDB API.
6
+
7
+ ## How it works
8
+
9
+ Registers a `MemoryProvider`:
10
+
11
+ | Method | Role |
12
+ |---|---|
13
+ | `prefetch(query)` | recall relevant context before a turn via `POST /query` (uses the server `llm_prompt` when present) |
14
+ | `sync_turn(user, assistant)` | persist the completed turn off-thread via `POST /context/ingest` |
15
+
16
+ No tools, hooks, or middleware. Public API only; no HydraDB SDK required.
17
+
18
+ ## Setup
19
+
20
+ Run `hermes memory setup` and pick `hydradb`, or set the environment directly:
21
+
22
+ ```bash
23
+ export HYDRADB_API_KEY="your-api-key"
24
+ export HYDRADB_DATABASE="your-tenant-id"
25
+ # optional: HYDRADB_COLLECTION, HYDRADB_BASE_URL
26
+ ```
27
+
28
+ Then enable it:
29
+
30
+ ```yaml
31
+ memory:
32
+ provider: hydradb
33
+ ```
34
+
35
+ ## Configuration
36
+
37
+ | Variable | Required | Purpose |
38
+ |---|---|---|
39
+ | `HYDRADB_API_KEY` | yes | HydraDB API key (secret) |
40
+ | `HYDRADB_DATABASE` | yes | database/tenant to read and write |
41
+ | `HYDRADB_COLLECTION` | no | sub-tenant scope |
42
+ | `HYDRADB_BASE_URL` | no | defaults to `https://api.hydradb.com` |
43
+
44
+ The provider reports unavailable until `HYDRADB_API_KEY` and `HYDRADB_DATABASE`
45
+ are both set.
46
+
47
+ ## License
48
+
49
+ Apache-2.0, Copyright (c) 2026 HydraDB
@@ -0,0 +1,108 @@
1
+ """HydraDB as a Hermes Agent memory provider.
2
+
3
+ Implements the ``MemoryProvider`` contract: ``prefetch`` recalls relevant context
4
+ before each turn (auto-recall), ``sync_turn`` persists completed turns
5
+ (non-blocking), over the public HydraDB API via the shared client.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import threading
12
+ from typing import Any, Optional
13
+
14
+ from .client import HydraDBClient
15
+
16
+ #: Canonical HydraDB env var -> accepted deprecated aliases. The canonical name
17
+ #: wins; the alias keeps older setups (and the pre-rename catalog entry) working.
18
+ _ENV_ALIASES = {
19
+ "HYDRADB_DATABASE": ("HYDRADB_TENANT_ID",),
20
+ "HYDRADB_COLLECTION": ("HYDRADB_SUB_TENANT_ID",),
21
+ }
22
+
23
+
24
+ def _env(canonical: str, default: str = "") -> str:
25
+ """Resolve a HydraDB env var by canonical name, falling back to aliases."""
26
+ val = os.environ.get(canonical)
27
+ if val is not None:
28
+ return val
29
+ for alias in _ENV_ALIASES.get(canonical, ()): # pragma: no branch
30
+ val = os.environ.get(alias)
31
+ if val is not None:
32
+ return val
33
+ return default
34
+
35
+
36
+ try:
37
+ from agent.memory_provider import MemoryProvider as _BaseMemoryProvider
38
+ except Exception: # pragma: no cover
39
+
40
+ class _BaseMemoryProvider:
41
+ pass
42
+
43
+
44
+ class HydraDBMemoryProvider(_BaseMemoryProvider):
45
+ """Recall/retain backed by HydraDB (public API only)."""
46
+
47
+ def __init__(self, client: Optional[HydraDBClient] = None) -> None:
48
+ self._client = client
49
+ self._search_mode = "knowledge"
50
+
51
+ @property
52
+ def name(self) -> str:
53
+ return "hydradb"
54
+
55
+ def is_available(self) -> bool:
56
+ return bool(os.environ.get("HYDRADB_API_KEY") and _env("HYDRADB_DATABASE"))
57
+
58
+ def initialize(self, session_id: str, **kwargs: Any) -> None:
59
+ if self._client is None:
60
+ self._client = HydraDBClient(
61
+ api_key=os.environ.get("HYDRADB_API_KEY", ""),
62
+ tenant_id=_env("HYDRADB_DATABASE"),
63
+ sub_tenant_id=_env("HYDRADB_COLLECTION"),
64
+ base_url=os.environ.get("HYDRADB_BASE_URL", "https://api.hydradb.com"),
65
+ )
66
+
67
+ def get_config_schema(self):
68
+ # Hermes reads the `env_var` key to persist each value into .env during
69
+ # `hermes memory setup`; the provider then resolves them from the
70
+ # environment on start (see is_available/initialize). Older
71
+ # HYDRADB_TENANT_ID / HYDRADB_SUB_TENANT_ID remain accepted as aliases.
72
+ return [
73
+ {"key": "api_key", "env_var": "HYDRADB_API_KEY", "secret": True, "required": True},
74
+ {"key": "database", "env_var": "HYDRADB_DATABASE", "required": True},
75
+ {"key": "collection", "env_var": "HYDRADB_COLLECTION", "required": False},
76
+ ]
77
+
78
+ def get_tool_schemas(self):
79
+ return []
80
+
81
+ def system_prompt_block(self) -> str:
82
+ return "HydraDB provides persistent long-term memory. Relevant memories are recalled automatically before each turn."
83
+
84
+ def prefetch(self, query: str, *, session_id: str = "") -> str:
85
+ if not query or self._client is None:
86
+ return ""
87
+ try:
88
+ return self._client.recall_prompt(query, kind=self._search_mode)
89
+ except Exception:
90
+ return ""
91
+
92
+ def sync_turn(self, user: str, assistant: str, *, session_id: str = "", messages: Any = None) -> None:
93
+ """Persist a completed turn. MUST be non-blocking, so ingest off-thread."""
94
+ if self._client is None:
95
+ return
96
+ client = self._client
97
+
98
+ def _persist() -> None:
99
+ try:
100
+ client.add_conversation(user, assistant, infer=False)
101
+ except Exception:
102
+ pass
103
+
104
+ threading.Thread(target=_persist, daemon=True).start()
105
+
106
+
107
+ def register(ctx) -> None:
108
+ ctx.register_memory_provider(HydraDBMemoryProvider())
@@ -0,0 +1,273 @@
1
+ """Minimal HydraDB HTTP client - public API only.
2
+
3
+ Wraps the three public endpoints these integrations need:
4
+
5
+ * ``POST /query`` - hybrid recall over memory or knowledge (JSON body)
6
+ * ``POST /context/ingest`` - write knowledge (multipart ``app_knowledge``)
7
+ * ``DELETE /context`` - remove context by id (JSON body)
8
+
9
+ Ingestion uses the public knowledge path (``app_knowledge``); the memory-family
10
+ write route is not exposed on the public API, so text/conversations are stored
11
+ as knowledge. Auth is ``Authorization: Bearer <api_key>``. Responses are the
12
+ standard ``{"success", "data", "error", "meta"}`` envelope; recall results live
13
+ in ``data.chunks``. Chunks are normalised so callers do not depend on the wire
14
+ shape.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import uuid
21
+ from dataclasses import dataclass, field
22
+ from typing import Any, Iterable
23
+
24
+ import requests
25
+
26
+ DEFAULT_BASE_URL = "https://api.hydradb.com"
27
+
28
+
29
+ class HydraDBError(RuntimeError):
30
+ """Raised when the HydraDB API returns an error envelope or bad status."""
31
+
32
+
33
+ @dataclass
34
+ class HydraChunk:
35
+ """A single recalled chunk, normalised across memory/knowledge results."""
36
+
37
+ text: str
38
+ score: float | None = None
39
+ source_title: str = ""
40
+ id: str = ""
41
+ metadata: dict[str, Any] = field(default_factory=dict)
42
+
43
+
44
+ class HydraDBClient:
45
+ """Thin, dependency-light client for HydraDB recall and ingestion."""
46
+
47
+ def __init__(
48
+ self,
49
+ api_key: str,
50
+ tenant_id: str,
51
+ sub_tenant_id: str = "",
52
+ base_url: str = DEFAULT_BASE_URL,
53
+ timeout: float = 15.0,
54
+ session: requests.Session | None = None,
55
+ ) -> None:
56
+ if not api_key:
57
+ raise ValueError("api_key is required")
58
+ if not tenant_id:
59
+ raise ValueError("tenant_id is required")
60
+ self.api_key = api_key
61
+ self.tenant_id = tenant_id
62
+ self.sub_tenant_id = sub_tenant_id
63
+ self.base_url = base_url.rstrip("/")
64
+ self.timeout = timeout
65
+ self._session = session or requests.Session()
66
+
67
+ @property
68
+ def _auth_headers(self) -> dict[str, str]:
69
+ return {"Authorization": f"Bearer {self.api_key}"}
70
+
71
+ def _unwrap(self, resp: requests.Response) -> dict[str, Any]:
72
+ try:
73
+ body = resp.json()
74
+ except ValueError:
75
+ raise HydraDBError(f"HTTP {resp.status_code}: {resp.text[:200]}")
76
+ if not body.get("success", False):
77
+ err = body.get("error") or {}
78
+ raise HydraDBError(
79
+ f"{err.get('code', 'ERROR')}: {err.get('message', resp.text[:200])}"
80
+ )
81
+ return body.get("data") or {}
82
+
83
+ def query(
84
+ self,
85
+ query: str,
86
+ kind: str = "memory",
87
+ mode: str = "fast",
88
+ max_results: int = 6,
89
+ alpha: float = 0.8,
90
+ recency_bias: float = 0.0,
91
+ graph_context: bool = True,
92
+ ) -> list[HydraChunk]:
93
+ """Hybrid recall. ``kind`` is ``"memory"`` or ``"knowledge"``."""
94
+ payload = {
95
+ "tenant_id": self.tenant_id,
96
+ "sub_tenant_id": self.sub_tenant_id,
97
+ "query": query,
98
+ "kind": kind,
99
+ "mode": mode,
100
+ "max_results": max_results,
101
+ "alpha": alpha,
102
+ "recency_bias": recency_bias,
103
+ "graph_context": graph_context,
104
+ }
105
+ resp = self._session.post(
106
+ f"{self.base_url}/query",
107
+ headers={**self._auth_headers, "Content-Type": "application/json"},
108
+ json=payload,
109
+ timeout=self.timeout,
110
+ )
111
+ data = self._unwrap(resp)
112
+ return [_to_chunk(c) for c in (data.get("chunks") or [])]
113
+
114
+ def recall_prompt(
115
+ self,
116
+ query: str,
117
+ kind: str = "knowledge",
118
+ mode: str = "fast",
119
+ max_results: int = 6,
120
+ ) -> str:
121
+ """Hybrid recall as a ready-to-inject string.
122
+
123
+ Prefers the server-rendered ``llm_prompt`` when present; otherwise builds
124
+ a compact block from the recalled chunks. Returns ``""`` when nothing is
125
+ recalled.
126
+ """
127
+ payload = {
128
+ "tenant_id": self.tenant_id,
129
+ "sub_tenant_id": self.sub_tenant_id,
130
+ "query": query,
131
+ "kind": kind,
132
+ "mode": mode,
133
+ "max_results": max_results,
134
+ }
135
+ resp = self._session.post(
136
+ f"{self.base_url}/query",
137
+ headers={**self._auth_headers, "Content-Type": "application/json"},
138
+ json=payload,
139
+ timeout=self.timeout,
140
+ )
141
+ data = self._unwrap(resp)
142
+ prompt = data.get("llm_prompt")
143
+ if isinstance(prompt, str) and prompt.strip():
144
+ return prompt
145
+ chunks = [_to_chunk(c) for c in (data.get("chunks") or [])]
146
+ lines = [f"- {c.text}" for c in chunks if c.text]
147
+ return "Relevant HydraDB memory:\n" + "\n".join(lines) if lines else ""
148
+
149
+ def add_knowledge(self, items: Iterable[dict[str, Any]]) -> dict[str, Any]:
150
+ """Ingest ``app_knowledge`` items via the public ``/context/ingest``.
151
+
152
+ Each item is ``{"id", "title", "content": {"text": ...}, "metadata",
153
+ "infer"}``. Ingestion is asynchronous: a success here means the sources
154
+ were accepted/queued, not yet indexed.
155
+ """
156
+ fields = {
157
+ "tenant_id": (None, self.tenant_id),
158
+ "sub_tenant_id": (None, self.sub_tenant_id),
159
+ "kind": (None, "knowledge"),
160
+ "app_knowledge": (None, json.dumps(list(items))),
161
+ }
162
+ resp = self._session.post(
163
+ f"{self.base_url}/context/ingest",
164
+ headers=self._auth_headers,
165
+ files=fields,
166
+ timeout=self.timeout,
167
+ )
168
+ return self._unwrap(resp)
169
+
170
+ def add_text(
171
+ self,
172
+ text: str,
173
+ infer: bool = True,
174
+ title: str | None = None,
175
+ metadata: dict[str, Any] | None = None,
176
+ source_id: str | None = None,
177
+ ) -> dict[str, Any]:
178
+ """Store a single note as knowledge. Returns the ingest ack."""
179
+ item = {
180
+ "id": source_id or f"note-{uuid.uuid4().hex}",
181
+ "title": title or "note",
182
+ "content": {"text": text},
183
+ "metadata": metadata or {},
184
+ "infer": infer,
185
+ }
186
+ return self.add_knowledge([item])
187
+
188
+ def add_conversation(
189
+ self, user: str, assistant: str, infer: bool = True
190
+ ) -> dict[str, Any]:
191
+ """Store a user/assistant turn as knowledge."""
192
+ return self.add_text(
193
+ f"User: {user}\nAssistant: {assistant}", infer=infer, title="conversation"
194
+ )
195
+
196
+ def delete(self, ids: list[str], kind: str = "knowledge") -> dict[str, Any]:
197
+ ids = [i for i in (ids or []) if i]
198
+ if not ids:
199
+ return {"deleted_count": 0, "results": []}
200
+ resp = self._session.delete(
201
+ f"{self.base_url}/context",
202
+ headers={**self._auth_headers, "Content-Type": "application/json"},
203
+ json={
204
+ "tenant_id": self.tenant_id,
205
+ "sub_tenant_id": self.sub_tenant_id,
206
+ "ids": ids,
207
+ "kind": kind,
208
+ },
209
+ timeout=self.timeout,
210
+ )
211
+ return self._unwrap(resp)
212
+
213
+
214
+ def _to_chunk(raw: dict[str, Any]) -> HydraChunk:
215
+ """Normalise a wire chunk into :class:`HydraChunk`.
216
+
217
+ ``chunk_content`` is often a stored envelope whose prose lives at
218
+ ``content.text``; recall must yield the prose, not the JSON scaffolding
219
+ (mirrors the plugin's normalizeRetrievalResponse). Content that merely looks
220
+ JSON-ish but does not parse is passed through untouched.
221
+ """
222
+ raw_text = raw.get("chunk_content")
223
+ if raw_text is None:
224
+ raw_text = raw.get("text") or raw.get("content") or ""
225
+ return HydraChunk(
226
+ text=_extract_text(raw_text),
227
+ score=raw.get("relevancy_score") or raw.get("score") or raw.get("relevance_score"),
228
+ source_title=raw.get("source_title") or raw.get("title") or "",
229
+ id=raw.get("chunk_uuid") or raw.get("id") or "",
230
+ metadata=raw.get("metadata") or {},
231
+ )
232
+
233
+
234
+ def _extract_text(value: Any) -> str:
235
+ """Unwrap a HydraDB content envelope to its prose, else return as-is.
236
+
237
+ Recall may return the stored envelope JSON followed by trailing graph
238
+ enrichment (``"\\n\\nExtra context: ..."``). The envelope is decoded from the
239
+ front with ``raw_decode`` so the trailing text no longer defeats the unwrap;
240
+ the prose is returned with any enrichment appended and the JSON dropped.
241
+ """
242
+ if isinstance(value, dict):
243
+ return _prose_from_envelope(value) or json.dumps(value)
244
+ if not isinstance(value, str):
245
+ return str(value)
246
+ stripped = value.strip()
247
+ if stripped.startswith("{"):
248
+ try:
249
+ obj, end = json.JSONDecoder().raw_decode(stripped)
250
+ except ValueError:
251
+ return value
252
+ prose = _prose_from_envelope(obj)
253
+ if prose is not None:
254
+ trailing = stripped[end:].strip()
255
+ return f"{prose}\n\n{trailing}" if trailing else prose
256
+ return value
257
+
258
+
259
+ def _prose_from_envelope(obj: Any) -> str | None:
260
+ if not isinstance(obj, dict):
261
+ return None
262
+ content = obj.get("content")
263
+ if isinstance(content, dict):
264
+ for key in ("text", "markdown"):
265
+ val = content.get(key)
266
+ if isinstance(val, str) and val.strip():
267
+ return val
268
+ if isinstance(content, str) and content.strip():
269
+ return content
270
+ top = obj.get("text")
271
+ if isinstance(top, str) and top.strip():
272
+ return top
273
+ return None
@@ -0,0 +1,10 @@
1
+ name: hydradb
2
+ version: 1.0.0
3
+ description: "HydraDB long-term memory for Hermes Agent: prompt-time recall (prefetch) and non-blocking turn capture (sync_turn) over the public HydraDB API. Registered as a MemoryProvider; no general tools or lifecycle hooks."
4
+ requires_hermes: ">=0.21.5"
5
+ provides_tools: []
6
+ provides_hooks: []
7
+ provides_middleware: []
8
+ requires_env:
9
+ - HYDRADB_API_KEY
10
+ - HYDRADB_DATABASE
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "hydradb-hermes"
7
+ version = "1.0.1"
8
+ description = "HydraDB memory provider for Hermes Agent."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "HydraDB", email = "support@hydradb.com" }]
13
+ keywords = ["hydradb", "hermes", "memory", "recall", "retain"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: Apache Software License",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
20
+ ]
21
+ dependencies = ["requests>=2.28"]
22
+
23
+ [project.optional-dependencies]
24
+ test = ["pytest>=7", "responses>=0.24"]
25
+
26
+ [project.entry-points."hermes_agent.memory_providers"]
27
+ hydradb = "hydradb_hermes:register"
28
+
29
+ [project.urls]
30
+ Homepage = "https://hydradb.com"
31
+ Repository = "https://github.com/hydra-db/hydradb-hermes"
32
+
33
+ [tool.hatch.build.targets.wheel]
34
+ packages = ["hydradb_hermes"]
35
+
36
+ [tool.pytest.ini_options]
37
+ addopts = "--import-mode=importlib"
@@ -0,0 +1,95 @@
1
+ """Offline tests for the HydraDB Hermes memory provider (no Hermes/network)."""
2
+
3
+ import time
4
+
5
+ import responses
6
+
7
+ from hydradb_hermes import HydraDBMemoryProvider
8
+ from hydradb_hermes.client import HydraDBClient
9
+
10
+ BASE = "https://api.hydradb.com"
11
+
12
+
13
+ def _provider():
14
+ client = HydraDBClient(api_key="k", tenant_id="test_beam", sub_tenant_id="")
15
+ return HydraDBMemoryProvider(client=client)
16
+
17
+
18
+ @responses.activate
19
+ def test_prefetch_prefers_server_llm_prompt():
20
+ responses.add(
21
+ responses.POST,
22
+ f"{BASE}/query",
23
+ json={
24
+ "success": True,
25
+ "data": {"llm_prompt": "# Query results\n- mascot is Hydrabyte", "chunks": []},
26
+ "error": None,
27
+ },
28
+ status=200,
29
+ )
30
+ out = _provider().prefetch("mascot", session_id="s1")
31
+ assert "mascot is Hydrabyte" in out
32
+
33
+
34
+ @responses.activate
35
+ def test_prefetch_falls_back_to_chunks():
36
+ responses.add(
37
+ responses.POST,
38
+ f"{BASE}/query",
39
+ json={
40
+ "success": True,
41
+ "data": {"chunks": [{"chunk_content": "deploy on Fridays", "chunk_uuid": "c1"}]},
42
+ "error": None,
43
+ },
44
+ status=200,
45
+ )
46
+ out = _provider().prefetch("deploy", session_id="s1")
47
+ assert "deploy on Fridays" in out
48
+
49
+
50
+ @responses.activate
51
+ def test_sync_turn_ingests_non_blocking():
52
+ responses.add(
53
+ responses.POST,
54
+ f"{BASE}/context/ingest",
55
+ json={"success": True, "data": {"success_count": 1}, "error": None},
56
+ status=200,
57
+ )
58
+ _provider().sync_turn("what is X?", "X is Y", session_id="s1")
59
+ for _ in range(50):
60
+ if responses.calls:
61
+ break
62
+ time.sleep(0.02)
63
+ assert responses.calls
64
+ body = responses.calls[0].request.body
65
+ assert b"app_knowledge" in body
66
+
67
+
68
+ def test_is_available_requires_key_and_tenant(monkeypatch):
69
+ monkeypatch.delenv("HYDRADB_API_KEY", raising=False)
70
+ monkeypatch.delenv("HYDRADB_DATABASE", raising=False)
71
+ assert _provider().is_available() is False
72
+ monkeypatch.setenv("HYDRADB_API_KEY", "x")
73
+ assert _provider().is_available() is False
74
+ monkeypatch.setenv("HYDRADB_DATABASE", "t")
75
+ assert _provider().is_available() is True
76
+
77
+
78
+ def test_name_and_schema():
79
+ p = _provider()
80
+ assert p.name == "hydradb"
81
+ assert any(f["key"] == "api_key" for f in p.get_config_schema())
82
+
83
+
84
+ def test_extract_text_unwraps_envelope_with_trailing_context():
85
+ """Recall text may be an envelope JSON plus trailing 'Extra context'."""
86
+ from hydradb_hermes.client import _extract_text
87
+
88
+ raw = (
89
+ '{"content": {"text": "Ship Friday."}, "document_metadata": {"a": "b"}}'
90
+ "\n\nExtra context: The beta ships Friday."
91
+ )
92
+ out = _extract_text(raw)
93
+ assert out.startswith("Ship Friday.")
94
+ assert "Extra context:" in out
95
+ assert "document_metadata" not in out