agent

package
v1.3.105 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenerateInsights added in v1.3.101

func GenerateInsights(stats RunStats) string

GenerateInsights produces a human-readable summary of the run stats suitable for saving to project memory. Returns empty string if the run is too trivial to warrant a memory entry (e.g., no tools were called).

func MergeInsights added in v1.3.101

func MergeInsights(existing, newEntry string) string

MergeInsights appends a new run reflection to the existing insights file, keeping only the most recent 10 entries to prevent unbounded growth. Shared between TUI, daemon, and desktop surfaces.

func ShouldReflect added in v1.3.101

func ShouldReflect(stats RunStats) bool

ShouldReflect returns true if the run stats warrant a reflection entry. Only runs with meaningful work (3+ tool calls, file edits, or commands) get reflections.

func SplitRunEntries added in v1.3.101

func SplitRunEntries(content string) []string

SplitRunEntries splits the memory file into individual run reflection blocks. Shared between TUI, daemon, and desktop surfaces.

Types

type Agent

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

Agent orchestrates the agentic loop: send messages to LLM, execute tool calls, loop.

func NewAgent

func NewAgent(p provider.Provider, tools *tool.Registry, systemPrompt string, maxIter int) *Agent

NewAgent creates a new agent with optional permission policy.

func (*Agent) AddMessage

func (a *Agent) AddMessage(msg provider.Message)

AddMessage appends a message to the conversation context.

func (*Agent) AddedSinceRunStart added in v1.3.101

func (a *Agent) AddedSinceRunStart() []provider.Message

AddedSinceRunStart returns messages added by the agent via Add() during the most recent RunStreamWithContent call. Used by session persistence to determine which messages need to be appended to the JSONL file.

func (*Agent) CancelPreCompact added in v1.1.45

func (a *Agent) CancelPreCompact()

CancelPreCompact aborts any in-flight pre-compact. Safe to call from session-clear, /clear, /compact, SetContextManager or app shutdown.

The goroutine sees its bgCtx cancelled, marks the state as cancelled, then closes done. A later consumeReadyPreCompact will discard the result.

func (*Agent) CheckpointManager

func (a *Agent) CheckpointManager() *checkpoint.Manager

CheckpointManager returns the checkpoint manager.

func (*Agent) Clear

func (a *Agent) Clear()

Clear resets the conversation (keeps system prompt).

func (*Agent) Close added in v1.1.60

func (a *Agent) Close()

Close releases resources held by the agent, including cancelling any in-flight pre-compact operations. Should be called on shutdown.

func (*Agent) ContextManager

func (a *Agent) ContextManager() ctxpkg.ContextManager

func (*Agent) GetHookConfig added in v1.3.98

func (a *Agent) GetHookConfig() hooks.HookConfig

GetHookConfig returns the current hook configuration (thread-safe).

func (*Agent) Messages

func (a *Agent) Messages() []provider.Message

Messages returns the current conversation messages.

func (*Agent) MicrocompactIfOverThreshold added in v1.3.101

func (a *Agent) MicrocompactIfOverThreshold() (compacted bool, beforeTokens int, afterTokens int)

MicrocompactIfOverThreshold is kept as a no-op for API compatibility. Microcompact was removed — precompact at 97.5% + reactive compact on PTL now handle all compaction needs without corrupting tool_result data.

func (*Agent) PermissionPolicy

func (a *Agent) PermissionPolicy() permission.PermissionPolicy

PermissionPolicy returns the current policy.

func (*Agent) PreCompactStatus added in v1.1.45

func (a *Agent) PreCompactStatus() PreCompactStatus

PreCompactStatus reports the current background pre-compact status, or a zero value if none is running. Used by the TUI status panel to surface a "compacting…" indicator instead of leaving the user wondering why tokens are at the threshold.

func (*Agent) ProcessErrorsWithLLM added in v1.3.101

func (a *Agent) ProcessErrorsWithLLM(errors []string, existingRules []Rule) (*ratchetLLMOutput, error)

ProcessErrorsWithLLM sends unmatched errors to the agent's provider for generalization. Uses the current model. Called asynchronously after a run.

func (*Agent) ProjectMemoryFiles added in v1.1.30

func (a *Agent) ProjectMemoryFiles() []string

func (*Agent) Provider

func (a *Agent) Provider() provider.Provider

func (*Agent) ReasoningEffort added in v1.3.68

func (a *Agent) ReasoningEffort() string

func (*Agent) ReconcileToolCalls added in v1.3.87

func (a *Agent) ReconcileToolCalls() bool

ReconcileToolCalls checks the conversation history for unpaired tool_use blocks (tool_calls without matching tool_result blocks across ALL assistant messages) and adds cancelled tool_result entries to keep the conversation valid for LLM APIs. See context.Manager.ReconcileToolCalls() for details.

func (*Agent) RunStream

func (a *Agent) RunStream(ctx context.Context, userMsg string, onEvent func(provider.StreamEvent)) error

RunStream runs the agent loop with streaming, sending events to the callback.

func (*Agent) RunStreamWithContent

func (a *Agent) RunStreamWithContent(ctx context.Context, content []provider.ContentBlock, onEvent func(provider.StreamEvent)) (err error)

RunStreamWithContent runs the agent loop and emits UI events for complete model turns.

func (*Agent) SetApprovalHandler

func (a *Agent) SetApprovalHandler(fn ApprovalFunc)

SetApprovalHandler sets a callback for interactive approval (Ask → Deny by default). If nil, Ask decisions are treated as Deny. The callback receives the per-run context so it can abort cleanly if the agent is cancelled while waiting.

func (*Agent) SetAutopilotGoal added in v1.3.92

func (a *Agent) SetAutopilotGoal(goal string)

SetAutopilotGoal stores the confirmed goal text. Called by the ask_user result handler when the goal confirmation question is answered.

func (*Agent) SetCheckpointHandler added in v1.1.43

func (a *Agent) SetCheckpointHandler(fn func(messages []provider.Message, tokenCount int))

SetCheckpointHandler sets a callback invoked after summarize compaction to persist the compacted message state.

func (*Agent) SetCheckpointManager

func (a *Agent) SetCheckpointManager(m *checkpoint.Manager)

SetCheckpointManager sets the checkpoint manager for undo support.

func (*Agent) SetContextManager

func (a *Agent) SetContextManager(cm ctxpkg.ContextManager)

SetContextManager replaces the default context manager.

func (*Agent) SetDiffConfirm

func (a *Agent) SetDiffConfirm(fn DiffConfirmFunc)

SetDiffConfirm sets the diff confirmation callback.

func (*Agent) SetHookConfig

func (a *Agent) SetHookConfig(cfg hooks.HookConfig)

SetHookConfig sets the hooks configuration.

func (*Agent) SetInterruptionHandler added in v1.1.15

func (a *Agent) SetInterruptionHandler(fn func() string)

SetInterruptionHandler sets a callback that drains user guidance arriving mid-run.

func (*Agent) SetMetricHandler added in v1.3.43

func (a *Agent) SetMetricHandler(fn func(metrics.MetricEvent))

SetMetricHandler sets a callback invoked after each LLM call or tool execution with performance metrics (TTFT, think time, tool duration, etc.). The callback must be non-blocking — it should send to a channel or drop if busy.

func (*Agent) SetPermissionPolicy

func (a *Agent) SetPermissionPolicy(policy permission.PermissionPolicy)

SetPermissionPolicy sets the permission policy for tool checks. When switching to or from autopilot mode, the autopilot Goal state is reset accordingly.

func (*Agent) SetProbeKey added in v1.2.11

func (a *Agent) SetProbeKey(key string)

SetProbeKey sets the probe cache key ("vendor|baseURL|model") used for context window auto-detection from overflow errors.

func (*Agent) SetProjectMemoryFiles added in v1.1.30

func (a *Agent) SetProjectMemoryFiles(files []string)

SetProjectMemoryFiles seeds the set of already-loaded project memory files so path-triggered dynamic loading can avoid reinjecting startup guidance.

func (*Agent) SetProvider

func (a *Agent) SetProvider(p provider.Provider)

ContextManager returns the context manager for external inspection.

func (*Agent) SetReasoningEffort added in v1.3.68

func (a *Agent) SetReasoningEffort(effort string) bool

func (*Agent) SetReflectionFunc added in v1.3.101

func (a *Agent) SetReflectionFunc(fn ReflectionFunc)

SetReflectionFunc registers a callback invoked after each run. Pass nil to disable. The callback is invoked asynchronously (in a goroutine) to avoid blocking the next user interaction.

func (*Agent) SetRunResultHandler added in v1.1.84

func (a *Agent) SetRunResultHandler(fn func(error))

SetRunResultHandler sets a callback invoked after each RunStreamWithContent call completes. The callback receives the final error, if any.

func (*Agent) SetRunResultWithContentHandler added in v1.1.84

func (a *Agent) SetRunResultWithContentHandler(fn func([]provider.ContentBlock, error))

SetRunResultWithContentHandler sets a callback invoked after each RunStreamWithContent call completes. The callback receives the original user content and the final error, if any.

func (*Agent) SetSessionID added in v1.3.101

func (a *Agent) SetSessionID(id string)

SetSessionID sets the current session ID and propagates it to the todo tool and context manager so both read/write from the same session-scoped path.

func (*Agent) SetSupportsVision added in v1.1.34

func (a *Agent) SetSupportsVision(v bool)

SetSupportsVision controls whether tool_result images are included in messages sent to the provider. When false, image data is stripped from tool results and only the text placeholder is sent.

func (*Agent) SetSystemPromptInjector added in v1.3.101

func (a *Agent) SetSystemPromptInjector(fn func() string)

SetSystemPromptInjector sets a callback that returns extra text to inject into the system prompt at the start of each RunStreamWithContent. This is used for dynamic warnings (e.g. lanchat peers editing the same workspace). If the callback returns empty string, no injection occurs.

func (*Agent) SetUsageHandler

func (a *Agent) SetUsageHandler(fn func(usage provider.TokenUsage))

SetUsageHandler sets a callback invoked after each API call with token usage.

func (*Agent) SetWorkingDir

func (a *Agent) SetWorkingDir(dir string)

SetWorkingDir sets the working directory for hooks.

func (*Agent) StartPreCompact added in v1.1.45

func (a *Agent) StartPreCompact()

StartPreCompact initiates a background compaction if conditions warrant it. Returns immediately. Safe to call after every agent run; it self-skips when tokens are below threshold or a compact is already in flight.

The background goroutine compacts an immutable snapshot with its own context.WithTimeout(60s). It never mutates the live context directly; the result is applied later by consumeReadyPreCompact only if it has already finished at a safe run boundary.

func (*Agent) StartRunTracking added in v1.3.101

func (a *Agent) StartRunTracking()

StartRunTracking clears the run-added message tracking. This is normally called inside RunStreamWithContent, but callers can invoke it earlier (e.g. before ExpandMentions) to ensure AddedSinceRunStart returns empty instead of stale data from a previous run if the agent never starts.

func (*Agent) SupportsVision added in v1.1.34

func (a *Agent) SupportsVision() bool

func (*Agent) SystemPrompt added in v1.1.43

func (a *Agent) SystemPrompt() string

SystemPrompt returns the current system prompt (from the first system message).

func (*Agent) ToolRegistry added in v1.1.43

func (a *Agent) ToolRegistry() *tool.Registry

ToolRegistry returns the tool registry used by this agent.

func (*Agent) UpdateSystemPrompt added in v1.1.34

func (a *Agent) UpdateSystemPrompt(text string)

UpdateSystemPrompt replaces the first system message in the context. Also updates baseSystemPrompt so dynamic injection resets to this base.

func (*Agent) WorkingDir added in v1.1.45

func (a *Agent) WorkingDir() string

type ApprovalFunc added in v1.1.45

type ApprovalFunc func(ctx context.Context, toolName string, input string) permission.Decision

ApprovalFunc is called when a tool requires interactive approval. It MUST honor ctx.Done() to avoid a goroutine leak if the TUI exits while a permission prompt is awaiting user input.

type DiffConfirmFunc

type DiffConfirmFunc func(ctx context.Context, filePath, diffText string) bool

DiffConfirmFunc is called before a file write to request user confirmation. It receives a context, the file path and unified diff string, and returns true if approved. Implementations MUST honor ctx.Done() so the agent goroutine doesn't leak when the TUI shuts down while a confirmation is in flight.

type PreCompactStatus added in v1.1.45

type PreCompactStatus struct {
	Running   bool
	StartedAt time.Time
	StartTok  int
}

PreCompactStatus is a UI-friendly snapshot of any in-flight pre-compact. Returned by Agent.PreCompactStatus(). All fields are zero-valued when none is running.

type ReflectionFunc added in v1.3.101

type ReflectionFunc func(stats RunStats)

ReflectionFunc is called after each RunStreamWithContent completes, with the accumulated stats. Implementations may save insights to memory, emit metrics, or trigger follow-up actions. The function must be safe to call from a goroutine and must not block the agent loop.

type Rule added in v1.3.101

type Rule struct {
	ID           string    `json:"id"`
	Category     string    `json:"category"`               // build | test | git | convention | security
	Rule         string    `json:"rule"`                   // human-readable rule text
	MatchPattern string    `json:"match_pattern"`          // regexp to match error OUTPUT (for auto-verify)
	ToolPattern  string    `json:"tool_pattern,omitempty"` // regexp to match tool ARGS (for injection)
	FixHint      string    `json:"fix_hint,omitempty"`     // optional actionable hint
	HitCount     int       `json:"hit_count"`
	LastSeen     time.Time `json:"last_seen"`
	CreatedAt    time.Time `json:"created_at"`
}

Rule represents a learned harness rule extracted from agent errors.

type RuleStore added in v1.3.101

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

RuleStore manages harness rules persisted to .ggcode/agent-rules.json.

func NewRuleStore added in v1.3.101

func NewRuleStore(workingDir string) *RuleStore

NewRuleStore creates a RuleStore for the given working directory.

func (*RuleStore) AddRule added in v1.3.101

func (rs *RuleStore) AddRule(r Rule)

AddRule adds a new rule, enforcing the max limit with LRU eviction.

func (*RuleStore) MatchErrors added in v1.3.101

func (rs *RuleStore) MatchErrors(errors []string) (matched []string, unmatched []string)

MatchErrors checks each error against existing rules. Returns matched (with updated hit_count) and unmatched errors.

func (*RuleStore) MatchingRulesForTool added in v1.3.101

func (rs *RuleStore) MatchingRulesForTool(toolName, args string) []Rule

MatchingRulesForTool returns rules whose category matches the tool name and whose ToolPattern (or MatchPattern as fallback) matches the tool arguments. Used for rule injection into tool results.

func (*RuleStore) Rules added in v1.3.101

func (rs *RuleStore) Rules() []Rule

Rules returns a copy of all rules.

type RunStats added in v1.3.101

type RunStats struct {
	// ToolCalls maps tool name to number of invocations.
	ToolCalls map[string]int

	// FilesEdited lists distinct file paths that were written or edited.
	FilesEdited []string

	// CommandsRun lists shell commands executed via run_command or start_command.
	CommandsRun []string

	// Errors records error messages from failed tool calls or stream errors.
	// Truncated to 500 chars each, max 10 entries.
	Errors []string

	// Duration is the wall-clock time from run start to completion.
	Duration time.Duration

	// Iterations is the number of LLM turns in the agent loop.
	Iterations int

	// Success is true if the run completed without error.
	Success bool

	// UserPrompt is the first 200 chars of the user's input, for context.
	UserPrompt string
	// contains filtered or unexported fields
}

RunStats accumulates observability data during a single RunStreamWithContent call. It is the input to the reflection system (the "hill climbing loop"): after each run, the stats are analyzed to extract insights that compound across sessions.

type VerifyResult added in v1.3.101

type VerifyResult struct {
	Passed  bool     `json:"passed"`
	Errors  []string `json:"errors,omitempty"`
	Command string   `json:"command"`
	Output  string   `json:"output,omitempty"`
}

VerifyResult is the outcome of an auto-verification check.

Jump to

Keyboard shortcuts

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