Skip to content

Commit e25b2ad

Browse files
yyovilclaudeharshitsinghbhandari
authored
feat(agent): opencode adapter + activity plugin hooks (#80)
* feat(agent): add opencode adapter + activity plugin hooks Add an opencode (sst/opencode) agent adapter implementing the 6-method ports.Agent interface and register it in the daemon's agent resolver, so a session with harness "opencode" spawns and restores a real opencode worker. opencode diverges from the claude-code/codex adapters in two ways the adapter bridges: - No native command-hook config. Unlike Claude Code (.claude/settings.local.json) and Codex (.codex/hooks.json), opencode has no "run this command on event" config (see anomalyco/opencode#5409). Its only lifecycle surface is a JS/TS plugin loaded from .opencode/plugins/. GetAgentHooks therefore //go:embeds an AO-owned plugin (assets/ao-activity.ts) and writes it atomically; install is an idempotent overwrite and uninstall is a sentinel-guarded delete, so user-authored plugins are never touched. The plugin maps opencode events onto AO's three normalized activity events: session.created -> session-start, message.updated/message.part.updated -> user-prompt-submit, and session.status(idle) -> stop (NOT the deprecated session.idle, which is unreliable under `opencode run`). It shells `ao hooks opencode <event>` via a guarded sh -c so a missing `ao` binary is a silent no-op. - A single approval flag. opencode exposes only --dangerously-skip-permissions (no graduated accept-edits/auto) and no system-prompt flag, so those map to a bypass-only permission flag and a documented no-op for the system prompt (deferred to opencode's own config). Launch uses the interactive TUI (`opencode --prompt <p>`); restore continues a captured native session via `opencode --session <id>`. opencode_test.go mirrors codex_test.go (12 tests) and the daemon wiring test now asserts the opencode harness resolves. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(agent): address Greptile review on opencode adapter (#80) - Dispatch all opencode plugin hooks synchronously (Bun.spawnSync). The session.created handler previously fired session-start via an async Bun.spawn; if opencode does not await the event handler, a following message.updated -> user-prompt-submit (sync) could complete before the in-flight async session-start, so AO would see the prompt before the session was registered. A sync spawn blocks opencode's single-threaded event loop, so events are now reported strictly in dispatch order. Removes the now-unused async callHook helper. - Fix package/doc comments that said .opencode/plugin/ (singular) to match the plural .opencode/plugins/ the adapter actually writes to. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(agent): surface opencode hook failures instead of swallowing them The activity plugin previously discarded every failure: callHookSync ignored the subprocess exit code/stderr and both catch blocks were empty, so a failing `ao hooks` invocation or a malformed event payload was completely invisible. Now failures are reported through opencode's structured logger (client.app.log) while still never crashing opencode: - callHookSync pipes stderr and checks result.success; a non-zero exit (a real `ao hooks` failure — the `command -v ao` guard makes a missing binary exit 0) is logged with its exit code and stderr. - spawn exceptions (e.g. no `sh`) are caught and logged. - the event-handler catch logs the offending event type instead of swallowing. - logHookFailure is itself best-effort (optional-chained, rejection swallowed), so logging can never throw back into opencode. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(agent): address opencode adapter review — install guard, prompt dedup, hook timeout Maintainer review on #80 surfaced three pre-merge issues: - GetAgentHooks could clobber a user file: install overwrote .opencode/plugins/ao-activity.ts unconditionally while uninstall was sentinel-guarded. Install now refuses (loud error) to overwrite a file that isn't AO-managed; absent/AO-managed targets still write idempotently. - Empty-prompt report poisoned the dedup: message.updated fired user-prompt-submit with an empty prompt AND marked the message seen, so the text from the following message.part.updated was deduped away and never reached AO — breaking title-from-prompt. reportUserPrompt now reports at most twice: an optional early empty report (keeps run-mode flows active) that does NOT block a later text report, and a text report that is terminal. - Bun.spawnSync had no timeout, so a hung `ao hooks` could block opencode indefinitely. Each spawn is now time-boxed at 30s, matching the claude-code and codex hook timeouts. Adds TestGetAgentHooksRefusesToClobberForeignFile and a spawn-timeout assertion. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix: harden opencode activity hooks --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: harshitsinghbhandari <[email protected]>
1 parent 210c9df commit e25b2ad

6 files changed

Lines changed: 1002 additions & 1 deletion

File tree

Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
// agent-orchestrator: managed opencode activity plugin (do not edit)
2+
//
3+
// It maps opencode's native lifecycle events onto AO's three normalized
4+
// activity events:
5+
// session.created -> `ao hooks opencode session-start`
6+
// message.updated / message.part.updated -> `ao hooks opencode user-prompt-submit`
7+
// session.status (status.type == idle) -> `ao hooks opencode stop`
8+
//
9+
// The opencode-native session id (and prompt/model where known) is piped to the
10+
// hook command as JSON on stdin, run with cwd set to the worktree so AO can
11+
// correlate the opencode session to its AO session. Every invocation is
12+
// best-effort and must never crash the user's opencode session: a missing `ao`
13+
// binary is a guarded no-op (`command -v ao`), and spawn exceptions, non-zero
14+
// exit codes, and malformed event payloads are caught and surfaced through
15+
// opencode's structured logger (client.app.log) for diagnosis — never rethrown.
16+
//
17+
// `import type` is erased at runtime by Bun's transpiler, so this loads even
18+
// before opencode has installed @opencode-ai/plugin into the config dir.
19+
import type { Plugin } from "@opencode-ai/plugin"
20+
21+
export const aoActivity: Plugin = async ({ directory, client }) => {
22+
// ao hooks must never be able to hang opencode: cap each invocation, matching
23+
// the 30s timeout the claude-code and codex hook entries use.
24+
const HOOK_TIMEOUT_MS = 30_000
25+
// A user message is reported at most twice (see reportUserPrompt): an optional
26+
// early empty report, then an upgrade carrying the prompt text. Maps a message
27+
// id to whether the report we already sent included the prompt text.
28+
const promptReports = new Map<string, boolean>()
29+
// message.* events don't carry the session id, so track it from events that do.
30+
let currentSessionID: string | null = null
31+
// The model of the most recent assistant message, forwarded for context.
32+
let currentModel: string | null = null
33+
const messageStore = new Map<string, any>()
34+
35+
// Wrap in `sh -c` with a guard so a missing `ao` binary is a silent no-op
36+
// (exit 0) rather than a per-event error in the user's session.
37+
function hookCmd(hookName: string): string[] {
38+
return ["sh", "-c", `if ! command -v ao >/dev/null 2>&1; then exit 0; fi; exec ao hooks opencode ${hookName}`]
39+
}
40+
41+
// Report a hook failure through opencode's structured logger. Best-effort: the
42+
// log call must itself never throw or reject back into opencode, hence the
43+
// optional chaining + swallowed rejection.
44+
function logHookFailure(hookName: string, detail: string) {
45+
try {
46+
void client?.app
47+
?.log?.({ body: { service: "ao-activity", level: "error", message: `hook ${hookName} failed: ${detail}` } })
48+
?.catch?.(() => {})
49+
} catch {
50+
// The logger itself is unavailable — nothing more we can safely do.
51+
}
52+
}
53+
54+
// All hooks are dispatched synchronously (Bun.spawnSync), for two reasons:
55+
// 1. Ordering. An async hook yields the event loop; if opencode does not
56+
// await the handler's promise, a later event (e.g. message.updated ->
57+
// user-prompt-submit) could complete before an in-flight async
58+
// session-start, so AO would see the prompt before the session is
59+
// registered. spawnSync blocks opencode's single-threaded loop until the
60+
// hook returns, so events are reported strictly in dispatch order.
61+
// 2. `opencode run` exits on the idle event, so an async stop hook would be
62+
// killed before completing.
63+
//
64+
// A non-zero exit (the guard makes a missing `ao` exit 0, so this is a real
65+
// `ao hooks` failure) or a spawn exception is logged with its stderr and never
66+
// rethrown, so reporting failures are diagnosable without crashing opencode.
67+
function callHookSync(hookName: string, payload: Record<string, unknown>) {
68+
try {
69+
const result = Bun.spawnSync(hookCmd(hookName), {
70+
cwd: directory,
71+
stdin: new TextEncoder().encode(JSON.stringify(payload) + "\n"),
72+
stdout: "ignore",
73+
stderr: "pipe",
74+
timeout: HOOK_TIMEOUT_MS,
75+
})
76+
if (!result.success) {
77+
const stderr = result.stderr ? new TextDecoder().decode(result.stderr).trim() : ""
78+
logHookFailure(hookName, `exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`)
79+
}
80+
} catch (err) {
81+
// The spawn itself failed (e.g. no `sh` on PATH). Never propagate.
82+
logHookFailure(hookName, err instanceof Error ? err.message : String(err))
83+
}
84+
}
85+
86+
function switchedSession(sessionID: string): boolean {
87+
if (currentSessionID === sessionID) return false
88+
promptReports.clear()
89+
messageStore.clear()
90+
currentModel = null
91+
currentSessionID = sessionID
92+
return true
93+
}
94+
95+
// Report a user prompt, preferring the one that carries the prompt text.
96+
// message.updated can arrive before message.part.updated with no text, so an
97+
// early empty report must NOT dedup away the later text report — otherwise the
98+
// prompt never reaches AO and title-from-prompt metadata breaks. Therefore: an
99+
// empty report fires at most once (so run-mode flows that omit the text part
100+
// still mark the session active), and a text report fires once and is terminal.
101+
function reportUserPrompt(sessionID: string, messageID: string, prompt: string) {
102+
const hasText = prompt.length > 0
103+
const reportedWithText = promptReports.get(messageID)
104+
if (reportedWithText) return // already reported with text — terminal
105+
if (reportedWithText === false && !hasText) return // already reported empty; no new info
106+
promptReports.set(messageID, hasText)
107+
callHookSync("user-prompt-submit", { session_id: sessionID, prompt, model: currentModel ?? "" })
108+
}
109+
110+
return {
111+
event: async ({ event }) => {
112+
try {
113+
switch (event.type) {
114+
case "session.created": {
115+
const session = (event as any).properties?.info
116+
if (!session?.id) break
117+
if (switchedSession(session.id)) {
118+
callHookSync("session-start", { session_id: session.id })
119+
}
120+
break
121+
}
122+
123+
case "message.updated": {
124+
const msg = (event as any).properties?.info
125+
if (!msg) break
126+
if (msg.sessionID && switchedSession(msg.sessionID)) {
127+
callHookSync("session-start", { session_id: msg.sessionID })
128+
}
129+
if (msg.role === "assistant" && msg.modelID) currentModel = msg.modelID
130+
// Fallback: some `opencode run` flows never deliver message.part.updated
131+
// for the prompt, so start the turn from the user message itself.
132+
if (msg.role === "user") {
133+
messageStore.set(msg.id, msg)
134+
const sessionID = msg.sessionID ?? currentSessionID
135+
if (sessionID) reportUserPrompt(sessionID, msg.id, "")
136+
}
137+
break
138+
}
139+
140+
case "message.part.updated": {
141+
const part = (event as any).properties?.part
142+
if (!part?.messageID) break
143+
const msg = messageStore.get(part.messageID)
144+
if (msg?.role === "user" && part.type === "text") {
145+
const sessionID = msg.sessionID ?? currentSessionID
146+
const prompt = part.text ?? ""
147+
if (sessionID) reportUserPrompt(sessionID, msg.id, prompt)
148+
if (prompt.length > 0) messageStore.delete(part.messageID)
149+
}
150+
break
151+
}
152+
153+
case "session.status": {
154+
// session.status fires in both TUI and `opencode run`; session.idle
155+
// is deprecated and not reliably emitted in run mode.
156+
// AO's "stop" hook means "the current turn is idle/finished", not
157+
// "the whole native session has terminated", so multi-turn TUI
158+
// sessions intentionally emit one stop per idle transition.
159+
const props = (event as any).properties
160+
if (props?.status?.type !== "idle") break
161+
const sessionID = props?.sessionID ?? currentSessionID
162+
if (!sessionID) break
163+
callHookSync("stop", { session_id: sessionID, model: currentModel ?? "" })
164+
break
165+
}
166+
}
167+
} catch (err) {
168+
// A malformed/unexpected event payload must never crash opencode; log
169+
// it (tagged with the event type) for diagnosis and move on.
170+
logHookFailure(`event:${(event as any)?.type ?? "unknown"}`, err instanceof Error ? err.message : String(err))
171+
}
172+
},
173+
}
174+
}
Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
package opencode
2+
3+
import (
4+
"context"
5+
"errors"
6+
"fmt"
7+
"os"
8+
"path/filepath"
9+
"strings"
10+
11+
_ "embed"
12+
13+
"github.com/aoagents/agent-orchestrator/backend/internal/ports"
14+
)
15+
16+
const (
17+
// opencode scans both `.opencode/plugin/` and `.opencode/plugins/` for
18+
// `*.js`/`*.ts` files (see opencode's ConfigPlugin glob
19+
// "{plugin,plugins}/*.{ts,js}"). AO writes the plural `plugins/`, matching
20+
// the directory the upstream opencode tooling (and the entire-cli reference
21+
// integration) uses.
22+
opencodePluginDirName = ".opencode"
23+
opencodePluginSubDir = "plugins"
24+
25+
// opencodePluginFileName is the AO-owned plugin file. AO fully owns this
26+
// filename: install overwrites it and uninstall deletes it (guarded by the
27+
// sentinel), so user-authored plugins in other files are never touched.
28+
// It is TypeScript (opencode runs on Bun); the file's only import is a
29+
// type-only import, which Bun erases at runtime.
30+
opencodePluginFileName = "ao-activity.ts"
31+
32+
// opencodePluginSentinel marks the file as AO-managed. AreHooksInstalled and
33+
// UninstallHooks key off it so AO never deletes a user file that happens to
34+
// share the name. It must appear verbatim in the embedded plugin source.
35+
opencodePluginSentinel = "agent-orchestrator: managed opencode activity plugin"
36+
37+
// opencodeHookCommandPrefix identifies the hook commands AO owns. The
38+
// embedded plugin shells `ao hooks opencode <event>`; this prefix is the
39+
// shared contract with the (forthcoming) `ao hooks` CLI and is asserted by
40+
// tests so the plugin can't silently drift away from it.
41+
opencodeHookCommandPrefix = "ao hooks opencode "
42+
)
43+
44+
// opencodePluginSource is the AO-managed opencode plugin, embedded so it ships
45+
// inside the binary and is written verbatim into a session's worktree on hook
46+
// install. It is a real, lintable source file under assets/ rather than a Go
47+
// string literal because it is opencode plugin source code, not a data
48+
// structure AO assembles (the way it builds Codex/Claude hook JSON).
49+
//
50+
//go:embed assets/ao-activity.ts
51+
var opencodePluginSource string
52+
53+
// opencodeManagedEvents are the three normalized activity events the embedded
54+
// plugin reports. They are defined here (not parsed from the file) so tests can
55+
// assert the plugin wires every one via the `ao hooks opencode <event>` command.
56+
var opencodeManagedEvents = []string{"session-start", "user-prompt-submit", "stop"}
57+
58+
// GetAgentHooks installs AO's opencode activity plugin into the worktree-local
59+
// .opencode/plugins/ directory. Unlike Claude Code and Codex, opencode has no
60+
// native command-hook config to merge into; its only lifecycle-extensibility
61+
// surface is a JS/TS plugin. AO therefore writes a dedicated, AO-owned plugin
62+
// file. The write is atomic and idempotent: re-installing overwrites AO's own
63+
// file with identical content. It refuses to overwrite a file that is NOT
64+
// AO-managed (no sentinel), so a user plugin that happens to occupy our path is
65+
// never silently destroyed — install fails loudly instead.
66+
func (p *Plugin) GetAgentHooks(ctx context.Context, cfg ports.WorkspaceHookConfig) error {
67+
if err := ctx.Err(); err != nil {
68+
return err
69+
}
70+
if strings.TrimSpace(cfg.WorkspacePath) == "" {
71+
return errors.New("opencode.GetAgentHooks: WorkspacePath is required")
72+
}
73+
74+
pluginPath := opencodePluginPath(cfg.WorkspacePath)
75+
// Guard against clobbering a user file at our path: overwrite only when the
76+
// target is absent or already AO-managed. A foreign file is a loud error,
77+
// not silent data loss (uninstall is sentinel-guarded the same way).
78+
if _, err := os.Stat(pluginPath); err == nil {
79+
managed, err := isAOManagedPlugin(pluginPath)
80+
if err != nil {
81+
return fmt.Errorf("opencode.GetAgentHooks: %w", err)
82+
}
83+
if !managed {
84+
return fmt.Errorf("opencode.GetAgentHooks: refusing to overwrite non-AO file at %s — move it so AO can install its plugin", pluginPath)
85+
}
86+
} else if !errors.Is(err, os.ErrNotExist) {
87+
return fmt.Errorf("opencode.GetAgentHooks: stat plugin: %w", err)
88+
}
89+
90+
if err := os.MkdirAll(filepath.Dir(pluginPath), 0o750); err != nil {
91+
return fmt.Errorf("opencode.GetAgentHooks: create plugin dir: %w", err)
92+
}
93+
if err := atomicWriteFile(pluginPath, []byte(opencodePluginSource), 0o600); err != nil {
94+
return fmt.Errorf("opencode.GetAgentHooks: write plugin: %w", err)
95+
}
96+
return nil
97+
}
98+
99+
// UninstallHooks removes AO's opencode plugin from the workspace-local
100+
// .opencode/plugins/ directory. It deletes the file only when it carries the AO
101+
// sentinel, so a user file that happens to share the name is left in place. A
102+
// missing file is a no-op.
103+
func (p *Plugin) UninstallHooks(ctx context.Context, workspacePath string) error {
104+
if err := ctx.Err(); err != nil {
105+
return err
106+
}
107+
if strings.TrimSpace(workspacePath) == "" {
108+
return errors.New("opencode.UninstallHooks: workspacePath is required")
109+
}
110+
111+
pluginPath := opencodePluginPath(workspacePath)
112+
managed, err := isAOManagedPlugin(pluginPath)
113+
if err != nil {
114+
return fmt.Errorf("opencode.UninstallHooks: %w", err)
115+
}
116+
if !managed {
117+
return nil
118+
}
119+
if err := os.Remove(pluginPath); err != nil && !errors.Is(err, os.ErrNotExist) {
120+
return fmt.Errorf("opencode.UninstallHooks: remove plugin: %w", err)
121+
}
122+
return nil
123+
}
124+
125+
// AreHooksInstalled reports whether AO's opencode plugin is present in the
126+
// workspace-local plugin dir. A missing file, or a same-named file without the
127+
// AO sentinel, means none are installed.
128+
func (p *Plugin) AreHooksInstalled(ctx context.Context, workspacePath string) (bool, error) {
129+
if err := ctx.Err(); err != nil {
130+
return false, err
131+
}
132+
if strings.TrimSpace(workspacePath) == "" {
133+
return false, errors.New("opencode.AreHooksInstalled: workspacePath is required")
134+
}
135+
managed, err := isAOManagedPlugin(opencodePluginPath(workspacePath))
136+
if err != nil {
137+
return false, fmt.Errorf("opencode.AreHooksInstalled: %w", err)
138+
}
139+
return managed, nil
140+
}
141+
142+
func opencodePluginPath(workspacePath string) string {
143+
return filepath.Join(workspacePath, opencodePluginDirName, opencodePluginSubDir, opencodePluginFileName)
144+
}
145+
146+
// isAOManagedPlugin reports whether the file at path exists and carries the AO
147+
// sentinel. A missing file yields (false, nil).
148+
func isAOManagedPlugin(path string) (bool, error) {
149+
data, err := os.ReadFile(path) //nolint:gosec // path built from caller-owned workspace dir
150+
if errors.Is(err, os.ErrNotExist) {
151+
return false, nil
152+
}
153+
if err != nil {
154+
return false, fmt.Errorf("read %s: %w", path, err)
155+
}
156+
return strings.Contains(string(data), opencodePluginSentinel), nil
157+
}
158+
159+
// atomicWriteFile writes data to path via a temp file + rename, so a crash mid-
160+
// write can't leave a truncated plugin file that opencode then fails to import
161+
// (silently disabling activity reporting).
162+
func atomicWriteFile(path string, data []byte, perm os.FileMode) error {
163+
tmp, err := os.CreateTemp(filepath.Dir(path), ".ao-tmp-*")
164+
if err != nil {
165+
return err
166+
}
167+
tmpName := tmp.Name()
168+
defer func() { _ = os.Remove(tmpName) }() // no-op once renamed
169+
if _, err := tmp.Write(data); err != nil {
170+
_ = tmp.Close()
171+
return err
172+
}
173+
if err := tmp.Chmod(perm); err != nil {
174+
_ = tmp.Close()
175+
return err
176+
}
177+
if err := tmp.Sync(); err != nil {
178+
_ = tmp.Close()
179+
return err
180+
}
181+
if err := tmp.Close(); err != nil {
182+
return err
183+
}
184+
return os.Rename(tmpName, path)
185+
}

0 commit comments

Comments
 (0)