agent

package
v0.153.3 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2026 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewAgentStateMachine

func NewAgentStateMachine() domain.AgentStateMachine

NewAgentStateMachine creates a new agent state machine

func RunCommandHooks added in v0.125.0

func RunCommandHooks(ctx context.Context, cfg *config.Config, provider domain.HookCommandProvider, modeKey string, hook domain.HookPoint, turn int, sessionID string)

RunCommandHooks is the single chokepoint both agents use to run command hooks. It asks the provider which commands are attached to hook, gates each on the per-mode bash allow-list - the SAME matcher a model-proposed bash command faces, so command hooks open no new bypass of the secure-by-default model - and runs the allowed ones fire-and-observe. Off-list commands are skipped and reported with the rejection hint (the user authorizes a command by allow-listing it, e.g. tools.bash.mode.*.allow or INFER_TOOLS_BASH_ALLOW_APPEND).

Both the event-driven chat agent and the headless `infer agent` loop call this from their dispatchHooks seam so the gate and observability cannot drift apart. cfg supplies the allow-list and the fallback provider; modeKey is the resolved per-mode allow-list key (standard/plan/auto); sessionID and turn populate the command's stdin JSON context. Commands run synchronously; their output is emitted as a hook_command stream event and logged, never fed back into the conversation or used to alter the loop (that feedback is a later iteration).

Types

type AgentServiceImpl

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

AgentServiceImpl implements the AgentService interface with direct chat functionality

func NewAgent

func NewAgent(
	client sdk.Client,
	toolService domain.ToolService,
	cfg *config.Config,
	conversationRepo domain.ConversationRepository,
	a2aAgentService domain.A2AAgentService,
	skillsService domain.SkillsService,
	messageQueue domain.MessageQueue,
	stateManager stateManager,
	timeoutSeconds int,
	optimizer domain.ConversationOptimizer,
	bgRegistry domain.BackgroundTaskRegistry,
) *AgentServiceImpl

func (*AgentServiceImpl) BuildSystemPrompt added in v0.117.0

func (s *AgentServiceImpl) BuildSystemPrompt() string

BuildSystemPrompt assembles the static system prompt sent as message[0] (base prompt + custom instructions + AGENTS.md + plugins + static context). It is deliberately byte-identical across turns within a session so local LLM servers get KV-cache prefix hits; volatile context (git, tree, memory, active skill, date) rides in volatileTailMessage instead. Returns "" when no base prompt is configured for the current mode.

func (*AgentServiceImpl) CancelRequest

func (s *AgentServiceImpl) CancelRequest(requestID string) error

CancelRequest cancels an active request. Safe to call multiple times for the same requestID - subsequent calls are no-ops via sync.Once on the underlying sessionCancel. Returns nil even when the request is unknown, so the UI can fire it on every Esc press without surfacing spurious errors after the session has already torn down. The agent loop publishes ChatCompleteEvent{Cancelled:true} as the single cancel-completion signal; no separate CancelledEvent broadcast is needed.

func (*AgentServiceImpl) GetMetrics

func (s *AgentServiceImpl) GetMetrics(requestID string) *domain.ChatMetrics

GetMetrics returns metrics for a completed request

func (*AgentServiceImpl) Run

Run executes an agent task synchronously (for background/batch processing)

func (*AgentServiceImpl) RunWithStream

func (s *AgentServiceImpl) RunWithStream(ctx context.Context, req *domain.AgentRequest) (<-chan domain.ChatEvent, error)

RunWithStream executes an agent task with streaming (for interactive chat)

func (*AgentServiceImpl) SetMemoryBackend added in v0.127.0

func (s *AgentServiceImpl) SetMemoryBackend(backend domain.MemoryBackend)

SetMemoryBackend wires the memory sync backend so the chat agent pulls memory once at session start (SyncIn on HookPreSession). SyncOut is driven by the Memory tool on write/delete, not here - chat fires HookPostSession after every message, so pushing there would commit-storm. A nil backend disables sync.

func (*AgentServiceImpl) SetTelemetryRecorder added in v0.145.0

func (s *AgentServiceImpl) SetTelemetryRecorder(rec *telemetry.Recorder)

SetTelemetryRecorder wires the telemetry recorder so per-request token usage is tapped in storeIterationMetrics. A nil recorder disables recording.

func (*AgentServiceImpl) SystemPromptSections added in v0.140.0

func (s *AgentServiceImpl) SystemPromptSections() []PromptSection

SystemPromptSections returns the labeled parts of the prompt context a fresh session (turn 0) would send — the static system prompt sections followed by the Volatile-marked tail sections — with empty parts omitted. Exposed for the `infer debug agent system_prompt --tokens` breakdown.

func (*AgentServiceImpl) VolatileTailText added in v0.151.0

func (s *AgentServiceImpl) VolatileTailText() (string, bool)

VolatileTailText renders the volatile-context tail a fresh session (turn 0) would send as a hidden per-request <system-reminder> user message; ok=false means no tail is sent. Exposed for the `infer debug agent system_prompt` command via type assertion, alongside SystemPromptSections.

type AgentStateMachineImpl

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

AgentStateMachineImpl implements the AgentStateMachine interface.

The state machine manages the agent's execution flow through the following states:

State Flow:

Idle → CheckingQueue → StreamingLLM → PostStream → EvaluatingTools → ApprovingTools/BlockingTools/ExecutingTools → PostToolExecution → CheckingQueue (loop) → Completing → Idle

State Descriptions:

  • Idle: Agent is not executing, waiting for work
  • CheckingQueue: Checking if there are queued messages or if completion criteria are met
  • StreamingLLM: Streaming responses from the LLM
  • PostStream: Processing LLM response, checking for tool calls or completion
  • EvaluatingTools: Determining if tool calls need approval
  • ApprovingTools: Waiting for user approval of tool calls (only in chat mode)
  • BlockingTools: Approval required but undeliverable (approval_behaviour=block); gated tools are rejected with a reason
  • ExecutingTools: Executing approved or auto-approved tool calls
  • PostToolExecution: Processing tool results, checking for completion or continuing
  • Completing: Finalizing the agent execution
  • Error: An error occurred during execution
  • Cancelled: User cancelled the execution
  • Stopped: Tool execution indicated stop (user rejection or error)

Thread Safety:

All state transitions are protected by a read-write mutex to ensure thread-safe access.

func (*AgentStateMachineImpl) CanTransition

func (sm *AgentStateMachineImpl) CanTransition(ctx *domain.AgentContext, targetState domain.AgentExecutionState) bool

CanTransition checks if a transition from current state to target state is valid This is useful for checking before attempting a transition

func (*AgentStateMachineImpl) GetCurrentState

func (sm *AgentStateMachineImpl) GetCurrentState() domain.AgentExecutionState

GetCurrentState returns the current state (thread-safe)

func (*AgentStateMachineImpl) GetPreviousState

func (sm *AgentStateMachineImpl) GetPreviousState() domain.AgentExecutionState

GetPreviousState returns the previous state (thread-safe)

func (*AgentStateMachineImpl) GetValidTransitions

func (sm *AgentStateMachineImpl) GetValidTransitions(ctx *domain.AgentContext) []domain.AgentExecutionState

GetValidTransitions returns all valid transitions from the current state

func (*AgentStateMachineImpl) Reset

func (sm *AgentStateMachineImpl) Reset()

Reset resets the state machine to idle

func (*AgentStateMachineImpl) Transition

func (sm *AgentStateMachineImpl) Transition(ctx *domain.AgentContext, targetState domain.AgentExecutionState) error

Transition attempts to transition to the target state

type EventDrivenAgent

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

EventDrivenAgent manages agent execution using event-driven state machine

func NewEventDrivenAgent

func NewEventDrivenAgent(
	service *AgentServiceImpl,
	cfg *config.AgentConfig,
	ctx context.Context,
	req *domain.AgentRequest,
	conversation *[]sdk.Message,
	eventPublisher *eventPublisher,
	cancelChan <-chan struct{},
	provider string,
	model string,
	registry domain.BackgroundTaskRegistry,
) *EventDrivenAgent

NewEventDrivenAgent creates a new event-driven agent

func (*EventDrivenAgent) Start

func (a *EventDrivenAgent) Start()

Start begins the event-driven agent execution. The state machine already begins in Idle, so seeding a MessageReceivedEvent drives the first transition (Idle -> CheckingQueue) via the Idle state handler.

func (*EventDrivenAgent) Wait

func (a *EventDrivenAgent) Wait()

Wait waits for the agent to complete

type IndexedToolResult

type IndexedToolResult struct {
	Index  int
	Result domain.ConversationEntry
}

type PromptSection added in v0.140.0

type PromptSection struct {
	Name     string
	Text     string
	Volatile bool
}

PromptSection is one labeled part of the assembled prompt context, exposed for diagnostics (e.g. per-section token estimates in `infer debug`). Text is the raw part as it appears in the prompt, including any separator prefix. Volatile marks sections delivered via the per-request tail message rather than the static system prompt.

type StateTransition

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

StateTransition represents a state transition with guard and action

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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