Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## 2.3.0

- Skip automatic recall, capture and compaction memory for subagent sessions (any session with a `parentID`) and, on OpenCode V1, for `opencode run` / `opencode github run`, including V5 session capture uploads. Opt back in with `captureSubagents` / `captureHeadless` or `SUPERMEMORY_CAPTURE_SUBAGENTS=true` / `SUPERMEMORY_CAPTURE_HEADLESS=true`.
- Treat Conductor and Vibe Kanban sessions as interactive; `captureOrchestrated: false` skips them.
- Replace an opening prompt of 200+ characters already captured from this machine for the same container in the last 24 hours with a one-line marker on the client-formatted (legacy server) capture path (`dedupeOpeningPrompt`), and re-serve the last successful recall for exact query repeats within 10 minutes instead of searching again (`dedupeRecallQueries`).
- `SUPERMEMORY_CAPTURE_*` / `SUPERMEMORY_DEDUPE_*` accept `true/1/yes/on` and `false/0/no/off`; OpenCode V1 headless detection skips the values of value-taking flags (`--port 4096 run` is headless, `--prompt run` is not); the parent-session lookup fails open after 2 seconds.

## 2.1.3

- Back off failed compaction summary saves with jittered exponential delays starting at 15s, and drop a summary after 5 failed attempts instead of re-sending it on every event (#128).
Expand Down
76 changes: 76 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,62 @@ Completed conversations are captured automatically:
- 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.

### Sessions without automatic memory

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 the `task` (V1) or `subagent` (OpenCode 2) tool. Set `captureSubagents: true` or
`SUPERMEMORY_CAPTURE_SUBAGENTS=true` to restore recall and capture for them.
- **Headless runs (OpenCode V1).** `opencode run` and `opencode github run` (including their
V5 session uploads), which host the
server and plugins in the CLI process. Set `captureHeadless: true` or
`SUPERMEMORY_CAPTURE_HEADLESS=true` to restore them. `opencode run --attach` on 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](#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).

### Repeated prompts

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`, default `true`). 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, and `logout` deletes the index. It applies to the client-formatted capture used
with legacy servers; V5 session capture uploads the transcript unchanged. Set
`SUPERMEMORY_DEDUPE_OPENING_PROMPT=false` to opt out.
- **Recall query** (`dedupeRecallQueries`, default `true`). 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, and `logout` deletes the file. Set
`SUPERMEMORY_DEDUPE_RECALL_QUERIES=false` to 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.

### Keyword Detection

Say "remember", "save this", "don't forget" etc. and the agent auto-saves to memory.
Expand Down Expand Up @@ -309,6 +365,11 @@ does not require a migration.
| `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`). |

### `~/.config/opencode/supermemory.jsonc`

Expand Down Expand Up @@ -390,6 +451,21 @@ scope, not from a different or malformed response.

// 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,
}
```

Expand Down
2 changes: 2 additions & 0 deletions bunfig.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[test]
preload = ["./scripts/test-preload.mjs"]
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "opencode-supermemory",
"version": "2.2.0",
"version": "2.3.0",
"description": "OpenCode plugin that gives coding agents persistent memory using Supermemory",
"type": "module",
"main": "dist/index.js",
Expand Down
10 changes: 10 additions & 0 deletions scripts/test-preload.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { mock } from "bun:test";
import { mkdtempSync } from "node:fs";
import os from "node:os";
import { join } from "node:path";

// Keep tests away from the developer's Supermemory config and local dedupe state.
const home = mkdtempSync(join(os.tmpdir(), "opencode-supermemory-test-"));
const homedir = () => home;
mock.module("node:os", () => ({ ...os, default: { ...os, homedir }, homedir }));
mock.module("os", () => ({ ...os, default: { ...os, homedir }, homedir }));
57 changes: 57 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { createHash } from "node:crypto";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";
Expand Down Expand Up @@ -43,6 +44,11 @@ interface SupermemoryConfig {
captureEveryNTurns?: number;
recallDirective?: string | null;
recallMode?: RecallMode;
captureSubagents?: boolean;
captureHeadless?: boolean;
captureOrchestrated?: boolean;
dedupeOpeningPrompt?: boolean;
dedupeRecallQueries?: boolean;
}

const DEFAULT_KEYWORD_PATTERNS = [
Expand Down Expand Up @@ -77,6 +83,11 @@ const DEFAULTS: Required<Omit<SupermemoryConfig, "apiKey" | "baseUrl" | "apiVers
autoRecallEveryPrompt: false,
captureEveryNTurns: 0,
recallMode: "direct",
captureSubagents: false,
captureHeadless: false,
captureOrchestrated: true,
dedupeOpeningPrompt: true,
dedupeRecallQueries: true,
};

function isValidRegex(pattern: string): boolean {
Expand Down Expand Up @@ -111,6 +122,13 @@ function validateCaptureEveryNTurns(
return value;
}

function resolveFlag(envName: string, value: unknown, fallback: boolean): boolean {
const env = process.env[envName]?.trim().toLowerCase() ?? "";
if (["true", "1", "yes", "on"].includes(env)) return true;
if (["false", "0", "no", "off"].includes(env)) return false;
return typeof value === "boolean" ? value : fallback;
}

function resolveRecallMode(): RecallMode {
if (
fileConfig.recallMode === "direct" ||
Expand Down Expand Up @@ -149,6 +167,20 @@ export function getApiKey(): string | undefined {
return loadCredentials();
}

/** Hash of the backend URL and credential that scopes local dedupe and recall caching; null without a credential. */
export function getDedupeScope(): string | null {
try {
const apiKey = getApiKey();
const saved = apiKey ? null : loadCredentialData();
const credential =
apiKey ?? (saved?.type === "oauth" ? (saved.refreshToken ?? saved.accessToken) : undefined);
if (!credential) return null;
return createHash("sha256").update(`${getApiBaseUrl()}\n${credential}`).digest("hex");
} catch {
return null;
}
}

function normalizeBaseUrl(baseUrl: unknown): string | null {
if (typeof baseUrl !== "string" || !baseUrl.trim()) return null;

Expand Down Expand Up @@ -285,6 +317,31 @@ export const CONFIG = {
configExisted ? 3 : DEFAULTS.captureEveryNTurns,
),
recallDirective: fileConfig.recallDirective ?? null,
captureSubagents: resolveFlag(
"SUPERMEMORY_CAPTURE_SUBAGENTS",
fileConfig.captureSubagents,
DEFAULTS.captureSubagents,
),
captureHeadless: resolveFlag(
"SUPERMEMORY_CAPTURE_HEADLESS",
fileConfig.captureHeadless,
DEFAULTS.captureHeadless,
),
captureOrchestrated: resolveFlag(
"SUPERMEMORY_CAPTURE_ORCHESTRATED",
fileConfig.captureOrchestrated,
DEFAULTS.captureOrchestrated,
),
dedupeOpeningPrompt: resolveFlag(
"SUPERMEMORY_DEDUPE_OPENING_PROMPT",
fileConfig.dedupeOpeningPrompt,
DEFAULTS.dedupeOpeningPrompt,
),
dedupeRecallQueries: resolveFlag(
"SUPERMEMORY_DEDUPE_RECALL_QUERIES",
fileConfig.dedupeRecallQueries,
DEFAULTS.dedupeRecallQueries,
),
};

/** Resolved on every call so login and logout apply without restarting OpenCode. */
Expand Down
60 changes: 51 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,11 @@ import {
type SupermemoryToolArgs,
} from "./services/memory-tool.js";
import { getTags } from "./services/tags.js";
import { isHeadlessCommand, SessionScope } from "./services/session-scope.js";
import { RecallQueryCache } from "./services/local-dedupe.js";
import { createCompactionHook, type CompactionContext } from "./services/compaction.js";

import { isConfigured, CONFIG, PLUGIN_VERSION } from "./config.js";
import { isConfigured, CONFIG, getDedupeScope, PLUGIN_VERSION } from "./config.js";
import { log } from "./services/logger.js";
import { checkNpmUpdate } from "./services/version-check.js";

Expand Down Expand Up @@ -55,6 +57,22 @@ function detectMemoryKeyword(text: string): boolean {
return MEMORY_KEYWORD_PATTERN.test(textWithoutCode);
}

function eventSessionID(event: { type: string; properties?: unknown }): string | undefined {
const props = event.properties as
| {
sessionID?: unknown;
info?: { id?: unknown; sessionID?: unknown };
part?: { sessionID?: unknown };
}
| undefined;
const id =
props?.sessionID ??
props?.info?.sessionID ??
props?.part?.sessionID ??
(event.type.startsWith("session.") ? props?.info?.id : undefined);
return typeof id === "string" && id ? id : undefined;
}

function isSupermemoryRecallSearch(input: Permission): boolean {
const type = String((input as { type?: unknown }).type ?? "");
const title = String((input as { title?: unknown }).title ?? "").toLowerCase();
Expand Down Expand Up @@ -83,6 +101,28 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => {
const injectedSessions = new Set<string>();
const recallSessions = new RecallSessionCache();
const activity = createMemoryActivityReporter(ctx.client);
const scope = new SessionScope({
headless: isHeadlessCommand(),
lookupParent: async (id) => {
const response = await ctx.client.session.get({ path: { id } });
if (!response.data) throw new Error(`Unable to read OpenCode session ${id}`);
return response.data.parentID;
},
});
const searchForRecall = (query: string) =>
supermemoryClient.searchMemoriesForRecall(
query,
tags.canonical,
tags.personalReads,
tags.projectReads,
{ timeoutMs: DIRECT_RECALL_TIMEOUT_MS },
);
const recallSearch = CONFIG.dedupeRecallQueries
? new RecallQueryCache(getDedupeScope).wrap(
[tags.canonical, ...tags.personalReads, ...tags.projectReads],
searchForRecall,
)
: searchForRecall;
log("Plugin init", { directory, tags, configured: isConfigured() });

if (!isConfigured()) {
Expand Down Expand Up @@ -130,6 +170,7 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => {
return {
"chat.message": async (input, output) => {
if (!isConfigured()) return;
if (await scope.skipReason(input.sessionID)) return;

const start = Date.now();

Expand Down Expand Up @@ -200,14 +241,7 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => {
prompt: userMessage,
sessionID: input.sessionID,
cache: recallSessions,
search: (query) =>
supermemoryClient.searchMemoriesForRecall(
query,
tags.canonical,
tags.personalReads,
tags.projectReads,
{ timeoutMs: DIRECT_RECALL_TIMEOUT_MS },
),
search: recallSearch,
suppressTexts: isFirstMessage
? profileRequest.then((result) =>
result?.success && result.profile
Expand Down Expand Up @@ -359,6 +393,10 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => {

event: async (input: { event: { type: string; properties?: unknown } }) => {
const props = input.event.properties as Record<string, unknown> | undefined;
if (input.event.type === "session.created" || input.event.type === "session.updated") {
const info = props?.info as { id?: string; parentID?: string } | undefined;
scope.note(info?.id, info?.parentID);
}
if (input.event.type === "session.deleted") {
const sessionID = (props?.info as { id?: string } | undefined)?.id;
if (sessionID) {
Expand All @@ -371,6 +409,10 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => {
}

if (!isConfigured()) return;
const sessionID = eventSessionID(input.event);
const skip = sessionID ? await scope.skipReason(sessionID) : scope.processSkipReason;
if (sessionID && input.event.type === "session.deleted") scope.forget(sessionID);
if (skip) return;
if (compactionHook) {
await compactionHook.event(input);
}
Expand Down
3 changes: 3 additions & 0 deletions src/services/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { join } from "node:path";
import { homedir } from "node:os";
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
import { createServer, type Server } from "node:http";
import { OPENING_PROMPTS_FILE, RECALL_QUERIES_FILE } from "./local-dedupe.js";
import { openUrl } from "./openUrl.js";
import { PLUGIN_VERSION } from "../version.js";

Expand Down Expand Up @@ -460,6 +461,8 @@ export async function settleAuth(): Promise<void> {

export async function clearCredentials(): Promise<Credentials | null> {
return withAuthLock(async (remaining) => {
fs.rmSync(RECALL_QUERIES_FILE, { force: true });
fs.rmSync(OPENING_PROMPTS_FILE, { force: true });
const credentials = loadCredentialData();
if (credentials?.type === "oauth" && credentials.refreshToken) {
await oauthRequest(issuerEndpoint(credentials.revocationEndpoint, credentials.issuer), {
Expand Down
Loading