OpenCode plugin for persistent memory using Supermemory. Your agent remembers what you tell it, across sessions and across projects.
One package supports both OpenCode generations: OpenCode V1 loads the root entry from
the plugin array, and OpenCode 2 loads opencode-supermemory/server (plus a small TUI
companion for notices) from the plugins array. See OpenCode 2.
bunx opencode-supermemory@latest install
bunx opencode-supermemory@latest login # or set SUPERMEMORY_API_KEY
bunx opencode-supermemory@latest status # check the connection any timeOr let your agent do it: paste this into OpenCode:
Install opencode-supermemory by following https://raw.githubusercontent.com/supermemoryai/opencode-supermemory/main/README.md
install, login, logout, and status are also available as in-chat commands
(/supermemory-init, /supermemory-login, /supermemory-logout, /supermemory-status)
once the plugin is registered.
Instructions for LLM agents
If you're an LLM agent helping set up opencode-supermemory, follow these steps:
Step 1: Run the installer
bunx opencode-supermemory@latest install --no-tuiThis registers the plugin in ~/.config/opencode/opencode.jsonc for both OpenCode V1
and OpenCode 2, and creates the /supermemory-index command. Add
--disable-context-recovery if the user also has
Oh My OpenCode installed, to avoid its auto-compact hook
fighting with this plugin's V1 compaction.
- Register the plugin in
~/.config/opencode/opencode.jsonc(pluginfor V1,pluginsfor OpenCode 2, plus anallowrule for the read-onlysupermemory_recalltool) - Create the
/supermemory-indexcommand (/supermemory-initis an alias)
cat ~/.config/opencode/opencode.jsoncShould contain the entries below. The installer preserves comments and other settings and is safe to re-run; if anything is missing, add it manually:
Step 3: Authenticate
bunx opencode-supermemory@latest loginlogin signs in with OAuth (browser consent, callback on 127.0.0.1:19880) and
saves refreshable credentials to ~/.supermemory-opencode/credentials.json. Running
OpenCode sessions pick up a login or logout without a restart. logout revokes the
saved refresh token. An existing saved API key keeps working until you run login.
For headless environments, set SUPERMEMORY_API_KEY manually, or create
~/.config/opencode/supermemory.jsonc:
{
"apiKey": "sm_...",
}Step 4: Verify setup
Tell the user to restart OpenCode and run bunx opencode-supermemory@latest status. The
status output lists whether the V1 and OpenCode 2 entries are registered. If it's not
connected, check: the user is authenticated (or SUPERMEMORY_API_KEY is set), the plugin
is in opencode.jsonc, opencode plugin list shows supermemory on OpenCode 2, and
~/.opencode-supermemory.log for errors.
Step 5: Initialize codebase memory (optional)
Run /supermemory-index to have the agent explore and memorize the codebase. /supermemory-init is an alias.
| 🧠 Context injection On a session's first message, the agent silently receives your profile, all project knowledge, and (if autoRecallEveryPrompt is on) a semantic search over personal memories. |
🔎 Reasoned recall Every turn, the agent is shown a directive asking it to decide whether recalling memory would help before answering. It searches via the supermemory tool only when it decides to; the search itself is auto-approved. |
| 💾 Automatic capture Completed turns are saved every captureEveryNTurns turns, with any remainder flushed when the session ends or OpenCode shuts down. Synthetic plugin context is excluded and <private> content is redacted. |
🗣️ Keyword detection Saying "remember", "save this", "don't forget", or a custom pattern nudges the agent to save to memory. |
🧭 Codebase indexing/supermemory-init has the agent explore and memorize the codebase's structure, patterns, and conventions. |
🗜️ Compaction memory On OpenCode V1, triggers summarization at 80% context capacity. On OpenCode 2, enriches the native compaction request. Both inject project memories into the summary and save the summary itself as a memory. |
| 🔒 Privacy Content wrapped in <private>...</private> is never stored. |
🔔 Update notices Checks npm for a newer release on session start and surfaces a one-line notice. |
[SUPERMEMORY]
User Profile:
- Prefers concise responses
- Expert in TypeScript
Project Knowledge:
- [100%] Uses Bun, not Node.js
- [100%] Build: bun run build
Relevant Memories:
- [82%] Build fails if .env.local missing
The agent uses this context automatically - no manual prompting needed.
On every substantive prompt, Supermemory directly searches the current project and injects up to five strong, fresh matches. Short prompts and commands are skipped, repeat results are suppressed per session, and recall fails open after three seconds so it never blocks the agent indefinitely.
Set recallMode to "advisory" to retain model-decided tool recall, or to
"off" to disable automatic recall. recallDirective customizes advisory mode.
Legacy autoRecallEveryPrompt: true maps to direct mode and false maps to
advisory mode when recallMode is unset.
Completed conversations are captured automatically:
- Every
captureEveryNTurnscompleted turns, OpenCode saves the new turn batch. - Any remaining turns are flushed when the session is deleted or the OpenCode instance shuts down.
- Synthetic plugin context is excluded and
<private>content is redacted. - Stable capture IDs retain batch identity across repeated lifecycle events; they do not guarantee exactly-once processing or billing after an ambiguous response.
Automatic recall, capture and compaction memory run only for sessions you drive yourself. By default the plugin makes no Supermemory calls from its hooks for:
- Subagent sessions. Any session with a
parentID, which OpenCode sets on child sessions spawned by thetask(V1) orsubagent(OpenCode 2) tool. SetcaptureSubagents: trueorSUPERMEMORY_CAPTURE_SUBAGENTS=trueto restore recall and capture for them. - Headless runs (OpenCode V1).
opencode runandopencode github run(including their V5 session uploads), which host the server and plugins in the CLI process. SetcaptureHeadless: trueorSUPERMEMORY_CAPTURE_HEADLESS=trueto restore them.opencode run --attachon V1 runs the plugin in the attached server, so it is treated as interactive.
OpenCode 2 opencode run is not detected as headless. OpenCode 2 gives plugins no signal for
it (it may share the background server with interactive sessions), so OpenCode 2 runs get recall
and capture like any interactive session. Only subagent sessions are skipped on OpenCode 2.
OpenCode's title generation never reaches the plugin's hooks, so it makes no Supermemory calls. Compaction only runs Compaction Memory for the session being summarised, which is skipped for subagent and headless sessions like everything else.
Sessions started by Conductor (CONDUCTOR_WORKSPACE_PATH, CONDUCTOR_SESSION_ID) or Vibe Kanban
(VK_WORKSPACE_ID) are real user work and always count as interactive, even through
opencode run. Set captureOrchestrated: false or SUPERMEMORY_CAPTURE_ORCHESTRATED=false to
skip them. The variables are inherited, so any opencode run started inside a Conductor or
Vibe Kanban workspace (a script, or an agent shelling out to OpenCode) also counts as
orchestrated and is captured. Orchestrators without an environment variable (Crystal, Claude
Squad) are not recognised; Claude Squad runs the interactive TUI, which is captured as usual. On OpenCode 2 the variables are read from the server process, so they only apply
when it was started from the orchestrator's environment (for example --standalone or run
without a background service).
Swarms of one-shot workers often send the same task prompt many times. Two small local
indexes under ~/.supermemory-opencode/ keep those repeats from being re-sent:
- Opening prompt (
dedupeOpeningPrompt, defaulttrue). When a session's first prompt is at least 200 characters and matches one this machine successfully captured for the same API base URL, credential and container tag in the last 24 hours, the capture is sent with a one-line[Opening prompt omitted: ...]marker in its place. The rest of the conversation is captured as usual. Older entries are ignored and pruned, nothing is deduped without a credential, andlogoutdeletes the index. It applies to the client-formatted capture used with legacy servers; V5 session capture uploads the transcript unchanged. SetSUPERMEMORY_DEDUPE_OPENING_PROMPT=falseto opt out. - Recall query (
dedupeRecallQueries, defaulttrue). When the same normalized query is recalled against the same container tag within 10 minutes, the result of the first successful search is re-served without another API call, so a new session still gets the same context. A failed or timed-out search is never cached. Entries are keyed on a hash of the API base URL, the credential, the container tags and the query, so another account or backend never reuses them; nothing is cached without a credential, andlogoutdeletes the file. SetSUPERMEMORY_DEDUPE_RECALL_QUERIES=falseto opt out.
The SUPERMEMORY_CAPTURE_* and SUPERMEMORY_DEDUPE_* variables accept true/1/yes/on
and false/0/no/off (any case) and override the config file in both directions.
Say "remember", "save this", "don't forget" etc. and the agent auto-saves to memory.
You: "Remember that this project uses bun"
Agent: [saves to project memory]
Add custom triggers via keywordPatterns config.
Run /supermemory-index to explore and memorize your codebase structure, patterns, and conventions. /supermemory-init is an alias.
On OpenCode V1, when context hits 80% capacity (compactionThreshold) the plugin triggers
OpenCode's summarization, injects project memories into the summary prompt, and saves the
resulting summary as a memory.
On OpenCode 2, OpenCode owns the compaction trigger and model. The plugin hooks the native
compaction request to add the same project memories, then saves each successful summary as
a memory. Set compactionEnabled: false to opt out on OpenCode 2.
Supermemory shows a short native notice when it recalls memories, saves a turn, falls open
because recall was unavailable, or a newer release exists. Notices never enter model
context. On OpenCode V1 they are TUI toasts; on OpenCode 2 they are rendered by the
opencode-supermemory/tui companion, which OpenCode loads automatically next to the
server plugin.
The same TUI plugin keeps a persistent ◪ supermemory footer. It turns blue while a
session is running and otherwise shows the latest recall or save activity, if any. On OpenCode V1
the installer enables it through ~/.config/opencode/tui.jsonc; on OpenCode 2 it appears
in the prompt footer without extra configuration.
Set SUPERMEMORY_DEBUG=1 to show a [recall-decision] line in each reply while testing
advisory recall.
OpenCode 2 uses the plural plugins config key and the new @opencode/plugin API. The
installer writes both generations, so one opencode.jsonc works for opencode (V1) and
OpenCode 2 side by side:
{
"plugin": ["opencode-supermemory@latest"],
"plugins": ["opencode-supermemory"],
"permission": { "supermemory_recall": "allow" },
}OpenCode 2 resolves the package's ./server export for the server plugin (id
supermemory) and ./tui for the notice companion (id supermemory.tui). Verify with
opencode plugin list (or v2 plugin registered in ~/.opencode-supermemory.log), and
update with opencode plugin update opencode-supermemory.
What is the same on both generations:
- Direct recall on substantive prompts, advisory mode, and
recallMode: "off" - First-message profile injection, keyword nudges, and automatic capture with the same cadence, privacy redaction, and idempotent capture IDs
- The
supermemorytool with identical modes, scopes, and result formatting - Activity notices, the persistent status footer, and update checks
What differs on OpenCode 2:
- Recall runs through the read-only
supermemory_recalltool (search only). The installer allows it without prompting;add,forget, and the rest stay behind the normalsupermemorypermission. An explicitdenyforsupermemory_recallis preserved. - Compaction is native: the plugin enriches OpenCode's compaction request and saves the
summary instead of triggering compaction itself (
compactionEnabled). - Recalled context is attached to the outgoing model request for the current prompt rather than persisted into the transcript.
To roll back on OpenCode 2 only, remove "opencode-supermemory" from plugins (or prefix
it with -) and restart. The V1 plugin entry is unaffected.
The supermemory tool is available to the agent:
| Mode | Args | Description |
|---|---|---|
add |
content, type?, scope? |
Store memory |
search |
query, scope? |
Search memories |
profile |
query? |
View user profile |
list |
scope?, limit? |
List memories |
forget |
memoryId, scope? |
Delete memory |
help |
none | List available modes |
Scopes: user (personal memories for the current project), project (default)
Types: project-config, architecture, error-solution, preference, learned-pattern, conversation
OpenCode sends the same shared coding-agent entity context as Claude Code and Codex.
Personal and project memories are distinguished with sm_scope metadata inside the
shared repository container.
| Scope | Tag | Metadata |
|---|---|---|
| User | repo_{project-name}__{repository-hash} |
sm_scope: "personal" |
| Project | repo_{project-name}__{repository-hash} |
sm_scope: "project" |
The repository hash comes from the normalized Git origin remote, so Claude Code,
Codex, Cursor, and OpenCode use the same container for the same repository.
Repositories with the same name but different remotes remain isolated. Without an
origin remote, OpenCode falls back to the repository's real filesystem path.
OpenCode also reads previous user_project_*, repo_<project-name>,
claudecode_project_*, codex_user_*, codex_project_*, opencode_user_*,
opencode_project_*, cursor_user_*, and cursor_project_* containers, so upgrading
does not require a migration.
| Variable | Purpose |
|---|---|
SUPERMEMORY_API_KEY |
Your Supermemory API key (takes precedence over the config file). |
SUPERMEMORY_API_URL / SUPERMEMORY_BASE_URL |
Override the Supermemory API base URL. |
SUPERMEMORY_API_VERSION |
Select legacy or v5, overriding apiVersion in the config file. |
SUPERMEMORY_MCP_URL |
OAuth resource / MCP URL (default https://mcp.supermemory.ai/mcp; required for OAuth against a custom API URL that is not api.*). |
SUPERMEMORY_OAUTH_ISSUER |
Override the OAuth issuer (default <API URL>/api/auth). |
SUPERMEMORY_AUTH_TIMEOUT |
Browser-login timeout in milliseconds (default 5 minutes). |
SUPERMEMORY_REPO_TAG |
Explicit project-container override, checked before the config value. |
SUPERMEMORY_ISOLATE_WORKTREES |
Set to true to key the project container on the worktree path instead of the Git remote. |
SUPERMEMORY_DEBUG |
Set to show [recall-decision] lines and enable debug logging. |
SUPERMEMORY_CAPTURE_SUBAGENTS |
true restores recall and capture for subagent sessions (overrides captureSubagents). |
SUPERMEMORY_CAPTURE_HEADLESS |
true restores recall and capture for opencode run (overrides captureHeadless). |
SUPERMEMORY_CAPTURE_ORCHESTRATED |
false skips sessions started by Conductor or Vibe Kanban (overrides captureOrchestrated). |
SUPERMEMORY_DEDUPE_OPENING_PROMPT |
false always sends repeated opening prompts (overrides dedupeOpeningPrompt). |
SUPERMEMORY_DEDUPE_RECALL_QUERIES |
false always searches for repeated recall queries instead of re-serving the cached result (overrides dedupeRecallQueries). |
Hosted content calls use the official Supermemory v5 SDK. Custom base URLs default
to the bundled legacy SDK so existing self-hosted servers, including 0.0.8, keep
working. After independently upgrading a custom server to support v5, opt in with
"apiVersion": "v5" or SUPERMEMORY_API_VERSION=v5. Set legacy explicitly to
keep the old content protocol on any endpoint. Failed requests never switch API
versions or reroute to hosted Supermemory, and existing container names, IDs,
credentials, capture cadence, and configuration files are not migrated or renamed.
The plugin never changes organization settings. Extraction guidance travels with
each saved document as entityContext, so it applies only to OpenCode's own
memories. Account status reads /session; only legacy mode falls back to
/v3/session for older servers.
v5 capture uses document POST append/diff with dreaming: "dynamic"; accepted
documents may take minutes to form recallable memories. The plugin does not enable
the extra-billable instant mode. Profiles normalize fact objects to text and issue
a separate search only when a query is requested. Document lists fetch canonical
content per document to retain the previous content-inclusive response, so lists
and compaction can require additional requests under the existing timeout budget.
Individual failed, invalid or late content reads retain the listed document's
identity, summary and lifecycle fields; hydration uses the remaining list budget
with a return grace. Content is accepted only from the matching document ID and
scope, not from a different or malformed response.
{
// API key (can also use SUPERMEMORY_API_KEY env var)
"apiKey": "sm_...",
// Supermemory API base URL (point at a self-hosted instance, e.g. http://localhost:8787)
"baseUrl": "https://api.supermemory.ai",
// Min similarity for memory retrieval (0-1)
"similarityThreshold": 0.55,
// Max memories injected per request
"maxMemories": 5,
// Max project memories listed
"maxProjectMemories": 10,
// Max profile facts injected
"maxProfileItems": 5,
// Include user profile in context
"injectProfile": true,
// Also run a semantic search over personal memories on a session's first
// message, not just profile + project list (default: true on upgrades,
// false on fresh installs)
"autoRecallEveryPrompt": true,
// Legacy prefix retained when reading containers made by older versions
"containerTagPrefix": "opencode",
// Optional legacy personal container to keep reading
"userContainerTag": "my-custom-user-tag",
// Optional: set exact project container tag (overrides auto-generated tag)
"projectContainerTag": "my-project-tag",
// Extra keyword patterns for memory detection (regex)
"keywordPatterns": ["log\\s+this", "write\\s+down"],
// OpenCode V1: context usage ratio that triggers compaction (0-1)
"compactionThreshold": 0.8,
// OpenCode 2: enrich native compaction with project memories and save summaries
"compactionEnabled": true,
// Save completed conversation batches every N turns (0 = session end only)
"captureEveryNTurns": 3,
// "direct" (default for new installs), "advisory", or "off"
"recallMode": "direct",
// Override the directive used in advisory mode
"recallDirective": null,
// Recall and capture subagent (child) sessions too
"captureSubagents": false,
// OpenCode V1: recall and capture `opencode run` / `opencode github run` too
"captureHeadless": false,
// Recall and capture sessions started by Conductor or Vibe Kanban
"captureOrchestrated": true,
// Replace a 200+ character opening prompt captured from this machine in the last 24h with a marker
"dedupeOpeningPrompt": true,
// Re-serve the last successful recall for a repeat of a query made in the last 10 minutes
"dedupeRecallQueries": true,
}All fields optional.
By default, new writes use:
- Repository tag:
repo_{project-name}__{hash(normalized-origin-remote)} - No origin remote:
repo_{project-name}__{hash(real-repository-path)}
Older {prefix}_user_* and {prefix}_project_* containers remain readable.
userContainerTag is treated as a legacy personal read. You can still override the
unified write container with projectContainerTag:
{
// Continue reading a personal container made by an older version
"userContainerTag": "my-team-workspace",
// Override the unified container used for new writes
"projectContainerTag": "my-awesome-project",
}This is useful to preserve a legacy personal memory container, sync memories between machines for the same project, organize memories with your own naming scheme, or integrate with existing Supermemory container tags from other tools.
If you're using Oh My OpenCode,
disable its built-in auto-compact hook to let supermemory handle context compaction
(or pass --disable-context-recovery to install):
{
"disabled_hooks": ["anthropic-context-window-limit-recovery"]
}Add that to ~/.config/opencode/oh-my-opencode.json.
Development
bun install
bun run build
bun run typecheckLocal install (OpenCode V1 loads the built package; OpenCode 2 loads server.ts and
tui.ts from the checkout, so bun install is enough):
// ~/.config/opencode/opencode.jsonc
{
"plugin": ["file:///path/to/opencode-supermemory"],
"plugins": ["/path/to/opencode-supermemory"],
}The TUI side of a local checkout is registered separately: OpenCode V1 reads
~/.config/opencode/tui.jsonc ("plugin": ["file:///path/to/opencode-supermemory/dist/tui.js"])
and OpenCode 2 reads ~/.config/opencode/cli.json ("plugins": ["/path/to/opencode-supermemory"]).
Published packages need neither; both generations find the ./tui export on their own.
opencode plugin list only shows package plugins, so confirm a checkout loaded by looking
for v2 plugin init and v2 plugin registered in ~/.opencode-supermemory.log.
Logs:
tail -f ~/.opencode-supermemory.logMIT
{ // OpenCode V1 "plugin": [ "opencode-supermemory@latest", // ... other plugins ], // OpenCode 2 "plugins": [ "opencode-supermemory", // ... other OpenCode 2 plugins ], // OpenCode V1 rejects V2 "permissions"; OpenCode 2 reads this as the same rule "permission": { "supermemory_recall": "allow", }, }