agent

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2026 License: Apache-2.0 Imports: 86 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 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   *runtimerequestctx.TurnMeta
	Output       struct{ Content, Model, MessageID, Error string }
	// Per-request controls
	AllowedChains []string
	DisableChains bool
}

func NewChainContext

func NewChainContext(in *QueryInput, out *QueryOutput, turn *runtimerequestctx.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          binding.History
	Elicitation      []*binding.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 WithIntakeService added in v0.1.7

func WithIntakeService(svc *intakesvc.Service) Option

WithIntakeService injects the pre-turn intake sidecar service. When set, agents with Intake.Enabled=true will run the sidecar before the main turn.

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 WithRelevanceSelector added in v0.1.7

func WithRelevanceSelector(fn func(context.Context, relevanceSelectorInput) (*relevanceSelectorOutput, error)) Option

WithRelevanceSelector overrides the relevance selector used to populate ContextProjection.HiddenTurnIDs. Intended primarily for testing or custom selector integrations.

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"`
	// ConversationTitle is an optional title for new conversations. When empty
	// the runtime may derive one from the query or leave it unset for
	// autoSummarize to fill in after the first turn.
	ConversationTitle string `json:"conversationTitle,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"`                  // Internal query/prompt submitted to the runtime
	DisplayQuery string                `json:"displayQuery,omitempty"` // Display-safe user task persisted in transcript/UI
	Attachments  []*binding.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"`

	// TemplateId optionally pre-selects an output template for this turn.
	// When set, the runtime will attempt to inject the template document before
	// the LLM starts so the worker doesn't need to call template:get explicitly.
	// Populated by the llm/agents runtime when a PromptProfile specifies a template.
	TemplateId string `json:"templateId,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"`
	Projection     *runtimeprojection.ContextProjection `json:"projection,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) (*binding.Binding, error)

func (*Service) BuildHistory

func (s *Service) BuildHistory(ctx context.Context, transcript apiconv.Transcript, binding *binding.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) 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)

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