### Custom TurnState Example Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/turnstate?view=agents-sdk-js-latest Example of how to create a derived class that extends TurnState to add additional state scopes. ```APIDOC ### Example ```javascript class MyTurnState extends TurnState { protected async onComputeStorageKeys(context) { const keys = await super.onComputeStorageKeys(context); keys['myScope'] = `myScopeKey`; return keys; } public get myScope() { const scope = this.getScope('myScope'); if (!scope) { throw new Error(`MyTurnState hasn't been loaded. Call load() first.`); } return scope.value; } public set myScope(value) { const scope = this.getScope('myScope'); if (!scope) { throw new Error(`MyTurnState hasn't been loaded. Call load() first.`); } scope.replace(value); } } ``` ``` -------------------------------- ### Define autostart behavior Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/animationcard Indicates whether the animation card should automatically start. ```TypeScript autostart: boolean ``` -------------------------------- ### Get Product Information Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting Generates a string containing SDK version and runtime environment details for telemetry and headers. ```TypeScript function getProductInfo(): string ``` -------------------------------- ### Initialize and run an AgentApplication Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentapplication Demonstrates basic setup of an AgentApplication with storage and an adapter, followed by a message handler and execution. ```TypeScript const app = new AgentApplication({ storage: new MemoryStorage(), adapter: myAdapter }); app.onMessage('hello', async (context, state) => { await context.sendActivity('Hello there!'); }); await app.run(turnContext); ``` -------------------------------- ### Method: get Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/conversationstate?view=agents-sdk-js-latest Gets the state from the turn context without loading it from storage. ```APIDOC ## Method: get ### Description Gets the state from the turn context without loading it from storage. ### Parameters - **context** (TurnContext) - Required - The turn context containing the state to get. ### Response - **any** - The state object, or undefined if no state is found. ``` -------------------------------- ### AgentStatePropertyAccessor - Basic Usage Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentstatepropertyaccessor Demonstrates the basic usage of AgentStatePropertyAccessor for creating, getting, modifying, and saving typed user profile state. ```APIDOC ## AgentStatePropertyAccessor - Basic Usage ### Description This example shows how to create a property accessor for a `UserProfile` object, retrieve its current value with a default, modify it, and then save the changes to the user state. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Request Example ```typescript // Assuming 'userState' and 'context' are already initialized interface UserProfile { name: string; preferences: { theme: string; language: string }; } // Create a property accessor const userProfile = userState.createProperty("userProfile"); // Get with default value const profile = await userProfile.get(context, { name: "", preferences: { theme: "light", language: "en" } }); // Modify the profile profile.preferences.theme = "dark"; // Save the changes await userProfile.set(context, profile); await userState.saveChanges(context); // Persist to storage ``` ### Response N/A (Illustrative Example) ``` -------------------------------- ### startTypingTimer Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentapplication Starts a typing indicator timer for the current turn context to provide feedback during processing. ```APIDOC ## startTypingTimer ### Description Starts a timer that sends typing activity indicators to the user at regular intervals. The indicator continues until a message is sent or the timer is stopped. ### Parameters - **context** (TurnContext) - Required - The turn context for the current conversation. ``` -------------------------------- ### Initialize turnStateFactory Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentapplicationoptions Example of a factory function used to create a new turn state instance for each conversation turn. ```typescript () => new MyCustomTurnState() ``` -------------------------------- ### Instantiate MsalTokenCredential Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/msaltokencredential?view=agents-sdk-js-latest Creates a new instance of MsalTokenCredential. Requires an AuthConfiguration object for authentication setup. ```typescript new MsalTokenCredential(authConfig: AuthConfiguration) ``` -------------------------------- ### Register onInstallationUpdateAdd handler Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/activityhandler Registers a handler for the InstallationUpdateAdd activity type, triggered when an agent is installed or upgraded. ```TypeScript function onInstallationUpdateAdd(handler: AgentHandler): ActivityHandler ``` -------------------------------- ### GET /api/attachments/{attachmentId} Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/turncontext Gets the content of an attachment. Deprecated. ```APIDOC ## POST getAttachment ### Description Gets the content of an attachment. Warning: This API is now deprecated. ### Method POST ### Endpoint /getAttachment ### Parameters #### Path Parameters - **attachmentId** (string) - Required - The ID of the attachment - **viewId** (string) - Required - The view to get ### Returns #### Success Response (200) Promise A promise that resolves to a readable stream of the attachment content ``` -------------------------------- ### Register onInstallationUpdate handler Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/activityhandler Registers a handler for the InstallationUpdate activity type, triggered during agent installation or uninstallation. ```TypeScript function onInstallationUpdate(handler: AgentHandler): ActivityHandler ``` -------------------------------- ### Initialize and Use FileStorage Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/filestorage?view=agents-sdk-js-latest Demonstrates how to initialize FileStorage with a directory, write data, read specific keys, and delete data. Ensure the directory exists or will be created. ```typescript const storage = new FileStorage('./data'); // Write some data await storage.write({ 'user123': { name: 'John', lastSeen: new Date().toISOString() }, 'conversation456': { turn: 5, context: 'discussing weather' } }); // Read specific keys const data = await storage.read(['user123']); console.log(data.user123); // { name: 'John', lastSeen: '...' } // Delete data await storage.delete(['conversation456']); ``` -------------------------------- ### GET /api/attachments/{attachmentId} Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/turncontext?view=agents-sdk-js-latest Gets the content of an attachment. Deprecated. ```APIDOC ## GET /api/attachments/{attachmentId} ### Description Gets the content of an attachment. This API is now deprecated. Use TurnContext.turnState.get(CloudAdapter.ConnectorClientKey) instead. ### Method GET ### Endpoint /api/attachments/{attachmentId} ### Parameters #### Path Parameters - **attachmentId** (string) - Required - The ID of the attachment - **viewId** (string) - Required - The view to get ### Response #### Success Response (200) - **Promise** - A promise that resolves to a readable stream of the attachment content ``` -------------------------------- ### Get Authentication Configuration with Defaults Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting Loads authentication configuration from provided settings or environment variables, applying defaults for authority and issuers. ```text tenantId=your-tenant-id clientId=your-client-id clientSecret=your-client-secret certPemFile=your-cert-pem-file certKeyFile=your-cert-key-file sendX5C=false FICClientId=your-FIC-client-id connectionName=your-connection-name authority=your-authority-endpoint ``` ```TypeScript function getAuthConfigWithDefaults(config?: AuthConfiguration): AuthConfiguration ``` -------------------------------- ### GET /api/attachments/{attachmentId}/info Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/turncontext Gets information about an attachment. Deprecated. ```APIDOC ## POST getAttachmentInfo ### Description Gets information about an attachment. Warning: This API is now deprecated. ### Method POST ### Endpoint /getAttachmentInfo ### Parameters #### Path Parameters - **attachmentId** (string) - Required - The ID of the attachment ### Returns #### Success Response (200) Promise A promise that resolves to the attachment information ``` -------------------------------- ### Configure AgentApplication instance Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentapplication Shows how to instantiate AgentApplication with advanced configuration options including typing timers, authorization, and transcript logging. ```TypeScript const app = new AgentApplication({ storage: new MemoryStorage(), adapter: myAdapter, startTypingTimer: true, authorization: { connectionName: 'oauth' }, transcriptLogger: myTranscriptLogger, }); ``` -------------------------------- ### GET /api/attachments/{attachmentId}/info Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/turncontext?view=agents-sdk-js-latest Gets information about an attachment. Deprecated. ```APIDOC ## GET /api/attachments/{attachmentId}/info ### Description Gets information about an attachment. This API is now deprecated. Use TurnContext.turnState.get(CloudAdapter.ConnectorClientKey) instead. ### Method GET ### Endpoint /api/attachments/{attachmentId}/info ### Parameters #### Path Parameters - **attachmentId** (string) - Required - The ID of the attachment ### Response #### Success Response (200) - **Promise** - A promise that resolves to the attachment information ``` -------------------------------- ### Method: run Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/middlewareset?view=agents-sdk-js-latest Runs the middleware chain. ```APIDOC ## Method: run ### Description Runs the middleware chain. ### Parameters - **context** (TurnContext) - Required - The turn context. - **next** (() => Promise) - Required - The next function to call. ### Response - **Returns** (Promise) - A promise representing the asynchronous operation. ``` -------------------------------- ### Get Token or Sign-In Resource Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/usertokenclient Retrieves an authentication token or the necessary information for user sign-in. Requires user ID, connection details, conversation references, and an optional redirect URL. ```typescript function getTokenOrSignInResource(userId: string, connectionName: string, channelIdComposite: string, conversation: ConversationReference, relatesTo: ConversationReference, code: string, finalRedirect?: string, fwdUrl?: string): Promise ``` -------------------------------- ### use Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/baseadapter?view=agents-sdk-js-latest Adds middleware to the adapter's middleware pipeline. ```APIDOC ## use ### Description Adds middleware to the adapter's middleware pipeline. ### Parameters - **middlewares** ((Middleware | MiddlewareHandler)[]) - Required - The middleware to add. ### Response - **Returns** (BaseAdapter) - The adapter instance. ``` -------------------------------- ### Run Agent Application Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentapplication Executes the application logic for a given turn context. This is the primary method to start processing a conversation turn. ```TypeScript const app = new AgentApplication(); await app.run(turnContext); ``` ```TypeScript function run(turnContext: TurnContext): Promise ``` -------------------------------- ### AgentApplicationOptions Interface Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting?view=agents-sdk-js-latest Configuration options for creating and initializing an Agent Application. ```APIDOC ## Interface: AgentApplicationOptions ### Description 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. ### Fields - **adapterSettings** (object) - Settings for the adapter. - **storage** (object) - Storage configuration. - **authorization** (object) - Authorization settings. - **featureFlags** (object) - Various feature flags. ``` -------------------------------- ### Start Typing Indicator Timer Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentapplication Starts a typing indicator timer for the current turn. The timer automatically stops when a message is sent. ```typescript app.startTypingTimer(turnContext); // Do some processing... await turnContext.sendActivity('Response after processing'); ``` -------------------------------- ### getAgenticUserToken Method Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/msaltokenprovider?view=agents-sdk-js-latest Gets an access token for the agentic user. ```APIDOC ## getAgenticUserToken Method ### Description Gets an access token for the agentic user. ### Method `getAgenticUserToken(tenantId: string, agentAppInstanceId: string, agenticUserId: string, scopes: string[]): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const token = await tokenProvider.getAgenticUserToken('tenant123', 'appInstance456', 'userId789', ['scope1', 'scope2']); ``` ### Response #### Success Response (200) - **token** (string) - The acquired access token. #### Response Example ```json { "token": "eyJ... } ``` ``` -------------------------------- ### Initialize AgentApplication Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentapplication?view=agents-sdk-js-latest Creates a new instance of AgentApplication with optional configuration. Supports memory storage, custom adapters, and authorization. ```typescript const app = new AgentApplication({ storage: new MemoryStorage(), adapter: myAdapter, startTypingTimer: true, authorization: { connectionName: 'oauth' }, transcriptLogger: myTranscriptLogger, }); ``` ```typescript new AgentApplication(options?: Partial>) ``` -------------------------------- ### Create and Use User Profile Accessor Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentstatepropertyaccessor?view=agents-sdk-js-latest Demonstrates creating a typed property accessor for user profiles, getting with default values, modifying, and saving changes to the state. ```typescript // Create a property accessor const userProfile = userState.createProperty("userProfile"); // Get with default value const profile = await userProfile.get(context, { name: "", preferences: { theme: "light", language: "en" } }); // Modify the profile profile.preferences.theme = "dark"; // Save the changes await userProfile.set(context, profile); await userState.saveChanges(context); // Persist to storage ``` -------------------------------- ### getAgenticInstanceToken Method Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/msaltokenprovider?view=agents-sdk-js-latest Gets an access token for the agentic instance. ```APIDOC ## getAgenticInstanceToken Method ### Description Gets an access token for the agentic instance. ### Method `getAgenticInstanceToken(tenantId: string, agentAppInstanceId: string): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const token = await tokenProvider.getAgenticInstanceToken('tenant123', 'appInstance456'); ``` ### Response #### Success Response (200) - **token** (string) - The acquired access token. #### Response Example ```json { "token": "eyJ... } ``` ``` -------------------------------- ### Manage Data with FileStorage Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting Demonstrates initializing file-based storage and performing read, write, and delete operations. ```typescript const storage = new FileStorage('./data'); // Write some data await storage.write({ 'user123': { name: 'John', lastSeen: new Date().toISOString() }, 'conversation456': { turn: 5, context: 'discussing weather' } }); // Read specific keys const data = await storage.read(['user123']); console.log(data.user123); // { name: 'John', lastSeen: '...' } // Delete data await storage.delete(['conversation456']); ``` -------------------------------- ### getAgenticApplicationToken Method Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/msaltokenprovider?view=agents-sdk-js-latest Gets an access token for the agentic application. ```APIDOC ## getAgenticApplicationToken Method ### Description Gets an access token for the agentic application. ### Method `getAgenticApplicationToken(tenantId: string, agentAppInstanceId: string): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const token = await tokenProvider.getAgenticApplicationToken('tenant123', 'appInstance456'); ``` ### Response #### Success Response (200) - **token** (string) - The acquired access token. #### Response Example ```json { "token": "eyJ... } ``` ``` -------------------------------- ### getAccessToken Method Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/msaltokenprovider?view=agents-sdk-js-latest Gets an access token for a specified scope. ```APIDOC ## getAccessToken Method (Overload 1) ### Description Gets an access token using the provided authentication configuration and scope. ### Method `getAccessToken(authConfig: AuthConfiguration, scope: string): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const token = await tokenProvider.getAccessToken(authConfig, 'api://scope'); ``` ### Response #### Success Response (200) - **token** (string) - The acquired access token. #### Response Example ```json { "token": "eyJ... } ``` ``` ```APIDOC ## getAccessToken Method (Overload 2) ### Description Gets an access token using the MsalTokenProvider instance's authentication configuration and the provided scope. ### Method `getAccessToken(scope: string): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const token = await tokenProvider.getAccessToken('api://scope'); ``` ### Response #### Success Response (200) - **token** (string) - The acquired access token. #### Response Example ```json { "token": "eyJ... } ``` ``` -------------------------------- ### MsalTokenProvider Constructor Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/msaltokenprovider Initializes a new instance of the MsalTokenProvider class. ```APIDOC ## MsalTokenProvider Constructor ### Description Initializes a new instance of the MsalTokenProvider class. ### Method `new MsalTokenProvider(connectionSettings?: AuthConfiguration)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const tokenProvider = new MsalTokenProvider(authConfig); ``` ### Response None ``` -------------------------------- ### MsalTokenProvider Constructor Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/msaltokenprovider?view=agents-sdk-js-latest Initializes a new instance of the MsalTokenProvider class. ```APIDOC ## MsalTokenProvider Constructor ### Description Initializes a new instance of the MsalTokenProvider class. ### Method `new MsalTokenProvider(connectionSettings?: AuthConfiguration)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const tokenProvider = new MsalTokenProvider(authConfig); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### getAgenticUserToken Method Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/msaltokenprovider Gets an access token for the agentic user. ```APIDOC ## getAgenticUserToken Method ### Description Gets an access token for the agentic user. ### Method `getAgenticUserToken(tenantId: string, agentAppInstanceId: string, agenticUserId: string, scopes: string[]): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const token = await tokenProvider.getAgenticUserToken('tenant-id', 'app-instance-id', 'user-id', ['scope1']); ``` ### Response #### Success Response (200) - **token** (string) - A promise that resolves to the access token. #### Response Example ```json { "token": "eyJ..."; } ``` ``` -------------------------------- ### AgentApplication Constructor Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentapplication Creates a new instance of AgentApplication with optional configuration settings. ```APIDOC ## Constructor AgentApplication ### Description Creates a new instance of AgentApplication with provided configuration options. ### Parameters #### Path Parameters - **options** (Partial>) - Optional - Configuration options for the application. ### Request Example const app = new AgentApplication({ storage: new MemoryStorage(), adapter: myAdapter, startTypingTimer: true, authorization: { connectionName: 'oauth' }, transcriptLogger: myTranscriptLogger }); ``` -------------------------------- ### getAgenticInstanceToken Method Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/msaltokenprovider Gets an access token for the agentic instance. ```APIDOC ## getAgenticInstanceToken Method ### Description Gets an access token for the agentic instance. ### Method `getAgenticInstanceToken(tenantId: string, agentAppInstanceId: string): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const token = await tokenProvider.getAgenticInstanceToken('tenant-id', 'app-instance-id'); ``` ### Response #### Success Response (200) - **token** (string) - A promise that resolves to the access token. #### Response Example ```json { "token": "eyJ..."; } ``` ``` -------------------------------- ### Authentication Configuration Environment Variables Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting Environment variable configuration for authentication settings. ```text tenantId=your-tenant-id clientId=your-client-id clientSecret=your-client-secret certPemFile=your-cert-pem-file certKeyFile=your-cert-key-file sendX5C=false FICClientId=your-FIC-client-id connectionName=your-connection-name authority=your-authority-endpoint ``` -------------------------------- ### getAgenticApplicationToken Method Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/msaltokenprovider Gets an access token for the agentic application. ```APIDOC ## getAgenticApplicationToken Method ### Description Gets an access token for the agentic application. ### Method `getAgenticApplicationToken(tenantId: string, agentAppInstanceId: string): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const token = await tokenProvider.getAgenticApplicationToken('tenant-id', 'app-instance-id'); ``` ### Response #### Success Response (200) - **token** (string) - A promise that resolves to the access token. #### Response Example ```json { "token": "eyJ..."; } ``` ``` -------------------------------- ### Capture Stack Trace Example Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/invokeexception?view=agents-sdk-js-latest Demonstrates how to use Error.captureStackTrace to create a .stack property on an object. The optional constructorOpt argument can be used to omit frames from the stack trace. ```javascript const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` ```javascript function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` -------------------------------- ### getAccessToken Method Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/msaltokenprovider Gets an access token for a given scope. ```APIDOC ## getAccessToken Method (Overload 1) ### Description Gets an access token using the provided authentication configuration and scope. ### Method `getAccessToken(authConfig: AuthConfiguration, scope: string): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const token = await tokenProvider.getAccessToken(authConfig, 'api://my-scope'); ``` ### Response #### Success Response (200) - **token** (string) - The acquired access token. #### Response Example ```json { "token": "eyJ..."; } ``` ## getAccessToken Method (Overload 2) ### Description Gets an access token using the instance's authentication configuration and the provided scope. ### Method `getAccessToken(scope: string): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const token = await tokenProvider.getAccessToken('api://my-scope'); ``` ### Response #### Success Response (200) - **token** (string) - The acquired access token. #### Response Example ```json { "token": "eyJ..."; } ``` ``` -------------------------------- ### FileStorage Constructor Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/filestorage?view=agents-sdk-js-latest Initializes a new FileStorage instance, creating the necessary folder and state file if they don't exist. ```APIDOC ## Constructor Details ### FileStorage(string) Creates a new FileStorage instance that stores data in the specified folder. ```typescript new FileStorage(folder: string) ``` #### Parameters - **folder** (string) - The absolute or relative path to the folder where the state.json file will be stored #### Remarks The constructor performs the following initialization steps: 1. Creates the target folder if it doesn't exist (including parent directories) 2. Creates an empty state.json file if it doesn't exist 3. Loads existing data from state.json into memory for fast access ``` -------------------------------- ### UserTokenClient Constructors Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/usertokenclient?view=agents-sdk-js-latest Provides information on how to create new instances of the UserTokenClient. ```APIDOC ## UserTokenClient Constructors ### UserTokenClient(AxiosInstance) Creates a new instance of UserTokenClient. **Parameters** * `axiosInstance` (AxiosInstance) - The axios instance. ### UserTokenClient(string) Creates a new instance of UserTokenClient. **Parameters** * `msAppId` (string) - The Microsoft application ID. ``` -------------------------------- ### Define onTurnError property Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/baseadapter Gets the error handler for the adapter. ```TypeScript (context: TurnContext, error: Error) => Promise onTurnError ``` -------------------------------- ### Create AgentStatePropertyAccessor Instance Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentstatepropertyaccessor?view=agents-sdk-js-latest Use AgentState.createProperty for recommended accessor creation. Direct construction is possible but not advised. ```typescript const userProfile = userState.createProperty("userProfile"); const accessor = new AgentStatePropertyAccessor(userState, "userProfile"); ``` -------------------------------- ### GET /attachments/{attachmentId} Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/connectorclient Retrieves information about an attachment by its ID. ```APIDOC ## GET /attachments/{attachmentId} ### Description Retrieves attachment information by attachment ID. ### Method GET ### Endpoint /attachments/{attachmentId} ### Parameters #### Path Parameters - **attachmentId** (string) - Required - The ID of the attachment. ### Response #### Success Response (200) - **info** (AttachmentInfo) - Attachment information. ``` -------------------------------- ### Method: get Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentstatepropertyaccessor?view=agents-sdk-js-latest Retrieves the value of a property from state storage. ```APIDOC ## Method get(TurnContext, T, CustomKey) ### Description Retrieves the value of the property from state storage. Returns undefined if the property does not exist. ### Parameters - **context** (TurnContext) - Required - The current turn context. - **defaultValue** (T) - Optional - The default value to return if the property is not set. - **customKey** (CustomKey) - Optional - A custom key for scoped storage access. ### Response - **value** (T) - The retrieved property value or the default value. ``` -------------------------------- ### AgentApplicationBuilder Methods Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentapplicationbuilder Methods available for configuring and building an AgentApplication instance. ```APIDOC ## build() ### Description Builds and returns a new AgentApplication instance configured with the provided options. ### Returns - **AgentApplication** - A new AgentApplication instance ## withAuthorization(AuthorizationOptions) ### Description Sets authentication options for the AgentApplication. ### Parameters - **authHandlers** (AuthorizationOptions) - Required - The user identity authentication options ### Returns - **AgentApplicationBuilder** - This builder instance for chaining ## withStorage(Storage) ### Description Sets the storage provider for the AgentApplication. ### Parameters - **storage** (Storage) - Required - The storage implementation to use ### Returns - **AgentApplicationBuilder** - This builder instance for chaining ## withTurnStateFactory(() => TState) ### Description Sets the factory function to create new TurnState instances. ### Parameters - **turnStateFactory** (() => TState) - Required - Function that creates a new TurnState ### Returns - **AgentApplicationBuilder** - This builder instance for chaining ``` -------------------------------- ### Get the streamed message Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/streamingresponse?view=agents-sdk-js-latest Retrieves the most recently processed message from the stream. ```TypeScript function getMessage(): string ``` -------------------------------- ### Basic Usage of AgentStatePropertyAccessor Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentstatepropertyaccessor Demonstrates creating a property accessor, retrieving values with defaults, modifying state, and persisting changes. ```TypeScript // Create a property accessor const userProfile = userState.createProperty("userProfile"); // Get with default value const profile = await userProfile.get(context, { name: "", preferences: { theme: "light", language: "en" } }); // Modify the profile profile.preferences.theme = "dark"; // Save the changes await userProfile.set(context, profile); await userState.saveChanges(context); // Persist to storage ``` -------------------------------- ### Get AgentApplication Adapter Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentapplication?view=agents-sdk-js-latest Retrieves the CloudAdapter instance used by the application. ```typescript CloudAdapter adapter ``` -------------------------------- ### ConnectorClient Initialization Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/connectorclient?view=agents-sdk-js-latest Methods for creating instances of the ConnectorClient with different authentication methods. ```APIDOC ## POST /api/connector/client/auth ### Description Creates a new instance of ConnectorClient with authentication. ### Method POST ### Endpoint /api/connector/client/auth ### Parameters #### Query Parameters - **baseURL** (string) - Required - The base URL for the API. - **scope** (string) - Required - The scope for the authentication token. #### Request Body - **authConfig** (AuthConfiguration) - Required - The authentication configuration. - **authProvider** (AuthProvider) - Required - The authentication provider. - **headers** (HeaderPropagationCollection) - Optional - Optional headers to propagate in the request. ### Response #### Success Response (200) - **ConnectorClient** (ConnectorClient) - A new instance of ConnectorClient. #### Response Example ```json { "message": "ConnectorClient created successfully" } ``` ## POST /api/connector/client/token ### Description Creates a new instance of ConnectorClient with a token. ### Method POST ### Endpoint /api/connector/client/token ### Parameters #### Query Parameters - **baseURL** (string) - Required - The base URL for the API. #### Request Body - **token** (string) - Required - The authentication token. - **headers** (HeaderPropagationCollection) - Optional - Optional headers to propagate in the request. ### Response #### Success Response (200) - **ConnectorClient** (ConnectorClient) - A new instance of ConnectorClient. #### Response Example ```json { "message": "ConnectorClient created successfully" } ``` ``` -------------------------------- ### Get access token Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/msaltokenprovider?view=agents-sdk-js-latest Methods to retrieve an access token for a given scope. ```TypeScript function getAccessToken(authConfig: AuthConfiguration, scope: string): Promise ``` ```TypeScript function getAccessToken(scope: string): Promise ``` -------------------------------- ### Initialize UserState Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/userstate?view=agents-sdk-js-latest Creates a new instance of UserState. Requires a storage provider and an optional namespace. ```typescript new UserState(storage: Storage, namespace?: string) ``` -------------------------------- ### CreateConversationOptionsBuilder Usage Example Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/createconversationoptionsbuilder Demonstrates how to use the CreateConversationOptionsBuilder to create conversation options. ```APIDOC ## CreateConversationOptionsBuilder Example ### Description This example shows how to instantiate and configure `CreateConversationOptions` using the `CreateConversationOptionsBuilder`. ### Method Static method `create` followed by chained builder methods. ### Endpoint N/A (Client-side builder) ### Request Example ```typescript const opts = CreateConversationOptionsBuilder .create('my-client-id', 'msteams') .withUser('user-aad-id') .withTenantId('tenant-id') .build() ``` ### Response Example ```json { "client_id": "my-client-id", "channel_id": "msteams", "user_id": "user-aad-id", "tenant_id": "tenant-id" } ``` ``` -------------------------------- ### Instantiate MsalTokenProvider Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/msaltokenprovider Creates a new instance of MsalTokenProvider. The connectionSettings parameter is optional and provides authentication configuration. ```typescript new MsalTokenProvider(connectionSettings?: AuthConfiguration) ``` -------------------------------- ### Initialize M365AttachmentDownloader Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/m365attachmentdownloader Constructor for creating a new instance of the downloader with an optional state key. ```TypeScript new M365AttachmentDownloader(stateKey?: string) ``` -------------------------------- ### Get Responded Status Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/turncontext Check if the turn has sent a response to the user. This is a boolean property. ```typescript boolean responded ``` -------------------------------- ### Get entries iterator Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/turncontextstatecollection Returns an iterable of key-value pairs for every entry in the collection. ```TypeScript function entries(): IterableIterator<[any, any]> ``` -------------------------------- ### Method: use Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/middlewareset?view=agents-sdk-js-latest Adds middleware to the set. ```APIDOC ## Method: use ### Description Adds middleware to the set. ### Parameters - **middlewares** ((Middleware | MiddlewareHandler)[]) - Required - The middleware handlers or middleware objects to add. ### Response - **Returns** (MiddlewareSet) - The current MiddlewareSet instance. ``` -------------------------------- ### Get an attachment Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/baseadapter Retrieves an attachment. Note: This API is deprecated; use TurnContext.turnState.get instead. ```TypeScript function getAttachment(context: TurnContext, attachmentId: string, viewId: string): Promise ``` -------------------------------- ### AgentApplicationOptions Interface Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentapplicationoptions?view=agents-sdk-js-latest Configuration options for creating and initializing an Agent Application, defining behavior, storage, and communication settings. ```APIDOC ## AgentApplicationOptions Interface ### Description This interface defines all the configurable aspects of an agent's behavior, including adapter settings, storage, authorization, and various feature flags. ### Properties - **adapter** (Object) - Optional - The adapter used for handling bot interactions. Defaults to CloudAdapter. - **adaptiveCardsOptions** (Object) - Optional - Configuration for handling Adaptive Card actions. - **agentAppId** (string) - Required - The unique application ID of the agent as registered in the Bot Framework. - **authorization** (Object) - Optional - Handlers for managing user authentication and authorization. - **connections** (Object) - Optional - Configuration for managing multiple authentication connections. - **fileDownloaders** (Array) - Optional - An array of file downloaders for handling different types of input files. - **headerPropagation** (Function) - Optional - A function to handle header propagation for incoming requests. - **longRunningMessages** (boolean) - Optional - Whether to enable support for long-running message processing operations. - **normalizeMentions** (boolean) - Optional - Whether to automatically normalize mentions in incoming messages. - **removeRecipientMention** (boolean) - Optional - Whether to automatically remove mentions of the bot's name from incoming messages. - **startTypingTimer** (boolean) - Optional - Whether to start a typing indicator timer when the bot begins processing a message. - **storage** (Object) - Required - The storage mechanism for persisting conversation and user state. - **transcriptLogger** (Object) - Optional - The transcript logger to use for logging conversations. - **turnStateFactory** (Function) - Optional - A factory function that creates a new instance of the turn state for each conversation turn. ### Example { "agentAppId": "12345678-1234-1234-1234-123456789012", "startTypingTimer": true, "removeRecipientMention": true } ``` -------------------------------- ### Get Conversations Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/connectorclient Retrieves a list of conversations. Supports pagination using a continuation token. ```TypeScript function getConversations(continuationToken?: string): Promise ``` -------------------------------- ### ActivityHandler Class Usage Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/activityhandler Demonstrates how to instantiate the ActivityHandler and register event handlers for specific activity types using the fluent API. ```APIDOC ## ActivityHandler Class ### Description The ActivityHandler class is the central hub for processing incoming activities in conversational AI applications. It provides a framework for handling activity types such as messages, conversation updates, message reactions, typing indicators, and invoke operations. ### Key Features - **Activity Routing**: Automatically routes activities to appropriate handlers based on activity type. - **Handler Registration**: Provides fluent API methods (e.g., onMessage, onConversationUpdate) for registering event handlers. - **Invoke Support**: Built-in handling for adaptive card actions and search invoke operations. ### Usage Example ```typescript const handler = new ActivityHandler() .onMessage(async (context, next) => { await context.sendActivity('Hello!'); await next(); }) .onMembersAdded(async (context, next) => { // Welcome new members await next(); }); ``` ``` -------------------------------- ### Define agentAppId Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentapplicationoptions Example of the unique application ID string required for bot registration. ```typescript "12345678-1234-1234-1234-123456789012" ``` -------------------------------- ### Get value by key Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/turncontextstatecollection Retrieves the value associated with the specified key, returning undefined if not found. ```TypeScript function get(key: any): any ``` ```TypeScript function get(key: any): T ``` -------------------------------- ### Method: load Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/conversationstate?view=agents-sdk-js-latest Loads the state from storage into the turn context. ```APIDOC ## Method: load ### Description Loads the state from storage into the turn context. If state is already cached and force is not set, the cached version is used. ### Parameters - **context** (TurnContext) - Required - The turn context to load state into. - **force** (boolean) - Optional - If true, forces a reload from storage. - **customKey** (CustomKey) - Optional - Custom storage key to use. ### Response - **Promise** - A promise that resolves to the loaded state object. ``` -------------------------------- ### AgentApplication Constructor Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentapplication Creates a new instance of the AgentApplication class with specified options. ```APIDOC ## Constructors ### AgentApplication(Partial>) Creates a new instance of AgentApplication. **Example** ```typescript const app = new AgentApplication({ storage: new MemoryStorage(), adapter: myAdapter }); app.onMessage('hello', async (context, state) => { await context.sendActivity('Hello there!'); }); await app.run(turnContext); ``` **Example** ```typescript const app = new AgentApplication({ storage: new MemoryStorage(), adapter: myAdapter, startTypingTimer: true, authorization: { connectionName: 'oauth' }, transcriptLogger: myTranscriptLogger, }); ``` ``` -------------------------------- ### Build an AgentApplication instance Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentapplicationbuilder Creates and returns a new AgentApplication instance based on the current builder configuration. ```TypeScript function build(): AgentApplication ``` -------------------------------- ### run Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentapplication Executes the application logic for a given turn context. This is the primary method for processing incoming activities. ```APIDOC ## POST /api/app/run ### Description Executes the application logic for a given turn context. ### Method POST ### Endpoint /api/app/run ### Parameters #### Request Body - **turnContext** (TurnContext) - Required - The context object for the current turn. ### Request Example ```typescript { "turnContext": "{ ... }" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the status of the execution. #### Response Example ```json { "status": "Turn processed successfully" } ``` ``` -------------------------------- ### Get Iterator for RouteList Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/routelist?view=agents-sdk-js-latest This function returns an iterator for the RouteList, allowing you to traverse through the defined AppRoute objects. ```typescript function [iterator](): Iterator, any, undefined> ``` -------------------------------- ### BaseAdapter Methods Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/baseadapter Documentation for the methods provided by the BaseAdapter class, covering conversation continuation, activity management, and middleware integration. ```APIDOC ## Methods ### continueConversation Continues a conversation. * **Parameters**: * `botAppIdOrIdentity` (string | JwtPayload) - The application ID or identity of the bot. * `reference` (Partial) - Required - The conversation reference to continue. * `logic` ((revocableContext: TurnContext) => Promise) - Required - The logic to execute. * **Returns**: `Promise` - A promise representing the completion of the continue operation. ### deleteActivity Deletes an existing activity. * **Parameters**: * `context` (TurnContext) - Required - The TurnContext for the current turn. * `reference` (Partial) - Required - The conversation reference of the activity to delete. * **Returns**: `Promise` - A promise representing the completion of the delete operation. ### getAttachment * **Warning**: This API is now deprecated. Use `TurnContext.turnState.get(CloudAdapter.ConnectorClientKey)`. Gets an attachment. * **Parameters**: * `context` (TurnContext) - Required. * `attachmentId` (string) - Required - The attachment ID. * `viewId` (string) - Required - The view ID. * **Returns**: `Promise` - A promise representing the NodeJS.ReadableStream for the requested attachment. ### getAttachmentInfo * **Parameters**: * `context` (TurnContext) - Required. * `attachmentId` (string) - Required. * **Returns**: `Promise` ### sendActivities Sends a set of activities to the conversation. * **Parameters**: * `context` (TurnContext) - Required. * `activities` (Activity[]) - Required. * **Returns**: `Promise` ### updateActivity Updates an existing activity. * **Parameters**: * `context` (TurnContext) - Required. * `activity` (Activity) - Required. * **Returns**: `Promise` ### uploadAttachment * **Parameters**: * `context` (TurnContext) - Required. * `conversationId` (string) - Required. * `attachmentData` (AttachmentData) - Required. * **Returns**: `Promise` ### use Adds middleware to the adapter's middleware pipeline. * **Parameters**: * `middleware` (Middleware | MiddlewareHandler[]) - Required - The middleware to add. * **Returns**: `void` ``` -------------------------------- ### Get Conversation Member Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/connectorclient Retrieves a specific member from a conversation. Requires user ID and conversation ID. ```TypeScript function getConversationMember(userId: string, conversationId: string): Promise ``` -------------------------------- ### GET /state/property Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentstatepropertyaccessor?view=agents-sdk-js-latest Retrieves the value of a property from state storage, with support for default values and custom keys. ```APIDOC ## GET /state/property ### Description Retrieves the value of the property from state storage. If the property does not exist and a default value is provided, the default is deep cloned, stored in state, and returned. ### Parameters - **context** (TurnContext) - Required - The turn context for the current conversation turn. - **defaultValue** (T) - Optional - Default value to use if the property doesn't exist. - **customKey** (CustomKey) - Optional - Custom key for accessing state in a specific storage location. ### Response - **Returns** (Promise) - A promise that resolves to the property value, the cloned default value, or undefined. ``` -------------------------------- ### Initialize TurnContext with Adapter Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/turncontext Creates a new instance using a base adapter, the incoming activity, and an optional identity. ```TypeScript new TurnContext(adapterOrContext: BaseAdapter, request: Activity, identity?: JwtPayload) ``` -------------------------------- ### Create TranscriptLoggerMiddleware Instance Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/transcriptloggermiddleware?view=agents-sdk-js-latest Instantiate the TranscriptLoggerMiddleware by providing a TranscriptLogger instance. ```typescript new TranscriptLoggerMiddleware(logger: TranscriptLogger) ``` -------------------------------- ### AgentStatePropertyAccessor - Custom Storage Keys Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentstatepropertyaccessor Demonstrates how to use custom storage keys with AgentStatePropertyAccessor for scenarios like multi-tenancy. ```APIDOC ## AgentStatePropertyAccessor - Custom Storage Keys ### Description This example shows how to utilize custom storage keys with `AgentStatePropertyAccessor`. This is particularly useful in multi-tenant applications where state needs to be isolated per tenant. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Request Example ```typescript // Assuming 'userState' and 'context' are already initialized // 'tenantId' and 'dataProperty' are defined elsewhere // Define a custom key for the specific tenant const customKey = { key: `tenant_${tenantId}` }; // Get state using the custom key const tenantData = await dataProperty.get(context, defaultData, customKey); // Set state using the custom key await dataProperty.set(context, updatedData, customKey); ``` ### Response N/A (Illustrative Example) ``` -------------------------------- ### Create video card attachment Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/cardfactory?view=agents-sdk-js-latest Creates a video card attachment. ```TypeScript static function videoCard(title: string, media: (string | MediaUrl)[], buttons?: (string | CardAction)[], other?: Partial): Attachment ``` -------------------------------- ### Get Streaming Response Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/turncontext Access the streaming response object for the current turn. This property holds a StreamingResponse object. ```typescript StreamingResponse streamingResponse ``` -------------------------------- ### Instantiate CloudAdapter Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/cloudadapter Creates a new instance of the CloudAdapter. Optional parameters include authentication configuration, authentication provider, and user token client. ```typescript new CloudAdapter(authConfig?: AuthConfiguration, authProvider?: AuthProvider, userTokenClient?: UserTokenClient) ``` -------------------------------- ### Configure Adaptive Card Options Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentapplicationoptions Set up configuration options for handling Adaptive Card actions and interactions, controlling how the agent processes card submissions and button clicks. ```typescript adaptiveCardsOptions?: AdaptiveCardsOptions ``` -------------------------------- ### Get State Scope by Name Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/turnstate?view=agents-sdk-js-latest Retrieves a specific state scope by its name. Returns undefined if the scope is not found. ```typescript function getScope(scope: string): undefined | TurnStateEntry ``` -------------------------------- ### Instantiate AgentState Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentstate?view=agents-sdk-js-latest Creates a new instance of the AgentState class. Requires a storage provider and a storage key factory. ```typescript new AgentState(storage: Storage, storageKey: StorageKeyFactory) ``` -------------------------------- ### Get Conversation State Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/turnstate?view=agents-sdk-js-latest Access the conversation-scoped state object. This state is shared across all turns within a conversation. ```typescript TConversationState conversation ``` -------------------------------- ### Get state property Source: https://learn.microsoft.com/en-us/javascript/api/%40microsoft/agents-hosting/agentstatepropertyaccessor?view=agents-sdk-js-latest Retrieves a property value from state, optionally providing a default value if the property does not exist. ```TypeScript const counterProperty = userState.createProperty("counter"); // Get with default value const count = await counterProperty.get(context, 0); console.log(count); // 0 if property doesn't exist, otherwise the stored value ``` ```TypeScript interface UserProfile { name: string; preferences: { theme: string; notifications: boolean }; } const userProfile = userState.createProperty("profile"); const profile = await userProfile.get(context, { name: "Anonymous", preferences: { theme: "light", notifications: true } }); ``` ```TypeScript const profile = await userProfile.get(context); if (profile === undefined) { console.log("Profile has not been set yet"); } else { console.log(`Welcome back, ${profile.name}!`); } ``` ```TypeScript const tenantKey = { key: `tenant_${tenantId}` }; const tenantData = await dataProperty.get(context, defaultData, tenantKey); ``` ```TypeScript function get(context: TurnContext, defaultValue?: T, customKey?: CustomKey): Promise ```