Skip to content
Merged
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.3",
"version": "2.2.0",
"description": "OpenCode plugin that gives coding agents persistent memory using Supermemory",
"type": "module",
"main": "dist/index.js",
Expand Down
103 changes: 100 additions & 3 deletions src/services/capture.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { describe, expect, test } from "bun:test";
import type { Part } from "@opencode-ai/sdk";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

import {
AUTOMATIC_CAPTURE_TIMEOUT_MS,
buildCadenceBatches,
buildCaptureTurns,
buildSessionEndBatch,
createCaptureHook,
createLegacyCaptureHook,
createSessionCaptureHook,
getCaptureId,
type SessionMessage,
} from "./capture.js";
Expand Down Expand Up @@ -144,7 +148,7 @@ describe("automatic conversation capture", () => {
projectReads: [],
allReads: [],
};
const hook = createCaptureHook(ctx, tags, {
const hook = createLegacyCaptureHook(ctx, tags, {
captureEveryNTurns: 3,
memoryClient: {
ingestConversation: async (
Expand Down Expand Up @@ -241,7 +245,7 @@ describe("automatic conversation capture", () => {
},
};

const hook = createCaptureHook(
const hook = createLegacyCaptureHook(
{
directory: "/repo",
client: {
Expand Down Expand Up @@ -285,3 +289,96 @@ describe("automatic conversation capture", () => {
expect(readAttempts).toBe(3);
});
});

describe("v5 session capture", () => {
test("sends a raw delta every N turns and flushes the rest at session end", async () => {
process.env.SUPERMEMORY_SESSION_DIR = mkdtempSync(join(tmpdir(), "sm-v1-session-"));
let messages = conversation(1);
const sent: Array<{ raw: string; offset: number }> = [];
const ctx = {
directory: "/repo",
client: { session: { messages: async () => ({ data: messages }) } },
};
const tags: ResolvedTags = {
canonical: "repo_test__0123456789abcdef",
user: "repo_test__0123456789abcdef",
project: "repo_test__0123456789abcdef",
projectId: "0123456789abcdef",
projectName: "test",
personalReads: [],
projectReads: [],
allReads: [],
};
const hook = createSessionCaptureHook(ctx, tags, {
captureEveryNTurns: 2,
writer: {
addSession: async (_namespace, raw, options) => {
sent.push({ raw, offset: options.offset });
},
},
});
const idle = { event: { type: "session.idle", properties: { sessionID: "session-1" } } };

await hook.event(idle);
expect(sent).toHaveLength(0);

messages = conversation(2);
await hook.event(idle);
expect(sent).toHaveLength(1);
expect(sent[0]?.offset).toBe(0);

messages = conversation(3);
await hook.event(idle);
expect(sent).toHaveLength(1);

await hook.event({
event: { type: "session.deleted", properties: { info: { id: "session-1" } } },
});
expect(sent).toHaveLength(2);
expect(sent[1]?.offset).toBe(4);
expect(sent[1]?.raw).toContain("question 3");
});

test("sends a deleted session from its last idle snapshot when the cadence is 0", async () => {
process.env.SUPERMEMORY_SESSION_DIR = mkdtempSync(join(tmpdir(), "sm-v1-session-"));
let deleted = false;
const sent: Array<{ raw: string; offset: number }> = [];
const ctx = {
directory: "/repo",
client: {
session: {
messages: async () => ({ data: deleted ? undefined : conversation(2) }),
},
},
};
const tags: ResolvedTags = {
canonical: "repo_test__0123456789abcdef",
user: "repo_test__0123456789abcdef",
project: "repo_test__0123456789abcdef",
projectId: "0123456789abcdef",
projectName: "test",
personalReads: [],
projectReads: [],
allReads: [],
};
const hook = createSessionCaptureHook(ctx, tags, {
captureEveryNTurns: 0,
writer: {
addSession: async (_namespace, raw, options) => {
sent.push({ raw, offset: options.offset });
},
},
});

await hook.event({ event: { type: "session.idle", properties: { sessionID: "session-2" } } });
expect(sent).toHaveLength(0);

deleted = true;
await hook.event({
event: { type: "session.deleted", properties: { info: { id: "session-2" } } },
});
expect(sent).toHaveLength(1);
expect(sent[0]?.offset).toBe(0);
expect(sent[0]?.raw).toContain("question 2");
});
});
164 changes: 162 additions & 2 deletions src/services/capture.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import { createHash } from "node:crypto";
import type { Part } from "@opencode-ai/sdk";

import { CONFIG } from "../config.js";
import { CONFIG, getApiVersion } from "../config.js";
import type { ConversationMessage } from "../types/index.js";
import { supermemoryClient } from "./client.js";
import { AGENT_ENTITY_CONTEXT } from "./entity-context.js";
import { log } from "./logger.js";
import { isFullyPrivate, stripPrivateContent } from "./privacy.js";
import {
captureSession,
holdExitUntilSettled,
SESSION_CAPTURE_TIMEOUT_MS,
sessionMetadata,
type SessionWriter,
} from "./session.js";
import type { ResolvedTags } from "./tags.js";

export const AUTOMATIC_CAPTURE_TIMEOUT_MS = 3_000;
Expand Down Expand Up @@ -66,6 +73,7 @@ interface ConversationWriter {
export interface CaptureOptions {
captureEveryNTurns?: number;
memoryClient?: ConversationWriter;
writer?: SessionWriter;
onSaved?: () => void;
}

Expand Down Expand Up @@ -209,7 +217,7 @@ export function getCaptureId(
return `opencode:capture:${digest}`;
}

export function createCaptureHook(
export function createLegacyCaptureHook(
ctx: CaptureContext,
tags: ResolvedTags,
options?: CaptureOptions,
Expand Down Expand Up @@ -412,3 +420,155 @@ export function createCaptureHook(
},
};
}

export function createSessionCaptureHook(
ctx: CaptureContext,
tags: ResolvedTags,
options?: CaptureOptions,
) {
const captureEveryNTurns =
options?.captureEveryNTurns ?? CONFIG.captureEveryNTurns;
const writer = options?.writer ?? supermemoryClient;
const activeSessions = new Set<string>();
const inFlight = new Map<string, Promise<void>>();
const snapshots = new Map<string, SessionMessage[]>();

async function readMessages(sessionID: string): Promise<SessionMessage[]> {
const response = await ctx.client.session.messages({
path: { id: sessionID },
query: { directory: ctx.directory },
});
if (!Array.isArray(response) && !response.data) {
throw new Error(`Unable to read OpenCode session ${sessionID}`);
}
return Array.isArray(response) ? response : (response.data ?? []);
}

async function loadMessages(
sessionID: string,
): Promise<SessionMessage[] | undefined> {
try {
const messages = await readMessages(sessionID);
snapshots.set(sessionID, messages);
return messages;
} catch (error) {
const cached = snapshots.get(sessionID);
log(
cached
? "[capture] failed to read session transcript; using the last idle snapshot"
: "[capture] failed to read session transcript",
{ sessionID, error: String(error) },
);
return cached;
}
}

async function capture(
sessionID: string,
everyNTurns?: number,
): Promise<boolean> {
const messages = await loadMessages(sessionID);
if (!messages) return false;
return captureSession({
writer,
namespace: tags.canonical,
sessionId: sessionID,
messages,
metadata: sessionMetadata(tags.projectName, tags.projectId),
supportingContext: AGENT_ENTITY_CONTEXT,
timeoutMs: SESSION_CAPTURE_TIMEOUT_MS,
everyNTurns,
onSaved: options?.onSaved,
});
}

async function runExclusive(
sessionID: string,
task: () => Promise<void>,
): Promise<void> {
const previous = inFlight.get(sessionID) ?? Promise.resolve();
const next = previous.catch(() => undefined).then(task);
inFlight.set(sessionID, next);
holdExitUntilSettled(next);
try {
await next;
} finally {
if (inFlight.get(sessionID) === next) {
inFlight.delete(sessionID);
}
}
}

function finish(sessionID: string): void {
activeSessions.delete(sessionID);
snapshots.delete(sessionID);
}

return {
async event({ event }: { event: { type: string; properties?: unknown } }) {
const props = event.properties as Record<string, unknown> | undefined;

if (event.type === "message.updated") {
const info = props?.info as CaptureMessageInfo | undefined;
if (info?.sessionID) activeSessions.add(info.sessionID);
return;
}

if (event.type === "session.idle") {
const sessionID = props?.sessionID as string | undefined;
if (!sessionID) return;
activeSessions.add(sessionID);
await runExclusive(sessionID, async () => {
if (captureEveryNTurns > 0) {
await capture(sessionID, captureEveryNTurns);
} else {
await loadMessages(sessionID);
}
});
Comment thread
capy-ai[bot] marked this conversation as resolved.
Resolved
return;
}

if (event.type === "session.deleted") {
const sessionID = (props?.info as { id?: string } | undefined)?.id;
if (!sessionID) return;
activeSessions.add(sessionID);
await runExclusive(sessionID, async () => {
if (await capture(sessionID)) finish(sessionID);
});
return;
}

if (event.type === "server.instance.disposed") {
await Promise.all(
[...activeSessions].map((sessionID) =>
runExclusive(sessionID, async () => {
if (await capture(sessionID)) finish(sessionID);
}),
),
);
}
},
};
}

// Legacy servers, including self-hosted 0.0.8, have no session endpoint, so they keep the client-formatted capture.
export function createCaptureHook(
ctx: CaptureContext,
tags: ResolvedTags,
options?: CaptureOptions,
) {
const legacy = createLegacyCaptureHook(ctx, tags, options);
const session = createSessionCaptureHook(ctx, tags, options);
return {
async event(input: { event: { type: string; properties?: unknown } }) {
let version: "legacy" | "v5";
try {
version = getApiVersion();
} catch (error) {
log("[capture] skipped; invalid apiVersion", { error: String(error) });
return;
}
await (version === "v5" ? session : legacy).event(input);
},
};
}
56 changes: 56 additions & 0 deletions src/services/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -726,6 +726,62 @@ export class SupermemoryClient {
storedMemoryIds: savedIds,
};
}

async addSession(
namespace: string,
raw: string,
options: {
sessionId: string;
generation?: number;
offset?: number;
metadata?: Record<string, string | number>;
supportingContext?: string;
timeoutMs?: number;
},
): Promise<void> {
const baseUrl = getApiBaseUrl().replace(/\/+$/, "");
const metadata: Record<string, string | number> = {
sm_source: OPENCODE_SOURCE,
sm_client: OPENCODE_SOURCE,
sm_plugin_version: PLUGIN_VERSION,
...(options.metadata ?? {}),
};
if (options.generation != null) {
metadata.sm_session_generation = options.generation;
}
if (options.offset != null) metadata.sm_session_offset = options.offset;
const body: {
content: string;
id: string;
metadata: Record<string, string | number>;
supportingContext?: string;
} = { content: raw, id: options.sessionId, metadata };
if (options.supportingContext) {
body.supportingContext = options.supportingContext;
}

const response = await fetch(
`${baseUrl}/ns/${encodeURIComponent(namespace)}/document`,
{
method: "POST",
Comment thread
capy-ai[bot] marked this conversation as resolved.
Resolved
headers: {
Authorization: `Bearer ${await getAuthToken(undefined, baseUrl)}`,
"Content-Type": "application/json",
"x-sm-source": OPENCODE_SOURCE,
"x-sm-session": OPENCODE_SOURCE,
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(options.timeoutMs ?? TIMEOUT_MS),
},
);
if (!response.ok) {
const text = await response.text().catch(() => "");
throw Object.assign(
new Error(`Supermemory session ${response.status}: ${text.slice(0, 200)}`),
{ status: response.status },
);
}
}
}

export const supermemoryClient = new SupermemoryClient();
Loading