tools

package
v1.6.1 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MaxBackupDirSize is the maximum total size of the backup directory (100MB).
	MaxBackupDirSize = 100 * 1024 * 1024
	// MinFreeDiskSpace is the minimum free disk space to maintain (50MB).
	MinFreeDiskSpace = 50 * 1024 * 1024
)
View Source
const (
	BashKillGracePeriod = time.Duration(types.DefaultBashKillGraceSecs) * time.Second
	BashWaitTimeout     = 30 * time.Second

	MaxBackupsPerFile = types.DefaultMaxBackupsPerFile
	DirPermission     = types.DirPermission
	FilePermission    = types.FilePermission

	MaxGlobResults = types.DefaultMaxGlobResults

	MaxGrepPatternLength  = 1024
	DefaultMaxGrepResults = types.DefaultMaxGrepResults

	MaxRedirects       = types.DefaultWebfetchMaxRedirects
	DefaultTimeoutSecs = 30
	MaxTimeoutSecs     = 120
	DNSCacheTTL        = 5 * time.Minute

	MinLinesForFuzzy     = 3
	LevenshteinThreshold = 0.7

	PermissionChannelBuffer = 8
	QuestionChannelBuffer   = 4
	DefaultAgentName        = "default"

	// Rate limiting: token bucket for tool execution.
	// Max 20 tools per second burst, sustained 10 tools/second.
	ToolRateLimitBurst  = 20
	ToolRateLimitPerSec = 10

	// Per-risk-level rate limits (M6): dangerous tools get stricter limits.
	DangerousRateLimitBurst  = 5
	DangerousRateLimitPerSec = 2

	// Max concurrent tool executions (M5): prevents resource exhaustion.
	MaxConcurrentTools = 8

	DefaultSearchBaseURL    = "https://search.sagibo.net"
	MaxSearchQueryLength    = 500
	DefaultMaxSearchResults = 5
	MaxSearchResults        = 10

	DefaultOutputMaxLines = 2000
	DefaultOutputMaxBytes = 51200
	OutputRetentionDays   = 7
)
View Source
const MaxAgentDepth = 2

MaxAgentDepth is the maximum nesting depth for subagents. Depth 0 is the root agent, depth 1 is a child, depth 2 is a grandchild. Going deeper is blocked to prevent runaway resource consumption.

Variables

View Source
var DefaultExtensions = []string{
	".go", ".py", ".js", ".ts", ".jsx", ".tsx",
	".rs", ".java", ".c", ".cpp", ".h", ".hpp",
	".rb", ".php", ".cs", ".swift", ".kt",
}

DefaultExtensions are the common source file extensions to analyze when no extensions are specified. Covers Go, Python, JS/TS, Rust, Java, C/C++.

View Source
var Version atomic.Value

Version is the application version used in User-Agent headers. Set via SetVersion() from cmd/m31a/main.go.

Functions

func BuildToolDefs

func BuildToolDefs(d *Dispatcher) []provider.ToolDefinition

BuildToolDefs creates provider.ToolDefinition slices from a Dispatcher's registered tools. This is shared between the workflow engine and the autonomous agent loop to avoid duplicating tool schema logic.

func ContainedInWorkDir added in v1.4.0

func ContainedInWorkDir(resolved, workDir string) error

ContainedInWorkDir checks that resolved is either equal to workDir or is contained within it (with a trailing separator guard to prevent prefix attacks).

func HumanSize added in v1.4.0

func HumanSize(b int64) string

HumanSize formats bytes into a human-readable string.

func LevenshteinBuf added in v1.4.0

func LevenshteinBuf(a, b string, prev, curr []int) int

LevenshteinBuf is like LevenshteinDistance but reuses pre-allocated buffers.

func LevenshteinDistance added in v1.4.0

func LevenshteinDistance(a, b string) int

LevenshteinDistance computes the edit distance between two strings.

func NewDispatcherFactory

func NewDispatcherFactory(backupDir, sessionsDir string, permCfg *config.PermissionsConfig, toolsCfg *config.ToolsConfig, manager *subagent.Manager, profiles map[string]config.SubagentProfileConfig) subagent.DispatcherFactory

NewDispatcherFactory returns a DispatcherFactory that creates a fresh tools.Dispatcher for each subagent workspace. The factory registers the Agent tool (with isChild=true) on every dispatcher so a subagent can spawn its own child, but forced-foreground to block runaway fan-out.

backupDir and sessionsDir are shared across all dispatchers; permCfg is reused verbatim so permission rules apply uniformly.

func ResolveAndContainPath added in v1.4.0

func ResolveAndContainPath(path, workDir string) (string, error)

ResolveAndContainPath resolves a path (joining relative to workDir if needed), resolves symlinks, and verifies the result is within workDir. If the file does not exist, it attempts to resolve the parent directory through symlinks instead. Returns the resolved absolute path or an error if it escapes the workDir.

func ResolveAndContainPathExists added in v1.4.0

func ResolveAndContainPathExists(path, workDir string) (string, error)

ResolveAndContainPathExists resolves a path and verifies it is within workDir. Unlike ResolveAndContainPath, this requires the path to already exist on disk.

func SetVersion

func SetVersion(v string)

SetVersion sets the application version for User-Agent headers.

Types

type Agent

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

Agent is a tool that spawns a parallel subagent to perform an independent task. The parent conversation receives the subagent's ID immediately and can continue issuing other tool calls while the subagent runs.

Background mode (default) returns the agent ID and delivers the final summary to the parent via SubagentEvent messages consumed by the TUI. Foreground mode (run_in_background=false) blocks until the subagent finishes and returns its summary as this tool's output.

func NewAgent

func NewAgent(m *subagent.Manager, isChild bool, depth int, profiles map[string]config.SubagentProfileConfig) *Agent

NewAgent creates an Agent tool backed by the given manager.

func (*Agent) Description

func (t *Agent) Description() string

func (*Agent) Execute

func (t *Agent) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

Execute validates input, spawns the subagent, and returns its ID + status.

func (*Agent) Name

func (t *Agent) Name() string

func (*Agent) ParameterSchema

func (t *Agent) ParameterSchema() string

ParameterSchema returns the JSON schema exposed to the LLM.

func (*Agent) RiskLevel

func (t *Agent) RiskLevel() types.RiskLevel

type AskUserQuestion

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

func NewAskUserQuestion

func NewAskUserQuestion(requestCh chan QuestionRequest, responseCh chan QuestionResponse, pending *sync.Map) *AskUserQuestion

func (*AskUserQuestion) Description

func (t *AskUserQuestion) Description() string

func (*AskUserQuestion) Execute

func (t *AskUserQuestion) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*AskUserQuestion) Name

func (t *AskUserQuestion) Name() string

func (*AskUserQuestion) ParameterSchema

func (t *AskUserQuestion) ParameterSchema() string

ParameterSchema returns the JSON Schema for AskUserQuestion tool parameters.

func (*AskUserQuestion) RiskLevel

func (t *AskUserQuestion) RiskLevel() types.RiskLevel

type Bash

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

func NewBash

func NewBash(workDir string) *Bash

func (*Bash) Description

func (t *Bash) Description() string

func (*Bash) Execute

func (t *Bash) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*Bash) Name

func (t *Bash) Name() string

func (*Bash) ParameterSchema

func (t *Bash) ParameterSchema() string

ParameterSchema returns the JSON Schema for Bash tool parameters.

func (*Bash) RiskLevel

func (t *Bash) RiskLevel() types.RiskLevel

type BatchApproval added in v1.6.0

type BatchApproval struct {
	ToolName  string
	RiskLevel types.RiskLevel
	ExpiresAt time.Time // zero = never expires (manual SetPermission)
}

BatchApproval records a user's "approve all" decision for a tool+risk combination. Approvals are task-scoped: they expire when the current task completes or the workflow phase transitions.

type CodeComplexity added in v1.1.0

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

CodeComplexity is a tool that analyzes the codebase and returns a complexity report with file counts, line counts, top packages, top files, and a complexity score. Default extensions cover all common languages.

func NewCodeComplexity added in v1.1.0

func NewCodeComplexity(workDir string, skipDirs []string) *CodeComplexity

NewCodeComplexity creates a new CodeComplexity tool. skipDirs is an optional override; if nil, types.SkipDirs is used.

func (*CodeComplexity) Description added in v1.1.0

func (t *CodeComplexity) Description() string

func (*CodeComplexity) Execute added in v1.1.0

func (t *CodeComplexity) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*CodeComplexity) Name added in v1.1.0

func (t *CodeComplexity) Name() string

func (*CodeComplexity) ParameterSchema added in v1.1.0

func (t *CodeComplexity) ParameterSchema() string

func (*CodeComplexity) RiskLevel added in v1.1.0

func (t *CodeComplexity) RiskLevel() types.RiskLevel

type CodeMap

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

CodeMap is a tool that queries the codebase intelligence layer for import graph, symbol definitions, and relevant file discovery.

func NewCodeMap

func NewCodeMap(workDir string) *CodeMap

func (*CodeMap) Description

func (t *CodeMap) Description() string

func (*CodeMap) Execute

func (t *CodeMap) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*CodeMap) Name

func (t *CodeMap) Name() string

func (*CodeMap) ParameterSchema

func (t *CodeMap) ParameterSchema() string

func (*CodeMap) RiskLevel

func (t *CodeMap) RiskLevel() types.RiskLevel

type ComplexityReport added in v1.1.0

type ComplexityReport struct {
	TotalFiles int
	TotalLines int
	Packages   []PackageStat
	Files      []FileStat
	Score      string
	Languages  map[string]int // extension → file count
}

ComplexityReport holds the results of a codebase complexity analysis.

type DNSCache added in v1.4.0

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

DNSCache is a shared DNS cache backed by a sync.Map with configurable TTL, periodic eviction, and maximum size limit. Both WebFetch and WebSearch share this implementation.

func NewDNSCache added in v1.4.0

func NewDNSCache(ttl time.Duration, evictThreshold int32) *DNSCache

NewDNSCache creates a DNS cache with the given TTL, eviction threshold, and maximum size. Eviction runs when the number of inserts since last eviction reaches threshold. Cache size is capped at maxSize entries.

func NewDNSCacheWithMaxSize added in v1.4.0

func NewDNSCacheWithMaxSize(ttl time.Duration, evictThreshold int32, maxSize int32) *DNSCache

NewDNSCacheWithMaxSize creates a DNS cache with explicit max size control.

func (*DNSCache) Resolve added in v1.4.0

func (dc *DNSCache) Resolve(ctx context.Context, host string) ([]net.IPAddr, error)

Resolve resolves DNS for a hostname, using the cache when available. If the host is a literal IP address, it is returned directly without caching. Enforces maximum cache size to prevent memory exhaustion attacks.

func (*DNSCache) Size added in v1.4.0

func (dc *DNSCache) Size() int32

Size returns the approximate number of entries in the cache.

type DevServer added in v1.3.0

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

func NewDevServer added in v1.3.0

func NewDevServer(workDir string) *DevServer

func (*DevServer) Description added in v1.3.0

func (d *DevServer) Description() string

func (*DevServer) Execute added in v1.3.0

func (d *DevServer) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*DevServer) Name added in v1.3.0

func (d *DevServer) Name() string

func (*DevServer) ParameterSchema added in v1.3.0

func (d *DevServer) ParameterSchema() string

func (*DevServer) RiskLevel added in v1.3.0

func (d *DevServer) RiskLevel() types.RiskLevel

func (*DevServer) StopAll added in v1.3.0

func (d *DevServer) StopAll()

StopAll terminates all managed dev servers. Called during cleanup.

type Dispatcher

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

func DefaultDispatcher

func DefaultDispatcher(workDir, backupDir, sessionsDir string, cfg *config.PermissionsConfig, toolsCfg *config.ToolsConfig) (*Dispatcher, error)

func NewDispatcher

func NewDispatcher(cfg *config.PermissionsConfig) *Dispatcher

NewDispatcher creates a new Dispatcher with a background rate-limiter goroutine. The caller MUST call Stop() when the Dispatcher is no longer needed to prevent goroutine leaks (e.g., during session restart or app shutdown).

func (*Dispatcher) ActiveBatchToolNames added in v1.6.0

func (d *Dispatcher) ActiveBatchToolNames() string

ActiveBatchToolNames returns a comma-separated list of tool names with active batch approvals (e.g. "bash,edit"). Empty string if none.

func (*Dispatcher) ApproveBatch added in v1.6.0

func (d *Dispatcher) ApproveBatch(toolName string, risk types.RiskLevel)

ApproveBatch records a batch approval for the given tool+risk combination. When active, all future permission requests matching this tool+risk are auto-approved without prompting the user. Approvals are task-scoped: they expire when RevokeBatchApprovals() is called (typically on task completion or phase transition).

func (*Dispatcher) ApprovePermission

func (d *Dispatcher) ApprovePermission(requestID int64, allowed bool, remember bool)

func (*Dispatcher) BatchApprovalCount added in v1.6.0

func (d *Dispatcher) BatchApprovalCount() int

BatchApprovalCount returns the number of active batch approvals.

func (*Dispatcher) Execute

func (d *Dispatcher) Execute(ctx context.Context, call types.ToolCall) (types.ToolResult, error)

func (*Dispatcher) GetTool

func (d *Dispatcher) GetTool(name string) (types.Tool, bool)

func (*Dispatcher) List

func (d *Dispatcher) List() []string

func (*Dispatcher) PendingPermCount added in v1.6.0

func (d *Dispatcher) PendingPermCount() int

PendingPermCount returns the number of permission requests currently waiting in the queue (between send and TUI response).

func (*Dispatcher) QuestionRequestCh

func (d *Dispatcher) QuestionRequestCh() chan QuestionRequest

func (*Dispatcher) QuestionResponseCh

func (d *Dispatcher) QuestionResponseCh() chan QuestionResponse

func (*Dispatcher) Register

func (d *Dispatcher) Register(tool types.Tool) error

func (*Dispatcher) RequestCh

func (d *Dispatcher) RequestCh() chan PermissionRequest

func (*Dispatcher) RespondQuestion

func (d *Dispatcher) RespondQuestion(requestID int64, answer string)

RespondQuestion routes a question response to the per-request channel for the given request ID. Falls back to the shared channel if no per-request channel exists. This prevents cross-caller response routing (H-2).

func (*Dispatcher) RevokeBatchApprovals added in v1.6.0

func (d *Dispatcher) RevokeBatchApprovals()

RevokeBatchApprovals clears all active batch approvals. Called on task completion or phase transition to reset session-scoped approvals.

func (*Dispatcher) SelectAgent

func (d *Dispatcher) SelectAgent(agent string) error

func (*Dispatcher) SetCollector added in v1.5.0

func (d *Dispatcher) SetCollector(c *metrics.Collector)

SetCollector attaches a metrics collector for recording tool execution metrics. Also propagates the collector to tools that support it (e.g., Edit for strategy tracking).

func (*Dispatcher) SetOutputStore added in v1.3.0

func (d *Dispatcher) SetOutputStore(store *OutputStore)

SetOutputStore configures the output store for bounding tool output.

func (*Dispatcher) SetPermission

func (d *Dispatcher) SetPermission(toolName string, allowed bool)

func (*Dispatcher) SetSessionID

func (d *Dispatcher) SetSessionID(id string)

func (*Dispatcher) SetTodoWriteCallback added in v1.1.0

func (d *Dispatcher) SetTodoWriteCallback(fn func(items []TodoItem))

SetTodoWriteCallback sets the callback invoked after successful TodoWrite tool executions.

func (*Dispatcher) Stop

func (d *Dispatcher) Stop()

Stop shuts down the rate limiter goroutine and ticker. Should be called when the Dispatcher is no longer needed (e.g., during app shutdown). C-12: Uses sync.Once to prevent TOCTOU race on concurrent calls.

func (*Dispatcher) SyncTodoFromTasks added in v1.4.0

func (d *Dispatcher) SyncTodoFromTasks(tasks []types.Task) error

SyncTodoFromTasks updates TODO.md from the task runner's current state. Called automatically after each execution group to keep the TODO in sync.

func (*Dispatcher) Unregister added in v1.3.0

func (d *Dispatcher) Unregister(name string)

Unregister removes a tool by name. Used by profile-based filtering to strip tools that a subagent profile should not access.

func (*Dispatcher) UpdatePermissions

func (d *Dispatcher) UpdatePermissions(cfg *config.PermissionsConfig)

UpdatePermissions hot-reloads the permission configuration.

type Edit

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

func NewEdit

func NewEdit(workDir, backupDir string) *Edit

func (*Edit) Description

func (t *Edit) Description() string

func (*Edit) Execute

func (t *Edit) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*Edit) Name

func (t *Edit) Name() string

func (*Edit) ParameterSchema

func (t *Edit) ParameterSchema() string

ParameterSchema returns the JSON Schema for Edit tool parameters.

func (*Edit) RiskLevel

func (t *Edit) RiskLevel() types.RiskLevel

func (*Edit) SetCollector added in v1.5.0

func (t *Edit) SetCollector(c *metrics.Collector)

SetCollector attaches a metrics collector for recording edit strategy usage.

type FileDelete

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

func NewFileDelete

func NewFileDelete(workDir, backupDir string) *FileDelete

func (*FileDelete) Description

func (t *FileDelete) Description() string

func (*FileDelete) Execute

func (t *FileDelete) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*FileDelete) Name

func (t *FileDelete) Name() string

func (*FileDelete) ParameterSchema

func (t *FileDelete) ParameterSchema() string

func (*FileDelete) RiskLevel

func (t *FileDelete) RiskLevel() types.RiskLevel

type FileList

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

func NewFileList

func NewFileList(workDir string) *FileList

func (*FileList) Description

func (t *FileList) Description() string

func (*FileList) Execute

func (t *FileList) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*FileList) Name

func (t *FileList) Name() string

func (*FileList) ParameterSchema

func (t *FileList) ParameterSchema() string

func (*FileList) RiskLevel

func (t *FileList) RiskLevel() types.RiskLevel

type FileMove

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

func NewFileMove

func NewFileMove(workDir, backupDir string) *FileMove

func (*FileMove) Description

func (t *FileMove) Description() string

func (*FileMove) Execute

func (t *FileMove) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*FileMove) Name

func (t *FileMove) Name() string

func (*FileMove) ParameterSchema

func (t *FileMove) ParameterSchema() string

func (*FileMove) RiskLevel

func (t *FileMove) RiskLevel() types.RiskLevel

type FileRead

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

func NewFileRead

func NewFileRead(workDir string) *FileRead

func (*FileRead) Description

func (t *FileRead) Description() string

func (*FileRead) Execute

func (t *FileRead) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*FileRead) Name

func (t *FileRead) Name() string

func (*FileRead) ParameterSchema

func (t *FileRead) ParameterSchema() string

ParameterSchema returns the JSON Schema for FileRead tool parameters.

func (*FileRead) RiskLevel

func (t *FileRead) RiskLevel() types.RiskLevel

type FileStat added in v1.1.0

type FileStat struct {
	Path  string
	Lines int
}

FileStat holds stats for a single source file.

type FileWrite

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

func NewFileWrite

func NewFileWrite(workDir, backupDir string) *FileWrite

func (*FileWrite) Description

func (t *FileWrite) Description() string

func (*FileWrite) Execute

func (t *FileWrite) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*FileWrite) Name

func (t *FileWrite) Name() string

func (*FileWrite) ParameterSchema

func (t *FileWrite) ParameterSchema() string

ParameterSchema returns the JSON Schema for FileWrite tool parameters.

func (*FileWrite) RiskLevel

func (t *FileWrite) RiskLevel() types.RiskLevel

type Glob

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

func NewGlob

func NewGlob(workDir string) *Glob

func (*Glob) Description

func (t *Glob) Description() string

func (*Glob) Execute

func (t *Glob) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*Glob) Name

func (t *Glob) Name() string

func (*Glob) ParameterSchema

func (t *Glob) ParameterSchema() string

ParameterSchema returns the JSON Schema for Glob tool parameters.

func (*Glob) RiskLevel

func (t *Glob) RiskLevel() types.RiskLevel

type Grep

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

func NewGrep

func NewGrep(workDir string) *Grep

func (*Grep) Description

func (t *Grep) Description() string

func (*Grep) Execute

func (t *Grep) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*Grep) Name

func (t *Grep) Name() string

func (*Grep) ParameterSchema

func (t *Grep) ParameterSchema() string

ParameterSchema returns the JSON Schema for Grep tool parameters.

func (*Grep) RiskLevel

func (t *Grep) RiskLevel() types.RiskLevel

type HTTPCheck added in v1.3.0

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

func NewHTTPCheck added in v1.3.0

func NewHTTPCheck() *HTTPCheck

func (*HTTPCheck) Description added in v1.3.0

func (h *HTTPCheck) Description() string

func (*HTTPCheck) Execute added in v1.3.0

func (h *HTTPCheck) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*HTTPCheck) Name added in v1.3.0

func (h *HTTPCheck) Name() string

func (*HTTPCheck) ParameterSchema added in v1.3.0

func (h *HTTPCheck) ParameterSchema() string

func (*HTTPCheck) RiskLevel added in v1.3.0

func (h *HTTPCheck) RiskLevel() types.RiskLevel

type MetricsTool added in v1.2.0

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

MetricsTool provides query access to session observability metrics. It supports four modes: summary, tool-stats, phase-stats, cost-report.

func NewMetricsTool added in v1.2.0

func NewMetricsTool(collector *metrics.Collector) *MetricsTool

NewMetricsTool creates a MetricsTool backed by the given collector.

func (*MetricsTool) Description added in v1.2.0

func (t *MetricsTool) Description() string

func (*MetricsTool) Execute added in v1.2.0

func (t *MetricsTool) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*MetricsTool) Name added in v1.2.0

func (t *MetricsTool) Name() string

func (*MetricsTool) ParameterSchema added in v1.2.0

func (t *MetricsTool) ParameterSchema() string

ParameterSchema returns the JSON Schema for Metrics tool parameters.

func (*MetricsTool) RiskLevel added in v1.2.0

func (t *MetricsTool) RiskLevel() types.RiskLevel

type OutputStore added in v1.3.0

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

OutputStore bounds tool output to prevent single tool calls from consuming the entire context window. When output exceeds configured limits, the full output is saved to a managed directory and a head+tail preview is returned.

func NewOutputStore added in v1.3.0

func NewOutputStore(baseDir string, maxLines, maxBytes int) *OutputStore

NewOutputStore creates an OutputStore with the given limits. baseDir is the directory where truncated outputs are saved (e.g., ~/.m31a/tool-output/).

func (*OutputStore) Bound added in v1.3.0

func (s *OutputStore) Bound(output string) (string, string, bool)

Bound checks if the output exceeds configured limits. If so, it saves the full output to a file and returns a head+tail preview with a truncation marker. Returns (boundedOutput, savedPath, wasTruncated).

func (*OutputStore) Cleanup added in v1.3.0

func (s *OutputStore) Cleanup(retention time.Duration) (int, error)

Cleanup removes output files older than the given retention period.

type PackageStat added in v1.1.0

type PackageStat struct {
	Path  string
	Files int
	Lines int
}

PackageStat holds aggregate stats for a single package (directory).

type PermissionContext

type PermissionContext struct {
	RuleTool    string // Tool name from the matched rule
	RulePattern string // Pattern from the matched rule
	RuleAction  string // The action that triggered (allow/deny/ask)
	Source      string // Source of the decision: "rule", "agent_default", or "risk_level"
}

PermissionContext carries additional info about a matched rule for display in the permission modal.

type PermissionPolicy added in v1.6.0

type PermissionPolicy string

PermissionPolicy defines how permissions are handled in headless mode

const (
	PolicyAllowSafe PermissionPolicy = "allow-safe"
	PolicyDenyAll   PermissionPolicy = "deny-all"
	PolicyPrompt    PermissionPolicy = "prompt"
)

func (PermissionPolicy) IsValid added in v1.6.0

func (p PermissionPolicy) IsValid() bool

func (PermissionPolicy) ShouldAutoAllow added in v1.6.0

func (p PermissionPolicy) ShouldAutoAllow(toolName string, risk types.RiskLevel) bool

ShouldAutoAllow determines if a tool is automatically allowed based on policy

type PermissionRequest

type PermissionRequest struct {
	ID          int64           `json:"id"`
	ToolName    string          `json:"tool_name"`
	Command     string          `json:"command"`
	RiskLevel   types.RiskLevel `json:"risk_level"`
	TimeoutSecs int             `json:"timeout_secs"`
	// QueueDepth is the number of pending permission requests behind this one.
	QueueDepth int `json:"queue_depth"`
	// Rule context (populated when a permission rule matched)
	RuleTool    string `json:"rule_tool,omitempty"`
	RulePattern string `json:"rule_pattern,omitempty"`
	RuleAction  string `json:"rule_action,omitempty"`
	// Policy indicates how permissions should be handled (AllowSafe/DenyAll/Prompt)
	Policy PermissionPolicy `json:"policy,omitempty"`
}

type PermissionResponse

type PermissionResponse struct {
	RequestID  int64 `json:"request_id"`
	Allowed    bool  `json:"allowed"`
	Remember   bool  `json:"remember"`
	ApproveAll bool  `json:"approve_all"` // approve all pending + future for this tool+risk
}

type PersistentPermissions added in v1.3.0

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

PersistentPermissions manages saved permission rules that survive across sessions. Rules are scoped by project directory and stored in ~/.m31a/permissions.json.

func NewPersistentPermissions added in v1.3.0

func NewPersistentPermissions() *PersistentPermissions

NewPersistentPermissions creates a PersistentPermissions instance that reads/writes to ~/.m31a/permissions.json.

func (*PersistentPermissions) Load added in v1.3.0

func (p *PersistentPermissions) Load(projectDir string) []config.PermissionRule

Load reads persistent permission rules for the given project directory.

func (*PersistentPermissions) Remove added in v1.3.0

func (p *PersistentPermissions) Remove(projectDir string) error

Remove clears all persistent rules for the given project directory.

func (*PersistentPermissions) Save added in v1.3.0

func (p *PersistentPermissions) Save(projectDir string, rule config.PermissionRule) error

Save adds a permission rule for the given project directory and persists it.

type QuestionRequest

type QuestionRequest struct {
	ID          int64
	Question    string
	Header      string
	Options     []string
	AllowCustom bool
	TimeoutSecs int
}

QuestionRequest represents a question sent from the tool to the TUI.

type QuestionResponse

type QuestionResponse struct {
	Answer string
}

QuestionResponse represents the user's answer from the TUI.

type SafeFileOp added in v1.4.0

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

SafeFileOp provides TOCTOU-safe file operations by opening a file descriptor and validating it before performing operations. This prevents race conditions where a symlink could be created between path resolution and file access.

func (*SafeFileOp) OpenAndValidate added in v1.4.0

func (s *SafeFileOp) OpenAndValidate(path, workDir string, flag int, perm os.FileMode) (*os.File, string, error)

OpenAndValidate opens a file and validates it's within the allowed directory. Returns the file handle and resolved path, or an error if validation fails. The caller is responsible for closing the returned file.

type TodoItem added in v1.1.0

type TodoItem struct {
	Content  string
	Status   string
	Priority string
}

TodoItem represents a parsed todo item from the TodoWrite tool.

type TodoRead added in v1.5.0

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

func NewTodoRead added in v1.5.0

func NewTodoRead(sessionsDir, sessionID string) *TodoRead

func (*TodoRead) Description added in v1.5.0

func (t *TodoRead) Description() string

func (*TodoRead) Execute added in v1.5.0

func (t *TodoRead) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*TodoRead) Name added in v1.5.0

func (t *TodoRead) Name() string

func (*TodoRead) ParameterSchema added in v1.5.0

func (t *TodoRead) ParameterSchema() string

ParameterSchema returns the JSON Schema for TodoRead tool parameters.

func (*TodoRead) RiskLevel added in v1.5.0

func (t *TodoRead) RiskLevel() types.RiskLevel

func (*TodoRead) SetSessionID added in v1.5.0

func (t *TodoRead) SetSessionID(id string)

type TodoWrite

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

func NewTodoWrite

func NewTodoWrite(sessionsDir, sessionID string) *TodoWrite

func (*TodoWrite) Description

func (t *TodoWrite) Description() string

func (*TodoWrite) Execute

func (t *TodoWrite) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*TodoWrite) Name

func (t *TodoWrite) Name() string

func (*TodoWrite) ParameterSchema

func (t *TodoWrite) ParameterSchema() string

ParameterSchema returns the JSON Schema for TodoWrite tool parameters.

func (*TodoWrite) RiskLevel

func (t *TodoWrite) RiskLevel() types.RiskLevel

func (*TodoWrite) SetOnUpdate added in v1.1.0

func (t *TodoWrite) SetOnUpdate(fn func(items []TodoItem))

SetOnUpdate sets the callback invoked after successful todo writes.

func (*TodoWrite) SetSessionID

func (t *TodoWrite) SetSessionID(id string)

func (*TodoWrite) SyncTodoFromTasks added in v1.4.0

func (t *TodoWrite) SyncTodoFromTasks(tasks []types.Task) error

SyncTodoFromTasks generates TODO.md from a task runner's current state. This bridges the gap between the task runner (which tracks execution state) and the TODO.md file (which provides user-visible progress tracking). It is called automatically after each execution group and at phase boundaries.

type WebFetch

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

func NewWebFetch

func NewWebFetch(sessionsDir string, allowPrivateIPs bool) *WebFetch

func (*WebFetch) Close added in v1.1.0

func (wf *WebFetch) Close()

Close releases idle connections held by the HTTP client's transport. Call this during shutdown to prevent connection leaks.

func (*WebFetch) Description

func (t *WebFetch) Description() string

func (*WebFetch) Execute

func (t *WebFetch) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*WebFetch) Name

func (t *WebFetch) Name() string

func (*WebFetch) ParameterSchema

func (t *WebFetch) ParameterSchema() string

ParameterSchema returns the JSON Schema for WebFetch tool parameters.

func (*WebFetch) RiskLevel

func (t *WebFetch) RiskLevel() types.RiskLevel

type WebSearch

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

func NewWebSearch

func NewWebSearch(baseURL string) *WebSearch

func (*WebSearch) Close added in v1.0.2

func (t *WebSearch) Close()

Close releases idle connections held by the HTTP client's transport. Call this during shutdown to prevent connection leaks.

func (*WebSearch) Description

func (t *WebSearch) Description() string

func (*WebSearch) Execute

func (t *WebSearch) Execute(ctx context.Context, input types.ToolInput) (types.ToolResult, error)

func (*WebSearch) Name

func (t *WebSearch) Name() string

func (*WebSearch) ParameterSchema

func (t *WebSearch) ParameterSchema() string

func (*WebSearch) RiskLevel

func (t *WebSearch) RiskLevel() types.RiskLevel

Directories

Path Synopsis
Package subagent implements parallel child-agent execution.
Package subagent implements parallel child-agent execution.

Jump to

Keyboard shortcuts

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