opencode-supermemory 0.1.8 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -199,28 +199,34 @@ Create `~/.config/opencode/supermemory.jsonc`:
199
199
  {
200
200
  // API key (can also use SUPERMEMORY_API_KEY env var)
201
201
  "apiKey": "sm_...",
202
-
202
+
203
203
  // Min similarity for memory retrieval (0-1)
204
204
  "similarityThreshold": 0.6,
205
-
205
+
206
206
  // Max memories injected per request
207
207
  "maxMemories": 5,
208
-
208
+
209
209
  // Max project memories listed
210
210
  "maxProjectMemories": 10,
211
-
211
+
212
212
  // Max profile facts injected
213
213
  "maxProfileItems": 5,
214
-
214
+
215
215
  // Include user profile in context
216
216
  "injectProfile": true,
217
-
218
- // Prefix for container tags
217
+
218
+ // Prefix for container tags (used when userContainerTag/projectContainerTag not set)
219
219
  "containerTagPrefix": "opencode",
220
-
220
+
221
+ // Optional: Set exact user container tag (overrides auto-generated tag)
222
+ "userContainerTag": "my-custom-user-tag",
223
+
224
+ // Optional: Set exact project container tag (overrides auto-generated tag)
225
+ "projectContainerTag": "my-project-tag",
226
+
221
227
  // Extra keyword patterns for memory detection (regex)
222
228
  "keywordPatterns": ["log\\s+this", "write\\s+down"],
223
-
229
+
224
230
  // Context usage ratio that triggers compaction (0-1)
225
231
  "compactionThreshold": 0.80
226
232
  }
@@ -228,6 +234,30 @@ Create `~/.config/opencode/supermemory.jsonc`:
228
234
 
229
235
  All fields optional. Env var `SUPERMEMORY_API_KEY` takes precedence over config file.
230
236
 
237
+ ### Container Tag Selection
238
+
239
+ By default, container tags are auto-generated using `containerTagPrefix` plus a hash:
240
+ - User tag: `{prefix}_user_{hash(git_email)}`
241
+ - Project tag: `{prefix}_project_{hash(directory)}`
242
+
243
+ You can override this by specifying exact container tags:
244
+
245
+ ```jsonc
246
+ {
247
+ // Use a specific container tag for user memories
248
+ "userContainerTag": "my-team-workspace",
249
+
250
+ // Use a specific container tag for project memories
251
+ "projectContainerTag": "my-awesome-project"
252
+ }
253
+ ```
254
+
255
+ This is useful when you want to:
256
+ - Share memories across team members (same `userContainerTag`)
257
+ - Sync memories between different machines for the same project
258
+ - Organize memories using your own naming scheme
259
+ - Integrate with existing Supermemory container tags from other tools
260
+
231
261
  ## Usage with Oh My OpenCode
232
262
 
233
263
  If you're using [Oh My OpenCode](https://github.com/code-yeongyu/oh-my-opencode), disable its built-in auto-compact hook to let supermemory handle context compaction:
package/dist/cli.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli.ts
4
- import { mkdirSync, writeFileSync, readFileSync, existsSync } from "node:fs";
5
- import { join } from "node:path";
6
- import { homedir } from "node:os";
4
+ import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2, readFileSync as readFileSync2, existsSync as existsSync2 } from "node:fs";
5
+ import { join as join2 } from "node:path";
6
+ import { homedir as homedir2 } from "node:os";
7
7
  import * as readline from "node:readline";
8
8
 
9
9
  // src/services/jsonc.ts
@@ -77,10 +77,132 @@ function stripJsoncComments(content) {
77
77
  return result.replace(/,\s*([}\]])/g, "$1");
78
78
  }
79
79
 
80
+ // src/services/auth.ts
81
+ import { createServer } from "node:http";
82
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
83
+ import { exec } from "node:child_process";
84
+ import { join } from "node:path";
85
+ import { homedir } from "node:os";
86
+ var CREDENTIALS_DIR = join(homedir(), ".supermemory-opencode");
87
+ var CREDENTIALS_FILE = join(CREDENTIALS_DIR, "credentials.json");
88
+ var AUTH_PORT = 19877;
89
+ var AUTH_BASE_URL = "https://console.supermemory.ai/auth/connect";
90
+ var CLIENT_NAME = "opencode";
91
+ function loadCredentials() {
92
+ if (!existsSync(CREDENTIALS_FILE))
93
+ return null;
94
+ try {
95
+ const content = readFileSync(CREDENTIALS_FILE, "utf-8");
96
+ return JSON.parse(content);
97
+ } catch {
98
+ return null;
99
+ }
100
+ }
101
+ function saveCredentials(apiKey) {
102
+ mkdirSync(CREDENTIALS_DIR, { recursive: true, mode: 448 });
103
+ const credentials = {
104
+ apiKey,
105
+ createdAt: new Date().toISOString()
106
+ };
107
+ writeFileSync(CREDENTIALS_FILE, JSON.stringify(credentials, null, 2), { mode: 384 });
108
+ }
109
+ function clearCredentials() {
110
+ if (!existsSync(CREDENTIALS_FILE))
111
+ return false;
112
+ rmSync(CREDENTIALS_FILE);
113
+ return true;
114
+ }
115
+ function openBrowser(url) {
116
+ const platform = process.platform;
117
+ const commands = {
118
+ darwin: `open "${url}"`,
119
+ win32: `start "" "${url}"`,
120
+ linux: `xdg-open "${url}"`
121
+ };
122
+ const cmd = commands[platform] ?? `xdg-open "${url}"`;
123
+ exec(cmd, (err) => {
124
+ if (err)
125
+ console.error("Failed to open browser:", err.message);
126
+ });
127
+ }
128
+ function startAuthFlow(timeoutMs = 120000) {
129
+ return new Promise((resolve) => {
130
+ let resolved = false;
131
+ const server = createServer((req, res) => {
132
+ if (resolved)
133
+ return;
134
+ const url = new URL(req.url || "/", `http://localhost:${AUTH_PORT}`);
135
+ if (url.pathname === "/callback") {
136
+ const apiKey = url.searchParams.get("apikey");
137
+ if (apiKey) {
138
+ saveCredentials(apiKey);
139
+ res.writeHead(200, { "Content-Type": "text/html" });
140
+ res.end(`
141
+ <!DOCTYPE html>
142
+ <html>
143
+ <head><title>Success</title></head>
144
+ <body style="font-family: system-ui; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; background: #0a0a0a; color: #fafafa;">
145
+ <div style="text-align: center;">
146
+ <h1 style="color: #22c55e;">✓ Connected!</h1>
147
+ <p>You can close this window and return to your terminal.</p>
148
+ </div>
149
+ </body>
150
+ </html>
151
+ `);
152
+ resolved = true;
153
+ server.close();
154
+ resolve({ success: true, apiKey });
155
+ } else {
156
+ res.writeHead(400, { "Content-Type": "text/html" });
157
+ res.end(`
158
+ <!DOCTYPE html>
159
+ <html>
160
+ <head><title>Error</title></head>
161
+ <body style="font-family: system-ui; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; background: #0a0a0a; color: #fafafa;">
162
+ <div style="text-align: center;">
163
+ <h1 style="color: #ef4444;">✗ Connection Failed</h1>
164
+ <p>No API key received. Please try again.</p>
165
+ </div>
166
+ </body>
167
+ </html>
168
+ `);
169
+ resolved = true;
170
+ server.close();
171
+ resolve({ success: false, error: "No API key received" });
172
+ }
173
+ } else {
174
+ res.writeHead(404);
175
+ res.end("Not Found");
176
+ }
177
+ });
178
+ server.on("error", (err) => {
179
+ if (err.code === "EADDRINUSE") {
180
+ resolve({ success: false, error: `Port ${AUTH_PORT} is already in use` });
181
+ } else {
182
+ resolve({ success: false, error: err.message });
183
+ }
184
+ });
185
+ server.listen(AUTH_PORT, () => {
186
+ const callbackUrl = `http://localhost:${AUTH_PORT}/callback`;
187
+ const authUrl = `${AUTH_BASE_URL}?callback=${encodeURIComponent(callbackUrl)}&client=${CLIENT_NAME}`;
188
+ console.log("Opening browser for authentication...");
189
+ console.log(`If it doesn't open, visit: ${authUrl}`);
190
+ openBrowser(authUrl);
191
+ });
192
+ setTimeout(() => {
193
+ if (!resolved) {
194
+ resolved = true;
195
+ server.close();
196
+ resolve({ success: false, error: "Authentication timed out" });
197
+ }
198
+ }, timeoutMs);
199
+ });
200
+ }
201
+
80
202
  // src/cli.ts
81
- var OPENCODE_CONFIG_DIR = join(homedir(), ".config", "opencode");
82
- var OPENCODE_COMMAND_DIR = join(OPENCODE_CONFIG_DIR, "command");
83
- var OH_MY_OPENCODE_CONFIG = join(OPENCODE_CONFIG_DIR, "oh-my-opencode.json");
203
+ var OPENCODE_CONFIG_DIR = join2(homedir2(), ".config", "opencode");
204
+ var OPENCODE_COMMAND_DIR = join2(OPENCODE_CONFIG_DIR, "command");
205
+ var OH_MY_OPENCODE_CONFIG = join2(OPENCODE_CONFIG_DIR, "oh-my-opencode.json");
84
206
  var PLUGIN_NAME = "opencode-supermemory@latest";
85
207
  var SUPERMEMORY_INIT_COMMAND = `---
86
208
  description: Initialize Supermemory with comprehensive codebase knowledge
@@ -233,6 +355,30 @@ Then ask: "I've initialized memory with X insights. Want me to continue refining
233
355
  5. Reflect and verify completeness
234
356
  6. Summarize what was learned and ask if user wants refinement
235
357
  `;
358
+ var SUPERMEMORY_LOGIN_COMMAND = `---
359
+ description: Authenticate with Supermemory via browser
360
+ ---
361
+
362
+ # Supermemory Login
363
+
364
+ Run this command to authenticate the user with Supermemory:
365
+
366
+ \`\`\`bash
367
+ bunx opencode-supermemory@latest login
368
+ \`\`\`
369
+
370
+ This will:
371
+ 1. Start a local server on port 19877
372
+ 2. Open the browser to Supermemory's authentication page
373
+ 3. After the user logs in, save credentials to ~/.supermemory-opencode/credentials.json
374
+
375
+ Wait for the command to complete, then inform the user whether authentication succeeded or failed.
376
+
377
+ If the user wants to log out instead, run:
378
+ \`\`\`bash
379
+ bunx opencode-supermemory@latest logout
380
+ \`\`\`
381
+ `;
236
382
  function createReadline() {
237
383
  return readline.createInterface({
238
384
  input: process.stdin,
@@ -248,11 +394,11 @@ async function confirm(rl, question) {
248
394
  }
249
395
  function findOpencodeConfig() {
250
396
  const candidates = [
251
- join(OPENCODE_CONFIG_DIR, "opencode.jsonc"),
252
- join(OPENCODE_CONFIG_DIR, "opencode.json")
397
+ join2(OPENCODE_CONFIG_DIR, "opencode.jsonc"),
398
+ join2(OPENCODE_CONFIG_DIR, "opencode.json")
253
399
  ];
254
400
  for (const path of candidates) {
255
- if (existsSync(path)) {
401
+ if (existsSync2(path)) {
256
402
  return path;
257
403
  }
258
404
  }
@@ -260,7 +406,7 @@ function findOpencodeConfig() {
260
406
  }
261
407
  function addPluginToConfig(configPath) {
262
408
  try {
263
- const content = readFileSync(configPath, "utf-8");
409
+ const content = readFileSync2(configPath, "utf-8");
264
410
  if (content.includes("opencode-supermemory")) {
265
411
  console.log("✓ Plugin already registered in config");
266
412
  return true;
@@ -289,14 +435,14 @@ function addPluginToConfig(configPath) {
289
435
  "${PLUGIN_NAME}"
290
436
  ${end}`;
291
437
  });
292
- writeFileSync(configPath, newContent);
438
+ writeFileSync2(configPath, newContent);
293
439
  } else {
294
440
  const newContent = content.replace(/^(\s*\{)/, `$1
295
441
  "plugin": ["${PLUGIN_NAME}"],`);
296
- writeFileSync(configPath, newContent);
442
+ writeFileSync2(configPath, newContent);
297
443
  }
298
444
  } else {
299
- writeFileSync(configPath, JSON.stringify(config, null, 2));
445
+ writeFileSync2(configPath, JSON.stringify(config, null, 2));
300
446
  }
301
447
  console.log(`✓ Added plugin to ${configPath}`);
302
448
  return true;
@@ -306,21 +452,24 @@ function addPluginToConfig(configPath) {
306
452
  }
307
453
  }
308
454
  function createNewConfig() {
309
- const configPath = join(OPENCODE_CONFIG_DIR, "opencode.jsonc");
310
- mkdirSync(OPENCODE_CONFIG_DIR, { recursive: true });
455
+ const configPath = join2(OPENCODE_CONFIG_DIR, "opencode.jsonc");
456
+ mkdirSync2(OPENCODE_CONFIG_DIR, { recursive: true });
311
457
  const config = `{
312
458
  "plugin": ["${PLUGIN_NAME}"]
313
459
  }
314
460
  `;
315
- writeFileSync(configPath, config);
461
+ writeFileSync2(configPath, config);
316
462
  console.log(`✓ Created ${configPath}`);
317
463
  return true;
318
464
  }
319
- function createCommand() {
320
- mkdirSync(OPENCODE_COMMAND_DIR, { recursive: true });
321
- const commandPath = join(OPENCODE_COMMAND_DIR, "supermemory-init.md");
322
- writeFileSync(commandPath, SUPERMEMORY_INIT_COMMAND);
465
+ function createCommands() {
466
+ mkdirSync2(OPENCODE_COMMAND_DIR, { recursive: true });
467
+ const initPath = join2(OPENCODE_COMMAND_DIR, "supermemory-init.md");
468
+ writeFileSync2(initPath, SUPERMEMORY_INIT_COMMAND);
323
469
  console.log(`✓ Created /supermemory-init command`);
470
+ const loginPath = join2(OPENCODE_COMMAND_DIR, "supermemory-login.md");
471
+ writeFileSync2(loginPath, SUPERMEMORY_LOGIN_COMMAND);
472
+ console.log(`✓ Created /supermemory-login command`);
324
473
  return true;
325
474
  }
326
475
  function isOhMyOpencodeInstalled() {
@@ -328,17 +477,17 @@ function isOhMyOpencodeInstalled() {
328
477
  if (!configPath)
329
478
  return false;
330
479
  try {
331
- const content = readFileSync(configPath, "utf-8");
480
+ const content = readFileSync2(configPath, "utf-8");
332
481
  return content.includes("oh-my-opencode");
333
482
  } catch {
334
483
  return false;
335
484
  }
336
485
  }
337
486
  function isAutoCompactAlreadyDisabled() {
338
- if (!existsSync(OH_MY_OPENCODE_CONFIG))
487
+ if (!existsSync2(OH_MY_OPENCODE_CONFIG))
339
488
  return false;
340
489
  try {
341
- const content = readFileSync(OH_MY_OPENCODE_CONFIG, "utf-8");
490
+ const content = readFileSync2(OH_MY_OPENCODE_CONFIG, "utf-8");
342
491
  const config = JSON.parse(content);
343
492
  const disabledHooks = config.disabled_hooks;
344
493
  return disabledHooks?.includes("anthropic-context-window-limit-recovery") ?? false;
@@ -349,8 +498,8 @@ function isAutoCompactAlreadyDisabled() {
349
498
  function disableAutoCompactHook() {
350
499
  try {
351
500
  let config = {};
352
- if (existsSync(OH_MY_OPENCODE_CONFIG)) {
353
- const content = readFileSync(OH_MY_OPENCODE_CONFIG, "utf-8");
501
+ if (existsSync2(OH_MY_OPENCODE_CONFIG)) {
502
+ const content = readFileSync2(OH_MY_OPENCODE_CONFIG, "utf-8");
354
503
  config = JSON.parse(content);
355
504
  }
356
505
  const disabledHooks = config.disabled_hooks || [];
@@ -358,7 +507,7 @@ function disableAutoCompactHook() {
358
507
  disabledHooks.push("anthropic-context-window-limit-recovery");
359
508
  }
360
509
  config.disabled_hooks = disabledHooks;
361
- writeFileSync(OH_MY_OPENCODE_CONFIG, JSON.stringify(config, null, 2));
510
+ writeFileSync2(OH_MY_OPENCODE_CONFIG, JSON.stringify(config, null, 2));
362
511
  console.log(`✓ Disabled anthropic-context-window-limit-recovery hook in oh-my-opencode.json`);
363
512
  return true;
364
513
  } catch (err) {
@@ -397,16 +546,16 @@ async function install(options) {
397
546
  }
398
547
  }
399
548
  console.log(`
400
- Step 2: Create /supermemory-init command`);
549
+ Step 2: Create /supermemory-init and /supermemory-login commands`);
401
550
  if (options.tui) {
402
- const shouldCreate = await confirm(rl, "Add /supermemory-init command?");
551
+ const shouldCreate = await confirm(rl, "Add supermemory commands?");
403
552
  if (!shouldCreate) {
404
553
  console.log("Skipped.");
405
554
  } else {
406
- createCommand();
555
+ createCommands();
407
556
  }
408
557
  } else {
409
- createCommand();
558
+ createCommands();
410
559
  }
411
560
  if (isOhMyOpencodeInstalled()) {
412
561
  console.log(`
@@ -430,42 +579,71 @@ Step 3: Configure Oh My OpenCode`);
430
579
  }
431
580
  }
432
581
  }
582
+ if (rl)
583
+ rl.close();
433
584
  console.log(`
434
585
  ` + "─".repeat(50));
435
586
  console.log(`
436
- \uD83D\uDD11 Final step: Set your API key
587
+ \uD83D\uDD11 Final step: Authenticate with Supermemory
437
588
  `);
438
- console.log("Get your API key from: https://console.supermemory.ai");
589
+ if (options.tui) {
590
+ return login();
591
+ }
592
+ console.log("Run this command to authenticate:");
593
+ console.log(" bunx opencode-supermemory@latest login");
439
594
  console.log(`
440
- Then add to your shell profile:
441
- `);
595
+ Or set your API key manually:`);
442
596
  console.log(' export SUPERMEMORY_API_KEY="sm_..."');
443
597
  console.log(`
444
- Or create ~/.config/opencode/supermemory.jsonc:
445
- `);
446
- console.log(' { "apiKey": "sm_..." }');
447
- console.log(`
448
598
  ` + "─".repeat(50));
449
599
  console.log(`
450
600
  ✓ Setup complete! Restart OpenCode to activate.
451
601
  `);
452
- if (rl)
453
- rl.close();
454
602
  return 0;
455
603
  }
604
+ async function login() {
605
+ const existing = loadCredentials();
606
+ if (existing) {
607
+ console.log("Already authenticated. Use 'logout' first to re-authenticate.");
608
+ return 0;
609
+ }
610
+ const result = await startAuthFlow();
611
+ if (result.success) {
612
+ console.log(`
613
+ ✓ Successfully authenticated with Supermemory!`);
614
+ console.log(`Restart OpenCode to activate.
615
+ `);
616
+ return 0;
617
+ } else {
618
+ console.error(`
619
+ ✗ Authentication failed: ${result.error}`);
620
+ return 1;
621
+ }
622
+ }
623
+ function logout() {
624
+ if (clearCredentials()) {
625
+ console.log("✓ Logged out. Credentials cleared.");
626
+ return 0;
627
+ } else {
628
+ console.log("No credentials found.");
629
+ return 0;
630
+ }
631
+ }
456
632
  function printHelp() {
457
633
  console.log(`
458
634
  opencode-supermemory - Persistent memory for OpenCode agents
459
635
 
460
636
  Commands:
461
- install Install and configure the plugin
462
- --no-tui Run in non-interactive mode (for LLM agents)
463
- --disable-context-recovery Disable Oh My OpenCode's context-window-limit-recovery hook (use with --no-tui)
637
+ install Install and configure the plugin
638
+ --no-tui Non-interactive mode (for LLM agents)
639
+ --disable-context-recovery Disable Oh My OpenCode's context hook
640
+ login Authenticate with Supermemory (opens browser)
641
+ logout Clear stored credentials
464
642
 
465
643
  Examples:
466
644
  bunx opencode-supermemory@latest install
467
- bunx opencode-supermemory@latest install --no-tui
468
- bunx opencode-supermemory@latest install --no-tui --disable-context-recovery
645
+ bunx opencode-supermemory@latest login
646
+ bunx opencode-supermemory@latest logout
469
647
  `);
470
648
  }
471
649
  var args = process.argv.slice(2);
@@ -483,6 +661,10 @@ if (args[0] === "install") {
483
661
  const noTui = args.includes("--no-tui");
484
662
  const disableAutoCompact = args.includes("--disable-context-recovery");
485
663
  install({ tui: !noTui, disableAutoCompact }).then((code) => process.exit(code));
664
+ } else if (args[0] === "login") {
665
+ login().then((code) => process.exit(code));
666
+ } else if (args[0] === "logout") {
667
+ process.exit(logout());
486
668
  } else {
487
669
  console.error(`Unknown command: ${args[0]}`);
488
670
  printHelp();
package/dist/config.d.ts CHANGED
@@ -6,6 +6,8 @@ export declare const CONFIG: {
6
6
  maxProfileItems: number;
7
7
  injectProfile: boolean;
8
8
  containerTagPrefix: string;
9
+ userContainerTag: string | undefined;
10
+ projectContainerTag: string | undefined;
9
11
  filterPrompt: string;
10
12
  keywordPatterns: string[];
11
13
  compactionThreshold: number;
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAyFA,eAAO,MAAM,mBAAmB,oBAAuD,CAAC;AAExF,eAAO,MAAM,MAAM;;;;;;;;;;CAalB,CAAC;AAEF,wBAAgB,YAAY,IAAI,OAAO,CAEtC"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAmGA,eAAO,MAAM,mBAAmB,oBAAc,CAAC;AAE/C,eAAO,MAAM,MAAM;;;;;;;;;;;;CAelB,CAAC;AAEF,wBAAgB,YAAY,IAAI,OAAO,CAEtC"}
package/dist/index.js CHANGED
@@ -13602,9 +13602,9 @@ Supermemory.Search = Search;
13602
13602
  Supermemory.Settings = Settings;
13603
13603
  Supermemory.Connections = Connections;
13604
13604
  // src/config.ts
13605
- import { existsSync, readFileSync } from "node:fs";
13606
- import { join } from "node:path";
13607
- import { homedir } from "node:os";
13605
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
13606
+ import { join as join2 } from "node:path";
13607
+ import { homedir as homedir2 } from "node:os";
13608
13608
 
13609
13609
  // src/services/jsonc.ts
13610
13610
  function stripJsoncComments(content) {
@@ -13677,11 +13677,28 @@ function stripJsoncComments(content) {
13677
13677
  return result.replace(/,\s*([}\]])/g, "$1");
13678
13678
  }
13679
13679
 
13680
+ // src/services/auth.ts
13681
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
13682
+ import { join } from "node:path";
13683
+ import { homedir } from "node:os";
13684
+ var CREDENTIALS_DIR = join(homedir(), ".supermemory-opencode");
13685
+ var CREDENTIALS_FILE = join(CREDENTIALS_DIR, "credentials.json");
13686
+ function loadCredentials() {
13687
+ if (!existsSync(CREDENTIALS_FILE))
13688
+ return null;
13689
+ try {
13690
+ const content = readFileSync(CREDENTIALS_FILE, "utf-8");
13691
+ return JSON.parse(content);
13692
+ } catch {
13693
+ return null;
13694
+ }
13695
+ }
13696
+
13680
13697
  // src/config.ts
13681
- var CONFIG_DIR = join(homedir(), ".config", "opencode");
13698
+ var CONFIG_DIR = join2(homedir2(), ".config", "opencode");
13682
13699
  var CONFIG_FILES = [
13683
- join(CONFIG_DIR, "supermemory.jsonc"),
13684
- join(CONFIG_DIR, "supermemory.json")
13700
+ join2(CONFIG_DIR, "supermemory.jsonc"),
13701
+ join2(CONFIG_DIR, "supermemory.json")
13685
13702
  ];
13686
13703
  var DEFAULT_KEYWORD_PATTERNS = [
13687
13704
  "remember",
@@ -13730,9 +13747,9 @@ function validateCompactionThreshold(value) {
13730
13747
  }
13731
13748
  function loadConfig() {
13732
13749
  for (const path2 of CONFIG_FILES) {
13733
- if (existsSync(path2)) {
13750
+ if (existsSync2(path2)) {
13734
13751
  try {
13735
- const content = readFileSync(path2, "utf-8");
13752
+ const content = readFileSync2(path2, "utf-8");
13736
13753
  const json2 = stripJsoncComments(content);
13737
13754
  return JSON.parse(json2);
13738
13755
  } catch {}
@@ -13741,7 +13758,14 @@ function loadConfig() {
13741
13758
  return {};
13742
13759
  }
13743
13760
  var fileConfig = loadConfig();
13744
- var SUPERMEMORY_API_KEY = fileConfig.apiKey ?? process.env.SUPERMEMORY_API_KEY;
13761
+ function getApiKey() {
13762
+ if (process.env.SUPERMEMORY_API_KEY)
13763
+ return process.env.SUPERMEMORY_API_KEY;
13764
+ if (fileConfig.apiKey)
13765
+ return fileConfig.apiKey;
13766
+ return loadCredentials()?.apiKey;
13767
+ }
13768
+ var SUPERMEMORY_API_KEY = getApiKey();
13745
13769
  var CONFIG = {
13746
13770
  similarityThreshold: fileConfig.similarityThreshold ?? DEFAULTS.similarityThreshold,
13747
13771
  maxMemories: fileConfig.maxMemories ?? DEFAULTS.maxMemories,
@@ -13749,6 +13773,8 @@ var CONFIG = {
13749
13773
  maxProfileItems: fileConfig.maxProfileItems ?? DEFAULTS.maxProfileItems,
13750
13774
  injectProfile: fileConfig.injectProfile ?? DEFAULTS.injectProfile,
13751
13775
  containerTagPrefix: fileConfig.containerTagPrefix ?? DEFAULTS.containerTagPrefix,
13776
+ userContainerTag: fileConfig.userContainerTag,
13777
+ projectContainerTag: fileConfig.projectContainerTag,
13752
13778
  filterPrompt: fileConfig.filterPrompt ?? DEFAULTS.filterPrompt,
13753
13779
  keywordPatterns: [
13754
13780
  ...DEFAULT_KEYWORD_PATTERNS,
@@ -13761,11 +13787,11 @@ function isConfigured() {
13761
13787
  }
13762
13788
 
13763
13789
  // src/services/logger.ts
13764
- import { appendFileSync, writeFileSync } from "fs";
13765
- import { homedir as homedir2 } from "os";
13766
- import { join as join2 } from "path";
13767
- var LOG_FILE = join2(homedir2(), ".opencode-supermemory.log");
13768
- writeFileSync(LOG_FILE, `
13790
+ import { appendFileSync, writeFileSync as writeFileSync2 } from "fs";
13791
+ import { homedir as homedir3 } from "os";
13792
+ import { join as join3 } from "path";
13793
+ var LOG_FILE = join3(homedir3(), ".opencode-supermemory.log");
13794
+ writeFileSync2(LOG_FILE, `
13769
13795
  --- Session started: ${new Date().toISOString()} ---
13770
13796
  `, { flag: "a" });
13771
13797
  function log(message, data) {
@@ -13777,8 +13803,8 @@ function log(message, data) {
13777
13803
  }
13778
13804
 
13779
13805
  // src/services/client.ts
13780
- var SUPERMEMORY_API_URL = "https://api.supermemory.ai";
13781
13806
  var TIMEOUT_MS = 30000;
13807
+ var MAX_CONVERSATION_CHARS = 1e5;
13782
13808
  function withTimeout(promise2, ms) {
13783
13809
  return Promise.race([
13784
13810
  promise2,
@@ -13788,6 +13814,19 @@ function withTimeout(promise2, ms) {
13788
13814
 
13789
13815
  class SupermemoryClient {
13790
13816
  client = null;
13817
+ formatConversationMessage(message) {
13818
+ const content = typeof message.content === "string" ? message.content : message.content.map((part) => part.type === "text" ? part.text : `[image] ${part.imageUrl.url}`).join(`
13819
+ `);
13820
+ const trimmed = content.trim();
13821
+ if (trimmed.length === 0) {
13822
+ return `[${message.role}]`;
13823
+ }
13824
+ return `[${message.role}] ${trimmed}`;
13825
+ }
13826
+ formatConversationTranscript(messages) {
13827
+ return messages.map((message, idx) => `${idx + 1}. ${this.formatConversationMessage(message)}`).join(`
13828
+ `);
13829
+ }
13791
13830
  getClient() {
13792
13831
  if (!this.client) {
13793
13832
  if (!isConfigured()) {
@@ -13880,34 +13919,64 @@ class SupermemoryClient {
13880
13919
  }
13881
13920
  }
13882
13921
  async ingestConversation(conversationId, messages, containerTags, metadata) {
13883
- log("ingestConversation: start", { conversationId, messageCount: messages.length });
13884
- try {
13885
- const response = await withTimeout(fetch(`${SUPERMEMORY_API_URL}/conversations`, {
13886
- method: "POST",
13887
- headers: {
13888
- "Content-Type": "application/json",
13889
- Authorization: `Bearer ${SUPERMEMORY_API_KEY}`
13890
- },
13891
- body: JSON.stringify({
13892
- conversationId,
13893
- messages,
13894
- containerTags,
13895
- metadata
13896
- })
13897
- }), TIMEOUT_MS);
13898
- if (!response.ok) {
13899
- const errorText = await response.text();
13900
- log("ingestConversation: error response", { status: response.status, error: errorText });
13901
- return { success: false, error: `HTTP ${response.status}: ${errorText}` };
13922
+ log("ingestConversation: start", {
13923
+ conversationId,
13924
+ messageCount: messages.length,
13925
+ containerTags
13926
+ });
13927
+ if (messages.length === 0) {
13928
+ return { success: false, error: "No messages to ingest" };
13929
+ }
13930
+ const uniqueTags = [...new Set(containerTags)].filter((tag) => tag.length > 0);
13931
+ if (uniqueTags.length === 0) {
13932
+ return { success: false, error: "At least one containerTag is required" };
13933
+ }
13934
+ const transcript = this.formatConversationTranscript(messages);
13935
+ const rawContent = `[Conversation ${conversationId}]
13936
+ ${transcript}`;
13937
+ const content = rawContent.length > MAX_CONVERSATION_CHARS ? `${rawContent.slice(0, MAX_CONVERSATION_CHARS)}
13938
+ ...[truncated]` : rawContent;
13939
+ const ingestMetadata = {
13940
+ type: "conversation",
13941
+ conversationId,
13942
+ messageCount: messages.length,
13943
+ originalContainerTags: uniqueTags,
13944
+ ...metadata
13945
+ };
13946
+ const savedIds = [];
13947
+ let firstError = null;
13948
+ for (const tag of uniqueTags) {
13949
+ const result = await this.addMemory(content, tag, ingestMetadata);
13950
+ if (result.success) {
13951
+ savedIds.push(result.id);
13952
+ } else if (!firstError) {
13953
+ firstError = result.error || "Failed to store conversation";
13902
13954
  }
13903
- const result = await response.json();
13904
- log("ingestConversation: success", { conversationId, status: result.status });
13905
- return { success: true, ...result };
13906
- } catch (error45) {
13907
- const errorMessage = error45 instanceof Error ? error45.message : String(error45);
13908
- log("ingestConversation: error", { error: errorMessage });
13909
- return { success: false, error: errorMessage };
13910
13955
  }
13956
+ if (savedIds.length === 0) {
13957
+ log("ingestConversation: error", { conversationId, error: firstError });
13958
+ return {
13959
+ success: false,
13960
+ error: firstError || "Failed to ingest conversation"
13961
+ };
13962
+ }
13963
+ const status = savedIds.length === uniqueTags.length ? "stored" : "partial";
13964
+ const response = {
13965
+ id: savedIds[0],
13966
+ conversationId,
13967
+ status
13968
+ };
13969
+ log("ingestConversation: success", {
13970
+ conversationId,
13971
+ status,
13972
+ storedCount: savedIds.length,
13973
+ requestedCount: uniqueTags.length
13974
+ });
13975
+ return {
13976
+ success: true,
13977
+ ...response,
13978
+ storedMemoryIds: savedIds
13979
+ };
13911
13980
  }
13912
13981
  }
13913
13982
  var supermemoryClient = new SupermemoryClient;
@@ -13974,6 +14043,9 @@ function getGitEmail() {
13974
14043
  }
13975
14044
  }
13976
14045
  function getUserTag() {
14046
+ if (CONFIG.userContainerTag) {
14047
+ return CONFIG.userContainerTag;
14048
+ }
13977
14049
  const email3 = getGitEmail();
13978
14050
  if (email3) {
13979
14051
  return `${CONFIG.containerTagPrefix}_user_${sha256(email3)}`;
@@ -13982,6 +14054,9 @@ function getUserTag() {
13982
14054
  return `${CONFIG.containerTagPrefix}_user_${sha256(fallback)}`;
13983
14055
  }
13984
14056
  function getProjectTag(directory) {
14057
+ if (CONFIG.projectContainerTag) {
14058
+ return CONFIG.projectContainerTag;
14059
+ }
13985
14060
  return `${CONFIG.containerTagPrefix}_project_${sha256(directory)}`;
13986
14061
  }
13987
14062
  function getTags(directory) {
@@ -14001,11 +14076,11 @@ function isFullyPrivate(content) {
14001
14076
  }
14002
14077
 
14003
14078
  // src/services/compaction.ts
14004
- import { existsSync as existsSync2, mkdirSync, readdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
14005
- import { join as join3 } from "node:path";
14006
- import { homedir as homedir3 } from "node:os";
14007
- var MESSAGE_STORAGE = join3(homedir3(), ".opencode", "messages");
14008
- var PART_STORAGE = join3(homedir3(), ".opencode", "parts");
14079
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "node:fs";
14080
+ import { join as join4 } from "node:path";
14081
+ import { homedir as homedir4 } from "node:os";
14082
+ var MESSAGE_STORAGE = join4(homedir4(), ".opencode", "messages");
14083
+ var PART_STORAGE = join4(homedir4(), ".opencode", "parts");
14009
14084
  var DEFAULT_THRESHOLD = 0.8;
14010
14085
  var MIN_TOKENS_FOR_COMPACTION = 50000;
14011
14086
  var COMPACTION_COOLDOWN_MS = 30000;
@@ -14050,31 +14125,31 @@ This context is critical for maintaining continuity after compaction.
14050
14125
  `;
14051
14126
  }
14052
14127
  function getMessageDir(sessionID) {
14053
- if (!existsSync2(MESSAGE_STORAGE))
14128
+ if (!existsSync3(MESSAGE_STORAGE))
14054
14129
  return null;
14055
- const directPath = join3(MESSAGE_STORAGE, sessionID);
14056
- if (existsSync2(directPath))
14130
+ const directPath = join4(MESSAGE_STORAGE, sessionID);
14131
+ if (existsSync3(directPath))
14057
14132
  return directPath;
14058
14133
  for (const dir of readdirSync(MESSAGE_STORAGE)) {
14059
- const sessionPath = join3(MESSAGE_STORAGE, dir, sessionID);
14060
- if (existsSync2(sessionPath))
14134
+ const sessionPath = join4(MESSAGE_STORAGE, dir, sessionID);
14135
+ if (existsSync3(sessionPath))
14061
14136
  return sessionPath;
14062
14137
  }
14063
14138
  return null;
14064
14139
  }
14065
14140
  function getOrCreateMessageDir(sessionID) {
14066
- if (!existsSync2(MESSAGE_STORAGE)) {
14067
- mkdirSync(MESSAGE_STORAGE, { recursive: true });
14141
+ if (!existsSync3(MESSAGE_STORAGE)) {
14142
+ mkdirSync2(MESSAGE_STORAGE, { recursive: true });
14068
14143
  }
14069
- const directPath = join3(MESSAGE_STORAGE, sessionID);
14070
- if (existsSync2(directPath))
14144
+ const directPath = join4(MESSAGE_STORAGE, sessionID);
14145
+ if (existsSync3(directPath))
14071
14146
  return directPath;
14072
14147
  for (const dir of readdirSync(MESSAGE_STORAGE)) {
14073
- const sessionPath = join3(MESSAGE_STORAGE, dir, sessionID);
14074
- if (existsSync2(sessionPath))
14148
+ const sessionPath = join4(MESSAGE_STORAGE, dir, sessionID);
14149
+ if (existsSync3(sessionPath))
14075
14150
  return sessionPath;
14076
14151
  }
14077
- mkdirSync(directPath, { recursive: true });
14152
+ mkdirSync2(directPath, { recursive: true });
14078
14153
  return directPath;
14079
14154
  }
14080
14155
  function findNearestMessageWithFields(messageDir) {
@@ -14082,7 +14157,7 @@ function findNearestMessageWithFields(messageDir) {
14082
14157
  const files = readdirSync(messageDir).filter((f) => f.endsWith(".json")).sort().reverse();
14083
14158
  for (const file2 of files) {
14084
14159
  try {
14085
- const content = readFileSync2(join3(messageDir, file2), "utf-8");
14160
+ const content = readFileSync3(join4(messageDir, file2), "utf-8");
14086
14161
  const msg = JSON.parse(content);
14087
14162
  if (msg.agent && msg.model?.providerID && msg.model?.modelID) {
14088
14163
  return msg;
@@ -14137,12 +14212,12 @@ function injectHookMessage(sessionID, hookContent, originalMessage) {
14137
14212
  sessionID
14138
14213
  };
14139
14214
  try {
14140
- writeFileSync2(join3(messageDir, `${messageID}.json`), JSON.stringify(messageMeta, null, 2));
14141
- const partDir = join3(PART_STORAGE, messageID);
14142
- if (!existsSync2(partDir)) {
14143
- mkdirSync(partDir, { recursive: true });
14215
+ writeFileSync3(join4(messageDir, `${messageID}.json`), JSON.stringify(messageMeta, null, 2));
14216
+ const partDir = join4(PART_STORAGE, messageID);
14217
+ if (!existsSync3(partDir)) {
14218
+ mkdirSync2(partDir, { recursive: true });
14144
14219
  }
14145
- writeFileSync2(join3(partDir, `${partID}.json`), JSON.stringify(textPart, null, 2));
14220
+ writeFileSync3(join4(partDir, `${partID}.json`), JSON.stringify(textPart, null, 2));
14146
14221
  log("[compaction] hook message injected", { sessionID, messageID });
14147
14222
  return true;
14148
14223
  } catch (err) {
@@ -0,0 +1,15 @@
1
+ interface Credentials {
2
+ apiKey: string;
3
+ createdAt: string;
4
+ }
5
+ export declare function loadCredentials(): Credentials | null;
6
+ export declare function saveCredentials(apiKey: string): void;
7
+ export declare function clearCredentials(): boolean;
8
+ export interface AuthResult {
9
+ success: boolean;
10
+ apiKey?: string;
11
+ error?: string;
12
+ }
13
+ export declare function startAuthFlow(timeoutMs?: number): Promise<AuthResult>;
14
+ export {};
15
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/services/auth.ts"],"names":[],"mappings":"AAYA,UAAU,WAAW;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,wBAAgB,eAAe,IAAI,WAAW,GAAG,IAAI,CAQpD;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAOpD;AAED,wBAAgB,gBAAgB,IAAI,OAAO,CAI1C;AAiBD,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,wBAAgB,aAAa,CAAC,SAAS,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC,CA+ErE"}
@@ -1,7 +1,9 @@
1
1
  import Supermemory from "supermemory";
2
- import type { MemoryType, ConversationMessage } from "../types/index.js";
2
+ import type { ConversationMessage, MemoryType } from "../types/index.js";
3
3
  export declare class SupermemoryClient {
4
4
  private client;
5
+ private formatConversationMessage;
6
+ private formatConversationTranscript;
5
7
  private getClient;
6
8
  searchMemories(query: string, containerTag: string): Promise<{
7
9
  results: Array<Supermemory.Search.SearchMemoriesResponse.Result>;
@@ -65,6 +67,7 @@ export declare class SupermemoryClient {
65
67
  success: false;
66
68
  error: string;
67
69
  } | {
70
+ storedMemoryIds: string[];
68
71
  id: string;
69
72
  conversationId: string;
70
73
  status: string;
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/services/client.ts"],"names":[],"mappings":"AAAA,OAAO,WAAW,MAAM,aAAa,CAAC;AAGtC,OAAO,KAAK,EACV,UAAU,EACV,mBAAmB,EAEpB,MAAM,mBAAmB,CAAC;AAe3B,qBAAa,iBAAiB;IAC5B,OAAO,CAAC,MAAM,CAA4B;IAE1C,OAAO,CAAC,SAAS;IAcX,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM;;;;;;;;;;;;;IAsBlD,UAAU,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM;;;;;;;;;;IAmB/C,SAAS,CACb,OAAO,EAAE,MAAM,EACf,YAAY,EAAE,MAAM,EACpB,QAAQ,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,UAAU,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE;;;;;;;;;IAqBnE,YAAY,CAAC,QAAQ,EAAE,MAAM;;;;;;;IAgB7B,YAAY,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,SAAK;;;;;;;;;;;;;;;IAqB7C,kBAAkB,CACtB,cAAc,EAAE,MAAM,EACtB,QAAQ,EAAE,mBAAmB,EAAE,EAC/B,aAAa,EAAE,MAAM,EAAE,EACvB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;;;;;;;;;;CAoCvD;AAED,eAAO,MAAM,iBAAiB,mBAA0B,CAAC"}
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/services/client.ts"],"names":[],"mappings":"AAAA,OAAO,WAAW,MAAM,aAAa,CAAC;AAGtC,OAAO,KAAK,EAEV,mBAAmB,EACnB,UAAU,EACX,MAAM,mBAAmB,CAAC;AAc3B,qBAAa,iBAAiB;IAC5B,OAAO,CAAC,MAAM,CAA4B;IAE1C,OAAO,CAAC,yBAAyB;IAmBjC,OAAO,CAAC,4BAA4B;IAMpC,OAAO,CAAC,SAAS;IAcX,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM;;;;;;;;;;;;;IAsBlD,UAAU,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM;;;;;;;;;;IAmB/C,SAAS,CACb,OAAO,EAAE,MAAM,EACf,YAAY,EAAE,MAAM,EACpB,QAAQ,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,UAAU,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE;;;;;;;;;IAqBnE,YAAY,CAAC,QAAQ,EAAE,MAAM;;;;;;;IAgB7B,YAAY,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,SAAK;;;;;;;;;;;;;;;IAqB7C,kBAAkB,CACtB,cAAc,EAAE,MAAM,EACtB,QAAQ,EAAE,mBAAmB,EAAE,EAC/B,aAAa,EAAE,MAAM,EAAE,EACvB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;;;;;;;;;;;CA0EvD;AAED,eAAO,MAAM,iBAAiB,mBAA0B,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"tags.d.ts","sourceRoot":"","sources":["../../src/services/tags.ts"],"names":[],"mappings":"AAQA,wBAAgB,WAAW,IAAI,MAAM,GAAG,IAAI,CAO3C;AAED,wBAAgB,UAAU,IAAI,MAAM,CAOnC;AAED,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAEvD;AAED,wBAAgB,OAAO,CAAC,SAAS,EAAE,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAK5E"}
1
+ {"version":3,"file":"tags.d.ts","sourceRoot":"","sources":["../../src/services/tags.ts"],"names":[],"mappings":"AAQA,wBAAgB,WAAW,IAAI,MAAM,GAAG,IAAI,CAO3C;AAED,wBAAgB,UAAU,IAAI,MAAM,CAanC;AAED,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAQvD;AAED,wBAAgB,OAAO,CAAC,SAAS,EAAE,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAK5E"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-supermemory",
3
- "version": "0.1.8",
3
+ "version": "2.0.2",
4
4
  "description": "OpenCode plugin that gives coding agents persistent memory using Supermemory",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",