Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(opencode): dedupe plugin session close
AkitaOnRails57052bfddb1a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9724e0ec..f29de938 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed+- OpenCode generated plugins now close sessions from the official+ `session.deleted` event and a deduped best-effort `dispose` fallback, so+ OpenCode sessions can produce automatic session summaries and handoffs without+ duplicate `session-end` emissions.+## [1.6.0] - 2026-07-01### Fixeddiff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 0bbf8721..66d995ad 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -1169,12 +1169,14 @@ const HOOK_FLUSH_INTERVAL_MS = 2000;const HOOK_FLUSH_THRESHOLD = 20;const HOOK_INTER_REQUEST_DELAY_MS = 50;const HOOK_REQUEST_TIMEOUT_MS = 2000;+const HOOK_DISPOSE_DRAIN_BUDGET_MS = 2000;const HOOK_IMMEDIATE_EVENTS = new Set(["session-start", "stop", "session-end", "pre-compact"]);type HookQueueItem = {{ event: string; url: URL; payload: Record<string, unknown> }};const hookQueue: HookQueueItem[] = [];let hookFlushTimer: ReturnType<typeof setTimeout> | undefined;let hookDraining = false;+let hookDrainPromise: Promise<void> | undefined;function sleep(ms: number): Promise<void> {{return new Promise((resolve) => setTimeout(resolve, ms));@@ -1184,16 +1186,37 @@ function scheduleHookFlush(): void {{if (hookFlushTimer) return;hookFlushTimer = setTimeout(() => {{hookFlushTimer = undefined;- void drainHookQueue();+ void requestHookDrain();}}, HOOK_FLUSH_INTERVAL_MS);hookFlushTimer.unref?.();}}+function requestHookDrain(): Promise<void> {{+ if (!hookDrainPromise) {{+ hookDrainPromise = drainHookQueue().finally(() => {{+ hookDrainPromise = undefined;+ if (hookQueue.length > 0) void requestHookDrain();+ }});+ }}+ return hookDrainPromise;+}}++function disposeDrainTimeout(): Promise<void> {{+ return new Promise((resolve) => {{+ const timer = setTimeout(resolve, HOOK_DISPOSE_DRAIN_BUDGET_MS);+ timer.unref?.();+ }});+}}++async function drainHookQueueForDispose(): Promise<void> {{+ await Promise.race([requestHookDrain(), disposeDrainTimeout()]);+}}+function enqueueHook(event: string, url: URL, payload: Record<string, unknown>): void {{if (hookQueue.length >= HOOK_QUEUE_MAX) hookQueue.shift();hookQueue.push({{ event, url, payload }});if (HOOK_IMMEDIATE_EVENTS.has(event) || hookQueue.length >= HOOK_FLUSH_THRESHOLD) {{- void drainHookQueue();+ void requestHookDrain();}} else {{scheduleHookFlush();}}@@ -1224,7 +1247,6 @@ async function drainHookQueue(): Promise<void> {{}}}} finally {{hookDraining = false;- if (hookQueue.length > 0) void drainHookQueue();}}}}@@ -1312,6 +1334,15 @@ function startSession(id: string | undefined, cwd: string, extra: Record<string,postHook("session-start", {{ sessionID: id, cwd, ...extra }});}}+function endSession(id: string | undefined, directory: string, cwd?: string): void {{+ if (!id || !startedSessions.delete(id)) return;+ const resolvedCwd = cwd || cwdFor(id, directory);+ postHook("session-end", {{ sessionID: id, cwd: resolvedCwd }});+ sessionCwds.delete(id);+ handoffChecked.delete(id);+ preCompactLast.delete(id);+}}+function postPreCompact(id: string | undefined, directory: string): void {{startSession(id, cwdFor(id, directory));const key = id || "unknown";@@ -1354,10 +1385,10 @@ async function fetchHandoff(cwd: string): Promise<string | undefined> {{export const AiMemoryHooks: Plugin = async ({{ directory }}) => {{return {{dispose: async () => {{- for (const id of startedSessions) {{- postHook("session-end", {{ sessionID: id, cwd: cwdFor(id, directory) }});+ for (const id of Array.from(startedSessions)) {{+ endSession(id, directory);}}- startedSessions.clear();+ await drainHookQueueForDispose();}},event: async (input) => {{const event = (input as any).event;@@ -1379,8 +1410,7 @@ export const AiMemoryHooks: Plugin = async ({{ directory }}) => {{if (event?.type === "session.deleted") {{const info = properties.info ?? {{}};const id = properties.sessionID ?? info.id;- const cwd = info.directory ?? cwdFor(id, directory);- postHook("session-end", {{ sessionID: id, cwd }});+ endSession(id, directory, info.directory);}}if (event?.type === "session.compacted") {{const id = properties.sessionID;@@ -3241,6 +3271,7 @@ model = "gpt-5"assert!(plugin.contains("export default AiMemoryHooks"));assert!(plugin.contains("const startedSessions = new Set<string>();"));assert!(plugin.contains("function startSession"));+ assert!(plugin.contains("function endSession"));assert!(plugin.contains("fetchHandoff"));assert!(plugin.contains("function applyMarkerParams"));assert!(plugin.contains("readFileSync(marker, \"utf8\")"));@@ -3255,9 +3286,25 @@ model = "gpt-5"assert!(plugin.contains("applyMarkerParams(url, cwd);"));assert!(plugin.contains("postPreCompact"));assert!(plugin.contains("dispose: async () =>"));+ assert!(plugin.contains("const HOOK_DISPOSE_DRAIN_BUDGET_MS = 2000;"));+ assert!(plugin.contains("let hookDrainPromise: Promise<void> | undefined;"));+ assert!(plugin.contains("function requestHookDrain(): Promise<void>"));+ assert!(plugin.contains("function disposeDrainTimeout(): Promise<void>"));+ assert!(plugin.contains("timer.unref?.();"));+ assert!(plugin.contains("async function drainHookQueueForDispose(): Promise<void>"));+ assert!(plugin.contains("for (const id of Array.from(startedSessions))"));+ assert!(plugin.contains("await drainHookQueueForDispose();"));assert!(plugin.contains("postHook(\"session-start\""));assert!(plugin.contains(r#""session.deleted")"#));- assert!(plugin.contains("postHook(\"session-end\""));+ assert_eq!(+ plugin.matches("postHook(\"session-end\"").count(),+ 1,+ "OpenCode generated plugin must route session closes through one idempotent helper"+ );+ assert!(plugin.contains("!startedSessions.delete(id)"));+ assert!(plugin.contains("sessionCwds.delete(id);"));+ assert!(plugin.contains("handoffChecked.delete(id);"));+ assert!(plugin.contains("preCompactLast.delete(id);"));assert!(plugin.contains("postHook(\"user-prompt\""));assert!(plugin.contains("Bearer ${TOKEN}"));assert!(plugin.contains("tok"));diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 0329d733..fb8349d1 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -59,9 +59,8 @@ from hook paths.3. On true `SessionEnd` events, the server synthesises a`sessions/<id>.md` summary page (rule-based, no LLM) and opens a`Handoff` row for the next agent. Auto-commits the wiki. Clients- without a true session-end hook (currently OpenCode and Antigravity- CLI) should call `memory_handoff_begin` before quitting when a- handoff is needed.+ without a true session-end hook (currently Antigravity CLI) should call+ `memory_handoff_begin` before quitting when a handoff is needed.4. When `AI_MEMORY_LLM_PROVIDER` is set, `memory_consolidate` rewritesthat summary into a richer durable page or fans out into amulti-page batch under `concepts/`, `decisions/`, `gotchas/`.diff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex dd78667e..2927ff30 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -553,9 +553,15 @@ that *starts* the next one - to play nicely with ai-memory:| Side | What's needed | Covered by ||---|---|---|-| **Ending side** | The agent must create a handoff, either through a true session-end hook or by calling `memory_handoff_begin`. | Built-in for Claude Code, Cursor, Gemini CLI, Grok Build CLI, OpenClaw, and OMP. Codex, OpenCode, and Antigravity CLI have no true session-end event in the current integration, so ask them to call `memory_handoff_begin` before quitting when you need a handoff. |+| **Ending side** | The agent must create a handoff, either through a true session-end hook or by calling `memory_handoff_begin`. | Built-in for Claude Code, Cursor, Gemini CLI, Grok Build CLI, OpenClaw, OpenCode, and OMP. Codex and Antigravity CLI have no true session-end event in the current integration, so ask them to call `memory_handoff_begin` before quitting when you need a handoff. || **Starting side** | Either (a) the session-start/plugin path injects the handoff via `/handoff`, OR (b) the model proactively calls `memory_handoff_accept` on first turn. | (a) is built-in for Claude Code / Codex / Cursor / Gemini CLI / Antigravity CLI / OpenClaw / OpenCode / OMP. Grok is explicitly excluded because it ignores SessionStart stdout; use (b). (b) works for any MCP-capable client if you nudge the model - see [the managed routing package](usage.md#install-the-routing-snippet-and-agent-skills). |+OpenCode uses its official `session.deleted` plugin event for true session-end+delivery. Its generated plugin also sends a deduped best-effort close for any+still-active sessions from `dispose` during normal plugin teardown; abrupt+process exits can still lose that fallback, so `session.deleted` remains the+primary close path.+So a typical mixed workflow looks like:- **Claude Code → Cursor.** Claude Code's `SessionEnd` creates the