agent

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 25 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 (
	// DefaultKeepRecentTokens is the verbatim tail automatic compaction keeps
	// when no configured value is set. Manual /compact is unaffected: it stays
	// at two turns.
	DefaultKeepRecentTokens = 20000
)

Automatic context management. The threshold math follows a reserve rule adapted to GoCode's resolved budget, and every cut point is a whole-turn boundary, so a tool result can never be separated from the call that declared it.

View Source
const DefaultMaxRepeatedToolCalls = 3

DefaultMaxRepeatedToolCalls caps identical repeats per turn; retrying the same call after the same result makes no progress.

View Source
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.

View Source
const DefaultVerifyTimeout = 120 * time.Second

DefaultVerifyTimeout bounds one auto-verify run when VerifyTimeout is unset.

View Source
const SteeringNotice = "[Queued steering applied to the next request.]"

SteeringNotice is emitted once for every drained steering batch. Front-ends key their queued-steering indicator off this exact text.

Variables

View Source
var ErrCompactBlockedByHook = errors.New("compaction blocked by hook")

ErrCompactBlockedByHook reports that a PreCompact hook denied the summary request. Callers must NOT fall back to placeholder compaction: the deny blocks compaction entirely.

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. The base instructions (including safety and approval rules) always come first; project and global context follow as explicitly delimited untrusted blocks. All per-turn state (environment, plan, scratchpad) is one trailing dynamic block, so the prefix above it stays byte-identical across turns and directories.

func EnsureToolPairing added in v0.7.4

func EnsureToolPairing(history []provider.Message) []provider.Message

EnsureToolPairing repairs history so it satisfies the provider wire invariant. OpenAI-shaped and Anthropic APIs reject histories that violate it:

1. at most one system message, and it is at index 0; any further system messages are merged into it rather than dropped; 2. 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; 3. 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

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.

func PruneToolResults added in v0.7.5

func PruneToolResults(history []provider.Message) ([]provider.Message, int)

PruneToolResults replaces oversized, old tool output with a token-count placeholder. The newest pruneProtectTokens of tool output are protected, results smaller than pruneMinResultTokens are never touched, and nothing is rewritten unless the total saving reaches pruneSavingsFloor. Only the content of tool messages changes, so call/result pairing stays valid.

Plan and scratchpad state live in the system prompt, not history, so pruning cannot lose them.

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. Kept for
	// compatibility alongside Bus; removal is a later cleanup once all
	// consumers ride the bus.
	Observe func(LoopEvent)
	// Bus, when set, receives every event the loop produces in addition to
	// Observe, with delivery classes per kind (see loop_bus.go): deltas are
	// lossy frame-fidelity (no coalescing keys), terminal events are
	// must-deliver. Nil-safe: the plain terminal loop and tests run without
	// a bus. The bus never changes what Observe sees, and the exactly-once
	// EventTurnEnd funnel is shared.
	Bus *pubsub.Broker[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
	// Hooks, when set, runs the hook engine on tool calls, turn boundaries
	// and compaction. Nil means no hooks: every hook path is a nil check, so
	// an unconfigured loop pays zero overhead.
	Hooks *hooks.Runner
	// NonInteractive skips TURN hooks (headless parity for non-interactive
	// sessions); tool hooks still fire. Subagent-style nested
	// loops keep Hooks nil and fire nothing.
	NonInteractive bool
	// contains filtered or unexported fields
}

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) AcceptSequence added in v0.8.0

func (a *AgentLoop) AcceptSequence() uint64

AcceptSequence reports the current monotonic accept counter.

func (*AgentLoop) AcceptTurn added in v0.8.0

func (a *AgentLoop) AcceptTurn(text string) uint64

AcceptTurn admits and enqueues a prompt atomically (fire-and-forget acceptance). The prompt runs as its own turn when the executor drains the queue; it is never folded into a running stream — mid-turn guidance is Steer's job. Returns the accept sequence.

func (*AgentLoop) BeginAccepted added in v0.8.0

func (a *AgentLoop) BeginAccepted() uint64

BeginAccepted admits a prompt and returns its monotonic accept sequence. Front-ends call it at accept time (when the prompt arrives), then enter the turn later with RunTurnAccepted; a Cancel landing in between is honored by the mark test at entry (cancel-on-entry).

func (*AgentLoop) CancelMark added in v0.8.0

func (a *AgentLoop) CancelMark() uint64

CancelMark reports the current cancel high-water mark.

func (*AgentLoop) CancelTurns added in v0.8.0

func (a *AgentLoop) CancelTurns() []DispatchCall

CancelTurns cancels the session's dispatch: it raises the cancel mark to the current accept-sequence, cancels the active turn's context (cooperatively — the stream returns context.Canceled and its partial assistant message is kept), and clears the queue, settling EVERY dropped prompt with a persisted cancelled turn row and a terminal cancelled event so no caller hangs. It returns the settled calls in queue order so a front-end can close its per-prompt accounting. Prompts accepted after this call carry sequences above the mark and run normally.

func (*AgentLoop) EnqueueTurn added in v0.8.0

func (a *AgentLoop) EnqueueTurn(seq uint64, text string)

EnqueueTurn queues a prompt accepted earlier with BeginAccepted. If a Cancel covered its sequence in the meantime, the entry test in RunTurnAccepted settles it as cancel-on-entry.

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.

func (*AgentLoop) NextQueuedTurn added in v0.8.0

func (a *AgentLoop) NextQueuedTurn() (text string, seq uint64, ok bool)

NextQueuedTurn pops the oldest queued prompt (FIFO). The executor enters it with RunTurnAccepted, which re-tests the cancel mark atomically.

func (*AgentLoop) PendingSteering added in v0.8.0

func (a *AgentLoop) PendingSteering() int

PendingSteering reports how many steering messages are queued for the running turn. It is observability for front-ends and tests; the queue is drained at the next provider round boundary.

func (*AgentLoop) PublishPermissionModeChanged added in v0.8.0

func (a *AgentLoop) PublishPermissionModeChanged(_ context.Context, change pubsub.PermissionModeChanged)

PublishPermissionModeChanged reports a permission mode switch on the bus.

func (*AgentLoop) PublishPermissionNotification added in v0.8.0

func (a *AgentLoop) PublishPermissionNotification(_ context.Context, n pubsub.PermissionNotification)

PublishPermissionNotification reports one lifecycle transition (requested/granted/denied/cancelled) on the bus.

func (*AgentLoop) PublishPermissionRequest added in v0.8.0

func (a *AgentLoop) PublishPermissionRequest(_ context.Context, req pubsub.PermissionRequest)

PublishPermissionRequest opens a prompt on the bus. The context is ignored in favor of the emit path's bounded must-deliver lane: a cancelled turn must still deliver the prompt's terminal notifications.

func (*AgentLoop) QueuedTurnCount added in v0.8.0

func (a *AgentLoop) QueuedTurnCount() int

QueuedTurnCount reports how many accepted prompts are waiting for their own turn. The TUI queued-pills indicator reads it live.

func (*AgentLoop) Run

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

Run drives the plain terminal loop, rendering engine events. Turn logic lives in RunTurn shared with the TUI: one agent implementation.

func (*AgentLoop) RunTurn added in v0.5.1

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

RunTurn processes one user input synchronously: slash command or full agent turn with tools. It is the self-contained entry for serial callers (the plain REPL, tests): it accepts the input now, and if a concurrent call queues behind it, it drains the queue FIFO before returning — each queued prompt runs as its own turn with its own terminal event. A turn that runs reports EventTurnStart before anything else and exactly one EventTurnEnd, whatever its outcome.

func (*AgentLoop) RunTurnAccepted added in v0.8.0

func (a *AgentLoop) RunTurnAccepted(ctx context.Context, input string, seq uint64) (ran bool, err error)

RunTurnAccepted enters a previously accepted prompt (seq from BeginAccepted/AcceptTurn) through the dispatch state machine. It is the executor entry for front-ends that drive the queue themselves (TUI, headless): it does NOT drain the queue, so the front-end keeps one turn-end handshake and one done record per turn. ran reports whether the turn actually executed: false for cancel-on-entry (settled with a terminal cancelled event), queued (a concurrent turn is active) and empty input. A seq of 0 accepts the input now.

func (*AgentLoop) Steer added in v0.7.5

func (a *AgentLoop) Steer(text string) bool

Steer queues user guidance for the turn that is running. It is accepted only while a turn is in flight: the queue is drained at the next provider round boundary and never injected into a stream already in progress.

type AutoCompactOutcome added in v0.7.5

type AutoCompactOutcome struct {
	// History is the rewritten history; when Changed is false it is the input.
	History []provider.Message
	// Changed reports whether anything (pruning or compaction) was applied.
	Changed bool
	// Summarized is true when the dropped span was replaced by a model-written
	// summary rather than the count-only placeholder.
	Summarized bool
	// PrunedTokens is the estimated token saving from pruning old tool output.
	PrunedTokens int
	// DroppedTurns counts the whole turns folded into the summary.
	DroppedTurns int
	// SummaryErr is set when the summary request failed and the placeholder
	// fallback was used instead.
	SummaryErr error
}

AutoCompactOutcome reports what one automatic context-management pass did.

type CommandContext added in v0.4.0

type CommandContext struct {
	Session        *Session
	Registry       *provider.Registry
	ContextManager *ContextManager
	WorkspaceRoot  string
	AskApproval    func(prompt string) bool
	// Hooks, when set, runs the hook engine for commands that compact
	// (PreCompact deny blocks /compact too). Nil means no hooks.
	Hooks *hooks.Runner
	// Plan, when set, is restated in the compaction summary prompt.
	Plan *tools.PlanStore

	// Ctx is the caller's context, installed by HandleCommand before the
	// handler runs. Handlers that are invoked directly (tests, the palette)
	// read it through Context, which never returns nil.
	Ctx context.Context
}

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

func (CommandContext) Context added in v0.7.5

func (c CommandContext) Context() context.Context

Context returns the caller's context, or a background one when a handler is invoked without HandleCommand.

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 CommandSpec added in v0.7.5

type CommandSpec struct {
	Name        string
	Aliases     []string
	Description string
	Usage       string
	Handle      func(CommandContext, string) CommandResult
}

CommandSpec is one entry in the slash-command registry: the metadata the help text, palette and completion read, and the handler dispatch runs.

Name and Aliases carry their leading slash; aliases without a slash (exit, quit) are the bare forms accepted for compatibility.

func Commands added in v0.7.5

func Commands() []CommandSpec

Commands returns a copy of the registry in display order. The TUI palette, completion and help rendering read it so command metadata has one source.

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
	// ProviderReportedContext is the last provider-reported prompt+completion
	// token count. A local estimate can undercount the same window (framing,
	// tokenizer differences, provider-side rewriting), so accounting uses the
	// larger of the two; see EffectiveTokens.
	ProviderReportedContext int
	// AutoCompact enables automatic compaction when the effective context
	// crosses AutoCompactThreshold. The zero value is off so tests and older
	// callers keep explicit-only behavior; the application wires it from
	// [context] auto_compact (on by default).
	AutoCompact bool
	// KeepRecentTokens is the approximate verbatim tail automatic compaction
	// preserves. Zero or negative means DefaultKeepRecentTokens.
	KeepRecentTokens int
	// Compactions counts every compacted history, so a turn's metrics can
	// report the delta without threading a counter through commands.
	Compactions atomic.Int64
	// PreCompact, when set, is consulted before a compaction summary request
	// Returning blocked=true aborts compaction entirely —
	// callers must not fall back to placeholder compaction. The trigger is
	// "auto" or "manual". Nil means no hook.
	PreCompact func(ctx context.Context, trigger string) (blocked bool, reason string)
	// PostCompact, when set, runs after a compaction summary was persisted
	// Nil means no hook.
	PostCompact func(ctx context.Context, trigger string)
	// LastSummary holds the model-written summary text from the most recent
	// successful CompactWithSummary. The loop persists it as the replay
	// anchor. Placeholder compaction clears it. Empty when no summary ran.
	LastSummary string
	// PlanSnapshot, when set, returns the current plan/todo text to restate in
	// the compaction summary prompt so the resuming assistant keeps tracking
	// it. Nil or empty means no plan block.
	PlanSnapshot func() string
}

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) AutoCompactHistory added in v0.7.5

func (cm *ContextManager) AutoCompactHistory(ctx context.Context, p provider.Provider, model string, history []provider.Message) AutoCompactOutcome

AutoCompactHistory prunes old tool output and, when a pair-safe cut point exists, replaces the turns older than the keep_recent_tokens tail with a summary. A summary failure falls back to the existing count-only placeholder. It never returns an error: when nothing can be done safely it reports Changed=false and leaves history alone.

func (*ContextManager) AutoCompactThreshold added in v0.7.5

func (cm *ContextManager) AutoCompactThreshold(window int) int

AutoCompactThreshold returns the effective-token count above which automatic compaction should run for a model window. The budget is the resolved one (80% of the window, or the configured override). The reserve is 15% of the window, at least minCompactionReserve, and at most half the budget: a small window must not produce a negative threshold.

func (*ContextManager) Compact added in v0.4.0

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

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) EffectiveTokens added in v0.7.5

func (cm *ContextManager) EffectiveTokens(local int) int

EffectiveTokens returns the effective context size for a local estimate: the larger of that estimate and the last provider report. Provider-side compression can make a window look smaller than it is; taking the maximum means growth cannot hide behind it.

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) ObserveProviderUsage added in v0.7.5

func (cm *ContextManager) ObserveProviderUsage(promptTokens, completionTokens int)

ObserveProviderUsage records the provider's own token count for the request it just answered. Non-positive counts are ignored: many providers omit usage, and keeping the previous observation beats replacing it with a wrong zero.

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.

func (*ContextManager) TruncateReport added in v0.7.5

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

TruncateReport is Truncate plus the number of whole turns it dropped, so the agent loop can report a silent last-resort drop instead of hiding it. A history that already fits reports zero.

type DispatchCall added in v0.8.0

type DispatchCall struct {
	Seq  uint64
	Text string
}

DispatchCall identifies one accepted prompt settled by CancelTurns, so a front-end can close its own per-prompt accounting (e.g. a headless turn_done record) for every dropped call.

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.
	// On EventToolDelta it carries the accumulated, sanitized argument preview
	// so far, so a card can update in place.
	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
	// Metrics carries the turn summary on EventTurnEnd; nil on every other
	// kind, so a zero TurnMetrics is never mistaken for a measurement.
	Metrics *TurnMetrics
	// PermissionRequest carries the prompt payload on EventPermissionRequest
	// nil on every other kind.
	PermissionRequest *pubsub.PermissionRequest
	// PermissionNotification carries the lifecycle payload on
	// EventPermissionNotification; nil on every other kind.
	PermissionNotification *pubsub.PermissionNotification
	// PermissionModeChanged carries the mode-switch payload on
	// EventPermissionModeChanged; nil on every other kind.
	PermissionModeChanged *pubsub.PermissionModeChanged
	// Cancelled marks a terminal EventTurnEnd for a turn that never entered
	// the stream: a cancel-on-entry settlement or a queued prompt dropped by
	// CancelTurns. A running turn cancelled mid-stream ends with
	// Err=context.Canceled but Cancelled=false — it ran and kept its partial
	// output. Front-ends use the flag to tell settlements from real turns.
	Cancelled bool
}

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 (
	// EventTurnStart reports that a turn began. It precedes every other event
	// of that turn, so a UI can arm timers before any provider output arrives.
	EventTurnStart LoopEventKind = iota
	// EventDelta is a fragment of assistant text for streaming to a display.
	EventDelta
	// EventToolStart reports a tool call before approval/execution so a UI can show pending state.
	EventToolStart
	// EventToolDelta reports streamed tool-call arguments before the call is
	// complete. It is display-only: approval and execution still wait for the
	// complete ToolCalls flush, so partial JSON can never be acted on.
	EventToolDelta
	// 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. It is
	// emitted exactly once per turn, on every exit path, and carries the
	// turn's metrics.
	EventTurnEnd
	// EventPermissionRequest opens a permission prompt. Must-deliver on
	// the bus; carries PermissionRequest. The UI transport stays the approval
	// bridge this milestone — bus observers get the payload in parallel.
	EventPermissionRequest
	// EventPermissionNotification reports a prompt lifecycle transition
	// (requested/granted/denied/cancelled, ). Must-deliver.
	EventPermissionNotification
	// EventPermissionModeChanged reports a permission mode switch.
	// Must-deliver.
	EventPermissionModeChanged
)

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.

func (*LoopGuard) CheckCall added in v0.5.0

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

CheckCall records a batch; non-nil error means the turn must stop (message is user-facing). Recorded before Execute so failing-tool loops are also bounded.

func (*LoopGuard) Summary added in v0.5.0

func (g *LoopGuard) Summary() string

Summary describes the turn's tool usage, or "" 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
	// 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 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) FlushMessages added in v0.8.0

func (s *Session) FlushMessages()

FlushMessages synchronously persists every queued message. The loop calls it on terminal transitions — turn end, abort, exit — so no message is lost when a turn is cut short. Writes are bounded by the store's busy timeout; this is the FlushAll contract non-interactive clients rely on.

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) RecordSummaryAnchor added in v0.8.0

func (s *Session) RecordSummaryAnchor(compacted []provider.Message)

RecordSummaryAnchor persists a compaction as a flagged summary message plus the retained tail, and anchors replay at the summary row. compacted is the live compacted window ([system?, user-summary, ack,...tail]). The summary and tail are appended AFTER the existing transcript so replay from the anchor reproduces the live window; pre-anchor rows are never deleted. The summary row is relabelled to a user turn on replay.

func (*Session) Scratchpad added in v0.7.4

func (s *Session) Scratchpad() string

Scratchpad returns the agent-maintained working state.

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) SetScratchpad added in v0.7.4

func (s *Session) SetScratchpad(content string)

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

func (s *Session) SetSystemMessage(content string)

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

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

type TurnMetrics added in v0.7.5

type TurnMetrics struct {
	// PromptTokens and CompletionTokens are the provider's own counts when
	// every request in the turn reported usage, and local estimates otherwise.
	PromptTokens     int
	CompletionTokens int
	ToolCalls        int
	Elapsed          time.Duration
	// Retries counts provider retries during the turn.
	Retries int64
	// ProviderReported says which source the token counts came from.
	ProviderReported bool
	// ContextTokens is the effective context size after the last request:
	// max(local estimate, provider-reported prompt+completion) so provider-side
	// compression cannot hide growth. ContextBudget is the resolved budget.
	ContextTokens int
	ContextBudget int
}

TurnMetrics is the observable summary of one turn, emitted with EventTurnEnd. Like the log record it carries counts and timings only: no message content, tool arguments, command text or file paths.

func (TurnMetrics) ContextPercent added in v0.7.5

func (tm TurnMetrics) ContextPercent() (float64, bool)

ContextPercent returns how full the context window is, and false when no budget was resolved or nothing has been measured yet.

Jump to

Keyboard shortcuts

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