-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathcli.ts
More file actions
537 lines (437 loc) · 16.8 KB
/
cli.ts
File metadata and controls
537 lines (437 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
#!/usr/bin/env node
import { mkdirSync, writeFileSync, readFileSync, existsSync } from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";
import * as readline from "node:readline";
import { stripJsoncComments } from "./services/jsonc.js";
import { startAuthFlow, clearCredentials, loadCredentials } from "./services/auth.js";
const OPENCODE_CONFIG_DIR = join(homedir(), ".config", "opencode");
const OPENCODE_COMMAND_DIR = join(OPENCODE_CONFIG_DIR, "command");
const OH_MY_OPENCODE_CONFIG = join(OPENCODE_CONFIG_DIR, "oh-my-opencode.json");
const PLUGIN_NAME = "opencode-supermemory@latest";
const SUPERMEMORY_INIT_COMMAND = `---
description: Initialize Supermemory with comprehensive codebase knowledge
---
# Initializing Supermemory
You are initializing persistent memory for this codebase. This is not just data collection - you're building context that will make you significantly more effective across all future sessions.
## Understanding Context
You are a **stateful** coding agent. Users expect to work with you over extended periods - potentially the entire lifecycle of a project. Your memory is how you get better over time and maintain continuity.
## What to Remember
### 1. Procedures (Rules & Workflows)
Explicit rules that should always be followed:
- "Never commit directly to main - always use feature branches"
- "Always run lint before tests"
- "Use conventional commits format"
### 2. Preferences (Style & Conventions)
Project and user coding style:
- "Prefer functional components over class components"
- "Use early returns instead of nested conditionals"
- "Always add JSDoc to exported functions"
### 3. Architecture & Context
How the codebase works and why:
- "Auth system was refactored in v2.0 - old patterns deprecated"
- "The monorepo used to have 3 modules before consolidation"
- "This pagination bug was fixed before - similar to PR #234"
## Memory Scopes
**Project-scoped** (\`scope: "project"\`):
- Build/test/lint commands
- Architecture and key directories
- Team conventions specific to this codebase
- Technology stack and framework choices
- Known issues and their solutions
**User-scoped** (\`scope: "user"\`):
- Personal coding preferences across all projects
- Communication style preferences
- General workflow habits
## Research Approach
This is a **deep research** initialization. Take your time and be thorough (~50+ tool calls). The goal is to genuinely understand the project, not just collect surface-level facts.
**What to uncover:**
- Tech stack and dependencies (explicit and implicit)
- Project structure and architecture
- Build/test/deploy commands and workflows
- Contributors & team dynamics (who works on what?)
- Commit conventions and branching strategy
- Code evolution (major refactors, architecture changes)
- Pain points (areas with lots of bug fixes)
- Implicit conventions not documented anywhere
## Research Techniques
### File-based
- README.md, CONTRIBUTING.md, AGENTS.md, CLAUDE.md
- Package manifests (package.json, Cargo.toml, pyproject.toml, go.mod)
- Config files (.eslintrc, tsconfig.json, .prettierrc)
- CI/CD configs (.github/workflows/)
### Git-based
- \`git log --oneline -20\` - Recent history
- \`git branch -a\` - Branching strategy
- \`git log --format="%s" -50\` - Commit conventions
- \`git shortlog -sn --all | head -10\` - Main contributors
### Explore Agent
Fire parallel explore queries for broad understanding:
\`\`\`
Task(explore, "What is the tech stack and key dependencies?")
Task(explore, "What is the project structure? Key directories?")
Task(explore, "How do you build, test, and run this project?")
Task(explore, "What are the main architectural patterns?")
Task(explore, "What conventions or patterns are used?")
\`\`\`
## How to Do Thorough Research
**Don't just collect data - analyze and cross-reference.**
Bad (shallow):
- Run commands, copy output
- List facts without understanding
Good (thorough):
- Cross-reference findings (if inconsistent, dig deeper)
- Resolve ambiguities (don't leave questions unanswered)
- Read actual file content, not just names
- Look for patterns (what do commits tell you about workflow?)
- Think like a new team member - what would you want to know?
## Saving Memories
Use the \`supermemory\` tool for each distinct insight:
\`\`\`
supermemory(mode: "add", content: "...", type: "...", scope: "project")
\`\`\`
**Types:**
- \`project-config\` - tech stack, commands, tooling
- \`architecture\` - codebase structure, key components, data flow
- \`learned-pattern\` - conventions specific to this codebase
- \`error-solution\` - known issues and their fixes
- \`preference\` - coding style preferences (use with user scope)
**Guidelines:**
- Save each distinct insight as a separate memory
- Be concise but include enough context to be useful
- Include the "why" not just the "what" when relevant
- Update memories incrementally as you research (don't wait until the end)
**Good memories:**
- "Uses Bun runtime and package manager. Commands: bun install, bun run dev, bun test"
- "API routes in src/routes/, handlers in src/handlers/. Hono framework."
- "Auth uses Redis sessions, not JWT. Implementation in src/lib/auth.ts"
- "Never use \`any\` type - strict TypeScript. Use \`unknown\` and narrow."
- "Database migrations must be backward compatible - we do rolling deploys"
## Upfront Questions
Before diving in, ask:
1. "Any specific rules I should always follow?"
2. "Preferences for how I communicate? (terse/detailed)"
## Reflection Phase
Before finishing, reflect:
1. **Completeness**: Did you cover commands, architecture, conventions, gotchas?
2. **Quality**: Are memories concise and searchable?
3. **Scope**: Did you correctly separate project vs user knowledge?
Then ask: "I've initialized memory with X insights. Want me to continue refining, or is this good?"
## Your Task
1. Ask upfront questions (research depth, rules, preferences)
2. Check existing memories: \`supermemory(mode: "list", scope: "project")\`
3. Research based on chosen depth
4. Save memories incrementally as you discover insights
5. Reflect and verify completeness
6. Summarize what was learned and ask if user wants refinement
`;
const SUPERMEMORY_LOGIN_COMMAND = `---
description: Authenticate with Supermemory via browser
---
# Supermemory Login
Run this command to authenticate the user with Supermemory:
\`\`\`bash
bunx opencode-supermemory@latest login
\`\`\`
This will:
1. Start a local server on port 19877
2. Open the browser to Supermemory's authentication page
3. After the user logs in, save credentials to ~/.supermemory-opencode/credentials.json
Wait for the command to complete, then inform the user whether authentication succeeded or failed.
If the user wants to log out instead, tell them to use the /supermemory-logout command.
`;
const SUPERMEMORY_LOGOUT_COMMAND = `---
description: Log out from Supermemory and clear credentials
---
# Supermemory Logout
Run this command to log out and clear Supermemory credentials:
\`\`\`bash
bunx opencode-supermemory@latest logout
\`\`\`
This will remove the saved credentials from ~/.supermemory-opencode/credentials.json.
Inform the user whether logout succeeded and that they'll need to run /supermemory-login to re-authenticate.
`;
function createReadline(): readline.Interface {
return readline.createInterface({
input: process.stdin,
output: process.stdout,
});
}
async function confirm(rl: readline.Interface, question: string): Promise<boolean> {
return new Promise((resolve) => {
rl.question(`${question} (y/n) `, (answer) => {
resolve(answer.toLowerCase() === "y" || answer.toLowerCase() === "yes");
});
});
}
function findOpencodeConfig(): string | null {
const candidates = [
join(OPENCODE_CONFIG_DIR, "opencode.jsonc"),
join(OPENCODE_CONFIG_DIR, "opencode.json"),
];
for (const path of candidates) {
if (existsSync(path)) {
return path;
}
}
return null;
}
function addPluginToConfig(configPath: string): boolean {
try {
const content = readFileSync(configPath, "utf-8");
if (content.includes("opencode-supermemory")) {
console.log("✓ Plugin already registered in config");
return true;
}
const jsonContent = stripJsoncComments(content);
let config: Record<string, unknown>;
try {
config = JSON.parse(jsonContent);
} catch {
console.error("✗ Failed to parse config file");
return false;
}
const plugins = (config.plugin as string[]) || [];
plugins.push(PLUGIN_NAME);
config.plugin = plugins;
if (configPath.endsWith(".jsonc")) {
if (content.includes('"plugin"')) {
const newContent = content.replace(
/("plugin"\s*:\s*\[)([^\]]*?)(\])/,
(_match, start, middle, end) => {
const trimmed = middle.trim();
if (trimmed === "") {
return `${start}\n "${PLUGIN_NAME}"\n ${end}`;
}
return `${start}${middle.trimEnd()},\n "${PLUGIN_NAME}"\n ${end}`;
}
);
writeFileSync(configPath, newContent);
} else {
const newContent = content.replace(
/^(\s*\{)/,
`$1\n "plugin": ["${PLUGIN_NAME}"],`
);
writeFileSync(configPath, newContent);
}
} else {
writeFileSync(configPath, JSON.stringify(config, null, 2));
}
console.log(`✓ Added plugin to ${configPath}`);
return true;
} catch (err) {
console.error("✗ Failed to update config:", err);
return false;
}
}
function createNewConfig(): boolean {
const configPath = join(OPENCODE_CONFIG_DIR, "opencode.jsonc");
mkdirSync(OPENCODE_CONFIG_DIR, { recursive: true });
const config = `{
"plugin": ["${PLUGIN_NAME}"]
}
`;
writeFileSync(configPath, config);
console.log(`✓ Created ${configPath}`);
return true;
}
function createCommands(): boolean {
mkdirSync(OPENCODE_COMMAND_DIR, { recursive: true });
const initPath = join(OPENCODE_COMMAND_DIR, "supermemory-init.md");
writeFileSync(initPath, SUPERMEMORY_INIT_COMMAND);
console.log(`✓ Created /supermemory-init command`);
const loginPath = join(OPENCODE_COMMAND_DIR, "supermemory-login.md");
writeFileSync(loginPath, SUPERMEMORY_LOGIN_COMMAND);
console.log(`✓ Created /supermemory-login command`);
const logoutPath = join(OPENCODE_COMMAND_DIR, "supermemory-logout.md");
writeFileSync(logoutPath, SUPERMEMORY_LOGOUT_COMMAND);
console.log(`✓ Created /supermemory-logout command`);
return true;
}
function isOhMyOpencodeInstalled(): boolean {
const configPath = findOpencodeConfig();
if (!configPath) return false;
try {
const content = readFileSync(configPath, "utf-8");
return content.includes("oh-my-opencode");
} catch {
return false;
}
}
function isAutoCompactAlreadyDisabled(): boolean {
if (!existsSync(OH_MY_OPENCODE_CONFIG)) return false;
try {
const content = readFileSync(OH_MY_OPENCODE_CONFIG, "utf-8");
const config = JSON.parse(content);
const disabledHooks = config.disabled_hooks as string[] | undefined;
return disabledHooks?.includes("anthropic-context-window-limit-recovery") ?? false;
} catch {
return false;
}
}
function disableAutoCompactHook(): boolean {
try {
let config: Record<string, unknown> = {};
if (existsSync(OH_MY_OPENCODE_CONFIG)) {
const content = readFileSync(OH_MY_OPENCODE_CONFIG, "utf-8");
config = JSON.parse(content);
}
const disabledHooks = (config.disabled_hooks as string[]) || [];
if (!disabledHooks.includes("anthropic-context-window-limit-recovery")) {
disabledHooks.push("anthropic-context-window-limit-recovery");
}
config.disabled_hooks = disabledHooks;
writeFileSync(OH_MY_OPENCODE_CONFIG, JSON.stringify(config, null, 2));
console.log(`✓ Disabled anthropic-context-window-limit-recovery hook in oh-my-opencode.json`);
return true;
} catch (err) {
console.error("✗ Failed to update oh-my-opencode.json:", err);
return false;
}
}
interface InstallOptions {
tui: boolean;
disableAutoCompact: boolean;
}
async function install(options: InstallOptions): Promise<number> {
console.log("\n🧠 opencode-supermemory installer\n");
const rl = options.tui ? createReadline() : null;
// Step 1: Register plugin in config
console.log("Step 1: Register plugin in OpenCode config");
const configPath = findOpencodeConfig();
if (configPath) {
if (options.tui) {
const shouldModify = await confirm(rl!, `Add plugin to ${configPath}?`);
if (!shouldModify) {
console.log("Skipped.");
} else {
addPluginToConfig(configPath);
}
} else {
addPluginToConfig(configPath);
}
} else {
if (options.tui) {
const shouldCreate = await confirm(rl!, "No OpenCode config found. Create one?");
if (!shouldCreate) {
console.log("Skipped.");
} else {
createNewConfig();
}
} else {
createNewConfig();
}
}
// Step 2: Create commands
console.log("\nStep 2: Create /supermemory-init, /supermemory-login, and /supermemory-logout commands");
if (options.tui) {
const shouldCreate = await confirm(rl!, "Add supermemory commands?");
if (!shouldCreate) {
console.log("Skipped.");
} else {
createCommands();
}
} else {
createCommands();
}
// Step 3: Configure Oh My OpenCode (if installed)
if (isOhMyOpencodeInstalled()) {
console.log("\nStep 3: Configure Oh My OpenCode");
console.log("Detected Oh My OpenCode plugin.");
console.log("Supermemory handles context compaction, so the built-in context-window-limit-recovery hook should be disabled.");
if (isAutoCompactAlreadyDisabled()) {
console.log("✓ anthropic-context-window-limit-recovery hook already disabled");
} else {
if (options.tui) {
const shouldDisable = await confirm(rl!, "Disable anthropic-context-window-limit-recovery hook to let Supermemory handle context?");
if (!shouldDisable) {
console.log("Skipped.");
} else {
disableAutoCompactHook();
}
} else if (options.disableAutoCompact) {
disableAutoCompactHook();
} else {
console.log("Skipped. Use --disable-context-recovery to disable the hook in non-interactive mode.");
}
}
}
if (rl) rl.close();
// Step 4: Authenticate
console.log("\n" + "─".repeat(50));
console.log("\n🔑 Final step: Authenticate with Supermemory\n");
if (options.tui) {
return login();
}
// Non-interactive mode - print instructions
console.log("Run this command to authenticate:");
console.log(" bunx opencode-supermemory@latest login");
console.log("\nOr set your API key manually:");
console.log(' export SUPERMEMORY_API_KEY="sm_..."');
console.log("\n" + "─".repeat(50));
console.log("\n✓ Setup complete! Restart OpenCode to activate.\n");
return 0;
}
async function login(): Promise<number> {
const existing = loadCredentials();
if (existing) {
console.log("Already authenticated. Use 'logout' first to re-authenticate.");
return 0;
}
const result = await startAuthFlow();
if (result.success) {
console.log("\n✓ Successfully authenticated with Supermemory!");
console.log("Restart OpenCode to activate.\n");
return 0;
} else {
console.error(`\n✗ Authentication failed: ${result.error}`);
return 1;
}
}
function logout(): number {
if (clearCredentials()) {
console.log("✓ Logged out. Credentials cleared.");
return 0;
} else {
console.log("No credentials found.");
return 0;
}
}
function printHelp(): void {
console.log(`
opencode-supermemory - Persistent memory for OpenCode agents
Commands:
install Install and configure the plugin
--no-tui Non-interactive mode (for LLM agents)
--disable-context-recovery Disable Oh My OpenCode's context hook
login Authenticate with Supermemory (opens browser)
logout Clear stored credentials
Examples:
bunx opencode-supermemory@latest install
bunx opencode-supermemory@latest login
bunx opencode-supermemory@latest logout
`);
}
const args = process.argv.slice(2);
if (args.length === 0 || args[0] === "help" || args[0] === "--help" || args[0] === "-h") {
printHelp();
process.exit(0);
}
if (args[0] === "install") {
const noTui = args.includes("--no-tui");
const disableAutoCompact = args.includes("--disable-context-recovery");
install({ tui: !noTui, disableAutoCompact }).then((code) => process.exit(code));
} else if (args[0] === "setup") {
console.log("Note: 'setup' is deprecated. Use 'install' instead.\n");
const noTui = args.includes("--no-tui");
const disableAutoCompact = args.includes("--disable-context-recovery");
install({ tui: !noTui, disableAutoCompact }).then((code) => process.exit(code));
} else if (args[0] === "login") {
login().then((code) => process.exit(code));
} else if (args[0] === "logout") {
process.exit(logout());
} else {
console.error(`Unknown command: ${args[0]}`);
printHelp();
process.exit(1);
}