opencode

package
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 27 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package opencode is the otag adapter for OpenCode v2 (tested with v2.0.20).

Topology (spike/results/opencode.md, docs/ADAPTERS.md): every run gets its own `opencode serve` on 127.0.0.1 with a random password, the account's XDG dirs (the same ones an account wrapper sets) and a per-launch OPENCODE_CONFIG_CONTENT that loads otag's v2 plugin (guards and the system note) and hard deny rules. ServerSetup creates the session over the API (the server picks a native ses_ id) and the pane runs the TUI as a client: `<account command> --server URL -s <id> --prompt ... dir`. Status comes from a sidecar that reads the server's SSE stream (`otag sidecar opencode`), not from hooks; the plugin's guard asks otag through `otag event opencode permission.evaluate`.

Index

Constants

View Source
const (
	KindSession   = "otag.session"        // sidecar: session bound (once per sidecar)
	KindReconcile = "otag.reconcile"      // sidecar: state after a (re)connect
	KindTUIExit   = "otag.tui.exit"       // tui.sh: the TUI process exited
	KindEvaluate  = "permission.evaluate" // plugin: guard question
)

Event kinds that are not OpenCode SSE types. SSE frames use their own type as kind.

View Source
const HeartbeatTimeout = 45 * time.Second

HeartbeatTimeout is the default Adapter.Heartbeat: OpenCode sends ": heartbeat" every 15 s; a stream silent for longer (or a server that sends no response headers for that long) is considered dead and reopened.

View Source
const KindInboxDelivered = "session.inbox.delivered"

KindInboxDelivered is the SSE type that proves a delivery.

View Source
const PluginID = "otag"

PluginID is the id of otag's OpenCode plugin (checked through /api/plugin).

Variables

This section is empty.

Functions

func ConfigContent

func ConfigContent(spec adapter.RunSpec) (string, error)

ConfigContent is the per-launch OPENCODE_CONFIG_CONTENT: otag's plugin (a directory, as v2 requires) and the hard denies. The config `instructions` key is not used: v2 accepts but never loads it; the plugin's context hook adds the system note.

func MessageID

func MessageID(seed string, now time.Time) string

MessageID returns an OpenCode message id (msg_ + 12 hex of the ascending time part + 14 base62) whose random part derives from seed.

func RecordedURL

func RecordedURL(base, runDir string) string

RecordedURL is the server URL otag records for the run (sessions.server_url): the base URL with the run dir in the fragment, so Stop and Deliver find the server password where Prepare put it, whatever the caller's environment.

func SidecarArgs

func SidecarArgs(spec adapter.RunSpec, url, sessionID string) []string

SidecarArgs are the arguments of the SSE sidecar for spec.

func TUIArgv

func TUIArgv(spec adapter.RunSpec, command, url, sessionID string) []string

TUIArgv is the pane command: the TUI as a client of the run's server, wrapped by tui.sh, which reports the TUI's exit as session_end. Without a session id (before SetupServer) the TUI would create one itself; SetupServer always fills it in.

Types

type Adapter

type Adapter struct {
	// FreePort returns a free TCP port on 127.0.0.1 (tests replace it).
	FreePort func() (int, error)
	// Secret returns the server password (tests replace it).
	Secret func() (string, error)
	// LookPath resolves a command name (tests replace it).
	LookPath func(string) (string, error)
	// Home is the user's home directory (tests replace it).
	Home func() (string, error)
	// Getenv finds the run dir for Stop and Deliver (default os.Getenv).
	Getenv func(string) string
	// SetupTimeout bounds SetupServer's waits for the API and the plugin.
	SetupTimeout time.Duration
	// Heartbeat is how long the sidecar's stream may stay silent (0 = HeartbeatTimeout).
	Heartbeat time.Duration
}

Adapter is the OpenCode adapter. The zero value is not usable; use New.

func New

func New() *Adapter

New returns the OpenCode adapter.

func (*Adapter) Deliver

func (a *Adapter) Deliver(ctx context.Context, t adapter.Target, msg adapter.Message) error

Deliver implements adapter.Deliverer (phase 4 plumbing): the message goes into the session inbox, "queue" (after the current turn) or "steer" (at the next step boundary). A message id of the form msg_* makes the delivery idempotent.

func (*Adapter) DeliverReceipt

func (a *Adapter) DeliverReceipt(ctx context.Context, t adapter.Target, m adapter.Message) (adapter.Receipt, error)

DeliverReceipt implements adapter.ReceiptDeliverer. The inbox id is a fresh msg_ id (OpenCode's own form) per attempt; an explicit msg_ Message.ID wins. No session, no server password, a refused connection or an HTTP 4xx wrap adapter.ErrNotSent; a timeout or 5xx after the request was sent is ambiguous.

func (*Adapter) DenyOutput

func (*Adapter) DenyOutput(_, reason string) []byte

DenyOutput implements adapter.Guarder.

func (*Adapter) GuardKind

func (*Adapter) GuardKind(kind string) bool

GuardKind implements adapter.Guarder: the plugin's permission question decides.

func (*Adapter) Harness

func (*Adapter) Harness() string

Harness implements adapter.Adapter.

func (*Adapter) LaunchProvedByTurnStart

func (*Adapter) LaunchProvedByTurnStart() bool

LaunchProvedByTurnStart implements adapter.LaunchTurnProver: the TUI submits the launch prompt itself (--prompt), with neither a receipt nor a hook carrying its text, so the first session.execution.started proves it.

func (*Adapter) NoopOutput

func (*Adapter) NoopOutput(kind string) []byte

NoopOutput implements adapter.Adapter: "{}" answers the plugin's guard question with "no opinion" (the plugin takes an empty answer, a nonzero exit or a signal as a failure and denies); SSE kinds ignore output.

func (*Adapter) ParseEvent

func (a *Adapter) ParseEvent(hc adapter.HookContext, kind string, raw []byte) (adapter.HookResult, error)

ParseEvent implements adapter.Adapter. It is pure: everything comes from the payload and hc.

func (*Adapter) Prepare

func (a *Adapter) Prepare(_ context.Context, spec adapter.RunSpec) (*adapter.LaunchSpec, error)

Prepare implements adapter.Adapter.

func (*Adapter) RunSidecar

func (a *Adapter) RunSidecar(ctx context.Context, sc adapter.Sidecar, args []string) error

RunSidecar implements adapter.SidecarRunner: it follows GET /api/event, forwards the run's events to the bridge (event id = the frame id, so replays dedupe), and after every reconnect reconciles what the stream may have missed. Args: --url URL --dir WORKDIR --session ID [--model provider/model] [--resume].

func (*Adapter) SetupServer

func (a *Adapter) SetupServer(ctx context.Context, spec adapter.RunSpec, launch *adapter.LaunchSpec) error

SetupServer implements adapter.ServerSetup: it checks that the server runs otag's per-launch config, creates the session (or finds the one to resume), checks that otag's plugin is active for the workspace, and points the TUI and the sidecar at the session.

func (*Adapter) Stop

func (a *Adapter) Stop(ctx context.Context, t adapter.Target) error

Stop implements adapter.Stopper: interrupt the running turn over the API, then quit the TUI (Ctrl-C quits an idle TUI; a second one covers a busy or non-empty prompt). otag kills the server and the pane afterwards.

type Model

type Model struct {
	ProviderID string `json:"providerID"`
	ID         string `json:"id"`
	Variant    string `json:"variant,omitempty"`
}

Model is an OpenCode model reference.

func ParseModel

func ParseModel(s string) (*Model, error)

ParseModel splits "provider/model[#variant]". An empty string means the OpenCode default (nil).

type Reconcile

type Reconcile struct {
	SessionID   string              `json:"sessionID"`
	Active      bool                `json:"active"`
	Deleted     bool                `json:"deleted,omitempty"`
	Outcome     string              `json:"outcome,omitempty"` // last finished turn: succeeded|failed|interrupted
	Permissions []permissionRequest `json:"permissions"`
	Forms       []form              `json:"forms"`
}

Reconcile is what the sidecar learned from the API after a reconnect: the stream drops events while disconnected (and OpenCode's local server keeps no replayable event log), so the sidecar reads the current state instead.

type Rule

type Rule struct {
	Action   string `json:"action"`
	Resource string `json:"resource"`
	Effect   string `json:"effect"`
}

Rule is an OpenCode v2 permission rule (last match wins; "*" matches anything, including "/").

func HardDenies

func HardDenies(deny []string) []Rule

HardDenies are the rules otag puts after everything else (config content and the session's own rules), so they win over the user's config and saved approvals: a configured deny is decided before any plugin hook runs. They back up the plugin's guard, and hold without otag: pushes with git options, wrappers (env, command, sudo, VAR=...) or a git path are covered too. OpenCode's "*" matches anything, spaces included, so a rare false positive is possible (a commit message like `git -C . commit -m "a push b"`); the agent then rewords it.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL