agent

package
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2026 License: MIT Imports: 18 Imported by: 0 modules, 0 packages

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

Documentation

Index

Constants

View Source
const DefaultMaxRepeatedToolCalls = 3

DefaultMaxRepeatedToolCalls is how many times the identical tool call (same name and same arguments) may repeat within one turn before the loop stops. A model that retries the exact same call after the exact same result is not making progress and will not make progress with another attempt.

View Source
const DefaultMaxToolIterations = 50

DefaultMaxToolIterations bounds how many provider round-trips a single user turn may make. Without a ceiling, a model that keeps requesting tools — or a tool that keeps failing in a way the model retries identically — produces an unbounded loop that burns tokens and API quota with no user-visible signal.

The limit is deliberately generous: legitimate multi-step work rarely needs more than a few dozen tool round-trips in one turn.

Variables

This section is empty.

Functions

func BuildSystemPrompt added in v0.2.0

func BuildSystemPrompt(projectContext, globalContext string) string

BuildSystemPrompt constructs the complete system prompt with project and global context.

func BuildSystemPromptWithOptions added in v0.4.0

func BuildSystemPromptWithOptions(opts PromptOptions) string

BuildSystemPromptWithOptions constructs the system prompt with rich runtime context.

func FindProjectContext added in v0.2.0

func FindProjectContext(startDir string) (string, string, error)

FindProjectContext scans startDir and parent directories for AGENTS.md, .gocode/AGENTS.md, or docs/AGENTS.md.

func IsExitRequest added in v0.5.1

func IsExitRequest(err error) bool

IsExitRequest reports whether err came from a /exit-style command.

func LoadGlobalContext added in v0.2.0

func LoadGlobalContext() (string, string, error)

LoadGlobalContext loads ~/.config/gocode/CONTEXT.md or %APPDATA%\gocode\CONTEXT.md.

Types

type AgentLoop

type AgentLoop struct {
	Registry       *provider.Registry
	Session        *Session
	ToolRegistry   *tools.Registry
	Approval       *tools.ApprovalGate
	ContextManager *ContextManager
	WorkspaceRoot  string
	// GuardConfig carries the per-turn tool limits. Shared with the TUI path
	// so both loops stop under the same conditions.
	GuardConfig LoopGuardConfig
	// Observe, when set, receives every event the loop produces. Nil means
	// events are discarded, which is only appropriate in tests.
	Observe func(LoopEvent)
	// AskApproval, when set, is used by slash commands that need to prompt
	// the user (for example /commit). The plain terminal loop supplies a
	// stdin-backed implementation; the TUI relies on the approval gate's
	// OnPresent instead and leaves this nil.
	AskApproval func(prompt string) bool
}

AgentLoop is the single agent engine. Both the plain terminal loop and the TUI drive this same type: Run for the plain loop, RunTurn for the TUI.

func NewAgentLoop

func NewAgentLoop(registry *provider.Registry, session *Session, toolReg *tools.Registry, approval *tools.ApprovalGate) *AgentLoop

func (*AgentLoop) EnsureSystemPrompt added in v0.5.1

func (a *AgentLoop) EnsureSystemPrompt()

EnsureSystemPrompt adds the system prompt if the session has none.

func (*AgentLoop) Run

func (a *AgentLoop) Run(ctx context.Context) error

Run drives the plain terminal loop: read a line, hand it to the engine, render the events it emits.

The engine's turn logic lives in RunTurn and is shared with the TUI, so there is exactly one implementation of agent behaviour in the codebase.

func (*AgentLoop) RunTurn added in v0.5.1

func (a *AgentLoop) RunTurn(ctx context.Context, input string) error

RunTurn processes one user input line: a slash command if it is one, otherwise a full agent turn including any tool calls.

This is the entry point the TUI uses. The plain loop in Run calls it too, so there is one implementation of turn handling in the codebase.

type CommandContext added in v0.4.0

type CommandContext struct {
	Session        *Session
	Registry       *provider.Registry
	ContextManager *ContextManager
	WorkspaceRoot  string
	AskApproval    func(prompt string) bool
}

CommandContext holds the environment and services needed to execute slash commands.

type CommandResult added in v0.4.0

type CommandResult struct {
	Handled bool
	Output  string
	Error   error
	Exit    bool
}

CommandResult represents the outcome of executing a command.

func HandleCommand added in v0.4.0

func HandleCommand(ctx context.Context, cmdCtx CommandContext, input string) CommandResult

HandleCommand processes slash commands (and exit/quit). Returns Handled=true if the input was a command, or Handled=false if it should be sent to the LLM.

type ContextManager

type ContextManager struct {
	MaxTokens int
}

ContextManager manages message history size, truncation, and compaction.

func NewContextManager

func NewContextManager(maxTokens int) *ContextManager

NewContextManager creates a ContextManager with the specified max tokens limit. If maxTokens <= 0, defaults to 8192.

func (*ContextManager) Compact added in v0.4.0

func (cm *ContextManager) Compact(history []provider.Message, keepLastTurns int) []provider.Message

Compact summarizes or compresses the history by retaining the system prompt, a brief summary of omitted turns, and the most recent N turns.

func (*ContextManager) EstimateTokens

func (cm *ContextManager) EstimateTokens(msg provider.Message) int

EstimateTokens calculates an approximate token count for a message.

func (*ContextManager) FormatContextStats added in v0.4.0

func (cm *ContextManager) FormatContextStats(history []provider.Message) string

FormatContextStats returns a formatted status string of token usage.

func (*ContextManager) Truncate

func (cm *ContextManager) Truncate(history []provider.Message) []provider.Message

Truncate enforces MaxTokens while preserving conversation structure: 1. Always preserves the system message (if present). 2. Truncates in whole conversation turns so tool-call / tool-result pairs are never separated. 3. Never leaves an orphaned "tool" message at the beginning of the context. 4. Always retains at least the latest user turn.

type LoopEvent added in v0.5.1

type LoopEvent struct {
	Kind    LoopEventKind
	Text    string // delta text, notice body, or error text
	Tool    string // tool name for EventToolResult
	IsError bool
	// Err carries the underlying error on EventTurnEnd.
	Err error
}

LoopEvent is a single thing the agent loop wants the UI to show.

The loop does not know whether it is driving a plain terminal or a Bubble Tea program, so it reports rather than prints. There is exactly one engine; each UI supplies a renderer for these events.

type LoopEventKind added in v0.5.1

type LoopEventKind int

LoopEventKind classifies what the agent loop is reporting.

const (
	// EventDelta is a fragment of assistant text, suitable for streaming to
	// a display.
	EventDelta LoopEventKind = iota
	// EventToolResult reports the outcome of a single tool call.
	EventToolResult
	// EventNotice is informational output that is not an error, such as the
	// tool-usage summary or a slash command's result.
	EventNotice
	// EventError reports a failure the user should see.
	EventError
	// EventExit reports that a slash command asked the UI to shut down. The
	// UI renders any accompanying notice and then quits.
	EventExit
	// EventTurnEnd signals that the turn finished, successfully or not.
	EventTurnEnd
)

type LoopGuard added in v0.5.0

type LoopGuard struct {
	// MaxIterations caps provider round-trips per turn. Zero means
	// DefaultMaxToolIterations.
	MaxIterations int
	// MaxRepeatedCalls caps repeated identical tool calls. Zero means
	// DefaultMaxRepeatedToolCalls.
	MaxRepeatedCalls int
	// ToolCalls counts every tool call seen this turn, for reporting.
	ToolCalls int
	// contains filtered or unexported fields
}

LoopGuard bounds an agent turn. Both the plain loop (agent/loop.go) and the TUI loop (tui/run.go) construct one so the two paths cannot drift again on termination behaviour.

func NewLoopGuard added in v0.5.0

func NewLoopGuard() *LoopGuard

NewLoopGuard returns a guard with defaults applied.

func NewLoopGuardWithConfig added in v0.5.0

func NewLoopGuardWithConfig(cfg LoopGuardConfig) *LoopGuard

NewLoopGuardWithConfig returns a guard configured from user settings, falling back to defaults for any unset or non-positive value.

func (*LoopGuard) CheckCall added in v0.5.0

func (g *LoopGuard) CheckCall(toolCalls []provider.ToolCall) error

CheckCall is called with each batch of tool calls the model requests. It records the calls and reports whether the turn may continue. A non-nil error means the turn must stop, and the message is suitable for showing to the user as the turn's final output.

Calls must be recorded before Execute runs so that the cap also bounds a loop of *failing* tools, not only a loop of succeeding ones.

func (*LoopGuard) Summary added in v0.5.0

func (g *LoopGuard) Summary() string

Summary returns a one-line description of the turn's tool usage, or an empty string when no tools were used.

type LoopGuardConfig added in v0.5.0

type LoopGuardConfig struct {
	// MaxIterations caps provider round-trips per turn.
	MaxIterations int
	// MaxRepeatedCalls caps identical tool calls (same name and arguments)
	// within one turn.
	MaxRepeatedCalls int
}

LoopGuardConfig carries user-configurable limits. Zero values mean "use the built-in default", so an empty config block behaves identically to no block.

type PromptOptions added in v0.4.0

type PromptOptions struct {
	ProjectContext string
	GlobalContext  string
	WorkspaceRoot  string
	OS             string
	Provider       string
	Model          string
}

PromptOptions provides runtime context and custom instructions for prompt construction.

func DefaultPromptOptions added in v0.4.0

func DefaultPromptOptions(workspaceRoot, provider, model string) PromptOptions

DefaultPromptOptions creates a PromptOptions prefilled with host OS and discovered context.

type Session

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

func NewSession

func NewSession(model string) *Session

func NewSessionWithStore added in v0.2.0

func NewSessionWithStore(id, providerName, model string, store *session.SessionStore) *Session

func (*Session) AddMessage

func (s *Session) AddMessage(msg provider.Message)

func (*Session) Clear

func (s *Session) Clear()

func (*Session) ClearModifiedFiles added in v0.2.0

func (s *Session) ClearModifiedFiles()

func (*Session) History

func (s *Session) History() []provider.Message

func (*Session) ID added in v0.2.0

func (s *Session) ID() string

func (*Session) LastAssistantMessage

func (s *Session) LastAssistantMessage() string

func (*Session) LoadMessages added in v0.2.0

func (s *Session) LoadMessages(msgs []provider.Message)

func (*Session) Model

func (s *Session) Model() string

func (*Session) ModifiedFiles added in v0.2.0

func (s *Session) ModifiedFiles() []string

func (*Session) Provider added in v0.2.0

func (s *Session) Provider() string

func (*Session) SetID added in v0.2.0

func (s *Session) SetID(id string)

func (*Session) SetModel

func (s *Session) SetModel(model string)

func (*Session) SetProvider added in v0.2.0

func (s *Session) SetProvider(p string)

func (*Session) Store added in v0.2.0

func (s *Session) Store() *session.SessionStore

func (*Session) TrackModifiedFile added in v0.2.0

func (s *Session) TrackModifiedFile(path string)

type Turn added in v0.4.0

type Turn struct {
	Messages []provider.Message
}

Turn represents a logical conversation turn starting with a user message and including all associated assistant responses, tool calls, and tool results.

func (Turn) Tokens added in v0.4.0

func (t Turn) Tokens(cm *ContextManager) int

Jump to

Keyboard shortcuts

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