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 ¶
- func BoolPtr(v bool) *bool
- func SetBuilderFunc(fn func(b *Builder) (Agent, error))
- func SetResolveProviderFunc(fn func(vendor, baseURL, api, apiKey string) (Provider, error))
- func VendorFromBaseURL(baseURL string) string
- type Agent
- type AgentConfigView
- type AgentContext
- type AgentID
- type BaseProvider
- type Builder
- func (b *Builder) Build() (Agent, error)
- func (b *Builder) Config() BuilderConfig
- func (b *Builder) WithApprovalHandler(h func(toolCallID, toolName string, args map[string]any) bool) *Builder
- func (b *Builder) WithCompaction(enabled bool, reserveTokens int) *Builder
- func (b *Builder) WithDelegateMode(enabled bool) *Builder
- func (b *Builder) WithExternalTools(tools ...ExternalTool) *Builder
- func (b *Builder) WithMaxIterations(n int) *Builder
- func (b *Builder) WithMaxTokens(n int) *Builder
- func (b *Builder) WithMode(mode string) *Builder
- func (b *Builder) WithModel(modelID string) *Builder
- func (b *Builder) WithMultiAgent(enabled bool) *Builder
- func (b *Builder) WithProvider(p Provider) *Builder
- func (b *Builder) WithProviderByName(vendor, baseURL, api, apiKey string) *Builder
- func (b *Builder) WithSandbox(enabled bool) *Builder
- func (b *Builder) WithSessionDir(dir string) *Builder
- func (b *Builder) WithSystemPromptExtra(extra string) *Builder
- func (b *Builder) WithThinkingLevel(level ThinkingLevel) *Builder
- func (b *Builder) WithToolExecutionMode(mode string) *Builder
- func (b *Builder) WithTools(tools []string) *Builder
- func (b *Builder) WithWorkDir(dir string) *Builder
- func (b *Builder) WithoutBuiltinTools() *Builder
- type BuilderConfig
- type CacheControl
- type ChatParams
- type ContentBlock
- type ContextUsage
- type CostBreakdown
- type Event
- type EventType
- type ExternalTool
- type ExternalToolPromptInfo
- type ExternalToolResult
- type FileDiff
- type ImageContent
- func (img ImageContent) MapNormalizedPointToOriginal(x, y, max float64) (float64, float64, bool)
- func (img ImageContent) MapNormalizedRectToOriginal(x, y, width, height, max float64) (float64, float64, float64, float64, bool)
- func (img ImageContent) MapPointToOriginal(x, y float64) (float64, float64, bool)
- func (img ImageContent) MapRectToOriginal(x, y, width, height float64) (float64, float64, float64, float64, bool)
- type Message
- func NewAssistantMessage(contents []ContentBlock) Message
- func NewAssistantTextMessage(content string) Message
- func NewSystemInjectedUserMessage(content string) Message
- func NewToolResultMessage(toolCallID, toolName, content string, isError bool) Message
- func NewToolResultMessageWithContents(toolCallID, toolName, text string, contents []ContentBlock, isError bool) Message
- func NewUserMessage(content string) Message
- type ModelCompat
- type ModelInfo
- type PlanStep
- type Provider
- type QuestionHandler
- type Role
- type StreamEvent
- type StreamEventType
- type TaskPlan
- type ThinkingLevel
- type ToolCallBlock
- type ToolDefinition
- type Usage
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BoolPtr ¶
BoolPtr returns a pointer to the given bool value. Useful for setting optional bool fields in ModelCompat.
func SetBuilderFunc ¶
SetBuilderFunc registers the internal builder function. Called by internal/agent package at init time.
func SetResolveProviderFunc ¶
SetResolveProviderFunc registers the provider resolution function.
func VendorFromBaseURL ¶
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 ¶
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 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.
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 ¶
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 ¶
WithCompaction configures context compaction.
func (*Builder) WithDelegateMode ¶
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 ¶
WithMaxIterations sets the safety limit for agent loop iterations.
func (*Builder) WithMaxTokens ¶
WithMaxTokens sets the maximum output tokens.
func (*Builder) WithMultiAgent ¶
WithMultiAgent enables multi-agent mode.
func (*Builder) WithProvider ¶
WithProvider sets the LLM provider.
func (*Builder) WithProviderByName ¶
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 ¶
WithSandbox enables or disables sandboxing.
func (*Builder) WithSessionDir ¶
WithSessionDir sets the session persistence directory.
func (*Builder) WithSystemPromptExtra ¶
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 ¶
WithToolExecutionMode sets how tool calls are executed: "sequential" or "parallel".
func (*Builder) WithWorkDir ¶
WithWorkDir sets the working directory.
func (*Builder) WithoutBuiltinTools ¶
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 ¶
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 ¶
NewAssistantTextMessage creates an assistant message with plain text.
func NewSystemInjectedUserMessage ¶
NewSystemInjectedUserMessage creates a user message marked as system-injected (skipped by cache markers).
func NewToolResultMessage ¶
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 ¶
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 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 ¶
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 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 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 ¶
CalculateCost computes cost based on model pricing.