-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbm-client.ts
More file actions
881 lines (749 loc) · 21.8 KB
/
bm-client.ts
File metadata and controls
881 lines (749 loc) · 21.8 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
import { setTimeout as delay } from "node:timers/promises"
import { Client } from "@modelcontextprotocol/sdk/client"
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
import { log } from "./logger.ts"
const DEFAULT_RETRY_DELAYS_MS = [500, 1000, 2000]
export class NoteAlreadyExistsError extends Error {
readonly permalink: string
constructor(title: string, permalink: string) {
super(`Note already exists: "${title}" (${permalink})`)
this.name = "NoteAlreadyExistsError"
this.permalink = permalink
}
}
const REQUIRED_TOOLS = [
"search_notes",
"read_note",
"write_note",
"edit_note",
"build_context",
"recent_activity",
"list_memory_projects",
"list_workspaces",
"create_memory_project",
"delete_note",
"move_note",
"schema_validate",
"schema_infer",
"schema_diff",
]
export interface SearchResult {
title: string
permalink: string
content: string
score?: number
file_path: string
}
export interface NoteResult {
title: string
permalink: string
content: string
file_path: string
frontmatter?: Record<string, unknown> | null
checksum?: string | null
action?: "created" | "updated"
}
export interface EditNoteResult {
title: string
permalink: string
file_path: string
operation: "append" | "prepend" | "find_replace" | "replace_section"
checksum?: string | null
}
interface ReadNoteOptions {
includeFrontmatter?: boolean
}
interface EditNoteOptions {
find_text?: string
section?: string
expected_replacements?: number
}
export interface ContextResult {
results: Array<{
primary_result: NoteResult
observations: Array<{
category: string
content: string
}>
related_results: Array<{
type: "relation" | "entity"
title?: string
permalink: string
relation_type?: string
from_entity?: string
to_entity?: string
}>
}>
}
export interface RecentResult {
title: string
permalink: string
file_path: string
created_at: string
}
export interface ProjectListResult {
name: string
path: string
display_name?: string | null
is_private?: boolean
is_default?: boolean
isDefault?: boolean
workspace_name?: string | null
workspace_type?: string | null
workspace_tenant_id?: string | null
}
export interface WorkspaceResult {
tenant_id: string
name: string
workspace_type: string
role: string
organization_id?: string | null
has_active_subscription: boolean
}
export interface SchemaValidationResult {
entity_type: string | null
total_notes: number
total_entities: number
valid_count: number
warning_count: number
error_count: number
results: Array<{
identifier: string
valid: boolean
warnings: string[]
errors: string[]
}>
}
export interface SchemaInferResult {
entity_type: string
notes_analyzed: number
field_frequencies: Array<{
name: string
percentage: number
count: number
total: number
source: string
sample_values?: string[]
is_array?: boolean
target_type?: string | null
}>
suggested_schema: Record<string, unknown>
suggested_required: string[]
suggested_optional: string[]
excluded: string[]
}
export interface SchemaDiffResult {
entity_type: string
schema_found: boolean
new_fields: Array<{
name: string
source: string
count: number
total: number
percentage: number
}>
dropped_fields: Array<{ name: string; source: string; declared_in?: string }>
cardinality_changes: string[]
}
function getErrorMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err)
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value)
}
function extractTextFromContent(content: unknown): string {
if (!Array.isArray(content)) return ""
const textBlocks = content
.filter(
(block): block is { type: "text"; text: string } =>
isRecord(block) &&
block.type === "text" &&
typeof block.text === "string",
)
.map((block) => block.text)
return textBlocks.join("\n").trim()
}
function isRecoverableConnectionError(err: unknown): boolean {
const msg = getErrorMessage(err).toLowerCase()
return (
msg.includes("connection closed") ||
msg.includes("not connected") ||
msg.includes("transport") ||
msg.includes("broken pipe") ||
msg.includes("econnreset") ||
msg.includes("epipe") ||
msg.includes("failed to start bm mcp stdio") ||
msg.includes("client is closed")
)
}
function _isNoteNotFoundError(err: unknown): boolean {
const msg = getErrorMessage(err).toLowerCase()
return (
msg.includes("entity not found") ||
msg.includes("note not found") ||
msg.includes("resource not found") ||
msg.includes("could not find note matching") ||
msg.includes("404")
)
}
function asString(value: unknown): string | null {
return typeof value === "string" ? value : null
}
export class BmClient {
private bmPath: string
private project: string
private cwd?: string
private env?: Record<string, string>
private shouldRun = false
private client: Client | null = null
private transport: StdioClientTransport | null = null
private connectPromise: Promise<void> | null = null
private retryDelaysMs = [...DEFAULT_RETRY_DELAYS_MS]
constructor(bmPath: string, project: string) {
this.bmPath = bmPath
this.project = project
}
async start(options?: {
cwd?: string
env?: Record<string, string>
}): Promise<void> {
this.shouldRun = true
if (options?.cwd) {
this.cwd = options.cwd
}
if (options?.env) {
this.env = options.env
}
await this.connectWithRetries()
}
async stop(): Promise<void> {
this.shouldRun = false
await this.disconnectCurrent(this.client, this.transport)
this.client = null
this.transport = null
}
private async connectWithRetries(): Promise<void> {
let lastErr: unknown
for (let attempt = 0; attempt <= this.retryDelaysMs.length; attempt++) {
try {
await this.ensureConnected()
return
} catch (err) {
lastErr = err
await this.disconnectCurrent(this.client, this.transport)
this.client = null
this.transport = null
if (attempt === this.retryDelaysMs.length) {
break
}
const waitMs = this.retryDelaysMs[attempt]
log.warn(
`BM MCP connect failed (attempt ${attempt + 1}/${this.retryDelaysMs.length + 1}): ${getErrorMessage(err)}; retrying in ${waitMs}ms`,
)
await delay(waitMs)
}
}
throw new Error(`BM MCP unavailable: ${getErrorMessage(lastErr)}`)
}
private async ensureConnected(): Promise<Client> {
if (!this.shouldRun) {
this.shouldRun = true
}
if (this.client && this.transport) {
return this.client
}
if (!this.connectPromise) {
this.connectPromise = this.connectFresh()
}
try {
await this.connectPromise
} finally {
this.connectPromise = null
}
if (!this.client) {
throw new Error("BM MCP client was not initialized")
}
return this.client
}
private async connectFresh(): Promise<void> {
const transport = new StdioClientTransport({
command: this.bmPath,
args: ["mcp", "--transport", "stdio"],
cwd: this.cwd,
env: this.env,
stderr: "pipe",
})
const client = new Client(
{
name: "openclaw-basic-memory",
version: "0.1.0",
},
{ capabilities: {} },
)
const stderr = transport.stderr
if (stderr) {
stderr.on("data", (data: Buffer) => {
const msg = data.toString().trim()
if (msg.length > 0) {
log.debug(`[bm mcp] ${msg}`)
}
})
}
transport.onclose = () => {
if (this.transport !== transport) return
log.warn("BM MCP stdio session closed")
this.client = null
this.transport = null
}
transport.onerror = (err: unknown) => {
if (this.transport !== transport) return
log.warn(`BM MCP transport error: ${getErrorMessage(err)}`)
}
this.client = client
this.transport = transport
try {
await client.connect(transport)
const tools = await client.listTools()
this.assertRequiredTools(tools.tools.map((tool) => tool.name))
log.info(
`connected to BM MCP stdio (project=${this.project}, pid=${transport.pid ?? "unknown"})`,
)
} catch (err) {
await this.disconnectCurrent(client, transport)
if (this.client === client) {
this.client = null
}
if (this.transport === transport) {
this.transport = null
}
throw new Error(`failed to start BM MCP stdio: ${getErrorMessage(err)}`)
}
}
private assertRequiredTools(toolNames: string[]): void {
const available = new Set(toolNames)
const missing = REQUIRED_TOOLS.filter((name) => !available.has(name))
if (missing.length > 0) {
throw new Error(
`BM MCP server missing required tools: ${missing.join(", ")}`,
)
}
}
private async disconnectCurrent(
client: Client | null,
transport: StdioClientTransport | null,
): Promise<void> {
if (client) {
try {
await client.close()
} catch {
// ignore shutdown errors
}
}
if (transport) {
try {
await transport.close()
} catch {
// ignore shutdown errors
}
}
}
private async callToolRaw(
name: string,
args: Record<string, unknown>,
): Promise<unknown> {
let lastErr: unknown
for (let attempt = 0; attempt <= this.retryDelaysMs.length; attempt++) {
try {
const client = await this.ensureConnected()
const result = await client.callTool({
name,
arguments: args,
})
if (isRecord(result) && result.isError === true) {
const message = extractTextFromContent(result.content)
throw new Error(
`BM MCP tool ${name} failed${message ? `: ${message}` : ""}`,
)
}
return result
} catch (err) {
if (!isRecoverableConnectionError(err)) {
throw err
}
lastErr = err
await this.disconnectCurrent(this.client, this.transport)
this.client = null
this.transport = null
if (attempt === this.retryDelaysMs.length) {
break
}
const waitMs = this.retryDelaysMs[attempt]
log.warn(
`BM MCP call ${name} failed (attempt ${attempt + 1}/${this.retryDelaysMs.length + 1}): ${getErrorMessage(err)}; retrying in ${waitMs}ms`,
)
await delay(waitMs)
}
}
throw new Error(`BM MCP unavailable: ${getErrorMessage(lastErr)}`)
}
private async callTool(
name: string,
args: Record<string, unknown>,
): Promise<unknown> {
const result = await this.callToolRaw(name, args)
if (!isRecord(result) || result.structuredContent === undefined) {
throw new Error(`BM MCP tool ${name} returned no structured payload`)
}
const structuredPayload = result.structuredContent
if (isRecord(structuredPayload) && structuredPayload.result !== undefined) {
return structuredPayload.result
}
return structuredPayload
}
async ensureProject(projectPath: string): Promise<void> {
const payload = await this.callTool("create_memory_project", {
project_name: this.project,
project_path: projectPath,
set_default: true,
output_format: "json",
})
if (!isRecord(payload)) {
throw new Error("invalid create_memory_project response")
}
}
async listWorkspaces(): Promise<WorkspaceResult[]> {
const payload = await this.callTool("list_workspaces", {
output_format: "json",
})
if (isRecord(payload) && Array.isArray(payload.workspaces)) {
return payload.workspaces as WorkspaceResult[]
}
throw new Error("invalid list_workspaces response")
}
async listProjects(workspace?: string): Promise<ProjectListResult[]> {
const args: Record<string, unknown> = { output_format: "json" }
if (workspace) args.workspace = workspace
const payload = await this.callTool("list_memory_projects", args)
if (isRecord(payload) && Array.isArray(payload.projects)) {
return payload.projects as ProjectListResult[]
}
throw new Error("invalid list_memory_projects response")
}
async search(
query?: string,
limit = 10,
project?: string,
metadata?: {
filters?: Record<string, unknown>
tags?: string[]
status?: string
note_types?: string[]
entity_types?: string[]
},
): Promise<SearchResult[]> {
const args: Record<string, unknown> = {
page: 1,
page_size: limit,
output_format: "json",
}
if (query) args.query = query
if (project) args.project = project
if (metadata?.filters) args.metadata_filters = metadata.filters
if (metadata?.tags) args.tags = metadata.tags
if (metadata?.status) args.status = metadata.status
if (metadata?.note_types) args.note_types = metadata.note_types
if (metadata?.entity_types) args.entity_types = metadata.entity_types
const payload = await this.callTool("search_notes", args)
if (!isRecord(payload) || !Array.isArray(payload.results)) {
throw new Error("invalid search_notes response")
}
return payload.results as SearchResult[]
}
async readNote(
identifier: string,
options: ReadNoteOptions = {},
project?: string,
): Promise<NoteResult> {
const args: Record<string, unknown> = {
identifier,
include_frontmatter: options.includeFrontmatter === true,
output_format: "json",
}
if (project) args.project = project
const payload = await this.callTool("read_note", args)
if (!isRecord(payload)) {
throw new Error("invalid read_note response")
}
const title = asString(payload.title)
const permalink = asString(payload.permalink)
const content = asString(payload.content)
const filePath = asString(payload.file_path)
if (!title || !permalink || content === null || !filePath) {
throw new Error("invalid read_note payload")
}
return {
title,
permalink,
content,
file_path: filePath,
frontmatter: isRecord(payload.frontmatter) ? payload.frontmatter : null,
}
}
async writeNote(
title: string,
content: string,
folder: string,
project?: string,
overwrite?: boolean,
): Promise<NoteResult> {
const args: Record<string, unknown> = {
title,
content,
directory: folder,
output_format: "json",
}
if (project) args.project = project
if (overwrite !== undefined) args.overwrite = overwrite
const payload = await this.callTool("write_note", args)
if (!isRecord(payload)) {
throw new Error("invalid write_note response")
}
if (payload.error === "NOTE_ALREADY_EXISTS") {
throw new NoteAlreadyExistsError(
asString(payload.title) ?? title,
asString(payload.permalink) ?? "",
)
}
const resultTitle = asString(payload.title)
const permalink = asString(payload.permalink)
const filePath = asString(payload.file_path)
if (!resultTitle || !permalink || !filePath) {
throw new Error("invalid write_note payload")
}
return {
title: resultTitle,
permalink,
content,
file_path: filePath,
checksum: asString(payload.checksum),
action:
payload.action === "created" || payload.action === "updated"
? payload.action
: undefined,
}
}
async buildContext(
url: string,
depth = 1,
project?: string,
): Promise<ContextResult> {
const args: Record<string, unknown> = {
url,
depth,
output_format: "json",
}
if (project) args.project = project
const payload = await this.callTool("build_context", args)
if (!isRecord(payload) || !Array.isArray(payload.results)) {
throw new Error("invalid build_context response")
}
return payload as unknown as ContextResult
}
async recentActivity(
timeframe = "24h",
project?: string,
): Promise<RecentResult[]> {
const args: Record<string, unknown> = {
timeframe,
output_format: "json",
}
if (project) args.project = project
const payload = await this.callTool("recent_activity", args)
if (Array.isArray(payload)) {
return payload as RecentResult[]
}
throw new Error("invalid recent_activity response")
}
async editNote(
identifier: string,
operation: "append" | "prepend" | "find_replace" | "replace_section",
content: string,
options: EditNoteOptions = {},
project?: string,
): Promise<EditNoteResult> {
const args: Record<string, unknown> = {
identifier,
operation,
content,
output_format: "json",
}
if (options.find_text) args.find_text = options.find_text
if (options.section) args.section = options.section
if (options.expected_replacements != null)
args.expected_replacements = options.expected_replacements
if (project) args.project = project
const payload = await this.callTool("edit_note", args)
if (!isRecord(payload)) {
throw new Error("invalid edit_note response")
}
const title = asString(payload.title)
const permalink = asString(payload.permalink)
const filePath = asString(payload.file_path)
if (!title || !permalink || !filePath) {
throw new Error("invalid edit_note payload")
}
return {
title,
permalink,
file_path: filePath,
operation,
checksum: asString(payload.checksum),
}
}
async deleteNote(
identifier: string,
project?: string,
): Promise<{ title: string; permalink: string; file_path: string }> {
const args: Record<string, unknown> = {
identifier,
output_format: "json",
}
if (project) args.project = project
const payload = await this.callTool("delete_note", args)
if (!isRecord(payload)) {
throw new Error("invalid delete_note response")
}
if (payload.deleted !== true) {
throw new Error(`delete_note did not delete "${identifier}"`)
}
return {
title: asString(payload.title) ?? identifier,
permalink: asString(payload.permalink) ?? identifier,
file_path: asString(payload.file_path) ?? identifier,
}
}
async moveNote(
identifier: string,
newFolder: string,
project?: string,
): Promise<NoteResult> {
const args: Record<string, unknown> = {
identifier,
destination_folder: newFolder,
output_format: "json",
}
if (project) args.project = project
const payload = await this.callTool("move_note", args)
if (!isRecord(payload)) {
throw new Error("invalid move_note response")
}
if (payload.moved !== true) {
throw new Error(
asString(payload.error) ??
`move_note did not move "${identifier}" to "${newFolder}"`,
)
}
return {
title: asString(payload.title) ?? identifier,
permalink: asString(payload.permalink) ?? identifier,
content: "",
file_path: asString(payload.file_path) ?? "",
}
}
async schemaValidate(
noteType?: string,
identifier?: string,
project?: string,
): Promise<SchemaValidationResult> {
const args: Record<string, unknown> = { output_format: "json" }
if (noteType) args.note_type = noteType
if (identifier) args.identifier = identifier
if (project) args.project = project
const payload = await this.callTool("schema_validate", args)
if (!isRecord(payload)) {
throw new Error("invalid schema_validate response")
}
return payload as unknown as SchemaValidationResult
}
async schemaInfer(
noteType: string,
threshold = 0.25,
project?: string,
): Promise<SchemaInferResult> {
const args: Record<string, unknown> = {
note_type: noteType,
threshold,
output_format: "json",
}
if (project) args.project = project
const payload = await this.callTool("schema_infer", args)
if (!isRecord(payload)) {
throw new Error("invalid schema_infer response")
}
return payload as unknown as SchemaInferResult
}
async schemaDiff(
noteType: string,
project?: string,
): Promise<SchemaDiffResult> {
const args: Record<string, unknown> = {
note_type: noteType,
output_format: "json",
}
if (project) args.project = project
const payload = await this.callTool("schema_diff", args)
if (!isRecord(payload)) {
throw new Error("invalid schema_diff response")
}
return payload as unknown as SchemaDiffResult
}
async indexConversation(
userMessage: string,
assistantResponse: string,
): Promise<void> {
const now = new Date()
const dateStr = now.toISOString().split("T")[0]
const timeStr = now.toTimeString().slice(0, 5)
const title = `conversations-${dateStr}`
const entry = [
`### ${timeStr}`,
"",
"**User:**",
userMessage,
"",
"**Assistant:**",
assistantResponse,
"",
"---",
].join("\n")
// Try append first — if it fails for ANY reason, fall through to create
try {
await this.editNote(title, "append", entry)
log.debug(`appended conversation to: ${title}`)
return
} catch (err) {
log.debug(`append failed, will create: ${getErrorMessage(err)}`)
}
// Create the note with frontmatter and first entry
const content = [
"---",
`title: Conversations ${dateStr}`,
"type: Conversation",
`date: "${dateStr}"`,
"---",
"",
`# Conversations ${dateStr}`,
"",
entry,
].join("\n")
try {
await this.writeNote(title, content, "conversations", undefined, true)
log.debug(`created conversation note: ${title}`)
} catch (err) {
log.error("conversation index failed", err)
}
}
getProject(): string {
return this.project
}
}