Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(opencode2): stop ending live sessions on plugin unload (#1074)

Vinícius DS Andrade364a9d24d73a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ca172515..fdefe2ae 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -151,6 +151,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`--agent-state` / credential flags into the repository's `.ai-jail`.
### Fixed
+- Fixed the generated OpenCode 2 plugin ending every tracked session when
+ OpenCode unloads it on idle-location eviction. Unload is not shutdown: the
+ host and its sessions stay alive, so each eviction froze a live session
+ (`SessionStart` cannot reopen an ended OpenCode session), fabricated a
+ spurious summary page and open handoff, and made the next baton fetch fail
+ with `invalid state: an ended session cannot accept a handoff`. Plugin
+ unload no longer posts `session-end`; deletion (`session.deleted`) remains
+ the end signal and a completed root turn already publishes its continuation
+ checkpoint and baton. Regenerate the plugin with
+ `ai-memory install-hooks --agent opencode2 --apply`. (#1074)
- Fixed the shell and PowerShell session-start hooks for Claude Code, Codex,
Cursor, Gemini CLI, OpenCode, Command Code, Devin, and Antigravity CLI not
sending the marker's `[briefing]` keys (`briefing`, `briefing_budget`) on the
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 1f66f043..e280964c 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -3302,8 +3302,8 @@ const OPENCODE2_BINDING: &str = r#"
type SessionInfo = Awaited<ReturnType<typeof ctx.session.get>>;
const sessions = new Map<SessionID, Promise<SessionInfo>>();
const assistantText = new Map<SessionID, string>();
- // Stops listening on unload. Deliveries keep `hookAbort` until the final
- // session-ends have had their drain budget.
+ // Stops listening on unload. Deliveries keep `hookAbort` until the queued
+ // events have had their drain budget.
const unload = new AbortController();
async function sessionInfo(id: SessionID): Promise<SessionInfo> {
@@ -3508,10 +3508,12 @@ const OPENCODE2_BINDING: &str = r#"
// Unload is best-effort; a dead host has nothing to unregister.
}
}
- for (const [id, pending] of sessions) {
- const session = await pending.catch(() => undefined);
- if (session) endSession(id, directory, undefined, subagentMarker(session));
- }
+ // Dispose is an unload, not a shutdown: OpenCode evicts idle location
+ // services and reloads this plugin while its sessions stay alive, so
+ // ending them here would freeze live sessions (a later SessionStart
+ // cannot reopen an ended session) and fabricate a baton and summary
+ // page per eviction (#1074). Real ends arrive as `session.deleted`, and
+ // each completed root turn already published its checkpoint and baton.
await drainHookQueueForDispose();
// Whatever is still in flight after the budget fails over to the spool.
hookAbort.abort();
@@ -9006,6 +9008,16 @@ model = "gpt-5"
// Hook registrations are disposed on unload so a reload cannot
// leave stale callbacks capturing twice.
assert!(plugin.contains("registration.dispose()"));
+ // #1074: OpenCode unloads the plugin on idle-location eviction while
+ // the host and its sessions stay alive, so dispose must not end
+ // tracked sessions. `session.deleted` (asserted above) stays the only
+ // end: the definition plus that one call are the whole `endSession`
+ // surface of the generated plugin.
+ assert_eq!(
+ plugin.matches("endSession(").count(),
+ 2,
+ "endSession must appear only as the definition and the session.deleted call"
+ );
// Pre-compaction arrives on its own start event; the completion
// event stays as the consolidation trigger, like v1.
assert!(plugin.contains("session.compaction.started"));
diff --git a/crates/ai-memory-cli/tests/fixtures/opencode2-plugin.mjs b/crates/ai-memory-cli/tests/fixtures/opencode2-plugin.mjs
index 3ad373bf..e600d613 100644
--- a/crates/ai-memory-cli/tests/fixtures/opencode2-plugin.mjs
+++ b/crates/ai-memory-cli/tests/fixtures/opencode2-plugin.mjs
@@ -107,11 +107,17 @@ try {
await b.hooks.get("session.prompt")({ sessionID: "root-b", messageID: "b1", prompt: { text: "beta" } });
await b.hooks.get("session.context")({ sessionID: "root-b", system: [] });
+ // Deletion, not unload, is the end signal: a deleted child keeps ancestry
+ // so its close does not hand the next session a sub-task baton.
+ a.emit({ type: "session.deleted", data: { sessionID: "child" } });
+ await until(() => requests.some((r) => r.url.searchParams.get("event") === "session-end" && r.payload.sessionID === "child"), "deleted session must end");
+ assert.equal(requests.find((r) => r.url.searchParams.get("event") === "session-end" && r.payload.sessionID === "child").payload.agent_id, "root-a", "child close must retain ancestry to suppress automatic handoffs");
+ // #1074: OpenCode unloads the plugin when it evicts idle location services;
+ // the host and its sessions stay alive, so unload must not end them.
await disposeA();
- assert.ok(requests.some((r) => r.url.searchParams.get("event") === "session-end" && r.payload.sessionID === "root-a"));
+ assert.ok(!requests.some((r) => r.url.searchParams.get("event") === "session-end" && r.payload.sessionID === "root-a"), "eviction unload must not end a live session");
assert.ok(!requests.some((r) => r.url.searchParams.get("event") === "session-end" && r.payload.sessionID === "root-b"), "location cleanup must not close another instance");
- assert.equal(requests.find((r) => r.url.searchParams.get("event") === "session-end" && r.payload.sessionID === "child").payload.agent_id, "root-a", "child close must retain ancestry to suppress automatic handoffs");
- console.log("PASS: resumed sessions, retained handoff, child isolation, terminal events, content-only output, per-location cleanup");
+ console.log("PASS: resumed sessions, retained handoff, child isolation, terminal events, deletion ends, unload does not");
} finally {
await disposeB();
}