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
5 changes: 3 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
# Changelog

## Unreleased
## 2.2.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`. 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 already captured from this machine for the same container with a one-line marker (`dedupeOpeningPrompt`), and skip recall for exact query repeats within 10 minutes (`dedupeRecallQueries`).
- 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 (`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.2

Expand Down
44 changes: 29 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,9 +185,12 @@ By default the plugin makes no Supermemory calls from its hooks for:
`SUPERMEMORY_CAPTURE_SUBAGENTS=true` to restore recall and capture for them.
- **Headless runs (OpenCode V1).** `opencode run` and `opencode github run`, which host the
server and plugins in the CLI process. Set `captureHeadless: true` or
`SUPERMEMORY_CAPTURE_HEADLESS=true` to restore them. OpenCode 2 gives plugins no signal for
`opencode run` (it may share the background server with interactive sessions), so headless
OpenCode 2 runs are still treated as interactive. `opencode run --attach` on V1 is the same.
`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,
Expand All @@ -196,8 +199,10 @@ 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. Orchestrators without an environment variable (Crystal, Claude Squad) are not
recognised. On OpenCode 2 the variables are read from the server process, so they only apply
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).

Expand All @@ -206,13 +211,22 @@ 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`, default `true`). When a session's first prompt
matches one this machine already captured for the same container tag, the capture is sent
with a one-line `[Opening prompt omitted: ...]` marker in its place. The rest of the
conversation is captured as usual. Set `SUPERMEMORY_DEDUPE_OPENING_PROMPT=false` to opt out.
- **Recall query** (`dedupeRecallQueries`, default `true`). Direct recall is skipped when the
exact same normalized query was already searched against the same container tag in the last
10 minutes. Set `SUPERMEMORY_DEDUPE_RECALL_QUERIES=false` to opt out.
- **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
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. 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

Expand Down Expand Up @@ -352,7 +366,7 @@ does not require a migration.
| `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 runs recall for repeated queries (overrides `dedupeRecallQueries`). |
| `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 @@ -444,10 +458,10 @@ scope, not from a different or malformed response.
// Recall and capture sessions started by Conductor or Vibe Kanban
"captureOrchestrated": true,

// Replace an opening prompt already captured from this machine with a marker
// Replace a 200+ character opening prompt captured from this machine in the last 24h with a marker
"dedupeOpeningPrompt": true,

// Skip recall for an exact repeat of a query made in the last 10 minutes
// Re-serve the last successful recall for a repeat of a query made in the last 10 minutes
"dedupeRecallQueries": true,
}
```
Expand Down
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.1.2",
"version": "2.2.0",
"description": "OpenCode plugin that gives coding agents persistent memory using Supermemory",
"type": "module",
"main": "dist/index.js",
Expand Down
21 changes: 18 additions & 3 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 @@ -122,9 +123,9 @@ function validateCaptureEveryNTurns(
}

function resolveFlag(envName: string, value: unknown, fallback: boolean): boolean {
const env = process.env[envName]?.trim().toLowerCase();
if (env === "true" || env === "1") return true;
if (env === "false" || env === "0") return false;
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;
}

Expand Down Expand Up @@ -166,6 +167,20 @@ export function getApiKey(): string | undefined {
return loadCredentials();
}

/** Hash of the backend URL and credential that scopes local recall caching; null without a credential. */
export function getRecallCacheScope(): 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
31 changes: 17 additions & 14 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ import {
} from "./services/memory-tool.js";
import { getTags } from "./services/tags.js";
import { isHeadlessCommand, SessionScope } from "./services/session-scope.js";
import { RecallQueryIndex } from "./services/local-dedupe.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, getRecallCacheScope, PLUGIN_VERSION } from "./config.js";
import { log } from "./services/logger.js";
import { checkNpmUpdate } from "./services/version-check.js";

Expand Down Expand Up @@ -109,7 +109,20 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => {
return response.data.parentID;
},
});
const recallQueries = CONFIG.dedupeRecallQueries ? new RecallQueryIndex() : null;
const searchForRecall = (query: string) =>
supermemoryClient.searchMemoriesForRecall(
query,
tags.canonical,
tags.personalReads,
tags.projectReads,
{ timeoutMs: DIRECT_RECALL_TIMEOUT_MS },
);
const recallSearch = CONFIG.dedupeRecallQueries
? new RecallQueryCache(getRecallCacheScope).wrap(
[tags.canonical, ...tags.personalReads, ...tags.projectReads],
searchForRecall,
)
: searchForRecall;
log("Plugin init", { directory, tags, configured: isConfigured() });

if (!isConfigured()) {
Expand Down Expand Up @@ -228,24 +241,14 @@ 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
? getInjectedProfileFactTexts(result)
: [],
)
: undefined,
skipQuery: recallQueries
? (query) => recallQueries.isRepeat(tags.canonical, query)
: undefined,
})
: Promise.resolve({
context: "",
Expand Down
2 changes: 2 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 { 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,7 @@ export async function settleAuth(): Promise<void> {

export async function clearCredentials(): Promise<Credentials | null> {
return withAuthLock(async (remaining) => {
fs.rmSync(RECALL_QUERIES_FILE, { force: true });
const credentials = loadCredentialData();
if (credentials?.type === "oauth" && credentials.refreshToken) {
await oauthRequest(issuerEndpoint(credentials.revocationEndpoint, credentials.issuer), {
Expand Down
84 changes: 71 additions & 13 deletions src/services/local-dedupe.test.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
import { describe, expect, test } from "bun:test";
import { mkdtempSync } from "node:fs";
import { mkdtempSync, statSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

import { OpeningPromptIndex, RecallQueryIndex } from "./local-dedupe.js";
import type { SearchResponse } from "./client.js";
import { OPENING_PROMPT_TTL_MS, OpeningPromptIndex, RecallQueryCache } from "./local-dedupe.js";

function tempFile(name: string): string {
return join(mkdtempSync(join(tmpdir(), "supermemory-dedupe-")), name);
}

const TASK =
"Run the nightly migration task against the staging database, verify every table row count matches the snapshot taken before the run, then write a short report with any mismatches and the exact SQL you used.";

describe("local dedupe indexes", () => {
test("sends an opening prompt once per container tag and keeps the owner session intact", () => {
test("sends a long opening prompt once per container tag and keeps the owner session intact", () => {
const index = new OpeningPromptIndex(tempFile("opening.json"));
const batch = [
{ role: "user" as const, content: "Run the nightly migration task" },
{ role: "user" as const, content: TASK },
{ role: "assistant" as const, content: "Done." },
];

Expand All @@ -23,27 +27,81 @@ describe("local dedupe indexes", () => {

expect(index.prepare("repo_a", "worker-1", batch).messages).toEqual(batch);
const repeat = index.prepare("repo_a", "worker-2", [
{ role: "user", content: "Run the nightly migration task" },
{ role: "user", content: TASK.replace(" ", " ") },
{ role: "assistant", content: "Done again." },
]);
expect(repeat.messages[0]?.content).toMatch(/^\[Opening prompt omitted: .*sha256:[0-9a-f]{12}\)\]$/);
expect(repeat.messages[1]).toEqual({ role: "assistant", content: "Done again." });
expect(index.prepare("repo_b", "worker-3", batch).messages).toEqual(batch);
});

test("leaves short opening prompts and prompts captured over 24 hours ago untouched", () => {
let now = 0;
const index = new OpeningPromptIndex(tempFile("opening.json"), () => now);
const short = [{ role: "user" as const, content: "fix the failing tests" }];
index.prepare("repo_a", "worker-1", short).commit();
expect(index.prepare("repo_a", "worker-2", short).messages).toEqual(short);

const long = [{ role: "user" as const, content: TASK }];
index.prepare("repo_a", "worker-1", long).commit();
now = OPENING_PROMPT_TTL_MS - 1;
expect(index.prepare("repo_a", "worker-2", long).messages).not.toEqual(long);
now = OPENING_PROMPT_TTL_MS;
const stale = index.prepare("repo_a", "worker-2", long);
expect(stale.messages).toEqual(long);
stale.commit();
expect(index.prepare("repo_a", "worker-3", long).messages).not.toEqual(long);
});

test("an uncommitted capture does not mark the prompt as sent", () => {
const index = new OpeningPromptIndex(tempFile("opening.json"));
const batch = [{ role: "user" as const, content: "same task" }];
const batch = [{ role: "user" as const, content: TASK }];
index.prepare("repo_a", "worker-1", batch);
expect(index.prepare("repo_a", "worker-2", batch).messages).toEqual(batch);
});

test("skips exact recall query repeats per tag within the window", () => {
const index = new RecallQueryIndex(tempFile("recall.json"), 1_000);
expect(index.isRepeat("repo_a", "How do we deploy?", 0)).toBe(false);
expect(index.isRepeat("repo_a", "how do we deploy?", 500)).toBe(true);
expect(index.isRepeat("repo_b", "How do we deploy?", 500)).toBe(false);
expect(index.isRepeat("repo_a", "How do we deploy to prod?", 500)).toBe(false);
expect(index.isRepeat("repo_a", "How do we deploy?", 1_500)).toBe(false);
test("re-serves a successful recall search per credential and tags within the window and retries failures", async () => {
let now = 0;
let scope: string | null = "backend-a:key-1";
const file = tempFile("recall.json");
const cache = new RecallQueryCache(() => scope, file, 1_000, () => now);
const calls: string[] = [];
let fail = false;
const search = async (query: string): Promise<SearchResponse> => {
calls.push(query);
return fail
? { success: false, error: "unavailable" }
: { success: true, results: [{ id: `m${calls.length}`, memory: "deploy with wrangler" }] };
};
const repoA = cache.wrap(["repo_a", "user_a"], search);

const first = await repoA("How do we deploy?");
now = 500;
expect(await repoA("how do we deploy?")).toEqual(first);
expect(calls).toHaveLength(1);
expect(statSync(file).mode & 0o777).toBe(0o600);
await cache.wrap(["repo_b", "user_a"], search)("How do we deploy?");
await repoA("How do we deploy to prod?");
expect(calls).toHaveLength(3);
now = 1_500;
await repoA("How do we deploy?");
expect(calls).toHaveLength(4);

fail = true;
expect((await repoA("What is pending?")).success).toBe(false);
fail = false;
expect((await repoA("What is pending?")).success).toBe(true);
expect(calls).toHaveLength(6);

scope = "backend-a:key-2";
await repoA("What is pending?");
expect(calls).toHaveLength(7);
scope = "backend-a:key-1";
await repoA("What is pending?");
expect(calls).toHaveLength(7);
scope = null;
await repoA("What is pending?");
await repoA("What is pending?");
expect(calls).toHaveLength(9);
});
});
Loading