### Install Dependencies and Start Agent Source: https://github.com/microsoft/agents-for-js/blob/main/test-agents/proactive-agent/README.md Installs project dependencies and starts the agent server. Ensure Node.js is installed and environment variables are configured. ```bash npm install npm start ``` -------------------------------- ### Start the Agent Locally Source: https://github.com/microsoft/agents-for-js/blob/main/test-agents/agentic-ai/README.md Execute this npm command to start the Agent application after dependencies have been installed. ```bash npm start ``` -------------------------------- ### Create and Use Copilot Studio Client Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-copilotstudio-client/README.md Example of creating a Copilot Studio client by loading settings from environment variables, acquiring a token, and starting a conversation. Ensure you have implemented `loadCopilotStudioConnectionSettingsFromEnv` and `acquireToken`. ```typescript const createClient = async (): Promise => { const settings = loadCopilotStudioConnectionSettingsFromEnv() const token = await acquireToken(settings) const copilotClient = new CopilotStudioClient(settings, token) return copilotClient } const copilotClient = await createClient() const replies = await copilotClient.startConversationAsync(true) replies.forEach(r => console.log(r.text)) ``` -------------------------------- ### Start the Sample Application Source: https://github.com/microsoft/agents-for-js/blob/main/test-agents/copilotstudio-console/README.md Execute the command to start the Copilot Studio console agent sample. ```bash npm run start ``` -------------------------------- ### Install Copilot Studio Client Package Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-copilotstudio-client/README.md Install the @microsoft/agents-copilotstudio-client package using npm or yarn. ```sh npm install @microsoft/agents-copilotstudio-client ``` -------------------------------- ### Install @microsoft/agents-hosting Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting/README.md Install the package using npm. ```sh npm install @microsoft/agents-hosting ``` -------------------------------- ### Install Slack Extension Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-extensions-slack/README.md Install the Slack channel extension using npm. This command adds the necessary package to your project. ```bash npm install @microsoft/agents-hosting-extensions-slack ``` -------------------------------- ### Install @microsoft/agents-activity Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-activity/README.md Install the package using npm. ```sh npm install @microsoft/agents-activity ``` -------------------------------- ### Install Agent Dependencies Source: https://github.com/microsoft/agents-for-js/blob/main/test-agents/agentic-ai/README.md Run this npm command in the agent's root directory to install all necessary project dependencies. ```bash npm install ``` -------------------------------- ### Install Teams Extension Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-extensions-teams/README.md Install the Teams extension package using npm. ```bash npm install @microsoft/agents-hosting-extensions-teams ``` -------------------------------- ### Install OpenTelemetry API Packages Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-telemetry/README.md Install the OpenTelemetry API packages for full integration with the SDK. These are optional; the SDK falls back to noop implementations if they are missing. ```sh npm install @opentelemetry/api @opentelemetry/api-logs ``` -------------------------------- ### Create an Echo Bot with AgentApplication Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting/README.md Example demonstrating how to create an echo bot using the AgentApplication object and MemoryStorage. ```ts import { AgentApplication, MemoryStorage, TurnContext, TurnState } from '@microsoft/agents-hosting' const echo = new AgentApplication({ storage: new MemoryStorage() }) echo.onConversationUpdate('membersAdded', async (context: TurnContext) => { await context.sendActivity('Welcome to the Echo sample, send a message to see the echo feature in action.') }) echo.onActivity('message', async (context: TurnContext, state: TurnState) => { let counter: number = state.getValue('conversation.counter') || 0 await context.sendActivity(`[${counter++}]You said: ${context.activity.text}`) state.setValue('conversation.counter', counter) }) ``` -------------------------------- ### Quick Start: Initialize and Register Slack Extension Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-extensions-slack/README.md Initialize the AgentApplication and register the SlackAgentExtension. This sets up basic message handling for Slack. ```typescript import { startServer } from '@microsoft/agents-hosting-express' import { AgentApplication, MemoryStorage, TurnState } from '@microsoft/agents-hosting' import { SlackAgentExtension } from '@microsoft/agents-hosting-extensions-slack' const app = new AgentApplication({ storage: new MemoryStorage() }) app.registerExtension(new SlackAgentExtension(app), (slack) => { slack.onSlackMessage(async (context, state) => { await context.sendActivity('Hello from Slack!') }) }) startServer(app) ``` -------------------------------- ### Start Express Server for Agents Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting-express.api.md Use this function to start an Express server that hosts an Agent Application or Activity Handler. It accepts an agent and optional authentication configuration. ```typescript import { ActivityHandler } from '@microsoft/agents-hosting'; import { AgentApplication } from '@microsoft/agents-hosting'; import { AuthConfiguration } from '@microsoft/agents-hosting'; import express from 'express'; import { TurnState } from '@microsoft/agents-hosting'; // @public export const startServer: (agent: AgentApplication> | ActivityHandler, authConfiguration?: AuthConfiguration) => express.Express; ``` -------------------------------- ### Basic Agent Setup with Teams Extension Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-extensions-teams/README.md Set up a basic agent application and register the Teams extension. This snippet shows the initial configuration and message handling. ```typescript import { AgentApplication, MemoryStorage, TurnContext, TurnState } from '@microsoft/agents-hosting' import { startServer } from '@microsoft/agents-hosting-express' import { TeamsAgentExtension } from '@microsoft/agents-hosting-extensions-teams' // Create the agent application const app = new AgentApplication({ storage: new MemoryStorage() }) // Create and register the Teams extension const teamsExt = new TeamsAgentExtension(app) app.registerExtension(teamsExt, (tae) => { // Configure Teams-specific handlers here console.log('Teams extension registered') }) // Handle messages app.onActivity('message', async (context: TurnContext, state: TurnState) => { await context.sendActivity(`I received your message: "${context.activity.text}"`) }) // Start the server startServer(app) ``` -------------------------------- ### Example cURL for Creating Teams Channel Conversation Source: https://github.com/microsoft/agents-for-js/blob/main/test-agents/proactive-agent/README.md Example cURL command to create a new Teams conversation. Requires user and tenant IDs, and optionally a Teams channel ID. ```bash curl -X POST http://localhost:3978/api/proactive/teams-channel \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "userId": "aad-object-id", "tenantId": "tenant-id" }' ``` -------------------------------- ### Host Agent in Express Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-express/README.md Starts an Express server to host the AgentApplication. Requires importing `AgentApplication` and `startServer`. ```typescript import { AgentApplication, TurnState } from '@microsoft/agents-hosting'; import { startServer } from '@microsoft/agents-hosting-express'; const app = new AgentApplication(); app.onMessage('hello', async (context, state) => { await context.sendActivity('Hello, world!'); }); startServer(app); ``` -------------------------------- ### Example cURL for Proactive Continue Source: https://github.com/microsoft/agents-for-js/blob/main/test-agents/proactive-agent/README.md Example cURL command to continue a previously stored conversation using its ID. Includes authorization header and JSON content type. ```bash curl -X POST http://localhost:3978/api/proactive/continue/19:abc123@thread.tacv2 \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "message": "Your nightly report is ready." }' ``` -------------------------------- ### Create New Container with /id Partition Key Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-storage-cosmos/CosmosDBErrorCodes.md Example of creating a new container with the correct partition key path '/id' when encountering unsupported custom partition key paths. ```typescript const storageOptions: CosmosDbPartitionedStorageOptions = { // ... other options containerId: 'bot-storage-new', // New container name compatibilityMode: false }; ``` -------------------------------- ### startServer Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting-express.api.md Initializes and starts an Express server to host an agent application or activity handler. This function is the primary entry point for integrating agents with an Express.js environment. ```APIDOC ## startServer ### Description Initializes and starts an Express server to host an agent application or activity handler. This function is the primary entry point for integrating agents with an Express.js environment. ### Signature ```typescript startServer(agent: AgentApplication> | ActivityHandler, authConfiguration?: AuthConfiguration) => express.Express ``` ### Parameters #### agent - **agent** (AgentApplication> | ActivityHandler) - Required - The agent application or activity handler to be hosted. #### authConfiguration - **authConfiguration** (AuthConfiguration) - Optional - Configuration for authentication. ### Returns - **express.Express** - The configured Express application instance. ``` -------------------------------- ### CopilotStudioClient startConversationAsync Method Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-copilotstudio-client.api.md Starts a new conversation with the Copilot Studio agent. Returns an async generator of activities. ```typescript startConversationAsync(emitStartConversationEvent?: boolean): AsyncGenerator; ``` -------------------------------- ### Express Server Setup for Agents SDK Source: https://github.com/microsoft/agents-for-js/blob/main/test-agents/SAMPLES-MIGRATION.md This snippet demonstrates setting up an Express server to handle incoming messages for the Agents SDK. It includes middleware for JSON parsing and JWT authentication, and processes requests using the adapter's process method. ```typescript import express, { Response } from 'express' import { Request, authorizeJWT } from '@microsoft/agents-hosting' const app = express() app.use(express.json()) app.use(authorizeJWT(authConfig)) app.post('/api/messages', async (req: Request, res: Response) => { await adapter.process(req, res, async (context) => await myAgent.run(context)) }) const port = process.env.PORT || 3978 app.listen(port, () => { console.log(` Server listening to port ${port} for appId ${authConfig.clientId} debug ${process.env.DEBUG}`) }) ``` -------------------------------- ### Get Agent Application Options Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting.api.md Retrieves the configuration options for the AgentApplication instance. ```typescript get options(): AgentApplicationOptions; ``` -------------------------------- ### Define a Custom Activity Handler Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting/README.md Example of creating a custom ActivityHandler class for an echo bot. ```ts // myHandler.ts import { ActivityHandler, MessageFactory } from '@microsoft/agents-hosting' export class MyHandler extends ActivityHandler { constructor () { super() this.onMessage(async (context, next) => { const replyText = `Agent: ${context.activity.text}` await context.sendActivity(MessageFactory.text(replyText)) await next() }) } } ``` -------------------------------- ### Host an Activity Handler Bot with Express Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting/README.md Example of hosting a bot using ActivityHandler with Express, CloudAdapter, and JWT authorization. ```ts // index.ts import express, { Response } from 'express' import { Request, CloudAdapter, authorizeJWT, AuthConfiguration, loadAuthConfigFromEnv } from '@microsoft/agents-hosting' import { EchoBot } from './myHandler' const authConfig: AuthConfiguration = loadAuthConfigFromEnv() const adapter = new CloudAdapter(authConfig) const myHandler = new MyHandler() const app = express() app.use(express.json()) app.use(authorizeJWT(authConfig)) app.post('/api/messages', async (req: Request, res: Response) => { await adapter.process(req, res, async (context) => await myHandler.run(context)) }) ``` -------------------------------- ### Configuration Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting-dialogs.api.md Interface for managing configuration settings. Allows getting and setting configuration values by path. ```APIDOC ## Interface: Configuration ### Description Interface for managing configuration settings. Allows getting and setting configuration values by path. ### Methods - **get(path?: string[]): T | undefined** Gets a configuration value by its path. - **set(path: string[], value: unknown): void** Sets a configuration value at the specified path. ``` -------------------------------- ### CosmosDB Storage Options with Key Suffix Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-storage-cosmos/CosmosDBErrorCodes.md Example of configuring CosmosDB storage options with a keySuffix for multi-tenant scenarios. Compatibility mode should be false or omitted. ```typescript const storageOptions: CosmosDbPartitionedStorageOptions = { // ... other options compatibilityMode: false, // or omit entirely keySuffix: '-prod' }; ``` -------------------------------- ### CosmosDB Storage Options with Compatibility Mode Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-storage-cosmos/CosmosDBErrorCodes.md Example of configuring CosmosDB storage options with compatibilityMode enabled. Key suffix should not be used when compatibilityMode is true. ```typescript const storageOptions: CosmosDbPartitionedStorageOptions = { // ... other options compatibilityMode: true // Do not specify keySuffix }; ``` -------------------------------- ### CosmosDB Storage Options with Database ID Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-storage-cosmos/CosmosDBErrorCodes.md Example of how to configure CosmosDB storage options, specifying the databaseId. The database should exist or will be created by the SDK. ```typescript const storageOptions: CosmosDbPartitionedStorageOptions = { cosmosClientOptions: { endpoint: '...', key: '...' }, databaseId: 'bot-database', // Name of your database containerId: 'bot-storage' }; ``` -------------------------------- ### CopilotStudioClient Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-copilotstudio-client.api.md Provides the main interface for interacting with a Copilot Studio agent. It allows for starting conversations, sending activities, and asking questions. ```APIDOC ## Class: CopilotStudioClient ### Description Represents a client for interacting with a Copilot Studio agent. It facilitates communication by sending and receiving activities, managing conversations, and asking questions. ### Constructor ```typescript constructor(settings: ConnectionSettings, token: string) ``` ### Methods #### askQuestionAsync ```typescript askQuestionAsync(question: string, conversationId?: string): AsyncGenerator ``` Asynchronously sends a question to the agent and returns a stream of activities in response. #### sendActivity ```typescript sendActivity(activity: Activity, conversationId?: string): AsyncGenerator ``` Asynchronously sends an activity to the agent and returns a stream of activities in response. #### startConversationAsync ```typescript startConversationAsync(emitStartConversationEvent?: boolean): AsyncGenerator ``` Asynchronously starts a new conversation with the agent and returns a stream of activities, potentially including a start conversation event. ``` -------------------------------- ### Express Middleware for JWT Authentication Source: https://github.com/microsoft/agents-for-js/blob/main/CLAUDE.md Provides an example of using authorizeJWT() middleware for Express applications to validate incoming requests. This is part of the authentication setup. ```typescript app.use(authorizeJWT()); ``` -------------------------------- ### Initialize CosmosDbPartitionedStorage with Options Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-storage-cosmos/CosmosDBErrorCodes.md Demonstrates the correct way to initialize CosmosDbPartitionedStorage by providing the required CosmosDbPartitionedStorageOptions object. ```typescript const storageOptions: CosmosDbPartitionedStorageOptions = { cosmosClientOptions: { endpoint: '...', key: '...' }, databaseId: 'bot-database', containerId: 'bot-storage' }; const storage = new CosmosDbPartitionedStorage(storageOptions); ``` -------------------------------- ### Build Sample Test Agents Source: https://github.com/microsoft/agents-for-js/blob/main/CLAUDE.md Builds the sample agents located in the test-agents directory. Useful for testing specific agent implementations. ```bash # Build sample test agents npm run build:samples ``` -------------------------------- ### loadCopilotStudioConnectionSettingsFromEnv Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-copilotstudio-client.api.md Loads Copilot Studio connection settings from environment variables. ```APIDOC ## Function: loadCopilotStudioConnectionSettingsFromEnv ### Description Loads and returns `ConnectionSettings` by reading configuration values from the environment variables. ### Returns - `ConnectionSettings` - The loaded connection settings. ``` -------------------------------- ### AtPathResolver Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting-dialogs.api.md A specific implementation of AliasPathResolver that resolves paths starting with '@'. ```APIDOC ## Class: AtPathResolver ### Description A concrete implementation of `AliasPathResolver` used for resolving paths that begin with the '@' alias. ### Methods - **constructor()** - **transformPath(path: string): string** ``` -------------------------------- ### AtAtPathResolver Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting-dialogs.api.md A specific implementation of AliasPathResolver that resolves paths starting with '@@'. ```APIDOC ## Class: AtAtPathResolver ### Description A concrete implementation of `AliasPathResolver` used for resolving paths that begin with the '@@' alias. ### Methods - **constructor()** ``` -------------------------------- ### Show all auth and connection logs Source: https://github.com/microsoft/agents-for-js/blob/main/README.md Use this command to display all logs related to authentication and connection processes. This is useful for debugging authentication flows. ```sh DEBUG=agents:authorization:* node index.js ``` -------------------------------- ### Create and Use a Trace Span in Callback Mode Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-telemetry/README.md Use `trace` to create validated spans in callback mode. The span is automatically started and ended around the provided asynchronous callback function. This mode is suitable for operations where the start and end points are clearly defined by a single function execution. ```typescript import { SpanNames, trace } from '@microsoft/agents-telemetry' const result = await trace( { name: SpanNames.AGENTS_APP_ROUTE_HANDLER, record: { conversationId: '', messageCount: 0 }, actions: ({ span }) => ({ setAttribute: (key: string, value: string) => span.setAttribute(key, value), }), end: ({ span, record, duration, error }) => { span.setAttribute('conversation.id', record.conversationId) span.setAttribute('message.count', record.messageCount) }, }, async ({ record, actions }) => { record({ conversationId }) actions.setAttribute('code.function', 'handleMessage') const result = await service.handleMessage(conversationId, text) record({ messageCount: result.count }) return result } ) ``` -------------------------------- ### Start Typing Timer Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting.api.md Activates a timer to indicate that the agent is currently typing a response. ```typescript startTypingTimer(context: TurnContext): void; ``` -------------------------------- ### loadCopilotStudioConnectionSettingsFromEnv Function Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-copilotstudio-client.api.md Loads Copilot Studio connection settings from environment variables. ```typescript loadCopilotStudioConnectionSettingsFromEnv: () => ConnectionSettings; ``` -------------------------------- ### AgentStatePropertyAccessor Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting.api.md Accessor for a specific property within AgentState, enabling get, set, and delete operations. ```APIDOC ## AgentStatePropertyAccessor ### Description Provides an interface to get, set, and delete a specific property within the AgentState. ### Methods #### constructor(state: AgentState, name: string) Initializes a new instance of AgentStatePropertyAccessor. #### delete(context: TurnContext, customKey?: CustomKey): Promise Deletes the property from the state. #### get(context: TurnContext, defaultValue?: T, customKey?: CustomKey): Promise Retrieves the value of the property. #### set(context: TurnContext, value: T, customKey?: CustomKey): Promise Sets the value of the property. ### Properties - **name** (string) - The name of the property. - **state** (AgentState) - The AgentState instance this accessor belongs to. ``` -------------------------------- ### Get Agent Application Authorization Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting.api.md Provides access to the authorization mechanisms configured for the agent application. ```typescript get authorization(): Authorization; ``` -------------------------------- ### Configure ConnectionSettings with Environment ID Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-copilotstudio-client/README.md Configure connection settings using the environment ID and Copilot Studio agent schema name. Ensure you have the necessary credentials. ```typescript const settings: ConnectionSettings = { environmentId: "your-environment-id", agentIdentifier: "your-agent-schema-name", }; ``` -------------------------------- ### ConnectionSettings Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-copilotstudio-client.api.md Configuration options for establishing a connection to a Copilot Studio agent. ```APIDOC ## Class: ConnectionSettings ### Description Defines the settings required to establish a connection with a Copilot Studio agent, extending `ConnectionOptions`. ### Constructor ```typescript constructor() constructor(options: ConnectionOptions) ``` Initializes a new instance of `ConnectionSettings`. ### Properties - **cloud** (PowerPlatformCloud) - Optional - Specifies the Power Platform cloud environment. - **copilotAgentType** (AgentType) - Optional - Specifies the type of the Copilot agent (Prebuilt or Published). ``` -------------------------------- ### CopilotStudioClient Constructor Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-copilotstudio-client.api.md Initializes a new instance of the CopilotStudioClient class. Requires connection settings and a token. ```typescript constructor(settings: ConnectionSettings, token: string); ``` -------------------------------- ### Configuration Interface Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting-dialogs.api.md Interface for managing configuration settings. Use to get and set configuration values. ```typescript export interface Configuration { // (undocumented) get(path?: string[]): T | undefined; // (undocumented) set(path: string[], value: unknown): void; } ``` -------------------------------- ### Clean and Rebuild Source: https://github.com/microsoft/agents-for-js/blob/main/CLAUDE.md Cleans the distribution directories and then rebuilds all packages. Use this to ensure a fresh build environment. ```bash # Clean dist directories and rebuild npm run build:clean ``` -------------------------------- ### Get Agent Application Adapter Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting.api.md Retrieves the adapter associated with the AgentApplication, used for communication and event handling. ```typescript get adapter(): BaseAdapter; ``` -------------------------------- ### Launch Agents Playground Source: https://github.com/microsoft/agents-for-js/blob/main/CLAUDE.md Launches the agents playground, an interactive tool for testing and experimenting with agents. This is useful for rapid development and debugging. ```bash # Launch agents playground (interactive testing tool) npm run play ``` -------------------------------- ### Start Long Running Call Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting.api.md Initiates a long-running operation within the agent application, managed by a provided handler. ```typescript protected startLongRunningCall(context: TurnContext, handler: (context: TurnContext) => Promise): Promise; ``` -------------------------------- ### Cosmos DB Initialization Options Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-storage-cosmos/CosmosDBErrorCodes.md Configuration options for initializing Cosmos DB storage, including client endpoint, key, database ID, and container ID. Ensure connection settings, network connectivity, and permissions are valid. ```typescript const storageOptions: CosmosDbPartitionedStorageOptions = { cosmosClientOptions: { endpoint: 'https://your-account.documents.azure.com:443/', key: 'valid-key-here' }, databaseId: 'bot-database', containerId: 'bot-storage' }; ``` -------------------------------- ### Build Browser Bundles Source: https://github.com/microsoft/agents-for-js/blob/main/CLAUDE.md Builds browser-compatible bundles for the packages. This process runs automatically after the main build. ```bash # Build browser bundles (runs automatically after build) npm run build:browser ``` -------------------------------- ### Conversation Parameters Interface Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-activity.api.md Defines the parameters required to start or manage a conversation, including the initial activity, agent, and members. ```typescript export interface ConversationParameters { activity: Activity; agent?: ChannelAccount; channelData: unknown; isGroup: boolean; members?: ChannelAccount[]; tenantId?: string; topicName?: string; } ``` -------------------------------- ### CopilotStudioWebChat createConnection Method Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-copilotstudio-client.api.md Creates a CopilotStudioWebChatConnection. Requires a CopilotStudioClient instance and optional settings. ```typescript static createConnection(client: CopilotStudioClient, settings?: CopilotStudioWebChatSettings): CopilotStudioWebChatConnection; ``` -------------------------------- ### AtPathResolver Class Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting-dialogs.api.md A path resolver that uses '@' as an alias. It extends AliasPathResolver and provides a default implementation for transforming paths starting with '@'. ```typescript // @public export class AtPathResolver extends AliasPathResolver { constructor(); transformPath(path: string): string; } ``` -------------------------------- ### trace.define Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-telemetry/README.md Declares a reusable trace definition without starting a span. This allows for type inference and consistent trace configurations. ```APIDOC ## trace.define(definition) ### Description Declares a reusable trace definition that can be used later with the `trace` function. This method does not start a span but provides a structured way to define trace configurations with full type inference. ### Method `trace.define` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body `definition` (TraceDefinition) - Required - The trace definition object, including name, record, and end hooks. ### Returns A `TraceDefinition` object that can be passed to the `trace` function. ### Request Example ```ts import { SpanNames, trace } from '@microsoft/agents-telemetry' const storageReadTrace = trace.define({ name: SpanNames.STORAGE_READ, record: { keys: 0 }, end: ({ span, record }) => { span.setAttribute('storage.keys', record.keys) }, }) // Later, to use the defined trace: trace(storageReadTrace, ({ record }) => { record({ keys: 5 }) return storage.read(keys) }) ``` ### Response #### Success Response (N/A - This method defines a trace, it does not return a direct response.) #### Response Example (N/A) ``` -------------------------------- ### Provide CosmosDB Endpoint in Options Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-storage-cosmos/CosmosDBErrorCodes.md Shows how to correctly set the Cosmos DB endpoint within the cosmosClientOptions for storage initialization. ```typescript const storageOptions: CosmosDbPartitionedStorageOptions = { cosmosClientOptions: { endpoint: 'https://your-cosmos-account.documents.azure.com:443/', key: 'your-key-here' }, databaseId: 'bot-database', containerId: 'bot-storage' }; ``` -------------------------------- ### Provide CosmosDB Credentials (Key-Based) Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-storage-cosmos/CosmosDBErrorCodes.md Illustrates how to provide Cosmos DB credentials using an account key for authentication. ```typescript cosmosClientOptions: { endpoint: 'https://your-cosmos-account.documents.azure.com:443/', key: 'your-primary-or-secondary-key' } ``` -------------------------------- ### Load ConnectionSettings from .env file with Direct Connect URL Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-copilotstudio-client/README.md Load connection settings from a .env file using a direct connect URL. This is useful for simplifying connection string management. ```dotenv directConnectUrl=https://direct.connect.url ``` -------------------------------- ### ThisMemoryScope Class Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting-dialogs.api.md Manages memory specific to an instance of a dialog. Use to get or set memory associated with a dialog context. ```typescript export class ThisMemoryScope extends MemoryScope { constructor(); getMemory(dialogContext: DialogContext): object; setMemory(dialogContext: DialogContext, memory: object): void; } ``` -------------------------------- ### Create Agent with AgentApplication Source: https://github.com/microsoft/agents-for-js/blob/main/CLAUDE.md Utilize AgentApplication for more complex agents, managing state and handling different activity types. Requires storage configuration. ```typescript import { AgentApplication, TurnContext, TurnState } from '@microsoft/agents-hosting' const app = new AgentApplication({ storage: new MemoryStorage() }) app.onActivity('message', async (context: TurnContext, state: TurnState) => { const counter = state.getValue('conversation.counter') || 0 await context.sendActivity(`[${counter}] You said: ${context.activity.text}`) state.setValue('conversation.counter', counter + 1) }) ``` -------------------------------- ### trace - Managed Mode Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-telemetry/README.md Starts a span with manual control over its lifecycle using `end` and `fail` methods. Suitable for long-lived operations. ```APIDOC ## trace(definition) ### Description Starts a span and returns a managed context object with methods to control the span's lifecycle (`record`, `actions`, `end`, `fail`). This mode is for operations where manual span management is required. ### Method `trace` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body `definition` (TraceDefinition) - Required - The trace definition object, including name, record, actions, and end hooks. ### Returns An object containing: - `record`: Function to update the record object associated with the span. - `actions`: Function to create span-scoped helper functions. - `end`: Function to manually end the span. - `fail`: Function to mark the span as failed with an error. ### Request Example ```ts import { SpanNames, trace } from '@microsoft/agents-telemetry' const { record, actions, end, fail } = trace({ name: SpanNames.ADAPTER_PROCESS, record: { status: 'pending' }, end: ({ span, record, duration }) => { span.setAttribute('status', record.status) }, }) try { record({ status: 'processing' }) await doWork() record({ status: 'done' }) end() } catch (error) { fail(error) end() throw error } ``` ### Response #### Success Response (200) N/A (This function initiates a trace, it does not return a direct response to the caller in the traditional sense, but rather a control object). #### Response Example (N/A) ERROR HANDLING: - The `end` hook receives `{ span, record, duration, error? }`. - Unrecognized span names throw immediately. - Disabled span categories run the callback with a noop context — no telemetry is emitted. ``` -------------------------------- ### Setting Up Conversation State and DialogSet Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-dialogs/README.md Initialize conversation state management using MemoryStorage and create a DialogSet to manage dialogs. A property is defined to capture dialog state. ```javascript // Set up a storage system that will capture the conversation state. const storage = new MemoryStorage(); const convoState = new ConversationState(storage); // Define a property associated with the conversation state. const dialogState = convoState.createProperty('dialogState'); // Initialize a DialogSet, passing in a property used to capture state. const dialogs = new DialogSet(dialogState); ``` -------------------------------- ### Semantic Action Schema Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-activity.api.md Defines the schema for a semantic action, including an ID, a state (start, continue, done), and a record of entities, each with a type. ```typescript semanticAction: z.ZodOptional, z.ZodString]>; entities: z.ZodRecord, z.objectInputType<{ type: z.ZodString; }, z.ZodTypeAny, "passthrough">>>; }, "strip", z.ZodTypeAny, { id: string; state: string; entities: Record; }, { id: string; state: string; entities: Record; }>>; ``` -------------------------------- ### trace - Callback Mode Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-telemetry/README.md Starts and ends a span automatically around a provided callback function. Useful for encapsulating operations within a trace. ```APIDOC ## trace(definition, callback) ### Description Starts a span and automatically ends it after the callback function completes or throws an error. The callback receives a context with `record` and `actions`. ### Method `trace` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body `definition` (TraceDefinition) - Required - The trace definition object, including name, record, actions, and end hooks. `callback` (Function) - Required - The asynchronous function to execute within the span. ### Request Example ```ts import { SpanNames, trace } from '@microsoft/agents-telemetry' const result = await trace( { name: SpanNames.AGENTS_APP_ROUTE_HANDLER, record: { conversationId: '', messageCount: 0 }, actions: ({ span }) => ({ setAttribute: (key: string, value: string) => span.setAttribute(key, value), }), end: ({ span, record, duration, error }) => { span.setAttribute('conversation.id', record.conversationId) span.setAttribute('message.count', record.messageCount) }, }, async ({ record, actions }) => { record({ conversationId }) actions.setAttribute('code.function', 'handleMessage') const result = await service.handleMessage(conversationId, text) record({ messageCount: result.count }) return result } ) ``` ### Response #### Success Response The return value of the callback function. #### Response Example (Depends on the callback's return value) ERROR HANDLING: - On success, the span status is set to `OK`. - On failure, the exception is recorded on the span, status is set to `ERROR`, and the error is rethrown. ``` -------------------------------- ### Load ConnectionSettings from .env file Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-copilotstudio-client/README.md Load connection settings from a .env file for environment ID and agent schema name. This simplifies configuration management. ```dotenv environmentId=your-environment-id agentIdentifier=your-agent-schema-name ``` -------------------------------- ### Generate API Documentation Source: https://github.com/microsoft/agents-for-js/blob/main/CLAUDE.md Generates API documentation for the project using TypeDoc. This command is crucial for maintaining up-to-date documentation. ```bash # Generate API documentation using TypeDoc npm run docs ``` -------------------------------- ### ThisMemoryScope Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting-dialogs.api.md Manages memory specific to the current instance or scope. It provides methods to get and set memory objects associated with a dialog context. ```APIDOC ## Class: ThisMemoryScope ### Description Manages memory specific to the current instance or scope. It provides methods to get and set memory objects associated with a dialog context. ### Methods #### constructor() Creates a new instance of ThisMemoryScope. #### getMemory(dialogContext: DialogContext): object Retrieves the memory object associated with the given dialog context. #### setMemory(dialogContext: DialogContext, memory: object): void Sets the memory object for the given dialog context. ``` -------------------------------- ### AgentApplicationBuilder Build Method Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting.api.md Builds and returns an instance of the AgentApplication based on the configured options. ```typescript build(): AgentApplication; ``` -------------------------------- ### Show all logs Source: https://github.com/microsoft/agents-for-js/blob/main/README.md This command enables logging for all categories within the agents library. Use this for comprehensive debugging when the source of an issue is unknown. ```sh DEBUG=agents:* node index.js ``` -------------------------------- ### CosmosDB Storage Options with Container ID Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-storage-cosmos/CosmosDBErrorCodes.md Example of configuring CosmosDB storage options, including both databaseId and containerId. The container can be created manually or by the SDK. ```typescript const storageOptions: CosmosDbPartitionedStorageOptions = { cosmosClientOptions: { endpoint: '...', key: '...' }, databaseId: 'bot-database', containerId: 'bot-storage' // Name of your container }; ``` -------------------------------- ### Example Request Body for Proactive Continue Source: https://github.com/microsoft/agents-for-js/blob/main/test-agents/proactive-agent/README.md Optional JSON request body for continuing a stored conversation. The 'message' field specifies the notification text. ```json { "message": "Your report is ready." } ``` -------------------------------- ### CopilotStudioClient askQuestionAsync Method Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-copilotstudio-client.api.md Asynchronously asks a question to the Copilot Studio agent. Returns an async generator of activities. ```typescript askQuestionAsync(question: string, conversationId?: string): AsyncGenerator; ``` -------------------------------- ### Basic Streaming Response in Slack Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-extensions-slack/README.md Implements a basic multi-part streaming response using createStream, start, append, and stop methods. Requires SlackAgentExtension and markdown. ```typescript import { SlackAgentExtension, markdown, } from '@microsoft/agents-hosting-extensions-slack' slack.onSlackMessage(/stream/i, async (context) => { const stream = slack.createStream(context) await stream.start() await stream.append('Thinking about your question...') await stream.append('Here is the answer: **42**.') await stream.stop('All done!') }) ``` -------------------------------- ### Disable Compatibility Mode for Automatic Container Creation Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-storage-cosmos/CosmosDBErrorCodes.md Example of disabling compatibility mode to allow the SDK to automatically create containers, useful when the container is not found. ```typescript const storageOptions: CosmosDbPartitionedStorageOptions = { // ... other options containerId: 'bot-storage', compatibilityMode: false // Allows automatic creation }; ``` -------------------------------- ### Initialize AdaptiveCardsActions Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting.api.md Demonstrates how to access the AdaptiveCardsActions class from an AgentApplication instance to manage adaptive card interactions. ```typescript get adaptiveCards(): AdaptiveCardsActions; ``` -------------------------------- ### Configure Blob Storage with Connection String Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-storage-blob/README.md Instantiate BlobStorage and Conversation/UserState using an Azure Blob Storage connection string and container ID. Ensure the BLOB_STORAGE_CONNECTION_STRING and BLOB_CONTAINER_ID environment variables are set. ```typescript const blobStorage = new BlobStorage(process.env.BLOB_STORAGE_CONNECTION_STRING!, process.env.BLOB_CONTAINER_ID!) const conversationState = new ConversationState(blobStorage) const userState = new UserState(blobStorage) ``` -------------------------------- ### TurnMemoryScope Class Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting-dialogs.api.md Manages memory specific to a single turn of interaction. Use to get or set memory associated with the current turn's dialog context. ```typescript export class TurnMemoryScope extends MemoryScope { constructor(); getMemory(dialogContext: DialogContext): object; setMemory(dialogContext: DialogContext, memory: object): void; } ``` -------------------------------- ### CopilotStudioWebChat Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-copilotstudio-client.api.md Provides static methods for creating and managing Copilot Studio web chat connections. ```APIDOC ## Class: CopilotStudioWebChat ### Description A utility class that provides static methods for creating and managing web chat connections to Copilot Studio. ### Static Methods #### createConnection ```typescript static createConnection(client: CopilotStudioClient, settings?: CopilotStudioWebChatSettings): CopilotStudioWebChatConnection ``` Creates a new web chat connection using the provided `CopilotStudioClient` and optional `CopilotStudioWebChatSettings`. ``` -------------------------------- ### Get Raw Slack Token Source: https://github.com/microsoft/agents-for-js/blob/main/packages/agents-hosting-extensions-slack/README.md Retrieve the raw Slack API token directly from channel data or environment variables. This is useful for passing to the official Slack SDK. ```typescript import { getSlackChannelData } from '@microsoft/agents-hosting-extensions-slack' slack.onSlackMessage(async (context) => { const token = getSlackChannelData(context)?.ApiToken // use token as needed }) ``` -------------------------------- ### AgentApplicationBuilder Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting.api.md A builder class for constructing AgentApplication instances. ```APIDOC ## Class: AgentApplicationBuilder ### Description A builder class for constructing AgentApplication instances. ### Methods - **build(): AgentApplication**: Builds and returns an AgentApplication instance. - **protected get options(): Partial>**: Gets the partial options for the application builder. ``` -------------------------------- ### CosmosDbPartitionedStorage Constructor Source: https://github.com/microsoft/agents-for-js/blob/main/compat/baseline/agents-hosting-storage-cosmos.api.md Initializes a new instance of the CosmosDbPartitionedStorage class. Requires options specifying database and container IDs for Cosmos DB. ```typescript import { CosmosClientOptions } from '@azure/cosmos'; import { Storage as Storage_2 } from '@microsoft/agents-hosting'; import { StoreItems } from '@microsoft/agents-hosting'; export class CosmosDbPartitionedStorage implements Storage_2 { constructor(cosmosDbStorageOptions: CosmosDbPartitionedStorageOptions); // (undocumented) [key: string]: any; delete(keys: string[]): Promise; length: number; read(keys: string[]): Promise; write(changes: StoreItems): Promise; } export interface CosmosDbPartitionedStorageOptions { compatibilityMode?: boolean; containerId: string; containerThroughput?: number; cosmosClientOptions?: CosmosClientOptions; databaseId: string; keySuffix?: string; } ```