agent

package
v0.1.8 Latest Latest
Warning

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

Go to latest
Published: May 11, 2026 License: Apache-2.0 Imports: 104 Imported by: 0

Documentation

Overview

Package agent coordinates an agent turn across multiple responsibilities

Index

Constants

View Source
const (
	PresetAssistantTextKey = "intake.preset.text"
	PresetAssistantKindKey = "intake.preset.kind"
)

PresetAssistantTextKey / PresetAssistantKindKey are the reserved QueryInput.Context keys carrying a workspace-intake preset assistant message produced by the classifier (action=answer or action=clarify).

When PresetAssistantTextKey is non-empty and PresetAssistantKindKey is one of "answer" / "clarify", the runtime publishes the text as the turn's assistant message via the standard transcript writer and short-circuits without invoking the agent's LLM. This is the "ONE LLM call for capability turns" wire-up — the classifier's single LLM call already produced the authoritative text; running the agent again would be wasteful and would risk diverging output.

Callers wanting to drive a preset directly (tests, integrations) may set these keys on QueryInput.Context themselves; the resolution logic in ensureAgent populates them automatically when the workspace-intake classifier returns action=answer or action=clarify.

View Source
const (
	ClassifierActionRoute   = "route"
	ClassifierActionPlanner = "planner"
	ClassifierActionAnswer  = "answer"
	ClassifierActionClarify = "clarify"
)

ClassifierAction enumerates the terminal outcomes of a workspace intake LLM call. Exactly one of {AgentID, Answer, Question} is populated per result.

Variables

This section is empty.

Functions

func ApplyPromptProfileExecutionDefaults added in v0.1.8

func ApplyPromptProfileExecutionDefaults(input *QueryInput, profile *promptdef.Profile)

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 ClassifierResult added in v0.1.8

type ClassifierResult struct {
	Action         string
	AgentID        string
	Answer         string
	Question       string
	PlannerTrigger string
}

ClassifierResult is the structured output of the workspace intake LLM call. This is the single source of truth for "agentId=auto" turn outcomes.

Exactly one of AgentID / Answer / Question is non-empty per Action:

Action=ClassifierActionRoute   → AgentID  is set
Action=ClassifierActionPlanner → AgentID  is set
Action=ClassifierActionAnswer  → Answer   is set (capability response)
Action=ClassifierActionClarify → Question is set (one disambiguation question)

An empty ClassifierResult (Action == "") means the LLM call produced no usable output; callers fall through to the deterministic continuity / default chain.

type ConversationMetadata

type ConversationMetadata struct {
	Tools       []string                   `json:"tools,omitempty"`
	ToolBundles []string                   `json:"toolBundles,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 WithPlannerContractResolver added in v0.1.8

func WithPlannerContractResolver(resolver planner.Resolver) Option

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 WithSkillService added in v0.1.8

func WithSkillService(svc *skillsvc.Service) Option

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 PlannerPassTrace added in v0.1.8

type PlannerPassTrace struct {
	ConversationID  string
	TurnID          string
	Attempt         int
	Validated       bool
	StrategyFamily  string
	BaseProfiles    []string
	ToolBundles     []string
	TemplateID      string
	EvidenceCount   int
	ExecutionOrder  []string
	Guards          []string
	ValidatorErrors []planner.ValidationError
}

func (*PlannerPassTrace) AsMap added in v0.1.8

func (p *PlannerPassTrace) AsMap() map[string]any

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"`
	Runtime         *agruntime.Context     `json:"runtime,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"`

	// PromptProfileId optionally selects a prompt profile for this turn.
	// For direct agent turns this is typically populated by intake/routing,
	// not by llm/agents child-run wiring.
	PromptProfileId string `json:"promptProfileId,omitempty"`
	// ParallelToolCalls optionally overrides the agent-level parallel tool
	// execution preference for this specific turn.
	ParallelToolCalls *bool `json:"parallelToolCalls,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) GetContext added in v0.1.8

func (i *QueryInput) GetContext() map[string]any

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    *execution.Elicitation               `json:"elicitation,omitempty"` // structured missing input request
	Plan           *execution.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) AsyncManager added in v0.1.8

func (s *Service) AsyncManager() *asynccfg.Manager

AsyncManager returns the async Manager owned by this service. Exposed so bootstrap wiring (e.g. executor.Builder) can forward workspace-level `default.async` settings into `manager.StartGC` / narrator overrides without reaching through package-private fields.

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) ReconcileRunningConversationStatuses added in v0.1.8

func (s *Service) ReconcileRunningConversationStatuses(ctx context.Context, limit int) error

ReconcileRunningConversationStatuses repairs persisted conversation.status rows that still say "running" even though execution is fully terminal. This is explicit maintenance for historical drift; it is intentionally separate from stale-run recovery watchdog logic.

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) SetSkillService added in v0.1.8

func (s *Service) SetSkillService(svc *skillsvc.Service)

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 WithWatchdogHandleTimeout added in v0.1.8

func WithWatchdogHandleTimeout(d time.Duration) WatchdogOption

WithWatchdogHandleTimeout bounds recovery work per stale run so one blocked recovery cannot stall the entire watchdog sweep.

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