Skip to content

fix(opencode): emit a V2-compatible plugin module - #11792

Closed
umi008 wants to merge 1 commit into
stablyai:mainfrom
umi008:fix/issue-11768-opencode-plugin-v2
Closed

umi008 wants to merge 1 commit into
stablyai:mainfrom
umi008:fix/issue-11768-opencode-plugin-v2

Conversation

@umi008

@umi008 umi008 commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #11768

The generated OpenCode status plugin (orca-opencode-status.js) only shipped the V1 named-export factory, so opencode 2.x rejected the module: its loader validates the module default export as a define'd { id, setup } object (define() is identity), and a bare function default fails schema validation.

  • Kept the V1 named-export factory (OrcaOpenCodeStatusPlugin) byte-compatible — the engine body is untouched, only renamed to an internal createOrcaOpenCodeStatusPlugin.
  • Added a default export carrying id / server / setup:
    • server keeps the V1 readV1Plugin path working on the same default object (verified against the opencode loader: default object with id + server is accepted; a default object without server would throw in the legacy path).
    • id + setup satisfy the V2 schema so the module loads under opencode 2.x.
  • The V2 setup guards on ctx.event.subscribe being a function: V2's PluginContext intentionally does not expose session events or the server client yet (per the opencode v2 plugin README), so it logs once ("status reporting disabled") instead of failing. When a future V2 build exposes ctx.event.subscribe, it subscribes all 11 known event types and routes them into the existing engine defensively (onValue / pipe({onValue}) / async-iterable, each in try/catch).

Verified against anomalyco/opencode dev-branch loader sources (readV1Plugin, legacy fallback, packages/plugin/src/v2/*, fixture config-promise-plugin.ts).

Screenshots

No visual change.

Testing

  • pnpm lint — passes (oxlint clean)
  • pnpm typecheck — passes (3× tsc --noEmit)
  • pnpm test — targeted suites: hook-service.test.ts 33/33 (7 new/updated pins + 4 new behavioral V2-contract tests), hook-plugin-* 61/61 unchanged, relay plugin suites 34/34 unchanged. Full suite not run.
  • Added or updated high-quality tests — 4 behavioral tests import the generated module from a temp .mjs and pin: default-export shape, server V1 contract, setup({}) no-op guard, and 11-type subscription routing to a SessionBusy POST
  • pnpm build — not run (heavy desktop build)

AI Review Report

  • Correctness: engine body byte-identical after the rename (internal string pins for const client = _ctx?.client; and the hook URL keep passing); V1 loader compatibility verified for both loader paths (default-object-with-server and legacy function exports — the named export stays a callable factory, proven by the 4 unchanged hook-plugin-* behavioral suites).
  • Reliability lens: 1 WARNING (V2 setup has no teardown for its 11 subscriptions — informational, process-lifetime status reporter) and 1 SUGGESTION (only the onValue stream branch is covered by tests; pipe/async-iterable branches are defensive fallbacks). No blockers.
  • Cross-platform: this change is a generated-JS template emitted identically on macOS, Linux, and Windows (local overlay + shared config + SSH relay install paths are transport-only and unchanged). The V1 path that every current Orca install uses is unaffected; only the added default export is new. No platform-specific code added.
  • Gap disclosed: no opencode V2 host was available in this environment. V2 loadability is verified structurally against opencode's own loader source and via dynamic-import behavioral tests, not on a live V2 binary.

Security Audit

  • No new input handling, authentication surface, secrets, or dependencies.
  • The generated module remains self-contained (no imports; the V2 define identity is inlined).
  • Event payloads are POSTed to the same localhost hook endpoint with the same X-Orca-Agent-Hook-Token as before — unchanged trust boundary.

Notes

  • Regression source: the V1-only export shape dates from the original plugin generation in hook-service.ts; opencode 2.x made the default-export contract load-bearing.

  • Worst case on V2 without ctx.event.subscribe: one console.debug line per setup, no functional regression on V1.

  • X: @umillann

The generated orca-opencode-status.js only shipped the V1 named-export factory, so opencode 2.x rejected the module (its loader validates the default export as a define'd { id, setup } object; define() is identity).

Keep the V1 named factory byte-compatible and add a default export carrying id/server/setup: the server key keeps the V1 readV1Plugin path working on the same default object, while id + setup satisfy the V2 schema so the module loads. The V2 setup guards on ctx.event.subscribe (V2 PluginContext does not expose session events or the client yet) and logs once instead of failing.

Verified against anomalyco/opencode dev loader sources; covered by 4 new behavioral tests (default-export shape, server contract, no-event-API guard, 11-type subscription routing) plus updated string pins. hook-plugin-* and relay plugin suites unchanged and green.
@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The OpenCode hook service now uses a reusable plugin factory and exports an OpenCode V2 default plugin with metadata, server creation, and setup handling. Setup supports multiple event stream interfaces, subscribes to known lifecycle and message events, forwards events to the shared hook handler, and logs unsupported or failed subscriptions. Tests dynamically load generated modules and cover V1 hooks, V2 exports, setup without events, subscriptions, and event forwarding.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR adds the required V2 default export, preserves V1 compatibility, handles V2 events, and adds regression tests for issue #11768.
Out of Scope Changes check ✅ Passed The changes are limited to OpenCode plugin generation and related regression tests, with no unrelated scope identified.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly identifies the main change: adding an OpenCode V2-compatible plugin module while preserving the existing integration.
Description check ✅ Passed The description covers all template sections, explains the implementation and risks, and clearly documents testing limits and cross-platform review.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/main/opencode/hook-service.test.ts (1)

249-294: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the pipe and async-iterator subscription branches.

This test only exercises the stream.onValue branch of setup. The implementation in hook-service.ts (Line 1022-1025) also supports stream.pipe and Symbol.asyncIterator streams, but neither branch has a test. Since this test's own mock defines the shape of subscribe's return value, it cannot catch a mismatch between the mock and any of the untested branches.

Add two more mock stream shapes (one exposing pipe, one exposing Symbol.asyncIterator) and confirm events routed through each still reach hooks.event.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 89e2345f-70e4-4003-b1aa-0266f0066e3e

📥 Commits

Reviewing files that changed from the base of the PR and between 79251d7 and ee8b06d.

📒 Files selected for processing (2)
  • src/main/opencode/hook-service.test.ts
  • src/main/opencode/hook-service.ts

Comment on lines +997 to +1031
'',
'// opencode V1: named-export factory (legacy loader contract).',
'export const OrcaOpenCodeStatusPlugin = createOrcaOpenCodeStatusPlugin;',
'',
"// opencode V2: module default export is the define'd plugin object (define()",
'// is identity). `server` also keeps the V1 readV1Plugin path on the same',
'// default export; `id` + `setup` satisfy the V2 schema so the module loads.',
'export default {',
' id: "orca-opencode-status",',
' server: createOrcaOpenCodeStatusPlugin,',
' setup: async (ctx) => {',
' const subscribe = ctx?.event?.subscribe',
' if (typeof subscribe !== "function") {',
' // V2 does not expose session events on PluginContext yet.',
' console.debug("[orca-opencode-status] opencode 2.x does not expose session events on the plugin context; status reporting disabled")',
' return',
' }',
' const hooks = await createOrcaOpenCodeStatusPlugin(ctx)',
' if (!hooks?.event) return',
' const types = ["session.status","session.idle","session.error","permission.asked","permission.replied","question.asked","question.replied","question.rejected","message.updated","message.part.updated","message.part.delta"]',
' for (const type of types) {',
' try {',
' const stream = subscribe(type)',
' const onEvent = (event) => { void hooks.event({ event }).catch(() => {}) }',
' if (stream?.onValue) stream.onValue(onEvent)',
' else if (stream?.pipe) stream.pipe({ onValue: onEvent })',
' else if (stream && typeof stream[Symbol.asyncIterator] === "function") {',
' void (async () => { for await (const event of stream) onEvent(event) })().catch(() => {})',
' }',
' } catch (error) {',
' console.debug("[orca-opencode-status] failed to subscribe to", type, error)',
' }',
' }',
' }',
'};',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🌐 Web query:

What is the exact PluginContext shape and event subscription API for OpenCode plugin V2 setup()?

💡 Result:

In OpenCode plugin V2, the setup function receives a PluginContext object, which acts as a server client providing access to core system domains [1]. PluginContext Shape The PluginContext interface includes the following primary domains and utilities [2][1]: - options: Readonly options derived from the plugin's configuration [2][1]. - agent: Domain for agent management (list, get, transform, reload) [1]. - catalog: Domain for model and provider management (transform, reload) [1]. - command: Domain for command management (list, transform, reload) [1]. - integration: Domain for managing connections and service integrations [1]. - plugin: Domain for managing plugin lifecycles and listing active plugin IDs [1]. - reference: Domain for reference management [1]. - skill: Domain for skill management [1]. - session: Domain for interacting with sessions (create, prompt, etc.) [1]. - aisdk: Domain providing hooks into the AI SDK [2][1]. - event: Provides the event subscription API [1]. Event Subscription API Plugins subscribe to the public server event stream via the event domain within the context [1]. The standard method is: await ctx.event.subscribe This returns an event stream (often used with an asynchronous iteration pattern) [3]. The setup function is intended for registering long-lived behavior and should not be used to block on infinite event streams directly without careful lifecycle management (e.g., triggering background tasks) [1]. While the setup function may return a cleanup function that the OpenCode server will await upon plugin deactivation or reload, it should remain responsive [1]. Note that some documentation variants or older plugin structures may utilize a different context object (e.g., containing project, client, or $) [4][3] or use a central Bus object for event subscription [5], but the V2 PluginContext as defined in the core repository follows the structure outlined above [2][1].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Repository files matching hook-service.ts:\n'
fd -a 'hook-service\.ts$' . || true

file="$(fd 'hook-service\.ts$' . | head -n 1 || true)"
if [ -n "$file" ]; then
  printf '\nFile: %s\n' "$file"
  wc -l "$file"
  printf '\nRelevant section (lines 960-1050):\n'
  sed -n '960,1050p' "$file" | nl -ba -v960
fi

printf '\nSearch for createOrcaOpenCodeStatusPlugin and related symbols:\n'
rg -n "createOrcaOpenCodeStatusPlugin|activeFactoryIDs|hooks.dispose|ctx.event.subscribe|ctx\.event\.subscribe|Plugin\.define|export default|OrcaOpenCodeStatusPlugin" . || true

Repository: stablyai/orca

Length of output: 1182


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file="./src/main/opencode/hook-service.ts"

if [ -f "$file" ]; then
  printf 'File: %s\n' "$file"
  wc -l "$file"
  printf '\nRelevant section (lines 960-1050):\n'
  sed -n '960,1050p' "$file" | awk '{printf "%5d     %s\n", NR+959, $0}'
else
  printf 'File not found: %s\n' "$file"
fi

printf '\nSearch for createOrcaOpenCodeStatusPlugin and related symbols:\n'
rg -n "createOrcaOpenCodeStatusPlugin|activeFactoryIDs|hooks.dispose|ctx.event.subscribe|ctx\.event\.subscribe|Plugin\.define|export default|OrcaOpenCodeStatusPlugin" . || true

Repository: stablyai/orca

Length of output: 50370


🌐 Web query:

OpenCode V2 ctx.event.subscribe plugin event API Plugin.define setup context

💡 Result:

In OpenCode V2, plugins are structured using the Plugin.define API, which provides a setup function that receives a context (ctx) object [1]. This context acts as an interface to the OpenCode server, allowing plugins to perform actions, register hooks, and interact with the system [1]. Plugin.define and Setup Context Plugins are defined by exporting the result of Plugin.define, which takes an object containing an id and a setup function [1]. The setup function is executed every time the plugin is activated [1]. Example: import { Plugin } from "@opencode-ai/plugin" export default Plugin.define({ id: "my-plugin", setup: async (ctx) => { // Register long-lived behavior or hooks here }, }) The setup function can return a cleanup function, which OpenCode will automatically await when the plugin is disabled, reloaded, or shut down [1]. ctx.event.subscribe The ctx.event.subscribe method allows plugins to subscribe to the public server event stream [2][1]. This is a core capability for responding to real-time system events [3]. Usage Example: The following example demonstrates subscribing to the server event stream within a plugin [4]: export const EventStream: Plugin = async (ctx) => { const events = await ctx.client.event.subscribe;(async => { for await (const event of events) { if (event.type === "session.error") { console.error("Session error:", event.properties) } } }) return {} } Important Considerations: 1. Volatility: The event stream is volatile; if a consumer is too slow, the stream will overflow and fail [5]. Events occurring during a disconnection may be missed [5]. 2. Setup Guidelines: The setup function itself should be used for registration; avoid waiting on an infinite event stream directly inside the setup function to prevent blocking the initialization process [1]. 3. Event Types: Plugins can listen to a wide range of system events, including session events (e.g., session.idle, session.error), command events, file events, and tool execution events [3][6].

Citations:


🌐 Web query:

@opencode-ai/plugin Plugin.define V2 source ctx context

💡 Result:

In OpenCode V2, Plugin.define is used to create a plugin module by exporting an object with an id and a setup function [1][2][3]. This approach replaces the V1 plugin structure [3][4]. The setup function receives a ctx (context) object, which serves as a client for the OpenCode server [1][2]. The context provides methods to interact with various server capabilities, including agents, catalogs, sessions, and tools [1][2]. Example usage: import { Plugin } from "@opencode-ai/plugin" export default Plugin.define({ id: "your-plugin-id", setup: async (ctx) => { // Access context capabilities await ctx.agent.transform((agents) => { // Perform transformations or register hooks }) }, }) The ctx object includes specialized methods for managing plugin behavior, such as: - ctx.agent: Operations like list, get, and transform [1][2]. - ctx.session: Methods for hooks, prompts, and session management [1][2]. - ctx.tool: Methods for tool hooking and transformation [1][2]. - ctx.options: Access to readonly configuration options provided by the matching config object [1][2]. - ctx.event: Subscription to the public server event stream [1][2]. This architecture allows plugins to dynamically modify agent behavior, inject context, or extend server functionality through the provided API surface [1][2].

Citations:


🌐 Web query:

site:github.com/anomalyco/opencode ctx.event.subscribe setup await

💡 Result:

In the context of the Opencode SDK, ctx.event.subscribe is an asynchronous method used to establish a subscription to a server-sent event (SSE) stream [1][2][3]. To use it, you must await the initial subscription call and then iterate over the resulting stream [4][2][5]. Implementation Pattern When subscribing, the method returns an object containing a stream property (or behaves as an iterable, depending on the specific version and configuration of your SDK) [4][2]. The standard pattern involves using an async loop to process events as they arrive [2][5]. Example usage: const events = await client.event.subscribe({ signal: abortController.signal }); for await (const event of events.stream) { console.log('Received event:', event.type, event.properties); // Handle event based on type } Key Considerations 1. Stream Handling: The result of the await is typically a stream object [2]. If you encounter a type error suggesting the object is not async iterable, ensure you are accessing the.stream property, which is explicitly designed to be iterated [4][2]. 2. AbortController: Always pass an AbortController signal to the subscribe method [1][2]. This allows you to properly terminate the network connection when the component unmounts or the operation is cancelled, preventing memory leaks and orphaned connections [1][2][6]. 3. Reconnection Logic: Because event streams are long-lived and susceptible to network interruptions, robust implementations often wrap the subscription in a loop (e.g., while(true)) with reconnection logic and error handling [1][6]. 4. Context: This pattern is commonly used in React hooks or CLI integrations to bridge server-side events to local application state [1][2][6]. If you are experiencing issues with the stream not being iterable, verify your SDK version and ensure the underlying generated code correctly supports streaming as per your project's configuration [4].

Citations:


🌐 Web query:

"ctx.event.subscribe(type)" "Plugin.define" OpenCode

💡 Result:

In OpenCode, Plugin.define and ctx.event.subscribe are components of the plugin architecture used to extend the platform's functionality [1][2]. Plugin.define Plugin.define is a function used to create and export a plugin module [1][2]. It typically takes an object containing an id and a setup function [1][2]. The setup function is executed when the plugin is activated and receives a context object (ctx), which provides access to various platform capabilities [1][2]. Example structure: import { Plugin } from "@opencode-ai/plugin" export default Plugin.define({ id: "my-plugin-id", setup: async (ctx) => { // Plugin initialization and capability usage }, }) ctx.event.subscribe ctx.event.subscribe is an API method available within the plugin context that allows plugins to subscribe to the public server event stream [1]. It enables plugins to react to real-time events occurring within the OpenCode environment [3][4]. Example usage: // Typically used within the setup or a hooked function const events = await ctx.event.subscribe // Consume the stream as needed Plugin vs. Events It is important to distinguish between hooks and bus events [5]. Plugin hooks (e.g., ctx.session.hook) are used for modifying or responding to specific lifecycle events in a blocking or synchronous manner, whereas event streams (via ctx.event.subscribe) are typically used for observing events on the bus [5]. Note: The OpenCode plugin system, particularly in v2, is subject to active development, and some capabilities may depend on specific build versions [6][7]. Always refer to the official documentation for the version of OpenCode you are targeting [1][2].

Citations:


🌐 Web query:

opencode plugin core src Plugin.define context.event.subscribe implementation

💡 Result:

In the OpenCode framework, Plugin.define and context.event.subscribe are core components for building plugins and interacting with system events [1]. Plugin.define The Plugin.define function is the standard factory used to register a plugin [1][2]. It accepts a configuration object that defines the plugin's identity (id) and setup logic (an effect) [3][4][1]. Example structure: import { Plugin } from "@opencode-ai/plugin" export default Plugin.define({ id: "your-plugin-id", setup: async (ctx) => { // Plugin logic and registrations go here }, }) context.event.subscribe The ctx.event.subscribe method allows a plugin to listen to the public server event stream [1]. This capability is provided through the PluginContext (ctx), which acts as a client interface for the plugin [1]. When you call ctx.event.subscribe, it typically returns a stream of events that your plugin can process [1][5]. Implementation context: The plugin's setup effect receives a PluginContext (ctx) [1]. The ctx object includes specialized capabilities, including ctx.event, which exposes the subscribe method [1]. Because OpenCode is built using the Effect ecosystem, these operations return Effect-native types such as Streams, enabling type-safe and composable event handling [5][6]. Registration: Plugin definitions are registered in the OpenCode core system, often via a batch operation or a service that manages plugin lifecycles and scopes [3][7][4]. When a plugin is loaded, the framework injects the PluginContext, ensuring that capabilities like event subscriptions are scoped to the plugin's lifecycle and cleaned up when the plugin is unloaded [1][6].

Citations:


🌐 Web query:

github.com/anomalyco/opdecode packages/plugin/src/v2 Plugin.define source

💡 Result:

The Plugin.define method in the OpenCode v2 plugin system is the primary entry point for defining plugins, typically exported as the default module export [1][2]. It is located within the @opencode-ai/plugin package, specifically under the v2 subpath [3]. Key details regarding Plugin.define: 1. Functionality: It is used to register plugin metadata (such as an ID) and define behavior through a setup function or effects [1]. 2. Structure: A typical plugin definition looks like this: export default Plugin.define({ id: "your-plugin-id", setup: async (ctx) => { // Plugin logic and hook registrations go here }, }) 3. Context: The setup function receives a PluginContext (ctx), which provides access to various system hooks (agent, command, integration, etc.) allowing the plugin to interact with the OpenCode lifecycle [1][4]. 4. Cleanup: The setup function can return an asynchronous or synchronous cleanup function, which OpenCode automatically executes when the plugin is disabled, reloaded, or the host shuts down [1]. The source code for the v2 plugin infrastructure, including the definition of the plugin system and its context, can be found in the anomalyco/opencode repository under packages/plugin/src/v2/ [3]. The core runtime logic that handles these definitions is managed in packages/core/src/plugin.ts [5].

Citations:


🌐 Web query:

raw.githubusercontent.com anomalyco/opencode packages/plugin/src/v2/effect/context.ts PluginContext subscribe

💡 Result:

In the OpenCode codebase, the PluginContext interface defined in packages/plugin/src/v2/effect/context.ts acts as a structured gateway for plugin interaction with the system, exposing various domain-specific hooks such as agent, command, and integration [1]. Regarding the subscribe method specifically: 1. The PluginContext interface in packages/plugin/src/v2/effect/context.ts does not explicitly define a subscribe method in the provided source snapshot [1]. 2. Instead, event subscription in the OpenCode plugin system is generally handled through the plugin's exported hooks object [2][3] or specific event-driven abstractions [4]. 3. Plugins typically subscribe to system events by hooking into the event system provided by the platform (e.g., session.updated, tool.execute.after) [2][3]. 4. Other projects that share naming conventions (like openacp or external SDKs) utilize a ctx.on() pattern for subscribing to events [5][6][7], rather than a subscribe method directly on the PluginContext object [1]. If you are developing a plugin, you should consult the packages/plugin/src/index.ts file to see the currently supported hooks [8], as these represent the primary way to observe and modify system behavior in the OpenCode architecture [2][3].

Citations:


Use Plugin defined export semantics and the async event subscription lifecycle.

OpenCode V2 plugin setup receives a PluginContext with event subscription support, but ctx.event.subscribe must be awaited and does not match a synchronous subscribe(type) stream API. Keep the raw object default export if the legacy V1 loader path depends on it, but handle the V2 event stream through the upstream EventStream/async iteration pattern instead of onValue/pipe checks.

@greptile-apps

greptile-apps Bot commented Jul 31, 2026

Copy link
Copy Markdown

Greptile Summary

This PR fixes a V2 compatibility regression in the generated OpenCode status plugin (orca-opencode-status.js). The plugin previously only shipped a V1 named-export factory; opencode 2.x requires the module's default export to be a define-produced { id, setup } object, which the old plugin didn't provide.

  • The internal factory is renamed from an exported function (OrcaOpenCodeStatusPlugin) to an unexported one (createOrcaOpenCodeStatusPlugin), with the V1 named export preserved as an alias to maintain backward compatibility.
  • A default export is added carrying id, server (aliased to the V1 factory for the legacy readV1Plugin path), and setup (V2 subscriber logic guarded behind ctx.event.subscribe availability).
  • Four new behavioral tests dynamically import the generated module as real ESM and pin the default-export shape, V1 contract, no-op guard, and end-to-end SessionBusy POST routing.

Confidence Score: 4/5

Safe to merge; the V1 path is unchanged and the V2 additions are guarded behind an availability check that currently always takes the no-op branch.

The engine body is untouched (byte-identical aside from the rename), the V1 named-export contract is preserved, and the V2 setup correctly short-circuits when ctx.event.subscribe is absent (which is always the case on current V2 builds). The defensive null-client guard already in the engine means it degrades gracefully when invoked without a client. The two speculative stream branches (pipe and async-iterator) in setup are untested and the pipe branch may not correctly register handlers in standard observable APIs, but those paths are only reachable from a future V2 build that exposes session events.

Files Needing Attention: The generated-source string array in hook-service.ts (lines 1004–1031) is where the V2 logic lives; the pipe stream-subscription branch there may need revisiting once opencode V2 actually exposes ctx.event.subscribe and the real stream shape is known.

Important Files Changed

Filename Overview
src/main/opencode/hook-service.ts Refactors the internal plugin factory from an exported function to an unexported one, re-exports it as the V1 named factory, and adds a V2-compatible default export with id/server/setup. The setup guard correctly handles the current V2 state (no ctx.event.subscribe), and the engine's existing defensive null-client guard means it degrades gracefully when called from V2 context. The pipe branch in setup may not correctly register handlers for observable APIs where pipe is a transformation operator.
src/main/opencode/hook-service.test.ts Adds 4 new behavioral tests that dynamically import the generated module as a real ESM (.mjs) file to verify the V2 default-export shape, V1 server contract, no-op setup guard, and end-to-end event routing to a SessionBusy POST. Only the onValue stream branch is covered; pipe and async-iterator paths are not tested.

Sequence Diagram

sequenceDiagram
    participant OC1 as opencode V1 loader
    participant OC2 as opencode V2 loader
    participant Module as orca-opencode-status.js
    participant Engine as createOrcaOpenCodeStatusPlugin
    participant Orca as Orca hook endpoint

    Note over Module: export const OrcaOpenCodeStatusPlugin = createOrcaOpenCodeStatusPlugin (V1 named)
    Note over Module: export default { id, server, setup } (V2 default)

    OC1->>Module: import named OrcaOpenCodeStatusPlugin
    Module-->>OC1: factory function (V1 contract)
    OC1->>Engine: "factory(ctx) → { event(), dispose() }"
    Engine->>Orca: POST /hook/opencode on each event

    OC2->>Module: import default export
    Module-->>OC2: "{ id, server, setup }"
    OC2->>Module: setup(ctx)
    alt ctx.event.subscribe is not a function (current V2)
        Module-->>OC2: console.debug + return (no-op)
    else ctx.event.subscribe is a function (future V2)
        Module->>Engine: createOrcaOpenCodeStatusPlugin(ctx)
        Engine-->>Module: "hooks { event(), dispose() }"
        loop for each of 11 event types
            Module->>OC2: subscribe(type) → stream
            OC2-->>Module: stream (onValue / pipe / asyncIterator)
            Module->>Module: stream.onValue(onEvent)
        end
        OC2->>Module: stream emits event
        Module->>Orca: POST /hook/opencode via hooks.event()
    end
Loading

Reviews (1): Last reviewed commit: "fix(opencode): emit a V2-compatible plug..." | Re-trigger Greptile

Comment on lines +1007 to +1031
' setup: async (ctx) => {',
' const subscribe = ctx?.event?.subscribe',
' if (typeof subscribe !== "function") {',
' // V2 does not expose session events on PluginContext yet.',
' console.debug("[orca-opencode-status] opencode 2.x does not expose session events on the plugin context; status reporting disabled")',
' return',
' }',
' const hooks = await createOrcaOpenCodeStatusPlugin(ctx)',
' if (!hooks?.event) return',
' const types = ["session.status","session.idle","session.error","permission.asked","permission.replied","question.asked","question.replied","question.rejected","message.updated","message.part.updated","message.part.delta"]',
' for (const type of types) {',
' try {',
' const stream = subscribe(type)',
' const onEvent = (event) => { void hooks.event({ event }).catch(() => {}) }',
' if (stream?.onValue) stream.onValue(onEvent)',
' else if (stream?.pipe) stream.pipe({ onValue: onEvent })',
' else if (stream && typeof stream[Symbol.asyncIterator] === "function") {',
' void (async () => { for await (const event of stream) onEvent(event) })().catch(() => {})',
' }',
' } catch (error) {',
' console.debug("[orca-opencode-status] failed to subscribe to", type, error)',
' }',
' }',
' }',
'};',

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 V2 setup has no teardown path

The setup function subscribes to 11 event types but returns void instead of a cleanup function. If opencode V2 ever adds a teardown lifecycle (the V2 plugin README currently doesn't expose one, per the PR description), all subscriptions from that plugin instance would leak indefinitely. For the async-iterator branch in particular, the for await loop has no cancellation signal, so the loop keeps running even after any future teardown. This is acknowledged in the PR as a process-lifetime reporter, but worth noting explicitly for when the V2 API evolves.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +1021 to +1023
' if (stream?.onValue) stream.onValue(onEvent)',
' else if (stream?.pipe) stream.pipe({ onValue: onEvent })',
' else if (stream && typeof stream[Symbol.asyncIterator] === "function") {',

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 The pipe branch passes { onValue: onEvent } to stream.pipe(), but most observable libraries (RxJS, Bacon.js) treat pipe as a transformation operator that returns a new stream — not a subscription call. Calling it with an observer-shape object either throws or silently no-ops, so events would be dropped if a future V2 stream has pipe but not onValue. Adding a stream.subscribe check (the RxJS sink convention) before the pipe branch would cover more stream shapes.

Suggested change
' if (stream?.onValue) stream.onValue(onEvent)',
' else if (stream?.pipe) stream.pipe({ onValue: onEvent })',
' else if (stream && typeof stream[Symbol.asyncIterator] === "function") {',
' if (stream?.onValue) stream.onValue(onEvent)',
' else if (stream?.subscribe) stream.subscribe(onEvent)',
' else if (stream?.pipe) stream.pipe({ onValue: onEvent })',
' else if (stream && typeof stream[Symbol.asyncIterator] === "function") {',

@nwparker

nwparker commented Oct 4, 2026

Copy link
Copy Markdown
Contributor

Superseded by the OpenCode plugin support now on main, including merged #24662. Credit to @umi008 for the original V2 loader fix and compatibility work.

Verified with installed OpenCode 2.0.16: the original V1-only generated module is rejected; the production-selected V2 module loads. A real question-tool turn then produces busy and question events, consumes the Unicode answer, and returns to idle with a successful session. The V1 export remains selected for V1 hosts.

This verifies plugin loading and the event bridge. It does not claim a full desktop/sidebar test. Closing this older implementation because its requested behavior is covered by the merged code.

@nwparker nwparker closed this Oct 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: OpenCode status plugin (orca-opencode-status.js) fails to load under opencode V2

4 participants