@microsoft/agents-hosting 1.5.0-beta.6.ga236d9a19c → 1.5.1

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 +36 -10
  9. package/dist/src/app/agentApplication.js +169 -99
  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 +18 -5
  20. package/dist/src/app/auth/authorizationManager.js +258 -45
  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 +48 -42
  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 +212 -86
  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 +297 -45
  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 +47 -41
@@ -13,7 +13,7 @@ import { Connections } from '../../auth/connections'
13
13
  /**
14
14
  * Authorization configuration options.
15
15
  */
16
- export type AuthorizationOptions = Record<string, AzureBotAuthorizationOptions | AgenticAuthorizationOptions>
16
+ export type AuthorizationOptions = Record<string, (AzureBotAuthorizationOptions & AzureBotAuthorizationOptionsLegacy) | AgenticAuthorizationOptions>
17
17
 
18
18
  /**
19
19
  * Represents the status of a handler registration attempt.
@@ -50,6 +50,14 @@ export interface AuthorizationHandler {
50
50
  * Unique identifier for the handler.
51
51
  */
52
52
  readonly id: string
53
+ /**
54
+ * The type of this handler (resolved, including env vars).
55
+ */
56
+ readonly type?: string
57
+ /**
58
+ * The scopes configured for this handler (resolved, including env vars).
59
+ */
60
+ readonly scopes?: string[]
53
61
  /**
54
62
  * Initiates the sign-in process for the handler.
55
63
  * @param context The turn context.
@@ -109,3 +117,96 @@ export interface AuthorizationHandlerTokenOptions {
109
117
  */
110
118
  scopes?: string[]
111
119
  }
120
+
121
+ /**
122
+ * Interface defining an authorization handler configuration.
123
+ * @remarks
124
+ * Properties can be configured via environment variables (case-insensitive).
125
+ * Use the format: `AgentApplication__UserAuthorization__handlers__{handlerId}__settings__{propertyName}`
126
+ * where `{handlerId}` is the handler's unique identifier and `{propertyName}` matches the property name.
127
+ *
128
+ * @example
129
+ * ```env
130
+ * # For a handler with id "myAuth":
131
+ * AgentApplication__UserAuthorization__handlers__myAuth__settings__azureBotOAuthConnectionName=MyConnection
132
+ * AgentApplication__UserAuthorization__handlers__myAuth__settings__oboScopes=api://scope1 api://scope2
133
+ * ```
134
+ */
135
+ export interface AzureBotAuthorizationOptionsLegacy {
136
+ /**
137
+ * Connection name for the auth provider.
138
+ * @deprecated Use `azureBotOAuthConnectionName` instead.
139
+ * @remarks Env (legacy): `{handlerId}_connectionName`
140
+ */
141
+ name?: string,
142
+ /**
143
+ * Maximum number of attempts for entering the magic code. Defaults to 2.
144
+ * @deprecated Use `invalidSignInRetryMax` instead.
145
+ * @remarks Env (legacy): `{handlerId}_maxAttempts`
146
+ */
147
+ maxAttempts?: number
148
+ /**
149
+ * Messages to display for various authentication scenarios.
150
+ * @deprecated Use `invalidSignInRetryMessage`, `invalidSignInRetryMessageFormat`, and `invalidSignInRetryMaxExceededMessage` instead.
151
+ * @remarks
152
+ * Env (legacy):
153
+ * - `{handlerId}_messages_invalidCode`
154
+ * - `{handlerId}_messages_invalidCodeFormat`
155
+ * - `{handlerId}_messages_maxAttemptsExceeded`
156
+ */
157
+ messages?: AzureBotAuthorizationOptionsMessages
158
+ /**
159
+ * Settings for on-behalf-of token acquisition.
160
+ * @deprecated Use `oboConnectionName` and `oboScopes` instead.
161
+ * @remarks
162
+ * Env (legacy):
163
+ * - `{handlerId}_obo_connection`
164
+ * - `{handlerId}_obo_scopes` (comma or space-separated)
165
+ */
166
+ obo?: AzureBotAuthorizationOptionsOBO
167
+ }
168
+
169
+ /**
170
+ * @deprecated
171
+ * Messages configuration for the AzureBotAuthorization handler.
172
+ */
173
+ interface AzureBotAuthorizationOptionsMessages {
174
+ /**
175
+ * @deprecated Use `invalidSignInRetryMessage` instead.
176
+ * Message displayed when an invalid code is entered.
177
+ * Use `{code}` as a placeholder for the entered code.
178
+ * Defaults to: 'The code entered is invalid. Please sign-in again to continue.'
179
+ */
180
+ invalidCode?: string
181
+ /**
182
+ * @deprecated Use `invalidSignInRetryMessageFormat` instead.
183
+ * Message displayed when the entered code format is invalid.
184
+ * Use `{attemptsLeft}` as a placeholder for the number of attempts left.
185
+ * Defaults to: 'Please enter a valid **6-digit** code format (_e.g. 123456_).\r\n**{attemptsLeft} attempt(s) left...**'
186
+ */
187
+ invalidCodeFormat?: string
188
+ /**
189
+ * @deprecated Use `invalidSignInRetryMaxExceededMessage` instead.
190
+ * Message displayed when the maximum number of attempts is exceeded.
191
+ * Use `{maxAttempts}` as a placeholder for the maximum number of attempts.
192
+ * Defaults to: 'You have exceeded the maximum number of sign-in attempts ({maxAttempts}).'
193
+ */
194
+ maxAttemptsExceeded?: string
195
+ }
196
+
197
+ /**
198
+ * @deprecated
199
+ * Settings for on-behalf-of token acquisition.
200
+ */
201
+ interface AzureBotAuthorizationOptionsOBO {
202
+ /**
203
+ * @deprecated Use `oboConnectionName` instead.
204
+ * Connection name to use for on-behalf-of token acquisition.
205
+ */
206
+ connection?: string
207
+ /**
208
+ * @deprecated Use `oboScopes` instead.
209
+ * Scopes to request for on-behalf-of token acquisition.
210
+ */
211
+ scopes?: string[]
212
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import { TurnContext } from '../../turnContext'
7
+ import { InvokeResponse } from '../../invoke'
8
+ import { Activity, ActivityTypes, Channels } from '@microsoft/agents-activity'
9
+
10
+ /**
11
+ * Sends an InvokeResponse activity if the channel is Microsoft Teams, including Copilot within MS Teams.
12
+ */
13
+ export function sendInvokeResponse<T> (context: TurnContext, response: InvokeResponse<T>) {
14
+ if (context.activity.channelIdChannel !== Channels.Msteams) {
15
+ return Promise.resolve()
16
+ }
17
+
18
+ return context.sendActivity(Activity.fromObject({
19
+ type: ActivityTypes.InvokeResponse,
20
+ value: response
21
+ }))
22
+ }
package/src/app/index.ts CHANGED
@@ -19,3 +19,4 @@ export * from './adaptiveCards'
19
19
  export * from './streaming/streamingResponse'
20
20
  export * from './streaming/citation'
21
21
  export * from './teamsAttachmentDownloader'
22
+ export * from './proactive'
@@ -0,0 +1,87 @@
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ import type { JwtPayload } from 'jsonwebtoken'
5
+ import type { ConversationReference } from '@microsoft/agents-activity'
6
+ import { ExceptionHelper } from '@microsoft/agents-activity'
7
+ import type { TurnContext } from '../../turnContext'
8
+ import { Errors } from '../../errorHelper'
9
+
10
+ /**
11
+ * JWT-like claims identifying the agent for proactive authentication.
12
+ * `aud` (the agent's client ID) is required; all other fields are optional.
13
+ */
14
+ export interface ConversationClaims {
15
+ aud: string
16
+ azp?: string
17
+ appid?: string
18
+ tid?: string
19
+ [key: string]: string | undefined
20
+ }
21
+
22
+ /**
23
+ * A serializable pair of a `ConversationReference` and the JWT claims needed
24
+ * to authenticate proactive calls on behalf of this agent.
25
+ *
26
+ * Instances are stored in and retrieved from the proactive storage backend.
27
+ * The `identity` getter produces the `JwtPayload` shape expected by
28
+ * `adapter.continueConversation()`.
29
+ */
30
+ export class Conversation {
31
+ reference: ConversationReference
32
+ claims: ConversationClaims
33
+
34
+ constructor (context: TurnContext)
35
+ constructor (claims: ConversationClaims, reference: ConversationReference)
36
+ constructor (
37
+ contextOrClaims: TurnContext | ConversationClaims,
38
+ reference?: ConversationReference
39
+ ) {
40
+ if ('activity' in contextOrClaims) {
41
+ // TurnContext overload
42
+ const context = contextOrClaims as TurnContext
43
+ this.reference = context.activity.getConversationReference()
44
+ const id = context.identity as JwtPayload | undefined
45
+ this.claims = {
46
+ ...(id ?? {}),
47
+ aud: Array.isArray(id?.aud) ? (id.aud as string[])[0] : (id?.aud ?? '')
48
+ } as ConversationClaims
49
+ } else {
50
+ // (claims, reference) overload — matches C# parameter order
51
+ this.claims = contextOrClaims as ConversationClaims
52
+ this.reference = reference!
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Returns a `JwtPayload`-compatible object for passing to
58
+ * `adapter.continueConversation()` as `botAppIdOrIdentity`.
59
+ */
60
+ get identity (): JwtPayload {
61
+ return this.claims as unknown as JwtPayload
62
+ }
63
+
64
+ /**
65
+ * Returns a JSON string of `{ reference, claims }` — suitable for use in
66
+ * HTTP request bodies when passing a conversation to another service.
67
+ */
68
+ toJson (): string {
69
+ return JSON.stringify({ reference: this.reference, claims: this.claims })
70
+ }
71
+
72
+ /**
73
+ * Throws if any required field is missing.
74
+ * Called by `Proactive.storeConversation()` before writing to storage.
75
+ */
76
+ validate (): void {
77
+ if (!this.reference.conversation?.id) {
78
+ throw ExceptionHelper.generateException(Error, Errors.ConversationInvalidId)
79
+ }
80
+ if (!this.reference.serviceUrl) {
81
+ throw ExceptionHelper.generateException(Error, Errors.ConversationInvalidServiceUrl)
82
+ }
83
+ if (!this.claims.aud) {
84
+ throw ExceptionHelper.generateException(Error, Errors.ConversationInvalidAud)
85
+ }
86
+ }
87
+ }
@@ -0,0 +1,139 @@
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ import type { ChannelAccount, ConversationAccount, ConversationReference } from '@microsoft/agents-activity'
5
+ import type { TurnContext } from '../../turnContext'
6
+ import { Conversation, type ConversationClaims } from './conversation'
7
+ import { ConversationReferenceBuilder } from './conversationReferenceBuilder'
8
+
9
+ /**
10
+ * Fluent builder for the `Conversation` class.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * // Build from scratch
15
+ * const conv = ConversationBuilder
16
+ * .create('my-client-id', 'msteams')
17
+ * .withUser('user-aad-id')
18
+ * .withConversationId('19:channel@thread.skype')
19
+ * .build()
20
+ *
21
+ * // Build from a live TurnContext
22
+ * const conv = ConversationBuilder.fromContext(turnContext).build()
23
+ * ```
24
+ */
25
+ export class ConversationBuilder {
26
+ private readonly _agentClientId: string
27
+ private readonly _channelId: string
28
+ private readonly _serviceUrl: string
29
+ private _claims: ConversationClaims
30
+ private _reference: Partial<ConversationReference>
31
+
32
+ private constructor (
33
+ agentClientId: string,
34
+ channelId: string,
35
+ serviceUrl: string,
36
+ claims: ConversationClaims,
37
+ reference: Partial<ConversationReference>
38
+ ) {
39
+ this._agentClientId = agentClientId
40
+ this._channelId = channelId
41
+ this._serviceUrl = serviceUrl
42
+ this._claims = claims
43
+ this._reference = reference
44
+ }
45
+
46
+ /**
47
+ * Creates a new builder for the given agent and channel.
48
+ * @param requestorId Optional: the client ID of the app making the request.
49
+ * Becomes the `appid` claim, used in multi-tenant Azure Bot scenarios.
50
+ */
51
+ static create (
52
+ agentClientId: string,
53
+ channelId: string,
54
+ serviceUrl?: string,
55
+ requestorId?: string
56
+ ): ConversationBuilder {
57
+ const claims: ConversationClaims = { aud: agentClientId }
58
+ if (requestorId) claims.appid = requestorId
59
+ return new ConversationBuilder(agentClientId, channelId, serviceUrl ?? '', claims, ConversationReferenceBuilder.create(agentClientId, channelId, serviceUrl).build())
60
+ }
61
+
62
+ /**
63
+ * Creates a builder pre-populated from a live `TurnContext`.
64
+ * Captures both the conversation reference and the JWT identity claims.
65
+ */
66
+ static fromContext (context: TurnContext): ConversationBuilder {
67
+ const ref = context.activity.getConversationReference()
68
+ const id = context.identity
69
+ const aud = Array.isArray(id?.aud) ? id.aud[0] : (id?.aud ?? '')
70
+ const claims: ConversationClaims = {
71
+ ...(id ?? {}),
72
+ aud,
73
+ } as ConversationClaims
74
+ return new ConversationBuilder(
75
+ aud,
76
+ ref.channelId,
77
+ ref.serviceUrl ?? '',
78
+ claims,
79
+ ref
80
+ )
81
+ }
82
+
83
+ /** Sets `reference.user`. */
84
+ withUser (userId: string, userName?: string): this {
85
+ const user: ChannelAccount = { id: userId, name: userName }
86
+ this._reference = { ...this._reference, user }
87
+ return this
88
+ }
89
+
90
+ /** Sets `reference.conversation.id`. */
91
+ withConversationId (id: string): this {
92
+ const conversation: ConversationAccount = { ...(this._reference.conversation ?? { isGroup: false }), id }
93
+ this._reference = { ...this._reference, conversation }
94
+ return this
95
+ }
96
+
97
+ /** Sets `reference.conversation` from a full `ConversationAccount`. */
98
+ withConversation (account: ConversationAccount): this {
99
+ this._reference = { ...this._reference, conversation: account }
100
+ return this
101
+ }
102
+
103
+ /** Sets `reference.activityId`. */
104
+ withActivityId (activityId: string): this {
105
+ this._reference = { ...this._reference, activityId }
106
+ return this
107
+ }
108
+
109
+ /**
110
+ * Merges a partial `ConversationReference` into the current one.
111
+ * Useful for overlaying externally-provided reference data without losing
112
+ * fields set by earlier builder calls.
113
+ */
114
+ withReference (ref: Partial<ConversationReference>): this {
115
+ this._reference = { ...this._reference, ...ref }
116
+ return this
117
+ }
118
+
119
+ /** Builds the `Conversation`, auto-filling `serviceUrl` from channel defaults if needed. */
120
+ build (): Conversation {
121
+ const serviceUrl =
122
+ this._serviceUrl ||
123
+ this._reference.serviceUrl ||
124
+ ConversationReferenceBuilder.serviceUrlForChannel(this._channelId)
125
+
126
+ const reference: ConversationReference = {
127
+ conversation: this._reference.conversation ?? { id: '', isGroup: false },
128
+ agent: this._reference.agent ?? { id: this._agentClientId },
129
+ ...this._reference,
130
+ // Ensure channelId and serviceUrl always use our resolved values
131
+ channelId: this._channelId,
132
+ serviceUrl,
133
+ }
134
+
135
+ const conv = new Conversation(this._claims, reference)
136
+ conv.validate()
137
+ return conv
138
+ }
139
+ }
@@ -0,0 +1,161 @@
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ import type { ChannelAccount, ConversationReference } from '@microsoft/agents-activity'
5
+ import { Channels, RoleTypes } from '@microsoft/agents-activity'
6
+ import { debug } from '@microsoft/agents-telemetry'
7
+
8
+ const logger = debug('agents:conversation-reference-builder')
9
+
10
+ /** Set of all channel IDs defined in the Channels enum, used for validation. */
11
+ const knownChannelIds = new Set(Object.values(Channels) as string[])
12
+
13
+ /**
14
+ * Well-known Teams service URLs for proactive messaging.
15
+ *
16
+ * Use only when the incoming `serviceUrl` from a real conversation is unavailable.
17
+ * Once you have received a `serviceUrl` from a real turn, cache and prefer that value.
18
+ */
19
+ export const TeamsServiceEndpoints = {
20
+ /** Standard public cloud Teams endpoint. */
21
+ publicGlobal: 'https://smba.trafficmanager.net/teams/',
22
+ /** US Government Community Cloud (GCC). */
23
+ gcc: 'https://smba.infra.gcc.teams.microsoft.com/teams',
24
+ /** US Government Community Cloud High (GCC-High). */
25
+ gccHigh: 'https://smba.infra.gov.teams.microsoft.us/teams',
26
+ /** US Department of Defense (DoD). */
27
+ dod: 'https://smba.infra.dod.teams.microsoft.us/teams',
28
+ } as const
29
+
30
+ /**
31
+ * Fluent builder for `ConversationReference`.
32
+ */
33
+ export class ConversationReferenceBuilder {
34
+ private readonly _channelId: string
35
+ private _serviceUrl: string
36
+ private _agent: ChannelAccount
37
+ private _user?: ChannelAccount
38
+ private _conversationId?: string
39
+ private _activityId?: string
40
+ private _locale?: string
41
+
42
+ private constructor (channelId: string, serviceUrl: string, agent: ChannelAccount) {
43
+ this._channelId = channelId
44
+ this._serviceUrl = serviceUrl
45
+ this._agent = agent
46
+ }
47
+
48
+ /**
49
+ * Creates a new builder seeded with the agent identity and channel.
50
+ * On Teams, the agent id is prefixed with `28:` automatically.
51
+ * @param agentClientId The agent's client (app) ID.
52
+ * @param channelId The target channel (e.g. `'msteams'`, `'webchat'`).
53
+ * @param serviceUrl Optional override. If omitted, `build()` fills in the
54
+ * channel default via `serviceUrlForChannel()`.
55
+ */
56
+ static create (
57
+ agentClientId: string,
58
+ channelId: string,
59
+ serviceUrl?: string
60
+ ): ConversationReferenceBuilder {
61
+ return new ConversationReferenceBuilder(
62
+ channelId,
63
+ serviceUrl ?? '',
64
+ ConversationReferenceBuilder.agentForChannel(channelId, agentClientId)
65
+ )
66
+ }
67
+
68
+ /**
69
+ * Returns the default service URL for a channel.
70
+ * Teams returns the public global endpoint; all other channels use the
71
+ * `https://{channelId}.botframework.com/` pattern (matching C# behavior).
72
+ */
73
+ static serviceUrlForChannel (channelId: string): string {
74
+ if (!channelId) return ''
75
+ if (channelId === Channels.Msteams) return TeamsServiceEndpoints.publicGlobal
76
+ if (!knownChannelIds.has(channelId)) {
77
+ logger.warn(
78
+ `serviceUrlForChannel: unrecognized channelId '${channelId}' — constructing fallback URL ` +
79
+ 'https://<channelId>.botframework.com/. Provide an explicit serviceUrl to suppress this warning.'
80
+ )
81
+ }
82
+ return `https://${channelId}.botframework.com/`
83
+ }
84
+
85
+ /** Sets `reference.user` from an id + optional name. Role defaults to `RoleTypes.User`. */
86
+ withUser (userId: string, userName?: string): this
87
+ /** Sets `reference.user` from a full `ChannelAccount`. */
88
+ withUser (account: ChannelAccount): this
89
+ withUser (userIdOrAccount: string | ChannelAccount, userName?: string): this {
90
+ this._user = typeof userIdOrAccount === 'string'
91
+ ? { id: userIdOrAccount, name: userName, role: RoleTypes.User }
92
+ : userIdOrAccount
93
+ return this
94
+ }
95
+
96
+ /** Sets `reference.agent` from an id + optional name. Role defaults to `RoleTypes.Agent`. On Teams, id is prefixed with `28:`. */
97
+ withAgent (agentClientId: string, agentName?: string): this
98
+ /** Sets `reference.agent` from a full `ChannelAccount`. */
99
+ withAgent (account: ChannelAccount): this
100
+ withAgent (agentIdOrAccount: string | ChannelAccount, agentName?: string): this {
101
+ this._agent = typeof agentIdOrAccount === 'string'
102
+ ? ConversationReferenceBuilder.agentForChannel(this._channelId, agentIdOrAccount, agentName)
103
+ : agentIdOrAccount
104
+ return this
105
+ }
106
+
107
+ /** Sets `reference.serviceUrl`. */
108
+ withServiceUrl (serviceUrl: string): this {
109
+ this._serviceUrl = serviceUrl
110
+ return this
111
+ }
112
+
113
+ /** Sets `reference.conversation.id`. */
114
+ withConversationId (id: string): this {
115
+ this._conversationId = id
116
+ return this
117
+ }
118
+
119
+ /** Sets `reference.activityId`. */
120
+ withActivityId (activityId: string): this {
121
+ this._activityId = activityId
122
+ return this
123
+ }
124
+
125
+ /** Sets `reference.locale`. */
126
+ withLocale (locale: string): this {
127
+ this._locale = locale
128
+ return this
129
+ }
130
+
131
+ /** Builds and returns the `ConversationReference`. */
132
+ build (): ConversationReference {
133
+ const serviceUrl =
134
+ this._serviceUrl || ConversationReferenceBuilder.serviceUrlForChannel(this._channelId)
135
+
136
+ const ref: ConversationReference = {
137
+ channelId: this._channelId,
138
+ serviceUrl,
139
+ conversation: { id: this._conversationId ?? '', isGroup: false },
140
+ agent: this._agent,
141
+ user: this._user ?? { role: RoleTypes.User },
142
+ }
143
+
144
+ if (this._activityId !== undefined) ref.activityId = this._activityId
145
+ if (this._locale !== undefined) ref.locale = this._locale
146
+
147
+ return ref
148
+ }
149
+
150
+ /**
151
+ * Builds a `ChannelAccount` for the agent, applying the Teams `28:` id prefix
152
+ * when the channel is `msteams`.
153
+ */
154
+ private static agentForChannel (channelId: string, agentClientId: string, agentName?: string): ChannelAccount {
155
+ return {
156
+ id: channelId === Channels.Msteams ? `28:${agentClientId}` : agentClientId,
157
+ name: agentName,
158
+ role: RoleTypes.Agent,
159
+ }
160
+ }
161
+ }
@@ -0,0 +1,35 @@
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ import type { ConversationParameters } from '@microsoft/agents-activity'
5
+ import type { ConversationClaims } from './conversation'
6
+
7
+ /**
8
+ * Default OAuth scope for Azure Bot Service authentication.
9
+ */
10
+ export const AzureBotScope = 'https://api.botframework.com'
11
+
12
+ /**
13
+ * Options passed to `Proactive.createConversation()`.
14
+ * Flattened — no nested Conversation wrapper.
15
+ */
16
+ export interface CreateConversationOptions {
17
+ /** JWT claims for the agent identity. `aud` must be the agent's client ID. */
18
+ identity: ConversationClaims
19
+ /** The target channel (e.g. `'msteams'`). */
20
+ channelId: string
21
+ /** The service URL for the channel. */
22
+ serviceUrl: string
23
+ /**
24
+ * OAuth scope for token acquisition.
25
+ * Defaults to `AzureBotScope` when not set by the builder.
26
+ */
27
+ scope: string
28
+ /**
29
+ * When `true`, the resulting `Conversation` is stored automatically after
30
+ * creation. Defaults to `false`.
31
+ */
32
+ storeConversation?: boolean
33
+ /** Conversation configuration passed to `adapter.createConversationAsync()`. */
34
+ parameters: Partial<ConversationParameters>
35
+ }