-
Notifications
You must be signed in to change notification settings - Fork 167
Add OpenCode agent support #341
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
adrianmg
wants to merge
3
commits into
entireio:main
Choose a base branch
from
adrianmg:adrianmg/opencode-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,178 @@ | ||
| // Entire integration plugin for OpenCode. | ||
| // This file is auto-generated by `entire enable` — do not edit manually. | ||
| // It hooks into OpenCode's plugin system to notify Entire of session lifecycle events. | ||
|
|
||
| import { execSync, execFileSync } from "child_process"; | ||
| import { writeFileSync, mkdirSync } from "fs"; | ||
| import { join } from "path"; | ||
| import { tmpdir } from "os"; | ||
|
|
||
| interface HookPayload { | ||
| session_id: string; | ||
| session_ref: string; | ||
| timestamp: string; | ||
| transcript_path: string; | ||
| tool_name?: string; | ||
| tool_use_id?: string; | ||
| tool_input?: Record<string, unknown>; | ||
| tool_response?: Record<string, unknown>; | ||
| subagent_transcript_path?: string; | ||
| } | ||
|
|
||
| // Resolve the entire binary path once at load time. | ||
| // Supports ENTIRE_BIN env var override for development/testing. | ||
| function resolveBinary(): string { | ||
| const envBin = process.env.ENTIRE_BIN; | ||
| if (envBin) return envBin; | ||
| try { | ||
| return execSync("which entire", { encoding: "utf-8" }).trim(); | ||
| } catch { | ||
| return "entire"; | ||
| } | ||
| } | ||
|
|
||
| const entireBin = resolveBinary(); | ||
|
|
||
| function callEntire( | ||
| log: (msg: string) => void, | ||
| verb: string, | ||
| payload: HookPayload, | ||
| ): void { | ||
| try { | ||
| const input = JSON.stringify(payload); | ||
| log(`calling: ${entireBin} hooks opencode ${verb}`); | ||
| execFileSync(entireBin, ["hooks", "opencode", verb], { | ||
| input, | ||
| stdio: ["pipe", "pipe", "pipe"], | ||
| timeout: 30_000, | ||
| }); | ||
| log(`hook ${verb} completed`); | ||
| } catch (e: any) { | ||
| log(`hook ${verb} failed: ${e?.message ?? e}`); | ||
| } | ||
| } | ||
|
|
||
| async function exportTranscript( | ||
| client: any, | ||
| log: (msg: string) => void, | ||
| sessionId: string, | ||
| ): Promise<string> { | ||
| const dir = join(tmpdir(), "entire-opencode"); | ||
| mkdirSync(dir, { recursive: true }); | ||
| const filePath = join(dir, `${sessionId}.jsonl`); | ||
| try { | ||
| log(`exporting transcript for session ${sessionId}`); | ||
| const response = await client.session.messages({ | ||
| path: { id: sessionId }, | ||
| }); | ||
| const messages: any[] = response.data ?? response ?? []; | ||
| const lines = messages.map((m: any) => JSON.stringify(m)); | ||
| writeFileSync(filePath, lines.join("\n") + "\n"); | ||
| log(`transcript exported: ${messages.length} messages → ${filePath}`); | ||
| } catch (e: any) { | ||
| log(`transcript export failed: ${e?.message ?? e}`); | ||
| // Write empty file so hook handler still runs | ||
| writeFileSync(filePath, ""); | ||
| } | ||
| return filePath; | ||
| } | ||
|
|
||
| export const EntirePlugin = async (ctx: { | ||
| project: any; | ||
| client: any; | ||
| $: any; | ||
| directory: string; | ||
| worktree: string; | ||
| }) => { | ||
| // Structured logging via OpenCode SDK | ||
| const log = (message: string) => { | ||
| ctx.client.app | ||
| .log({ | ||
| body: { | ||
| service: "entire", | ||
| level: "info", | ||
| message, | ||
| }, | ||
| }) | ||
| .catch(() => {}); | ||
| }; | ||
|
|
||
| log(`plugin loaded, binary: ${entireBin}`); | ||
|
|
||
| return { | ||
| event: async ({ event }: { event: { type: string; properties: any } }) => { | ||
| if (event.type === "session.created") { | ||
| const sessionId = event.properties.info?.id; | ||
| log(`session.created event, sessionId=${sessionId}`); | ||
| if (!sessionId) return; | ||
| const payload: HookPayload = { | ||
| session_id: sessionId, | ||
| session_ref: sessionId, | ||
| timestamp: new Date().toISOString(), | ||
| transcript_path: "", | ||
| }; | ||
| callEntire(log, "session-start", payload); | ||
| } | ||
|
|
||
| if (event.type === "session.idle") { | ||
| const sessionId = event.properties.sessionID; | ||
| log(`session.idle event, sessionId=${sessionId}`); | ||
| if (!sessionId) return; | ||
| const transcriptPath = await exportTranscript( | ||
| ctx.client, | ||
| log, | ||
| sessionId, | ||
| ); | ||
| const payload: HookPayload = { | ||
| session_id: sessionId, | ||
| session_ref: sessionId, | ||
| timestamp: new Date().toISOString(), | ||
| transcript_path: transcriptPath, | ||
| }; | ||
| callEntire(log, "stop", payload); | ||
| } | ||
| }, | ||
|
|
||
| "tool.execute.before": async ( | ||
| input: { tool: string; sessionID: string; callID: string }, | ||
| output: { args: Record<string, unknown> }, | ||
| ) => { | ||
| if (input.tool !== "task") return; | ||
| log(`tool.execute.before: task ${input.callID}`); | ||
| const payload: HookPayload = { | ||
| session_id: input.sessionID, | ||
| session_ref: input.sessionID, | ||
| timestamp: new Date().toISOString(), | ||
| transcript_path: "", | ||
| tool_name: input.tool, | ||
| tool_use_id: input.callID, | ||
| tool_input: output.args, | ||
| }; | ||
| callEntire(log, "task-start", payload); | ||
| }, | ||
|
|
||
| "tool.execute.after": async ( | ||
| input: { tool: string; sessionID: string; callID: string }, | ||
| output: { title: string; output: string; metadata: any }, | ||
| ) => { | ||
| if (input.tool !== "task") return; | ||
| log(`tool.execute.after: task ${input.callID}`); | ||
| const transcriptPath = await exportTranscript( | ||
| ctx.client, | ||
| log, | ||
| input.sessionID, | ||
| ); | ||
| const payload: HookPayload = { | ||
| session_id: input.sessionID, | ||
| session_ref: input.sessionID, | ||
| timestamp: new Date().toISOString(), | ||
| transcript_path: transcriptPath, | ||
| tool_name: input.tool, | ||
| tool_use_id: input.callID, | ||
| tool_response: { output: output.output }, | ||
| subagent_transcript_path: transcriptPath, | ||
| }; | ||
| callEntire(log, "task-complete", payload); | ||
| }, | ||
| }; | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| package opencode | ||
|
|
||
| import ( | ||
| "embed" | ||
| "fmt" | ||
| "os" | ||
| "path/filepath" | ||
|
|
||
| "github.com/entireio/cli/cmd/entire/cli/agent" | ||
| "github.com/entireio/cli/cmd/entire/cli/paths" | ||
| ) | ||
|
|
||
| // Ensure OpenCodeAgent implements HookSupport and HookHandler | ||
| var ( | ||
| _ agent.HookSupport = (*OpenCodeAgent)(nil) | ||
| _ agent.HookHandler = (*OpenCodeAgent)(nil) | ||
| ) | ||
|
|
||
| // pluginFileName is the name of the Entire plugin file installed into OpenCode. | ||
| const pluginFileName = "entire.ts" | ||
|
|
||
| // pluginDir is the directory within .opencode where plugins are stored. | ||
| const pluginDir = "plugins" | ||
|
|
||
| //go:embed entire.ts | ||
| var pluginFS embed.FS | ||
|
|
||
| // GetHookNames returns the hook verbs OpenCode supports. | ||
| // These become subcommands: entire hooks opencode <verb> | ||
| func (o *OpenCodeAgent) GetHookNames() []string { | ||
| return []string{ | ||
| HookNameSessionStart, | ||
| HookNameStop, | ||
| HookNameTaskStart, | ||
| HookNameTaskComplete, | ||
| } | ||
| } | ||
|
|
||
| // InstallHooks installs the Entire plugin into .opencode/plugins/entire.ts. | ||
| // OpenCode auto-loads TypeScript plugins from .opencode/plugins/ at startup. | ||
| // If force is true, overwrites the existing plugin file. | ||
| // Returns the number of hooks installed (1 plugin file = 1). | ||
| func (o *OpenCodeAgent) InstallHooks(_ bool, force bool) (int, error) { | ||
| repoRoot, err := paths.RepoRoot() | ||
| if err != nil { | ||
| repoRoot, err = os.Getwd() //nolint:forbidigo // Intentional fallback when RepoRoot() fails (tests run outside git repos) | ||
| if err != nil { | ||
| return 0, fmt.Errorf("failed to get current directory: %w", err) | ||
| } | ||
| } | ||
|
|
||
| pluginPath := filepath.Join(repoRoot, ".opencode", pluginDir, pluginFileName) | ||
|
|
||
| // Idempotency: if plugin already exists and force is false, skip | ||
| if !force { | ||
| if _, err := os.Stat(pluginPath); err == nil { | ||
| return 0, nil | ||
| } | ||
| } | ||
|
|
||
| // Read the embedded plugin source | ||
| pluginContent, err := pluginFS.ReadFile(pluginFileName) | ||
| if err != nil { | ||
| return 0, fmt.Errorf("failed to read embedded plugin: %w", err) | ||
| } | ||
|
|
||
| // Create the plugins directory | ||
| if err := os.MkdirAll(filepath.Dir(pluginPath), 0o750); err != nil { | ||
| return 0, fmt.Errorf("failed to create plugins directory: %w", err) | ||
| } | ||
|
|
||
| // Write the plugin file | ||
| if err := os.WriteFile(pluginPath, pluginContent, 0o600); err != nil { | ||
| return 0, fmt.Errorf("failed to write plugin file: %w", err) | ||
| } | ||
|
|
||
| return 1, nil | ||
| } | ||
|
|
||
| // UninstallHooks removes the Entire plugin from .opencode/plugins/. | ||
| func (o *OpenCodeAgent) UninstallHooks() error { | ||
| repoRoot, err := paths.RepoRoot() | ||
| if err != nil { | ||
| repoRoot = "." | ||
| } | ||
|
|
||
| pluginPath := filepath.Join(repoRoot, ".opencode", pluginDir, pluginFileName) | ||
| if err := os.Remove(pluginPath); err != nil && !os.IsNotExist(err) { | ||
| return fmt.Errorf("failed to remove plugin file: %w", err) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // AreHooksInstalled checks if the Entire plugin file exists. | ||
| func (o *OpenCodeAgent) AreHooksInstalled() bool { | ||
| repoRoot, err := paths.RepoRoot() | ||
| if err != nil { | ||
| repoRoot = "." | ||
| } | ||
|
|
||
| pluginPath := filepath.Join(repoRoot, ".opencode", pluginDir, pluginFileName) | ||
| _, err = os.Stat(pluginPath) | ||
| return err == nil | ||
| } | ||
|
|
||
| // GetSupportedHooks returns the hook types OpenCode supports. | ||
| func (o *OpenCodeAgent) GetSupportedHooks() []agent.HookType { | ||
| return []agent.HookType{ | ||
| agent.HookSessionStart, | ||
| agent.HookStop, | ||
| agent.HookPreToolUse, | ||
| agent.HookPostToolUse, | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The PR description states that the ENTIRE_BIN environment variable is "set by hook handlers", but there's no code in hooks_opencode_handlers.go or the hook execution path that actually sets this variable. The resolveBinary function will fall back to using 'which entire' or PATH lookup, which works fine, but the PR description is misleading. Either the description should be corrected to say ENTIRE_BIN is optional (with fallback to PATH), or the hook handlers should actually set this variable for consistency.