Share via


@microsoft/agents-hosting package

Classes

ActivityHandler

Handles incoming activities from channels and dispatches them to the appropriate handlers.

AdaptiveCardsActions

A class to handle Adaptive Card actions such as executing actions, submitting actions, and performing searches.

AgentApplication

Main application class for handling agent conversations and routing.

AgentApplicationBuilder

Builder class for creating and configuring AgentApplication instances.

AgentClient

Client for communicating with other agents through HTTP requests. Manages configuration, authentication, and activity exchange with target agents.

AgentExtension

Represents an extension that adds channel-specific routing functionality to an agent application. This class allows you to register routes that are only active for a specific channel.

AgentState

Manages the state of an Agent across turns in a conversation.

AgentStatePropertyAccessor

Provides typed access to an Agent state property with automatic state loading and persistence management.

AttachmentDownloader

A utility class for downloading input files from activity attachments.

Authorization

Class responsible for managing authorization and OAuth flows. Handles multiple OAuth providers and manages the complete authentication lifecycle.

BaseAdapter

Abstract base class for all adapters in the Agents framework.

CardFactory

Factory class for creating various types of cards.

ClaimsIdentity

Represents an identity with a collection of claims.

CloudAdapter

Adapter for handling agent interactions with various channels through cloud-based services.

ConnectorClient

ConnectorClient is a client for interacting with the Microsoft Connector API.

ConsoleTranscriptLogger

A transcript logger that logs activities to the console.

ConversationState

Manages the state of a conversation.

FileStorage

A file-based storage implementation that persists data to the local filesystem.

InvokeException

Represents an exception that occurs during an invoke operation.

MemoryStorage

A simple in-memory storage provider that implements the Storage interface.

MessageFactory

A factory class for creating various types of message activities.

MiddlewareSet

Represents a set of middleware.

MsalTokenCredential

Token credential implementation that uses MSAL (Microsoft Authentication Library) to acquire access tokens. Implements the Azure Core Auth TokenCredential interface for authentication scenarios.

MsalTokenProvider

Provides tokens using MSAL.

OAuthFlow

Manages the OAuth flow

RouteList
TaskModuleAction

Represents a task module action.

TranscriptLoggerMiddleware

Middleware for logging agent conversations to a transcript logger.

TurnContext

Represents the context for a single turn in a conversation between a user and an agent.

TurnContextStateCollection

A collection for managing state within a turn context.

TurnState

Base class defining a collection of turn state scopes.

TurnStateEntry

Represents an entry in the turn state that can be tracked for changes and stored.

UserState

Manages the state of a user.

UserTokenClient

Client for managing user tokens.

Interfaces

AadResourceUrls

Represents a collection of Azure Active Directory (AAD) resource URLs. This interface defines the structure of a collection of resource URLs.

AdaptiveCard

Represents an Adaptive Card, which is a card framework that enables developers to exchange UI content in a common and consistent way.

See Adaptive Cards Documentation

AdaptiveCardAuthentication

Represents the authentication information for an adaptive card.

AdaptiveCardInvokeResponse

Represents the response of an adaptive card invoke request.

AdaptiveCardInvokeValue

Represents the value of an adaptive card invoke request.

AdaptiveCardSearchResult

Represents a single search result item returned from an Adaptive Card search operation.

AdaptiveCardsOptions

Configuration options for Adaptive Cards.

AgentApplicationOptions

Configuration options for creating and initializing an Agent Application. This interface defines all the configurable aspects of an agent's behavior, including adapter settings, storage, authorization, and various feature flags.

AgentClientConfig

Configuration settings required to connect to an agent endpoint.

AnimationCard

Represents an Animation Card.

AppMemory

Interface for memory operations that provides a way to store and retrieve values by path. Allows components to persist state data during a conversation.

AppRoute

Represents a route configuration for handling bot activities within an application.

AttachmentData

Represents the data of an attachment.

AttachmentInfo

Represents information about an attachment.

AttachmentView

Represents a view of an attachment.

AudioCard

Represents an Audio Card.

AuthConfiguration

Represents the authentication configuration.

AuthHandler

Interface defining an authorization handler for OAuth flows.

AuthProvider

Represents an authentication provider.

AuthorizationHandlers

Options for configuring user authorization. Contains settings to configure OAuth connections.

CachedAgentState

Represents agent state that has been cached in the turn context. Used internally to track state changes and avoid unnecessary storage operations.

CardImage

Represents a Card Image.

Claim

Represents a claim with a type and value.

ConversationData

Data structure to store conversation state for agent interactions

ConversationMembers

Represents the members of a conversation.

ConversationResourceResponse

Represents the response from a conversation resource operation.

ConversationsResult

Represents the result of a conversation query.

CustomKey

Represents a custom key for storing state in a specific location. Allows state to be persisted with channel and conversation identifiers independent of the current context.

DefaultConversationState

Default interface for conversation state. Extend this interface to define custom conversation state properties.

DefaultTempState

Default interface for temporary state that persists only during the current turn. Contains properties used for handling user input, file attachments, and OAuth flows.

DefaultUserState

Default interface for user state. Extend this interface to define custom user state properties.

Fact

Represents a Fact.

FlowState

Represents the state of the OAuth flow.

HeroCard

Represents a Hero Card.

InputFile

Represents a file input with its content, type, and optional URL.

InputFileDownloader

Interface for downloading input files in a specific turn context and state.

InvokeResponse

Represents the response of an invoke request.

MediaUrl

Represents a media URL.

Middleware

Interface for middleware.

O365ConnectorCard

Represents an O365 connector card.

O365ConnectorCardActionBase

Represents a base action in an O365 connector card.

O365ConnectorCardFact

Represents a fact in an O365 connector card.

O365ConnectorCardImage

Represents an image in an O365 connector card.

O365ConnectorCardSection

Represents a section in an O365 connector card.

OAuthCard

Represents an OAuth card. This interface defines the structure of an OAuth card, including its buttons, connection name, text, and associated resources.

PagedResult

Paged result of items.

ReceiptCard

Represents a receipt card.

ReceiptItem

Represents an item in a receipt card.

Request

Represents a Node.js HTTP Request, including the minimal set of use properties. Compatible with Restify, Express, and Node.js core http.

ResourceResponse

Represents a response containing a resource ID.

SearchInvokeOptions

Represents the options for a search invoke request.

SearchInvokeResponse

Represents the response of a search invoke request.

SearchInvokeValue

Represents the value of a search invoke request.

SignInResource

Represents a resource for signing in. This interface defines the structure of a sign-in resource, including the sign-in link, token exchange resource, and token post resource.

SignInState

Represents the state of a sign-in process.

StatePropertyAccessor

Interface for accessing a property in state storage with type safety.

The interface defines standard methods for working with persisted state properties, allowing property access with strong typing to reduce errors when working with complex state objects.

Storage

Defines the interface for storage operations in the Agents platform.

StoreItem

Represents an item to be stored in a storage provider. Each item can contain arbitrary data along with an optional eTag for optimistic concurrency control.

StoreItems

Represents a collection of store items indexed by key. Used as the return type for storage read operations.

ThumbnailCard

Represents a thumbnail card.

ThumbnailUrl

Represents a thumbnail URL.

TokenExchangeInvokeRequest

Represents a token exchange invoke request.

TokenExchangeRequest

Represents a request for exchanging tokens. This interface defines the structure of a token exchange request, including the URI, token, and ID.

TokenExchangeResource

Represents a resource for exchanging tokens. This interface defines the structure of a token exchange resource, including its ID, URI, and provider ID.

TokenOrSinginResourceResponse

Represents a response containing either a token or a sign-in resource. This interface defines the structure of a response that includes a token response and a sign-in resource.

TokenPostResource

Represents a resource for posting tokens. This interface defines the structure of a token post resource, including its SAS URL.

TokenResponse

Represents the response containing OAuth token information. This interface encapsulates all data related to an OAuth token response.

TokenStatus

Represents the status of a token. This interface defines the structure of a token status, including channel ID, connection name, and other metadata.

TranscriptInfo

Information about a transcript.

TranscriptLogger

Interface for logging activities to a transcript.

TranscriptStore

Interface for storing and managing transcripts.

VideoCard

Represents a video card.

Type Aliases

ActivityImageType

Defines the type of activity image to display in an O365 connector card section.

  • 'avatar': Displays the image as a profile avatar (typically circular or small)
  • 'article': Displays the image as an article thumbnail (typically rectangular or larger)
AgentHandler

Type definition for agent handler function

ApplicationEventHandler

Event handler function type for application events.

ConversationUpdateEvents

Represents the types of conversation update events that can occur.

  • membersAdded: Triggered when new members are added to the conversation.
  • membersRemoved: Triggered when members are removed from the conversation.
DeleteActivityHandler

Defines a handler for deleting an activity. Used for middleware that needs to intercept or handle activity deletions.

MiddlewareHandler

Type for middleware handler.

O365ConnectorCardActionType

Defines the possible types of actions in an O365 connector card.

  • ViewAction: Represents an action to view content.
  • OpenUri: Represents an action to open a URI.
  • HttpPOST: Represents an action to make an HTTP POST request.
  • ActionCard: Represents an action that opens a card with additional actions or inputs.
RouteHandler

A handler function for routing operations in a specific turn context and state.

RouteSelector

A specialized selector for routing operations.

Selector

A function that determines whether a specific condition is met in the given turn context.

SendActivitiesHandler

Defines a handler for processing and sending activities. Used for middleware that needs to intercept or modify activities being sent.

StorageKeyFactory

A factory function to generate storage keys based on the conversation context. Allows different storage strategies based on the conversation state.

TurnEvents

Represents the types of events that can occur during a turn in the application.

  • beforeTurn: Triggered before the turn starts.
  • afterTurn: Triggered after the turn ends.
UpdateActivityHandler

Defines a handler for updating an activity. Used for middleware that needs to intercept or modify activity updates.

Enums

AdaptiveCardActionExecuteResponseType

Defines the types of responses that can be returned after executing an Adaptive Card action.

RouteRank

Defines the priority ranking for route evaluation in the agent hosting framework.

StatusCodes

HTTP status codes enumeration for agent hosting responses.

This enum provides a comprehensive set of HTTP status codes commonly used in agent hosting scenarios, including success, redirection, client error, and server error status codes.

Functions

authorizeJWT(AuthConfiguration)

Middleware to authorize JWT tokens.

configureResponseController(Application, CloudAdapter, ActivityHandler, ConversationState)

To enable Agent to Agent communication, configures the agent response controller endpoint for handling incoming activities from external services.

getProductInfo()

Generates a string containing information about the SDK version and runtime environment. This is used for telemetry and User-Agent headers in HTTP requests.

loadAuthConfigFromEnv(string)

Loads the authentication configuration from environment variables.

loadPrevAuthConfigFromEnv()

Loads the agent authentication configuration from previous version environment variables.

Function Details

authorizeJWT(AuthConfiguration)

Middleware to authorize JWT tokens.

function authorizeJWT(authConfig: AuthConfiguration): (req: Request<Record<string, unknown>, Record<string, undefined | string | string[]>>, res: Response<any, Record<string, any>>, next: NextFunction) => Promise<void>

Parameters

authConfig
AuthConfiguration

The authentication configuration.

Returns

(req: Request<Record<string, unknown>, Record<string, undefined | string | string[]>>, res: Response<any, Record<string, any>>, next: NextFunction) => Promise<void>

An Express middleware function.

configureResponseController(Application, CloudAdapter, ActivityHandler, ConversationState)

To enable Agent to Agent communication, configures the agent response controller endpoint for handling incoming activities from external services.

function configureResponseController(app: Application, adapter: CloudAdapter, agent: ActivityHandler, conversationState: ConversationState)

Parameters

app

Application

The Express application instance to configure the route on

adapter
CloudAdapter

The CloudAdapter instance used for processing bot framework activities and managing conversations

agent
ActivityHandler

The ActivityHandler instance that contains the bot's logic for processing different types of activities

conversationState
ConversationState

The ConversationState instance used for managing conversation-specific state and conversation references

Remarks

The endpoint expects activities to be sent to: POST /api/agentresponse/v3/conversations/{conversationId}/activities/{activityId}

The function handles:

  • Normalizing incoming activity data from the request body
  • Retrieving conversation references from conversation state
  • Continuing conversations using the stored conversation reference
  • Processing EndOfConversation activities by cleaning up conversation state
  • Sending activities through the turn context and returning responses

This function sets up a POST endpoint that receives activities (messages, events, etc.) from external services and processes them through the bot framework's activity handling pipeline. It's typically used when the agent needs to receive and respond to activities from channels or services that send activities to a specific webhook endpoint.

Example

const app = express();
const adapter = new CloudAdapter();
const agent = new MyActivityHandler();
const conversationState = new ConversationState(memoryStorage);

configureResponseController(app, adapter, agent, conversationState);

getProductInfo()

Generates a string containing information about the SDK version and runtime environment. This is used for telemetry and User-Agent headers in HTTP requests.

function getProductInfo(): string

Returns

string

A formatted string containing the SDK version, Node.js version, and OS details

loadAuthConfigFromEnv(string)

Loads the authentication configuration from environment variables.

function loadAuthConfigFromEnv(cnxName?: string): AuthConfiguration

Parameters

cnxName

string

Returns

The authentication configuration.

Remarks

clientId is required'

Example

tenantId=your-tenant-id
clientId=your-client-id
clientSecret=your-client-secret

certPemFile=your-cert-pem-file
certKeyFile=your-cert-key-file

FICClientId=your-FIC-client-id

connectionName=your-connection-name
authority=your-authority-endpoint

loadPrevAuthConfigFromEnv()

Loads the agent authentication configuration from previous version environment variables.

function loadPrevAuthConfigFromEnv(): AuthConfiguration

Returns

The agent authentication configuration.

Remarks

Example

MicrosoftAppId=your-client-id
MicrosoftAppPassword=your-client-secret
MicrosoftAppTenantId=your-tenant-id