Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions go-opencode/go.mod
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
module github.com/opencode-ai/opencode

go 1.23.0

toolchain go1.24.7
go 1.25

require (
// Eino LLM Framework
Expand Down Expand Up @@ -32,6 +30,7 @@ require (
github.com/mark3labs/mcp-go v0.43.1
github.com/modelcontextprotocol/go-sdk v1.1.0
github.com/rs/zerolog v1.34.0
github.com/sergi/go-diff v1.4.0
github.com/spf13/cobra v1.10.1
github.com/sst/opencode-sdk-go v0.0.0-00010101000000-000000000000
github.com/stretchr/testify v1.11.1
Expand Down Expand Up @@ -117,7 +116,7 @@ require (
golang.org/x/text v0.28.0 // indirect
golang.org/x/tools v0.36.0 // indirect
google.golang.org/protobuf v1.36.8 // indirect
gopkg.in/yaml.v2 v2.2.8 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)

replace github.com/sst/opencode-sdk-go => ../packages/sdk/go
Expand Down
6 changes: 5 additions & 1 deletion go-opencode/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,8 @@ github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
Expand All @@ -254,6 +256,7 @@ github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSS
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
Expand Down Expand Up @@ -371,8 +374,9 @@ gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMy
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Expand Down
78 changes: 66 additions & 12 deletions go-opencode/internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,31 @@ import (
)

// Load loads configuration from multiple sources (priority order):
// 1. Global config (~/.opencode/ - TypeScript compatible)
// 2. Global config (~/.config/opencode/ - XDG compatible)
// 3. Project config (.opencode/)
// 4. OPENCODE_CONFIG file
// 5. OPENCODE_CONFIG_CONTENT inline JSON
// 6. Environment variables
// 1. Global config (~/.opencode/ - TypeScript compatible)
// 2. Global config (~/.config/opencode/ - XDG compatible)
// 3. Project configs discovered while walking up from the working directory
// (opencode.json/opencode.jsonc and .opencode/opencode.json/opencode.jsonc)
// 4. OPENCODE_CONFIG file
// 5. OPENCODE_CONFIG_CONTENT inline JSON
// 6. Environment variables
func Load(directory string) (*types.Config, error) {
config := &types.Config{
Provider: make(map[string]types.ProviderConfig),
Agent: make(map[string]types.AgentConfig),
Keybinds: types.DefaultKeybinds(),
}

// Track loaded files to avoid duplicates
loaded := make(map[string]bool)
var loadedFiles []string

// Normalize working directory for deterministic traversal
if directory != "" {
if absDir, err := filepath.Abs(directory); err == nil {
directory = absDir
}
}

loadOnce := func(path string, baseDir string) {
absPath, err := filepath.Abs(path)
if err != nil {
Expand Down Expand Up @@ -60,13 +69,25 @@ func Load(directory string) (*types.Config, error) {
loadOnce(filepath.Join(globalPath, "opencode.json"), globalPath)
loadOnce(filepath.Join(globalPath, "opencode.jsonc"), globalPath)

// 3. Project config
var searchDirs []string
if directory != "" {
projectConfigDir := filepath.Join(directory, ".opencode")
loadOnce(filepath.Join(directory, "opencode.json"), directory)
loadOnce(filepath.Join(directory, "opencode.jsonc"), directory)
loadOnce(filepath.Join(projectConfigDir, "opencode.json"), projectConfigDir)
loadOnce(filepath.Join(projectConfigDir, "opencode.jsonc"), projectConfigDir)
searchDirs = walkUpDirectories(directory)
}

// 3. Project config (root -> leaf for top-level files)
if len(searchDirs) > 0 {
for i := len(searchDirs) - 1; i >= 0; i-- {
dir := searchDirs[i]
loadOnce(filepath.Join(dir, "opencode.jsonc"), dir)
loadOnce(filepath.Join(dir, "opencode.json"), dir)
}

// .opencode directories (leaf -> root, matching TS loader)
for _, dir := range searchDirs {
projectConfigDir := filepath.Join(dir, ".opencode")
loadOnce(filepath.Join(projectConfigDir, "opencode.jsonc"), projectConfigDir)
loadOnce(filepath.Join(projectConfigDir, "opencode.json"), projectConfigDir)
}
}

// 4. OPENCODE_CONFIG file override
Expand Down Expand Up @@ -228,6 +249,9 @@ func mergeConfig(target, source *types.Config) {
target.Share = source.Share
}

// Merge keybinds (per-field override)
target.Keybinds = types.MergeKeybinds(target.Keybinds, source.Keybinds)

// Merge tools
if source.Tools != nil {
if target.Tools == nil {
Expand Down Expand Up @@ -391,3 +415,33 @@ func GetConfigDir() string {
// Fall back to XDG location
return GetPaths().Config
}

// walkUpDirectories returns a slice of directories from the starting directory
// up to either the git root (if found) or filesystem root. The starting directory
// is always the first element in the returned slice.
func walkUpDirectories(start string) []string {
var dirs []string
current := start

for {
dirs = append(dirs, current)

if isGitRoot(current) {
break
}

parent := filepath.Dir(current)
if parent == current {
break
}
current = parent
}

return dirs
}

// isGitRoot checks whether the provided directory contains a .git entry.
func isGitRoot(dir string) bool {
_, err := os.Stat(filepath.Join(dir, ".git"))
return err == nil
}
74 changes: 74 additions & 0 deletions go-opencode/internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,32 @@ func TestLoadTypeScriptConfig(t *testing.T) {
assert.True(t, coder.Tools["edit"])
}

func TestDefaultKeybindsApplied(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "opencode-test-*")
require.NoError(t, err)
defer os.RemoveAll(tmpDir)

// Isolate config paths to avoid picking up user configs
oldHome := os.Getenv("HOME")
oldXdgConfig := os.Getenv("XDG_CONFIG_HOME")
os.Setenv("HOME", tmpDir)
os.Setenv("XDG_CONFIG_HOME", filepath.Join(tmpDir, ".config"))
defer func() {
os.Setenv("HOME", oldHome)
if oldXdgConfig == "" {
os.Unsetenv("XDG_CONFIG_HOME")
} else {
os.Setenv("XDG_CONFIG_HOME", oldXdgConfig)
}
}()

cfg, err := Load("")
require.NoError(t, err)

assert.Equal(t, "ctrl+x", cfg.Keybinds.Leader)
assert.Equal(t, "escape", cfg.Keybinds.SessionInterrupt)
}

func TestJSONCComments(t *testing.T) {
// Create a temporary directory
tmpDir, err := os.MkdirTemp("", "opencode-test-*")
Expand Down Expand Up @@ -262,6 +288,54 @@ func TestConfigMerge(t *testing.T) {
assert.True(t, cfg.Agent["coder"].Tools["edit"])
}

func TestLoadConfigFromParentDirectory(t *testing.T) {
root := t.TempDir()

// Isolate HOME/XDG to avoid picking up user config
oldHome := os.Getenv("HOME")
oldXdg := os.Getenv("XDG_CONFIG_HOME")
os.Setenv("HOME", root)
os.Setenv("XDG_CONFIG_HOME", filepath.Join(root, ".config"))
defer func() {
os.Setenv("HOME", oldHome)
if oldXdg == "" {
os.Unsetenv("XDG_CONFIG_HOME")
} else {
os.Setenv("XDG_CONFIG_HOME", oldXdg)
}
}()

// Parent-level configs
require.NoError(t, os.WriteFile(filepath.Join(root, "opencode.json"), []byte(`{"small_model":"parent-small"}`), 0644))

parentConfigDir := filepath.Join(root, ".opencode")
require.NoError(t, os.MkdirAll(parentConfigDir, 0755))
parentConfig := `{
"model": "parent-model",
"mcp": {
"parent-server": {
"type": "remote",
"url": "https://parent.example.com/mcp"
}
}
}`
require.NoError(t, os.WriteFile(filepath.Join(parentConfigDir, "opencode.json"), []byte(parentConfig), 0644))

workDir := filepath.Join(root, "nested", "project")
require.NoError(t, os.MkdirAll(workDir, 0755))

cfg, err := Load(workDir)
require.NoError(t, err)

assert.Equal(t, "parent-model", cfg.Model)
assert.Equal(t, "parent-small", cfg.SmallModel)
require.NotNil(t, cfg.MCP)
remote, ok := cfg.MCP["parent-server"]
require.True(t, ok)
assert.Equal(t, "remote", remote.Type)
assert.Equal(t, "https://parent.example.com/mcp", remote.URL)
}

func TestEnvVarOverride(t *testing.T) {
// Set test environment variables
os.Setenv("OPENCODE_MODEL", "env-model")
Expand Down
13 changes: 8 additions & 5 deletions go-opencode/internal/event/bus.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,14 @@ import (
type EventType string

const (
SessionCreated EventType = "session.created"
SessionUpdated EventType = "session.updated"
SessionDeleted EventType = "session.deleted"
SessionIdle EventType = "session.idle"
SessionError EventType = "session.error"
SessionCreated EventType = "session.created"
SessionUpdated EventType = "session.updated"
SessionDeleted EventType = "session.deleted"
SessionIdle EventType = "session.idle"
SessionStatus EventType = "session.status"
SessionDiff EventType = "session.diff"
SessionError EventType = "session.error"
SessionCompacted EventType = "session.compacted"
MessageCreated EventType = "message.created"
MessageUpdated EventType = "message.updated"
MessageRemoved EventType = "message.removed"
Expand Down
24 changes: 24 additions & 0 deletions go-opencode/internal/event/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,36 @@ type SessionIdleData struct {
SessionID string `json:"sessionID"`
}

// SessionStatusData is the data for session.status events.
// SDK compatible: uses "sessionID" and "status" fields.
type SessionStatusData struct {
SessionID string `json:"sessionID"`
Status SessionStatusInfo `json:"status"`
}

// SessionStatusInfo represents the current status of a session.
type SessionStatusInfo struct {
Type string `json:"type"` // "busy" | "idle"
}

// SessionDiffData is the data for session.diff events.
// SDK compatible: uses "sessionID" and "diff" fields.
type SessionDiffData struct {
SessionID string `json:"sessionID"`
Diff []types.FileDiff `json:"diff"`
}

// SessionErrorData is the data for session.error events.
type SessionErrorData struct {
SessionID string `json:"sessionID,omitempty"`
Error *types.MessageError `json:"error,omitempty"`
}

// SessionCompactedData is the data for session.compacted events.
type SessionCompactedData struct {
SessionID string `json:"sessionID"`
}

// MessageCreatedData is the data for message.created events.
// SDK compatible: uses "info" field for message object.
type MessageCreatedData struct {
Expand Down
Loading
Loading