Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
336 lines (292 loc) · 13.3 KB
/
Copy pathserver.ts
File metadata and controls
336 lines (292 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// bb-plugin-noema — federated agentic memory for BB.
//
// Bridges BB threads into **your own** Noema cortex over Noema's Streamable
// HTTP MCP endpoint (default http://127.0.0.1:3004). Not a hosted service —
// you run the Noema server yourself (`noema serve --transport http`).
//
// Registers six native agent tools that mirror Hermes's Noema access:
// noema_search, noema_remember, noema_recall, noema_list, noema_update, noema_lineage.
//
// Tools call the configured Streamable HTTP MCP endpoint (≥0.20.0) with full
// session lifecycle management (initialize, re-initialize on 404 expiry).
import { type BbPluginApi } from "@get-bb/plugin-sdk";
import { z } from "zod";
// ─── Noema MCP HTTP client ───────────────────────────────────────────
class NoemaClient {
private sessionId: string | null = null;
private initPromise: Promise<void> | null = null;
constructor(
private baseUrl: string,
private accessKey?: string,
) {}
private authHeaders(): Record<string, string> {
const h: Record<string, string> = {
"Content-Type": "application/json",
Accept: "application/json, text/event-stream",
};
if (this.accessKey) h["Authorization"] = `Bearer ${this.accessKey}`;
return h;
}
private async initialize(): Promise<void> {
// Serialize init calls so concurrent tool invocations don't race
if (this.initPromise) return this.initPromise;
this.initPromise = this._doInit();
try {
await this.initPromise;
} finally {
this.initPromise = null;
}
}
private async _doInit(): Promise<void> {
const body = JSON.stringify({
jsonrpc: "2.0",
method: "initialize",
params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "bb-plugin-noema", version: "0.2.1" } },
id: 1,
});
const resp = await fetch(`${this.baseUrl}/mcp`, {
method: "POST",
headers: this.authHeaders(),
body,
});
if (!resp.ok) throw new Error(`Noema init failed: HTTP ${resp.status}`);
const sid = resp.headers.get("mcp-session-id");
const text = await resp.text();
// Streamable HTTP: response is SSE-framed. Parse data: lines for the
// initialize result (message id 1).
let gotInit = false;
for (const line of text.split("\n")) {
if (line.startsWith("data: ") && line.length > 6) {
const msg = JSON.parse(line.slice(6));
if (msg.id === 1) {
gotInit = true;
if (msg.error) throw new Error(`Noema init error: ${msg.error.message}`);
}
}
}
if (!gotInit) throw new Error("Noema init: no initialize response in SSE stream");
if (!sid) throw new Error("Noema init: no Mcp-Session-Id header");
// Noema 0.22.x requires the initialized notification before serving tool calls
await fetch(`${this.baseUrl}/mcp`, {
method: "POST",
headers: { ...this.authHeaders(), "Mcp-Session-Id": sid },
body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }),
});
this.sessionId = sid;
}
async callTool(name: string, args: Record<string, unknown>): Promise<unknown> {
if (!this.sessionId) await this.initialize();
const body = JSON.stringify({
jsonrpc: "2.0",
method: "tools/call",
params: { name, arguments: args },
id: 2,
});
const resp = await fetch(`${this.baseUrl}/mcp`, {
method: "POST",
headers: {
...this.authHeaders(),
"Mcp-Session-Id": this.sessionId!,
},
body,
});
// Session expired — reinitialize once and retry
if (resp.status === 404) {
this.sessionId = null;
await this.initialize();
return this.callTool(name, args);
}
if (!resp.ok) throw new Error(`Noema HTTP ${resp.status}`);
const text = await resp.text();
for (const line of text.split("\n")) {
if (line.startsWith("data: ") && line.length > 6) {
const msg = JSON.parse(line.slice(6));
if (msg.id === 2) {
if (msg.error) {
// Surface the MCP error text to the agent
throw new Error(`Noema: ${msg.error.message}`);
}
return msg.result;
}
}
}
throw new Error("Noema: no tool result in SSE response");
}
}
// ─── Agent tool schemas ──────────────────────────────────────────────
const searchSchema = z.object({ query: z.string().min(1).describe("Search query — keywords or natural phrases.") });
const rememberSchema = z.object({
title: z.string().min(1).max(100).describe("Short descriptive title (no date — ID prepends date automatically)."),
type: z.enum(["fact", "decision", "preference", "context", "skill", "intent", "observation", "note"]).describe("Memory type."),
body: z.string().min(1).describe("Full content of the memory (markdown)."),
tags: z.string().optional().describe("Comma-separated keyword tags."),
derived_from: z.string().optional().describe("Comma-separated trace IDs this memory was derived from."),
});
const recallSchema = z.object({ id: z.string().min(1).describe("Trace ID (e.g. 20260412-my-trace).") });
const listSchema = z.object({
type: z.string().optional().describe("Filter by trace type."),
author: z.string().optional().describe("Filter by author."),
tag: z.string().optional().describe("Filter by tag."),
origin: z.string().optional().describe("Filter by origin cortex."),
});
const updateSchema = z.object({
id: z.string().min(1).describe("Trace ID to update."),
title: z.string().max(100).optional().describe("New title."),
type: z.enum(["fact", "decision", "preference", "context", "skill", "intent", "observation", "note"]).optional().describe("New type."),
body: z.string().optional().describe("New body content."),
tags: z.string().optional().describe("New tags (comma-separated, replaces existing)."),
});
const lineageSchema = z.object({ id: z.string().min(1).describe("Trace ID to query the derivation graph for.") });
// ─── Plugin entry ────────────────────────────────────────────────────
export default async function plugin(bb: BbPluginApi) {
bb.log.info("bb-plugin-noema loaded");
const settings = bb.settings.define({
noemaHttpUrl: {
type: "string",
label: "Noema HTTP URL",
default: process.env.NOEMA_HTTP_URL ?? "http://127.0.0.1:3004",
description: "Your local Noema server's Streamable HTTP MCP endpoint (noema serve --transport http)",
},
noemaActivityJournal: {
type: "boolean",
label: "Activity journal",
default: true,
description: "Append one metadata line to an 'Activity journal' trace in Noema whenever a thread goes idle",
},
noemaAccessKey: {
type: "string",
label: "MCP access key",
default: process.env.NOEMA_MCP_KEY ?? "",
secret: true,
},
});
let { noemaHttpUrl, noemaAccessKey, noemaActivityJournal } = await settings.get();
// Re-read settings on change without a plugin reload.
settings.onChange((next) => {
({ noemaHttpUrl, noemaAccessKey, noemaActivityJournal } = next);
client = new NoemaClient(noemaHttpUrl, noemaAccessKey || undefined);
bb.log.info(`[noema] server URL updated → ${noemaHttpUrl}`);
});
let client = new NoemaClient(noemaHttpUrl, noemaAccessKey || undefined);
bb.log.info(`Noema client → ${noemaHttpUrl} (local Noema server)`);
// Noema 0.22.x renamed its MCP tools; map agent-facing names to server tools.
const serverTools = {
noema_search: "search_traces",
noema_remember: "create_trace",
noema_recall: "get_trace",
noema_list: "list_traces",
noema_update: "update_trace",
noema_lineage: "trace_lineage",
};
// ── Register agent tools ─────────────────────────────────────────
bb.agents.registerTool({
name: "noema_search",
description: `Search your Noema memory for relevant traces. Returns matching memories ranked by relevance (FTS5 full-text search)`,
parameters: searchSchema,
async execute({ query }, { threadId }) {
bb.log.info(`[noema] thread ${threadId}: noema_search '${query}'`);
const result = await client.callTool(serverTools.noema_search, { query });
return typeof result === "string" ? result : JSON.stringify(result, null, 2);
},
});
bb.agents.registerTool({
name: "noema_remember",
description: `Create a new memory trace in Noema. Choose a type that reflects the intent: fact, decision, preference, context, skill, intent, observation, or note`,
parameters: rememberSchema,
async execute(args) {
// Strip undefined optional fields so Noema doesn't receive them
const clean: Record<string, unknown> = {};
for (const [k, v] of Object.entries(args)) {
if (v !== undefined) clean[k] = v;
}
const result = await client.callTool(serverTools.noema_remember, clean);
return typeof result === "string" ? result : JSON.stringify(result, null, 2);
},
});
bb.agents.registerTool({
name: "noema_recall",
description: `Read a specific Noema memory trace by ID, including its full body`,
parameters: recallSchema,
async execute({ id }) {
const result = await client.callTool(serverTools.noema_recall, { id });
return typeof result === "string" ? result : JSON.stringify(result, null, 2);
},
});
bb.agents.registerTool({
name: "noema_list",
description: `List Noema memory traces, optionally filtered by type, author, tag, or origin`,
parameters: listSchema,
async execute(args) {
const clean: Record<string, unknown> = {};
for (const [k, v] of Object.entries(args)) {
if (v !== undefined) clean[k] = v;
}
const result = await client.callTool(serverTools.noema_list, clean);
return typeof result === "string" ? result : JSON.stringify(result, null, 2);
},
});
bb.agents.registerTool({
name: "noema_update",
description: `Update fields of an existing Noema memory trace. Only provided fields are changed`,
parameters: updateSchema,
async execute(args) {
const clean: Record<string, unknown> = {};
for (const [k, v] of Object.entries(args)) {
if (v !== undefined) clean[k] = v;
}
const result = await client.callTool(serverTools.noema_update, clean);
return typeof result === "string" ? result : JSON.stringify(result, null, 2);
},
});
bb.agents.registerTool({
name: "noema_lineage",
description: `Show the derivation graph for a Noema trace: what it was derived from and what derives from it`,
parameters: lineageSchema,
async execute({ id }) {
const result = await client.callTool(serverTools.noema_lineage, { id });
return typeof result === "string" ? result : JSON.stringify(result, null, 2);
},
});
// ── Activity journal ──────────────────────────────────────────────
// Observe-only side channel: one metadata line per idle transition in a
// dedicated "Activity journal" trace. Never injects into conversations
// and never stores thread content — only when a thread finished.
if (noemaActivityJournal) {
let journalTraceId: string | null = null;
const journalIdPattern = /\d{8}-activity-journal/;
async function writeJournalLine(line: string) {
if (!journalTraceId) {
// Re-discover the journal after a plugin restart; create it once.
const found = await client.callTool(serverTools.noema_search, { query: "Activity journal" });
journalTraceId = JSON.stringify(found).match(journalIdPattern)?.[0] ?? null;
}
if (!journalTraceId) {
const created = await client.callTool(serverTools.noema_remember, {
title: "Activity journal",
type: "note",
tags: "journal,bb",
body: "# BB thread activity journal\n",
});
journalTraceId = JSON.stringify(created).match(journalIdPattern)?.[0] ?? null;
}
if (!journalTraceId) {
bb.log.warn("[noema] could not resolve activity journal trace id");
return;
}
await client.callTool("append_trace", { id: journalTraceId, content: line });
}
bb.events.on("thread.idle", ({ thread }) => {
writeJournalLine(`- ${new Date().toISOString()} thread ${thread.id} (project ${thread.projectId}) went idle`)
.catch((e) => bb.log.warn(`[noema] activity journal write failed: ${e instanceof Error ? e.message : String(e)}`));
});
bb.events.on("thread.failed", ({ thread, error }) => {
bb.log.warn(`[noema] thread ${thread.id} failed${error ? `: ${error}` : ""}`);
writeJournalLine(`- ${new Date().toISOString()} FAILED thread ${thread.id} (project ${thread.projectId})${error ? `: ${error}` : ""}`)
.catch((e) => bb.log.warn(`[noema] activity journal write failed: ${e instanceof Error ? e.message : String(e)}`));
});
}
// ── Cleanup ──────────────────────────────────────────────────────
bb.onDispose(() => {
bb.log.info("bb-plugin-noema disposed");
});
}