orchestrator

package
v0.5.4 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2026 License: MIT Imports: 56 Imported by: 0

Documentation

Overview

Package ratchetplugin is a workflow EnginePlugin that provides ratchet-specific module types, pipeline steps, and wiring hooks.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DeleteVaultConfig

func DeleteVaultConfig(dir string) error

DeleteVaultConfig removes the vault config file.

func EstimateTokens

func EstimateTokens(messages []provider.Message) int

EstimateTokens estimates the number of tokens in a message slice. Uses a rough heuristic of 4 characters per token (standard for English text).

func SaveVaultConfig

func SaveVaultConfig(dir string, cfg *VaultConfigFile) error

SaveVaultConfig writes vault config to dir/vault-config.json. The token is encrypted at rest using AES-256-GCM with a machine-local key.

func TeamIDFromContext

func TeamIDFromContext(ctx context.Context) string

TeamIDFromContext returns the team ID from context, if set.

func WithTeamID

func WithTeamID(ctx context.Context, teamID string) context.Context

WithTeamID returns a context with the team ID set for policy enforcement.

Types

type AIProviderModule

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

AIProviderModule wraps an AI provider.Provider as a modular.Module. It registers itself in the service registry so steps can look it up by name.

func (*AIProviderModule) Agents

func (m *AIProviderModule) Agents() []AgentSeed

Agents returns the agent seeds configured for this provider module.

func (*AIProviderModule) Init

Init registers this module as a named service. Returns an error if the module was constructed with an invalid provider type.

func (*AIProviderModule) Name

func (m *AIProviderModule) Name() string

Name implements modular.Module.

func (*AIProviderModule) Provider

func (m *AIProviderModule) Provider() provider.Provider

Provider returns the underlying AI provider.

func (*AIProviderModule) ProvidesServices

func (m *AIProviderModule) ProvidesServices() []modular.ServiceProvider

ProvidesServices declares the provider service.

func (*AIProviderModule) RequiresServices

func (m *AIProviderModule) RequiresServices() []modular.ServiceDependency

RequiresServices declares no dependencies.

func (*AIProviderModule) Start

func (m *AIProviderModule) Start(_ context.Context) error

Start implements modular.Startable (no-op).

func (*AIProviderModule) Stop

Stop implements modular.Stoppable (no-op).

func (*AIProviderModule) TestHTTPSource

func (m *AIProviderModule) TestHTTPSource() *HTTPSource

TestHTTPSource returns the HTTPSource if the provider is a test provider in HTTP mode.

type AgentExecuteStep

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

AgentExecuteStep runs the autonomous agent loop for a single task.

func (*AgentExecuteStep) Execute

func (*AgentExecuteStep) Name

func (s *AgentExecuteStep) Name() string

type AgentPermissionCheck

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

AgentPermissionCheck flags agents that have unrestricted tool access.

func (*AgentPermissionCheck) Name

func (c *AgentPermissionCheck) Name() string

func (*AgentPermissionCheck) Run

type AgentSeed

type AgentSeed struct {
	ID           string `yaml:"id"`
	Name         string `yaml:"name"`
	Role         string `yaml:"role"`
	SystemPrompt string `yaml:"system_prompt"`
	Provider     string `yaml:"provider"`
	Model        string `yaml:"model"`
	TeamID       string `yaml:"team_id"`
	IsLead       bool   `yaml:"is_lead"`
}

AgentSeed holds the definition of an agent to seed into the database.

type Approval

type Approval struct {
	ID              string
	AgentID         string
	TaskID          string
	Action          string
	Reason          string
	Details         string
	Status          ApprovalStatus
	ReviewerComment string
	CreatedAt       time.Time
	ResolvedAt      *time.Time
	TimeoutMinutes  int
}

Approval represents a human approval request.

type ApprovalManager

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

ApprovalManager manages approval records in the database and pushes SSE notifications.

func NewApprovalManager

func NewApprovalManager(db *sql.DB) *ApprovalManager

NewApprovalManager creates a new ApprovalManager with default 30-minute timeout.

func (*ApprovalManager) Approve

func (am *ApprovalManager) Approve(ctx context.Context, id string, comment string) error

Approve marks an approval as approved and records the reviewer's comment.

func (*ApprovalManager) CheckTimeout

func (am *ApprovalManager) CheckTimeout(ctx context.Context) error

CheckTimeout marks any pending approvals that have exceeded their timeout.

func (*ApprovalManager) Create

func (am *ApprovalManager) Create(ctx context.Context, approval Approval) error

Create inserts a new approval record and optionally pushes an SSE event.

func (*ApprovalManager) CreateApproval

func (am *ApprovalManager) CreateApproval(ctx context.Context, agentID, taskID, action, reason, details string) (string, error)

CreateApproval is a convenience method that satisfies the tools.ApprovalCreator interface. It creates an Approval via Create() and returns the generated ID.

func (*ApprovalManager) Get

func (am *ApprovalManager) Get(ctx context.Context, id string) (*Approval, error)

Get retrieves an approval by ID.

func (*ApprovalManager) ListPending

func (am *ApprovalManager) ListPending(ctx context.Context) ([]Approval, error)

ListPending returns all approvals with status 'pending'.

func (*ApprovalManager) Reject

func (am *ApprovalManager) Reject(ctx context.Context, id string, comment string) error

Reject marks an approval as rejected and records the reviewer's comment.

func (*ApprovalManager) SetSSEHub

func (am *ApprovalManager) SetSSEHub(hub *SSEHub)

SetSSEHub wires the SSE hub for push notifications.

func (*ApprovalManager) WaitForResolution

func (am *ApprovalManager) WaitForResolution(ctx context.Context, id string, timeout time.Duration) (*Approval, error)

WaitForResolution polls the database every 2 seconds until the approval is resolved or the given timeout elapses. Returns the resolved approval or an error.

type ApprovalResolveStep

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

ApprovalResolveStep handles POST /api/approvals/:id/approve and /api/approvals/:id/reject.

func (*ApprovalResolveStep) Execute

func (*ApprovalResolveStep) Name

func (s *ApprovalResolveStep) Name() string

type ApprovalStatus

type ApprovalStatus string

ApprovalStatus represents the resolution state of an approval.

const (
	ApprovalPending  ApprovalStatus = "pending"
	ApprovalApproved ApprovalStatus = "approved"
	ApprovalRejected ApprovalStatus = "rejected"
	ApprovalTimeout  ApprovalStatus = "timeout"
)

type AuditCheck

type AuditCheck interface {
	Name() string
	Run(ctx context.Context) []AuditFinding
}

AuditCheck is implemented by each individual security check.

type AuditFinding

type AuditFinding struct {
	Check       string
	Severity    AuditSeverity
	Title       string
	Description string
	Remediation string
}

AuditFinding represents a single security finding.

type AuditReport

type AuditReport struct {
	Timestamp time.Time
	Findings  []AuditFinding
	Summary   map[AuditSeverity]int // count by severity
	Score     int                   // 0-100, higher is better
}

AuditReport contains all findings from a security audit run.

type AuditSeverity

type AuditSeverity string

AuditSeverity represents the severity of an audit finding.

const (
	SeverityCritical AuditSeverity = "critical"
	SeverityHigh     AuditSeverity = "high"
	SeverityMedium   AuditSeverity = "medium"
	SeverityLow      AuditSeverity = "low"
	SeverityInfo     AuditSeverity = "info"
)

type AuthCheck

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

AuthCheck verifies that authentication is properly configured.

func (*AuthCheck) Name

func (c *AuthCheck) Name() string

func (*AuthCheck) Run

func (c *AuthCheck) Run(_ context.Context) []AuditFinding

type BcryptCheckStep

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

BcryptCheckStep compares a password against a bcrypt hash. Reads "password" and "password_hash" from pc.Current. Returns {match: true/false}.

func (*BcryptCheckStep) Execute

func (*BcryptCheckStep) Name

func (s *BcryptCheckStep) Name() string

type BcryptHashStep

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

BcryptHashStep hashes a password with bcrypt. Reads "password" from pc.Current. Returns {hash: "$2a$..."}.

func (*BcryptHashStep) Execute

func (*BcryptHashStep) Name

func (s *BcryptHashStep) Name() string

type BrowserManager

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

BrowserManager manages a shared Rod browser instance and per-agent pages. The browser is lazily initialized on first use to avoid consuming resources unless browser tools are actually invoked.

func NewBrowserManager

func NewBrowserManager(headless bool) *BrowserManager

NewBrowserManager creates a BrowserManager. The browser is not started until GetPage is first called.

func (*BrowserManager) GetPage

func (bm *BrowserManager) GetPage(agentID string) (*rod.Page, error)

GetPage returns the page associated with agentID, creating one if needed. If the browser has not been started yet, it is started now.

func (*BrowserManager) IsAvailable

func (bm *BrowserManager) IsAvailable() bool

IsAvailable checks whether a Chrome/Chromium binary is accessible.

func (*BrowserManager) ReleasePage

func (bm *BrowserManager) ReleasePage(agentID string)

ReleasePage closes the page associated with agentID and removes it from the map.

func (*BrowserManager) Shutdown

func (bm *BrowserManager) Shutdown() error

Shutdown closes all agent pages and then the browser itself.

type CORSCheck

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

CORSCheck flags wildcard CORS configurations.

func (*CORSCheck) Name

func (c *CORSCheck) Name() string

func (*CORSCheck) Run

func (c *CORSCheck) Run(_ context.Context) []AuditFinding

type ChannelSource

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

ChannelSource delivers interactions via Go channels, enabling test goroutines to drive the agent loop interactively from within a Go test.

func NewChannelSource

func NewChannelSource() (source *ChannelSource, interactionsCh <-chan Interaction, responsesCh chan<- InteractionResponse)

NewChannelSource creates a ChannelSource and returns the source along with the test-side channels:

  • interactionsCh receives Interactions from the provider (test reads from this)
  • responsesCh accepts InteractionResponses from the test (test writes to this)

func (*ChannelSource) GetResponse

func (cs *ChannelSource) GetResponse(ctx context.Context, interaction Interaction) (*InteractionResponse, error)

GetResponse implements ResponseSource. It sends the interaction on the interactions channel and blocks until a response arrives on the responses channel or the context is cancelled.

type ContainerControlStep

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

ContainerControlStep manages container lifecycle as a pipeline step. Actions: "start", "stop", "remove", "status".

func (*ContainerControlStep) Execute

func (*ContainerControlStep) Name

func (s *ContainerControlStep) Name() string

type ContainerManager

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

ContainerManager manages Docker containers for project workspaces. It maintains a cache of projectID -> containerID mappings and persists state to the workspace_containers table.

func NewContainerManager

func NewContainerManager(db *sql.DB) *ContainerManager

NewContainerManager creates a ContainerManager. It attempts to connect to the Docker daemon; if unavailable, the manager is marked as not available and all operations gracefully fall back.

func (*ContainerManager) Close

func (cm *ContainerManager) Close() error

Close stops all managed containers and closes the Docker client.

func (*ContainerManager) EnsureContainer

func (cm *ContainerManager) EnsureContainer(ctx context.Context, projectID, workspacePath string, spec WorkspaceSpec) (string, error)

EnsureContainer creates or reuses a container for the given project. The workspace path is bind-mounted at /workspace inside the container.

func (*ContainerManager) ExecInContainer

func (cm *ContainerManager) ExecInContainer(ctx context.Context, projectID, command, workDir string, timeout int) (stdout, stderr string, exitCode int, err error)

ExecInContainer executes a command inside the container for the given project.

func (*ContainerManager) GetContainerStatus

func (cm *ContainerManager) GetContainerStatus(ctx context.Context, projectID string) (string, error)

GetContainerStatus returns the status of the container for a project.

func (*ContainerManager) IsAvailable

func (cm *ContainerManager) IsAvailable() bool

IsAvailable returns true if the Docker daemon is reachable.

func (*ContainerManager) RemoveContainer

func (cm *ContainerManager) RemoveContainer(ctx context.Context, projectID string) error

RemoveContainer stops and removes the container for a project.

func (*ContainerManager) StopContainer

func (cm *ContainerManager) StopContainer(ctx context.Context, projectID string) error

StopContainer stops the container for a project.

type ContainerSecurityCheck

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

ContainerSecurityCheck inspects container configurations for security issues.

func (*ContainerSecurityCheck) Name

func (c *ContainerSecurityCheck) Name() string

func (*ContainerSecurityCheck) Run

type ContextManager

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

ContextManager tracks token usage across a message array and compacts the conversation when it approaches the model's context limit.

func NewContextManager

func NewContextManager(providerName string, compactionThreshold float64) *ContextManager

NewContextManager creates a ContextManager for the given provider. The model name is used to look up the context window size. compactionThreshold sets the fraction of the context limit that triggers compaction; pass 0 to use the default (0.80).

func (*ContextManager) Compact

func (cm *ContextManager) Compact(
	ctx context.Context,
	messages []provider.Message,
	aiProvider provider.Provider,
) []provider.Message

Compact compresses the conversation history by:

  1. Keeping the system message (index 0) and the most recent 2 exchanges.
  2. Summarising the middle portion using the LLM provider.
  3. Injecting the summary as a system-level context note.

If summarisation fails, the middle messages are replaced with a placeholder rather than aborting. Returns the compacted message slice.

func (*ContextManager) Compactions

func (cm *ContextManager) Compactions() int

Compactions returns how many times compaction has been applied.

func (*ContextManager) ContextLimitTokens

func (cm *ContextManager) ContextLimitTokens() int

ContextLimitTokens returns the model's context window size in tokens.

func (*ContextManager) NeedsCompaction

func (cm *ContextManager) NeedsCompaction(messages []provider.Message) bool

NeedsCompaction returns true if the estimated token count exceeds the threshold.

func (*ContextManager) SetModelLimit

func (cm *ContextManager) SetModelLimit(model string, limit int)

SetModelLimit overrides the context token limit for a specific model name pattern. This allows module config to adjust limits without modifying the built-in defaults.

func (*ContextManager) TokenUsage

func (cm *ContextManager) TokenUsage(messages []provider.Message) (estimated, limit int)

TokenUsage returns the current estimated tokens and the context limit.

type DatabaseSecurityCheck

type DatabaseSecurityCheck struct{}

DatabaseSecurityCheck checks the SQLite database file permissions.

func (*DatabaseSecurityCheck) Name

func (c *DatabaseSecurityCheck) Name() string

func (*DatabaseSecurityCheck) Run

type DefaultCredentialCheck

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

DefaultCredentialCheck looks for known default or weak credentials.

func (*DefaultCredentialCheck) Name

func (c *DefaultCredentialCheck) Name() string

func (*DefaultCredentialCheck) Run

type HTTPSource

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

HTTPSource exposes pending interactions via an API so that humans or QA scripts can act as the LLM. When the agent calls Chat(), the interaction is stored as pending and an SSE event is broadcast. A subsequent API call provides the response, unblocking the waiting goroutine.

func NewHTTPSource

func NewHTTPSource(hub *SSEHub) *HTTPSource

NewHTTPSource creates an HTTPSource. The optional SSEHub is used to push notifications when new interactions arrive.

func (*HTTPSource) GetInteraction

func (h *HTTPSource) GetInteraction(id string) (*Interaction, error)

GetInteraction returns the full interaction details for a given ID.

func (*HTTPSource) GetResponse

func (h *HTTPSource) GetResponse(ctx context.Context, interaction Interaction) (*InteractionResponse, error)

GetResponse implements ResponseSource. It adds the interaction to the pending map, broadcasts an SSE event, and blocks until a response is submitted via Respond() or the context is cancelled.

func (*HTTPSource) ListPending

func (h *HTTPSource) ListPending() []InteractionSummary

ListPending returns summaries of all pending interactions.

func (*HTTPSource) PendingCount

func (h *HTTPSource) PendingCount() int

PendingCount returns the number of interactions awaiting responses.

func (*HTTPSource) Respond

func (h *HTTPSource) Respond(id string, resp InteractionResponse) error

Respond submits a response for a pending interaction, unblocking the waiting GetResponse() call.

func (*HTTPSource) SetSSEHub

func (h *HTTPSource) SetSSEHub(hub *SSEHub)

SetSSEHub sets or replaces the SSE hub for push notifications.

type HumanRequest

type HumanRequest struct {
	ID              string
	AgentID         string
	TaskID          string
	ProjectID       string
	RequestType     RequestType
	Title           string
	Description     string
	Urgency         string // "low", "normal", "high", "critical"
	Status          RequestStatus
	ResponseData    string // JSON: the human's answer
	ResponseComment string
	ResolvedBy      string
	TimeoutMinutes  int
	Metadata        string // JSON: extra context hints
	CreatedAt       time.Time
	ResolvedAt      *time.Time
}

HumanRequest represents an agent's request for human assistance.

type HumanRequestManager

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

HumanRequestManager manages human request records in the database and pushes SSE notifications.

func NewHumanRequestManager

func NewHumanRequestManager(db *sql.DB) *HumanRequestManager

NewHumanRequestManager creates a new HumanRequestManager.

func (*HumanRequestManager) Cancel

func (m *HumanRequestManager) Cancel(ctx context.Context, id, comment string) error

Cancel marks a human request as cancelled.

func (*HumanRequestManager) CheckExpired

func (m *HumanRequestManager) CheckExpired(ctx context.Context) error

CheckExpired marks any pending requests that have exceeded their timeout (timeout_minutes > 0).

func (*HumanRequestManager) Create

Create inserts a new human request record and pushes an SSE event.

func (*HumanRequestManager) CreateRequest

func (m *HumanRequestManager) CreateRequest(ctx context.Context, agentID, taskID, projectID, reqType, title, desc, urgency, metadata string) (string, error)

CreateRequest is a convenience method that satisfies the tools.HumanRequestCreator interface.

func (*HumanRequestManager) Get

Get retrieves a human request by ID.

func (*HumanRequestManager) GetRequest

func (m *HumanRequestManager) GetRequest(ctx context.Context, id string) (map[string]any, error)

GetRequest retrieves a human request by ID and returns it as a map[string]any. This satisfies the tools.HumanRequestChecker interface.

func (*HumanRequestManager) ListByAgent

func (m *HumanRequestManager) ListByAgent(ctx context.Context, agentID string) ([]HumanRequest, error)

ListByAgent returns all human requests for a given agent.

func (*HumanRequestManager) ListPending

func (m *HumanRequestManager) ListPending(ctx context.Context) ([]HumanRequest, error)

ListPending returns all human requests with status 'pending', ordered by urgency then creation time.

func (*HumanRequestManager) Resolve

func (m *HumanRequestManager) Resolve(ctx context.Context, id, responseData, comment, resolvedBy string) error

Resolve marks a human request as resolved with the provided response data.

func (*HumanRequestManager) SetSSEHub

func (m *HumanRequestManager) SetSSEHub(hub *SSEHub)

SetSSEHub wires the SSE hub for push notifications.

func (*HumanRequestManager) WaitForResolution

func (m *HumanRequestManager) WaitForResolution(ctx context.Context, id string, timeout time.Duration) (*HumanRequest, error)

WaitForResolution polls the database every 2 seconds until the request is resolved or the given timeout elapses. Returns the resolved request or marks it expired.

type HumanRequestResolveStep

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

HumanRequestResolveStep handles POST /api/requests/:id/resolve and /api/requests/:id/cancel.

func (*HumanRequestResolveStep) Execute

func (*HumanRequestResolveStep) Name

func (s *HumanRequestResolveStep) Name() string

type Interaction

type Interaction struct {
	ID        string             `json:"id"`
	Messages  []provider.Message `json:"messages"`
	Tools     []provider.ToolDef `json:"tools"`
	CreatedAt time.Time          `json:"created_at"`
}

Interaction represents a single LLM call that needs a response.

type InteractionResponse

type InteractionResponse struct {
	Content   string              `json:"content"`
	ToolCalls []provider.ToolCall `json:"tool_calls,omitempty"`
	Error     string              `json:"error,omitempty"`
	Usage     provider.Usage      `json:"usage,omitempty"`
}

InteractionResponse is the response supplied by a ResponseSource.

type InteractionSummary

type InteractionSummary struct {
	ID        string    `json:"id"`
	MsgCount  int       `json:"msg_count"`
	ToolCount int       `json:"tool_count"`
	CreatedAt time.Time `json:"created_at"`
}

InteractionSummary is a brief view of a pending interaction for list endpoints.

type JWTDecodeStep

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

JWTDecodeStep decodes a JWT token from the Authorization header. Tries multiple sources: HTTP request metadata, Current, trigger data. Returns decoded claims: {sub, username, role, authenticated}.

func (*JWTDecodeStep) Execute

func (*JWTDecodeStep) Name

func (s *JWTDecodeStep) Name() string

type JWTGenerateStep

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

JWTGenerateStep creates a signed JWT token. Reads "user_id", "username", "role" from pc.Current. Returns {token: "eyJ..."}.

func (*JWTGenerateStep) Execute

func (*JWTGenerateStep) Name

func (s *JWTGenerateStep) Name() string

type LLMProviderConfig

type LLMProviderConfig struct {
	ID         string `json:"id"`
	Alias      string `json:"alias"`
	Type       string `json:"type"`        // provider type (e.g. "anthropic", "openai", "copilot_models", "openai_azure", "anthropic_foundry", "anthropic_vertex", "anthropic_bedrock")
	Model      string `json:"model"`       // model identifier
	SecretName string `json:"secret_name"` // key in secrets provider for API key
	BaseURL    string `json:"base_url"`    // optional override
	MaxTokens  int    `json:"max_tokens"`  // optional override
	IsDefault  int    `json:"is_default"`  // 1 if this is the default provider
	Settings   string `json:"settings"`    // JSON object with provider-specific settings (resource, region, deployment_name, project_id, etc.)
}

LLMProviderConfig represents a configured LLM provider stored in the database.

type LoopDetector

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

LoopDetector detects agent execution loops using multiple heuristics.

func NewLoopDetector

func NewLoopDetector(cfg LoopDetectorConfig) *LoopDetector

NewLoopDetector creates a LoopDetector with the given config. Zero values in cfg are replaced with defaults (MaxConsecutive=3, MaxErrors=2, MaxAlternating=3, MaxNoProgress=3).

func (*LoopDetector) Check

func (ld *LoopDetector) Check() (LoopStatus, string)

Check evaluates the recorded history for loop patterns and returns the current status along with a human-readable explanation. Checks are evaluated in priority order: hard breaks take precedence over warnings.

func (*LoopDetector) Record

func (ld *LoopDetector) Record(toolName string, args map[string]any, result string, isError bool)

Record appends a tool invocation to the history.

func (*LoopDetector) Reset

func (ld *LoopDetector) Reset()

Reset clears recorded history.

type LoopDetectorConfig

type LoopDetectorConfig struct {
	// MaxConsecutive is the number of identical consecutive tool calls before a loop is detected.
	// Default: 3.
	MaxConsecutive int
	// MaxErrors is the number of times the same tool call can return the same error before a loop is detected.
	// Default: 2.
	MaxErrors int
	// MaxAlternating is the number of A/B alternating cycles before a loop is detected.
	// Default: 3.
	MaxAlternating int
	// MaxNoProgress is the number of identical (same args + same result) non-error calls before a loop is detected.
	// Default: 3.
	MaxNoProgress int
}

LoopDetectorConfig holds configurable thresholds for loop detection.

type LoopStatus

type LoopStatus int

LoopStatus represents the result of a loop check.

const (
	// LoopStatusOK means no loop detected.
	LoopStatusOK LoopStatus = iota
	// LoopStatusWarning means a potential loop pattern is forming.
	LoopStatusWarning
	// LoopStatusBreak means a definitive loop is detected; execution should stop.
	LoopStatusBreak
)

type MCPClientModule

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

MCPClientModule connects to external MCP servers.

func (*MCPClientModule) Init

func (*MCPClientModule) Name

func (m *MCPClientModule) Name() string

func (*MCPClientModule) ProvidesServices

func (m *MCPClientModule) ProvidesServices() []modular.ServiceProvider

func (*MCPClientModule) ReloadServers

func (m *MCPClientModule) ReloadServers(configs []mcpServerConfig) (int, []string)

ReloadServers stops all existing MCP clients and starts new ones from the given configs. Returns the count of successfully started servers and any error messages.

func (*MCPClientModule) RequiresServices

func (m *MCPClientModule) RequiresServices() []modular.ServiceDependency

func (*MCPClientModule) Start

func (m *MCPClientModule) Start(ctx context.Context) error

func (*MCPClientModule) Stop

func (m *MCPClientModule) Stop(_ context.Context) error

type MCPReloadStep

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

MCPReloadStep triggers a hot-reload of MCP server connections from the database.

func (*MCPReloadStep) Execute

func (*MCPReloadStep) Name

func (s *MCPReloadStep) Name() string

type MCPServerCheck

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

MCPServerCheck inspects MCP server configurations for risky capabilities.

func (*MCPServerCheck) Name

func (c *MCPServerCheck) Name() string

func (*MCPServerCheck) Run

type MCPServerModule

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

MCPServerModule exposes Ratchet APIs as MCP tools over HTTP/JSON-RPC.

func (*MCPServerModule) Init

func (*MCPServerModule) Name

func (m *MCPServerModule) Name() string

func (*MCPServerModule) Path

func (m *MCPServerModule) Path() string

Path returns the configured MCP endpoint path.

func (*MCPServerModule) ProvidesServices

func (m *MCPServerModule) ProvidesServices() []modular.ServiceProvider

func (*MCPServerModule) RequiresServices

func (m *MCPServerModule) RequiresServices() []modular.ServiceDependency

func (*MCPServerModule) ServeHTTP

func (m *MCPServerModule) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles MCP JSON-RPC requests over HTTP POST.

func (*MCPServerModule) Start

func (m *MCPServerModule) Start(_ context.Context) error

func (*MCPServerModule) Stop

func (m *MCPServerModule) Stop(_ context.Context) error

type MCPToolAdapter

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

MCPToolAdapter wraps an MCP tool as a ratchet plugin.Tool.

func (*MCPToolAdapter) Definition

func (t *MCPToolAdapter) Definition() provider.ToolDef

func (*MCPToolAdapter) Description

func (t *MCPToolAdapter) Description() string

func (*MCPToolAdapter) Execute

func (t *MCPToolAdapter) Execute(ctx context.Context, args map[string]any) (any, error)

func (*MCPToolAdapter) Name

func (t *MCPToolAdapter) Name() string

type MemoryEntry

type MemoryEntry struct {
	ID        string
	AgentID   string
	Content   string
	Category  string    // e.g., "decision", "fact", "preference", "general"
	Embedding []float32 // optional vector embedding
	CreatedAt time.Time
}

MemoryEntry is a single piece of persistent agent memory.

type MemoryExtractStep

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

MemoryExtractStep extracts memories from completed task transcripts and saves them.

func (*MemoryExtractStep) Execute

func (*MemoryExtractStep) Name

func (s *MemoryExtractStep) Name() string

type MemoryStore

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

MemoryStore provides persistent memory storage for agents using SQLite FTS5 and optional vector embeddings for hybrid semantic search.

func NewMemoryStore

func NewMemoryStore(db *sql.DB) *MemoryStore

NewMemoryStore creates a new MemoryStore backed by the given database.

func (*MemoryStore) ExtractAndSave

func (ms *MemoryStore) ExtractAndSave(ctx context.Context, agentID, transcript string, embedder provider.Embedder) error

ExtractAndSave extracts key facts from a conversation transcript and saves them. If an embedder is provided, embeddings are computed and stored.

func (*MemoryStore) InitTables

func (ms *MemoryStore) InitTables() error

InitTables creates the memory_entries table and FTS5 virtual table if they don't exist.

func (*MemoryStore) Save

func (ms *MemoryStore) Save(ctx context.Context, entry MemoryEntry) error

Save persists a memory entry. If entry.ID is empty, a new UUID is assigned.

func (*MemoryStore) SaveMemory

func (ms *MemoryStore) SaveMemory(ctx context.Context, agentID, content, category string) error

SaveMemory is a convenience method that satisfies tools.MemoryStoreSaver.

func (*MemoryStore) Search

func (ms *MemoryStore) Search(ctx context.Context, agentID, query string, limit int) ([]MemoryEntry, error)

Search uses FTS5 BM25 ranking to find relevant memories for an agent.

func (*MemoryStore) SearchHybrid

func (ms *MemoryStore) SearchHybrid(ctx context.Context, agentID, query string, queryEmbedding []float32, limit int) ([]MemoryEntry, error)

SearchHybrid combines 70% cosine similarity + 30% BM25 for hybrid semantic search. queryEmbedding is the embedding of the search query. Falls back to FTS-only if nil.

func (*MemoryStore) SearchMemory

func (ms *MemoryStore) SearchMemory(ctx context.Context, agentID, query string, limit int) ([]tools.MemoryEntryResult, error)

SearchMemory satisfies tools.MemoryStoreSearcher, returning lightweight result structs.

type OAuthExchangeStep

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

OAuthExchangeStep handles OAuth authorization code exchange server-side, proxying to provider OAuth endpoints to avoid CORS issues in the browser.

func (*OAuthExchangeStep) Execute

func (*OAuthExchangeStep) Name

func (s *OAuthExchangeStep) Name() string

type PolicyAction

type PolicyAction string

PolicyAction defines the action of a tool policy.

const (
	PolicyAllow PolicyAction = "allow"
	PolicyDeny  PolicyAction = "deny"
)

type PolicyScope

type PolicyScope string

PolicyScope defines the scope of a tool policy.

const (
	PolicyScopeGlobal PolicyScope = "global"
	PolicyScopeTeam   PolicyScope = "team"
	PolicyScopeAgent  PolicyScope = "agent"
)

type ProviderFactory

type ProviderFactory func(apiKey string, cfg LLMProviderConfig) (provider.Provider, error)

ProviderFactory creates a provider.Provider from an API key and config.

type ProviderModelsStep

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

ProviderModelsStep fetches available models from a provider's API. Requires provider type and API key in the request body.

func (*ProviderModelsStep) Execute

func (*ProviderModelsStep) Name

func (s *ProviderModelsStep) Name() string

type ProviderRegistry

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

ProviderRegistry manages AI provider lifecycle: factory creation, caching, and DB lookup.

func NewProviderRegistry

func NewProviderRegistry(db *sql.DB, secretsProvider secrets.Provider) *ProviderRegistry

NewProviderRegistry creates a new ProviderRegistry with built-in factories registered.

func (*ProviderRegistry) GetByAlias

func (r *ProviderRegistry) GetByAlias(ctx context.Context, alias string) (provider.Provider, error)

GetByAlias looks up a provider by its alias. It checks the cache first, then falls back to DB lookup, secret resolution, and factory creation.

func (*ProviderRegistry) GetDefault

func (r *ProviderRegistry) GetDefault(ctx context.Context) (provider.Provider, error)

GetDefault finds the default provider (is_default=1) and returns it.

func (*ProviderRegistry) InvalidateCache

func (r *ProviderRegistry) InvalidateCache()

InvalidateCache clears all cached providers.

func (*ProviderRegistry) InvalidateCacheAlias

func (r *ProviderRegistry) InvalidateCacheAlias(alias string)

InvalidateCacheAlias removes a specific cached provider by alias.

func (*ProviderRegistry) InvalidateCacheBySecret

func (r *ProviderRegistry) InvalidateCacheBySecret(secretName string)

InvalidateCacheBySecret removes all cached providers that use the given secret name.

func (*ProviderRegistry) TestConnection

func (r *ProviderRegistry) TestConnection(ctx context.Context, alias string) (bool, string, time.Duration, error)

TestConnection sends a minimal test message to the provider and returns success, a status message, the latency, and any error.

func (*ProviderRegistry) UpdateSecretsProvider

func (r *ProviderRegistry) UpdateSecretsProvider(p secrets.Provider)

UpdateSecretsProvider swaps the underlying secrets provider and clears the cache.

type ProviderSecurityCheck

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

ProviderSecurityCheck verifies AI provider API keys are stored in the vault.

func (*ProviderSecurityCheck) Name

func (c *ProviderSecurityCheck) Name() string

func (*ProviderSecurityCheck) Run

type ProviderTestStep

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

ProviderTestStep tests connectivity to a configured AI provider.

func (*ProviderTestStep) Execute

func (*ProviderTestStep) Name

func (s *ProviderTestStep) Name() string

type RatchetPlugin

type RatchetPlugin struct {
	plugin.BaseEnginePlugin
}

RatchetPlugin implements plugin.EnginePlugin.

func New

func New() *RatchetPlugin

New creates a new RatchetPlugin ready to register with the workflow engine.

func (*RatchetPlugin) Capabilities

func (p *RatchetPlugin) Capabilities() []capability.Contract

Capabilities returns the capability contracts for this plugin.

func (*RatchetPlugin) ModuleFactories

func (p *RatchetPlugin) ModuleFactories() map[string]plugin.ModuleFactory

ModuleFactories returns the module factories registered by this plugin. "agent.provider" is registered here so ratchetplugin is self-contained and does not need workflow-plugin-agent loaded as a separate engine plugin (which would cause a duplicate step.agent_execute conflict).

func (*RatchetPlugin) ModuleSchemas

func (p *RatchetPlugin) ModuleSchemas() []*schema.ModuleSchema

ModuleSchemas returns schema definitions for IDE completions and config validation.

func (*RatchetPlugin) StepFactories

func (p *RatchetPlugin) StepFactories() map[string]plugin.StepFactory

StepFactories returns the pipeline step factories registered by this plugin. step.agent_execute uses ratchet's richer implementation (browser, sub-agent, skill injection, etc.). step.provider_test and step.provider_models are delegated to the agent plugin's factories since ratchetplugin absorbs the agent plugin to avoid duplicate step registration.

func (*RatchetPlugin) WiringHooks

func (p *RatchetPlugin) WiringHooks() []plugin.WiringHook

WiringHooks returns the post-init wiring hooks for this plugin. agentplugin.ProviderRegistryHook() is included here because ratchetplugin absorbs the workflow-plugin-agent to avoid duplicate step type registration.

type RateLimitCheck

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

RateLimitCheck verifies rate limiting is properly configured.

func (*RateLimitCheck) Name

func (c *RateLimitCheck) Name() string

func (*RateLimitCheck) Run

type RequestStatus

type RequestStatus string

RequestStatus represents the resolution state of a human request.

const (
	RequestPending   RequestStatus = "pending"
	RequestResolved  RequestStatus = "resolved"
	RequestCancelled RequestStatus = "cancelled"
	RequestExpired   RequestStatus = "expired"
)

type RequestType

type RequestType string

RequestType categorizes what the agent needs from the human.

const (
	RequestTypeToken  RequestType = "token"  // API keys, PATs, secrets
	RequestTypeBinary RequestType = "binary" // Install a CLI tool or binary
	RequestTypeAccess RequestType = "access" // Grant access to a service/repo
	RequestTypeInfo   RequestType = "info"   // Clarification or instructions
	RequestTypeCustom RequestType = "custom" // Anything else
)

type ResponseSource

type ResponseSource interface {
	// GetResponse receives the current interaction (messages + tools) and returns
	// a response. Implementations may block (e.g. waiting for human input).
	GetResponse(ctx context.Context, interaction Interaction) (*InteractionResponse, error)
}

ResponseSource is the interface that pluggable backends implement to supply responses for the TestProvider.

type SSEHub

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

SSEHub is a modular.Module that manages Server-Sent Events connections. It provides an HTTP handler for SSE clients and a Broadcast method for pushing events from pipeline steps or other parts of the system.

func (*SSEHub) Broadcast

func (h *SSEHub) Broadcast(event []byte)

Broadcast sends a raw SSE payload to all connected clients.

func (*SSEHub) BroadcastEvent

func (h *SSEHub) BroadcastEvent(eventType, data string)

BroadcastEvent formats and broadcasts a named SSE event with data.

func (*SSEHub) Init

func (h *SSEHub) Init(app modular.Application) error

Init registers the hub as a named service.

func (*SSEHub) Name

func (h *SSEHub) Name() string

Name implements modular.Module.

func (*SSEHub) Path

func (h *SSEHub) Path() string

Path returns the configured SSE endpoint path.

func (*SSEHub) ProvidesServices

func (h *SSEHub) ProvidesServices() []modular.ServiceProvider

ProvidesServices declares the SSE hub service.

func (*SSEHub) RequiresServices

func (h *SSEHub) RequiresServices() []modular.ServiceDependency

RequiresServices declares no dependencies.

func (*SSEHub) ServeHTTP

func (h *SSEHub) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles an incoming SSE connection. It sets the required headers, registers the client channel, and streams events until the client disconnects or the server shuts down.

func (*SSEHub) Start

func (h *SSEHub) Start(_ context.Context) error

Start implements modular.Startable (no-op — the hub starts on first HTTP connection).

func (*SSEHub) Stop

func (h *SSEHub) Stop(_ context.Context) error

Stop implements modular.Stoppable — closes all connected clients.

type ScriptedScenario

type ScriptedScenario struct {
	Name        string         `yaml:"name" json:"name"`
	Description string         `yaml:"description,omitempty" json:"description,omitempty"`
	Steps       []ScriptedStep `yaml:"steps" json:"steps"`
	Loop        bool           `yaml:"loop,omitempty" json:"loop,omitempty"`
}

ScriptedScenario is a named sequence of steps loadable from YAML.

func LoadScenario

func LoadScenario(path string) (*ScriptedScenario, error)

LoadScenario reads a ScriptedScenario from a YAML file.

type ScriptedSource

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

ScriptedSource returns responses from a pre-defined sequence of steps. It is safe for concurrent use.

func NewScriptedSource

func NewScriptedSource(steps []ScriptedStep, loop bool) *ScriptedSource

NewScriptedSource creates a ScriptedSource from the given steps. If loop is true, steps cycle indefinitely; otherwise GetResponse returns an error when all steps are exhausted.

func NewScriptedSourceFromScenario

func NewScriptedSourceFromScenario(scenario *ScriptedScenario) *ScriptedSource

NewScriptedSourceFromScenario creates a ScriptedSource from a loaded scenario.

func (*ScriptedSource) GetResponse

func (s *ScriptedSource) GetResponse(ctx context.Context, interaction Interaction) (*InteractionResponse, error)

GetResponse implements ResponseSource.

func (*ScriptedSource) Remaining

func (s *ScriptedSource) Remaining() int

Remaining returns how many unconsumed steps remain.

type ScriptedStep

type ScriptedStep struct {
	Content   string              `yaml:"content" json:"content"`
	ToolCalls []provider.ToolCall `yaml:"tool_calls,omitempty" json:"tool_calls,omitempty"`
	Error     string              `yaml:"error,omitempty" json:"error,omitempty"`
	Delay     time.Duration       `yaml:"delay,omitempty" json:"delay,omitempty"`
}

ScriptedStep defines a single scripted response in a test scenario.

type SecretExposureCheck

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

SecretExposureCheck scans recent transcripts for potential credential leakage.

func (*SecretExposureCheck) Name

func (c *SecretExposureCheck) Name() string

func (*SecretExposureCheck) Run

type SecretGuard

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

SecretGuard scans text for known secret values and redacts them.

func NewSecretGuard

func NewSecretGuard(p secrets.Provider, backend string) *SecretGuard

func (*SecretGuard) AddKnownSecret

func (sg *SecretGuard) AddKnownSecret(name, value string)

AddKnownSecret adds a secret value to the guard's redaction list.

func (*SecretGuard) BackendName

func (sg *SecretGuard) BackendName() string

BackendName returns the name of the current backend.

func (*SecretGuard) CheckAndRedact

func (sg *SecretGuard) CheckAndRedact(msg *provider.Message) bool

CheckAndRedact redacts secret values in a message. Returns true if redaction occurred.

func (*SecretGuard) LoadAllSecrets

func (sg *SecretGuard) LoadAllSecrets(ctx context.Context) error

LoadAllSecrets loads all available secrets from the provider.

func (*SecretGuard) LoadSecrets

func (sg *SecretGuard) LoadSecrets(ctx context.Context, names []string) error

LoadSecrets loads secret values from the provider for the given keys.

func (*SecretGuard) Provider

func (sg *SecretGuard) Provider() secrets.Provider

Provider returns the underlying secrets.Provider.

func (*SecretGuard) Redact

func (sg *SecretGuard) Redact(text string) string

Redact replaces known secret values with [REDACTED:name].

func (*SecretGuard) SetProvider

func (sg *SecretGuard) SetProvider(p secrets.Provider, backend string)

SetProvider hot-swaps the secrets provider and reloads all secrets. Secrets are loaded from the new provider before swapping to avoid a window where no secrets are available for redaction.

type SecretManageStep

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

SecretManageStep manages secrets (set, delete, list) as a pipeline step.

func (*SecretManageStep) Execute

func (*SecretManageStep) Name

func (s *SecretManageStep) Name() string

type SecurityAuditStep

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

SecurityAuditStep runs a full security audit and returns the report as JSON.

func (*SecurityAuditStep) Execute

func (*SecurityAuditStep) Name

func (s *SecurityAuditStep) Name() string

type SecurityAuditor

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

SecurityAuditor orchestrates all audit checks.

func NewSecurityAuditor

func NewSecurityAuditor(db *sql.DB, app modular.Application) *SecurityAuditor

NewSecurityAuditor creates a SecurityAuditor wired with all built-in checks.

func (*SecurityAuditor) RunAll

func (sa *SecurityAuditor) RunAll(ctx context.Context) *AuditReport

RunAll executes all checks and returns an AuditReport.

type Skill

type Skill struct {
	ID            string
	Name          string
	Description   string
	Content       string   // the markdown body (injected into system prompt)
	Category      string   // e.g., "development", "analysis", "communication"
	RequiredTools []string // tools needed for this skill
	CreatedAt     time.Time
}

Skill represents a composable skill that can be assigned to agents.

type SkillManager

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

SkillManager manages skills stored in SQLite, loaded from markdown files.

func NewSkillManager

func NewSkillManager(db *sql.DB, skillDir string) *SkillManager

NewSkillManager creates a new SkillManager with the given database and skill directory.

func (*SkillManager) AssignToAgent

func (sm *SkillManager) AssignToAgent(ctx context.Context, agentID, skillID string) error

AssignToAgent assigns a skill to an agent.

func (*SkillManager) BuildSkillPrompt

func (sm *SkillManager) BuildSkillPrompt(ctx context.Context, agentID string) (string, error)

BuildSkillPrompt concatenates all assigned skill contents for an agent into a prompt section.

func (*SkillManager) GetAgentSkills

func (sm *SkillManager) GetAgentSkills(ctx context.Context, agentID string) ([]Skill, error)

GetAgentSkills returns all skills assigned to an agent.

func (*SkillManager) GetSkill

func (sm *SkillManager) GetSkill(ctx context.Context, id string) (*Skill, error)

GetSkill retrieves a skill by ID.

func (*SkillManager) InitTables

func (sm *SkillManager) InitTables() error

InitTables creates the skills and agent_skills tables.

func (*SkillManager) ListSkills

func (sm *SkillManager) ListSkills(ctx context.Context) ([]Skill, error)

ListSkills returns all skills.

func (*SkillManager) LoadFromDirectory

func (sm *SkillManager) LoadFromDirectory() error

LoadFromDirectory reads .md files from skillDir and upserts them into the DB.

func (*SkillManager) RemoveFromAgent

func (sm *SkillManager) RemoveFromAgent(ctx context.Context, agentID, skillID string) error

RemoveFromAgent removes a skill assignment from an agent.

type SubAgentManager

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

SubAgentManager manages ephemeral sub-agents spawned by parent agents. It implements the tools.SubAgentSpawner interface.

func NewSubAgentManager

func NewSubAgentManager(db *sql.DB, maxPerParent, maxDepth int) *SubAgentManager

NewSubAgentManager creates a new SubAgentManager. maxPerParent is the maximum number of concurrent sub-agents per parent (default 5 when <= 0). maxDepth is the maximum spawn depth — ephemeral agents at this depth cannot spawn further (default 1 when <= 0).

func (*SubAgentManager) CancelChildren

func (sm *SubAgentManager) CancelChildren(ctx context.Context, parentAgentID string) error

CancelChildren cancels all active sub-agent tasks for the given parent agent.

func (*SubAgentManager) CheckTask

func (sm *SubAgentManager) CheckTask(ctx context.Context, taskID string) (status string, result string, err error)

CheckTask returns the current status and result of a task.

func (*SubAgentManager) CountActive

func (sm *SubAgentManager) CountActive(ctx context.Context, parentAgentID string) (int, error)

CountActive returns the number of active (non-completed, non-failed) sub-agents for the given parent.

func (*SubAgentManager) Spawn

func (sm *SubAgentManager) Spawn(ctx context.Context, parentAgentID string, name string, taskDesc string, systemPrompt string) (taskID string, err error)

Spawn creates an ephemeral sub-agent and assigns it a task. Returns the task ID for tracking.

func (*SubAgentManager) WaitTasks

func (sm *SubAgentManager) WaitTasks(ctx context.Context, taskIDs []string, timeout time.Duration) (map[string]tools.SubTaskResult, error)

WaitTasks polls all given task IDs until they complete or timeout expires. Returns a map of taskID -> tools.SubTaskResult.

type TestInteractStep

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

TestInteractStep is a pipeline step that bridges HTTP requests to an HTTPSource. It supports three operations: list_pending, get_interaction, and respond.

func (*TestInteractStep) Execute

func (*TestInteractStep) Name

func (s *TestInteractStep) Name() string

type TestProvider

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

TestProvider implements provider.Provider by delegating to a ResponseSource. It enables interactive and scripted E2E testing of the agent execution pipeline.

func NewTestProvider

func NewTestProvider(source ResponseSource, opts ...TestProviderOption) *TestProvider

NewTestProvider creates a TestProvider backed by the given ResponseSource.

func (*TestProvider) AuthModeInfo

func (tp *TestProvider) AuthModeInfo() provider.AuthModeInfo

AuthModeInfo implements provider.Provider.

func (*TestProvider) Chat

func (tp *TestProvider) Chat(ctx context.Context, messages []provider.Message, tools []provider.ToolDef) (*provider.Response, error)

Chat implements provider.Provider.

func (*TestProvider) InteractionCount

func (tp *TestProvider) InteractionCount() int64

InteractionCount returns how many interactions have been processed.

func (*TestProvider) Name

func (tp *TestProvider) Name() string

Name implements provider.Provider.

func (*TestProvider) Source

func (tp *TestProvider) Source() ResponseSource

Source returns the underlying ResponseSource.

func (*TestProvider) Stream

func (tp *TestProvider) Stream(ctx context.Context, messages []provider.Message, tools []provider.ToolDef) (<-chan provider.StreamEvent, error)

Stream implements provider.Provider by wrapping Chat() into stream events.

type TestProviderOption

type TestProviderOption func(*TestProvider)

TestProviderOption configures a TestProvider.

func WithName

func WithName(s string) TestProviderOption

WithName sets the provider name returned by Name().

func WithTimeout

func WithTimeout(d time.Duration) TestProviderOption

WithTimeout sets the maximum time to wait for a response from the source.

type ToolPolicy

type ToolPolicy struct {
	ID          string
	Scope       PolicyScope
	ScopeID     string // empty for global, team_id for team, agent_id for agent
	ToolPattern string // tool name or "group:fs", "group:runtime", etc.
	Action      PolicyAction
	CreatedAt   time.Time
}

ToolPolicy represents a policy controlling tool access.

type ToolPolicyEngine

type ToolPolicyEngine struct {
	DefaultPolicy PolicyAction // "allow" or "deny"; defaults to "deny" (fail-closed)
	// contains filtered or unexported fields
}

ToolPolicyEngine evaluates tool access policies stored in SQLite.

func NewToolPolicyEngine

func NewToolPolicyEngine(db *sql.DB) *ToolPolicyEngine

NewToolPolicyEngine creates a new ToolPolicyEngine backed by the given DB. The default policy is "deny" (fail-closed) when no matching policies exist.

func (*ToolPolicyEngine) AddPolicy

func (tpe *ToolPolicyEngine) AddPolicy(ctx context.Context, policy ToolPolicy) error

AddPolicy inserts a new policy into the database.

func (*ToolPolicyEngine) InitTable

func (tpe *ToolPolicyEngine) InitTable() error

InitTable creates the tool_policies table if it does not already exist.

func (*ToolPolicyEngine) IsAllowed

func (tpe *ToolPolicyEngine) IsAllowed(ctx context.Context, toolName string, agentID string, teamID string) (bool, string)

IsAllowed checks whether the given tool is permitted for the given agent and team.

Resolution order (most specific wins for allow; deny-wins across all matching):

  1. Expand group patterns to concrete tool names.
  2. Collect all policies that match the tool name (global, team, agent).
  3. If ANY matching policy denies → return false.
  4. If no explicit policy exists → apply DefaultPolicy ("deny" by default, fail-closed).

func (*ToolPolicyEngine) ListPolicies

func (tpe *ToolPolicyEngine) ListPolicies(ctx context.Context) ([]ToolPolicy, error)

ListPolicies returns all policies ordered by scope specificity.

func (*ToolPolicyEngine) RemovePolicy

func (tpe *ToolPolicyEngine) RemovePolicy(ctx context.Context, id string) error

RemovePolicy deletes a policy by ID.

type ToolRegistry

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

ToolRegistry merges built-in tools and MCP tools into a unified registry.

func NewToolRegistry

func NewToolRegistry() *ToolRegistry

func (*ToolRegistry) AllDefs

func (tr *ToolRegistry) AllDefs() []provider.ToolDef

AllDefs returns tool definitions for all registered tools.

func (*ToolRegistry) Execute

func (tr *ToolRegistry) Execute(ctx context.Context, name string, args map[string]any) (any, error)

Execute runs a tool by name with the given arguments. If a policy engine is set, access control is checked before execution.

func (*ToolRegistry) Get

func (tr *ToolRegistry) Get(name string) (plugin.Tool, bool)

Get returns a tool by name.

func (*ToolRegistry) Names

func (tr *ToolRegistry) Names() []string

Names returns all registered tool names.

func (*ToolRegistry) Register

func (tr *ToolRegistry) Register(tool plugin.Tool)

Register adds a tool to the registry.

func (*ToolRegistry) RegisterMCP

func (tr *ToolRegistry) RegisterMCP(serverName string, tools []plugin.Tool)

RegisterMCP registers MCP tools with a server-prefixed name.

func (*ToolRegistry) SetPolicyEngine

func (tr *ToolRegistry) SetPolicyEngine(engine *ToolPolicyEngine)

SetPolicyEngine attaches a ToolPolicyEngine for access control enforcement.

func (*ToolRegistry) UnregisterMCP

func (tr *ToolRegistry) UnregisterMCP(serverName string)

UnregisterMCP removes all tools registered under the given MCP server name.

type TranscriptEntry

type TranscriptEntry struct {
	ID         string              `json:"id"`
	AgentID    string              `json:"agent_id"`
	TaskID     string              `json:"task_id"`
	ProjectID  string              `json:"project_id"`
	Iteration  int                 `json:"iteration"`
	Role       provider.Role       `json:"role"`
	Content    string              `json:"content"`
	ToolCalls  []provider.ToolCall `json:"tool_calls"`
	ToolCallID string              `json:"tool_call_id"`
	Redacted   bool                `json:"redacted"`
	CreatedAt  string              `json:"created_at"`
}

TranscriptEntry represents one entry in the transcript log.

type TranscriptRecorder

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

TranscriptRecorder records agent interactions to the database.

func NewTranscriptRecorder

func NewTranscriptRecorder(db *sql.DB, guard *SecretGuard) *TranscriptRecorder

func (*TranscriptRecorder) GetByAgent

func (tr *TranscriptRecorder) GetByAgent(ctx context.Context, agentID string) ([]TranscriptEntry, error)

GetByAgent returns all transcript entries for a given agent.

func (*TranscriptRecorder) GetByTask

func (tr *TranscriptRecorder) GetByTask(ctx context.Context, taskID string) ([]TranscriptEntry, error)

GetByTask returns all transcript entries for a given task.

func (*TranscriptRecorder) Record

func (tr *TranscriptRecorder) Record(ctx context.Context, entry TranscriptEntry) error

Record saves a transcript entry to the database.

type VaultCheck

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

VaultCheck flags when vault-dev is used in a production environment.

func (*VaultCheck) Name

func (c *VaultCheck) Name() string

func (*VaultCheck) Run

func (c *VaultCheck) Run(_ context.Context) []AuditFinding

type VaultConfigFile

type VaultConfigFile struct {
	Backend   string `json:"backend"`              // "vault-dev" or "vault-remote"
	Address   string `json:"address,omitempty"`    // remote vault address
	Token     string `json:"token,omitempty"`      // encrypted remote vault token
	MountPath string `json:"mount_path,omitempty"` // KV v2 mount path
	Namespace string `json:"namespace,omitempty"`  // vault namespace
}

VaultConfigFile stores persistent vault backend configuration. Saved as JSON to data/vault-config.json so it's available before DB init. The token field is encrypted at rest using AES-256-GCM.

func LoadVaultConfig

func LoadVaultConfig(dir string) (*VaultConfigFile, error)

LoadVaultConfig reads vault config from dir/vault-config.json. Returns nil (not error) if the file doesn't exist. Tokens are decrypted transparently.

type VaultConfigStep

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

VaultConfigStep manages vault backend configuration as a pipeline step. Actions: get_status, test, configure, migrate, reset

func (*VaultConfigStep) Execute

func (*VaultConfigStep) Name

func (s *VaultConfigStep) Name() string

type Webhook

type Webhook struct {
	ID           string
	Source       string // "github", "slack", "generic"
	Name         string
	SecretName   string // name of secret in vault for HMAC verification
	Filter       string // event filter e.g. "issues.opened", "push"
	TaskTemplate string // Go template for task title/description
	Enabled      bool
	CreatedAt    time.Time
}

Webhook represents a configured inbound webhook endpoint.

type WebhookManager

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

WebhookManager manages webhook configurations and processing logic.

func NewWebhookManager

func NewWebhookManager(db *sql.DB, guard *SecretGuard) *WebhookManager

NewWebhookManager creates a new WebhookManager.

func (*WebhookManager) Create

func (wm *WebhookManager) Create(ctx context.Context, wh Webhook) error

Create inserts a new webhook into the database.

func (*WebhookManager) Delete

func (wm *WebhookManager) Delete(ctx context.Context, id string) error

Delete removes a webhook by ID.

func (*WebhookManager) ExtractEventType

func (wm *WebhookManager) ExtractEventType(source string, headers map[string]string, payload map[string]any) string

ExtractEventType extracts the event type from request headers or payload.

func (*WebhookManager) GetBySource

func (wm *WebhookManager) GetBySource(ctx context.Context, source string) ([]Webhook, error)

GetBySource returns all enabled webhooks matching a source identifier.

func (*WebhookManager) List

func (wm *WebhookManager) List(ctx context.Context) ([]Webhook, error)

List returns all webhooks.

func (*WebhookManager) MatchesFilter

func (wm *WebhookManager) MatchesFilter(source string, eventType string, filter string) bool

MatchesFilter returns true if the event type matches the webhook filter. An empty filter matches everything. Filter format: "event.action" (e.g. "issues.opened", "push") or just "event" (e.g. "push").

func (*WebhookManager) RenderTaskTemplate

func (wm *WebhookManager) RenderTaskTemplate(tmpl string, payload map[string]any) (title string, description string, err error)

RenderTaskTemplate renders the Go template with the webhook payload as data. The template can use {{.title}} and {{.description}} fields or any payload fields. Returns title, description, and any rendering error.

Example template:

title: "GitHub issue: {{.payload.title}}"
description: "Opened by {{.payload.user.login}}"

func (*WebhookManager) VerifySignature

func (wm *WebhookManager) VerifySignature(source string, secret string, payload []byte, signature string, timestamp string) bool

VerifySignature verifies the HMAC signature of a webhook payload. Returns true if the signature matches or if no secret is configured (SecretName is empty).

Signature schemes:

  • github: X-Hub-Signature-256: sha256=<hex>
  • slack: X-Slack-Signature: v0=<hex> (message: "v0:<timestamp>:<body>")
  • generic: X-Webhook-Signature: sha256=<hex>

For Slack, timestamp is the value of the X-Slack-Request-Timestamp header and is required to construct the correct base string and enforce replay protection.

type WebhookProcessStep

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

WebhookProcessStep processes an inbound webhook request. It:

  1. Extracts the webhook source from the URL path parameter (:source / {source})
  2. Reads the raw request body
  3. Looks up matching webhook configs from the DB
  4. Verifies HMAC signature if a secret is configured
  5. Applies event type filters
  6. Creates a task using the webhook's task template
  7. Returns the created task ID

func (*WebhookProcessStep) Execute

Execute processes the inbound webhook and auto-creates a task.

func (*WebhookProcessStep) Name

func (s *WebhookProcessStep) Name() string

type WebhookSecurityCheck

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

WebhookSecurityCheck looks for webhook configurations lacking HMAC verification.

func (*WebhookSecurityCheck) Name

func (c *WebhookSecurityCheck) Name() string

func (*WebhookSecurityCheck) Run

type WorkspaceInitStep

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

WorkspaceInitStep creates a project workspace directory.

func (*WorkspaceInitStep) Execute

func (*WorkspaceInitStep) Name

func (s *WorkspaceInitStep) Name() string

type WorkspaceSpec

type WorkspaceSpec struct {
	Image        string            `json:"image"`
	InitCommands []string          `json:"init_commands,omitempty"`
	Env          map[string]string `json:"env,omitempty"`
	MemoryLimit  int64             `json:"memory_limit,omitempty"`
	CPULimit     float64           `json:"cpu_limit,omitempty"`
	NetworkMode  string            `json:"network_mode,omitempty"`
}

WorkspaceSpec describes the container configuration for a project workspace.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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