@hivemagnus/hivemem-sdk 0.0.0-stage → 1.0.0

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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
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 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 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 those 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
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,120 @@
1
- # Temporary Holding Version
1
+ # @hivemagnus/hivemem-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ TypeScript client for [HiveMem](https://github.com/ChefTaco/hive/tree/main/services/hive-mem), the shared long-term memory service for AI agents. It wraps the HiveMem REST API with typed helpers for memories, search, sessions, prompt context, peer cards, conclusions, queue operations, and webhooks.
4
+
5
+ - Zero runtime dependencies; uses the platform `fetch` (Node.js 18.17+, Deno, Bun, browsers, edge runtimes).
6
+ - ESM-only, with bundled type declarations.
7
+ - Retries 5xx responses, supports request timeouts, request IDs, and token refresh hooks.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install @hivemagnus/hivemem-sdk
13
+ ```
14
+
15
+ You need a running HiveMem server and an agent token. See the [HiveMem README](https://github.com/ChefTaco/hive/tree/main/services/hive-mem#readme) for how to run the server and register an agent.
16
+
17
+ ## Quick start
18
+
19
+ ```ts
20
+ import { HiveMem } from "@hivemagnus/hivemem-sdk";
21
+
22
+ const hivemem = new HiveMem({
23
+ baseUrl: "https://memory.example.com", // or set HIVEMEM_API_URL
24
+ token: process.env.HIVEMEM_TOKEN,
25
+ workspaceId: "default",
26
+ });
27
+
28
+ // Store a memory. HiveMem embeds the text server-side.
29
+ await hivemem.createMemory({
30
+ content: "The user prefers direct status summaries.",
31
+ type: "semantic",
32
+ scope: "private",
33
+ tags: ["preference"],
34
+ });
35
+
36
+ // Search with score explanations.
37
+ const results = await hivemem.searchMemories("status summary preferences", { limit: 5 }, { explain: true });
38
+
39
+ // Build a token-budgeted, source-cited prompt context and hand it to your model.
40
+ const context = await hivemem.context({ tokens: 2000, search_query: "current project" });
41
+ const messages = context.toOpenAI(); // or context.toAnthropic()
42
+ ```
43
+
44
+ ## Configuration
45
+
46
+ | Option | Environment fallback | Default |
47
+ | --- | --- | --- |
48
+ | `baseUrl` | `HIVEMEM_API_URL` | `http://localhost:18790` |
49
+ | `token` | `HIVEMEM_TOKEN`, then `HIVEMEM_MCP_TOKEN` | none |
50
+ | `workspaceId` | `HIVEMEM_WORKSPACE_ID` | `default` |
51
+ | `timeoutMs` | | `30000` |
52
+ | `maxRetries` | | `2` (5xx responses only) |
53
+ | `fetchImpl` | | global `fetch` |
54
+ | `requestIdProvider` | | sends `X-Request-ID` when set |
55
+ | `authRefresh` | | called before each attempt; a returned token replaces the current one |
56
+ | `onRequest` / `onResponse` | | observability hooks |
57
+
58
+ Explicit constructor options win over environment variables. Environment variables are only read where `process.env` exists.
59
+
60
+ ## Common operations
61
+
62
+ ```ts
63
+ // Memories
64
+ const memory = await hivemem.getMemory(id);
65
+ const original = await hivemem.getMemory(oldId, { includeHistory: true }); // superseded/retired versions
66
+ await hivemem.browseMemories({ limit: 20 });
67
+
68
+ // Sessions and session-scoped context
69
+ const session = await hivemem.createSession({ session_id: "chat-42" });
70
+ const sessionContext = await hivemem.sessionContext("chat-42", { search_query: "open questions" });
71
+
72
+ // Peer cards and conclusions
73
+ const card = await hivemem.getPeerCard("user");
74
+ const page = await hivemem.listConclusionsPage("user", { limit: 50 });
75
+ const next = page.next_cursor ? await hivemem.listConclusionsPage("user", { limit: 50, cursor: page.next_cursor }) : null;
76
+ const conclusion = await hivemem.getConclusion(conclusionId, { includeHistory: true });
77
+
78
+ // Idempotent background operations
79
+ const job = await hivemem.getQueueOperation("nightly-2026-01-01", "consolidation");
80
+
81
+ // Knowledge sources
82
+ await hivemem.syncKnowledgeSource({ mode: "preview", project_id: "docs", source_id: "repo:docs", source_uri: "repo://docs", revision: "abc123", observed_at: new Date().toISOString(), chunks: [] });
83
+ ```
84
+
85
+ ## Errors
86
+
87
+ Non-2xx responses throw `HiveMemHTTPError` with `statusCode`, the server's `detail` as `message`, and the parsed body as `details`. All SDK errors extend `HiveMemError`.
88
+
89
+ ```ts
90
+ import { HiveMemHTTPError } from "@hivemagnus/hivemem-sdk";
91
+
92
+ try {
93
+ await hivemem.getMemory("missing");
94
+ } catch (error) {
95
+ if (error instanceof HiveMemHTTPError && error.statusCode === 404) {
96
+ // not found or not visible to this agent
97
+ }
98
+ }
99
+ ```
100
+
101
+ ## Verifying webhooks
102
+
103
+ HiveMem signs webhook deliveries with HMAC-SHA256. Verify them before trusting the payload:
104
+
105
+ ```ts
106
+ import { verifyHiveMemWebhook } from "@hivemagnus/hivemem-sdk";
107
+
108
+ const ok = await verifyHiveMemWebhook({
109
+ secret: process.env.HIVEMEM_WEBHOOK_SECRET!,
110
+ body: rawBody, // the exact bytes received
111
+ signature: headers["x-hivemem-signature"],
112
+ timestamp: headers["x-hivemem-timestamp"],
113
+ nonce: headers["x-hivemem-nonce"],
114
+ seenNonces, // optional Set<string> for replay protection
115
+ });
116
+ ```
117
+
118
+ ## License
119
+
120
+ Apache-2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,49 @@
1
+ import { ContextPackage } from "./context.js";
2
+ import type { ConclusionPage, ConclusionRecord, HiveMemOptions, KnowledgeSourceSyncResponse, MemoryRecord, PeerCardResponse, QueueJobRecord, QueueStatusResponse, SearchResponse, SessionRecord, WebhookEndpoint } from "./types.js";
3
+ export declare class HiveMem {
4
+ readonly baseUrl: string;
5
+ token?: string;
6
+ readonly workspaceId: string;
7
+ readonly timeoutMs: number;
8
+ readonly maxRetries: number;
9
+ private readonly fetchImpl;
10
+ private readonly requestIdProvider?;
11
+ private readonly authRefresh?;
12
+ private readonly onRequest?;
13
+ private readonly onResponse?;
14
+ constructor(options?: HiveMemOptions);
15
+ private url;
16
+ private request;
17
+ health(): Promise<Record<string, unknown>>;
18
+ getMemory(memoryId: string, options?: {
19
+ includeHistory?: boolean;
20
+ }): Promise<MemoryRecord>;
21
+ createMemory(body: Record<string, unknown>): Promise<MemoryRecord>;
22
+ searchMemories(query: string, body?: Record<string, unknown>, options?: {
23
+ explain?: boolean;
24
+ }): Promise<SearchResponse>;
25
+ syncKnowledgeSource(body: Record<string, unknown>): Promise<KnowledgeSourceSyncResponse>;
26
+ browseMemories(params?: Record<string, unknown>): Promise<Record<string, unknown>>;
27
+ createSession(body?: Record<string, unknown>): Promise<SessionRecord>;
28
+ listSessions(params?: Record<string, unknown>): Promise<SessionRecord[]>;
29
+ context(body?: Record<string, unknown>): Promise<ContextPackage>;
30
+ sessionContext(sessionId: string, body?: Record<string, unknown>): Promise<ContextPackage>;
31
+ queueStatus(params?: Record<string, unknown>): Promise<QueueStatusResponse>;
32
+ getQueueOperation(operationId: string, taskType: "consolidation" | "dream", params?: Record<string, unknown>): Promise<QueueJobRecord>;
33
+ listConclusions(peerId: string, params?: Record<string, unknown>): Promise<ConclusionRecord[]>;
34
+ listConclusionsPage(peerId: string, params?: Record<string, unknown>): Promise<ConclusionPage>;
35
+ getConclusion(conclusionId: string, options?: {
36
+ includeHistory?: boolean;
37
+ }): Promise<ConclusionRecord>;
38
+ peerRepresentation(peerId: string, params?: Record<string, unknown>): Promise<Record<string, unknown>>;
39
+ getPeerCard(peerId: string, params?: Record<string, unknown>): Promise<PeerCardResponse>;
40
+ upsertPeerCard(peerId: string, content: string, body?: Record<string, unknown>): Promise<Record<string, unknown>>;
41
+ rebuildPeerCard(peerId: string, body?: Record<string, unknown>): Promise<Record<string, unknown>>;
42
+ reviewPeerCard(peerId: string, params?: Record<string, unknown>): Promise<Record<string, unknown>>;
43
+ exportAgentBundle(agentId: string): Promise<Record<string, unknown>>;
44
+ importAgentBundle(agentId: string, bundle: Record<string, unknown>): Promise<Record<string, unknown>>;
45
+ createWebhook(url: string, body?: Record<string, unknown>): Promise<WebhookEndpoint>;
46
+ listWebhooks(params?: Record<string, unknown>): Promise<WebhookEndpoint[]>;
47
+ testWebhook(body?: Record<string, unknown>): Promise<Record<string, unknown>>;
48
+ webhookDeliveries(params?: Record<string, unknown>): Promise<Record<string, unknown>>;
49
+ }
package/dist/client.js ADDED
@@ -0,0 +1,173 @@
1
+ import { ContextPackage } from "./context.js";
2
+ import { HiveMemHTTPError } from "./errors.js";
3
+ function env(name) {
4
+ const proc = globalThis;
5
+ return proc.process?.env?.[name];
6
+ }
7
+ export class HiveMem {
8
+ baseUrl;
9
+ token;
10
+ workspaceId;
11
+ timeoutMs;
12
+ maxRetries;
13
+ fetchImpl;
14
+ requestIdProvider;
15
+ authRefresh;
16
+ onRequest;
17
+ onResponse;
18
+ constructor(options = {}) {
19
+ this.baseUrl = (options.baseUrl ?? env("HIVEMEM_API_URL") ?? "http://localhost:18790").replace(/\/$/, "");
20
+ this.token = options.token ?? env("HIVEMEM_TOKEN") ?? env("HIVEMEM_MCP_TOKEN");
21
+ this.workspaceId = options.workspaceId ?? env("HIVEMEM_WORKSPACE_ID") ?? "default";
22
+ this.timeoutMs = options.timeoutMs ?? 30_000;
23
+ this.maxRetries = options.maxRetries ?? 2;
24
+ this.fetchImpl = options.fetchImpl ?? fetch;
25
+ this.requestIdProvider = options.requestIdProvider;
26
+ this.authRefresh = options.authRefresh;
27
+ this.onRequest = options.onRequest;
28
+ this.onResponse = options.onResponse;
29
+ }
30
+ url(path) {
31
+ return `${this.baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
32
+ }
33
+ async request(method, path, init = {}, params) {
34
+ const url = new URL(this.url(path));
35
+ for (const [key, value] of Object.entries(params ?? {})) {
36
+ if (value !== undefined && value !== null)
37
+ url.searchParams.set(key, String(value));
38
+ }
39
+ const headers = new Headers(init.headers);
40
+ headers.set("Accept", "application/json");
41
+ if (init.body && !headers.has("Content-Type"))
42
+ headers.set("Content-Type", "application/json");
43
+ if (this.requestIdProvider)
44
+ headers.set("X-Request-ID", this.requestIdProvider());
45
+ if (this.token)
46
+ headers.set("Authorization", `Bearer ${this.token}`);
47
+ for (let attempt = 0; attempt <= this.maxRetries; attempt += 1) {
48
+ const refreshed = await this.authRefresh?.();
49
+ if (refreshed) {
50
+ this.token = refreshed;
51
+ headers.set("Authorization", `Bearer ${this.token}`);
52
+ }
53
+ const controller = new AbortController();
54
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
55
+ try {
56
+ const requestInit = { ...init, method, headers, signal: controller.signal };
57
+ this.onRequest?.(method, String(url), requestInit);
58
+ const response = await this.fetchImpl(url, requestInit);
59
+ this.onResponse?.(response);
60
+ if (response.status >= 500 && attempt < this.maxRetries)
61
+ continue;
62
+ if (!response.ok) {
63
+ let details;
64
+ let message = response.statusText;
65
+ try {
66
+ details = await response.json();
67
+ if (details && typeof details === "object" && "detail" in details)
68
+ message = String(details.detail);
69
+ }
70
+ catch {
71
+ message = await response.text();
72
+ }
73
+ throw new HiveMemHTTPError(response.status, message, details);
74
+ }
75
+ if (response.status === 204)
76
+ return undefined;
77
+ return (await response.json());
78
+ }
79
+ finally {
80
+ clearTimeout(timeout);
81
+ }
82
+ }
83
+ throw new HiveMemHTTPError(599, "HiveMem request retries exhausted");
84
+ }
85
+ health() {
86
+ return this.request("GET", "/v1/health");
87
+ }
88
+ getMemory(memoryId, options = {}) {
89
+ const params = options.includeHistory ? { include_history: true } : {};
90
+ return this.request("GET", `/v1/memories/${encodeURIComponent(memoryId)}`, {}, params);
91
+ }
92
+ createMemory(body) {
93
+ return this.request("POST", "/v1/memories", { body: JSON.stringify({ workspace_id: this.workspaceId, ...body }) });
94
+ }
95
+ searchMemories(query, body = {}, options = {}) {
96
+ return this.request("POST", "/v1/memories/search", { body: JSON.stringify({ workspace_id: this.workspaceId, ...body, query }) }, { explain: options.explain ?? false });
97
+ }
98
+ syncKnowledgeSource(body) {
99
+ return this.request("POST", "/v1/knowledge/sources/sync", { body: JSON.stringify({ workspace_id: this.workspaceId, ...body }) });
100
+ }
101
+ browseMemories(params = {}) {
102
+ return this.request("GET", "/v1/memories/browse", {}, { workspace_id: this.workspaceId, ...params });
103
+ }
104
+ createSession(body = {}) {
105
+ return this.request("POST", "/v1/sessions", { body: JSON.stringify({ workspace_id: this.workspaceId, ...body }) });
106
+ }
107
+ listSessions(params = {}) {
108
+ return this.request("GET", "/v1/sessions", {}, { workspace_id: this.workspaceId, ...params });
109
+ }
110
+ context(body = {}) {
111
+ return this.request("POST", "/v1/context", { body: JSON.stringify({ workspace_id: this.workspaceId, ...body }) }).then((data) => new ContextPackage(data));
112
+ }
113
+ sessionContext(sessionId, body = {}) {
114
+ return this.request("POST", `/v1/sessions/${encodeURIComponent(sessionId)}/context`, { body: JSON.stringify({ workspace_id: this.workspaceId, ...body }) }).then((data) => new ContextPackage(data));
115
+ }
116
+ queueStatus(params = {}) {
117
+ return this.request("GET", "/v1/queue/status", {}, params);
118
+ }
119
+ getQueueOperation(operationId, taskType, params = {}) {
120
+ return this.request("GET", `/v1/queue/operations/${encodeURIComponent(operationId)}`, {}, {
121
+ workspace_id: this.workspaceId,
122
+ ...params,
123
+ task_type: taskType,
124
+ });
125
+ }
126
+ listConclusions(peerId, params = {}) {
127
+ return this.request("GET", `/v1/peers/${encodeURIComponent(peerId)}/conclusions`, {}, { workspace_id: this.workspaceId, ...params });
128
+ }
129
+ listConclusionsPage(peerId, params = {}) {
130
+ return this.request("GET", `/v1/peers/${encodeURIComponent(peerId)}/conclusions`, {}, {
131
+ workspace_id: this.workspaceId,
132
+ ...params,
133
+ paginate: true,
134
+ });
135
+ }
136
+ getConclusion(conclusionId, options = {}) {
137
+ const params = options.includeHistory ? { include_history: true } : {};
138
+ return this.request("GET", `/v1/conclusions/${encodeURIComponent(conclusionId)}`, {}, params);
139
+ }
140
+ peerRepresentation(peerId, params = {}) {
141
+ return this.request("GET", `/v1/peers/${encodeURIComponent(peerId)}/representation`, {}, { workspace_id: this.workspaceId, ...params });
142
+ }
143
+ getPeerCard(peerId, params = {}) {
144
+ return this.request("GET", `/v1/peers/${encodeURIComponent(peerId)}/card`, {}, { workspace_id: this.workspaceId, ...params });
145
+ }
146
+ upsertPeerCard(peerId, content, body = {}) {
147
+ return this.request("POST", `/v1/peers/${encodeURIComponent(peerId)}/card`, { body: JSON.stringify({ workspace_id: this.workspaceId, ...body, content }) });
148
+ }
149
+ rebuildPeerCard(peerId, body = {}) {
150
+ return this.request("POST", `/v1/peers/${encodeURIComponent(peerId)}/card/rebuild`, { body: JSON.stringify({ workspace_id: this.workspaceId, ...body }) });
151
+ }
152
+ reviewPeerCard(peerId, params = {}) {
153
+ return this.request("POST", `/v1/peers/${encodeURIComponent(peerId)}/card/review`, {}, { workspace_id: this.workspaceId, ...params });
154
+ }
155
+ exportAgentBundle(agentId) {
156
+ return this.request("GET", `/v1/agents/${encodeURIComponent(agentId)}/bundle`);
157
+ }
158
+ importAgentBundle(agentId, bundle) {
159
+ return this.request("POST", `/v1/agents/${encodeURIComponent(agentId)}/bundle`, { body: JSON.stringify(bundle) });
160
+ }
161
+ createWebhook(url, body = {}) {
162
+ return this.request("POST", "/v1/webhooks", { body: JSON.stringify({ workspace_id: this.workspaceId, ...body, url }) });
163
+ }
164
+ listWebhooks(params = {}) {
165
+ return this.request("GET", "/v1/webhooks", {}, params);
166
+ }
167
+ testWebhook(body = {}) {
168
+ return this.request("POST", "/v1/webhooks/test", { body: JSON.stringify({ workspace_id: this.workspaceId, ...body }) });
169
+ }
170
+ webhookDeliveries(params = {}) {
171
+ return this.request("GET", "/v1/webhooks/deliveries", {}, params);
172
+ }
173
+ }
@@ -0,0 +1,18 @@
1
+ import type { ContextResponse } from "./types.js";
2
+ export declare class ContextPackage {
3
+ readonly data: ContextResponse;
4
+ constructor(data: ContextResponse);
5
+ toOpenAI(options?: {
6
+ assistantPeerId?: string;
7
+ }): Array<{
8
+ role: string;
9
+ content: string;
10
+ }>;
11
+ toAnthropic(options?: {
12
+ assistantPeerId?: string;
13
+ }): Array<{
14
+ role: string;
15
+ content: string;
16
+ }>;
17
+ raw(): ContextResponse;
18
+ }
@@ -0,0 +1,42 @@
1
+ export class ContextPackage {
2
+ data;
3
+ constructor(data) {
4
+ this.data = data;
5
+ }
6
+ toOpenAI(options = {}) {
7
+ const formatted = this.data.formatted_context;
8
+ if (Array.isArray(formatted))
9
+ return formatted;
10
+ if (formatted && typeof formatted === "object" && Array.isArray(formatted.messages)) {
11
+ return formatted.messages;
12
+ }
13
+ const messages = [];
14
+ if (options.assistantPeerId) {
15
+ messages.push({ role: "system", content: `Assistant peer id: ${options.assistantPeerId}` });
16
+ }
17
+ const summary = this.data.summary;
18
+ if (summary) {
19
+ messages.push({ role: "system", content: `HiveMem summary:\n${typeof summary === "string" ? summary : summary.content ?? ""}` });
20
+ }
21
+ const representation = this.data.representation;
22
+ if (representation) {
23
+ const content = typeof representation === "string" ? representation : representation.context;
24
+ if (content)
25
+ messages.push({ role: "system", content: `HiveMem peer context:\n${content}` });
26
+ }
27
+ for (const memory of (this.data.memories ?? [])) {
28
+ messages.push({ role: "system", content: `Memory: ${memory.content}` });
29
+ }
30
+ return messages;
31
+ }
32
+ toAnthropic(options = {}) {
33
+ const formatted = this.data.formatted_context;
34
+ if (Array.isArray(formatted))
35
+ return formatted;
36
+ const content = this.toOpenAI(options).map((message) => message.content).join("\n\n");
37
+ return content ? [{ role: "user", content }] : [];
38
+ }
39
+ raw() {
40
+ return this.data;
41
+ }
42
+ }
@@ -0,0 +1,7 @@
1
+ export declare class HiveMemError extends Error {
2
+ }
3
+ export declare class HiveMemHTTPError extends HiveMemError {
4
+ readonly statusCode: number;
5
+ readonly details: unknown;
6
+ constructor(statusCode: number, message: string, details?: unknown);
7
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,12 @@
1
+ export class HiveMemError extends Error {
2
+ }
3
+ export class HiveMemHTTPError extends HiveMemError {
4
+ statusCode;
5
+ details;
6
+ constructor(statusCode, message, details) {
7
+ super(message);
8
+ this.name = "HiveMemHTTPError";
9
+ this.statusCode = statusCode;
10
+ this.details = details;
11
+ }
12
+ }
@@ -0,0 +1,6 @@
1
+ export { HiveMem } from "./client.js";
2
+ export { ContextPackage } from "./context.js";
3
+ export { HiveMemError, HiveMemHTTPError } from "./errors.js";
4
+ export type * from "./types.js";
5
+ export { signHiveMemWebhookBody, verifyHiveMemWebhook } from "./webhooks.js";
6
+ export type { VerifyHiveMemWebhookOptions } from "./webhooks.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { HiveMem } from "./client.js";
2
+ export { ContextPackage } from "./context.js";
3
+ export { HiveMemError, HiveMemHTTPError } from "./errors.js";
4
+ export { signHiveMemWebhookBody, verifyHiveMemWebhook } from "./webhooks.js";
@@ -0,0 +1,178 @@
1
+ export type MemoryScope = "private" | "shared";
2
+ export type MemoryType = "episodic" | "semantic" | "procedural";
3
+ export type WebhookEventType = "memory.created" | "session.created" | "queue.empty" | "summary.updated" | "peer_card.updated" | "conflict.detected" | "webhook.test";
4
+ export interface HiveMemOptions {
5
+ baseUrl?: string;
6
+ token?: string;
7
+ workspaceId?: string;
8
+ timeoutMs?: number;
9
+ maxRetries?: number;
10
+ fetchImpl?: typeof fetch;
11
+ requestIdProvider?: () => string;
12
+ authRefresh?: () => string | undefined | Promise<string | undefined>;
13
+ onRequest?: (method: string, url: string, init: RequestInit) => void;
14
+ onResponse?: (response: Response) => void;
15
+ }
16
+ export interface MemoryRecord {
17
+ id: string;
18
+ agent_id: string;
19
+ content: string;
20
+ type: MemoryType;
21
+ scope: MemoryScope;
22
+ source?: string;
23
+ confidence?: number;
24
+ importance?: number;
25
+ tags?: string[];
26
+ metadata?: Record<string, unknown>;
27
+ workspace_id?: string;
28
+ session_id?: string | null;
29
+ created_at?: string;
30
+ updated_at?: string;
31
+ observed_at?: string | null;
32
+ expires_at?: string | null;
33
+ valid_from?: string | null;
34
+ valid_to?: string | null;
35
+ supersedes?: string | null;
36
+ superseded_by?: string | null;
37
+ superseded_at?: string | null;
38
+ [key: string]: unknown;
39
+ }
40
+ export interface SearchResponse {
41
+ results: Array<{
42
+ memory: MemoryRecord;
43
+ score: number;
44
+ collection: string;
45
+ is_own: boolean;
46
+ explanation?: {
47
+ vector_score: number;
48
+ importance_boost: number;
49
+ text_match: boolean;
50
+ final_score: number;
51
+ } | null;
52
+ citation?: {
53
+ memory_id: string;
54
+ publisher: string;
55
+ source_ref: string | null;
56
+ revision: string | null;
57
+ observed_at: string | null;
58
+ valid_from: string | null;
59
+ valid_to: string | null;
60
+ expires_at: string | null;
61
+ freshness: "current" | "live_recheck" | "historical";
62
+ relationship_path: string[];
63
+ };
64
+ score_components?: Record<string, number | null>;
65
+ selection_reason?: "query" | "relationship" | "entity";
66
+ }>;
67
+ total_searched: number;
68
+ collections_searched: string[];
69
+ }
70
+ export interface SessionRecord {
71
+ session_id: string;
72
+ owner_agent_id: string;
73
+ scope: MemoryScope;
74
+ title?: string | null;
75
+ workspace_id: string;
76
+ metadata?: Record<string, unknown>;
77
+ created_at: string;
78
+ updated_at: string;
79
+ deleted_at?: string | null;
80
+ }
81
+ export interface QueueStatusResponse {
82
+ jobs: unknown[];
83
+ total: number;
84
+ pending_count: number;
85
+ in_progress_count: number;
86
+ failed_count: number;
87
+ dead_letter_count: number;
88
+ offset: number;
89
+ limit: number;
90
+ }
91
+ export interface QueueJobRecord {
92
+ id: string;
93
+ task_type: string;
94
+ status: "pending" | "in_progress" | "completed" | "failed" | "dead_letter" | "cancelled";
95
+ work_unit_key: string;
96
+ payload: Record<string, unknown>;
97
+ owner_agent_id: string;
98
+ workspace_id: string;
99
+ session_id: string | null;
100
+ peer_id: string | null;
101
+ observer_peer_id: string | null;
102
+ observed_peer_id: string | null;
103
+ idempotency_key: string;
104
+ priority: number;
105
+ retry_count: number;
106
+ created_at: string;
107
+ not_before: string | null;
108
+ started_at: string | null;
109
+ finished_at: string | null;
110
+ locked_at: string | null;
111
+ error: string | null;
112
+ result: Record<string, unknown> | null;
113
+ }
114
+ export type ConclusionKind = "explicit" | "deductive" | "inductive" | "abductive" | "summary" | "peer_card" | "manual";
115
+ export interface ConclusionRecord {
116
+ id: string;
117
+ owner_agent_id: string;
118
+ observer_peer_id: string;
119
+ observed_peer_id: string;
120
+ session_id: string | null;
121
+ workspace_id: string;
122
+ source_memory_ids: string[];
123
+ content: string;
124
+ kind: ConclusionKind;
125
+ confidence: number;
126
+ metadata: Record<string, unknown>;
127
+ created_at: string;
128
+ updated_at: string;
129
+ supersedes: string | null;
130
+ superseded_by: string | null;
131
+ deleted_at: string | null;
132
+ }
133
+ export interface ConclusionPage {
134
+ results: ConclusionRecord[];
135
+ next_cursor: string | null;
136
+ }
137
+ export interface WebhookEndpoint {
138
+ id: string;
139
+ owner_agent_id: string;
140
+ workspace_id: string;
141
+ url: string;
142
+ event_types: WebhookEventType[];
143
+ enabled: boolean;
144
+ has_secret: boolean;
145
+ headers: Record<string, string>;
146
+ metadata: Record<string, unknown>;
147
+ created_at: string;
148
+ updated_at: string;
149
+ deleted_at?: string | null;
150
+ }
151
+ export interface ContextResponse {
152
+ summary?: unknown;
153
+ memories?: MemoryRecord[];
154
+ representation?: unknown;
155
+ formatted_context?: unknown;
156
+ [key: string]: unknown;
157
+ }
158
+ export interface PeerCardResponse {
159
+ peer_id: string;
160
+ observer_peer_id: string;
161
+ workspace_id: string;
162
+ cards: unknown[];
163
+ generated_at: string;
164
+ }
165
+ export interface KnowledgeSourceSyncResponse {
166
+ mode: "preview" | "apply";
167
+ workspace_id: string;
168
+ project_id: string;
169
+ source_id: string;
170
+ revision: string;
171
+ created: number;
172
+ superseded: number;
173
+ retired: number;
174
+ unchanged: number;
175
+ created_ids: string[];
176
+ superseded_ids: string[];
177
+ retired_ids: string[];
178
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ export interface VerifyHiveMemWebhookOptions {
2
+ secret: string;
3
+ body: string | Uint8Array;
4
+ signature: string;
5
+ timestamp: string;
6
+ nonce: string;
7
+ toleranceSeconds?: number;
8
+ seenNonces?: Set<string>;
9
+ }
10
+ export declare function signHiveMemWebhookBody(secret: string, body: string | Uint8Array, timestamp: string, nonce: string): Promise<string>;
11
+ export declare function verifyHiveMemWebhook(options: VerifyHiveMemWebhookOptions): Promise<boolean>;
@@ -0,0 +1,56 @@
1
+ const encoder = new TextEncoder();
2
+ function bytes(value) {
3
+ return typeof value === "string" ? encoder.encode(value) : value;
4
+ }
5
+ function concatBytes(parts) {
6
+ const total = parts.reduce((sum, part) => sum + part.length, 0);
7
+ const out = new Uint8Array(total);
8
+ let offset = 0;
9
+ for (const part of parts) {
10
+ out.set(part, offset);
11
+ offset += part.length;
12
+ }
13
+ return out;
14
+ }
15
+ function hex(input) {
16
+ return Array.from(new Uint8Array(input), byte => byte.toString(16).padStart(2, "0")).join("");
17
+ }
18
+ async function hmacSha256(secret, data) {
19
+ const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
20
+ return hex(await crypto.subtle.sign("HMAC", key, data));
21
+ }
22
+ function constantTimeEqual(a, b) {
23
+ if (a.length !== b.length)
24
+ return false;
25
+ let diff = 0;
26
+ for (let i = 0; i < a.length; i += 1)
27
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
28
+ return diff === 0;
29
+ }
30
+ export async function signHiveMemWebhookBody(secret, body, timestamp, nonce) {
31
+ const signed = concatBytes([bytes(timestamp), bytes("."), bytes(nonce), bytes("."), bytes(body)]);
32
+ return `sha256=${await hmacSha256(secret, signed)}`;
33
+ }
34
+ export async function verifyHiveMemWebhook(options) {
35
+ const toleranceSeconds = options.toleranceSeconds ?? 300;
36
+ if (!/^\d+$/.test(options.timestamp) || !Number.isFinite(toleranceSeconds) || toleranceSeconds < 0)
37
+ return false;
38
+ const ts = Number(options.timestamp);
39
+ if (!Number.isSafeInteger(ts))
40
+ return false;
41
+ if (Math.abs(Math.floor(Date.now() / 1000) - ts) > toleranceSeconds)
42
+ return false;
43
+ if (!options.nonce)
44
+ return false;
45
+ if (options.seenNonces?.has(options.nonce))
46
+ return false;
47
+ const expected = await signHiveMemWebhookBody(options.secret, options.body, options.timestamp, options.nonce);
48
+ if (!constantTimeEqual(options.signature, expected))
49
+ return false;
50
+ // Signing yields to WebCrypto. Recheck after it resolves so concurrent calls
51
+ // sharing this set cannot both accept the same valid nonce.
52
+ if (options.seenNonces?.has(options.nonce))
53
+ return false;
54
+ options.seenNonces?.add(options.nonce);
55
+ return true;
56
+ }
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@hivemagnus/hivemem-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "TypeScript client for HiveMem, the shared long-term memory service for AI agents",
5
+ "keywords": [
6
+ "hivemem",
7
+ "hive",
8
+ "memory",
9
+ "agents",
10
+ "ai",
11
+ "llm",
12
+ "rag",
13
+ "context",
14
+ "sdk"
15
+ ],
16
+ "homepage": "https://github.com/ChefTaco/hive/tree/main/services/hive-mem/sdks/typescript#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/ChefTaco/hive/issues"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/ChefTaco/hive.git",
23
+ "directory": "services/hive-mem/sdks/typescript"
24
+ },
25
+ "license": "Apache-2.0",
26
+ "author": "ChefTaco",
27
+ "type": "module",
28
+ "main": "./dist/index.js",
29
+ "types": "./dist/index.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "import": "./dist/index.js",
34
+ "default": "./dist/index.js"
35
+ },
36
+ "./package.json": "./package.json"
37
+ },
38
+ "files": [
39
+ "dist",
40
+ "README.md",
41
+ "LICENSE"
42
+ ],
43
+ "sideEffects": false,
44
+ "engines": {
45
+ "node": ">=18.17"
46
+ },
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "scripts": {
51
+ "build": "tsc -p tsconfig.json",
52
+ "typecheck": "tsc -p tsconfig.json --noEmit",
53
+ "test": "node --test test/*.test.mjs",
54
+ "prepublishOnly": "npm run build && npm test"
55
+ },
56
+ "devDependencies": {
57
+ "typescript": "^5.6.0"
58
+ }
59
+ }