diff --git a/CHANGELOG.md b/CHANGELOG.md index c138ad2..0f89e6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 2.3.0 + +- Skip automatic recall, capture and compaction memory for subagent sessions (any session with a `parentID`) and, on OpenCode V1, for `opencode run` / `opencode github run`, including V5 session capture uploads. Opt back in with `captureSubagents` / `captureHeadless` or `SUPERMEMORY_CAPTURE_SUBAGENTS=true` / `SUPERMEMORY_CAPTURE_HEADLESS=true`. +- Treat Conductor and Vibe Kanban sessions as interactive; `captureOrchestrated: false` skips them. +- Replace an opening prompt of 200+ characters already captured from this machine for the same container in the last 24 hours with a one-line marker on the client-formatted (legacy server) capture path (`dedupeOpeningPrompt`), and re-serve the last successful recall for exact query repeats within 10 minutes instead of searching again (`dedupeRecallQueries`). +- `SUPERMEMORY_CAPTURE_*` / `SUPERMEMORY_DEDUPE_*` accept `true/1/yes/on` and `false/0/no/off`; OpenCode V1 headless detection skips the values of value-taking flags (`--port 4096 run` is headless, `--prompt run` is not); the parent-session lookup fails open after 2 seconds. + ## 2.1.3 - Back off failed compaction summary saves with jittered exponential delays starting at 15s, and drop a summary after 5 failed attempts instead of re-sending it on every event (#128). diff --git a/README.md b/README.md index b18e38d..13e1c01 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,62 @@ Completed conversations are captured automatically: - Synthetic plugin context is excluded and `` content is redacted. - Stable capture IDs retain batch identity across repeated lifecycle events; they do not guarantee exactly-once processing or billing after an ambiguous response. +### Sessions without automatic memory + +Automatic recall, capture and compaction memory run only for sessions you drive yourself. +By default the plugin makes no Supermemory calls from its hooks for: + +- **Subagent sessions.** Any session with a `parentID`, which OpenCode sets on child sessions + spawned by the `task` (V1) or `subagent` (OpenCode 2) tool. Set `captureSubagents: true` or + `SUPERMEMORY_CAPTURE_SUBAGENTS=true` to restore recall and capture for them. +- **Headless runs (OpenCode V1).** `opencode run` and `opencode github run` (including their + V5 session uploads), which host the + server and plugins in the CLI process. Set `captureHeadless: true` or + `SUPERMEMORY_CAPTURE_HEADLESS=true` to restore them. `opencode run --attach` on V1 runs the + plugin in the attached server, so it is treated as interactive. + +**OpenCode 2 `opencode run` is not detected as headless.** OpenCode 2 gives plugins no signal for +it (it may share the background server with interactive sessions), so OpenCode 2 runs get recall +and capture like any interactive session. Only subagent sessions are skipped on OpenCode 2. + +OpenCode's title generation never reaches the plugin's hooks, so it makes no Supermemory calls. +Compaction only runs [Compaction Memory](#compaction-memory) for the session being summarised, +which is skipped for subagent and headless sessions like everything else. + +Sessions started by Conductor (`CONDUCTOR_WORKSPACE_PATH`, `CONDUCTOR_SESSION_ID`) or Vibe Kanban +(`VK_WORKSPACE_ID`) are real user work and always count as interactive, even through +`opencode run`. Set `captureOrchestrated: false` or `SUPERMEMORY_CAPTURE_ORCHESTRATED=false` to +skip them. The variables are inherited, so any `opencode run` started inside a Conductor or +Vibe Kanban workspace (a script, or an agent shelling out to OpenCode) also counts as +orchestrated and is captured. Orchestrators without an environment variable (Crystal, Claude +Squad) are not recognised; Claude Squad runs the interactive TUI, which is captured as usual. On OpenCode 2 the variables are read from the server process, so they only apply +when it was started from the orchestrator's environment (for example `--standalone` or `run` +without a background service). + +### Repeated prompts + +Swarms of one-shot workers often send the same task prompt many times. Two small local +indexes under `~/.supermemory-opencode/` keep those repeats from being re-sent: + +- **Opening prompt** (`dedupeOpeningPrompt`, default `true`). When a session's first prompt is + at least 200 characters and matches one this machine successfully captured for the same API + base URL, credential and container tag in the last 24 hours, the capture is sent with a + one-line `[Opening prompt omitted: ...]` marker in its place. The rest of the conversation is + captured as usual. Older entries are ignored and pruned, nothing is deduped without a + credential, and `logout` deletes the index. It applies to the client-formatted capture used + with legacy servers; V5 session capture uploads the transcript unchanged. Set + `SUPERMEMORY_DEDUPE_OPENING_PROMPT=false` to opt out. +- **Recall query** (`dedupeRecallQueries`, default `true`). When the same normalized query is + recalled against the same container tag within 10 minutes, the result of the first successful + search is re-served without another API call, so a new session still gets the same context. A + failed or timed-out search is never cached. Entries are keyed on a hash of the API base URL, + the credential, the container tags and the query, so another account or backend never reuses + them; nothing is cached without a credential, and `logout` deletes the file. Set + `SUPERMEMORY_DEDUPE_RECALL_QUERIES=false` to opt out. + +The `SUPERMEMORY_CAPTURE_*` and `SUPERMEMORY_DEDUPE_*` variables accept `true`/`1`/`yes`/`on` +and `false`/`0`/`no`/`off` (any case) and override the config file in both directions. + ### Keyword Detection Say "remember", "save this", "don't forget" etc. and the agent auto-saves to memory. @@ -309,6 +365,11 @@ does not require a migration. | `SUPERMEMORY_REPO_TAG` | Explicit project-container override, checked before the config value. | | `SUPERMEMORY_ISOLATE_WORKTREES` | Set to `true` to key the project container on the worktree path instead of the Git remote. | | `SUPERMEMORY_DEBUG` | Set to show `[recall-decision]` lines and enable debug logging. | +| `SUPERMEMORY_CAPTURE_SUBAGENTS` | `true` restores recall and capture for subagent sessions (overrides `captureSubagents`). | +| `SUPERMEMORY_CAPTURE_HEADLESS` | `true` restores recall and capture for `opencode run` (overrides `captureHeadless`). | +| `SUPERMEMORY_CAPTURE_ORCHESTRATED` | `false` skips sessions started by Conductor or Vibe Kanban (overrides `captureOrchestrated`). | +| `SUPERMEMORY_DEDUPE_OPENING_PROMPT` | `false` always sends repeated opening prompts (overrides `dedupeOpeningPrompt`). | +| `SUPERMEMORY_DEDUPE_RECALL_QUERIES` | `false` always searches for repeated recall queries instead of re-serving the cached result (overrides `dedupeRecallQueries`). | ### `~/.config/opencode/supermemory.jsonc` @@ -390,6 +451,21 @@ scope, not from a different or malformed response. // Override the directive used in advisory mode "recallDirective": null, + + // Recall and capture subagent (child) sessions too + "captureSubagents": false, + + // OpenCode V1: recall and capture `opencode run` / `opencode github run` too + "captureHeadless": false, + + // Recall and capture sessions started by Conductor or Vibe Kanban + "captureOrchestrated": true, + + // Replace a 200+ character opening prompt captured from this machine in the last 24h with a marker + "dedupeOpeningPrompt": true, + + // Re-serve the last successful recall for a repeat of a query made in the last 10 minutes + "dedupeRecallQueries": true, } ``` diff --git a/bunfig.toml b/bunfig.toml new file mode 100644 index 0000000..8962bbb --- /dev/null +++ b/bunfig.toml @@ -0,0 +1,2 @@ +[test] +preload = ["./scripts/test-preload.mjs"] diff --git a/package.json b/package.json index 2891406..72de33b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opencode-supermemory", - "version": "2.2.0", + "version": "2.3.0", "description": "OpenCode plugin that gives coding agents persistent memory using Supermemory", "type": "module", "main": "dist/index.js", diff --git a/scripts/test-preload.mjs b/scripts/test-preload.mjs new file mode 100644 index 0000000..ba32c00 --- /dev/null +++ b/scripts/test-preload.mjs @@ -0,0 +1,10 @@ +import { mock } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import os from "node:os"; +import { join } from "node:path"; + +// Keep tests away from the developer's Supermemory config and local dedupe state. +const home = mkdtempSync(join(os.tmpdir(), "opencode-supermemory-test-")); +const homedir = () => home; +mock.module("node:os", () => ({ ...os, default: { ...os, homedir }, homedir })); +mock.module("os", () => ({ ...os, default: { ...os, homedir }, homedir })); diff --git a/src/config.ts b/src/config.ts index 9edc348..3841354 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,3 +1,4 @@ +import { createHash } from "node:crypto"; import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { homedir } from "node:os"; @@ -43,6 +44,11 @@ interface SupermemoryConfig { captureEveryNTurns?: number; recallDirective?: string | null; recallMode?: RecallMode; + captureSubagents?: boolean; + captureHeadless?: boolean; + captureOrchestrated?: boolean; + dedupeOpeningPrompt?: boolean; + dedupeRecallQueries?: boolean; } const DEFAULT_KEYWORD_PATTERNS = [ @@ -77,6 +83,11 @@ const DEFAULTS: Required { const injectedSessions = new Set(); const recallSessions = new RecallSessionCache(); const activity = createMemoryActivityReporter(ctx.client); + const scope = new SessionScope({ + headless: isHeadlessCommand(), + lookupParent: async (id) => { + const response = await ctx.client.session.get({ path: { id } }); + if (!response.data) throw new Error(`Unable to read OpenCode session ${id}`); + return response.data.parentID; + }, + }); + const searchForRecall = (query: string) => + supermemoryClient.searchMemoriesForRecall( + query, + tags.canonical, + tags.personalReads, + tags.projectReads, + { timeoutMs: DIRECT_RECALL_TIMEOUT_MS }, + ); + const recallSearch = CONFIG.dedupeRecallQueries + ? new RecallQueryCache(getDedupeScope).wrap( + [tags.canonical, ...tags.personalReads, ...tags.projectReads], + searchForRecall, + ) + : searchForRecall; log("Plugin init", { directory, tags, configured: isConfigured() }); if (!isConfigured()) { @@ -130,6 +170,7 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => { return { "chat.message": async (input, output) => { if (!isConfigured()) return; + if (await scope.skipReason(input.sessionID)) return; const start = Date.now(); @@ -200,14 +241,7 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => { prompt: userMessage, sessionID: input.sessionID, cache: recallSessions, - search: (query) => - supermemoryClient.searchMemoriesForRecall( - query, - tags.canonical, - tags.personalReads, - tags.projectReads, - { timeoutMs: DIRECT_RECALL_TIMEOUT_MS }, - ), + search: recallSearch, suppressTexts: isFirstMessage ? profileRequest.then((result) => result?.success && result.profile @@ -359,6 +393,10 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => { event: async (input: { event: { type: string; properties?: unknown } }) => { const props = input.event.properties as Record | undefined; + if (input.event.type === "session.created" || input.event.type === "session.updated") { + const info = props?.info as { id?: string; parentID?: string } | undefined; + scope.note(info?.id, info?.parentID); + } if (input.event.type === "session.deleted") { const sessionID = (props?.info as { id?: string } | undefined)?.id; if (sessionID) { @@ -371,6 +409,10 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => { } if (!isConfigured()) return; + const sessionID = eventSessionID(input.event); + const skip = sessionID ? await scope.skipReason(sessionID) : scope.processSkipReason; + if (sessionID && input.event.type === "session.deleted") scope.forget(sessionID); + if (skip) return; if (compactionHook) { await compactionHook.event(input); } diff --git a/src/services/auth.ts b/src/services/auth.ts index 2c1c266..1e65115 100644 --- a/src/services/auth.ts +++ b/src/services/auth.ts @@ -3,6 +3,7 @@ import { join } from "node:path"; import { homedir } from "node:os"; import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto"; import { createServer, type Server } from "node:http"; +import { OPENING_PROMPTS_FILE, RECALL_QUERIES_FILE } from "./local-dedupe.js"; import { openUrl } from "./openUrl.js"; import { PLUGIN_VERSION } from "../version.js"; @@ -460,6 +461,8 @@ export async function settleAuth(): Promise { export async function clearCredentials(): Promise { return withAuthLock(async (remaining) => { + fs.rmSync(RECALL_QUERIES_FILE, { force: true }); + fs.rmSync(OPENING_PROMPTS_FILE, { force: true }); const credentials = loadCredentialData(); if (credentials?.type === "oauth" && credentials.refreshToken) { await oauthRequest(issuerEndpoint(credentials.revocationEndpoint, credentials.issuer), { diff --git a/src/services/capture.ts b/src/services/capture.ts index 81af06f..0fe73ee 100644 --- a/src/services/capture.ts +++ b/src/services/capture.ts @@ -1,10 +1,11 @@ import { createHash } from "node:crypto"; import type { Part } from "@opencode-ai/sdk"; -import { CONFIG, getApiVersion } from "../config.js"; +import { CONFIG, getApiVersion, getDedupeScope } from "../config.js"; import type { ConversationMessage } from "../types/index.js"; import { supermemoryClient } from "./client.js"; import { AGENT_ENTITY_CONTEXT } from "./entity-context.js"; +import { OpeningPromptIndex } from "./local-dedupe.js"; import { log } from "./logger.js"; import { isFullyPrivate, stripPrivateContent } from "./privacy.js"; import { @@ -75,6 +76,23 @@ export interface CaptureOptions { memoryClient?: ConversationWriter; writer?: SessionWriter; onSaved?: () => void; + openingPrompts?: OpeningPromptIndex | null; +} + +export function defaultOpeningPromptIndex(): OpeningPromptIndex | null { + return CONFIG.dedupeOpeningPrompt ? new OpeningPromptIndex(getDedupeScope) : null; +} + +/** Replaces an opening prompt this machine already captured for the tag with a marker. */ +export function prepareCaptureMessages( + index: OpeningPromptIndex | null, + containerTag: string, + sessionID: string, + batch: CaptureBatch, +): { messages: ConversationMessage[]; commit: () => void } { + const messages = batch.turns.flatMap((turn) => turn.messages); + if (!index || batch.startTurn !== 1) return { messages, commit: () => {} }; + return index.prepare(containerTag, sessionID, messages); } function extractText(parts: Part[] | undefined): string { @@ -225,6 +243,10 @@ export function createLegacyCaptureHook( const captureEveryNTurns = options?.captureEveryNTurns ?? CONFIG.captureEveryNTurns; const memoryClient = options?.memoryClient ?? supermemoryClient; + const openingPrompts = + options?.openingPrompts !== undefined + ? options.openingPrompts + : defaultOpeningPromptIndex(); const snapshots = new Map(); const activeSessions = new Set(); const completedCaptureIds = new Set(); @@ -253,7 +275,12 @@ export function createLegacyCaptureHook( const captureId = getCaptureId(sessionID, batch); if (completedCaptureIds.has(captureId)) return true; - const messages = batch.turns.flatMap((turn) => turn.messages); + const { messages, commit } = prepareCaptureMessages( + openingPrompts, + tags.canonical, + sessionID, + batch, + ); if (messages.length === 0) { completedCaptureIds.add(captureId); return true; @@ -290,6 +317,7 @@ export function createLegacyCaptureHook( if (result.success) { completedCaptureIds.add(captureId); + commit(); options?.onSaved?.(); log("[capture] conversation batch saved", { sessionID, diff --git a/src/services/local-dedupe.test.ts b/src/services/local-dedupe.test.ts new file mode 100644 index 0000000..6540afc --- /dev/null +++ b/src/services/local-dedupe.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, test } from "bun:test"; +import { mkdtempSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import type { SearchResponse } from "./client.js"; +import { OPENING_PROMPT_TTL_MS, OpeningPromptIndex, RecallQueryCache } from "./local-dedupe.js"; + +function tempFile(name: string): string { + return join(mkdtempSync(join(tmpdir(), "supermemory-dedupe-")), name); +} + +const TASK = + "Run the nightly migration task against the staging database, verify every table row count matches the snapshot taken before the run, then write a short report with any mismatches and the exact SQL you used."; + +describe("local dedupe indexes", () => { + test("sends a long opening prompt once per credential and container tag and keeps the owner session intact", () => { + let scope: string | null = "backend-a:key-1"; + const file = tempFile("opening.json"); + const index = new OpeningPromptIndex(() => scope, file); + const batch = [ + { role: "user" as const, content: TASK }, + { role: "assistant" as const, content: "Done." }, + ]; + + const first = index.prepare("repo_a", "worker-1", batch); + expect(first.messages).toEqual(batch); + first.commit(); + + expect(index.prepare("repo_a", "worker-1", batch).messages).toEqual(batch); + const repeat = index.prepare("repo_a", "worker-2", [ + { role: "user", content: TASK.replace(" ", " ") }, + { role: "assistant", content: "Done again." }, + ]); + expect(repeat.messages[0]?.content).toMatch(/^\[Opening prompt omitted: .*sha256:[0-9a-f]{12}\)\]$/); + expect(repeat.messages[1]).toEqual({ role: "assistant", content: "Done again." }); + expect(index.prepare("repo_b", "worker-3", batch).messages).toEqual(batch); + expect(statSync(file).mode & 0o777).toBe(0o600); + + scope = "backend-b:key-1"; + expect(index.prepare("repo_a", "worker-4", batch).messages).toEqual(batch); + scope = null; + const anonymous = index.prepare("repo_a", "worker-5", batch); + expect(anonymous.messages).toEqual(batch); + anonymous.commit(); + scope = "backend-a:key-1"; + expect(index.prepare("repo_a", "worker-6", batch).messages).not.toEqual(batch); + }); + + test("leaves short opening prompts and prompts captured over 24 hours ago untouched", () => { + let now = 0; + const index = new OpeningPromptIndex(() => "backend-a:key-1", tempFile("opening.json"), () => now); + const short = [{ role: "user" as const, content: "fix the failing tests" }]; + index.prepare("repo_a", "worker-1", short).commit(); + expect(index.prepare("repo_a", "worker-2", short).messages).toEqual(short); + + const long = [{ role: "user" as const, content: TASK }]; + index.prepare("repo_a", "worker-1", long).commit(); + now = OPENING_PROMPT_TTL_MS - 1; + expect(index.prepare("repo_a", "worker-2", long).messages).not.toEqual(long); + now = OPENING_PROMPT_TTL_MS; + const stale = index.prepare("repo_a", "worker-2", long); + expect(stale.messages).toEqual(long); + stale.commit(); + expect(index.prepare("repo_a", "worker-3", long).messages).not.toEqual(long); + }); + + test("an uncommitted capture does not mark the prompt as sent", () => { + const index = new OpeningPromptIndex(() => "backend-a:key-1", tempFile("opening.json")); + const batch = [{ role: "user" as const, content: TASK }]; + index.prepare("repo_a", "worker-1", batch); + expect(index.prepare("repo_a", "worker-2", batch).messages).toEqual(batch); + }); + + test("re-serves a successful recall search per credential and tags within the window and retries failures", async () => { + let now = 0; + let scope: string | null = "backend-a:key-1"; + const file = tempFile("recall.json"); + const cache = new RecallQueryCache(() => scope, file, 1_000, () => now); + const calls: string[] = []; + let fail = false; + const search = async (query: string): Promise => { + calls.push(query); + return fail + ? { success: false, error: "unavailable" } + : { success: true, results: [{ id: `m${calls.length}`, memory: "deploy with wrangler" }] }; + }; + const repoA = cache.wrap(["repo_a", "user_a"], search); + + const first = await repoA("How do we deploy?"); + now = 500; + expect(await repoA("how do we deploy?")).toEqual(first); + expect(calls).toHaveLength(1); + expect(statSync(file).mode & 0o777).toBe(0o600); + await cache.wrap(["repo_b", "user_a"], search)("How do we deploy?"); + await repoA("How do we deploy to prod?"); + expect(calls).toHaveLength(3); + now = 1_500; + await repoA("How do we deploy?"); + expect(calls).toHaveLength(4); + + fail = true; + expect((await repoA("What is pending?")).success).toBe(false); + fail = false; + expect((await repoA("What is pending?")).success).toBe(true); + expect(calls).toHaveLength(6); + + scope = "backend-a:key-2"; + await repoA("What is pending?"); + expect(calls).toHaveLength(7); + scope = "backend-a:key-1"; + await repoA("What is pending?"); + expect(calls).toHaveLength(7); + scope = null; + await repoA("What is pending?"); + await repoA("What is pending?"); + expect(calls).toHaveLength(9); + }); +}); diff --git a/src/services/local-dedupe.ts b/src/services/local-dedupe.ts new file mode 100644 index 0000000..0f95518 --- /dev/null +++ b/src/services/local-dedupe.ts @@ -0,0 +1,172 @@ +import { createHash, randomBytes } from "node:crypto"; +import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; + +import type { ConversationMessage } from "../types/index.js"; +import type { SearchResponse } from "./client.js"; + +const STATE_DIR = join(homedir(), ".supermemory-opencode"); +export const OPENING_PROMPTS_FILE = join(STATE_DIR, "opening-prompts.json"); +export const RECALL_QUERIES_FILE = join(STATE_DIR, "recall-queries.json"); +const MAX_OPENING_PROMPTS = 1_000; +const MAX_RECALL_QUERIES = 500; +export const RECALL_REPEAT_WINDOW_MS = 10 * 60 * 1000; +export const OPENING_PROMPT_MIN_CHARS = 200; +export const OPENING_PROMPT_TTL_MS = 24 * 60 * 60 * 1000; + +type Entries = Record; + +function sha256(value: string): string { + return createHash("sha256").update(value).digest("hex"); +} + +function readEntries(file: string): Entries { + try { + const parsed = JSON.parse(readFileSync(file, "utf-8")) as unknown; + return parsed && typeof parsed === "object" && !Array.isArray(parsed) + ? (parsed as Entries) + : {}; + } catch { + return {}; + } +} + +function writeEntries(file: string, entries: Entries): void { + mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); + const temporary = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`; + try { + writeFileSync(temporary, JSON.stringify(entries), { mode: 0o600, flag: "wx" }); + renameSync(temporary, file); + } finally { + rmSync(temporary, { force: true }); + } +} + +function newest(entries: Entries, limit: number, at: (value: T) => number): Entries { + return Object.fromEntries( + Object.entries(entries) + .sort(([, left], [, right]) => at(right) - at(left)) + .slice(0, limit), + ); +} + +/** + * Remembers which session first captured each long opening prompt per backend, + * credential and container tag in the last 24 hours, so repeated one-shot workers + * do not re-send it. + */ +export class OpeningPromptIndex { + constructor( + private readonly scope: () => string | null, + private readonly file = OPENING_PROMPTS_FILE, + private readonly now: () => number = Date.now, + ) {} + + /** Returns the batch to send and a commit to call once the capture is accepted. */ + prepare( + containerTag: string, + sessionID: string, + messages: ConversationMessage[], + ): { messages: ConversationMessage[]; commit: () => void } { + const unchanged = { messages, commit: () => {} }; + const opening = messages[0]; + if (opening?.role !== "user" || typeof opening.content !== "string" || !opening.content.trim()) { + return unchanged; + } + + const prompt = opening.content.replace(/\s+/g, " ").trim(); + if (prompt.length < OPENING_PROMPT_MIN_CHARS) return unchanged; + + try { + const scope = this.scope(); + if (!scope) return unchanged; + const hash = sha256([scope, containerTag, prompt].join("\n")); + const owner = this.#fresh()[hash]; + if (owner && owner.sessionId !== sessionID) { + return { + messages: [ + { + role: "user", + content: `[Opening prompt omitted: identical to one already captured from this machine (sha256:${hash.slice(0, 12)})]`, + }, + ...messages.slice(1), + ], + commit: () => {}, + }; + } + if (owner) return unchanged; + return { + messages, + commit: () => { + try { + const entries = this.#fresh(); + entries[hash] ??= { sessionId: sessionID, at: this.now() }; + writeEntries(this.file, newest(entries, MAX_OPENING_PROMPTS, (entry) => entry.at)); + } catch {} + }, + }; + } catch { + return unchanged; + } + } + + #fresh(): Entries<{ sessionId: string; at: number }> { + const now = this.now(); + return Object.fromEntries( + Object.entries(readEntries<{ sessionId: string; at: number }>(this.file)).filter( + ([, entry]) => + typeof entry?.at === "number" && + typeof entry.sessionId === "string" && + now - entry.at < OPENING_PROMPT_TTL_MS, + ), + ); + } +} + +/** Re-serves the last successful recall search per backend, credential, container tags and normalized query within the window. */ +export class RecallQueryCache { + constructor( + private readonly scope: () => string | null, + private readonly file = RECALL_QUERIES_FILE, + private readonly windowMs = RECALL_REPEAT_WINDOW_MS, + private readonly now: () => number = Date.now, + ) {} + + wrap( + containerTags: readonly string[], + search: (query: string) => Promise, + ): (query: string) => Promise { + return async (query) => { + const scope = this.scope(); + if (!scope) return search(query); + const hash = sha256( + [scope, ...containerTags, query.toLowerCase().replace(/\s+/g, " ").trim()].join("\n"), + ); + const cached = this.#fresh()[hash]; + if (cached) return cached.response; + + const response = await search(query); + if (response.success) { + try { + const entries = this.#fresh(); + entries[hash] = { at: this.now(), response }; + writeEntries(this.file, newest(entries, MAX_RECALL_QUERIES, (entry) => entry.at)); + } catch {} + } + return response; + }; + } + + #fresh(): Entries<{ at: number; response: SearchResponse }> { + const now = this.now(); + return Object.fromEntries( + Object.entries(readEntries<{ at: number; response: SearchResponse }>(this.file)).filter( + ([, entry]) => + typeof entry?.at === "number" && + entry.response?.success === true && + now - entry.at < this.windowMs, + ), + ); + } +} diff --git a/src/services/session-scope.test.ts b/src/services/session-scope.test.ts new file mode 100644 index 0000000..99c6b1b --- /dev/null +++ b/src/services/session-scope.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, test } from "bun:test"; + +import { + getProcessSkipReason, + isHeadlessCommand, + SessionScope, + type SessionScopeConfig, +} from "./session-scope.js"; + +const defaults: SessionScopeConfig = { + captureSubagents: false, + captureHeadless: false, + captureOrchestrated: true, +}; + +describe("session scope", () => { + test("detects OpenCode V1 headless commands from the host argv", () => { + const argv = (...args: string[]) => ["bun", "/$bunfs/root/opencode", ...args]; + expect(isHeadlessCommand(argv("run", "fix the bug"))).toBe(true); + expect(isHeadlessCommand(argv("--log-level", "INFO", "run", "hi"))).toBe(true); + expect(isHeadlessCommand(argv("--print-logs", "run"))).toBe(true); + expect(isHeadlessCommand(argv("github", "run"))).toBe(true); + expect(isHeadlessCommand(argv())).toBe(false); + expect(isHeadlessCommand(argv("./project"))).toBe(false); + expect(isHeadlessCommand(argv("serve"))).toBe(false); + expect(isHeadlessCommand(argv("github", "install"))).toBe(false); + expect(isHeadlessCommand(argv("--port", "4096", "run", "x"))).toBe(true); + expect(isHeadlessCommand(argv("-m", "p/m", "run", "x"))).toBe(true); + expect(isHeadlessCommand(argv("--prompt", "run"))).toBe(false); + expect(isHeadlessCommand(argv("--agent", "run"))).toBe(false); + expect(isHeadlessCommand(argv("-s", "run"))).toBe(false); + expect(isHeadlessCommand(argv("--port", "4096"))).toBe(false); + }); + + test("orchestrated sessions count as interactive unless opted out", () => { + const conductor = { CONDUCTOR_WORKSPACE_PATH: "/w/tokyo" }; + expect(getProcessSkipReason({ config: defaults, headless: true, env: {} })).toBe("headless"); + expect(getProcessSkipReason({ config: defaults, headless: true, env: conductor })).toBeNull(); + expect( + getProcessSkipReason({ config: { ...defaults, captureHeadless: true }, headless: true, env: {} }), + ).toBeNull(); + expect( + getProcessSkipReason({ + config: { ...defaults, captureOrchestrated: false }, + headless: false, + env: { VK_WORKSPACE_ID: "ws" }, + }), + ).toBe("orchestrated"); + }); + + test("skips child sessions unless captureSubagents is set", async () => { + const lookups: string[] = []; + const parents: Record = { child: "root" }; + const lookupParent = async (id: string) => { + lookups.push(id); + if (id === "broken") throw new Error("unavailable"); + return parents[id]; + }; + const scope = new SessionScope({ lookupParent, headless: false, config: defaults, env: {} }); + + expect(await scope.skipReason("root")).toBeNull(); + expect(await scope.skipReason("child")).toBe("subagent"); + expect(await scope.skipReason("child")).toBe("subagent"); + scope.note("noted", "root"); + expect(await scope.skipReason("noted")).toBe("subagent"); + expect(await scope.skipReason("broken")).toBeNull(); + expect(lookups).toEqual(["root", "child", "broken"]); + + const optedIn = new SessionScope({ + lookupParent, + headless: true, + config: { ...defaults, captureSubagents: true, captureHeadless: true }, + env: {}, + }); + expect(await optedIn.skipReason("child")).toBeNull(); + }); + + test("treats a hung parent lookup as a root session and retries it later", async () => { + let calls = 0; + const scope = new SessionScope({ + lookupParent: (id) => { + calls += 1; + return calls === 1 ? new Promise(() => {}) : Promise.resolve(id); + }, + headless: false, + config: defaults, + env: {}, + lookupTimeoutMs: 20, + }); + expect(await scope.skipReason("slow")).toBeNull(); + expect(await scope.skipReason("slow")).toBe("subagent"); + expect(calls).toBe(2); + }); +}); diff --git a/src/services/session-scope.ts b/src/services/session-scope.ts new file mode 100644 index 0000000..8bf6519 --- /dev/null +++ b/src/services/session-scope.ts @@ -0,0 +1,156 @@ +import { CONFIG } from "../config.js"; +import { log } from "./logger.js"; + +export type SessionSkipReason = "subagent" | "headless" | "orchestrated"; + +export type SessionScopeConfig = Pick< + typeof CONFIG, + "captureSubagents" | "captureHeadless" | "captureOrchestrated" +>; + +// Conductor (conductor.build/docs/reference/environment-variables) and Vibe Kanban +// (BloopAI/vibe-kanban crates/local-deployment/src/container.rs) set these for agents they run. +const ORCHESTRATOR_ENV_VARS = [ + "CONDUCTOR_WORKSPACE_PATH", + "CONDUCTOR_SESSION_ID", + "VK_WORKSPACE_ID", +] as const; + +// Global and default-command flags of opencode V1 (1.19) that take a value. +const VALUE_FLAGS = new Set([ + "--log-level", + "--port", + "--hostname", + "--mdns-domain", + "--cors", + "-m", + "--model", + "-s", + "--session", + "--prompt", + "--agent", + "--replay-limit", +]); + +export const PARENT_LOOKUP_TIMEOUT_MS = 2_000; + +export function isOrchestrated(env: NodeJS.ProcessEnv = process.env): boolean { + return ORCHESTRATOR_ENV_VARS.some((name) => Boolean(env[name]?.trim())); +} + +/** + * OpenCode V1 runs `opencode run` and `opencode github run` with the server and + * plugins in the CLI process (packages/opencode/src/cli/cmd/run.ts, github.ts). + */ +export function isHeadlessCommand(argv: readonly string[] = process.argv): boolean { + const positionals: string[] = []; + const args = argv.slice(2); + for (let index = 0; index < args.length && positionals.length < 2; index += 1) { + const arg = args[index] ?? ""; + if (arg === "--") break; + if (VALUE_FLAGS.has(arg)) { + index += 1; + continue; + } + if (!arg.startsWith("-")) positionals.push(arg); + } + return ( + positionals[0] === "run" || + (positionals[0] === "github" && positionals[1] === "run") + ); +} + +export function getProcessSkipReason(options: { + config: SessionScopeConfig; + headless: boolean; + env?: NodeJS.ProcessEnv; +}): SessionSkipReason | null { + if (isOrchestrated(options.env)) { + return options.config.captureOrchestrated ? null : "orchestrated"; + } + return options.headless && !options.config.captureHeadless ? "headless" : null; +} + +/** + * Decides whether a session gets automatic recall and capture. Child sessions + * (`parentID` set by the host's task/subagent tool) and headless runs are + * skipped unless the matching opt-in flag is set. + */ +export class SessionScope { + readonly #config: SessionScopeConfig; + readonly #processReason: SessionSkipReason | null; + readonly #lookupParent: (sessionID: string) => Promise; + readonly #lookupTimeoutMs: number; + readonly #children = new Map>(); + readonly #logged = new Set(); + + constructor(options: { + lookupParent: (sessionID: string) => Promise; + headless: boolean; + config?: SessionScopeConfig; + env?: NodeJS.ProcessEnv; + lookupTimeoutMs?: number; + }) { + this.#config = options.config ?? CONFIG; + this.#lookupParent = options.lookupParent; + this.#lookupTimeoutMs = options.lookupTimeoutMs ?? PARENT_LOOKUP_TIMEOUT_MS; + this.#processReason = getProcessSkipReason({ + config: this.#config, + headless: options.headless, + env: options.env, + }); + if (this.#processReason) { + log("Automatic memory disabled for this process", { reason: this.#processReason }); + } + } + + get processSkipReason(): SessionSkipReason | null { + return this.#processReason; + } + + note(sessionID: string | undefined, parentID: string | undefined): void { + if (sessionID && !this.#children.has(sessionID)) { + this.#children.set(sessionID, Promise.resolve(Boolean(parentID))); + } + } + + forget(sessionID: string): void { + this.#children.delete(sessionID); + this.#logged.delete(sessionID); + } + + async skipReason(sessionID: string): Promise { + if (this.#processReason) return this.#processReason; + if (this.#config.captureSubagents) return null; + + let isChild = this.#children.get(sessionID); + if (!isChild) { + let timer: ReturnType | undefined; + isChild = Promise.race([ + Promise.resolve().then(() => this.#lookupParent(sessionID)), + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error("OpenCode session lookup timed out")), + this.#lookupTimeoutMs, + ); + }), + ]) + .finally(() => clearTimeout(timer)) + .then( + (parentID) => Boolean(parentID), + () => { + this.#children.delete(sessionID); + return false; + }, + ); + this.#children.set(sessionID, isChild); + } + if (!(await isChild)) return null; + + if (!this.#logged.has(sessionID)) { + this.#logged.add(sessionID); + log("Automatic memory skipped for subagent session", { sessionID }); + } + return "subagent"; + } +} diff --git a/src/v2/runtime.test.ts b/src/v2/runtime.test.ts index 5a9fbe9..ee55cc4 100644 --- a/src/v2/runtime.test.ts +++ b/src/v2/runtime.test.ts @@ -189,6 +189,7 @@ function harness( get: async ({ sessionID }: { sessionID: string }) => ({ id: sessionID, location: { directory: "/repo" }, + ...(sessionID.startsWith("child") ? { parentID: "s1" } : {}), }), context: async () => state.transcript, }, @@ -394,6 +395,58 @@ describe("OpenCode 2 runtime", () => { h.runtime.cleanup(); }); + test("leaves subagent sessions alone unless captureSubagents is set", async () => { + const h = harness(); + await h.runtime.register(); + h.transcript = [user("u1", "explore the repo"), assistant("a1", "found it")]; + + const message = request("m1", "Find where the auth middleware lives"); + await h.runtime.handleContext({ sessionID: "child-1", messages: [message] }); + await h.runtime.handleCompaction({ sessionID: "child-1", system: [] }); + await h.runtime.handleEvent({ + id: "c1", + type: "session.execution.succeeded", + data: { sessionID: "child-1" }, + }); + await h.runtime.handleEvent({ id: "c2", type: "session.deleted", data: { sessionID: "child-1" } }); + await h.runtime.idle(); + expect(texts(message)).toEqual(["Find where the auth middleware lives"]); + expect(h.queries).toEqual([]); + expect(h.writes).toEqual([]); + h.runtime.cleanup(); + + const optedIn = harness({ captureSubagents: true }); + await optedIn.runtime.register(); + optedIn.transcript = [user("u1", "explore the repo"), assistant("a1", "found it")]; + await optedIn.runtime.handleContext({ + sessionID: "child-2", + messages: [request("m2", "Find where the auth middleware lives")], + }); + await optedIn.runtime.handleEvent({ + id: "c3", + type: "session.execution.succeeded", + data: { sessionID: "child-2" }, + }); + await optedIn.runtime.idle(); + expect(optedIn.queries).toHaveLength(1); + expect(optedIn.writes).toHaveLength(1); + optedIn.runtime.cleanup(); + + const v5 = harness({}, "v5"); + await v5.runtime.register(); + v5.transcript = [user("u1", "explore the repo"), assistant("a1", "found it")]; + await v5.runtime.handleCompaction({ sessionID: "child-3", system: [] }); + await v5.runtime.handleEvent({ + id: "c4", + type: "session.execution.succeeded", + data: { sessionID: "child-3" }, + }); + await v5.runtime.handleEvent({ id: "c5", type: "session.deleted", data: { sessionID: "child-3" } }); + await v5.runtime.idle(); + expect(v5.sessions).toEqual([]); + v5.runtime.cleanup(); + }); + test("captures completed turns idempotently and saves compaction summaries", async () => { const h = harness(); await h.runtime.register(); diff --git a/src/v2/runtime.ts b/src/v2/runtime.ts index 9ae8dd8..b277837 100644 --- a/src/v2/runtime.ts +++ b/src/v2/runtime.ts @@ -3,7 +3,7 @@ import { createHash } from "node:crypto"; import type { Plugin } from "@opencode/plugin"; import type { SessionHooks } from "@opencode/plugin/promise/session"; -import { CONFIG, getApiVersion, isConfigured, PLUGIN_VERSION } from "../config.js"; +import { CONFIG, getApiVersion, getDedupeScope, isConfigured, PLUGIN_VERSION } from "../config.js"; import { createMemoryActivityReporterFromSink, type MemoryActivityNotice, @@ -13,7 +13,9 @@ import { AUTOMATIC_CAPTURE_TIMEOUT_MS, buildCadenceBatches, buildSessionEndBatch, + defaultOpeningPromptIndex, getCaptureId, + prepareCaptureMessages, type CaptureBatch, type CaptureTurn, } from "../services/capture.js"; @@ -53,6 +55,8 @@ import { type DirectRecallResult, } from "../services/recall.js"; import { getTags, type ResolvedTags } from "../services/tags.js"; +import { OpeningPromptIndex, RecallQueryCache } from "../services/local-dedupe.js"; +import { SessionScope, type SessionScopeConfig } from "../services/session-scope.js"; import { checkNpmUpdate, type UpdateInfo } from "../services/version-check.js"; import { SUPERMEMORY_RPC } from "../rpc.js"; @@ -131,7 +135,8 @@ type RuntimeConfig = Pick< | "compactionEnabled" | "keywordPatterns" | "maxProjectMemories" ->; +> & + Partial; export interface V2RuntimeDependencies { /** Auth state; a function is re-checked per hook so login/logout apply live. */ @@ -142,6 +147,8 @@ export interface V2RuntimeDependencies { resolveTags: typeof getTags; logger: typeof log; checkUpdate: () => Promise; + openingPrompts: OpeningPromptIndex | null; + recallQueries: RecallQueryCache | null; apiVersion: typeof getApiVersion; } @@ -154,6 +161,8 @@ const DEFAULT_DEPENDENCIES: V2RuntimeDependencies = { logger: log, checkUpdate: () => checkNpmUpdate("opencode-supermemory", PLUGIN_VERSION, UPDATE_COMMAND), + openingPrompts: defaultOpeningPromptIndex(), + recallQueries: CONFIG.dedupeRecallQueries ? new RecallQueryCache(getDedupeScope) : null, apiVersion: getApiVersion, }; @@ -459,6 +468,7 @@ export class V2Runtime { readonly #deduper = new EventDeduper(); readonly #registrations: Registration[] = []; readonly #abortController = new AbortController(); + readonly #scope: SessionScope; #emitActivity: ((notice: MemoryActivityNotice) => void) | undefined; #activity: MemoryActivityReporter; #active = true; @@ -471,6 +481,13 @@ export class V2Runtime { this.#ctx = ctx; this.#deps = mergeDependencies(options); this.#isOwner = isOwner; + // OpenCode 2 gives plugins no per-session signal for `opencode run`, so only child sessions are detected here. + this.#scope = new SessionScope({ + headless: false, + config: { ...CONFIG, ...this.#deps.config }, + lookupParent: async (sessionID) => + ((await ctx.session.get({ sessionID })) as { parentID?: string }).parentID, + }); this.#activity = createMemoryActivityReporterFromSink((notice) => { this.#deps.logger("[activity]", { kind: notice.kind, message: notice.message }); this.#emitActivity?.(notice); @@ -675,6 +692,7 @@ export class V2Runtime { messages: RequestMessage[]; }): Promise { if (!this.#configured) return; + if (await this.#scope.skipReason(event.sessionID)) return; const latestUser = event.messages.findLast((message) => message.role === "user"); if (!latestUser) return; const userText = extractMessageText(latestUser); @@ -709,6 +727,7 @@ export class V2Runtime { system: Array<{ type: "text"; text: string }>; }): Promise { if (!this.#configured) return; + if (await this.#scope.skipReason(event.sessionID)) return; if (this.#deps.apiVersion() === "v5") { void this.#runCaptureExclusive(event.sessionID, () => this.#captureSession(event.sessionID), @@ -726,6 +745,13 @@ export class V2Runtime { async handleEvent(event: V2Event): Promise { if (!this.active || !this.#configured || this.#deduper.hasSeen(event.id)) return; const sessionID = this.#eventSessionID(event); + if (sessionID && (await this.#scope.skipReason(sessionID))) { + if (event.type === "session.deleted") { + this.#states.delete(sessionID); + this.#scope.forget(sessionID); + } + return; + } if (sessionID && event.type !== "session.compaction.ended") { void this.#retryPendingSummaries(sessionID); @@ -753,11 +779,15 @@ export class V2Runtime { if (!sessionID) return; const state = this.#states.get(sessionID); this.#recall.delete(sessionID); - if (!state) return; + if (!state) { + this.#scope.forget(sessionID); + return; + } await this.#runCaptureExclusive(sessionID, () => this.#captureSessionEnd(sessionID), ); this.#states.delete(sessionID); + this.#scope.forget(sessionID); return; } @@ -951,20 +981,26 @@ export class V2Runtime { count: 0, tokens: 0, }; + const searchForRecall = (query: string) => + memoryClient.searchMemoriesForRecall( + query, + tags.canonical, + tags.personalReads, + tags.projectReads, + { timeoutMs: DIRECT_RECALL_TIMEOUT_MS }, + ); const directRecall = config.recallMode === "direct" ? buildDirectRecallResult({ prompt: userText, sessionID, cache: this.#recall, - search: (query) => - memoryClient.searchMemoriesForRecall( - query, - tags.canonical, - tags.personalReads, - tags.projectReads, - { timeoutMs: DIRECT_RECALL_TIMEOUT_MS }, - ), + search: this.#deps.recallQueries + ? this.#deps.recallQueries.wrap( + [tags.canonical, ...tags.personalReads, ...tags.projectReads], + searchForRecall, + ) + : searchForRecall, suppressTexts: isFirstMessage ? profileRequest.then((result) => result?.success && result.profile @@ -1062,15 +1098,23 @@ export class V2Runtime { ): 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) { + if (batch.turns.every((turn) => turn.messages.length === 0)) { state.completedCaptureIds.add(captureId); return true; } let result: { success: boolean; error?: string }; + let commit = () => {}; try { const tags = await this.#resolveSession(sessionID); + const prepared = prepareCaptureMessages( + this.#deps.openingPrompts, + tags.canonical, + sessionID, + batch, + ); + commit = prepared.commit; + const messages = prepared.messages; result = await this.#deps.memoryClient.ingestConversation( `${sessionID}:${batch.startTurn}-${batch.endTurn}`, messages, @@ -1100,6 +1144,7 @@ export class V2Runtime { if (result.success) { state.completedCaptureIds.add(captureId); + commit(); this.#activity.saved(); this.#deps.logger("[capture] conversation batch saved", { sessionID, @@ -1121,6 +1166,7 @@ export class V2Runtime { } async #captureCadence(sessionID: string): Promise { + if (await this.#scope.skipReason(sessionID)) return; const state = this.#state(sessionID); if (this.#deps.apiVersion() === "v5") { const everyNTurns = this.#deps.config.captureEveryNTurns; @@ -1138,6 +1184,7 @@ export class V2Runtime { } async #captureSessionEnd(sessionID: string): Promise { + if (await this.#scope.skipReason(sessionID)) return; if (this.#deps.apiVersion() === "v5") { await this.#captureSession(sessionID); return; diff --git a/src/version.ts b/src/version.ts index 57237f3..4be058f 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.2.0"; +export const PLUGIN_VERSION = "2.3.0";