Skip to content

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

Rust

Merge PR #622: first-party OpenCode 2.0 beta support [2.1]

AkitaOnRails30ef4812f89f
diff --cc CHANGELOG.md
index ae9779aa,d37948b7..33d89521
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -8,97 -8,26 +8,115 @@@ and this project adheres to [Semantic V
## [Unreleased]
### Added
+ - Added first-party OpenCode 2.0 beta (`opencode2`) support.
+ `install-mcp --client opencode2` merges the V2 `mcp.servers` remote entry
+ (no `enabled` field, `oauth: false` for header credentials);
+ `install-hooks --agent opencode2` writes an `ai-memory-opencode2.ts`
+ plugin in the beta `{ id, setup }` shape (no runtime dependency:
+ `Plugin.define` is identity), with handoff injection through the
+ `context` hook and the same `session.*` lifecycle coverage as v1;
+ `ai-memory run opencode2` launches through the `opencode2` binary and
+ imports the beta `session_v2`/`session_message` transcript. The beta
+ shares v1's config dir, session store, and agent kind, so no store
+ migration ships. Verified live against beta-18999 (hook capture,
+ handoff loop, managed launch/resume/import, `opencode↔opencode2`
+ session resume). Two beta caveats are documented: back up
+ `~/.local/share/opencode` first (the beta has migrated the shared
+ database in place before), and move its background service off port
+ 49374 when ai-memory serves there. Managed ledger-delta
+ acknowledgement does not fire through the shared background service
+ (redelivery, never loss); see the managed-workstreams notes (#622).
+- `install-hooks --agent codex` now wires Codex's `SessionEnd` hook, so a
+ finished Codex session gets the same automatic end-of-session summary
+ and cross-agent handoff Claude Code already gets. Codex shipped a
+ first-class `SessionEnd` event in Codex CLI 0.145.0 (openai/codex#33895);
+ the `hooks/codex/session-end.{sh,ps1}` scripts already existed and only
+ needed adding to the Codex hook profile. On older Codex the event key is
+ inert; `ai-memory finalize-session --agent codex` remains the fallback.
+ `merge_codex_payload` no longer strips a `SessionEnd` key on every apply
+ — a third-party `SessionEnd` hook is preserved alongside ours. ([#604])
+- `AI_MEMORY_LLM_HEADERS` (`llm_headers` in `config.toml`) attaches extra
+ HTTP headers to every LLM chat request, for gateways that require a
+ caller-identifying header. Entries are `Name=Value` or `Name: Value`,
+ comma separated in the env var. Parsed and validated once at the
+ configuration boundary, so a malformed entry fails at startup rather than
+ on the first consolidation pass, and providers consume typed header
+ material instead of operator strings. Headers ai-memory sets itself
+ (`authorization`, `content-type`, `x-api-key`, `x-goog-api-key`,
+ `anthropic-version`, `anthropic-beta`, `openai-beta`, `host`,
+ `content-length`) are refused: `reqwest` appends rather than replaces, so a
+ duplicate would break the request instead of overriding it. Values are
+ marked sensitive on the wire and never logged — the `Debug` output carries
+ header names only. ([#606])
+
+### Changed
+- Every LLM chat request now sends `User-Agent: ai-memory/<version>`.
+ `reqwest` sends no user agent unless one is configured, so provider
+ requests previously arrived anonymous, and gateways that require callers to
+ identify themselves reported ai-memory as an unknown client. An
+ `AI_MEMORY_LLM_HEADERS` entry for `user-agent` overrides it. The Copilot
+ provider is unchanged: it keeps `GitHubCopilotChat/<version>`, the
+ editor-plugin agent GitHub's Copilot API expects. ([#606])
+- `x-opencode-session` and the `opencode` user agent, both shipped in 2.0.2,
+ are now operator-overridable like any other header: an
+ `AI_MEMORY_LLM_HEADERS` entry for either name takes precedence over the
+ provider's default. The default remains 2.0.2's — one `LlmOperationId` per
+ logical operation, stable across retries and the strict/tolerant fallback —
+ so nothing changes unless an operator asks for it. Override the session
+ header to tell several ai-memory instances apart in OpenCode's metrics.
+ ([#606])
+- Release, Docker, and the `cargo install --git` snippet now build with
+ `--locked` (#628). Without it `cargo install` re-resolves dependencies and
+ ignores the committed `Cargo.lock`, so a source install could silently pull
+ a different `schemars` than the one tested — a plausible source of
+ build-to-build structured-output schema drift. A unit guard also asserts the
+ strict-schema normalizer keeps `required` equal to `properties` (and closes
+ open maps), catching that drift class at build time rather than in
+ production.
+- The `_pending/auto-improve/` sidecar no longer renders a `status:` line
+ (#624). It was written once at staging and could never change from
+ `pending` — no code path updates or garbage-collects the sidecar — so it
+ contradicted design principle 14 (SQLite owns approval status) and misled a
+ human (or a second agent) reading the file. Status lives in
+ `ai-memory pending-writes list` / SQLite; the sidecar is a staging-time
+ snapshot.
### Fixed
+- The OpenCode provider now sends `gpt-5.6-luna` requests to OpenCode Go's
+ Responses endpoint. Luna is not served through Chat Completions, where plain
+ and structured ai-memory calls returned HTTP 500 (#618).
+- `finalize-session --agent hermes` (and `claude-desktop`, `crush`, `other`)
+ is accepted again (#623). These agents are captured and stored, but
+ `finalize-session` reused the install-oriented agent enum — which is
+ deliberately limited to agents with a first-party installer — so it rejected
+ them at parse time and their sessions could never be closed, summarised, or
+ consolidated. `finalize-session` is agent-agnostic, so `--agent` now accepts
+ any agent the store recognises (a genuine typo is still rejected);
+ `install-hooks`/`setup-agent` stay limited. A drift guard keeps the two sets
+ from diverging again.
+- generated TypeScript integrations (`--agent open-code`, `omp`, `pi`,
+ `openclaw`) authenticate again under `install-hooks --apply`. Since #552
+ the bearer is deliberately omitted from the rendered file and persisted to
+ the 0600 `<data_dir>/auth-token` file, but only the native hook runtimes
+ learned to read it back: the generated TS adapters kept rendering
+ `TOKEN = null` with no runtime resolution, so every request they make
+ (hook capture, spool drain, handoff fetch) goes out unauthenticated and is
+ rejected by a Bearer-enabled server. The templates now render a
+ `resolveToken()` helper (static embed, then `AI_MEMORY_AUTH_TOKEN`, then
+ the auth-token file) used by `authHeaders()` and the spool writer.
+ `fetchHandoff()` in the same adapters also ignored `response.ok`, so a
+ 401 error body could be injected into model context as if it were a
+ handoff; non-OK responses now return `undefined` like other failures.
+- `bootstrap` now retries a chunk's LLM call on a transient error before
+ giving up, instead of letting one blip discard the whole multi-chunk run
+ (#617). A provider `5xx`/`429` or a transport timeout/connect failure on
+ chunk *n* previously aborted the run and threw away chunks *1..n-1* — the
+ reporter's own runs died repeatedly to provider `520`s and connection
+ resets. Each chunk now gets up to 3 short, fixed-delay attempts;
+ deterministic failures (auth, schema, a `4xx`, malformed JSON) are not
+ retried. The retry is deliberately short and bounded, not tenacity-style
+ escalating backoff (cognee #2840). A durable `--resume` for the rarer
+ crash/hard-failure case remains tracked separately in #617.
- `bootstrap` no longer aborts the whole multi-chunk run when one chunk
returns no `pages` key (#614). Later chunks are told which paths
earlier ones wrote, so a model that judges the material already
diff --cc crates/ai-memory-cli/src/commands/install_hooks.rs
index 119bb113,56b96751..23bc8b5c
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@@ -7637,6 -7919,91 +7923,94 @@@ model = "gpt-5
assert!(plugin.contains("url.searchParams.set(\"project\", repoProject)"));
}
+ #[test]
+ fn opencode2_plugin_binds_the_v2_api() {
+ let plugin = build_opencode2_plugin("http://127.0.0.1:49374", Some("tok"), None).unwrap();
+
+ // Ownership markers the uninstall gate keys on.
+ assert!(plugin.contains("install-hooks --agent opencode2 --apply"));
+ assert!(plugin.contains("const AGENT = \"opencode2\";"));
+ // Type-only import: `Plugin.define` is identity, and a runtime
+ // import does not resolve from the global plugins dir (the beta
+ // refuses the load). The host only needs the `{ id, setup }` shape.
+ assert!(plugin.contains("import type { Plugin } from \"@opencode-ai/plugin\";"));
+ assert!(!plugin.contains("export default Plugin.define"));
+ assert!(!plugin.contains("Plugin.define({"));
+ assert!(plugin.contains("const AiMemoryOpencode2: Plugin = {"));
+ assert!(plugin.contains("export default AiMemoryOpencode2;"));
+ // Beta hooks, verified against `@opencode-ai/plugin@beta`.
+ assert!(plugin.contains("ctx.event.subscribe"));
+ assert!(plugin.contains("ctx.session.hook(\"prompt\""));
+ assert!(plugin.contains("ctx.session.hook(\"context\""));
+ assert!(plugin.contains("ctx.tool.hook(\"execute.before\""));
+ assert!(plugin.contains("ctx.tool.hook(\"execute.after\""));
+ // V2 lifecycle envelopes carry `{ type, data, location }`.
+ for event in [
+ "session.created",
+ "session.idle",
+ "session.deleted",
+ "session.compacted",
+ ] {
+ assert!(plugin.contains(event), "missing {event}");
+ }
+ // Handoff injection moved off v1's removed experimental hook and
+ // fires once per session (the context hook runs per model call).
+ // System items are `{ type: "text", text }` objects on the V2 API, not strings.
+ assert!(plugin.contains("handoffInjected"));
+ assert!(plugin.contains("system.push({ type: \"text\", text: handoff })"));
+ assert!(!plugin.contains("experimental."));
+ // Hook registrations are disposed on unload so a reload cannot
+ // leave stale callbacks capturing twice.
+ assert!(plugin.contains("registration.dispose()"));
+ // Pre-compaction arrives on its own start event; the completion
+ // event stays as the consolidation trigger, like v1.
+ assert!(plugin.contains("session.compaction.started"));
+ // Tool failures share the channel with the reason preserved.
+ assert!(plugin.contains("status === \"error\""));
+ // No v1 remnants.
+ assert!(!plugin.contains("export default AiMemoryHooks"));
+ assert!(!plugin.contains("chat.message"));
+ // Shared capture prelude survived the rewrite byte-identical.
+ for shared in [
+ "function startSession",
+ "function endSession",
+ "postHook(\"session-start\"",
+ "postHook(\"user-prompt\"",
+ "function applyMarkerParams",
+ "requestSpoolDrain();",
+ ] {
+ assert!(plugin.contains(shared), "missing {shared}");
+ }
- assert!(plugin.contains("Bearer ${TOKEN}"));
++ // #625 made the generated adapters resolve the bearer at runtime
++ // (resolveToken() -> `${token}`) instead of the static `${TOKEN}`;
++ // the opencode2 plugin derives from v1 so it inherits that.
++ assert!(plugin.contains("Bearer ${token}"));
+ assert!(plugin.contains("tok"));
+ }
+
+ #[test]
+ fn opencode2_plugin_rejects_v1_template_drift() {
+ // The builder rewrites the v1 template, so a v1 edit that moves the
+ // binding anchor must fail loudly instead of shipping a hybrid.
+ let plugin =
+ build_opencode2_plugin("http://127.0.0.1:49374/", None, Some("repo-root")).unwrap();
+ assert!(plugin.contains("const TOKEN: string | null = null;"));
+ assert!(
+ plugin.contains("const DEFAULT_PROJECT_STRATEGY = \"repo-root\";"),
+ "strategy bake-through must survive the v2 rewrite"
+ );
+ }
+
+ #[test]
+ fn opencode2_anchor_rewrite_fails_loudly_on_drift() {
+ let err =
+ replace_opencode_anchor("no v1 anchors here", "missing", "x", "banner").unwrap_err();
+ assert!(
+ err.to_string().contains("banner"),
+ "drift must name the moved anchor: {err:#}"
+ );
+ }
+
#[test]
fn opencode_plugin_normalizes_payloads_without_legacy_wrapper() {
let plugin = build_opencode_plugin("http://127.0.0.1:49374/", None, None);
diff --cc docs/mcp-install.md
index 76da5bee,d292ea17..5ea64025
--- a/docs/mcp-install.md
+++ b/docs/mcp-install.md
@@@ -1277,11 -1277,13 +1277,13 @@@ that *starts* the next one - to play ni
| Side | What's needed | Covered by |
|---|---|---|
- | **Ending side** | The agent must create a handoff through a true session-end hook, the manual finalizer, or `memory_handoff_begin`. | Built-in automatically for Claude Code, Codex (native `SessionEnd`, Codex CLI 0.145.0+), Devin CLI, Cursor, Gemini CLI, Grok Build CLI, Zero, Kimi Code, OpenClaw, OpenCode, and OMP. Antigravity CLI, both Kiro CLI engines, and Command Code have no reliable true session-end event; run `ai-memory finalize-session` with the corresponding `--agent` after the final turn (also the fallback on Codex older than 0.145.0). MCP-only clients such as Swival must call `memory_handoff_begin` explicitly. |
- | **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 / Devin CLI / Cursor / Gemini CLI / Antigravity CLI / Kimi Code / both Kiro CLI engines / Command Code / OpenClaw / OpenCode / OMP. It requires a client that consumes startup-hook stdout or an equivalent context-injection result. Grok and Zero discard SessionStart stdout; Swival is MCP-only. Use (b) for those clients. (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). |
-| **Ending side** | The agent must create a handoff through a true session-end hook, the manual finalizer, or `memory_handoff_begin`. | Built-in automatically for Claude Code, Devin CLI, Cursor, Gemini CLI, Grok Build CLI, Zero, Kimi Code, OpenClaw, OpenCode, OpenCode 2 beta, and OMP. Codex, Antigravity CLI, both Kiro CLI engines, and Command Code have no reliable true session-end event; run `ai-memory finalize-session` with the corresponding `--agent` after the final turn. MCP-only clients such as Swival must call `memory_handoff_begin` explicitly. |
++| **Ending side** | The agent must create a handoff through a true session-end hook, the manual finalizer, or `memory_handoff_begin`. | Built-in automatically for Claude Code, Codex (native `SessionEnd`, Codex CLI 0.145.0+), Devin CLI, Cursor, Gemini CLI, Grok Build CLI, Zero, Kimi Code, OpenClaw, OpenCode, OpenCode 2 beta, and OMP. Antigravity CLI, both Kiro CLI engines, and Command Code have no reliable true session-end event; run `ai-memory finalize-session` with the corresponding `--agent` after the final turn (also the fallback on Codex older than 0.145.0). MCP-only clients such as Swival must call `memory_handoff_begin` explicitly. |
+ | **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 / Devin CLI / Cursor / Gemini CLI / Antigravity CLI / Kimi Code / both Kiro CLI engines / Command Code / OpenClaw / OpenCode / OpenCode 2 beta / OMP. It requires a client that consumes startup-hook stdout or an equivalent context-injection result. Grok and Zero discard SessionStart stdout; Swival is MCP-only. Use (b) for those clients. (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
+ delivery. The OpenCode 2 beta plugin subscribes to the same event name on the
+ V2 event stream and injects handoffs through the `context` hook instead of
+ v1's removed `experimental.chat.system.transform`. 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.