tool

package
v0.1.47 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2026 License: MIT Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
const FileChangesSep = "\n====DIFF====\n"

FileChangesSep separates the compact per-file block from the full diff block inside a FILES message. The UI renders the compact part by default and the diff part when the user expands the block.

Variables

This section is empty.

Functions

func AllowKey

func AllowKey(cmd string) string

AllowKey returns the session rule key for a command, or "" when the command is not gated at all (so "always allow" only ever applies to gated rules). The key is coarse on purpose (first word + git subcommand): "rm" covers every rm invocation, "git push" covers plain pushes, "git push --force" is a distinct key so force-pushing stays gated even after plain pushes are allowed.

func ApplyResilientEdit

func ApplyResilientEdit(content, target, replacement string) (string, string, error)

ApplyResilientEdit attempts to replace target in content with replacement using a 6-tier resilience pipeline:

Tier 1: Exact substring match
Tier 2: CRLF and trailing whitespace normalization
Tier 3: Relative indentation alignment (preserving base indentation of destination)
Tier 4: Line-trimmed matching (ignoring indentation differences per line)
Tier 5: Block-Anchor matching (anchored by unique first and last lines)
Tier 6: Unique fuzzy similarity window (threshold >= 80% match, single candidate)

Returns (newContent, matchTier, error).

func CapOutput

func CapOutput(s string) string

CapOutput truncates tool output to maxCommandOutputChars and redacts any accidental secrets, keeping a visible marker so the model knows more output exists beyond the cap.

func ChangesLen

func ChangesLen() int

ChangesLen returns how many changes are recorded this turn.

func CleanupStaleSnapshots

func CleanupStaleSnapshots() int

CleanupStaleSnapshots removes every registered backup and returns how many were deleted. Called at the start of a real user turn (the tool loop's internal iterations never touch it): a snapshot is the one-turn rollback window; the user's next prompt is the accept signal. It also removes the (now empty) snapshots tree, clearing any stray files left by a crashed turn.

func CumulativeChangeDiff added in v0.1.1

func CumulativeChangeDiff(path string) string

CumulativeChangeDiff returns the unified diff for path from the FIRST recorded change's original content to the LAST recorded change's content this turn — one growing diff per file (created → modified → deleted), so the live chat entry updates in place instead of spawning a new entry per edit. Returns "" when path has no recorded change this turn.

func ExtractCleanMarkdownFromHTML added in v0.1.37

func ExtractCleanMarkdownFromHTML(rawHTML string) (string, error)

ExtractCleanMarkdownFromHTML parses raw HTML into a DOM tree, prunes boilerplate (scripts, ads, nav), and converts the main content into clean, token-efficient Markdown.

func FetchAndCleanURL added in v0.1.37

func FetchAndCleanURL(ctx context.Context, targetURL string) (string, error)

FetchAndCleanURL fetches a remote webpage and returns clean, DOM-pruned Markdown.

func FetchUnifiedDocs added in v0.1.37

func FetchUnifiedDocs(ctx context.Context, library, query string) (string, string, error)

FetchUnifiedDocs executes 3-tier docs resolution cascade: 1. Tier 1: Local / llms.txt (workspace or direct docs) 2. Tier 2: Native Context7 REST API 3. Tier 3: Web Search Cascade (Tavily/Exa/Free)

func FileChangesCompact

func FileChangesCompact(ch []FileChange) string

FileChangesCompact renders one line per file: action glyph, path and line counts — the collapsed view.

func FileChangesDiff

func FileChangesDiff(ch []FileChange) string

func FileChangesMessage

func FileChangesMessage(ch []FileChange) string

FileChangesMessage builds the full FILES message for the turn's changes: compact per-file rows (one line each with action + line counts), a separator, then the per-file unified diff. The UI shows the compact rows collapsed and the diff when expanded.

func FileChangesOneLine

func FileChangesOneLine(ch []FileChange) string

FileChangesOneLine renders a single compact summary line for the activity slot: total file count, net line deltas, and a per-file breakdown. Used for the real-time "what just changed" HUD during a turn (P2 #2) — kept to one line so it never floods the term.

func FindClosestBlock added in v0.1.22

func FindClosestBlock(content, target string) string

FindClosestBlock scans content for the line window of the same length as target that has the highest similarity to target, providing an immediate diagnostic suggestion.

func FindClosestBlockWithLines added in v0.1.47

func FindClosestBlockWithLines(content, target string) (string, int, int)

FindClosestBlockWithLines scans content for the line window with the highest similarity to target and returns the closest snippet, 1-based start line, and 1-based end line.

func GuardFile

func GuardFile(path string) error

GuardFile protects a file path against both sensitive files and heavy dirs.

func GuardHeavyPath

func GuardHeavyPath(path string) error

GuardHeavyPath blocks reading/writing inside a heavy dir (node_modules, vendor, target, ...). listPath may be true when the call is a listing that legitimately shows the directory name but must not descend into it.

func GuardSensitiveCommand

func GuardSensitiveCommand(cmd string) string

GuardSensitiveCommand blocks bash commands that clearly read or dump a sensitive file (cat/less/head/tail .env, etc.). Not a security boundary — the permission gate is — but a hard native habit: the agent never even tries. Returns "" when the command is fine.

func GuardSensitivePath

func GuardSensitivePath(path string) error

GuardSensitivePath blocks reading a file whose name or extension marks it as sensitive (secrets, keys, env). Returns a hard error the model sees, so it learns the path is off-limits instead of silently getting nothing.

func IsHeavyDir

func IsHeavyDir(name string) bool

IsHeavyDir reports whether a directory name is a dependency/build/VCS dir the agent must not read. Exported so glob walking and the repo map reuse the same rule.

func MaskSecrets added in v0.1.12

func MaskSecrets(s string) string

MaskSecrets scrubs raw API keys and auth tokens from tool outputs so secrets never leak into the model's context window.

func ProgressFromContext added in v0.1.2

func ProgressFromContext(ctx context.Context) func(state string, info string)

ProgressFromContext extracts a progress callback, or nil if none set.

func PurgeAllSnapshots

func PurgeAllSnapshots()

PurgeAllSnapshots removes the entire .brocode/snapshots tree regardless of the in-memory list. Called once at session startup so a turn that crashed mid-edit (whose in-memory list is already gone) cannot leave backups behind.

func RecordChange

func RecordChange(c FileChange)

RecordChange appends a file mutation to the current turn's change list.

func ResetChanges

func ResetChanges()

ResetChanges clears the turn's change list (called at user-turn start).

func RestoreAllSnapshots

func RestoreAllSnapshots() int

RestoreAllSnapshots reverts every live snapshot (LIFO) and returns how many files were restored. Used when the user asks to roll back the whole turn.

func RestoreLastSnapshot

func RestoreLastSnapshot() (string, error)

RestoreLastSnapshot reverts the most recent backed-up file and returns a human-readable summary. Snapshots are LIFO: repeated calls walk backwards through the turn's edits.

func RestoreNSnapshots

func RestoreNSnapshots(n int) (int, error)

RestoreNSnapshots reverts the n most recent snapshots (LIFO). Returns the number actually restored (fewer if n exceeds the live snapshot count). This is the multi-step rollback primitive: the user can jump back N edits in one call instead of invoking undo repeatedly.

func SafeCommandContext added in v0.1.24

func SafeCommandContext(ctx context.Context, name string, args ...string) *exec.Cmd

SafeCommandContext prepares an exec.Cmd configured with non-interactive environment variables, isolated process group (PGID), and clean process-tree termination on cancellation/timeout.

func Snapshot

func Snapshot(filePath string) error

Snapshot captures the state of a file before modification. If the repo is a git repository, git already tracks the original — the manual backup is a failsafe for files git does not cover (untracked, ignored) and for the one-turn rollback window. Backups are written under .brocode/snapshots and are bounded in both memory and on disk.

Deduplication: if the same file is snapshotted multiple times in one turn (e.g. 3 consecutive edits), only the FIRST snapshot reads + writes. Subsequent calls for the same path are no-ops — the already-captured backup is reused for undo. This cuts 2/3 I/O on batched-edit turns.

func SnapshotCount

func SnapshotCount() int

SnapshotCount returns how many live snapshots remain (files edited this turn that can still be rolled back).

func SnapshotSummary

func SnapshotSummary() []string

SnapshotSummary lists the currently live snapshots (most recent first) so the user/agent can see how many rollback steps exist.

func SortSymbolLines

func SortSymbolLines(syms []search.SymbolItem) []search.SymbolItem

SortSymbolLines is a convenience for tests: returns symbols sorted by line.

func ValidateJSONNoDuplicateKeys added in v0.1.1

func ValidateJSONNoDuplicateKeys(content string) error

ValidateJSONNoDuplicateKeys checks if a JSON string contains duplicate keys within any object scope. Returns an error if duplicate keys are detected or if the JSON is malformed. BOM characters are silently stripped before parsing.

func ValidateSyntaxIntegrity added in v0.1.22

func ValidateSyntaxIntegrity(path, originalContent, newContent string) error

ValidateSyntaxIntegrity checks whether an edited file contains broken syntax or unbalanced delimiters that would break execution (e.g. malformed JSX, unclosed braces/parentheses/brackets, invalid JSON). ValidateSyntaxIntegrity checks whether an edited file contains broken syntax or unbalanced delimiters across ALL programming languages, scripts, markup, and config files (Go, Rust, Python, JS/TS/JSX/TSX, C/C++, C#, Java, Kotlin, PHP, Ruby, Swift, Dart, Lua, SQL, HTML, XML, YAML, TOML, JSON, etc.).

func WithProgress added in v0.1.2

func WithProgress(ctx context.Context, cb func(state string, info string)) context.Context

WithProgress attaches a progress callback to the context so blocking tools like subagent/scout can forward interim updates without changing the Tool interface signature.

func WithTurnFiles added in v0.1.2

func WithTurnFiles(ctx context.Context) context.Context

WithTurnFiles attaches an initially-empty turn-file collector to ctx. The engine wraps each tool call with this so file tools can record co-occurrence.

Types

type AskQuestion

type AskQuestion = provider.AskQuestion

AskQuestion and AskResult alias the provider types so the OpenCode CLI adapter (which lives in provider) can present clarification questions through the same interactive modal as the ask_user tool, without the provider package importing tool (which would be an import cycle).

type AskResult

type AskResult = provider.AskResult

type AskUserTool

type AskUserTool struct {
	Ask func(ctx context.Context, questions []AskQuestion) ([]AskResult, error)
}

AskUserTool asks the user interactive multiple-choice questions. The Ask handler is wired by the UI layer; without it (headless) the tool fails gracefully with an error the model can read.

func (*AskUserTool) Description

func (t *AskUserTool) Description() string

func (*AskUserTool) Execute

func (t *AskUserTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*AskUserTool) Name

func (t *AskUserTool) Name() string

func (*AskUserTool) Parameters

func (t *AskUserTool) Parameters() map[string]any

type BashTool

type BashTool struct {
	// Container, when non-nil and Enabled, routes every command through a
	// Docker container instead of the host shell (see ContainerSandbox). It is
	// wired by Registry.SetSandbox from the sandbox.json policy.
	Container *ContainerSandbox
	// WorkDir is the project root, mounted at /workspace inside the container.
	WorkDir string
}

BashTool

func (*BashTool) Description

func (t *BashTool) Description() string

func (*BashTool) Execute

func (t *BashTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*BashTool) Name

func (t *BashTool) Name() string

func (*BashTool) Parameters

func (t *BashTool) Parameters() map[string]any

type BlastRadiusTool added in v0.1.32

type BlastRadiusTool struct {
	Index *search.GlobalIndex
}

BlastRadiusTool performs impact analysis on symbols or files across the codebase.

func (*BlastRadiusTool) Description added in v0.1.32

func (t *BlastRadiusTool) Description() string

func (*BlastRadiusTool) Execute added in v0.1.32

func (t *BlastRadiusTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*BlastRadiusTool) Name added in v0.1.32

func (t *BlastRadiusTool) Name() string

func (*BlastRadiusTool) Parameters added in v0.1.32

func (t *BlastRadiusTool) Parameters() map[string]any

type CheckpointTool

type CheckpointTool struct{}

CheckpointTool snapshots the project's source tree to a named, restorable checkpoint — git-style rollback without touching the user's git history. create → copy the working tree (git-tracked + untracked when in a repo, otherwise a vendor/heavy-dir aware walk) into .brocode/checkpoints/<name>. list → existing checkpoints. restore → copy a checkpoint's files back.

func (*CheckpointTool) Description

func (t *CheckpointTool) Description() string

func (*CheckpointTool) Execute

func (t *CheckpointTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*CheckpointTool) Name

func (t *CheckpointTool) Name() string

func (*CheckpointTool) Parameters

func (t *CheckpointTool) Parameters() map[string]any

type CodeImpactTool added in v0.1.16

type CodeImpactTool struct{}

CodeImpactTool analyzes blast radius and caller/callee dependencies before editing.

func (*CodeImpactTool) Description added in v0.1.16

func (t *CodeImpactTool) Description() string

func (*CodeImpactTool) Execute added in v0.1.16

func (t *CodeImpactTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*CodeImpactTool) Name added in v0.1.16

func (t *CodeImpactTool) Name() string

func (*CodeImpactTool) Parameters added in v0.1.16

func (t *CodeImpactTool) Parameters() map[string]any

type CodeLocateTool

type CodeLocateTool struct {
	Index *search.GlobalIndex
}

CodeLocateTool answers repo-wide "where is X and who uses it" questions in one call using the persistent session index (symbols + reference graph) — no LSP spawn and no full-file reads. This is the repo-map equivalent that lets the model navigate precisely before reading anything.

func (*CodeLocateTool) Description

func (t *CodeLocateTool) Description() string

func (*CodeLocateTool) Execute

func (t *CodeLocateTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*CodeLocateTool) Name

func (t *CodeLocateTool) Name() string

func (*CodeLocateTool) Parameters

func (t *CodeLocateTool) Parameters() map[string]any

type CodeOutlineTool added in v0.1.16

type CodeOutlineTool struct{}

CodeOutlineTool extracts structural symbols with line ranges and call info.

func (*CodeOutlineTool) Description added in v0.1.16

func (t *CodeOutlineTool) Description() string

func (*CodeOutlineTool) Execute added in v0.1.16

func (t *CodeOutlineTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*CodeOutlineTool) Name added in v0.1.16

func (t *CodeOutlineTool) Name() string

func (*CodeOutlineTool) Parameters added in v0.1.16

func (t *CodeOutlineTool) Parameters() map[string]any

type CodeSliceTool added in v0.1.36

type CodeSliceTool struct {
	Index *search.GlobalIndex
}

CodeSliceTool extracts an AST-level dependency slice (definition body + inbound callers + outbound callees). This provides deep, surgical context without polluting the prompt with thousands of lines of unrelated code.

func (*CodeSliceTool) Description added in v0.1.36

func (t *CodeSliceTool) Description() string

func (*CodeSliceTool) Execute added in v0.1.36

func (t *CodeSliceTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*CodeSliceTool) Name added in v0.1.36

func (t *CodeSliceTool) Name() string

func (*CodeSliceTool) Parameters added in v0.1.36

func (t *CodeSliceTool) Parameters() map[string]any

type CodeSymbolsTool

type CodeSymbolsTool struct{}

CodeSymbolsTool returns a compact structural map (functions, structs, classes, methods + line numbers) of one or more files — the agent sees a file's shape without reading its whole body into context.

func (*CodeSymbolsTool) Description

func (t *CodeSymbolsTool) Description() string

func (*CodeSymbolsTool) Execute

func (t *CodeSymbolsTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*CodeSymbolsTool) Name

func (t *CodeSymbolsTool) Name() string

func (*CodeSymbolsTool) Parameters

func (t *CodeSymbolsTool) Parameters() map[string]any

type ContainerSandbox

type ContainerSandbox struct {
	Enabled bool   `json:"enabled"`
	Image   string `json:"image"`
}

ContainerSandbox routes every bash command through a Docker container for real OS-level isolation. The project root is mounted read-write at /workspace and commands run as `sh -c <cmd>` inside the chosen image, so a destructive or buggy command cannot touch the host. Opt-in via .brocode/sandbox.json:

{ "container": { "enabled": true, "image": "golang:1.23-alpine" } }

The image should contain the toolchain the project needs (go, node, etc.). When enabled but docker is unavailable the tool errors clearly — it never silently falls back to running on the host (that would defeat the point).

type Context7Client added in v0.1.37

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

Context7Client communicates directly with Context7 REST API (https://context7.com/api/v1). Native Go implementation eliminates Node.js/npx overhead and MCP protocol fragility.

func NewContext7Client added in v0.1.37

func NewContext7Client(apiKey string) *Context7Client

NewContext7Client creates a new Context7 API client.

func (*Context7Client) GetDocs added in v0.1.37

func (c *Context7Client) GetDocs(ctx context.Context, libraryID, query string) (string, error)

GetDocs retrieves targeted documentation from Context7 for a library and specific query.

func (*Context7Client) ResolveLibrary added in v0.1.37

func (c *Context7Client) ResolveLibrary(ctx context.Context, libraryName string) (string, error)

ResolveLibrary finds the most relevant library ID for a given package/framework name.

type ContextRecallTool added in v0.1.2

type ContextRecallTool struct {
	Store *store.Store
}

ContextRecallTool exposes the self-aware notes store to the agent: search across every captured action/experience/insight from past sessions (and this one) by keyword. This is the agent-facing "retrieve" primitive of the retain→recall→reflect discipline — active self-retrieval, not just passive warm-start injection.

The store is wired by the UI (nil store = tool reports it is unavailable).

func (*ContextRecallTool) Description added in v0.1.2

func (t *ContextRecallTool) Description() string

func (*ContextRecallTool) Execute added in v0.1.2

func (t *ContextRecallTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*ContextRecallTool) Name added in v0.1.2

func (t *ContextRecallTool) Name() string

func (*ContextRecallTool) Parameters added in v0.1.2

func (t *ContextRecallTool) Parameters() map[string]any

type DeleteFileTool

type DeleteFileTool struct{}

DeleteFileTool permanently removes a file. It is gated (GateAction asks the user before deletion) and its old content is recorded so the turn's change summary shows the deletion and the undo snapshot can restore the file.

func (*DeleteFileTool) Description

func (t *DeleteFileTool) Description() string

func (*DeleteFileTool) Execute

func (t *DeleteFileTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*DeleteFileTool) Name

func (t *DeleteFileTool) Name() string

func (*DeleteFileTool) Parameters

func (t *DeleteFileTool) Parameters() map[string]any

type DocLookupTool added in v0.1.37

type DocLookupTool struct{}

DocLookupTool retrieves official framework/library documentation using native Context7 API and web fallback.

func (*DocLookupTool) Description added in v0.1.37

func (t *DocLookupTool) Description() string

func (*DocLookupTool) Execute added in v0.1.37

func (t *DocLookupTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*DocLookupTool) Name added in v0.1.37

func (t *DocLookupTool) Name() string

func (*DocLookupTool) Parameters added in v0.1.37

func (t *DocLookupTool) Parameters() map[string]any

type EditFileTool

type EditFileTool struct{}

EditFileTool

func (*EditFileTool) Description

func (t *EditFileTool) Description() string

func (*EditFileTool) Execute

func (t *EditFileTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*EditFileTool) Name

func (t *EditFileTool) Name() string

func (*EditFileTool) Parameters

func (t *EditFileTool) Parameters() map[string]any

type EditSymbolTool added in v0.1.12

type EditSymbolTool struct{}

EditSymbolTool enables AST-addressable code editing: targeting functions, methods, structs, and classes directly by symbol name without relying on string search or guessing line numbers.

func (*EditSymbolTool) Description added in v0.1.12

func (t *EditSymbolTool) Description() string

func (*EditSymbolTool) Execute added in v0.1.12

func (t *EditSymbolTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*EditSymbolTool) Name added in v0.1.12

func (t *EditSymbolTool) Name() string

func (*EditSymbolTool) Parameters added in v0.1.12

func (t *EditSymbolTool) Parameters() map[string]any

type FetchURLTool

type FetchURLTool struct{}

FetchURLTool fetches a URL and returns its readable text content.

func (*FetchURLTool) Description

func (t *FetchURLTool) Description() string

func (*FetchURLTool) Execute

func (t *FetchURLTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*FetchURLTool) Name

func (t *FetchURLTool) Name() string

func (*FetchURLTool) Parameters

func (t *FetchURLTool) Parameters() map[string]any

type FileActionDecision

type FileActionDecision struct {
	Allow  bool // false = discard (deny) the action
	Always bool // remember this path for the rest of the session
}

FileActionDecision is the user's answer to a file-action confirmation.

type FileActionRequest

type FileActionRequest struct {
	Kind string // "create_file" | "delete_file"
	Path string
}

FileActionRequest describes a critical file mutation (create/delete) that needs the user's confirmation before it runs.

type FileChange

type FileChange struct {
	Path   string `json:"path"`
	Action string `json:"action"` // "created" | "modified" | "deleted"
	Old    string `json:"old,omitempty"`
	New    string `json:"new,omitempty"`
}

FileChange records one file mutation made by a native tool during a turn, with the content before and after so the UI can render a +/- diff summary per file (created / modified / deleted) at the end of the response.

func DeduplicateChanges added in v0.1.16

func DeduplicateChanges(ch []FileChange) []FileChange

DeduplicateChanges merges multiple mutations to the same file path within a turn into a single cumulative change (original Old -> latest New), so the summary lists each file exactly once and the diff is clean.

func PeekChanges

func PeekChanges() []FileChange

PeekChanges returns a copy of the turn's recorded changes WITHOUT clearing the list (unlike TakeChanges). Used by review gates to size the diff.

func TakeChanges

func TakeChanges() []FileChange

TakeChanges returns the turn's recorded changes and clears the list (called at user-turn end, after the answer is appended).

type GateDecision

type GateDecision int

GateDecision is the outcome of gating a command before execution.

const (
	// GateAllow runs the command silently.
	GateAllow GateDecision = iota
	// GateAsk pauses for the user (permission modal).
	GateAsk
	// GateDeny blocks the command outright — never executed regardless of the
	// user's choice (the genuinely catastrophic cases, e.g. rm -rf /).
	GateDeny
)

func GateCommand

func GateCommand(cmd, repoRoot string, allow map[string]bool) GateDecision

GateCommand decides whether cmd may run, needs confirmation, or is blocked. repoRoot anchors the out-of-repo escape check for cd/pushd; allow is the session allow-list (keys from AllowKey) — matching keys skip the gate.

type GitShadowManager

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

GitShadowManager manages zero-overhead atomic git working tree snapshots. It uses git plumbing (`write-tree`, `commit-tree`, `update-ref`) to snapshot the entire repository state before mutations without touching HEAD or creating user-visible branch commits.

func NewGitShadowManager

func NewGitShadowManager(repoDir string) *GitShadowManager

NewGitShadowManager initializes a shadow manager for repoDir.

func (*GitShadowManager) CreateShadowSnapshot

func (m *GitShadowManager) CreateShadowSnapshot(sessionID string, seq int) (string, error)

CreateShadowSnapshot captures the current working directory state into an isolated git commit ref.

func (*GitShadowManager) IsGit

func (m *GitShadowManager) IsGit() bool

IsGit reports whether repoDir is a valid Git repository.

func (*GitShadowManager) PurgeAll

func (m *GitShadowManager) PurgeAll()

PurgeAll removes all brocode shadow snapshot refs.

func (*GitShadowManager) RollbackLast

func (m *GitShadowManager) RollbackLast() (string, error)

RollbackLast restores the working directory to the most recent shadow snapshot.

type GitTool

type GitTool struct{}

GitTool runs git commands with built-in atomic commit staging and read-only queries.

func (*GitTool) Description

func (t *GitTool) Description() string

func (*GitTool) Execute

func (t *GitTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*GitTool) Name

func (t *GitTool) Name() string

func (*GitTool) Parameters

func (t *GitTool) Parameters() map[string]any

type GlobTool

type GlobTool struct{}

GlobTool

func (*GlobTool) Description

func (t *GlobTool) Description() string

func (*GlobTool) Execute

func (t *GlobTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*GlobTool) Name

func (t *GlobTool) Name() string

func (*GlobTool) Parameters

func (t *GlobTool) Parameters() map[string]any

type GrepTool

type GrepTool struct{}

GrepTool

func (*GrepTool) Description

func (t *GrepTool) Description() string

func (*GrepTool) Execute

func (t *GrepTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*GrepTool) Name

func (t *GrepTool) Name() string

func (*GrepTool) Parameters

func (t *GrepTool) Parameters() map[string]any

type LibrarySearchResult added in v0.1.37

type LibrarySearchResult struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Stars       int    `json:"stars,omitempty"`
}

LibrarySearchResult holds a library match from Context7.

type ListDirTool

type ListDirTool struct{}

ListDirTool

func (*ListDirTool) Description

func (t *ListDirTool) Description() string

func (*ListDirTool) Execute

func (t *ListDirTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*ListDirTool) Name

func (t *ListDirTool) Name() string

func (*ListDirTool) Parameters

func (t *ListDirTool) Parameters() map[string]any

type MemoryTool

type MemoryTool struct {
	Store *memory.Store
}

MemoryTool exposes the cross-session project memory to the agent:

  • recall <query> — BM25 search over stored facts (past sessions' learnings)
  • retain <fact> — store a durable fact (optionally in a section)
  • list — show everything stored

The store is wired by the UI (nil store = tool reports it is unavailable).

func (*MemoryTool) Description

func (t *MemoryTool) Description() string

func (*MemoryTool) Execute

func (t *MemoryTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*MemoryTool) Name

func (t *MemoryTool) Name() string

func (*MemoryTool) Parameters

func (t *MemoryTool) Parameters() map[string]any

type MultiGitShadowManager added in v0.1.1

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

MultiGitShadowManager manages shadow snapshots across multiple Git repositories within a multi-repo workspace.

func NewMultiGitShadowManager added in v0.1.1

func NewMultiGitShadowManager(rootPath string, repoPaths []string) *MultiGitShadowManager

NewMultiGitShadowManager creates a multi-repo shadow manager for a workspace root.

func (*MultiGitShadowManager) CreateShadowSnapshot added in v0.1.1

func (m *MultiGitShadowManager) CreateShadowSnapshot(sessionID string, seq int) ([]string, error)

CreateShadowSnapshot captures working tree snapshots across all active git repos.

func (*MultiGitShadowManager) PurgeAll added in v0.1.1

func (m *MultiGitShadowManager) PurgeAll()

PurgeAll removes all shadow snapshot refs across all repos.

func (*MultiGitShadowManager) RollbackLast added in v0.1.1

func (m *MultiGitShadowManager) RollbackLast() ([]string, error)

RollbackLast restores all repositories in the workspace to the most recent turn snapshot.

type ReadFileTool

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

ReadFileTool

func (*ReadFileTool) Description

func (t *ReadFileTool) Description() string

func (*ReadFileTool) Execute

func (t *ReadFileTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*ReadFileTool) Name

func (t *ReadFileTool) Name() string

func (*ReadFileTool) Parameters

func (t *ReadFileTool) Parameters() map[string]any

type RefactorClusterTool added in v0.1.16

type RefactorClusterTool struct{}

RefactorClusterTool groups functions in a large file into cohesive target modules.

func (*RefactorClusterTool) Description added in v0.1.16

func (t *RefactorClusterTool) Description() string

func (*RefactorClusterTool) Execute added in v0.1.16

func (t *RefactorClusterTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*RefactorClusterTool) Name added in v0.1.16

func (t *RefactorClusterTool) Name() string

func (*RefactorClusterTool) Parameters added in v0.1.16

func (t *RefactorClusterTool) Parameters() map[string]any

type Registry

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

Registry holds all registered tools plus the permission gate state.

func NewRegistry

func NewRegistry() *Registry

NewRegistry initializes default built-in tools.

func (*Registry) Definitions

func (r *Registry) Definitions() []provider.ToolDefinition

func (*Registry) Execute

func (r *Registry) Execute(ctx context.Context, name, argsJSON string) (result string, err error)

func (*Registry) GateAction

func (r *Registry) GateAction(ctx context.Context, tc provider.ToolCall) (approved bool, reason string, err error)

GateAction decides whether a tool call may proceed. Only bash commands are gated (the proven legacy design): risky/destructive commands either run silently, ask the user for approval (Allow once / Always allow / Deny), or are hard-blocked. write_file/edit_file are not gated — the PLANNER mode guard already handles read-only enforcement.

func (*Registry) Lookup

func (r *Registry) Lookup(name string) Tool

Lookup returns a registered tool by name, or nil if not found.

func (*Registry) Register

func (r *Registry) Register(t Tool)

func (*Registry) RepoRoot

func (r *Registry) RepoRoot() string

RepoRoot returns the configured repo root (anchors the cd/pushd escape check and path resolution for pre-flight context packing).

func (*Registry) Sandbox

func (r *Registry) Sandbox() *Sandbox

Sandbox returns the active sandbox policy, or nil when none is configured.

func (*Registry) SetCommandFilter added in v0.1.36

func (r *Registry) SetCommandFilter(fn func(cmd string) (bool, bool))

SetCommandFilter sets a dynamic command permission filter (e.g. from an active CustomAgent).

func (*Registry) SetExecutionPolicy

func (r *Registry) SetExecutionPolicy(readOnly, readOnlyBash bool)

SetExecutionPolicy hard-enforces a read-only mode at the executor level. readOnly=true blocks write_file/edit_file/delete_file everywhere; readOnlyBash additionally blocks bash (PLANNER mode). Safe to call at any time; mutating tools return a clear error instead of executing.

func (*Registry) SetFileActionHandler

func (r *Registry) SetFileActionHandler(fn func(context.Context, FileActionRequest) (FileActionDecision, error))

SetFileActionHandler wires the input-bar confirmation for critical file mutations (create/delete file). Without it (headless), gated file actions run — mirroring the bash gate's unattended behavior.

func (*Registry) SetKnowledgeStore added in v0.1.2

func (r *Registry) SetKnowledgeStore(st *store.Store)

SetKnowledgeStore wires the Smart Context Graph backend into the read/edit Tools so they can update and invalidate knowledge entries. The same store backs the self-aware notes layer (context_recall), so it is wired here too. Nil disables both.

func (*Registry) SetMemoryStore

func (r *Registry) SetMemoryStore(st *memory.Store)

SetMemoryStore wires the cross-session project memory into the memory tool. Nil leaves the tool reporting that memory is unavailable.

func (*Registry) SetRepoRoot

func (r *Registry) SetRepoRoot(path string)

SetRepoRoot anchors the out-of-repo escape check for cd/pushd gates and tells the bash tool where the project root is (so a container sandbox can mount it at /workspace).

func (*Registry) SetSandbox

func (r *Registry) SetSandbox(s *Sandbox)

SetSandbox applies a granular per-tool permission policy (from .brocode/sandbox.json). Nil or disabled sandboxes leave the default gate-only behavior untouched. When the sandbox enables the container sandbox, the bash tool is switched to run inside Docker.

func (*Registry) SetSearchEmbedder

func (r *Registry) SetSearchEmbedder(e *search.Embedder)

SetSearchEmbedder wires an OpenAI-compatible embeddings endpoint onto the registered search_code tool (BM25 stays the fallback when it is nil).

func (*Registry) SetToolFilter added in v0.1.36

func (r *Registry) SetToolFilter(fn func(toolName string) bool)

SetToolFilter sets a dynamic tool filter (e.g. from an active CustomAgent).

func (*Registry) SetUserAskHandler

func (r *Registry) SetUserAskHandler(fn func(context.Context, []AskQuestion) ([]AskResult, error))

SetUserAskHandler wires the interactive ask modal so gated commands can request approval from the user. Without it (headless), gated commands run.

func (*Registry) SubRegistry

func (r *Registry) SubRegistry() *Registry

SubRegistry returns a copy of the registry safe for sub-agent execution: tool instances are shared (they are stateless), but the interactive tools (ask_user, review_changes) and subagent itself are dropped so a sub-agent can never pop a modal, ask the user, or recurse. Gated commands are always DENIED in a sub-agent — destructive operations must go through the main agent's approval modal, never a silent background run.

func (*Registry) ToolByName

func (r *Registry) ToolByName(name string) Tool

ToolByName returns a registered tool by name, or nil when not present. Used by the engine for pre-flight context packing (e.g. running lsp_scan itself before the model does, so diagnostics land in the first prompt instead of costing a tool round-trip).

type ReviewChangesTool

type ReviewChangesTool struct {
	Ask func(ctx context.Context, questions []AskQuestion) ([]AskResult, error)
}

ReviewChangesTool shows the current uncommitted diff to the user in the interactive modal and lets them approve or roll back the turn's changes.

func (*ReviewChangesTool) Description

func (t *ReviewChangesTool) Description() string

func (*ReviewChangesTool) Execute

func (t *ReviewChangesTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*ReviewChangesTool) Name

func (t *ReviewChangesTool) Name() string

func (*ReviewChangesTool) Parameters

func (t *ReviewChangesTool) Parameters() map[string]any

type RunTestsTool

type RunTestsTool struct {
	// Plan returns the shell command lines to run, in order. Nil falls back
	// to defaultTestPlan(), which detects common configs in the cwd.
	Plan func() []string
}

RunTestsTool runs the project's test/build command on demand with a structured pass/fail summary — the model can call it during TSR REPRODUCE (watch a failing test) and VERIFY (confirm the fix) phases, complementing the engine's automatic verification. The command plan is injected (the loop's richer language/monorepo detection) with a self-contained fallback so the tool works even un-wired.

func (*RunTestsTool) Description

func (t *RunTestsTool) Description() string

func (*RunTestsTool) Execute

func (t *RunTestsTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*RunTestsTool) Name

func (t *RunTestsTool) Name() string

func (*RunTestsTool) Parameters

func (t *RunTestsTool) Parameters() map[string]any

type Sandbox

type Sandbox struct {
	Deny          []string          `json:"deny"`          // tool names blocked outright
	AllowOnly     []string          `json:"allowOnly"`     // if set, only these tools run
	DenyCommands  []string          `json:"denyCommands"`  // substrings blocked in bash/git
	AllowCommands []string          `json:"allowCommands"` // substrings that override denyCommands
	Container     *ContainerSandbox `json:"container"`     // when enabled, bash runs inside Docker
}

Sandbox is a parsed permission policy.

func LoadSandbox

func LoadSandbox(projectRoot string) *Sandbox

LoadSandbox reads the first sandbox.json found (project then global). Missing/invalid files yield an empty (disabled) sandbox, never an error.

func (*Sandbox) CheckTool

func (s *Sandbox) CheckTool(name, argsJSON string) (reason string)

CheckTool evaluates the sandbox for a tool invocation. Returns the reason a call is blocked, or "" when it may proceed. deniedByPolicy distinguishes a hard sandbox block from a gate ask (so callers never prompt for a blocked tool).

func (*Sandbox) Disabled

func (s *Sandbox) Disabled() bool

Disabled reports whether no restrictions are configured.

type SearchCodeTool

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

SearchCodeTool performs a relevance search over the codebase — ranks files against a natural-language query. BM25 first; when an embedding endpoint is wired (SetEmbedder), the top candidates are re-ranked by vector cosine similarity for true semantic matching.

func (*SearchCodeTool) Description

func (t *SearchCodeTool) Description() string

func (*SearchCodeTool) Execute

func (t *SearchCodeTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*SearchCodeTool) Name

func (t *SearchCodeTool) Name() string

func (*SearchCodeTool) Parameters

func (t *SearchCodeTool) Parameters() map[string]any

func (*SearchCodeTool) SetEmbedder

func (t *SearchCodeTool) SetEmbedder(e *search.Embedder)

SetEmbedder wires an OpenAI-compatible embeddings endpoint so search_code re-ranks BM25 hits semantically (with a persistent per-file cache). Nil keeps the tool BM25-only.

type Tool

type Tool interface {
	Name() string
	Description() string
	Parameters() map[string]any
	Execute(ctx context.Context, argsJSON string) (string, error)
}

Tool represents an executable native tool.

type ToolCache

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

ToolCache is a small bounded, FIFO-evicting cache for tool results.

func (*ToolCache) Get

func (c *ToolCache) Get(tool, args string) (string, bool)

Get returns a cached result for (tool, args) and whether it was present.

func (*ToolCache) InvalidatePath

func (c *ToolCache) InvalidatePath(path string)

InvalidatePath drops every cached entry that could be affected by a change to path: that file's own reads, plus every "global" (tree-wide) result.

func (*ToolCache) Put

func (c *ToolCache) Put(tool, args, val, scope string)

Put stores a result. scope groups entries for invalidation: "file:<path>" invalidates with that path; "global" is dropped on any file write.

type UndoTool

type UndoTool struct{}

UndoTool reverts the most recent file modification(s) made this turn.

func (*UndoTool) Description

func (t *UndoTool) Description() string

func (*UndoTool) Execute

func (t *UndoTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*UndoTool) Name

func (t *UndoTool) Name() string

func (*UndoTool) Parameters

func (t *UndoTool) Parameters() map[string]any

type WebSearchResult

type WebSearchResult struct {
	Title   string `json:"title"`
	URL     string `json:"url"`
	Snippet string `json:"snippet,omitempty"`
}

func FreeWebSearch

func FreeWebSearch(ctx context.Context, query string, maxResults int) ([]WebSearchResult, error)

FreeWebSearch queries public search endpoints with multi-tier fallback (DuckDuckGo HTML -> Lite -> Wikipedia). It requires NO API key and runs with pure standard library HTTP + regex parsing.

type WebSearchTool

type WebSearchTool struct{}

WebSearchTool searches the web via the Exa API (semantic search for AI agents). Requires the EXA_API_KEY environment variable.

func (*WebSearchTool) Description

func (t *WebSearchTool) Description() string

func (*WebSearchTool) Execute

func (t *WebSearchTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*WebSearchTool) Name

func (t *WebSearchTool) Name() string

func (*WebSearchTool) Parameters

func (t *WebSearchTool) Parameters() map[string]any

type WorktreeInfo added in v0.1.36

type WorktreeInfo struct {
	Directory string `json:"directory"`
	Branch    string `json:"branch"`
	Head      string `json:"head"`
}

WorktreeInfo represents an active git worktree.

type WorktreeManager added in v0.1.36

type WorktreeManager struct {
	WorkspaceDir string
}

WorktreeManager manages isolated background git worktrees.

func NewWorktreeManager added in v0.1.36

func NewWorktreeManager(workspaceDir string) *WorktreeManager

NewWorktreeManager creates a new WorktreeManager for a workspace.

func (*WorktreeManager) CreateWorktree added in v0.1.36

func (m *WorktreeManager) CreateWorktree(taskName string) (string, string, error)

CreateWorktree creates a lightweight isolated worktree under .brocode/worktrees/<name>.

func (*WorktreeManager) ListWorktrees added in v0.1.36

func (m *WorktreeManager) ListWorktrees() ([]WorktreeInfo, error)

ListWorktrees returns all active worktrees.

func (*WorktreeManager) MergeWorktree added in v0.1.36

func (m *WorktreeManager) MergeWorktree(branchName string) (string, error)

MergeWorktree merges the worktree branch into the active branch.

func (*WorktreeManager) RemoveWorktree added in v0.1.36

func (m *WorktreeManager) RemoveWorktree(worktreeDir, branchName string, deleteBranch bool) error

RemoveWorktree deletes the worktree and prunes git tracking.

type WriteFileTool

type WriteFileTool struct{}

WriteFileTool

func (*WriteFileTool) Description

func (t *WriteFileTool) Description() string

func (*WriteFileTool) Execute

func (t *WriteFileTool) Execute(ctx context.Context, argsJSON string) (string, error)

func (*WriteFileTool) Name

func (t *WriteFileTool) Name() string

func (*WriteFileTool) Parameters

func (t *WriteFileTool) Parameters() map[string]any

Jump to

Keyboard shortcuts

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