tools

package
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: May 11, 2026 License: MIT Imports: 52 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ShellDefaultTimeoutSec = defaultTimeoutSec
	ShellMaxTimeoutSec     = maxTimeoutSec
)
View Source
const (
	// SkillListingMaxTotal is the character budget for the Available Skills
	// section (not counting the preamble text shared by all tools).
	SkillListingMaxTotal = 4000
	// SkillListingMaxDescPerEntry is the per-skill description character budget.
	SkillListingMaxDescPerEntry = 160
	// SkillListingMaxEntries is the default max skills shown; overflow shows "+N more".
	SkillListingMaxEntries = 32
)

Listing budget constants for the Available Skills section.

View Source
const (
	NameRead         = "Read"
	NameWrite        = "Write"
	NameEdit         = "Edit"
	NameDelete       = "Delete"
	NameGrep         = "Grep"
	NameGlob         = "Glob"
	NameWebFetch     = "WebFetch"
	NameShell        = "Shell"
	NameSpawn        = "Spawn"
	NameSpawnStatus  = "SpawnStatus"
	NameSpawnStop    = "SpawnStop"
	NameLsp          = "Lsp"
	NameTodoWrite    = "TodoWrite"
	NameQuestion     = "Question"
	NameDelegate     = "Delegate"
	NameNotify       = "Notify"
	NameSkill        = "Skill"
	NameHandoff      = "Handoff"
	NameEscalate     = "Escalate"
	NameCancel       = "Cancel"
	NameComplete     = "Complete"
	NameSaveArtifact = "SaveArtifact"
	NameReadArtifact = "ReadArtifact"
)
View Source
const (
	// MaxOutputLines is the maximum number of lines kept in truncated output.
	MaxOutputLines = 2000
	// MaxOutputBytes is the maximum byte length before truncation is triggered.
	MaxOutputBytes = 50 * 1024
	// MaxLineLength is the maximum UTF-8 byte length per output line before
	// per-line truncation (suffix aligned to a valid UTF-8 boundary).
	MaxLineLength = 2000
)
View Source
const MaxReadFileBytes = 50 * 1024 * 1024

MaxReadFileBytes is the maximum file size (50 MiB) that Read will load into memory to avoid OOM when reading very large files. Use offset/limit to read portions of larger files, or delegate to a sub-agent with Grep/Read on specific ranges.

View Source
const MaxReadOutputTokens = 20_000

MaxReadOutputTokens is the approximate token budget for the formatted Read output that is sent back into the conversation. This is intentionally stricter than the file-size gate so large-but-readable files still require paging.

Variables

View Source
var ErrBinaryFile = errors.New("binary file")

Functions

func AgentIDFromContext

func AgentIDFromContext(ctx context.Context) string

AgentIDFromContext extracts the agent ID from the context, or returns "" if absent.

func AppendArtifactGuidance

func AppendArtifactGuidance(content string, truncated TruncateResult, guidance string) string

func BuildSkillListing

func BuildSkillListing(entries []SkillListingEntry, header string) string

BuildSkillListing builds the Available Skills listing section with truncation budgets. The header (e.g. "\n\n## Available Skills\n") is included in the total budget. Returns empty string when no entries remain.

func CleanupSpawnLogs

func CleanupSpawnLogs(sessionDir string) error

func ConcurrencyConflict

func ConcurrencyConflict(a, b ConcurrencyPolicy) bool

func DecodeTextBytesForAgent

func DecodeTextBytesForAgent(data []byte) (string, error)

DecodeTextBytesForAgent exposes file decoding for agent-side diff helpers.

func DecodeToolStringArgForAgent

func DecodeToolStringArgForAgent(raw string) (string, error)

DecodeToolStringArgForAgent exposes tool-argument decoding for agent-side helpers.

func ExecuteSpawnForTest

func ExecuteSpawnForTest(ctx context.Context, kind string, command, description string, timeout *int) (string, error)

func ExecuteSpawnForTestWithShell

func ExecuteSpawnForTestWithShell(ctx context.Context, kind string, command, description string, timeout *int, shellType string) (string, error)

func FormatNonInteractiveRuntimeError added in v0.5.2

func FormatNonInteractiveRuntimeError(toolName, command string, err error, output string) error

func GenerateUnifiedDiff

func GenerateUnifiedDiff(oldContent, newContent, filename string) string

GenerateUnifiedDiff produces a unified-diff string comparing oldContent to newContent. filename is used only in the header lines. Returns an empty string when there are no differences. The edit script is computed on the middle region after stripping common prefix/suffix lines so typical small edits in large files avoid a full-file LCS. Very long diff output is truncated after maxDiffOutputLines with a trailing notice.

func IsBinaryExtension

func IsBinaryExtension(name string) bool

IsBinaryExtension reports whether the given filename has an extension that Chord always treats as binary (non-text, non-referenceable). Comparison is case-insensitive. Files with no extension return false — they need a real content sniff (via looksBinary) to decide.

func IsFileMutation added in v0.2.0

func IsFileMutation(name string) bool

IsFileMutation reports whether the tool mutates files in the workspace.

func IsReadLike added in v0.2.0

func IsReadLike(name string) bool

IsReadLike reports whether tool output should be treated as read-only context that can be compacted into a re-runnable summary.

func IsSkippedDirName

func IsSkippedDirName(name string) bool

IsSkippedDirName reports whether Chord always excludes a directory with this basename from Grep/Glob/@-mention walks (e.g. VCS metadata, tool caches, compiled-bytecode dirs).

func ListArtifactFiles

func ListArtifactFiles(sessionDir string) ([]string, error)

func NormalizeDeletePaths

func NormalizeDeletePaths(paths []string) []string

NormalizeDeletePaths applies trimming, filepath.Clean, de-duplication, and a stable lexical sort. Empty path entries are discarded.

func NormalizeEmptySuccessOutput

func NormalizeEmptySuccessOutput(toolName, result string, err error) string

func ReadAndDecodeTextFile

func ReadAndDecodeTextFile(path string) (decodedText, []byte, error)

ReadAndDecodeTextFile reads a text file and returns both decoded text and raw bytes. Use this only when the caller truly needs the raw bytes (for example, to report byte counts).

func ReadDecodedTextFile

func ReadDecodedTextFile(path string) (decodedText, error)

ReadDecodedTextFile reads and decodes a text file, reusing the two-level cache. On path+hash cache hit it returns without re-reading the file body.

func ResetSpawnRegistryForTest

func ResetSpawnRegistryForTest() func()

func ResolveSessionArtifactPath added in v0.2.0

func ResolveSessionArtifactPath(sessionDir, relPath string) (string, error)

func SessionDirFromContext

func SessionDirFromContext(ctx context.Context) string

SessionDirFromContext extracts the session directory from the context, or returns "" if absent.

func ShouldExpandResult added in v0.2.0

func ShouldExpandResult(name string) bool

ShouldExpandResult reports whether TUI should expand the tool result by default.

func StopAllSpawnedForAgent

func StopAllSpawnedForAgent(agentID string, reason string) int

func StopAllSpawnedForSessionSwitch

func StopAllSpawnedForSessionSwitch() int

func StopAllSpawnedForShutdown

func StopAllSpawnedForShutdown() int

func TaskIDFromContext

func TaskIDFromContext(ctx context.Context) string

TaskIDFromContext extracts the task ID from the context, or returns "" if absent.

func TruncateSkillDesc

func TruncateSkillDesc(desc string) string

TruncateSkillDesc truncates a skill description to fit the per-entry budget.

func ValidateToolArgs

func ValidateToolArgs(tool Tool, args json.RawMessage) error

ValidateToolArgs checks whether raw JSON arguments conform to a tool's declared input schema at a basic structural level.

func WithAgentID

func WithAgentID(ctx context.Context, id string) context.Context

WithAgentID returns a new context that carries the given agent ID.

func WithEventSender

func WithEventSender(ctx context.Context, sender EventSender) context.Context

WithEventSender returns a new context that carries the given event sender.

func WithSessionDir

func WithSessionDir(ctx context.Context, dir string) context.Context

WithSessionDir returns a new context that carries the session directory path.

func WithTaskID

func WithTaskID(ctx context.Context, id string) context.Context

WithTaskID returns a new context that carries the current task ID.

func WithToolProgressReporter

func WithToolProgressReporter(ctx context.Context, reporter ToolProgressReporter) context.Context

WithToolProgressReporter returns a new context that carries the given progress reporter.

Types

type AgentInfo

type AgentInfo struct {
	Name             string
	Description      string
	Capabilities     []string
	PreferredTasks   []string
	WriteMode        string
	DelegationPolicy string
}

AgentInfo holds the name and description of an available SubAgent type.

type ArtifactRef added in v0.2.0

type ArtifactRef struct {
	ID             string `json:"id,omitempty"`
	Type           string `json:"type,omitempty"`
	RelPath        string `json:"rel_path,omitempty"`
	Path           string `json:"path,omitempty"`
	Description    string `json:"description,omitempty"`
	MimeType       string `json:"mime_type,omitempty"`
	SizeBytes      int64  `json:"size_bytes,omitempty"`
	CreatedByTask  string `json:"created_by_task,omitempty"`
	CreatedByAgent string `json:"created_by_agent,omitempty"`
}

ArtifactRef is a typed reference to a runtime-managed artifact. Paths are session-relative and must stay within the active session directory.

func NormalizeArtifactRef added in v0.2.0

func NormalizeArtifactRef(ref ArtifactRef) ArtifactRef

func NormalizeArtifactRefs added in v0.2.0

func NormalizeArtifactRefs(refs []ArtifactRef) []ArtifactRef

type AvailableTool

type AvailableTool interface {
	Tool
	IsAvailable() bool
}

AvailableTool can opt out of registration in the LLM-visible tool list even if it is present in the registry. This is used for tools whose backing runtime provider is not yet configured.

type CancelTool

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

func NewCancelTool

func NewCancelTool(stopper SubAgentStopper) *CancelTool

func (CancelTool) Description

func (CancelTool) Description() string

func (*CancelTool) Execute

func (t *CancelTool) Execute(ctx context.Context, raw json.RawMessage) (string, error)

func (CancelTool) IsReadOnly

func (CancelTool) IsReadOnly() bool

func (CancelTool) Name

func (CancelTool) Name() string

func (CancelTool) Parameters

func (CancelTool) Parameters() map[string]any

func (CancelTool) VisibleWithRuleset

func (CancelTool) VisibleWithRuleset(ruleset permission.Ruleset) bool

type CompleteTool

type CompleteTool struct{}

CompleteTool marks the current task as complete. It is only available to SubAgents. In normal flow, this tool is intercepted by SubAgent.handleLLMResponse (which parses the summary and sends EventAgentDone); Execute is a fallback that returns a placeholder string.

func (CompleteTool) Description

func (CompleteTool) Description() string

func (CompleteTool) Execute

func (CompleteTool) Execute(_ context.Context, raw json.RawMessage) (string, error)

func (CompleteTool) IsReadOnly

func (CompleteTool) IsReadOnly() bool

func (CompleteTool) Name

func (CompleteTool) Name() string

func (CompleteTool) Parameters

func (CompleteTool) Parameters() map[string]any

type ConcurrencyAwareTool

type ConcurrencyAwareTool interface {
	Tool
	ConcurrencyPolicy(args json.RawMessage) ConcurrencyPolicy
}

ConcurrencyAwareTool can classify a finalized tool call for safe batching. Unknown tools are treated conservatively as exclusive by the agent runtime.

type ConcurrencyMode

type ConcurrencyMode string
const (
	ConcurrencyModeExclusive ConcurrencyMode = "exclusive"
	ConcurrencyModeRead      ConcurrencyMode = "read"
	ConcurrencyModeWrite     ConcurrencyMode = "write"
)

type ConcurrencyPolicy

type ConcurrencyPolicy struct {
	Resource             string
	Mode                 ConcurrencyMode
	AbortSiblingsOnError bool
}

func PolicyForTool

func PolicyForTool(registry *Registry, toolName string, args json.RawMessage) ConcurrencyPolicy

type DelegateTool

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

DelegateTool delegates a task to a SubAgent for parallel execution. Only available to the MainAgent.

func NewDelegateTool

func NewDelegateTool(creator SubAgentCreator) *DelegateTool

NewDelegateTool creates a DelegateTool backed by the given SubAgentCreator.

func (DelegateTool) Description

func (DelegateTool) Description() string

func (*DelegateTool) Execute

func (t *DelegateTool) Execute(ctx context.Context, raw json.RawMessage) (string, error)

func (*DelegateTool) IsAvailable

func (t *DelegateTool) IsAvailable() bool

IsAvailable reports whether the DelegateTool should be registered. Returns false when no subagent-mode agents are configured, so the tool is omitted entirely from the LLM's tool list.

func (DelegateTool) IsReadOnly

func (DelegateTool) IsReadOnly() bool

func (DelegateTool) Name

func (DelegateTool) Name() string

func (*DelegateTool) Parameters

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

type DeleteRequest

type DeleteRequest struct {
	Paths  []string `json:"paths"`
	Reason string   `json:"reason"`
}

DeleteRequest is the normalized Delete tool input.

func DecodeDeleteRequest

func DecodeDeleteRequest(raw json.RawMessage) (DeleteRequest, error)

DecodeDeleteRequest parses, validates, cleans, de-duplicates, and sorts the Delete tool arguments. Unknown fields are rejected.

type DeleteResultGroups

type DeleteResultGroups struct {
	Deleted       []string
	AlreadyAbsent []string
	Blocked       []string
	Failed        []string
	NotAttempted  []string
}

DeleteResultGroups parses the structured Delete tool result text.

func ParseDeleteResult

func ParseDeleteResult(text string) DeleteResultGroups

ParseDeleteResult extracts grouped path lists from Delete tool output.

type DeleteTool

type DeleteTool struct {
	LSP *lsp.Manager // nil when LSP not configured
}

DeleteTool removes one or more explicit files or symlinks from disk. If LSP is set, it closes matching documents in language servers and clears touched-file tracking for deleted or already-absent paths.

func (DeleteTool) ConcurrencyPolicy

func (DeleteTool) ConcurrencyPolicy(args json.RawMessage) ConcurrencyPolicy

func (DeleteTool) Description

func (t DeleteTool) Description() string

func (DeleteTool) Execute

func (t DeleteTool) Execute(ctx context.Context, raw json.RawMessage) (string, error)

func (DeleteTool) IsReadOnly

func (t DeleteTool) IsReadOnly() bool

func (DeleteTool) Name

func (t DeleteTool) Name() string

func (DeleteTool) Parameters

func (t DeleteTool) Parameters() map[string]any

type DescriptiveTool

type DescriptiveTool interface {
	Tool
	DescriptionForTools(visible map[string]struct{}) string
}

DescriptiveTool can tailor its model-facing description using the current registry surface. The registry passes the visible tool names that will be exposed to the model in the current session/role.

type DiffSummary

type DiffSummary struct {
	Text    string
	Added   int
	Removed int
}

DiffSummary carries both the rendered unified diff (possibly truncated) and the exact total add/remove counts computed from the full edit script.

func GenerateUnifiedDiffSummary

func GenerateUnifiedDiffSummary(oldContent, newContent, filename string) DiffSummary

GenerateUnifiedDiffSummary returns the rendered unified diff plus the exact full add/remove counts before any maxDiffOutputLines truncation is applied.

type EditTool

type EditTool struct {
	LSP *lsp.Manager // nil when LSP not configured
}

EditTool performs exact string replacements in files. If LSP is set, notifies LSP of the change after a successful edit.

func (EditTool) ConcurrencyPolicy

func (EditTool) ConcurrencyPolicy(args json.RawMessage) ConcurrencyPolicy

func (EditTool) Description

func (t EditTool) Description() string

func (EditTool) Execute

func (t EditTool) Execute(ctx context.Context, raw json.RawMessage) (string, error)

func (EditTool) IsReadOnly

func (t EditTool) IsReadOnly() bool

func (EditTool) Name

func (t EditTool) Name() string

func (EditTool) Parameters

func (t EditTool) Parameters() map[string]any

type EscalateTool

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

EscalateTool requests intervention from the direct owner / coordination chain. Only available to SubAgents. Use when the SubAgent is blocked and needs parent-agent coordination or escalation back to MainAgent.

func NewEscalateTool

func NewEscalateTool(sender EventSender) *EscalateTool

NewEscalateTool creates an EscalateTool with the given EventSender.

func (EscalateTool) Description

func (EscalateTool) Description() string

func (*EscalateTool) Execute

func (t *EscalateTool) Execute(ctx context.Context, raw json.RawMessage) (string, error)

func (EscalateTool) IsReadOnly

func (EscalateTool) IsReadOnly() bool

func (EscalateTool) Name

func (EscalateTool) Name() string

func (EscalateTool) Parameters

func (EscalateTool) Parameters() map[string]any

type EventSender

type EventSender interface {
	// SendAgentEvent sends a typed event from a SubAgent to the MainAgent.
	// eventType identifies the kind of event (e.g. "escalate", "agent_notify").
	// sourceID is the calling agent's instance ID.
	// payload carries event-specific data.
	SendAgentEvent(eventType, sourceID string, payload any)
}

EventSender is the interface for sending events to MainAgent without importing the agent package (avoiding circular imports). NotifyTool and EscalateTool use this interface.

func EventSenderFromContext

func EventSenderFromContext(ctx context.Context) EventSender

EventSenderFromContext extracts the event sender from the context, or returns nil if absent.

type GitIgnoreMatcher

type GitIgnoreMatcher = gitIgnoreMatcher

GitIgnoreMatcher is the exported type used by TUI @-mention scanning.

func NewGitIgnoreMatcher

func NewGitIgnoreMatcher(dir string) *GitIgnoreMatcher

NewGitIgnoreMatcher loads .gitignore patterns from dir. Returns nil when no .gitignore exists or it cannot be read. Safe to call on a nil result: the Match method guards against a nil receiver.

type GlobTool

type GlobTool struct{}

GlobTool finds files matching a glob pattern with support for ** recursive matching.

func (GlobTool) ConcurrencyPolicy

func (GlobTool) ConcurrencyPolicy(args json.RawMessage) ConcurrencyPolicy

func (GlobTool) Description

func (GlobTool) Description() string

func (GlobTool) Execute

func (GlobTool) Execute(_ context.Context, raw json.RawMessage) (string, error)

func (GlobTool) IsReadOnly

func (GlobTool) IsReadOnly() bool

func (GlobTool) Name

func (GlobTool) Name() string

func (GlobTool) Parameters

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

type GrepTool

type GrepTool struct{}

GrepTool searches file contents using a regex pattern.

func (GrepTool) ConcurrencyPolicy

func (GrepTool) ConcurrencyPolicy(args json.RawMessage) ConcurrencyPolicy

func (GrepTool) Description

func (GrepTool) Description() string

func (GrepTool) Execute

func (GrepTool) Execute(ctx context.Context, raw json.RawMessage) (string, error)

func (GrepTool) IsReadOnly

func (GrepTool) IsReadOnly() bool

func (GrepTool) Name

func (GrepTool) Name() string

func (GrepTool) Parameters

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

type HandoffTool

type HandoffTool struct{}

HandoffTool signals that plan generation is complete and hands off control to another agent for execution. Called by the MainAgent in planner role after writing the plan document. The target agent is chosen by the user in the TUI (default: builder).

func (HandoffTool) Description

func (HandoffTool) Description() string

func (HandoffTool) Execute

func (HandoffTool) Execute(ctx context.Context, raw json.RawMessage) (string, error)

func (HandoffTool) IsReadOnly

func (HandoffTool) IsReadOnly() bool

func (HandoffTool) Name

func (HandoffTool) Name() string

func (HandoffTool) Parameters

func (HandoffTool) Parameters() map[string]any

type InlineSegment

type InlineSegment struct {
	Text string
	Kind string
}

InlineSegment is one segment of an inline (character-level) diff. Kind is "equal", "delete", or "insert".

func InlineDiff

func InlineDiff(old, new string) (oldSegs, newSegs []InlineSegment)

InlineDiff computes a token-aware diff between old and new and returns segments for the old line (equal + delete) and new line (equal + insert). It aligns on coarse code-friendly tokens first, then refines matching changed tokens with rune-level diff so the TUI gets stable structure plus precise intra-token highlighting.

type InteractiveCommandFinding added in v0.5.1

type InteractiveCommandFinding struct {
	Command string
	Reason  string
	Hint    string
}

func DetectInteractiveShellCommand added in v0.5.1

func DetectInteractiveShellCommand(command string) *InteractiveCommandFinding

func (*InteractiveCommandFinding) Error added in v0.5.1

func (f *InteractiveCommandFinding) Error() error

type LspTool

type LspTool struct {
	LSP *lsp.Manager // nil when LSP not configured
}

LspTool exposes LSP code intelligence (definition, find references, implementations) to the agent.

func (LspTool) ConcurrencyPolicy

func (LspTool) ConcurrencyPolicy(args json.RawMessage) ConcurrencyPolicy

func (LspTool) Description

func (t LspTool) Description() string

func (LspTool) Execute

func (t LspTool) Execute(ctx context.Context, raw json.RawMessage) (string, error)

func (LspTool) IsReadOnly

func (t LspTool) IsReadOnly() bool

func (LspTool) Name

func (t LspTool) Name() string

func (LspTool) Parameters

func (t LspTool) Parameters() map[string]any

type NonInteractiveRuntimeFinding added in v0.5.2

type NonInteractiveRuntimeFinding struct {
	Reason string
}

func ClassifyNonInteractiveRuntimeFailure added in v0.5.2

func ClassifyNonInteractiveRuntimeFailure(command string, err error, output string) *NonInteractiveRuntimeFinding

type NotifyTool

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

func NewNotifyTool

func NewNotifyTool(sender EventSender, messenger SubAgentMessenger, allowOwner, allowTarget bool) *NotifyTool

func (*NotifyTool) Description

func (t *NotifyTool) Description() string

func (*NotifyTool) Execute

func (t *NotifyTool) Execute(ctx context.Context, raw json.RawMessage) (string, error)

func (*NotifyTool) IsAvailable

func (t *NotifyTool) IsAvailable() bool

func (NotifyTool) IsReadOnly

func (NotifyTool) IsReadOnly() bool

func (NotifyTool) Name

func (NotifyTool) Name() string

func (*NotifyTool) Parameters

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

func (*NotifyTool) VisibleWithRuleset

func (t *NotifyTool) VisibleWithRuleset(ruleset permission.Ruleset) bool

type QuestionAnswer

type QuestionAnswer struct {
	Header   string   `json:"header"`
	Selected []string `json:"selected"` // selected labels or free-text entries
}

QuestionAnswer holds the user's response to one question.

type QuestionFunc

type QuestionFunc func(ctx context.Context, questions []QuestionItem) ([]QuestionAnswer, error)

QuestionFunc is the callback invoked when the Question tool needs user input. It presents questions to the user one at a time and returns their answers. Each answer is a slice of selected option labels (or a single free-text entry).

type QuestionItem

type QuestionItem struct {
	Question string           `json:"question"`
	Header   string           `json:"header"`
	Options  []QuestionOption `json:"options,omitempty"`
	Multiple bool             `json:"multiple,omitempty"`
}

QuestionItem represents a single question to ask the user.

type QuestionOption

type QuestionOption struct {
	Label       string `json:"label"`
	Description string `json:"description"`
}

QuestionOption represents one selectable choice.

type QuestionTool

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

QuestionTool asks the user one or more questions and returns their answers. It is read-only (does not mutate files or processes) and integrates with the TUI via a QuestionFunc callback injected at creation time.

func NewQuestionTool

func NewQuestionTool(fn QuestionFunc) *QuestionTool

NewQuestionTool creates a QuestionTool with the given callback. The callback is responsible for presenting questions to the user (typically via TUI channels) and collecting answers.

func (QuestionTool) Description

func (QuestionTool) Description() string

func (*QuestionTool) Execute

func (t *QuestionTool) Execute(ctx context.Context, raw json.RawMessage) (string, error)

func (QuestionTool) IsReadOnly

func (QuestionTool) IsReadOnly() bool

func (QuestionTool) Name

func (QuestionTool) Name() string

func (QuestionTool) Parameters

func (QuestionTool) Parameters() map[string]any

type ReadArtifactTool added in v0.2.0

type ReadArtifactTool struct{}

ReadArtifactTool reads only artifacts under the active session artifacts dir.

func (ReadArtifactTool) Description added in v0.2.0

func (ReadArtifactTool) Description() string

func (ReadArtifactTool) Execute added in v0.2.0

func (ReadArtifactTool) IsReadOnly added in v0.2.0

func (ReadArtifactTool) IsReadOnly() bool

func (ReadArtifactTool) Name added in v0.2.0

func (ReadArtifactTool) Name() string

func (ReadArtifactTool) Parameters added in v0.2.0

func (ReadArtifactTool) Parameters() map[string]any

type ReadTool

type ReadTool struct {
	LSP lspStarter // nil when LSP not configured
}

ReadTool reads file contents with optional offset/limit paging.

func (ReadTool) ConcurrencyPolicy

func (ReadTool) ConcurrencyPolicy(args json.RawMessage) ConcurrencyPolicy

func (ReadTool) Description

func (ReadTool) Description() string

func (ReadTool) Execute

func (t ReadTool) Execute(ctx context.Context, raw json.RawMessage) (string, error)

func (ReadTool) IsReadOnly

func (ReadTool) IsReadOnly() bool

func (ReadTool) Name

func (ReadTool) Name() string

func (ReadTool) Parameters

func (ReadTool) Parameters() map[string]any

type Registry

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

Registry stores and manages a collection of tools. All methods are safe for concurrent use.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates an empty tool registry.

func (*Registry) Clone

func (r *Registry) Clone() *Registry

Clone returns a shallow copy of the registry. The new registry contains the same tool instances as the original; callers can Register additional tools on the clone without affecting the original.

func (*Registry) Execute

func (r *Registry) Execute(ctx context.Context, name string, args json.RawMessage) (string, error)

Execute looks up a tool by name and runs it. Returns an error if the tool is not found.

func (*Registry) Get

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

Get looks up a tool by name.

func (*Registry) ListDefinitions

func (r *Registry) ListDefinitions() []message.ToolDefinition

ListDefinitions converts every registered tool into a message.ToolDefinition suitable for sending to an LLM API.

func (*Registry) ListTools

func (r *Registry) ListTools() []Tool

ListTools returns all registered tools sorted alphabetically by name.

func (*Registry) Register

func (r *Registry) Register(tool Tool)

Register adds a tool to the registry. If a tool with the same name already exists it is silently replaced.

func (*Registry) Unregister added in v0.5.1

func (r *Registry) Unregister(name string)

Unregister removes a tool from the registry by name.

func (*Registry) UnregisterPrefix added in v0.5.1

func (r *Registry) UnregisterPrefix(prefix string) int

UnregisterPrefix removes every tool whose name has the given prefix. It returns the number of removed tools.

type RepetitionDetector

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

RepetitionDetector prevents tool call loops by using two complementary strategies:

  1. Consecutive-repetition guard: rejects a call if the exact same (name, args) has been seen consecutively maxRepeat times in a row.

  2. Sliding-window loop guard: maintains a fixed-size window of recent call signatures (SHA-256 hashes). If the same signature appears more than windowMaxHits times within the window, the call is rejected. This catches A→B→A→B alternating loops that the consecutive guard misses.

func NewRepetitionDetector

func NewRepetitionDetector() *RepetitionDetector

NewRepetitionDetector creates a detector that rejects the 3rd consecutive identical tool call (i.e., allows at most 2 in a row), and also rejects any tool call whose SHA-256 signature appears more than 5 times in the last 10 calls (sliding-window loop detection).

func NewRepetitionDetectorFull

func NewRepetitionDetectorFull(maxRepeat, windowSize, windowMaxHits int) *RepetitionDetector

NewRepetitionDetectorFull creates a detector with fully custom parameters.

  • maxRepeat: max consecutive identical calls allowed before rejection.
  • windowSize: number of recent calls tracked in the sliding window.
  • windowMaxHits: max occurrences of one signature within the window before rejection.

func NewRepetitionDetectorWithMax

func NewRepetitionDetectorWithMax(max int) *RepetitionDetector

NewRepetitionDetectorWithMax creates a detector with a custom consecutive maximum. The sliding-window parameters use defaults.

func (*RepetitionDetector) Check

func (d *RepetitionDetector) Check(name string, args json.RawMessage) bool

Check returns true if the tool call is allowed to proceed, false if it should be rejected due to detected looping.

Two rejection conditions:

  1. The same (name, args) pair has appeared consecutively maxRepeat times.
  2. The SHA-256 hash of this call appears windowMaxHits or more times within the sliding window of the last windowSize calls.

func (*RepetitionDetector) Reset

func (d *RepetitionDetector) Reset()

Reset clears all state, as if the detector were newly created.

type RulesetAwareVisibilityTool

type RulesetAwareVisibilityTool interface {
	Tool
	VisibleWithRuleset(ruleset permission.Ruleset) bool
}

RulesetAwareVisibilityTool can further refine whether a registered tool should be exposed to the model under the current ruleset. This is used for grouped capabilities where one tool's visibility depends on another tool's permission family.

type SaveArtifactTool added in v0.2.0

type SaveArtifactTool struct{}

SaveArtifactTool writes a runtime artifact under the active session artifacts dir.

func (SaveArtifactTool) Description added in v0.2.0

func (SaveArtifactTool) Description() string

func (SaveArtifactTool) Execute added in v0.2.0

func (SaveArtifactTool) IsReadOnly added in v0.2.0

func (SaveArtifactTool) IsReadOnly() bool

func (SaveArtifactTool) Name added in v0.2.0

func (SaveArtifactTool) Name() string

func (SaveArtifactTool) Parameters added in v0.2.0

func (SaveArtifactTool) Parameters() map[string]any

type ShellAnalysis added in v0.5.2

type ShellAnalysis struct {
	RawCommand  string
	Subcommands []ShellSubcommand
	ParseMode   string
}

ShellAnalysis describes the static shape of a Shell command string.

func AnalyzeShellCommand added in v0.5.2

func AnalyzeShellCommand(command string) (ShellAnalysis, error)

AnalyzeShellCommand parses a Shell command and extracts simple subcommands in source order. Function declaration bodies are skipped so permission matching does not treat dormant helper definitions as immediately executing commands.

type ShellSubcommand added in v0.5.2

type ShellSubcommand struct {
	Source string
	Kind   string
	Index  int
}

ShellSubcommand is one atomic simple command extracted from a Shell command.

type ShellTimeoutInfo added in v0.5.2

type ShellTimeoutInfo struct {
	RequestedSec int
	EffectiveSec int
	HasRequested bool
	HasLimit     bool
	UsesDefault  bool
	Clamped      bool
}

func ResolveShellTimeout added in v0.5.2

func ResolveShellTimeout(timeout *int) ShellTimeoutInfo

func ResolveShellTimeoutValue added in v0.5.2

func ResolveShellTimeoutValue(requestedSec int, hasTimeout bool) ShellTimeoutInfo

func ResolveSpawnTimeout

func ResolveSpawnTimeout(timeout *int) ShellTimeoutInfo

func ResolveSpawnTimeoutValue

func ResolveSpawnTimeoutValue(requestedSec int, hasTimeout bool) ShellTimeoutInfo

type ShellTool added in v0.5.2

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

ShellTool executes shell commands.

func NewShellTool added in v0.5.2

func NewShellTool(shellType string) ShellTool

NewShellTool creates a ShellTool with the detected shell type.

func (ShellTool) ConcurrencyPolicy added in v0.5.2

func (ShellTool) ConcurrencyPolicy(_ json.RawMessage) ConcurrencyPolicy

func (ShellTool) Description added in v0.5.2

func (t ShellTool) Description() string

func (ShellTool) DescriptionForTools added in v0.5.2

func (t ShellTool) DescriptionForTools(visible map[string]struct{}) string

func (ShellTool) Execute added in v0.5.2

func (t ShellTool) Execute(ctx context.Context, raw json.RawMessage) (string, error)

func (ShellTool) IsReadOnly added in v0.5.2

func (ShellTool) IsReadOnly() bool

func (ShellTool) Name added in v0.5.2

func (ShellTool) Name() string

func (ShellTool) Parameters added in v0.5.2

func (ShellTool) Parameters() map[string]any

type SkillListingEntry

type SkillListingEntry struct {
	Name, Desc string
}

SkillListingEntry is a lightweight name+description pair used by the shared listing builder. Both tools.SkillTool and agent prompt blocks can use it.

type SkillProvider

type SkillProvider interface {
	ListSkills() []*skill.Meta
	InvokedSkills() []*skill.Meta
	MarkSkillInvoked(meta *skill.Meta)
	LoadSkill(name string) (*skill.Skill, error)
}

SkillProvider exposes discovered skills, invoked skill state, and can load a skill's full content on demand.

type SkillTool

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

SkillTool loads a skill's full instructions on demand.

func NewSkillTool

func NewSkillTool(provider SkillProvider) *SkillTool

func (SkillTool) Description

func (SkillTool) Description() string

func (SkillTool) DescriptionForTools

func (t SkillTool) DescriptionForTools(_ map[string]struct{}) string

func (SkillTool) Execute

func (t SkillTool) Execute(_ context.Context, raw json.RawMessage) (string, error)

func (SkillTool) IsAvailable

func (t SkillTool) IsAvailable() bool

func (SkillTool) IsReadOnly

func (SkillTool) IsReadOnly() bool

func (SkillTool) Name

func (SkillTool) Name() string

func (SkillTool) Parameters

func (SkillTool) Parameters() map[string]any

type SpawnFinishedPayload

type SpawnFinishedPayload struct {
	BackgroundID  string
	AgentID       string
	Kind          string
	Status        string
	Command       string
	Description   string
	MaxRuntimeSec int
	Message       string
	LogFile       string
}

func (*SpawnFinishedPayload) EffectiveID

func (p *SpawnFinishedPayload) EffectiveID() string

type SpawnRegistry

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

type SpawnState

type SpawnState struct {
	ID            string
	AgentID       string
	Kind          string
	Description   string
	Command       string
	LogFile       string
	StartedAt     time.Time
	MaxRuntimeSec int
	Status        string
	FinishedAt    time.Time
}

func SnapshotSpawnedProcesses

func SnapshotSpawnedProcesses() []SpawnState

type SpawnStatusTool

type SpawnStatusTool struct{}

SpawnStatusTool reads lightweight lifecycle state for a background process started by Spawn.

func (SpawnStatusTool) Description

func (SpawnStatusTool) Description() string

func (SpawnStatusTool) Execute

func (SpawnStatusTool) IsReadOnly

func (SpawnStatusTool) IsReadOnly() bool

func (SpawnStatusTool) Name

func (SpawnStatusTool) Name() string

func (SpawnStatusTool) Parameters

func (SpawnStatusTool) Parameters() map[string]any

type SpawnStopTool

type SpawnStopTool struct{}

SpawnStopTool stops a background process started by Spawn.

func (SpawnStopTool) Description

func (SpawnStopTool) Description() string

func (SpawnStopTool) Execute

func (SpawnStopTool) IsReadOnly

func (SpawnStopTool) IsReadOnly() bool

func (SpawnStopTool) Name

func (SpawnStopTool) Name() string

func (SpawnStopTool) Parameters

func (SpawnStopTool) Parameters() map[string]any

type SpawnTool

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

SpawnTool starts a background process that runs independently of the current turn.

func NewSpawnTool

func NewSpawnTool(shellType string) SpawnTool

NewSpawnTool creates a SpawnTool with the detected shell type.

func (SpawnTool) ConcurrencyPolicy

func (SpawnTool) ConcurrencyPolicy(_ json.RawMessage) ConcurrencyPolicy

func (SpawnTool) Description

func (SpawnTool) Description() string

func (SpawnTool) DescriptionForTools

func (SpawnTool) DescriptionForTools(visible map[string]struct{}) string

func (SpawnTool) Execute

func (t SpawnTool) Execute(ctx context.Context, raw json.RawMessage) (string, error)

func (SpawnTool) IsReadOnly

func (SpawnTool) IsReadOnly() bool

func (SpawnTool) Name

func (SpawnTool) Name() string

func (SpawnTool) Parameters

func (SpawnTool) Parameters() map[string]any

type SubAgentCreator

type SubAgentCreator interface {
	// CreateSubAgent creates a new SubAgent for the given task.
	// Returns a structured handle for the created worker, or an error.
	CreateSubAgent(ctx context.Context, description, agentType string, planTaskRef, semanticTaskKey string, expectedWriteScope WriteScope) (TaskHandle, error)
	// AvailableSubAgents returns the list of subagent-mode agents that can be
	// used with the Delegate tool. Used to populate the agent_type description.
	AvailableSubAgents() []AgentInfo
}

SubAgentCreator is the interface used by TaskTool to create SubAgents. Defined here (in the tools package) to avoid circular imports — the agent package imports tools, so tools cannot import agent. MainAgent implements this interface and is injected at construction time.

type SubAgentMessenger

type SubAgentMessenger interface {
	NotifySubAgent(ctx context.Context, taskID, message, kind string) (TaskHandle, error)
}

SubAgentMessenger is the interface used by NotifyTool to continue or reply to an existing worker without importing the agent package.

type SubAgentStopper

type SubAgentStopper interface {
	CancelSubAgent(ctx context.Context, taskID, reason string) (TaskHandle, error)
}

SubAgentStopper is the interface used by CancelTool to stop an existing worker without importing the agent package.

type TaskHandle

type TaskHandle struct {
	Status             string     `json:"status"`
	TaskID             string     `json:"task_id"`
	AgentID            string     `json:"agent_id"`
	PreviousAgentID    string     `json:"previous_agent_id,omitempty"`
	Rehydrated         bool       `json:"rehydrated,omitempty"`
	Message            string     `json:"message"`
	PlanTaskRef        string     `json:"plan_task_ref,omitempty"`
	SemanticTaskKey    string     `json:"semantic_task_key,omitempty"`
	ExpectedWriteScope WriteScope `json:"expected_write_scope,omitempty"`
	ScopeConflict      bool       `json:"scope_conflict,omitempty"`
	SuggestedTaskID    string     `json:"suggested_task_id,omitempty"`
	SuggestedAgentID   string     `json:"suggested_agent_id,omitempty"`
	SuggestedAction    string     `json:"suggested_action,omitempty"`
	DuplicateDetected  bool       `json:"duplicate_detected,omitempty"`
}

type TodoItem

type TodoItem struct {
	ID         string `json:"id"`
	Content    string `json:"content"`
	Status     string `json:"status"`
	ActiveForm string `json:"active_form,omitempty"` // current action being performed (e.g. "editing main.go")
}

TodoItem represents a single item in the todo list.

type TodoStore

type TodoStore interface {
	UpdateTodos(todos []TodoItem) error
	GetTodos() []TodoItem
}

TodoStore is the interface for persisting todo state. Defined here to avoid circular imports — MainAgent implements this interface and injects it at construction time.

type TodoWriteTool

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

TodoWriteTool updates the todo list by providing the complete replacement list. Only available to the MainAgent.

func NewTodoWriteTool

func NewTodoWriteTool(store TodoStore) *TodoWriteTool

NewTodoWriteTool creates a TodoWriteTool backed by the given TodoStore.

func (TodoWriteTool) Description

func (TodoWriteTool) Description() string

func (*TodoWriteTool) Execute

func (t *TodoWriteTool) Execute(_ context.Context, raw json.RawMessage) (string, error)

func (TodoWriteTool) IsReadOnly

func (TodoWriteTool) IsReadOnly() bool

func (TodoWriteTool) Name

func (TodoWriteTool) Name() string

func (TodoWriteTool) Parameters

func (TodoWriteTool) Parameters() map[string]any

type Tool

type Tool interface {
	// Name returns the unique identifier for this tool.
	Name() string
	// Description returns a human-readable description of what the tool does.
	Description() string
	// Parameters returns a JSON Schema object describing the tool's input.
	Parameters() map[string]any
	// Execute runs the tool with the given JSON arguments and returns output or an error.
	Execute(ctx context.Context, args json.RawMessage) (string, error)
	// IsReadOnly returns true if the tool does not modify any state (files, processes, etc.).
	IsReadOnly() bool
}

Tool is the interface that every tool must implement.

type ToolProgressReporter

type ToolProgressReporter interface {
	ReportToolProgress(progress ToolProgressSnapshot)
}

ToolProgressReporter delivers progress snapshots for a single visible tool call. Tools should treat the reporter as optional.

func ToolProgressReporterFromContext

func ToolProgressReporterFromContext(ctx context.Context) ToolProgressReporter

ToolProgressReporterFromContext extracts the tool progress reporter from the context, or returns nil if absent.

type ToolProgressSnapshot

type ToolProgressSnapshot struct {
	Label   string
	Current int64
	Total   int64
	Text    string
}

ToolProgressSnapshot is a best-effort, structured progress snapshot emitted by tools that have real progress signals.

type TruncateOptions

type TruncateOptions struct {
	// MaxLines is the maximum number of lines to keep. Defaults to MaxOutputLines (2000).
	MaxLines int
	// MaxBytes is the maximum byte length before truncation is triggered. Defaults to MaxOutputBytes (50KB).
	MaxBytes int
	// Direction controls which part of the output is preserved:
	//   "head"      – keep only the first MaxLines lines
	//   "tail"      – keep only the last MaxLines lines
	//   "head+tail" – keep the first 40% and last 60% of MaxLines (default)
	Direction string
	// ArtifactKey enables idempotent artifact storage. When non-empty, repeated
	// truncation of the same finalized tool result reuses the same file path.
	ArtifactKey string
}

TruncateOptions controls how output truncation is performed.

type TruncateResult

type TruncateResult struct {
	// Content is the (possibly truncated) output text.
	Content string
	// Truncated is true when the original output exceeded limits.
	Truncated bool
	// SavedPath is the file path where the full output was saved, or "" if
	// it was not truncated or the save failed.
	SavedPath string
	// Hint is a truncation notice (without agent-specific suggestions) that
	// callers can use or augment depending on the agent's capabilities.
	Hint string
	// Preview is the model-facing preview kept inline after truncation.
	Preview string
	// ArtifactReference is the stable reference text for the saved full output.
	ArtifactReference string
}

TruncateResult holds the result of truncating tool output.

func TruncateOutputWithOptions

func TruncateOutputWithOptions(output string, sessionDir string, opts TruncateOptions) TruncateResult

TruncateOutputWithOptions truncates output according to the supplied options. When truncation occurs the full output is saved to a file under sessionDir and a notice is included in the returned content.

type WebFetchTool

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

WebFetchTool fetches a URL and returns its content as plain text or Markdown.

func NewWebFetchTool

func NewWebFetchTool(cfg config.WebFetchConfig, globalProxy string) WebFetchTool

func (WebFetchTool) ConcurrencyPolicy

func (WebFetchTool) ConcurrencyPolicy(args json.RawMessage) ConcurrencyPolicy

func (WebFetchTool) Description

func (WebFetchTool) Description() string

func (WebFetchTool) Execute

func (t WebFetchTool) Execute(ctx context.Context, raw json.RawMessage) (string, error)

func (WebFetchTool) IsReadOnly

func (WebFetchTool) IsReadOnly() bool

func (WebFetchTool) Name

func (WebFetchTool) Name() string

func (WebFetchTool) Parameters

func (WebFetchTool) Parameters() map[string]any

type WriteScope

type WriteScope struct {
	Files      []string `json:"files,omitempty"`
	PathPrefix []string `json:"path_prefix,omitempty"`
	Modules    []string `json:"modules,omitempty"`
	ReadOnly   bool     `json:"read_only,omitempty"`
}

func (WriteScope) Empty

func (s WriteScope) Empty() bool

func (WriteScope) Normalized

func (s WriteScope) Normalized() WriteScope

func (WriteScope) Summary

func (s WriteScope) Summary() string

type WriteTool

type WriteTool struct {
	LSP *lsp.Manager // nil when LSP not configured
}

WriteTool writes content to a file, creating parent directories as needed. If LSP is set, notifies LSP of the change after a successful write.

func (WriteTool) ConcurrencyPolicy

func (WriteTool) ConcurrencyPolicy(args json.RawMessage) ConcurrencyPolicy

func (WriteTool) Description

func (t WriteTool) Description() string

func (WriteTool) Execute

func (t WriteTool) Execute(ctx context.Context, raw json.RawMessage) (string, error)

func (WriteTool) IsReadOnly

func (t WriteTool) IsReadOnly() bool

func (WriteTool) Name

func (t WriteTool) Name() string

func (WriteTool) Parameters

func (t WriteTool) Parameters() map[string]any

Jump to

Keyboard shortcuts

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