Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

fix(opencode): make the 2.x plugin observable, report shadowed copies, honor OPENCODE_CONFIG_DIR (#1285)

kyle-elliott-asymptotef8518e56c138
diff --git a/cli/beacon/cmd/endpoint_cli_regression_test.go b/cli/beacon/cmd/endpoint_cli_regression_test.go
index 2372fcbf..0a76640b 100644
--- a/cli/beacon/cmd/endpoint_cli_regression_test.go
+++ b/cli/beacon/cmd/endpoint_cli_regression_test.go
@@ -176,7 +176,7 @@ func TestEverySessionSyncIsAQuietNoOpWithoutItsRuntime(t *testing.T) {
testenv.SetHome(t, home)
// Each runtime's own directory override would otherwise point outside the empty home.
for _, key := range []string{"CLAUDE_CONFIG_DIR", "CODEX_HOME", "COPILOT_HOME", "CURSOR_CONFIG_DIR", "CLINE_DIR", "DSH_HOME",
- "HERMES_HOME", "HERMES_DATA_DIR_SUFFIX", "OPENCLAW_STATE_DIR", "OPENCODE_DB", "PI_CODING_AGENT_DIR",
+ "HERMES_HOME", "HERMES_DATA_DIR_SUFFIX", "OPENCLAW_STATE_DIR", "OPENCODE_CONFIG_DIR", "OPENCODE_DB", "PI_CODING_AGENT_DIR",
"PRIME_AGENT_CODING_AGENT_DIR", "XDG_CONFIG_HOME", "XDG_DATA_HOME"} {
t.Setenv(key, "")
}
diff --git a/cli/beacon/cmd/endpoint_hooks.go b/cli/beacon/cmd/endpoint_hooks.go
index b7b18a5b..2df2be0a 100644
--- a/cli/beacon/cmd/endpoint_hooks.go
+++ b/cli/beacon/cmd/endpoint_hooks.go
@@ -151,6 +151,12 @@ func installEndpointHookTargetTo(report, notes io.Writer, name string, cfg endpo
return err
}
fmt.Fprintf(report, "opencode plugin installed: %s\n", status.PluginPath)
+ if len(status.IgnoredPluginPaths) > 0 {
+ fmt.Fprintln(notes, status.Message)
+ }
+ if status.DefaultPluginPath != "" {
+ fmt.Fprintf(notes, "Beacon's opencode plugin is also at %s, which OpenCode sessions started without OPENCODE_CONFIG_DIR use. OpenCode 1.x sessions started with it load both copies and record each event twice. If every OpenCode session sets OPENCODE_CONFIG_DIR, remove that file.\n", status.DefaultPluginPath)
+ }
case "cline":
status, err := endpointhooks.InstallCline(endpointhooks.ClineOptions{
Level: endpointhooks.Level(endpointOpts.hookLevel),
diff --git a/cli/beacon/cmd/mcp_connect_test.go b/cli/beacon/cmd/mcp_connect_test.go
index ddc39e45..0b51b1a2 100644
--- a/cli/beacon/cmd/mcp_connect_test.go
+++ b/cli/beacon/cmd/mcp_connect_test.go
@@ -74,7 +74,7 @@ func newMCPFixture(t *testing.T, detected ...string) *mcpFixture {
t.Helper()
fx := &mcpFixture{home: t.TempDir(), requests: &requestLog{}, strays: &requestLog{}, auth: &requestLog{}}
testenv.SetHome(t, fx.home)
- for _, key := range []string{"XDG_CONFIG_HOME", "CLAUDE_CONFIG_DIR", "CODEX_HOME", "PI_CODING_AGENT_DIR", "PI_CONFIG_DIR", "OMP_PROFILE", "PI_PROFILE", "CI", "CONTINUOUS_INTEGRATION", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE", "JENKINS_URL", "TEAMCITY_VERSION"} {
+ for _, key := range []string{"XDG_CONFIG_HOME", "OPENCODE_CONFIG_DIR", "CLAUDE_CONFIG_DIR", "CODEX_HOME", "PI_CODING_AGENT_DIR", "PI_CONFIG_DIR", "OMP_PROFILE", "PI_PROFILE", "CI", "CONTINUOUS_INTEGRATION", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE", "JENKINS_URL", "TEAMCITY_VERSION"} {
t.Setenv(key, "")
os.Unsetenv(key)
}
diff --git a/cli/beacon/internal/endpoint/harness/opencode_test.go b/cli/beacon/internal/endpoint/harness/opencode_test.go
index 53794d29..6a29900b 100644
--- a/cli/beacon/internal/endpoint/harness/opencode_test.go
+++ b/cli/beacon/internal/endpoint/harness/opencode_test.go
@@ -16,6 +16,7 @@ func TestDiscoverOpenCodeHonorsXDGConfigHome(t *testing.T) {
t.Setenv("PATH", t.TempDir())
xdg := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", xdg)
+ t.Setenv("OPENCODE_CONFIG_DIR", "")
pluginPath := filepath.Join(xdg, "opencode", "plugins", "beacon.ts")
if err := os.MkdirAll(filepath.Dir(pluginPath), 0755); err != nil {
t.Fatal(err)
diff --git a/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts b/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts
index 85fc79ed..a2e29843 100644
--- a/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts
+++ b/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts
@@ -2,9 +2,16 @@
// Beacon endpoint telemetry plugin for opencode.
// Managed by beacon endpoint hooks install --harness opencode.
+import { appendFile, mkdir } from "node:fs/promises"
+import { homedir } from "node:os"
+import { dirname, join } from "node:path"
+
const beaconCommand = "__BEACON_COMMAND__"
const pluginID = "beacon.endpoint"
const debugEnabled = process.env.BEACON_OPENCODE_DEBUG === "1"
+// OpenCode 2.x gives plugins no logger and discards the server's stderr unless it runs
+// standalone with --print-logs, so debug lines without client.app.log go to this file.
+const debugFile = join(homedir(), ".beacon", "endpoint", "logs", "opencode-plugin-debug.log")
const sendTimeoutMs = 2000
const directHookTypes = new Set([
"chat.message",
@@ -33,13 +40,20 @@ const forwardedEvents = new Set([
async function debugLog(client, message, extra) {
if (!debugEnabled) return
try {
- await client?.app?.log?.({
- body: {
- service: "beacon-opencode-plugin",
- level: "debug",
- message,
- extra,
- },
+ if (typeof client?.app?.log === "function") {
+ await client.app.log({
+ body: {
+ service: "beacon-opencode-plugin",
+ level: "debug",
+ message,
+ extra,
+ },
+ })
+ return
+ }
+ await mkdir(dirname(debugFile), { recursive: true, mode: 0o700 })
+ await appendFile(debugFile, JSON.stringify({ time: new Date().toISOString(), message, extra }) + "\n", {
+ mode: 0o600,
})
} catch {
// Debug logging must stay best-effort.
@@ -459,7 +473,10 @@ function v2Events(event, models) {
const created = typeof event?.created === "number" ? event.created : Date.now()
switch (event?.type) {
case "session.created":
- case "session.model.selected": {
+ case "session.model.selected":
+ // The step is the one event that always names the model: OpenCode often creates a session
+ // before the plugin's event stream is subscribed, and a default model is never "selected".
+ case "session.step.started": {
const model = v2Model(data.model)
if (sid && model) models.set(sid, model)
if (event.type !== "session.created") return []
@@ -551,16 +568,24 @@ export default {
})
const models = new Map()
const registrations = []
+ const registered = []
const register = async (domain, name, callback) => {
+ if (typeof domain?.hook !== "function") {
+ await debugLog(ctx, "Beacon V2 hook API unavailable", { name })
+ return
+ }
try {
- const registration = await domain?.hook?.(name, async (input) => {
+ const registration = await domain.hook(name, async (input) => {
try {
await callback(input)
} catch (err) {
await debugLog(ctx, "Beacon V2 hook failed", { name, error: String(err) })
}
})
- if (registration) registrations.push(registration)
+ if (registration) {
+ registrations.push(registration)
+ registered.push(name)
+ }
} catch (err) {
await debugLog(ctx, "Beacon V2 hook registration failed", { name, error: String(err) })
}
@@ -610,6 +635,11 @@ export default {
},
})
})
+ await debugLog(ctx, "Beacon V2 setup complete", {
+ opencode: ctx?.app?.version,
+ hooks: registered,
+ events: typeof ctx?.event?.subscribe === "function",
+ })
const controller = new AbortController()
const consuming = (async () => {
diff --git a/cli/beacon/internal/endpoint/hooks/opencode.go b/cli/beacon/internal/endpoint/hooks/opencode.go
index 30afcc46..7df22dbf 100644
--- a/cli/beacon/internal/endpoint/hooks/opencode.go
+++ b/cli/beacon/internal/endpoint/hooks/opencode.go
@@ -4,6 +4,8 @@ import (
"fmt"
"os"
"path/filepath"
+ "runtime"
+ "sort"
"strings"
opencodeplugin "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks/assets/opencode"
@@ -27,6 +29,13 @@ type OpenCodeStatus struct {
BinaryPath string `json:"binary_path,omitempty"`
PluginPath string `json:"plugin_path,omitempty"`
Message string `json:"message,omitempty"`
+ // IgnoredPluginPaths are Beacon plugin copies OpenCode loads but never runs, because another
+ // copy with the same plugin ID loads before them. It includes PluginPath when that is one.
+ IgnoredPluginPaths []string `json:"ignored_plugin_paths,omitempty"`
+ // DefaultPluginPath is Beacon's user-level plugin in OpenCode's default config directory while
+ // OPENCODE_CONFIG_DIR moves the one Beacon manages elsewhere. Sessions started without the
+ // variable still use it, so install leaves it in place; uninstall removes it.
+ DefaultPluginPath string `json:"default_plugin_path,omitempty"`
}
var opencodeRuntime = hookRuntime{
@@ -42,7 +51,9 @@ func InstallOpenCode(opts OpenCodeOptions) (OpenCodeStatus, error) {
if err != nil {
return OpenCodeStatus{}, err
}
- return opencodeStatusFromRuntime(status), nil
+ out := opencodeStatusFromRuntime(status)
+ out.DefaultPluginPath = opencodeDefaultDirPlugin(opts.Level)
+ return out, nil
}
func UninstallOpenCode(opts OpenCodeOptions) (OpenCodeStatus, error) {
@@ -50,7 +61,46 @@ func UninstallOpenCode(opts OpenCodeOptions) (OpenCodeStatus, error) {
if err != nil {
return OpenCodeStatus{}, err
}
- return opencodeStatusFromRuntime(status), nil
+ out := opencodeStatusFromRuntime(status)
+ if path := opencodeDefaultDirPlugin(opts.Level); path != "" {
+ if _, err := removeOpenCodePlugin(path); err != nil {
+ return OpenCodeStatus{}, err
+ }
+ out.DefaultPluginPath = path
+ out.Message += fmt.Sprintf("; also removed the Beacon plugin at %s", path)
+ }
+ return out, nil
+}
+
+// opencodeDefaultDirPlugin returns Beacon's user-level plugin in the default config directory when
+// OPENCODE_CONFIG_DIR moves the one Beacon manages elsewhere, or "" when there is none. An earlier
+// Beacon, or an install run without the variable, wrote it. Sessions started without the variable
+// load only that copy, OpenCode 1.x sessions started with it load both, and nothing else reports
+// it. The two directories are compared by identity, not by name, so a symlink or a case-folding
+// filesystem never makes the managed copy look like a second one.
+func opencodeDefaultDirPlugin(level Level) string {
+ if (level != "" && level != LevelUser) || os.Getenv("OPENCODE_CONFIG_DIR") == "" {
+ return ""
+ }
+ home, _ := os.UserHomeDir()
+ dir, err := opencodeDefaultConfigDir(home)
+ if err != nil {
+ return ""
+ }
+ path := filepath.Join(dir, "plugins", opencodePluginFileName)
+ current, err := opencodePluginPath(level)
+ if err != nil || current == path {
+ return ""
+ }
+ if a, err := os.Stat(filepath.Dir(current)); err == nil {
+ if b, err := os.Stat(filepath.Dir(path)); err == nil && os.SameFile(a, b) {
+ return ""
+ }
+ }
+ if !isOpenCodeInstalledAt(path) {
+ return ""
+ }
+ return path
}
func OpenCodeHookStatus(opts OpenCodeOptions) OpenCodeStatus {
@@ -75,14 +125,138 @@ func opencodeStatusFromRuntime(status runtimeStatus) OpenCodeStatus {
return out
}
data, err := os.ReadFile(out.PluginPath)
- if err != nil || !strings.Contains(string(data), out.BinaryPath) || strings.Contains(string(data), "__BEACON_") {
+ // Search for the binary as the renderer wrote it: shell-quoted, then a %q string literal,
+ // which doubles a Windows path's backslashes and escapes an apostrophe's quoting.
+ quoted := fmt.Sprintf("%q", hookCommandQuote(out.BinaryPath))
+ if err != nil || !strings.Contains(string(data), quoted[1:len(quoted)-1]) || strings.Contains(string(data), "__BEACON_") {
out.Installed = false
out.Message = fmt.Sprintf("opencode plugin at %s does not reference the active Beacon hook binary", out.PluginPath)
}
}
+ if out.Installed {
+ markIgnoredOpenCodePlugins(&out)
+ }
return out
}
+// markIgnoredOpenCodePlugins reports the Beacon plugin copies OpenCode would never run. When the
+// copy this status describes is one of them, it is not active even though its file is in place.
+func markIgnoredOpenCodePlugins(out *OpenCodeStatus) {
+ dir, err := os.Getwd()
+ if err != nil {
+ return
+ }
+ home, _ := os.UserHomeDir()
+ loaded := opencodeLoadedPlugins(home, dir)
+ if len(loaded) < 2 && (len(loaded) == 0 || loaded[0] == out.PluginPath) {
+ return
+ }
+ running := loaded[0]
+ out.IgnoredPluginPaths = loaded[1:]
+ if running == out.PluginPath {
+ out.Message += fmt.Sprintf("; OpenCode never runs the other Beacon plugin copies at %s, because the one at %s loads first with the same plugin ID: remove them",
+ strings.Join(out.IgnoredPluginPaths, ", "), running)
+ return
+ }
+ out.Installed = false
+ out.Message = fmt.Sprintf("OpenCode never runs the Beacon plugin at %s: the copy at %s loads first with the same plugin ID, and OpenCode runs only that one. Remove one of them.",
+ out.PluginPath, running)
+}
+
+// opencodeSystemDir is OpenCode's platform system configuration directory
+// (packages/core/src/config/discovery.ts systemDirectory). A variable so tests never read the host's.
+var opencodeSystemDir = func() string {
+ switch runtime.GOOS {
+ case "darwin":
+ return "/Library/Application Support/opencode"
+ case "windows":
+ base := os.Getenv("ProgramData")
+ if base == "" {
+ base = `C:\ProgramData`
+ }
+ return filepath.Join(base, "opencode")
+ default:
+ return "/etc/opencode"
+ }
+}
+
+// opencodeLoadedPlugins returns the Beacon-managed plugin files OpenCode 2.x loads for a session
+// started in dir, in the order it loads them. Every copy defines plugin ID beacon.endpoint and
+// OpenCode runs only the first, dropping the rest without logging anything, so only the first
+// copy's hook command ever receives telemetry.
+//
+// The order follows OpenCode's config loading (packages/core/src/config.ts, config/discovery.ts and
+// plugin/source-directory.ts): the global config directory, then each .opencode directory from the
+// filesystem root down to dir, then the system directory; within one directory, the entries of
+// plugin/ and plugins/ sorted by path.
+func opencodeLoadedPlugins(home, dir string) []string {
+ global, err := OpenCodeConfigDir(home)
+ if err != nil {
+ global = ""
+ }
+ system := opencodeSystemDir()
+ roots := []string{}
+ if global != "" {
+ roots = append(roots, global)
+ }
+ roots = append(roots, opencodeProjectDirs(dir, global, system)...)
+ roots = append(roots, system)
+
+ var loaded []string
+ for _, root := range roots {
+ var entries []string
+ for _, name := range []string{"plugin", "plugins"} {
+ children, err := os.ReadDir(filepath.Join(root, name))
+ if err != nil {
+ continue
+ }
+ for _, child := range children {
+ entries = append(entries, filepath.Join(root, name, child.Name()))
+ }
+ }
+ sort.Strings(entries)
+ for _, entry := range entries {
+ if ext := filepath.Ext(entry); (ext == ".ts" || ext == ".js") && isOpenCodeInstalledAt(entry) {
+ loaded = append(loaded, entry)
+ }
+ }
+ }
+ return loaded
+}
+
+// opencodeProjectDirs lists the .opencode directories OpenCode reads for a session in dir,
+// outermost first. Like OpenCode, it reads none when dir is one of the global config roots, and
+// skips any that resolves to one.
+func opencodeProjectDirs(dir string, globalRoots ...string) []string {
+ resolve := func(path string) string {
+ if real, err := filepath.EvalSymlinks(path); err == nil {
+ return real
+ }
+ return filepath.Clean(path)
+ }
+ global := map[string]bool{}
+ for _, root := range globalRoots {
+ if root != "" {
+ global[resolve(root)] = true
+ }
+ }
+ if global[resolve(dir)] {
+ return nil
+ }
+ var dirs []string
+ for current := dir; ; {
+ candidate := filepath.Join(current, ".opencode")
+ if info, err := os.Stat(candidate); err == nil && info.IsDir() && !global[resolve(candidate)] {
+ dirs = append([]string{candidate}, dirs...)
+ }
+ parent := filepath.Dir(current)
+ if parent == current {
+ return dirs
+ }
+ current = parent
+ }
+}
+
func opencodeEmbeddedPluginSourcePath() string {
return filepath.Clean(filepath.Join("assets", "opencode", "beacon.ts"))
}
@@ -139,15 +313,30 @@ func opencodePluginPath(level Level) (string, error) {
// OpenCodeConfigDir returns OpenCode's global config directory for the given home directory.
//
-// OpenCode roots it at `$XDG_CONFIG_HOME/opencode` and falls back to `~/.config/opencode`
+// A non-empty OPENCODE_CONFIG_DIR wins. OpenCode 2.x uses it instead of the default directory
+// (packages/cli/src/index.ts and server-process.ts: `process.env.OPENCODE_CONFIG_DIR ? { config:
+// process.env.OPENCODE_CONFIG_DIR } : {}`), so a plugin left in the default directory never loads.
+// OpenCode 1.x reads it as one more config directory after the default (packages/opencode/src/
+// config/paths.ts) and loads its plugins and opencode.json as well, so the same directory works
+// for both.
+//
+// Otherwise OpenCode roots it at `$XDG_CONFIG_HOME/opencode` and falls back to `~/.config/opencode`
// (packages/util/src/global-roots.ts: `process.env.XDG_CONFIG_HOME || path.join(home, ".config")`).
-// An empty value falls back and nothing is trimmed; a relative value is resolved against the
-// working directory, so it is made absolute here. The home directory is only needed for the
-// default, so an XDG_CONFIG_HOME override resolves without one.
+// For both variables an empty value falls back and nothing is trimmed; a relative value is resolved
+// against the working directory, so it is made absolute here. The home directory is only needed
+// for the default, so either override resolves without one.
//
// Exported because discovery and the inventory scan report on the same plugin the installer
// writes and must not rebuild the path themselves.
func OpenCodeConfigDir(home string) (string, error) {
+ if dir := os.Getenv("OPENCODE_CONFIG_DIR"); dir != "" {
+ return filepath.Abs(dir)
+ }
+ return opencodeDefaultConfigDir(home)
+}
+
+// opencodeDefaultConfigDir is OpenCode's global config directory when OPENCODE_CONFIG_DIR is unset.
+func opencodeDefaultConfigDir(home string) (string, error) {
if base := os.Getenv("XDG_CONFIG_HOME"); base != "" {
abs, err := filepath.Abs(base)
if err != nil {
@@ -164,10 +353,8 @@ func OpenCodeConfigDir(home string) (string, error) {
func opencodePluginDir(level Level) (string, error) {
switch level {
case "", LevelUser:
- home, err := os.UserHomeDir()
- if err != nil && os.Getenv("XDG_CONFIG_HOME") == "" {
- return "", err
- }
+ // OpenCodeConfigDir reports a missing home directory only when no override needs one.
+ home, _ := os.UserHomeDir()
dir, err := OpenCodeConfigDir(home)
if err != nil {
return "", err
diff --git a/cli/beacon/internal/endpoint/hooks/opencode_test.go b/cli/beacon/internal/endpoint/hooks/opencode_test.go
index 62a6f064..c832eabf 100644
--- a/cli/beacon/internal/endpoint/hooks/opencode_test.go
+++ b/cli/beacon/internal/endpoint/hooks/opencode_test.go
@@ -149,6 +149,7 @@ func mustOpenCodePluginPath(t *testing.T, level Level) string {
func TestOpenCodePluginPathHonorsXDGConfigHome(t *testing.T) {
home := t.TempDir()
testenv.SetHome(t, home)
+ t.Setenv("OPENCODE_CONFIG_DIR", "")
project := t.TempDir()
t.Chdir(project)
cwd, err := os.Getwd()
@@ -191,3 +192,181 @@ func TestOpenCodePluginPathHonorsXDGConfigHome(t *testing.T) {
t.Fatalf("IsOpenCodeInstalled = false for a managed plugin at %q", want)
}
}
+
+// OPENCODE_CONFIG_DIR replaces OpenCode 2.x's global config directory outright, so a plugin
+// written under XDG_CONFIG_HOME or ~/.config never loads while it is set.
+func TestOpenCodePluginPathHonorsOpenCodeConfigDir(t *testing.T) {
+ testenv.SetHome(t, t.TempDir())
+ t.Chdir(t.TempDir())
+ cwd, err := os.Getwd()
+ if err != nil {
+ t.Fatal(err)
+ }
+ xdg := filepath.Join(t.TempDir(), "xdg")
+ t.Setenv("XDG_CONFIG_HOME", xdg)
+ custom := filepath.Join(t.TempDir(), "opencode-config")
+ for name, tc := range map[string]struct{ value, want string }{
+ "absolute": {custom, filepath.Join(custom, "plugins", "beacon.ts")},
+ "relative": {"rel-config", filepath.Join(cwd, "rel-config", "plugins", "beacon.ts")},
+ "empty": {"", filepath.Join(xdg, "opencode", "plugins", "beacon.ts")},
+ } {
+ t.Run(name, func(t *testing.T) {
+ t.Setenv("OPENCODE_CONFIG_DIR", tc.value)
+ if got := mustOpenCodePluginPath(t, LevelUser); got != tc.want {
+ t.Fatalf("user plugin path = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+// OpenCode 2.x runs only the first plugin with a given ID and drops the rest without a log line, so
+// a second Beacon copy (a project install under a user install, or a stale one in plugin/) never
+// receives telemetry while its file looks installed.
+func TestOpenCodeStatusReportsCopiesOpenCodeNeverRuns(t *testing.T) {
+ // The backslash and the apostrophe put the hook binary on a path the plugin's shell quoting
+ // and string literal both escape, as every Windows path and a profile like O'Brien are.
+ home := filepath.Join(t.TempDir(), `o'brien\slash`)
+ if err := os.MkdirAll(home, 0755); err != nil {
+ t.Fatal(err)
+ }
+ testenv.SetHome(t, home)
+ t.Setenv("XDG_CONFIG_HOME", "")
+ t.Setenv("OPENCODE_CONFIG_DIR", "")
+ system := t.TempDir()
+ defaultSystemDir := opencodeSystemDir
+ opencodeSystemDir = func() string { return system }
+ t.Cleanup(func() { opencodeSystemDir = defaultSystemDir })
+ outer := t.TempDir()
+ inner := filepath.Join(outer, "repo")
+ if err := os.MkdirAll(inner, 0755); err != nil {
+ t.Fatal(err)
+ }
+ t.Chdir(inner)
+ cwd, err := os.Getwd()
+ if err != nil {
+ t.Fatal(err)
+ }
+ outer = filepath.Dir(cwd)
+
+ binary, err := endpointHookBinaryPath(true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.MkdirAll(filepath.Dir(binary), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(binary, []byte("hooks"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ global := filepath.Join(home, ".config", "opencode")
+ write := func(path string) string {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := installOpenCodePlugin(path, binary, "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatal(err)
+ }
+ return path
+ }
+ user := filepath.Join(global, "plugins", "beacon.ts")
+ project := write(filepath.Join(cwd, ".opencode", "plugins", "beacon.ts"))
+ outerProject := write(filepath.Join(outer, ".opencode", "plugins", "beacon.ts"))
+ systemCopy := write(filepath.Join(system, "plugins", "beacon.ts"))
+
+ // Without a user copy, the outermost project directory loads first.
+ status := OpenCodeHookStatus(OpenCodeOptions{Level: LevelProject, UserMode: true})
+ if status.Installed || !strings.Contains(status.Message, outerProject) {
+ t.Fatalf("shadowed project copy reported as %+v", status)
+ }
+
+ write(user)
+ if got, want := opencodeLoadedPlugins(home, cwd), []string{user, outerProject, project, systemCopy}; strings.Join(got, "\n") != strings.Join(want, "\n") {
+ t.Fatalf("load order = %q, want %q", got, want)
+ }
+ status = OpenCodeHookStatus(OpenCodeOptions{Level: LevelUser, UserMode: true})
+ if !status.Installed || strings.Join(status.IgnoredPluginPaths, "\n") != strings.Join([]string{outerProject, project, systemCopy}, "\n") {
+ t.Fatalf("running user copy reported as %+v", status)
+ }
+
+ // plugin/ sorts before plugins/, so a stale copy there shadows the one Beacon writes.
+ stale := filepath.Join(global, "plugin", "beacon.ts")
+ if err := os.MkdirAll(filepath.Dir(stale), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := installOpenCodePlugin(stale, "/old/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatal(err)
+ }
+ status = OpenCodeHookStatus(OpenCodeOptions{Level: LevelUser, UserMode: true})
+ if status.Installed || !strings.Contains(status.Message, stale) {
+ t.Fatalf("user copy shadowed by %s reported as %+v", stale, status)
+ }
+}
+
+// With OPENCODE_CONFIG_DIR set, Beacon manages the plugin under it, but a copy an earlier Beacon (or
+// an install run without the variable) wrote to the default directory is still what sessions
+// started without the variable load. Install keeps and reports it; uninstall removes it too.
+func TestOpenCodeKeepsDefaultDirCopyOnInstallAndRemovesItOnUninstall(t *testing.T) {
+ home := t.TempDir()
+ testenv.SetHome(t, home)
+ t.Setenv("XDG_CONFIG_HOME", "")
+ t.Chdir(t.TempDir())
+ defaultCopy := filepath.Join(home, ".config", "opencode", "plugins", "beacon.ts")
+ if err := os.MkdirAll(filepath.Dir(defaultCopy), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := installOpenCodePlugin(defaultCopy, "/old/beacon-hooks", "/tmp/runtime.jsonl", "/tmp/config.json"); err != nil {
+ t.Fatal(err)
+ }
+ custom := filepath.Join(t.TempDir(), "custom")
+ t.Setenv("OPENCODE_CONFIG_DIR", custom)
+ opts := OpenCodeOptions{Level: LevelUser, LogPath: filepath.Join(home, "runtime.jsonl"), UserMode: true}
+
+ status, err := InstallOpenCode(opts)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := filepath.Join(custom, "plugins", "beacon.ts"); !status.Installed || status.PluginPath != want || status.DefaultPluginPath != defaultCopy {
+ t.Fatalf("install = %+v, want installed at %s and %s reported", status, want, defaultCopy)
+ }
+ if !isOpenCodeInstalledAt(defaultCopy) {
+ t.Fatalf("install removed %s, which sessions without OPENCODE_CONFIG_DIR still load", defaultCopy)
+ }
+
+ if status, err = UninstallOpenCode(opts); err != nil {
+ t.Fatal(err)
+ }
+ if status.DefaultPluginPath != defaultCopy || !strings.Contains(status.Message, defaultCopy) {
+ t.Fatalf("uninstall = %+v, want %s removed", status, defaultCopy)
+ }
+ for _, path := range []string{defaultCopy, status.PluginPath} {
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatalf("uninstall left %s: %v", path, err)
+ }
+ }
+}
+
+// OPENCODE_CONFIG_DIR may name the default directory under another spelling. The plugin Beacon
+// manages there is then the same file, and uninstall must not treat it as a second copy.
+func TestOpenCodeDefaultDirAliasIsNotASecondCopy(t *testing.T) {
+ home := t.TempDir()
+ testenv.SetHome(t, home)
+ t.Setenv("XDG_CONFIG_HOME", "")
+ t.Chdir(t.TempDir())
+ defaultDir := filepath.Join(home, ".config", "opencode")
+ if err := os.MkdirAll(defaultDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ alias := filepath.Join(t.TempDir(), "alias")
+ if err := os.Symlink(defaultDir, alias); err != nil {
+ t.Skipf("symlinks unavailable: %v", err)
+ }
+ t.Setenv("OPENCODE_CONFIG_DIR", alias)
+ status, err := InstallOpenCode(OpenCodeOptions{Level: LevelUser, LogPath: filepath.Join(home, "runtime.jsonl"), UserMode: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !status.Installed || status.DefaultPluginPath != "" {
+ t.Fatalf("install through an alias of the default directory = %+v", status)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/inventory/inventory.go b/cli/beacon/internal/endpoint/inventory/inventory.go
index 29b26f3f..68df2dcd 100644
--- a/cli/beacon/internal/endpoint/inventory/inventory.go
+++ b/cli/beacon/internal/endpoint/inventory/inventory.go
@@ -446,7 +446,8 @@ func copilotCandidates(home string) []candidate {
return []candidate{{runtime: "copilot_cli", path: shellProfilePath(home), scope: ScopeUser, format: formatMetadataOnly, kind: KindProfile}}
}
-// opencodeCandidates resolves the user plugin through XDG_CONFIG_HOME, as OpenCode does.
+// opencodeCandidates resolves the user plugin through OPENCODE_CONFIG_DIR and XDG_CONFIG_HOME, as
+// OpenCode does.
func opencodeCandidates(home, wd string) []candidate {
items := []candidate{}
if dir, err := hooks.OpenCodeConfigDir(home); err == nil {
diff --git a/cli/beacon/internal/endpoint/inventory/inventory_test.go b/cli/beacon/internal/endpoint/inventory/inventory_test.go
index 737b0642..4e746515 100644
--- a/cli/beacon/internal/endpoint/inventory/inventory_test.go
+++ b/cli/beacon/internal/endpoint/inventory/inventory_test.go
@@ -402,6 +402,7 @@ func TestScanReadsOpenCodePluginFromXDGConfigHome(t *testing.T) {
home := t.TempDir()
xdg := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", xdg)
+ t.Setenv("OPENCODE_CONFIG_DIR", "")
writeFile(t, filepath.Join(xdg, "opencode", "plugins", "beacon.ts"), `// beacon-managed-opencode-plugin:v1`)
result := Scan(Options{HomeDir: home, WorkingDir: t.TempDir(), Now: fixedNow})
@@ -449,6 +450,7 @@ func TestScanReadsClaudeUserFilesFromClaudeConfigDir(t *testing.T) {
func TestScanIncludesAllSupportedCurrentUserAndProjectConfigs(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", "")
+ t.Setenv("OPENCODE_CONFIG_DIR", "")
home := t.TempDir()
work := t.TempDir()
t.Setenv("SHELL", "/bin/bash")
diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
index fbdc0ac8..4a07c51b 100644
--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
@@ -211,7 +211,8 @@ var inventoryJobPathEnv = []string{
"DSH_HOME",
"OH_PERSISTENCE_DIR",
"OPENCLAW_STATE_DIR",
- "XDG_CONFIG_HOME", // Muse, and VS Code on Linux
+ "XDG_CONFIG_HOME", // Muse, OpenCode, and VS Code on Linux
+ "OPENCODE_CONFIG_DIR", // OpenCode
"PI_CODING_AGENT_DIR", // Pi, Oh My Pi's default profile, and OMO's last fallback
"OMO_CODING_AGENT_DIR", // OMO
"SENPI_CODING_AGENT_DIR", // OMO's legacy name
diff --git a/cli/beacon/internal/handoff/detached.go b/cli/beacon/internal/handoff/detached.go
index bf7c6899..be448da4 100644
--- a/cli/beacon/internal/handoff/detached.go
+++ b/cli/beacon/internal/handoff/detached.go
@@ -82,6 +82,7 @@ var carriedEnvNames = []string{
"OH_PERSISTENCE_DIR",
"OMP_PROFILE",
"OPENCLAW_STATE_DIR",
+ "OPENCODE_CONFIG_DIR",
"OPENCODE_DB",
"PI_CODING_AGENT_DIR",
"PI_CONFIG_DIR",
diff --git a/cli/beacon/internal/mcpconnect/harness_test.go b/cli/beacon/internal/mcpconnect/harness_test.go
index 91674e43..e860c43c 100644
--- a/cli/beacon/internal/mcpconnect/harness_test.go
+++ b/cli/beacon/internal/mcpconnect/harness_test.go
@@ -438,6 +438,7 @@ func isolate(t *testing.T) string {
home := t.TempDir()
testenv.SetHome(t, home)
t.Setenv("XDG_CONFIG_HOME", "")
+ t.Setenv("OPENCODE_CONFIG_DIR", "")
t.Setenv("CLAUDE_CONFIG_DIR", "")
t.Setenv("CODEX_HOME", "")
t.Setenv("GEMINI_CLI_HOME", "")
@@ -839,6 +840,10 @@ func TestOpenCodePrefersAnExistingConfigFile(t *testing.T) {
if got := targetPath(t, target, home); got != filepath.Join(home, "xdg", "opencode", "opencode.jsonc") {
t.Fatalf("XDG_CONFIG_HOME was not honored: %s", got)
}
+ t.Setenv("OPENCODE_CONFIG_DIR", filepath.Join(home, "custom"))
+ if got := targetPath(t, target, home); got != filepath.Join(home, "custom", "opencode.jsonc") {
+ t.Fatalf("OPENCODE_CONFIG_DIR was not honored: %s", got)
+ }
}
func TestSymlinkedConfigIsWrittenThroughTheLink(t *testing.T) {
diff --git a/docs/cli/hooks.mdx b/docs/cli/hooks.mdx
index 071df94d..bfa76ef3 100644
--- a/docs/cli/hooks.mdx
+++ b/docs/cli/hooks.mdx
@@ -452,9 +452,11 @@ If Codex session context is missing, check the selected level, confirm the hook
## OpenCode troubleshooting
-Beacon installs an owned OpenCode plugin at `~/.config/opencode/plugins/beacon.ts` for user-level hooks or `./.opencode/plugins/beacon.ts` for project-level hooks. The plugin is a thin local adapter: it forwards supported OpenCode hook payloads to Beacon's Go hook binary, and Beacon handles normalization, redaction, retention, and JSONL output.
+Beacon installs an owned OpenCode plugin at `plugins/beacon.ts` in OpenCode's global config directory (`$OPENCODE_CONFIG_DIR`, else `$XDG_CONFIG_HOME/opencode`, else `~/.config/opencode`) for user-level hooks or `./.opencode/plugins/beacon.ts` for project-level hooks. The plugin is a thin local adapter: it forwards supported OpenCode hook payloads to Beacon's Go hook binary, and Beacon handles normalization, redaction, retention, and JSONL output.
-For local troubleshooting, set `BEACON_OPENCODE_DEBUG=1` in the environment that launches OpenCode to emit best-effort plugin debug logs. Beacon telemetry should not interrupt OpenCode execution if the hook command fails.
+For local troubleshooting, set `BEACON_OPENCODE_DEBUG=1` in the environment of the OpenCode server process to emit best-effort plugin debug logs: OpenCode 1.x writes them to its own log, and on OpenCode 2.x they go to `~/.beacon/endpoint/logs/opencode-plugin-debug.log`. For the OpenCode 2.x background service, run `opencode service set env BEACON_OPENCODE_DEBUG 1` and then `opencode service restart`. Beacon telemetry should not interrupt OpenCode execution if the hook command fails.
+
+OpenCode 2.x runs only the first Beacon plugin copy it loads, so a second copy (for example, a project-level install under a user-level one) never receives telemetry. `beacon endpoint hooks status --harness opencode` lists those copies in `ignored_plugin_paths`.
## Devin troubleshooting
diff --git a/docs/runtimes/opencode.mdx b/docs/runtimes/opencode.mdx
index f99d08f3..969ec64c 100644
--- a/docs/runtimes/opencode.mdx
+++ b/docs/runtimes/opencode.mdx
@@ -22,7 +22,7 @@ Before enabling OpenCode telemetry, make sure:
## Collection path
-Beacon installs an owned OpenCode plugin at `$XDG_CONFIG_HOME/opencode/plugins/beacon.ts` (default `~/.config/opencode/plugins/beacon.ts`) for user-level hooks or `./.opencode/plugins/beacon.ts` for project-level hooks. The plugin forwards supported OpenCode hook payloads to Beacon's hook adapter.
+Beacon installs an owned OpenCode plugin at `plugins/beacon.ts` in OpenCode's global config directory for user-level hooks, or at `./.opencode/plugins/beacon.ts` for project-level hooks. The global config directory is `$OPENCODE_CONFIG_DIR` when that is set, else `$XDG_CONFIG_HOME/opencode`, else `~/.config/opencode`. OpenCode 2.x reads only `$OPENCODE_CONFIG_DIR` when it is set, so set it in the shell that runs the install, the same way you set it for OpenCode. If Beacon's plugin is also in the default directory, from an earlier Beacon or an install run without the variable, a user-level install with the variable set leaves that copy in place and names it, because sessions started without the variable still use it. OpenCode 1.x sessions started with the variable load both copies and record each event twice, so remove the default copy if every session sets the variable. A user-level uninstall with the variable set removes both. The plugin forwards supported OpenCode hook payloads to Beacon's hook adapter.
The one plugin file loads in both OpenCode 1.x and OpenCode 2.x. Its default export carries the plugin `id`, the 1.x `server` entry, and the 2.x `setup` entry. On 2.x, `setup` registers the session `prompt` hook and the tool `execute.before`/`execute.after` hooks, and it subscribes to the event stream. It translates those into the same payloads the 1.x hooks produce, so events from either version look the same in the runtime log. After upgrading OpenCode from 1.x to 2.x, run `beacon endpoint hooks install --harness opencode` again, because a plugin written by an older Beacon exports only the 1.x factory, and OpenCode 2.x refuses to load it ("Plugin must export a default definition with an id and an effect or setup function").
@@ -32,7 +32,7 @@ For backfill, `beacon endpoint opencode sync` reads OpenCode's local `opencode.d
## Discovery and status
-Beacon detects OpenCode through the `opencode` executable or `$XDG_CONFIG_HOME/opencode` (default `~/.config/opencode`), then checks for Beacon plugin configuration.
+Beacon detects OpenCode through the `opencode` executable or its global config directory (`$OPENCODE_CONFIG_DIR`, else `$XDG_CONFIG_HOME/opencode`, else `~/.config/opencode`), then checks for Beacon plugin configuration.
Use `beacon endpoint hooks status --harness opencode` to inspect OpenCode plugin status.
Use `beacon endpoint opencode status` to inspect persisted session-store collection progress.
@@ -75,7 +75,9 @@ The plugin uses OpenCode session, message, part, permission request, and tool ca
Restart OpenCode after installing or removing hooks so new sessions pick up the updated plugin configuration.
-For local troubleshooting, set `BEACON_OPENCODE_DEBUG=1` in the environment that launches OpenCode to emit best-effort plugin debug logs. The adapter has a bounded local subprocess timeout and remains fail-open, so telemetry failures do not interrupt OpenCode execution.
+Every copy of Beacon's plugin uses the plugin ID `beacon.endpoint`, and OpenCode 2.x runs only the first one it loads. It drops the others without logging anything. OpenCode loads plugins from the user config directory first, then from each `.opencode` directory between the filesystem root and the working directory (outermost first), then from the system config directory (`/etc/opencode` on Linux, `/Library/Application Support/opencode` on macOS). Inside each directory, files in `plugin/` load before files in `plugins/`. So a user-level install hides a project-level one, and a stale copy in `plugin/` hides the one Beacon writes to `plugins/`. `beacon endpoint hooks status` lists the copies OpenCode never runs in `ignored_plugin_paths`, and reports a copy as not installed when another copy hides it.
+
+For local troubleshooting, set `BEACON_OPENCODE_DEBUG=1` in the environment of the OpenCode server process to emit best-effort plugin debug logs. OpenCode 1.x writes them to its own log. OpenCode 2.x gives plugins no logger, so the plugin appends them to `~/.beacon/endpoint/logs/opencode-plugin-debug.log`, beginning with one `Beacon V2 setup complete` line that lists the hooks it registered. The OpenCode 2.x background service keeps the environment it started with: run `opencode service set env BEACON_OPENCODE_DEBUG 1`, then `opencode service restart`. The adapter has a bounded local subprocess timeout and remains fail-open, so telemetry failures do not interrupt OpenCode execution.
For historical collection or deployments where OpenCode did not load the plugin, run `beacon endpoint opencode sync --print` to preview mapped events, then `beacon endpoint opencode sync` to append them to the runtime log. Use `--watch` or a scheduler if you want the poll path to stay current.
diff --git a/plugins/opencode-beacon/src/beacon.test.ts b/plugins/opencode-beacon/src/beacon.test.ts
index 93977687..c0c73f64 100644
--- a/plugins/opencode-beacon/src/beacon.test.ts
+++ b/plugins/opencode-beacon/src/beacon.test.ts
@@ -705,6 +705,42 @@ describe("OpenCode 2.x plugin definition", () => {
expect(payloads[10].properties.status.type).toBe("idle")
expect(v2.disposed.sort()).toEqual(["session.prompt", "tool.execute.after", "tool.execute.before"])
})
+
+ // OpenCode creates the first session in a location before the plugin subscribes to events, so
+ // session.created never arrives, and a default model is never "selected".
+ test("takes the session's model from the step when no session event names it", async () => {
+ const v2 = v2Context()
+ const cleanup = await BeaconDefinition.setup(v2.ctx as any)
+ const prompt = (messageID: string) =>
+ v2.fire("session.prompt", { sessionID: "ses_1", messageID, prompt: { text: "ok?" }, delivery: "immediate" })
+
+ await prompt("msg_user_1")
+ v2.emit("session.step.started", {
+ sessionID: "ses_1",
+ assistantMessageID: "msg_1",
+ agent: "build",
+ model: { id: "big-pickle", providerID: "opencode" },
+ started: 1,
+ })
+ v2.emit("session.text.ended", { sessionID: "ses_1", assistantMessageID: "msg_1", ordinal: 0, text: "ok" })
+ v2.emit("session.step.ended", {
+ sessionID: "ses_1",
+ assistantMessageID: "msg_1",
+ finish: "stop",
+ cost: 0,
+ tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
+ })
+ await nextTurn()
+ await prompt("msg_user_2")
+ await (cleanup as any)()
+
+ expect(payloads.map((item) => [item.type, item.model])).toEqual([
+ ["chat.message", ""],
+ ["message.part.updated", "opencode/big-pickle"],
+ ["message.updated", "opencode/big-pickle"],
+ ["chat.message", "opencode/big-pickle"],
+ ])
+ })
})
describe("direct-hook queue deadlines", () => {
diff --git a/plugins/opencode-beacon/src/beacon.ts b/plugins/opencode-beacon/src/beacon.ts
index 85fc79ed..a2e29843 100644
--- a/plugins/opencode-beacon/src/beacon.ts
+++ b/plugins/opencode-beacon/src/beacon.ts
@@ -2,9 +2,16 @@
// Beacon endpoint telemetry plugin for opencode.
// Managed by beacon endpoint hooks install --harness opencode.
+import { appendFile, mkdir } from "node:fs/promises"
+import { homedir } from "node:os"
+import { dirname, join } from "node:path"
+
const beaconCommand = "__BEACON_COMMAND__"
const pluginID = "beacon.endpoint"
const debugEnabled = process.env.BEACON_OPENCODE_DEBUG === "1"
+// OpenCode 2.x gives plugins no logger and discards the server's stderr unless it runs
+// standalone with --print-logs, so debug lines without client.app.log go to this file.
+const debugFile = join(homedir(), ".beacon", "endpoint", "logs", "opencode-plugin-debug.log")
const sendTimeoutMs = 2000
const directHookTypes = new Set([
"chat.message",
@@ -33,13 +40,20 @@ const forwardedEvents = new Set([
async function debugLog(client, message, extra) {
if (!debugEnabled) return
try {
- await client?.app?.log?.({
- body: {
- service: "beacon-opencode-plugin",
- level: "debug",
- message,
- extra,
- },
+ if (typeof client?.app?.log === "function") {
+ await client.app.log({
+ body: {
+ service: "beacon-opencode-plugin",
+ level: "debug",
+ message,
+ extra,
+ },
+ })
+ return
+ }
+ await mkdir(dirname(debugFile), { recursive: true, mode: 0o700 })
+ await appendFile(debugFile, JSON.stringify({ time: new Date().toISOString(), message, extra }) + "\n", {
+ mode: 0o600,
})
} catch {
// Debug logging must stay best-effort.
@@ -459,7 +473,10 @@ function v2Events(event, models) {
const created = typeof event?.created === "number" ? event.created : Date.now()
switch (event?.type) {
case "session.created":
- case "session.model.selected": {
+ case "session.model.selected":
+ // The step is the one event that always names the model: OpenCode often creates a session
+ // before the plugin's event stream is subscribed, and a default model is never "selected".
+ case "session.step.started": {
const model = v2Model(data.model)
if (sid && model) models.set(sid, model)
if (event.type !== "session.created") return []
@@ -551,16 +568,24 @@ export default {
})
const models = new Map()
const registrations = []
+ const registered = []
const register = async (domain, name, callback) => {
+ if (typeof domain?.hook !== "function") {
+ await debugLog(ctx, "Beacon V2 hook API unavailable", { name })
+ return
+ }
try {
- const registration = await domain?.hook?.(name, async (input) => {
+ const registration = await domain.hook(name, async (input) => {
try {
await callback(input)
} catch (err) {
await debugLog(ctx, "Beacon V2 hook failed", { name, error: String(err) })
}
})
- if (registration) registrations.push(registration)
+ if (registration) {
+ registrations.push(registration)
+ registered.push(name)
+ }
} catch (err) {
await debugLog(ctx, "Beacon V2 hook registration failed", { name, error: String(err) })
}
@@ -610,6 +635,11 @@ export default {
},
})
})
+ await debugLog(ctx, "Beacon V2 setup complete", {
+ opencode: ctx?.app?.version,
+ hooks: registered,
+ events: typeof ctx?.event?.subscribe === "function",
+ })
const controller = new AbortController()
const consuming = (async () => {