Documentation
¶
Index ¶
- Constants
- func BuildSystemPrompt(projectContext, globalContext string) string
- func BuildSystemPromptWithOptions(opts PromptOptions) string
- func EnsureToolPairing(history []provider.Message) []provider.Message
- func FindProjectContext(startDir string) (string, string, error)
- func IsExitRequest(err error) bool
- func LoadGlobalContext() (string, string, error)
- type AgentLoop
- type CommandContext
- type CommandResult
- type ContextManager
- func (cm *ContextManager) Compact(history []provider.Message, keepLastTurns int) []provider.Message
- func (cm *ContextManager) CompactWithSummary(ctx context.Context, p provider.Provider, model string, ...) ([]provider.Message, error)
- func (cm *ContextManager) EstimateTokens(msg provider.Message) int
- func (cm *ContextManager) FormatContextStats(history []provider.Message) string
- func (cm *ContextManager) ResolveBudget(reg *provider.Registry, model string) int
- func (cm *ContextManager) Truncate(history []provider.Message) []provider.Message
- type LoopEvent
- type LoopEventKind
- type LoopGuard
- type LoopGuardConfig
- type PromptOptions
- type Session
- func (s *Session) AddMessage(msg provider.Message)
- func (s *Session) Clear()
- func (s *Session) ClearModifiedFiles()
- func (s *Session) History() []provider.Message
- func (s *Session) ID() string
- func (s *Session) LastAssistantMessage() string
- func (s *Session) LoadMessages(msgs []provider.Message)
- func (s *Session) Model() string
- func (s *Session) ModifiedFiles() []string
- func (s *Session) Provider() string
- func (s *Session) Scratchpad() string
- func (s *Session) SetID(id string)
- func (s *Session) SetModel(model string)
- func (s *Session) SetProvider(p string)
- func (s *Session) SetScratchpad(content string)
- func (s *Session) SetSystemMessage(content string)
- func (s *Session) Store() *session.SessionStore
- func (s *Session) TrackModifiedFile(path string)
- type Turn
Constants ¶
const DefaultMaxRepeatedToolCalls = 3
DefaultMaxRepeatedToolCalls caps identical repeats per turn; retrying the same call after the same result makes no progress.
const DefaultMaxToolIterations = 50
DefaultMaxToolIterations bounds provider round-trips per turn; without it a model requesting tools endlessly burns tokens and quota with no visible signal.
const DefaultVerifyTimeout = 120 * time.Second
DefaultVerifyTimeout bounds one auto-verify run when VerifyTimeout is unset.
Variables ¶
This section is empty.
Functions ¶
func BuildSystemPrompt ¶ added in v0.2.0
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. The base instructions (including safety and approval rules) always come first; project and global context follow as explicitly delimited untrusted blocks, and the environment section closes the prompt.
func EnsureToolPairing ¶ added in v0.7.4
EnsureToolPairing repairs history so it satisfies the provider wire invariant. OpenAI-shaped and Anthropic APIs reject histories that violate it:
- at most one system message, and it is at index 0; any further system messages are merged into it rather than dropped;
- every tool message directly follows an assistant tool_calls message that declares its ToolCallID, and every assistant tool_calls message is followed by exactly one tool result per declared call, in call order;
- tool messages no assistant declares are dropped, and calls without a result get a synthetic result at the call's position, so results always follow the declared call order.
Assistant text content is never dropped. The returned slice is new; the input is not modified.
func FindProjectContext ¶ added in v0.2.0
FindProjectContext scans startDir and parent directories for AGENTS.md, .gocode/AGENTS.md, or docs/AGENTS.md.
func IsExitRequest ¶ added in v0.5.1
IsExitRequest reports whether err came from a /exit-style command.
func LoadGlobalContext ¶ added in v0.2.0
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
// Plan, when set, is rendered into the system prompt and updated by the
// plan tool.
Plan *tools.PlanStore
// Scratchpad, when set, is the working-state store written by the
// scratchpad tool. Its content is mirrored into the session and rendered
// into the system prompt after each successful write.
Scratchpad *tools.ScratchpadStore
// VerifyCommand, when non-empty, runs once after any provider round that
// executed a mutating tool. The user configured it explicitly, so it runs
// without the approval gate, like shell_exec.
VerifyCommand string
// VerifyTimeout bounds each VerifyCommand run; zero or negative means
// DefaultVerifyTimeout.
VerifyTimeout time.Duration
// 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 prompts for slash commands needing confirmation (e.g. /commit).
// The plain loop supplies stdin backing; the TUI uses the approval gate instead.
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 (*AgentLoop) EnsureSystemPrompt ¶ added in v0.5.1
func (a *AgentLoop) EnsureSystemPrompt()
EnsureSystemPrompt installs the prompt for the current run, replacing any prompt carried over from a resumed transcript. Workspace, branch and AGENTS.md context are per-run; a stored prompt would describe the old repo.
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
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
// ConfiguredMaxTokens is the budget the caller asked for. Zero means the
// budget is resolved from the active model's context window each round.
ConfiguredMaxTokens int
// Compactions counts every compacted history, so a turn's metrics can
// report the delta without threading a counter through commands.
Compactions atomic.Int64
}
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, the budget is resolved from the model's context window by ResolveBudget; until then MaxTokens defaults to 8192.
func (*ContextManager) Compact ¶ added in v0.4.0
Compact retains the system prompt, a summary of omitted turns, and the last N turns. The result satisfies EnsureToolPairing's invariant even when an omitted turn boundary splits a call from its result.
func (*ContextManager) CompactWithSummary ¶ added in v0.7.4
func (cm *ContextManager) CompactWithSummary(ctx context.Context, p provider.Provider, model string, history []provider.Message, keepLastTurns int) ([]provider.Message, error)
CompactWithSummary replaces older turns with a model-written summary of them. It keeps the system prompt, a summary pair, and the last keepLastTurns turns. Unlike Compact, the summary records decisions and open files instead of only counting what was dropped, so the model can continue coherently.
The provider call is bounded; an error or an empty answer is returned to the caller, which is expected to fall back to Compact.
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) ResolveBudget ¶ added in v0.7.4
func (cm *ContextManager) ResolveBudget(reg *provider.Registry, model string) int
ResolveBudget picks the token budget for model and stores it in MaxTokens. An explicit configured budget always wins. Otherwise the budget is 80% of the model's context window, clamped to [4096, window], leaving headroom for the response. The loop calls this before every Truncate, so switching models takes effect on the next provider round.
func (*ContextManager) Truncate ¶
func (cm *ContextManager) Truncate(history []provider.Message) []provider.Message
Truncate enforces MaxTokens in whole turns, preserving system message and latest turn. It always returns history satisfying EnsureToolPairing's invariant: resumed transcripts and compaction can leave orphaned calls or results behind.
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 EventToolStart and EventToolResult
IsError bool
// ToolCallID correlates start/result for the same call so a UI cannot attribute
// a result to the wrong call when several run in one batch.
ToolCallID string
// Args carries raw JSON arguments on EventToolStart so a card can show the
// request without waiting for execution; the UI decides how much to show.
Args string
// Diff carries a unified diff on EventToolResult; kept separate from Text
// so a UI can colour added/removed lines instead of parsing prose.
Diff string
// Err carries the underlying error on EventTurnEnd.
Err error
}
LoopEvent is a single thing the agent loop wants the UI to show. The loop reports rather than prints; each UI supplies a renderer.
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 for streaming to a display. EventDelta LoopEventKind = iota // EventToolStart reports a tool call before approval/execution so a UI can show pending state. EventToolStart // EventToolResult reports the outcome of a single tool call. EventToolResult // EventNotice is informational output that is not an error. 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 plain and TUI loops use one so they cannot drift 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.
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
// Plan is the agent-authored checklist rendered by the plan tool. It is
// placed before untrusted context, because the assistant itself wrote it.
Plan string
// Scratchpad is agent-maintained working state persisted across compaction.
// Like Plan it is written by the assistant, so it renders before untrusted
// context and is explicitly labelled as state, not policy.
Scratchpad 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 NewSessionWithStore ¶ added in v0.2.0
func NewSessionWithStore(id, providerName, model string, store *session.SessionStore) *Session
func (*Session) AddMessage ¶
func (*Session) ClearModifiedFiles ¶ added in v0.2.0
func (s *Session) ClearModifiedFiles()
func (*Session) LastAssistantMessage ¶
func (*Session) LoadMessages ¶ added in v0.2.0
func (*Session) ModifiedFiles ¶ added in v0.2.0
func (*Session) Scratchpad ¶ added in v0.7.4
Scratchpad returns the agent-maintained working state.
func (*Session) SetProvider ¶ added in v0.2.0
func (*Session) SetScratchpad ¶ added in v0.7.4
SetScratchpad replaces the agent-maintained working state and persists it when the session is bound to a store.
func (*Session) SetSystemMessage ¶ added in v0.7.4
SetSystemMessage makes content the session's only system message, replacing an existing prompt (and dropping duplicates) or prepending when none exists. Resumed transcripts carry the prompt of the workspace they were recorded in, so callers rebuild it instead of trusting the stored copy.
func (*Session) Store ¶ added in v0.2.0
func (s *Session) Store() *session.SessionStore