The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
opencode: load the managed plugin in OpenCode 2.x
Claudefffef730f948
diff --git a/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts b/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.tsindex 747b1804..4725609a 100644--- a/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts+++ b/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts@@ -3,6 +3,7 @@// Managed by beacon endpoint hooks install --harness opencode.const beaconCommand = "__BEACON_COMMAND__"+const pluginID = "beacon.endpoint"const debugEnabled = process.env.BEACON_OPENCODE_DEBUG === "1"const sendTimeoutMs = 2000const directHookTypes = new Set([@@ -387,3 +388,222 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien},}}++// OpenCode 2.x loads only a default definition with an id and a setup+// function; 1.x reads the same default export's server field. setup adapts+// the V2 hooks and event stream onto the V1 handlers above, so both runtimes+// send the same payloads to beacon-hooks.+function v2Model(ref) {+ if (!ref?.id) return undefined+ return ref.providerID ? { providerID: ref.providerID, modelID: ref.id } : { modelID: ref.id }+}++function v2PromptParts(prompt) {+ const parts = []+ if (prompt?.text) parts.push({ type: "text", text: prompt.text })+ for (const file of prompt?.files || []) {+ if (file?.uri) parts.push({ type: "file", filename: file.name || file.uri, url: file.uri })+ }+ for (const agent of prompt?.agents || []) {+ if (agent?.name) parts.push({ type: "agent", name: agent.name })+ }+ return parts+}++function v2ToolResponse(result) {+ const structured = result?.output+ const text = (result?.content || [])+ .filter((item) => item?.type === "text" && typeof item.text === "string")+ .map((item) => item.text)+ .join("\n")+ const output = typeof structured === "string" ? structured : structured?.output ?? text+ const metadata = { ...(result?.metadata || {}) }+ if (metadata.exit === undefined && typeof structured?.exit === "number") metadata.exit = structured.exit+ return { output, metadata }+}++// Translates one V2 event into the V1 {type, properties} events the handler+// understands. Tool success and failure arrive through the tool hooks instead.+function v2Events(event, models) {+ const data = event?.data || {}+ const sid = data.sessionID+ const created = typeof event?.created === "number" ? event.created : Date.now()+ switch (event?.type) {+ case "session.created":+ case "session.model.selected": {+ const model = v2Model(data.model)+ if (sid && model) models.set(sid, model)+ if (event.type !== "session.created") return []+ return [{ type: "session.created", properties: { ...data, info: { ...data, id: sid, ...(model || {}) } } }]+ }+ case "session.deleted":+ case "session.idle":+ case "session.status":+ case "permission.replied":+ return [{ type: event.type, properties: data }]+ case "permission.asked":+ return [+ {+ type: "permission.asked",+ properties: { ...data, permission: data.action, patterns: data.resources },+ },+ ]+ case "session.execution.started":+ return [{ type: "session.status", properties: { sessionID: sid, status: { type: "busy" } } }]+ case "session.execution.succeeded":+ case "session.execution.failed":+ case "session.execution.interrupted": {+ const events = []+ if (event.type === "session.execution.failed") {+ events.push({ type: "session.error", properties: { sessionID: sid, error: data.error } })+ }+ events.push({ type: "session.status", properties: { sessionID: sid, status: { type: "idle" } } })+ return events+ }+ case "session.text.ended":+ case "session.reasoning.ended": {+ const messageID = data.assistantMessageID+ const type = event.type === "session.text.ended" ? "text" : "reasoning"+ return [+ {+ type: "message.updated",+ properties: { sessionID: sid, info: { id: messageID, role: "assistant", sessionID: sid, ...(models.get(sid) || {}) } },+ },+ {+ type: "message.part.updated",+ properties: {+ sessionID: sid,+ part: {+ id: `${messageID}:${type}:${data.ordinal ?? 0}`,+ messageID,+ sessionID: sid,+ type,+ text: data.text || "",+ time: { start: created, end: created },+ },+ },+ },+ ]+ }+ case "session.step.ended":+ return [+ {+ type: "message.updated",+ properties: {+ sessionID: sid,+ info: {+ id: data.assistantMessageID,+ role: "assistant",+ sessionID: sid,+ ...(models.get(sid) || {}),+ finish: data.finish,+ tokens: data.tokens,+ cost: data.cost,+ time: { completed: created },+ },+ },+ },+ ]+ default:+ return []+ }+}++export default {+ id: pluginID,+ server: BeaconEndpointPlugin,+ async setup(ctx) {+ const location = ctx?.location || {}+ const hooks = await BeaconEndpointPlugin({+ project: location.project,+ directory: location.directory,+ worktree: location.project?.canonical || location.project?.directory || location.directory,+ client: ctx,+ })+ const models = new Map()+ const registrations = []+ const register = async (domain, name, callback) => {+ try {+ 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)+ } catch (err) {+ await debugLog(ctx, "Beacon V2 hook registration failed", { name, error: String(err) })+ }+ }++ await register(ctx?.session, "prompt", (input) =>+ hooks["chat.message"](+ { sessionID: input?.sessionID, messageID: input?.messageID, ...(models.get(input?.sessionID) || {}) },+ { message: { id: input?.messageID }, parts: v2PromptParts(input?.prompt) },+ ),+ )+ await register(ctx?.tool, "execute.before", (input) =>+ hooks["tool.execute.before"](+ { sessionID: input?.sessionID, tool: input?.tool, callID: input?.id },+ { args: structuredClone(input?.input ?? {}) },+ ),+ )+ await register(ctx?.tool, "execute.after", async (input) => {+ if (input?.status === "completed") {+ await hooks["tool.execute.after"](+ { sessionID: input.sessionID, tool: input.tool, callID: input.id, args: input.input ?? {} },+ v2ToolResponse(input.result),+ )+ return+ }+ const now = Date.now()+ await hooks.event({+ event: {+ type: "message.part.updated",+ properties: {+ sessionID: input?.sessionID,+ part: {+ id: `${input?.messageID}:tool:${input?.id}`,+ messageID: input?.messageID,+ sessionID: input?.sessionID,+ callID: input?.id,+ type: "tool",+ tool: input?.tool,+ state: {+ status: "error",+ input: input?.input ?? {},+ error: input?.error?.message || String(input?.error ?? "tool failed"),+ time: { start: now, end: now },+ },+ },+ },+ },+ })+ })++ const controller = new AbortController()+ const consuming = (async () => {+ if (typeof ctx?.event?.subscribe !== "function") return+ for await (const event of ctx.event.subscribe({ signal: controller.signal })) {+ if (controller.signal.aborted) break+ for (const translated of v2Events(event, models)) {+ try {+ await hooks.event({ event: translated })+ } catch (err) {+ await debugLog(ctx, "Beacon V2 event failed", { type: translated.type, error: String(err) })+ }+ }+ if (event?.type === "session.deleted") models.delete(event?.data?.sessionID)+ }+ })().catch((err) => {+ if (!controller.signal.aborted) void debugLog(ctx, "Beacon V2 event subscription failed", { error: String(err) })+ })++ return async () => {+ controller.abort()+ await consuming+ await Promise.all(registrations.map((item) => item.dispose?.().catch(() => undefined)))+ }+ },+}diff --git a/cli/beacon/internal/endpoint/hooks/opencode_test.go b/cli/beacon/internal/endpoint/hooks/opencode_test.goindex e401686d..6f0df372 100644--- a/cli/beacon/internal/endpoint/hooks/opencode_test.go+++ b/cli/beacon/internal/endpoint/hooks/opencode_test.go@@ -21,6 +21,9 @@ func TestInstallOpenCodePluginWritesManagedPlugin(t *testing.T) {for _, want := range []string{opencodeManagedPluginMarker,"BeaconEndpointPlugin",+ "export default {",+ "server: BeaconEndpointPlugin",+ "async setup(ctx)","BEACON_OPENCODE_DEBUG","--platform opencode","opencode-event",diff --git a/docs/runtimes/opencode.mdx b/docs/runtimes/opencode.mdxindex cadf8727..ce9cff4c 100644--- a/docs/runtimes/opencode.mdx+++ b/docs/runtimes/opencode.mdx@@ -24,6 +24,8 @@ Before enabling OpenCode telemetry, make sure: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 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").+The integration is plugin-based. OpenCode's native OTLP export is neither configured nor required by Beacon.For backfill, `beacon endpoint opencode sync` reads OpenCode's local `opencode.db` when present and falls back to the legacy `storage/session`, `storage/message`, `storage/part`, and `storage/project` tree. Those events are marked `harness.collection_method=poll` because Beacon reads committed records after the fact; nothing on that path can hold or deny a tool call.diff --git a/plugins/opencode-beacon/src/beacon.test.ts b/plugins/opencode-beacon/src/beacon.test.tsindex 8975a8e0..d5204491 100644--- a/plugins/opencode-beacon/src/beacon.test.ts+++ b/plugins/opencode-beacon/src/beacon.test.ts@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test"-import { BeaconEndpointPlugin } from "./beacon"+import BeaconDefinition, { BeaconEndpointPlugin } from "./beacon"const payloads: any[] = []const senderKey = Symbol.for("beacon.opencode.testSender")@@ -430,3 +430,156 @@ describe("BeaconEndpointPlugin", () => {expect(payloads.map((item) => item.type)).toEqual(["tool.execute.before", "session.diff"])})})++// A minimal OpenCode 2.x promise-plugin context: hooks are captured so the test+// can fire them, and the event stream yields whatever the test pushes.+function v2Context() {+ const hooks = new Map<string, (input: any) => Promise<void> | void>()+ const queue: any[] = []+ let wake: (() => void) | undefined+ let closed = false+ const disposed: string[] = []+ const hook = (domain: string) => async (name: string, callback: any) => {+ hooks.set(`${domain}.${name}`, callback)+ return { dispose: async () => void disposed.push(`${domain}.${name}`) }+ }+ const ctx = {+ location: {+ directory: "/repo",+ project: { id: "project-1", directory: "/repo", canonical: "/repo" },+ },+ session: { hook: hook("session") },+ tool: { hook: hook("tool") },+ event: {+ subscribe: ({ signal }: { signal?: AbortSignal } = {}) => ({+ async *[Symbol.asyncIterator]() {+ signal?.addEventListener("abort", () => {+ closed = true+ wake?.()+ })+ while (!closed) {+ if (queue.length === 0) await new Promise<void>((resolve) => (wake = resolve))+ while (queue.length > 0) yield queue.shift()+ }+ },+ }),+ },+ }+ return {+ ctx,+ disposed,+ fire: async (name: string, input: any) => hooks.get(name)!(input),+ emit: (type: string, data: any, created = 5) => {+ queue.push({ id: `evt_${queue.length}`, type, created, data })+ wake?.()+ },+ }+}++describe("OpenCode 2.x plugin definition", () => {+ test("exports the default definition both loaders accept", () => {+ expect(BeaconDefinition.id).toBe("beacon.endpoint")+ expect(typeof BeaconDefinition.setup).toBe("function")+ expect(BeaconDefinition.server).toBe(BeaconEndpointPlugin)+ })++ test("maps V2 hooks and events onto the V1 payloads", async () => {+ const v2 = v2Context()+ const cleanup = await BeaconDefinition.setup(v2.ctx as any)++ v2.emit("session.created", {+ sessionID: "ses_1",+ projectID: "project-1",+ slug: "s",+ version: "2.0.15",+ model: { id: "kimi-k3", providerID: "moonshotai" },+ })+ await Bun.sleep(10)+ await v2.fire("session.prompt", {+ sessionID: "ses_1",+ messageID: "msg_user",+ prompt: { text: "summarize" },+ delivery: "immediate",+ })+ await v2.fire("tool.execute.before", {+ tool: "shell",+ sessionID: "ses_1",+ agent: "build",+ messageID: "msg_1",+ id: "call_1",+ input: { command: "git status --short" },+ })+ await v2.fire("tool.execute.after", {+ tool: "shell",+ sessionID: "ses_1",+ agent: "build",+ messageID: "msg_1",+ id: "call_1",+ input: { command: "git status --short" },+ status: "completed",+ result: {+ output: { output: " M a.txt", exit: 0, truncated: false },+ content: [{ type: "text", text: " M a.txt" }],+ metadata: { status: "completed" },+ },+ })+ await v2.fire("tool.execute.after", {+ tool: "read",+ sessionID: "ses_1",+ agent: "build",+ messageID: "msg_1",+ id: "call_2",+ input: { filePath: "/repo/missing" },+ status: "error",+ error: { _tag: "Tool.Error", message: "not found" },+ })+ v2.emit("session.execution.started", { sessionID: "ses_1" })+ v2.emit("session.status", { sessionID: "ses_1", status: { type: "busy" } })+ v2.emit("session.text.ended", { sessionID: "ses_1", assistantMessageID: "msg_1", ordinal: 0, text: "Done" })+ v2.emit("session.step.ended", {+ sessionID: "ses_1",+ assistantMessageID: "msg_1",+ finish: "stop",+ cost: 0.01,+ tokens: { input: 3, output: 4, reasoning: 1, cache: { read: 2, write: 0 } },+ })+ v2.emit("permission.asked", { id: "per_1", sessionID: "ses_1", action: "bash", resources: ["git push"] })+ v2.emit("permission.replied", { sessionID: "ses_1", requestID: "per_1", reply: "reject" })+ v2.emit("session.execution.succeeded", { sessionID: "ses_1" })+ v2.emit("session.idle", { sessionID: "ses_1" })+ await Bun.sleep(30)+ await (cleanup as any)()++ expect(payloads.map((item) => item.type)).toEqual([+ "session.created",+ "chat.message",+ "tool.execute.before",+ "tool.execute.after",+ "message.part.updated",+ "session.status",+ "message.part.updated",+ "message.updated",+ "permission.asked",+ "permission.replied",+ "session.status",+ ])+ expect(payloads[0]).toMatchObject({ session_id: "ses_1", directory: "/repo", worktree: "/repo" })+ expect(payloads[1]).toMatchObject({+ session_id: "ses_1",+ model: "moonshotai/kimi-k3",+ output: { parts: [{ type: "text", text: "summarize" }] },+ })+ expect(payloads[2]).toMatchObject({ call_id: "call_1", tool_name: "shell", tool_input: { command: "git status --short" } })+ expect(payloads[3]).toMatchObject({+ call_id: "call_1",+ tool_response: { output: " M a.txt", metadata: { exit: 0 } },+ })+ expect(payloads[4].part).toMatchObject({ type: "tool", callID: "call_2", state: { status: "error", error: "not found" } })+ expect(payloads[6]).toMatchObject({ model: "moonshotai/kimi-k3", part: { type: "text", text: "Done" } })+ expect(payloads[7].properties.info).toMatchObject({ tokens: { input: 3, output: 4 }, cost: 0.01 })+ expect(payloads[8].properties).toMatchObject({ permission: "bash", patterns: ["git push"] })+ expect(payloads[9].properties).toMatchObject({ requestID: "per_1", reply: "reject", permission: "bash" })+ expect(payloads[10].properties.status.type).toBe("idle")+ expect(v2.disposed.sort()).toEqual(["session.prompt", "tool.execute.after", "tool.execute.before"])+ })+})diff --git a/plugins/opencode-beacon/src/beacon.ts b/plugins/opencode-beacon/src/beacon.tsindex 747b1804..4725609a 100644--- a/plugins/opencode-beacon/src/beacon.ts+++ b/plugins/opencode-beacon/src/beacon.ts@@ -3,6 +3,7 @@// Managed by beacon endpoint hooks install --harness opencode.const beaconCommand = "__BEACON_COMMAND__"+const pluginID = "beacon.endpoint"const debugEnabled = process.env.BEACON_OPENCODE_DEBUG === "1"const sendTimeoutMs = 2000const directHookTypes = new Set([@@ -387,3 +388,222 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien},}}++// OpenCode 2.x loads only a default definition with an id and a setup+// function; 1.x reads the same default export's server field. setup adapts+// the V2 hooks and event stream onto the V1 handlers above, so both runtimes+// send the same payloads to beacon-hooks.+function v2Model(ref) {+ if (!ref?.id) return undefined+ return ref.providerID ? { providerID: ref.providerID, modelID: ref.id } : { modelID: ref.id }+}++function v2PromptParts(prompt) {+ const parts = []+ if (prompt?.text) parts.push({ type: "text", text: prompt.text })+ for (const file of prompt?.files || []) {+ if (file?.uri) parts.push({ type: "file", filename: file.name || file.uri, url: file.uri })+ }+ for (const agent of prompt?.agents || []) {+ if (agent?.name) parts.push({ type: "agent", name: agent.name })+ }+ return parts+}++function v2ToolResponse(result) {+ const structured = result?.output+ const text = (result?.content || [])+ .filter((item) => item?.type === "text" && typeof item.text === "string")+ .map((item) => item.text)+ .join("\n")+ const output = typeof structured === "string" ? structured : structured?.output ?? text+ const metadata = { ...(result?.metadata || {}) }+ if (metadata.exit === undefined && typeof structured?.exit === "number") metadata.exit = structured.exit+ return { output, metadata }+}++// Translates one V2 event into the V1 {type, properties} events the handler+// understands. Tool success and failure arrive through the tool hooks instead.+function v2Events(event, models) {+ const data = event?.data || {}+ const sid = data.sessionID+ const created = typeof event?.created === "number" ? event.created : Date.now()+ switch (event?.type) {+ case "session.created":+ case "session.model.selected": {+ const model = v2Model(data.model)+ if (sid && model) models.set(sid, model)+ if (event.type !== "session.created") return []+ return [{ type: "session.created", properties: { ...data, info: { ...data, id: sid, ...(model || {}) } } }]+ }+ case "session.deleted":+ case "session.idle":+ case "session.status":+ case "permission.replied":+ return [{ type: event.type, properties: data }]+ case "permission.asked":+ return [+ {+ type: "permission.asked",+ properties: { ...data, permission: data.action, patterns: data.resources },+ },+ ]+ case "session.execution.started":+ return [{ type: "session.status", properties: { sessionID: sid, status: { type: "busy" } } }]+ case "session.execution.succeeded":+ case "session.execution.failed":+ case "session.execution.interrupted": {+ const events = []+ if (event.type === "session.execution.failed") {+ events.push({ type: "session.error", properties: { sessionID: sid, error: data.error } })+ }+ events.push({ type: "session.status", properties: { sessionID: sid, status: { type: "idle" } } })+ return events+ }+ case "session.text.ended":+ case "session.reasoning.ended": {+ const messageID = data.assistantMessageID+ const type = event.type === "session.text.ended" ? "text" : "reasoning"+ return [+ {+ type: "message.updated",+ properties: { sessionID: sid, info: { id: messageID, role: "assistant", sessionID: sid, ...(models.get(sid) || {}) } },+ },+ {+ type: "message.part.updated",+ properties: {+ sessionID: sid,+ part: {+ id: `${messageID}:${type}:${data.ordinal ?? 0}`,+ messageID,+ sessionID: sid,+ type,+ text: data.text || "",+ time: { start: created, end: created },+ },+ },+ },+ ]+ }+ case "session.step.ended":+ return [+ {+ type: "message.updated",+ properties: {+ sessionID: sid,+ info: {+ id: data.assistantMessageID,+ role: "assistant",+ sessionID: sid,+ ...(models.get(sid) || {}),+ finish: data.finish,+ tokens: data.tokens,+ cost: data.cost,+ time: { completed: created },+ },+ },+ },+ ]+ default:+ return []+ }+}++export default {+ id: pluginID,+ server: BeaconEndpointPlugin,+ async setup(ctx) {+ const location = ctx?.location || {}+ const hooks = await BeaconEndpointPlugin({+ project: location.project,+ directory: location.directory,+ worktree: location.project?.canonical || location.project?.directory || location.directory,+ client: ctx,+ })+ const models = new Map()+ const registrations = []+ const register = async (domain, name, callback) => {+ try {+ 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)+ } catch (err) {+ await debugLog(ctx, "Beacon V2 hook registration failed", { name, error: String(err) })+ }+ }++ await register(ctx?.session, "prompt", (input) =>+ hooks["chat.message"](+ { sessionID: input?.sessionID, messageID: input?.messageID, ...(models.get(input?.sessionID) || {}) },+ { message: { id: input?.messageID }, parts: v2PromptParts(input?.prompt) },+ ),+ )+ await register(ctx?.tool, "execute.before", (input) =>+ hooks["tool.execute.before"](+ { sessionID: input?.sessionID, tool: input?.tool, callID: input?.id },+ { args: structuredClone(input?.input ?? {}) },+ ),+ )+ await register(ctx?.tool, "execute.after", async (input) => {+ if (input?.status === "completed") {+ await hooks["tool.execute.after"](+ { sessionID: input.sessionID, tool: input.tool, callID: input.id, args: input.input ?? {} },+ v2ToolResponse(input.result),+ )+ return+ }+ const now = Date.now()+ await hooks.event({+ event: {+ type: "message.part.updated",+ properties: {+ sessionID: input?.sessionID,+ part: {+ id: `${input?.messageID}:tool:${input?.id}`,+ messageID: input?.messageID,+ sessionID: input?.sessionID,+ callID: input?.id,+ type: "tool",+ tool: input?.tool,+ state: {+ status: "error",+ input: input?.input ?? {},+ error: input?.error?.message || String(input?.error ?? "tool failed"),+ time: { start: now, end: now },+ },+ },+ },+ },+ })+ })++ const controller = new AbortController()+ const consuming = (async () => {+ if (typeof ctx?.event?.subscribe !== "function") return+ for await (const event of ctx.event.subscribe({ signal: controller.signal })) {+ if (controller.signal.aborted) break+ for (const translated of v2Events(event, models)) {+ try {+ await hooks.event({ event: translated })+ } catch (err) {+ await debugLog(ctx, "Beacon V2 event failed", { type: translated.type, error: String(err) })+ }+ }+ if (event?.type === "session.deleted") models.delete(event?.data?.sessionID)+ }+ })().catch((err) => {+ if (!controller.signal.aborted) void debugLog(ctx, "Beacon V2 event subscription failed", { error: String(err) })+ })++ return async () => {+ controller.abort()+ await consuming+ await Promise.all(registrations.map((item) => item.dispose?.().catch(() => undefined)))+ }+ },+}