agent

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrBusy         = errors.New("agent is busy")
	ErrStopped      = errors.New("agent is stopped")
	ErrInvalidState = errors.New("invalid agent state transition")
	ErrQueueFull    = errors.New("agent control queue is full")
)

Functions

func RegisterDriver

func RegisterDriver(name string, factory DriverFactory) error

func RegisteredDrivers

func RegisteredDrivers() []string

Types

type Agent

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

Agent is the thread-safe state owner and event hub for one runtime session.

func New

func New(driver AgentDriver) *Agent

func (*Agent) Abort

func (a *Agent) Abort(reason string) error

func (*Agent) AppendConversation

func (a *Agent) AppendConversation(msg AgentMessage) error

func (*Agent) Continue

func (a *Agent) Continue(ctx context.Context) error

Continue resumes an existing session without appending a new user prompt.

func (*Agent) ControlQueue

func (a *Agent) ControlQueue() *ControlQueue

func (*Agent) ConversationLen

func (a *Agent) ConversationLen() int

ConversationLen returns the number of conversation entries without cloning the entire session payload.

func (*Agent) FollowUp

func (a *Agent) FollowUp(message string) error

func (*Agent) MarkTurnCompleted

func (a *Agent) MarkTurnCompleted()

func (*Agent) MarkTurnStarted

func (a *Agent) MarkTurnStarted()

func (*Agent) Prompt

func (a *Agent) Prompt(ctx context.Context, prompt string) error

Prompt starts an agent turn with a user prompt.

func (*Agent) RecordError

func (a *Agent) RecordError()

func (*Agent) RecordToolFinished

func (a *Agent) RecordToolFinished()

func (*Agent) RecordToolStarted

func (a *Agent) RecordToolStarted()

func (*Agent) Session

func (a *Agent) Session() *Session

func (*Agent) SetSession

func (a *Agent) SetSession(session *Session)

func (*Agent) Start

func (a *Agent) Start(ctx context.Context, session *Session, prompt string) error

func (*Agent) State

func (a *Agent) State() AgentState

func (*Agent) Steer

func (a *Agent) Steer(message string) error

func (*Agent) Stop

func (a *Agent) Stop(ctx context.Context) error

func (*Agent) Subscribe

func (a *Agent) Subscribe(fn func(AgentEvent)) (unsubscribe func())

func (*Agent) Transition

func (a *Agent) Transition(to AgentState) error

Transition applies an FSM transition and emits state_change on success.

type AgentDriver

type AgentDriver interface {
	Start(ctx context.Context, session *Session, prompt string) error
	Resume(ctx context.Context, session *Session) error
	Stop(ctx context.Context) error
	Subscribe(fn func(AgentEvent)) (unsubscribe func())
}

AgentDriver is the runtime-level driver contract shared by native and adapter drivers.

func NewDriver

func NewDriver(name string, cfg DriverConfig) (AgentDriver, error)

type AgentEvent

type AgentEvent struct {
	Type            AgentEventType
	SessionID       string
	DriverSessionID string
	State           AgentState
	Turn            int
	Message         *AgentMessage
	Assistant       *ai.AssistantMessage
	ToolName        string
	ToolCallID      string
	ToolResult      *AgentToolResult
	Delta           string
	ControlMessage  string
	Error           error
	ErrorMessage    string
	At              time.Time
	Metadata        map[string]any
}

AgentEvent is the normalized event payload used by all driver implementations.

type AgentEventType

type AgentEventType string

AgentEventType is the canonical runtime event taxonomy.

const (
	EventSessionStarted        AgentEventType = "session_started"
	EventSessionEnded          AgentEventType = "session_ended"
	EventTurnStarted           AgentEventType = "turn_started"
	EventTurnCompleted         AgentEventType = "turn_completed"
	EventAgentMessageDelta     AgentEventType = "agent_message_delta"
	EventAgentMessageCompleted AgentEventType = "agent_message_completed"
	EventThinkingDelta         AgentEventType = "thinking_delta"
	EventToolStarted           AgentEventType = "tool_started"
	EventToolUpdate            AgentEventType = "tool_update"
	EventToolCompleted         AgentEventType = "tool_completed"
	EventStateChange           AgentEventType = "state_change"
	EventSteeringApplied       AgentEventType = "steering_applied"
	EventFollowUpEnqueued      AgentEventType = "followup_enqueued"
	EventAborted               AgentEventType = "aborted"
	EventDriverError           AgentEventType = "driver_error"
	EventProviderError         AgentEventType = "provider_error"
	EventToolError             AgentEventType = "tool_error"
	EventTerminalToolCompleted AgentEventType = "terminal_tool_completed"
)

type AgentLoopService

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

AgentLoopService is the in-process implementation of agentapi.AgentService.

func NewAgentLoopService

func NewAgentLoopService(publisher EventPublisher, opts ...ServiceOption) *AgentLoopService

func (*AgentLoopService) Abort

func (*AgentLoopService) Close

func (s *AgentLoopService) Close() error

func (*AgentLoopService) Continue

func (*AgentLoopService) FollowUp

func (*AgentLoopService) GetSession

func (*AgentLoopService) ResumeSession

func (*AgentLoopService) SendMessage

func (*AgentLoopService) SetDriverFactory

func (s *AgentLoopService) SetDriverFactory(factory func(name string, cfg DriverConfig) (AgentDriver, error))

SetDriverFactory overrides the driver factory. Primarily used in tests.

func (*AgentLoopService) Steer

func (*AgentLoopService) SubscribeEvents

type AgentMessage

type AgentMessage struct {
	Turn      int
	Message   ai.Message
	CreatedAt time.Time
}

AgentMessage stores a conversation entry and the turn it belongs to.

type AgentState

type AgentState string

AgentState is the finite-state machine state for one agent instance.

const (
	StateIdle            AgentState = "idle"
	StateStreaming       AgentState = "streaming"
	StateToolExecution   AgentState = "tool_execution"
	StateWaitingFollowUp AgentState = "waiting_follow_up"
	StateExited          AgentState = "exited"
)

type AgentTool

type AgentTool struct {
	ai.Tool
	Label    string
	Terminal bool
	Execute  func(ctx context.Context, toolCallID string, params map[string]any, onUpdate func(AgentToolResult)) (AgentToolResult, error)
}

AgentTool is the backend-agnostic tool contract used by the agent loop.

type AgentToolResult

type AgentToolResult struct {
	Content    []ai.ContentBlock
	SnapshotID string
	ExitCode   *int
	IsError    bool
	Metadata   map[string]any
}

AgentToolResult is the normalized result contract for tool execution callbacks.

type BusyError

type BusyError struct {
	State AgentState
}

BusyError is returned when a state-changing operation is requested while active work is in flight.

func (BusyError) Error

func (e BusyError) Error() string

func (BusyError) Unwrap

func (BusyError) Unwrap() error

type ControlCommand

type ControlCommand struct {
	Type      ControlCommandType
	Message   string
	CreatedAt time.Time
}

ControlCommand represents one serialized control-plane request.

type ControlCommandType

type ControlCommandType string

ControlCommandType is the serialized control-plane command taxonomy.

const (
	ControlSteer    ControlCommandType = "steer"
	ControlFollowUp ControlCommandType = "followup"
	ControlAbort    ControlCommandType = "abort"
)

type ControlQueue

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

ControlQueue serializes steer/follow-up/abort commands from concurrent callers.

func NewControlQueue

func NewControlQueue(buffer int) *ControlQueue

func (*ControlQueue) C

func (q *ControlQueue) C() <-chan ControlCommand

func (*ControlQueue) Close

func (q *ControlQueue) Close()

func (*ControlQueue) Drain

func (q *ControlQueue) Drain() []ControlCommand

func (*ControlQueue) Enqueue

func (q *ControlQueue) Enqueue(cmd ControlCommand) error

func (*ControlQueue) EnqueueAbort

func (q *ControlQueue) EnqueueAbort(message string) error

func (*ControlQueue) EnqueueFollowUp

func (q *ControlQueue) EnqueueFollowUp(message string) error

func (*ControlQueue) EnqueueSteer

func (q *ControlQueue) EnqueueSteer(message string) error

type DriverConfig

type DriverConfig struct {
	Model            ai.Model
	Options          ai.SimpleStreamOptions
	SystemPrompt     string
	Tools            []AgentTool
	EnvironmentTools func() []AgentTool
	Metadata         map[string]any
}

DriverConfig carries optional dependencies into driver factories.

Tools can be provided directly via the Tools field, or lazily via EnvironmentTools. When EnvironmentTools is set and Tools is empty, NativeDriver calls EnvironmentTools() once at start to populate the tool catalog. This avoids a circular import between internal/agent and internal/sandbox/environment — callers wire it via tools.EnvironmentToolsFunc(env).

type DriverFactory

type DriverFactory func(cfg DriverConfig) (AgentDriver, error)

DriverFactory creates an AgentDriver from config.

type EventPublisher

type EventPublisher interface {
	Publish(sessionID string, event AgentEvent)
}

EventPublisher publishes session events to an external sink.

type InvalidStateError

type InvalidStateError struct {
	From AgentState
	To   AgentState
}

InvalidStateError reports an illegal FSM transition.

func (InvalidStateError) Error

func (e InvalidStateError) Error() string

func (InvalidStateError) Unwrap

func (InvalidStateError) Unwrap() error

type NativeDriver

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

NativeDriver implements the canonical LLM -> tools -> LLM turn loop.

func NewNativeDriver

func NewNativeDriver(cfg DriverConfig) *NativeDriver

func (*NativeDriver) Resume

func (d *NativeDriver) Resume(ctx context.Context, session *Session) error

func (*NativeDriver) Start

func (d *NativeDriver) Start(ctx context.Context, session *Session, prompt string) error

func (*NativeDriver) Stop

func (d *NativeDriver) Stop(ctx context.Context) error

func (*NativeDriver) Subscribe

func (d *NativeDriver) Subscribe(fn func(AgentEvent)) func()

type ServiceCode

type ServiceCode string
const (
	CodeInvalidArgument    ServiceCode = "invalid_argument"
	CodeNotFound           ServiceCode = "not_found"
	CodeAlreadyExists      ServiceCode = "already_exists"
	CodeFailedPrecondition ServiceCode = "failed_precondition"
	CodeResourceExhausted  ServiceCode = "resource_exhausted"
	CodeUnavailable        ServiceCode = "unavailable"
	CodeDeadlineExceeded   ServiceCode = "deadline_exceeded"
	CodeCanceled           ServiceCode = "canceled"
	CodeInternal           ServiceCode = "internal"
)

type ServiceError

type ServiceError struct {
	Code    ServiceCode
	Message string
	Cause   error
}

func (*ServiceError) Error

func (e *ServiceError) Error() string

func (*ServiceError) Unwrap

func (e *ServiceError) Unwrap() error

type ServiceOption

type ServiceOption func(*AgentLoopService)

func WithCloseDrainTimeout

func WithCloseDrainTimeout(d time.Duration) ServiceOption

WithCloseDrainTimeout sets the close drain timeout.

func WithMaxSessions

func WithMaxSessions(n int) ServiceOption

WithMaxSessions sets the maximum concurrent session count. Zero means unlimited.

func WithToolCatalogFactory

func WithToolCatalogFactory(factory ToolCatalogFactory) ServiceOption

WithToolCatalogFactory configures how session tools are built from SessionConfig. If nil, the default noop catalog is used.

type Session

type Session struct {
	ID              string
	DriverSessionID string
	ConversationLog []AgentMessage
	StateHistory    []AgentState
	Metrics         SessionMetrics
}

Session is the authoritative runtime session record.

func (*Session) Clone

func (s *Session) Clone() *Session

Clone returns a deep-copy of session slices and maps for safe external reads.

type SessionMetrics

type SessionMetrics struct {
	TurnsStarted      uint64
	TurnsCompleted    uint64
	MessagesAppended  uint64
	ToolCallsStarted  uint64
	ToolCallsFinished uint64
	Errors            uint64
}

SessionMetrics stores low-cardinality counters for session instrumentation.

type StoppedError

type StoppedError struct{}

StoppedError is returned when an operation is attempted after the agent has exited.

func (StoppedError) Error

func (StoppedError) Error() string

func (StoppedError) Unwrap

func (StoppedError) Unwrap() error

type TermmuxDriverAdapter

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

TermmuxDriverAdapter bridges a termmux session to the AgentDriver interface. This allows 3rd party CLI agents (Claude Code, Codex) managed via termmux to be consumed through the same driver contract as the native agent loop.

func NewTermmuxDriverAdapter

func NewTermmuxDriverAdapter(session *termmux.Session) *TermmuxDriverAdapter

NewTermmuxDriverAdapter creates a new adapter wrapping a termmux session.

func (*TermmuxDriverAdapter) IsPaused

func (a *TermmuxDriverAdapter) IsPaused() bool

IsPaused returns whether the termmux session is currently paused.

func (*TermmuxDriverAdapter) Pause

func (a *TermmuxDriverAdapter) Pause(ctx context.Context) error

Pause pauses the termmux session, gating new interactions.

func (*TermmuxDriverAdapter) Resume

func (a *TermmuxDriverAdapter) Resume(ctx context.Context, session *Session) error

Resume resumes an existing termmux session.

func (*TermmuxDriverAdapter) Start

func (a *TermmuxDriverAdapter) Start(ctx context.Context, session *Session, prompt string) error

Start launches the termmux session and begins forwarding events.

func (*TermmuxDriverAdapter) Stop

Stop stops the termmux session.

func (*TermmuxDriverAdapter) Subscribe

func (a *TermmuxDriverAdapter) Subscribe(fn func(AgentEvent)) (unsubscribe func())

Subscribe registers a callback for events. Returns an unsubscribe function. Callbacks are isolated — a panic in one doesn't affect others.

func (*TermmuxDriverAdapter) Unpause

func (a *TermmuxDriverAdapter) Unpause(ctx context.Context) error

Unpause resumes a paused termmux session. Named Unpause (not Resume) to avoid conflict with the existing Resume(ctx, session) method which restarts a stopped session.

type ToolCatalogFactory

type ToolCatalogFactory func(cfg agentapi.SessionConfig) ([]AgentTool, error)

ToolCatalogFactory builds the runtime tool catalog for a session.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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