agent

package
v1.1.60 Latest Latest
Warning

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

Go to latest
Published: Jul 6, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package agent defines the public Agent interface and related types. External Go developers can import this package to create custom Agent implementations or use the Builder to instantiate the built-in Agent.

Import path: github.com/startvibecoding/mothx/agent

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BoolPtr

func BoolPtr(v bool) *bool

BoolPtr returns a pointer to the given bool value. Useful for setting optional bool fields in ModelCompat.

func SetBuilderFunc

func SetBuilderFunc(fn func(b *Builder) (Agent, error))

SetBuilderFunc registers the internal builder function. Called by internal/agent package at init time.

func SetResolveProviderFunc

func SetResolveProviderFunc(fn func(vendor, baseURL, api, apiKey string) (Provider, error))

SetResolveProviderFunc registers the provider resolution function.

func VendorFromBaseURL

func VendorFromBaseURL(baseURL string) string

VendorFromBaseURL attempts to identify the vendor from a base URL. Returns empty string if no match.

Types

type Agent

type Agent interface {
	// ID returns the unique identifier for this agent.
	ID() AgentID

	// ParentID returns the ID of the parent agent, or empty if top-level.
	ParentID() AgentID

	// Run processes a user message and streams events back.
	Run(ctx context.Context, userMsg string) <-chan Event

	// RunWithMessages processes with explicit message history.
	RunWithMessages(ctx context.Context, messages []Message) <-chan Event

	// Abort signals the agent to stop processing.
	Abort()

	// GetMessages returns a copy of the current message history.
	GetMessages() []Message

	// SetMessages replaces the message history.
	SetMessages(msgs []Message)

	// GetContext returns a copy of the current agent context.
	GetContext() *AgentContext

	// SetContext replaces the agent context.
	SetContext(ctx *AgentContext)

	// GetContextUsage returns the current context window usage, or nil if unavailable.
	GetContextUsage() *ContextUsage

	// LoadHistoryMessages loads historical messages into agent context.
	LoadHistoryMessages(messages []Message)

	// HandleApprovalResponse processes the user's approval response for a pending tool call.
	HandleApprovalResponse(approvalID string, approved bool)
}

Agent is the interface that all agent implementations must satisfy.

type AgentConfigView

type AgentConfigView struct {
	ID       AgentID
	ParentID AgentID
	Mode     string
	ModelID  string
}

AgentConfigView is a read-only view of agent configuration for external inspection.

type AgentContext

type AgentContext struct {
	SystemPrompt string
	Messages     []Message
	Tools        []ToolDefinition
}

AgentContext holds the current agent conversation context.

type AgentID

type AgentID string

AgentID uniquely identifies an agent instance.

type BaseProvider

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

BaseProvider provides common functionality for provider implementations. Embed this in your custom Provider to get Models/GetModel for free.

func NewBaseProvider

func NewBaseProvider(name string, models []ModelInfo) BaseProvider

NewBaseProvider creates a new BaseProvider.

func (*BaseProvider) GetModel

func (p *BaseProvider) GetModel(id string) *ModelInfo

GetModel returns a model by ID, or nil if not found.

func (*BaseProvider) Models

func (p *BaseProvider) Models() []ModelInfo

Models returns the list of available models.

func (*BaseProvider) Name

func (p *BaseProvider) Name() string

Name returns the provider's name.

type Builder

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

Builder provides a fluent API for creating Agent instances. External developers use this to instantiate the built-in Agent without depending on internal packages.

Usage:

a, err := agent.NewBuilder().
    WithProvider(myProvider).
    WithModel("gpt-4").
    WithMode("yolo").
    WithWorkDir("/home/user/project").
    Build()

func NewBuilder

func NewBuilder() *Builder

NewBuilder creates a new Builder with sensible defaults.

func (*Builder) Build

func (b *Builder) Build() (Agent, error)

Build creates and returns an Agent instance. Returns an error if required fields are missing.

func (*Builder) Config

func (b *Builder) Config() BuilderConfig

Config returns a read-only snapshot of the Builder's current configuration. Called by the internal builder function to extract settings without exporting individual fields.

func (*Builder) WithApprovalHandler

func (b *Builder) WithApprovalHandler(h func(toolCallID, toolName string, args map[string]any) bool) *Builder

WithApprovalHandler sets a custom approval handler for tool calls.

func (*Builder) WithCompaction

func (b *Builder) WithCompaction(enabled bool, reserveTokens int) *Builder

WithCompaction configures context compaction.

func (*Builder) WithDelegateMode

func (b *Builder) WithDelegateMode(enabled bool) *Builder

WithDelegateMode enables blocking single sub-agent delegation mode.

func (*Builder) WithExternalTools

func (b *Builder) WithExternalTools(tools ...ExternalTool) *Builder

WithExternalTools registers host-provided custom tools. These are exposed to the agent in addition to the built-in tools, unless WithoutBuiltinTools is also set, in which case only the external tools are available.

func (*Builder) WithMaxIterations

func (b *Builder) WithMaxIterations(n int) *Builder

WithMaxIterations sets the safety limit for agent loop iterations.

func (*Builder) WithMaxTokens

func (b *Builder) WithMaxTokens(n int) *Builder

WithMaxTokens sets the maximum output tokens.

func (*Builder) WithMode

func (b *Builder) WithMode(mode string) *Builder

WithMode sets the agent mode: "plan", "agent", or "yolo".

func (*Builder) WithModel

func (b *Builder) WithModel(modelID string) *Builder

WithModel sets the model ID.

func (*Builder) WithMultiAgent

func (b *Builder) WithMultiAgent(enabled bool) *Builder

WithMultiAgent enables multi-agent mode.

func (*Builder) WithProvider

func (b *Builder) WithProvider(p Provider) *Builder

WithProvider sets the LLM provider.

func (*Builder) WithProviderByName

func (b *Builder) WithProviderByName(vendor, baseURL, api, apiKey string) *Builder

WithProviderByName creates a provider from vendor/baseURL/api/apiKey configuration. This is a convenience method that delegates to the internal provider registry.

func (*Builder) WithSandbox

func (b *Builder) WithSandbox(enabled bool) *Builder

WithSandbox enables or disables sandboxing.

func (*Builder) WithSessionDir

func (b *Builder) WithSessionDir(dir string) *Builder

WithSessionDir sets the session persistence directory.

func (*Builder) WithSystemPromptExtra

func (b *Builder) WithSystemPromptExtra(extra string) *Builder

WithSystemPromptExtra adds extra context to the system prompt.

func (*Builder) WithThinkingLevel

func (b *Builder) WithThinkingLevel(level ThinkingLevel) *Builder

WithThinkingLevel sets the thinking/reasoning level.

func (*Builder) WithToolExecutionMode

func (b *Builder) WithToolExecutionMode(mode string) *Builder

WithToolExecutionMode sets how tool calls are executed: "sequential" or "parallel".

func (*Builder) WithTools

func (b *Builder) WithTools(tools []string) *Builder

WithTools sets a filter for available tools. Empty means all tools.

func (*Builder) WithWorkDir

func (b *Builder) WithWorkDir(dir string) *Builder

WithWorkDir sets the working directory.

func (*Builder) WithoutBuiltinTools

func (b *Builder) WithoutBuiltinTools() *Builder

WithoutBuiltinTools disables all built-in coding tools (read/write/edit/bash/...). Use together with WithExternalTools to run an agent that may only use the host-provided tools. This is the recommended mode for embedding the agent as a controlled orchestration layer over an application's own tool set.

type BuilderConfig

type BuilderConfig struct {
	Provider            Provider
	ModelID             string
	Mode                string
	WorkDir             string
	ThinkingLevel       ThinkingLevel
	MaxTokens           int
	SystemPromptExtra   string
	MaxIterations       int
	ToolExecutionMode   string
	Tools               []string
	SandboxEnabled      bool
	SessionDir          string
	CompactionEnabled   bool
	CompactionReserve   int
	MultiAgent          bool
	DelegateMode        bool
	ApprovalHandler     func(toolCallID, toolName string, args map[string]any) bool
	ExternalTools       []ExternalTool
	DisableBuiltinTools bool
}

BuilderConfig is the read-only snapshot of Builder state. It is used by the internal package to construct the agent without exposing Builder fields directly.

type CacheControl

type CacheControl struct {
	Type string // "ephemeral"
}

CacheControl represents cache control metadata on a content block.

type ChatParams

type ChatParams struct {
	Messages      []Message
	Tools         []ToolDefinition
	SystemPrompt  string
	ThinkingLevel ThinkingLevel
	MaxTokens     int
	ModelID       string
	Abort         chan struct{}
}

ChatParams holds parameters for a chat request.

type ContentBlock

type ContentBlock struct {
	Type         string // "text", "toolCall", "thinking", "image"
	Text         string
	ToolCall     *ToolCallBlock
	Thinking     string
	Signature    string
	Image        *ImageContent
	CacheControl *CacheControl
}

ContentBlock represents a typed block within a message.

type ContextUsage

type ContextUsage struct {
	Tokens        int
	ContextWindow int
	Percent       *float64
}

ContextUsage reports how much of the context window is consumed.

type CostBreakdown

type CostBreakdown struct {
	Input      float64
	Output     float64
	CacheRead  float64
	CacheWrite float64
	Total      float64
}

CostBreakdown itemizes the cost of an LLM call.

type Event

type Event struct {
	AgentID AgentID
	Type    EventType

	// Agent lifecycle
	Messages []Message

	// Turn lifecycle
	TurnMessage     Message
	TurnToolResults []Message

	// Message lifecycle
	Message Message

	// Stream events
	TextDelta  string
	ThinkDelta string

	// Tool events
	ToolCall      *ToolCallBlock
	ToolCallID    string
	ToolName      string
	ToolArgs      map[string]any
	ToolResult    string
	ToolDiff      *FileDiff
	ToolError     error
	PartialResult any

	// Plan events
	Plan *TaskPlan

	// Approval events
	ApprovalID     string
	ApprovalTool   string
	ApprovalArgs   map[string]any
	ApprovalResult bool

	// Question events
	QuestionID      string
	QuestionText    string
	QuestionOptions []string
	QuestionContext string
	QuestionAnswer  string

	// Status
	StatusMessage string

	// Completion
	Done       bool
	StopReason string
	Error      error

	// Usage
	Usage *Usage

	// Context usage
	ContextUsage *ContextUsage
}

Event represents an event from the agent to the consumer.

type EventType

type EventType int

EventType identifies the type of agent event.

const (
	// Agent lifecycle events
	EventAgentStart EventType = iota
	EventAgentEnd

	// Turn lifecycle events (a turn = one assistant response + tool calls/results)
	EventTurnStart
	EventTurnEnd

	// Message lifecycle events
	EventMessageStart
	EventMessageUpdate
	EventMessageEnd

	// Streaming events
	EventTextDelta
	EventThinkDelta

	// Tool execution events
	EventToolCall
	EventToolExecutionStart
	EventToolExecutionUpdate
	EventToolExecutionEnd
	EventToolResult
	EventToolApprovalRequest  // Request user approval for tool execution
	EventToolApprovalResponse // User response to approval request
	EventQuestionRequest      // Ask user a multiple-choice question
	EventQuestionResponse     // User response to question
	EventPlanUpdate           // Structured task plan update

	// Status events
	EventStatus
	EventDone
	EventError
	EventUsage

	// Compaction events
	EventCompactionStart
	EventCompactionEnd
)

type ExternalTool

type ExternalTool interface {
	// Name returns the tool's name (must match ^[a-zA-Z0-9_-]+$ for most providers).
	Name() string

	// Description returns a human-readable description of what the tool does.
	Description() string

	// Parameters returns the JSON Schema (as raw JSON bytes) for the tool's
	// input parameters.
	Parameters() []byte

	// Execute runs the tool with the decoded parameters.
	Execute(ctx context.Context, params map[string]any) (ExternalToolResult, error)
}

ExternalTool is a custom tool supplied by an embedding application (for example, PostgreBase's schema/data tools).

External tools let host applications expose their own controlled capabilities to the agent without depending on the agent's built-in coding tools. Combine with Builder.WithoutBuiltinTools to run an agent that may ONLY use the host-provided tools.

type ExternalToolPromptInfo

type ExternalToolPromptInfo interface {
	// PromptSnippet returns a short one-line description for the system prompt.
	PromptSnippet() string
	// PromptGuidelines returns guideline bullets for the system prompt.
	PromptGuidelines() []string
}

ExternalToolPromptInfo is an optional interface an ExternalTool may implement to contribute richer system-prompt hints. When not implemented, the agent falls back to the tool name and description.

type ExternalToolResult

type ExternalToolResult struct {
	// Text is the plain-text result surfaced to the model and logs.
	Text string

	// IsError marks the result as an error so the agent can react accordingly.
	IsError bool

	// Contents optionally carries rich content blocks (e.g. images) for
	// multimodal results. When empty, Text is used.
	Contents []ContentBlock
}

ExternalToolResult is the normalized result returned by an ExternalTool.

type FileDiff

type FileDiff struct {
	Path         string
	Added        int
	Deleted      int
	AddedLines   []int
	DeletedLines []int
	Unified      string
	Truncated    bool
}

FileDiff describes a file change produced by a write-like tool.

type ImageContent

type ImageContent struct {
	MimeType       string
	Data           string // base64-encoded
	Width          int
	Height         int
	Bytes          int
	OriginalWidth  int
	OriginalHeight int
	OriginalBytes  int
	Detail         string
	Scale          float64
	Cropped        bool
	CropX          int
	CropY          int
	CropWidth      int
	CropHeight     int
}

ImageContent represents an image in a content block.

func (ImageContent) MapNormalizedPointToOriginal

func (img ImageContent) MapNormalizedPointToOriginal(x, y, max float64) (float64, float64, bool)

MapNormalizedPointToOriginal maps a point from a normalized coordinate space such as [0,1000] back to the original source image coordinate space.

func (ImageContent) MapNormalizedRectToOriginal

func (img ImageContent) MapNormalizedRectToOriginal(x, y, width, height, max float64) (float64, float64, float64, float64, bool)

MapNormalizedRectToOriginal maps a rectangle from a normalized coordinate space such as [0,1000] back to the original source image coordinate space.

func (ImageContent) MapPointToOriginal

func (img ImageContent) MapPointToOriginal(x, y float64) (float64, float64, bool)

MapPointToOriginal maps a point in the sent image coordinate space back to the original source image coordinate space.

func (ImageContent) MapRectToOriginal

func (img ImageContent) MapRectToOriginal(x, y, width, height float64) (float64, float64, float64, float64, bool)

MapRectToOriginal maps a rectangle in sent image coordinates back to the original source image coordinate space.

type Message

type Message struct {
	Role           Role
	Content        string
	Contents       []ContentBlock
	IsError        bool
	SystemInjected bool
	ToolCallID     string
	ToolName       string
	Usage          *Usage
}

Message represents a single message in the conversation.

func NewAssistantMessage

func NewAssistantMessage(contents []ContentBlock) Message

NewAssistantMessage creates an assistant message with content blocks.

func NewAssistantTextMessage

func NewAssistantTextMessage(content string) Message

NewAssistantTextMessage creates an assistant message with plain text.

func NewSystemInjectedUserMessage

func NewSystemInjectedUserMessage(content string) Message

NewSystemInjectedUserMessage creates a user message marked as system-injected (skipped by cache markers).

func NewToolResultMessage

func NewToolResultMessage(toolCallID, toolName, content string, isError bool) Message

NewToolResultMessage creates a tool result message with plain text.

func NewToolResultMessageWithContents

func NewToolResultMessageWithContents(toolCallID, toolName, text string, contents []ContentBlock, isError bool) Message

NewToolResultMessageWithContents creates a tool result message with rich content blocks.

func NewUserMessage

func NewUserMessage(content string) Message

NewUserMessage creates a user message with plain text content.

type ModelCompat

type ModelCompat struct {
	// Thinking/reasoning
	ThinkingFormat                      string `json:"thinkingFormat,omitempty"` // "deepseek"|"openai"|"anthropic"|"together"|"zai"|"qwen"
	RequiresReasoningContentOnAssistant bool   `json:"requiresReasoningContentOnAssistant,omitempty"`
	ForceAdaptiveThinking               bool   `json:"forceAdaptiveThinking,omitempty"`

	// API parameter compatibility
	SupportsDeveloperRole   *bool  `json:"supportsDeveloperRole,omitempty"`   // nil = true
	SupportsStore           *bool  `json:"supportsStore,omitempty"`           // nil = true
	SupportsReasoningEffort *bool  `json:"supportsReasoningEffort,omitempty"` // nil = true
	SupportsStrictMode      *bool  `json:"supportsStrictMode,omitempty"`      // nil = true
	MaxTokensField          string `json:"maxTokensField,omitempty"`          // "max_tokens"|"max_completion_tokens"

	// Cache
	SupportsCacheControlOnTools *bool `json:"supportsCacheControlOnTools,omitempty"` // nil = true
	SupportsLongCacheRetention  *bool `json:"supportsLongCacheRetention,omitempty"`  // nil = true
	SendSessionAffinityHeaders  bool  `json:"sendSessionAffinityHeaders,omitempty"`

	// Streaming
	SupportsEagerToolInputStreaming *bool `json:"supportsEagerToolInputStreaming,omitempty"` // nil = true
}

ModelCompat defines per-model compatibility flags. These flags control how the provider adjusts requests/responses for vendor-specific differences. Reference: pi/packages/ai/src/models.generated.ts compat field

type ModelInfo

type ModelInfo struct {
	ID            string
	Name          string
	Provider      string
	Reasoning     bool
	Input         []string
	ContextWindow int
	MaxTokens     int
	Compat        *ModelCompat
}

ModelInfo describes a model available from a provider.

type PlanStep

type PlanStep struct {
	Title  string
	Status string
}

PlanStep describes one step in a task plan.

type Provider

type Provider interface {
	// Chat sends a chat request and returns a channel of streaming events.
	Chat(ctx context.Context, params ChatParams) <-chan StreamEvent

	// Name returns the provider's name (e.g. "openai", "anthropic").
	Name() string

	// Models returns the list of available models.
	Models() []ModelInfo

	// GetModel returns a model by ID, or nil if not found.
	GetModel(id string) *ModelInfo
}

Provider is the interface that all LLM provider implementations must satisfy. External developers implement this to integrate custom LLM backends.

type QuestionHandler

type QuestionHandler interface {
	Agent
	HandleQuestionResponse(questionID string, answer string)
}

QuestionHandler is an optional extension of Agent that supports interactive questions. Only implemented by agents in TUI plan mode. Use type assertion to check support.

type Role

type Role string

Role identifies who produced a message.

const (
	RoleUser       Role = "user"
	RoleAssistant  Role = "assistant"
	RoleToolResult Role = "toolResult"
	RoleSystem     Role = "system"
)

type StreamEvent

type StreamEvent struct {
	Type       StreamEventType
	TextDelta  string
	ThinkDelta string
	ToolCall   *ToolCallBlock
	Usage      *Usage
	StopReason string
	Error      error
}

StreamEvent represents an event from the LLM stream.

type StreamEventType

type StreamEventType int

StreamEventType identifies the type of stream event.

const (
	StreamStart StreamEventType = iota
	StreamTextDelta
	StreamThinkDelta
	StreamToolCall
	StreamUsage
	StreamDone
	StreamError
)

type TaskPlan

type TaskPlan struct {
	Title string
	Steps []PlanStep
	Note  string
}

TaskPlan describes a structured task plan emitted by the plan tool.

type ThinkingLevel

type ThinkingLevel string

ThinkingLevel represents the thinking/reasoning level.

const (
	ThinkingOff     ThinkingLevel = "off"
	ThinkingMinimal ThinkingLevel = "minimal"
	ThinkingLow     ThinkingLevel = "low"
	ThinkingMedium  ThinkingLevel = "medium"
	ThinkingHigh    ThinkingLevel = "high"
	ThinkingXHigh   ThinkingLevel = "xhigh"
)

type ToolCallBlock

type ToolCallBlock struct {
	ID               string
	Name             string
	Arguments        []byte
	InvalidArguments string
	ThoughtSignature string
}

ToolCallBlock represents a tool call requested by the LLM.

type ToolDefinition

type ToolDefinition struct {
	Name         string
	Description  string
	Parameters   []byte // JSON Schema
	Kind         string // "function" (default) or "hosted"
	Provider     string
	ProviderType string
	Model        string
}

ToolDefinition describes a tool available to the LLM.

type Usage

type Usage struct {
	InputTokens  int
	OutputTokens int
	CacheRead    int
	CacheWrite   int
	TotalTokens  int
	Cost         CostBreakdown
}

Usage tracks token consumption for a single LLM response.

func (*Usage) CalculateCost

func (u *Usage) CalculateCost(inputPrice, outputPrice, cacheReadPrice, cacheWritePrice float64)

CalculateCost computes cost based on model pricing.

Jump to

Keyboard shortcuts

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