hivemind-memory 2.31.0 → 2.31.1

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/README.md CHANGED
@@ -21,9 +21,11 @@ await using hive = await Hivemind.connect();
21
21
  console.log(hive.whoami);
22
22
  ```
23
23
 
24
+ `await using` closes the connection at the end of the block. It needs TypeScript 5.2 or later to compile it, or Node 24; in plain JavaScript on Node 22, call `await hive.close()` in a `finally` block instead.
25
+
24
26
  `connect()` reads `HIVEMIND_MCP_URL` (the `/mcp` endpoint) and `HIVEMIND_API_KEY`. You can pass `{ url, apiKey }` instead, and an option wins over the variable. If neither is set, it throws an error that names the variable. `connect()` calls `hive_whoami` and keeps the reply as `hive.whoami`; `await hive.refreshWhoami()` asks again. Without `await using`, call `await hive.close()` when you are done.
25
27
 
26
- Each tool has a method: `search`, `get`, `list`, `pinned`, `write`, `feedback`, `withdraw`, `pin`, `register`. Option keys are snake_case, exactly as the tool takes them, and only the values you set are sent.
28
+ Each tool has a method: `search`, `get`, `list`, `pinned`, `write`, `feedback`, `withdraw`, `pin`, `register`. Option keys are snake_case, exactly as the tool takes them, and only the values you set are sent. Each returns the reply as a plain object. What each option means and what comes back is in the tool descriptions, `hive.tools`, which are also what the model reads; the [spec](https://github.com/monochrome-muncher/hivemind/blob/main/SPEC.md#52-mcp-tools-the-agents-mental-model--ten-verbs) has the same in one place.
27
29
 
28
30
  ```ts
29
31
  const written = await hive.write("fact", "The staging DB is reset every Monday", { scope: "fleet" });
@@ -32,65 +34,72 @@ const found = await hive.search("when is staging reset?", { limit: 5 });
32
34
 
33
35
  ## A loop with the Anthropic Messages API
34
36
 
37
+ `instructions()` is the system prompt, `anthropicTools()` the tool list, and `runTool()` runs what the model asked for. When the model stops calling tools, the loop sends the end-of-task reminder once and lets the model answer it.
38
+
35
39
  ```ts
36
40
  import Anthropic from "@anthropic-ai/sdk";
37
41
  import { Hivemind } from "hivemind-memory";
38
42
 
39
- const anthropic = new Anthropic();
40
- await using hive = await Hivemind.connect();
41
-
42
- const messages: Anthropic.MessageParam[] = [{ role: "user", content: task }];
43
- while (true) {
44
- const response = await anthropic.messages.create({
45
- model: "claude-sonnet-4-5",
46
- max_tokens: 4096,
47
- system: hive.instructions(),
48
- tools: hive.anthropicTools(),
49
- messages,
50
- });
51
- messages.push({ role: "assistant", content: response.content });
52
- const calls = response.content.filter((b) => b.type === "tool_use");
53
- if (calls.length === 0) break;
54
- messages.push({
55
- role: "user",
56
- content: await Promise.all(
57
- calls.map(async (c) => ({
58
- type: "tool_result" as const,
59
- tool_use_id: c.id,
60
- content: await hive.runTool(c.name, c.input as object),
61
- })),
62
- ),
63
- });
43
+ async function run(task: string): Promise<void> {
44
+ const anthropic = new Anthropic();
45
+ await using hive = await Hivemind.connect();
46
+ const messages: Anthropic.MessageParam[] = [{ role: "user", content: task }];
47
+ let reminded = false;
48
+ while (true) {
49
+ const response = await anthropic.messages.create({
50
+ model: "claude-sonnet-5-5",
51
+ max_tokens: 4096,
52
+ system: hive.instructions(),
53
+ tools: hive.anthropicTools(),
54
+ messages,
55
+ });
56
+ messages.push({ role: "assistant", content: response.content });
57
+ const calls = response.content.filter((b) => b.type === "tool_use");
58
+ if (calls.length === 0) {
59
+ if (reminded) return;
60
+ messages.push({ role: "user", content: hive.reminder() });
61
+ reminded = true;
62
+ continue;
63
+ }
64
+ const results: Anthropic.ToolResultBlockParam[] = [];
65
+ for (const call of calls) {
66
+ results.push({ type: "tool_result", tool_use_id: call.id, content: await hive.runTool(call.name, call.input as object) });
67
+ }
68
+ messages.push({ role: "user", content: results });
69
+ }
64
70
  }
71
+
72
+ await run("Find out when the staging database is reset.");
65
73
  ```
66
74
 
67
75
  `runTool` returns the reply as JSON text and never throws on an error reply, so the model sees the refusal and can react. `openaiTools()` gives the same tools in the OpenAI function-calling shape. Neither needs the Anthropic or OpenAI package.
68
76
 
69
77
  ## The end-of-task reminder
70
78
 
71
- When a task ends, send `hive.reminder()` once as a user turn and let the agent answer. It asks the agent to write what others could reuse and to rate the entries its work tested. The same text is exported as `REMINDER`.
72
-
73
- ```ts
74
- messages.push({ role: "user", content: hive.reminder() });
75
- ```
79
+ When a task ends, send `hive.reminder()` once as a user turn and let the agent answer, as the loop above does. It asks the agent to write what others could reuse and to rate the entries its work tested. The same text is exported as `REMINDER`.
76
80
 
77
81
  ## Vercel AI SDK
78
82
 
79
- `hivemind-memory/ai-sdk` returns the tools as AI SDK tools. `ai` is an optional peer dependency, so install it yourself (version 7 or later).
83
+ `hivemind-memory/ai-sdk` returns the tools as AI SDK tools. `ai` is an optional peer dependency, so install it yourself (version 7 or later), with the provider package for your model.
80
84
 
81
85
  ```ts
82
- import { generateText } from "ai";
86
+ import { anthropic } from "@ai-sdk/anthropic";
87
+ import { generateText, stepCountIs } from "ai";
88
+ import { Hivemind } from "hivemind-memory";
83
89
  import { aiSdkTools, systemPrompt } from "hivemind-memory/ai-sdk";
84
90
 
91
+ await using hive = await Hivemind.connect();
85
92
  const { text } = await generateText({
86
- model,
93
+ model: anthropic("claude-sonnet-5-5"),
87
94
  tools: aiSdkTools(hive),
88
95
  system: systemPrompt(hive),
89
- prompt: task,
96
+ prompt: "Find out when the staging database is reset.",
97
+ stopWhen: stepCountIs(20),
90
98
  });
99
+ console.log(text);
91
100
  ```
92
101
 
93
- Errors reach the model as text, as with `runTool`.
102
+ Set `stopWhen`: by default `generateText` stops after one step, so the model would call a tool and never see the result. Errors reach the model as text, as with `runTool`. For the end-of-task reminder, run `generateText` once more with the returned `response.messages` and `hive.reminder()` as the next user message.
94
103
 
95
104
  ## Other frameworks
96
105
 
@@ -102,7 +111,7 @@ A key belongs to one agent, and one `Hivemind` object uses one key. To act as an
102
111
 
103
112
  ## Errors
104
113
 
105
- A refusal from the server throws `HivemindError`, with the server's code in `.code` (`not_found`, `permission_denied`, `invalid_input`, and so on). A rejected or locked key throws `AuthenticationError`, a subclass, from `connect()` (HTTP 401, or the codes `unauthenticated` and `key_locked`). Network and protocol failures are ordinary errors from the MCP SDK.
114
+ A refusal from the server throws `HivemindError`, with the server's code in `.code` (`not_found`, `permission_denied`, `invalid_input`, and so on). A rejected or locked key throws `AuthenticationError`, a subclass, with the code `unauthenticated` or `key_locked` and the server's message, from `connect()` or any later call. A failed call that carries no code becomes `tool_error`. Network and protocol failures are ordinary errors from the MCP SDK.
106
115
 
107
116
  ```ts
108
117
  import { HivemindError } from "hivemind-memory";
@@ -115,3 +124,12 @@ try {
115
124
  }
116
125
  }
117
126
  ```
127
+
128
+ ## Development
129
+
130
+ ```sh
131
+ npm ci
132
+ npm test
133
+ ```
134
+
135
+ `npm test` builds the package and runs the unit tests against a fake MCP server. `test/live.test.ts` runs against a real server when `HIVEMIND_LIVE=1`, `HIVEMIND_MCP_URL` and `HIVEMIND_API_KEY` are set. The skill and reminder under `text/` are copies of the plugin's files; do not edit them here.
package/dist/client.d.ts CHANGED
@@ -6,6 +6,7 @@ export interface ConnectOptions {
6
6
  }
7
7
  export declare class Hivemind implements AsyncDisposable {
8
8
  private readonly client;
9
+ private readonly rejection;
9
10
  readonly tools: readonly ToolDefinition[];
10
11
  private serverInstructions;
11
12
  private current;
@@ -15,6 +16,7 @@ export declare class Hivemind implements AsyncDisposable {
15
16
  static connect(options?: ConnectOptions): Promise<Hivemind>;
16
17
  close(): Promise<void>;
17
18
  [Symbol.asyncDispose](): Promise<void>;
19
+ /** The reply text; a failed call that is not already the error envelope is wrapped in one. */
18
20
  private callText;
19
21
  call(name: string, args?: Record<string, unknown>): Promise<Reply>;
20
22
  /** For model loops: the reply JSON text, and an error envelope as text rather than a throw. */
package/dist/client.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
2
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
3
- import { AuthenticationError, HivemindError, errorFromEnvelope } from "./errors.js";
3
+ import { HivemindError, refusal, rejectedKey } from "./errors.js";
4
4
  import { toAnthropic, toOpenAI } from "./formats.js";
5
5
  import { REMINDER, VERSION, skillBody } from "./text.js";
6
6
  function setting(value, variable) {
@@ -16,16 +16,42 @@ function defined(args) {
16
16
  function errorText(code, message) {
17
17
  return JSON.stringify({ error: { code, message } });
18
18
  }
19
- function isUnauthorized(error) {
20
- return typeof error === "object" && error !== null && error.code === 401;
19
+ function parsed(text) {
20
+ try {
21
+ return JSON.parse(text);
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ }
27
+ /** Keeps why the server answered 401: the MCP SDK reports only the status. */
28
+ class Rejection {
29
+ seen;
30
+ fetch = async (url, init) => {
31
+ const response = await fetch(url, init);
32
+ if (response.status === 401) {
33
+ this.seen = rejectedKey(response.clone());
34
+ }
35
+ return response;
36
+ };
37
+ async throwIfSeen() {
38
+ if (this.seen) {
39
+ throw await this.seen;
40
+ }
41
+ }
42
+ forget() {
43
+ this.seen = undefined;
44
+ }
21
45
  }
22
46
  export class Hivemind {
23
47
  client;
48
+ rejection;
24
49
  tools;
25
50
  serverInstructions;
26
51
  current;
27
- constructor(client, tools, serverInstructions, current) {
52
+ constructor(client, rejection, tools, serverInstructions, current) {
28
53
  this.client = client;
54
+ this.rejection = rejection;
29
55
  this.tools = tools;
30
56
  this.serverInstructions = serverInstructions;
31
57
  this.current = current;
@@ -38,8 +64,10 @@ export class Hivemind {
38
64
  const url = setting(options.url, "HIVEMIND_MCP_URL");
39
65
  const apiKey = setting(options.apiKey, "HIVEMIND_API_KEY");
40
66
  const client = new Client({ name: "hivemind-memory", version: VERSION });
67
+ const rejection = new Rejection();
41
68
  const transport = new StreamableHTTPClientTransport(new URL(url), {
42
69
  requestInit: { headers: { Authorization: `Bearer ${apiKey}` } },
70
+ fetch: rejection.fetch,
43
71
  });
44
72
  try {
45
73
  await client.connect(transport);
@@ -49,15 +77,13 @@ export class Hivemind {
49
77
  description: t.description ?? "",
50
78
  inputSchema: t.inputSchema,
51
79
  }));
52
- const hive = new Hivemind(client, tools, client.getInstructions() ?? "", {});
80
+ const hive = new Hivemind(client, rejection, tools, client.getInstructions() ?? "", {});
53
81
  await hive.refreshWhoami();
54
82
  return hive;
55
83
  }
56
84
  catch (error) {
57
85
  await client.close().catch(() => undefined);
58
- if (isUnauthorized(error)) {
59
- throw new AuthenticationError("unauthenticated", "the server rejected the API key (HTTP 401)");
60
- }
86
+ await rejection.throwIfSeen();
61
87
  throw error;
62
88
  }
63
89
  }
@@ -67,54 +93,51 @@ export class Hivemind {
67
93
  async [Symbol.asyncDispose]() {
68
94
  await this.close();
69
95
  }
96
+ /** The reply text; a failed call that is not already the error envelope is wrapped in one. */
70
97
  async callText(name, args) {
71
- const result = await this.client.callTool({ name, arguments: args });
72
- const first = result.content?.[0];
73
- const text = first?.type === "text" ? (first.text ?? "") : "";
74
- if (result.isError) {
75
- try {
76
- JSON.parse(text);
77
- return text;
78
- }
79
- catch {
80
- return errorText("tool_error", text || `${name} failed`);
81
- }
98
+ let result;
99
+ try {
100
+ result = await this.client.callTool({ name, arguments: args });
101
+ }
102
+ catch (error) {
103
+ await this.rejection.throwIfSeen();
104
+ throw error;
105
+ }
106
+ this.rejection.forget();
107
+ const blocks = (result.content ?? []);
108
+ const text = blocks.map((b) => (b.type === "text" ? (b.text ?? "") : "")).join("");
109
+ if (result.isError && !refusal(parsed(text))) {
110
+ return errorText("tool_error", text || `${name} failed`);
82
111
  }
83
112
  return text;
84
113
  }
85
114
  async call(name, args = {}) {
86
- const text = await this.callText(name, args);
87
- let parsed;
88
- try {
89
- parsed = JSON.parse(text);
90
- }
91
- catch {
92
- throw new HivemindError("invalid_reply", `${name} answered with text that is not JSON`);
115
+ const reply = parsed(await this.callText(name, args));
116
+ const error = refusal(reply);
117
+ if (error) {
118
+ throw error;
93
119
  }
94
- const envelope = parsed?.error;
95
- if (envelope && typeof envelope === "object") {
96
- throw errorFromEnvelope(envelope.code ?? "tool_error", envelope.message ?? "");
120
+ if (typeof reply !== "object" || reply === null || Array.isArray(reply)) {
121
+ throw new HivemindError("invalid_reply", `${name} did not answer with a JSON object`);
97
122
  }
98
- return parsed;
123
+ return reply;
99
124
  }
100
125
  /** For model loops: the reply JSON text, and an error envelope as text rather than a throw. */
101
126
  async runTool(name, args = {}) {
102
127
  if (!this.tools.some((t) => t.name === name)) {
103
128
  return errorText("invalid_input", `unknown tool ${name}`);
104
129
  }
105
- let parsed = args;
130
+ let input = args;
106
131
  if (typeof args === "string") {
107
- try {
108
- parsed = args.trim() === "" ? {} : JSON.parse(args);
109
- }
110
- catch {
132
+ input = args.trim() === "" ? {} : parsed(args);
133
+ if (input === undefined) {
111
134
  return errorText("invalid_input", `arguments for ${name} are not valid JSON`);
112
135
  }
113
136
  }
114
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
137
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
115
138
  return errorText("invalid_input", `arguments for ${name} must be a JSON object`);
116
139
  }
117
- return this.callText(name, parsed);
140
+ return this.callText(name, input);
118
141
  }
119
142
  async refreshWhoami() {
120
143
  this.current = await this.call("hive_whoami", {});
package/dist/errors.d.ts CHANGED
@@ -6,3 +6,7 @@ export declare class HivemindError extends Error {
6
6
  export declare class AuthenticationError extends HivemindError {
7
7
  }
8
8
  export declare function errorFromEnvelope(code: string, message: string): HivemindError;
9
+ /** The error behind a reply that is the `{"error": {"code", "message"}}` envelope, if it is one. */
10
+ export declare function refusal(reply: unknown): HivemindError | undefined;
11
+ /** The server's 401 body is `{"error": "key_locked" | "unauthorized", "detail": ...}`. */
12
+ export declare function rejectedKey(response: Response): Promise<AuthenticationError>;
package/dist/errors.js CHANGED
@@ -13,3 +13,22 @@ const AUTH_CODES = new Set(["unauthenticated", "key_locked"]);
13
13
  export function errorFromEnvelope(code, message) {
14
14
  return AUTH_CODES.has(code) ? new AuthenticationError(code, message) : new HivemindError(code, message);
15
15
  }
16
+ /** The error behind a reply that is the `{"error": {"code", "message"}}` envelope, if it is one. */
17
+ export function refusal(reply) {
18
+ if (typeof reply !== "object" || reply === null || Object.keys(reply).join() !== "error") {
19
+ return undefined;
20
+ }
21
+ const error = reply.error;
22
+ if (typeof error !== "object" || error === null) {
23
+ return undefined;
24
+ }
25
+ const { code, message } = error;
26
+ return errorFromEnvelope(String(code || ""), String(message || ""));
27
+ }
28
+ /** The server's 401 body is `{"error": "key_locked" | "unauthorized", "detail": ...}`. */
29
+ export async function rejectedKey(response) {
30
+ const body = (await response.json().catch(() => ({})));
31
+ const code = body?.error === "key_locked" ? "key_locked" : "unauthenticated";
32
+ const detail = typeof body?.detail === "string" && body.detail ? body.detail : "";
33
+ return new AuthenticationError(code, detail || "the server rejected the API key (HTTP 401)");
34
+ }
package/dist/formats.d.ts CHANGED
@@ -6,7 +6,10 @@ export interface ToolDefinition {
6
6
  export interface AnthropicTool {
7
7
  name: string;
8
8
  description: string;
9
- input_schema: Record<string, unknown>;
9
+ input_schema: {
10
+ type: "object";
11
+ [key: string]: unknown;
12
+ };
10
13
  }
11
14
  export interface OpenAITool {
12
15
  type: "function";
package/dist/formats.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export function toAnthropic(tools) {
2
- return tools.map((t) => ({ name: t.name, description: t.description, input_schema: t.inputSchema }));
2
+ return tools.map((t) => ({ name: t.name, description: t.description, input_schema: { ...t.inputSchema, type: "object" } }));
3
3
  }
4
4
  export function toOpenAI(tools) {
5
5
  return tools.map((t) => ({
package/package.json CHANGED
@@ -1,8 +1,24 @@
1
1
  {
2
2
  "name": "hivemind-memory",
3
- "version": "2.31.0",
3
+ "version": "2.31.1",
4
4
  "description": "Client for Hivemind, the shared memory service for AI agents: MCP tools, instructions and tool definitions for agents built outside the supported harnesses.",
5
5
  "license": "MIT",
6
+ "keywords": [
7
+ "agents",
8
+ "memory",
9
+ "mcp",
10
+ "hivemind",
11
+ "ai-sdk"
12
+ ],
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/monochrome-muncher/hivemind.git",
16
+ "directory": "clients/typescript"
17
+ },
18
+ "homepage": "https://github.com/monochrome-muncher/hivemind/tree/main/clients/typescript#readme",
19
+ "bugs": {
20
+ "url": "https://github.com/monochrome-muncher/hivemind/issues"
21
+ },
6
22
  "type": "module",
7
23
  "engines": {
8
24
  "node": ">=22"