tools

package
v0.7.4 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	PlanStatusPending    = "pending"
	PlanStatusInProgress = "in_progress"
	PlanStatusDone       = "done"
)

Plan item statuses accepted by the plan tool.

View Source
const MaxScratchpadBytes = 8 * 1024

MaxScratchpadBytes bounds the working-state text the model may record. It is small on purpose: the scratchpad is a compaction-safe summary, not a log.

Variables

This section is empty.

Functions

func CheckSensitiveFile added in v0.7.0

func CheckSensitiveFile(m *ignore.SensitiveMatcher, path string, isDir bool) (bool, string, error)

CheckSensitiveFile rejects normalisation tricks, then applies ignore and case-folded sensitive checks.

func DescribeFlags added in v0.5.0

func DescribeFlags(flagged []string) string

DescribeFlags renders the advisory warnings shown in the approval preview.

func DescribeRedactions added in v0.5.0

func DescribeRedactions(hits []string) string

DescribeRedactions renders a note listing which secret patterns were masked.

func InvalidateSensitiveIdentityCache added in v0.7.4

func InvalidateSensitiveIdentityCache(root string)

InvalidateSensitiveIdentityCache drops cached identity sets for root. It is called after a successful file_write/file_patch so approvals and subsequent checks never rely on pre-write identities for the TTL window.

func IsBlockedByIdentity added in v0.7.0

func IsBlockedByIdentity(set []os.FileInfo, info os.FileInfo) bool

IsBlockedByIdentity reports whether info is SameFile-equal to any entry in set.

func RedactToolOutput added in v0.7.0

func RedactToolOutput(output string) (string, []string)

RedactToolOutput masks credential-shaped values unconditionally. SECURITY: it is the transcript boundary.

func ScrubbedEnv added in v0.7.4

func ScrubbedEnv(extra []string) []string

ScrubbedEnv returns os.Environ() minus credential-shaped variables and any names or patterns in extra. Essential variables always survive. Child processes therefore never inherit provider API keys by default.

func SensitiveIdentitySet added in v0.7.0

func SensitiveIdentitySet(root string, m *ignore.SensitiveMatcher) []os.FileInfo

SensitiveIdentitySet returns FileInfo of blocked files. SECURITY: hardlink aliases match by identity. Callers filter candidates by identity instead of by name.

The set is cached per (normalized root, matcher) for sensitiveIdentityCacheTTL and MUST be treated as read-only: the returned slice may be shared with other callers, so callers must never mutate or append to it. Invalidate the cache with InvalidateSensitiveIdentityCache after modifying the workspace.

func ValidatePath added in v0.4.0

func ValidatePath(workspaceRoot, requestedPath string) (string, error)

ValidatePath ensures the requested path resolves inside the workspace root. Returns the absolute path.

Types

type ApprovalChoice added in v0.7.4

type ApprovalChoice int

ApprovalChoice is the user's answer to an approval prompt. It is richer than a bool so a UI can offer once-only, session-scoped, and edit paths.

const (
	// ApprovalDeny rejects this invocation.
	ApprovalDeny ApprovalChoice = iota
	// ApprovalOnce approves this invocation only.
	ApprovalOnce
	// ApprovalGrantExact approves this invocation and remembers the exact
	// arguments for the life of this gate.
	ApprovalGrantExact
	// ApprovalReadOnlyTurn allows tools that declare themselves read-only for
	// the rest of the current turn.
	ApprovalReadOnlyTurn
	// ApprovalEdit asks the gate to collect edited arguments and re-prompt.
	ApprovalEdit
)

func (ApprovalChoice) Approved added in v0.7.4

func (c ApprovalChoice) Approved() bool

Approved reports whether the choice approves the current invocation. The read-only flag itself is not an approval of the pending call: the gate re-checks whether that particular tool is read-only.

type ApprovalGate

type ApprovalGate struct {
	OnPresent func(toolName string, args json.RawMessage, preview string) (bool, error)
	// OnPresentChoice is the richer presentation hook. When set it takes
	// precedence over OnPresent, letting a UI return grant/read-only/edit
	// choices instead of a plain yes/no.
	OnPresentChoice func(toolName string, args json.RawMessage, preview string) (ApprovalChoice, error)
	// EditArgs collects replacement arguments when the user chooses edit. The
	// gate validates the result, regenerates the preview when it has one, and
	// re-prompts exactly once. Nil means editing is unavailable.
	EditArgs func(toolName string, args json.RawMessage) (json.RawMessage, error)
	// OnDecision, when set, observes every approval outcome: auto-approved,
	// denied by policy, and user-decided. It cannot alter the decision; the
	// loop uses it for per-turn metrics. Nil means no observer.
	OnDecision func(toolName string, approved bool, auto bool)
	// contains filtered or unexported fields
}

func NewApprovalGate

func NewApprovalGate() *ApprovalGate

func NewApprovalGateWithPermissions added in v0.2.0

func NewApprovalGateWithPermissions(autoApprove, deny []string) *ApprovalGate

func (*ApprovalGate) BeginTurn added in v0.7.4

func (g *ApprovalGate) BeginTurn()

BeginTurn clears the per-turn read-only flag. Session grants intentionally survive: they are scoped to the gate, not to a turn. RunTurn calls this at the top of every user turn so the flag never outlives the turn that set it.

func (*ApprovalGate) IsAutoApproved added in v0.2.0

func (g *ApprovalGate) IsAutoApproved(toolName string) bool

func (*ApprovalGate) IsDenied added in v0.2.0

func (g *ApprovalGate) IsDenied(toolName string) bool

func (*ApprovalGate) Prepare added in v0.7.4

func (g *ApprovalGate) Prepare(ctx context.Context, tool Tool, args json.RawMessage) (func(context.Context) (Result, error), error)

Prepare runs the whole decision flow — permissions, session grants, the per-turn read-only flag, preview, and the user prompt — and returns a closure that runs the approved call with the final arguments. A denial returns a closure that reports the denial Result and never executes the tool.

Running every decision before any execution lets a caller prompt for a whole batch in a deterministic order and then execute independent calls concurrently. Prepare only mutates gate state (grants, read-only flag, decision observers); the closure only runs the tool.

func (*ApprovalGate) RequestApproval

func (g *ApprovalGate) RequestApproval(toolName string, args json.RawMessage, preview string) (bool, error)

RequestApproval is the legacy yes/no entry point. It accepts the same keys as the full prompt; a grant it records has the same session scope.

func (*ApprovalGate) SessionGrantCount added in v0.7.4

func (g *ApprovalGate) SessionGrantCount() int

SessionGrantCount reports how many exact-argument grants this gate holds.

func (*ApprovalGate) SetInputReader added in v0.5.0

func (g *ApprovalGate) SetInputReader(r *bufio.Reader)

SetInputReader makes the gate read answers from r. Callers sharing the stream must pass their reader.

func (*ApprovalGate) SetPermissions added in v0.2.0

func (g *ApprovalGate) SetPermissions(autoApprove, deny []string)

func (*ApprovalGate) WrapExecution

func (g *ApprovalGate) WrapExecution(ctx context.Context, tool Tool, args json.RawMessage) (Result, error)

WrapExecution runs preview → approval → execute. Denied operations never call Execute.

type CodeSearchTool added in v0.4.0

type CodeSearchTool struct {
	IgnoreMatcher    ignore.Matcher
	SensitiveMatcher *ignore.SensitiveMatcher
	WorkspaceRoot    string
	// MaxFileBytes skips files larger than this; 0 uses defaultMaxSearchFileBytes.
	MaxFileBytes int64
	// MaxScanLines caps lines scanned per file; 0 uses defaultSearchScanLines.
	MaxScanLines int
}

CodeSearchTool searches for patterns across workspace files.

func (*CodeSearchTool) Execute added in v0.4.0

func (c *CodeSearchTool) Execute(ctx context.Context, args json.RawMessage) (Result, error)

func (*CodeSearchTool) RequiresApproval added in v0.4.0

func (c *CodeSearchTool) RequiresApproval() bool

func (*CodeSearchTool) Spec added in v0.4.0

func (c *CodeSearchTool) Spec() ToolSpec

type FilePatchTool

type FilePatchTool struct {
	IgnoreMatcher    ignore.Matcher
	SensitiveMatcher *ignore.SensitiveMatcher
	WorkspaceRoot    string
	OnModified       func(path string)
	// contains filtered or unexported fields
}

func (*FilePatchTool) Execute

func (f *FilePatchTool) Execute(ctx context.Context, args json.RawMessage) (Result, error)

Execute applies the patch. Called only after approval.

func (*FilePatchTool) Preview added in v0.4.0

func (f *FilePatchTool) Preview(ctx context.Context, args json.RawMessage) (Preview, error)

Preview shows a diff preview without modifying files.

func (*FilePatchTool) RequiresApproval

func (f *FilePatchTool) RequiresApproval() bool

func (*FilePatchTool) Spec

func (f *FilePatchTool) Spec() ToolSpec

type FileReadTool

type FileReadTool struct {
	IgnoreMatcher    ignore.Matcher
	SensitiveMatcher *ignore.SensitiveMatcher
	WorkspaceRoot    string
	// MaxFileBytes bounds whole-file reads; 0 uses defaultMaxFileBytes. Ranged
	// reads (offset/limit) stream instead of rejecting an oversized file.
	MaxFileBytes int64
}

func (*FileReadTool) Execute

func (f *FileReadTool) Execute(ctx context.Context, args json.RawMessage) (Result, error)

func (*FileReadTool) RequiresApproval

func (f *FileReadTool) RequiresApproval() bool

func (*FileReadTool) Spec

func (f *FileReadTool) Spec() ToolSpec

type FileWriteTool

type FileWriteTool struct {
	IgnoreMatcher    ignore.Matcher
	SensitiveMatcher *ignore.SensitiveMatcher
	WorkspaceRoot    string
	OnModified       func(path string)
	// contains filtered or unexported fields
}

func (*FileWriteTool) Execute

func (f *FileWriteTool) Execute(ctx context.Context, args json.RawMessage) (Result, error)

Execute writes the file. Called only after approval.

func (*FileWriteTool) Preview added in v0.4.0

func (f *FileWriteTool) Preview(ctx context.Context, args json.RawMessage) (Preview, error)

Preview shows a diff preview without modifying files.

func (*FileWriteTool) RequiresApproval

func (f *FileWriteTool) RequiresApproval() bool

func (*FileWriteTool) Spec

func (f *FileWriteTool) Spec() ToolSpec

type PlanItem added in v0.7.4

type PlanItem struct {
	ID     string `json:"id"`
	Text   string `json:"text"`
	Status string `json:"status"`
}

PlanItem is one entry in an agent-maintained task list.

type PlanStore added in v0.7.4

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

PlanStore holds the current plan. It is shared by the plan tool, which writes it, and the agent loop, which renders it into the system prompt.

func NewPlanStore added in v0.7.4

func NewPlanStore() *PlanStore

NewPlanStore returns an empty store.

func (*PlanStore) Items added in v0.7.4

func (s *PlanStore) Items() []PlanItem

Items returns a copy of the current plan.

func (*PlanStore) Render added in v0.7.4

func (s *PlanStore) Render() string

Render returns the checklist in a stable, plain-text form:

  • [x] (1) Write the parser
  • [~] (2) Add tests
  • [ ] (3) Update docs

An empty plan renders as the empty string.

func (*PlanStore) Replace added in v0.7.4

func (s *PlanStore) Replace(items []PlanItem)

Replace swaps the whole plan for items, copying the slice so callers cannot mutate the store through their own slice.

type PlanTool added in v0.7.4

type PlanTool struct {
	Store *PlanStore
}

PlanTool lets the model maintain a task list for multi-step work. It only records text; it cannot touch the workspace, so it needs no approval.

func (*PlanTool) Execute added in v0.7.4

func (p *PlanTool) Execute(_ context.Context, args json.RawMessage) (Result, error)

func (*PlanTool) RequiresApproval added in v0.7.4

func (p *PlanTool) RequiresApproval() bool

RequiresApproval is false: the tool only records text in the session.

func (*PlanTool) Spec added in v0.7.4

func (p *PlanTool) Spec() ToolSpec

type Preview added in v0.4.0

type Preview struct {
	Description string `json:"description,omitempty"`
	Diff        string `json:"diff,omitempty"`
	Command     string `json:"command,omitempty"`
	WorkDir     string `json:"work_dir,omitempty"`
}

Preview contains the information shown to the user before approval.

func (Preview) String added in v0.4.0

func (p Preview) String() string

type Previewer added in v0.4.0

type Previewer interface {
	Preview(ctx context.Context, args json.RawMessage) (Preview, error)
}

Previewer optionally provides a preview for approval before execution.

type ReadOnlyTool added in v0.7.4

type ReadOnlyTool interface {
	ReadOnly() bool
}

ReadOnlyTool is implemented by tools that are safe to auto-approve for a turn after the user chooses "read-only tools this turn". Built-in read-only tools do not prompt at all; the interface is for MCP and future tools that require approval even when they only read.

type Registry

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

func NewRegistry

func NewRegistry() *Registry

func (*Registry) Get

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

func (*Registry) List

func (r *Registry) List() []string

func (*Registry) Register

func (r *Registry) Register(t Tool) error

func (*Registry) Specs

func (r *Registry) Specs() []ToolSpec

type Result

type Result struct {
	Output string `json:"output,omitempty"`
	Error  string `json:"error,omitempty"`
	Diff   string `json:"diff,omitempty"`
}

func RedactToolResult added in v0.7.4

func RedactToolResult(r Result, err error) (Result, error)

RedactToolResult applies the same transcript boundary to a result a caller executed itself from a Prepare closure. It cannot be turned off.

func (Result) String

func (r Result) String() string

type ScratchpadStore added in v0.7.4

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

ScratchpadStore holds agent-maintained working state (goal, decisions, open files) that must survive history compaction. It is shared by the scratchpad tool, which writes it, and the agent loop, which mirrors it into the session and therefore into the system prompt.

func NewScratchpadStore added in v0.7.4

func NewScratchpadStore() *ScratchpadStore

NewScratchpadStore returns an empty store.

func (*ScratchpadStore) Append added in v0.7.4

func (s *ScratchpadStore) Append(content string) error

Append adds content after the existing scratchpad, separating the parts with a newline. The combined text must fit MaxScratchpadBytes.

func (*ScratchpadStore) Get added in v0.7.4

func (s *ScratchpadStore) Get() string

Get returns the raw scratchpad text.

func (*ScratchpadStore) Render added in v0.7.4

func (s *ScratchpadStore) Render() string

Render returns the scratchpad text trimmed for prompt rendering. An empty scratchpad renders as the empty string.

func (*ScratchpadStore) Set added in v0.7.4

func (s *ScratchpadStore) Set(content string) error

Set replaces the whole scratchpad. Content larger than MaxScratchpadBytes is rejected and leaves the previous value untouched. An empty value clears it.

type ScratchpadTool added in v0.7.4

type ScratchpadTool struct {
	Store *ScratchpadStore
}

ScratchpadTool lets the model record working state that must survive compaction. It only records text; it cannot touch the workspace, so it needs no approval.

func (*ScratchpadTool) Execute added in v0.7.4

func (t *ScratchpadTool) Execute(_ context.Context, args json.RawMessage) (Result, error)

func (*ScratchpadTool) RequiresApproval added in v0.7.4

func (t *ScratchpadTool) RequiresApproval() bool

RequiresApproval is false: the tool only records text in the session.

func (*ScratchpadTool) Spec added in v0.7.4

func (t *ScratchpadTool) Spec() ToolSpec

type ShellExecTool

type ShellExecTool struct {
	Timeout        time.Duration
	WorkspaceRoot  string
	MaxOutputBytes int
	// EnvScrub lists additional env var names or patterns to drop from the
	// child process environment, on top of the built-in credential patterns.
	EnvScrub []string
	// Guard redacts secrets and warns about sensitive paths in previews. May be nil.
	Guard *ShellGuard
}

func (*ShellExecTool) Execute

func (s *ShellExecTool) Execute(ctx context.Context, args json.RawMessage) (Result, error)

func (*ShellExecTool) Preview added in v0.4.0

func (s *ShellExecTool) Preview(ctx context.Context, args json.RawMessage) (Preview, error)

Preview returns command execution metadata without running the command.

func (*ShellExecTool) RequiresApproval

func (s *ShellExecTool) RequiresApproval() bool

func (*ShellExecTool) Spec

func (s *ShellExecTool) Spec() ToolSpec

type ShellGuard added in v0.5.0

type ShellGuard struct {
	// SensitiveMatcher flags sensitive paths. May be nil; redaction still applies.
	SensitiveMatcher *ignore.SensitiveMatcher
	// RedactSecretOutput enables redaction of secret-shaped values in output.
	RedactSecretOutput bool
}

ShellGuard redacts secrets from shell output and warns about sensitive paths. It does not sandbox the shell. SECURITY: file tools stay confined via ValidatePath; the shell is advisory-only.

func (*ShellGuard) FlagSensitivePaths added in v0.5.0

func (g *ShellGuard) FlagSensitivePaths(command string) []string

FlagSensitivePaths returns sensitive paths referenced by a command for the approval preview. Advisory only.

func (*ShellGuard) RedactSecrets added in v0.5.0

func (g *ShellGuard) RedactSecrets(output string) (string, []string)

RedactSecrets masks secret-shaped values. With redaction disabled the text is unchanged.

type Tool

type Tool interface {
	Spec() ToolSpec
	Execute(ctx context.Context, args json.RawMessage) (Result, error)
	RequiresApproval() bool
}

type ToolSpec

type ToolSpec struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	Parameters  json.RawMessage `json:"parameters"`
}

Jump to

Keyboard shortcuts

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