diff --git a/package.json b/package.json index c93529f..2891406 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/services/capture.test.ts b/src/services/capture.test.ts index 8104e01..679560e 100644 --- a/src/services/capture.test.ts +++ b/src/services/capture.test.ts @@ -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"; @@ -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 ( @@ -241,7 +245,7 @@ describe("automatic conversation capture", () => { }, }; - const hook = createCaptureHook( + const hook = createLegacyCaptureHook( { directory: "/repo", client: { @@ -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"); + }); +}); diff --git a/src/services/capture.ts b/src/services/capture.ts index aaa2af4..81af06f 100644 --- a/src/services/capture.ts +++ b/src/services/capture.ts @@ -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; @@ -66,6 +73,7 @@ interface ConversationWriter { export interface CaptureOptions { captureEveryNTurns?: number; memoryClient?: ConversationWriter; + writer?: SessionWriter; onSaved?: () => void; } @@ -209,7 +217,7 @@ export function getCaptureId( return `opencode:capture:${digest}`; } -export function createCaptureHook( +export function createLegacyCaptureHook( ctx: CaptureContext, tags: ResolvedTags, options?: CaptureOptions, @@ -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(); + const inFlight = new Map>(); + const snapshots = new Map(); + + async function readMessages(sessionID: string): Promise { + 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 { + 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 { + 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, + ): Promise { + 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 | 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); + } + }); + 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); + }, + }; +} diff --git a/src/services/client.ts b/src/services/client.ts index 34617c4..914b228 100644 --- a/src/services/client.ts +++ b/src/services/client.ts @@ -726,6 +726,62 @@ export class SupermemoryClient { storedMemoryIds: savedIds, }; } + + async addSession( + namespace: string, + raw: string, + options: { + sessionId: string; + generation?: number; + offset?: number; + metadata?: Record; + supportingContext?: string; + timeoutMs?: number; + }, + ): Promise { + const baseUrl = getApiBaseUrl().replace(/\/+$/, ""); + const metadata: Record = { + 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; + 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", + 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(); diff --git a/src/services/session.test.ts b/src/services/session.test.ts new file mode 100644 index 0000000..1b18552 --- /dev/null +++ b/src/services/session.test.ts @@ -0,0 +1,125 @@ +import { beforeEach, expect, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { captureSession, readCursor, type SessionWriter } from "./session.js"; + +type Sent = { raw: string; offset: number; generation: number }; + +function message(id: string, text: string) { + return { info: { id, role: "user" }, parts: [{ type: "text", text }] }; +} + +function recordingWriter(sent: Sent[], fail = false): SessionWriter { + return { + async addSession(_namespace, raw, options) { + if (fail) throw new Error("network down"); + sent.push({ raw, offset: options.offset, generation: options.generation }); + }, + }; +} + +function capture(sessionId: string, messages: unknown[], writer: SessionWriter) { + return captureSession({ + writer, + namespace: "ns_test", + sessionId, + messages, + logger: () => undefined, + }); +} + +beforeEach(() => { + process.env.SUPERMEMORY_SESSION_DIR = mkdtempSync(join(tmpdir(), "sm-session-")); +}); + +test("sends only the messages added since the last accepted send", async () => { + const sent: Sent[] = []; + const writer = recordingWriter(sent); + const first = [message("m1", "one"), message("m2", "two")]; + expect(await capture("s1", first, writer)).toBe(true); + expect(await capture("s1", [...first, message("m3", "three")], writer)).toBe(true); + + expect(sent.map((s) => s.offset)).toEqual([0, 2]); + expect(sent[1]?.raw).toContain("three"); + expect(sent[1]?.raw).not.toContain("one"); + expect(readCursor("s1", "ns_test").count).toBe(3); +}); + +test("a failed send keeps the cursor so the next capture resends it", async () => { + const messages = [message("m1", "one"), message("m2", "two")]; + expect(await capture("s2", messages, recordingWriter([], true))).toBe(false); + expect(readCursor("s2", "ns_test").count).toBe(0); + + const sent: Sent[] = []; + expect(await capture("s2", messages, recordingWriter(sent))).toBe(true); + expect(sent).toHaveLength(1); + expect(sent[0]?.offset).toBe(0); + expect(sent[0]?.raw).toContain("one"); + expect(readCursor("s2", "ns_test").count).toBe(2); +}); + +test("the cursor moves only after the server accepts the send", async () => { + let accept!: () => void; + const writer: SessionWriter = { + addSession: () => new Promise((resolve) => (accept = resolve)), + }; + const pending = capture("s3", [message("m1", "one")], writer); + await Bun.sleep(10); + expect(readCursor("s3", "ns_test").count).toBe(0); + + accept(); + expect(await pending).toBe(true); + expect(readCursor("s3", "ns_test").count).toBe(1); +}); + +test("a cursor accepted by one destination does not suppress another", async () => { + const messages = [message("m1", "one")]; + const sent: Sent[] = []; + expect(await capture("s4", messages, recordingWriter(sent))).toBe(true); + expect(await capture("s4", messages, recordingWriter(sent))).toBe(true); + expect(sent).toHaveLength(1); + + const previous = process.env.SUPERMEMORY_API_URL; + process.env.SUPERMEMORY_API_URL = "https://other.example.com"; + try { + expect(await capture("s4", messages, recordingWriter(sent))).toBe(true); + } finally { + if (previous === undefined) delete process.env.SUPERMEMORY_API_URL; + else process.env.SUPERMEMORY_API_URL = previous; + } + expect(sent).toHaveLength(2); + expect(sent[1]?.offset).toBe(0); +}); + +test("private blocks are stripped and fully private turns never leave the machine", async () => { + const sent: Sent[] = []; + const messages = [ + message("m1", "use sk-secret here"), + message("m2", "only secret"), + { info: { id: "m3", role: "assistant", finish: "stop" }, parts: [{ type: "text", text: "echo only secret" }] }, + message("m4", "public"), + ]; + expect(await capture("s5", messages, recordingWriter(sent))).toBe(true); + expect(sent[0]?.raw).toContain("[REDACTED]"); + expect(sent[0]?.raw).not.toContain("sk-secret"); + expect(sent[0]?.raw).not.toContain("only secret"); + expect(sent[0]?.raw).toContain("public"); + expect(readCursor("s5", "ns_test").count).toBe(2); +}); + +test("process.exit waits for an in-flight capture to finish", () => { + const sessionModule = join(import.meta.dir, "session.ts"); + const script = ` + const { holdExitUntilSettled } = await import(${JSON.stringify(sessionModule)}); + holdExitUntilSettled(new Promise((resolve) => setTimeout(() => { console.log("capture finished"); resolve(); }, 200))); + process.exit(3); + `; + const result = Bun.spawnSync([process.execPath, "-e", script], { + env: { ...process.env, HOME: mkdtempSync(join(tmpdir(), "sm-home-")) }, + }); + + expect(result.stdout.toString()).toContain("capture finished"); + expect(result.exitCode).toBe(3); +}); diff --git a/src/services/session.ts b/src/services/session.ts new file mode 100644 index 0000000..970ce1e --- /dev/null +++ b/src/services/session.ts @@ -0,0 +1,334 @@ +import { createHash } from "node:crypto"; +import { + existsSync, + mkdirSync, + readFileSync, + renameSync, + writeFileSync, +} from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; + +import { getApiBaseUrl } from "../config.js"; +import { log as defaultLog } from "./logger.js"; +import { isFullyPrivate, stripPrivateContent } from "./privacy.js"; + +export const SESSION_CAPTURE_TIMEOUT_MS = 25_000; + +function sessionDir(): string { + const override = process.env.SUPERMEMORY_SESSION_DIR?.trim(); + return override || join(homedir(), ".supermemory-opencode", "session"); +} + +export interface SessionCursor { + count: number; + generation: number; + headHash: string; +} + +export interface SessionDelta { + raw: string; + generation: number; + offset: number; + count: number; + completedTurns: number; + commit: () => void; +} + +export type SessionMetadata = Record; + +export interface SessionWriter { + addSession: ( + namespace: string, + raw: string, + options: { + sessionId: string; + generation: number; + offset: number; + metadata?: SessionMetadata; + supportingContext?: string; + timeoutMs?: number; + }, + ) => Promise; +} + +export function sessionMetadata( + projectName: string, + projectId: string, +): SessionMetadata { + return { + type: "session_turn", + project: projectName, + sm_project_id: projectId, + sm_scope: "personal", + sm_capture_mode: "automatic", + timestamp: new Date().toISOString(), + }; +} + +function sanitizeSegment(value: string): string { + return value.replace(/[^a-zA-Z0-9._-]/g, "_"); +} + +// Keyed by destination too, so a send accepted by one backend or namespace never hides history from another. +function cursorPath(sessionId: string, namespace: string): string { + const destination = createHash("sha256") + .update(`${getApiBaseUrl()}\n${namespace}`) + .digest("hex") + .slice(0, 16); + return join( + sessionDir(), + `${sanitizeSegment(sessionId)}.${destination}.json`, + ); +} + +function ensureDir(): void { + const dir = sessionDir(); + if (!existsSync(dir)) mkdirSync(dir, { recursive: true }); +} + +export function readCursor( + sessionId: string, + namespace: string, +): SessionCursor { + try { + const cursor = JSON.parse( + readFileSync(cursorPath(sessionId, namespace), "utf8"), + ) as Partial; + if ( + typeof cursor.count === "number" && + typeof cursor.generation === "number" + ) { + return { + count: cursor.count, + generation: cursor.generation, + headHash: typeof cursor.headHash === "string" ? cursor.headHash : "", + }; + } + } catch {} + return { count: 0, generation: 0, headHash: "" }; +} + +function writeCursor( + sessionId: string, + namespace: string, + cursor: SessionCursor, +): void { + ensureDir(); + const path = cursorPath(sessionId, namespace); + const temp = `${path}.${process.pid}.tmp`; + writeFileSync(temp, JSON.stringify(cursor)); + renameSync(temp, path); +} + +function messageId(message: unknown): string { + if (message && typeof message === "object") { + const record = message as { id?: unknown; info?: { id?: unknown } }; + if (typeof record.info?.id === "string") return record.info.id; + if (typeof record.id === "string") return record.id; + } + return ""; +} + +interface TranscriptPart { + type?: string; + text?: unknown; + synthetic?: boolean; + ignored?: boolean; +} + +interface TranscriptRecord { + info?: { role?: string; finish?: unknown; summary?: unknown }; + role?: string; + type?: string; + text?: unknown; + finish?: unknown; + summary?: unknown; + parts?: TranscriptPart[]; + content?: TranscriptPart[]; +} + +function asRecord(message: unknown): TranscriptRecord { + return message && typeof message === "object" + ? (message as TranscriptRecord) + : {}; +} + +function roleOf(message: TranscriptRecord): string { + return message.info?.role ?? message.role ?? message.type ?? ""; +} + +function promptText(message: TranscriptRecord): string { + const parts = message.parts ?? message.content; + if (!Array.isArray(parts)) { + return typeof message.text === "string" ? message.text : ""; + } + return parts + .filter( + (part) => + part?.type === "text" && + part.synthetic !== true && + part.ignored !== true && + typeof part.text === "string", + ) + .map((part) => part.text as string) + .join("\n"); +} + +function isFinalAssistant(message: TranscriptRecord): boolean { + const info = message.info ?? message; + return ( + roleOf(message) === "assistant" && + info.summary !== true && + typeof info.finish === "string" && + info.finish.length > 0 && + info.finish !== "tool-calls" + ); +} + +// A fully private prompt hides its whole turn, as legacy capture did; the filter is prefix-stable so cursor counts stay valid. +function withoutPrivateTurns(messages: readonly unknown[]): unknown[] { + let hidden = false; + return messages.filter((message) => { + const record = asRecord(message); + if (roleOf(record) === "user") { + const text = promptText(record).trim(); + hidden = text.length > 0 && isFullyPrivate(text); + } + return !hidden; + }); +} + +function redactPrivate(_key: string, value: unknown): unknown { + return typeof value === "string" ? stripPrivateContent(value) : value; +} + +function hashPrefix(ids: string[], count: number): string { + if (count <= 0) return ""; + return createHash("sha256") + .update(ids.slice(0, count).join("\n")) + .digest("hex"); +} + +// OpenCode has no append-only transcript file: the host returns the whole +// message history each call and compaction rewrites its head. The message count +// is the append offset; a shorter list or a changed already-sent prefix means the +// history was rewritten, so the generation is bumped and the delta restarts at 0. +export function buildSessionDelta( + sessionId: string, + namespace: string, + transcript: readonly unknown[], +): SessionDelta | null { + const messages = withoutPrivateTurns(transcript); + const previous = readCursor(sessionId, namespace); + const ids = messages.map(messageId); + let offset = previous.count; + let generation = previous.generation; + + const consumedHash = hashPrefix(ids, Math.min(previous.count, ids.length)); + if ( + messages.length < previous.count || + (previous.headHash !== "" && previous.headHash !== consumedHash) + ) { + offset = 0; + generation = previous.generation + 1; + } + + if (messages.length <= offset) return null; + + const added = messages.slice(offset); + const raw = `${added + .map((message) => JSON.stringify(message, redactPrivate)) + .join("\n")}\n`; + const count = messages.length; + const headHash = hashPrefix(ids, count); + + return { + raw, + generation, + offset, + count, + completedTurns: added.filter((message) => isFinalAssistant(asRecord(message))) + .length, + commit: () => + writeCursor(sessionId, namespace, { count, generation, headHash }), + }; +} + +const pendingCaptures = new Set>(); +let exitHeld = false; + +export function holdExitUntilSettled(work: Promise): void { + const settled = work.then( + () => undefined, + () => undefined, + ); + pendingCaptures.add(settled); + void settled.then(() => pendingCaptures.delete(settled)); + if (exitHeld) return; + exitHeld = true; + const exit = process.exit.bind(process); + process.exit = ((code?: number | string | null) => { + if (pendingCaptures.size === 0) return exit(code); + const grace = new Promise((resolve) => + setTimeout(resolve, SESSION_CAPTURE_TIMEOUT_MS), + ); + void Promise.race([Promise.all(pendingCaptures), grace]).then(() => + exit(code), + ); + return undefined as never; + }) as typeof process.exit; +} + +export async function captureSession(options: { + writer: SessionWriter; + namespace: string; + sessionId: string; + messages: readonly unknown[]; + metadata?: SessionMetadata; + supportingContext?: string; + timeoutMs?: number; + everyNTurns?: number; + onSaved?: () => void; + logger?: typeof defaultLog; +}): Promise { + const { writer, namespace, sessionId, messages } = options; + const logger = options.logger ?? defaultLog; + if (!namespace) return false; + + const delta = buildSessionDelta(sessionId, namespace, messages); + if (!delta) return true; + if (options.everyNTurns && delta.completedTurns < options.everyNTurns) { + return true; + } + + try { + await writer.addSession(namespace, delta.raw, { + sessionId, + generation: delta.generation, + offset: delta.offset, + metadata: options.metadata, + supportingContext: options.supportingContext, + timeoutMs: options.timeoutMs ?? SESSION_CAPTURE_TIMEOUT_MS, + }); + } catch (error) { + logger("[session] failed to send session session", { + sessionId, + generation: delta.generation, + offset: delta.offset, + error: error instanceof Error ? error.message : String(error), + }); + return false; + } + + delta.commit(); + options.onSaved?.(); + logger("[session] session session sent", { + sessionId, + generation: delta.generation, + offset: delta.offset, + count: delta.count, + bytes: delta.raw.length, + }); + return true; +} diff --git a/src/v2/runtime.test.ts b/src/v2/runtime.test.ts index bb05a5a..5a9fbe9 100644 --- a/src/v2/runtime.test.ts +++ b/src/v2/runtime.test.ts @@ -1,4 +1,7 @@ -import { describe, expect, test } from "bun:test"; +import { beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { COMPACTION_CONTEXT_MARKER } from "../services/compaction-prompt.js"; import { executeSupermemoryTool } from "../services/memory-tool.js"; @@ -18,6 +21,10 @@ import { type V2RuntimeDependencies, } from "./runtime.js"; +beforeEach(() => { + process.env.SUPERMEMORY_SESSION_DIR = mkdtempSync(join(tmpdir(), "sm-v2-session-")); +}); + const tags: ResolvedTags = { canonical: "repo_test__0123456789abcdef", user: "repo_test__0123456789abcdef", @@ -132,18 +139,21 @@ interface Harness { queries: string[]; writes: Array<{ customId?: string; timeoutMs?: number; metadata?: Record }>; adds: Array<{ content: string; customId?: string; metadata?: Record }>; + sessions: Array<{ raw: string; offset: number; generation: number }>; emitted: Array<{ kind?: unknown; message?: unknown }>; transcript: TranscriptMessage[]; } function harness( config: Partial = {}, + apiVersion: "legacy" | "v5" = "legacy", ): Harness { const tools = new Map(); const hooks: Harness["hooks"] = {}; const queries: string[] = []; const writes: Harness["writes"] = []; const adds: Harness["adds"] = []; + const sessions: Harness["sessions"] = []; const emitted: Harness["emitted"] = []; const state: { transcript: TranscriptMessage[] } = { transcript: [] }; const registration = { dispose: async () => undefined }; @@ -238,6 +248,13 @@ function harness( writes.push({ customId: options?.customId, timeoutMs: options?.timeoutMs, metadata }); return { success: true }; }, + addSession: async ( + _namespace: string, + raw: string, + options: { offset: number; generation: number }, + ) => { + sessions.push({ raw, offset: options.offset, generation: options.generation }); + }, addMemory: async ( content: string, _containerTag: string, @@ -270,6 +287,7 @@ function harness( latestVersion: "9.9.9", updateCommand: "bunx opencode-supermemory@latest install", }), + apiVersion: () => apiVersion, }); return { @@ -280,6 +298,7 @@ function harness( queries, writes, adds, + sessions, emitted, get transcript() { return state.transcript; @@ -446,6 +465,103 @@ describe("OpenCode 2 runtime", () => { h.runtime.cleanup(); }); + test("v5 capture honors the cadence, strips private content, and flushes before compaction", async () => { + const h = harness({ captureEveryNTurns: 2 }, "v5"); + await h.runtime.register(); + const succeeded = async (id: string) => { + await h.runtime.handleEvent({ + id, + type: "session.execution.succeeded", + data: { sessionID: "v5-cadence" }, + }); + await h.runtime.idle(); + }; + + h.transcript = [user("u1", "deploy with key abc now"), assistant("a1", "done")]; + await succeeded("v1"); + expect(h.sessions).toHaveLength(0); + + h.transcript = [ + ...h.transcript, + user("u2", "my password is hunter2"), + assistant("a2", "noted hunter2"), + user("u3", "next"), + assistant("a3", "ok"), + ]; + await succeeded("v2"); + expect(h.sessions).toHaveLength(1); + expect(h.sessions[0]?.offset).toBe(0); + expect(h.sessions[0]?.raw).toContain("[REDACTED]"); + expect(h.sessions[0]?.raw).not.toContain("key abc"); + expect(h.sessions[0]?.raw).not.toContain("hunter2"); + expect(h.sessions[0]?.raw).toContain("next"); + + h.transcript = [...h.transcript, user("u4", "one more"), assistant("a4", "sure")]; + await h.runtime.handleCompaction({ sessionID: "v5-cadence", system: [] }); + await h.runtime.idle(); + expect(h.sessions).toHaveLength(2); + expect(h.sessions[1]?.offset).toBe(4); + expect(h.sessions[1]?.raw).toContain("one more"); + + h.transcript = [...h.transcript, user("u5", "last"), assistant("a5", "bye")]; + await h.runtime.handleEvent({ + id: "v3", + type: "session.deleted", + data: { sessionID: "v5-cadence" }, + }); + expect(h.sessions).toHaveLength(3); + expect(h.sessions[2]?.raw).toContain("last"); + expect(h.writes).toHaveLength(0); + h.runtime.cleanup(); + }); + + test("v5 capture waits for session end when the cadence is 0", async () => { + const h = harness({ captureEveryNTurns: 0 }, "v5"); + await h.runtime.register(); + h.transcript = [user("u1", "question"), assistant("a1", "answer")]; + await h.runtime.handleEvent({ + id: "z1", + type: "session.execution.succeeded", + data: { sessionID: "v5-end" }, + }); + await h.runtime.idle(); + expect(h.sessions).toHaveLength(0); + + await h.runtime.handleEvent({ + id: "z2", + type: "session.deleted", + data: { sessionID: "v5-end" }, + }); + expect(h.sessions).toHaveLength(1); + expect(h.sessions[0]?.raw).toContain("question"); + h.runtime.cleanup(); + }); + + test("v5 capture sends a deleted session from its last snapshot", async () => { + const h = harness({ captureEveryNTurns: 0 }, "v5"); + await h.runtime.register(); + h.transcript = [user("u1", "question"), assistant("a1", "answer")]; + await h.runtime.handleEvent({ + id: "y1", + type: "session.execution.succeeded", + data: { sessionID: "v5-gone" }, + }); + await h.runtime.idle(); + expect(h.sessions).toHaveLength(0); + + h.ctx.session.context = async () => { + throw new Error("session not found"); + }; + await h.runtime.handleEvent({ + id: "y2", + type: "session.deleted", + data: { sessionID: "v5-gone" }, + }); + expect(h.sessions).toHaveLength(1); + expect(h.sessions[0]?.raw).toContain("question"); + h.runtime.cleanup(); + }); + test("reports tool-driven recall activity", async () => { const h = harness(); await h.runtime.register(); diff --git a/src/v2/runtime.ts b/src/v2/runtime.ts index d454709..9ae8dd8 100644 --- a/src/v2/runtime.ts +++ b/src/v2/runtime.ts @@ -3,7 +3,7 @@ import { createHash } from "node:crypto"; import type { Plugin } from "@opencode/plugin"; import type { SessionHooks } from "@opencode/plugin/promise/session"; -import { CONFIG, isConfigured, PLUGIN_VERSION } from "../config.js"; +import { CONFIG, getApiVersion, isConfigured, PLUGIN_VERSION } from "../config.js"; import { createMemoryActivityReporterFromSink, type MemoryActivityNotice, @@ -18,6 +18,12 @@ import { type CaptureTurn, } from "../services/capture.js"; import { supermemoryClient, type SupermemoryClient } from "../services/client.js"; +import { + captureSession, + holdExitUntilSettled, + SESSION_CAPTURE_TIMEOUT_MS, + sessionMetadata, +} from "../services/session.js"; import { createCompactionPrompt, fitProjectMemories, @@ -108,6 +114,7 @@ type RuntimeMemoryClient = Pick< SupermemoryClient, | "addMemory" | "ingestConversation" + | "addSession" | "getProfileScoped" | "searchMemoriesForRecall" | "searchMemoriesScoped" @@ -135,6 +142,7 @@ export interface V2RuntimeDependencies { resolveTags: typeof getTags; logger: typeof log; checkUpdate: () => Promise; + apiVersion: typeof getApiVersion; } const DEFAULT_DEPENDENCIES: V2RuntimeDependencies = { @@ -146,6 +154,7 @@ const DEFAULT_DEPENDENCIES: V2RuntimeDependencies = { logger: log, checkUpdate: () => checkNpmUpdate("opencode-supermemory", PLUGIN_VERSION, UPDATE_COMMAND), + apiVersion: getApiVersion, }; /** Minimal shape of an OpenCode 2 event as read from `ctx.event.subscribe()`. */ @@ -179,6 +188,7 @@ interface SessionState { turns: CaptureTurn[]; turnIndex: Map; completedCaptureIds: Set; + messages?: unknown[]; } interface PendingSummary { @@ -698,7 +708,13 @@ export class V2Runtime { sessionID: string; system: Array<{ type: "text"; text: string }>; }): Promise { - if (!this.#configured || !this.#deps.config.compactionEnabled) return; + if (!this.#configured) return; + if (this.#deps.apiVersion() === "v5") { + void this.#runCaptureExclusive(event.sessionID, () => + this.#captureSession(event.sessionID), + ); + } + if (!this.#deps.config.compactionEnabled) return; const memories = await this.#projectMemories(event.sessionID); event.system.push({ type: "text", text: createCompactionPrompt(memories) }); this.#deps.logger("v2 compaction context injected", { @@ -1106,6 +1122,12 @@ export class V2Runtime { async #captureCadence(sessionID: string): Promise { const state = this.#state(sessionID); + if (this.#deps.apiVersion() === "v5") { + const everyNTurns = this.#deps.config.captureEveryNTurns; + if (everyNTurns > 0) await this.#captureSession(sessionID, everyNTurns); + else await this.#readSession(sessionID); + return; + } const turns = await this.#refreshTurns(sessionID, state); for (const batch of buildCadenceBatches( turns, @@ -1116,6 +1138,10 @@ export class V2Runtime { } async #captureSessionEnd(sessionID: string): Promise { + if (this.#deps.apiVersion() === "v5") { + await this.#captureSession(sessionID); + return; + } const state = this.#state(sessionID); const turns = await this.#refreshTurns(sessionID, state); for (const batch of buildCadenceBatches( @@ -1133,6 +1159,56 @@ export class V2Runtime { } } + async #readSession( + sessionID: string, + ): Promise<{ tags: ResolvedTags; messages: unknown[] } | undefined> { + const state = this.#state(sessionID); + + let tags: ResolvedTags; + try { + tags = await this.#resolveSession(sessionID); + } catch (error) { + this.#deps.logger("v2 session capture skipped; no session directory", { + sessionID, + error: String(error), + }); + return undefined; + } + + try { + const context = (await this.#ctx.session.context({ sessionID })) as unknown; + state.messages = Array.isArray(context) ? context : []; + } catch (error) { + this.#deps.logger( + state.messages + ? "v2 session transcript read failed; using the last snapshot" + : "v2 session transcript read failed", + { sessionID, error: String(error) }, + ); + if (!state.messages) return undefined; + } + return { tags, messages: state.messages }; + } + + async #captureSession(sessionID: string, everyNTurns?: number): Promise { + const session = await this.#readSession(sessionID); + if (!session) return; + const { tags, messages } = session; + + await captureSession({ + writer: this.#deps.memoryClient, + namespace: tags.canonical, + sessionId: sessionID, + messages, + metadata: sessionMetadata(tags.projectName, tags.projectId), + supportingContext: AGENT_ENTITY_CONTEXT, + timeoutMs: SESSION_CAPTURE_TIMEOUT_MS, + everyNTurns, + onSaved: () => this.#activity.saved(), + logger: this.#deps.logger, + }); + } + async #flushAll(allowInactive = false): Promise { const sessions = [...this.#states.keys()]; const pending = new Set( @@ -1157,6 +1233,7 @@ export class V2Runtime { const previous = this.#captureInFlight.get(sessionID) ?? Promise.resolve(); const next = previous.catch(() => undefined).then(task); this.#captureInFlight.set(sessionID, next); + holdExitUntilSettled(next); try { await next; } catch (error) { diff --git a/src/version.ts b/src/version.ts index 76d5b83..57237f3 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,3 +1,3 @@ // AUTO-GENERATED by scripts/sync-version.mjs — do not edit by hand. // Sourced from package.json "version" so the two cannot drift. -export const PLUGIN_VERSION = "2.1.3"; +export const PLUGIN_VERSION = "2.2.0";