Documentation
¶
Overview ¶
Package agent provides an abstraction layer for managing communication with OpenCode in agent mode, with a focus on MCP (Model Context Protocol) server configuration.
The agent package enables programmatic control of AI agents through the OpenCode SDK, providing structured configuration for MCP servers, permissions, sessions, and prompts.
Overview ¶
The package is built around several core concepts:
- Agent: The main entry point for interacting with OpenCode
- MCP (Model Context Protocol): Server configuration for tool access
- Session: Conversation context management
- Permission: Fine-grained control over agent capabilities
- Prompt: Structured message construction
- Event: Asynchronous response handling
Native Agentic Framework ¶
The package also provides a standalone, LLM-agnostic agentic framework for building autonomous agents that can run locally using standard goframe components.
The native framework includes three core primitives:
1. Tool Registry (agent.Tool) ¶
The Registry manages available tools with automatic schema generation:
registry := agent.NewRegistry()
// Create tool from function
searchTool, _ := agent.NewToolFromFunc(
"search",
"Search for documents matching a query",
func(ctx context.Context, params SearchParams) (SearchResult, error) {
// implementation
},
)
registry.MustRegisterTool(searchTool)
2. Governance (agent.IntegrityCheck) ¶
Integrity checks validate tool executions before they run:
governance := agent.NewGovernance(
agent.NewPermissionCheck().Allow("read", "write").Deny("delete"),
agent.NewParameterCheck().Require("write", "path"),
)
3. Autonomous Loop (agent.AgentLoop) ¶
The AgentLoop manages the think-act-observe lifecycle:
loop, _ := agent.NewAgentLoop(model, registry,
agent.WithLoopMaxIterations(20),
agent.WithLoopGovernance(governance),
agent.WithLoopSystemPrompt("You are a helpful assistant"),
)
result, _ := loop.Run(ctx, task, nil)
MCP Server Configuration ¶
MCP servers are the primary focus of this package. They enable agents to access external tools and resources. Two transport types are supported:
Local (stdio) servers run as subprocesses:
server := agent.LocalMCPServer("filesystem",
[]string{"mcp-filesystem", "/path/to/repo"},
agent.WithEnv(map[string]string{"LOG_LEVEL": "debug"}),
)
Remote (HTTP/SSE) servers connect over HTTP:
server := agent.RemoteMCPServer("brave-search",
"https://mcp.brave.com/search",
agent.WithHeaders(map[string]string{"Authorization": "Bearer token"}),
)
Servers are managed through an MCPRegistry:
registry := agent.NewMCPRegistry(server1, server2)
agent, _ := agent.New(
agent.WithMCPRegistry(registry),
agent.WithModel("anthropic/claude-3-5-sonnet"),
)
Permissions ¶
Permissions control what actions agents can take. Use the PermissionBuilder for fluent configuration:
perms := agent.NewPermissions().
AllowBash("go test", "go build").
AskBash("rm *").
AllowEdit().
DenyWebfetch().
Build()
agent, _ := agent.New(agent.WithPermissions(perms))
Sessions and Prompts ¶
Agents operate within sessions that maintain conversation context:
session, _ := agent.NewSession(ctx, agent.WithTitle("Code Review"))
defer agent.DeleteSession(ctx, session.ID)
response, _ := session.Prompt(ctx, "Explain this code")
Prompts can include files and other content:
response, _ := session.Prompt(ctx,
"Compare these files",
agent.WithFiles("main.go", "utils.go"),
agent.WithTemperature(0.7),
)
Event Streaming ¶
For async responses, use streaming:
events, _ := agent.Stream(ctx, "Write a haiku")
for event := range events {
switch event.Type {
case agent.EventTypeComplete:
// Handle completion
case agent.EventTypeError:
// Handle error
}
}
Configuration Files ¶
Load configuration from opencode.json files:
config, err := agent.LoadConfigFromDir(".")
agent, _ := agent.New(
agent.WithModel(config.Model),
agent.WithMCPRegistry(agent.NewMCPRegistry(config.GetMCPServers()...)),
)
Thread Safety ¶
The Agent type is safe for concurrent use. All exported methods handle their own synchronization internally.
Index ¶
- Variables
- func SaveConfig(config *Config, path string) error
- func ValidatePath(path, workingDir string) (string, error)
- type ActionVerifier
- type Agent
- func (a *Agent) AddMCPServer(ctx context.Context, server *MCPServer) error
- func (a *Agent) Ask(ctx context.Context, prompt string, opts ...PromptOption) (*Response, error)
- func (a *Agent) DeleteSession(ctx context.Context, id string) error
- func (a *Agent) GetClient() *opencode.Client
- func (a *Agent) GetConfig() *Config
- func (a *Agent) GetEventHandler() *EventHandler
- func (a *Agent) GetSession(ctx context.Context, id string) (*Session, error)
- func (a *Agent) ListMCPServers(ctx context.Context) []*MCPServer
- func (a *Agent) ListSessions(ctx context.Context) ([]*Session, error)
- func (a *Agent) NewSession(ctx context.Context, opts ...SessionOption) (*Session, error)
- func (a *Agent) RemoveMCPServer(ctx context.Context, name string)
- func (a *Agent) Stream(ctx context.Context, prompt string, opts ...PromptOption) (<-chan Event, error)
- type AgentConfig
- type AgentError
- type AgentLoop
- type AgentLoopWithMiddleware
- type AgentMode
- type AgentRefPart
- type AgentType
- type ChannelApprovalHandler
- type CompositeCheck
- type Config
- type ConfigBuilder
- func (b *ConfigBuilder) AddLocalMCP(name string, command []string, env map[string]string) *ConfigBuilder
- func (b *ConfigBuilder) AddRemoteMCP(name string, url string, headers map[string]string) *ConfigBuilder
- func (b *ConfigBuilder) Build() *Config
- func (b *ConfigBuilder) WithAgent(name string, config AgentConfig) *ConfigBuilder
- func (b *ConfigBuilder) WithModel(model string) *ConfigBuilder
- func (b *ConfigBuilder) WithPermissions(perm *PermissionConfig) *ConfigBuilder
- func (b *ConfigBuilder) WithSmallModel(model string) *ConfigBuilder
- type ContentSafetyCheck
- type DefaultRiskAssessor
- type Event
- type EventHandler
- func (h *EventHandler) Clear(eventType EventType)
- func (h *EventHandler) ClearAll()
- func (h *EventHandler) Handle(ctx context.Context, event Event) error
- func (h *EventHandler) On(eventType EventType, handler EventHandlerFunc)
- func (h *EventHandler) OnComplete(handler func(ctx context.Context, resp Response) error)
- func (h *EventHandler) OnError(handler func(ctx context.Context, err error) error)
- func (h *EventHandler) OnFile(handler func(ctx context.Context, file FileInfo) error)
- func (h *EventHandler) OnMessage(handler func(ctx context.Context, msg Message) error)
- func (h *EventHandler) OnPermission(handler func(ctx context.Context, req PermissionRequest) error)
- func (h *EventHandler) OnTextPart(handler func(ctx context.Context, text string) error)
- func (h *EventHandler) OnToolCall(handler func(ctx context.Context, tool ToolCall) error)
- type EventHandlerFunc
- type EventType
- type ExecutionResult
- type FeedbackLoop
- type FeedbackLoopOption
- type FileInfo
- type FilePart
- type Governance
- type HookConfig
- type HookEvent
- type HookFunc
- type HumanApprovalHandler
- type HumanApprovalRequest
- type ImplementRequest
- type ImplementResult
- type IntegrityCheck
- type IntegrityCheckFunc
- type LLMAssistedVerifier
- type LLMAssistedVerifierOption
- type LoopResult
- type LoopState
- type MCPError
- type MCPOption
- type MCPRegistry
- func (r *MCPRegistry) Add(server *MCPServer) error
- func (r *MCPRegistry) Clear()
- func (r *MCPRegistry) Count() int
- func (r *MCPRegistry) Get(name string) (*MCPServer, bool)
- func (r *MCPRegistry) List() []*MCPServer
- func (r *MCPRegistry) Merge(other *MCPRegistry) error
- func (r *MCPRegistry) Remove(name string)
- func (r *MCPRegistry) ToConfigMap() map[string]opencode.ConfigMcp
- type MCPServer
- type MCPServerType
- type Message
- type MiddlewareConfig
- type MiddlewareOption
- func WithActionVerifier(verifier ActionVerifier) MiddlewareOption
- func WithApprovalTimeout(timeout time.Duration) MiddlewareOption
- func WithHighRiskThreshold(level RiskLevel) MiddlewareOption
- func WithHumanApprovalHandler(handler HumanApprovalHandler) MiddlewareOption
- func WithMaxSelfHealingAttempts(n int) MiddlewareOption
- func WithRiskAssessor(assessor RiskAssessor) MiddlewareOption
- func WithVerification(enabled bool) MiddlewareOption
- type MockApprovalHandler
- type Model
- type NativeLoopOption
- func WithLoopGovernance(g *Governance) NativeLoopOption
- func WithLoopLogger(logger *slog.Logger) NativeLoopOption
- func WithLoopMaxIterations(n int) NativeLoopOption
- func WithLoopSystemPrompt(prompt string) NativeLoopOption
- func WithLoopTemperature(temp float64) NativeLoopOption
- func WithLoopTraceID(gen func() string) NativeLoopOption
- type Option
- func WithAgentType(agentType AgentType) Option
- func WithBaseURL(baseURL string) Option
- func WithClient(client *opencode.Client) Option
- func WithLogger(logger *slog.Logger) Option
- func WithMCPRegistry(registry *MCPRegistry) Option
- func WithMCPServers(servers ...*MCPServer) Option
- func WithModel(model string) Option
- func WithPathMapping(mapping map[string]string) Option
- func WithPermissionHandler(handler PermissionHandler) Option
- func WithPermissions(perm *PermissionConfig) Option
- func WithSmallModel(model string) Option
- func WithWorkingDir(dir string) Option
- type PRHandler
- type ParameterCheck
- type Part
- type PermissionBuilder
- func (b *PermissionBuilder) AllowBash(patterns ...string) *PermissionBuilder
- func (b *PermissionBuilder) AllowEdit() *PermissionBuilder
- func (b *PermissionBuilder) AllowWebfetch() *PermissionBuilder
- func (b *PermissionBuilder) AskBash(patterns ...string) *PermissionBuilder
- func (b *PermissionBuilder) AskEdit() *PermissionBuilder
- func (b *PermissionBuilder) AskWebfetch() *PermissionBuilder
- func (b *PermissionBuilder) Build() *PermissionConfig
- func (b *PermissionBuilder) DenyBash(patterns ...string) *PermissionBuilder
- func (b *PermissionBuilder) DenyEdit() *PermissionBuilder
- func (b *PermissionBuilder) DenyWebfetch() *PermissionBuilder
- type PermissionCheck
- type PermissionConfig
- type PermissionHandler
- type PermissionLevel
- type PermissionRequest
- type PermissionResponse
- type PermissionType
- type PromptBuilder
- func (b *PromptBuilder) AddAgentRef(name string) *PromptBuilder
- func (b *PromptBuilder) AddFile(path string) *PromptBuilder
- func (b *PromptBuilder) AddFileFromContent(path string, content []byte, mime string) *PromptBuilder
- func (b *PromptBuilder) AddSymbol(path string, name string, kind int) *PromptBuilder
- func (b *PromptBuilder) AddText(content string) *PromptBuilder
- func (b *PromptBuilder) Build(opts ...PromptOption) *PromptConfig
- type PromptConfig
- type PromptOption
- func WithAgent(name string) PromptOption
- func WithContext(ctx string) PromptOption
- func WithFiles(paths ...string) PromptOption
- func WithParts(parts ...PromptPart) PromptOption
- func WithPromptModel(model string) PromptOption
- func WithSystemPrompt(prompt string) PromptOption
- func WithTemperature(temp float64) PromptOption
- type PromptPart
- func AgentRef(name string) PromptPart
- func File(path string) PromptPart
- func FileFromContent(path string, content []byte, mime string) PromptPart
- func FileWithWorkingDir(path string, workingDir string) PromptPart
- func Symbol(path string, name string, kind int) PromptPart
- func SymbolFromContent(path string, name string, kind int, content []byte) PromptPart
- func SymbolWithWorkingDir(path string, name string, kind int, workingDir string) PromptPart
- func Text(content string) PromptPart
- type RateLimitCheck
- type Registry
- func (r *Registry) Definitions() []map[string]any
- func (r *Registry) Execute(ctx context.Context, name string, params map[string]any) (any, error)
- func (r *Registry) Get(name string) (Tool, error)
- func (r *Registry) GetSchemaMap() map[string]map[string]any
- func (r *Registry) List() []Tool
- func (r *Registry) MustRegisterTool(tool Tool)
- func (r *Registry) Register(tool Tool) error
- func (r *Registry) Unregister(name string)
- type Response
- type ReviewHandler
- type ReviewResult
- type RiskAssessor
- type RiskLevel
- type Session
- func (s *Session) Abort(ctx context.Context) error
- func (s *Session) Close() error
- func (s *Session) Messages(ctx context.Context) ([]Message, error)
- func (s *Session) Prompt(ctx context.Context, prompt string, opts ...PromptOption) (*Response, error)
- func (s *Session) PromptStream(ctx context.Context, prompt string, opts ...PromptOption) (<-chan Event, error)
- func (s *Session) Refresh(ctx context.Context) error
- func (s *Session) Revert(ctx context.Context, messageID string) error
- func (s *Session) Share(ctx context.Context) (string, error)
- func (s *Session) Summarize(ctx context.Context) error
- func (s *Session) Unshare(ctx context.Context) error
- func (s *Session) UpdateTitle(ctx context.Context, title string) error
- type SessionConfig
- type SessionOption
- type StreamResult
- type SymbolPart
- type Task
- type TextPart
- type TextPartData
- type TokenUsage
- type Tool
- type ToolCall
- type ToolCallRecord
- type ToolFunc
- type VerifierResult
Constants ¶
This section is empty.
Variables ¶
var ( // ErrHumanInterventionRequired signals that the agent needs human approval. ErrHumanInterventionRequired = errors.New("agent: human intervention required for high-risk operation") // ErrActionFailedVerification signals that an action did not achieve its intended goal. ErrActionFailedVerification = errors.New("agent: action failed verification") // ErrApprovalTimedOut signals that human approval was not received within the timeout. ErrApprovalTimedOut = errors.New("agent: human approval timed out") )
var ( // ErrNilClient is returned when a nil OpenCode client is provided ErrNilClient = errors.New("client cannot be nil") // ErrNoModel is returned when no model is specified ErrNoModel = errors.New("no model specified") // ErrInvalidModel is returned when the model format is invalid ErrInvalidModel = errors.New("invalid model format, expected provider/model") // ErrSessionNotFound is returned when a session cannot be found ErrSessionNotFound = errors.New("session not found") // ErrSessionAborted is returned when a session is aborted ErrSessionAborted = errors.New("session was aborted") // ErrNoMCPServers is returned when no MCP servers are configured ErrNoMCPServers = errors.New("no MCP servers configured") // ErrMCPServerExists is returned when trying to add a duplicate MCP server ErrMCPServerExists = errors.New("MCP server already exists") // ErrMCPServerNotFound is returned when an MCP server cannot be found ErrMCPServerNotFound = errors.New("MCP server not found") // ErrInvalidMCPConfig is returned when MCP server configuration is invalid ErrInvalidMCPConfig = errors.New("invalid MCP server configuration") // ErrPermissionDenied is returned when an action is denied by permissions ErrPermissionDenied = errors.New("permission denied") // ErrPromptFailed is returned when a prompt operation fails ErrPromptFailed = errors.New("prompt failed") // ErrStreamFailed is returned when a stream operation fails ErrStreamFailed = errors.New("stream failed") )
Error types for the agent package
var ( ErrReviewRejected = errors.New("review rejected") ErrMaxRetries = errors.New("max retries exceeded") ErrToolNotFound = errors.New("tool not found") ErrReviewFailed = errors.New("review failed") ErrExecutionFailed = errors.New("execution failed") )
var ( ErrMaxIterations = errors.New("agent: maximum iterations exceeded") ErrNoLLM = errors.New("agent: no LLM model provided") ErrNoRegistry = errors.New("agent: no tool registry provided") ErrLoopCancelled = errors.New("agent: loop cancelled by context") )
var ( ErrPathTraversal = errors.New("path traversal detected: path outside working directory") ErrEmptyPath = errors.New("empty path provided") )
var ( ErrToolInvalidParams = errors.New("agent: invalid tool parameters") ErrToolExecution = errors.New("agent: tool execution failed") )
var (
ErrGovernanceDenied = errors.New("agent: governance check denied tool execution")
)
Functions ¶
func SaveConfig ¶
func ValidatePath ¶
Types ¶
type ActionVerifier ¶
type ActionVerifier interface {
// VerifyAction checks if a tool execution achieved its goal.
VerifyAction(ctx context.Context, toolName string, params map[string]any, result any) (VerifierResult, error)
}
ActionVerifier verifies that actions achieved their intended goals.
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
func (*Agent) AddMCPServer ¶
func (*Agent) Ask ¶
Ask sends a one-off prompt and returns the response. Note: This creates a new session for each call. For multiple prompts, use NewSession and session.Prompt instead to reuse the session.
func (*Agent) GetEventHandler ¶
func (a *Agent) GetEventHandler() *EventHandler
func (*Agent) GetSession ¶
func (*Agent) NewSession ¶
func (*Agent) Stream ¶
func (a *Agent) Stream(ctx context.Context, prompt string, opts ...PromptOption) (<-chan Event, error)
Stream sends a one-off prompt and returns a channel for streaming responses. Note: This creates a new session for each call. For multiple prompts, use NewSession and session.PromptStream instead to reuse the session.
type AgentConfig ¶
type AgentConfig struct {
Description string `json:"description"`
Prompt string `json:"prompt"`
Model string `json:"model"`
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"top_p,omitempty"`
Mode AgentMode `json:"mode"`
Permissions *PermissionConfig `json:"permissions,omitempty"`
Tools map[string]bool `json:"tools,omitempty"`
}
type AgentError ¶
type AgentError struct {
// Op is the operation that failed
Op string
// Session is the session ID if applicable
Session string
// Err is the underlying error
Err error
// Details contains additional error context
Details map[string]interface{}
}
AgentError represents an error from agent operations
type AgentLoop ¶
type AgentLoop struct {
// GenerateTraceID generates a unique trace ID for the loop.
// If nil, a default UUID-based ID is generated.
GenerateTraceID func() string
// contains filtered or unexported fields
}
AgentLoop manages the "Think-Act-Observe" lifecycle for autonomous agents.
func NewAgentLoop ¶
func NewAgentLoop(model llms.Model, registry *Registry, opts ...NativeLoopOption) (*AgentLoop, error)
NewAgentLoop creates a new agent loop with the given configuration.
func (*AgentLoop) Run ¶
func (l *AgentLoop) Run(ctx context.Context, task Task, history []schema.MessageContent) (*LoopResult, error)
Run executes the autonomous loop for a given task and session. The session maintains the conversation history across iterations.
func (*AgentLoop) RunStream ¶
func (l *AgentLoop) RunStream(ctx context.Context, task Task, history []schema.MessageContent) (<-chan StreamResult, error)
RunStream executes the loop and streams results. This allows real-time monitoring of the agent's progress.
func (*AgentLoop) SetGovernance ¶
func (l *AgentLoop) SetGovernance(g *Governance)
SetGovernance attaches a governance manager to the agent loop. This allows the agent to perform integrity checks, risk assessments, and validation before executing any tools.
type AgentLoopWithMiddleware ¶
type AgentLoopWithMiddleware struct {
*AgentLoop
// contains filtered or unexported fields
}
AgentLoopWithMiddleware extends AgentLoop with agentic middleware.
func NewAgentLoopWithMiddleware ¶
func NewAgentLoopWithMiddleware( model llms.Model, registry *Registry, mwOpts []MiddlewareOption, nativeOpts ...NativeLoopOption, ) (*AgentLoopWithMiddleware, error)
NewAgentLoopWithMiddleware now accepts both types of options.
func (*AgentLoopWithMiddleware) Run ¶
func (l *AgentLoopWithMiddleware) Run(ctx context.Context, task Task, history []schema.MessageContent) (*LoopResult, error)
Run executes the autonomous loop with middleware interception.
Middleware Flow:
- THINK: Call LLM with task + tool definitions
- ASSESS_RISK: If high-risk tool call, assess risk level
- REQUEST_APPROVAL: If above threshold, request human approval
- AWAIT_APPROVAL: Block until human responds
- ACT: Execute tool if approved, abort if rejected
- VERIFY: Check if action achieved intended goal
- SELF_HEAL: If verification failed, inject failure and retry
- OBSERVE: Record result in session history
- REPEAT until LLM produces final answer
type AgentRefPart ¶
type AgentRefPart struct {
// contains filtered or unexported fields
}
func (*AgentRefPart) ToInput ¶
func (p *AgentRefPart) ToInput() (opencode.SessionPromptParamsPartUnion, error)
type ChannelApprovalHandler ¶
type ChannelApprovalHandler struct {
// ApprovalChan receives approval decisions from UI.
ApprovalChan <-chan bool
// RequestChan sends approval requests to UI.
RequestChan chan<- HumanApprovalRequest
// Timeout is the default approval timeout.
Timeout time.Duration
// Logger records approval events.
Logger *slog.Logger
}
ChannelApprovalHandler implements HumanApprovalHandler using channels.
func NewChannelApprovalHandler ¶
func NewChannelApprovalHandler(approvalChan <-chan bool, requestChan chan<- HumanApprovalRequest, timeout time.Duration) *ChannelApprovalHandler
NewChannelApprovalHandler creates a channel-based approval handler.
func (*ChannelApprovalHandler) RequestApproval ¶
func (h *ChannelApprovalHandler) RequestApproval(ctx context.Context, req HumanApprovalRequest) (bool, error)
RequestApproval sends a request and waits for approval.
type CompositeCheck ¶
type CompositeCheck struct {
// contains filtered or unexported fields
}
CompositeCheck combines multiple checks into one.
func NewCompositeCheck ¶
func NewCompositeCheck(checks ...IntegrityCheck) *CompositeCheck
func (*CompositeCheck) Add ¶
func (c *CompositeCheck) Add(check IntegrityCheck)
type Config ¶
type Config struct {
Model string
SmallModel string
AgentType AgentType
Permissions *PermissionConfig
Hooks *HookConfig
WorkingDir string
// PathMapping maps host paths to container paths for Docker-based agents
PathMapping map[string]string
Tools map[string]bool
// contains filtered or unexported fields
}
func LoadConfig ¶
func LoadConfigFromDir ¶
func (*Config) GetAgents ¶
func (c *Config) GetAgents() map[string]AgentConfig
func (*Config) GetMCPServers ¶
type ConfigBuilder ¶
type ConfigBuilder struct {
// contains filtered or unexported fields
}
func NewConfigBuilder ¶
func NewConfigBuilder() *ConfigBuilder
func (*ConfigBuilder) AddLocalMCP ¶
func (b *ConfigBuilder) AddLocalMCP(name string, command []string, env map[string]string) *ConfigBuilder
func (*ConfigBuilder) AddRemoteMCP ¶
func (b *ConfigBuilder) AddRemoteMCP(name string, url string, headers map[string]string) *ConfigBuilder
func (*ConfigBuilder) Build ¶
func (b *ConfigBuilder) Build() *Config
func (*ConfigBuilder) WithAgent ¶
func (b *ConfigBuilder) WithAgent(name string, config AgentConfig) *ConfigBuilder
func (*ConfigBuilder) WithModel ¶
func (b *ConfigBuilder) WithModel(model string) *ConfigBuilder
func (*ConfigBuilder) WithPermissions ¶
func (b *ConfigBuilder) WithPermissions(perm *PermissionConfig) *ConfigBuilder
func (*ConfigBuilder) WithSmallModel ¶
func (b *ConfigBuilder) WithSmallModel(model string) *ConfigBuilder
type ContentSafetyCheck ¶
type ContentSafetyCheck struct {
// BlockedPatterns maps tool names to patterns that should block execution.
BlockedPatterns map[string][]string
}
ContentSafetyCheck validates content for safety concerns. This is a simple implementation - production systems should use more sophisticated checks.
func NewContentSafetyCheck ¶
func NewContentSafetyCheck() *ContentSafetyCheck
func (*ContentSafetyCheck) BlockPattern ¶
func (c *ContentSafetyCheck) BlockPattern(tool string, patterns ...string) *ContentSafetyCheck
type DefaultRiskAssessor ¶
type DefaultRiskAssessor struct {
// contains filtered or unexported fields
}
DefaultRiskAssessor provides basic risk assessment.
func NewDefaultRiskAssessor ¶
func NewDefaultRiskAssessor() *DefaultRiskAssessor
NewDefaultRiskAssessor creates a risk assessor with sensible defaults.
func (*DefaultRiskAssessor) AddCriticalRiskTool ¶
func (r *DefaultRiskAssessor) AddCriticalRiskTool(toolName string)
AddCriticalRiskTool marks a tool as critical-risk.
func (*DefaultRiskAssessor) AddHighRiskTool ¶
func (r *DefaultRiskAssessor) AddHighRiskTool(toolName string)
AddHighRiskTool marks a tool as high-risk.
func (*DefaultRiskAssessor) AssessRisk ¶
func (r *DefaultRiskAssessor) AssessRisk(ctx context.Context, toolName string, params map[string]any) RiskLevel
AssessRisk evaluates the risk level of a tool execution.
type EventHandler ¶
type EventHandler struct {
// contains filtered or unexported fields
}
func NewEventHandler ¶
func NewEventHandler() *EventHandler
func (*EventHandler) Clear ¶
func (h *EventHandler) Clear(eventType EventType)
func (*EventHandler) ClearAll ¶
func (h *EventHandler) ClearAll()
func (*EventHandler) On ¶
func (h *EventHandler) On(eventType EventType, handler EventHandlerFunc)
func (*EventHandler) OnComplete ¶
func (h *EventHandler) OnComplete(handler func(ctx context.Context, resp Response) error)
func (*EventHandler) OnError ¶
func (h *EventHandler) OnError(handler func(ctx context.Context, err error) error)
func (*EventHandler) OnFile ¶
func (h *EventHandler) OnFile(handler func(ctx context.Context, file FileInfo) error)
func (*EventHandler) OnMessage ¶
func (h *EventHandler) OnMessage(handler func(ctx context.Context, msg Message) error)
func (*EventHandler) OnPermission ¶
func (h *EventHandler) OnPermission(handler func(ctx context.Context, req PermissionRequest) error)
func (*EventHandler) OnTextPart ¶
func (h *EventHandler) OnTextPart(handler func(ctx context.Context, text string) error)
func (*EventHandler) OnToolCall ¶
func (h *EventHandler) OnToolCall(handler func(ctx context.Context, tool ToolCall) error)
type ExecutionResult ¶
type FeedbackLoop ¶
type FeedbackLoop struct {
// contains filtered or unexported fields
}
func NewFeedbackLoop ¶
func NewFeedbackLoop(agent *Agent, session *Session, opts ...FeedbackLoopOption) *FeedbackLoop
func (*FeedbackLoop) ImplementWithReview ¶
func (fl *FeedbackLoop) ImplementWithReview(ctx context.Context, req ImplementRequest) (*ImplementResult, error)
type FeedbackLoopOption ¶
type FeedbackLoopOption func(*FeedbackLoop)
func WithMaxRetries ¶
func WithMaxRetries(retries int) FeedbackLoopOption
func WithPRHandler ¶
func WithPRHandler(handler PRHandler) FeedbackLoopOption
func WithPRTool ¶
func WithPRTool(tool string) FeedbackLoopOption
func WithReviewHandler ¶
func WithReviewHandler(handler ReviewHandler) FeedbackLoopOption
func WithReviewTool ¶
func WithReviewTool(tool string) FeedbackLoopOption
type FilePart ¶
type FilePart struct {
// contains filtered or unexported fields
}
func (*FilePart) GetContent ¶
type Governance ¶
type Governance struct {
// contains filtered or unexported fields
}
Governance manages integrity checks for tool execution.
func NewGovernance ¶
func NewGovernance(checks ...IntegrityCheck) *Governance
NewGovernance creates a new governance manager with optional checks.
func (*Governance) AddCheck ¶
func (g *Governance) AddCheck(check IntegrityCheck)
AddCheck appends a new integrity check.
func (*Governance) RemoveAllChecks ¶
func (g *Governance) RemoveAllChecks()
RemoveAllChecks clears all integrity checks.
func (*Governance) SetLogger ¶
func (g *Governance) SetLogger(logger *slog.Logger)
SetLogger configures the governance logger.
type HookConfig ¶
type HumanApprovalHandler ¶
type HumanApprovalHandler interface {
// RequestApproval requests human approval and blocks until received.
// Returns true if approved, false if rejected, or error on timeout/failure.
RequestApproval(ctx context.Context, req HumanApprovalRequest) (bool, error)
}
HumanApprovalHandler handles human approval requests.
type HumanApprovalRequest ¶
type HumanApprovalRequest struct {
// ToolName is the tool being executed.
ToolName string
// Params are the parameters for the tool call.
Params map[string]any
// Reason explains why this action is necessary.
Reason string
// Impact describes the potential impact.
Impact string
// RiskLevel is the assessed risk level.
RiskLevel RiskLevel
// Timeout is the maximum wait time for approval.
Timeout time.Duration
}
HumanApprovalRequest represents a request for human approval.
type ImplementRequest ¶
type ImplementResult ¶
type IntegrityCheck ¶
type IntegrityCheck interface {
// Validate checks if a tool execution should be allowed.
// Returns nil to allow execution, or an error to deny it.
// The error message will be provided to the agent as observation for self-correction.
Validate(ctx context.Context, toolName string, params map[string]any) error
}
IntegrityCheck validates tool executions before they run. Implementations can enforce policies, validate inputs, or prevent dangerous operations.
type IntegrityCheckFunc ¶
IntegrityCheckFunc is an adapter to use a function as an IntegrityCheck.
type LLMAssistedVerifier ¶
type LLMAssistedVerifier struct {
// contains filtered or unexported fields
}
LLMAssistedVerifier uses an LLM to verify action results.
func NewLLMAssistedVerifier ¶
func NewLLMAssistedVerifier(model Model, opts ...LLMAssistedVerifierOption) *LLMAssistedVerifier
NewLLMAssistedVerifier creates a verifier that uses an LLM for verification.
func (*LLMAssistedVerifier) VerifyAction ¶
func (v *LLMAssistedVerifier) VerifyAction(ctx context.Context, toolName string, params map[string]any, result any) (VerifierResult, error)
VerifyAction verifies that a tool execution achieved its intended goal.
type LLMAssistedVerifierOption ¶
type LLMAssistedVerifierOption func(*LLMAssistedVerifier)
LLMAssistedVerifierOption configures the verifier.
func WithVerifierLogger ¶
func WithVerifierLogger(logger *slog.Logger) LLMAssistedVerifierOption
WithVerifierLogger sets the logger.
func WithVerifierMaxRetries ¶
func WithVerifierMaxRetries(n int) LLMAssistedVerifierOption
WithVerifierMaxRetries sets the maximum verification retries.
type LoopResult ¶
type LoopResult struct {
// Response is the final answer from the LLM.
Response string
// ToolCalls is the list of tool calls made during execution.
ToolCalls []ToolCallRecord
// Iterations is the number of think-act-observe cycles completed.
Iterations int
// Tokens is the total token usage across all LLM calls.
Tokens TokenUsage
// State is the final loop state.
State LoopState
// TraceID is a unique identifier for tracing loop execution.
TraceID string
}
LoopResult represents the final result of an agent loop execution.
type MCPError ¶
type MCPError struct {
// Server is the name of the MCP server
Server string
// Err is the underlying error
Err error
// Details contains additional error context
Details map[string]interface{}
}
MCPError represents an error from MCP server operations
type MCPOption ¶
type MCPOption func(*MCPServer)
MCPOption configures an MCP server
func WithEnabled ¶
WithEnabled sets whether the server is enabled
func WithHeaders ¶
WithHeaders sets HTTP headers for remote MCP servers
type MCPRegistry ¶
type MCPRegistry struct {
// contains filtered or unexported fields
}
MCPRegistry manages a collection of MCP servers
func NewMCPRegistry ¶
func NewMCPRegistry(servers ...*MCPServer) *MCPRegistry
NewMCPRegistry creates a new registry with the given servers
func (*MCPRegistry) Add ¶
func (r *MCPRegistry) Add(server *MCPServer) error
Add adds an MCP server to the registry
func (*MCPRegistry) Clear ¶
func (r *MCPRegistry) Clear()
Clear removes all servers from the registry
func (*MCPRegistry) Count ¶
func (r *MCPRegistry) Count() int
Count returns the number of servers in the registry
func (*MCPRegistry) Get ¶
func (r *MCPRegistry) Get(name string) (*MCPServer, bool)
Get retrieves an MCP server by name
func (*MCPRegistry) List ¶
func (r *MCPRegistry) List() []*MCPServer
List returns all MCP servers in the registry
func (*MCPRegistry) Merge ¶
func (r *MCPRegistry) Merge(other *MCPRegistry) error
Merge combines another registry into this one
func (*MCPRegistry) Remove ¶
func (r *MCPRegistry) Remove(name string)
Remove removes an MCP server from the registry
func (*MCPRegistry) ToConfigMap ¶
func (r *MCPRegistry) ToConfigMap() map[string]opencode.ConfigMcp
ToConfigMap converts all servers to the OpenCode SDK configuration format
type MCPServer ¶
type MCPServer struct {
// Name is the unique identifier for the server
Name string `json:"name"`
// Type specifies whether this is a local or remote server
Type MCPServerType `json:"type"`
// Command is the executable and arguments for local servers
Command []string `json:"command,omitempty"`
// Environment variables for local servers
Environment map[string]string `json:"environment,omitempty"`
// URL is the endpoint for remote servers
URL string `json:"url,omitempty"`
// Headers for remote server authentication
Headers map[string]string `json:"headers,omitempty"`
// Enabled determines if the server is active
Enabled bool `json:"enabled"`
// Disabled explicitly disables a server
Disabled bool `json:"disabled,omitempty"`
}
MCPServer defines an MCP (Model Context Protocol) server configuration
func LocalMCPServer ¶
LocalMCPServer creates a local MCP server that runs as a subprocess using stdio for communication.
Example:
server := LocalMCPServer("filesystem",
[]string{"mcp-filesystem", "/path/to/repo"},
WithEnv(map[string]string{"LOG_LEVEL": "debug"}),
WithEnabled(true),
)
func RemoteMCPServer ¶
RemoteMCPServer creates a remote MCP server that connects via HTTP/SSE.
Example:
server := RemoteMCPServer("brave-search",
"https://mcp.brave.com/search",
WithHeaders(map[string]string{"Authorization": "Bearer token"}),
WithEnabled(true),
)
type MCPServerType ¶
type MCPServerType string
MCPServerType defines the type of MCP server connection
const ( // MCPServerTypeLocal represents a local MCP server using stdio transport MCPServerTypeLocal MCPServerType = "local" // MCPServerTypeRemote represents a remote MCP server using HTTP/SSE transport MCPServerTypeRemote MCPServerType = "remote" )
type MiddlewareConfig ¶
type MiddlewareConfig struct {
// HumanApprovalHandler handles high-risk tool approval requests.
HumanApprovalHandler HumanApprovalHandler
// RiskAssessor evaluates the risk level of tool calls.
RiskAssessor RiskAssessor
// ActionVerifier verifies that actions achieved their goals.
ActionVerifier ActionVerifier
// VerificationEnabled enables action verification after tool calls.
VerificationEnabled bool
// HighRiskThreshold is the minimum risk level requiring human approval.
HighRiskThreshold RiskLevel
// ApprovalTimeout is the maximum wait time for human approval.
ApprovalTimeout time.Duration
// MaxSelfHealingAttempts is the maximum retry attempts for self-healing.
MaxSelfHealingAttempts int
}
MiddlewareConfig configures agentic middleware for the agent loop.
func DefaultMiddlewareConfig ¶
func DefaultMiddlewareConfig() MiddlewareConfig
DefaultMiddlewareConfig returns sensible defaults.
type MiddlewareOption ¶
type MiddlewareOption func(*MiddlewareConfig)
MiddlewareOption configures the middleware.
func WithActionVerifier ¶
func WithActionVerifier(verifier ActionVerifier) MiddlewareOption
WithActionVerifier sets the action verifier.
func WithApprovalTimeout ¶
func WithApprovalTimeout(timeout time.Duration) MiddlewareOption
WithApprovalTimeout sets the human approval timeout.
func WithHighRiskThreshold ¶
func WithHighRiskThreshold(level RiskLevel) MiddlewareOption
WithHighRiskThreshold sets the risk level that requires human approval.
func WithHumanApprovalHandler ¶
func WithHumanApprovalHandler(handler HumanApprovalHandler) MiddlewareOption
WithHumanApprovalHandler sets the human approval handler.
func WithMaxSelfHealingAttempts ¶
func WithMaxSelfHealingAttempts(n int) MiddlewareOption
WithMaxSelfHealingAttempts sets the maximum retry attempts for self-healing.
func WithRiskAssessor ¶
func WithRiskAssessor(assessor RiskAssessor) MiddlewareOption
WithRiskAssessor sets the risk assessor.
func WithVerification ¶
func WithVerification(enabled bool) MiddlewareOption
WithVerification enables or disables action verification.
type MockApprovalHandler ¶
type MockApprovalHandler struct {
AutoApprove bool
AutoReject bool
Delay time.Duration
Logger *slog.Logger
}
MockApprovalHandler is a simple approval handler for testing.
func NewMockApprovalHandler ¶
func NewMockApprovalHandler(autoApprove bool) *MockApprovalHandler
NewMockApprovalHandler creates a mock handler for testing.
func (*MockApprovalHandler) RequestApproval ¶
func (h *MockApprovalHandler) RequestApproval(ctx context.Context, req HumanApprovalRequest) (bool, error)
RequestApproval returns a configured response for testing.
type NativeLoopOption ¶
type NativeLoopOption func(*AgentLoop)
NativeLoopOption configures the agent loop.
func WithLoopGovernance ¶
func WithLoopGovernance(g *Governance) NativeLoopOption
WithLoopGovernance sets the governance checks.
func WithLoopLogger ¶
func WithLoopLogger(logger *slog.Logger) NativeLoopOption
WithLoopLogger sets the logger for the loop.
func WithLoopMaxIterations ¶
func WithLoopMaxIterations(n int) NativeLoopOption
WithLoopMaxIterations sets the maximum number of iterations.
func WithLoopSystemPrompt ¶
func WithLoopSystemPrompt(prompt string) NativeLoopOption
WithLoopSystemPrompt sets the system prompt for the LLM.
func WithLoopTemperature ¶
func WithLoopTemperature(temp float64) NativeLoopOption
WithLoopTemperature sets the LLM temperature.
func WithLoopTraceID ¶
func WithLoopTraceID(gen func() string) NativeLoopOption
WithLoopTraceID sets a custom trace ID generator. The trace ID is useful for correlating logs across a multi-step agent execution.
type Option ¶
func WithAgentType ¶
func WithBaseURL ¶
func WithClient ¶
func WithLogger ¶
func WithMCPRegistry ¶
func WithMCPRegistry(registry *MCPRegistry) Option
func WithMCPServers ¶
func WithPathMapping ¶
WithPathMapping configures path translation for Docker-based agents. It maps host paths to container paths so that when the agent creates a session, the directory is correctly translated for the container. Example: {"/home/user/agent-workspaces": "/agent-workspaces"}
func WithPermissionHandler ¶
func WithPermissionHandler(handler PermissionHandler) Option
func WithPermissions ¶
func WithPermissions(perm *PermissionConfig) Option
func WithSmallModel ¶
func WithWorkingDir ¶
type ParameterCheck ¶
type ParameterCheck struct {
// Required maps tool names to their required parameter keys.
Required map[string][]string
// Forbidden maps tool names to parameters that must not be present.
Forbidden map[string][]string
}
ParameterCheck validates tool parameters against required fields.
func NewParameterCheck ¶
func NewParameterCheck() *ParameterCheck
func (*ParameterCheck) Forbid ¶
func (p *ParameterCheck) Forbid(tool string, params ...string) *ParameterCheck
func (*ParameterCheck) Require ¶
func (p *ParameterCheck) Require(tool string, params ...string) *ParameterCheck
type PermissionBuilder ¶
type PermissionBuilder struct {
// contains filtered or unexported fields
}
func NewPermissions ¶
func NewPermissions() *PermissionBuilder
func (*PermissionBuilder) AllowBash ¶
func (b *PermissionBuilder) AllowBash(patterns ...string) *PermissionBuilder
func (*PermissionBuilder) AllowEdit ¶
func (b *PermissionBuilder) AllowEdit() *PermissionBuilder
func (*PermissionBuilder) AllowWebfetch ¶
func (b *PermissionBuilder) AllowWebfetch() *PermissionBuilder
func (*PermissionBuilder) AskBash ¶
func (b *PermissionBuilder) AskBash(patterns ...string) *PermissionBuilder
func (*PermissionBuilder) AskEdit ¶
func (b *PermissionBuilder) AskEdit() *PermissionBuilder
func (*PermissionBuilder) AskWebfetch ¶
func (b *PermissionBuilder) AskWebfetch() *PermissionBuilder
func (*PermissionBuilder) Build ¶
func (b *PermissionBuilder) Build() *PermissionConfig
func (*PermissionBuilder) DenyBash ¶
func (b *PermissionBuilder) DenyBash(patterns ...string) *PermissionBuilder
func (*PermissionBuilder) DenyEdit ¶
func (b *PermissionBuilder) DenyEdit() *PermissionBuilder
func (*PermissionBuilder) DenyWebfetch ¶
func (b *PermissionBuilder) DenyWebfetch() *PermissionBuilder
type PermissionCheck ¶
type PermissionCheck struct {
// Allowed is a set of tool names that are permitted.
Allowed map[string]bool
// Denied is a set of tool names that are explicitly blocked.
Denied map[string]bool
}
PermissionCheck validates tool execution based on a permission map.
func NewPermissionCheck ¶
func NewPermissionCheck() *PermissionCheck
func (*PermissionCheck) Allow ¶
func (p *PermissionCheck) Allow(tools ...string) *PermissionCheck
func (*PermissionCheck) Deny ¶
func (p *PermissionCheck) Deny(tools ...string) *PermissionCheck
type PermissionConfig ¶
type PermissionConfig struct {
Bash PermissionLevel `json:"bash"`
BashMap map[string]PermissionLevel `json:"bashMap,omitempty"`
Edit PermissionLevel `json:"edit"`
Webfetch PermissionLevel `json:"webfetch"`
}
type PermissionHandler ¶
type PermissionHandler func(ctx context.Context, req *PermissionRequest) (*PermissionResponse, error)
func AllowAllPermissionHandler ¶
func AllowAllPermissionHandler() PermissionHandler
func DefaultPermissionHandler ¶
func DefaultPermissionHandler() PermissionHandler
func DenyAllPermissionHandler ¶
func DenyAllPermissionHandler() PermissionHandler
type PermissionLevel ¶
type PermissionLevel string
const ( PermissionAsk PermissionLevel = "ask" PermissionAllow PermissionLevel = "allow" PermissionDeny PermissionLevel = "deny" )
type PermissionRequest ¶
type PermissionRequest struct {
ID string
Session string
Type PermissionType
Details map[string]interface{}
}
type PermissionResponse ¶
type PermissionType ¶
type PermissionType string
const ( PermissionTypeBash PermissionType = "bash" PermissionTypeEdit PermissionType = "edit" PermissionTypeWebfetch PermissionType = "webfetch" )
type PromptBuilder ¶
type PromptBuilder struct {
// contains filtered or unexported fields
}
func NewPromptBuilder ¶
func NewPromptBuilder() *PromptBuilder
func (*PromptBuilder) AddAgentRef ¶
func (b *PromptBuilder) AddAgentRef(name string) *PromptBuilder
func (*PromptBuilder) AddFile ¶
func (b *PromptBuilder) AddFile(path string) *PromptBuilder
func (*PromptBuilder) AddFileFromContent ¶
func (b *PromptBuilder) AddFileFromContent(path string, content []byte, mime string) *PromptBuilder
func (*PromptBuilder) AddSymbol ¶
func (b *PromptBuilder) AddSymbol(path string, name string, kind int) *PromptBuilder
func (*PromptBuilder) AddText ¶
func (b *PromptBuilder) AddText(content string) *PromptBuilder
func (*PromptBuilder) Build ¶
func (b *PromptBuilder) Build(opts ...PromptOption) *PromptConfig
type PromptConfig ¶
type PromptOption ¶
type PromptOption func(*PromptConfig)
func WithAgent ¶
func WithAgent(name string) PromptOption
func WithContext ¶
func WithContext(ctx string) PromptOption
func WithFiles ¶
func WithFiles(paths ...string) PromptOption
func WithParts ¶
func WithParts(parts ...PromptPart) PromptOption
func WithPromptModel ¶
func WithPromptModel(model string) PromptOption
func WithSystemPrompt ¶
func WithSystemPrompt(prompt string) PromptOption
func WithTemperature ¶
func WithTemperature(temp float64) PromptOption
type PromptPart ¶
type PromptPart interface {
ToInput() (opencode.SessionPromptParamsPartUnion, error)
}
func AgentRef ¶
func AgentRef(name string) PromptPart
func File ¶
func File(path string) PromptPart
func FileFromContent ¶
func FileFromContent(path string, content []byte, mime string) PromptPart
func FileWithWorkingDir ¶
func FileWithWorkingDir(path string, workingDir string) PromptPart
func SymbolFromContent ¶
func SymbolFromContent(path string, name string, kind int, content []byte) PromptPart
func SymbolWithWorkingDir ¶
func SymbolWithWorkingDir(path string, name string, kind int, workingDir string) PromptPart
func Text ¶
func Text(content string) PromptPart
type RateLimitCheck ¶
type RateLimitCheck struct {
// contains filtered or unexported fields
}
RateLimitCheck enforces rate limits on tool execution.
func NewRateLimitCheck ¶
func NewRateLimitCheck() *RateLimitCheck
func (*RateLimitCheck) Reset ¶
func (r *RateLimitCheck) Reset(tool string)
func (*RateLimitCheck) SetLimit ¶
func (r *RateLimitCheck) SetLimit(tool string, maxPerSession int) *RateLimitCheck
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry manages available tools for an agent. It provides lookup, validation, and execution capabilities.
func NewRegistryWithTools ¶
NewRegistryWithTools creates a registry pre-populated with tools.
func (*Registry) Definitions ¶
Definitions returns tool definitions in the format expected by LLMs. This returns a slice format suitable for most LLM APIs.
func (*Registry) Execute ¶
Execute runs a tool by name with the given parameters. Returns ErrToolNotFound if the tool doesn't exist, or ErrToolExecution if execution fails.
func (*Registry) Get ¶
Get retrieves a tool by name. Returns ErrToolNotFound if the tool doesn't exist.
func (*Registry) GetSchemaMap ¶
GetSchemaMap returns tool schemas as a map keyed by tool name. This format is useful for parallel tool-calling protocols and supports complex tool orchestration workflows.
Example:
schemas := registry.GetSchemaMap() searchSchema := schemas["search"] // Use schema for validation or introspection
func (*Registry) MustRegisterTool ¶
MustRegisterTool registers a tool and panics on error. Use for static initialization of tools.
func (*Registry) Register ¶
Register adds a tool to the registry. Returns an error if a tool with the same name already exists.
func (*Registry) Unregister ¶
Unregister removes a tool from the registry.
type ReviewHandler ¶
type ReviewResult ¶
type RiskAssessor ¶
type RiskAssessor interface {
// AssessRisk returns the risk level for a tool execution.
AssessRisk(ctx context.Context, toolName string, params map[string]any) RiskLevel
}
RiskAssessor evaluates the risk level of tool executions.
type Session ¶
type Session struct {
ID string
Title string
Directory string
ProjectID string
Created float64
Updated float64
// contains filtered or unexported fields
}
func (*Session) PromptStream ¶
type SessionConfig ¶
type SessionOption ¶
type SessionOption func(*SessionConfig)
func WithDirectory ¶
func WithDirectory(dir string) SessionOption
func WithParentID ¶
func WithParentID(parentID string) SessionOption
func WithProjectID ¶
func WithProjectID(projectID string) SessionOption
func WithTitle ¶
func WithTitle(title string) SessionOption
type StreamResult ¶
type StreamResult struct {
// State indicates the current loop state.
State LoopState
// Text is the partial text content from the LLM.
Text string
// ToolCall is a tool call being executed.
ToolCall *ToolCallRecord
// Error is any error that occurred.
Error error
// Done indicates if the loop has completed.
Done bool
}
StreamResult represents a partial result during streaming execution.
type SymbolPart ¶
type SymbolPart struct {
// contains filtered or unexported fields
}
func (*SymbolPart) ToInput ¶
func (p *SymbolPart) ToInput() (opencode.SessionPromptParamsPartUnion, error)
type Task ¶
type Task struct {
// ID is a unique identifier for the task.
ID string
// Description is the human-readable task description.
Description string
// Context provides additional context for the task.
Context string
// Priority indicates task priority (higher = more important).
Priority int
}
Task represents a unit of work for the agent.
type TextPartData ¶
type TextPartData struct {
Text string
}
type TokenUsage ¶
type Tool ¶
type Tool interface {
// Name returns the tool's unique identifier.
Name() string
// Description returns a human-readable description of what the tool does.
Description() string
// ParametersSchema returns a JSON Schema describing the tool's parameters.
ParametersSchema() map[string]any
// Execute runs the tool with the given parameters.
// The params map contains the arguments parsed from the LLM's tool call.
Execute(ctx context.Context, params map[string]any) (any, error)
}
Tool defines the interface for agent tools. Tools are functions that an agent can call during execution.
func NewToolFromFunc ¶
NewToolFromFunc creates a Tool from a function using reflection. The function must have a signature like: func(ctx context.Context, params T) (R, error) where T is a struct with JSON tags and R is the return type.
Example:
tool, err := NewToolFromFunc(
"search",
"Search for documents matching a query",
func(ctx context.Context, params SearchParams) (SearchResult, error) {
// implementation
},
)
type ToolCallRecord ¶
type ToolCallRecord struct {
// Name is the tool that was called.
Name string
// Params are the parameters passed to the tool.
Params map[string]any
// Result is the tool's return value.
Result any
// Error is any error that occurred during execution.
Error error
}
ToolCallRecord records a single tool execution.
type ToolFunc ¶
type ToolFunc struct {
// contains filtered or unexported fields
}
ToolFunc is an adapter to use a function as a Tool.
func (*ToolFunc) Description ¶
func (*ToolFunc) ParametersSchema ¶
type VerifierResult ¶
type VerifierResult struct {
// Verified indicates if the action achieved its intended goal.
Verified bool
// Reason explains why verification failed (if not verified).
Reason string
// Correction proposes a fix for failed actions.
Correction string
// Screenshot hints for UI (optional).
ScreenshotHint string
}
VerifierResult represents the outcome of action verification.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
basic
command
Example demonstrates basic usage of the agent package with MCP servers
|
Example demonstrates basic usage of the agent package with MCP servers |
|
feedback-loop
command
|
|
|
mcp-feedback
command
|