tool

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2026 License: MIT Imports: 26 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 5-tier resilience pipeline:

Tier 1: Exact substring match
Tier 2: CRLF and trailing whitespace normalization
Tier 3: Line-trimmed matching (ignoring indentation differences per line)
Tier 4: Relative indentation alignment (preserving base indentation of destination)
Tier 5: Unique fuzzy similarity window (threshold >= 85% match, single candidate)

Returns (newContent, matchTier, error).

func CapOutput

func CapOutput(s string) string

CapOutput truncates tool output to maxCommandOutputChars, keeping a visible marker so the model knows more output exists beyond the cap. The marker names the way out (narrow the query / smaller range) because a model that sees a bare "truncated" notice tends to retry the same read or fight it with bash sed/head/tail loops instead of adapting — which burns rounds.

The slice is rune-safe: cutting at a byte boundary could split a multi-byte UTF-8 rune (CJK comments, emoji) and leave an invalid tail in the model's context — so the cap lands on a rune boundary via a clipped []rune slice.

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 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 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 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 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.

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.

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 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 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 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 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 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 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 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 read-only git commands only — no commands that mutate the repo.

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 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 ReadFileTool

type ReadFileTool struct{}

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 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) (string, 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) 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) 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) 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 DuckDuckGo's public HTML endpoint as a zero-config fallback. 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 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