Documentation
¶
Overview ¶
Package tools defines tool handlers and execution helpers for agents.
Index ¶
- Constants
- Variables
- func AdaptiveCompactionThreshold(m BudgetQuerier) int
- func BuildHandlers(workingDir string, taskCfg *TaskConfig, ex executor.Executor) (map[string]Handler, []llms.Tool)
- func BuildHandlersWithSkill(workingDir string, taskCfg *TaskConfig, ex executor.Executor, ...) (map[string]Handler, []llms.Tool)
- func CollectEditedFiles(messages []llms.MessageContent) map[string]bool
- func CompactionSummary(messages []llms.MessageContent, rc *ReadCache) string
- func ContainsReadCommand(cmd string) bool
- func EditDeadlineReached(ctx context.Context) bool
- func EditsApplied(ctx context.Context) bool
- func ExtractRecentFiles(msgs []llms.MessageContent) map[string]bool
- func GenerateFileSummary(content string) string
- func GetIteration(ctx context.Context) int
- func GetSkillStack(ctx context.Context) *skill.Stack
- func HashContent(data []byte) string
- func InitBgCommandRegistry(ctx context.Context) context.Context
- func InitCommentsOnlyMode(ctx context.Context) context.Context
- func InitEditDeadline(ctx context.Context) context.Context
- func InitEdits(ctx context.Context) context.Context
- func InitFileTracker(ctx context.Context) context.Context
- func InitIterationCounter(ctx context.Context) context.Context
- func InitReadCache(ctx context.Context) context.Context
- func InitTokenCalibration(ctx context.Context) context.Context
- func IsBlockedCommand(cmd string) (bool, string)
- func IsCommentsOnlyMode(ctx context.Context) bool
- func IsSafeCommand(cmd string) bool
- func MarkEditDeadlineReached(ctx context.Context)
- func MarkEditsApplied(ctx context.Context)
- func ResetEditsApplied(ctx context.Context)
- func ResolvePath(workingDir, input string) (string, error)
- func RunWithTools(ctx context.Context, llm llms.Model, ...) (string, error)
- func SetEditEnforcer(ctx context.Context, e *EditEnforcer) context.Context
- func SetIteration(ctx context.Context, i int)
- func SetPhaseEnforcer(ctx context.Context, pe *PhaseEnforcer) context.Context
- func TaskDepth(ctx context.Context) int
- func TruncateString(s string, maxLen int) string
- func TruncateToLines(content string, headLines, tailLines int) string
- func TruncateToolOutputHeadTail(output string, maxBytes int) string
- func ValidateCommentsOnly(oldText, newText string) error
- func WithConfirmRuntime(ctx context.Context, r *ConfirmRuntime) context.Context
- func WithSkillRuntime(ctx context.Context, r *SkillRuntime) context.Context
- func WithTaskDepth(ctx context.Context, depth int) context.Context
- type AutoConfirmMode
- type BackgroundTaskRegistry
- type BackgroundTaskResult
- type BgCommand
- type BgCommandRegistry
- type BudgetQuerier
- type CallModelFunc
- type ChildMaxCostFunc
- type ChildMaxIterFunc
- type ConfirmRuntime
- type EditEnforcer
- type FailedEdit
- type FileTracker
- type Finding
- type FindingsStore
- type FlexBool
- type Handler
- type LoopDetector
- type MessageRelevance
- type MultiEditArgs
- type MultiEditOperation
- type PhaseEnforcer
- type ReadCache
- func (rc *ReadCache) BumpCompactionEpoch()
- func (rc *ReadCache) Check(path string, contentHash string) (ReadCacheEntry, bool)
- func (rc *ReadCache) CompactionEpoch() int
- func (rc *ReadCache) Has(path string) bool
- func (rc *ReadCache) IncrementStreak() int
- func (rc *ReadCache) IsStaleAfterCompaction(entry ReadCacheEntry) bool
- func (rc *ReadCache) Len() int
- func (rc *ReadCache) ResetStreak()
- func (rc *ReadCache) Store(path, contentHash string, lines, bytes, iteration int, summary string)
- func (rc *ReadCache) Summaries() map[string]string
- type ReadCacheEntry
- type RepeatTracker
- type RunWithToolsConfig
- type SkillRuntime
- type SmartReadResult
- type SystemInfo
- type TaskConfig
- type TokenCalibration
Constants ¶
const ( // DefaultAutoBackgroundTimeout is the duration after which a bash command // is automatically moved to the background. DefaultAutoBackgroundTimeout = 120 * time.Second )
const DefaultConcurrentTasks = 4
DefaultConcurrentTasks is the default concurrent background task limit.
const ( // DefaultMaxRetries is the number of additional attempts after a failed // LLM call when no explicit override is supplied. Total attempts = // DefaultMaxRetries + 1. DefaultMaxRetries = 3 )
const MaxTaskDepth = 3
MaxTaskDepth is the maximum nesting depth for Task tool invocations.
const MaxToolIterations = 100
MaxToolIterations is the default cap on tool-calling iterations per run when no explicit --max-iterations flag is provided.
const ProgressCheckPrompt = "[PROGRESS CHECK] You have used 25%% of your cost budget ($%.2f remaining). " +
"Have you made any edits yet? If not, you should have enough context — start editing NOW. " +
"List what you plan to change and begin immediately. Do not read more files."
ProgressCheckPrompt is injected at 25% budget to check if the agent is making progress.
const ToolEfficiencyPrompt = `` /* 721-byte string literal not displayed */
ToolEfficiencyPrompt is injected into all agent system prompts to encourage batching of tool calls and efficient file reading.
Variables ¶
var ( // ErrToolExecutionFailed indicates a tool handler returned an error. ErrToolExecutionFailed = errors.New("tool execution failed") // ErrIterationLimitReached indicates the agent hit its max iteration count. ErrIterationLimitReached = errors.New("iteration limit reached") // ErrLoopDetected indicates the agent was stuck repeating identical tool calls. ErrLoopDetected = errors.New("loop detected: agent repeating identical tool calls") // ErrEditDeadlineReached indicates the agent failed to make edits within the deadline. ErrEditDeadlineReached = errors.New("edit deadline reached without edits") // ErrBlockedCommand indicates a dangerous command was rejected by the safety filter. ErrBlockedCommand = errors.New("blocked command") // ErrFileNotRead indicates an edit was attempted on a file that hasn't been read. ErrFileNotRead = errors.New("file not read before edit") // ErrStaleRead indicates a file was modified after the agent last read it. ErrStaleRead = errors.New("file modified since last read") )
Sentinel errors for common agent failure modes. Use errors.Is() to check for these in callers.
Functions ¶
func AdaptiveCompactionThreshold ¶
func AdaptiveCompactionThreshold(m BudgetQuerier) int
AdaptiveCompactionThreshold returns a context token threshold that tightens as the cost budget is consumed. This ensures agents operating near their budget limit don't waste tokens on stale context.
func BuildHandlers ¶
func BuildHandlers(workingDir string, taskCfg *TaskConfig, ex executor.Executor) (map[string]Handler, []llms.Tool)
BuildHandlers returns a map of tool-name → Handler and a sorted list of tool definitions to be passed to the LLM. When taskCfg is non-nil the Task and TaskResult tools are registered; when taskCfg.Findings is set the ReportFinding tool is also registered. MCP tools from taskCfg.ExtraTools are appended last.
func BuildHandlersWithSkill ¶
func BuildHandlersWithSkill(workingDir string, taskCfg *TaskConfig, ex executor.Executor, skillRuntime *SkillRuntime, confirmRuntime *ConfirmRuntime) (map[string]Handler, []llms.Tool)
BuildHandlersWithSkill is the exported variant of buildHandlersWithSkill, used by callers in other packages (e.g. the OpenAI Responses API path) that need to register the Skill and Confirm tools.
func CollectEditedFiles ¶
func CollectEditedFiles(messages []llms.MessageContent) map[string]bool
CollectEditedFiles scans messages for successful Edit/Write tool calls and returns a set of edited file paths.
func CompactionSummary ¶
func CompactionSummary(messages []llms.MessageContent, rc *ReadCache) string
CompactionSummary extracts structured information from messages before they are compacted, preserving the agent's "mental map" of what it has done. When rc is non-nil, per-file summaries (line count + declarations) are included so the model can write edits without re-reading files.
func ContainsReadCommand ¶
ContainsReadCommand checks whether a compound shell command contains any read-like operations. It splits on shell operators (&&, ||, ;, |) and checks each segment for known read binaries. This catches bypass patterns like "cd /path && cat file" that IsSafeCommand misses because the overall command doesn't start with "cat ".
func EditDeadlineReached ¶
EditDeadlineReached returns true if the edit deadline stopped the loop.
func EditsApplied ¶
EditsApplied reports whether any file edits have been applied in this run.
func ExtractRecentFiles ¶
func ExtractRecentFiles(msgs []llms.MessageContent) map[string]bool
ExtractRecentFiles scans messages for file paths mentioned in tool calls.
func GenerateFileSummary ¶
GenerateFileSummary produces a brief summary of a file's top-level declarations (func, type, class, def, fn). The summary is stored in the read cache and included in compaction summaries so the model can write edits without re-reading the file.
func GetIteration ¶
GetIteration returns the current iteration index from ctx, or 0 if not set.
func GetSkillStack ¶
GetSkillStack is a convenience for callers that only need the stack — most of the file tools just want path-containment lookups.
func HashContent ¶
HashContent returns a hex-encoded SHA-256 hash of data.
func InitBgCommandRegistry ¶
InitBgCommandRegistry attaches a registry to the context.
func InitCommentsOnlyMode ¶
InitCommentsOnlyMode marks ctx as comments-only. While set, Edit and MultiEdit calls reject any change that modifies non-comment lines.
func InitEditDeadline ¶
InitEditDeadline sets up the edit deadline tracking on the context.
func InitFileTracker ¶
InitFileTracker attaches a FileTracker to the context.
func InitIterationCounter ¶
InitIterationCounter attaches an iteration counter (starting at 0) to ctx.
func InitReadCache ¶
InitReadCache attaches a new ReadCache to ctx for the duration of a run.
func InitTokenCalibration ¶
InitTokenCalibration attaches a TokenCalibration to the context.
func IsBlockedCommand ¶
IsBlockedCommand returns true and a reason if the command is dangerous and should not be executed by an agent.
func IsCommentsOnlyMode ¶
IsCommentsOnlyMode reports whether ctx is in comments-only mode.
func IsSafeCommand ¶
IsSafeCommand returns true if the command is known to be read-only.
func MarkEditDeadlineReached ¶
MarkEditDeadlineReached records that the edit deadline was hit.
func MarkEditsApplied ¶
MarkEditsApplied sets the edits-applied flag to true on ctx.
func ResetEditsApplied ¶
ResetEditsApplied resets the edits-applied flag to false on ctx.
func ResolvePath ¶
ResolvePath resolves input against workingDir and verifies the result is inside the working directory, rejecting path-traversal attempts.
func RunWithTools ¶
func RunWithTools(ctx context.Context, llm llms.Model, systemPrompt, userPrompt, workingDir string, cfg RunWithToolsConfig, callOpts ...llms.CallOption) (string, error)
RunWithTools drives the tool-calling loop for a LangChain-compatible LLM. It initialises the read cache, file tracker, and enforcer machinery, then iterates between model calls and tool executions until the model stops calling tools, the iteration cap is hit, or a budget/loop error is raised.
func SetEditEnforcer ¶
func SetEditEnforcer(ctx context.Context, e *EditEnforcer) context.Context
SetEditEnforcer stores the enforcer on the context so tool handlers can query it.
func SetIteration ¶
SetIteration updates the current iteration index stored on ctx.
func SetPhaseEnforcer ¶
func SetPhaseEnforcer(ctx context.Context, pe *PhaseEnforcer) context.Context
SetPhaseEnforcer stores pe on ctx so tool handlers can retrieve it.
func TruncateString ¶
TruncateString truncates s to maxLen bytes, appending "..." when truncation occurs.
func TruncateToLines ¶
TruncateToLines returns the first headLines and last tailLines of the content.
func TruncateToolOutputHeadTail ¶
TruncateToolOutputHeadTail trims tool output that exceeds maxBytes, keeping 75% from the head and 25% from the tail with an omission notice in between.
func ValidateCommentsOnly ¶
ValidateCommentsOnly returns nil when the diff between oldText and newText touches only comment lines or blank lines, and an error otherwise. The check is line-based and language-agnostic for common comment markers (`//`, `#`, `--`, `/*`, `*/`, leading `*` inside a block comment).
"Comment line" means the trimmed line is empty or starts with one of those markers. The check enforces that the multiset of non-comment, non-blank lines is identical in old and new — any added or removed code line is a rejection.
func WithConfirmRuntime ¶
func WithConfirmRuntime(ctx context.Context, r *ConfirmRuntime) context.Context
WithConfirmRuntime attaches r to ctx so the Confirm handler can find it.
func WithSkillRuntime ¶
func WithSkillRuntime(ctx context.Context, r *SkillRuntime) context.Context
WithSkillRuntime returns ctx with the runtime attached. Subsequent tool calls can recover it via GetSkillRuntime to consult the stack or catalog.
Types ¶
type AutoConfirmMode ¶
type AutoConfirmMode string
AutoConfirmMode controls how Confirm resolves when no TTY is attached.
const ( AutoConfirmUnset AutoConfirmMode = "" AutoConfirmYes AutoConfirmMode = "yes" AutoConfirmNo AutoConfirmMode = "no" AutoConfirmAbort AutoConfirmMode = "abort" )
Recognised --auto-confirm values. AutoConfirmUnset is treated the same as AutoConfirmAbort but kept distinct so logs can show that no flag was set.
func (AutoConfirmMode) IsValid ¶
func (m AutoConfirmMode) IsValid() bool
IsValid reports whether m is one of the documented values. An empty mode (unset) is considered valid — the runner uses it as the "no flag given" signal.
type BackgroundTaskRegistry ¶
type BackgroundTaskRegistry struct {
// contains filtered or unexported fields
}
BackgroundTaskRegistry manages background task spawning and results.
func NewBackgroundTaskRegistry ¶
func NewBackgroundTaskRegistry(concurrency int) *BackgroundTaskRegistry
NewBackgroundTaskRegistry creates a new registry with the given concurrency limit. If concurrency is <= 0, DefaultConcurrentTasks is used.
func (*BackgroundTaskRegistry) GetResult ¶
func (r *BackgroundTaskRegistry) GetResult(taskID string, wait bool) (*BackgroundTaskResult, bool)
GetResult returns the result for a task ID, blocking until complete if wait is true.
func (*BackgroundTaskRegistry) SpawnTask ¶
func (r *BackgroundTaskRegistry) SpawnTask(ctx context.Context, cfg TaskConfig, args taskArgs, workDir string) string
SpawnTask runs a task in the background and returns its ID immediately.
type BackgroundTaskResult ¶
type BackgroundTaskResult struct {
Output string
Metrics *metrics.Metrics
Err error
Done chan struct{}
}
BackgroundTaskResult holds the result of a background task.
type BgCommandRegistry ¶
type BgCommandRegistry struct {
// contains filtered or unexported fields
}
BgCommandRegistry manages background shell commands.
func GetBgCommandRegistry ¶
func GetBgCommandRegistry(ctx context.Context) *BgCommandRegistry
GetBgCommandRegistry retrieves the registry from context.
func NewBgCommandRegistry ¶
func NewBgCommandRegistry() *BgCommandRegistry
NewBgCommandRegistry creates a new background command registry.
type BudgetQuerier ¶
BudgetQuerier is satisfied by *metrics.Metrics and allows testing without importing the full metrics package.
type CallModelFunc ¶
type CallModelFunc func(ctx context.Context, agentsDir, agentName, prompt, workingDir, mode string) (string, *metrics.Metrics, error)
CallModelFunc is the function signature for invoking a model run from within the Task tool. It mirrors the core model invocation path.
type ChildMaxCostFunc ¶
TaskConfig holds the configuration needed to spawn child agent runs from within the Task tool. ChildMaxCostFunc returns the dedicated cost cap for the named child agent. Returns 0 if no dedicated cap is configured (use remaining budget).
type ChildMaxIterFunc ¶
ChildMaxIterFunc returns the iteration cap for the named child agent. Returns 0 if no dedicated cap is configured (inherit parent's cap).
type ConfirmRuntime ¶
type ConfirmRuntime struct {
// In is the source of user input. Typically os.Stdin.
In io.Reader
// Out is where the prompt is written. Typically os.Stderr because
// stdout is often captured for the agent's final response.
Out io.Writer
// IsTTY, when non-nil, decides whether to take the interactive path.
// A nil IsTTY is treated as "not a TTY" so non-TTY policy applies.
IsTTY func() bool
// AutoConfirm is the resolution policy for non-TTY runs.
AutoConfirm AutoConfirmMode
}
ConfirmRuntime is the per-run state the Confirm tool needs. A nil runtime is treated as if AutoConfirm=abort and no TTY — Confirm calls fail safely. This keeps tests, pipelines, and routines deterministic.
func GetConfirmRuntime ¶
func GetConfirmRuntime(ctx context.Context) *ConfirmRuntime
GetConfirmRuntime returns the runtime stored on ctx, or nil if absent.
type EditEnforcer ¶
type EditEnforcer struct {
Deadline int
// contains filtered or unexported fields
}
EditEnforcer tracks whether an agent has called Edit within a deadline. When the deadline is reached without any Edit calls, it signals the loop to stop — preventing agents from endlessly reading without producing edits.
func GetEditEnforcer ¶
func GetEditEnforcer(ctx context.Context) *EditEnforcer
GetEditEnforcer retrieves the enforcer from the context.
func NewEditEnforcer ¶
func NewEditEnforcer(deadline int) *EditEnforcer
NewEditEnforcer creates an enforcer that triggers after deadline iterations with no Edit call. Returns nil if deadline <= 0 (disabled). The configured deadline is respected as-is — it is never scaled up automatically so that callers retain precise control.
func (*EditEnforcer) CheckNames ¶
func (e *EditEnforcer) CheckNames(names []string) bool
CheckNames inspects tool call names and returns true if the loop should stop. It does NOT set editSeen — call ConfirmEdit after verifying the edit succeeded.
func (*EditEnforcer) ConfirmEdit ¶
func (e *EditEnforcer) ConfirmEdit(toolCalls []llms.ToolCall, results map[string]string)
ConfirmEdit marks the enforcer as having seen a successful edit. Call this after tool execution, only for edit tools whose results indicate success (no error). A failed Edit should not disarm enforcement.
func (*EditEnforcer) PreEdit ¶
func (e *EditEnforcer) PreEdit() bool
PreEdit reports whether the agent has not yet made any edits. It is nil-safe: a nil enforcer is treated as pre-edit.
func (*EditEnforcer) ResetReadProgress ¶
func (e *EditEnforcer) ResetReadProgress()
ResetReadProgress resets the read-only iteration counter. Call this when the agent made discovery progress (read new files) so it isn't penalised for legitimate exploration of a large codebase.
func (*EditEnforcer) ShouldBlockReads ¶
func (e *EditEnforcer) ShouldBlockReads() bool
ShouldBlockReads returns true when the agent has used at least half its edit deadline budget without making any edits. Blocking at the midpoint gives the model enough remaining iterations to actually produce edits, rather than waiting until 2 iterations before the deadline when the agent has already switched to Bash workarounds.
type FailedEdit ¶
type FailedEdit struct {
Index int `json:"index"`
Old string `json:"old"`
Error string `json:"error"`
}
FailedEdit records an edit operation that could not be applied.
type FileTracker ¶
type FileTracker struct {
// contains filtered or unexported fields
}
FileTracker records when files were read by the agent so that edit tools can verify the agent has seen the current content before modifying it.
func GetFileTracker ¶
func GetFileTracker(ctx context.Context) *FileTracker
GetFileTracker retrieves the FileTracker from context, or nil if not set.
func NewFileTracker ¶
func NewFileTracker() *FileTracker
NewFileTracker creates an empty file tracker.
func (*FileTracker) LastReadTime ¶
func (ft *FileTracker) LastReadTime(path string) time.Time
LastReadTime returns when a file was last read, or zero time if never read.
func (*FileTracker) RecordRead ¶
func (ft *FileTracker) RecordRead(path string)
RecordRead records that a file was read at the current time.
func (*FileTracker) ValidateBeforeEdit ¶
func (ft *FileTracker) ValidateBeforeEdit(path string) error
ValidateBeforeEdit checks that the file has been read and hasn't been modified since the last read. Returns nil if safe to edit, or an error describing the problem.
type Finding ¶
type Finding struct {
Title string `json:"title"`
Severity string `json:"severity"`
Category string `json:"category,omitempty"`
Description string `json:"description"`
Evidence string `json:"evidence,omitempty"`
Agent string `json:"agent,omitempty"`
}
Finding represents a single structured finding reported by an agent.
type FindingsStore ¶
type FindingsStore struct {
// contains filtered or unexported fields
}
FindingsStore collects findings from multiple agents in a thread-safe way.
func NewFindingsStore ¶
func NewFindingsStore() *FindingsStore
NewFindingsStore creates an empty findings store.
func (*FindingsStore) Add ¶
func (s *FindingsStore) Add(f Finding)
Add appends a finding to the store.
func (*FindingsStore) All ¶
func (s *FindingsStore) All() []Finding
All returns a copy of all findings.
func (*FindingsStore) Count ¶
func (s *FindingsStore) Count() int
Count returns the number of findings.
func (*FindingsStore) FormatJSON ¶
func (s *FindingsStore) FormatJSON() (string, error)
FormatJSON returns JSON-formatted findings.
func (*FindingsStore) FormatMarkdown ¶
func (s *FindingsStore) FormatMarkdown() string
FormatMarkdown returns a markdown-formatted findings report.
type FlexBool ¶
type FlexBool bool
FlexBool unmarshals both JSON booleans and string representations ("true"/"false") that LLMs sometimes produce for boolean fields.
func (*FlexBool) UnmarshalJSON ¶
type Handler ¶
type Handler struct {
Def llms.Tool
Call func(ctx context.Context, rawArgs []byte) (string, error)
}
Handler pairs a tool definition with its implementation function. Extra tools (e.g., from MCP servers) are registered as Handlers so they participate in the same dispatch path as built-in tools.
type LoopDetector ¶
type LoopDetector struct {
// contains filtered or unexported fields
}
LoopDetector watches for repetitive tool-call patterns by hashing recent (tool-calls + tool-results) steps and detecting when the same signature appears too many times within a sliding window.
func (*LoopDetector) Record ¶
func (ld *LoopDetector) Record(calls []llms.ToolCall, results map[string]string)
Record adds a step (tool calls + their results) to the detector's history.
func (*LoopDetector) Stuck ¶
func (ld *LoopDetector) Stuck() bool
Stuck returns true if any step signature appears more than loopMaxRepeats times within the last loopWindowSize steps.
type MessageRelevance ¶
MessageRelevance pairs a message index with its relevance score.
func ScoreMessages ¶
func ScoreMessages( middle []llms.MessageContent, editedFiles map[string]bool, recentFiles map[string]bool, ) []MessageRelevance
ScoreMessages assigns relevance scores to compactable messages based on which files have been edited and which files are referenced in recent context.
type MultiEditArgs ¶
type MultiEditArgs struct {
Path string `json:"path"`
Edits []MultiEditOperation `json:"edits"`
}
MultiEditArgs are the arguments for the MultiEdit tool.
type MultiEditOperation ¶
type MultiEditOperation struct {
Old string `json:"old"`
New string `json:"new"`
ReplaceAll FlexBool `json:"replace_all"`
}
MultiEditOperation describes a single find-and-replace within a file.
type PhaseEnforcer ¶
type PhaseEnforcer struct {
// NudgeAfter is the number of consecutive read-only iterations before
// injecting the first nudge message telling the agent to start editing.
NudgeAfter int
// contains filtered or unexported fields
}
PhaseEnforcer tracks whether an agent is making progress (editing files) and injects escalating nudge messages when the agent spends too long exploring. After multiple ignored nudges, ShouldBlockReads returns true to force the model to stop reading and start editing.
func GetPhaseEnforcer ¶
func GetPhaseEnforcer(ctx context.Context) *PhaseEnforcer
GetPhaseEnforcer retrieves the PhaseEnforcer from ctx, or nil if not set.
func NewPhaseEnforcer ¶
func NewPhaseEnforcer(nudgeAfter int) *PhaseEnforcer
NewPhaseEnforcer creates a PhaseEnforcer that nudges after n read-only iterations. Returns nil if n <= 0 (disabled).
func (*PhaseEnforcer) ConfirmEdit ¶
func (pe *PhaseEnforcer) ConfirmEdit(toolCalls []llms.ToolCall, results map[string]string)
ConfirmEdit marks the phase enforcer as having seen a successful edit.
func (*PhaseEnforcer) NudgesSent ¶
func (pe *PhaseEnforcer) NudgesSent() int
NudgesSent returns the number of nudge messages sent so far.
func (*PhaseEnforcer) ObserveTools ¶
func (pe *PhaseEnforcer) ObserveTools(toolNames []string) string
ObserveTools inspects the tool calls for the current iteration and returns a nudge message if the agent should be prompted to start editing. Nudges escalate: first is a gentle check, subsequent ones are increasingly forceful. Returns empty string if no nudge is needed. Note: this does NOT set editSeen — call ConfirmEdit after verifying success.
func (*PhaseEnforcer) ResetReadProgress ¶
func (pe *PhaseEnforcer) ResetReadProgress()
ResetReadProgress resets the read-only iteration counter and nudge count. Call this when the agent made discovery progress (read new files) so the enforcer stops treating it as stuck in a loop.
func (*PhaseEnforcer) ShouldBlockReads ¶
func (pe *PhaseEnforcer) ShouldBlockReads() bool
ShouldBlockReads returns true when 2+ nudges have been sent and ignored, indicating the model is stuck in a read loop and reads should be blocked.
type ReadCache ¶
type ReadCache struct {
// contains filtered or unexported fields
}
ReadCache tracks files already read in the current session to avoid wasting tokens on redundant re-reads.
func GetReadCache ¶
GetReadCache retrieves the ReadCache from ctx, or nil if not set.
func (*ReadCache) BumpCompactionEpoch ¶
func (rc *ReadCache) BumpCompactionEpoch()
BumpCompactionEpoch increments the compaction epoch. Call this after context compaction so that subsequent cache hits know the content has been evicted from the conversation and should be served again.
func (*ReadCache) Check ¶
func (rc *ReadCache) Check(path string, contentHash string) (ReadCacheEntry, bool)
Check returns the cached entry if the file content is unchanged. Returns (entry, true) if cached with same hash, (zero, false) otherwise.
func (*ReadCache) CompactionEpoch ¶
CompactionEpoch returns the current compaction epoch for the cache.
func (*ReadCache) Has ¶
Has reports whether a path exists in the cache (regardless of hash). Used to distinguish "new file read" from "re-read" when deciding whether to block reads.
func (*ReadCache) IncrementStreak ¶
IncrementStreak increments and returns the consecutive cache-hit streak counter.
func (*ReadCache) IsStaleAfterCompaction ¶
func (rc *ReadCache) IsStaleAfterCompaction(entry ReadCacheEntry) bool
IsStaleAfterCompaction reports whether the entry was stored before the most recent compaction, meaning its content has been evicted from the conversation and should be served again on the next read.
func (*ReadCache) ResetStreak ¶
func (rc *ReadCache) ResetStreak()
ResetStreak resets the consecutive cache-hit streak counter to zero.
type ReadCacheEntry ¶
type ReadCacheEntry struct {
ContentHash string // SHA-256 of file content
Lines int // number of lines
Bytes int // file size
Iteration int // iteration when first read
Summary string // brief content summary (top-level declarations) for compaction
CompactionEpoch int // compaction epoch when this entry was last served
}
ReadCacheEntry records metadata about a file that has already been read during the current tool-loop session.
type RepeatTracker ¶
RepeatTracker detects when the model calls the same tool with identical arguments multiple times in a row so the loop can be interrupted.
func (*RepeatTracker) Exceeded ¶
func (t *RepeatTracker) Exceeded() bool
Exceeded reports whether the repeat limit for the last tool has been reached.
func (*RepeatTracker) Update ¶
func (t *RepeatTracker) Update(calls []llms.ToolCall)
Update records the current batch of tool calls and increments the repeat counter when the call signature is identical to the previous batch.
type RunWithToolsConfig ¶
type RunWithToolsConfig struct {
// MaxIterations caps the number of model+tool-call cycles. Zero means
// the package default [MaxToolIterations] is used.
MaxIterations int
// EditDeadline is the iteration number after which read-only tools are
// blocked to force the model to commit pending edits. Zero disables the
// deadline.
EditDeadline int
// TaskCfg wires in the Task/TaskResult tools and child-agent dispatch.
// Nil disables the Task tool entirely.
TaskCfg *TaskConfig
// Metrics accumulates token counts and cost across all iterations.
// Nil is allowed; cost tracking and budget enforcement are skipped.
Metrics *metrics.Metrics
// Executor runs shell commands issued by the agent (Bash, Write, etc.).
Executor executor.Executor
// UseCacheControl wraps the system and user prompts with Anthropic's
// cache_control hint. Set this only for the Anthropic provider; other
// LangChain providers silently drop the wrapper.
UseCacheControl bool
// ForceFirstToolCall, when true, appends tool_choice:"required" to the
// call options for the first iteration only. Intended for openai-compat
// endpoints whose default tool_choice:"auto" lets the model skip tools and
// answer immediately. Not set for the regular openai provider, which relies
// on auto behavior.
ForceFirstToolCall bool
// Skill carries the per-run Agent Skills catalog and stack. When non-nil
// and the catalog exposes at least one visible skill, the Skill tool is
// registered and the Read/Bash anchor relaxes to permit access inside
// any skill dir that has been pushed onto the stack.
Skill *SkillRuntime
// Confirm carries the per-run TTY input + auto-confirm policy used by
// the Confirm tool. A nil runtime causes Confirm calls to abort, which
// is the documented default for unattended runs.
Confirm *ConfirmRuntime
// MaxRetries is the number of additional attempts after a failed LLM
// call for transient errors. Zero falls back to DefaultMaxRetries.
MaxRetries int
// SplitToolResults, when true, emits one llms.MessageContent per tool
// result instead of batching all parts into a single message. Required
// for OpenAI chat completions, whose API rejects a single role:"tool"
// message with multiple parts ("expected exactly one part for role
// tool"). Anthropic requires the single-message form, so leave this
// false for the anthropic provider.
SplitToolResults bool
}
RunWithToolsConfig holds the configuration options for RunWithTools.
type SkillRuntime ¶
type SkillRuntime struct {
Entries []skill.Entry
Stack *skill.Stack
// OnLoad, when non-nil, is invoked each time Skill(name) successfully
// pushes an entry. Used by the runner to emit a session event.
OnLoad func(entry skill.Entry)
}
SkillRuntime bundles the per-run skill state the Skill tool needs. Entries is the filtered set the agent's system prompt already lists — the catalog is filtered upstream (in agent.BuildBundleWithOptions) so the Skill tool can only load what the model was told about. Stack is mutated as skills are loaded.
func GetSkillRuntime ¶
func GetSkillRuntime(ctx context.Context) *SkillRuntime
GetSkillRuntime returns the runtime stored on ctx, or nil if none was set.
func (*SkillRuntime) AllowsTool ¶
func (r *SkillRuntime) AllowsTool(name string) bool
AllowsTool reports whether the tool named name is permitted under the active skill stack. The Skill tool itself is always allowed — otherwise a restrictive skill would lock the agent out of loading other skills. When multiple skills are stacked, every skill's allowed-tools list must permit the call (intersection semantics): a skill without a list imposes no restriction, but a single restrictive skill is enough to deny.
func (*SkillRuntime) HasCatalog ¶
func (r *SkillRuntime) HasCatalog() bool
HasCatalog reports whether r is non-nil and exposes at least one skill. The Skill tool is only registered when this is true.
type SmartReadResult ¶
type SmartReadResult struct {
Action string // "full", "warn", "truncate"
Warning string // prepended warning (for "warn" and "truncate")
}
SmartReadResult describes how to handle a file read based on its size.
func ClassifyFileSize ¶
func ClassifyFileSize(lineCount, byteCount int) SmartReadResult
ClassifyFileSize determines the read strategy for a file.
type SystemInfo ¶
type SystemInfo struct {
Hostname string `json:"hostname"`
OS string `json:"os"`
Kernel string `json:"kernel"`
Architecture string `json:"architecture"`
CPUs string `json:"cpus"`
Memory string `json:"memory"`
Disk string `json:"disk"`
Interfaces []string `json:"interfaces,omitempty"`
Containers []string `json:"containers,omitempty"`
Users string `json:"current_user"`
}
SystemInfo holds structured information about the execution environment.
type TaskConfig ¶
type TaskConfig struct {
AgentsDir string
WorkingDir string
MaxIterations int
MaxCost float64 // original budget ceiling from parent
CallModel CallModelFunc
Registry *BackgroundTaskRegistry
ParentMetrics *metrics.Metrics // parent metrics for cost aggregation
Findings *FindingsStore // shared findings store for ReportFinding tool
AgentName string // current agent name (for finding attribution)
ExtraTools []Handler // additional tools injected by MCP servers or other providers
ChildMaxCost ChildMaxCostFunc // per-child budget lookup (nil = use remaining budget)
ChildMaxIter ChildMaxIterFunc // per-child iteration cap (nil = inherit parent's cap)
// RemoteOnly suppresses registration of local-filesystem tools
// (Read/Write/Edit/MultiEdit/Glob/Grep/Bash/RepoMap/SystemInfo) for
// agents whose entire toolset is remote MCP tools.
RemoteOnly bool
}
TaskConfig holds the configuration needed to spawn child agent runs from within the Task tool. It is created once per parent run and shared across all Task tool invocations in that run.
type TokenCalibration ¶
type TokenCalibration struct {
// contains filtered or unexported fields
}
TokenCalibration tracks the ratio between estimated and actual token counts to improve the accuracy of estimateTokens over time.
func GetTokenCalibration ¶
func GetTokenCalibration(ctx context.Context) *TokenCalibration
GetTokenCalibration retrieves the TokenCalibration from context, or nil.
func NewTokenCalibration ¶
func NewTokenCalibration() *TokenCalibration
NewTokenCalibration creates a new calibration tracker.
func (*TokenCalibration) CalibratedEstimate ¶
func (tc *TokenCalibration) CalibratedEstimate(rawEstimate int) int
CalibratedEstimate returns an adjusted token estimate.
func (*TokenCalibration) CorrectionFactor ¶
func (tc *TokenCalibration) CorrectionFactor() float64
CorrectionFactor returns the ratio actual/estimated. Returns 1.0 if no samples recorded yet.
func (*TokenCalibration) Record ¶
func (tc *TokenCalibration) Record(estimated, actual int)
Record adds a sample of estimated vs actual token count.
func (*TokenCalibration) Samples ¶
func (tc *TokenCalibration) Samples() int
Samples returns the number of calibration samples recorded.