@microsoft/agents-hosting 1.5.0-beta.2.gf6783d691c → 1.5.0-beta.26.gaab35a7b76

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/dist/package.json +10 -9
  2. package/dist/src/activityHandler.js +2 -2
  3. package/dist/src/activityHandler.js.map +1 -1
  4. package/dist/src/agent-client/agentClient.js +49 -40
  5. package/dist/src/agent-client/agentClient.js.map +1 -1
  6. package/dist/src/agent-client/agentResponseHandler.js +2 -2
  7. package/dist/src/agent-client/agentResponseHandler.js.map +1 -1
  8. package/dist/src/app/agentApplication.d.ts +53 -19
  9. package/dist/src/app/agentApplication.js +201 -117
  10. package/dist/src/app/agentApplication.js.map +1 -1
  11. package/dist/src/app/agentApplicationBuilder.d.ts +15 -0
  12. package/dist/src/app/agentApplicationBuilder.js +22 -4
  13. package/dist/src/app/agentApplicationBuilder.js.map +1 -1
  14. package/dist/src/app/agentApplicationOptions.d.ts +38 -0
  15. package/dist/src/app/attachmentDownloader.js +2 -2
  16. package/dist/src/app/attachmentDownloader.js.map +1 -1
  17. package/dist/src/app/auth/authorization.js +12 -9
  18. package/dist/src/app/auth/authorization.js.map +1 -1
  19. package/dist/src/app/auth/authorizationManager.d.ts +22 -5
  20. package/dist/src/app/auth/authorizationManager.js +268 -54
  21. package/dist/src/app/auth/authorizationManager.js.map +1 -1
  22. package/dist/src/app/auth/handlerStorage.js +3 -1
  23. package/dist/src/app/auth/handlerStorage.js.map +1 -1
  24. package/dist/src/app/auth/handlers/agenticAuthorization.d.ts +19 -16
  25. package/dist/src/app/auth/handlers/agenticAuthorization.js +46 -52
  26. package/dist/src/app/auth/handlers/agenticAuthorization.js.map +1 -1
  27. package/dist/src/app/auth/handlers/azureBotAuthorization.d.ts +51 -75
  28. package/dist/src/app/auth/handlers/azureBotAuthorization.js +217 -192
  29. package/dist/src/app/auth/handlers/azureBotAuthorization.js.map +1 -1
  30. package/dist/src/app/auth/types.d.ts +100 -1
  31. package/dist/src/app/auth/utils.d.ts +10 -0
  32. package/dist/src/app/auth/utils.js +21 -0
  33. package/dist/src/app/auth/utils.js.map +1 -0
  34. package/dist/src/app/index.d.ts +1 -0
  35. package/dist/src/app/index.js +1 -0
  36. package/dist/src/app/index.js.map +1 -1
  37. package/dist/src/app/proactive/conversation.d.ts +43 -0
  38. package/dist/src/app/proactive/conversation.js +67 -0
  39. package/dist/src/app/proactive/conversation.js.map +1 -0
  40. package/dist/src/app/proactive/conversationBuilder.d.ts +54 -0
  41. package/dist/src/app/proactive/conversationBuilder.js +110 -0
  42. package/dist/src/app/proactive/conversationBuilder.js.map +1 -0
  43. package/dist/src/app/proactive/conversationReferenceBuilder.d.ts +68 -0
  44. package/dist/src/app/proactive/conversationReferenceBuilder.js +125 -0
  45. package/dist/src/app/proactive/conversationReferenceBuilder.js.map +1 -0
  46. package/dist/src/app/proactive/createConversationOptions.d.ts +30 -0
  47. package/dist/src/app/proactive/createConversationOptions.js +10 -0
  48. package/dist/src/app/proactive/createConversationOptions.js.map +1 -0
  49. package/dist/src/app/proactive/createConversationOptionsBuilder.d.ts +69 -0
  50. package/dist/src/app/proactive/createConversationOptionsBuilder.js +141 -0
  51. package/dist/src/app/proactive/createConversationOptionsBuilder.js.map +1 -0
  52. package/dist/src/app/proactive/index.d.ts +7 -0
  53. package/dist/src/app/proactive/index.js +26 -0
  54. package/dist/src/app/proactive/index.js.map +1 -0
  55. package/dist/src/app/proactive/proactive.d.ts +248 -0
  56. package/dist/src/app/proactive/proactive.js +310 -0
  57. package/dist/src/app/proactive/proactive.js.map +1 -0
  58. package/dist/src/app/proactive/proactiveOptions.d.ts +19 -0
  59. package/dist/src/app/proactive/proactiveOptions.js +5 -0
  60. package/dist/src/app/proactive/proactiveOptions.js.map +1 -0
  61. package/dist/src/app/streaming/streamingResponse.js +2 -2
  62. package/dist/src/app/streaming/streamingResponse.js.map +1 -1
  63. package/dist/src/app/teamsAttachmentDownloader.js +2 -2
  64. package/dist/src/app/teamsAttachmentDownloader.js.map +1 -1
  65. package/dist/src/app/turnState.js +2 -2
  66. package/dist/src/app/turnState.js.map +1 -1
  67. package/dist/src/auth/authConfiguration.d.ts +61 -0
  68. package/dist/src/auth/authConfiguration.js +52 -3
  69. package/dist/src/auth/authConfiguration.js.map +1 -1
  70. package/dist/src/auth/jwt-middleware.js +2 -2
  71. package/dist/src/auth/jwt-middleware.js.map +1 -1
  72. package/dist/src/auth/msalConnectionManager.js +20 -0
  73. package/dist/src/auth/msalConnectionManager.js.map +1 -1
  74. package/dist/src/auth/msalTokenCredential.js +3 -0
  75. package/dist/src/auth/msalTokenCredential.js.map +1 -1
  76. package/dist/src/auth/msalTokenProvider.js +136 -110
  77. package/dist/src/auth/msalTokenProvider.js.map +1 -1
  78. package/dist/src/baseAdapter.js +2 -2
  79. package/dist/src/baseAdapter.js.map +1 -1
  80. package/dist/src/cloudAdapter.js +201 -154
  81. package/dist/src/cloudAdapter.js.map +1 -1
  82. package/dist/src/connector-client/connectorClient.js +176 -127
  83. package/dist/src/connector-client/connectorClient.js.map +1 -1
  84. package/dist/src/errorHelper.js +108 -0
  85. package/dist/src/errorHelper.js.map +1 -1
  86. package/dist/src/middlewareSet.js +2 -2
  87. package/dist/src/middlewareSet.js.map +1 -1
  88. package/dist/src/oauth/userTokenClient.js +78 -48
  89. package/dist/src/oauth/userTokenClient.js.map +1 -1
  90. package/dist/src/observability/index.d.ts +2 -0
  91. package/dist/src/observability/index.js +21 -0
  92. package/dist/src/observability/index.js.map +1 -0
  93. package/dist/src/observability/metrics.d.ts +21 -0
  94. package/dist/src/observability/metrics.js +87 -0
  95. package/dist/src/observability/metrics.js.map +1 -0
  96. package/dist/src/observability/traces.d.ts +234 -0
  97. package/dist/src/observability/traces.js +962 -0
  98. package/dist/src/observability/traces.js.map +1 -0
  99. package/dist/src/state/agentState.js +2 -2
  100. package/dist/src/state/agentState.js.map +1 -1
  101. package/dist/src/storage/fileStorage.js +38 -28
  102. package/dist/src/storage/fileStorage.js.map +1 -1
  103. package/dist/src/storage/memoryStorage.js +41 -30
  104. package/dist/src/storage/memoryStorage.js.map +1 -1
  105. package/dist/src/transcript/fileTranscriptLogger.js +2 -2
  106. package/dist/src/transcript/fileTranscriptLogger.js.map +1 -1
  107. package/dist/src/transcript/transcriptLoggerMiddleware.js +2 -2
  108. package/dist/src/transcript/transcriptLoggerMiddleware.js.map +1 -1
  109. package/dist/src/turnContext.js +55 -43
  110. package/dist/src/turnContext.js.map +1 -1
  111. package/package.json +10 -9
  112. package/src/activityHandler.ts +1 -1
  113. package/src/agent-client/agentClient.ts +53 -42
  114. package/src/agent-client/agentResponseHandler.ts +1 -1
  115. package/src/app/agentApplication.ts +248 -104
  116. package/src/app/agentApplicationBuilder.ts +26 -4
  117. package/src/app/agentApplicationOptions.ts +43 -0
  118. package/src/app/attachmentDownloader.ts +1 -1
  119. package/src/app/auth/authorization.ts +11 -8
  120. package/src/app/auth/authorizationManager.ts +311 -54
  121. package/src/app/auth/handlerStorage.ts +3 -1
  122. package/src/app/auth/handlers/agenticAuthorization.ts +68 -72
  123. package/src/app/auth/handlers/azureBotAuthorization.ts +260 -264
  124. package/src/app/auth/types.ts +102 -1
  125. package/src/app/auth/utils.ts +22 -0
  126. package/src/app/index.ts +1 -0
  127. package/src/app/proactive/conversation.ts +87 -0
  128. package/src/app/proactive/conversationBuilder.ts +139 -0
  129. package/src/app/proactive/conversationReferenceBuilder.ts +161 -0
  130. package/src/app/proactive/createConversationOptions.ts +35 -0
  131. package/src/app/proactive/createConversationOptionsBuilder.ts +181 -0
  132. package/src/app/proactive/index.ts +10 -0
  133. package/src/app/proactive/proactive.ts +524 -0
  134. package/src/app/proactive/proactiveOptions.ts +24 -0
  135. package/src/app/streaming/streamingResponse.ts +1 -1
  136. package/src/app/teamsAttachmentDownloader.ts +1 -1
  137. package/src/app/turnState.ts +1 -1
  138. package/src/auth/authConfiguration.ts +58 -1
  139. package/src/auth/jwt-middleware.ts +1 -1
  140. package/src/auth/msalConnectionManager.ts +22 -0
  141. package/src/auth/msalTokenCredential.ts +4 -0
  142. package/src/auth/msalTokenProvider.ts +138 -107
  143. package/src/baseAdapter.ts +1 -1
  144. package/src/cloudAdapter.ts +239 -184
  145. package/src/connector-client/connectorClient.ts +169 -126
  146. package/src/errorHelper.ts +124 -0
  147. package/src/middlewareSet.ts +1 -1
  148. package/src/oauth/userTokenClient.ts +70 -46
  149. package/src/observability/index.ts +5 -0
  150. package/src/observability/metrics.ts +103 -0
  151. package/src/observability/traces.ts +988 -0
  152. package/src/state/agentState.ts +1 -1
  153. package/src/storage/fileStorage.ts +36 -26
  154. package/src/storage/memoryStorage.ts +40 -29
  155. package/src/transcript/fileTranscriptLogger.ts +1 -1
  156. package/src/transcript/transcriptLoggerMiddleware.ts +1 -1
  157. package/src/turnContext.ts +53 -42
@@ -3,12 +3,11 @@
3
3
  * Licensed under the MIT License.
4
4
  */
5
5
 
6
- import { Activity, ActivityTypes, ConversationReference } from '@microsoft/agents-activity'
6
+ import { Activity, ActivityTypes, ConversationReference, ExceptionHelper } from '@microsoft/agents-activity'
7
7
  import { ResourceResponse } from '../connector-client'
8
- import { debug } from '@microsoft/agents-activity/logger'
9
8
  import { TurnContext } from '../turnContext'
10
9
  import { AdaptiveCardsActions } from './adaptiveCards'
11
- import { AgentApplicationOptions } from './agentApplicationOptions'
10
+ import { AgentApplicationOptions, TypingTimingOptions } from './agentApplicationOptions'
12
11
  import { ConversationUpdateEvents } from './conversationUpdateEvents'
13
12
  import { AgentExtension } from './extensions'
14
13
  import { RouteHandler } from './routeHandler'
@@ -20,11 +19,30 @@ import { RouteList } from './routeList'
20
19
  import { TranscriptLoggerMiddleware } from '../transcript'
21
20
  import { CloudAdapter } from '../cloudAdapter'
22
21
  import { Authorization, UserAuthorization, AuthorizationManager } from './auth'
22
+ import { Proactive } from './proactive'
23
23
  import { JwtPayload } from 'jsonwebtoken'
24
+ import { trace, debug } from '@microsoft/agents-telemetry'
25
+ import { AgentApplicationTraceDefinitions } from '../observability'
26
+ import { Errors } from '../errorHelper'
24
27
 
25
28
  const logger = debug('agents:app')
26
29
 
27
- const TYPING_TIMER_DELAY = 1000
30
+ // Resend typing every 4 seconds to stay ahead of the ~5 second timeout seen in
31
+ // Web Chat and Microsoft 365. Teams may keep typing indicators visible longer.
32
+ const DEFAULT_TYPING_INITIAL_DELAY = 0
33
+ const DEFAULT_TYPING_INTERVAL = 4000
34
+ const TYPING_TIMER_STATE_KEY = Symbol('typingTimerState')
35
+
36
+ type TypingTimerState = {
37
+ timer?: NodeJS.Timeout
38
+ lastSend: Promise<unknown>
39
+ stop: () => void
40
+ }
41
+
42
+ type StreamInfoEntity = {
43
+ type?: string
44
+ streamType?: string
45
+ }
28
46
 
29
47
  /**
30
48
  * Event handler function type for application events.
@@ -74,9 +92,9 @@ export class AgentApplication<TState extends TurnState> {
74
92
  protected readonly _beforeTurn: ApplicationEventHandler<TState>[] = []
75
93
  protected readonly _afterTurn: ApplicationEventHandler<TState>[] = []
76
94
  private readonly _adapter?: CloudAdapter
77
- private readonly _authorizationManager?: AuthorizationManager
78
- private readonly _authorization?: Authorization
79
- private _typingTimer: NodeJS.Timeout | undefined
95
+ private readonly _authorizationManager: AuthorizationManager
96
+ private readonly _authorization: Authorization
97
+ private readonly _proactive?: Proactive<TState>
80
98
  protected readonly _extensions: AgentExtension<TState>[] = []
81
99
  private readonly _adaptiveCards: AdaptiveCardsActions<TState>
82
100
 
@@ -112,6 +130,7 @@ export class AgentApplication<TState extends TurnState> {
112
130
  ...options,
113
131
  turnStateFactory: options?.turnStateFactory || (() => new TurnState() as TState),
114
132
  startTypingTimer: options?.startTypingTimer !== undefined ? options.startTypingTimer : false,
133
+ typing: options?.typing || undefined,
115
134
  longRunningMessages: options?.longRunningMessages !== undefined ? options.longRunningMessages : false,
116
135
  removeRecipientMention: options?.removeRecipientMention !== undefined ? options.removeRecipientMention : true,
117
136
  transcriptLogger: options?.transcriptLogger || undefined,
@@ -125,9 +144,12 @@ export class AgentApplication<TState extends TurnState> {
125
144
  this._adapter = new CloudAdapter()
126
145
  }
127
146
 
128
- if (this._options.authorization) {
129
- this._authorizationManager = new AuthorizationManager(this, this._adapter.connectionManager)
130
- this._authorization = new UserAuthorization(this._authorizationManager)
147
+ // Create Proactive whenever proactive options are explicitly configured or a storage
148
+ // backend is available — no explicit `proactive` option is required.
149
+ if (this._options.proactive !== undefined || this._options.storage !== undefined) {
150
+ const proactiveOpts = this._options.proactive ?? {}
151
+ const proactiveStorage = proactiveOpts.storage ?? this._options.storage
152
+ this._proactive = new Proactive<TState>(this, { ...proactiveOpts, storage: proactiveStorage })
131
153
  }
132
154
 
133
155
  if (this._options.longRunningMessages && !this._adapter && !this._options.agentAppId) {
@@ -141,7 +163,11 @@ export class AgentApplication<TState extends TurnState> {
141
163
  this._adapter?.use(new TranscriptLoggerMiddleware(this._options.transcriptLogger))
142
164
  }
143
165
  }
166
+
144
167
  logger.debug('AgentApplication created with options:', this._options)
168
+
169
+ this._authorizationManager = new AuthorizationManager(this, this._adapter.connectionManager)
170
+ this._authorization = new UserAuthorization(this._authorizationManager)
145
171
  }
146
172
 
147
173
  /**
@@ -151,12 +177,33 @@ export class AgentApplication<TState extends TurnState> {
151
177
  * @throws Error if no authentication options were configured.
152
178
  */
153
179
  public get authorization (): Authorization {
154
- if (!this._authorization) {
180
+ if (this._authorizationManager.handlers.length === 0) {
155
181
  throw new Error('The Application.authorization property is unavailable because no authorization options were configured.')
156
182
  }
157
183
  return this._authorization
158
184
  }
159
185
 
186
+ /**
187
+ * Gets the proactive messaging subsystem.
188
+ *
189
+ * @throws Error if no storage backend was configured (neither `options.storage` nor
190
+ * `options.proactive.storage`).
191
+ */
192
+ public get proactive (): Proactive<TState> {
193
+ if (!this._proactive) {
194
+ throw ExceptionHelper.generateException(Error, Errors.ProactivePropertyUnavailable)
195
+ }
196
+ return this._proactive
197
+ }
198
+
199
+ /**
200
+ * Returns `true` if user authorization was configured, without throwing.
201
+ * Used internally by the Proactive subsystem to check whether token acquisition is available.
202
+ */
203
+ public get hasUserAuthorization (): boolean {
204
+ return this._authorization !== undefined
205
+ }
206
+
160
207
  /**
161
208
  * Gets the options used to configure the application.
162
209
  *
@@ -583,10 +630,10 @@ export class AgentApplication<TState extends TurnState> {
583
630
  * While this method is public, it's typically called internally by the `run` method.
584
631
  *
585
632
  * The method performs the following operations:
586
- * 1. Starts typing timer if configured
587
- * 2. Processes mentions if configured
588
- * 3. Loads turn state
589
- * 4. Handles authentication flows
633
+ * 1. Handles authentication flows for routes that have auth handlers configured. If NOT authorized, it will not continue with the 2nd step, returning false.
634
+ * 2. Starts typing timer if configured
635
+ * 3. Processes mentions if configured
636
+ * 4. Loads turn state
590
637
  * 5. Downloads files if file downloaders are configured
591
638
  * 6. Executes before-turn event handlers
592
639
  * 7. Routes to appropriate handlers
@@ -600,15 +647,56 @@ export class AgentApplication<TState extends TurnState> {
600
647
  * console.log('No handler matched the activity');
601
648
  * }
602
649
  * ```
603
- *
604
650
  */
605
651
  public async runInternal (turnContext: TurnContext): Promise<boolean> {
606
- if (turnContext.activity.type === ActivityTypes.Typing) {
652
+ const { authorized, context } = await this.handleAuthorization(turnContext)
653
+
654
+ if (!authorized) {
655
+ const managed = trace(AgentApplicationTraceDefinitions.run)
656
+ managed.record({ authorized, activity: context.activity })
657
+ managed.end()
658
+ // We don't log a message here because it is handled by the authorization manager and could cause confusion during mid sign-in operations.
607
659
  return false
608
660
  }
609
661
 
610
- logger.info('Running application with activity:', turnContext.activity.id!)
611
- return await this.startLongRunningCall(turnContext, async (context) => {
662
+ const isLongRunning =
663
+ (turnContext.activity.type === ActivityTypes.Invoke && turnContext.activity.name === 'signin/tokenExchange') ||
664
+ (this._options.longRunningMessages && turnContext.activity.type === ActivityTypes.Message)
665
+
666
+ if (isLongRunning) {
667
+ logger.debug('Starting long-running messages for activity:', context.activity.id!)
668
+ this.startLongRunningCall(context, ctx => this.runTurn(ctx))
669
+ return true
670
+ }
671
+
672
+ logger.info('Running application with activity:', context.activity.id!)
673
+ return this.runTurn(context)
674
+ }
675
+
676
+ /**
677
+ * Determines if the incoming activity is authorized to be processed by the application.
678
+ * @returns An object containing the authorization status and the context (could have the continuation activity) to be used for further processing.
679
+ */
680
+ private async handleAuthorization (context: TurnContext) {
681
+ if (context.activity.type === ActivityTypes.Typing) {
682
+ return { authorized: true, context }
683
+ }
684
+
685
+ return this._authorizationManager?.process(context, async activity => {
686
+ // The incoming activity may come from the storage, so we need to restore the auth handlers.
687
+ // Since the current route may not have auth handlers.
688
+ const route = await this.getRoute(new TurnContext(context.adapter, activity, context.identity))
689
+ return route?.authHandlers ?? []
690
+ }) ?? { authorized: true, context } // If no authorization manager is configured, we assume the activity is authorized.
691
+ }
692
+
693
+ /**
694
+ * Executes the turn processing logic for the given context, including routing and handler execution.
695
+ */
696
+ private async runTurn (context: TurnContext): Promise<boolean> {
697
+ return trace(AgentApplicationTraceDefinitions.run, async ({ record }) => {
698
+ record({ authorized: true, activity: context.activity })
699
+
612
700
  try {
613
701
  if (this._options.startTypingTimer) {
614
702
  this.startTypingTimer(context)
@@ -626,40 +714,45 @@ export class AgentApplication<TState extends TurnState> {
626
714
  const state = turnStateFactory()
627
715
  await state.load(context, storage)
628
716
 
629
- const { authorized } = await this._authorizationManager?.process(context, async activity => {
630
- // The incoming activity may come from the storage, so we need to restore the auth handlers.
631
- // Since the current route may not have auth handlers.
632
- const route = await this.getRoute(new TurnContext(context.adapter, activity, turnContext.identity))
633
- return route?.authHandlers ?? []
634
- }) ?? { authorized: true } // Default to authorized if no auth manager
635
-
636
- if (!authorized) {
637
- await state.save(context, storage)
638
- return false
639
- }
640
-
641
717
  const route = await this.getRoute(context)
642
718
 
719
+ record({ routeMatched: route !== undefined })
720
+
643
721
  if (!route) {
644
722
  logger.debug('No matching route found for activity:', context.activity)
645
723
  return false
646
724
  }
647
725
 
648
- if (Array.isArray(this._options.fileDownloaders) && this._options.fileDownloaders.length > 0) {
649
- for (let i = 0; i < this._options.fileDownloaders.length; i++) {
650
- await this._options.fileDownloaders[i].downloadAndStoreFiles(context, state)
651
- }
726
+ const fileDownloaders = this._options.fileDownloaders
727
+ if (Array.isArray(fileDownloaders) && fileDownloaders.length > 0) {
728
+ await trace(AgentApplicationTraceDefinitions.downloadFiles, async ({ record }) => {
729
+ record({ attachmentsCount: context.activity.attachments?.length })
730
+ for (let i = 0; i < fileDownloaders.length; i++) {
731
+ await fileDownloaders[i].downloadAndStoreFiles(context, state)
732
+ }
733
+ })
652
734
  }
653
735
 
654
- if (!(await this.callEventHandlers(context, state, this._beforeTurn))) {
655
- await state.save(context, storage)
656
- return false
736
+ if (this._beforeTurn.length > 0) {
737
+ await trace(AgentApplicationTraceDefinitions.beforeTurn, async () => {
738
+ if (!(await this.callEventHandlers(context, state, this._beforeTurn))) {
739
+ await state.save(context, storage)
740
+ return false
741
+ }
742
+ })
657
743
  }
658
744
 
659
- await route.handler(context, state)
745
+ await trace(AgentApplicationTraceDefinitions.routeHandler, async ({ record }) => {
746
+ record({ isInvoke: route.isInvokeRoute, isAgentic: route.isAgenticRoute })
747
+ await route.handler(context, state)
748
+ })
660
749
 
661
- if (await this.callEventHandlers(context, state, this._afterTurn)) {
662
- await state.save(context, storage)
750
+ if (this._afterTurn.length > 0) {
751
+ await trace(AgentApplicationTraceDefinitions.afterTurn, async () => {
752
+ if (await this.callEventHandlers(context, state, this._afterTurn)) {
753
+ await state.save(context, storage)
754
+ }
755
+ })
663
756
  }
664
757
 
665
758
  return true
@@ -667,7 +760,7 @@ export class AgentApplication<TState extends TurnState> {
667
760
  logger.error(err)
668
761
  throw err
669
762
  } finally {
670
- this.stopTypingTimer()
763
+ this.stopTypingTimer(context)
671
764
  }
672
765
  })
673
766
  }
@@ -744,41 +837,82 @@ export class AgentApplication<TState extends TurnState> {
744
837
  *
745
838
  */
746
839
  public startTypingTimer (context: TurnContext): void {
747
- if (context.activity.type === ActivityTypes.Message && !this._typingTimer) {
748
- let timerRunning = true
749
- context.onSendActivities(async (context, activities, next) => {
750
- if (timerRunning) {
751
- for (let i = 0; i < activities.length; i++) {
752
- if (activities[i].type === ActivityTypes.Message || activities[i].channelData?.streamType) {
753
- this.stopTypingTimer()
754
- timerRunning = false
755
- await lastSend
756
- break
757
- }
758
- }
840
+ const turnState = context.turnState
841
+ const typingOptions = this.getTypingTimingOptions(context)
842
+ // Timer state is stored on the current turn so concurrent turns stay isolated.
843
+ const currentState = () => turnState.get<TypingTimerState>(TYPING_TIMER_STATE_KEY)
844
+
845
+ if (context.activity.type !== ActivityTypes.Message || currentState()) {
846
+ return
847
+ }
848
+
849
+ const state: TypingTimerState = {
850
+ lastSend: Promise.resolve(),
851
+ stop: () => {
852
+ if (state.timer) {
853
+ clearTimeout(state.timer)
854
+ state.timer = undefined
759
855
  }
760
856
 
761
- return next()
762
- })
857
+ turnState.delete(TYPING_TIMER_STATE_KEY)
858
+ }
859
+ }
860
+
861
+ turnState.set(TYPING_TIMER_STATE_KEY, state)
763
862
 
764
- let lastSend: Promise<any> = Promise.resolve()
765
- const onTimeout = async () => {
766
- try {
767
- lastSend = context.sendActivity(Activity.fromObject({ type: ActivityTypes.Typing }))
768
- await lastSend
769
- } catch (err: any) {
863
+ context.onSendActivities(async (context, activities, next) => {
864
+ // Any real response or stream start ends the typing loop for this turn.
865
+ if (activities.some(activity => activity.type === ActivityTypes.Message || this.getStreamType(activity) !== undefined)) {
866
+ state.stop()
867
+ // Wait for any in-flight typing send to finish before sending the real response.
868
+ await state.lastSend.catch((err: any) => {
770
869
  logger.error(err)
771
- this._typingTimer = undefined
772
- timerRunning = false
773
- lastSend = Promise.resolve()
774
- }
870
+ })
871
+ }
775
872
 
776
- if (timerRunning) {
777
- this._typingTimer = setTimeout(onTimeout, TYPING_TIMER_DELAY)
778
- }
873
+ return next()
874
+ })
875
+
876
+ const onTimeout = async () => {
877
+ try {
878
+ state.lastSend = this.sendTypingActivity(context)
879
+ await state.lastSend
880
+ } catch (err: any) {
881
+ logger.error(err)
882
+ state.lastSend = Promise.resolve()
883
+ state.stop()
884
+ return
885
+ }
886
+
887
+ // Only reschedule if this turn still owns the active timer state.
888
+ if (currentState() === state) {
889
+ state.timer = setTimeout(onTimeout, typingOptions.intervalMs)
779
890
  }
780
- this._typingTimer = setTimeout(onTimeout, TYPING_TIMER_DELAY)
781
891
  }
892
+
893
+ state.timer = setTimeout(onTimeout, typingOptions.initialDelayMs)
894
+ }
895
+
896
+ private getTypingTimingOptions (context: TurnContext): Required<TypingTimingOptions> {
897
+ const channelId = context.activity.channelId || context.activity.channelIdChannel || ''
898
+ const channelOptions = channelId ? this._options.typing?.channelStrategies?.[channelId] : undefined
899
+
900
+ return {
901
+ initialDelayMs: channelOptions?.initialDelayMs ?? this._options.typing?.initialDelayMs ?? DEFAULT_TYPING_INITIAL_DELAY,
902
+ intervalMs: channelOptions?.intervalMs ?? this._options.typing?.intervalMs ?? DEFAULT_TYPING_INTERVAL
903
+ }
904
+ }
905
+
906
+ private getStreamType (activity: Activity): string | undefined {
907
+ const streamingEntity = activity.entities?.find((entity) => (entity as StreamInfoEntity).type === 'streaminfo') as StreamInfoEntity | undefined
908
+ return streamingEntity?.streamType ?? activity.channelData?.streamType
909
+ }
910
+
911
+ private async sendTypingActivity (context: TurnContext): Promise<ResourceResponse[] | undefined> {
912
+ const conversationReference = context.activity.getConversationReference()
913
+ const typingActivity = Activity.fromObject({ type: ActivityTypes.Typing }).applyConversationReference(conversationReference)
914
+
915
+ return await context.adapter.sendActivities(context, [typingActivity])
782
916
  }
783
917
 
784
918
  /**
@@ -816,23 +950,37 @@ export class AgentApplication<TState extends TurnState> {
816
950
  * @returns void
817
951
  *
818
952
  * @remarks
819
- * This method clears the typing indicator timer to prevent further typing indicators
820
- * from being sent. It's typically called automatically when a message is sent, but
821
- * can also be called manually to stop the typing indicator.
953
+ * Calling this overload without a context is deprecated. It only logs a warning and does not stop any timer.
954
+ *
955
+ * @deprecated Pass the current TurnContext to stop only that turn's typing timer.
956
+ */
957
+ public stopTypingTimer (): void
958
+
959
+ /**
960
+ * Stops the typing indicator timer for the provided turn context.
961
+ *
962
+ * @param context - The turn context whose typing timer should be stopped.
963
+ * @returns void
964
+ *
965
+ * @remarks
966
+ * This method clears the typing indicator timer for the current turn to prevent further typing indicators
967
+ * from being sent. It's typically called automatically when a message is sent, but can also be called manually.
822
968
  *
823
969
  * @example
824
970
  * ```typescript
825
- * app.startTypingTimer(turnContext);
971
+ * app.startTypingTimer(turnContext)
826
972
  * // Do some processing...
827
- * app.stopTypingTimer(); // Manually stop the typing indicator
973
+ * app.stopTypingTimer(turnContext)
828
974
  * ```
829
- *
830
975
  */
831
- public stopTypingTimer (): void {
832
- if (this._typingTimer) {
833
- clearTimeout(this._typingTimer)
834
- this._typingTimer = undefined
976
+ public stopTypingTimer (context: TurnContext): void
977
+ public stopTypingTimer (context?: TurnContext): void {
978
+ if (!context) {
979
+ logger.warn('Application.stopTypingTimer() without a context is deprecated. Pass the current TurnContext instead.')
980
+ return
835
981
  }
982
+
983
+ context.turnState.get<TypingTimerState>(TYPING_TIMER_STATE_KEY)?.stop()
836
984
  }
837
985
 
838
986
  /**
@@ -900,35 +1048,31 @@ export class AgentApplication<TState extends TurnState> {
900
1048
  }
901
1049
 
902
1050
  /**
903
- * Starts a long-running call, potentially in a new conversation context.
1051
+ * Starts a long-running call by continuing the conversation asynchronously (fire-and-forget).
1052
+ * The current request/response cycle is not blocked; errors are forwarded to the adapter's error handler.
904
1053
  *
905
1054
  * @param context - The turn context for the current conversation.
906
- * @param handler - The handler function to execute.
907
- * @returns A promise that resolves to the result of the handler.
1055
+ * @param handler - The handler function to execute in the continued conversation.
908
1056
  */
909
1057
  protected startLongRunningCall (
910
1058
  context: TurnContext,
911
- handler: (context: TurnContext) => Promise<boolean>
912
- ): Promise<boolean> {
913
- if (context.activity.type === ActivityTypes.Message && this._options.longRunningMessages) {
914
- return new Promise<boolean>((resolve, reject) => {
915
- this.continueConversationAsync(context.identity, context, async (ctx) => {
916
- try {
917
- for (const key in context.activity) {
918
- (ctx.activity as any)[key] = (context.activity as any)[key]
919
- }
920
-
921
- const result = await handler(ctx)
922
- resolve(result)
923
- } catch (err: any) {
924
- logger.error(err)
925
- reject(err)
926
- }
927
- })
928
- })
929
- } else {
930
- return handler(context)
931
- }
1059
+ handler: (context: TurnContext) => Promise<any>
1060
+ ) {
1061
+ const activity = Activity.fromObject(context.activity)
1062
+ this.continueConversationAsync(context.identity, activity.getConversationReference(), async (ctx) => {
1063
+ try {
1064
+ Object.assign(ctx.activity, activity)
1065
+ await handler(ctx)
1066
+ } catch (err) {
1067
+ if (this.adapter.onTurnError && err instanceof Error) {
1068
+ await this.adapter.onTurnError(ctx, err)
1069
+ } else {
1070
+ throw err
1071
+ }
1072
+ }
1073
+ }).catch(err => {
1074
+ logger.error(`Unhandled error in long-running call for activity '${activity.type}' (id: ${activity.id}):`, err)
1075
+ })
932
1076
  }
933
1077
 
934
1078
  /**
@@ -7,7 +7,9 @@ import { Storage } from '../storage'
7
7
  import { AgentApplication } from './agentApplication'
8
8
  import { AgentApplicationOptions } from './agentApplicationOptions'
9
9
  import { AuthorizationOptions } from './auth/types'
10
+ import { ProactiveOptions } from './proactive'
10
11
  import { TurnState } from './turnState'
12
+ import { TypingOptions } from './agentApplicationOptions'
11
13
 
12
14
  /**
13
15
  * Builder class for creating and configuring AgentApplication instances.
@@ -49,10 +51,20 @@ export class AgentApplicationBuilder<TState extends TurnState = TurnState> {
49
51
  * @param startTypingTimer Whether to show typing indicators
50
52
  * @returns This builder instance for chaining
51
53
  */
52
- // public setStartTypingTimer (startTypingTimer: boolean): this {
53
- // this._options.startTypingTimer = startTypingTimer
54
- // return this
55
- // }
54
+ public setStartTypingTimer (startTypingTimer: boolean): this {
55
+ this._options.startTypingTimer = startTypingTimer
56
+ return this
57
+ }
58
+
59
+ /**
60
+ * Configures timing behavior for automatic typing indicators.
61
+ * @param typing Typing timer options
62
+ * @returns This builder instance for chaining
63
+ */
64
+ public withTyping (typing: TypingOptions): this {
65
+ this._options.typing = typing
66
+ return this
67
+ }
56
68
 
57
69
  /**
58
70
  * Sets authentication options for the AgentApplication.
@@ -64,6 +76,16 @@ export class AgentApplicationBuilder<TState extends TurnState = TurnState> {
64
76
  return this
65
77
  }
66
78
 
79
+ /**
80
+ * Configures the proactive messaging subsystem.
81
+ * @param options Proactive options including optional storage backend
82
+ * @returns This builder instance for chaining
83
+ */
84
+ public withProactive (options: ProactiveOptions): this {
85
+ this._options.proactive = options
86
+ return this
87
+ }
88
+
67
89
  /**
68
90
  * Builds and returns a new AgentApplication instance configured with the provided options.
69
91
  * @returns A new AgentApplication instance
@@ -12,6 +12,36 @@ import { TurnState } from './turnState'
12
12
  import { HeaderPropagationDefinition } from '../headerPropagation'
13
13
  import { AuthorizationOptions } from './auth/types'
14
14
  import { Connections } from '../auth/connections'
15
+ import { ProactiveOptions } from './proactive'
16
+
17
+ /**
18
+ * Typing timer settings for a specific channel or the global default.
19
+ */
20
+ export interface TypingTimingOptions {
21
+ /**
22
+ * Delay in milliseconds before the first typing indicator is sent.
23
+ *
24
+ * @default 0
25
+ */
26
+ initialDelayMs?: number
27
+
28
+ /**
29
+ * Delay in milliseconds between subsequent typing indicators.
30
+ *
31
+ * @default 4000
32
+ */
33
+ intervalMs?: number
34
+ }
35
+
36
+ /**
37
+ * Configuration options for automatic typing indicators.
38
+ */
39
+ export interface TypingOptions extends TypingTimingOptions {
40
+ /**
41
+ * Optional channel-specific timing overrides keyed by channel ID.
42
+ */
43
+ channelStrategies?: Record<string, TypingTimingOptions>
44
+ }
15
45
 
16
46
  /**
17
47
  * Configuration options for creating and initializing an Agent Application.
@@ -59,6 +89,13 @@ export interface AgentApplicationOptions<TState extends TurnState> {
59
89
  */
60
90
  startTypingTimer: boolean;
61
91
 
92
+ /**
93
+ * Optional timing settings for automatic typing indicators.
94
+ *
95
+ * @default undefined
96
+ */
97
+ typing?: TypingOptions;
98
+
62
99
  /**
63
100
  * Whether to enable support for long-running message processing operations.
64
101
  * When enabled, the agent can handle operations that take longer than the typical
@@ -147,4 +184,10 @@ export interface AgentApplicationOptions<TState extends TurnState> {
147
184
  * identity providers.
148
185
  */
149
186
  connections?: Connections
187
+
188
+ /**
189
+ * Optional. Configuration for the proactive messaging subsystem.
190
+ * When provided, `app.proactive` will be available.
191
+ */
192
+ proactive?: ProactiveOptions
150
193
  }
@@ -9,7 +9,7 @@ import { TurnState } from './turnState'
9
9
  import { TurnContext } from '../turnContext'
10
10
  import { Attachment } from '@microsoft/agents-activity'
11
11
  import { AuthProvider } from '../auth/authProvider'
12
- import { debug } from '@microsoft/agents-activity/logger'
12
+ import { debug } from '@microsoft/agents-telemetry'
13
13
  import { loadAuthConfigFromEnv, MsalTokenProvider } from '../auth'
14
14
 
15
15
  const logger = debug('agents:attachmentDownloader')