Class Agent
- All Implemented Interfaces:
AgentGroupManager.GroupContext,AgentHierarchyManager.HierarchyContext,AgentInitializer.InitializerContext,AgentMessagingHandler.MessagingContext,AgentOrchestrator.OrchestratorContext,AgentCommunicationManager.MessageReceiver
- Direct Known Subclasses:
ConfigurableAgent
Agent = identity (WHO). Role = capabilities (WHAT: @Goal, @State, @Action).
Subclasses implement getLLM() and getRoles().
Uses lazy init with double-checked locking; template methods are never
called in the constructor.
Supports DI via the 4-arg constructor for testability.
Chat, tool execution, streaming, knowledge base are delegated to
AgentOrchestrator. Cognitive features (planning, reasoning,
evaluation, environment, feedback) are in AgentCognitiveSupport
and AgentCapabilities.
- Author:
- TnsAI Team
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionfinal ActionOutcomeactOnEnvironment(String actionName, Map<String, Object> parameters) Acts on the attached environment.final voidAdds a child agent (maintains bidirectional consistency).final booleanaddChildDirect(Agent child) Adds a child directly to the internal list.final voidaddChildren(Agent... children) Adds multiple child agents at once.final voidaddEvalHook(EvalHook hook) Adds an evaluation hook for metric collection.final booleanReturns whether the agent should auto-start (default: true).final StringSends a message to the agent and returns the LLM response.final StringSends a message with optional conversation history.final StringSends a message with full control over history and tools.final Stringchat(String message, boolean useHistory, boolean useTools, ChatRetrievalContext retrievalContext) Sends a message with request-local retrieval isolation and lifecycle context.final StringchatInternal(String message, boolean useHistory) Internal chat method for query handling.final StringchatWithEvents(String message, String sessionId) Chat with events published to a session on the configured publisher.final StringchatWithEvents(String message, Consumer<TnsAIEvent> eventConsumer) Chat with real-time TnsAI event emission (AG-UI integration).final StringchatWithEvents(String message, Consumer<TnsAIEvent> eventConsumer, ChatRetrievalContext retrievalContext) Emits events with request-local retrieval isolation and lifecycle context.final <T> TchatWithFormat(String message, Class<T> targetClass, int maxRetries) Chat with structured output using annotation-defined format or JSON default.final <T> TchatWithFormat(String message, Class<T> targetClass, int maxRetries, ChatRetrievalContext retrievalContext) Annotation-formatted chat with request-local retrieval context.final <T> TchatWithFormat(String message, Class<T> targetClass, OutputFormat format, int maxRetries) Chat with structured output in a specific format.final <T> TchatWithFormat(String message, Class<T> targetClass, OutputFormat format, int maxRetries, ChatRetrievalContext retrievalContext) Formatted chat with request-local retrieval isolation and lifecycle context.final <T> TchatWithStructure(String message, OutputParser<T> parser, int maxRetries) Sends a message and returns a structured, validated response using guardrails pattern.final <T> TchatWithStructure(String message, OutputParser<T> parser, int maxRetries, ChatRetrievalContext retrievalContext) Structured chat with request-local retrieval isolation and lifecycle context.final voidClears all stored conversation messages.final EvalContextClears the current evaluation context and creates a new session.final voidDelegates an action to a child agent.final StringReturns the agent description from @AgentSpec (may be empty).final voidInternal: detaches from parent without triggering bidirectional updates.final Stringdid()Returns the DID (Decentralized Identifier) for this agent.enableContextGraph(SnapshotStore snapshotStore, DecisionTraceStore decisionTraceStore) Enables context graph tracking (decision tracing + snapshots).final voidfinal voidescalateToParent(String actionName, Map<String, Object> parameters) Escalates an action to the parent agent.final ActionResponseexecuteAction(ActionRequest request) Executes an action using a typed request.final ActionResponseexecuteAction(ActionRequest request, ChatRetrievalContext retrievalContext) Executes a typed action request with request-local retrieval context.final ObjectexecuteAction(String actionName, Object input) Executes a named action with a typed input bean — Javarecord, POJO withgetX/isXaccessors, or class with public fields.final ObjectexecuteAction(String actionName, Map<String, Object> parameters) Executes a named action (untyped).final ObjectexecuteAction(String actionName, Map<String, Object> parameters, ChatRetrievalContext retrievalContext) Executes an action with request-local retrieval isolation and lifecycle context.final ActionResponseexecuteActionOnRole(String roleId, ActionRequest request) Executes a typed action on a specific role.final ActionResponseexecuteActionOnRole(String roleId, ActionRequest request, ChatRetrievalContext retrievalContext) Executes a typed role action with request-local retrieval context.final ObjectexecuteActionOnRole(String roleId, String actionName, Object input) Executes an action on a specific role with a typed input bean.final ObjectExecutes an action on a specific role (untyped).final ObjectexecuteActionOnRole(String roleId, String actionName, Map<String, Object> parameters, ChatRetrievalContext retrievalContext) Executes a role action with request-local retrieval context.final PlannerHandle.PlanResultexecutePlan(List<PlannerHandle.PlanStep> steps) Executes a plan on the first role.Extracts current @State from all roles.final AgentfindChildById(String childId) Finds a child by ID.final voidfireOnAfterChat(String result, long latencyMs) final voidfireOnAfterToolCall(String toolName, Object result, boolean success, long latencyMs) final voidfireOnBeforeChat(String message) final voidfireOnBeforeToolCall(String toolName, Map<String, Object> arguments) final voidfireOnError(Exception e, String context) final ActionExecutorThegetActionKnowledge()names, copied.final Class<?> Returns the agent's class for reflectionfinal StringReturns the agent's unique identifier.final List<KnowledgeEntry> The agent's knowledge with each entry'suse: what its@AgentSpecdeclares, with thegetKnowledge()entries layered over it by name.final Optional<KnowledgeScope> final List<KnowledgeSourceConfig> final LLMClientfinal MemoryStorefinal StringReturns the agent's name for logging.final AgentReturns the agent reference itself.final AgentRestartPolicyfinal ToolSchemaGeneratorReturns the callback dispatcher for @OnMessageReceived callbacks.final Optional<ChatKnowledgeBinding> Returns the owner-scoped canonical chat binding, if configured.Returns the child agents (unmodifiable).Returns an unmodifiable snapshot of the children list.Returns the communication manager for inter-agent messaging.final CommunicationReturns the memory consolidation pipeline resolved from@Memory(TAN-5049), ornullwhen the agent has no@Memoryannotation or conversation memory is disabled.Returns the context manager if context graph is enabled.final ContextManagerHandleReturns an immutable copy of the conversation history.final intReturns the number of messages in conversation history.final RetryPolicyfinal AgentEnsembleExecutorReturns the ensemble executor for parallel LLM operations.final Optional<Environment> Returns the environment if configured.final List<ErrorRecoveryScenario> final List<ErrorRecoveryScenario> final EvalContextfinal EventHandlerRegistryfinal TnsAIEventPublisherfinal FeedbackCollectorReturns the feedback collector (never null; no-op if tnsai-intelligence absent).final Set<AgentGroup> Returns all groups this agent is a member of.final AgentHealthStateReturns the current resilience health state.final StringgetId()Alias forgetAgentId().final List<AgentIdentity> final longReturns milliseconds since last activity, or -1 if not monitored.final ActionExecutorfinal LLMClientfinal MemoryStoreReturns the last reasoning result, or empty.final LLMClientfinal Integerfinal MemoryStorefinal StringgetName()Alias forgetAgentName().final AgentOutputFormatterReturns the output formatter for serialization.final AgentReturns the parent agent, or null if root.final AgentReturns the current parent agent.final PaymentBrokerReturns the payment broker (never null; defaults toPaymentBroker.noOp()).final Optional<PlannerHandle> Returns the planner handle if configured.final ProtocolManagerHandleReturns the protocol manager (null if no protocol annotations).final Optional<ReasoningStrategyHandle> Returns the reasoning strategy if configured.final ReasoningStrategyHandlefinal AgentResilienceManagerReturns the resilience manager.final Optional<RetrievalConfig> The settings a chat turn searches with: the chat defaults under the merged search of the SEARCH entries in the chat scope ofgetAgentKnowledgeEntries().final RolegetRole()Returns the primary (first) role, or null.final SkillManagerfinal AgentStategetState()Returns the agent's current lifecycle state.final StringReturns the complete system prompt (identity + roles + learned behavior).final StringgetSystemPromptForMessage(String latestUserMessage) System prompt rendered for a specific user message — used by the chat orchestrator so theSkillResolversees the latest turn and can surface the most-relevant descriptions for that turn (TNS-289).final StringReturns a human-readable description of all available tools/actions.Returns tool catalog as JSON-Schema fragments for LLM binding (List<Map<String, Object>>per Anthropic-style tool-use).final AgentVariantGets the current agent variant (quality/speed/cost tier).final VariantSelectorGets the configured variant selector.final voidhandleCNPMessageHook(AgentMessage message, CNPMessageType type) Hook for CNP message handling (delegated back to Agent for override support).voidhandleMessage(AgentMessage message) Handles an incoming agent message.final booleanChecks if the given agent is a child.final Stringid()Returns the agent ID (never null, no init required).final intReturns the idle timeout in milliseconds (0 = never suspend).final longAdvances the chat source revision used by subsequent retrievals.final Optional<ActiveSkill> Programmatically activate a skill by name (TNS-289).final booleanfinal booleanReturns true if an environment is attached.final booleanChecks if evaluation hooks are enabled.final booleanReturns true if idle monitoring is active.final booleanReturns true if a PlannerHandle is configured.final booleanfinal voidjoinGroup(AgentGroup group) Joins an existing group.final voidJoins a group by ID.final voidleaveGroup(AgentGroup group) Leaves a group.final voidleaveGroup(String groupId) Leaves a group by ID.final LLMClientllm()Returns the LLM client used by this agent.final Stringname()Returns the human-readable agent name (derived from class name).final voidfinal Perceptperceive()Perceives the current environment state.final List<PlannerHandle.PlanStep> plan()Generates a plan for all unsatisfied goals.final List<PlannerHandle.PlanStep> planForGoal(String goalName) Generates a plan for a specific goal.final voidreceiveMessage(AgentMessage message) final voidrecordGoalCompletion(String goalId, boolean success, Map<String, Object> details) Manually records a goal completion event for evaluation.final voidrecordToolOutcome(String toolName, Object result, boolean success, long latencyMs) final voidremoveChild(Agent child) Removes a child agent.final booleanremoveChildDirect(Agent child) Removes a child directly from the internal list.final booleanremoveEvalHook(EvalHook hook) Removes an evaluation hook.voidreportKnowledgeUsage(String scope, List<KnowledgeUsage> usage) Hands a call's knowledge usage to the listener.final AgentVariantresolveVariant(String taskDescription) Resolves the effective variant for a given task.final voidrestartAgent(String reason) Restarts the agent with fresh state.roles()Returns the assigned roles (never null, never empty).final voidBinds a live or provider-backed canonical retrieval source to chat.final voidSets the communication manager for inter-agent messaging.final voidsetEnvironment(Environment environment) Sets the environment (null to detach).final voidsetEvalEnabled(boolean enabled) Enables or disables evaluation hooks.final voidsetEventPublisher(TnsAIEventPublisher eventPublisher) Sets the event publisher for event-based chat methods.final voidsetFeedbackCollector(FeedbackCollector collector) Sets the feedback collector (null resets to no-op).final voidfinal voidReplaces the LLM client; conversation history is preserved.final voidSets the parent agent (maintains bidirectional consistency).final voidsetParentRef(Agent parent) Sets the parent agent reference directly (no bidirectional updates).final voidsetPaymentBroker(PaymentBroker broker) Sets the payment broker (null resets toPaymentBroker.noOp()).final voidsetPlannerHandle(PlannerHandle handle) Sets the planner handle (null to disable).final voidsetReasoningStrategy(ReasoningStrategyHandle strategy) Sets the reasoning strategy (null to disable).final voidsetToolCallFilter(ToolCallFilter filter) Sets a filter controlling which tool calls are allowed.final voidsetToolCallListener(ToolCallListener listener) Sets a listener for tool call lifecycle events.final voidsetVariant(AgentVariant variant) Sets the agent variant for runtime quality tier switching.final voidsetVariantSelector(VariantSelector selector) Sets the variant selector for automatic variant selection.final voidstart()No-op: protocols auto-start when annotations are detected.final voidstop()Stops the protocol manager, idle monitor, role registry and releases resources.streamChat(String message) Streams response tokens without tool support.final StringstreamChatWithRetrievedContext(String outboundMessage, String historyMessage, Consumer<ChatChunk> handler) Streams canonically fenced retrieved context while persisting only the original user message.final StringstreamChatWithRetrievedContext(String outboundMessage, String historyMessage, Consumer<ChatChunk> handler, ChatRetrievalContext retrievalContext) Streams pre-rendered evidence with request-local retrieval lifecycle context.final StringstreamChatWithTools(String message, Consumer<ChatChunk> handler) Streams response with full tool-calling loop.final StringstreamChatWithTools(String message, Consumer<ChatChunk> handler, ChatRetrievalContext retrievalContext) Streams tools with request-local retrieval isolation and lifecycle context.final Stringversion()Returns the agent version from @AgentSpec (default: "1.0.0").Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface com.tnsai.agents.init.AgentInitializer.InitializerContext
getAutoStartOverride, getDescriptionOverride, getDidConfigOverride, getGroupSpecOverride, getIdleTimeoutMsOverride, getVersionOverride
-
Method Details
-
getState
Returns the agent's current lifecycle state. SeeAgentStatefor the transition graph.- Since:
- 0.5.0 (issue #21)
-
reportKnowledgeUsage
Hands a call's knowledge usage to the listener. A listener that throws is logged at WARN and the turn or action continues.- Specified by:
reportKnowledgeUsagein interfaceAgentOrchestrator.OrchestratorContext- Parameters:
scope-"chat"or the action nameusage- one row per source, in declaration order- Since:
- 0.18.0
-
getAgentId
Description copied from interface:AgentHierarchyManager.HierarchyContextReturns the agent's unique identifier.- Specified by:
getAgentIdin interfaceAgentGroupManager.GroupContext- Specified by:
getAgentIdin interfaceAgentHierarchyManager.HierarchyContext- Specified by:
getAgentIdin interfaceAgentInitializer.InitializerContext- Specified by:
getAgentIdin interfaceAgentMessagingHandler.MessagingContext- Specified by:
getAgentIdin interfaceAgentOrchestrator.OrchestratorContext
-
getId
Alias forgetAgentId(). -
getName
Alias forgetAgentName(). -
getRole
Returns the primary (first) role, or null. -
handleMessage
Handles an incoming agent message. Override for custom behavior. -
getAgentName
Description copied from interface:AgentMessagingHandler.MessagingContextReturns the agent's name for logging.- Specified by:
getAgentNamein interfaceAgentMessagingHandler.MessagingContext- Specified by:
getAgentNamein interfaceAgentOrchestrator.OrchestratorContext
-
getAgentRoles
- Specified by:
getAgentRolesin interfaceAgentOrchestrator.OrchestratorContext
-
getAgentLLM
- Specified by:
getAgentLLMin interfaceAgentOrchestrator.OrchestratorContext
-
getAgentMemoryStore
- Specified by:
getAgentMemoryStorein interfaceAgentOrchestrator.OrchestratorContext
-
getConsolidationPipeline
Returns the memory consolidation pipeline resolved from@Memory(TAN-5049), ornullwhen the agent has no@Memoryannotation or conversation memory is disabled.The pipeline is driven automatically on
stop()(final consolidation viaonSessionEnd()).@Memory.conversation()exposes no interval setting, so periodic auto-consolidation is NOT started by the framework — callMemoryConsolidationPipeline.startAutoConsolidation(java.time.Duration)yourself if you want time-based consolidation, oronIdle()/consolidate()for event-/demand-driven runs. -
clearConversationHistory
public final void clearConversationHistory()Clears all stored conversation messages. @see AgentOrchestrator#clearConversationHistory() -
getConversationHistory
Returns an immutable copy of the conversation history. @see AgentOrchestrator#getConversationHistory() -
getConversationSize
public final int getConversationSize()Returns the number of messages in conversation history. @see AgentOrchestrator#getConversationSize() -
getAgentActionExecutor
- Specified by:
getAgentActionExecutorin interfaceAgentOrchestrator.OrchestratorContext
-
getAgentSchemaGenerator
- Specified by:
getAgentSchemaGeneratorin interfaceAgentOrchestrator.OrchestratorContext
-
getAgentRef
Description copied from interface:AgentHierarchyManager.HierarchyContextReturns the agent reference itself.- Specified by:
getAgentRefin interfaceAgentGroupManager.GroupContext- Specified by:
getAgentRefin interfaceAgentHierarchyManager.HierarchyContext
-
getParentRef
Description copied from interface:AgentHierarchyManager.HierarchyContextReturns the current parent agent.- Specified by:
getParentRefin interfaceAgentHierarchyManager.HierarchyContext
-
setParentRef
Description copied from interface:AgentHierarchyManager.HierarchyContextSets the parent agent reference directly (no bidirectional updates).- Specified by:
setParentRefin interfaceAgentHierarchyManager.HierarchyContext
-
getChildrenSnapshot
Description copied from interface:AgentHierarchyManager.HierarchyContextReturns an unmodifiable snapshot of the children list.- Specified by:
getChildrenSnapshotin interfaceAgentHierarchyManager.HierarchyContext
-
hasChild
Description copied from interface:AgentHierarchyManager.HierarchyContextChecks if the given agent is a child.- Specified by:
hasChildin interfaceAgentHierarchyManager.HierarchyContext
-
addChildDirect
Description copied from interface:AgentHierarchyManager.HierarchyContextAdds a child directly to the internal list.- Specified by:
addChildDirectin interfaceAgentHierarchyManager.HierarchyContext- Returns:
- true if added, false if already present
-
removeChildDirect
Description copied from interface:AgentHierarchyManager.HierarchyContextRemoves a child directly from the internal list.- Specified by:
removeChildDirectin interfaceAgentHierarchyManager.HierarchyContext- Returns:
- true if removed, false if not present
-
findChildById
Description copied from interface:AgentHierarchyManager.HierarchyContextFinds a child by ID.- Specified by:
findChildByIdin interfaceAgentHierarchyManager.HierarchyContext- Returns:
- the child agent or null if not found
-
getCommunicationManager
Description copied from interface:AgentHierarchyManager.HierarchyContextReturns the communication manager for inter-agent messaging.- Specified by:
getCommunicationManagerin interfaceAgentHierarchyManager.HierarchyContext- Specified by:
getCommunicationManagerin interfaceAgentMessagingHandler.MessagingContext
-
detachFromParent
public final void detachFromParent()Internal: detaches from parent without triggering bidirectional updates. -
getCallbackDispatcher
Description copied from interface:AgentMessagingHandler.MessagingContextReturns the callback dispatcher for @OnMessageReceived callbacks.- Specified by:
getCallbackDispatcherin interfaceAgentMessagingHandler.MessagingContext
-
chatInternal
Description copied from interface:AgentMessagingHandler.MessagingContextInternal chat method for query handling.- Specified by:
chatInternalin interfaceAgentMessagingHandler.MessagingContext
-
handleCNPMessageHook
Description copied from interface:AgentMessagingHandler.MessagingContextHook for CNP message handling (delegated back to Agent for override support).- Specified by:
handleCNPMessageHookin interfaceAgentMessagingHandler.MessagingContext
-
getMaxContextTokensDirect
- Specified by:
getMaxContextTokensDirectin interfaceAgentOrchestrator.OrchestratorContext
-
getErrorRecoveryScenariosDirect
- Specified by:
getErrorRecoveryScenariosDirectin interfaceAgentOrchestrator.OrchestratorContext
-
getEventPublisher
- Specified by:
getEventPublisherin interfaceAgentOrchestrator.OrchestratorContext
-
getEventHandlerRegistry
- Specified by:
getEventHandlerRegistryin interfaceAgentOrchestrator.OrchestratorContext
-
ensureEvalContext
public final void ensureEvalContext()- Specified by:
ensureEvalContextin interfaceAgentOrchestrator.OrchestratorContext
-
getEvalContext
- Specified by:
getEvalContextin interfaceAgentOrchestrator.OrchestratorContext
-
fireOnBeforeChat
- Specified by:
fireOnBeforeChatin interfaceAgentOrchestrator.OrchestratorContext
-
fireOnAfterChat
- Specified by:
fireOnAfterChatin interfaceAgentOrchestrator.OrchestratorContext
-
fireOnError
- Specified by:
fireOnErrorin interfaceAgentOrchestrator.OrchestratorContext
-
fireOnBeforeToolCall
- Specified by:
fireOnBeforeToolCallin interfaceAgentOrchestrator.OrchestratorContext
-
fireOnAfterToolCall
public final void fireOnAfterToolCall(String toolName, Object result, boolean success, long latencyMs) - Specified by:
fireOnAfterToolCallin interfaceAgentOrchestrator.OrchestratorContext
-
recordToolOutcome
public final void recordToolOutcome(String toolName, Object result, boolean success, long latencyMs) - Specified by:
recordToolOutcomein interfaceAgentOrchestrator.OrchestratorContext
-
isReasoningEnabled
public final boolean isReasoningEnabled()- Specified by:
isReasoningEnabledin interfaceAgentOrchestrator.OrchestratorContext
-
getReasoningStrategyRaw
- Specified by:
getReasoningStrategyRawin interfaceAgentOrchestrator.OrchestratorContext
-
setLastReasoningResult
- Specified by:
setLastReasoningResultin interfaceAgentOrchestrator.OrchestratorContext
-
notifyActivity
public final void notifyActivity()- Specified by:
notifyActivityin interfaceAgentOrchestrator.OrchestratorContext
-
isContextGraphEnabled
public final boolean isContextGraphEnabled()- Specified by:
isContextGraphEnabledin interfaceAgentOrchestrator.OrchestratorContext
-
getContextManagerDirect
- Specified by:
getContextManagerDirectin interfaceAgentOrchestrator.OrchestratorContext
-
setToolCallFilter
Sets a filter controlling which tool calls are allowed. @see AgentOrchestrator#setToolCallFilter -
setToolCallListener
Sets a listener for tool call lifecycle events. @see AgentOrchestrator#setToolCallListener -
setChatKnowledgeBinding
Binds a live or provider-backed canonical retrieval source to chat. A builder-suppliedKnowledgeBaseis installed as a snapshot binding and retains precedence during initialization. -
getChatKnowledgeBinding
Returns the owner-scoped canonical chat binding, if configured. -
invalidateChatKnowledge
public final long invalidateChatKnowledge()Advances the chat source revision used by subsequent retrievals. -
getFeedbackCollector
Returns the feedback collector (never null; no-op if tnsai-intelligence absent). @see AgentCapabilities#getFeedbackCollector() -
setFeedbackCollector
Sets the feedback collector (null resets to no-op). @see AgentCapabilities#setFeedbackCollector -
getPaymentBroker
Returns the payment broker (never null; defaults toPaymentBroker.noOp()). @see AgentCapabilities#getPaymentBroker() -
setPaymentBroker
Sets the payment broker (null resets toPaymentBroker.noOp()). @see AgentCapabilities#setPaymentBroker -
getAgentClass
Description copied from interface:AgentInitializer.InitializerContextReturns the agent's class for reflection- Specified by:
getAgentClassin interfaceAgentInitializer.InitializerContext- Specified by:
getAgentClassin interfaceAgentOrchestrator.OrchestratorContext
-
getLLMTemplate
- Specified by:
getLLMTemplatein interfaceAgentInitializer.InitializerContext
-
getRolesTemplate
- Specified by:
getRolesTemplatein interfaceAgentInitializer.InitializerContext
-
getIdentitiesTemplate
- Specified by:
getIdentitiesTemplatein interfaceAgentInitializer.InitializerContext
-
getCommunicationTemplate
- Specified by:
getCommunicationTemplatein interfaceAgentInitializer.InitializerContext
-
getPlansTemplate
- Specified by:
getPlansTemplatein interfaceAgentInitializer.InitializerContext
-
getErrorRecoveryScenariosTemplate
- Specified by:
getErrorRecoveryScenariosTemplatein interfaceAgentInitializer.InitializerContext
-
getMemoryStoreTemplate
- Specified by:
getMemoryStoreTemplatein interfaceAgentInitializer.InitializerContext
-
getMaxContextTokensTemplate
- Specified by:
getMaxContextTokensTemplatein interfaceAgentInitializer.InitializerContext
-
getRetrievalConfig
The settings a chat turn searches with: the chat defaults under the merged search of the SEARCH entries in the chat scope ofgetAgentKnowledgeEntries().- Returns:
- the chat search settings, or empty when chat searches nothing
- Since:
- 0.13.0
-
getAgentKnowledgeSources
- Specified by:
getAgentKnowledgeSourcesin interfaceAgentOrchestrator.OrchestratorContext- Returns:
- the sources of the agent's action-level knowledge
-
getAgentKnowledgeEntries
The agent's knowledge with each entry'suse: what its@AgentSpecdeclares, with thegetKnowledge()entries layered over it by name.- Specified by:
getAgentKnowledgeEntriesin interfaceAgentOrchestrator.OrchestratorContext- Returns:
- the agent's knowledge with each entry's
use; by default everyAgentOrchestrator.OrchestratorContext.getAgentKnowledgeSources()source, searched - Since:
- 0.18.0
-
getAgentActionKnowledge
ThegetActionKnowledge()names, copied.- Specified by:
getAgentActionKnowledgein interfaceAgentOrchestrator.OrchestratorContext- Returns:
- entry names by action name that replace an action's own knowledge; empty by default
- Since:
- 0.18.0
-
getAgentKnowledgeScope
- Specified by:
getAgentKnowledgeScopein interfaceAgentOrchestrator.OrchestratorContext
-
getDefaultRetryPolicyTemplate
- Specified by:
getDefaultRetryPolicyTemplatein interfaceAgentInitializer.InitializerContext
-
getAgentRestartPolicyTemplate
- Specified by:
getAgentRestartPolicyTemplatein interfaceAgentInitializer.InitializerContext
-
getInjectedLLM
- Specified by:
getInjectedLLMin interfaceAgentInitializer.InitializerContext
-
getInjectedMemoryStore
- Specified by:
getInjectedMemoryStorein interfaceAgentInitializer.InitializerContext
-
getInjectedActionExecutor
- Specified by:
getInjectedActionExecutorin interfaceAgentInitializer.InitializerContext
-
id
Returns the agent ID (never null, no init required).- Specified by:
idin interfaceAgentCommunicationManager.MessageReceiver
-
name
Returns the human-readable agent name (derived from class name). -
description
Returns the agent description from @AgentSpec (may be empty). -
version
Returns the agent version from @AgentSpec (default: "1.0.0"). -
autoStart
public final boolean autoStart()Returns whether the agent should auto-start (default: true). -
idleTimeoutMs
public final int idleTimeoutMs()Returns the idle timeout in milliseconds (0 = never suspend). -
did
Returns the DID (Decentralized Identifier) for this agent. -
roles
Returns the assigned roles (never null, never empty). -
llm
Returns the LLM client used by this agent. -
setLLM
Replaces the LLM client; conversation history is preserved. -
getProtocolManager
Returns the protocol manager (null if no protocol annotations). -
getHealthState
Returns the current resilience health state. @see AgentCapabilities#getHealthState() -
getResilienceManager
Returns the resilience manager. @see AgentCapabilities#getResilienceManager() -
getVariant
Gets the current agent variant (quality/speed/cost tier). -
setVariant
Sets the agent variant for runtime quality tier switching. -
setVariantSelector
Sets the variant selector for automatic variant selection. -
getVariantSelector
Gets the configured variant selector. -
resolveVariant
Resolves the effective variant for a given task. -
getSystemPrompt
Returns the complete system prompt (identity + roles + learned behavior). Sent to LLM with every request.- Specified by:
getSystemPromptin interfaceAgentOrchestrator.OrchestratorContext
-
getSystemPromptForMessage
System prompt rendered for a specific user message — used by the chat orchestrator so theSkillResolversees the latest turn and can surface the most-relevant descriptions for that turn (TNS-289).When no
SkillStoreis wired, this is exactlygetSystemPrompt(). -
invokeSkill
public final Optional<ActiveSkill> invokeSkill(String name, List<String> arguments, Map<String, String> environment) Programmatically activate a skill by name (TNS-289). Equivalent to the user typing/skill-name args...but bypasses theuser-invocableflag so framework code can drive activation regardless of the skill's user-facing visibility.- Returns:
- the
ActiveSkillon success, orOptional.empty()if no skill with the given name is registered or no skill manager is wired
-
getSkillManager
-
setCommunicationManager
Sets the communication manager for inter-agent messaging. -
start
public final void start()No-op: protocols auto-start when annotations are detected. -
stop
public final void stop()Stops the protocol manager, idle monitor, role registry and releases resources. Idempotent — calling on an already-stopped agent is a no-op (issue #21). TransitionsRUNNING → STOPPING → STOPPED; if called fromSTARTINGthe agent transitions directly toSTOPPEDwithout ever reachingRUNNING. -
addEvalHook
Adds an evaluation hook for metric collection. -
removeEvalHook
Removes an evaluation hook. -
clearEvalContext
Clears the current evaluation context and creates a new session. -
setEvalEnabled
public final void setEvalEnabled(boolean enabled) Enables or disables evaluation hooks. -
isEvalEnabled
public final boolean isEvalEnabled()Checks if evaluation hooks are enabled. -
recordGoalCompletion
Manually records a goal completion event for evaluation. -
restartAgent
Restarts the agent with fresh state.- Specified by:
restartAgentin interfaceAgentOrchestrator.OrchestratorContext
-
chat
Sends a message to the agent and returns the LLM response. Uses history and tools by default. -
chat
Sends a message with optional conversation history. Tools enabled by default. -
chat
Sends a message with full control over history and tools. -
chat
public final String chat(String message, boolean useHistory, boolean useTools, ChatRetrievalContext retrievalContext) Sends a message with request-local retrieval isolation and lifecycle context. -
chatWithStructure
Sends a message and returns a structured, validated response using guardrails pattern. -
chatWithStructure
public final <T> T chatWithStructure(String message, OutputParser<T> parser, int maxRetries, ChatRetrievalContext retrievalContext) Structured chat with request-local retrieval isolation and lifecycle context. -
chatWithFormat
public final <T> T chatWithFormat(String message, Class<T> targetClass, OutputFormat format, int maxRetries) Chat with structured output in a specific format. -
chatWithFormat
public final <T> T chatWithFormat(String message, Class<T> targetClass, OutputFormat format, int maxRetries, ChatRetrievalContext retrievalContext) Formatted chat with request-local retrieval isolation and lifecycle context. -
chatWithFormat
Chat with structured output using annotation-defined format or JSON default. -
chatWithFormat
public final <T> T chatWithFormat(String message, Class<T> targetClass, int maxRetries, ChatRetrievalContext retrievalContext) Annotation-formatted chat with request-local retrieval context. -
getEnsembleExecutor
Returns the ensemble executor for parallel LLM operations. @see AgentOrchestrator#getEnsembleExecutor() -
getOutputFormatter
Returns the output formatter for serialization. @see AgentOrchestrator#getOutputFormatter() -
streamChat
Streams response tokens without tool support. @see AgentOrchestrator#streamChat(String) -
streamChatWithTools
Streams response with full tool-calling loop. @see AgentOrchestrator#streamChatWithTools -
streamChatWithTools
public final String streamChatWithTools(String message, Consumer<ChatChunk> handler, ChatRetrievalContext retrievalContext) Streams tools with request-local retrieval isolation and lifecycle context. -
streamChatWithRetrievedContext
public final String streamChatWithRetrievedContext(String outboundMessage, String historyMessage, Consumer<ChatChunk> handler) Streams canonically fenced retrieved context while persisting only the original user message.- Parameters:
outboundMessage- message sent to the LLM for this requesthistoryMessage- original user message persisted in conversation historyhandler- callback receiving streamed chunks- Returns:
- the complete response
-
streamChatWithRetrievedContext
public final String streamChatWithRetrievedContext(String outboundMessage, String historyMessage, Consumer<ChatChunk> handler, ChatRetrievalContext retrievalContext) Streams pre-rendered evidence with request-local retrieval lifecycle context. -
chatWithEvents
Chat with real-time TnsAI event emission (AG-UI integration). @see AgentOrchestrator#chatWithEvents -
chatWithEvents
public final String chatWithEvents(String message, Consumer<TnsAIEvent> eventConsumer, ChatRetrievalContext retrievalContext) Emits events with request-local retrieval isolation and lifecycle context. -
chatWithEvents
Chat with events published to a session on the configured publisher. @see #setEventPublisher -
setEventPublisher
Sets the event publisher for event-based chat methods. -
executeAction
Executes a named action (untyped). PreferexecuteAction(com.tnsai.actions.model.ActionRequest). @see AgentOrchestrator#executeActionPublic- Specified by:
executeActionin interfaceAgentMessagingHandler.MessagingContext
-
executeAction
public final Object executeAction(String actionName, Map<String, Object> parameters, ChatRetrievalContext retrievalContext) Executes an action with request-local retrieval isolation and lifecycle context. -
executeAction
Executes a named action with a typed input bean — Javarecord, POJO withgetX/isXaccessors, or class with public fields. The bean's components are mapped to the action's parameter parameters by name viaParamBeanMapper.Eliminates the
Map.of(...)call site for the common case:public record SummariseInput(String path, String question) {} agent.executeAction("summarise", new SummariseInput( "/data/sales.csv", "Top region?" ));Java overload resolution routes
Map<String, Object>call sites toexecuteAction(String, Map)(more specific), so existing code is unchanged. Records and other beans bind to this overload.- Parameters:
actionName- the action's method nameinput- a Javarecord, POJO,Map, ornull- Returns:
- the action's return value, as produced by the underlying executor
- Since:
- 0.8.0
- See Also:
-
executeAction
Executes an action using a typed request. @see AgentOrchestrator#executeActionTyped -
executeAction
public final ActionResponse executeAction(ActionRequest request, ChatRetrievalContext retrievalContext) Executes a typed action request with request-local retrieval context. -
executeActionOnRole
public final Object executeActionOnRole(String roleId, String actionName, Map<String, Object> parameters) Executes an action on a specific role (untyped). Prefer the typed overload. @see AgentOrchestrator#executeActionOnRole -
executeActionOnRole
public final Object executeActionOnRole(String roleId, String actionName, Map<String, Object> parameters, ChatRetrievalContext retrievalContext) Executes a role action with request-local retrieval context. -
executeActionOnRole
Executes an action on a specific role with a typed input bean. SeeexecuteAction(String, Object)for the bean shapes accepted.- Parameters:
roleId- the role identifieractionName- the action's method nameinput- a Javarecord, POJO,Map, ornull- Returns:
- the action's return value
- Since:
- 0.8.0
-
executeActionOnRole
Executes a typed action on a specific role. @see AgentOrchestrator#executeActionOnRoleTyped -
executeActionOnRole
public final ActionResponse executeActionOnRole(String roleId, ActionRequest request, ChatRetrievalContext retrievalContext) Executes a typed role action with request-local retrieval context. -
getParent
Returns the parent agent, or null if root. @see AgentHierarchyManager#getParent() -
setParent
Sets the parent agent (maintains bidirectional consistency). @see AgentHierarchyManager#setParent -
getChildren
Returns the child agents (unmodifiable). @see AgentHierarchyManager#getChildren() -
addChild
Adds a child agent (maintains bidirectional consistency). @see AgentHierarchyManager#addChild -
addChildren
Adds multiple child agents at once. @see AgentHierarchyManager#addChildren -
removeChild
Removes a child agent. @see AgentHierarchyManager#removeChild -
delegateToChild
Delegates an action to a child agent. @see AgentHierarchyManager#delegateToChild -
escalateToParent
Escalates an action to the parent agent. @see AgentHierarchyManager#escalateToParent -
receiveMessage
- Specified by:
receiveMessagein interfaceAgentCommunicationManager.MessageReceiver
-
getToolsDescription
Returns a human-readable description of all available tools/actions. @see AgentOrchestrator#getToolsDescription() -
getToolsForLLM
Returns tool catalog as JSON-Schema fragments for LLM binding (List<Map<String, Object>>per Anthropic-style tool-use). Type changed fromList<ToolDefinition>in v0.6.0 (RFC #188).- See Also:
-
joinGroup
Joins a group by ID. -
joinGroup
Joins an existing group. -
leaveGroup
Leaves a group by ID. -
leaveGroup
Leaves a group. -
getGroups
Returns all groups this agent is a member of. -
isIdleMonitoringEnabled
public final boolean isIdleMonitoringEnabled()Returns true if idle monitoring is active. -
getIdleTime
public final long getIdleTime()Returns milliseconds since last activity, or -1 if not monitored. -
plan
Generates a plan for all unsatisfied goals. @see AgentCapabilities#plan() -
planForGoal
Generates a plan for a specific goal. @see AgentCapabilities#planForGoal -
executePlan
Executes a plan on the first role. Plan steps do not pass the access gate, so the bundled planner refuses a plan whose step declares an execution policy or@SecuritywithSecurityExceptionbefore any step runs; a customPlannerHandledecides for itself.- See Also:
-
extractCurrentState
Extracts current @State from all roles. @see AgentCapabilities#extractCurrentState() -
getPlannerHandle
Returns the planner handle if configured. -
setPlannerHandle
Sets the planner handle (null to disable). -
isPlanningEnabled
public final boolean isPlanningEnabled()Returns true if a PlannerHandle is configured. -
setEnvironment
Sets the environment (null to detach). @see AgentCapabilities#setEnvironment -
getEnvironment
Returns the environment if configured. -
isEnvironmentEnabled
public final boolean isEnvironmentEnabled()Returns true if an environment is attached. -
perceive
Perceives the current environment state. @see AgentCapabilities#perceive() -
actOnEnvironment
Acts on the attached environment. @see AgentCapabilities#actOnEnvironment -
enableContextGraph
Enables context graph tracking (decision tracing + snapshots). @see AgentCapabilities#enableContextGraph -
getContextManager
Returns the context manager if context graph is enabled. @see AgentCapabilities#getContextManager() -
getReasoningStrategy
Returns the reasoning strategy if configured. @see AgentCapabilities#getReasoningStrategy() -
setReasoningStrategy
Sets the reasoning strategy (null to disable). @see AgentCapabilities#setReasoningStrategy -
getLastReasoningResult
Returns the last reasoning result, or empty. @see AgentCapabilities#getLastReasoningResult()
-