Documentation - v1.2.0-alpha.3
    Preparing search index...

    Class AgentApplication<TState>

    Main application class for handling agent conversations and routing.

    The AgentApplication class provides a framework for building conversational agents. It handles routing activities to appropriate handlers, manages conversation state, supports authentication flows, and provides various event handling capabilities.

    Key features:

    • Activity routing based on type, content, or custom selectors
    • State management with automatic load/save
    • OAuth authentication support
    • Typing indicators and long-running message support
    • Extensible architecture with custom extensions
    • Event handlers for before/after turn processing
    const app = new AgentApplication<MyState>({
    storage: new MemoryStorage(),
    adapter: myAdapter
    });

    app.onMessage('hello', async (context, state) => {
    await context.sendActivity('Hello there!');
    });

    await app.run(turnContext);

    Type Parameters

    • TState extends TurnState

      The state type extending TurnState.

    Index

    Constructors

    Properties

    _afterTurn: ApplicationEventHandler<TState>[] = []
    _beforeTurn: ApplicationEventHandler<TState>[] = []
    _extensions: AgentExtension<TState>[] = []
    _routes: RouteList<TState> = ...

    Accessors

    • get adaptiveCards(): AdaptiveCardsActions<TState>

      Gets the adaptive cards actions handler for the application.

      Returns AdaptiveCardsActions<TState>

      The adaptive cards actions instance.

      The adaptive cards actions handler provides functionality for handling adaptive card interactions, such as submit actions and other card-based events.

      app.adaptiveCards.actionSubmit('doStuff', async (context, state, data) => {
      await context.sendActivity(`Received data: ${JSON.stringify(data)}`);
      });

    Methods

    • Adds a new route to the application for handling activities.

      Parameters

      • selector: Selector

        The selector function that determines if a route should handle the current activity.

      • handler: RouteHandler<TState>

        The handler function that will be called if the selector returns true.

      • isInvokeRoute: boolean = false

        Whether this route is for invoke activities. Defaults to false.

      • rank: number = RouteRank.Unspecified

        The rank of the route, used to determine the order of evaluation. Defaults to RouteRank.Unspecified.

      • authHandlers: string[] = []

        Array of authentication handler names for this route. Defaults to empty array.

      • isAgenticRoute: boolean = false

        Whether this route is for agentic requests only. Defaults to false.

      Returns this

      The current instance of the application.

      Routes are evaluated by rank order (if provided), otherwise, in the order they are added. Invoke-based activities receive special treatment and are matched separately as they typically have shorter execution timeouts.

      app.addRoute(
      async (context) => context.activity.type === ActivityTypes.Message,
      async (context, state) => {
      await context.sendActivity('I received your message');
      },
      false, // isInvokeRoute
      RouteRank.First // rank
      );
    • Continues a conversation asynchronously.

      Parameters

      • botAppIdOrIdentity: string | JwtPayload
      • conversationReferenceOrContext: TurnContext | ConversationReference

        The conversation reference or turn context.

      • logic: (context: TurnContext) => Promise<void>

        The logic to execute during the conversation.

      Returns Promise<void>

      A promise that resolves when the conversation logic has completed.

      Error if the adapter is not configured.

    • Adds a handler for specific activity types.

      Parameters

      • type: string | RegExp | Selector | (string | RegExp | Selector)[]

        The activity type(s) to handle. Can be a string, RegExp, RouteSelector, or array of these types.

      • handler: (context: TurnContext, state: TState) => Promise<void>

        The handler function that will be called when the specified activity type is received.

      • authHandlers: string[] = []

        Array of authentication handler names for this activity. Defaults to empty array.

      • rank: RouteRank = RouteRank.Unspecified

        The rank of the route, used to determine the order of evaluation. Defaults to RouteRank.Unspecified.

      • isAgenticRoute: boolean = false

        Indicates if this handler is for agentic requests only. Defaults to false.

      Returns this

      The current instance of the application.

      This method allows you to register handlers for specific activity types such as 'message', 'conversationUpdate', etc. You can specify multiple activity types by passing an array.

      app.onActivity(ActivityTypes.Message, async (context, state) => {
      await context.sendActivity('I received your message');
      });
    • Adds a handler for conversation update events.

      Parameters

      • event: ConversationUpdateEvents

        The conversation update event to handle (e.g., 'membersAdded', 'membersRemoved').

      • handler: (context: TurnContext, state: TState) => Promise<void>

        The handler function that will be called when the specified event occurs.

      • authHandlers: string[] = []

        Array of authentication handler names for this event. Defaults to empty array.

      • rank: RouteRank = RouteRank.Unspecified

        The rank of the route, used to determine the order of evaluation. Defaults to RouteRank.Unspecified.

      • isAgenticRoute: boolean = false

        Indicates if this handler is for agentic requests only. Defaults to false.

      Returns this

      The current instance of the application.

      Error if the handler is not a function.

      Conversation update events occur when the state of a conversation changes, such as when members join or leave.

      app.onConversationUpdate('membersAdded', async (context, state) => {
      const membersAdded = context.activity.membersAdded;
      for (const member of membersAdded) {
      if (member.id !== context.activity.recipient.id) {
      await context.sendActivity('Hello and welcome!');
      }
      }
      });
    • Sets an error handler for the application.

      Parameters

      • handler: (context: TurnContext, error: Error) => Promise<void>

        The error handler function to be called when an error occurs.

      Returns this

      The current instance of the application.

      This method allows you to handle any errors that occur during turn processing. The handler will receive the turn context and the error that occurred.

      app.onError(async (context, error) => {
      console.error(`An error occurred: ${error.message}`);
      await context.sendActivity('Sorry, something went wrong!');
      });
    • Adds a handler for message activities that match the specified keyword or pattern.

      Parameters

      • keyword: string | RegExp | Selector | (string | RegExp | Selector)[]

        The keyword, pattern, or selector function to match against message text. Can be a string, RegExp, RouteSelector, or array of these types.

      • handler: (context: TurnContext, state: TState) => Promise<void>

        The handler function that will be called when a matching message is received.

      • authHandlers: string[] = []

        Array of authentication handler names for this message handler. Defaults to empty array.

      • rank: RouteRank = RouteRank.Unspecified

        The rank of the route, used to determine the order of evaluation. Defaults to RouteRank.Unspecified.

      • isAgenticRoute: boolean = false

        Indicates if this handler is for agentic requests only. Defaults to false.

      Returns this

      The current instance of the application.

      This method allows you to register handlers for specific message patterns. If keyword is a string, it matches messages containing that string. If keyword is a RegExp, it tests the message text against the regular expression. If keyword is a function, it calls the function with the context to determine if the message matches.

      app.onMessage('hello', async (context, state) => {
      await context.sendActivity('Hello there!');
      });

      app.onMessage(/help/i, async (context, state) => {
      await context.sendActivity('How can I help you?');
      });
    • Adds a handler for message reaction added events.

      Parameters

      • handler: (context: TurnContext, state: TState) => Promise<void>

        The handler function that will be called when a message reaction is added.

      • rank: RouteRank = RouteRank.Unspecified

        The rank of the route, used to determine the order of evaluation. Defaults to RouteRank.Unspecified.

      • isAgenticRoute: boolean = false

        Indicates if this handler is for agentic requests only. Defaults to false.

      Returns this

      The current instance of the application.

      This method registers a handler that will be invoked when a user adds a reaction to a message, such as a like, heart, or other emoji reaction.

      app.onMessageReactionAdded(async (context, state) => {
      const reactionsAdded = context.activity.reactionsAdded;
      if (reactionsAdded && reactionsAdded.length > 0) {
      await context.sendActivity(`Thanks for your ${reactionsAdded[0].type} reaction!`);
      }
      });
    • Adds a handler for message reaction removed events.

      Parameters

      • handler: (context: TurnContext, state: TState) => Promise<void>

        The handler function that will be called when a message reaction is removed.

      • rank: RouteRank = RouteRank.Unspecified

        The rank of the route, used to determine the order of evaluation. Defaults to RouteRank.Unspecified.

      • isAgenticRoute: boolean = false

        Indicates if this handler is for agentic requests only. Defaults to false.

      Returns this

      The current instance of the application.

      This method registers a handler that will be invoked when a user removes a reaction from a message, such as unliking or removing an emoji reaction.

      app.onMessageReactionRemoved(async (context, state) => {
      const reactionsRemoved = context.activity.reactionsRemoved;
      if (reactionsRemoved && reactionsRemoved.length > 0) {
      await context.sendActivity(`You removed your ${reactionsRemoved[0].type} reaction.`);
      }
      });
    • Sets a handler to be called when a sign-in attempt fails.

      Parameters

      • handler: (context: TurnContext, state: TurnState, id?: string) => Promise<void>

        The handler function to be called after a failed sign-in attempt.

      Returns this

      The current instance of the application.

      Error if authentication options were not configured.

      This method allows you to handle cases where a user fails to authenticate, such as when they cancel the sign-in process or an error occurs.

      app.onSignInFailure(async (context, state) => {
      await context.sendActivity('Sign-in failed. Please try again.');
      });
    • Sets a handler to be called when a user successfully signs in.

      Parameters

      • handler: (context: TurnContext, state: TurnState, id?: string) => Promise<void>

        The handler function to be called after successful sign-in.

      Returns this

      The current instance of the application.

      Error if authentication options were not configured.

      This method allows you to perform actions after a user has successfully authenticated. The handler will receive the turn context and state.

      app.onSignInSuccess(async (context, state) => {
      await context.sendActivity('You have successfully signed in!');
      });
    • Adds an event handler for specified turn events.

      Parameters

      • event: TurnEvents | TurnEvents[]

        The turn event(s) to handle. Can be 'beforeTurn', 'afterTurn', or other custom events.

      • handler: (context: TurnContext, state: TState) => Promise<boolean>

        The handler function that will be called when the event occurs.

      Returns this

      The current instance of the application.

      Turn events allow you to execute logic before or after the main turn processing. Handlers added for 'beforeTurn' are executed before routing logic. Handlers added for 'afterTurn' are executed after routing logic.

      app.onTurn('beforeTurn', async (context, state) => {
      console.log('Processing before turn');
      return true; // Continue execution
      });
    • Registers an extension with the application.

      Type Parameters

      Parameters

      • extension: T

        The extension instance to register.

      • regcb: (ext: T) => void

        Callback function called after successful registration.

      Returns void

      Error if the extension is already registered.

      Extensions provide a way to add custom functionality to the application. Each extension can only be registered once to prevent conflicts.

      const myExtension = new MyCustomExtension();
      app.registerExtension(myExtension, (ext) => {
      console.log('Extension registered:', ext.name);
      });
    • Executes the application logic for a given turn context.

      Parameters

      • turnContext: TurnContext

        The context for the current turn of the conversation.

      Returns Promise<void>

      A promise that resolves when the application logic has completed.

      This method is the entry point for processing a turn in the conversation. It delegates the actual processing to the runInternal method, which handles the core logic for routing and executing handlers.

      const app = new AgentApplication();
      await app.run(turnContext);
    • Executes the application logic for a given turn context.

      Parameters

      • turnContext: TurnContext

        The context for the current turn of the conversation.

      Returns Promise<boolean>

      A promise that resolves to true if a handler was executed, false otherwise.

      This is the core internal method that processes a turn in the conversation. It handles routing and executing handlers based on the activity type and content. While this method is public, it's typically called internally by the run method.

      The method performs the following operations:

      1. Starts typing timer if configured
      2. Processes mentions if configured
      3. Loads turn state
      4. Handles authentication flows
      5. Downloads files if file downloaders are configured
      6. Executes before-turn event handlers
      7. Routes to appropriate handlers
      8. Executes after-turn event handlers
      9. Saves turn state
      const handled = await app.runInternal(turnContext);
      if (!handled) {
      console.log('No handler matched the activity');
      }
    • Sends a proactive message to a conversation.

      Parameters

      • botAppIdOrIdentity: string | JwtPayload
      • context: TurnContext | ConversationReference

        The turn context or conversation reference to use.

      • activityOrText: string | Activity

        The activity or text to send.

      • Optionalspeak: string

        Optional text to be spoken by the bot on a speech-enabled channel.

      • OptionalinputHint: string

        Optional input hint for the activity.

      Returns Promise<ResourceResponse | undefined>

      A promise that resolves to the resource response from sending the activity.

      This method allows you to send messages proactively to a conversation, outside the normal turn flow.

      // With conversation reference
      await app.sendProactiveActivity(conversationReference, 'Important notification!');

      // From an existing context
      await app.sendProactiveActivity(turnContext, 'Important notification!');
    • Starts a long-running call, potentially in a new conversation context.

      Parameters

      • context: TurnContext

        The turn context for the current conversation.

      • handler: (context: TurnContext) => Promise<boolean>

        The handler function to execute.

      Returns Promise<boolean>

      A promise that resolves to the result of the handler.

    • Starts a typing indicator timer for the current turn context.

      Parameters

      • context: TurnContext

        The turn context for the current conversation.

      Returns void

      void

      This method starts a timer that sends typing activity indicators to the user at regular intervals. The typing indicator continues until a message is sent or the timer is explicitly stopped.

      The typing indicator helps provide feedback to users that the agent is processing their message, especially when responses might take time to generate.

      app.startTypingTimer(turnContext);
      // Do some processing...
      await turnContext.sendActivity('Response after processing');
      // Typing timer automatically stops when sending a message
    • Stops the typing indicator timer if it's currently running.

      Returns void

      void

      This method clears the typing indicator timer to prevent further typing indicators from being sent. It's typically called automatically when a message is sent, but can also be called manually to stop the typing indicator.

      app.startTypingTimer(turnContext);
      // Do some processing...
      app.stopTypingTimer(); // Manually stop the typing indicator