memorix icon indicating copy to clipboard operation
memorix copied to clipboard

OpenCode: message.updated event not working, no hook captures AI response

Open skywalker-35 opened this issue 7 months ago • 2 comments

Summary

The OpenCode plugin template generated by memorix hooks install is missing the message.updated event. However, even after manually adding it, the event does not fire because OpenCode's plugin system does not map message.updated as a standalone plugin hook key (unlike session.created, file.edited, etc.).

This means OpenCode is the only supported agent that cannot capture AI response content via hooks.

Environment

  • memorix: 1.0.8
  • OpenCode: latest (TUI mode on Windows 11)
  • OS: Windows 11

Details

1. Installer template is incomplete

The generateOpenCodePlugin() function in src/hooks/installers/index.ts (OPENCODE_PLUGIN_VERSION=3) generates events:

events: ['session_start', 'session_end', 'post_tool', 'post_edit', 'post_compact', 'post_command']
// Missing: post_response / message.updated

All other agents include post_response:

  • Windsurf: post_cascade_response
  • Antigravity: AfterAgent
  • Gemini CLI: AfterAgent
  • Claude Code: Stop

2. Even when manually added, it doesn't work

OpenCode's plugin system has two hook types:

  • Interceptor hooks: registered as direct keys (e.g., tool.execute.after) — these work
  • Bus events: subscribed via the catch-all event hook — message.updated is one of these

session.created and file.edited work as direct keys because OpenCode internally maps them. But message.updated has no such mapping — registering it as a direct plugin key has no effect.

Furthermore, OpenCode's message.updated bus event fires on updateMessage() (metadata changes like editing a message), not when an AI response completes. This is a semantic mismatch with memorix's post_response mapping.

3. No equivalent hook exists in OpenCode

OpenCode currently has no plugin hook that fires when an AI assistant response is generated. Comparison:

Agent Captures AI response OpenCode equivalent
Claude Code Stop None
Windsurf post_cascade_response None
Gemini CLI AfterAgent / AfterModel None
OpenCode None None

Suggestions

  1. Document the limitation: Update the OpenCode row in the event mapping table and installation docs to note that post_response is not available for OpenCode
  2. Consider chat.message interceptor: OpenCode has a chat.message interceptor hook that receives { message, parts } in the output — this might be able to capture assistant messages if it fires for both user and assistant turns
  3. Upstream request: Consider filing a feature request with sst/opencode for a post_response / assistant.response plugin hook

Workaround

For OpenCode users, the only reliable approach is to configure agent rules (AGENTS.md) that instruct the AI to proactively call memorix_store after completing valuable tasks, rather than relying on automatic hook capture.

skywalker-35 avatar Apr 27 '26 07:04 skywalker-35

I looked into opencode-notifier, a plugin that faces a similar problem (detecting when AI finishes). Its approach could serve as a temporary workaround for OpenCode, though with notable caveats.


Temporary workaround: session.idle + client.session.messages()

opencode-notifier successfully detects "AI finished" events by subscribing to OpenCode's event bus. The relevant pattern:

How it works

// 1. Listen on the catch-all event hook
event: async ({ event }) => {
  // 2. Track when work starts
  if (
    event.type === "session.status" &&
    event.properties.status.type === "busy"
  ) {
    markSessionBusy(event.properties.sessionID);
  }

  // 3. When session goes idle, it likely means AI finished
  if (event.type === "session.idle") {
    scheduleSessionIdle(client, config, projectName, event, sessionID);
    // 350ms delay then fetch messages via SDK:
    // const messages = await client.session.messages({ path: { id: sessionID } })
    // → last assistant message gives you the AI response
  }
};

This is production-proven — the plugin has 500+ stars and 50+ forks.

Why it could work for memorix

  • session.idle is empirically the closest event to "AI finished generating"
  • client.session.messages() is an available SDK call that returns full message history
  • You can extract the last role === "assistant" message and pass it to memorix_store

Known caveats

Issue Impact Mitigation
Timing race When session.idle fires, the last AI message may not be fully written to the session store yet Deferred fetch (350ms + configurable delay, like notifier does)
False positives User stops typing, network drops, or AI gets cancelled in the middle — all produce session.idle without a complete response Check message content for truncation/error markers; use sequence numbers to deduplicate
Missed messages Rapid back-and-forth: a new busy can override before idle handler runs Debounce with session-scoped sequence counters (notifier already does this)
No 1:1 mapping One session.idle does not correspond to one specific user prompt → can miss or duplicate captures Track the last-captured message timestamp to avoid re-capturing
Message format uncertainty The shape of client.session.messages() response may change between SDK versions Validate structure before extracting content

Expected capture rate

Realistically ~80-90% of AI responses would be captured with this approach. The remaining ~10-20% would be lost to timing races or false idle events.

Recommended hybrid strategy

session.idle → try SDK capture (best effort)
         ↓ fallback
AGENTS.md: "After completing a response, call memorix_store"

This way:

  • Most responses are captured automatically via session.idle
  • The remaining ones are covered by the agent proactively calling memorix_store
  • No response is missed entirely

FurryWolfX avatar Apr 28 '26 13:04 FurryWolfX

Thanks, I dug through this more carefully and patched it locally with tests.

Two separate problems were hiding here:

  1. the OpenCode installer was not wiring post_response through its returned events set
  2. even with message.updated recognized by the normalizer, the payload path and handler thresholds meant AI responses were still not being turned into observations reliably

I also re-checked the current OpenCode plugin docs. message.updated and session.idle are both official plugin events, but the docs do not promise that message.updated alone is the final response boundary.

So the safer fix is:

  • subscribe to message.updated in the OpenCode plugin
  • cache the latest assistant message text
  • flush that cached assistant response to Memorix on session.idle as post_response

That gives Memorix a stable end-of-turn capture path without pretending every intermediate message update is the final answer.

Validation I added locally:

  • normalizer test for OpenCode message.updated -> post_response
  • OpenCode e2e pipeline tests for assistant response capture
  • installer/plugin content tests for the new event wiring
  • npm run lint passes

So yes: this issue is real, and the fix should be to treat message.updated plus session.idle as a paired strategy rather than only adding a missing string to the template.

AVIDS2 avatar Apr 28 '26 13:04 AVIDS2