@memoryrelay/plugin-memoryrelay-ai 0.10.1 → 0.11.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.
Files changed (2) hide show
  1. package/index.ts +3518 -25
  2. package/package.json +1 -1
package/index.ts CHANGED
@@ -1,12 +1,19 @@
1
1
  /**
2
- * OpenClaw Memory Plugin - MemoryRelay (Single File Version)
3
- * Version: 0.10.1
2
+ * OpenClaw Memory Plugin - MemoryRelay
3
+ * Version: 0.11.1 (Full Single-File)
4
+ *
5
+ * Long-term memory with vector search using MemoryRelay API.
6
+ * Provides auto-recall and auto-capture via lifecycle hooks.
7
+ * Includes: memories, entities, agents, sessions, decisions, patterns, projects.
8
+ *
9
+ * API: https://api.memoryrelay.net
10
+ * Docs: https://memoryrelay.ai
4
11
  */
5
12
 
6
13
  import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
7
14
 
8
15
  // ============================================================================
9
- // DebugLogger (Inlined)
16
+ // DebugLogger (Inlined from src/debug-logger.ts)
10
17
  // ============================================================================
11
18
 
12
19
  interface LogEntry {
@@ -81,7 +88,7 @@ class DebugLogger {
81
88
  }
82
89
 
83
90
  // ============================================================================
84
- // StatusReporter (Inlined)
91
+ // StatusReporter (Inlined from src/status-reporter.ts)
85
92
  // ============================================================================
86
93
 
87
94
  class StatusReporter {
@@ -104,32 +111,775 @@ class StatusReporter {
104
111
  }
105
112
  }
106
113
 
114
+ interface MemoryRelayConfig {
115
+ apiKey?: string;
116
+ agentId?: string;
117
+ apiUrl?: string;
118
+ autoCapture?: boolean;
119
+ autoRecall?: boolean;
120
+ recallLimit?: number;
121
+ recallThreshold?: number;
122
+ excludeChannels?: string[];
123
+ defaultProject?: string;
124
+ enabledTools?: string;
125
+ // Debug and logging options (v0.8.0)
126
+ debug?: boolean;
127
+ verbose?: boolean;
128
+ logFile?: string;
129
+ maxLogEntries?: number;
130
+ }
131
+
132
+ interface Memory {
133
+ id: string;
134
+ content: string;
135
+ agent_id: string;
136
+ user_id: string;
137
+ metadata: Record<string, string>;
138
+ entities: string[];
139
+ created_at: number;
140
+ updated_at: number;
141
+ }
142
+
143
+ interface SearchResult {
144
+ memory: Memory;
145
+ score: number;
146
+ }
147
+
148
+ interface Stats {
149
+ total_memories: number;
150
+ last_updated?: string;
151
+ }
152
+
107
153
  // ============================================================================
108
- // Plugin Code
154
+ // Utility Functions
109
155
  // ============================================================================
110
156
 
111
- const DEFAULT_API_URL = "https://api.memoryrelay.net";
157
+ /**
158
+ * Sleep for specified milliseconds
159
+ */
160
+ function sleep(ms: number): Promise<void> {
161
+ return new Promise((resolve) => setTimeout(resolve, ms));
162
+ }
112
163
 
113
- export default function plugin(api: OpenClawPluginApi): void {
114
- const cfg = api.pluginConfig as any;
115
-
164
+ /**
165
+ * Check if error is retryable (network/timeout errors)
166
+ */
167
+ function isRetryableError(error: unknown): boolean {
168
+ const errStr = String(error).toLowerCase();
169
+ return (
170
+ errStr.includes("timeout") ||
171
+ errStr.includes("econnrefused") ||
172
+ errStr.includes("enotfound") ||
173
+ errStr.includes("network") ||
174
+ errStr.includes("fetch failed") ||
175
+ errStr.includes("502") ||
176
+ errStr.includes("503") ||
177
+ errStr.includes("504")
178
+ );
179
+ }
180
+
181
+ /**
182
+ * Fetch with timeout
183
+ */
184
+ async function fetchWithTimeout(
185
+ url: string,
186
+ options: RequestInit,
187
+ timeoutMs: number,
188
+ ): Promise<Response> {
189
+ const controller = new AbortController();
190
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
191
+
192
+ try {
193
+ const response = await fetch(url, {
194
+ ...options,
195
+ signal: controller.signal,
196
+ });
197
+ clearTimeout(timeout);
198
+ return response;
199
+ } catch (err) {
200
+ clearTimeout(timeout);
201
+ if ((err as Error).name === "AbortError") {
202
+ throw new Error("Request timeout");
203
+ }
204
+ throw err;
205
+ }
206
+ }
207
+
208
+ // ============================================================================
209
+ // MemoryRelay API Client (Full Suite)
210
+ // ============================================================================
211
+
212
+ class MemoryRelayClient {
213
+ private debugLogger?: DebugLogger;
214
+ private statusReporter?: StatusReporter;
215
+
216
+ constructor(
217
+ private readonly apiKey: string,
218
+ private readonly agentId: string,
219
+ private readonly apiUrl: string = DEFAULT_API_URL,
220
+ debugLogger?: DebugLogger,
221
+ statusReporter?: StatusReporter,
222
+ ) {
223
+ this.debugLogger = debugLogger;
224
+ this.statusReporter = statusReporter;
225
+ }
226
+
227
+ /**
228
+ * Extract tool name from API path
229
+ */
230
+ private extractToolName(path: string): string {
231
+ // /v1/memories -> memory
232
+ // /v1/memories/batch -> memory_batch
233
+ // /v1/sessions/123/end -> session_end
234
+ const parts = path.split("/").filter(Boolean);
235
+ if (parts.length < 2) return "unknown";
236
+
237
+ let toolName = parts[1].replace(/s$/, ""); // Remove trailing 's'
238
+
239
+ // Check for specific endpoints
240
+ if (path.includes("/batch")) toolName += "_batch";
241
+ if (path.includes("/recall")) toolName += "_recall";
242
+ if (path.includes("/context")) toolName += "_context";
243
+ if (path.includes("/end")) toolName += "_end";
244
+ if (path.includes("/health")) return "memory_health";
245
+
246
+ return toolName;
247
+ }
248
+
249
+ /**
250
+ * Make HTTP request with retry logic and timeout
251
+ */
252
+ private async request<T>(
253
+ method: string,
254
+ path: string,
255
+ body?: unknown,
256
+ retryCount = 0,
257
+ ): Promise<T> {
258
+ const url = `${this.apiUrl}${path}`;
259
+ const startTime = Date.now();
260
+ const toolName = this.extractToolName(path);
261
+
262
+ try {
263
+ const response = await fetchWithTimeout(
264
+ url,
265
+ {
266
+ method,
267
+ headers: {
268
+ "Content-Type": "application/json",
269
+ Authorization: `Bearer ${this.apiKey}`,
270
+ "User-Agent": "openclaw-memory-memoryrelay/0.8.0",
271
+ },
272
+ body: body ? JSON.stringify(body) : undefined,
273
+ },
274
+ REQUEST_TIMEOUT_MS,
275
+ );
276
+
277
+ const duration = Date.now() - startTime;
278
+
279
+ if (!response.ok) {
280
+ const errorData = await response.json().catch(() => ({}));
281
+ const errorMsg = errorData.detail || errorData.message || "";
282
+ const error = new Error(
283
+ `MemoryRelay API error: ${response.status} ${response.statusText}` +
284
+ (errorMsg ? ` - ${errorMsg}` : ""),
285
+ );
286
+
287
+ // Log error
288
+ if (this.debugLogger) {
289
+ this.debugLogger.log({
290
+ timestamp: new Date().toISOString(),
291
+ tool: toolName,
292
+ method,
293
+ path,
294
+ duration,
295
+ status: "error",
296
+ responseStatus: response.status,
297
+ error: error.message,
298
+ retries: retryCount,
299
+ requestBody: this.debugLogger && body ? body : undefined,
300
+ });
301
+ }
302
+
303
+ // Track failure
304
+ if (this.statusReporter) {
305
+ this.statusReporter.recordFailure(toolName, `${response.status} ${errorMsg || response.statusText}`);
306
+ }
307
+
308
+ // Retry on 5xx errors
309
+ if (response.status >= 500 && retryCount < MAX_RETRIES) {
310
+ const delay = INITIAL_RETRY_DELAY_MS * Math.pow(2, retryCount);
311
+ await sleep(delay);
312
+ return this.request<T>(method, path, body, retryCount + 1);
313
+ }
314
+
315
+ throw error;
316
+ }
317
+
318
+ const result = await response.json();
319
+
320
+ // Log success
321
+ if (this.debugLogger) {
322
+ this.debugLogger.log({
323
+ timestamp: new Date().toISOString(),
324
+ tool: toolName,
325
+ method,
326
+ path,
327
+ duration,
328
+ status: "success",
329
+ responseStatus: response.status,
330
+ retries: retryCount,
331
+ requestBody: this.debugLogger && body ? body : undefined,
332
+ responseBody: this.debugLogger && result ? result : undefined,
333
+ });
334
+ }
335
+
336
+ // Track success
337
+ if (this.statusReporter) {
338
+ this.statusReporter.recordSuccess(toolName);
339
+ }
340
+
341
+ return result;
342
+ } catch (err) {
343
+ const duration = Date.now() - startTime;
344
+
345
+ // Log error
346
+ if (this.debugLogger) {
347
+ this.debugLogger.log({
348
+ timestamp: new Date().toISOString(),
349
+ tool: toolName,
350
+ method,
351
+ path,
352
+ duration,
353
+ status: "error",
354
+ error: String(err),
355
+ retries: retryCount,
356
+ requestBody: this.debugLogger && body ? body : undefined,
357
+ });
358
+ }
359
+
360
+ // Track failure
361
+ if (this.statusReporter) {
362
+ this.statusReporter.recordFailure(toolName, String(err));
363
+ }
364
+
365
+ // Retry on network errors
366
+ if (isRetryableError(err) && retryCount < MAX_RETRIES) {
367
+ const delay = INITIAL_RETRY_DELAY_MS * Math.pow(2, retryCount);
368
+ await sleep(delay);
369
+ return this.request<T>(method, path, body, retryCount + 1);
370
+ }
371
+
372
+ throw err;
373
+ }
374
+ }
375
+
376
+ // --------------------------------------------------------------------------
377
+ // Memory operations
378
+ // --------------------------------------------------------------------------
379
+
380
+ async store(
381
+ content: string,
382
+ metadata?: Record<string, string>,
383
+ options?: {
384
+ deduplicate?: boolean;
385
+ dedup_threshold?: number;
386
+ project?: string;
387
+ importance?: number;
388
+ tier?: string;
389
+ },
390
+ ): Promise<Memory> {
391
+ return this.request<Memory>("POST", "/v1/memories", {
392
+ content,
393
+ metadata,
394
+ agent_id: this.agentId,
395
+ ...options,
396
+ });
397
+ }
398
+
399
+ async search(
400
+ query: string,
401
+ limit: number = 5,
402
+ threshold: number = 0.3,
403
+ options?: {
404
+ include_confidential?: boolean;
405
+ include_archived?: boolean;
406
+ compress?: boolean;
407
+ max_context_tokens?: number;
408
+ project?: string;
409
+ tier?: string;
410
+ min_importance?: number;
411
+ },
412
+ ): Promise<SearchResult[]> {
413
+ const response = await this.request<{ data: SearchResult[] }>(
414
+ "POST",
415
+ "/v1/memories/search",
416
+ {
417
+ query,
418
+ limit,
419
+ threshold,
420
+ agent_id: this.agentId,
421
+ ...options,
422
+ },
423
+ );
424
+ return response.data || [];
425
+ }
426
+
427
+ async list(limit: number = 20, offset: number = 0): Promise<Memory[]> {
428
+ const response = await this.request<{ data: Memory[] }>(
429
+ "GET",
430
+ `/v1/memories?limit=${limit}&offset=${offset}&agent_id=${encodeURIComponent(this.agentId)}`,
431
+ );
432
+ return response.data || [];
433
+ }
434
+
435
+ async get(id: string): Promise<Memory> {
436
+ return this.request<Memory>("GET", `/v1/memories/${id}`);
437
+ }
438
+
439
+ async update(id: string, content: string, metadata?: Record<string, string>): Promise<Memory> {
440
+ return this.request<Memory>("PUT", `/v1/memories/${id}`, {
441
+ content,
442
+ metadata,
443
+ });
444
+ }
445
+
446
+ async delete(id: string): Promise<void> {
447
+ await this.request<void>("DELETE", `/v1/memories/${id}`);
448
+ }
449
+
450
+ async batchStore(
451
+ memories: Array<{ content: string; metadata?: Record<string, string> }>,
452
+ ): Promise<any> {
453
+ return this.request("POST", "/v1/memories/batch", {
454
+ memories,
455
+ agent_id: this.agentId,
456
+ });
457
+ }
458
+
459
+ async buildContext(
460
+ query: string,
461
+ limit?: number,
462
+ threshold?: number,
463
+ maxTokens?: number,
464
+ project?: string,
465
+ ): Promise<any> {
466
+ return this.request("POST", "/v1/memories/context", {
467
+ query,
468
+ limit,
469
+ threshold,
470
+ max_tokens: maxTokens,
471
+ agent_id: this.agentId,
472
+ project,
473
+ });
474
+ }
475
+
476
+ async promote(memoryId: string, importance: number, tier?: string): Promise<any> {
477
+ return this.request("PUT", `/v1/memories/${memoryId}/importance`, {
478
+ importance,
479
+ tier,
480
+ });
481
+ }
482
+
483
+ // --------------------------------------------------------------------------
484
+ // Entity operations
485
+ // --------------------------------------------------------------------------
486
+
487
+ async createEntity(
488
+ name: string,
489
+ type: string,
490
+ metadata?: Record<string, string>,
491
+ ): Promise<any> {
492
+ return this.request("POST", "/v1/entities", {
493
+ name,
494
+ type,
495
+ metadata,
496
+ agent_id: this.agentId,
497
+ });
498
+ }
499
+
500
+ async linkEntity(
501
+ entityId: string,
502
+ memoryId: string,
503
+ relationship?: string,
504
+ ): Promise<any> {
505
+ return this.request("POST", `/v1/entities/links`, {
506
+ entity_id: entityId,
507
+ memory_id: memoryId,
508
+ relationship,
509
+ });
510
+ }
511
+
512
+ async listEntities(limit: number = 20, offset: number = 0): Promise<any> {
513
+ return this.request("GET", `/v1/entities?limit=${limit}&offset=${offset}`);
514
+ }
515
+
516
+ async entityGraph(
517
+ entityId: string,
518
+ depth: number = 2,
519
+ maxNeighbors: number = 10,
520
+ ): Promise<any> {
521
+ return this.request(
522
+ "GET",
523
+ `/v1/entities/${entityId}/neighborhood?depth=${depth}&max_neighbors=${maxNeighbors}`,
524
+ );
525
+ }
526
+
527
+ // --------------------------------------------------------------------------
528
+ // Agent operations
529
+ // --------------------------------------------------------------------------
530
+
531
+ async listAgents(limit: number = 20): Promise<any> {
532
+ return this.request("GET", `/v1/agents?limit=${limit}`);
533
+ }
534
+
535
+ async createAgent(name: string, description?: string): Promise<any> {
536
+ return this.request("POST", "/v1/agents", { name, description });
537
+ }
538
+
539
+ async getAgent(id: string): Promise<any> {
540
+ return this.request("GET", `/v1/agents/${id}`);
541
+ }
542
+
543
+ // --------------------------------------------------------------------------
544
+ // Session operations
545
+ // --------------------------------------------------------------------------
546
+
547
+ async startSession(
548
+ title?: string,
549
+ project?: string,
550
+ metadata?: Record<string, string>,
551
+ ): Promise<any> {
552
+ return this.request("POST", "/v1/sessions", {
553
+ title,
554
+ project,
555
+ metadata,
556
+ agent_id: this.agentId,
557
+ });
558
+ }
559
+
560
+ async endSession(id: string, summary?: string): Promise<any> {
561
+ return this.request("PUT", `/v1/sessions/${id}/end`, { summary });
562
+ }
563
+
564
+ async getSession(id: string): Promise<any> {
565
+ return this.request("GET", `/v1/sessions/${id}`);
566
+ }
567
+
568
+ async listSessions(
569
+ limit: number = 20,
570
+ project?: string,
571
+ status?: string,
572
+ ): Promise<any> {
573
+ let path = `/v1/sessions?limit=${limit}`;
574
+ if (project) path += `&project=${encodeURIComponent(project)}`;
575
+ if (status) path += `&status=${encodeURIComponent(status)}`;
576
+ return this.request("GET", path);
577
+ }
578
+
579
+ // --------------------------------------------------------------------------
580
+ // Decision operations
581
+ // --------------------------------------------------------------------------
582
+
583
+ async recordDecision(
584
+ title: string,
585
+ rationale: string,
586
+ alternatives?: string,
587
+ project?: string,
588
+ tags?: string[],
589
+ status?: string,
590
+ ): Promise<any> {
591
+ return this.request("POST", "/v1/decisions", {
592
+ title,
593
+ rationale,
594
+ alternatives,
595
+ project_slug: project,
596
+ tags,
597
+ status,
598
+ agent_id: this.agentId,
599
+ });
600
+ }
601
+
602
+ async listDecisions(
603
+ limit: number = 20,
604
+ project?: string,
605
+ status?: string,
606
+ tags?: string,
607
+ ): Promise<any> {
608
+ let path = `/v1/decisions?limit=${limit}`;
609
+ if (project) path += `&project=${encodeURIComponent(project)}`;
610
+ if (status) path += `&status=${encodeURIComponent(status)}`;
611
+ if (tags) path += `&tags=${encodeURIComponent(tags)}`;
612
+ return this.request("GET", path);
613
+ }
614
+
615
+ async supersedeDecision(
616
+ id: string,
617
+ title: string,
618
+ rationale: string,
619
+ alternatives?: string,
620
+ tags?: string[],
621
+ ): Promise<any> {
622
+ return this.request("POST", `/v1/decisions/${id}/supersede`, {
623
+ title,
624
+ rationale,
625
+ alternatives,
626
+ tags,
627
+ });
628
+ }
629
+
630
+ async checkDecisions(
631
+ query: string,
632
+ project?: string,
633
+ limit?: number,
634
+ threshold?: number,
635
+ includeSuperseded?: boolean,
636
+ ): Promise<any> {
637
+ const params = new URLSearchParams();
638
+ params.set("query", query);
639
+ if (project) params.set("project", project);
640
+ if (limit !== undefined) params.set("limit", String(limit));
641
+ if (threshold !== undefined) params.set("threshold", String(threshold));
642
+ if (includeSuperseded) params.set("include_superseded", "true");
643
+ return this.request("GET", `/v1/decisions/check?${params.toString()}`);
644
+ }
645
+
646
+ // --------------------------------------------------------------------------
647
+ // Pattern operations
648
+ // --------------------------------------------------------------------------
649
+
650
+ async createPattern(
651
+ title: string,
652
+ description: string,
653
+ category?: string,
654
+ exampleCode?: string,
655
+ scope?: string,
656
+ tags?: string[],
657
+ sourceProject?: string,
658
+ ): Promise<any> {
659
+ return this.request("POST", "/v1/patterns", {
660
+ title,
661
+ description,
662
+ category,
663
+ example_code: exampleCode,
664
+ scope,
665
+ tags,
666
+ source_project: sourceProject,
667
+ });
668
+ }
669
+
670
+ async searchPatterns(
671
+ query: string,
672
+ category?: string,
673
+ project?: string,
674
+ limit?: number,
675
+ threshold?: number,
676
+ ): Promise<any> {
677
+ const params = new URLSearchParams();
678
+ params.set("query", query);
679
+ if (category) params.set("category", category);
680
+ if (project) params.set("project", project);
681
+ if (limit !== undefined) params.set("limit", String(limit));
682
+ if (threshold !== undefined) params.set("threshold", String(threshold));
683
+ return this.request("GET", `/v1/patterns/search?${params.toString()}`);
684
+ }
685
+
686
+ async adoptPattern(id: string, project: string): Promise<any> {
687
+ return this.request("POST", `/v1/patterns/${id}/adopt`, { project });
688
+ }
689
+
690
+ async suggestPatterns(project: string, limit?: number): Promise<any> {
691
+ let path = `/v1/patterns/suggest?project=${encodeURIComponent(project)}`;
692
+ if (limit) path += `&limit=${limit}`;
693
+ return this.request("GET", path);
694
+ }
695
+
696
+ // --------------------------------------------------------------------------
697
+ // Project operations
698
+ // --------------------------------------------------------------------------
699
+
700
+ async registerProject(
701
+ slug: string,
702
+ name: string,
703
+ description?: string,
704
+ stack?: Record<string, unknown>,
705
+ repoUrl?: string,
706
+ ): Promise<any> {
707
+ return this.request("POST", "/v1/projects", {
708
+ slug,
709
+ name,
710
+ description,
711
+ stack,
712
+ repo_url: repoUrl,
713
+ });
714
+ }
715
+
716
+ async listProjects(limit: number = 20): Promise<any> {
717
+ return this.request("GET", `/v1/projects?limit=${limit}`);
718
+ }
719
+
720
+ async getProject(slug: string): Promise<any> {
721
+ return this.request("GET", `/v1/projects/${encodeURIComponent(slug)}`);
722
+ }
723
+
724
+ async addProjectRelationship(
725
+ from: string,
726
+ to: string,
727
+ type: string,
728
+ metadata?: Record<string, unknown>,
729
+ ): Promise<any> {
730
+ return this.request("POST", `/v1/projects/${encodeURIComponent(from)}/relationships`, {
731
+ target_project: to,
732
+ relationship_type: type,
733
+ metadata,
734
+ });
735
+ }
736
+
737
+ async getProjectDependencies(project: string): Promise<any> {
738
+ return this.request(
739
+ "GET",
740
+ `/v1/projects/${encodeURIComponent(project)}/dependencies`,
741
+ );
742
+ }
743
+
744
+ async getProjectDependents(project: string): Promise<any> {
745
+ return this.request(
746
+ "GET",
747
+ `/v1/projects/${encodeURIComponent(project)}/dependents`,
748
+ );
749
+ }
750
+
751
+ async getProjectRelated(project: string): Promise<any> {
752
+ return this.request(
753
+ "GET",
754
+ `/v1/projects/${encodeURIComponent(project)}/related`,
755
+ );
756
+ }
757
+
758
+ async projectImpact(project: string, changeDescription: string): Promise<any> {
759
+ return this.request(
760
+ "POST",
761
+ `/v1/projects/impact-analysis`,
762
+ { project, change_description: changeDescription },
763
+ );
764
+ }
765
+
766
+ async getSharedPatterns(projectA: string, projectB: string): Promise<any> {
767
+ const params = new URLSearchParams();
768
+ params.set("a", projectA);
769
+ params.set("b", projectB);
770
+ return this.request(
771
+ "GET",
772
+ `/v1/projects/shared-patterns?${params.toString()}`,
773
+ );
774
+ }
775
+
776
+ async getProjectContext(project: string): Promise<any> {
777
+ return this.request(
778
+ "GET",
779
+ `/v1/projects/${encodeURIComponent(project)}/context`,
780
+ );
781
+ }
782
+
783
+ // --------------------------------------------------------------------------
784
+ // Health & stats
785
+ // --------------------------------------------------------------------------
786
+
787
+ async health(): Promise<{ status: string }> {
788
+ return this.request<{ status: string }>("GET", "/v1/health");
789
+ }
790
+
791
+ async stats(): Promise<Stats> {
792
+ const response = await this.request<{ data: Stats }>(
793
+ "GET",
794
+ `/v1/stats?agent_id=${encodeURIComponent(this.agentId)}`,
795
+ );
796
+ return {
797
+ total_memories: response.data?.total_memories ?? 0,
798
+ last_updated: response.data?.last_updated,
799
+ };
800
+ }
801
+
802
+ /**
803
+ * Export all memories as JSON
804
+ */
805
+ async export(): Promise<Memory[]> {
806
+ const allMemories: Memory[] = [];
807
+ let offset = 0;
808
+ const limit = 100;
809
+
810
+ while (true) {
811
+ const batch = await this.list(limit, offset);
812
+ if (batch.length === 0) break;
813
+ allMemories.push(...batch);
814
+ offset += limit;
815
+ if (batch.length < limit) break;
816
+ }
817
+
818
+ return allMemories;
819
+ }
820
+ }
821
+
822
+ // ============================================================================
823
+ // Pattern Detection (for auto-capture)
824
+ // ============================================================================
825
+
826
+ const CAPTURE_PATTERNS = [
827
+ /remember\s+(?:that\s+)?/i,
828
+ /(?:my|the)\s+(?:name|email|phone|address|preference)/i,
829
+ /important(?:ly)?[:\s]/i,
830
+ /always\s+(?:use|prefer|want)/i,
831
+ /(?:do|don't)\s+(?:like|want|prefer)/i,
832
+ /(?:api|key|token|password|secret)(?:\s+is)?[:\s]/i,
833
+ /(?:ssh|server|host|ip|port)(?:\s+is)?[:\s]/i,
834
+ ];
835
+
836
+ function shouldCapture(text: string): boolean {
837
+ if (text.length < 20 || text.length > 2000) {
838
+ return false;
839
+ }
840
+ return CAPTURE_PATTERNS.some((pattern) => pattern.test(text));
841
+ }
842
+
843
+ // ============================================================================
844
+ // Plugin Export
845
+ export default async function plugin(api: OpenClawPluginApi): Promise<void> {
846
+ const cfg = api.pluginConfig as MemoryRelayConfig | undefined;
847
+
848
+ // Fall back to environment variables
116
849
  const apiKey = cfg?.apiKey || process.env.MEMORYRELAY_API_KEY;
117
850
  const agentId = cfg?.agentId || process.env.MEMORYRELAY_AGENT_ID || api.agentName;
118
851
 
119
852
  if (!apiKey) {
120
- api.logger.error("memory-memoryrelay: Missing API key");
853
+ api.logger.error(
854
+ "memory-memoryrelay: Missing API key in config or MEMORYRELAY_API_KEY env var.\n\n" +
855
+ "REQUIRED: Add config after installation:\n\n" +
856
+ 'cat ~/.openclaw/openclaw.json | jq \'.plugins.entries."plugin-memoryrelay-ai".config = {\n' +
857
+ ' "apiKey": "YOUR_API_KEY",\n' +
858
+ ' "agentId": "YOUR_AGENT_ID"\n' +
859
+ "}' > /tmp/config.json && mv /tmp/config.json ~/.openclaw/openclaw.json\n\n" +
860
+ "Or set environment variable:\n" +
861
+ 'export MEMORYRELAY_API_KEY="mem_prod_..."\n\n' +
862
+ "Then restart: openclaw gateway restart\n\n" +
863
+ "Get your API key from: https://memoryrelay.ai",
864
+ );
121
865
  return;
122
866
  }
123
867
 
124
868
  if (!agentId) {
125
- api.logger.error("memory-memoryrelay: Missing agentId");
869
+ api.logger.error("memory-memoryrelay: Missing agentId in config or MEMORYRELAY_AGENT_ID env var");
126
870
  return;
127
871
  }
128
872
 
129
873
  const apiUrl = cfg?.apiUrl || process.env.MEMORYRELAY_API_URL || DEFAULT_API_URL;
874
+ const defaultProject = cfg?.defaultProject || process.env.MEMORYRELAY_DEFAULT_PROJECT;
875
+
876
+ // ========================================================================
877
+ // Debug Logger and Status Reporter (v0.8.0)
878
+ // ========================================================================
130
879
 
131
880
  const debugEnabled = cfg?.debug || false;
132
881
  const verboseEnabled = cfg?.verbose || false;
882
+ const logFile = cfg?.logFile;
133
883
  const maxLogEntries = cfg?.maxLogEntries || 100;
134
884
 
135
885
  let debugLogger: DebugLogger | undefined;
@@ -140,27 +890,2770 @@ export default function plugin(api: OpenClawPluginApi): void {
140
890
  enabled: true,
141
891
  verbose: verboseEnabled,
142
892
  maxEntries: maxLogEntries,
893
+ logFile: logFile,
143
894
  });
144
- api.logger.info(`memory-memoryrelay: debug mode enabled`);
895
+ api.logger.info(`memory-memoryrelay: debug mode enabled (verbose: ${verboseEnabled}, maxEntries: ${maxLogEntries})`);
145
896
  }
146
897
 
147
898
  statusReporter = new StatusReporter(debugLogger);
899
+
900
+ const client = new MemoryRelayClient(apiKey, agentId, apiUrl, debugLogger, statusReporter);
148
901
 
149
- // Register a simple test tool
150
- api.registerTool({
151
- name: "memory_test",
152
- description: "Test MemoryRelay connection",
153
- handler: async () => {
154
- return {
155
- content: [
156
- {
157
- type: "text",
158
- text: `MemoryRelay plugin loaded! API: ${apiUrl}, Agent: ${agentId}`,
159
- },
160
- ],
902
+ // Verify connection on startup (with timeout)
903
+ try {
904
+ await client.health();
905
+ api.logger.info(`memory-memoryrelay: connected to ${apiUrl}`);
906
+ } catch (err) {
907
+ api.logger.error(`memory-memoryrelay: health check failed: ${String(err)}`);
908
+ // Continue loading plugin even if health check fails (will retry on first use)
909
+ }
910
+
911
+ // ========================================================================
912
+ // Status Reporting (for openclaw status command)
913
+ // ========================================================================
914
+
915
+ api.registerGatewayMethod?.("memory.status", async ({ respond }) => {
916
+ try {
917
+ // Get connection status
918
+ const startTime = Date.now();
919
+ const health = await client.health();
920
+ const responseTime = Date.now() - startTime;
921
+
922
+ const healthStatus = String(health.status).toLowerCase();
923
+ const isConnected = VALID_HEALTH_STATUSES.includes(healthStatus);
924
+
925
+ const connectionStatus = {
926
+ status: isConnected ? "connected" as const : "disconnected" as const,
927
+ endpoint: apiUrl,
928
+ lastCheck: new Date().toISOString(),
929
+ responseTime,
930
+ };
931
+
932
+ // Get memory stats
933
+ let memoryCount = 0;
934
+ try {
935
+ const stats = await client.stats();
936
+ memoryCount = stats.total_memories;
937
+ } catch (statsErr) {
938
+ api.logger.debug?.(`memory-memoryrelay: stats endpoint unavailable: ${String(statsErr)}`);
939
+ }
940
+
941
+ const memoryStats = {
942
+ total_memories: memoryCount,
161
943
  };
944
+
945
+ // Get config
946
+ const pluginConfig = {
947
+ agentId: agentId,
948
+ autoRecall: cfg?.autoRecall ?? true,
949
+ autoCapture: cfg?.autoCapture ?? false,
950
+ recallLimit: cfg?.recallLimit ?? 5,
951
+ recallThreshold: cfg?.recallThreshold ?? 0.3,
952
+ excludeChannels: cfg?.excludeChannels ?? [],
953
+ defaultProject: defaultProject,
954
+ };
955
+
956
+ // Build comprehensive status report
957
+ if (statusReporter) {
958
+ const report = statusReporter.buildReport(
959
+ connectionStatus,
960
+ pluginConfig,
961
+ memoryStats,
962
+ TOOL_GROUPS,
963
+ );
964
+
965
+ // Format and output
966
+ const formatted = StatusReporter.formatReport(report);
967
+ api.logger.info(formatted);
968
+
969
+ // Also return structured data for programmatic access
970
+ respond(true, {
971
+ available: true,
972
+ connected: isConnected,
973
+ endpoint: apiUrl,
974
+ memoryCount: memoryCount,
975
+ agentId: agentId,
976
+ debug: debugEnabled,
977
+ verbose: verboseEnabled,
978
+ report: report,
979
+ vector: {
980
+ available: true,
981
+ enabled: true,
982
+ },
983
+ });
984
+ } else {
985
+ // Fallback to simple status (shouldn't happen)
986
+ respond(true, {
987
+ available: true,
988
+ connected: isConnected,
989
+ endpoint: apiUrl,
990
+ memoryCount: memoryCount,
991
+ agentId: agentId,
992
+ vector: {
993
+ available: true,
994
+ enabled: true,
995
+ },
996
+ });
997
+ }
998
+ } catch (err) {
999
+ respond(true, {
1000
+ available: false,
1001
+ connected: false,
1002
+ error: String(err),
1003
+ endpoint: apiUrl,
1004
+ agentId: agentId,
1005
+ vector: {
1006
+ available: false,
1007
+ enabled: true,
1008
+ },
1009
+ });
1010
+ }
1011
+ });
1012
+
1013
+ // ========================================================================
1014
+ // Helper to check if a tool is enabled (by group)
1015
+ // ========================================================================
1016
+
1017
+ // Tool group mapping — matches MCP server's TOOL_GROUPS
1018
+ const TOOL_GROUPS: Record<string, string[]> = {
1019
+ memory: [
1020
+ "memory_store", "memory_recall", "memory_forget", "memory_list",
1021
+ "memory_get", "memory_update", "memory_batch_store", "memory_context",
1022
+ "memory_promote",
1023
+ ],
1024
+ entity: ["entity_create", "entity_link", "entity_list", "entity_graph"],
1025
+ agent: ["agent_list", "agent_create", "agent_get"],
1026
+ session: ["session_start", "session_end", "session_recall", "session_list"],
1027
+ decision: ["decision_record", "decision_list", "decision_supersede", "decision_check"],
1028
+ pattern: ["pattern_create", "pattern_search", "pattern_adopt", "pattern_suggest"],
1029
+ project: [
1030
+ "project_register", "project_list", "project_info",
1031
+ "project_add_relationship", "project_dependencies", "project_dependents",
1032
+ "project_related", "project_impact", "project_shared_patterns", "project_context",
1033
+ ],
1034
+ health: ["memory_health"],
1035
+ };
1036
+
1037
+ // Build a set of enabled tool names from group names
1038
+ const enabledToolNames: Set<string> | null = (() => {
1039
+ if (!cfg?.enabledTools) return null; // all enabled
1040
+ const groups = cfg.enabledTools.split(",").map((s) => s.trim().toLowerCase());
1041
+ if (groups.includes("all")) return null;
1042
+ const enabled = new Set<string>();
1043
+ for (const group of groups) {
1044
+ const tools = TOOL_GROUPS[group];
1045
+ if (tools) {
1046
+ for (const tool of tools) {
1047
+ enabled.add(tool);
1048
+ }
1049
+ }
1050
+ }
1051
+ return enabled;
1052
+ })();
1053
+
1054
+ function isToolEnabled(name: string): boolean {
1055
+ if (!enabledToolNames) return true;
1056
+ return enabledToolNames.has(name);
1057
+ }
1058
+
1059
+ // ========================================================================
1060
+ // Tools (39 total)
1061
+ // ========================================================================
1062
+
1063
+ // --------------------------------------------------------------------------
1064
+ // 1. memory_store
1065
+ // --------------------------------------------------------------------------
1066
+ if (isToolEnabled("memory_store")) {
1067
+ api.registerTool(
1068
+ {
1069
+ name: "memory_store",
1070
+ description:
1071
+ "Store a new memory in MemoryRelay. Use this to save important information, facts, preferences, or context that should be remembered for future conversations." +
1072
+ (defaultProject ? ` Project defaults to '${defaultProject}' if not specified.` : "") +
1073
+ " Set deduplicate=true to avoid storing near-duplicate memories.",
1074
+ parameters: {
1075
+ type: "object",
1076
+ properties: {
1077
+ content: {
1078
+ type: "string",
1079
+ description: "The memory content to store. Be specific and include relevant context.",
1080
+ },
1081
+ metadata: {
1082
+ type: "object",
1083
+ description: "Optional key-value metadata to attach to the memory",
1084
+ additionalProperties: { type: "string" },
1085
+ },
1086
+ deduplicate: {
1087
+ type: "boolean",
1088
+ description: "If true, check for duplicate memories before storing. Default false.",
1089
+ },
1090
+ dedup_threshold: {
1091
+ type: "number",
1092
+ description: "Similarity threshold for deduplication (0-1). Default 0.9.",
1093
+ },
1094
+ project: {
1095
+ type: "string",
1096
+ description: "Project slug to associate with this memory.",
1097
+ },
1098
+ importance: {
1099
+ type: "number",
1100
+ description: "Importance score (0-1). Higher values are retained longer.",
1101
+ },
1102
+ tier: {
1103
+ type: "string",
1104
+ description: "Memory tier: hot, warm, or cold.",
1105
+ enum: ["hot", "warm", "cold"],
1106
+ },
1107
+ },
1108
+ required: ["content"],
1109
+ },
1110
+ execute: async (
1111
+ _id,
1112
+ args: {
1113
+ content: string;
1114
+ metadata?: Record<string, string>;
1115
+ deduplicate?: boolean;
1116
+ dedup_threshold?: number;
1117
+ project?: string;
1118
+ importance?: number;
1119
+ tier?: string;
1120
+ },
1121
+ ) => {
1122
+ try {
1123
+ const { content, metadata, ...opts } = args;
1124
+ if (!opts.project && defaultProject) opts.project = defaultProject;
1125
+ const memory = await client.store(content, metadata, opts);
1126
+ return {
1127
+ content: [
1128
+ {
1129
+ type: "text",
1130
+ text: `Memory stored successfully (id: ${memory.id.slice(0, 8)}...)`,
1131
+ },
1132
+ ],
1133
+ details: { id: memory.id, stored: true },
1134
+ };
1135
+ } catch (err) {
1136
+ return {
1137
+ content: [{ type: "text", text: `Failed to store memory: ${String(err)}` }],
1138
+ details: { error: String(err) },
1139
+ };
1140
+ }
1141
+ },
1142
+ },
1143
+ { name: "memory_store" },
1144
+ );
1145
+ }
1146
+
1147
+ // --------------------------------------------------------------------------
1148
+ // 2. memory_recall
1149
+ // --------------------------------------------------------------------------
1150
+ if (isToolEnabled("memory_recall")) {
1151
+ api.registerTool(
1152
+ {
1153
+ name: "memory_recall",
1154
+ description:
1155
+ "Search memories using natural language. Returns the most relevant memories based on semantic similarity to the query." +
1156
+ (defaultProject ? ` Results scoped to project '${defaultProject}' by default; pass project explicitly to override or omit to search all.` : ""),
1157
+ parameters: {
1158
+ type: "object",
1159
+ properties: {
1160
+ query: {
1161
+ type: "string",
1162
+ description: "Natural language search query",
1163
+ },
1164
+ limit: {
1165
+ type: "number",
1166
+ description: "Maximum results (1-50). Default 5.",
1167
+ minimum: 1,
1168
+ maximum: 50,
1169
+ },
1170
+ threshold: {
1171
+ type: "number",
1172
+ description: "Minimum similarity threshold (0-1). Default 0.3.",
1173
+ },
1174
+ project: {
1175
+ type: "string",
1176
+ description: "Filter by project slug.",
1177
+ },
1178
+ tier: {
1179
+ type: "string",
1180
+ description: "Filter by memory tier: hot, warm, or cold.",
1181
+ enum: ["hot", "warm", "cold"],
1182
+ },
1183
+ min_importance: {
1184
+ type: "number",
1185
+ description: "Minimum importance score filter (0-1).",
1186
+ },
1187
+ compress: {
1188
+ type: "boolean",
1189
+ description: "If true, compress results for token efficiency.",
1190
+ },
1191
+ },
1192
+ required: ["query"],
1193
+ },
1194
+ execute: async (
1195
+ _id,
1196
+ args: {
1197
+ query: string;
1198
+ limit?: number;
1199
+ threshold?: number;
1200
+ project?: string;
1201
+ tier?: string;
1202
+ min_importance?: number;
1203
+ compress?: boolean;
1204
+ },
1205
+ ) => {
1206
+ try {
1207
+ const {
1208
+ query,
1209
+ limit = 5,
1210
+ threshold,
1211
+ project,
1212
+ tier,
1213
+ min_importance,
1214
+ compress,
1215
+ } = args;
1216
+ const searchThreshold = threshold ?? cfg?.recallThreshold ?? 0.3;
1217
+ const searchProject = project ?? defaultProject;
1218
+ const results = await client.search(query, limit, searchThreshold, {
1219
+ project: searchProject,
1220
+ tier,
1221
+ min_importance,
1222
+ compress,
1223
+ });
1224
+
1225
+ if (results.length === 0) {
1226
+ return {
1227
+ content: [{ type: "text", text: "No relevant memories found." }],
1228
+ details: { count: 0 },
1229
+ };
1230
+ }
1231
+
1232
+ const formatted = results
1233
+ .map(
1234
+ (r) =>
1235
+ `- [${r.score.toFixed(2)}] ${r.memory.content.slice(0, 200)}${
1236
+ r.memory.content.length > 200 ? "..." : ""
1237
+ }`,
1238
+ )
1239
+ .join("\n");
1240
+
1241
+ return {
1242
+ content: [
1243
+ {
1244
+ type: "text",
1245
+ text: `Found ${results.length} relevant memories:\n${formatted}`,
1246
+ },
1247
+ ],
1248
+ details: {
1249
+ count: results.length,
1250
+ memories: results.map((r) => ({
1251
+ id: r.memory.id,
1252
+ content: r.memory.content,
1253
+ score: r.score,
1254
+ })),
1255
+ },
1256
+ };
1257
+ } catch (err) {
1258
+ return {
1259
+ content: [{ type: "text", text: `Search failed: ${String(err)}` }],
1260
+ details: { error: String(err) },
1261
+ };
1262
+ }
1263
+ },
1264
+ },
1265
+ { name: "memory_recall" },
1266
+ );
1267
+ }
1268
+
1269
+ // --------------------------------------------------------------------------
1270
+ // 3. memory_forget
1271
+ // --------------------------------------------------------------------------
1272
+ if (isToolEnabled("memory_forget")) {
1273
+ api.registerTool(
1274
+ {
1275
+ name: "memory_forget",
1276
+ description: "Delete a memory by ID, or search by query to find candidates. Provide memoryId for direct deletion, or query to search first. A single high-confidence match (>0.9) is auto-deleted; otherwise candidates are listed for you to choose.",
1277
+ parameters: {
1278
+ type: "object",
1279
+ properties: {
1280
+ memoryId: {
1281
+ type: "string",
1282
+ description: "Memory ID to delete",
1283
+ },
1284
+ query: {
1285
+ type: "string",
1286
+ description: "Search query to find memory",
1287
+ },
1288
+ },
1289
+ },
1290
+ execute: async (_id, { memoryId, query }: { memoryId?: string; query?: string }) => {
1291
+ if (memoryId) {
1292
+ try {
1293
+ await client.delete(memoryId);
1294
+ return {
1295
+ content: [{ type: "text", text: `Memory ${memoryId.slice(0, 8)}... deleted.` }],
1296
+ details: { action: "deleted", id: memoryId },
1297
+ };
1298
+ } catch (err) {
1299
+ return {
1300
+ content: [{ type: "text", text: `Delete failed: ${String(err)}` }],
1301
+ details: { error: String(err) },
1302
+ };
1303
+ }
1304
+ }
1305
+
1306
+ if (query) {
1307
+ const results = await client.search(query, 5, 0.5, { project: defaultProject });
1308
+
1309
+ if (results.length === 0) {
1310
+ return {
1311
+ content: [{ type: "text", text: "No matching memories found." }],
1312
+ details: { count: 0 },
1313
+ };
1314
+ }
1315
+
1316
+ // If single high-confidence match, delete it
1317
+ if (results.length === 1 && results[0].score > 0.9) {
1318
+ await client.delete(results[0].memory.id);
1319
+ return {
1320
+ content: [
1321
+ { type: "text", text: `Forgotten: "${results[0].memory.content.slice(0, 60)}..."` },
1322
+ ],
1323
+ details: { action: "deleted", id: results[0].memory.id },
1324
+ };
1325
+ }
1326
+
1327
+ const list = results
1328
+ .map((r) => `- [${r.memory.id.slice(0, 8)}] ${r.memory.content.slice(0, 60)}...`)
1329
+ .join("\n");
1330
+
1331
+ return {
1332
+ content: [
1333
+ {
1334
+ type: "text",
1335
+ text: `Found ${results.length} candidates. Specify memoryId:\n${list}`,
1336
+ },
1337
+ ],
1338
+ details: { action: "candidates", count: results.length },
1339
+ };
1340
+ }
1341
+
1342
+ return {
1343
+ content: [{ type: "text", text: "Provide query or memoryId." }],
1344
+ details: { error: "missing_param" },
1345
+ };
1346
+ },
1347
+ },
1348
+ { name: "memory_forget" },
1349
+ );
1350
+ }
1351
+
1352
+ // --------------------------------------------------------------------------
1353
+ // 4. memory_list
1354
+ // --------------------------------------------------------------------------
1355
+ if (isToolEnabled("memory_list")) {
1356
+ api.registerTool(
1357
+ {
1358
+ name: "memory_list",
1359
+ description: "List recent memories chronologically for this agent. Use to review what has been stored or to find memory IDs for update/delete operations.",
1360
+ parameters: {
1361
+ type: "object",
1362
+ properties: {
1363
+ limit: {
1364
+ type: "number",
1365
+ description: "Number of memories to return (1-100). Default 20.",
1366
+ minimum: 1,
1367
+ maximum: 100,
1368
+ },
1369
+ offset: {
1370
+ type: "number",
1371
+ description: "Offset for pagination. Default 0.",
1372
+ minimum: 0,
1373
+ },
1374
+ },
1375
+ },
1376
+ execute: async (_id, args: { limit?: number; offset?: number }) => {
1377
+ try {
1378
+ const memories = await client.list(args.limit ?? 20, args.offset ?? 0);
1379
+ if (memories.length === 0) {
1380
+ return {
1381
+ content: [{ type: "text", text: "No memories found." }],
1382
+ details: { count: 0 },
1383
+ };
1384
+ }
1385
+ const formatted = memories
1386
+ .map((m) => `- [${m.id.slice(0, 8)}] ${m.content.slice(0, 120)}`)
1387
+ .join("\n");
1388
+ return {
1389
+ content: [{ type: "text", text: `${memories.length} memories:\n${formatted}` }],
1390
+ details: { count: memories.length, memories },
1391
+ };
1392
+ } catch (err) {
1393
+ return {
1394
+ content: [{ type: "text", text: `Failed to list memories: ${String(err)}` }],
1395
+ details: { error: String(err) },
1396
+ };
1397
+ }
1398
+ },
1399
+ },
1400
+ { name: "memory_list" },
1401
+ );
1402
+ }
1403
+
1404
+ // --------------------------------------------------------------------------
1405
+ // 5. memory_get
1406
+ // --------------------------------------------------------------------------
1407
+ if (isToolEnabled("memory_get")) {
1408
+ api.registerTool(
1409
+ {
1410
+ name: "memory_get",
1411
+ description: "Retrieve a specific memory by its ID.",
1412
+ parameters: {
1413
+ type: "object",
1414
+ properties: {
1415
+ id: {
1416
+ type: "string",
1417
+ description: "The memory ID (UUID) to retrieve.",
1418
+ },
1419
+ },
1420
+ required: ["id"],
1421
+ },
1422
+ execute: async (_id, args: { id: string }) => {
1423
+ try {
1424
+ const memory = await client.get(args.id);
1425
+ return {
1426
+ content: [{ type: "text", text: JSON.stringify(memory, null, 2) }],
1427
+ details: { memory },
1428
+ };
1429
+ } catch (err) {
1430
+ return {
1431
+ content: [{ type: "text", text: `Failed to get memory: ${String(err)}` }],
1432
+ details: { error: String(err) },
1433
+ };
1434
+ }
1435
+ },
1436
+ },
1437
+ { name: "memory_get" },
1438
+ );
1439
+ }
1440
+
1441
+ // --------------------------------------------------------------------------
1442
+ // 6. memory_update
1443
+ // --------------------------------------------------------------------------
1444
+ if (isToolEnabled("memory_update")) {
1445
+ api.registerTool(
1446
+ {
1447
+ name: "memory_update",
1448
+ description: "Update the content of an existing memory. Use to correct or expand stored information.",
1449
+ parameters: {
1450
+ type: "object",
1451
+ properties: {
1452
+ id: {
1453
+ type: "string",
1454
+ description: "The memory ID (UUID) to update.",
1455
+ },
1456
+ content: {
1457
+ type: "string",
1458
+ description: "The new content to replace the existing memory.",
1459
+ },
1460
+ metadata: {
1461
+ type: "object",
1462
+ description: "Updated metadata (replaces existing).",
1463
+ additionalProperties: { type: "string" },
1464
+ },
1465
+ },
1466
+ required: ["id", "content"],
1467
+ },
1468
+ execute: async (_id, args: { id: string; content: string; metadata?: Record<string, string> }) => {
1469
+ try {
1470
+ const memory = await client.update(args.id, args.content, args.metadata);
1471
+ return {
1472
+ content: [{ type: "text", text: `Memory ${args.id.slice(0, 8)}... updated.` }],
1473
+ details: { id: memory.id, updated: true },
1474
+ };
1475
+ } catch (err) {
1476
+ return {
1477
+ content: [{ type: "text", text: `Failed to update memory: ${String(err)}` }],
1478
+ details: { error: String(err) },
1479
+ };
1480
+ }
1481
+ },
1482
+ },
1483
+ { name: "memory_update" },
1484
+ );
1485
+ }
1486
+
1487
+ // --------------------------------------------------------------------------
1488
+ // 7. memory_batch_store
1489
+ // --------------------------------------------------------------------------
1490
+ if (isToolEnabled("memory_batch_store")) {
1491
+ api.registerTool(
1492
+ {
1493
+ name: "memory_batch_store",
1494
+ description: "Store multiple memories at once. More efficient than individual calls for bulk storage.",
1495
+ parameters: {
1496
+ type: "object",
1497
+ properties: {
1498
+ memories: {
1499
+ type: "array",
1500
+ description: "Array of memories to store.",
1501
+ items: {
1502
+ type: "object",
1503
+ properties: {
1504
+ content: { type: "string", description: "Memory content." },
1505
+ metadata: {
1506
+ type: "object",
1507
+ description: "Optional metadata.",
1508
+ additionalProperties: { type: "string" },
1509
+ },
1510
+ },
1511
+ required: ["content"],
1512
+ },
1513
+ },
1514
+ },
1515
+ required: ["memories"],
1516
+ },
1517
+ execute: async (
1518
+ _id,
1519
+ args: { memories: Array<{ content: string; metadata?: Record<string, string> }> },
1520
+ ) => {
1521
+ try {
1522
+ const result = await client.batchStore(args.memories);
1523
+ return {
1524
+ content: [
1525
+ {
1526
+ type: "text",
1527
+ text: `Batch stored ${args.memories.length} memories successfully.`,
1528
+ },
1529
+ ],
1530
+ details: { count: args.memories.length, result },
1531
+ };
1532
+ } catch (err) {
1533
+ return {
1534
+ content: [{ type: "text", text: `Batch store failed: ${String(err)}` }],
1535
+ details: { error: String(err) },
1536
+ };
1537
+ }
1538
+ },
1539
+ },
1540
+ { name: "memory_batch_store" },
1541
+ );
1542
+ }
1543
+
1544
+ // --------------------------------------------------------------------------
1545
+ // 8. memory_context
1546
+ // --------------------------------------------------------------------------
1547
+ if (isToolEnabled("memory_context")) {
1548
+ api.registerTool(
1549
+ {
1550
+ name: "memory_context",
1551
+ description:
1552
+ "Build a context window from relevant memories, optimized for injecting into agent prompts with token budget awareness." +
1553
+ (defaultProject ? ` Project defaults to '${defaultProject}' if not specified.` : ""),
1554
+ parameters: {
1555
+ type: "object",
1556
+ properties: {
1557
+ query: {
1558
+ type: "string",
1559
+ description: "The query to build context around.",
1560
+ },
1561
+ limit: {
1562
+ type: "number",
1563
+ description: "Maximum number of memories to include.",
1564
+ },
1565
+ threshold: {
1566
+ type: "number",
1567
+ description: "Minimum similarity threshold (0-1).",
1568
+ },
1569
+ max_tokens: {
1570
+ type: "number",
1571
+ description: "Maximum token budget for the context.",
1572
+ },
1573
+ project: {
1574
+ type: "string",
1575
+ description: "Project slug to scope the context.",
1576
+ },
1577
+ },
1578
+ required: ["query"],
1579
+ },
1580
+ execute: async (
1581
+ _id,
1582
+ args: { query: string; limit?: number; threshold?: number; max_tokens?: number; project?: string },
1583
+ ) => {
1584
+ try {
1585
+ const project = args.project ?? defaultProject;
1586
+ const result = await client.buildContext(
1587
+ args.query,
1588
+ args.limit,
1589
+ args.threshold,
1590
+ args.max_tokens,
1591
+ project,
1592
+ );
1593
+ return {
1594
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
1595
+ details: { result },
1596
+ };
1597
+ } catch (err) {
1598
+ return {
1599
+ content: [{ type: "text", text: `Context build failed: ${String(err)}` }],
1600
+ details: { error: String(err) },
1601
+ };
1602
+ }
1603
+ },
1604
+ },
1605
+ { name: "memory_context" },
1606
+ );
1607
+ }
1608
+
1609
+ // --------------------------------------------------------------------------
1610
+ // 9. memory_promote
1611
+ // --------------------------------------------------------------------------
1612
+ if (isToolEnabled("memory_promote")) {
1613
+ api.registerTool(
1614
+ {
1615
+ name: "memory_promote",
1616
+ description:
1617
+ "Promote a memory by updating its importance score and/or tier. Use to ensure critical memories are retained longer.",
1618
+ parameters: {
1619
+ type: "object",
1620
+ properties: {
1621
+ memory_id: {
1622
+ type: "string",
1623
+ description: "The memory ID to promote.",
1624
+ },
1625
+ importance: {
1626
+ type: "number",
1627
+ description: "New importance score (0-1).",
1628
+ minimum: 0,
1629
+ maximum: 1,
1630
+ },
1631
+ tier: {
1632
+ type: "string",
1633
+ description: "Target tier: hot, warm, or cold.",
1634
+ enum: ["hot", "warm", "cold"],
1635
+ },
1636
+ },
1637
+ required: ["memory_id", "importance"],
1638
+ },
1639
+ execute: async (_id, args: { memory_id: string; importance: number; tier?: string }) => {
1640
+ try {
1641
+ const result = await client.promote(args.memory_id, args.importance, args.tier);
1642
+ return {
1643
+ content: [
1644
+ {
1645
+ type: "text",
1646
+ text: `Memory ${args.memory_id.slice(0, 8)}... promoted (importance: ${args.importance}${args.tier ? `, tier: ${args.tier}` : ""}).`,
1647
+ },
1648
+ ],
1649
+ details: { result },
1650
+ };
1651
+ } catch (err) {
1652
+ return {
1653
+ content: [{ type: "text", text: `Promote failed: ${String(err)}` }],
1654
+ details: { error: String(err) },
1655
+ };
1656
+ }
1657
+ },
1658
+ },
1659
+ { name: "memory_promote" },
1660
+ );
1661
+ }
1662
+
1663
+ // --------------------------------------------------------------------------
1664
+ // 10. entity_create
1665
+ // --------------------------------------------------------------------------
1666
+ if (isToolEnabled("entity_create")) {
1667
+ api.registerTool(
1668
+ {
1669
+ name: "entity_create",
1670
+ description:
1671
+ "Create a named entity (person, place, organization, project, concept) for the knowledge graph. Entities help organize and connect memories.",
1672
+ parameters: {
1673
+ type: "object",
1674
+ properties: {
1675
+ name: {
1676
+ type: "string",
1677
+ description: "Entity name (1-200 characters).",
1678
+ },
1679
+ type: {
1680
+ type: "string",
1681
+ description: "Entity type classification.",
1682
+ enum: ["person", "place", "organization", "project", "concept", "other"],
1683
+ },
1684
+ metadata: {
1685
+ type: "object",
1686
+ description: "Optional key-value metadata.",
1687
+ additionalProperties: { type: "string" },
1688
+ },
1689
+ },
1690
+ required: ["name", "type"],
1691
+ },
1692
+ execute: async (
1693
+ _id,
1694
+ args: { name: string; type: string; metadata?: Record<string, string> },
1695
+ ) => {
1696
+ try {
1697
+ const result = await client.createEntity(args.name, args.type, args.metadata);
1698
+ return {
1699
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
1700
+ details: { result },
1701
+ };
1702
+ } catch (err) {
1703
+ return {
1704
+ content: [{ type: "text", text: `Failed to create entity: ${String(err)}` }],
1705
+ details: { error: String(err) },
1706
+ };
1707
+ }
1708
+ },
1709
+ },
1710
+ { name: "entity_create" },
1711
+ );
1712
+ }
1713
+
1714
+ // --------------------------------------------------------------------------
1715
+ // 11. entity_link
1716
+ // --------------------------------------------------------------------------
1717
+ if (isToolEnabled("entity_link")) {
1718
+ api.registerTool(
1719
+ {
1720
+ name: "entity_link",
1721
+ description: "Link an entity to a memory to establish relationships in the knowledge graph.",
1722
+ parameters: {
1723
+ type: "object",
1724
+ properties: {
1725
+ entity_id: {
1726
+ type: "string",
1727
+ description: "Entity UUID.",
1728
+ },
1729
+ memory_id: {
1730
+ type: "string",
1731
+ description: "Memory UUID.",
1732
+ },
1733
+ relationship: {
1734
+ type: "string",
1735
+ description:
1736
+ 'Relationship type (e.g., "mentioned_in", "created_by", "relates_to"). Default "mentioned_in".',
1737
+ },
1738
+ },
1739
+ required: ["entity_id", "memory_id"],
1740
+ },
1741
+ execute: async (
1742
+ _id,
1743
+ args: { entity_id: string; memory_id: string; relationship?: string },
1744
+ ) => {
1745
+ try {
1746
+ const result = await client.linkEntity(
1747
+ args.entity_id,
1748
+ args.memory_id,
1749
+ args.relationship,
1750
+ );
1751
+ return {
1752
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
1753
+ details: { result },
1754
+ };
1755
+ } catch (err) {
1756
+ return {
1757
+ content: [{ type: "text", text: `Failed to link entity: ${String(err)}` }],
1758
+ details: { error: String(err) },
1759
+ };
1760
+ }
1761
+ },
1762
+ },
1763
+ { name: "entity_link" },
1764
+ );
1765
+ }
1766
+
1767
+ // --------------------------------------------------------------------------
1768
+ // 12. entity_list
1769
+ // --------------------------------------------------------------------------
1770
+ if (isToolEnabled("entity_list")) {
1771
+ api.registerTool(
1772
+ {
1773
+ name: "entity_list",
1774
+ description: "List entities in the knowledge graph.",
1775
+ parameters: {
1776
+ type: "object",
1777
+ properties: {
1778
+ limit: {
1779
+ type: "number",
1780
+ description: "Maximum entities to return. Default 20.",
1781
+ minimum: 1,
1782
+ maximum: 100,
1783
+ },
1784
+ offset: {
1785
+ type: "number",
1786
+ description: "Offset for pagination. Default 0.",
1787
+ minimum: 0,
1788
+ },
1789
+ },
1790
+ },
1791
+ execute: async (_id, args: { limit?: number; offset?: number }) => {
1792
+ try {
1793
+ const result = await client.listEntities(args.limit, args.offset);
1794
+ return {
1795
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
1796
+ details: { result },
1797
+ };
1798
+ } catch (err) {
1799
+ return {
1800
+ content: [{ type: "text", text: `Failed to list entities: ${String(err)}` }],
1801
+ details: { error: String(err) },
1802
+ };
1803
+ }
1804
+ },
1805
+ },
1806
+ { name: "entity_list" },
1807
+ );
1808
+ }
1809
+
1810
+ // --------------------------------------------------------------------------
1811
+ // 13. entity_graph
1812
+ // --------------------------------------------------------------------------
1813
+ if (isToolEnabled("entity_graph")) {
1814
+ api.registerTool(
1815
+ {
1816
+ name: "entity_graph",
1817
+ description:
1818
+ "Explore the knowledge graph around an entity. Returns the entity and its neighborhood of connected entities and memories.",
1819
+ parameters: {
1820
+ type: "object",
1821
+ properties: {
1822
+ entity_id: {
1823
+ type: "string",
1824
+ description: "Entity UUID to explore from.",
1825
+ },
1826
+ depth: {
1827
+ type: "number",
1828
+ description: "How many hops to traverse. Default 2.",
1829
+ minimum: 1,
1830
+ maximum: 5,
1831
+ },
1832
+ max_neighbors: {
1833
+ type: "number",
1834
+ description: "Maximum neighbors per node. Default 10.",
1835
+ minimum: 1,
1836
+ maximum: 50,
1837
+ },
1838
+ },
1839
+ required: ["entity_id"],
1840
+ },
1841
+ execute: async (
1842
+ _id,
1843
+ args: { entity_id: string; depth?: number; max_neighbors?: number },
1844
+ ) => {
1845
+ try {
1846
+ const result = await client.entityGraph(
1847
+ args.entity_id,
1848
+ args.depth,
1849
+ args.max_neighbors,
1850
+ );
1851
+ return {
1852
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
1853
+ details: { result },
1854
+ };
1855
+ } catch (err) {
1856
+ return {
1857
+ content: [{ type: "text", text: `Failed to get entity graph: ${String(err)}` }],
1858
+ details: { error: String(err) },
1859
+ };
1860
+ }
1861
+ },
1862
+ },
1863
+ { name: "entity_graph" },
1864
+ );
1865
+ }
1866
+
1867
+ // --------------------------------------------------------------------------
1868
+ // 14. agent_list
1869
+ // --------------------------------------------------------------------------
1870
+ if (isToolEnabled("agent_list")) {
1871
+ api.registerTool(
1872
+ {
1873
+ name: "agent_list",
1874
+ description: "List available agents.",
1875
+ parameters: {
1876
+ type: "object",
1877
+ properties: {
1878
+ limit: {
1879
+ type: "number",
1880
+ description: "Maximum agents to return. Default 20.",
1881
+ minimum: 1,
1882
+ maximum: 100,
1883
+ },
1884
+ },
1885
+ },
1886
+ execute: async (_id, args: { limit?: number }) => {
1887
+ try {
1888
+ const result = await client.listAgents(args.limit);
1889
+ return {
1890
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
1891
+ details: { result },
1892
+ };
1893
+ } catch (err) {
1894
+ return {
1895
+ content: [{ type: "text", text: `Failed to list agents: ${String(err)}` }],
1896
+ details: { error: String(err) },
1897
+ };
1898
+ }
1899
+ },
1900
+ },
1901
+ { name: "agent_list" },
1902
+ );
1903
+ }
1904
+
1905
+ // --------------------------------------------------------------------------
1906
+ // 15. agent_create
1907
+ // --------------------------------------------------------------------------
1908
+ if (isToolEnabled("agent_create")) {
1909
+ api.registerTool(
1910
+ {
1911
+ name: "agent_create",
1912
+ description: "Create a new agent. Agents serve as memory namespaces and isolation boundaries.",
1913
+ parameters: {
1914
+ type: "object",
1915
+ properties: {
1916
+ name: {
1917
+ type: "string",
1918
+ description: "Agent name.",
1919
+ },
1920
+ description: {
1921
+ type: "string",
1922
+ description: "Optional agent description.",
1923
+ },
1924
+ },
1925
+ required: ["name"],
1926
+ },
1927
+ execute: async (_id, args: { name: string; description?: string }) => {
1928
+ try {
1929
+ const result = await client.createAgent(args.name, args.description);
1930
+ return {
1931
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
1932
+ details: { result },
1933
+ };
1934
+ } catch (err) {
1935
+ return {
1936
+ content: [{ type: "text", text: `Failed to create agent: ${String(err)}` }],
1937
+ details: { error: String(err) },
1938
+ };
1939
+ }
1940
+ },
1941
+ },
1942
+ { name: "agent_create" },
1943
+ );
1944
+ }
1945
+
1946
+ // --------------------------------------------------------------------------
1947
+ // 16. agent_get
1948
+ // --------------------------------------------------------------------------
1949
+ if (isToolEnabled("agent_get")) {
1950
+ api.registerTool(
1951
+ {
1952
+ name: "agent_get",
1953
+ description: "Get details about a specific agent by ID.",
1954
+ parameters: {
1955
+ type: "object",
1956
+ properties: {
1957
+ id: {
1958
+ type: "string",
1959
+ description: "Agent UUID.",
1960
+ },
1961
+ },
1962
+ required: ["id"],
1963
+ },
1964
+ execute: async (_id, args: { id: string }) => {
1965
+ try {
1966
+ const result = await client.getAgent(args.id);
1967
+ return {
1968
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
1969
+ details: { result },
1970
+ };
1971
+ } catch (err) {
1972
+ return {
1973
+ content: [{ type: "text", text: `Failed to get agent: ${String(err)}` }],
1974
+ details: { error: String(err) },
1975
+ };
1976
+ }
1977
+ },
1978
+ },
1979
+ { name: "agent_get" },
1980
+ );
1981
+ }
1982
+
1983
+ // --------------------------------------------------------------------------
1984
+ // 17. session_start
1985
+ // --------------------------------------------------------------------------
1986
+ if (isToolEnabled("session_start")) {
1987
+ api.registerTool(
1988
+ {
1989
+ name: "session_start",
1990
+ description:
1991
+ "Start a new work session. Sessions track the lifecycle of a task or conversation for later review. Call this early in your workflow and save the returned session ID for session_end later." +
1992
+ (defaultProject ? ` Project defaults to '${defaultProject}' if not specified.` : ""),
1993
+ parameters: {
1994
+ type: "object",
1995
+ properties: {
1996
+ title: {
1997
+ type: "string",
1998
+ description: "Session title describing the goal or task.",
1999
+ },
2000
+ project: {
2001
+ type: "string",
2002
+ description: "Project slug to associate this session with.",
2003
+ },
2004
+ metadata: {
2005
+ type: "object",
2006
+ description: "Optional key-value metadata.",
2007
+ additionalProperties: { type: "string" },
2008
+ },
2009
+ },
2010
+ },
2011
+ execute: async (
2012
+ _id,
2013
+ args: { title?: string; project?: string; metadata?: Record<string, string> },
2014
+ ) => {
2015
+ try {
2016
+ const project = args.project ?? defaultProject;
2017
+ const result = await client.startSession(args.title, project, args.metadata);
2018
+ return {
2019
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
2020
+ details: { result },
2021
+ };
2022
+ } catch (err) {
2023
+ return {
2024
+ content: [{ type: "text", text: `Failed to start session: ${String(err)}` }],
2025
+ details: { error: String(err) },
2026
+ };
2027
+ }
2028
+ },
2029
+ },
2030
+ { name: "session_start" },
2031
+ );
2032
+ }
2033
+
2034
+ // --------------------------------------------------------------------------
2035
+ // 18. session_end
2036
+ // --------------------------------------------------------------------------
2037
+ if (isToolEnabled("session_end")) {
2038
+ api.registerTool(
2039
+ {
2040
+ name: "session_end",
2041
+ description: "End an active session with a summary of what was accomplished. Always include a meaningful summary — it serves as the historical record of the session.",
2042
+ parameters: {
2043
+ type: "object",
2044
+ properties: {
2045
+ id: {
2046
+ type: "string",
2047
+ description: "Session ID to end.",
2048
+ },
2049
+ summary: {
2050
+ type: "string",
2051
+ description: "Summary of what was accomplished during this session.",
2052
+ },
2053
+ },
2054
+ required: ["id"],
2055
+ },
2056
+ execute: async (_id, args: { id: string; summary?: string }) => {
2057
+ try {
2058
+ const result = await client.endSession(args.id, args.summary);
2059
+ return {
2060
+ content: [{ type: "text", text: `Session ${args.id.slice(0, 8)}... ended.` }],
2061
+ details: { result },
2062
+ };
2063
+ } catch (err) {
2064
+ return {
2065
+ content: [{ type: "text", text: `Failed to end session: ${String(err)}` }],
2066
+ details: { error: String(err) },
2067
+ };
2068
+ }
2069
+ },
2070
+ },
2071
+ { name: "session_end" },
2072
+ );
2073
+ }
2074
+
2075
+ // --------------------------------------------------------------------------
2076
+ // 19. session_recall
2077
+ // --------------------------------------------------------------------------
2078
+ if (isToolEnabled("session_recall")) {
2079
+ api.registerTool(
2080
+ {
2081
+ name: "session_recall",
2082
+ description: "Retrieve details of a specific session including its timeline and associated memories.",
2083
+ parameters: {
2084
+ type: "object",
2085
+ properties: {
2086
+ id: {
2087
+ type: "string",
2088
+ description: "Session ID to retrieve.",
2089
+ },
2090
+ },
2091
+ required: ["id"],
2092
+ },
2093
+ execute: async (_id, args: { id: string }) => {
2094
+ try {
2095
+ const result = await client.getSession(args.id);
2096
+ return {
2097
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
2098
+ details: { result },
2099
+ };
2100
+ } catch (err) {
2101
+ return {
2102
+ content: [{ type: "text", text: `Failed to recall session: ${String(err)}` }],
2103
+ details: { error: String(err) },
2104
+ };
2105
+ }
2106
+ },
2107
+ },
2108
+ { name: "session_recall" },
2109
+ );
2110
+ }
2111
+
2112
+ // --------------------------------------------------------------------------
2113
+ // 20. session_list
2114
+ // --------------------------------------------------------------------------
2115
+ if (isToolEnabled("session_list")) {
2116
+ api.registerTool(
2117
+ {
2118
+ name: "session_list",
2119
+ description: "List sessions, optionally filtered by project or status." +
2120
+ (defaultProject ? ` Scoped to project '${defaultProject}' by default.` : ""),
2121
+ parameters: {
2122
+ type: "object",
2123
+ properties: {
2124
+ limit: {
2125
+ type: "number",
2126
+ description: "Maximum sessions to return. Default 20.",
2127
+ minimum: 1,
2128
+ maximum: 100,
2129
+ },
2130
+ project: {
2131
+ type: "string",
2132
+ description: "Filter by project slug.",
2133
+ },
2134
+ status: {
2135
+ type: "string",
2136
+ description: "Filter by status (active, ended).",
2137
+ enum: ["active", "ended"],
2138
+ },
2139
+ },
2140
+ },
2141
+ execute: async (
2142
+ _id,
2143
+ args: { limit?: number; project?: string; status?: string },
2144
+ ) => {
2145
+ try {
2146
+ const project = args.project ?? defaultProject;
2147
+ const result = await client.listSessions(args.limit, project, args.status);
2148
+ return {
2149
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
2150
+ details: { result },
2151
+ };
2152
+ } catch (err) {
2153
+ return {
2154
+ content: [{ type: "text", text: `Failed to list sessions: ${String(err)}` }],
2155
+ details: { error: String(err) },
2156
+ };
2157
+ }
2158
+ },
2159
+ },
2160
+ { name: "session_list" },
2161
+ );
2162
+ }
2163
+
2164
+ // --------------------------------------------------------------------------
2165
+ // 21. decision_record
2166
+ // --------------------------------------------------------------------------
2167
+ if (isToolEnabled("decision_record")) {
2168
+ api.registerTool(
2169
+ {
2170
+ name: "decision_record",
2171
+ description:
2172
+ "Record an architectural or design decision. Captures the rationale and alternatives considered for future reference. Always check existing decisions with decision_check first to avoid contradictions." +
2173
+ (defaultProject ? ` Project defaults to '${defaultProject}' if not specified.` : ""),
2174
+ parameters: {
2175
+ type: "object",
2176
+ properties: {
2177
+ title: {
2178
+ type: "string",
2179
+ description: "Short title summarizing the decision.",
2180
+ },
2181
+ rationale: {
2182
+ type: "string",
2183
+ description: "Why this decision was made. Include context and reasoning.",
2184
+ },
2185
+ alternatives: {
2186
+ type: "string",
2187
+ description: "What alternatives were considered and why they were rejected.",
2188
+ },
2189
+ project: {
2190
+ type: "string",
2191
+ description: "Project slug this decision applies to.",
2192
+ },
2193
+ tags: {
2194
+ type: "array",
2195
+ description: "Tags for categorizing the decision.",
2196
+ items: { type: "string" },
2197
+ },
2198
+ status: {
2199
+ type: "string",
2200
+ description: "Decision status.",
2201
+ enum: ["active", "experimental"],
2202
+ },
2203
+ },
2204
+ required: ["title", "rationale"],
2205
+ },
2206
+ execute: async (
2207
+ _id,
2208
+ args: {
2209
+ title: string;
2210
+ rationale: string;
2211
+ alternatives?: string;
2212
+ project?: string;
2213
+ tags?: string[];
2214
+ status?: string;
2215
+ },
2216
+ ) => {
2217
+ try {
2218
+ const project = args.project ?? defaultProject;
2219
+ const result = await client.recordDecision(
2220
+ args.title,
2221
+ args.rationale,
2222
+ args.alternatives,
2223
+ project,
2224
+ args.tags,
2225
+ args.status,
2226
+ );
2227
+ return {
2228
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
2229
+ details: { result },
2230
+ };
2231
+ } catch (err) {
2232
+ return {
2233
+ content: [{ type: "text", text: `Failed to record decision: ${String(err)}` }],
2234
+ details: { error: String(err) },
2235
+ };
2236
+ }
2237
+ },
2238
+ },
2239
+ { name: "decision_record" },
2240
+ );
2241
+ }
2242
+
2243
+ // --------------------------------------------------------------------------
2244
+ // 22. decision_list
2245
+ // --------------------------------------------------------------------------
2246
+ if (isToolEnabled("decision_list")) {
2247
+ api.registerTool(
2248
+ {
2249
+ name: "decision_list",
2250
+ description: "List recorded decisions, optionally filtered by project, status, or tags." +
2251
+ (defaultProject ? ` Scoped to project '${defaultProject}' by default.` : ""),
2252
+ parameters: {
2253
+ type: "object",
2254
+ properties: {
2255
+ limit: {
2256
+ type: "number",
2257
+ description: "Maximum decisions to return. Default 20.",
2258
+ minimum: 1,
2259
+ maximum: 100,
2260
+ },
2261
+ project: {
2262
+ type: "string",
2263
+ description: "Filter by project slug.",
2264
+ },
2265
+ status: {
2266
+ type: "string",
2267
+ description: "Filter by status.",
2268
+ enum: ["active", "superseded", "reverted", "experimental"],
2269
+ },
2270
+ tags: {
2271
+ type: "string",
2272
+ description: "Comma-separated tags to filter by.",
2273
+ },
2274
+ },
2275
+ },
2276
+ execute: async (
2277
+ _id,
2278
+ args: { limit?: number; project?: string; status?: string; tags?: string },
2279
+ ) => {
2280
+ try {
2281
+ const project = args.project ?? defaultProject;
2282
+ const result = await client.listDecisions(args.limit, project, args.status, args.tags);
2283
+ return {
2284
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
2285
+ details: { result },
2286
+ };
2287
+ } catch (err) {
2288
+ return {
2289
+ content: [{ type: "text", text: `Failed to list decisions: ${String(err)}` }],
2290
+ details: { error: String(err) },
2291
+ };
2292
+ }
2293
+ },
2294
+ },
2295
+ { name: "decision_list" },
2296
+ );
2297
+ }
2298
+
2299
+ // --------------------------------------------------------------------------
2300
+ // 23. decision_supersede
2301
+ // --------------------------------------------------------------------------
2302
+ if (isToolEnabled("decision_supersede")) {
2303
+ api.registerTool(
2304
+ {
2305
+ name: "decision_supersede",
2306
+ description:
2307
+ "Supersede an existing decision with a new one. The old decision is marked as superseded and linked to the replacement.",
2308
+ parameters: {
2309
+ type: "object",
2310
+ properties: {
2311
+ id: {
2312
+ type: "string",
2313
+ description: "ID of the decision to supersede.",
2314
+ },
2315
+ title: {
2316
+ type: "string",
2317
+ description: "Title of the new replacement decision.",
2318
+ },
2319
+ rationale: {
2320
+ type: "string",
2321
+ description: "Why the previous decision is being replaced.",
2322
+ },
2323
+ alternatives: {
2324
+ type: "string",
2325
+ description: "Alternatives considered for the new decision.",
2326
+ },
2327
+ tags: {
2328
+ type: "array",
2329
+ description: "Tags for the new decision.",
2330
+ items: { type: "string" },
2331
+ },
2332
+ },
2333
+ required: ["id", "title", "rationale"],
2334
+ },
2335
+ execute: async (
2336
+ _id,
2337
+ args: {
2338
+ id: string;
2339
+ title: string;
2340
+ rationale: string;
2341
+ alternatives?: string;
2342
+ tags?: string[];
2343
+ },
2344
+ ) => {
2345
+ try {
2346
+ const result = await client.supersedeDecision(
2347
+ args.id,
2348
+ args.title,
2349
+ args.rationale,
2350
+ args.alternatives,
2351
+ args.tags,
2352
+ );
2353
+ return {
2354
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
2355
+ details: { result },
2356
+ };
2357
+ } catch (err) {
2358
+ return {
2359
+ content: [{ type: "text", text: `Failed to supersede decision: ${String(err)}` }],
2360
+ details: { error: String(err) },
2361
+ };
2362
+ }
2363
+ },
2364
+ },
2365
+ { name: "decision_supersede" },
2366
+ );
2367
+ }
2368
+
2369
+ // --------------------------------------------------------------------------
2370
+ // 24. decision_check
2371
+ // --------------------------------------------------------------------------
2372
+ if (isToolEnabled("decision_check")) {
2373
+ api.registerTool(
2374
+ {
2375
+ name: "decision_check",
2376
+ description:
2377
+ "Check if there are existing decisions relevant to a topic. ALWAYS call this before making architectural choices to avoid contradicting past decisions." +
2378
+ (defaultProject ? ` Scoped to project '${defaultProject}' by default.` : ""),
2379
+ parameters: {
2380
+ type: "object",
2381
+ properties: {
2382
+ query: {
2383
+ type: "string",
2384
+ description: "Natural language description of the topic or decision area.",
2385
+ },
2386
+ project: {
2387
+ type: "string",
2388
+ description: "Project slug to scope the search.",
2389
+ },
2390
+ limit: {
2391
+ type: "number",
2392
+ description: "Maximum results. Default 5.",
2393
+ },
2394
+ threshold: {
2395
+ type: "number",
2396
+ description: "Minimum similarity threshold (0-1). Default 0.3.",
2397
+ },
2398
+ include_superseded: {
2399
+ type: "boolean",
2400
+ description: "Include superseded decisions in results. Default false.",
2401
+ },
2402
+ },
2403
+ required: ["query"],
2404
+ },
2405
+ execute: async (
2406
+ _id,
2407
+ args: {
2408
+ query: string;
2409
+ project?: string;
2410
+ limit?: number;
2411
+ threshold?: number;
2412
+ include_superseded?: boolean;
2413
+ },
2414
+ ) => {
2415
+ try {
2416
+ const project = args.project ?? defaultProject;
2417
+ const result = await client.checkDecisions(
2418
+ args.query,
2419
+ project,
2420
+ args.limit,
2421
+ args.threshold,
2422
+ args.include_superseded,
2423
+ );
2424
+ return {
2425
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
2426
+ details: { result },
2427
+ };
2428
+ } catch (err) {
2429
+ return {
2430
+ content: [{ type: "text", text: `Failed to check decisions: ${String(err)}` }],
2431
+ details: { error: String(err) },
2432
+ };
2433
+ }
2434
+ },
2435
+ },
2436
+ { name: "decision_check" },
2437
+ );
2438
+ }
2439
+
2440
+ // --------------------------------------------------------------------------
2441
+ // 25. pattern_create
2442
+ // --------------------------------------------------------------------------
2443
+ if (isToolEnabled("pattern_create")) {
2444
+ api.registerTool(
2445
+ {
2446
+ name: "pattern_create",
2447
+ description:
2448
+ "Create a reusable pattern (coding convention, architecture pattern, or best practice) that can be shared across projects. Include example_code for maximum usefulness." +
2449
+ (defaultProject ? ` Source project defaults to '${defaultProject}' if not specified.` : ""),
2450
+ parameters: {
2451
+ type: "object",
2452
+ properties: {
2453
+ title: {
2454
+ type: "string",
2455
+ description: "Pattern title.",
2456
+ },
2457
+ description: {
2458
+ type: "string",
2459
+ description: "Detailed description of the pattern, when to use it, and why.",
2460
+ },
2461
+ category: {
2462
+ type: "string",
2463
+ description: "Category (e.g., architecture, testing, error-handling, naming).",
2464
+ },
2465
+ example_code: {
2466
+ type: "string",
2467
+ description: "Example code demonstrating the pattern.",
2468
+ },
2469
+ scope: {
2470
+ type: "string",
2471
+ description: "Scope: global (visible to all projects) or project (visible to source project only).",
2472
+ enum: ["global", "project"],
2473
+ },
2474
+ tags: {
2475
+ type: "array",
2476
+ description: "Tags for categorization.",
2477
+ items: { type: "string" },
2478
+ },
2479
+ source_project: {
2480
+ type: "string",
2481
+ description: "Project slug where this pattern originated.",
2482
+ },
2483
+ },
2484
+ required: ["title", "description"],
2485
+ },
2486
+ execute: async (
2487
+ _id,
2488
+ args: {
2489
+ title: string;
2490
+ description: string;
2491
+ category?: string;
2492
+ example_code?: string;
2493
+ scope?: string;
2494
+ tags?: string[];
2495
+ source_project?: string;
2496
+ },
2497
+ ) => {
2498
+ try {
2499
+ const sourceProject = args.source_project ?? defaultProject;
2500
+ const result = await client.createPattern(
2501
+ args.title,
2502
+ args.description,
2503
+ args.category,
2504
+ args.example_code,
2505
+ args.scope,
2506
+ args.tags,
2507
+ sourceProject,
2508
+ );
2509
+ return {
2510
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
2511
+ details: { result },
2512
+ };
2513
+ } catch (err) {
2514
+ return {
2515
+ content: [{ type: "text", text: `Failed to create pattern: ${String(err)}` }],
2516
+ details: { error: String(err) },
2517
+ };
2518
+ }
2519
+ },
2520
+ },
2521
+ { name: "pattern_create" },
2522
+ );
2523
+ }
2524
+
2525
+ // --------------------------------------------------------------------------
2526
+ // 26. pattern_search
2527
+ // --------------------------------------------------------------------------
2528
+ if (isToolEnabled("pattern_search")) {
2529
+ api.registerTool(
2530
+ {
2531
+ name: "pattern_search",
2532
+ description: "Search for established patterns by natural language query. Call this before writing code to find and follow existing conventions." +
2533
+ (defaultProject ? ` Scoped to project '${defaultProject}' by default.` : ""),
2534
+ parameters: {
2535
+ type: "object",
2536
+ properties: {
2537
+ query: {
2538
+ type: "string",
2539
+ description: "Natural language search query.",
2540
+ },
2541
+ category: {
2542
+ type: "string",
2543
+ description: "Filter by category.",
2544
+ },
2545
+ project: {
2546
+ type: "string",
2547
+ description: "Filter by project slug.",
2548
+ },
2549
+ limit: {
2550
+ type: "number",
2551
+ description: "Maximum results. Default 10.",
2552
+ },
2553
+ threshold: {
2554
+ type: "number",
2555
+ description: "Minimum similarity threshold (0-1). Default 0.3.",
2556
+ },
2557
+ },
2558
+ required: ["query"],
2559
+ },
2560
+ execute: async (
2561
+ _id,
2562
+ args: {
2563
+ query: string;
2564
+ category?: string;
2565
+ project?: string;
2566
+ limit?: number;
2567
+ threshold?: number;
2568
+ },
2569
+ ) => {
2570
+ try {
2571
+ const project = args.project ?? defaultProject;
2572
+ const result = await client.searchPatterns(
2573
+ args.query,
2574
+ args.category,
2575
+ project,
2576
+ args.limit,
2577
+ args.threshold,
2578
+ );
2579
+ return {
2580
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
2581
+ details: { result },
2582
+ };
2583
+ } catch (err) {
2584
+ return {
2585
+ content: [{ type: "text", text: `Failed to search patterns: ${String(err)}` }],
2586
+ details: { error: String(err) },
2587
+ };
2588
+ }
2589
+ },
2590
+ },
2591
+ { name: "pattern_search" },
2592
+ );
2593
+ }
2594
+
2595
+ // --------------------------------------------------------------------------
2596
+ // 27. pattern_adopt
2597
+ // --------------------------------------------------------------------------
2598
+ if (isToolEnabled("pattern_adopt")) {
2599
+ api.registerTool(
2600
+ {
2601
+ name: "pattern_adopt",
2602
+ description: "Adopt an existing pattern for use in a project. Creates a link between the pattern and the project.",
2603
+ parameters: {
2604
+ type: "object",
2605
+ properties: {
2606
+ id: {
2607
+ type: "string",
2608
+ description: "Pattern ID to adopt.",
2609
+ },
2610
+ project: {
2611
+ type: "string",
2612
+ description: "Project slug adopting the pattern.",
2613
+ },
2614
+ },
2615
+ required: ["id", "project"],
2616
+ },
2617
+ execute: async (_id, args: { id: string; project: string }) => {
2618
+ try {
2619
+ const result = await client.adoptPattern(args.id, args.project);
2620
+ return {
2621
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
2622
+ details: { result },
2623
+ };
2624
+ } catch (err) {
2625
+ return {
2626
+ content: [{ type: "text", text: `Failed to adopt pattern: ${String(err)}` }],
2627
+ details: { error: String(err) },
2628
+ };
2629
+ }
2630
+ },
2631
+ },
2632
+ { name: "pattern_adopt" },
2633
+ );
2634
+ }
2635
+
2636
+ // --------------------------------------------------------------------------
2637
+ // 28. pattern_suggest
2638
+ // --------------------------------------------------------------------------
2639
+ if (isToolEnabled("pattern_suggest")) {
2640
+ api.registerTool(
2641
+ {
2642
+ name: "pattern_suggest",
2643
+ description:
2644
+ "Get pattern suggestions for a project based on its stack and existing patterns from related projects.",
2645
+ parameters: {
2646
+ type: "object",
2647
+ properties: {
2648
+ project: {
2649
+ type: "string",
2650
+ description: "Project slug to get suggestions for.",
2651
+ },
2652
+ limit: {
2653
+ type: "number",
2654
+ description: "Maximum suggestions. Default 10.",
2655
+ },
2656
+ },
2657
+ required: ["project"],
2658
+ },
2659
+ execute: async (_id, args: { project: string; limit?: number }) => {
2660
+ try {
2661
+ const result = await client.suggestPatterns(args.project, args.limit);
2662
+ return {
2663
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
2664
+ details: { result },
2665
+ };
2666
+ } catch (err) {
2667
+ return {
2668
+ content: [{ type: "text", text: `Failed to suggest patterns: ${String(err)}` }],
2669
+ details: { error: String(err) },
2670
+ };
2671
+ }
2672
+ },
2673
+ },
2674
+ { name: "pattern_suggest" },
2675
+ );
2676
+ }
2677
+
2678
+ // --------------------------------------------------------------------------
2679
+ // 29. project_register
2680
+ // --------------------------------------------------------------------------
2681
+ if (isToolEnabled("project_register")) {
2682
+ api.registerTool(
2683
+ {
2684
+ name: "project_register",
2685
+ description: "Register a new project in MemoryRelay. Projects organize memories, decisions, patterns, and sessions.",
2686
+ parameters: {
2687
+ type: "object",
2688
+ properties: {
2689
+ slug: {
2690
+ type: "string",
2691
+ description: "URL-friendly project identifier (e.g., 'my-api', 'frontend-app').",
2692
+ },
2693
+ name: {
2694
+ type: "string",
2695
+ description: "Human-readable project name.",
2696
+ },
2697
+ description: {
2698
+ type: "string",
2699
+ description: "Project description.",
2700
+ },
2701
+ stack: {
2702
+ type: "object",
2703
+ description: "Technology stack details (e.g., {language: 'python', framework: 'fastapi'}).",
2704
+ },
2705
+ repo_url: {
2706
+ type: "string",
2707
+ description: "Repository URL.",
2708
+ },
2709
+ },
2710
+ required: ["slug", "name"],
2711
+ },
2712
+ execute: async (
2713
+ _id,
2714
+ args: {
2715
+ slug: string;
2716
+ name: string;
2717
+ description?: string;
2718
+ stack?: Record<string, unknown>;
2719
+ repo_url?: string;
2720
+ },
2721
+ ) => {
2722
+ try {
2723
+ const result = await client.registerProject(
2724
+ args.slug,
2725
+ args.name,
2726
+ args.description,
2727
+ args.stack,
2728
+ args.repo_url,
2729
+ );
2730
+ return {
2731
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
2732
+ details: { result },
2733
+ };
2734
+ } catch (err) {
2735
+ return {
2736
+ content: [{ type: "text", text: `Failed to register project: ${String(err)}` }],
2737
+ details: { error: String(err) },
2738
+ };
2739
+ }
2740
+ },
2741
+ },
2742
+ { name: "project_register" },
2743
+ );
2744
+ }
2745
+
2746
+ // --------------------------------------------------------------------------
2747
+ // 30. project_list
2748
+ // --------------------------------------------------------------------------
2749
+ if (isToolEnabled("project_list")) {
2750
+ api.registerTool(
2751
+ {
2752
+ name: "project_list",
2753
+ description: "List all registered projects.",
2754
+ parameters: {
2755
+ type: "object",
2756
+ properties: {
2757
+ limit: {
2758
+ type: "number",
2759
+ description: "Maximum projects to return. Default 20.",
2760
+ minimum: 1,
2761
+ maximum: 100,
2762
+ },
2763
+ },
2764
+ },
2765
+ execute: async (_id, args: { limit?: number }) => {
2766
+ try {
2767
+ const result = await client.listProjects(args.limit);
2768
+ return {
2769
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
2770
+ details: { result },
2771
+ };
2772
+ } catch (err) {
2773
+ return {
2774
+ content: [{ type: "text", text: `Failed to list projects: ${String(err)}` }],
2775
+ details: { error: String(err) },
2776
+ };
2777
+ }
2778
+ },
2779
+ },
2780
+ { name: "project_list" },
2781
+ );
2782
+ }
2783
+
2784
+ // --------------------------------------------------------------------------
2785
+ // 31. project_info
2786
+ // --------------------------------------------------------------------------
2787
+ if (isToolEnabled("project_info")) {
2788
+ api.registerTool(
2789
+ {
2790
+ name: "project_info",
2791
+ description: "Get detailed information about a specific project.",
2792
+ parameters: {
2793
+ type: "object",
2794
+ properties: {
2795
+ slug: {
2796
+ type: "string",
2797
+ description: "Project slug.",
2798
+ },
2799
+ },
2800
+ required: ["slug"],
2801
+ },
2802
+ execute: async (_id, args: { slug: string }) => {
2803
+ try {
2804
+ const result = await client.getProject(args.slug);
2805
+ return {
2806
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
2807
+ details: { result },
2808
+ };
2809
+ } catch (err) {
2810
+ return {
2811
+ content: [{ type: "text", text: `Failed to get project: ${String(err)}` }],
2812
+ details: { error: String(err) },
2813
+ };
2814
+ }
2815
+ },
2816
+ },
2817
+ { name: "project_info" },
2818
+ );
2819
+ }
2820
+
2821
+ // --------------------------------------------------------------------------
2822
+ // 32. project_add_relationship
2823
+ // --------------------------------------------------------------------------
2824
+ if (isToolEnabled("project_add_relationship")) {
2825
+ api.registerTool(
2826
+ {
2827
+ name: "project_add_relationship",
2828
+ description:
2829
+ "Add a relationship between two projects (e.g., depends_on, api_consumer, shares_schema, shares_infra, pattern_source, forked_from).",
2830
+ parameters: {
2831
+ type: "object",
2832
+ properties: {
2833
+ from: {
2834
+ type: "string",
2835
+ description: "Source project slug.",
2836
+ },
2837
+ to: {
2838
+ type: "string",
2839
+ description: "Target project slug.",
2840
+ },
2841
+ type: {
2842
+ type: "string",
2843
+ description: "Relationship type (e.g., depends_on, api_consumer, shares_schema, shares_infra, pattern_source, forked_from).",
2844
+ },
2845
+ metadata: {
2846
+ type: "object",
2847
+ description: "Optional metadata about the relationship.",
2848
+ },
2849
+ },
2850
+ required: ["from", "to", "type"],
2851
+ },
2852
+ execute: async (
2853
+ _id,
2854
+ args: { from: string; to: string; type: string; metadata?: Record<string, unknown> },
2855
+ ) => {
2856
+ try {
2857
+ const result = await client.addProjectRelationship(
2858
+ args.from,
2859
+ args.to,
2860
+ args.type,
2861
+ args.metadata,
2862
+ );
2863
+ return {
2864
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
2865
+ details: { result },
2866
+ };
2867
+ } catch (err) {
2868
+ return {
2869
+ content: [{ type: "text", text: `Failed to add relationship: ${String(err)}` }],
2870
+ details: { error: String(err) },
2871
+ };
2872
+ }
2873
+ },
2874
+ },
2875
+ { name: "project_add_relationship" },
2876
+ );
2877
+ }
2878
+
2879
+ // --------------------------------------------------------------------------
2880
+ // 33. project_dependencies
2881
+ // --------------------------------------------------------------------------
2882
+ if (isToolEnabled("project_dependencies")) {
2883
+ api.registerTool(
2884
+ {
2885
+ name: "project_dependencies",
2886
+ description: "List projects that a given project depends on.",
2887
+ parameters: {
2888
+ type: "object",
2889
+ properties: {
2890
+ project: {
2891
+ type: "string",
2892
+ description: "Project slug.",
2893
+ },
2894
+ },
2895
+ required: ["project"],
2896
+ },
2897
+ execute: async (_id, args: { project: string }) => {
2898
+ try {
2899
+ const result = await client.getProjectDependencies(args.project);
2900
+ return {
2901
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
2902
+ details: { result },
2903
+ };
2904
+ } catch (err) {
2905
+ return {
2906
+ content: [{ type: "text", text: `Failed to get dependencies: ${String(err)}` }],
2907
+ details: { error: String(err) },
2908
+ };
2909
+ }
2910
+ },
2911
+ },
2912
+ { name: "project_dependencies" },
2913
+ );
2914
+ }
2915
+
2916
+ // --------------------------------------------------------------------------
2917
+ // 34. project_dependents
2918
+ // --------------------------------------------------------------------------
2919
+ if (isToolEnabled("project_dependents")) {
2920
+ api.registerTool(
2921
+ {
2922
+ name: "project_dependents",
2923
+ description: "List projects that depend on a given project.",
2924
+ parameters: {
2925
+ type: "object",
2926
+ properties: {
2927
+ project: {
2928
+ type: "string",
2929
+ description: "Project slug.",
2930
+ },
2931
+ },
2932
+ required: ["project"],
2933
+ },
2934
+ execute: async (_id, args: { project: string }) => {
2935
+ try {
2936
+ const result = await client.getProjectDependents(args.project);
2937
+ return {
2938
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
2939
+ details: { result },
2940
+ };
2941
+ } catch (err) {
2942
+ return {
2943
+ content: [{ type: "text", text: `Failed to get dependents: ${String(err)}` }],
2944
+ details: { error: String(err) },
2945
+ };
2946
+ }
2947
+ },
2948
+ },
2949
+ { name: "project_dependents" },
2950
+ );
2951
+ }
2952
+
2953
+ // --------------------------------------------------------------------------
2954
+ // 35. project_related
2955
+ // --------------------------------------------------------------------------
2956
+ if (isToolEnabled("project_related")) {
2957
+ api.registerTool(
2958
+ {
2959
+ name: "project_related",
2960
+ description: "List all projects related to a given project (any relationship direction).",
2961
+ parameters: {
2962
+ type: "object",
2963
+ properties: {
2964
+ project: {
2965
+ type: "string",
2966
+ description: "Project slug.",
2967
+ },
2968
+ },
2969
+ required: ["project"],
2970
+ },
2971
+ execute: async (_id, args: { project: string }) => {
2972
+ try {
2973
+ const result = await client.getProjectRelated(args.project);
2974
+ return {
2975
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
2976
+ details: { result },
2977
+ };
2978
+ } catch (err) {
2979
+ return {
2980
+ content: [{ type: "text", text: `Failed to get related projects: ${String(err)}` }],
2981
+ details: { error: String(err) },
2982
+ };
2983
+ }
2984
+ },
2985
+ },
2986
+ { name: "project_related" },
2987
+ );
2988
+ }
2989
+
2990
+ // --------------------------------------------------------------------------
2991
+ // 36. project_impact
2992
+ // --------------------------------------------------------------------------
2993
+ if (isToolEnabled("project_impact")) {
2994
+ api.registerTool(
2995
+ {
2996
+ name: "project_impact",
2997
+ description:
2998
+ "Analyze the impact of a proposed change on a project and its dependents. Helps understand blast radius before making changes.",
2999
+ parameters: {
3000
+ type: "object",
3001
+ properties: {
3002
+ project: {
3003
+ type: "string",
3004
+ description: "Project slug to analyze.",
3005
+ },
3006
+ change_description: {
3007
+ type: "string",
3008
+ description: "Description of the proposed change.",
3009
+ },
3010
+ },
3011
+ required: ["project", "change_description"],
3012
+ },
3013
+ execute: async (_id, args: { project: string; change_description: string }) => {
3014
+ try {
3015
+ const result = await client.projectImpact(args.project, args.change_description);
3016
+ return {
3017
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
3018
+ details: { result },
3019
+ };
3020
+ } catch (err) {
3021
+ return {
3022
+ content: [{ type: "text", text: `Failed to analyze impact: ${String(err)}` }],
3023
+ details: { error: String(err) },
3024
+ };
3025
+ }
3026
+ },
3027
+ },
3028
+ { name: "project_impact" },
3029
+ );
3030
+ }
3031
+
3032
+ // --------------------------------------------------------------------------
3033
+ // 37. project_shared_patterns
3034
+ // --------------------------------------------------------------------------
3035
+ if (isToolEnabled("project_shared_patterns")) {
3036
+ api.registerTool(
3037
+ {
3038
+ name: "project_shared_patterns",
3039
+ description: "Find patterns shared between two projects. Useful for maintaining consistency across related projects.",
3040
+ parameters: {
3041
+ type: "object",
3042
+ properties: {
3043
+ project_a: {
3044
+ type: "string",
3045
+ description: "First project slug.",
3046
+ },
3047
+ project_b: {
3048
+ type: "string",
3049
+ description: "Second project slug.",
3050
+ },
3051
+ },
3052
+ required: ["project_a", "project_b"],
3053
+ },
3054
+ execute: async (_id, args: { project_a: string; project_b: string }) => {
3055
+ try {
3056
+ const result = await client.getSharedPatterns(args.project_a, args.project_b);
3057
+ return {
3058
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
3059
+ details: { result },
3060
+ };
3061
+ } catch (err) {
3062
+ return {
3063
+ content: [{ type: "text", text: `Failed to get shared patterns: ${String(err)}` }],
3064
+ details: { error: String(err) },
3065
+ };
3066
+ }
3067
+ },
3068
+ },
3069
+ { name: "project_shared_patterns" },
3070
+ );
3071
+ }
3072
+
3073
+ // --------------------------------------------------------------------------
3074
+ // 38. project_context
3075
+ // --------------------------------------------------------------------------
3076
+ if (isToolEnabled("project_context")) {
3077
+ api.registerTool(
3078
+ {
3079
+ name: "project_context",
3080
+ description:
3081
+ "Load full project context including hot-tier memories, active decisions, adopted patterns, and recent sessions. Call this FIRST when starting work on a project to understand existing context before making changes.",
3082
+ parameters: {
3083
+ type: "object",
3084
+ properties: {
3085
+ project: {
3086
+ type: "string",
3087
+ description: "Project slug.",
3088
+ },
3089
+ },
3090
+ required: ["project"],
3091
+ },
3092
+ execute: async (_id, args: { project: string }) => {
3093
+ try {
3094
+ const result = await client.getProjectContext(args.project);
3095
+ return {
3096
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
3097
+ details: { result },
3098
+ };
3099
+ } catch (err) {
3100
+ return {
3101
+ content: [{ type: "text", text: `Failed to load project context: ${String(err)}` }],
3102
+ details: { error: String(err) },
3103
+ };
3104
+ }
3105
+ },
3106
+ },
3107
+ { name: "project_context" },
3108
+ );
3109
+ }
3110
+
3111
+ // --------------------------------------------------------------------------
3112
+ // 39. memory_health
3113
+ // --------------------------------------------------------------------------
3114
+ if (isToolEnabled("memory_health")) {
3115
+ api.registerTool(
3116
+ {
3117
+ name: "memory_health",
3118
+ description: "Check the MemoryRelay API connectivity and health status.",
3119
+ parameters: {
3120
+ type: "object",
3121
+ properties: {},
3122
+ },
3123
+ execute: async () => {
3124
+ try {
3125
+ const health = await client.health();
3126
+ return {
3127
+ content: [{ type: "text", text: JSON.stringify(health, null, 2) }],
3128
+ details: { health },
3129
+ };
3130
+ } catch (err) {
3131
+ return {
3132
+ content: [{ type: "text", text: `Health check failed: ${String(err)}` }],
3133
+ details: { error: String(err) },
3134
+ };
3135
+ }
3136
+ },
3137
+ },
3138
+ { name: "memory_health" },
3139
+ );
3140
+ }
3141
+
3142
+ // ========================================================================
3143
+ // CLI Commands
3144
+ // ========================================================================
3145
+
3146
+ api.registerCli(
3147
+ ({ program }) => {
3148
+ const mem = program.command("memoryrelay").description("MemoryRelay memory plugin commands");
3149
+
3150
+ mem
3151
+ .command("status")
3152
+ .description("Check MemoryRelay connection status")
3153
+ .action(async () => {
3154
+ try {
3155
+ const health = await client.health();
3156
+ const stats = await client.stats();
3157
+ console.log(`Status: ${health.status}`);
3158
+ console.log(`Agent ID: ${agentId}`);
3159
+ console.log(`API: ${apiUrl}`);
3160
+ console.log(`Total Memories: ${stats.total_memories}`);
3161
+ if (stats.last_updated) {
3162
+ console.log(`Last Updated: ${new Date(stats.last_updated).toLocaleString()}`);
3163
+ }
3164
+ } catch (err) {
3165
+ console.error(`Connection failed: ${String(err)}`);
3166
+ }
3167
+ });
3168
+
3169
+ mem
3170
+ .command("stats")
3171
+ .description("Show agent statistics")
3172
+ .action(async () => {
3173
+ try {
3174
+ const stats = await client.stats();
3175
+ console.log(`Total Memories: ${stats.total_memories}`);
3176
+ if (stats.last_updated) {
3177
+ console.log(`Last Updated: ${new Date(stats.last_updated).toLocaleString()}`);
3178
+ }
3179
+ } catch (err) {
3180
+ console.error(`Failed to fetch stats: ${String(err)}`);
3181
+ }
3182
+ });
3183
+
3184
+ mem
3185
+ .command("list")
3186
+ .description("List recent memories")
3187
+ .option("--limit <n>", "Max results", "10")
3188
+ .action(async (opts) => {
3189
+ try {
3190
+ const memories = await client.list(parseInt(opts.limit));
3191
+ for (const m of memories) {
3192
+ console.log(`[${m.id.slice(0, 8)}] ${m.content.slice(0, 80)}...`);
3193
+ }
3194
+ console.log(`\nTotal: ${memories.length} memories`);
3195
+ } catch (err) {
3196
+ console.error(`Failed to list memories: ${String(err)}`);
3197
+ }
3198
+ });
3199
+
3200
+ mem
3201
+ .command("search")
3202
+ .description("Search memories")
3203
+ .argument("<query>", "Search query")
3204
+ .option("--limit <n>", "Max results", "5")
3205
+ .action(async (query, opts) => {
3206
+ try {
3207
+ const results = await client.search(query, parseInt(opts.limit));
3208
+ for (const r of results) {
3209
+ console.log(`[${r.score.toFixed(2)}] ${r.memory.content.slice(0, 80)}...`);
3210
+ }
3211
+ } catch (err) {
3212
+ console.error(`Search failed: ${String(err)}`);
3213
+ }
3214
+ });
3215
+
3216
+ mem
3217
+ .command("delete")
3218
+ .description("Delete a memory by ID")
3219
+ .argument("<id>", "Memory ID")
3220
+ .action(async (id) => {
3221
+ try {
3222
+ await client.delete(id);
3223
+ console.log(`Memory ${id.slice(0, 8)}... deleted.`);
3224
+ } catch (err) {
3225
+ console.error(`Delete failed: ${String(err)}`);
3226
+ }
3227
+ });
3228
+
3229
+ mem
3230
+ .command("export")
3231
+ .description("Export all memories to JSON file")
3232
+ .option("--output <path>", "Output file path", "memories-export.json")
3233
+ .action(async (opts) => {
3234
+ try {
3235
+ console.log("Exporting memories...");
3236
+ const memories = await client.export();
3237
+ const fs = await import("fs/promises");
3238
+ await fs.writeFile(opts.output, JSON.stringify(memories, null, 2));
3239
+ console.log(`Exported ${memories.length} memories to ${opts.output}`);
3240
+ } catch (err) {
3241
+ console.error(`Export failed: ${String(err)}`);
3242
+ }
3243
+ });
162
3244
  },
3245
+ { commands: ["memoryrelay"] },
3246
+ );
3247
+
3248
+ // ========================================================================
3249
+ // Lifecycle Hooks
3250
+ // ========================================================================
3251
+
3252
+ // Workflow instructions + auto-recall: always inject workflow guidance,
3253
+ // optionally recall relevant memories if autoRecall is enabled
3254
+ api.on("before_agent_start", async (event) => {
3255
+ if (!event.prompt || event.prompt.length < 10) {
3256
+ return;
3257
+ }
3258
+
3259
+ // Check if current channel is excluded
3260
+ if (cfg?.excludeChannels && event.channel) {
3261
+ const channelId = String(event.channel);
3262
+ if (cfg.excludeChannels.some((excluded) => channelId.includes(excluded))) {
3263
+ api.logger.debug?.(
3264
+ `memory-memoryrelay: skipping for excluded channel: ${channelId}`,
3265
+ );
3266
+ return;
3267
+ }
3268
+ }
3269
+
3270
+ // Build workflow instructions dynamically based on enabled tools
3271
+ const lines: string[] = [
3272
+ "You have MemoryRelay tools available for persistent memory across sessions.",
3273
+ ];
3274
+
3275
+ if (defaultProject) {
3276
+ lines.push(`Default project: \`${defaultProject}\` (auto-applied when you omit the project parameter).`);
3277
+ }
3278
+
3279
+ lines.push("", "## Recommended Workflow", "");
3280
+
3281
+ // Starting work section — only include steps for enabled tools
3282
+ const startSteps: string[] = [];
3283
+ if (isToolEnabled("project_context")) {
3284
+ startSteps.push(`**Load context**: Call \`project_context(${defaultProject ? `"${defaultProject}"` : "project"})\` to load hot-tier memories, active decisions, and adopted patterns`);
3285
+ }
3286
+ if (isToolEnabled("session_start")) {
3287
+ startSteps.push(`**Start session**: Call \`session_start(title${defaultProject ? "" : ", project"})\` to begin tracking your work`);
3288
+ }
3289
+ if (isToolEnabled("decision_check")) {
3290
+ startSteps.push(`**Check decisions**: Call \`decision_check(query${defaultProject ? "" : ", project"})\` before making architectural choices`);
3291
+ }
3292
+ if (isToolEnabled("pattern_search")) {
3293
+ startSteps.push("**Find patterns**: Call `pattern_search(query)` to find established conventions before writing code");
3294
+ }
3295
+
3296
+ if (startSteps.length > 0) {
3297
+ lines.push("When starting work on a project:");
3298
+ startSteps.forEach((step, i) => lines.push(`${i + 1}. ${step}`));
3299
+ lines.push("");
3300
+ }
3301
+
3302
+ // While working section
3303
+ const workSteps: string[] = [];
3304
+ if (isToolEnabled("memory_store")) {
3305
+ workSteps.push("**Store findings**: Call `memory_store(content, metadata)` for important information worth remembering");
3306
+ }
3307
+ if (isToolEnabled("decision_record")) {
3308
+ workSteps.push(`**Record decisions**: Call \`decision_record(title, rationale${defaultProject ? "" : ", project"})\` when making significant architectural choices`);
3309
+ }
3310
+ if (isToolEnabled("pattern_create")) {
3311
+ workSteps.push("**Create patterns**: Call `pattern_create(title, description)` when establishing reusable conventions");
3312
+ }
3313
+
3314
+ if (workSteps.length > 0) {
3315
+ lines.push("While working:");
3316
+ const offset = startSteps.length;
3317
+ workSteps.forEach((step, i) => lines.push(`${offset + i + 1}. ${step}`));
3318
+ lines.push("");
3319
+ }
3320
+
3321
+ // When done section
3322
+ if (isToolEnabled("session_end")) {
3323
+ const offset = startSteps.length + workSteps.length;
3324
+ lines.push("When done:");
3325
+ lines.push(`${offset + 1}. **End session**: Call \`session_end(session_id, summary)\` with a summary of what was accomplished`);
3326
+ lines.push("");
3327
+ }
3328
+
3329
+ // First-time setup — only if project tools are enabled
3330
+ if (isToolEnabled("project_register")) {
3331
+ lines.push("## First-Time Setup", "");
3332
+ lines.push("If the project is not yet registered, start with:");
3333
+ lines.push("1. `project_register(slug, name, description, stack)` to register the project");
3334
+ lines.push("2. Then follow the workflow above");
3335
+ lines.push("");
3336
+ if (isToolEnabled("project_list")) {
3337
+ lines.push("Use `project_list()` to see existing projects before registering a new one.");
3338
+ }
3339
+ }
3340
+
3341
+ // Memory-only fallback — if no session/decision/project tools are enabled
3342
+ if (startSteps.length === 0 && workSteps.length === 0) {
3343
+ lines.push("Use `memory_store(content)` to save important information and `memory_recall(query)` to find relevant memories.");
3344
+ }
3345
+
3346
+ const workflowInstructions = lines.join("\n");
3347
+
3348
+ let prependContext = `<memoryrelay-workflow>\n${workflowInstructions}\n</memoryrelay-workflow>`;
3349
+
3350
+ // Auto-recall: search and inject relevant memories
3351
+ if (cfg?.autoRecall) {
3352
+ try {
3353
+ const results = await client.search(
3354
+ event.prompt,
3355
+ cfg.recallLimit || 5,
3356
+ cfg.recallThreshold || 0.3,
3357
+ );
3358
+
3359
+ if (results.length > 0) {
3360
+ const memoryContext = results.map((r) => `- ${r.memory.content}`).join("\n");
3361
+
3362
+ api.logger.info?.(
3363
+ `memory-memoryrelay: injecting ${results.length} memories into context`,
3364
+ );
3365
+
3366
+ prependContext +=
3367
+ `\n\n<relevant-memories>\nThe following memories from MemoryRelay may be relevant:\n${memoryContext}\n</relevant-memories>`;
3368
+ }
3369
+ } catch (err) {
3370
+ api.logger.warn?.(`memory-memoryrelay: recall failed: ${String(err)}`);
3371
+ }
3372
+ }
3373
+
3374
+ return { prependContext };
163
3375
  });
164
3376
 
165
- api.logger.info(`memory-memoryrelay: connected to ${apiUrl}`);
3377
+ // Auto-capture: analyze and store important information after agent ends
3378
+ if (cfg?.autoCapture) {
3379
+ api.on("agent_end", async (event) => {
3380
+ if (!event.success || !event.messages || event.messages.length === 0) {
3381
+ return;
3382
+ }
3383
+
3384
+ try {
3385
+ const texts: string[] = [];
3386
+ for (const msg of event.messages) {
3387
+ if (!msg || typeof msg !== "object") continue;
3388
+ const msgObj = msg as Record<string, unknown>;
3389
+ const role = msgObj.role;
3390
+ if (role !== "user" && role !== "assistant") continue;
3391
+
3392
+ const content = msgObj.content;
3393
+ if (typeof content === "string") {
3394
+ texts.push(content);
3395
+ } else if (Array.isArray(content)) {
3396
+ for (const block of content) {
3397
+ if (
3398
+ block &&
3399
+ typeof block === "object" &&
3400
+ "type" in block &&
3401
+ (block as Record<string, unknown>).type === "text" &&
3402
+ "text" in block
3403
+ ) {
3404
+ texts.push((block as Record<string, unknown>).text as string);
3405
+ }
3406
+ }
3407
+ }
3408
+ }
3409
+
3410
+ const toCapture = texts.filter((text) => text && shouldCapture(text));
3411
+ if (toCapture.length === 0) return;
3412
+
3413
+ let stored = 0;
3414
+ for (const text of toCapture.slice(0, 3)) {
3415
+ // Check for duplicates via search
3416
+ const existing = await client.search(text, 1, 0.95);
3417
+ if (existing.length > 0) continue;
3418
+
3419
+ await client.store(text, { source: "auto-capture" });
3420
+ stored++;
3421
+ }
3422
+
3423
+ if (stored > 0) {
3424
+ api.logger.info?.(`memory-memoryrelay: auto-captured ${stored} memories`);
3425
+ }
3426
+ } catch (err) {
3427
+ api.logger.warn?.(`memory-memoryrelay: capture failed: ${String(err)}`);
3428
+ }
3429
+ });
3430
+ }
3431
+
3432
+ api.logger.info?.(
3433
+ `memory-memoryrelay: plugin v0.8.0 loaded (39 tools, autoRecall: ${cfg?.autoRecall}, autoCapture: ${cfg?.autoCapture}, debug: ${debugEnabled})`,
3434
+ );
3435
+
3436
+ // ========================================================================
3437
+ // CLI Helper Tools (v0.8.0)
3438
+ // ========================================================================
3439
+
3440
+ // Register CLI-accessible tools for debugging and diagnostics
3441
+
3442
+ // memoryrelay:logs - Get debug logs
3443
+ if (debugLogger) {
3444
+ api.registerGatewayMethod?.("memoryrelay.logs", async ({ respond, args }) => {
3445
+ try {
3446
+ const limit = args?.limit || 20;
3447
+ const toolName = args?.tool;
3448
+ const errorsOnly = args?.errorsOnly || false;
3449
+
3450
+ let logs: LogEntry[];
3451
+ if (toolName) {
3452
+ logs = debugLogger.getToolLogs(toolName, limit);
3453
+ } else if (errorsOnly) {
3454
+ logs = debugLogger.getErrorLogs(limit);
3455
+ } else {
3456
+ logs = debugLogger.getRecentLogs(limit);
3457
+ }
3458
+
3459
+ const formatted = DebugLogger.formatTable(logs);
3460
+ respond(true, {
3461
+ logs,
3462
+ formatted,
3463
+ count: logs.length,
3464
+ });
3465
+ } catch (err) {
3466
+ respond(false, { error: String(err) });
3467
+ }
3468
+ });
3469
+ }
3470
+
3471
+ // memoryrelay:health - Comprehensive health check
3472
+ api.registerGatewayMethod?.("memoryrelay.health", async ({ respond }) => {
3473
+ try {
3474
+ const startTime = Date.now();
3475
+ const health = await client.health();
3476
+ const healthDuration = Date.now() - startTime;
3477
+
3478
+ const results: any = {
3479
+ api: {
3480
+ status: health.status,
3481
+ endpoint: apiUrl,
3482
+ responseTime: healthDuration,
3483
+ reachable: true,
3484
+ },
3485
+ authentication: {
3486
+ status: "valid",
3487
+ apiKey: apiKey.substring(0, 16) + "...",
3488
+ },
3489
+ tools: {},
3490
+ };
3491
+
3492
+ // Test critical tools
3493
+ const toolTests = [
3494
+ { name: "memory_store", test: async () => {
3495
+ const testMem = await client.store("Plugin health check test", { test: "true" });
3496
+ await client.delete(testMem.id);
3497
+ return { success: true };
3498
+ }},
3499
+ { name: "memory_recall", test: async () => {
3500
+ await client.search("test", 1, 0.5);
3501
+ return { success: true };
3502
+ }},
3503
+ { name: "memory_list", test: async () => {
3504
+ await client.list(1);
3505
+ return { success: true };
3506
+ }},
3507
+ ];
3508
+
3509
+ for (const { name, test } of toolTests) {
3510
+ const testStart = Date.now();
3511
+ try {
3512
+ await test();
3513
+ results.tools[name] = {
3514
+ status: "working",
3515
+ duration: Date.now() - testStart,
3516
+ };
3517
+ } catch (err) {
3518
+ results.tools[name] = {
3519
+ status: "error",
3520
+ error: String(err),
3521
+ duration: Date.now() - testStart,
3522
+ };
3523
+ }
3524
+ }
3525
+
3526
+ // Overall status
3527
+ const allToolsWorking = Object.values(results.tools).every(
3528
+ (t: any) => t.status === "working"
3529
+ );
3530
+ results.overall = allToolsWorking ? "healthy" : "degraded";
3531
+
3532
+ respond(true, results);
3533
+ } catch (err) {
3534
+ respond(false, {
3535
+ overall: "unhealthy",
3536
+ error: String(err),
3537
+ });
3538
+ }
3539
+ });
3540
+
3541
+ // memoryrelay:metrics - Performance metrics
3542
+ if (debugLogger) {
3543
+ api.registerGatewayMethod?.("memoryrelay.metrics", async ({ respond }) => {
3544
+ try {
3545
+ const stats = debugLogger.getStats();
3546
+ const allLogs = debugLogger.getAllLogs();
3547
+
3548
+ // Calculate per-tool metrics
3549
+ const toolMetrics: Record<string, any> = {};
3550
+ for (const log of allLogs) {
3551
+ if (!toolMetrics[log.tool]) {
3552
+ toolMetrics[log.tool] = {
3553
+ calls: 0,
3554
+ successes: 0,
3555
+ failures: 0,
3556
+ totalDuration: 0,
3557
+ durations: [],
3558
+ };
3559
+ }
3560
+ const metric = toolMetrics[log.tool];
3561
+ metric.calls++;
3562
+ if (log.status === "success") {
3563
+ metric.successes++;
3564
+ } else {
3565
+ metric.failures++;
3566
+ }
3567
+ metric.totalDuration += log.duration;
3568
+ metric.durations.push(log.duration);
3569
+ }
3570
+
3571
+ // Calculate averages and percentiles
3572
+ for (const tool in toolMetrics) {
3573
+ const metric = toolMetrics[tool];
3574
+ metric.avgDuration = Math.round(metric.totalDuration / metric.calls);
3575
+ metric.successRate = Math.round((metric.successes / metric.calls) * 100);
3576
+
3577
+ // Calculate p95 and p99
3578
+ const sorted = metric.durations.sort((a: number, b: number) => a - b);
3579
+ const p95Index = Math.floor(sorted.length * 0.95);
3580
+ const p99Index = Math.floor(sorted.length * 0.99);
3581
+ metric.p95Duration = sorted[p95Index] || 0;
3582
+ metric.p99Duration = sorted[p99Index] || 0;
3583
+
3584
+ delete metric.durations; // Don't include raw data in response
3585
+ }
3586
+
3587
+ respond(true, {
3588
+ summary: stats,
3589
+ toolMetrics,
3590
+ });
3591
+ } catch (err) {
3592
+ respond(false, { error: String(err) });
3593
+ }
3594
+ });
3595
+ }
3596
+
3597
+ // memoryrelay:test - Test individual tool
3598
+ api.registerGatewayMethod?.("memoryrelay.test", async ({ respond, args }) => {
3599
+ try {
3600
+ const toolName = args?.tool;
3601
+ if (!toolName) {
3602
+ respond(false, { error: "Missing required argument: tool" });
3603
+ return;
3604
+ }
3605
+
3606
+ const startTime = Date.now();
3607
+ let result: any;
3608
+ let error: string | undefined;
3609
+
3610
+ // Test the specified tool
3611
+ try {
3612
+ switch (toolName) {
3613
+ case "memory_store":
3614
+ const mem = await client.store("Test memory", { test: "true" });
3615
+ await client.delete(mem.id);
3616
+ result = { success: true, message: "Memory stored and deleted successfully" };
3617
+ break;
3618
+
3619
+ case "memory_recall":
3620
+ const searchResults = await client.search("test", 1, 0.5);
3621
+ result = { success: true, results: searchResults.length, message: "Search completed" };
3622
+ break;
3623
+
3624
+ case "memory_list":
3625
+ const list = await client.list(5);
3626
+ result = { success: true, count: list.length, message: "List retrieved" };
3627
+ break;
3628
+
3629
+ case "project_list":
3630
+ const projects = await client.listProjects(5);
3631
+ result = { success: true, count: projects.length, message: "Projects listed" };
3632
+ break;
3633
+
3634
+ case "memory_health":
3635
+ const health = await client.health();
3636
+ result = { success: true, status: health.status, message: "Health check passed" };
3637
+ break;
3638
+
3639
+ default:
3640
+ result = { success: false, message: `Unknown tool: ${toolName}` };
3641
+ }
3642
+ } catch (err) {
3643
+ error = String(err);
3644
+ result = { success: false, error };
3645
+ }
3646
+
3647
+ const duration = Date.now() - startTime;
3648
+
3649
+ respond(true, {
3650
+ tool: toolName,
3651
+ duration,
3652
+ result,
3653
+ error,
3654
+ });
3655
+ } catch (err) {
3656
+ respond(false, { error: String(err) });
3657
+ }
3658
+ });
166
3659
  }