tools

package
v0.0.60 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: MIT Imports: 46 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func A2ATools added in v0.0.15

func A2ATools(cache *ClientCache) []tool.Tool

A2ATools returns the A2A tools built from the client cache.

func AgentTools

func AgentTools(orch *subagent.Orchestrator, onEvent AgentEventCallback) ([]tool.Tool, error)

AgentTools returns tools that require an orchestrator (the subagent tool). The optional onEvent callback is invoked for each subagent event.

func BashControlTools added in v0.0.53

func BashControlTools(sup *BashSupervisor) ([]tool.Tool, error)

BashControlTools returns the tools for inspecting and stopping commands that the bash tool moved to the background.

They are separate from CoreTools because they are only worth advertising to the model when something can actually background a command — a caller that builds its own supervisor and never streams need not carry the extra schema.

func BuildCompactorCallback added in v0.0.4

func BuildCompactorCallback(cfg CompactorConfig, metrics *CompactMetrics) llmagent.AfterToolCallback

BuildCompactorCallback creates an AfterToolCallback that compacts tool output.

func BuildDedupCallback added in v0.0.48

func BuildDedupCallback(d *ResultDeduper) llmagent.AfterToolCallback

BuildDedupCallback returns an AfterToolCallback that elides byte-identical repeat results. It must run AFTER the compactor so that both calls are compared in their final, post-compaction form — otherwise two results that compact to the same bytes would still be sent twice.

func CoreTools

func CoreTools(sandbox *Sandbox, opts ...CoreOption) ([]tool.Tool, error)

CoreTools returns the core coding agent tools as ADK FunctionTools. The sandbox restricts file-system access to the given root directory.

func DetectImageMIMEType added in v0.0.47

func DetectImageMIMEType(data []byte) string

DetectImageMIMEType sniffs the image's MIME type from its bytes. Returns "application/octet-stream" if it cannot be determined.

func LSPTools

func LSPTools(mgr *lsp.Manager) ([]tool.Tool, error)

LSPTools returns the LSP ADK tools.

func MemoryTools added in v0.0.10

func MemoryTools(store memory.Store) ([]tool.Tool, error)

MemoryTools returns memory search tools that operate against the given store. Returns nil if store is nil (memory disabled).

func NewA2ATool added in v0.0.15

func NewA2ATool(cache *ClientCache) (tool.Tool, error)

NewA2ATool creates the a2a ADK tool using the provided client cache.

func NewSubagentTool added in v0.0.10

func NewSubagentTool(orch *subagent.Orchestrator, onEvent SubagentEventCallback) (tool.Tool, error)

NewSubagentTool creates the subagent ADK tool wired to an Orchestrator.

func SubagentTools added in v0.0.10

func SubagentTools(orch *subagent.Orchestrator, onEvent SubagentEventCallback) ([]tool.Tool, error)

SubagentTools returns tools containing the subagent tool.

Types

type A2AInput added in v0.0.15

type A2AInput struct {
	// AgentName is the name of the configured A2A agent to call.
	AgentName string `json:"agent_name,omitempty"`
	// Prompt is the message to send to the agent.
	Prompt string `json:"prompt,omitempty"`
	// Stream enables streaming response mode.
	Stream bool `json:"stream,omitempty"`
}

A2AInput defines the parameters for the a2a tool.

type A2AOutput added in v0.0.15

type A2AOutput struct {
	Agent  string `json:"agent"`
	Status string `json:"status"` // "completed", "streaming", "failed"
	Result string `json:"result,omitempty"`
	Error  string `json:"error,omitempty"`
}

A2AOutput is the result from an A2A agent call.

type A2AToolset added in v0.0.15

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

A2AToolset implements tool.Toolset for A2A tools.

func NewA2AToolset added in v0.0.15

func NewA2AToolset(cfg *config.A2AConfig) *A2AToolset

NewA2AToolset creates a new A2A toolsets from configuration.

func (*A2AToolset) Name added in v0.0.15

func (t *A2AToolset) Name() string

Name returns the name of the toolset.

func (*A2AToolset) Tools added in v0.0.15

func (t *A2AToolset) Tools(ctx agent.ReadonlyContext) ([]tool.Tool, error)

Tools returns the A2A tools available.

type ActionEntry added in v0.0.15

type ActionEntry struct {
	Title       string `json:"title"`
	Kind        string `json:"kind,omitempty"`
	IsPreferred bool   `json:"isPreferred"`
}

ActionEntry is a single code action for tool output.

type AgentEventCallback

type AgentEventCallback func(agentID, eventType, content string)

AgentEventCallback is the legacy callback type for subagent events. Deprecated: Use SubagentEventCallback instead.

type AgentResult added in v0.0.10

type AgentResult struct {
	Agent     string `json:"agent"`
	AgentID   string `json:"agent_id"`
	Status    string `json:"status"` // "completed", "failed", "timeout"
	Result    string `json:"result"`
	Error     string `json:"error,omitempty"`
	Duration  string `json:"duration"`
	SessionID string `json:"session_id,omitempty"`
}

AgentResult holds the result from a single agent execution.

type BashInput

type BashInput struct {
	// The shell command to execute.
	Command string `json:"command"`
	// Optional timeout in milliseconds. Default: 120000 (2 minutes). Max: 600000 (10 minutes).
	// On expiry the command is moved to the background, not killed.
	Timeout int `json:"timeout,omitempty"`
	// Optional idle timeout in milliseconds. A command that produces no output
	// at all for this long is moved to the background. Default: 90000.
	// Set it higher for commands that are legitimately quiet for a long time.
	IdleTimeout int `json:"idle_timeout,omitempty"`
}

BashInput defines the parameters for the bash tool.

type BashKillInput added in v0.0.53

type BashKillInput struct {
	// Handle returned by a previous bash call.
	Handle string `json:"handle"`
}

BashKillInput identifies a backgrounded command to stop.

type BashOutput

type BashOutput struct {
	// Standard output from the command.
	Stdout string `json:"stdout"`
	// Standard error from the command.
	Stderr string `json:"stderr"`
	// Exit code of the command. -1 when the command has not exited.
	ExitCode int `json:"exit_code"`
	// Running is true when the command outlived its timeout and is still
	// executing in the background.
	Running bool `json:"running,omitempty"`
	// Handle identifies a still-running command for bash_output and bash_kill.
	Handle string `json:"handle,omitempty"`
	// Note explains a non-obvious outcome in terms the model can act on.
	Note string `json:"note,omitempty"`
}

BashOutput contains the result of executing a shell command.

type BashOutputInput added in v0.0.53

type BashOutputInput struct {
	// Handle returned by a previous bash call.
	Handle string `json:"handle"`
	// WaitMs blocks up to this long for new output or for the command to exit,
	// instead of returning immediately. Max 60000. Prefer waiting over polling
	// in a loop.
	WaitMs int `json:"wait_ms,omitempty"`
}

BashOutputInput asks for output accumulated by a backgrounded command.

type BashStatus added in v0.0.53

type BashStatus struct {
	Handle  string `json:"handle"`
	Command string `json:"command"`
	// Running reports whether the command is still executing.
	Running bool `json:"running"`
	// ExitCode is meaningful only once Running is false.
	ExitCode int `json:"exit_code,omitempty"`
	// Stdout and Stderr carry only what was produced since the previous read.
	Stdout string `json:"stdout"`
	Stderr string `json:"stderr"`
	// Elapsed is how long the command has been running in total.
	Elapsed string `json:"elapsed,omitempty"`
	// Idle is how long it has been since the command last produced output.
	Idle string `json:"idle,omitempty"`
	Note string `json:"note,omitempty"`
}

BashStatus is the result of inspecting or stopping a backgrounded command.

type BashSupervisor added in v0.0.53

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

BashSupervisor runs shell commands, streams their output while they run, and owns any command that outlives its foreground call.

The unit of work is a process group, not a process. A shell command is a tree — pipelines, subshells, whatever the model wrote — and every operation here (cancel, timeout, kill) acts on the whole tree. That is the difference between a timeout that works and one that leaves orphans holding pipes.

func NewBashSupervisor added in v0.0.53

func NewBashSupervisor() *BashSupervisor

NewBashSupervisor returns a supervisor with no sink attached. Output is still captured and still streamed internally; it just goes nowhere visible until SetSink is called.

func (*BashSupervisor) Handles added in v0.0.53

func (s *BashSupervisor) Handles() []string

Handles lists the background commands the supervisor currently knows about, oldest first.

func (*BashSupervisor) KillAll added in v0.0.53

func (s *BashSupervisor) KillAll()

KillAll stops every background command. Call it when the session ends: a backgrounded command has no other owner, and leaving it running is precisely the leak this supervisor exists to prevent.

func (*BashSupervisor) Run added in v0.0.53

func (s *BashSupervisor) Run(ctx context.Context, req runRequest) (BashOutput, error)

Run executes command and blocks until it finishes, stalls, or exceeds its timeout.

It returns without killing anything. A command that outruns either limit is handed to the background and reported with a handle, because the alternative — killing it — throws away work the model may still want and tells it nothing about why. The model then chooses: read more output, or kill it.

Canceling ctx (the user pressing Esc, the turn ending) does kill the command and everything it spawned, but only while it is still in the foreground. Once handed off it is the supervisor's, and outlives the turn.

func (*BashSupervisor) SetSink added in v0.0.53

func (s *BashSupervisor) SetSink(sink OutputSink)

SetSink attaches a live-output destination. It may be called after tools are built, which matters because the UI channel the sink writes to is created later in startup than the tool registry.

type ChainItem added in v0.0.10

type ChainItem struct {
	Agent string `json:"agent"`
	Task  string `json:"task"` // supports {previous} and {previous_json}
}

ChainItem defines a single step in chain mode.

type ClientCache added in v0.0.15

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

ClientCache manages A2A client instances for each configured agent. It automatically evicts stale clients when agent configurations change.

func NewClientCache added in v0.0.15

func NewClientCache(cfg *config.A2AConfig) *ClientCache

NewClientCache creates a new ClientCache for the given A2A configuration.

func (*ClientCache) Close added in v0.0.16

func (c *ClientCache) Close()

Close destroys all cached clients and clears the cache.

func (*ClientCache) GetClient added in v0.0.15

func (c *ClientCache) GetClient(ctx context.Context, agentName string) (*a2aclient.Client, error)

GetClient returns or creates an A2A client for the given agent name.

func (*ClientCache) SendMessage added in v0.0.15

func (c *ClientCache) SendMessage(ctx context.Context, agentName string, prompt string, stream bool) A2AOutput

SendMessage sends a message to an A2A agent and returns the result. It handles both streaming and non-streaming modes.

func (*ClientCache) UpdateAgents added in v0.0.16

func (c *ClientCache) UpdateAgents(cfg *config.A2AConfig)

UpdateAgents replaces the agent configuration and evicts stale clients. Clients for removed agents are closed and removed from the cache.

type CompactMetrics added in v0.0.4

type CompactMetrics struct {
	Records []CompactRecord `json:"records"`
	// contains filtered or unexported fields
}

CompactMetrics tracks per-session compaction statistics.

func NewCompactMetrics added in v0.0.4

func NewCompactMetrics() *CompactMetrics

NewCompactMetrics creates a new CompactMetrics instance.

func (*CompactMetrics) FormatStats added in v0.0.4

func (m *CompactMetrics) FormatStats() string

FormatStats returns a human-readable string of compaction stats.

func (*CompactMetrics) Record added in v0.0.4

func (m *CompactMetrics) Record(techniques []string, origSize, compSize int, toolName string)

Record adds a compaction record.

func (*CompactMetrics) Save added in v0.0.4

func (m *CompactMetrics) Save(sessionDir string) error

Save persists metrics to a JSON file in the session directory.

func (*CompactMetrics) Summary added in v0.0.4

func (m *CompactMetrics) Summary() CompactSummary

Summary computes aggregated compaction statistics.

type CompactRecord added in v0.0.4

type CompactRecord struct {
	Tool       string    `json:"tool"`
	Techniques []string  `json:"techniques"`
	OrigSize   int       `json:"orig_size"`
	CompSize   int       `json:"comp_size"`
	Timestamp  time.Time `json:"timestamp"`
}

CompactRecord is a single compaction event.

type CompactResult added in v0.0.4

type CompactResult struct {
	Output     string   // compacted output text
	Techniques []string // techniques applied (e.g., "ansi", "test-aggregate")
	OrigSize   int      // original size in bytes
	CompSize   int      // compacted size in bytes
}

CompactResult is returned by each compaction pipeline.

type CompactSummary added in v0.0.4

type CompactSummary struct {
	TotalOrig  int                       `json:"total_orig"`
	TotalComp  int                       `json:"total_comp"`
	SavingsPct float64                   `json:"savings_pct"`
	ByTool     map[string]ToolCompactSum `json:"by_tool"`
}

CompactSummary provides aggregated compaction statistics.

type CompactorConfig added in v0.0.4

type CompactorConfig struct {
	Enabled               bool   `json:"enabled"`
	StripAnsi             bool   `json:"strip_ansi"`
	AggregateTestOutput   bool   `json:"aggregate_test_output"`
	FilterBuildOutput     bool   `json:"filter_build_output"`
	CompactGitOutput      bool   `json:"compact_git_output"`
	AggregateLinterOutput bool   `json:"aggregate_linter_output"`
	GroupSearchOutput     bool   `json:"group_search_output"`
	SmartTruncate         bool   `json:"smart_truncate"`
	SourceCodeFiltering   string `json:"source_code_filtering"` // "none", "minimal", "aggressive"

	MaxChars         int `json:"max_chars"`
	MaxLines         int `json:"max_lines"`
	MaxTestFailures  int `json:"max_test_failures"`
	MaxTestFailLines int `json:"max_test_fail_lines"`
	MaxBuildErrors   int `json:"max_build_errors"`
	MaxBuildErrLines int `json:"max_build_err_lines"`
	MaxDiffLines     int `json:"max_diff_lines"`
	MaxDiffHunkLines int `json:"max_diff_hunk_lines"`
	MaxStatusFiles   int `json:"max_status_files"`
	MaxLogEntries    int `json:"max_log_entries"`
	MaxLinterRules   int `json:"max_linter_rules"`
	MaxLinterFiles   int `json:"max_linter_files"`
	MaxSearchPerFile int `json:"max_search_per_file"`
	MaxSearchTotal   int `json:"max_search_total"`
}

CompactorConfig holds all compaction settings, loaded from config.json.

func DefaultCompactorConfig added in v0.0.4

func DefaultCompactorConfig() CompactorConfig

DefaultCompactorConfig returns a CompactorConfig with all stages enabled and reasonable limits (doubled from rtk-optimizer defaults).

type CoreOption added in v0.0.53

type CoreOption func(*coreConfig)

CoreOption customizes the core tool set.

func WithBashSupervisor added in v0.0.53

func WithBashSupervisor(sup *BashSupervisor) CoreOption

WithBashSupervisor makes the bash tool use a caller-owned supervisor, so the caller can attach a live-output sink and stop backgrounded commands at shutdown. Without it CoreTools builds a private supervisor: commands still get process-group isolation and background handoff, but nothing outside the tool can see or reap them.

func WithReadLedger added in v0.0.60

func WithReadLedger(l *ReadLedger) CoreOption

WithReadLedger makes read, write and edit share a caller-owned ledger, so the read-before-write check spans a whole session rather than one tool set. Without it CoreTools builds a private one and the check still holds, but only for tools built by this call.

type DiagnosticEntry

type DiagnosticEntry struct {
	Line     int    `json:"line"`
	Column   int    `json:"column"`
	Severity string `json:"severity"`
	Message  string `json:"message"`
	Source   string `json:"source,omitempty"`
}

DiagnosticEntry is a single diagnostic for tool output.

type EditInput

type EditInput struct {
	// The absolute path to the file to edit.
	FilePath string `json:"file_path"`
	// The exact string to find and replace.
	OldString string `json:"old_string"`
	// The replacement string. Optional — empty means delete old_string.
	NewString string `json:"new_string,omitempty"`
	// If true, replace all occurrences. Default: replace first occurrence only.
	ReplaceAll bool `json:"replace_all,omitempty"`
}

EditInput defines the parameters for the edit tool.

type EditOutput

type EditOutput struct {
	// The path of the edited file.
	Path string `json:"path"`
	// Number of replacements made.
	Replacements int `json:"replacements"`
}

EditOutput contains the result of editing a file.

type FindInput

type FindInput struct {
	// The glob pattern to match files against (e.g. "**/*.go", "*.ts").
	Pattern string `json:"pattern"`
	// The directory to search in. Defaults to current directory.
	Path string `json:"path,omitempty"`
}

FindInput defines the parameters for the find tool.

type FindOutput

type FindOutput struct {
	// List of matching file paths.
	Files []string `json:"files"`
	// Total matches found (may be more than returned if truncated).
	TotalFiles int `json:"total_files"`
	// Whether results were truncated due to limits.
	Truncated bool `json:"truncated,omitempty"`
}

FindOutput contains the matching file paths.

type GitFileDiffInput

type GitFileDiffInput struct {
	// File path to diff (relative to repo root).
	File string `json:"file"`
	// If true, show staged (cached) diff instead of unstaged. Default: false.
	Staged bool `json:"staged,omitempty"`
}

GitFileDiffInput defines the parameters for the git-file-diff tool.

type GitFileDiffOutput

type GitFileDiffOutput struct {
	// File path that was diffed.
	File string `json:"file"`
	// Unified diff output.
	Diff string `json:"diff"`
	// Diff statistics: lines added.
	LinesAdded int `json:"lines_added"`
	// Diff statistics: lines removed.
	LinesRemoved int `json:"lines_removed"`
	// True if the file is binary.
	Binary bool `json:"binary,omitempty"`
	// True if diff output was truncated.
	Truncated bool `json:"truncated,omitempty"`
}

GitFileDiffOutput contains the unified diff for a single file.

type GitHunkInput

type GitHunkInput struct {
	// File path to inspect hunks for (relative to repo root).
	File string `json:"file"`
	// If true, show hunks from staged diff. Default: false.
	Staged bool `json:"staged,omitempty"`
}

GitHunkInput defines the parameters for the git-hunk tool.

type GitHunkOutput

type GitHunkOutput struct {
	// File path.
	File string `json:"file"`
	// Parsed hunks.
	Hunks []Hunk `json:"hunks"`
	// Total number of hunks.
	TotalHunks int `json:"total_hunks"`
}

GitHunkOutput contains parsed hunks for a file.

type GitOverviewInput

type GitOverviewInput struct {
	// Include staged files in the output. Default: true.
	IncludeStaged *bool `json:"include_staged,omitempty"`
	// Include unstaged modified files in the output. Default: true.
	IncludeUnstaged *bool `json:"include_unstaged,omitempty"`
	// Include untracked files in the output. Default: true.
	IncludeUntracked *bool `json:"include_untracked,omitempty"`
}

GitOverviewInput defines the parameters for the git-overview tool.

type GitOverviewOutput

type GitOverviewOutput struct {
	// Current branch name.
	Branch string `json:"branch"`
	// Recent commits (up to 10, most recent first).
	RecentCommits []string `json:"recent_commits"`
	// Files staged for commit (index column of porcelain).
	StagedFiles []string `json:"staged_files,omitempty"`
	// Files modified but not staged (worktree column of porcelain).
	UnstagedFiles []string `json:"unstaged_files,omitempty"`
	// Untracked files.
	UntrackedFiles []string `json:"untracked_files,omitempty"`
	// Upstream tracking branch (empty if none).
	Upstream string `json:"upstream,omitempty"`
	// Commits ahead of upstream.
	Ahead int `json:"ahead"`
	// Commits behind upstream.
	Behind int `json:"behind"`
}

GitOverviewOutput contains the git repository overview.

type GitignorePattern added in v0.0.15

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

GitignorePattern represents a parsed .gitignore pattern.

type GrepInput

type GrepInput struct {
	// The regex pattern to search for.
	Pattern string `json:"pattern"`
	// The file or directory to search in. Defaults to current directory.
	Path string `json:"path,omitempty"`
	// Glob pattern to filter files (e.g. "*.go", "*.{ts,tsx}").
	Glob string `json:"glob,omitempty"`
	// If true, perform case-insensitive matching.
	CaseInsensitive bool `json:"case_insensitive,omitempty"`
}

GrepInput defines the parameters for the grep tool.

type GrepMatch

type GrepMatch struct {
	File    string `json:"file"`
	Line    int    `json:"line"`
	Content string `json:"content"`
}

GrepMatch represents a single grep match.

type GrepOutput

type GrepOutput struct {
	// List of matches with file path, line number, and content.
	Matches []GrepMatch `json:"matches"`
	// Total number of matches found (may be more than returned if truncated).
	TotalMatches int `json:"total_matches"`
	// Whether results were truncated due to limits.
	Truncated bool `json:"truncated,omitempty"`
}

GrepOutput contains the search results.

type Hunk

type Hunk struct {
	// Hunk header (e.g. "@@ -1,3 +1,5 @@").
	Header string `json:"header"`
	// Raw hunk content (context + added + removed lines).
	Content string `json:"content"`
	// Number of lines added in this hunk.
	Added int `json:"added"`
	// Number of lines removed in this hunk.
	Removed int `json:"removed"`
}

Hunk represents a single diff hunk with metadata.

type LSPCodeActionInput added in v0.0.15

type LSPCodeActionInput struct {
	File      string `json:"file"`
	StartLine int    `json:"startLine"`
	StartCol  int    `json:"startCol"`
	EndLine   int    `json:"endLine"`
	EndCol    int    `json:"endCol"`
}

LSPCodeActionInput is input for code action tool.

type LSPCodeActionOutput added in v0.0.15

type LSPCodeActionOutput struct {
	File    string        `json:"file"`
	Actions []ActionEntry `json:"actions"`
	Error   string        `json:"error,omitempty"`
}

LSPCodeActionOutput is output for code action tool.

type LSPDiagnosticsOutput

type LSPDiagnosticsOutput struct {
	File           string            `json:"file"`
	Diagnostics    []DiagnosticEntry `json:"diagnostics"`
	LSPDiagnostics string            `json:"lsp_diagnostics"` // styled string for display (compatible with formatToolResult)
	Error          string            `json:"error,omitempty"`
}

LSPDiagnosticsOutput is the output of the lsp-diagnostics tool.

type LSPFileInput

type LSPFileInput struct {
	File string `json:"file"`
}

LSPFileInput is shared input for tools that take only a file path.

type LSPHoverOutput

type LSPHoverOutput struct {
	Content string `json:"content"`
	Error   string `json:"error,omitempty"`
}

LSPHoverOutput is the output of the lsp-hover tool.

type LSPLocationsOutput

type LSPLocationsOutput struct {
	Locations []LocationEntry `json:"locations"`
	Error     string          `json:"error,omitempty"`
}

LSPLocationsOutput is the output for definition/references tools.

type LSPPositionInput

type LSPPositionInput struct {
	File   string `json:"file"`
	Line   int    `json:"line,omitempty"`
	Column int    `json:"column,omitempty"`
}

LSPPositionInput is shared input for tools that take a file + position.

type LSPSymbolsOutput

type LSPSymbolsOutput struct {
	File    string        `json:"file"`
	Symbols []SymbolEntry `json:"symbols"`
	Error   string        `json:"error,omitempty"`
}

LSPSymbolsOutput is the output of the lsp-symbols tool.

type LSPWorkspaceSymbolInput added in v0.0.15

type LSPWorkspaceSymbolInput struct {
	Query string `json:"query"`
}

LSPWorkspaceSymbolInput is input for workspace symbol search.

type LSPWorkspaceSymbolOutput added in v0.0.15

type LSPWorkspaceSymbolOutput struct {
	Symbols []WorkspaceSymbolEntry `json:"symbols"`
	Error   string                 `json:"error,omitempty"`
}

LSPWorkspaceSymbolOutput is output for workspace symbol search.

type LocationEntry

type LocationEntry struct {
	File   string `json:"file"`
	Line   int    `json:"line"`
	Column int    `json:"column"`
}

LocationEntry is a single location for tool output.

type LsEntry

type LsEntry struct {
	Name  string `json:"name"`
	IsDir bool   `json:"is_dir"`
	Size  int64  `json:"size"`
}

LsEntry represents a single directory entry.

type LsInput

type LsInput struct {
	// The directory path to list. Defaults to current directory.
	Path string `json:"path,omitempty"`
}

LsInput defines the parameters for the ls tool.

type LsOutput

type LsOutput struct {
	// List of entries in the directory.
	Entries []LsEntry `json:"entries"`
	// Total entries in the directory (may be more than returned if truncated).
	TotalEntries int `json:"total_entries"`
	// Whether results were truncated due to limits.
	Truncated bool `json:"truncated,omitempty"`
}

LsOutput contains the directory listing.

type MemGetInput added in v0.0.10

type MemGetInput struct {
	// Observation IDs to fetch.
	IDs []int64 `json:"ids"`
}

MemGetInput defines parameters for the mem-get tool.

type MemGetOutput added in v0.0.10

type MemGetOutput struct {
	// Markdown-formatted observation details.
	Content string `json:"content"`
	// Number of observations returned.
	Count int `json:"count"`
}

MemGetOutput contains full observation details.

type MemSearchInput added in v0.0.10

type MemSearchInput struct {
	// Full-text search query.
	Query string `json:"query"`
	// Optional project scope.
	Project string `json:"project,omitempty"`
	// Optional observation type filter (bugfix, feature, discovery, etc.).
	Type string `json:"type,omitempty"`
	// Max results to return (default 20).
	Limit int `json:"limit,omitempty"`
}

MemSearchInput defines parameters for the mem-search tool.

type MemSearchOutput added in v0.0.10

type MemSearchOutput struct {
	// Markdown-formatted results table.
	Content string `json:"content"`
	// Total number of matching observations.
	Total int `json:"total"`
}

MemSearchOutput contains search results.

type MemTimelineInput added in v0.0.10

type MemTimelineInput struct {
	// Anchor observation ID to center the timeline on.
	Anchor int64 `json:"anchor"`
	// Number of observations to show before the anchor (default 5).
	DepthBefore int `json:"depth_before,omitempty"`
	// Number of observations to show after the anchor (default 5).
	DepthAfter int `json:"depth_after,omitempty"`
}

MemTimelineInput defines parameters for the mem-timeline tool.

type MemTimelineOutput added in v0.0.10

type MemTimelineOutput struct {
	// Markdown-formatted timeline.
	Content string `json:"content"`
	// Number of observations returned.
	Count int `json:"count"`
}

MemTimelineOutput contains timeline results.

type OutputSink added in v0.0.53

type OutputSink func(execID, kind, content string)

OutputSink receives live activity from running shell commands.

kind is one of "start", "output", "stderr", "heartbeat", "stall", "background" or "exit". Implementations must not block: the sink is called from the goroutines copying the command's pipes, and blocking there stalls the command itself. The TUI's implementation drops events when its channel is full, which is the correct trade — a dropped progress line costs nothing, a stalled pipe costs the command.

type ReadImageInput added in v0.0.47

type ReadImageInput struct {
	// The path or URL of the image to read.
	//
	// Accepted forms:
	//   - An absolute or sandbox-relative path to a local file.
	//   - An https:// URL pointing to a remote image (fetched to the
	//     session cache, then handled like a local file).
	//
	// http:// URLs are rejected. Remote hosts are resolved to IPs and
	// loopback / private / link-local / multicast addresses are blocked to
	// prevent SSRF.
	FilePath string `json:"file_path"`
}

ReadImageInput defines the parameters for the read_image tool.

type ReadImageOutput added in v0.0.47

type ReadImageOutput struct {
	// The path that was read. For URL inputs, this is the cached local file.
	Path string `json:"path"`
	// The detected MIME type (e.g. image/png).
	MIMEType string `json:"mime_type"`
	// The image width in pixels (0 if undetectable).
	Width int `json:"width"`
	// The image height in pixels (0 if undetectable).
	Height int `json:"height"`
	// The file size in bytes.
	Size int `json:"size"`
	// The original URL when the input was a remote URL, otherwise empty.
	SourceURL string `json:"source_url,omitempty"`
}

ReadImageOutput contains metadata about the read image. The image bytes are deliberately NOT returned here: embedding them would bloat the text tool result and count them as tokens. A BeforeModelCallback re-reads the file and injects the bytes as an InlineData part that a vision model can actually see.

When the input was a URL, Path contains the cached local file path (a content-addressed entry under .pi-go-image-cache/) and SourceURL is the original URL the caller provided. This makes the response self-describing without bloating the text tool result.

type ReadInput

type ReadInput struct {
	// The absolute path to the file to read.
	FilePath string `json:"file_path"`
	// Optional line offset to start reading from (1-based). Defaults to 1.
	Offset int `json:"offset,omitempty"`
	// Optional maximum number of lines to read. 0 means up to 2000 lines.
	Limit int `json:"limit,omitempty"`
}

ReadInput defines the parameters for the read tool.

type ReadLedger added in v0.0.60

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

ReadLedger records what the agent has actually seen of each file.

It exists to stop one specific failure: an overwrite of a file the agent never read, or read only a window of. Both destroy content the agent did not know was there, and neither is recoverable from the transcript, because the bytes it replaced were never in the transcript to begin with.

Tracking a partial view separately from a full one is what makes the refusal accurate rather than merely cautious. "You have not read this file" is wrong and confusing when the agent has read 2000 of its 5000 lines; the honest message names the real problem, which is the 3000 lines it has not seen.

func NewReadLedger added in v0.0.60

func NewReadLedger() *ReadLedger

NewReadLedger creates an empty ledger.

func (*ReadLedger) CheckOverwrite added in v0.0.60

func (l *ReadLedger) CheckOverwrite(path string, info os.FileInfo) error

CheckOverwrite reports why path may not be overwritten, or nil when it may.

Creating a file that does not exist yet is always allowed: there is nothing to destroy, and requiring a read first would only produce a pointless error.

func (*ReadLedger) Forget added in v0.0.60

func (l *ReadLedger) Forget(path string)

Forget drops a path, so a later write is judged on a fresh read rather than on a view of bytes that no longer exist.

func (*ReadLedger) Record added in v0.0.60

func (l *ReadLedger) Record(path string, info os.FileInfo, partial bool)

Record notes that path was read, and whether the view was a partial one.

func (*ReadLedger) Touch added in v0.0.60

func (l *ReadLedger) Touch(path string, info os.FileInfo)

Touch refreshes the recorded mtime and size after the agent itself changed the file, keeping whatever view it already had.

A targeted edit is not a reason to make the agent re-read: it knows exactly what it changed. Without this the mtime check would fire on the agent's own edit and demand a re-read that would teach it nothing. A file the ledger has never seen stays unseen — Touch does not grant a view.

type ReadOutput

type ReadOutput struct {
	// The file content with line numbers.
	Content string `json:"content"`
	// Total number of lines in the file.
	TotalLines int `json:"total_lines"`
	// Whether the output was truncated.
	Truncated bool `json:"truncated,omitempty"`
	// NextOffset is the offset that continues exactly where this call stopped.
	// Zero when the file was read to the end.
	//
	// It is precomputed so the model never has to do pagination arithmetic —
	// getting it wrong costs a wasted turn and a re-read of the same bytes.
	NextOffset int `json:"next_offset,omitempty"`
	// Note explains an outcome the content alone does not: an empty file, an
	// offset past the end, a clamped line. Silence is the most expensive thing
	// this tool can return, because an invisible non-answer costs a turn to
	// discover and another to work around.
	Note string `json:"note,omitempty"`
}

ReadOutput contains the result of reading a file.

type ResultDeduper added in v0.0.48

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

ResultDeduper elides byte-identical repeats of read-only tool results within a single session. It is safe for concurrent use by parallel tool calls.

func NewResultDeduper added in v0.0.48

func NewResultDeduper() *ResultDeduper

NewResultDeduper creates an empty deduper.

func (*ResultDeduper) FormatStats added in v0.0.48

func (d *ResultDeduper) FormatStats() string

FormatStats renders a human-readable summary for /rtk and /status.

func (*ResultDeduper) Reset added in v0.0.48

func (d *ResultDeduper) Reset()

Reset clears the dedup memory. Call this after compaction installs a fresh context window: the earlier results the pointers refer to are no longer in the conversation, so a pointer to them would dangle.

func (*ResultDeduper) Stats added in v0.0.48

func (d *ResultDeduper) Stats() (calls, bytes int)

Stats reports how many results were elided and how many bytes that saved on the turn they were elided. The lifetime saving is larger, because an elided result would otherwise have been re-sent on every later turn too.

type Sandbox

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

Sandbox provides a secure file system abstraction that restricts all file operations to a specific directory tree.

SECURITY MODEL:

  • All file paths are resolved relative to the sandbox root
  • Access outside the sandbox is blocked via os.Root (Go 1.24+)
  • This prevents the agent from accessing sensitive files outside the working directory

LIMITATIONS:

  • Files outside the sandbox cannot be accessed
  • Symlinks pointing outside are blocked
  • Absolute paths are converted to relative

WORKAROUNDS:

  • Change the working directory to access different files
  • Use tools that explicitly access external resources (e.g., fetch URLs)

func NewSandbox

func NewSandbox(dir string, worktreeDir ...string) (*Sandbox, error)

NewSandbox opens an os.Root anchored at dir. Optionally pass worktreeDir if this is a subagent sandbox that needs to resolve relative paths from a different working directory.

func (*Sandbox) AddExtraDir added in v0.0.15

func (s *Sandbox) AddExtraDir(dir string) error

AddExtraDir registers an additional directory that the sandbox can access. Paths under this directory are resolved using a separate os.Root.

func (*Sandbox) Close

func (s *Sandbox) Close() error

Close releases the underlying os.Root file descriptor.

func (*Sandbox) Dir

func (s *Sandbox) Dir() string

Dir returns the absolute path of the sandbox root.

func (*Sandbox) FS

func (s *Sandbox) FS() fs.FS

FS returns an fs.FS scoped to the sandbox root directory.

func (*Sandbox) LoadGitignorePatterns added in v0.0.15

func (s *Sandbox) LoadGitignorePatterns() ([]GitignorePattern, error)

LoadGitignorePatterns loads .gitignore patterns from the sandbox root. Returns nil if no patterns found (non-fatal).

The result is memoized for gitignoreTTL: collecting it costs a walk of the whole tree, and grep/find call this on every invocation.

func (*Sandbox) MkdirAll

func (s *Sandbox) MkdirAll(name string, perm os.FileMode) error

MkdirAll creates a directory path within the sandbox.

func (*Sandbox) Open

func (s *Sandbox) Open(name string) (*os.File, error)

Open opens a file for reading within the sandbox.

func (*Sandbox) ReadDir

func (s *Sandbox) ReadDir(name string) ([]os.DirEntry, error)

ReadDir lists entries in a directory within the sandbox.

func (*Sandbox) ReadFile

func (s *Sandbox) ReadFile(name string) ([]byte, error)

ReadFile reads the named file within the sandbox. Transient errors (e.g. "text file busy") are retried up to 3 times with increasing delay. Non-transient errors are returned immediately.

func (*Sandbox) Resolve

func (s *Sandbox) Resolve(name string) (string, error)

Resolve converts an absolute or relative path to a relative path under the sandbox root. Returns an error with the sandbox root path if the resolved path would escape the directory tree.

For subagent contexts with worktree directories, paths like "../../go.mod" are resolved relative to the worktree, then made relative to the sandbox root.

SECURITY: This is intentional. The sandbox restricts file system access to prevent the agent from reading/writing files outside the working directory.

func (*Sandbox) SetWorktreeDir added in v0.0.14

func (s *Sandbox) SetWorktreeDir(dir string) error

SetWorktreeDir sets the worktree directory for path normalization. This is used by subagent sandboxes that need to resolve relative paths from a different working directory than the sandbox root.

func (*Sandbox) Stat

func (s *Sandbox) Stat(name string) (os.FileInfo, error)

Stat returns FileInfo for a path within the sandbox.

func (*Sandbox) WriteFile

func (s *Sandbox) WriteFile(name string, data []byte, perm os.FileMode) error

WriteFile writes data to the named file within the sandbox, creating it if necessary (parent directories are created automatically).

type SessionStatsInput added in v0.0.47

type SessionStatsInput struct {
	// Number of hours to look back. Default: 24.
	Hours int `json:"hours,omitempty"`
	// Minimum tool calls to flag as high-usage. Default: 20.
	HighToolCalls int `json:"high_tool_calls,omitempty"`
	// Minimum turns to flag as excessive cycles. Default: 5.
	HighTurns int `json:"high_turns,omitempty"`
	// Show all sessions (not just anomalous ones). Default: false.
	All bool `json:"all,omitempty"`
	// Session directory override. Default: ~/.pi-go/sessions.
	SessionDir string `json:"session_dir,omitempty"`
}

SessionStatsInput defines the parameters for the session-stats tool.

type SessionStatsOutput added in v0.0.47

type SessionStatsOutput struct {
	// Markdown-formatted report.
	Content string `json:"content"`
	// Total sessions scanned.
	TotalSessions int `json:"total_sessions"`
	// Sessions with anomalies.
	AnomalousSessions int `json:"anomalous_sessions"`
}

SessionStatsOutput contains the session analysis results.

type SubagentEvent added in v0.0.10

type SubagentEvent struct {
	AgentID    string `json:"agent_id"`
	Kind       string `json:"kind"` // "spawn", "text_delta", "tool_call", "tool_result", "error", "done"
	Content    string `json:"content"`
	PipelineID string `json:"pipeline_id"` // groups agents in same call
	Mode       string `json:"mode"`        // "single", "parallel", "chain"
	Step       int    `json:"step"`        // 1-based position
	Total      int    `json:"total"`       // total agents in pipeline
}

SubagentEvent extends agent events with pipeline metadata for the TUI.

type SubagentEventCallback added in v0.0.10

type SubagentEventCallback func(event SubagentEvent)

SubagentEventCallback is called for each subagent event with pipeline metadata.

type SubagentInput added in v0.0.10

type SubagentInput struct {
	// Single mode: agent name to spawn.
	Agent string `json:"agent,omitempty"`
	// Single mode: task prompt for the agent.
	Task string `json:"task,omitempty"`

	// Parallel mode: list of tasks to run concurrently.
	Tasks []TaskItem `json:"tasks,omitempty"`

	// Chain mode: sequential pipeline of agents.
	Chain []ChainItem `json:"chain,omitempty"`
}

SubagentInput defines the parameters for the subagent tool.

type SubagentOutput added in v0.0.10

type SubagentOutput struct {
	Mode    string        `json:"mode"`
	Results []AgentResult `json:"results"`
	Summary string        `json:"summary"`
}

SubagentOutput is the result from a completed subagent call.

type SymbolEntry

type SymbolEntry struct {
	Name    string `json:"name"`
	Kind    string `json:"kind"`
	Line    int    `json:"line"`
	EndLine int    `json:"end_line"`
}

SymbolEntry is a single symbol for tool output.

type TaskItem added in v0.0.10

type TaskItem struct {
	Agent string `json:"agent"`
	Task  string `json:"task"`
}

TaskItem defines a single task in parallel mode.

type ToolCompactSum added in v0.0.4

type ToolCompactSum struct {
	Count int `json:"count"`
	Orig  int `json:"orig"`
	Comp  int `json:"comp"`
}

ToolCompactSum holds per-tool aggregated stats.

type TreeInput

type TreeInput struct {
	// Directory path to show. Defaults to current directory.
	Path string `json:"path,omitempty"`
	// Maximum depth to recurse. Default 3, max 10.
	Depth int `json:"depth,omitempty"`
}

TreeInput defines the parameters for the tree tool.

type TreeOutput

type TreeOutput struct {
	Tree  string `json:"tree"`
	Dirs  int    `json:"dirs"`
	Files int    `json:"files"`
}

TreeOutput contains the tree listing.

type WorkspaceSymbolEntry added in v0.0.15

type WorkspaceSymbolEntry struct {
	Name          string `json:"name"`
	Kind          string `json:"kind"`
	File          string `json:"file"`
	Line          int    `json:"line"`
	Column        int    `json:"column"`
	ContainerName string `json:"containerName,omitempty"`
}

WorkspaceSymbolEntry is a single workspace symbol for tool output.

type WriteInput

type WriteInput struct {
	// The absolute path to the file to write.
	FilePath string `json:"file_path"`
	// The content to write to the file.
	Content string `json:"content"`
}

WriteInput defines the parameters for the write tool.

type WriteOutput

type WriteOutput struct {
	// The path of the written file.
	Path string `json:"path"`
	// Number of bytes written.
	BytesWritten int `json:"bytes_written"`
}

WriteOutput contains the result of writing a file.

Jump to

Keyboard shortcuts

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