loop

package
v0.1.39 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// FallbackAuto (default): retry the primary once on transient errors, then
	// route to the next healthy fallback, skipping providers in cooldown.
	FallbackAuto = "auto"
	// FallbackConfirm asks the user before serving a fallback from a DIFFERENT
	// vendor than the primary; same-vendor fallbacks route automatically.
	FallbackConfirm = "confirm"
	// FallbackPrimaryOnly never falls back — a primary failure ends the turn
	// with an error.
	FallbackPrimaryOnly = "primary_only"
)

FallbackPolicy controls automatic model routing when the primary provider fails mid-turn.

Variables

This section is empty.

Functions

func CalculateAdaptiveToolBudget

func CalculateAdaptiveToolBudget(prompt string, mode string) int

func SelfHealLadder

func SelfHealLadder(ctx context.Context, filePath string) (string, bool)

SelfHealLadder executes deterministic local formatters/fixers on edited files. It repairs syntax formatting (e.g. gofmt, prettier, eslint --fix) locally before wasting LLM turns on minor syntax or formatting errors.

func TestCommandPlan

func TestCommandPlan() []string

TestCommandPlan returns the planned verification commands as shell command lines (for the model-callable run_tests tool), in order, or nil when the project has no recognized test/build system. Reuses planVerification so the harness gate and the on-demand tool never diverge.

Types

type AgentTurn

type AgentTurn struct {
	Reasoning string              `json:"reasoning"`
	ToolCalls []provider.ToolCall `json:"tool_calls,omitempty"`
	Answer    string              `json:"answer,omitempty"`
}

AgentTurn enforces thinking before answering (§2.2).

type Engine

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

Engine orchestrates the ReAct loop and verification ladder.

func NewEngine

func NewEngine(adapter provider.ProviderAdapter, tools *tool.Registry, ctxMgr *bcontext.Manager, model string) *Engine

NewEngine creates an agent loop engine instance.

func (*Engine) AddFallback

func (e *Engine) AddFallback(fb Fallback)

AddFallback registers a fallback provider+model tried on primary failure.

func (*Engine) CostSummary

func (e *Engine) CostSummary() string

CostSummary returns the session's estimated cost report (per model + total).

func (*Engine) CostUSD

func (e *Engine) CostUSD() float64

CostUSD returns the accumulated estimated spend (USD) for the current turn.

func (*Engine) FallbackCount

func (e *Engine) FallbackCount() int

FallbackCount returns how many turns a fallback provider has served.

func (*Engine) LastFallbackModel

func (e *Engine) LastFallbackModel() string

LastFallbackModel returns the fallback model used in the most recent turn ("" when the primary provider served it).

func (*Engine) LastFallbackReason

func (e *Engine) LastFallbackReason() string

LastFallbackReason returns the primary provider's error that triggered the fallback in the most recent turn ("" when the primary served it). This is how the UI tells the user WHY — e.g. a FreeBuff duration/queue limit or an invalid model — rather than silently swapping providers.

func (*Engine) LearnerStats

func (e *Engine) LearnerStats() string

LearnerStats returns the self-improving layer's status line for the HUD/debug.

func (*Engine) Mode

func (e *Engine) Mode() string

func (*Engine) PrimaryCooldownRemaining

func (e *Engine) PrimaryCooldownRemaining() time.Duration

PrimaryCooldownRemaining reports how long the primary provider is currently cooling down from recent failures (0 when healthy). While positive, the router skips the primary and goes straight to a healthy fallback.

func (*Engine) RunTurn

func (e *Engine) RunTurn(ctx context.Context, userQuery string, onUpdate TurnOutputHandler) (answer string, err error)

func (*Engine) RunTurnWithUsage added in v0.1.1

func (e *Engine) RunTurnWithUsage(ctx context.Context, userQuery string, onUpdate TurnOutputHandler) (answer string, tokens int, cost float64, compactions int, err error)

RunTurnWithUsage runs a full turn and additionally returns the raw token count and estimated cost attributed to it. Both are available on the error path too, so callers (sub-agents, phase attribution) can bill partial work when a turn fails partway through.

func (*Engine) SessionCostUSD

func (e *Engine) SessionCostUSD() float64

SessionCostUSD returns the total estimated spend so far (for the footer).

func (*Engine) SetAgentPrompt added in v0.1.36

func (e *Engine) SetAgentPrompt(p string)

SetAgentPrompt sets the custom instructions for the active custom agent.

func (*Engine) SetAskHandler

func (e *Engine) SetAskHandler(fn func(question string, options []string) (string, error))

SetAskHandler wires an interactive question handler for turn extensions.

func (*Engine) SetBudgetUSD

func (e *Engine) SetBudgetUSD(usd float64)

SetBudgetUSD caps the turn's total estimated spend in USD. 0 (the default) disables the cap. Applied per user turn — the counter resets when the turn starts.

func (*Engine) SetCompactModel

func (e *Engine) SetCompactModel(m string)

SetCompactModel routes compaction summarization to a (cheaper) model. Empty keeps it on the main synthesis model.

func (*Engine) SetDetectedStacks added in v0.1.1

func (e *Engine) SetDetectedStacks(stacks []prompt.Stack)

SetDetectedStacks wires the repo's detected languages (with evidence files) so the prompt builder can render a STACK hint and bias the skill-catalog ranking toward the repo.

func (*Engine) SetDiagnosticsChecker

func (e *Engine) SetDiagnosticsChecker(fn func(path string) string)

SetDiagnosticsChecker wires a native type-error checker (the UI provides one backed by the LSP manager). It runs on edited files after the convention review, catching type errors without waiting for a full build.

func (*Engine) SetEarlyExitOnError added in v0.1.2

func (e *Engine) SetEarlyExitOnError(v bool)

SetEarlyExitOnError enables stopping remaining tool execution in a round when a mutating tool fails. This prevents the model from cascading into error-after-error when a prerequisite edit/build command fails. Enabled by default.

func (*Engine) SetFallbackPolicy

func (e *Engine) SetFallbackPolicy(policy string)

SetFallbackPolicy sets the routing policy (FallbackAuto / FallbackConfirm / FallbackPrimaryOnly). The default is FallbackAuto.

func (*Engine) SetHooks

func (e *Engine) SetHooks(h *hooks.Manager)

SetHooks wires a lifecycle hooks manager. Nil disables hooks.

func (*Engine) SetKnowledgeStore added in v0.1.2

func (e *Engine) SetKnowledgeStore(st *store.Store)

SetKnowledgeStore wires the Smart Context Graph backend. When set, the engine queries it at turn-start for relevance-ranked file hints and injects them as a "SMART CONTEXT" block in the system prompt — helping the agent avoid re-scanning files it has already analyzed in prior sessions.

func (*Engine) SetLSPStatus

func (e *Engine) SetLSPStatus(n int)

SetLSPStatus records how many language servers are available this session. The system prompt reads it to decide whether lsp_scan is usable and to steer the model away from installing external linters when LSP is missing.

func (*Engine) SetLearner

func (e *Engine) SetLearner(l *learn.Learner)

SetLearner attaches the self-improving control layer. It immediately applies the learned compaction ratio so the session starts with the tuned threshold rather than the default, and observes each turn to keep converging.

func (*Engine) SetMaxIterations

func (e *Engine) SetMaxIterations(n int)

SetMaxIterations overrides the loop iteration cap (default 25). Used by the benchmark harness to bound each case. Setting it also marks the cap as explicit (baseMaxIterations > 0), so the per-turn reset honors it instead of re-deriving a complexity tier.

func (*Engine) SetMemoryStore

func (e *Engine) SetMemoryStore(st *memory.Store)

SetMemoryStore wires the cross-session project memory. When set, a warm-start excerpt of past sessions' learnings is injected into the system prompt, and compaction summaries are auto-merged back into memory.

func (*Engine) SetMode

func (e *Engine) SetMode(m string)

func (*Engine) SetOnChange

func (e *Engine) SetOnChange(fn func(path, diff string))

SetOnChange wires a callback invoked whenever a write/edit tool succeeds, with the file path and its unified diff — so the host can render a live red/green diff entry in the chat as each edit lands.

func (*Engine) SetOnFileEdited

func (e *Engine) SetOnFileEdited(fn func(path string))

SetOnFileEdited wires a callback invoked whenever a write/edit tool succeeds, so the host can keep session-scoped caches (e.g. the symbol index) fresh.

func (*Engine) SetPrimaryIdentity

func (e *Engine) SetPrimaryIdentity(id, protocol string)

SetPrimaryIdentity tells the router which provider is the active primary and its wire protocol, so health tracking keys correctly and the "confirm" policy can distinguish cross-vendor fallbacks.

func (*Engine) SetProjectContext

func (e *Engine) SetProjectContext(pc string)

SetProjectContext injects a compact structural overview of the project into every turn's system prompt (see search.BuildProjectContext). Empty disables.

func (*Engine) SetRepoMap

func (e *Engine) SetRepoMap(rm string)

SetRepoMap injects the deterministic project map (entry points, structure, hot files by usage) into every turn's system prompt. Empty disables.

func (*Engine) SetReviewLLM

func (e *Engine) SetReviewLLM(on bool)

SetReviewLLM toggles the senior-level LLM code review (Layer 2) that runs after the deterministic checks pass. On by default; turn off where an extra completion per edit is not worth it (tests, cheap/headless contexts).

func (*Engine) SetScopeFiles added in v0.1.2

func (e *Engine) SetScopeFiles(files []string)

SetScopeFiles injects the full project file list for smart scope pre-selection: given a user prompt, ScoreFiles() ranks files by relevance so BroCode can focus exploration on the most likely targets instead of scanning the entire workspace. Empty disables.

func (*Engine) SetScoutManager

func (e *Engine) SetScoutManager(sm ScoutDrainer)

SetScoutManager wires the background scout manager. Nil disables scout result delivery (the scout tool itself then reports an error).

func (*Engine) SetSkillCatalog added in v0.1.1

func (e *Engine) SetSkillCatalog(entries []prompt.SkillEntry)

SetSkillCatalog injects the installed skill catalog (name + description only; the model loads each SKILL.md itself). Empty disables the skills block. The catalog is relevance-filtered by the prompt builder when it exceeds the tuning threshold.

func (*Engine) SetStreamHandler

func (e *Engine) SetStreamHandler(fn func(delta string))

SetStreamHandler wires a callback receiving content deltas while the model streams its answer. Nil disables streaming (adapters fall back to Complete).

func (*Engine) SetSymbolsProvider

func (e *Engine) SetSymbolsProvider(fn func() map[string]map[string]bool)

SetSymbolsProvider wires a global symbol provider for cross-file duplicate detection and DRY enforcement.

func (*Engine) SetToolDescBudget

func (e *Engine) SetToolDescBudget(n int)

SetToolDescBudget caps each tool description to n characters in the request (0 = send full descriptions). A lean tool surface frees window space.

func (*Engine) SetTuning added in v0.1.1

func (e *Engine) SetTuning(t *prompt.Tuning)

SetTuning replaces the runtime tuning surface (block/rule toggles, skill catalog budgets). Nil keeps the defaults.

func (*Engine) SetUsageRecorder

func (e *Engine) SetUsageRecorder(fn func(paths []string))

SetUsageRecorder wires a callback that receives the files the model touched each turn (read, searched, edited) so usage can persist across sessions.

func (*Engine) SetUsageTracker added in v0.1.36

func (e *Engine) SetUsageTracker(u *UsageTracker)

SetUsageTracker shares an existing usage tracker with this engine.

func (*Engine) State

func (e *Engine) State() LoopState

State returns current engine phase.

func (*Engine) TurnCompactions added in v0.1.1

func (e *Engine) TurnCompactions() int

TurnCompactions returns how many context compactions fired during the most recent turn (delta of the session counter, so repeated turns accumulate).

func (*Engine) TurnTokenStats added in v0.1.2

func (e *Engine) TurnTokenStats() tokens.TurnTokenStats

TurnTokenStats returns the turn's token economy: total tokens vs. the productive subset (answer + file-mutating rounds). The ratio is BroCode's north-star efficiency metric — a high ratio means the agent went straight to the result instead of thrashing through the codebase.

func (*Engine) TurnTokens

func (e *Engine) TurnTokens() int

TurnTokens returns the raw token count consumed by this turn's completions (per-turn HUD, P2 #3).

func (*Engine) UsageTracker added in v0.1.36

func (e *Engine) UsageTracker() *UsageTracker

UsageTracker returns the engine's session usage tracker.

type Fallback

type Fallback struct {
	// ID is a stable provider identity (e.g. "groq", "opencode") used for
	// health tracking in the adaptive router.
	ID string
	// Protocol is the wire protocol ("anthropic" / "openai-compatible"), used
	// by the "confirm" fallback policy to ask only when the fallback is a
	// different vendor than the primary.
	Protocol string
	Adapter  provider.ProviderAdapter
	Model    string
}

Fallback is an alternative adapter+model pair tried when the primary provider fails (automatic model routing).

type LoopState

type LoopState int

LoopState defines explicit state machine phases (§2.1).

const (
	StateThinking LoopState = iota
	StateActing
	StateObserving
	StateVerifying
	StateDone
	StateBlocked
	StateFailed
)

func (LoopState) String

func (s LoopState) String() string

type ModelUsage

type ModelUsage struct {
	PromptTokens     int
	CompletionTokens int
	TotalTokens      int
	CostUSD          float64
}

ModelUsage accumulates tokens and estimated cost for one model.

type ReviewCouncil

type ReviewCouncil struct{}

ReviewCouncil performs static peer review audits on critical code changes. It checks for N+1 queries, unhandled errors, and breaking changes.

func NewReviewCouncil

func NewReviewCouncil() *ReviewCouncil

NewReviewCouncil creates a new council reviewer instance.

func (*ReviewCouncil) AuditDiff

func (rc *ReviewCouncil) AuditDiff(filePath, content string) []string

AuditDiff inspects file content changes for architectural or security risks.

func (*ReviewCouncil) FormatFindings

func (rc *ReviewCouncil) FormatFindings(findings []string) string

FormatFindings renders review council alerts into human-readable text.

type ScoutDrainer

type ScoutDrainer interface {
	// Drain returns one formatted report per finished job and removes them.
	Drain() []string
	// Pending returns the number of jobs still running.
	Pending() int
}

ScoutDrainer delivers completed background research findings. Implemented by *subagent.ScoutManager; defined here as an interface to avoid an import cycle (subagent imports loop for its isolated sub-loops).

type TreeDebugger

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

TreeDebugger maintains the interactive time-travel snapshot tree.

func NewTreeDebugger

func NewTreeDebugger() *TreeDebugger

NewTreeDebugger initializes a new Time-Travel Debugger store.

func (*TreeDebugger) RecordTurn

func (td *TreeDebugger) RecordTurn(prompt string, state LoopState, editedFiles []string)

RecordTurn records a turn state checkpoint.

func (*TreeDebugger) TreeView

func (td *TreeDebugger) TreeView() string

TreeView renders the visual conversation state tree (for /tree command).

func (*TreeDebugger) UndoLast

func (td *TreeDebugger) UndoLast() (TurnSnapshot, bool)

UndoLast turns back to the previous snapshot.

type TurnOutputHandler

type TurnOutputHandler func(state LoopState, info string)

RunTurn executes the ReAct loop until a terminal state is reached.

type TurnSnapshot

type TurnSnapshot struct {
	TurnIndex int
	Prompt    string
	State     LoopState
	Files     []string
}

TurnSnapshot records state at a specific turn checkpoint.

type UsageTracker

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

UsageTracker accumulates per-model usage across a session.

func NewUsageTracker

func NewUsageTracker() *UsageTracker

NewUsageTracker creates an empty tracker.

func (*UsageTracker) Record

func (u *UsageTracker) Record(model string, usg provider.Usage)

Record adds one completion's usage under a model name.

func (*UsageTracker) Summary

func (u *UsageTracker) Summary() string

Summary renders a compact multi-line cost report (for /cost).

func (*UsageTracker) TelemetryAdvisor

func (u *UsageTracker) TelemetryAdvisor() string

TelemetryAdvisor analyzes session usage patterns and returns optimization suggestions (Fase 5.2).

func (*UsageTracker) TotalCost

func (u *UsageTracker) TotalCost() float64

TotalCost returns the summed estimated cost across all models.

func (*UsageTracker) TotalTokens

func (u *UsageTracker) TotalTokens() int

TotalTokens returns the summed token usage.

Jump to

Keyboard shortcuts

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