-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathindex.ts
More file actions
592 lines (519 loc) · 20.9 KB
/
Copy pathindex.ts
File metadata and controls
592 lines (519 loc) · 20.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
import type { Plugin, PluginInput } from "@opencode-ai/plugin";
import type { Part, Permission } from "@opencode-ai/sdk";
import { tool } from "@opencode-ai/plugin";
import { supermemoryClient } from "./services/client.js";
import { formatContextForPrompt } from "./services/context.js";
import { buildRecallDirective } from "./services/recall.js";
import { getTags } from "./services/tags.js";
import { stripPrivateContent, isFullyPrivate } from "./services/privacy.js";
import { createCompactionHook, type CompactionContext } from "./services/compaction.js";
import { isConfigured, CONFIG, PLUGIN_VERSION } from "./config.js";
import { log } from "./services/logger.js";
import { checkNpmUpdate, formatUpdateNotice } from "./services/version-check.js";
import type { MemoryScope, MemoryType } from "./types/index.js";
const CODE_BLOCK_PATTERN = /```[\s\S]*?```/g;
const INLINE_CODE_PATTERN = /`[^`]+`/g;
const MEMORY_KEYWORD_PATTERN = new RegExp(`\\b(${CONFIG.keywordPatterns.join("|")})\\b`, "i");
const MEMORY_NUDGE_MESSAGE = `[MEMORY TRIGGER DETECTED]
The user wants you to remember something. You MUST use the \`supermemory\` tool with \`mode: "add"\` to save this information.
Extract the key information the user wants remembered and save it as a concise, searchable memory.
- Use \`scope: "project"\` for project-specific preferences (e.g., "run lint with tests")
- Use \`scope: "user"\` for cross-project preferences (e.g., "prefers concise responses")
- Choose an appropriate \`type\`: "preference", "project-config", "learned-pattern", etc.
DO NOT skip this step. The user explicitly asked you to remember.`;
const UPDATE_COMMAND = "bunx opencode-supermemory@latest install";
function removeCodeBlocks(text: string): string {
return text.replace(CODE_BLOCK_PATTERN, "").replace(INLINE_CODE_PATTERN, "");
}
function detectMemoryKeyword(text: string): boolean {
const textWithoutCode = removeCodeBlocks(text);
return MEMORY_KEYWORD_PATTERN.test(textWithoutCode);
}
function combineContextParts(parts: Array<string | null | undefined>): string {
return parts.map((part) => part?.trim()).filter(Boolean).join("\n\n");
}
// Positively identify a permission request as the supermemory recall *search*
// (a read-only memory lookup). The allow-list is deliberately narrow: only the
// `supermemory` tool in `search` mode. Anything we can't positively match —
// including the tool's own `add`/`forget` writes — returns false and falls
// through to OpenCode's normal permission flow. We never use this to deny.
function isSupermemoryRecallSearch(input: Permission): boolean {
const type = String((input as { type?: unknown }).type ?? "");
const title = String((input as { title?: unknown }).title ?? "").toLowerCase();
const metadata =
((input as { metadata?: Record<string, unknown> }).metadata ?? {}) as Record<string, unknown>;
const toolName = String(metadata.tool ?? metadata.toolName ?? type);
const isSupermemory =
type === "supermemory" || toolName === "supermemory" || title.includes("supermemory");
if (!isSupermemory) return false;
// Tool args may live under a few keys depending on the permission shape.
const args = (metadata.args ?? metadata.input ?? metadata.arguments ?? metadata) as Record<
string,
unknown
>;
return String(args.mode ?? "") === "search";
}
export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => {
const { directory } = ctx;
const tags = getTags(directory);
const injectedSessions = new Set<string>();
log("Plugin init", { directory, tags, configured: isConfigured() });
if (!isConfigured()) {
log("Plugin disabled - SUPERMEMORY_API_KEY not set");
}
// Fetch model limits once at plugin init
const modelLimits = new Map<string, number>();
(async () => {
try {
const response = await ctx.client.provider.list();
if (response.data?.all) {
for (const provider of response.data.all) {
if (provider.models) {
for (const [modelId, model] of Object.entries(provider.models)) {
if (model.limit?.context) {
modelLimits.set(`${provider.id}/${modelId}`, model.limit.context);
}
}
}
}
}
log("Model limits loaded", { count: modelLimits.size });
} catch (error) {
log("Failed to fetch model limits", { error: String(error) });
}
})();
const getModelLimit = (providerID: string, modelID: string): number | undefined => {
return modelLimits.get(`${providerID}/${modelID}`);
};
const compactionHook = isConfigured() && ctx.client
? createCompactionHook(ctx as CompactionContext, tags, {
threshold: CONFIG.compactionThreshold,
getModelLimit,
})
: null;
return {
"chat.message": async (input, output) => {
if (!isConfigured()) return;
const start = Date.now();
try {
const textParts = output.parts.filter(
(p): p is Part & { type: "text"; text: string } => p.type === "text"
);
if (textParts.length === 0) {
log("chat.message: no text parts found");
return;
}
const userMessage = textParts.map((p) => p.text).join("\n");
if (!userMessage.trim()) {
log("chat.message: empty message, skipping");
return;
}
log("chat.message: processing", {
messagePreview: userMessage.slice(0, 100),
partsCount: output.parts.length,
textPartsCount: textParts.length,
});
if (detectMemoryKeyword(userMessage)) {
log("chat.message: memory keyword detected");
const nudgePart: Part = {
id: `prt_supermemory-nudge-${Date.now()}`,
sessionID: input.sessionID,
messageID: output.message.id,
type: "text",
text: MEMORY_NUDGE_MESSAGE,
synthetic: true,
};
output.parts.push(nudgePart);
}
// Reasoned per-turn recall: inject the directive on every turn so the
// model silently decides whether searching saved memory helps THIS
// message (and, if so, calls the `supermemory` tool in `search` mode —
// auto-approved by the permission.ask hook below). No network call here.
const recallPart: Part = {
id: `prt_supermemory-recall-${Date.now()}`,
sessionID: input.sessionID,
messageID: output.message.id,
type: "text",
text: buildRecallDirective(),
synthetic: true,
};
output.parts.push(recallPart);
const isFirstMessage = !injectedSessions.has(input.sessionID);
if (isFirstMessage) {
injectedSessions.add(input.sessionID);
let memoryContext = "";
const updateCheck = checkNpmUpdate(
"opencode-supermemory",
PLUGIN_VERSION,
UPDATE_COMMAND
).then((info) => (info ? formatUpdateNotice(info) : null));
if (CONFIG.autoRecallEveryPrompt) {
const [profileResult, userMemoriesResult, projectMemoriesListResult] = await Promise.all([
supermemoryClient.getProfile(tags.user, userMessage),
supermemoryClient.searchMemories(userMessage, tags.user),
supermemoryClient.listMemories(tags.project, CONFIG.maxProjectMemories),
]);
const profile = profileResult.success ? profileResult : null;
const userMemories = userMemoriesResult.success ? userMemoriesResult : { results: [] };
const projectMemoriesList = projectMemoriesListResult.success ? projectMemoriesListResult : { memories: [] };
const projectMemories = {
results: (projectMemoriesList.memories || []).map((m: any) => ({
id: m.id,
memory: m.summary || m.content || m.title || "",
similarity: 1,
title: m.title,
metadata: m.metadata,
})),
total: projectMemoriesList.memories?.length || 0,
timing: 0,
};
memoryContext = formatContextForPrompt(
profile,
userMemories,
projectMemories
);
} else {
const profileResult = await supermemoryClient.getProfile(tags.user);
const profile = profileResult.success ? profileResult : null;
memoryContext = formatContextForPrompt(profile, { results: [] }, { results: [] });
}
const updateNotice = await updateCheck;
const firstMessageContext = combineContextParts([memoryContext, updateNotice]);
if (firstMessageContext) {
const contextPart: Part = {
id: `prt_supermemory-context-${Date.now()}`,
sessionID: input.sessionID,
messageID: output.message.id,
type: "text",
text: firstMessageContext,
synthetic: true,
};
output.parts.unshift(contextPart);
const duration = Date.now() - start;
log("chat.message: context injected", {
duration,
contextLength: firstMessageContext.length,
});
}
}
} catch (error) {
log("chat.message: ERROR", { error: String(error) });
}
},
tool: {
supermemory: tool({
description:
"Manage and query the Supermemory persistent memory system. Use 'search' to find relevant memories, 'add' to store new knowledge, 'profile' to view user profile, 'list' to see recent memories, 'forget' to remove a memory.",
args: {
mode: tool.schema
.enum(["add", "search", "profile", "list", "forget", "help"])
.optional(),
content: tool.schema.string().optional(),
query: tool.schema.string().optional(),
type: tool.schema
.enum([
"project-config",
"architecture",
"error-solution",
"preference",
"learned-pattern",
"conversation",
])
.optional(),
scope: tool.schema.enum(["user", "project"]).optional(),
memoryId: tool.schema.string().optional(),
limit: tool.schema.number().optional(),
},
async execute(args: {
mode?: string;
content?: string;
query?: string;
type?: MemoryType;
scope?: MemoryScope;
memoryId?: string;
limit?: number;
}) {
if (!isConfigured()) {
return JSON.stringify({
success: false,
error:
"SUPERMEMORY_API_KEY not set. Set it in your environment to use Supermemory.",
});
}
const mode = args.mode || "help";
try {
switch (mode) {
case "help": {
return JSON.stringify({
success: true,
message: "Supermemory Usage Guide",
commands: [
{
command: "add",
description: "Store a new memory",
args: ["content", "type?", "scope?"],
},
{
command: "search",
description: "Search memories",
args: ["query", "scope?"],
},
{
command: "profile",
description: "View user profile",
args: ["query?"],
},
{
command: "list",
description: "List recent memories",
args: ["scope?", "limit?"],
},
{
command: "forget",
description: "Remove a memory",
args: ["memoryId", "scope?"],
},
],
scopes: {
user: "Cross-project preferences and knowledge",
project: "Project-specific knowledge (default)",
},
types: [
"project-config",
"architecture",
"error-solution",
"preference",
"learned-pattern",
"conversation",
],
});
}
case "add": {
if (!args.content) {
return JSON.stringify({
success: false,
error: "content parameter is required for add mode",
});
}
const sanitizedContent = stripPrivateContent(args.content);
if (isFullyPrivate(args.content)) {
return JSON.stringify({
success: false,
error: "Cannot store fully private content",
});
}
const scope = args.scope || "project";
const containerTag =
scope === "user" ? tags.user : tags.project;
const result = await supermemoryClient.addMemory(
sanitizedContent,
containerTag,
{ type: args.type }
);
if (!result.success) {
return JSON.stringify({
success: false,
error: result.error || "Failed to add memory",
});
}
return JSON.stringify({
success: true,
message: `Memory added to ${scope} scope`,
id: result.id,
scope,
type: args.type,
});
}
case "search": {
if (!args.query) {
return JSON.stringify({
success: false,
error: "query parameter is required for search mode",
});
}
const scope = args.scope;
if (scope === "user") {
const result = await supermemoryClient.searchMemories(
args.query,
tags.user
);
if (!result.success) {
return JSON.stringify({
success: false,
error: result.error || "Failed to search memories",
});
}
return formatSearchResults(args.query, scope, result, args.limit);
}
if (scope === "project") {
const result = await supermemoryClient.searchMemories(
args.query,
tags.project
);
if (!result.success) {
return JSON.stringify({
success: false,
error: result.error || "Failed to search memories",
});
}
return formatSearchResults(args.query, scope, result, args.limit);
}
const [userResult, projectResult] = await Promise.all([
supermemoryClient.searchMemories(args.query, tags.user),
supermemoryClient.searchMemories(args.query, tags.project),
]);
if (!userResult.success || !projectResult.success) {
return JSON.stringify({
success: false,
error: userResult.error || projectResult.error || "Failed to search memories",
});
}
const combined = [
...(userResult.results || []).map((r) => ({
...r,
scope: "user" as const,
})),
...(projectResult.results || []).map((r) => ({
...r,
scope: "project" as const,
})),
].sort((a, b) => (b.similarity ?? 0) - (a.similarity ?? 0));
return JSON.stringify({
success: true,
query: args.query,
count: combined.length,
results: combined.slice(0, args.limit || 10).map((r) => ({
id: r.id,
content: r.memory || r.chunk,
similarity: Math.round((r.similarity ?? 0) * 100),
scope: r.scope,
})),
});
}
case "profile": {
const result = await supermemoryClient.getProfile(
tags.user,
args.query
);
if (!result.success) {
return JSON.stringify({
success: false,
error: result.error || "Failed to fetch profile",
});
}
return JSON.stringify({
success: true,
profile: {
static: result.profile?.static || [],
dynamic: result.profile?.dynamic || [],
},
});
}
case "list": {
const scope = args.scope || "project";
const limit = args.limit || 20;
const containerTag =
scope === "user" ? tags.user : tags.project;
const result = await supermemoryClient.listMemories(
containerTag,
limit
);
if (!result.success) {
return JSON.stringify({
success: false,
error: result.error || "Failed to list memories",
});
}
const memories = result.memories || [];
return JSON.stringify({
success: true,
scope,
count: memories.length,
memories: memories.map((m) => ({
id: m.id,
content: m.summary,
createdAt: m.createdAt,
metadata: m.metadata,
})),
});
}
case "forget": {
if (!args.memoryId) {
return JSON.stringify({
success: false,
error: "memoryId parameter is required for forget mode",
});
}
const scope = args.scope || "project";
const result = await supermemoryClient.deleteMemory(
args.memoryId
);
if (!result.success) {
return JSON.stringify({
success: false,
error: result.error || "Failed to delete memory",
});
}
return JSON.stringify({
success: true,
message: `Memory ${args.memoryId} removed from ${scope} scope`,
});
}
default:
return JSON.stringify({
success: false,
error: `Unknown mode: ${mode}`,
});
}
} catch (error) {
return JSON.stringify({
success: false,
error: error instanceof Error ? error.message : String(error),
});
}
},
}),
},
"permission.ask": async (input, output) => {
// Auto-approve the reasoned recall search so it feels as silent as the
// save path. OpenCode usually doesn't prompt for plugin tools, so this is
// narrow defense-in-depth for users with strict `permission` config.
// We only ever set "allow" (never "deny") and only for the read-only
// supermemory search; everything else is left untouched.
if (!isConfigured()) return;
try {
if (isSupermemoryRecallSearch(input)) {
output.status = "allow";
log("permission.ask: auto-allowing supermemory recall search");
}
} catch (error) {
// Fail open — never block a tool call because our approve hook errored.
log("permission.ask: ERROR", { error: String(error) });
}
},
event: async (input: { event: { type: string; properties?: unknown } }) => {
if (compactionHook) {
await compactionHook.event(input);
}
},
};
};
function formatSearchResults(
query: string,
scope: string | undefined,
results: { results?: Array<{ id: string; memory?: string; chunk?: string; similarity?: number }> },
limit?: number
): string {
const memoryResults = results.results || [];
return JSON.stringify({
success: true,
query,
scope,
count: memoryResults.length,
results: memoryResults.slice(0, limit || 10).map((r) => ({
id: r.id,
content: r.memory || r.chunk,
similarity: Math.round((r.similarity ?? 0) * 100),
})),
});
}