agent

package
v0.1.2 Latest Latest
Warning

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

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

Documentation

Overview

Package agent coordinates an agent turn across multiple responsibilities

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DebugEnabled

func DebugEnabled() bool

DebugEnabled reports whether conversation debug logging is enabled. Enable with AGENTLY_DEBUG=1 (or true/yes/on). Also accepts AGENTLY_SCHEDULER_DEBUG. Legacy env (deprecated): AGENTLY_CONVERSATION_DEBUG.

func EnsureGenerateOptions

func EnsureGenerateOptions(ctx context.Context, i *core.GenerateInput, agent *agent.Agent)

Types

type ChainContext

type ChainContext struct {
	Agent        *agentmdl.Agent
	Conversation *apiconv.Conversation
	Context      map[string]interface{}
	UserID       string
	ParentTurn   *memory.TurnMeta
	Output       struct{ Content, Model, MessageID, Error string }
	// Per-request controls
	AllowedChains []string
	DisableChains bool
}

func NewChainContext

func NewChainContext(in *QueryInput, out *QueryOutput, turn *memory.TurnMeta) ChainContext

NewChainContext builds a ChainContext from the current turn context, parent input and output. Conversation can be attached by the caller.

type ConversationMetadata

type ConversationMetadata struct {
	Tools   []string                   `json:"tools,omitempty"`
	Context map[string]interface{}     `json:"context,omitempty"`
	Extra   map[string]json.RawMessage `json:"-"`
}

ConversationMetadata is a typed representation of conversation metadata. It preserves unknown fields during round trips.

func (ConversationMetadata) MarshalJSON

func (m ConversationMetadata) MarshalJSON() ([]byte, error)

func (*ConversationMetadata) UnmarshalJSON

func (m *ConversationMetadata) UnmarshalJSON(data []byte) error

type HistoryResult

type HistoryResult struct {
	History          prompt.History
	Elicitation      []*prompt.Message
	Overflow         bool
	MaxOverflowBytes int
}

HistoryResult holds the combined result of building prompt history with overflow preview and elicitation extraction.

type Option

type Option func(*Service)

Option customises Service instances.

func WithCancelRegistry

func WithCancelRegistry(reg cancels.Registry) Option

WithCancelRegistry injects a registry to register per-turn cancel functions when executing Agent.Query. When nil, cancel registration is skipped.

func WithDataService

func WithDataService(d data.Service) Option

WithDataService injects a data service for run record management.

func WithElicitationRouter

func WithElicitationRouter(r elicrouter.ElicitationRouter) Option

WithElicitationRouter injects a router to coordinate elicitation waits for assistant-originated prompts. When set, the agent will register a waiter and block until the HTTP/UI handler completes the elicitation.

func WithMCPManager

func WithMCPManager(m *mcpmgr.Manager) Option

WithMCPManager attaches an MCP Manager to resolve resources via MCP servers.

func WithNewElicitationAwaiter

func WithNewElicitationAwaiter(newAwaiter func() elicitation.Awaiter) Option

WithNewElicitationAwaiter configures a local awaiter used to resolve assistant-originated elicitations in interactive environments (CLI).

func WithTokenProvider

func WithTokenProvider(p token.Provider) Option

WithTokenProvider injects a token provider for auth token lifecycle management.

func WithToolBundles

func WithToolBundles(provider func(ctx context.Context) ([]*toolbundle.Bundle, error)) Option

WithToolBundles configures a provider returning global tool bundles.

type QueryInput

type QueryInput struct {
	RequestTime time.Time `json:"requestTime,omitempty"`

	// ConversationID is an optional identifier for the conversation session.
	// If provided, conversation history will be tracked and reused.
	ConversationID       string `json:"conversationId,omitempty"`
	ParentConversationID string `json:"parentConversationId,omitempty"`
	// Optional client-supplied identifier for the user message. When empty the
	// service will generate a UUID.
	MessageID   string               `json:"messageId,omitempty"`
	AgentID     string               `json:"agentId"` // Agent ID to use
	UserId      string               `json:"userId"`
	Agent       *agentmdl.Agent      `json:"agent"` // Agent to use (alternative to agentId)
	Query       string               `json:"query"` // The query to submit
	Attachments []*prompt.Attachment `json:"attachments,omitempty"`

	MaxResponseSize int    `json:"maxResponseSize"` // Maximum size of the response in bytes
	MaxDocuments    int    `json:"maxDocuments"`    // Maximum number of documents to retrieve
	IncludeFile     bool   `json:"includeFile"`     // Whether to include complete file content
	EmbeddingModel  string `json:"embeddingModel"`  // Find to use for embeddings

	// Optional runtime overrides (single-turn)
	ModelOverride string   `json:"model,omitempty"` // llm model name
	ToolsAllowed  []string `json:"tools,omitempty"` // allow-list for tools (empty = default)
	// ToolBundles selects global tool bundles by id for this turn. When provided,
	// bundles are expanded into a concrete tool allow-list sent to the model.
	ToolBundles []string `json:"toolBundles,omitempty"`
	// AutoSelectTools enables tool-bundle auto selection for this turn when the caller did
	// not explicitly provide tools or bundles.
	AutoSelectTools *bool                  `json:"autoSelectTools,omitempty"`
	Context         map[string]interface{} `json:"context,omitempty"`
	// ModelPreferences optionally overrides or hints model selection
	// preferences for this turn. When nil, the agent's configured
	// ModelSelection.Preferences are used.
	ModelPreferences *llm.ModelPreferences `json:"modelPreferences,omitempty"`

	Transcript conversation.Transcript `json:"transcript,omitempty"`

	// ElicitationMode controls how missing-input requests are handled.
	ElicitationMode string `json:"elicitationMode,omitempty" yaml:"elicitationMode,omitempty"`

	AutoSummarize *bool `json:"autoSummarize,omitempty"`

	AllowedChains []string `json:"allowedChains,omitempty"` //

	DisableChains bool `json:"disableChains,omitempty"`

	ToolCallExposure *agentmdl.ToolCallExposure `json:"toolCallExposure,omitempty"`

	// ReasoningEffort optionally overrides agent-level Reasoning.Effort for this turn.
	// Valid values (OpenAI o-series): low | medium | high.
	ReasoningEffort *string `json:"reasoningEffort,omitempty"`

	// ScheduleId links this query to the schedule that triggered it.
	// When set, the created conversation will have schedule_id populated.
	ScheduleId string `json:"scheduleId,omitempty"`

	// IsNewConversation indicates if this is a new conversation without prior history.
	IsNewConversation bool `json:"-"`
	// SkipInitialUserMessage tells Query to reuse an already persisted starter
	// user message (e.g. queued turn) instead of adding a duplicate.
	SkipInitialUserMessage bool `json:"-"`
	// AutoSelected reports whether the runtime auto-routed the agent for this turn.
	AutoSelected bool `json:"-"`
	// RoutingReason captures the auto-routing reason when AutoSelected is true.
	RoutingReason string `json:"-"`
}

QueryInput represents the input for querying an agent's knowledge

func (*QueryInput) Actor

func (i *QueryInput) Actor() string

func (*QueryInput) ShallAutoSummarize

func (i *QueryInput) ShallAutoSummarize() bool

type QueryOutput

type QueryOutput struct {
	ConversationID string            `json:"conversationId,omitempty"`
	Agent          *agentmdl.Agent   `json:"agent"`                 // Agent used for the query
	Content        string            `json:"content"`               // Generated content from the agent
	Elicitation    *plan.Elicitation `json:"elicitation,omitempty"` // structured missing input request
	Plan           *plan.Plan        `json:"plan,omitempty"`        // current execution plan (optional)
	Usage          *usage.Aggregator `json:"usage,omitempty"`
	Model          string            `json:"model,omitempty"`
	MessageID      string            `json:"messageId,omitempty"`
	Warnings       []string          `json:"warnings,omitempty"`
	// contains filtered or unexported fields
}

QueryOutput represents the result of an agent knowledge query

type Service

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

func New

func New(llm *core.Service, agentFinder agent.Finder, augmenter *augmenter.Service, registry tool.Registry,
	defaults *config.Defaults,
	convClient apiconv.Client,

	opts ...Option) *Service

New creates a new agent service instance with the given tool registry.

func (*Service) BuildBinding

func (s *Service) BuildBinding(ctx context.Context, input *QueryInput) (*prompt.Binding, error)

func (*Service) BuildHistory

func (s *Service) BuildHistory(ctx context.Context, transcript apiconv.Transcript, binding *prompt.Binding) error

func (*Service) Compact

func (s *Service) Compact(ctx context.Context, conversationID string) error

Compact generates an LLM summary of the conversation history, archiving old messages and replacing them with the summary. Uses an atomic guard to prevent concurrent compaction on the same conversation.

func (*Service) Finder

func (s *Service) Finder() agent.Finder

func (*Service) Method

func (s *Service) Method(name string) (svc.Executable, error)

Method returns the specified method

func (*Service) Methods

func (s *Service) Methods() svc.Signatures

Methods returns the service methods

func (*Service) Name

func (s *Service) Name() string

Name returns the service name

func (*Service) Prune

func (s *Service) Prune(ctx context.Context, conversationID string) error

Prune uses an LLM to select low-value messages for removal from the conversation history. Uses an atomic guard to prevent concurrent operations.

func (*Service) Query

func (s *Service) Query(ctx context.Context, input *QueryInput, output *QueryOutput) (retErr error)

Query executes a query against an agent.

func (*Service) ResolveElicitation

func (s *Service) ResolveElicitation(ctx context.Context, conversationID, elicitationID, action string, payload map[string]interface{}) error

ResolveElicitation applies an elicitation decision (accept/decline/cancel) and persists status/payload through the elicitation service.

func (*Service) SetElicitationStreamPublisher

func (s *Service) SetElicitationStreamPublisher(p streaming.Publisher)

SetElicitationStreamPublisher wires the streaming publisher into the agent's internal elicitation service so that LLM-generated elicitation events reach the SSE bus.

func (*Service) Summarize

func (s *Service) Summarize(ctx context.Context, conv *apiconv.Conversation) error

func (*Service) Terminate

func (s *Service) Terminate(ctx context.Context, conversationID string) error

Terminate cancels all active turns for a conversation and marks it as canceled.

type ToolExecutionsResult

type ToolExecutionsResult struct {
	Calls            []*llm.ToolCall
	Overflow         bool
	MaxOverflowBytes int
}

ToolExecutionsResult holds the combined result of building tool call executions from transcript history.

type Watchdog

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

Watchdog periodically detects stale runs and either marks them failed or resumes them (when the conversation still has pending work).

func NewWatchdog

func NewWatchdog(data data.Service, agent *Service, opts ...WatchdogOption) *Watchdog

NewWatchdog creates a watchdog for stale run detection and resume.

func (*Watchdog) Start

func (w *Watchdog) Start(ctx context.Context)

Start begins the watchdog polling loop. It blocks until ctx is canceled.

type WatchdogOption

type WatchdogOption func(*Watchdog)

WatchdogOption configures a Watchdog.

func WithWatchdogInterval

func WithWatchdogInterval(d time.Duration) WatchdogOption

WithWatchdogInterval sets the polling interval.

func WithWatchdogTokenProvider

func WithWatchdogTokenProvider(p token.Provider) WatchdogOption

WithWatchdogTokenProvider sets the token provider for restoring auth on resume.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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