From ab75f014dac0cb64ca07a1aa52a251e0c6b7ee27 Mon Sep 17 00:00:00 2001 From: Prasanna A P <106952318+Prasanna721@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:55:14 -0700 Subject: [PATCH 1/7] Migrate to V5 API and improve how sessions feed memory Send the session to the V5 /ns/{tag}/document route and let the server derive memory from it, instead of summarizing on the client. Preserves the existing memory metadata and entity context so recall is unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) --- src/services/capture.test.ts | 287 ------------------------------ src/services/capture.ts | 326 ++++------------------------------- src/services/client.ts | 57 ++++++ src/services/session.ts | 209 ++++++++++++++++++++++ src/v2/runtime.test.ts | 136 +-------------- src/v2/runtime.ts | 268 +++++----------------------- 6 files changed, 337 insertions(+), 946 deletions(-) delete mode 100644 src/services/capture.test.ts create mode 100644 src/services/session.ts diff --git a/src/services/capture.test.ts b/src/services/capture.test.ts deleted file mode 100644 index 8104e01..0000000 --- a/src/services/capture.test.ts +++ /dev/null @@ -1,287 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import type { Part } from "@opencode-ai/sdk"; - -import { - AUTOMATIC_CAPTURE_TIMEOUT_MS, - buildCadenceBatches, - buildCaptureTurns, - buildSessionEndBatch, - createCaptureHook, - getCaptureId, - type SessionMessage, -} from "./capture.js"; -import { SupermemoryClient } from "./client.js"; -import type { ResolvedTags } from "./tags.js"; - -function textPart( - messageID: string, - text: string, - synthetic = false, -): Part { - return { - id: `part-${messageID}`, - sessionID: "session-1", - messageID, - type: "text", - text, - synthetic, - }; -} - -function user(id: string, text: string): SessionMessage { - return { - info: { id, role: "user", sessionID: "session-1" }, - parts: [textPart(id, text)], - }; -} - -function assistant(id: string, text: string): SessionMessage { - return { - info: { - id, - role: "assistant", - sessionID: "session-1", - finish: "stop", - }, - parts: [textPart(id, text)], - }; -} - -function conversation(turnCount: number): SessionMessage[] { - return Array.from({ length: turnCount }, (_, index) => { - const turn = index + 1; - return [ - user(`user-${turn}`, `question ${turn}`), - assistant(`assistant-${turn}`, `answer ${turn}`), - ]; - }).flat(); -} - -describe("automatic conversation capture", () => { - test("builds fixed cadence batches and a final remainder", () => { - const turns = buildCaptureTurns(conversation(7)); - const cadence = buildCadenceBatches(turns, 3); - const sessionEnd = buildSessionEndBatch(turns, 3); - - expect(cadence.map((batch) => [batch.startTurn, batch.endTurn])).toEqual([ - [1, 3], - [4, 6], - ]); - expect(sessionEnd && [sessionEnd.startTurn, sessionEnd.endTurn]).toEqual([ - 7, 7, - ]); - }); - - test("uses a stable capture ID within the API length limit", () => { - const batch = buildCadenceBatches( - [ - { - id: `msg_${"a".repeat(48)}`, - messages: [{ role: "user", content: "test" }], - }, - ], - 1, - )[0]!; - const sessionID = `ses_${"b".repeat(48)}`; - const captureId = getCaptureId(sessionID, batch); - - expect(captureId).toBe(getCaptureId(sessionID, batch)); - expect(captureId.length).toBeLessThanOrEqual(100); - expect(captureId).not.toContain(sessionID); - }); - - test("excludes synthetic context and protects private turns", () => { - const messages = [ - { - ...user("user-1", "real prompt"), - parts: [ - textPart("user-1", "injected recall", true), - textPart("user-1", "real prompt"), - ], - }, - assistant("assistant-1", "real answer"), - user("user-2", "secret prompt"), - assistant("assistant-2", "secret-derived answer"), - user("user-3", "token secret"), - assistant("assistant-3", "safe answer"), - ]; - - const turns = buildCaptureTurns(messages); - expect(turns[0]?.messages).toEqual([ - { role: "user", content: "real prompt" }, - { role: "assistant", content: "real answer" }, - ]); - expect(turns[1]?.messages).toEqual([]); - expect(turns[2]?.messages[0]).toEqual({ - role: "user", - content: "token [REDACTED]", - }); - }); - - test("captures on the third idle and flushes the final remainder once", async () => { - let messages = conversation(1); - const writes: Array<{ - conversationId: string; - metadata?: Record; - customId?: string; - timeoutMs?: 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 = createCaptureHook(ctx, tags, { - captureEveryNTurns: 3, - memoryClient: { - ingestConversation: async ( - conversationId, - _conversationMessages, - _containerTags, - metadata, - options, - ) => { - writes.push({ - conversationId, - metadata, - customId: options?.customId, - timeoutMs: options?.timeoutMs, - }); - return { success: true }; - }, - }, - }); - - await hook.event({ - event: { - type: "session.idle", - properties: { sessionID: "session-1" }, - }, - }); - messages = conversation(3); - await hook.event({ - event: { - type: "session.idle", - properties: { sessionID: "session-1" }, - }, - }); - await hook.event({ - event: { - type: "session.idle", - properties: { sessionID: "session-1" }, - }, - }); - - expect(writes).toHaveLength(1); - expect(writes[0]?.metadata?.captureReason).toBe("cadence"); - expect(writes[0]?.timeoutMs).toBe(AUTOMATIC_CAPTURE_TIMEOUT_MS); - - messages = conversation(4); - await hook.event({ - event: { - type: "session.idle", - properties: { sessionID: "session-1" }, - }, - }); - await hook.event({ - event: { - type: "session.deleted", - properties: { info: { id: "session-1" } }, - }, - }); - await hook.event({ - event: { - type: "session.deleted", - properties: { info: { id: "session-1" } }, - }, - }); - - expect(writes).toHaveLength(2); - expect(writes[1]?.metadata?.captureReason).toBe("session_end"); - expect(writes[0]?.customId).not.toBe(writes[1]?.customId); - }); - - test("retains terminal capture state after failure and retries with bounded SDK options", async () => { - const sdkOptions: Array<{ timeout?: number; maxRetries?: number }> = []; - let attempts = 0; - let readAttempts = 0; - const memoryClient = new SupermemoryClient(); - ( - memoryClient as unknown as { - client: { - memories: { - add: ( - payload: unknown, - options?: { timeout?: number; maxRetries?: number }, - ) => Promise<{ id: string }>; - }; - }; - } - ).client = { - memories: { - add: async (_payload, options) => { - sdkOptions.push(options ?? {}); - attempts += 1; - if (attempts === 1) throw new Error("temporary capture failure"); - return { id: "memory-1" }; - }, - }, - }; - - const hook = createCaptureHook( - { - directory: "/repo", - client: { - session: { - messages: async () => { - readAttempts += 1; - if (readAttempts === 1) { - throw new Error("temporary transcript read failure"); - } - return { data: conversation(1) }; - }, - }, - }, - }, - { - canonical: "repo_test__0123456789abcdef", - user: "repo_test__0123456789abcdef", - project: "repo_test__0123456789abcdef", - projectId: "0123456789abcdef", - projectName: "test", - personalReads: [], - projectReads: [], - allReads: [], - }, - { captureEveryNTurns: 0, memoryClient }, - ); - - for (let attempt = 0; attempt < 4; attempt += 1) { - await hook.event({ - event: { - type: "session.deleted", - properties: { info: { id: "session-1" } }, - }, - }); - } - - expect(sdkOptions).toEqual([ - { timeout: AUTOMATIC_CAPTURE_TIMEOUT_MS, maxRetries: 0 }, - { timeout: AUTOMATIC_CAPTURE_TIMEOUT_MS, maxRetries: 0 }, - ]); - expect(readAttempts).toBe(3); - }); -}); diff --git a/src/services/capture.ts b/src/services/capture.ts index aaa2af4..3298f10 100644 --- a/src/services/capture.ts +++ b/src/services/capture.ts @@ -1,15 +1,15 @@ -import { createHash } from "node:crypto"; import type { Part } from "@opencode-ai/sdk"; -import { CONFIG } 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 type { ResolvedTags } from "./tags.js"; - -export const AUTOMATIC_CAPTURE_TIMEOUT_MS = 3_000; +import { + captureSession, + SESSION_CAPTURE_TIMEOUT_MS, + sessionMetadata, + type SessionWriter, +} from "./session.js"; interface CaptureMessageInfo { id: string; @@ -24,17 +24,6 @@ export interface SessionMessage { parts?: Part[]; } -export interface CaptureTurn { - id: string; - messages: ConversationMessage[]; -} - -export interface CaptureBatch { - startTurn: number; - endTurn: number; - turns: CaptureTurn[]; -} - interface CaptureContext { directory: string; client: { @@ -49,180 +38,21 @@ interface CaptureContext { }; } -interface ConversationWriter { - ingestConversation: ( - conversationId: string, - messages: ConversationMessage[], - containerTags: string[], - metadata?: Record, - options?: { - defaultEntityContext?: string; - customId?: string; - timeoutMs?: number; - }, - ) => Promise<{ success: boolean; error?: string }>; -} - export interface CaptureOptions { - captureEveryNTurns?: number; - memoryClient?: ConversationWriter; + writer?: SessionWriter; onSaved?: () => void; } -function extractText(parts: Part[] | undefined): string { - const text = (parts ?? []) - .filter( - (part): part is Part & { type: "text"; text: string } => - part.type === "text" && - part.synthetic !== true && - part.ignored !== true && - typeof part.text === "string", - ) - .map((part) => part.text) - .join("\n") - .trim(); - - if (!text || isFullyPrivate(text)) return ""; - return stripPrivateContent(text).trim(); -} - -function isFinalAssistantMessage(info: CaptureMessageInfo): boolean { - return ( - info.role === "assistant" && - info.summary !== true && - typeof info.finish === "string" && - info.finish.length > 0 && - info.finish !== "tool-calls" - ); -} - -export function buildCaptureTurns(messages: SessionMessage[]): CaptureTurn[] { - const turns: CaptureTurn[] = []; - let current: - | { - id: string; - messages: ConversationMessage[]; - fullyPrivate: boolean; - complete: boolean; - } - | undefined; - - const finishCurrent = () => { - if (current?.complete) { - turns.push({ - id: current.id, - messages: current.fullyPrivate ? [] : current.messages, - }); - } - current = undefined; - }; - - for (const message of messages) { - const { info } = message; - - if (info.role === "user") { - finishCurrent(); - const rawText = (message.parts ?? []) - .filter( - (part): part is Part & { type: "text"; text: string } => - part.type === "text" && - part.synthetic !== true && - part.ignored !== true && - typeof part.text === "string", - ) - .map((part) => part.text) - .join("\n") - .trim(); - const text = extractText(message.parts); - current = { - id: info.id, - messages: text ? [{ role: "user", content: text }] : [], - fullyPrivate: rawText.length > 0 && isFullyPrivate(rawText), - complete: false, - }; - continue; - } - - if (!current || info.role !== "assistant" || info.summary === true) { - continue; - } - - const text = extractText(message.parts); - if (text && !current.fullyPrivate) { - current.messages.push({ role: "assistant", content: text }); - } - if (isFinalAssistantMessage(info)) { - current.complete = true; - } - } - - finishCurrent(); - return turns; -} - -export function buildCadenceBatches( - turns: CaptureTurn[], - captureEveryNTurns: number, -): CaptureBatch[] { - if (captureEveryNTurns <= 0) return []; - - const batches: CaptureBatch[] = []; - const completeBatchCount = Math.floor(turns.length / captureEveryNTurns); - for (let index = 0; index < completeBatchCount; index += 1) { - const start = index * captureEveryNTurns; - const end = start + captureEveryNTurns; - batches.push({ - startTurn: start + 1, - endTurn: end, - turns: turns.slice(start, end), - }); - } - return batches; -} - -export function buildSessionEndBatch( - turns: CaptureTurn[], - captureEveryNTurns: number, -): CaptureBatch | null { - if (turns.length === 0) return null; - - const remainder = - captureEveryNTurns > 0 ? turns.length % captureEveryNTurns : turns.length; - if (remainder === 0) return null; - - const start = turns.length - remainder; - return { - startTurn: start + 1, - endTurn: turns.length, - turns: turns.slice(start), - }; -} - -export function getCaptureId( - sessionID: string, - batch: CaptureBatch, -): string { - const firstTurn = batch.turns[0]?.id ?? String(batch.startTurn); - const lastTurn = batch.turns.at(-1)?.id ?? String(batch.endTurn); - const fingerprint = `${sessionID}:${firstTurn}:${lastTurn}`; - const digest = createHash("sha256").update(fingerprint).digest("hex"); - return `opencode:capture:${digest}`; -} - export function createCaptureHook( ctx: CaptureContext, tags: ResolvedTags, options?: CaptureOptions, ) { - const captureEveryNTurns = - options?.captureEveryNTurns ?? CONFIG.captureEveryNTurns; - const memoryClient = options?.memoryClient ?? supermemoryClient; - const snapshots = new Map(); + const writer = options?.writer ?? supermemoryClient; const activeSessions = new Set(); - const completedCaptureIds = new Set(); const inFlight = new Map>(); - async function refreshSnapshot(sessionID: string): Promise { + async function readMessages(sessionID: string): Promise { const response = await ctx.client.session.messages({ path: { id: sessionID }, query: { directory: ctx.directory }, @@ -230,111 +60,30 @@ export function createCaptureHook( if (!Array.isArray(response) && !response.data) { throw new Error(`Unable to read OpenCode session ${sessionID}`); } - const rawMessages = Array.isArray(response) ? response : response.data ?? []; - const turns = buildCaptureTurns(rawMessages); - snapshots.set(sessionID, turns); - activeSessions.add(sessionID); - return turns; + return Array.isArray(response) ? response : (response.data ?? []); } - async function saveBatch( - sessionID: string, - batch: CaptureBatch, - reason: "cadence" | "session_end", - ): Promise { - const captureId = getCaptureId(sessionID, batch); - if (completedCaptureIds.has(captureId)) return true; - - const messages = batch.turns.flatMap((turn) => turn.messages); - if (messages.length === 0) { - completedCaptureIds.add(captureId); - return true; - } - - let result: { success: boolean; error?: string }; + async function capture(sessionID: string): Promise { + let messages: SessionMessage[]; try { - result = await memoryClient.ingestConversation( - `${sessionID}:${batch.startTurn}-${batch.endTurn}`, - messages, - [tags.canonical], - { - project: tags.projectName, - sm_project_id: tags.projectId, - sm_scope: "personal", - sm_capture_mode: "automatic", - captureReason: reason, - sessionId: sessionID, - turnStart: batch.startTurn, - turnEnd: batch.endTurn, - }, - { - defaultEntityContext: AGENT_ENTITY_CONTEXT, - customId: captureId, - timeoutMs: AUTOMATIC_CAPTURE_TIMEOUT_MS, - }, - ); + messages = await readMessages(sessionID); } catch (error) { - result = { - success: false, - error: error instanceof Error ? error.message : String(error), - }; - } - - if (result.success) { - completedCaptureIds.add(captureId); - options?.onSaved?.(); - log("[capture] conversation batch saved", { + log("[capture] failed to read session transcript", { sessionID, - reason, - startTurn: batch.startTurn, - endTurn: batch.endTurn, + error: String(error), }); - return true; + return false; } - - log("[capture] failed to save conversation batch", { - sessionID, - reason, - startTurn: batch.startTurn, - endTurn: batch.endTurn, - error: result.error, + return captureSession({ + writer, + namespace: tags.canonical, + sessionId: sessionID, + messages, + metadata: sessionMetadata(tags.projectName, tags.projectId), + supportingContext: AGENT_ENTITY_CONTEXT, + timeoutMs: SESSION_CAPTURE_TIMEOUT_MS, + onSaved: options?.onSaved, }); - return false; - } - - async function captureCadence( - sessionID: string, - turns: CaptureTurn[], - ): Promise { - let complete = true; - for (const batch of buildCadenceBatches(turns, captureEveryNTurns)) { - if (!(await saveBatch(sessionID, batch, "cadence"))) { - complete = false; - } - } - return complete; - } - - async function captureSessionEnd(sessionID: string): Promise { - let turns = snapshots.get(sessionID); - if (!turns) { - try { - turns = await refreshSnapshot(sessionID); - } catch (error) { - log("[capture] failed to read terminal session", { - sessionID, - error: String(error), - }); - return false; - } - } - - const cadenceComplete = await captureCadence(sessionID, turns); - const finalBatch = buildSessionEndBatch(turns, captureEveryNTurns); - const finalComplete = finalBatch - ? await saveBatch(sessionID, finalBatch, "session_end") - : true; - return cadenceComplete && finalComplete; } async function runExclusive( @@ -367,32 +116,18 @@ export function createCaptureHook( const sessionID = props?.sessionID as string | undefined; if (!sessionID) return; activeSessions.add(sessionID); - await runExclusive(sessionID, async () => { - try { - const turns = await refreshSnapshot(sessionID); - await captureCadence(sessionID, turns); - } catch (error) { - log("[capture] failed to process idle session", { - sessionID, - error: String(error), - }); - } + await capture(sessionID); }); return; } if (event.type === "session.deleted") { - const sessionInfo = props?.info as { id?: string } | undefined; - const sessionID = sessionInfo?.id; + const sessionID = (props?.info as { id?: string } | undefined)?.id; if (!sessionID) return; activeSessions.add(sessionID); - await runExclusive(sessionID, async () => { - if (await captureSessionEnd(sessionID)) { - snapshots.delete(sessionID); - activeSessions.delete(sessionID); - } + if (await capture(sessionID)) activeSessions.delete(sessionID); }); return; } @@ -401,10 +136,7 @@ export function createCaptureHook( await Promise.all( [...activeSessions].map((sessionID) => runExclusive(sessionID, async () => { - if (await captureSessionEnd(sessionID)) { - snapshots.delete(sessionID); - activeSessions.delete(sessionID); - } + if (await capture(sessionID)) activeSessions.delete(sessionID); }), ), ); diff --git a/src/services/client.ts b/src/services/client.ts index 0604f7a..b46adaf 100644 --- a/src/services/client.ts +++ b/src/services/client.ts @@ -736,6 +736,63 @@ 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 { + if (!SUPERMEMORY_API_KEY) throw new Error("SUPERMEMORY_API_KEY not set"); + 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 ${SUPERMEMORY_API_KEY}`, + "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.ts b/src/services/session.ts new file mode 100644 index 0000000..3059181 --- /dev/null +++ b/src/services/session.ts @@ -0,0 +1,209 @@ +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 { log as defaultLog } from "./logger.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; + 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, "_"); +} + +function cursorPath(sessionId: string): string { + return join(sessionDir(), `${sanitizeSegment(sessionId)}.json`); +} + +function ensureDir(): void { + const dir = sessionDir(); + if (!existsSync(dir)) mkdirSync(dir, { recursive: true }); +} + +export function readCursor(sessionId: string): SessionCursor { + try { + const cursor = JSON.parse( + readFileSync(cursorPath(sessionId), "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, cursor: SessionCursor): void { + ensureDir(); + const path = cursorPath(sessionId); + 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 ""; +} + +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, + messages: readonly unknown[], +): SessionDelta | null { + const previous = readCursor(sessionId); + 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 raw = `${messages + .slice(offset) + .map((message) => JSON.stringify(message)) + .join("\n")}\n`; + const count = messages.length; + const headHash = hashPrefix(ids, count); + + return { + raw, + generation, + offset, + count, + commit: () => writeCursor(sessionId, { count, generation, headHash }), + }; +} + +export async function captureSession(options: { + writer: SessionWriter; + namespace: string; + sessionId: string; + messages: readonly unknown[]; + metadata?: SessionMetadata; + supportingContext?: string; + timeoutMs?: 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, messages); + if (!delta) 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..99d2525 100644 --- a/src/v2/runtime.test.ts +++ b/src/v2/runtime.test.ts @@ -6,14 +6,11 @@ import { DEFAULT_RECALL_DIRECTIVE } from "../services/recall.js"; import type { ResolvedTags } from "../services/tags.js"; import { applyInjection, - buildTranscriptTurns, buildV2RecallDirective, - mergeTurns, SUPERMEMORY_RECALL_TOOL_NAME, SUPERMEMORY_TOOL_NAME, V2Runtime, type RequestMessage, - type TranscriptMessage, type V2Context, type V2RuntimeDependencies, } from "./runtime.js"; @@ -29,18 +26,6 @@ const tags: ResolvedTags = { allReads: [], }; -function user(id: string, text: string): TranscriptMessage { - return { id, type: "user", text }; -} - -function assistant( - id: string, - text: string, - finish: string = "stop", -): TranscriptMessage { - return { id, type: "assistant", finish, content: [{ type: "text", text }] }; -} - function request(id: string, text: string): RequestMessage { return { id, @@ -55,49 +40,6 @@ function texts(message: RequestMessage): string[] { ); } -describe("OpenCode 2 transcript capture", () => { - test("groups completed turns and protects private content", () => { - const turns = buildTranscriptTurns([ - { id: "sys", type: "system", text: "injected" }, - user("u1", "real prompt"), - assistant("a1", "calling a tool", "tool-calls"), - assistant("a2", "real answer"), - user("u2", "secret prompt"), - assistant("a3", "secret answer"), - user("u3", "token secret"), - assistant("a4", "safe answer"), - user("u4", "still streaming"), - ]); - - expect(turns.map((turn) => turn.id)).toEqual(["u1", "u2", "u3"]); - expect(turns[0]?.messages).toEqual([ - { role: "user", content: "real prompt" }, - { role: "assistant", content: "calling a tool" }, - { role: "assistant", content: "real answer" }, - ]); - expect(turns[1]?.messages).toEqual([]); - expect(turns[2]?.messages[0]).toEqual({ - role: "user", - content: "token [REDACTED]", - }); - }); - - test("keeps turn positions stable when the transcript is compacted", () => { - const existing = mergeTurns( - [], - new Map(), - buildTranscriptTurns([user("u1", "one"), assistant("a1", "1")]), - ); - const index = new Map([["u1", 0]]); - mergeTurns( - existing, - index, - buildTranscriptTurns([user("u2", "two"), assistant("a2", "2")]), - ); - expect(existing.map((turn) => turn.id)).toEqual(["u1", "u2"]); - }); -}); - describe("OpenCode 2 request injection", () => { test("points the advisory directive at the recall helper", () => { const directive = buildV2RecallDirective(DEFAULT_RECALL_DIRECTIVE); @@ -133,7 +75,7 @@ interface Harness { writes: Array<{ customId?: string; timeoutMs?: number; metadata?: Record }>; adds: Array<{ content: string; customId?: string; metadata?: Record }>; emitted: Array<{ kind?: unknown; message?: unknown }>; - transcript: TranscriptMessage[]; + transcript: unknown[]; } function harness( @@ -145,7 +87,7 @@ function harness( const writes: Harness["writes"] = []; const adds: Harness["adds"] = []; const emitted: Harness["emitted"] = []; - const state: { transcript: TranscriptMessage[] } = { transcript: [] }; + const state: { transcript: unknown[] } = { transcript: [] }; const registration = { dispose: async () => undefined }; const ctx = { @@ -255,7 +197,6 @@ function harness( config: { recallMode: "direct", injectProfile: true, - captureEveryNTurns: 1, compactionEnabled: true, keywordPatterns: ["remember"], maxProjectMemories: 10, @@ -284,7 +225,7 @@ function harness( get transcript() { return state.transcript; }, - set transcript(value: TranscriptMessage[]) { + set transcript(value: unknown[]) { state.transcript = value; }, }; @@ -375,77 +316,6 @@ describe("OpenCode 2 runtime", () => { h.runtime.cleanup(); }); - test("captures completed turns idempotently and saves compaction summaries", async () => { - const h = harness(); - await h.runtime.register(); - - h.transcript = [user("u1", "question 1"), assistant("a1", "answer 1")]; - await h.runtime.handleEvent({ - id: "e1", - type: "session.execution.succeeded", - data: { sessionID: "s1" }, - }); - await h.runtime.idle(); - await h.runtime.handleEvent({ - id: "e2", - type: "session.execution.succeeded", - data: { sessionID: "s1" }, - }); - await h.runtime.idle(); - expect(h.writes).toHaveLength(1); - expect(h.writes[0]?.customId).toStartWith("opencode:capture:"); - expect(h.writes[0]?.timeoutMs).toBe(3_000); - expect(h.writes[0]?.metadata).toMatchObject({ - captureReason: "cadence", - sm_capture_mode: "automatic", - }); - - // Compaction truncates the transcript; the earlier turn keeps its slot. - h.transcript = [ - { id: "c1", type: "compaction" }, - user("u2", "question 2"), - assistant("a2", "answer 2"), - ]; - await h.runtime.handleEvent({ - id: "e3", - type: "session.execution.succeeded", - data: { sessionID: "s1" }, - }); - await h.runtime.idle(); - expect(h.writes).toHaveLength(2); - expect(h.writes[1]?.customId).not.toBe(h.writes[0]?.customId); - - const summary = "Summary ".repeat(20); - await h.runtime.handleEvent({ - id: "e4", - type: "session.compaction.ended", - data: { sessionID: "s1", text: summary, reason: "auto" }, - }); - await h.runtime.handleEvent({ - id: "e4", - type: "session.compaction.ended", - data: { sessionID: "s1", text: summary, reason: "auto" }, - }); - expect(h.adds).toHaveLength(1); - expect(h.adds[0]?.customId).toStartWith("opencode:compaction:"); - expect(h.adds[0]?.metadata).toMatchObject({ sm_capture_mode: "compaction" }); - - const system: Array<{ type: "text"; text: string }> = []; - await h.runtime.handleCompaction({ sessionID: "s1", system }); - expect(system[0]?.text).toContain(COMPACTION_CONTEXT_MARKER); - expect(system[0]?.text).toContain("Build: bun run build"); - - await h.runtime.handleEvent({ - id: "e5", - type: "session.deleted", - data: { sessionID: "s1" }, - }); - expect(h.runtime.trackedSessionCount).toBe(0); - expect(h.writes).toHaveLength(2); - expect(h.emitted.filter((event) => event.kind === "saved")).toHaveLength(3); - 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 2fee56b..5af1ac3 100644 --- a/src/v2/runtime.ts +++ b/src/v2/runtime.ts @@ -9,15 +9,12 @@ import { type MemoryActivityNotice, type MemoryActivityReporter, } from "../services/activity.js"; -import { - AUTOMATIC_CAPTURE_TIMEOUT_MS, - buildCadenceBatches, - buildSessionEndBatch, - getCaptureId, - type CaptureBatch, - type CaptureTurn, -} from "../services/capture.js"; import { supermemoryClient, type SupermemoryClient } from "../services/client.js"; +import { + captureSession, + SESSION_CAPTURE_TIMEOUT_MS, + sessionMetadata, +} from "../services/session.js"; import { createCompactionPrompt, fitProjectMemories, @@ -38,7 +35,6 @@ import { type SupermemoryToolArgs, } from "../services/memory-tool.js"; import { RECALL_PERMISSION } from "../services/opencode-permissions.js"; -import { isFullyPrivate, stripPrivateContent } from "../services/privacy.js"; import { buildDirectRecallResult, buildRecallDirective, @@ -62,6 +58,7 @@ const SYNTHETIC_METADATA_KEY = "supermemory"; const UPDATE_COMMAND = "bunx opencode-supermemory@latest install"; const MAX_DISPATCHES_PER_SESSION = 8; const MIN_SUMMARY_CHARS = 100; +const SUMMARY_SAVE_TIMEOUT_MS = 3_000; export const SUPERMEMORY_TOOL_NAME = "supermemory"; export const SUPERMEMORY_RECALL_TOOL_NAME = "supermemory_recall"; @@ -105,7 +102,7 @@ export const SUPERMEMORY_RECALL_INPUT = { type RuntimeMemoryClient = Pick< SupermemoryClient, | "addMemory" - | "ingestConversation" + | "addSession" | "getProfileScoped" | "searchMemoriesForRecall" | "searchMemoriesScoped" @@ -118,7 +115,6 @@ type RuntimeConfig = Pick< typeof CONFIG, | "recallMode" | "injectProfile" - | "captureEveryNTurns" | "compactionEnabled" | "keywordPatterns" | "maxProjectMemories" @@ -152,15 +148,6 @@ export interface V2Event { data?: Record; } -/** Minimal shape of a persisted OpenCode 2 transcript message. */ -export interface TranscriptMessage { - id: string; - type: string; - text?: string; - finish?: string; - content?: ReadonlyArray<{ type: string; text?: string }>; -} - interface Injection { start: string[]; end: string[]; @@ -173,9 +160,6 @@ interface SessionState { injectedInitialContext: boolean; dispatches: Map>; dispatchOrder: string[]; - turns: CaptureTurn[]; - turnIndex: Map; - completedCaptureIds: Set; } interface PendingSummary { @@ -294,105 +278,6 @@ export function applyInjection( } } -function sanitizeCaptureText(text: string): string { - if (!text || isFullyPrivate(text)) return ""; - return stripPrivateContent(text).trim(); -} - -function isFinalAssistant(message: TranscriptMessage): boolean { - return ( - typeof message.finish === "string" && - message.finish.length > 0 && - message.finish !== "tool-calls" - ); -} - -function assistantText(message: TranscriptMessage): string { - return (message.content ?? []) - .filter((part) => part.type === "text" && typeof part.text === "string") - .map((part) => part.text as string) - .join("\n") - .trim(); -} - -/** - * Groups an OpenCode 2 transcript into completed user/assistant turns using - * the same rules as the V1 capture hook: synthetic and system messages are - * ignored, `` content is redacted, and a fully private prompt hides - * its whole turn. - */ -export function buildTranscriptTurns( - messages: ReadonlyArray, -): CaptureTurn[] { - const turns: CaptureTurn[] = []; - let current: - | { - id: string; - messages: CaptureTurn["messages"]; - fullyPrivate: boolean; - complete: boolean; - } - | undefined; - - const finish = () => { - if (current?.complete) { - turns.push({ - id: current.id, - messages: current.fullyPrivate ? [] : current.messages, - }); - } - current = undefined; - }; - - for (const message of messages) { - if (message.type === "user") { - finish(); - const rawText = (message.text ?? "").trim(); - const text = sanitizeCaptureText(rawText); - current = { - id: message.id, - messages: text ? [{ role: "user", content: text }] : [], - fullyPrivate: rawText.length > 0 && isFullyPrivate(rawText), - complete: false, - }; - continue; - } - - if (!current || message.type !== "assistant") continue; - - const text = sanitizeCaptureText(assistantText(message)); - if (text && !current.fullyPrivate) { - current.messages.push({ role: "assistant", content: text }); - } - if (isFinalAssistant(message)) current.complete = true; - } - - finish(); - return turns; -} - -/** - * Merges freshly read turns into the session's cumulative turn list. The - * transcript OpenCode returns may shrink after compaction, so turn positions - * (and therefore capture IDs) are anchored to the first time a turn was seen. - */ -export function mergeTurns( - existing: CaptureTurn[], - index: Map, - incoming: CaptureTurn[], -): CaptureTurn[] { - for (const turn of incoming) { - const position = index.get(turn.id); - if (position === undefined) { - index.set(turn.id, existing.length); - existing.push(turn); - } else { - existing[position] = turn; - } - } - return existing; -} - export class EventDeduper { readonly #limit: number; readonly #seen = new Set(); @@ -585,7 +470,6 @@ export class V2Runtime { hooks: ["session.context", "session.compaction", "permission.evaluate", "tool.execute"], activity: this.#emitActivity ? "rpc" : "log-only", recallMode: this.#deps.config.recallMode, - captureEveryNTurns: this.#deps.config.captureEveryNTurns, compactionEnabled: this.#deps.config.compactionEnabled, }); } @@ -710,7 +594,7 @@ export class V2Runtime { case "session.execution.succeeded": { if (!sessionID) return; void this.#runCaptureExclusive(sessionID, () => - this.#captureCadence(sessionID), + this.#captureSession(sessionID), ); return; } @@ -719,7 +603,7 @@ export class V2Runtime { if (!sessionID || event.data?.reason !== "shutdown") return; if (!this.#states.has(sessionID)) return; void this.#runCaptureExclusive(sessionID, () => - this.#captureSessionEnd(sessionID), + this.#captureSession(sessionID), ); return; } @@ -730,7 +614,7 @@ export class V2Runtime { this.#recall.delete(sessionID); if (!state) return; await this.#runCaptureExclusive(sessionID, () => - this.#captureSessionEnd(sessionID), + this.#captureSession(sessionID), ); this.#states.delete(sessionID); return; @@ -805,9 +689,6 @@ export class V2Runtime { injectedInitialContext: false, dispatches: new Map(), dispatchOrder: [], - turns: [], - turnIndex: new Map(), - completedCaptureIds: new Set(), }; this.#states.set(sessionID, state); return state; @@ -1004,118 +885,47 @@ export class V2Runtime { } } - async #refreshTurns(sessionID: string, state: SessionState): Promise { + async #sessionMessages(sessionID: string): Promise { + const messages = (await this.#ctx.session.context({ sessionID })) as unknown; + return Array.isArray(messages) ? messages : []; + } + + async #captureSession(sessionID: string): Promise { + this.#state(sessionID); + + let tags: ResolvedTags; try { - const messages = (await this.#ctx.session.context({ sessionID })) as unknown; - if (Array.isArray(messages)) { - mergeTurns( - state.turns, - state.turnIndex, - buildTranscriptTurns(messages as TranscriptMessage[]), - ); - } + tags = await this.#resolveSession(sessionID); } catch (error) { - this.#deps.logger("v2 capture transcript read failed; using cached turns", { + this.#deps.logger("v2 session capture skipped; no session directory", { sessionID, error: String(error), }); - } - return state.turns; - } - - async #saveBatch( - sessionID: string, - state: SessionState, - batch: CaptureBatch, - reason: "cadence" | "session_end", - ): Promise { - const captureId = getCaptureId(sessionID, batch); - if (state.completedCaptureIds.has(captureId)) return true; - const messages = batch.turns.flatMap((turn) => turn.messages); - if (messages.length === 0) { - state.completedCaptureIds.add(captureId); - return true; + return; } - let result: { success: boolean; error?: string }; + let messages: unknown[]; try { - const tags = await this.#resolveSession(sessionID); - result = await this.#deps.memoryClient.ingestConversation( - `${sessionID}:${batch.startTurn}-${batch.endTurn}`, - messages, - [tags.canonical], - { - project: tags.projectName, - sm_project_id: tags.projectId, - sm_scope: "personal", - sm_capture_mode: "automatic", - captureReason: reason, - sessionId: sessionID, - turnStart: batch.startTurn, - turnEnd: batch.endTurn, - }, - { - defaultEntityContext: AGENT_ENTITY_CONTEXT, - customId: captureId, - timeoutMs: AUTOMATIC_CAPTURE_TIMEOUT_MS, - }, - ); + messages = await this.#sessionMessages(sessionID); } catch (error) { - result = { - success: false, - error: error instanceof Error ? error.message : String(error), - }; - } - - if (result.success) { - state.completedCaptureIds.add(captureId); - this.#activity.saved(); - this.#deps.logger("[capture] conversation batch saved", { + this.#deps.logger("v2 session transcript read failed", { sessionID, - reason, - startTurn: batch.startTurn, - endTurn: batch.endTurn, + error: String(error), }); - return true; + return; } - this.#deps.logger("[capture] failed to save conversation batch", { - sessionID, - reason, - startTurn: batch.startTurn, - endTurn: batch.endTurn, - error: result.error, + 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, + onSaved: () => this.#activity.saved(), + logger: this.#deps.logger, }); - return false; - } - - async #captureCadence(sessionID: string): Promise { - const state = this.#state(sessionID); - const turns = await this.#refreshTurns(sessionID, state); - for (const batch of buildCadenceBatches( - turns, - this.#deps.config.captureEveryNTurns, - )) { - await this.#saveBatch(sessionID, state, batch, "cadence"); - } - } - - async #captureSessionEnd(sessionID: string): Promise { - const state = this.#state(sessionID); - const turns = await this.#refreshTurns(sessionID, state); - for (const batch of buildCadenceBatches( - turns, - this.#deps.config.captureEveryNTurns, - )) { - await this.#saveBatch(sessionID, state, batch, "cadence"); - } - const finalBatch = buildSessionEndBatch( - turns, - this.#deps.config.captureEveryNTurns, - ); - if (finalBatch) { - await this.#saveBatch(sessionID, state, finalBatch, "session_end"); - } } async #flushAll(allowInactive = false): Promise { @@ -1126,7 +936,7 @@ export class V2Runtime { await Promise.all([ ...sessions.map((sessionID) => this.#runCaptureExclusive(sessionID, () => - this.#captureSessionEnd(sessionID), + this.#captureSession(sessionID), ), ), ...[...pending].map((sessionID) => @@ -1195,7 +1005,7 @@ export class V2Runtime { { customId: summary.customId, entityContext: AGENT_ENTITY_CONTEXT, - timeoutMs: AUTOMATIC_CAPTURE_TIMEOUT_MS, + timeoutMs: SUMMARY_SAVE_TIMEOUT_MS, }, ); if (result.success) { From 479958dcc180f96d54b32152fffac6921fc2f60b Mon Sep 17 00:00:00 2001 From: MaheshtheDev <38828053+MaheshtheDev@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:01:27 +0000 Subject: [PATCH 2/7] fix: advance the session cursor before sending so opencode run keeps it opencode run exits on session idle without waiting for plugin hooks, so the response never arrived and every run resent the whole session from offset 0. The cursor now moves when the send starts and rolls back if the send fails. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- src/services/session.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/services/session.ts b/src/services/session.ts index 3059181..c7db527 100644 --- a/src/services/session.ts +++ b/src/services/session.ts @@ -30,6 +30,7 @@ export interface SessionDelta { offset: number; count: number; commit: () => void; + rollback: () => void; } export type SessionMetadata = Record; @@ -156,9 +157,11 @@ export function buildSessionDelta( offset, count, commit: () => writeCursor(sessionId, { count, generation, headHash }), + rollback: () => writeCursor(sessionId, previous), }; } +// The cursor advances before the send because `opencode run` exits on idle without waiting for plugins; a failed send rolls it back. export async function captureSession(options: { writer: SessionWriter; namespace: string; @@ -177,6 +180,7 @@ export async function captureSession(options: { const delta = buildSessionDelta(sessionId, messages); if (!delta) return true; + delta.commit(); try { await writer.addSession(namespace, delta.raw, { sessionId, @@ -187,6 +191,7 @@ export async function captureSession(options: { timeoutMs: options.timeoutMs ?? SESSION_CAPTURE_TIMEOUT_MS, }); } catch (error) { + delta.rollback(); logger("[session] failed to send session session", { sessionId, generation: delta.generation, @@ -196,7 +201,6 @@ export async function captureSession(options: { return false; } - delta.commit(); options.onSaved?.(); logger("[session] session session sent", { sessionId, From 520170d7682ca4cea330ab2ac302702bf21a800e Mon Sep 17 00:00:00 2001 From: Ishaan Gupta Date: Tue, 17 Nov 2026 13:46:22 +0530 Subject: [PATCH 3/7] fix: use OAuth-aware token for session capture --- src/services/client.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/services/client.ts b/src/services/client.ts index f7178a4..914b228 100644 --- a/src/services/client.ts +++ b/src/services/client.ts @@ -739,7 +739,6 @@ export class SupermemoryClient { timeoutMs?: number; }, ): Promise { - if (!SUPERMEMORY_API_KEY) throw new Error("SUPERMEMORY_API_KEY not set"); const baseUrl = getApiBaseUrl().replace(/\/+$/, ""); const metadata: Record = { sm_source: OPENCODE_SOURCE, @@ -766,7 +765,7 @@ export class SupermemoryClient { { method: "POST", headers: { - Authorization: `Bearer ${SUPERMEMORY_API_KEY}`, + Authorization: `Bearer ${await getAuthToken(undefined, baseUrl)}`, "Content-Type": "application/json", "x-sm-source": OPENCODE_SOURCE, "x-sm-session": OPENCODE_SOURCE, From 68e35606c41524d681205a366de2882e5b55ae6f Mon Sep 17 00:00:00 2001 From: Ishaan Gupta Date: Tue, 17 Nov 2026 14:46:13 +0530 Subject: [PATCH 4/7] fix: finish session capture before opencode exits --- src/services/capture.ts | 2 + src/services/session.test.ts | 90 ++++++++++++++++++++++++++++++++++++ src/services/session.ts | 31 +++++++++++-- src/v2/runtime.ts | 2 + 4 files changed, 120 insertions(+), 5 deletions(-) create mode 100644 src/services/session.test.ts diff --git a/src/services/capture.ts b/src/services/capture.ts index 3298f10..54495d8 100644 --- a/src/services/capture.ts +++ b/src/services/capture.ts @@ -6,6 +6,7 @@ import { log } from "./logger.js"; import type { ResolvedTags } from "./tags.js"; import { captureSession, + holdExitUntilSettled, SESSION_CAPTURE_TIMEOUT_MS, sessionMetadata, type SessionWriter, @@ -93,6 +94,7 @@ export function createCaptureHook( const previous = inFlight.get(sessionID) ?? Promise.resolve(); const next = previous.catch(() => undefined).then(task); inFlight.set(sessionID, next); + holdExitUntilSettled(next); try { await next; } finally { diff --git a/src/services/session.test.ts b/src/services/session.test.ts new file mode 100644 index 0000000..fcdddf2 --- /dev/null +++ b/src/services/session.test.ts @@ -0,0 +1,90 @@ +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").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").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").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").count).toBe(0); + + accept(); + expect(await pending).toBe(true); + expect(readCursor("s3").count).toBe(1); +}); + +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 index c7db527..550d9c2 100644 --- a/src/services/session.ts +++ b/src/services/session.ts @@ -30,7 +30,6 @@ export interface SessionDelta { offset: number; count: number; commit: () => void; - rollback: () => void; } export type SessionMetadata = Record; @@ -157,11 +156,34 @@ export function buildSessionDelta( offset, count, commit: () => writeCursor(sessionId, { count, generation, headHash }), - rollback: () => writeCursor(sessionId, previous), }; } -// The cursor advances before the send because `opencode run` exits on idle without waiting for plugins; a failed send rolls it back. +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; @@ -180,7 +202,6 @@ export async function captureSession(options: { const delta = buildSessionDelta(sessionId, messages); if (!delta) return true; - delta.commit(); try { await writer.addSession(namespace, delta.raw, { sessionId, @@ -191,7 +212,6 @@ export async function captureSession(options: { timeoutMs: options.timeoutMs ?? SESSION_CAPTURE_TIMEOUT_MS, }); } catch (error) { - delta.rollback(); logger("[session] failed to send session session", { sessionId, generation: delta.generation, @@ -201,6 +221,7 @@ export async function captureSession(options: { return false; } + delta.commit(); options.onSaved?.(); logger("[session] session session sent", { sessionId, diff --git a/src/v2/runtime.ts b/src/v2/runtime.ts index 3f485e2..bb0396d 100644 --- a/src/v2/runtime.ts +++ b/src/v2/runtime.ts @@ -12,6 +12,7 @@ import { import { supermemoryClient, type SupermemoryClient } from "../services/client.js"; import { captureSession, + holdExitUntilSettled, SESSION_CAPTURE_TIMEOUT_MS, sessionMetadata, } from "../services/session.js"; @@ -957,6 +958,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) { From 353bafac128b4b4d385b1b8c8953394c6080fb69 Mon Sep 17 00:00:00 2001 From: MaheshtheDev <38828053+MaheshtheDev@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:53:00 +0000 Subject: [PATCH 5/7] fix: keep private content, capture cadence and legacy servers working with session capture Strip blocks and drop fully private turns before the raw session leaves the machine, honor captureEveryNTurns (flushing before V2 compaction), keep the client-formatted capture for legacy API servers, and key session cursors by backend URL and namespace. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- src/services/capture.test.ts | 341 +++++++++++++++++++++++++++++ src/services/capture.ts | 414 ++++++++++++++++++++++++++++++++++- src/services/session.test.ts | 45 +++- src/services/session.ts | 126 +++++++++-- src/v2/runtime.test.ts | 229 ++++++++++++++++++- src/v2/runtime.ts | 279 +++++++++++++++++++++-- 6 files changed, 1395 insertions(+), 39 deletions(-) create mode 100644 src/services/capture.test.ts diff --git a/src/services/capture.test.ts b/src/services/capture.test.ts new file mode 100644 index 0000000..d652a83 --- /dev/null +++ b/src/services/capture.test.ts @@ -0,0 +1,341 @@ +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, + createLegacyCaptureHook, + createSessionCaptureHook, + getCaptureId, + type SessionMessage, +} from "./capture.js"; +import { SupermemoryClient } from "./client.js"; +import type { ResolvedTags } from "./tags.js"; + +function textPart( + messageID: string, + text: string, + synthetic = false, +): Part { + return { + id: `part-${messageID}`, + sessionID: "session-1", + messageID, + type: "text", + text, + synthetic, + }; +} + +function user(id: string, text: string): SessionMessage { + return { + info: { id, role: "user", sessionID: "session-1" }, + parts: [textPart(id, text)], + }; +} + +function assistant(id: string, text: string): SessionMessage { + return { + info: { + id, + role: "assistant", + sessionID: "session-1", + finish: "stop", + }, + parts: [textPart(id, text)], + }; +} + +function conversation(turnCount: number): SessionMessage[] { + return Array.from({ length: turnCount }, (_, index) => { + const turn = index + 1; + return [ + user(`user-${turn}`, `question ${turn}`), + assistant(`assistant-${turn}`, `answer ${turn}`), + ]; + }).flat(); +} + +describe("automatic conversation capture", () => { + test("builds fixed cadence batches and a final remainder", () => { + const turns = buildCaptureTurns(conversation(7)); + const cadence = buildCadenceBatches(turns, 3); + const sessionEnd = buildSessionEndBatch(turns, 3); + + expect(cadence.map((batch) => [batch.startTurn, batch.endTurn])).toEqual([ + [1, 3], + [4, 6], + ]); + expect(sessionEnd && [sessionEnd.startTurn, sessionEnd.endTurn]).toEqual([ + 7, 7, + ]); + }); + + test("uses a stable capture ID within the API length limit", () => { + const batch = buildCadenceBatches( + [ + { + id: `msg_${"a".repeat(48)}`, + messages: [{ role: "user", content: "test" }], + }, + ], + 1, + )[0]!; + const sessionID = `ses_${"b".repeat(48)}`; + const captureId = getCaptureId(sessionID, batch); + + expect(captureId).toBe(getCaptureId(sessionID, batch)); + expect(captureId.length).toBeLessThanOrEqual(100); + expect(captureId).not.toContain(sessionID); + }); + + test("excludes synthetic context and protects private turns", () => { + const messages = [ + { + ...user("user-1", "real prompt"), + parts: [ + textPart("user-1", "injected recall", true), + textPart("user-1", "real prompt"), + ], + }, + assistant("assistant-1", "real answer"), + user("user-2", "secret prompt"), + assistant("assistant-2", "secret-derived answer"), + user("user-3", "token secret"), + assistant("assistant-3", "safe answer"), + ]; + + const turns = buildCaptureTurns(messages); + expect(turns[0]?.messages).toEqual([ + { role: "user", content: "real prompt" }, + { role: "assistant", content: "real answer" }, + ]); + expect(turns[1]?.messages).toEqual([]); + expect(turns[2]?.messages[0]).toEqual({ + role: "user", + content: "token [REDACTED]", + }); + }); + + test("captures on the third idle and flushes the final remainder once", async () => { + let messages = conversation(1); + const writes: Array<{ + conversationId: string; + metadata?: Record; + customId?: string; + timeoutMs?: 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 = createLegacyCaptureHook(ctx, tags, { + captureEveryNTurns: 3, + memoryClient: { + ingestConversation: async ( + conversationId, + _conversationMessages, + _containerTags, + metadata, + options, + ) => { + writes.push({ + conversationId, + metadata, + customId: options?.customId, + timeoutMs: options?.timeoutMs, + }); + return { success: true }; + }, + }, + }); + + await hook.event({ + event: { + type: "session.idle", + properties: { sessionID: "session-1" }, + }, + }); + messages = conversation(3); + await hook.event({ + event: { + type: "session.idle", + properties: { sessionID: "session-1" }, + }, + }); + await hook.event({ + event: { + type: "session.idle", + properties: { sessionID: "session-1" }, + }, + }); + + expect(writes).toHaveLength(1); + expect(writes[0]?.metadata?.captureReason).toBe("cadence"); + expect(writes[0]?.timeoutMs).toBe(AUTOMATIC_CAPTURE_TIMEOUT_MS); + + messages = conversation(4); + await hook.event({ + event: { + type: "session.idle", + properties: { sessionID: "session-1" }, + }, + }); + await hook.event({ + event: { + type: "session.deleted", + properties: { info: { id: "session-1" } }, + }, + }); + await hook.event({ + event: { + type: "session.deleted", + properties: { info: { id: "session-1" } }, + }, + }); + + expect(writes).toHaveLength(2); + expect(writes[1]?.metadata?.captureReason).toBe("session_end"); + expect(writes[0]?.customId).not.toBe(writes[1]?.customId); + }); + + test("retains terminal capture state after failure and retries with bounded SDK options", async () => { + const sdkOptions: Array<{ timeout?: number; maxRetries?: number }> = []; + let attempts = 0; + let readAttempts = 0; + const memoryClient = new SupermemoryClient(); + ( + memoryClient as unknown as { + client: { + memories: { + add: ( + payload: unknown, + options?: { timeout?: number; maxRetries?: number }, + ) => Promise<{ id: string }>; + }; + }; + } + ).client = { + memories: { + add: async (_payload, options) => { + sdkOptions.push(options ?? {}); + attempts += 1; + if (attempts === 1) throw new Error("temporary capture failure"); + return { id: "memory-1" }; + }, + }, + }; + + const hook = createLegacyCaptureHook( + { + directory: "/repo", + client: { + session: { + messages: async () => { + readAttempts += 1; + if (readAttempts === 1) { + throw new Error("temporary transcript read failure"); + } + return { data: conversation(1) }; + }, + }, + }, + }, + { + canonical: "repo_test__0123456789abcdef", + user: "repo_test__0123456789abcdef", + project: "repo_test__0123456789abcdef", + projectId: "0123456789abcdef", + projectName: "test", + personalReads: [], + projectReads: [], + allReads: [], + }, + { captureEveryNTurns: 0, memoryClient }, + ); + + for (let attempt = 0; attempt < 4; attempt += 1) { + await hook.event({ + event: { + type: "session.deleted", + properties: { info: { id: "session-1" } }, + }, + }); + } + + expect(sdkOptions).toEqual([ + { timeout: AUTOMATIC_CAPTURE_TIMEOUT_MS, maxRetries: 0 }, + { timeout: AUTOMATIC_CAPTURE_TIMEOUT_MS, maxRetries: 0 }, + ]); + 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"); + }); +}); diff --git a/src/services/capture.ts b/src/services/capture.ts index 54495d8..b060ba6 100644 --- a/src/services/capture.ts +++ b/src/services/capture.ts @@ -1,9 +1,12 @@ +import { createHash } from "node:crypto"; import type { Part } from "@opencode-ai/sdk"; +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 type { ResolvedTags } from "./tags.js"; +import { isFullyPrivate, stripPrivateContent } from "./privacy.js"; import { captureSession, holdExitUntilSettled, @@ -11,6 +14,9 @@ import { sessionMetadata, type SessionWriter, } from "./session.js"; +import type { ResolvedTags } from "./tags.js"; + +export const AUTOMATIC_CAPTURE_TIMEOUT_MS = 3_000; interface CaptureMessageInfo { id: string; @@ -25,6 +31,17 @@ export interface SessionMessage { parts?: Part[]; } +export interface CaptureTurn { + id: string; + messages: ConversationMessage[]; +} + +export interface CaptureBatch { + startTurn: number; + endTurn: number; + turns: CaptureTurn[]; +} + interface CaptureContext { directory: string; client: { @@ -39,16 +56,378 @@ interface CaptureContext { }; } +interface ConversationWriter { + ingestConversation: ( + conversationId: string, + messages: ConversationMessage[], + containerTags: string[], + metadata?: Record, + options?: { + defaultEntityContext?: string; + customId?: string; + timeoutMs?: number; + }, + ) => Promise<{ success: boolean; error?: string }>; +} + export interface CaptureOptions { + captureEveryNTurns?: number; + memoryClient?: ConversationWriter; writer?: SessionWriter; onSaved?: () => void; } -export function createCaptureHook( +function extractText(parts: Part[] | undefined): string { + const text = (parts ?? []) + .filter( + (part): part is Part & { type: "text"; text: string } => + part.type === "text" && + part.synthetic !== true && + part.ignored !== true && + typeof part.text === "string", + ) + .map((part) => part.text) + .join("\n") + .trim(); + + if (!text || isFullyPrivate(text)) return ""; + return stripPrivateContent(text).trim(); +} + +function isFinalAssistantMessage(info: CaptureMessageInfo): boolean { + return ( + info.role === "assistant" && + info.summary !== true && + typeof info.finish === "string" && + info.finish.length > 0 && + info.finish !== "tool-calls" + ); +} + +export function buildCaptureTurns(messages: SessionMessage[]): CaptureTurn[] { + const turns: CaptureTurn[] = []; + let current: + | { + id: string; + messages: ConversationMessage[]; + fullyPrivate: boolean; + complete: boolean; + } + | undefined; + + const finishCurrent = () => { + if (current?.complete) { + turns.push({ + id: current.id, + messages: current.fullyPrivate ? [] : current.messages, + }); + } + current = undefined; + }; + + for (const message of messages) { + const { info } = message; + + if (info.role === "user") { + finishCurrent(); + const rawText = (message.parts ?? []) + .filter( + (part): part is Part & { type: "text"; text: string } => + part.type === "text" && + part.synthetic !== true && + part.ignored !== true && + typeof part.text === "string", + ) + .map((part) => part.text) + .join("\n") + .trim(); + const text = extractText(message.parts); + current = { + id: info.id, + messages: text ? [{ role: "user", content: text }] : [], + fullyPrivate: rawText.length > 0 && isFullyPrivate(rawText), + complete: false, + }; + continue; + } + + if (!current || info.role !== "assistant" || info.summary === true) { + continue; + } + + const text = extractText(message.parts); + if (text && !current.fullyPrivate) { + current.messages.push({ role: "assistant", content: text }); + } + if (isFinalAssistantMessage(info)) { + current.complete = true; + } + } + + finishCurrent(); + return turns; +} + +export function buildCadenceBatches( + turns: CaptureTurn[], + captureEveryNTurns: number, +): CaptureBatch[] { + if (captureEveryNTurns <= 0) return []; + + const batches: CaptureBatch[] = []; + const completeBatchCount = Math.floor(turns.length / captureEveryNTurns); + for (let index = 0; index < completeBatchCount; index += 1) { + const start = index * captureEveryNTurns; + const end = start + captureEveryNTurns; + batches.push({ + startTurn: start + 1, + endTurn: end, + turns: turns.slice(start, end), + }); + } + return batches; +} + +export function buildSessionEndBatch( + turns: CaptureTurn[], + captureEveryNTurns: number, +): CaptureBatch | null { + if (turns.length === 0) return null; + + const remainder = + captureEveryNTurns > 0 ? turns.length % captureEveryNTurns : turns.length; + if (remainder === 0) return null; + + const start = turns.length - remainder; + return { + startTurn: start + 1, + endTurn: turns.length, + turns: turns.slice(start), + }; +} + +export function getCaptureId( + sessionID: string, + batch: CaptureBatch, +): string { + const firstTurn = batch.turns[0]?.id ?? String(batch.startTurn); + const lastTurn = batch.turns.at(-1)?.id ?? String(batch.endTurn); + const fingerprint = `${sessionID}:${firstTurn}:${lastTurn}`; + const digest = createHash("sha256").update(fingerprint).digest("hex"); + return `opencode:capture:${digest}`; +} + +export function createLegacyCaptureHook( ctx: CaptureContext, tags: ResolvedTags, options?: CaptureOptions, ) { + const captureEveryNTurns = + options?.captureEveryNTurns ?? CONFIG.captureEveryNTurns; + const memoryClient = options?.memoryClient ?? supermemoryClient; + const snapshots = new Map(); + const activeSessions = new Set(); + const completedCaptureIds = new Set(); + const inFlight = new Map>(); + + async function refreshSnapshot(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}`); + } + const rawMessages = Array.isArray(response) ? response : response.data ?? []; + const turns = buildCaptureTurns(rawMessages); + snapshots.set(sessionID, turns); + activeSessions.add(sessionID); + return turns; + } + + async function saveBatch( + sessionID: string, + batch: CaptureBatch, + reason: "cadence" | "session_end", + ): Promise { + const captureId = getCaptureId(sessionID, batch); + if (completedCaptureIds.has(captureId)) return true; + + const messages = batch.turns.flatMap((turn) => turn.messages); + if (messages.length === 0) { + completedCaptureIds.add(captureId); + return true; + } + + let result: { success: boolean; error?: string }; + try { + result = await memoryClient.ingestConversation( + `${sessionID}:${batch.startTurn}-${batch.endTurn}`, + messages, + [tags.canonical], + { + project: tags.projectName, + sm_project_id: tags.projectId, + sm_scope: "personal", + sm_capture_mode: "automatic", + captureReason: reason, + sessionId: sessionID, + turnStart: batch.startTurn, + turnEnd: batch.endTurn, + }, + { + defaultEntityContext: AGENT_ENTITY_CONTEXT, + customId: captureId, + timeoutMs: AUTOMATIC_CAPTURE_TIMEOUT_MS, + }, + ); + } catch (error) { + result = { + success: false, + error: error instanceof Error ? error.message : String(error), + }; + } + + if (result.success) { + completedCaptureIds.add(captureId); + options?.onSaved?.(); + log("[capture] conversation batch saved", { + sessionID, + reason, + startTurn: batch.startTurn, + endTurn: batch.endTurn, + }); + return true; + } + + log("[capture] failed to save conversation batch", { + sessionID, + reason, + startTurn: batch.startTurn, + endTurn: batch.endTurn, + error: result.error, + }); + return false; + } + + async function captureCadence( + sessionID: string, + turns: CaptureTurn[], + ): Promise { + let complete = true; + for (const batch of buildCadenceBatches(turns, captureEveryNTurns)) { + if (!(await saveBatch(sessionID, batch, "cadence"))) { + complete = false; + } + } + return complete; + } + + async function captureSessionEnd(sessionID: string): Promise { + let turns = snapshots.get(sessionID); + if (!turns) { + try { + turns = await refreshSnapshot(sessionID); + } catch (error) { + log("[capture] failed to read terminal session", { + sessionID, + error: String(error), + }); + return false; + } + } + + const cadenceComplete = await captureCadence(sessionID, turns); + const finalBatch = buildSessionEndBatch(turns, captureEveryNTurns); + const finalComplete = finalBatch + ? await saveBatch(sessionID, finalBatch, "session_end") + : true; + return cadenceComplete && finalComplete; + } + + 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); + try { + await next; + } finally { + if (inFlight.get(sessionID) === next) { + inFlight.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 () => { + try { + const turns = await refreshSnapshot(sessionID); + await captureCadence(sessionID, turns); + } catch (error) { + log("[capture] failed to process idle session", { + sessionID, + error: String(error), + }); + } + }); + return; + } + + if (event.type === "session.deleted") { + const sessionInfo = props?.info as { id?: string } | undefined; + const sessionID = sessionInfo?.id; + if (!sessionID) return; + activeSessions.add(sessionID); + + await runExclusive(sessionID, async () => { + if (await captureSessionEnd(sessionID)) { + snapshots.delete(sessionID); + activeSessions.delete(sessionID); + } + }); + return; + } + + if (event.type === "server.instance.disposed") { + await Promise.all( + [...activeSessions].map((sessionID) => + runExclusive(sessionID, async () => { + if (await captureSessionEnd(sessionID)) { + snapshots.delete(sessionID); + activeSessions.delete(sessionID); + } + }), + ), + ); + } + }, + }; +} + +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>(); @@ -64,7 +443,10 @@ export function createCaptureHook( return Array.isArray(response) ? response : (response.data ?? []); } - async function capture(sessionID: string): Promise { + async function capture( + sessionID: string, + everyNTurns?: number, + ): Promise { let messages: SessionMessage[]; try { messages = await readMessages(sessionID); @@ -83,6 +465,7 @@ export function createCaptureHook( metadata: sessionMetadata(tags.projectName, tags.projectId), supportingContext: AGENT_ENTITY_CONTEXT, timeoutMs: SESSION_CAPTURE_TIMEOUT_MS, + everyNTurns, onSaved: options?.onSaved, }); } @@ -118,8 +501,9 @@ export function createCaptureHook( const sessionID = props?.sessionID as string | undefined; if (!sessionID) return; activeSessions.add(sessionID); + if (captureEveryNTurns <= 0) return; await runExclusive(sessionID, async () => { - await capture(sessionID); + await capture(sessionID, captureEveryNTurns); }); return; } @@ -146,3 +530,25 @@ export function createCaptureHook( }, }; } + +// 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/session.test.ts b/src/services/session.test.ts index fcdddf2..1b18552 100644 --- a/src/services/session.test.ts +++ b/src/services/session.test.ts @@ -44,20 +44,20 @@ test("sends only the messages added since the last accepted send", async () => { 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").count).toBe(3); + 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").count).toBe(0); + 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").count).toBe(2); + expect(readCursor("s2", "ns_test").count).toBe(2); }); test("the cursor moves only after the server accepts the send", async () => { @@ -67,11 +67,46 @@ test("the cursor moves only after the server accepts the send", async () => { }; const pending = capture("s3", [message("m1", "one")], writer); await Bun.sleep(10); - expect(readCursor("s3").count).toBe(0); + expect(readCursor("s3", "ns_test").count).toBe(0); accept(); expect(await pending).toBe(true); - expect(readCursor("s3").count).toBe(1); + 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", () => { diff --git a/src/services/session.ts b/src/services/session.ts index 550d9c2..970ce1e 100644 --- a/src/services/session.ts +++ b/src/services/session.ts @@ -9,7 +9,9 @@ import { 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; @@ -29,6 +31,7 @@ export interface SessionDelta { generation: number; offset: number; count: number; + completedTurns: number; commit: () => void; } @@ -67,8 +70,16 @@ function sanitizeSegment(value: string): string { return value.replace(/[^a-zA-Z0-9._-]/g, "_"); } -function cursorPath(sessionId: string): string { - return join(sessionDir(), `${sanitizeSegment(sessionId)}.json`); +// 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 { @@ -76,10 +87,13 @@ function ensureDir(): void { if (!existsSync(dir)) mkdirSync(dir, { recursive: true }); } -export function readCursor(sessionId: string): SessionCursor { +export function readCursor( + sessionId: string, + namespace: string, +): SessionCursor { try { const cursor = JSON.parse( - readFileSync(cursorPath(sessionId), "utf8"), + readFileSync(cursorPath(sessionId, namespace), "utf8"), ) as Partial; if ( typeof cursor.count === "number" && @@ -95,9 +109,13 @@ export function readCursor(sessionId: string): SessionCursor { return { count: 0, generation: 0, headHash: "" }; } -function writeCursor(sessionId: string, cursor: SessionCursor): void { +function writeCursor( + sessionId: string, + namespace: string, + cursor: SessionCursor, +): void { ensureDir(); - const path = cursorPath(sessionId); + const path = cursorPath(sessionId, namespace); const temp = `${path}.${process.pid}.tmp`; writeFileSync(temp, JSON.stringify(cursor)); renameSync(temp, path); @@ -112,6 +130,79 @@ function messageId(message: unknown): string { 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") @@ -125,9 +216,11 @@ function hashPrefix(ids: string[], count: number): string { // history was rewritten, so the generation is bumped and the delta restarts at 0. export function buildSessionDelta( sessionId: string, - messages: readonly unknown[], + namespace: string, + transcript: readonly unknown[], ): SessionDelta | null { - const previous = readCursor(sessionId); + const messages = withoutPrivateTurns(transcript); + const previous = readCursor(sessionId, namespace); const ids = messages.map(messageId); let offset = previous.count; let generation = previous.generation; @@ -143,9 +236,9 @@ export function buildSessionDelta( if (messages.length <= offset) return null; - const raw = `${messages - .slice(offset) - .map((message) => JSON.stringify(message)) + 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); @@ -155,7 +248,10 @@ export function buildSessionDelta( generation, offset, count, - commit: () => writeCursor(sessionId, { count, generation, headHash }), + completedTurns: added.filter((message) => isFinalAssistant(asRecord(message))) + .length, + commit: () => + writeCursor(sessionId, namespace, { count, generation, headHash }), }; } @@ -192,6 +288,7 @@ export async function captureSession(options: { metadata?: SessionMetadata; supportingContext?: string; timeoutMs?: number; + everyNTurns?: number; onSaved?: () => void; logger?: typeof defaultLog; }): Promise { @@ -199,8 +296,11 @@ export async function captureSession(options: { const logger = options.logger ?? defaultLog; if (!namespace) return false; - const delta = buildSessionDelta(sessionId, messages); + 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, { diff --git a/src/v2/runtime.test.ts b/src/v2/runtime.test.ts index 99d2525..6e06297 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"; @@ -6,15 +9,22 @@ import { DEFAULT_RECALL_DIRECTIVE } from "../services/recall.js"; import type { ResolvedTags } from "../services/tags.js"; import { applyInjection, + buildTranscriptTurns, buildV2RecallDirective, + mergeTurns, SUPERMEMORY_RECALL_TOOL_NAME, SUPERMEMORY_TOOL_NAME, V2Runtime, type RequestMessage, + type TranscriptMessage, type V2Context, 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", @@ -26,6 +36,18 @@ const tags: ResolvedTags = { allReads: [], }; +function user(id: string, text: string): TranscriptMessage { + return { id, type: "user", text }; +} + +function assistant( + id: string, + text: string, + finish: string = "stop", +): TranscriptMessage { + return { id, type: "assistant", finish, content: [{ type: "text", text }] }; +} + function request(id: string, text: string): RequestMessage { return { id, @@ -40,6 +62,49 @@ function texts(message: RequestMessage): string[] { ); } +describe("OpenCode 2 transcript capture", () => { + test("groups completed turns and protects private content", () => { + const turns = buildTranscriptTurns([ + { id: "sys", type: "system", text: "injected" }, + user("u1", "real prompt"), + assistant("a1", "calling a tool", "tool-calls"), + assistant("a2", "real answer"), + user("u2", "secret prompt"), + assistant("a3", "secret answer"), + user("u3", "token secret"), + assistant("a4", "safe answer"), + user("u4", "still streaming"), + ]); + + expect(turns.map((turn) => turn.id)).toEqual(["u1", "u2", "u3"]); + expect(turns[0]?.messages).toEqual([ + { role: "user", content: "real prompt" }, + { role: "assistant", content: "calling a tool" }, + { role: "assistant", content: "real answer" }, + ]); + expect(turns[1]?.messages).toEqual([]); + expect(turns[2]?.messages[0]).toEqual({ + role: "user", + content: "token [REDACTED]", + }); + }); + + test("keeps turn positions stable when the transcript is compacted", () => { + const existing = mergeTurns( + [], + new Map(), + buildTranscriptTurns([user("u1", "one"), assistant("a1", "1")]), + ); + const index = new Map([["u1", 0]]); + mergeTurns( + existing, + index, + buildTranscriptTurns([user("u2", "two"), assistant("a2", "2")]), + ); + expect(existing.map((turn) => turn.id)).toEqual(["u1", "u2"]); + }); +}); + describe("OpenCode 2 request injection", () => { test("points the advisory directive at the recall helper", () => { const directive = buildV2RecallDirective(DEFAULT_RECALL_DIRECTIVE); @@ -74,20 +139,23 @@ 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: 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: unknown[] } = { transcript: [] }; + const state: { transcript: TranscriptMessage[] } = { transcript: [] }; const registration = { dispose: async () => undefined }; const ctx = { @@ -180,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, @@ -197,6 +272,7 @@ function harness( config: { recallMode: "direct", injectProfile: true, + captureEveryNTurns: 1, compactionEnabled: true, keywordPatterns: ["remember"], maxProjectMemories: 10, @@ -211,6 +287,7 @@ function harness( latestVersion: "9.9.9", updateCommand: "bunx opencode-supermemory@latest install", }), + apiVersion: () => apiVersion, }); return { @@ -221,11 +298,12 @@ function harness( queries, writes, adds, + sessions, emitted, get transcript() { return state.transcript; }, - set transcript(value: unknown[]) { + set transcript(value: TranscriptMessage[]) { state.transcript = value; }, }; @@ -316,6 +394,149 @@ describe("OpenCode 2 runtime", () => { h.runtime.cleanup(); }); + test("captures completed turns idempotently and saves compaction summaries", async () => { + const h = harness(); + await h.runtime.register(); + + h.transcript = [user("u1", "question 1"), assistant("a1", "answer 1")]; + await h.runtime.handleEvent({ + id: "e1", + type: "session.execution.succeeded", + data: { sessionID: "s1" }, + }); + await h.runtime.idle(); + await h.runtime.handleEvent({ + id: "e2", + type: "session.execution.succeeded", + data: { sessionID: "s1" }, + }); + await h.runtime.idle(); + expect(h.writes).toHaveLength(1); + expect(h.writes[0]?.customId).toStartWith("opencode:capture:"); + expect(h.writes[0]?.timeoutMs).toBe(3_000); + expect(h.writes[0]?.metadata).toMatchObject({ + captureReason: "cadence", + sm_capture_mode: "automatic", + }); + + // Compaction truncates the transcript; the earlier turn keeps its slot. + h.transcript = [ + { id: "c1", type: "compaction" }, + user("u2", "question 2"), + assistant("a2", "answer 2"), + ]; + await h.runtime.handleEvent({ + id: "e3", + type: "session.execution.succeeded", + data: { sessionID: "s1" }, + }); + await h.runtime.idle(); + expect(h.writes).toHaveLength(2); + expect(h.writes[1]?.customId).not.toBe(h.writes[0]?.customId); + + const summary = "Summary ".repeat(20); + await h.runtime.handleEvent({ + id: "e4", + type: "session.compaction.ended", + data: { sessionID: "s1", text: summary, reason: "auto" }, + }); + await h.runtime.handleEvent({ + id: "e4", + type: "session.compaction.ended", + data: { sessionID: "s1", text: summary, reason: "auto" }, + }); + expect(h.adds).toHaveLength(1); + expect(h.adds[0]?.customId).toStartWith("opencode:compaction:"); + expect(h.adds[0]?.metadata).toMatchObject({ sm_capture_mode: "compaction" }); + + const system: Array<{ type: "text"; text: string }> = []; + await h.runtime.handleCompaction({ sessionID: "s1", system }); + expect(system[0]?.text).toContain(COMPACTION_CONTEXT_MARKER); + expect(system[0]?.text).toContain("Build: bun run build"); + + await h.runtime.handleEvent({ + id: "e5", + type: "session.deleted", + data: { sessionID: "s1" }, + }); + expect(h.runtime.trackedSessionCount).toBe(0); + expect(h.writes).toHaveLength(2); + expect(h.emitted.filter((event) => event.kind === "saved")).toHaveLength(3); + 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("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 13d41e1..6d4a37c 100644 --- a/src/v2/runtime.ts +++ b/src/v2/runtime.ts @@ -3,12 +3,20 @@ 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, type MemoryActivityReporter, } from "../services/activity.js"; +import { + AUTOMATIC_CAPTURE_TIMEOUT_MS, + buildCadenceBatches, + buildSessionEndBatch, + getCaptureId, + type CaptureBatch, + type CaptureTurn, +} from "../services/capture.js"; import { supermemoryClient, type SupermemoryClient } from "../services/client.js"; import { captureSession, @@ -36,6 +44,7 @@ import { type SupermemoryToolArgs, } from "../services/memory-tool.js"; import { RECALL_PERMISSION } from "../services/opencode-permissions.js"; +import { isFullyPrivate, stripPrivateContent } from "../services/privacy.js"; import { buildDirectRecallResult, buildRecallDirective, @@ -59,7 +68,6 @@ const SYNTHETIC_METADATA_KEY = "supermemory"; const UPDATE_COMMAND = "bunx opencode-supermemory@latest install"; const MAX_DISPATCHES_PER_SESSION = 8; const MIN_SUMMARY_CHARS = 100; -const SUMMARY_SAVE_TIMEOUT_MS = 3_000; const MAX_SUMMARY_ATTEMPTS = 5; const SUMMARY_RETRY_BASE_MS = 15_000; @@ -105,6 +113,7 @@ export const SUPERMEMORY_RECALL_INPUT = { type RuntimeMemoryClient = Pick< SupermemoryClient, | "addMemory" + | "ingestConversation" | "addSession" | "getProfileScoped" | "searchMemoriesForRecall" @@ -118,6 +127,7 @@ type RuntimeConfig = Pick< typeof CONFIG, | "recallMode" | "injectProfile" + | "captureEveryNTurns" | "compactionEnabled" | "keywordPatterns" | "maxProjectMemories" @@ -132,6 +142,7 @@ export interface V2RuntimeDependencies { resolveTags: typeof getTags; logger: typeof log; checkUpdate: () => Promise; + apiVersion: typeof getApiVersion; } const DEFAULT_DEPENDENCIES: V2RuntimeDependencies = { @@ -143,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()`. */ @@ -152,6 +164,15 @@ export interface V2Event { data?: Record; } +/** Minimal shape of a persisted OpenCode 2 transcript message. */ +export interface TranscriptMessage { + id: string; + type: string; + text?: string; + finish?: string; + content?: ReadonlyArray<{ type: string; text?: string }>; +} + interface Injection { start: string[]; end: string[]; @@ -164,6 +185,9 @@ interface SessionState { injectedInitialContext: boolean; dispatches: Map>; dispatchOrder: string[]; + turns: CaptureTurn[]; + turnIndex: Map; + completedCaptureIds: Set; } interface PendingSummary { @@ -284,6 +308,105 @@ export function applyInjection( } } +function sanitizeCaptureText(text: string): string { + if (!text || isFullyPrivate(text)) return ""; + return stripPrivateContent(text).trim(); +} + +function isFinalAssistant(message: TranscriptMessage): boolean { + return ( + typeof message.finish === "string" && + message.finish.length > 0 && + message.finish !== "tool-calls" + ); +} + +function assistantText(message: TranscriptMessage): string { + return (message.content ?? []) + .filter((part) => part.type === "text" && typeof part.text === "string") + .map((part) => part.text as string) + .join("\n") + .trim(); +} + +/** + * Groups an OpenCode 2 transcript into completed user/assistant turns using + * the same rules as the V1 capture hook: synthetic and system messages are + * ignored, `` content is redacted, and a fully private prompt hides + * its whole turn. + */ +export function buildTranscriptTurns( + messages: ReadonlyArray, +): CaptureTurn[] { + const turns: CaptureTurn[] = []; + let current: + | { + id: string; + messages: CaptureTurn["messages"]; + fullyPrivate: boolean; + complete: boolean; + } + | undefined; + + const finish = () => { + if (current?.complete) { + turns.push({ + id: current.id, + messages: current.fullyPrivate ? [] : current.messages, + }); + } + current = undefined; + }; + + for (const message of messages) { + if (message.type === "user") { + finish(); + const rawText = (message.text ?? "").trim(); + const text = sanitizeCaptureText(rawText); + current = { + id: message.id, + messages: text ? [{ role: "user", content: text }] : [], + fullyPrivate: rawText.length > 0 && isFullyPrivate(rawText), + complete: false, + }; + continue; + } + + if (!current || message.type !== "assistant") continue; + + const text = sanitizeCaptureText(assistantText(message)); + if (text && !current.fullyPrivate) { + current.messages.push({ role: "assistant", content: text }); + } + if (isFinalAssistant(message)) current.complete = true; + } + + finish(); + return turns; +} + +/** + * Merges freshly read turns into the session's cumulative turn list. The + * transcript OpenCode returns may shrink after compaction, so turn positions + * (and therefore capture IDs) are anchored to the first time a turn was seen. + */ +export function mergeTurns( + existing: CaptureTurn[], + index: Map, + incoming: CaptureTurn[], +): CaptureTurn[] { + for (const turn of incoming) { + const position = index.get(turn.id); + if (position === undefined) { + index.set(turn.id, existing.length); + existing.push(turn); + } else { + existing[position] = turn; + } + } + return existing; +} + export class EventDeduper { readonly #limit: number; readonly #seen = new Set(); @@ -480,6 +603,7 @@ export class V2Runtime { hooks: ["session.context", "session.compaction", "permission.evaluate", "tool.execute"], activity: this.#emitActivity ? "rpc" : "log-only", recallMode: this.#deps.config.recallMode, + captureEveryNTurns: this.#deps.config.captureEveryNTurns, compactionEnabled: this.#deps.config.compactionEnabled, }); } @@ -583,7 +707,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", { @@ -604,7 +734,7 @@ export class V2Runtime { case "session.execution.succeeded": { if (!sessionID) return; void this.#runCaptureExclusive(sessionID, () => - this.#captureSession(sessionID), + this.#captureCadence(sessionID), ); return; } @@ -613,7 +743,7 @@ export class V2Runtime { if (!sessionID || event.data?.reason !== "shutdown") return; if (!this.#states.has(sessionID)) return; void this.#runCaptureExclusive(sessionID, () => - this.#captureSession(sessionID), + this.#captureSessionEnd(sessionID), ); return; } @@ -624,7 +754,7 @@ export class V2Runtime { this.#recall.delete(sessionID); if (!state) return; await this.#runCaptureExclusive(sessionID, () => - this.#captureSession(sessionID), + this.#captureSessionEnd(sessionID), ); this.#states.delete(sessionID); return; @@ -705,6 +835,9 @@ export class V2Runtime { injectedInitialContext: false, dispatches: new Map(), dispatchOrder: [], + turns: [], + turnIndex: new Map(), + completedCaptureIds: new Set(), }; this.#states.set(sessionID, state); return state; @@ -901,12 +1034,130 @@ export class V2Runtime { } } - async #sessionMessages(sessionID: string): Promise { - const messages = (await this.#ctx.session.context({ sessionID })) as unknown; - return Array.isArray(messages) ? messages : []; + async #refreshTurns(sessionID: string, state: SessionState): Promise { + try { + const messages = (await this.#ctx.session.context({ sessionID })) as unknown; + if (Array.isArray(messages)) { + mergeTurns( + state.turns, + state.turnIndex, + buildTranscriptTurns(messages as TranscriptMessage[]), + ); + } + } catch (error) { + this.#deps.logger("v2 capture transcript read failed; using cached turns", { + sessionID, + error: String(error), + }); + } + return state.turns; + } + + async #saveBatch( + sessionID: string, + state: SessionState, + batch: CaptureBatch, + reason: "cadence" | "session_end", + ): Promise { + const captureId = getCaptureId(sessionID, batch); + if (state.completedCaptureIds.has(captureId)) return true; + const messages = batch.turns.flatMap((turn) => turn.messages); + if (messages.length === 0) { + state.completedCaptureIds.add(captureId); + return true; + } + + let result: { success: boolean; error?: string }; + try { + const tags = await this.#resolveSession(sessionID); + result = await this.#deps.memoryClient.ingestConversation( + `${sessionID}:${batch.startTurn}-${batch.endTurn}`, + messages, + [tags.canonical], + { + project: tags.projectName, + sm_project_id: tags.projectId, + sm_scope: "personal", + sm_capture_mode: "automatic", + captureReason: reason, + sessionId: sessionID, + turnStart: batch.startTurn, + turnEnd: batch.endTurn, + }, + { + defaultEntityContext: AGENT_ENTITY_CONTEXT, + customId: captureId, + timeoutMs: AUTOMATIC_CAPTURE_TIMEOUT_MS, + }, + ); + } catch (error) { + result = { + success: false, + error: error instanceof Error ? error.message : String(error), + }; + } + + if (result.success) { + state.completedCaptureIds.add(captureId); + this.#activity.saved(); + this.#deps.logger("[capture] conversation batch saved", { + sessionID, + reason, + startTurn: batch.startTurn, + endTurn: batch.endTurn, + }); + return true; + } + + this.#deps.logger("[capture] failed to save conversation batch", { + sessionID, + reason, + startTurn: batch.startTurn, + endTurn: batch.endTurn, + error: result.error, + }); + return false; + } + + 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); + return; + } + const turns = await this.#refreshTurns(sessionID, state); + for (const batch of buildCadenceBatches( + turns, + this.#deps.config.captureEveryNTurns, + )) { + await this.#saveBatch(sessionID, state, batch, "cadence"); + } + } + + 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( + turns, + this.#deps.config.captureEveryNTurns, + )) { + await this.#saveBatch(sessionID, state, batch, "cadence"); + } + const finalBatch = buildSessionEndBatch( + turns, + this.#deps.config.captureEveryNTurns, + ); + if (finalBatch) { + await this.#saveBatch(sessionID, state, finalBatch, "session_end"); + } } - async #captureSession(sessionID: string): Promise { + async #captureSession(sessionID: string, everyNTurns?: number): Promise { this.#state(sessionID); let tags: ResolvedTags; @@ -922,7 +1173,8 @@ export class V2Runtime { let messages: unknown[]; try { - messages = await this.#sessionMessages(sessionID); + const context = (await this.#ctx.session.context({ sessionID })) as unknown; + messages = Array.isArray(context) ? context : []; } catch (error) { this.#deps.logger("v2 session transcript read failed", { sessionID, @@ -939,6 +1191,7 @@ export class V2Runtime { metadata: sessionMetadata(tags.projectName, tags.projectId), supportingContext: AGENT_ENTITY_CONTEXT, timeoutMs: SESSION_CAPTURE_TIMEOUT_MS, + everyNTurns, onSaved: () => this.#activity.saved(), logger: this.#deps.logger, }); @@ -952,7 +1205,7 @@ export class V2Runtime { await Promise.all([ ...sessions.map((sessionID) => this.#runCaptureExclusive(sessionID, () => - this.#captureSession(sessionID), + this.#captureSessionEnd(sessionID), ), ), ...[...pending].map((sessionID) => @@ -1026,7 +1279,7 @@ export class V2Runtime { { customId: summary.customId, entityContext: AGENT_ENTITY_CONTEXT, - timeoutMs: SUMMARY_SAVE_TIMEOUT_MS, + timeoutMs: AUTOMATIC_CAPTURE_TIMEOUT_MS, }, ); if (result.success) { From 40d0c8591247305c99c911256fc9e23e3f2b66c2 Mon Sep 17 00:00:00 2001 From: Ishaan Gupta Date: Mon, 23 Nov 2026 18:34:35 +0530 Subject: [PATCH 6/7] fix: capture deleted sessions from the last idle snapshot --- src/services/capture.test.ts | 43 ++++++++++++++++++++++++++++++++ src/services/capture.ts | 48 +++++++++++++++++++++++++----------- src/v2/runtime.test.ts | 25 +++++++++++++++++++ src/v2/runtime.ts | 32 ++++++++++++++++-------- 4 files changed, 124 insertions(+), 24 deletions(-) diff --git a/src/services/capture.test.ts b/src/services/capture.test.ts index d652a83..679560e 100644 --- a/src/services/capture.test.ts +++ b/src/services/capture.test.ts @@ -338,4 +338,47 @@ describe("v5 session capture", () => { 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 b060ba6..81af06f 100644 --- a/src/services/capture.ts +++ b/src/services/capture.ts @@ -431,6 +431,7 @@ export function createSessionCaptureHook( 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({ @@ -443,20 +444,31 @@ export function createSessionCaptureHook( return Array.isArray(response) ? response : (response.data ?? []); } - async function capture( + async function loadMessages( sessionID: string, - everyNTurns?: number, - ): Promise { - let messages: SessionMessage[]; + ): Promise { try { - messages = await readMessages(sessionID); + const messages = await readMessages(sessionID); + snapshots.set(sessionID, messages); + return messages; } catch (error) { - log("[capture] failed to read session transcript", { - sessionID, - error: String(error), - }); - return false; + 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, @@ -487,6 +499,11 @@ export function createSessionCaptureHook( } } + 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; @@ -501,9 +518,12 @@ export function createSessionCaptureHook( const sessionID = props?.sessionID as string | undefined; if (!sessionID) return; activeSessions.add(sessionID); - if (captureEveryNTurns <= 0) return; await runExclusive(sessionID, async () => { - await capture(sessionID, captureEveryNTurns); + if (captureEveryNTurns > 0) { + await capture(sessionID, captureEveryNTurns); + } else { + await loadMessages(sessionID); + } }); return; } @@ -513,7 +533,7 @@ export function createSessionCaptureHook( if (!sessionID) return; activeSessions.add(sessionID); await runExclusive(sessionID, async () => { - if (await capture(sessionID)) activeSessions.delete(sessionID); + if (await capture(sessionID)) finish(sessionID); }); return; } @@ -522,7 +542,7 @@ export function createSessionCaptureHook( await Promise.all( [...activeSessions].map((sessionID) => runExclusive(sessionID, async () => { - if (await capture(sessionID)) activeSessions.delete(sessionID); + if (await capture(sessionID)) finish(sessionID); }), ), ); diff --git a/src/v2/runtime.test.ts b/src/v2/runtime.test.ts index 6e06297..5a9fbe9 100644 --- a/src/v2/runtime.test.ts +++ b/src/v2/runtime.test.ts @@ -537,6 +537,31 @@ describe("OpenCode 2 runtime", () => { 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 6d4a37c..9ae8dd8 100644 --- a/src/v2/runtime.ts +++ b/src/v2/runtime.ts @@ -188,6 +188,7 @@ interface SessionState { turns: CaptureTurn[]; turnIndex: Map; completedCaptureIds: Set; + messages?: unknown[]; } interface PendingSummary { @@ -1124,6 +1125,7 @@ export class V2Runtime { 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); @@ -1157,8 +1159,10 @@ export class V2Runtime { } } - async #captureSession(sessionID: string, everyNTurns?: number): Promise { - this.#state(sessionID); + async #readSession( + sessionID: string, + ): Promise<{ tags: ResolvedTags; messages: unknown[] } | undefined> { + const state = this.#state(sessionID); let tags: ResolvedTags; try { @@ -1168,20 +1172,28 @@ export class V2Runtime { sessionID, error: String(error), }); - return; + return undefined; } - let messages: unknown[]; try { const context = (await this.#ctx.session.context({ sessionID })) as unknown; - messages = Array.isArray(context) ? context : []; + state.messages = Array.isArray(context) ? context : []; } catch (error) { - this.#deps.logger("v2 session transcript read failed", { - sessionID, - error: String(error), - }); - return; + 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, From 607e6e2588758fd8a21dba45a56a8a11547496f1 Mon Sep 17 00:00:00 2001 From: MaheshtheDev <38828053+MaheshtheDev@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:44:24 +0000 Subject: [PATCH 7/7] chore(release): 2.2.0 Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- package.json | 2 +- src/version.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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/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";