adapterruntime

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: May 1, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package adapterruntime is a Go SDK for ox adapter authors.

It handles protocol framing, serve-mode dispatch, graceful shutdown, and unknown-method responses so adapter authors can focus on agent-specific logic (session file discovery, transcript parsing, hook installation).

Non-Go adapters implement the same protocol directly against the spec. This package is a convenience layer, not a requirement.

Index

Constants

This section is empty.

Variables

View Source
var ErrSessionNotFound = fmt.Errorf("session not found")

ErrSessionNotFound is returned when an agent_id has no stored session state.

Functions

func AssistantEntry

func AssistantEntry(ts time.Time, content string) adapterprotocol.RawEntry

AssistantEntry creates an assistant message entry.

func Run

func Run(cfg Config)

Run dispatches to the appropriate handler based on os.Args[1]. It reads the subcommand from the CLI arguments, calls the handler, serializes the result as compact JSON to stdout, and exits. For --serve, it enters serve mode (blocking).

func RunWithArgs

func RunWithArgs(cfg Config, args []string, stdin io.Reader, stdout io.Writer) error

RunWithArgs is like Run but accepts explicit args and IO for testing. Returns an error instead of calling os.Exit, making it safe for tests and embedding.

func SystemEntry

func SystemEntry(ts time.Time, content string) adapterprotocol.RawEntry

SystemEntry creates a system/context injection entry.

func ToolResultEntry

func ToolResultEntry(ts time.Time, toolOutput string, isError bool) adapterprotocol.RawEntry

ToolResultEntry creates a tool result entry (error output from a tool call).

func ToolResultWithID

func ToolResultWithID(ts time.Time, toolOutput string, isError bool, callID string) adapterprotocol.RawEntry

ToolResultWithID creates a tool result entry with a correlation ID.

func ToolUseEntry

func ToolUseEntry(ts time.Time, toolName, toolInput string) adapterprotocol.RawEntry

ToolUseEntry creates a tool invocation entry (tool call, no result yet).

func ToolUseWithID

func ToolUseWithID(ts time.Time, toolName, toolInput, callID string) adapterprotocol.RawEntry

ToolUseWithID creates a tool invocation entry with a correlation ID. Use the same callID in ToolResultWithID to correlate call and result.

func UserEntry

func UserEntry(ts time.Time, content string) adapterprotocol.RawEntry

UserEntry creates a user message entry.

func ValidateRepoRoot

func ValidateRepoRoot(root string) error

ValidateRepoRoot checks that a repo root path is non-empty, absolute, and contains a .sageox/ directory. All adapters using this SDK get this validation for free when called via the find-session dispatch path. The .sageox stat uses a 500ms timeout to prevent NFS hangs in hook paths.

func ValidateSessionID

func ValidateSessionID(id string) error

ValidateSessionID checks that a session ID is safe to use in file path construction. It rejects path traversal attempts (../, absolute paths) and path separators that could escape the intended directory.

Types

type CancelSubagentHandler

CancelSubagentHandler handles cancel-subagent requests.

type Config

type Config struct {
	Info              func() (*adapterprotocol.InfoResponse, error)
	Detect            func() (*adapterprotocol.DetectResponse, error)
	InstallHooks      func(adapterprotocol.HookParams) (*adapterprotocol.InstallHooksResponse, error)
	CheckHooks        func(adapterprotocol.HookParams) (*adapterprotocol.CheckHooksResponse, error)
	UninstallHooks    func(adapterprotocol.HookParams) (*adapterprotocol.UninstallHooksResponse, error)
	Read              func(adapterprotocol.ReadParams) (*adapterprotocol.ReadResult, error)
	ReadMetadata      func(adapterprotocol.ReadParams) (*adapterprotocol.ReadMetadataResult, error)
	Diagnose          func(adapterprotocol.DiagnoseParams) (*adapterprotocol.DiagnoseResult, error)
	FindSession       func(adapterprotocol.FindSessionParams) (*adapterprotocol.FindSessionResult, error)
	ReadFromOffset    func(adapterprotocol.ReadFromOffsetParams) (*adapterprotocol.ReadFromOffsetResult, error)
	ImportSession     func(adapterprotocol.ImportSessionParams) (*adapterprotocol.ImportSessionResult, error)
	CapturePrior      func(adapterprotocol.CapturePriorParams) (*adapterprotocol.CapturePriorResult, error)
	InstallRules      func(adapterprotocol.RulesParams) (*adapterprotocol.InstallRulesResponse, error)
	CheckRules        func(adapterprotocol.RulesParams) (*adapterprotocol.CheckRulesResponse, error)
	UninstallRules    func(adapterprotocol.RulesParams) (*adapterprotocol.UninstallRulesResponse, error)
	InstallCommands   func(adapterprotocol.CommandsParams) (*adapterprotocol.InstallCommandsResponse, error)
	CheckCommands     func(adapterprotocol.CommandsParams) (*adapterprotocol.CheckCommandsResponse, error)
	UninstallCommands func(adapterprotocol.CommandsParams) (*adapterprotocol.UninstallCommandsResponse, error)
	Serve             func(*Server)
}

Config holds the handler functions for each adapter subcommand. Nil handlers cause the subcommand to return an error.

type EndSessionHandler

type EndSessionHandler func(ctx context.Context, p adapterprotocol.EndSessionParams) error

EndSessionHandler handles end-session requests.

type FileWatcher

type FileWatcher struct {
	// contains filtered or unexported fields
}

FileWatcher watches session files for changes and pushes entry events. Thread-safe: multiple sessions can be watched concurrently.

func NewFileWatcher

func NewFileWatcher(writer *Writer, readFn ReadFunc) (*FileWatcher, error)

NewFileWatcher creates a watcher that pushes entry events via the writer. readFn is called to read new entries from the session file at a given offset.

func (*FileWatcher) Close

func (fw *FileWatcher) Close()

Close shuts down the file watcher.

func (*FileWatcher) Unwatch

func (fw *FileWatcher) Unwatch(agentID string)

Unwatch stops watching for the given agent.

func (*FileWatcher) Watch

func (fw *FileWatcher) Watch(agentID, sessionFile string, offset int64) error

Watch starts watching a session file for the given agent.

type FindSessionHandler

FindSessionHandler handles find-session requests.

type ReadFromOffsetHandler

ReadFromOffsetHandler handles read-from-offset requests.

type ReadFunc

type ReadFunc func(sessionFile string, offset int64) ([]adapterprotocol.RawEntry, int64, error)

ReadFunc reads new entries from offset and returns them with the new offset.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server manages the serve-mode request/response loop.

func NewServer

func NewServer(r io.Reader, w io.Writer) *Server

NewServer creates a serve-mode server reading from r, writing to w.

func (*Server) Context

func (s *Server) Context() context.Context

Context returns the server's context, canceled on shutdown.

func (*Server) OnCancelSubagent

func (s *Server) OnCancelSubagent(h CancelSubagentHandler)

OnCancelSubagent registers the handler for cancel-subagent requests.

func (*Server) OnEndSession

func (s *Server) OnEndSession(h EndSessionHandler)

OnEndSession registers the handler for end-session requests.

func (*Server) OnFindSession

func (s *Server) OnFindSession(h FindSessionHandler)

OnFindSession registers the handler for find-session requests.

func (*Server) OnReadFromOffset

func (s *Server) OnReadFromOffset(h ReadFromOffsetHandler)

OnReadFromOffset registers the handler for read-from-offset requests.

func (*Server) OnSpawnSubagent

func (s *Server) OnSpawnSubagent(h SpawnSubagentHandler)

OnSpawnSubagent registers the handler for spawn-subagent requests.

func (*Server) OnSubagentStatus

func (s *Server) OnSubagentStatus(h SubagentStatusHandler)

OnSubagentStatus registers the handler for subagent-status requests.

func (*Server) Serve

func (s *Server) Serve()

Serve runs the serve-mode loop. It blocks until shutdown or EOF.

func (*Server) Writer

func (s *Server) Writer() *Writer

Writer returns the thread-safe writer for push events.

type SessionStore

type SessionStore[T any] struct {
	// contains filtered or unexported fields
}

SessionStore is a typed, concurrent-safe store for per-session state. Adapters use it to cache file handles, byte offsets, and other state keyed by agent_id.

func NewSessionStore

func NewSessionStore[T any]() *SessionStore[T]

NewSessionStore creates a new SessionStore.

func (*SessionStore[T]) Delete

func (s *SessionStore[T]) Delete(agentID string) (T, bool)

Delete removes and returns state for an agent.

func (*SessionStore[T]) Get

func (s *SessionStore[T]) Get(agentID string) (T, bool)

Get retrieves state for an agent. Returns false if not found.

func (*SessionStore[T]) Set

func (s *SessionStore[T]) Set(agentID string, state T)

Set stores state for an agent.

type SpawnSubagentHandler

SpawnSubagentHandler handles spawn-subagent requests.

type SubagentStatusHandler

SubagentStatusHandler handles subagent-status requests.

type Writer

type Writer struct {
	// contains filtered or unexported fields
}

Writer provides thread-safe JSON writing to stdout. Both serve-mode responses and push events share the same pipe. Writes are buffered to a bytes.Buffer and flushed as a single Write call to ensure atomicity on pipes (writes < PIPE_BUF are atomic on POSIX).

func NewWriter

func NewWriter(w io.Writer) *Writer

NewWriter creates a thread-safe Writer.

func (*Writer) PushEvent

func (w *Writer) PushEvent(evt adapterprotocol.Event)

PushEvent writes an unsolicited event (e.g., file_watcher entries push).

func (*Writer) WriteResponse

func (w *Writer) WriteResponse(resp adapterprotocol.Response)

WriteResponse writes a serve-mode response.

Jump to

Keyboard shortcuts

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